Waiting for a Process to Terminate
The parent process typically lets the child process execute,
but wants to know when the child has terminated,
and whether the child terminated successfully or otherwise.
A parent process calls the wait() system call to suspend
its own execution, and to wait for any of its child processes to
terminate.
The (new?) syntax &status
permits the wait() system call (in the operating system kernel)
to modify the calling function's variable.
In this way, the parent process is able to receive information about
how the child process terminated.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void function(void)
{
switch ( fork() ) {
case -1 :
printf("fork() failed\n"); // process creation failed
exit(EXIT_FAILURE);
break;
case 0: // new child process
printf("child is pid=%i\n", getpid() );
for(int t=0 ; t<3 ; ++t) {
printf(" tick\n");
sleep(1);
}
exit(EXIT_SUCCESS);
break;
default: { // original parent process
int child, status;
printf("parent waiting\n");
child = wait( &status );
printf("process pid=%i terminated with exit status=%i\n",
child, WEXITSTATUS(status) );
exit(EXIT_SUCCESS);
break;
}
}
}
|
CITS2002 Systems Programming, Lecture 9, p4, 19th August 2024.
|