Tuesday, March 4, 2008

CSE 2031 Lecture 13

fork()

getpid() // get process ID

getppid() // get parent process ID


 

fork is a system call w/ no arguments but it returns a value

the parent and the child see different return values

the newly created child see's return value 0

the parent that called fork see's a nonzero return value, namely the ppid of the newly created child


 

a child finds a parents process ID by calling getppid()


 

when a child terminates, OS saves PID, exit status, cpu time ... of child

and passes this to the parent when parent calls wait() or waitpid


 

until then the child is a 'zombie'

the OS can't free up the resources for the child until the parent waits on the child

if the parent finishes before the child, then the child is reparented

    wait

            - block until first child finishes

    waitpid

        - block

        -specify which child to wait for

pid of child <- wait(int*)

int status

wait(&status)


 

%a.out

    - what we have here is the shell foks off a child and waits for the child to return

    child - executes a.out

    once done the parent outputs the prompt and waits for another command to be inputted

if %a.out &

    -the shell doesn't wait.

-----------------------------------------------------------------------------------------------------------------------------------------------


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;

fork();

fork();

printf("Hello\n");

return 0;

}


 

// prints 4 'Hello" lines

-----------------------------------------------------------------------------------------------------------------------------------------------


 

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

#include <stlib.h>


 

#define MAX 10

int main(void)

{


 

int i;


 

switch(fork())

{

case -1:

    perror("Bad fork");

    exit(1)

case 0:

    /* CHILD */

    for (i=0; i < MAX; i++)

    {

        printf("CHILD\n");

    }break;

default:

    /* PARENT */

    for(i = 0; i < MAX; i++)

    {

        printf("\tPARENT\n");

    }

    printf("pid = %d\n", getpid());

    printf("ppid = %d\n", getppid());

return 0;    


 

}


 

/*prints CHILD 10 times, pid = 2153, ppid = 2152, prints PARENT 10 times then , pid = 2255, ppid = 27289

eventually the parent executes before the child because it is left to the OS to decide the PPID*/

/* if wait((int * ) 0);

was typed after /*PARENT*/ it will always print CHILD first*/


 

along with fork() there is exec()


 

%a.out hello there world becomes


 

argv -> -> a.out

->hello

->there

->world

->null


 

-------------------------------------------------

execlp("cat", "-n", "temp", NULL);

"cat"

No comments: