pipe代码

使用管道完成简单进程通信

/* 使用匿名管道完成父子进程通信  */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define MESSAGE "can you hear me?"

int main()
{
    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    
    // 通信方向:父进程写入, 子进程读取
    if (pid > 0)
    {
        close(fds[0]); // 关闭读管道的功能
        write(fds[1], MESSAGE, strlen(MESSAGE));
        printf("parent pid:%d send message:%s\n", getpid(), MESSAGE);
        while(1);
    }
    else if (pid == 0)
    {
        char buffer[1024];
        bzero(buffer, sizeof(buffer));
        close(fds[1]); // 关闭写管道的功能

        int len;
        read(fds[0], buffer, sizeof(buffer));
        printf("child pid:%d recv message:%s\n", getpid(), buffer);
    }
    else
    {
        perror("fork call failed\n");
        exit(0);
    }

    return 0;
}

 

posted @ 2020-08-24 08:53  x_Aaron  阅读(176)  评论(0编辑  收藏  举报