在Linux系统下,写一个c程序,实现父子间进程通信,父子间进程可以互发消息
时间: 2024-04-13 14:30:38 浏览: 85
当然可以!在 Linux 系统下,可以使用管道(pipe)来实现父子进程之间的通信。下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MSG_SIZE 100
int main() {
int fd[2]; // 管道文件描述符
pid_t pid;
char message[MSG_SIZE];
// 创建管道
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) {
// 父进程
close(fd[0]); // 关闭读端
while (1) {
printf("父进程发送消息:");
fgets(message, MSG_SIZE, stdin);
// 向管道写入消息
write(fd[1], message, strlen(message) + 1);
if (strcmp(message, "bye\n") == 0) {
break;
}
}
close(fd[1]); // 关闭写端
} else {
// 子进程
close(fd[1]); // 关闭写端
while (1) {
// 从管道读取消息
read(fd[0], message, MSG_SIZE);
printf("子进程接收到消息:%s", message);
if (strcmp(message, "bye\n") == 0) {
break;
}
}
close(fd[0]); // 关闭读端
}
return 0;
}
```
这个程序通过 `pipe` 函数创建了一个管道,父进程和子进程分别通过管道的读端和写端进行通信。父进程从标准输入读取消息,并将其写入管道;子进程则从管道读取消息,并将其打印出来。
你可以编译并运行这个程序,然后在父进程和子进程之间互发消息。输入 "bye" 以退出程序。
注意:这只是一个简单的示例,实际应用中可能需要更复杂的通信方式,比如使用信号、共享内存等。