after fork(), parent process can still change variable value?

    #include <stdlib.h>
    int main()
            int i=1;
            pid_t j=fork();
            i=5;    // will this line runs in both parent and child?



I think after fork() in the child process, i is 1 no matter how the parent process change it but the result is 4 why not 1?


You change the value of i in the parent and in the child. All the code after fork() runs in both processes.

pid_t j=fork();
i=4;              // <- this runs in both parent and child
if(j==0) {
   ...            // <- this runs only in child because of the if
i=5;              // <- this runs in both parent and child

The execution in the child starts at the line after fork, and then runs normally. There is nothing special in the execution of the child at all from being a "child" - normal code flow happens just as in the parent.

If you want to clearly separate what happens in the child and what goes on in the parent, make it explicit in your code:

pid_t j = fork();
if (j < 0) {
  // fork failed, no child created at all
  // handle error
} else if (j == 0) {
  /* In child process */
} else {
  /* In parent process */

The code below fork runs in both parent and child..

Need Your Help

Get height of Parent

c# windows windows-store-apps windows-store

I am creating canvas at run-time with rectangle and thumb as a child.

VS2010 output window next message jumping to lines other than warning or error

c# visual-studio-2010 build

I'm used to this nice shortcut for jumping to next message in build output window (F4).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.