linux编程---进程间通信---FIFO---有名管道

无名管道是临时的,在完成通信后将自动消失,且只能在具有亲缘关系的进程间实现通信。

有名管道FIFO有效地克服了这一问题,它是一个存在的特殊文件,可以在不同进程间通信。

管道是单向的,要实现双向,需要两个管道。


创建有名管道

int mkfifo (const char *FILENAME, mode_t MODE)


使用示例

非亲缘关系的两个进程使用有名管道实现数据传输的实例程序。

写进程将要发送的数据发送到有名管道,读进程从有名管道中读取发送端发送的数据。

发送端程序

#include
#include
#include
#include
#include
#include
#include
#include
#include


#define FIFO_NAME "myfifo"

int main(int argc,char* argv[])
{
        int pipefd;
        int res;
        char buf[20];

        assert(argc == 2);

        bzero(buf,20);
        strcpy(buf,argv[1]);

        if(access(FIFO_NAME,F_OK) == -1)
        {
                res = mkfifo(FIFO_NAME,0766);
                if(res != 0)
                {
                        fprintf(stderr,"could not create fifo %s\n",FIFO_NAME);
                        exit(EXIT_FAILURE);
                }
        }

        pipefd = open(FIFO_NAME,O_WRONLY);
        if(pipefd != -1)
        {
                res = write(pipefd,buf,strlen(buf));
                if(res == -1)
                {
                        fprintf(stderr,"write error %s\n",FIFO_NAME);
                        exit(EXIT_FAILURE);
                }
                printf("write data is %s,%d bytes\n",buf,res);

                close(pipefd);
        }
        else
                exit(-1);
        exit(0);

}

读取端程序

#include
#include
#include
#include
#include
#include
#include
#include
#include


#define FIFO_NAME "myfifo"

int main(int argc,char* argv[])
{
        int pipefd;
        int res;
        char buf[20];

        bzero(buf,20);

        pipefd = open(FIFO_NAME,O_RDONLY);
        if(pipefd != -1)
        {
                res = read(pipefd,buf,sizeof(buf));
                if(res == -1)
                {
                        fprintf(stderr,"write error %s\n",FIFO_NAME);
                        exit(EXIT_FAILURE);
                }
                printf("read data is %s,%d bytes\n",buf,res);

                close(pipefd);
        }
        else
                exit(-1);

        exit(0);

}


你可能感兴趣的:(linux编程)