Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does fork() works in this example?

regarding this code:

#include <stdio.h>
int main(){
    int x = 1;
    if (0 == fork()){
        int x = x + 1;
        fork();
    }
    else{
        int x = 4 * x;
        fork();
    }
    printf("%d",x);
}

Some friends of mine told me that the result should be 2244, but when I try and run it, I get 1111.

Can you please help me understand how to fork() works here, and which answer is correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks a lot!

>Solution :

The only thing that gets printed is x in the outermost scope of the main definition. It is 1, so only “1” is printed, once by each of the four processes created.

Inside the inner blocks, int x = …; creates a new object distinct from the outer x even though they have the same name. These objects are not printed, so their values are irrelevant.

In more detail, in int x = x + 1;, the second x in the initializer refers to the x being declared, so this definition attempts to use the object in its own initialization. The behavior of this is not defined by the C standard,1 so the program would be permitted by the standard to go horribly astray here. However, typical compilers implement some simplistic code here, either ignoring the initialization since it is essentially meaningless or implementing the x + 1 using whatever bits happen to be already in the memory allocated for the new x. int x = 4 * x; has the same problem.

Footnote

1 Due to C 2018 6.3.2.1 2, which says the behavior is not defined when the value is used of an uninitialized automatic object whose address is not taken.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading