使用 /dev/tty 重置 STDOUT 和 STDERR
我正在尝试将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只需使用
dup
调用保存以前的设置,然后在想要恢复它们时使用dup2
。这是尤其,因为您希望将其设置回的“原始设置”可能根本不是终端设备(这对您来说是一个不明智的假设) - 用户可能已经在外部使用了重定向你的影响范围。这样您就不必担心重新打开它们,包括您可能会得到错误的参数或必须进行任何特殊设置(例如使用
ioctl
)。大致如下:
I would just save the previous settings away with a
dup
call, then usedup2
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: