I just started studying C Language for my OS course and I'm facing a problem!
This is an exercise I'm trying to solve but just couldn't find a correct way of doing so it is asking me to create 2 child processes from the same parent process and then each child should print its PID and PPID before exit. After creating the two children processes, the parent enters the wait state by executing the system call wait(). Once a child exits, the parent prints its PID.
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(){
int id = fork();
if(id){
fork();}
printf("ID= %d PID= %d PPID= %d\n", id, getpid(), getppid());
return 0;
}```
Sample Run:
ID= 11091 PID= 11090 PPID= 8951
ID= 11091 PID= 11092 PPID= 1
ID= 0 PID= 11091 PPID= 11090
The problem is that when i create the 2 child from 1 parent by
int id = fork();
if(id){
fork();}
I just don't know what to do after that, I'm completely lost, how am I supposed to split the processes to make them do what I want to do it just seems I'm stuck inside the fork() call forever!
any help would be appreciated!
You are missing:
Here an example of code:
for (i=0; i < n_children; i++) {
pid = fork();
if (pid == 0) {
printf("Child created with PID %d. Parent PID %d\n”, getpid(), getppid());
exit(0);
} else if (pid > 0) {
printf("%d: child created with PID %d\n”, getpid(), pid);
} else {
printf("Fork error");
exit(1);
}
}