main.c
:
#include <stdio.h>
#include <unistd.h>int main() {int fd[2];// 创建管道if (pipe(fd) == -1) {fprintf(stderr, "pipe(fd) failed\n");return -1;}// 创建子进程pid_t pid = fork();if (pid < 0) {fprintf(stderr, "fork() failed\n");return -1;}// 父进程if (pid > 0) {close(fd[0]); // 关闭读端printf("Parent process pid: %d\n", getpid());printf("Subprocess pid: %d\n", pid);printf("Parent send: ");char str[100];scanf("%s", str);write(fd[1], str, sizeof(str)); // 父进程向管道写数据close(fd[1]); // 关闭写端}// 子进程else {close(fd[1]); // 关闭写端char buf[100] = {};read(fd[0], buf, sizeof(buf)); // 子进程从管道读数据printf("Child receive: %s\n", buf);close(fd[0]); // 关闭读端}
}
$ ./main
Parent process pid: 76015
Subprocess pid: 76016
Parent send: hello
Child receive: hello