I'm creating child processes in a for
-loop. Inside the child process, I can retrieve the child PID with getpid()
.
However, for some reason when I try to store the value of getpid()
into a variable declared by the parent process, the change is nullified when I check for it in the parent process. I'm assuming this has to do with some sort of process variable scope. Not really familiar with C, so can't be too sure.
Anyhow what is a way of storing the result of getpid()
of a child PID (when called from the child process) into a variable in the parent process?
Or maybe another approach is storing fork()
into a variable in the parent and calling some function on that variable to retrieve the child's PID? I don't know how to do this either, so if this is the better way, how would you do this?
As mentioned in previous answer that "fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process." So, the code can be written in this way:
This link is very helpful and explains in detail.
if
fork()
is successfully created then it returns 0 value in the child process.fork
already returns the child's pid. Just store the return value.look at man 2 fork:
There are two main functions to get the process id of parent process and child. getpid() and getppid()
If you are calling fork in the following way:
Then pid is in fact your child PID. So you can print it out from the parent.