Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

fork

exec

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;
 }  
like image 982
Roopa Avatar asked Dec 08 '25 14:12

Roopa


1 Answers

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).

like image 177
user3386109 Avatar answered Dec 10 '25 03:12

user3386109