在Linux中,管道(pipe)是一种进程间通信(IPC)机制,它允许一个进程的输出作为另一个进程的输入。管道是半双工的,数据只能单向流动,而且只能在具有亲缘关系的进程间使用(通常是父子进程)。
pipe()
系统调用创建。mkfifo()
系统调用创建,并通过open()
来打开。ls | grep "txt"
,ls
的输出作为grep
的输入。以下是一个简单的C语言示例,展示如何使用匿名管道在父子进程中传递数据:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.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) {
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]);
}
return 0;
}
select()
/poll()
来管理多个文件描述符。可以使用fcntl()
函数将文件描述符设置为非阻塞模式,或者使用select()
/poll()
来监视多个文件描述符的状态,从而实现非阻塞的读写操作。
领取专属 10元无门槛券
手把手带您无忧上云