进程间通信-命名管道fifo

练习:兄弟进程间通信ls |wc - l

#include 
#include 
#include 
void exit(int);
void sys_error(const char *str){
        perror(str);
        exit(1);
}
int main(int argc,char *agrv[]){
    pid_t pid_ret1;
    int i=0;
    int fd[2];
    int ret = pipe(fd);
    if(-1 == ret)
    {
        sys_error("pipe failed");
    }
    for(;i<2;i++){
        pid_ret1 = fork();
        if(-1 == pid_ret1){sys_error("fork failed");}
        if(0 == pid_ret1){break;}//子进程关闭
    }
    //父进程
    if(2 == i){
//必须保证管道中数据是单向流动的,不能同时多个读端和写端
        close(fd[0]);
        close(fd[1]);
        wait(NULL);
        wait(NULL);
    }
    //兄弟
    if(0 == i)
    {
            close(fd[0]);
            dup2(fd[1],STDOUT_FILENO);
            execlp("ls","ls",NULL);
            //以下两行是不能执行的,由于execlp.
            close(fd[1]);
            printf("bro1\n");
    }
    //兄弟
    if(1 == i)
    {
            close(fd[1]);
            sleep(1);
            dup2(fd[0],STDIN_FILENO);
            execlp("wc","wc","-l",NULL);
            close(fd[0]);       
            printf("parent\n");
    }
}
命名管道fifo

应用:无血缘关系的进程间。
1、创建方式
命令:mkfifo FIFO名字
函数:int mkfifo(pathname,mode)

2、使用命名管道类似于使用文件读写
open/read/write

共享内存映射

mmap 允许反复读取
而fifo只允许读取一次。
代码参照课堂Code.

你可能感兴趣的:(进程间通信-命名管道fifo)