3

I have a parent process having some children which don't need the FIFO descriptor opened by the parent before forking. I have tried to do the following approaches that

  • fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); after opening the fd.
  • fd = open(/tmp/testfifo, O_RDONLY|O_CLOEXEC|O_NONBLOCK);

To see whether it works correctly I do following steps but the first one doesn't work since it is decided as a bug. However, I don't understand what the wrong with the second is.

First approach,

if (fcntl(fd, F_GETFD) & FD_CLOEXEC) {
    fprintf(stderr, "FD_CLOEXEC is set\n");
}

Second approach over the terminal,

lsof -n | grep /private/tmp/testfifo

With two children it prints,

program   17898 soner    3r     FIFO     0t0 5274098 /private/tmp/testfifo
program   17898 soner    4w     FIFO     0t0 5274098 /private/tmp/testfifo
program   17899 soner    3r     FIFO     0t0 5274098 /private/tmp/testfifo
program   17899 soner    4w     FIFO     0t0 5274098 /private/tmp/testfifo
program   17900 soner    3r     FIFO     0t0 5274098 /private/tmp/testfifo
program   17900 soner    4w     FIFO     0t0 5274098 /private/tmp/testfifo

Is my approach wrong? Or did I do something wrong? Or did I misunderstand rationale of the flag?

  • 1
    Are you calling `exec()` in the child process? – Barmar Apr 18 '19 at 16:13
  • @Barmar no sir, but what if even I call that? Assume that I've done the steps before exec. – Soner from The Ottoman Empire Apr 18 '19 at 16:14
  • 3
    `CLOEXEC` is short for "close on exec". It means the descriptor will be closed automatically when the process calls `exec()`. It's not closed when forking. – Barmar Apr 18 '19 at 16:15
  • @Barmar so, do all children close it by calling _close()_? Isn't there another way? – Soner from The Ottoman Empire Apr 18 '19 at 16:17
  • 1
    Yes, that's what they normally do. – Barmar Apr 18 '19 at 16:19
  • A (perhaps questionable) idiom I've seen used: `if ((pid = fork()) != 0) { for (i=3;i<256;i++) close(i); }` – BadZen Apr 18 '19 at 16:57
  • Related, see [Prevent file descriptors inheritance during Linux fork](https://stackoverflow.com/q/5713242/608639), [Why does closing file descriptors after fork affect the child process?](https://stackoverflow.com/q/27483556/608639), [Close all File Handles when Calling posix_spawn](https://stackoverflow.com/q/21950549/608639), etc. The `posix_spawn` Q&A provides a very good sample that avoids closing `STDIN_FILENO` and friends if they are numbered in an unusual way. – jww Apr 18 '19 at 18:08

0 Answers0