practical examples use dup or dup2

前端 未结 5 1494
滥情空心
滥情空心 2020-11-29 16:49

I know what dup / dup2 does, but I have no idea when it would be used.

Any practical examples?

Thanks.

5条回答
  •  孤城傲影
    2020-11-29 17:10

    I/O redirection in the shell would most likely be implemented using dup2/fcnlt system calls.

    We can easily emulate the $program 2>&1 > logfile.log type of redirection using the dup2 function.

    The program below redirects both stdout and stderr .i.e emulates behavior of $program 2>&1 > output using the dup2.

    #include 
    #include 
    #include 
    #include 
    
    int
    main(void){
        int close_this_fd;
        dup2(close_this_fd = open("output", O_WRONLY), 1);
        dup2(1,2);
        close(close_this_fd);
        fprintf(stdout, "standard output\n");
        fprintf(stderr, "standard error\n");
        fflush(stdout);
        sleep(100); //sleep to examine the filedes in /proc/pid/fd level.
        return;
    }
    
    vagrant@precise64:/vagrant/advC$ ./a.out
    ^Z
    [2]+  Stopped                 ./a.out
    vagrant@precise64:/vagrant/advC$ cat output
    standard error
    standard output
    vagrant@precise64:/vagrant/advC$ ll /proc/2761/fd
    total 0
    dr-x------ 2 vagrant vagrant  0 Jun 20 22:07 ./
    dr-xr-xr-x 8 vagrant vagrant  0 Jun 20 22:07 ../
    lrwx------ 1 vagrant vagrant 64 Jun 20 22:07 0 -> /dev/pts/0
    l-wx------ 1 vagrant vagrant 64 Jun 20 22:07 1 -> /vagrant/advC/output
    l-wx------ 1 vagrant vagrant 64 Jun 20 22:07 2 -> /vagrant/advC/output
    

提交回复
热议问题