dup2 를 이용하여 키보드 입력을 프로그램에서 대신하는 코드인데요..

vlzkcbcb의 이미지

프로그램에서 키보드입력을 하려합니다.

여기서는 간단하게 echo hello 라고 입력하여 화면에 hello 라는 글자만 나오면 일단 목적은 달성이 되는데요.

컴파일때는 전혀 문제 없는데

실행하면 그냥 아무글자도 안뜨고 끝나네요 ;;

echo hello 라는 글자를 echo hello > /home/test/aaa.txt

라고 바꾸어서 실행해도..aaa.txt 라는 파일은 생기질 않습니다.

뭐가 문제일까요?

#include <fcntl.h>
#include <sys/io.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
 
#define BUFSIZE 1024
 
int ori_stdin;
 
void stdin_to_program();
void stdin_restore();
 
int main(int argc, char **argv)
{    
    stdin_to_program();
 
    return 0;
}
 
void stdin_to_program( )
{
 
    int fd[2];
    pid_t pid;
 
    if( pipe(fd) == -1 )
        exit(1);
 
    pid = fork();
 
    // 부모는 STDIN 을 리드파이프로 바꿔주기만 함.
    if( pid>0 )
    {
        close( fd[1] );
        ori_stdin = dup( 0 );
        dup2( fd[0], 0 );
        close( fd[0] );
    }
 
    // 자식은 입력파이프에 내용을 입력하여 STDIN 에 전달 후 마치면 STDIN 복구..
    else if( pid==0 )
    {
        int n=0;
        int len;
        char buf[BUFSIZE];
        close( fd[0] );
 
        /////////////////////////////////////////////////////////////////
        //
        // 여기서부터는 프로그램이 키보드입력을 할 수 있다.
 
        n += sprintf(buf + n, "%s","echo hello");
        len = strlen(buf);
        printf("buf = [%s], len = [%d]\n",buf,len);    // 디버그용...
        write( fd[1], buf, len );
 
        // 여기까지 프로그램이 입력을 마친다.
        //
        /////////////////////////////////////////////////////////////////
 
        close( fd[1] );
        stdin_restore();
        exit(0);
    }
}
 
void stdin_restore()
{
    fflush( stdin );    
 
    close( 0 );
 
    dup2( ori_stdin, 0 );
}

위에서 디버그용으로 넣은

printf("buf = [%s], len = [%d]\n",buf,len);

의 결과는

buf = [echo hello], len = [10]

입니다..

도움 부탁드립니다.