gpt4 book ai didi

c - 使用 exec 后将标准输出重定向到管道

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:15 33 4
gpt4 key购买 nike

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

        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);
}

为什么 head 的结果没有写入 stderr?怎么写到dup(p[1])了???

最佳答案

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

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

close(1);
dup(p[1]);

在单线程进程中相当于

dup2(p[1],1);

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

关于c - 使用 exec 后将标准输出重定向到管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597239/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com