Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C fork dealing with global variable

I'm not understanding the output of this program:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

int i = 0;

int main()
{
    while(i<3)
    {
        fork();

        printf("%d\n",i);
        ++i;
    }
}

The output is:

0
1
2
2
1
2
0
1
2
2
2
1
2
2

Can please someone tell me how I should tackle this issue in order to fully understand why I'm getting this output?

like image 376
Bruno Avatar asked Jan 28 '10 22:01

Bruno


People also ask

Does forked process share global variables?

No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents.

Does C support global variables?

C and C++ The C language does not have a global keyword. However, variables declared outside a function have "file scope," meaning they are visible within the file.

What will happen when line C fork () is executed?

fork() in C. Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process.

Do child processes inherit global variables?

A global variable can be inherited by a child process. This means that we can define and assign a global variable in a parent process, then access and assign values to it in a function executed by a child process.


2 Answers

Fork will make a copy of the process. An independent copy of the process. So, if a global variable contains 3 at the time you fork, each copy of the process gets their very own 3. And if they modify, their modifications are completely independent.

like image 138
bmargulies Avatar answered Oct 05 '22 18:10

bmargulies


Change your code to this and the output should make a lot more sense:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int i = 0;

int main()
{
    while (i < 3)
    {
        fork();
        printf("pid = %d, i = %d\n", getpid(), i);
        ++i;
    }
    return 0;
}
like image 38
Paul R Avatar answered Oct 05 '22 17:10

Paul R