0

Why pid is not carried for child process

Refer code below: Why Int I value is carried in child process , but not pid. https://sololearn.com/compiler-playground/cjVeE2SBfj8y/?ref=app

6th Jun 2024, 7:01 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Antworten
+ 2
Sounds good Brian I got idea about i variable and can understand that it gets copied to new process with values One doubt still about fork process output that is pid. If it was unitinialized at the time of duplicate process creation, does it guarantee to have default value or random value may occur in some case?
7th Jun 2024, 4:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Ketan Lalcheta to the best of my knowledge (which is not authoritative in C++, but rooted in my C expertise), it would not fill in a default value. If you remain in doubt, the wisest approach would be to initialize pid to a predetermined value (0) and then call fork(). The optimizer would remove a redundant assignment if the compiler already fills in the same default. Also, making it explicit makes better code for future maintenance. EDIT: I see that you updated the code to try this idea, and it proved that I was wrong. john ds replied with the right answer.
7th Jun 2024, 5:12 AM
Brian
Brian - avatar
+ 2
Ketan Lalcheta Upon successful completion, fork() returns 0 to the child process. https://pubs.opengroup.org/onlinepubs/007908775/xsh/fork.html#:~:text=The%20fork()%20function%20creates,has%20a%20unique%20process%20ID.
7th Jun 2024, 1:41 PM
john ds
john ds - avatar
+ 1
Ketan Lalcheta I think the fork occurs first, and then pid gets its assigned value - that is, *after* the fork() function returns. See if this makes sense: 1. Creates pid variable, uninitialized. 2. Calls fork() 3. Creates duplicate process and copies all variable values. 4. Returns from fork() and assigns PID to variable pid. The forked process gets whatever undefined value happens to be in the newly-defined pid variable.
7th Jun 2024, 3:39 AM
Brian
Brian - avatar