'dup2'에 해당되는 글 1건

  1. 2009.04.10 dup, dup2

dup, dup2

開發 - Computer/Linux 2009. 4. 10. 12:04

문득 궁금해져서...새벽에 삽질했습니다.

부모 프로세스가 stdin또는 stdout을 다른 I/O로 redirection 했다면,
fork로 만든 자식 프로세스나 exec로 실행한 서브 프로그램도
stdin, stdout을 redirection한 I/O를 유지하고 있을까?
-> yes!



// dupout.cc
// 자식/서브 프로세스가 부모 프로세스의 stdin/stdout의 특성을 물려받는지 알아보기 위한 테스트

#include <fcntl.h>
#include <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>

int main(int argc, char **argv)
{
    //int fd = open("flist.cc", O_RDONLY);
    int fd = open( "a.txt", _O_CREAT|_O_RDWR|_O_TRUNC, S_IRWXU|S_IRWXG|S_IRWXO );
    if( fd<=0 )
    {
        char * errmsg = "Cannot created file\n";
        write( STDOUT_FILENO, errmsg, strlen(errmsg) );
        return 0;
    }

    // 예제 1
    // STDOUT_FILENO의 입력을 File로

    // STDOUT_FILENO으로의 입력을 fd로 redirection
    int tempFd = dup(STDOUT_FILENO);
    dup2( fd, STDOUT_FILENO );

    // STDOUT_FILENO에 기록 - fd에 기록된다
    char * msg1 = "this is file output\n";
    write( STDOUT_FILENO, msg1, strlen(msg1) );
   
    // 자식 프로세스 생성
    // fork로 생성한 자식 프로세스가 부모 프로세스의 stdin/stdout 성질을 물려받는가?
    int pid = fork();
    if( pid>0 )
    {
        // parent
        int stat=0;
        wait(&stat);
    }
    else if( pid==0 )
    {
        // child
        char * msgch = "this is message from the child\n";
        write( STDOUT_FILENO, msgch, strlen(msgch) );

        // 한번 더 자식 프로세스 생성, 증손이네ㅋㅋ       
        // execl로 실행한 서브 프로세스가 부모 프로세스의 stdin/stdout 성질을 물려받는가?
        int pid = fork();
        if( pid==0 )
            // Child
            execl( "/bin/ls", "/bin/ls", NULL );
        return 0;
    }
    else
    {
        // error
    }
   
    close( fd );

    // STDOUT_FILENO 복구
    dup2( tempFd, STDOUT_FILENO );
    close( tempFd );
   
    // STDOUT_FILENO에 기록 - 화면에 출력된다
    char * msg2 = "this is screen output\n";
    write( STDOUT_FILENO, msg2, strlen(msg2) );
   
    return 0;
}

Posted by 배트
,