slide1 n.
Download
Skip this Video
Download Presentation
Processes and Inter-Process Communication

Loading in 2 Seconds...

play fullscreen
1 / 122

Processes and Inter-Process Communication - PowerPoint PPT Presentation


  • 188 Views
  • Uploaded on

Processes and Inter-Process Communication. Contents. What is a Process? Process Control Process Relationship Inter- Process Communication. What is a Process?. Program An executable file Process

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Processes and Inter-Process Communication' - barney


Download Now An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide1
Processes

and

Inter-Process Communication

contents
Contents
  • What is a Process?
  • Process Control
  • Process Relationship
  • Inter- Process Communication
what is a process
What is a Process?
  • Program
    • An executable file
  • Process
    • An instance of a program that is being executed by the OS.
    • Every process has a unique ID (PID).
slide4
PID
  • Every process has a unique ID (PID).
  • PIDs are 16-bit numbers that are assigned sequentially by Linux as new processes are created.
pid in c c
PID in C/C++
  • In C or C++ use the pid_t type
    • Defined in <sys/types.h>
  • getpid() : obtain the PID of the process
  • getppid(): obtain the PID of the parent
    • Every process has a parent process
  • Printing the process ID:
process management
Process Management
  • The Unix OS is a time-sharing system.
  • Each process is represented by a task_struct data structure.
  • The task_vector is an array of pointers to every task_struct data structure in the system.
process statuses
Process Statuses
  • Running
        • The process is either running or it is ready to run.
  • Waiting
        • The process is waiting for an event or for a resource.
  • Stopped
        • The process has been stopped, usually by receiving a signal.
  • Zombie
        • This is a halted process which, for some reason, still has a task_struct data structure in the task vector.
type of processes
Type of Processes
  • Interactive Process
    • Initiated from (and controlled by) a shell
  • Daemon Process
    • Run in the background until required
related commands
Related Commands
  • ps
    • Report process status.
  • pstree
    • Display a tree of processes.
  • nice
    • Run a program with modified scheduling priority.
  • renice
    • Alter priority of running process.
  • kill
    • Send signal to a process.
related commands cont
Related Commands (Cont.)
  • top
    • Display top CPU processes.
  • jobs
    • List the active jobs.
  • bg
    • Place a job in background (similar to &);
  • fg
    • Place a job in foreground.
  • Ctrl+z
    • Stopped a process.
  • Ctrl+c
    • Terminate a process.
process scheduling
Process Scheduling
  • Linux schedules the parent and child processes independently
  • Linux promises that each process will run eventually
  • Alter execution priority:
    • By default, every process has a niceness of zero.
    • A higher niceness value means that the process is given a lesser execution priority;
    • conversely, a process with a lower (that is, negative) niceness gets more execution time.
  • $ nice –n value command
  • renice command to change the niceness of a running process
viewing active processes
Viewing active processes
  • ps displays the processes controlled by the terminal in which ps is invoked.
  • -e : display all processes running on the system
  • -o pidd.ppidd,command : what information to show about each process
contents1
Contents
  • What is a Process?
  • Process Control
  • Process Relationship
  • Inter- Process Communication
process control
Process Control
  • fork and vfork
  • exit
  • wait and waitpid
  • exec
  • signal
  • kill
creating a new process
Creating a new process
  • system: simple but inefficient, has security risks
  • fork and exec: more complex but provides greater flexibility,speed, and security
using system
Using system
  • The system function in the standard C library provides an easy way to execute a command from within a program.
  • In fact, system creates a subprocess running the standard Bourne shell (/bin/sh) and hands the command to that shell for execution.
  • it’s subject to the features, limitations, and security flaws of the system’s shell
creating processes
Creating Processes
  • Using fork and exec
  • fork: make a child process in an exact copy of it’s parent process
  • exec: causes a process to become an instance of another program
slide18
fork

PID2

PID1

fork

Child

Parent

