gpt4 book ai didi

c - 如何在 C 中回滚重定向的 stdio?

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:27 25 4
gpt4 key购买 nike

第一轮

从一些示例中,我知道如何将 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 < 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;
}

执行代码后,我的控制台显示:

test1

test2 被重定向到/dev/null。

但是,现在,我想将 stdio 从/dev/null 回滚到标准输入和输出。

我该怎么做?

第二轮

感谢您的回复。

实际上,我遇到了一个程序重定向 stdio(例如示例 1)并 fork 我的程序(例如示例 2)的问题。

示例 1
#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;
}
示例 2
#include <stdio.h>

int main()
{
printf("Hello World!\n");

return 0;
}

运行示例 1 后,我的控制台显示:

test1

如何更改示例 2 以将 printf() 重定向到控制台?谢谢。

最佳答案

一个简单的解决方案是使用 dup 保存初始文件描述符(您不应该假设它们是相同的),然后稍后使用 dup2 恢复它们。

关于c - 如何在 C 中回滚重定向的 stdio?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35007738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com