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가 예약되어 엔트리 경우 stdin
, stdout
그리고 stderr
각각.
stdin - 0
stdout - 1
stderr - 2
당신은 재 지정하려면 stdout
및 stderr
에 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;
}
순서에 관심이 있다면 stdout을 파일로 리디렉션하면 줄 바꿈에서 버퍼를 플러시하지 않으므로 fflush 호출은 fprintf를 따라야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다