C 匿名管道通信

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
posted @ 2025-03-13 04:34  Undefined443  阅读(11)  评论(0)    收藏  举报