dup () 및 dup2 ()를 사용하여 case 'f'에 대해 열린 파일에 case 's'를 누를 때 stdout에 인쇄되는 메시지를 복제하고 싶습니다.
dup 시스템 호출이 어떻게 작동하는지 그리고 stdout을 파일에 어떻게 복제 할 수 있는지 잘 모르겠습니다. dup을 사용하여 stdout이 가리키는 것을 캡처 한 다음 dup2를 사용하여 화면과 파일 사이를 전환해야한다는 것을 알고 있습니다.
내 코드는 다음과 같습니다.
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#define BUFFER_SIZE 128
#define PERMS 0666
int main(int argc, char *argv[])
{
char outBuffer[BUFFER_SIZE] = "This is a message\n";
int count;
int fd;
char input =0;
int a;
if(argc!=2){
printf("Provide an valid file as an argument\n");
exit(1);
}
if((fd = open(argv[1],O_CREAT|O_WRONLY|O_APPEND,PERMS)) == -1)
{
printf("Could not open file\n");
exit(1);
}
printf("0 to terminate, s to write to stdout, f to write to file\n");
do{
scanf(" %c", &input);
switch(input)
{
case 'f':
case 's':
write(1,outBuffer,strlen(outBuffer));
break;
default:
printf("Invalid Choice\n");
}
}while(input != '0');
close(fd);
return 0;
}
stdout을 파일로 보내는 기능이있는 'tee'프로그램 (자식 프로세스에 대한 파이프) 사용을 고려하십시오.
case 'f':
pipe fd2[2] ;
pipe(fd2) ;
if ( fork() > 0 ) {
// Child
dup2(fd[0], 0) ;
close(fd[1]) ;
close(
// create command line for 'tee'
char teecmd[256] ;
sprintf(teecmd, "...", ...) ;
execlp(teecmd) ;
} ;
// Parent
fd = fd[1] ;
close(fd[0]) ;
...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다