gpt4 book ai didi

c - 子进程如何从管道读取stdout,而父进程如何将stdin写入管道?

转载 作者:行者123 更新时间:2023-11-30 18:25:52 27 4
gpt4 key购买 nike

// This code is pasted from
// http://linux.die.net/man/2/pipe

#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */ <----- Point A
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */ <----- Point B
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}

据我了解,

if (...)
............; ---+
else |---> " Only ONE of them can be reached! "
............; ---+

那么,在此代码中,子进程如何从管道读取并且父进程如何写入管道?

最佳答案

fork() 的结果是一个进程变成两个进程(通过无性繁殖)。因此,虽然在一个进程中仍然会只采用 if/else block 的一个分支,但有两个进程,每个进程都会采用一条路径。

更具体地说,看看 fork() 返回的内容:父级的 PID,新子级的 0。除此之外,这两个过程几乎相同。因此,if (cpid == 0) 检查是 fork() 之后的常见模式,以便您可以在每个进程中执行不同的逻辑。就您而言,这是在一个进程中读取并在另一个进程中写入。

关于c - 子进程如何从管道读取stdout,而父进程如何将stdin写入管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434732/

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