进程间通信--FIFO(命名管道)

匿名管道只能解决具有亲缘关系的进程间通信,但是任意两个进程间不能通信。

FIFO不同于管道之处在于提供了一个路径名与之关联,以FIFO的文件形式存储到文件系统中。

命名管道是一个设备文件,因此进程间不需要亲缘关系,只要可以访问与之关联的路径即可,就能同FIFO通信

命名管道通过mkfifo命名一个管道,然后通过open read write进行文件读写

管道可以根据open选项设置阻塞非阻塞

注意:命名管道可能出现粘包的问题

命名管道代码示例:

server.cpp

#include<iostream>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <unistd.h>

int main(){
    unlink("../myfifo");
    int ret = mkfifo("../myfifo",S_IFIFO|0666);
    if (ret == -1) 
    {   
        printf("fifo create err\n");
        return -1; 
    }   
    int fd = open("../myfifo",O_RDWR);
    if (fd == -1) 
    {   
        printf("open file err\n");
        return -1; 
    }   
    int n =  0;  
    while(1)
    {   
        char buf[1024] = {0};
        n = read(fd,buf,1024);
        if(n > 0)
        {   
            printf("recv[%d]%s\n",n,buf);
        }   
        else
        {   
            printf("recv buf[%d] failed\n",n);
            break;
        }   
    }   
    close(fd);
}      

  

client.cpp


#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

int main(){
    int fd = open("../myfifo",O_RDWR);
    if (fd == -1) 
    {   
        printf("open fifo file err\n");
        return -1; 
    }   
    int num = 10; 
    char buf[1024] = {0};
    while(num--)
    {   
        sprintf(buf,"hello server,..num=%d\n",num);
        if(write(fd,buf,strlen(buf)) == -1) 
        {   
            printf("write fifo err\n");
            return -1; 
        }   
        usleep(100);                                                                       
    }   
    close(fd);
}

  

猜你喜欢

转载自www.cnblogs.com/flycc/p/12815230.html