IPC-PIPE管道-pipe-read/write-wait

概念


管道读写特点

管道的局限性

创建管道函数pipe

读写管道函数read/write

等待子进程中断或结束的函数wait

使用管道的特殊情况

创建无名管道

/*
    创建无名管道,创建子进程
*/
void pipe_func(void)
{
    int res;
    int num;
    pid_t pid;
    int pipe_fd[2];
    char r_buf[100], w_buf[100];

    memset(r_buf, 0, sizeof(r_buf));
    memset(w_buf, 0, sizeof(w_buf));

    // 创建管道
    if (pipe(pipe_fd) < 0)
    {
        perror("pipe error");
        exit(EXIT_FAILURE);
    }
    // 创建子进程
    res = fork();
    if (res < 0)
    {
        perror("fork error");
        exit(EXIT_FAILURE);
    }
    else if (res == 0)
    {   // 子进程关闭写
        close(pipe_fd[1]);
        if ((num = read(pipe_fd[0], r_buf, sizeof(r_buf))) > 0)
        {
            printf("child fork read from pipe %d types, string is %s\n", num, r_buf);
        }
        close(pipe_fd[0]);
        exit(EXIT_SUCCESS);
    }
    else
    {   // 父进程关闭读
        close(pipe_fd[0]);
        printf("Please inpur str:");
        scanf("%s", w_buf);
        if ((num = write(pipe_fd[1], w_buf, strlen(w_buf)) != -1))
        {
            printf("prent fork write to pipe %d types, string is %s\n", num, w_buf);
        }
        waitpid(res, NULL, 0);
        exit(EXIT_SUCCESS);
    }
}
posted @ 2022-05-03 10:14  starc的miao  阅读(37)  评论(0)    收藏  举报