子进程项父进程发送自己的进程表示符,以及某字符串。父进程则通过管道读出子进程发来的消息,将消息显示在屏幕上,然后终止
时间: 2024-05-03 18:19:57 浏览: 9
子进程。
以下是示例代码:
父进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd[2];
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
close(fd[0]); // 关闭读端
char str[] = "Hello, parent process!";
write(fd[1], &pid, sizeof(pid));
write(fd[1], str, strlen(str) + 1); // 包括字符串末尾的'\0'
close(fd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else {
// 父进程
close(fd[1]); // 关闭写端
pid_t child_pid;
char buf[256];
read(fd[0], &child_pid, sizeof(child_pid));
read(fd[0], buf, 256);
printf("Received message from child process %d: %s\n", child_pid, buf);
close(fd[0]); // 关闭读端
waitpid(pid, NULL, 0); // 等待子进程终止
exit(EXIT_SUCCESS);
}
}
```
子进程发送进程表示符和字符串到管道,并终止自己。
父进程从管道中读取子进程发送的消息,并将消息显示到屏幕上,然后等待子进程终止。最后,父进程也终止。