使用 /dev/tty 重置 STDOUT 和 STDERR

发布于 2024-12-12 00:59:49 字数 588 浏览 0 评论 0原文

我正在尝试将 stdout 和 stderr 重定向到一个文件,然后将它们恢复到原始设置。我已成功将输出重定向到文件,但我似乎无法从 tty 恢复它们。这是我的代码:

            fid = open("/dev/tty", O_WRONLY);
            if (fid < 0) {
                fprintf(stderr, "Opening TTY failed.");
                exit(1);
            } else {
                close(1);
                dup(fid);

                close(fid);
            }

tty 上的 open 调用总是失败。 (返回-1)。我想做的事情有根本性的错误吗?

我还认为这可能是一个权限问题,所以我检查了它们:

crw-rw-rw- 1 root wheel 2, 0 Oct 21 10:46 /dev/tty

我正在 Snow Leopard 上开发它的价值,

谢谢提前寻求任何帮助。

I am trying to redirect stdout and stderr to a file, and then restore them back to their original settings. I have successfully redirected the output to a file, but I can't seem to restore them from the tty. This is the code that I have:

            fid = open("/dev/tty", O_WRONLY);
            if (fid < 0) {
                fprintf(stderr, "Opening TTY failed.");
                exit(1);
            } else {
                close(1);
                dup(fid);

                close(fid);
            }

the open call on tty always fails. (returns -1). Is there something fundementally wrong that I'm trying to do?

I also though that maybe it might be a permissions issue, so I checked them:

crw-rw-rw- 1 root wheel 2, 0 Oct 21 10:46 /dev/tty

I am developing on Snow Leopard for what its worth,

Thanks in advance for any help.

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

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

发布评论

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

评论(1

半世晨晓 2024-12-19 00:59:49

我只需使用 dup 调用保存以前的设置,然后在想要恢复它们时使用 dup2 。这是尤其,因为您希望将其设置回的“原始设置”可能根本不是终端设备(这对您来说是一个不明智的假设) - 用户可能已经在外部使用了重定向你的影响范围。

这样您就不必担心重新打开它们,包括您可能会得到错误的参数或必须进行任何特殊设置(例如使用ioctl)。

大致如下:

int saveFd = dup (1);        // check for errors.

blahBlahBlah();              // close file desc 1, reopen,
                             //   and weave your magic.

int rc = dup2 (1, saveFd);   // check for errors.

I would just save the previous settings away with a dup call, then use dup2 when you want to restore them. This is especially true since the "original settings" you wish to set them back to may not be the terminal device at all (that's an unwise assumption on your part) - the user may have already used redirection outside of your sphere of influence.

That way you don't have to worry about re-opening them at all, including the possibility that you may get the arguments wrong or have to do any special setup (such as with ioctl).

Something along the lines of:

int saveFd = dup (1);        // check for errors.

blahBlahBlah();              // close file desc 1, reopen,
                             //   and weave your magic.

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