如何设置默认的close-on-EXEC [英] how to set close-on-exec by default

查看:346
本文介绍了如何设置默认的close-on-EXEC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施库运行命令。图书馆是C,在Linux上。

I'm implementing a library to run commands. The library is C, on Linux.

目前,它做了的popen()调用来运行一个命令,并得到输出。问题是,该命令继承了所有当前打开的文件处理程序。

It currently does a popen() call to run a command and get output. The problem is that the command inherits all currently open file handlers.

如果我做了一个叉/ EXEC我可以在孩子关闭处理程序作了明确规定。但是,这意味着重新实现的popen()。

If I did a fork/exec I could close the handlers in child explicitly. But that means re-implementing popen().

我可以设置近距离上EXEC上的所有处理器,而不由一个通过他们的循环呢?

Can I set close-on-exec on all handlers without looping through them one by one?

我可以设置近距离上EXEC为默认程序?

Can I set close-on-exec as default for the process?

谢谢!

推荐答案

没有,没有。

您只需要小心,并设置近距离上EXEC对你所关心的所有文件描述符。

You simply need to be careful and set close-on-exec on all file descriptors you care about.

设置很容易,但:

#include <fcntl.h>
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);

#include <unistd.h>
/* please don't do this */
for (i = getdtablesize(); i --> 3;) {
    if ((flags = fcntl(i, F_GETFD)) != -1)
        fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}

如果您运行的是Linux内核和GE; 2.6.23和glibc&GE; 2.7 打开(以及其他类似的系统调用)接受一个新的标志 O_CLOEXEC

If you are running Linux kernel ≥2.6.23 and glibc ≥2.7, open (along with other similar syscalls) accepts a new flag O_CLOEXEC:

#include <unistd.h>
fd = open("...", ... | O_CLOEXEC);

如果您运行的是Linux内核和GE; 2.6.24和glibc&GE; 2.7 的fcntl 接受新参数 F_DUPFD_CLOEXEC

If you are running Linux kernel ≥2.6.24 and glibc ≥2.7, fcntl accepts a new argument F_DUPFD_CLOEXEC:

#include <fcntl.h>
newfd = fcntl(oldfd, F_DUPFD_CLOEXEC);

如果您运行的是Linux内核和GE; 2.6.27和glibc&GE; 2.9,有新的系统调用 pipe2 dup3 等等,还有更多的系统调用获得新的 * _ CLOEXEC 标记:

If you are running Linux kernel ≥2.6.27 and glibc ≥2.9, there are new syscalls pipe2, dup3, etc., and many more syscalls gain new *_CLOEXEC flags:

#define _GNU_SOURCE
#include <unistd.h>
pipe2(pipefds, O_CLOEXEC);
dup3(oldfd, newfd, O_CLOEXEC);

注意 POSIX specifies

的popen()的功能应保证从previous的的popen()的调用,在父进程中保持开放的溪流在新的子进程被关闭

The popen() function shall ensure that any streams from previous popen() calls that remain open in the parent process are closed in the new child process.

所以,如果你担心的的泄漏,不要。

so if you're worried about that leak, don't be.

这篇关于如何设置默认的close-on-EXEC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