Derek
Derek

Reputation: 53

Another Fork() program in C

So I am continuing some more problems on Fork() and found some sample code on a website called geeksforgeeks. The following code segment:

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

void forkexample() 
{
    int x = 1;

    if (fork() == 0)
        printf("Child has x = %d\n", ++x);
    else
        printf("Parent has x = %d\n", --x);
}
int main()
{
    forkexample();
    return 0;
}

Now I can see why the solution can be either Child has x = 2 and Parent has x = 0 but I am having some issues trying to visualize the tree. The big problem that I have visualizing this is that the first if statement is for the child process, so how would the tree look? Here is what I have come up with in terms of a visualization of this program.

image

Or would the main node on Level 0 be a Child node because of the order of the if statement coming first (this is a possibility but the else statement could come first as well as it is running concurrently).

Any help? Is this visualization correct or is there something I am missing?

Would appreciate the help , thank you.

Upvotes: 0

Views: 689

Answers (2)

Nicolas Guerin
Nicolas Guerin

Reputation: 366

I don't see where the question is here..

The schema is good it's like this. Fork() creates a new process by duplicating the calling process. On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created (google). You must check the return value to be sure that you're in the child process which is running independently.

Try this :

#include <unistd.h>

int main() 
{
  pid_t p;
  int   x;

  x = 1;
  p = fork();
  printf("pid = %d\n", p);
  if (p == 0) {
    printf("Child has x = %d and pid = %d\n", ++x, p);
    sleep(1);
  } else {
    printf("Parent has x = %d and pid = %d\n", --x, p);
    sleep(1);
  }
}

They are executed at the same time because they are independant but the parent is primary at the ouput

Nicolas

Upvotes: 0

Octavio Galindo
Octavio Galindo

Reputation: 340

No, your visualization is wrong.

After the fork you have TWO processes: Parent and Child. (PERIOD)

A single parent may spawn multiple children, and each may spawn children of their own. But after a single fork, the "tree" is two "nodes".

Not sure if you are trying to graph:

  • Processes over time, then YES, you are correct, one process has become two.
  • Process relationship, then NO, you should only have one parent, one child.
  • Execution path, I guess... at some point fork() is called, next thing you know, you have two processes executing the if() statement.

Upvotes: 1

Related Questions