-2

I am a bit confused about the value which the function fork returns. I understand that value 0 is for child process and value >0 is for parent process. I have the code below

int main()   
{    
   int pid;
   pid = fork();
   if(pid == 0)
       //DO SOMETHING
   else
       //DO SOMETHING ELSE 
   return 0;
}

The valiable pid after fork is different for each process ? I can't understand how it switches value. And I have a second part with code

int main()
{
    int pid;
    if (pid == 0)
    {
          return 5;
    }
    printf("parent = %d waits for child = %d ", getpid(), pid);
    waitpid(pid, NULL, 0);
    printf("child terminates!")
    return 0;
}

in which I can't understand why pid on line with first printf has the value of child. It shouldn't be the id of parent ?

1 Answers1

0

The valiable pid after fork is different for each process ?

Yes, that's the new process ID you get as the return value. There can't be same processes with the same ID at the same time, so whenever you fork your usually get an unique one.

The process is cloned while still inside the fork() call, including copies of all variable memory contents (heap, stack, data segments). Once the copy is completed, the kernel resumes execution of both processes, but gives different return values.

in which I can't understand why pid on line with first printf has the value of child. It shouldn't be the id of parent ?

getpid() returns the ID of the parent, since that is the context in which you are executing it now. pid is just garbage (uninitialized memory) in that example, so whatever you think you are seeing, it's not an process ID but only some random memory content.

Ext3h
  • 5,713
  • 17
  • 43
  • In the second question you say that `pid` it not a process ID. But the parent uses waitpid() for waiting the child process and it waits. So why it's not a process ID ? – Dimitris Baltzis Sep 16 '17 at 19:33
  • @DimitrisMpl It's a stack allocated integer variable, which wasn't initialized at all. It is NOT the same `pid` variable you used in the other function, despite the same name. So it just contains whatever was last written to the stack in the place. – Ext3h Sep 16 '17 at 19:49