无名管道

#include "stdio.h"
#include "unistd.h"
#include "string.h"

int main(void) {
    int pipefd[2];
    // 创建无名管道,pipefd[0]读端 pipefd[1]写端
    if (pipe(pipefd) == -1) {
        perror("pipe");
    }
    int pid = fork();
    if (pid == 0) {
        close(pipefd[1]);
        for (;;) {
            char buf[128];
            int flag = read(pipefd[0], buf, sizeof(buf));
            if (flag == -1) {
                perror("read");
                return -1;
            }
            if (flag == 0) {
                break;
            }
            printf(">>%s", buf);
        }
        close(pipefd[0]);
        return 0;
    }
    close(pipefd[0]);
    for (;;) {
        char buf[128];
        fgets(buf, sizeof(buf), stdin);
        if (strcmp(buf, "!\n") == 0) {
            break;
        }
        if (write(pipefd[1], buf, strlen(buf)) == -1) {
            perror("write");
            return -1;
        }
    }
    close(pipefd[1]);
    return 0;
}

 

posted on 2023-04-20 21:24  信奉上帝的小和尚  阅读(6)  评论(0编辑  收藏  举报

导航