进程间通讯:无名管道

无名管道只能在有亲缘关系的进程间通讯 

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>

int main()
{
    int fd[2];
    int ret;
    pid_t pid;
    char buff[1024] = {0};
    ret = pipe(fd);//创建管道
    if(!(pid = fork()))
    {
        //child
        close(fd[0]);
        scanf ("%s",buff);
        ret = write(fd[1],buff,10);
        if (ret < 0)
        {
            perror("write");
            close(fd[1]);
            return -1;
        }
        printf ("sent msg\n");
        close(fd[1]);
        return 0;
    }
    //parent
    close(fd[1]);
    ret = read(fd[0],buff,10);//阻塞
    if(ret < 0)
    {
        perror("read");
        close(fd[0]);
        return -1;
    }
    printf ("recv msg:%s\n",buff);
    wait(&pid);
    close(fd[0]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/nanqiang/p/9982490.html