I need to write a program in C that will:
- create child process (child_process1)
- print PID of parent process using getppid()
- the child_process1 will create another subprocess (child_process2)
- child_process2 will print PID of parent process (child_process1) using getppid() and its own PID using getpid()
So far, I’ve written something like that:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
//declaration of PID holding variables
pid_t child1, child2;
pid_t child1_PID, child2_PID;
//forking parent process
child1 = fork();
//redeclaring PID so as to omit double execution of code by both parent and child processes
child1_PID = child1;
//check whether child1_PID contains PID of a child process
if(child1_PID == 0){
//print PID of parent process
printf("%dn",getppid());
//make child process child1 fork child process child2
child2 = fork();
//redeclaring PID so as to omit double execution of code by both parent and child processes
child2_PID = child2;
//check whether child2_PID contains PID of a child process
if(child2_PID == 0){
//print PID of parent process of child process child2 (child1)
printf("%dn",getppid());
//print PID of child process child2
printf("%dn",getpid());
}
}
return 0;
}
But the code doesn’t seem to work the way I want. Furthermore, sometimes it prints 4 PIDs, sometimes only one.
New contributor
Krzysztoff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.