初探管道..

进程间通信 IPC

1.管道

匿名管道
pipe();
命名管道
mkfifo()
内核提供
管道和队列没什么区别
管道有自同步机制(迁就慢的那一方)
必须凑够读写双方
单工

2.pipe匿名管道

可以用在具有亲缘关系的进程之间

NAME
       pipe, pipe2 - create pipe

SYNOPSIS
       #include <unistd.h>

       int pipe(int pipefd[2]);

创造一个管道,返回给你两个文件描述符 0是读 1是写
先pipe,然后在fork,子进程中也会有两个文件描述符

3.pipe的demo

int main()
{
    
    
    char Buf[1024];
    int fd[2];
    pid_t pid;
    int res;

    res = pipe(fd);
    if(res < 0)
    {
    
    
            perror("pipe()");
            exit(1);
    }


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

    if(0 == pid)
    {
    
    
            close(fd[0]);
            write(fd[1], "Hello\n", 6);
            close(fd[1]);
    }
    else
    {
    
    
            close(fd[1]);
            read(fd[0], Buf, 6);
            puts(Buf);
            close(fd[0]);
            wait(NULL);
    }



    return 0;
}

4.mkfifo

NAME
       mkfifo - make a FIFO special file (a named pipe)

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>

       int mkfifo(const char *pathname, mode_t mode);
       							名字      权限

不相关的进程也能接收数据

猜你喜欢

转载自blog.csdn.net/ZZHinclude/article/details/119878234