fork cont
fork (cont.)
  • int fork();
  • The only way a new process is created by the Unix kernel.
    • The new process created is called the child process.
  • The child is a copy of the parent.
    • The child gets a copy of the parent’s data space, heap and stack.
    • The parent and child don’t share these portions of memory.
fork cont1
fork (cont.)
  • This function is called once, but return twice.
    • The process ID of the new child (to the parent).
      • A process can have more than one child.
    • 0 (to the child).
fork sample
fork Sample

main()

{

int pid;

pid = fork();

if (pid < 0)

// error

else if (pid == 0)

//child

else

//parent

}

fork cont2
fork (cont.)
  • We never know if the child starts executing before the parent or vice versa.
    • This depends on the scheduling algorithm used by the kernel.
vfork
vfork
  • int = vfork();
  • It has the same calling sequence and same return values as fork.
  • The child doesn’t copy the parent data space.
    • The child runs in the address space of the parent.
  • With vfork, child runs first, then parent runs.
slide27

Compile: g++ -o VForkTest VForkTest.cpp Run: VForkTest

  • Child Process: Global variable: 3 Stack variable: 21 Parent Process: Global variable: 3 Stack variable: 21
  • The child process executed first, updated the variables which are shared between the processes and NOT unique, and then the parent process executes using variables which the child has updated.
slide28
exit
  • Normal termination
    • Executing a return from the main function.
    • Calling the exit function.
    • Calling the _exit function.
  • Abnormal termination
    • Calling abort.
    • Receives certain signals.
exit cont
exit (cont.)
  • void exit (int state);
  • Sometimes we want the terminating process to be able to notify its parent how it terminated.
  • For the exit and _exit function this is done by passing an exit status as the argument to these two functions.
  • The parent of the process can obtain the termination status from either the wait or waitpid function.
exit vs exit
exit() vs _exit()
  • The C library function exit() calls the kernel system call _exit() internally
  • The kernel system call _exit() will cause the kernel to close descriptors, free memory, and perform the kernel terminating process clean-up.
  • The C library function exit() call will flush I/O buffers and perform additional clean-up before calling _exit() internally.
termination conditions
Termination Conditions
  • Parent terminate before the child
    • The init process becomes the parent process of any process whose parent terminated.
termination conditions1
Termination Conditions
  • If child terminate before the parent
  • If its parent is calling a wait function
    • the child process vanishes and its termination status is passed to its parent via the wait call
termination conditions2
Termination Conditions
  • Else
    • The kernel has to keep a certain amount of information for every terminating process.
    • The process that has terminated, but whose parent has not waited for it, is called zombie.
  • What happens if the parent does not clean up its children? They stay around in the system, as zombie processes
termination conditions3
Termination Conditions
  • Child terminate before the parent
    • The child is completely disappeared, but the parent wouldn’t be able to fetch its termination status.
    • The kernel has to keep a certain amount of information for every terminating process.
    • The process that has terminated, but whose parent has not waited for it, is called zombie.
slide37
wait
  • The parent process will often want to wait until all child processes have been completed. this can be implemented with the wait() function call.
  • wait(): Blocks calling process until the child process terminates. If child process has already teminated, the wait() call returns immediately. if the calling process has multiple child processes, the function returns when one returns.
  • waitpid(): Options available to block calling process for a particular child process not the first one.
slide38
wait
  • When a process terminates, the parent is notified by the kernel sending the parent the SIGCHLD signal.
  • The parent of the process can obtain the termination status from either the wait or waitpid function.
wait cont
wait (cont.)
  • The process that calls wait or waitpid can:
    • Block (if all of its children are still running)
    • Return immediately with the termination status of a child (if a child has terminated)
    • Return immediately with an error (if it doesn’t have any child process)
wait and waitpid
wait and waitpid
  • int wait (int *statloc);
  • int waitpid (int pid, int *statloc, int options);
    • If statloc is not a null pointer, the termination status of the terminated process is stored in this location.
  • The difference between these two function:
    • wait can block, while waitpid has an option that prevents it from blocking.
    • waitpid doesn’t wait for the first child to terminate (it can control which process it waits for)
