Roopa
Roopa

Reputation: 31

Is it possible to use fork without exec if both processes are executing the same program?

Here is a code sample where the fork library call is used to create a child process which shares the parent's address space. The child process executes its code without using the exec system call. My question is: is the exec system call not required in the case that both the parent and child processes are executing the same program?

  #include <stdio.h>
  int main()
  {
      int count;
      count = fork();
      if (count == 0)
          printf("\nHi I'm child process and count =%d\n", count);
      else
          printf("\nHi I'm parent process and count =%d\n", count);
     return 0;
 }  

Upvotes: 3

Views: 1822

Answers (2)

user3386109
user3386109

Reputation: 34839

The answer to this question may be different depending on the operating system. The man page for fork on OS X contains this ominous warning (bold portion is a paraphrase of the original):

There are limits to what you can do in the child process. To be totally safe you should restrict yourself to only executing async-signal safe operations until such time as one of the exec functions is called. All APIs, including global data symbols, in any framework or library should be assumed to be unsafe after a fork() unless explicitly documented to be safe or async-signal safe. If you need to use these frameworks in the child process, you must exec. In this situation it's reasonable to exec another copy of the same executable.

The list of async-signal safe functions can be found in the man page for sigaction(2).

Upvotes: 4

kaylum
kaylum

Reputation: 14044

Is it possible to use fork without exec

Yes, it is possible.

is the exec system call not required in the case that both the parent and child processes are executing the same program

Yes, it is not required in that case.

Upvotes: 3

Related Questions