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.

- 514
- 3
- 8
-
Which one? You have two processes after `fork()`. – Ignacio Vazquez-Abrams Aug 08 '17 at 12:15
-
2It would cause 0 data loss in the parent process (except that they might continue sharing file descriptors so some data loss might occur unless they're closed in the child); and 100 % data loss in the child process if the exec was successful...... – Antti Haapala -- Слава Україні Aug 08 '17 at 12:17
-
there is beautiful explanation [here](https://stackoverflow.com/questions/1653340/differences-between-fork-and-exec) for the confused mind – Ulug Toprak Aug 08 '17 at 12:22
-
@Ignacio Vazquez-Abrams : I meant Parent Process – Twinkle Aug 08 '17 at 12:43
1 Answers
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.

- 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