slide41
exec
  • A process cause another program to be executed by calling one of the exec functions.
  • When a process calls one of the exec functions, that process is completely replaced by the new program.
  • The process ID doesn’t change across an exec.
exec functions
exec functions
  • int execl (char *path, char *arg0, … /*(char *) 0 */);
  • int execle (char *path, char *arg0, … /*(char *) 0, char *envp[] */);
  • int execlp (char *filename, char *arg0, … /*(char *) 0 */);
  • int execv (char *pathname, char *argv0[]);
  • int execve (char *pathname, char *argv0[], char *envp[]);
  • int execvp (char *filename, char *envp[]);
exec functions1
exec functions
  • Functions that contain the letter p in their names (execvp and execlp) accept a program name and search for a program in the current execution path. Functions that don’t contain p must be given the full path of the program to be executed.
  • Functions that contain the letter v in their names (execv, execvp, and execve) accept the argument list for the new program as a NULL-terminated array of pointers to strings.
  • functions that contain the letter l (execl, execlp, and execle) accept the argument list using the C language’s varargs mechanism.
  • Functions that contain the letter e in their names (execve and execle) accept an additional argument, an array of environment variables. The argument should be a NULL-terminated array of pointers to character strings. Each character string should be of the form “VARIABLE=value”.
signal
signal
  • Signals are software interrupts.
  • Signals are asynchronous; when a process receives a signal, it processes the signal immediately
  • For communicating with and manipulating processes in Linux
  • Signals are defined in /usr/include/bits/signum.h
  • The name of signals all begin with the three character SIG : SIGABRT
  • include <signal.h>in your programs
signal cont
signal (cont.)
  • When a process receives a signal, it may do one of several things, depending on the signal’s disposition.
    • default disposition
    • ignore the signal
    • call a special signal-handler
  • The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.
signal cont1
signal (cont.)
  • The Linux system sends signals to processes in response to specific conditions.
  • Example of signals :
    • SIGBUS (bus error)
    • SIGSEGV (segmentation violation)
    • SIGFPE (floating point exception)
    • The default disposition for these signals it to terminate the process and produce a core file.
  • A process may also send a signal to another process.
  • For example: end another process by sending it a SIGTERM or SIGKILL
signal1
signal
  • Signals are software interrupts.
  • The name of signals all begin with the three character SIG : SIGABRT
signal cont2
signal (cont.)
  • void (*signal (int signo, void (*func) (int)))(int);
  • Kernel do when a signal occurs:
    • Ignore the signal
      • Can not ignore : SIGKILL, SIGSTOP
    • Catch the signal
    • Let the default action apply
signal sample
signal Sample

main()

{

signal (SIGUSER, sig_user);

while (1);

}

//---------------------------------

void sig_user (int signo)

{

if (signo == SIGUSER)

printf (“receive signal\n”);

return;

}

sigaction function
Sigaction function
  • The sigaction() system call is used to change the action taken by a process on receipt of a specific signal.
  • Description :
    • sigaction (SIG_NUM, & sa_handler, & old_handler);
  • SIG_NUM specifies the signal and can be any valid signal except SIGKILL and SIGSTOP
sigaction function1
Sigaction function
  • sa_handler can take one of three values:
    • SIG_DFL, which specifies the default disposition for the signal.
    • SIG_IGN, which specifies that the signal should be ignored.
    • A pointer to a signal-handler function.
slide63
kill
  • int kill (int pid, int signo);
  • Send a signal to a process or group of the processes.
  • Include the <sys/types.h> and <signal.h> headers
  • To list available signals, enter:
    • kill -l
slide64
kill
  • int kill (int pid, int signo);
  • Send a signal to a process or group of the processes.
contents2
Contents
  • What is a Process?
  • Process Control
  • Process Relationship
  • Inter- Process Communication
