title: How does the fork() know whether it is in child process and in parent process?
body: <p>When a fork() system call gets executed , the processor turns into kernel mode.</p>
  <p>Thus at the end of the fork call a new process has spawned with a copy of almost all the constructs of the calling process (like the stack , user data and user programs etc.)</p>
  <p>It is also clear from many very well answered explanations that how a process (a programmer) can identify the difference between a child process and a parent process. As per the many documented answers on SO and elsewhere:</p>
  <blockquote>
  <p>if a call to <strong>fork()</strong> returns 0 it means that it is the child process that called the <strong>fork()</strong>. While if the return value of <code>fork()</code> is a positive integer, it means that the <strong>fork()</strong> was executed in the parent process and the returned positive integer is a PID of the child process. Ignoring the case of negative value returns for the sake of brevity.</p>
  </blockquote>
  <p><em>Hopefully my understanding above is correct :fingers_crossed:</em></p>
  <p>However, the below is what I am trying to understand better and hopefully in more details/depth:</p>
  <p><em>(please pardon my ignorance on the subject.I am just curious to understand this better from an internal perspective. This topic and my want to get a clearer understanding around it has literally started hijacking my dreams now :P )</em></p>
  <p>How does the system call (that gets invoked when <strong>fork()</strong> is called) know that now it is being executed as part of the child process <strong>and hence</strong> should return 0?</p>
  <p>Alternatively put, how does the system call know that it is being executed in the context of the parent process <strong>and hence</strong> it should now return the child process' PID this time and not 0?</p>
  <p>Or is it such that out of the 2 processes, since both are exact replicas, one of them randomly gets the return value as 0 and the other as the PID <strong>and then</strong> based on the which one got what return value, it is considered parent and child accordingly? :thinking_face:</p>
  <p>I'd be happy to be guided in the direction with any resources that I should go through. I would really appreciate any help in this direction actually. :pray:</p>