I'm trying to learn UNIX programming and came across a question regarding fork(). I understand that fork() creates an identical process of the currently running process, but where does it start? For example, if I have code

int main (int argc, char **argv)

    int retval;
    printf ("This is most definitely the parent process\n");
    fflush (stdout);
    retval = fork ();
    printf ("Which process printed this?\n");

    return (EXIT_SUCCESS);

The output is:

This is most definitely the parent process
Which process printed this?
Which process printed this?

I thought that fork() creates a same process, so I initially thought that in that program, the fork() call would be recursively called forever. I guess that new process created from fork() starts after the fork() call?

If I add the following code, to differentiate between a parent and child process,

if (child_pid = fork ()) printf ("This is the parent, child pid is %d\n", child_pid);
else printf ("This is the child, pid is %d\n",getpid ());

after the fork() call, where does the child process begin its execution?

  • Also, how do I format the code? =)
    – thomas1234
    Nov 28, 2010 at 2:30
  • Indent the whole block of code by four spaces to format it. Nov 28, 2010 at 2:32

3 Answers 3


The actual fork forking happens inside the fork() primitive.

You can just imagine that inside the code of fork, a system call actually duplicates the process and start their execution at the same point with a slight difference:

  • the parent process fork function will return the process ID of the child process
  • the child process fork function will return 0.

Thus you know where you are during the programming, for instance

  if (fork())
     printf("Parent speaking\n");
     // parent's tasks
     printf("Child here\n");
     // child's tasks

fork() will copy the Process that is forked in the state it's currently in.*

It can be hard to say in which line of code the child process starts, you'd really have to look at a disassembled compiled version to understand. But it's often okay to assume it starts after fork has been called, certainly in your case.

It's copying all of it's variables, the stack, the whole thing (it's space in memory in fact) is copied byte by byte. The only thing that changes is the Process ID**.

If you do this:

int i = random_integer();

The child process will have the same value for i as it's parent.

*: In the child process, the return value of fork() will be 0 instead of the process ID.

**: Also, the child process will not have the parents Locks and resource utilisation.


The child process begins execution right after the fork() call. More specifically, right after fork() has returned either the child's processes ID or 0.

Your Answer

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