...
Sometimes it is not practical for a program to close all active file descriptors before issuing a system call such as system() or exec(). An alternative on some POSIX systems is to use the OFD_CLOEXEC flag, or FDO_CLOEXEC flags when available, to set the close-on-exec flag for the file descriptor.
| Code Block | ||
|---|---|---|
| ||
int fd; int flags; char *editor; if(!(fd = open(file_name, 0, O_RDONLY)) == -1) { /* Handle Error */ } if((flags = fcntl(fd, F_GETFD, 0)) == -1) { /* Handle Error */ } if(fcntl(fd, F_SET_FDSETFD, flags | FD_CLOEXEC) == -1) { /* Handle Error */ } /* ... */ editor = getenv("EDITOR"); if (editor == NULL) { /* Handle getenv() error */ } system(editor); |
Some systems (Linux >= 2.6.23) provide have an O_CLOEXEC flag which provides the close-on-exec function directly in open(). This flag will be required by POSIX.1-2008. In multi-threaded programs this flag should be used if possible as it avoids a timing hole between open() and fcntl() when using FD_CLOEXEC, during which another thread could create a child process while the file descriptor does not have close-on-exec set.
| Code Block | ||
|---|---|---|
| ||
int fd; char *editor; if(!(fd = open(file_name, O_CLOEXEC, RDONLY|O_RDONLYCLOEXEC)) == -1) { /* Handle Error */ } /* ... */ editor = getenv("EDITOR"); if (editor == NULL) { /* Handle getenv() error */ } system(editor); |
...