我有一个任务,需要将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);
}
dup
吗? - Daniel Walkerdup2
。 - Daniel Walker