1

I am comparatively new to the linux programming. I wonder whether the exec() function called after fork() can cause data loss in the parent process.

Twinkle
  • 514
  • 3
  • 8

1 Answers1

6

After a successful call to fork, a new process is created which is a duplicate of the calling process. One thing that gets duplicated are the file descriptors, so it's possible for the new process to read/write the same file descriptors as the original process. These may be files, sockets, pipes, etc.

The exec function replaces the currently running program in the current process with a new program, overwriting the memory of the old program in that process. So any data stored in the memory of the old program is lost. This does not however affect the parent process that forked this process.

When a new program is executed via exec, any open file descriptors that do not have the FD_CLOEXEC (close-on-exec) flag set (see the fcntl man page) are again preserved. So now you have two processes, each possibly running a different program, which may both write to the same file descriptor. If that happens, and the processes don't properly synchronize, data written by one process to the file may overwritten by the other process.

So data loss can occur with regard to writing to file descriptors that the child process inherited from the parent process.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    *When a new program is executed via exec, open file descriptors are again preserved.* In general, that's true. But open file descriptors with the [`FD_CLOEXEC` flag set are closed on `exec*` calls](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/fcntl.h.html): "`FD_CLOEXEC` Close the file descriptor upon execution of an *exec* family function." – Andrew Henle Aug 08 '17 at 12:56
  • @AndrewHenle Thanks for bringing that up. I've included that detail in the answer. – dbush Aug 08 '17 at 14:04