在Linux系统中,父子进程之间可以通过管道(pipe)来进行通信。管道是一种半双工的通信方式,数据只能单向流动,且只能在具有亲缘关系的进程间使用(通常是父子进程)。
基础概念:
相关优势:
类型:
应用场景:
ls | grep "txt"
。问题与解决:
示例代码(匿名管道):
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main() {
int pipefd[2];
pid_t cpid;
char buf[256];
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) { // fork失败
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
read(pipefd[0], buf, sizeof(buf));
printf("子进程收到数据: %s
", buf);
close(pipefd[0]);
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[0]); // 关闭读端
write(pipefd[1], "Hello from parent!", strlen("Hello from parent!"));
close(pipefd[1]);
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
}
在这个示例中,父进程通过管道向子进程发送一条消息,子进程接收并打印这条消息。
领取专属 10元无门槛券
手把手带您无忧上云