1) 编写一段程序exp1_学号.c, 使用管道来实现父子进程之间的通信。子进程向管道写入自己的进程标识符,以及字符串“is sending a message to parent”。父进程则通过管道读出子进程发来的消息,将消息显示在屏幕上,然后终止。
时间: 2023-06-05 22:05:05 浏览: 170
好的,这是一个技术问题,我将会回答。以下是exp1_学号.c的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUF_SIZE 30
int main() {
int pfd[2];
pid_t pid;
char buf[BUF_SIZE];
if (pipe(pfd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pfd[0]); // 关闭读端
pid_t child_pid = getpid();
char message[] = "is sending a message to parent";
sprintf(buf, "%d %s", child_pid, message);
write(pfd[1], buf, BUF_SIZE);
close(pfd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else { // 父进程
close(pfd[1]); // 关闭写端
if (read(pfd[0], buf, BUF_SIZE) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Message received from child: %s\n", buf);
close(pfd[0]); // 关闭读端
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
}
```
该程序使用pipe函数创建一个管道,然后通过fork函数创建子进程。子进程向管道中写入一个包含自己pid和消息的字符串,父进程则从管道中读取该字符串并将其显示。最后,父进程结束并等待子进程结束。