process relationship
Process Relationship

fork

fork

fork

exec

exec

fork & exec

exec

fork

exec

thread
Thread
  • a thread of execution is the smallest unit of processing that can be scheduled by an operating system
  • Each thread in a process is identified by a thread ID.
    • When referring to thread IDs in C or C++, use the type pthread_t.
threads vs processes
Threads vs. Processes
  • Both are methods of parallelizing an application.
  • processes are independent execution units, contain their own state information, use their own address spaces
  • only interact with each other via IPC mechanisms
  • A single process might contains multiple threads; all threads within a process share the same state and same memory space
  • can communicate with each other directly, because they share the same variables.
threads vs processes1
Threads vs. Processes
  • Applications are typically divided into processes during the design phase, and a master process explicitly spawns sub-processes when it makes sense to logically separate significant application functionality.
  • Processes, in other words, are an architectural construct.
  • By contrast, a thread is a coding construct that doesn't affect the architecture of an application.
thread resources
Thread resources
  • When you invoke a program, Linux creates a new process and in that process creates a single thread, which runs the program sequentially.
  • That thread can create additional threads.
  • Each thread may be executing a different part of the program at any given time.
  • The creating and the created thread share same memory space, file descriptors and other system resources.
thread resources1
Thread resources
  • all threads in a single program share the same address space. This means that if one thread modifies a location in memory, the change is visible to all other threads
  • Each thread has its own call stack. This allows each thread to execute different code and to call and return from subroutines in the usual way
thread function
Thread function
  • All thread functions and data types are declared in the header file <pthread.h>.
  • The pthread functions are not included in the standard C library. Instead, they are in libpthread
    • add –lpthread to the command line when you link your program.
thread creation
Thread Creation
  • The pthread_create function creates a new thread. You provide it with the following:
    • A pointer to a pthread_t variable
    • A pointer to a thread attribute object. This object controls details of how the thread interacts with the rest of the program.
    • A pointer to the thread function. The type of this function is void* (*) (void*)
    • A thread argument value of type void*, use to pass data to thread
passing data to thread
Passing data to thread
  • Use thread argument to pass a pointer to some structure or array of data
joining threads
Joining Threads
  • Prevent Linux from scheduling the three threads in such a way that main finishes executing before other threads.
  • Use the function pthread_join, which takes two arguments :
    • The thread ID of the thread to wait for
    • A pointer to a variable that will receive the finished thread’s return value
contents3
Contents
  • What is a Process?
  • Process Control
  • Process Relationship
  • Inter- Process Communication
slide81
IPC
  • This part describes means for inter process communication.
  • Various ways for communicating between parents and children, between “unrelated” processes, and even between processes on different machines.
slide82
IPC
  • Pipe
  • FIFO
  • Message queue
  • Shared memory
  • socket
slide83

Child

Parent

pipe

pipe
  • It provides a one-way flow of data.
  • It is in the kernel
  • It can only be used between processes that have a parent process in common.
pipe cont
pipe (cont.)
  • int pipe (int *filedes);
  • filedes[0] : open for reading
  • filedes[1] : open for writing
  • pipe command :
    • who | sort | lpr
pipe synchronization
Pipe synchronization
  • In a shell symbol | creates a pipe.
  • ls | less
    • This shell command causes the shell to produce two child processes, one for ls and one for less
  • A pipe’s data capacity is limited.
  • If the writer process writes faster than the reader process consume data, and if the pipe can not store more data, the writer process block until more capacity become available.
  • If the reader tries to read but no data is available, it blocks until data becomes available.
  • Thus, the pipe automatically synchronizes the two processes.
pipe creation
Pipe creation
  • Supply an integer array of size 2.
  • The call to pipe stores the reading file descriptor in array position 0 and the writing file descriptor in position 1.
  • For example, consider this code:

int pipe_fds[2];

int read_fd;

int write_fd;

pipe (pipe_fds);

