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?
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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With