有没有办法在 UNIX 中临时禁用 fd 2?

发布于 2024-10-16 14:20:24 字数 252 浏览 2 评论 0原文

我编写了一个使用 fork 和 execv 启动另一个进程的应用程序。我创建了一个用于通知状态的管道,并从启动进程的主条目中写入一些字节来通知它已正确启动。否则,read 返回 0,因为写入管道已在 fork 进程中关闭。

唯一的麻烦是当进程没有启动(缺少库)时,我在 stderr 中收到一条关于此的消息。 shell的信息是写什么错误的。我宁愿安静地做。但是,如果我在 execv 之前关闭(2),我不会收到我想要的消息。我仍然想保持 fd 2 对 stderr 开放。

I've written an application which uses fork and execv to launch another process. I made a pipe for notification about status, and from main entry of the launched process, I write some bytes to notify that it's launched correctly. Otherwise, read returns 0 since the writing pipe has been closed in forked process.

The only trouble is when the process does not launch (absent library), I get a message in stderr about this. The message is written to shell what is wrong. I'd prefer to do it quietly. However if I do close(2) before execv I don't have the message what is what I want. Still I'd like to keep the fd 2 open for stderr.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨落成白 2024-10-23 14:20:24

据推测应用程序根本不喜欢没有 stderr 流。 而不是

close(2);

我尝试。

int tmpfd = open("/dev/null", O_WRONLY);
dup2(tmpfd, 2);
close(tmpfd);

当然,我们诚挚地邀请您添加错误处理,

Presumably the application does not like not having a stderr stream at all. Rather than

close(2);

I'd try

int tmpfd = open("/dev/null", O_WRONLY);
dup2(tmpfd, 2);
close(tmpfd);

Of course you are cordially invited to add error handling.

花海 2024-10-23 14:20:24

谢谢你们俩。我通过将 stderr 重定向到 /dev/null 解决了问题。但是我必须启动子进程两次。首先,我检查它是否在抑制 stderr 的情况下启动,然后如果第一次成功则再次启动它。因此,我对子进程有正确的默认 stderr,并且在失败时没有 shell 输出。

Thank you both. I resolved the problem with redirecting stderr to /dev/null. However I have to launch the child process two times. First I check if it launches at all with suppressed stderr and then I launch it again if the first time was successful. So I have correct default stderr for child process and no shell output in case of failure.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文