read_fd = pipe_fds[0];

write_fd = pipe_fds[1];

  • Data written to the file descriptor read_fd can be read back from write_fd.
slide89
FIFO
  • It is similar to a pipe.
  • Unlike pipes, a FIFO has a name associated with it (named pipe).
  • It uses a file as a communication way.
  • int mknod (char *path, int mode, int dev)
    • mode is or’ed with S_IFIFO
    • dev is equal 0 for FIFO.
fifo in shell
FIFO in shell
  • You can make a FIFO using the mkfifo command. Specify the path to the FIFO
  • on the command line. For example, create a FIFO in /tmp/fifo by invoking this:

% mkfifo /tmp/fifo

% ls -l /tmp/fifo

prw-rw-rw- 1 samuel users 0 Jan 16 14:04 /tmp/fifo

  • The first character of the output from ls is p, indicating that this file is actually a FIFO.
fifo in shell1
FIFO in shell
  • In one window, read from the FIFO by invoking the following:
    • % cat < /tmp/fifo
  • In a second window, write to the FIFO by invoking this:
    • % cat > /tmp/fifo
  • Then type in some lines of text. Each time you press Enter, the line of text is sent through the FIFO and appears in the first window.
  • Close the FIFO by pressing Ctrl+D in the second window.
  • Remove the FIFO:
    • % rm /tmp/fifo
fifo creation
FIFO creation
  • This command creates a fifo in /home/cnd/mod_done, with read/write permisasions for owner, and with read permissions for group and others.

#include <sys/types.h>

#include <sys/stat.h>

status = mkfifo("/home/cnd/mod_done", S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);

accessing a fifo
Accessing a FIFO
  • Access a FIFO just like an ordinary file.
  • To communicate through a FIFO, one program must open it for writing, and another program must open it for reading.
  • For example, to write a buffer of data to a FIFO using low-level I/O routines, you could use this code:

int fd = open (fifo_path, O_WRONLY);

write (fd, data, data_length);

close (fd);

  • To read a string from the FIFO using C library I/O functions, you could use this code:

FILE* fifo = fopen (fifo_path, “r”);

fscanf (fifo, “%s”, buffer);

fclose (fifo);

name space
Name Space
  • The set of possible names for a given type of IPC is called its name space.
  • The name is how the client and server connect to exchange messages.
  • key_t ftok (char *path, char proj);
message queue
Message Queue
  • Message queues are a linked list of messages stored within the kernel.
  • We don’t have to fetch messages in a first-int, first-out order.
    • We can fetch messages based on their type field.
  • A process wants to impose some structure on the data being transferred.
message queue cont
Message Queue (cont.)
  • int msgget (key_t key, int msgflag);
  • A new queue is created, or an existing queue is open by msgget.
message queue cont1
Message Queue (cont.)
  • int msgsnd(int msgid, void *ptr, size_t len, int flag);
  • Data is placed onto a message queue by calling msgsnd;
  • ptr points to a long integer that contains the positive integer message type, and it is immediately followed by the message data.
    • Struct my_msg

{

long type;

char data[SIZE];

}

message queue cont2
Message Queue (cont.)
  • int msgrcv (int msgid, void *ptr, sizet len, long mtype, int flag);
  • The type argument lets us specify which message we want:
    • mtype == 0, the first message on the queue
    • mtype > 0, the first message on the queue whose type equals mtype.
    • mtype < 0, the first message on the queue whose type is the lowest value less or equal to the absolute value of mtype.
message queue cont3
Message Queue (cont.)
  • int msgctl (int msgid, int cmd, struct msgid_ds *buf);
  • The msgctl function performs various operations in a queue.
shared memory
Shared memory

Client

Server

Input

file

Output

file

Pipe, FIFO,

message

kernel

shared memory cont
Shared memory (cont.)

Shared memory

Client

Server

Input

file

Output

file

Kernel

