进程通信实验代码 linux
时间: 2024-01-31 07:02:03 浏览: 27
进程通信是 Linux 系统编程中比较重要的一部分,常见的进程通信方式包括管道、消息队列、共享内存和信号量等。下面是一个简单的进程通信实验代码,使用了管道进行进程通信。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_BUF 1024
int main() {
int fd[2];
pid_t pid;
char buf[MAX_BUF];
if (pipe(fd) == -1) {
fprintf(stderr, "Failed to create pipe.\n");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
fprintf(stderr, "Failed to create child process.\n");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process
close(fd[1]); // Close unused write end
while (read(fd[0], buf, MAX_BUF) > 0) {
printf("Received message: %s\n", buf);
}
close(fd[0]);
exit(EXIT_SUCCESS);
} else { // Parent process
close(fd[0]); // Close unused read end
printf("Enter message: ");
fgets(buf, MAX_BUF, stdin);
write(fd[1], buf, strlen(buf));
close(fd[1]);
wait(NULL);
exit(EXIT_SUCCESS);
}
return 0;
}
```
该程序通过调用 `pipe()` 创建一个管道,然后通过 `fork()` 创建一个子进程。子进程通过读取管道接收来自父进程的消息,父进程通过向管道写入消息向子进程发送消息,实现了进程间的通信。在实际使用中,可以根据需要选择不同的进程通信方式。