1

I am new to Operating Systems and Linux hence this may be very basic question but I cannot find an answer.

According the resources I have read so far, the fork() method creates new process by generating system call to the operating system. The created process is an exact copy of the calling process.

However, I think that the created process(child) and the calling process(parent) are not exactly same. The codes coming before the fork() method in parent process are not copied to child process.

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

int main(void){
   X
   int child1 = fork();
   A
   B
   C
   D
   int child2 = fork();
   E
   F
   return 0; 
}

The child2 process does not contain the code lines A B C D ,whereas the child1 process contains all of the lines except for X. Actually this is my thought. On the other hand, in everywhere, it is said that child process is exact copy of parent process.

Can anyone say that which one is true ?

  • 1
    It is a copy. Nowhere does it say the new process starts over from the beginning. If it did, then they wouldn't be a copy, they'd each have arrived at the same point (assuming the code doesn't branch differently) independently. Which would be no different from just launching the program twice. – Patrick Mar 3 '18 at 21:44
  • 1
    Just a couple notes. ‘Method’ is not a C term. fork() is a syscall and the way it is often written is fork(2) which is the man section. 2 is syscalls and 3 are library functions. You should also be aware that it returns a pid_t and not an int. – Pryftan Mar 4 '18 at 21:23
2

fork() "returns twice". In the parent process, it returns the PID of the child. In the child process, it returns zero. This is assuming there were no errors. This means that your code, doing two forks, will result in a total of four processes.

The processes are identical in all ways except in the ways described in fork(2) (man 2 fork).

For example, in the code

while (1) {
   A
   B
   C
   fork();
}

the statements A, B and C will be executed by an ever increasing number of processes (don't actually write code like this, it may cause your system to lock up).

In your example, the instructions will exist for execution by the child processes too, but there is no code path that leads back to these instructions. The child process, since it is identical to the parent at the time of the call to fork(), will start to execute at the point in the code where the fork() was called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.