shared memory cont1
Shared memory (cont.)
  • int shmget (key_t key, int size, int flag);
  • A shared memory segment is created, or an existing one is accessed with the shmget system call.
shared memory cont2
Shared memory (cont.)
  • Char *shmat (int shmid, char *shmaddr, int shmfalg);
  • The shmget dose not provide access to the segment for the calling process.
  • We must attach the shared memory segment by calling the shmat system call.
shared memory cont3
Shared memory (cont.)
  • int shmdt (char *shmaddr);
  • When a process is finished with a shared memory segment, it detaches the segment by calling the shmdt system call.
  • This call dose not delete the shared memory segment.
shared memory cont4
Shared memory (cont.)
  • int shmctl (int shmid, int cmd, struct shmid_ds *buf);
  • The msgctl function performs various operations in a shared memory segment.
shared memory cont5
Shared memory (cont.)
  • Two or more processes access the same memory
  • The fastest form of IPC, as fast as accessing a process unshared memory
  • It dose not require a system call or entry to the kernel.
  • Each process can either read and write
synchronization
synchronization
  • Kernel does not synchronize accesses to shared memory.
  • You must provide your own synchronization
      • A process should not read from the memory until after data is written there
      • Two processes must not write to the same memory location at the same time
shared memory cont6
Shared memory (cont.)
  • To use a shared memory segment, one process must allocate the segment.
  • Then each process desiring to access the segment, must attach the segment.
  • After finishing its use of the segment, each process detaches the segment.
  • At same point, one process must deallocate the segment.
  • for multiple processes to use a shared segment, they must make arrangements to use the same key.
allocate a shared memory segment
allocate a shared memory segment
  • int shmget (key_t key, int size, int flag);
  • A shared memory segment is created, or an existing one is accessed with the shmget system call.
attach a shared memory segment
Attach a shared memory segment
  • Char *shmat (int shmid, char *shmaddr, int shmfalg);
  • The shmget dose not provide access to the segment for the calling process.
  • We must attach the shared memory segment by calling the shmat system call.
detach a shared memory segment
Detach a shared memory segment
  • int shmdt (char *shmaddr);
  • When a process is finished with a shared memory segment, it detaches the segment by calling the shmdt system call.
  • This call dose not delete the shared memory segment.
operations in a shared memory segment
operations in a shared memory segment
  • int shmctl (int shmid, int cmd, struct shmid_ds *buf);
  • The msgctl function performs various operations in a shared memory segment.
semaphore
Semaphore
  • Semaphores are a synchronization primitive.
  • To obtain a shared resource:
    • Test the semaphore that controls the resource.
    • If the value is positive the process can use the resource. The process decrements the value by 1.
    • If the value is 0, the process goes to sleep until the value is greater than 0.
semaphore1
Semaphore
  • Processes must coordinate access to shared memory
  • Semaphores can be used for synchronizing

Processes

  • To obtain a shared resource:
    • Test the semaphore that controls the resource.
    • If the value is positive the process can use the resource. The process decrements the value by 1.
    • If the value is 0, the process goes to sleep until the value is greater than 0.
semaphore cont
Semaphore (cont.)
  • int semget (key_t key, int nsems, int flag);
  • This function get a semaphore ID.
  • int semctl (int semid, int semnum, int cmd, union semun arg);
  • The semctl function performs various operations in a semaphore.
semaphore cont1
Semaphore (cont.)
  • int semop (int semid, struct sembuf *semop, size_t nops);
  • Struct sembuf

{

ushort sem_num;

short sem_op;

shoet sem_flag;

}

semaphore cont2
Semaphore (cont.)
  • Each particular operation is specified by a sem_op value:
    • sem_op > 0, this correspond to the release of resources. The sem_op value is added to the current value;
    • sem_op == 0, the caller wants to wait until the semaphore’s value become zero.
    • sem_op < 0, this correspond to the allocation od resources. The caller wants to wait until the value become greater or equal the absolute value of sem_op. then the absolute value of sem_op is subtracted from the current value.