I am doing 3 consecutive forks in a C program.
1. Is it going to execute in the same order ? ( My guess is yes ).
2. If I do a pgrep myexecutable
from shell, would it give the process ids in the same order as they were started ? ( my guess is no, because you cant guarantee what pid the system gives the child, right ? )

- 7,888
- 13
- 48
- 85
-
1It should not matter, for any reasonable program. – Lightness Races in Orbit Feb 15 '11 at 10:12
-
PID of last forked process is `$!` https://stackoverflow.com/a/25361436/6655092... I found this question while actually looking for `$!`, so I thought I'd post it here. – JakeD May 25 '18 at 23:41
2 Answers
There would be a total of 8 processes running after 3 forks are executed
so now the pid would be depend on which order the child process are created by and also in which order the children of children are created.
could be like
main - 12345
child1_of_main_after_fork1 12346
child2_of_child1_after_fork2 12347
child3_of_main_after_fork2 12348
child4_of_main_after_fork3 12349
child5_of_child1_after_fork3 12350
child6_of_child2_after_fork3 12351
child7_of_child3_after_fork3 12352

- 8,409
- 22
- 75
- 99

- 14,350
- 11
- 53
- 100
Shrinath, you should check the documentation for fork()
, here it is:
Upon successful completion, fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, a value of -1 is returned to the parent process, no child process is created, and the global variable errno is set to indi- cate the error.
All that means for you, is that means your parent process will get the child's PID when it forks. The child knows it's the child, because fork()
will return 0 to the child, so something like:
if((cpid = fork())) { // This is the parent processs, child pid // is in `cpid` variable }else{ // This is the child process, do your child // work here. }
Beware for the chance that you get a minus number (so there's no child), you should check for that.
The output of ps
will vary by system, but you should see an example, if you look at the whole tree (make your processes sleep, so you have time to check the ps
output.)

- 6,270
- 5
- 49
- 81
-
Please go through the question again and tell me which part of the question isn't clear... I am not asking "how to create a child process", or "how will I know the pid of the child"... All I am asking is would it be in same order everytime ? Thanks for your valuable time – Shrinath Feb 15 '11 at 10:10