I was given the task of creating exactly 6 processes using the c language and the command fork() and then have all 6 sleep using sleep() for a minute or two. The tougher part with this is that we are not allowed to use any loops at all, and only 3 calls to fork() total. I have managed to create 8 successfully but that is too many. So I was wondering if it is possible to fork or kill specific processes.I tried something I saw here but it is giving me 8 process not 6
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
/* fork a child process */
pid_t child = fork();
pid_t parent = getpid();
fork(); //2
if (fork() > 0) {//now we have 2 processes
//only the parent calls this fork because of the if, so we have 3 processes
fork(); //all 3 processes calls this fork, so we have 6 processes
wait(NULL);
printf("I am the child process");
printf("my PID = %d ",child);
printf("I am the parent process. My PID is %d\n", parent);
wait(NULL);
}
else if (child < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
}
out I am getting is:
I am the child processmy PID = 22150 I am the parent process. My PID is 22149
I am the child processmy PID = 22150 I am the parent process. My PID is 22149
I am the child processmy PID = 0 I am the parent process. My PID is 22150
I am the child processmy PID = 22150 I am the parent process. My PID is 22149
I am the child processmy PID = 0 I am the parent process. My PID is 22150
I am the child processmy PID = 0 I am the parent process. My PID is 22150
I am the child processmy PID = 0 I am the parent process. My PID is 22150
I am the child processmy PID = 22150 I am the parent process. My PID is 22149