在Linux中,管道(pipe)是一种用于进程间通信(IPC)的机制。它允许一个进程将数据发送到另一个进程。管道通常用于父子进程之间的通信,但也可以用于其他进程之间的关系。
管道分为两种类型:
下面是使用匿名管道进行进程间通信的一个简单示例:
创建管道
#include <unistd.h>
int pipe(int pipefd[2]);
pipe()
函数接受一个包含两个整数的数组pipefd
作为参数。pipefd[0]
用于读取数据,pipefd[1]
用于写入数据。
示例代码
以下是一个简单的示例,展示了如何使用匿名管道在父子进程之间进行通信:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[128];
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
// 从管道读取数据
ssize_t bytes_read = read(pipefd[0], buffer, sizeof(buffer));
if (bytes_read > 0) {
buffer[bytes_read] = '\0';
printf("子进程收到消息: %s\n", buffer);
}
close(pipefd[0]);
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[0]); // 关闭读端
const char *message = "你好,子进程!";
// 向管道写入数据
ssize_t bytes_written = write(pipefd[1], message, strlen(message) + 1);
if (bytes_written > 0) {
printf("父进程发送消息: %s\n", message);
}
close(pipefd[1]);
wait(NULL); // 等待子进程结束
}
return 0;
}
编译并运行此代码,您将看到父进程发送消息到子进程,子进程从管道接收并打印消息。
对于命名管道,您可以使用mkfifo()
函数创建一个具有特定名称的管道,然后使用标准的文件操作函数(如open()
、read()
、write()
等)进行通信。