Processes
Download
1 / 122

Processes and Inter-Process Communication - PowerPoint PPT Presentation


  • 184 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


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

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).


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


    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.


    • 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.


    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 cont1
    exit (cont.)


    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.



    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.


    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)


    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.



    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


    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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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


    Create a thread
    Create a thread processor


    Passing data to thread
    Passing data to thread processor

    • Use thread argument to pass a pointer to some structure or array of data


    • ` processor


    Joining threads
    Joining Threads processor

    • 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 processor

    • What is a Process?

    • Process Control

    • Process Relationship

    • Inter- Process Communication


    IPC processor

    • 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.


    IPC processor

    • Pipe

    • FIFO

    • Message queue

    • Shared memory

    • socket


    Child processor

    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 processor (cont.)

    • int pipe (int *filedes);

    • filedes[0] : open for reading

    • filedes[1] : open for writing

    • pipe command :

      • who | sort | lpr


    Pipe synchronization
    Pipe synchronization processor

    • 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 processor

    • 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.


    Pipe example
    Pipe example processor


    FIFO processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor(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 processor(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 processor(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 processor(cont.)

    • int msgctl (int msgid, int cmd, struct msgid_ds *buf);

    • The msgctl function performs various operations in a queue.


    Shared memory
    Shared memory processor

    Client

    Server

    Input

    file

    Output

    file

    Pipe, FIFO,

    message

    kernel


    Shared memory cont
    Shared memory processor(cont.)

    Shared memory

    Client

    Server

    Input

    file

    Output

    file

    Kernel


    Shared memory cont1
    Shared memory processor(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 processor(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 processor(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 processor(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.) processor

    • 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 processor

    • 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.) processor

    • 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 processor

    • 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 processor

    • 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 processor

    • 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 processor

    • int shmctl (int shmid, int cmd, struct shmid_ds *buf);

    • The msgctl function performs various operations in a shared memory segment.



    Semaphore
    Semaphore processor

    • 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 processor

    • 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 processor(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 processor(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 processor(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.



    Question? processor


    ad