如何在C中回滚重定向的stdio? 第一轮
通过一些示例,我知道如何将stdio重定向到null如何在C中回滚重定向的stdio? 第一轮,c,libc,C,Libc,通过一些示例,我知道如何将stdio重定向到null #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int fd = open("/dev/null", O_RDWR); int in, out, err; if (fd &l
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("/dev/null", O_RDWR);
int in, out, err;
if (fd < 0) {
perror("open file error!");
return -1;
}
printf("test1\n");
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
printf("test2\n");
close(fd);
return 0;
}
test2被重定向到/dev/null
但是,现在,我想将stdio从/dev/null回滚到标准输入和输出
我该怎么做
第二轮
谢谢你的回复
实际上,我遇到了一个问题,程序重定向stdio(如示例1)并分叉我的程序(如示例2)
例1
如何更改示例2以将printf()重定向到控制台?
谢谢。一个简单的解决方案是使用
dup
保存初始文件描述符(您不应该假设它们是相同的),然后在以后使用dup2
恢复它们,前提是您有一个控制终端(这是/dev/null
习惯用法所建议的),您应该能够将输出重定向到/dev/tty
但是您应该知道,真正的守护进程(如从cron启动的守护进程)没有控制终端,在这种情况下,将不会定义
/dev/tty
。对于您的第二轮问题,exec call和类似的preserve open file描述符,这意味着您需要恢复调用excl之前所做的操作,有关如何保存/恢复它们的示例,请参见以下内容:
我不确定在任何情况下都能做到这一点。例如,一旦文本被传送到Windows控制台,除非您手动清除屏幕,否则它将永远在那里
test1
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("/dev/null", O_RDWR);
if (fd < 0) {
perror("open file error!");
return -1;
}
printf("test1\n");
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
execl("hello_world", NULL);
close(fd);
return 0;
}
#include <stdio.h>
int main()
{
printf("Hello World!\n");
return 0;
}
test1