使用exec

时间:2017-12-01 16:11:19

标签: c linux

所以在这段代码片段中,一个进程分叉了一个子进程。子进程计算了一个随机数r,并用exec函数调用linux命令'head -r“文件',该函数破坏了进程本身,但是为了将结果发送回父进程,子进程首先复制了一个写进程结束管道p,与父进程共享,然后关闭管道p的两端并关闭stdout文件描述符...在execlp之后,父进程可以从管道读取命令'head -r“fil2”'的结果页。 这怎么可能?

        if (pid == 0) 
        {
            /* code of child */

            srand(time(NULL)); 

            nr=atoi(argv[(i*2)+2]); 
            r=mia_random(nr); //calc random value

            close(1); //closing standard output???
            dup(p[1]); //duplicating write end of inherited pipe from parent            
            close(p[0]);//closing read end of inherited pipe
            close(p[1]);//closing write end of inherited pipe

            //creating a variable to hold an argument for `head`
            sprintf(option, "-%d", r);

            //calling head on a file given as argument in main
            execlp("head", "head", option, argv[(i*2)+1], (char *)0);


            /* must not be here anymore*/
            /* using perror to check for errors since stdout is closed? or connected to the pipe?*/
            perror("Problem esecuting  head by child process");
            exit(-1);
        }

为什么不将头部的结果写入stderr?怎么写到dup(p [1])???

1 个答案:

答案 0 :(得分:1)

系统保证以尽可能低的文件描述符打开每个新文件。

实际上,这意味着如果fd 01已打开且p[1] != 1,那么

close(1);
dup(p[1]);
单线程进程中的

等同于

dup2(p[1],1);

或者换句话说,如果此上下文中的dup调用成功,它将返回(filedescriptor)1。

相关问题