gpt4 book ai didi

c - 如何将 stderr 和 stdout 重定向到同一个文件

转载 作者:行者123 更新时间:2023-12-03 09:49:52 25 4
gpt4 key购买 nike

我的任务是让 stderr 和 stdout 打印到一个名为“log.out”的文件。我不允许删除代码行,只能添加它们。stdout 部分很简单,我刚刚添加了 close(1);现在它正在工作。但我已经花了几个小时试图学习如何使用整个 dup/dup1/dup2 技术,但即使在互联网上阅读了很多关于该主题的内容后,我还是无法让它发挥作用。如果有人能告诉我需要添加哪些代码行才能使其正常工作,并向我解释它是如何工作的,那就太好了。谢谢!

#include<stdio.h>
#include<stdlib.h>
#include <unistd.h> // for fork, sleep etc.
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

void fork_son(char*, int);
void do_son();
int open_file(char*);

int
main()
{
fork_son("1st", 0);
fork_son("2nd", 1);
exit(0);
}

void fork_son(char* which, int need_file)
{
int pid;
int status;
if (need_file)
{
close(1); //close stdout

open_file("log.out");
}
// close and open files before forking

pid = fork();
if (pid <0)
{
fprintf(stderr,"process %d, Fork Failed... Exiting\n", getpid());
exit(1);
}
if (pid == 0)
do_son(which);
else
{
printf("waiting for %s son...", which);
wait(&status);
printf("%s son exited!\n", which);
}
return;
}

void do_son(char* which)
{
fprintf(stdout,"Hello from %s son!\n", which);
fprintf(stderr,"%s son: I'm going to exit\n", which);
exit(0);
}

int open_file(char* name)
{
int fd;
fd = open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
// check if open succeeded
if (fd <0)
{
fprintf(stderr, "ERROR: open \"%s\" failed (%d). Exiting\n", name, fd);
exit(2);
}
// if (fd != 1)
// {
// fprintf(stderr,"ERROR: open \"%s\" - fd is %d (expected 1). Exiting\n", name, fd);
// exit(3);
// }
printf("opened file %s, file descriptor is: %d\n",name, fd);
return(fd);
}

最佳答案

open 的工作方式是,它在文件描述符表中搜索空闲条目。其中条目 0、1 和 2 分别保留给 stdinstdoutstderr

stdin  - 0
stdout - 1
stderr - 2

如果你想将 stdoutstderr 重定向到 log.out 你可以简单地执行以下操作:

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main()
{
int fd = - 1;
fd = open("log.out", O_RDWR | O_CREAT);

dup2(fd, 1); // redirects stdout to log.out
dup2(fd, 2); // redirects stderr to log.out

/* Print to stderr and to stdout */
fprintf(stdout, "%s", "Hello world\n");
fprintf(stderr, "%s", "Stack overflow!\n");
return 0;
}

如果您关心顺序,对 fflush 的调用应该跟在 fprintf 之后,因为将 stdout 重定向到文件不会在换行时刷新缓冲区。

关于c - 如何将 stderr 和 stdout 重定向到同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61938539/

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