功能简述:一个程序运行时创建了一个子进程,子进程负责将键盘输入的内容写到pipe,父进程完成将从pipe中读到的内容输出到屏幕。当输入quit时,父子进程都退出。

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>

#define N 64

int main()
{
    int fd[2], i;
    pid_t pid;
    char buf[N] = {0};
    ssize_t n;

    if (pipe(fd) == -1)
    { perror("pipe");
        exit(-1);
    }

    if ((pid = fork()) == -1)
    {
        perror("fork");
        exit(-1);
    }

    if (pid == 0) //child write
    {
        close(fd[0]);

        while (fgets(buf, N, stdin) != NULL)//abc\n----a b c \n \0
        {
            write(fd[1], buf, strlen(buf)+1);
            if(strncmp(buf, "quit", 4) == 0)
            {
                break;
            }
        }
        close(fd[1]);
    }
    else//parent read
    {
        close(fd[1]);

        while (1)
        {
            bzero(buf, sizeof(buf));
            sleep(1);
            n = read(fd[0], buf, N);
            printf("n=%d ,buf=%s", n, buf);
            if(strncmp(buf, "quit", 4) == 0)
            {
                break;
            }
        }
        close(fd[0]);
    }

    return 0;
}

利用pipe实现进程通信一例

相关文章: