下面是一个示例代码,用于创建一个无名管道并在父子进程之间进行通信:
#include
#include
#include
int main() {
int pipefd[2];
pid_t pid;
char buffer[20];
// 创建无名管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pipefd[0]); // 关闭读端
char message[] = "Hello from child!";
write(pipefd[1], message, sizeof(message));
close(pipefd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
printf("Received message from child: %s\n", buffer);
close(pipefd[0]); // 关闭读端
exit(EXIT_SUCCESS);
}
return 0;
}
这个程序首先创建了一个无名管道pipefd
,然后使用fork()
创建了一个子进程。在子进程中,我们关闭了管道的读端,然后写入了一条消息,最后关闭了管道的写端。在父进程中,我们关闭了管道的写端,然后读取子进程发送的消息,最后关闭了管道的读端。