I am supposed to create a chain of N processes, where N is the command line parameter. Each process creates a child process, prints out its own PID and its parent's PID, and then waits for its child to terminate by calling the wait() function.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (int argc, char *argv[])
{
pid_t childpid = 0;
int i, nbrOfProcesses;
if (argc != 2) {
fprintf(stderr, "Usage: %s <processes>\n", argv[0]);
return 1;
}
nbrOfProcesses = atoi(argv[1]);
for (i = 0; i < nbrOfProcesses; i++) {
childpid = fork();
if (childpid == -1) {
perror("Fork failed");
exit(1);
}
else if (childpid != 0) {
printf("i: %d process ID: %4d parent ID: %4d child ID: %4d\n", i+1, getpid(), getppid(), childpid);
break;
}
}
wait(NULL);
return 0;
}
The response i Get is this:
[rajp1@gator lab6]$ ./chainofn
Usage: ./chainofn <processes>
What am i Doing wrong?
Any Advise will help
Thanks