source code of /small-scripts/stackexchange/chainfork.c
Last modified | |
Lines | 37 |
Parent directory Download CGIread sitemap Main page
Quick links: (none)
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define N_PROCS 42
int main(int argc, char *argv[])
{
int i;
pid_t child;
int status;
for (i = 0; i < N_PROCS; i++)
{
child = fork();
if (-1 == child)
{
fprintf(stderr, "fork() failed\n");
return 1;
}
/*
* The next iteration of the loop will only be executed
* by the child process.
*/
if (child) break;
}
printf("I'm process #%d (PID=%d)\n", i, (long)getpid());
/*
* On the last iteration of the while loop, child is zero
* for the last process in the chain.
*/
if (child) wait(&status);
return 0;
}