编写一段程序,使用管道来实现父子进程之间的进程通信
时间: 2024-04-29 11:25:11 浏览: 11
当然可以,以下是一段使用管道实现父子进程通信的代码示例:
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main() {
int fd[2];
pid_t pid;
if (pipe(fd) < 0) { // 创建管道
perror("pipe error");
exit(1);
}
if ((pid = fork()) < 0) { // 创建子进程
perror("fork error");
exit(1);
} else if (pid > 0) { // 父进程
close(fd[0]); // 关闭读端口
char message[] = "Hello, child process!\n";
write(fd[1], message, strlen(message)); // 写入管道
close(fd[1]); // 关闭写端口
waitpid(pid, NULL, 0); // 等待子进程结束
} else { // 子进程
close(fd[1]); // 关闭写端口
char message[100];
read(fd[0], message, sizeof(message)); // 从管道读取数据
printf("Message received from parent process: %s", message);
close(fd[0]); // 关闭读端口
exit(0);
}
return 0;
}
```
这段代码创建了一个管道,父进程向管道中写入了一条消息,子进程从管道中读取了该消息并打印到控制台上。注意,父进程在写入完数据后要关闭写端口,否则子进程的读取操作会一直阻塞。同理,子进程在读取完数据后也要关闭读端口。