天天看點

Linux 程序間通訊之有名管道方式

有名管道mkfifo:

int   mkfifo(const char *pathname, mode_t mode)

pathname: FIFO檔案名

mode: 屬性

一旦建立了了FIFO,就可open去打開它,可以使用open,read,close等去操作FIFO

當打開FIFO時,非阻塞标志(O_NONBLOCK)将會對讀寫産生如下影響:

1、沒有使用O_NONBLOCK:通路要求無法滿足時程序将阻塞。如試圖讀取空的FIFO,将導緻程序阻塞;

2、使用O_NONBLOCK:通路要求無法滿足時不阻塞,立即出錯傳回,errno是ENXIO;

示例:

讀管道example:

#include <stdio.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

#include <string.h>

#include <stdlib.h>

#define P_FIFO         "/tmp/p_fifo"

int main(int argc, char** argv){

         charcache[100];

         intfd;

         memset(cache,0, sizeof(cache));                               //初始化記憶體

         if(access(P_FIFO,F_OK)==0){                                        //管道檔案存在

                   execlp("rm","-f", P_FIFO, NULL);                      //删掉

                   printf("access.\n");

         }

         if(mkfifo(P_FIFO, 0777) < 0){            

                   printf("createnamed pipe failed.\n");

         }

         fd= open(P_FIFO,O_RDONLY|O_NONBLOCK);        //     非阻塞方式打開,隻讀

         while(1){                                                                             //     一直去讀

                   memset(cache,0, sizeof(cache));

                   if((read(fd,cache, 100)) == 0 ){                           //     沒有讀到資料

                            printf("nodata:\n");

                   }

                   else

                            printf("getdata:%s\n", cache);                //     讀到資料,将其列印

                            sleep(1); //休眠1s

         }

         close(fd);

         return0;

}

寫管道example:

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

#define P_FIFO "/tmp/p_fifo"

int main(int argc, char argv[]){

         intfd;

         if(argc< 2){

                   printf("pleaseinput the write data.\n");

         }

         fd= open(P_FIFO,O_WRONLY|O_NONBLOCK);                //非阻塞方式

         write(fd,argv[1], 100);                                                            //将argv[1]寫道fd裡面去

         close(fd);

}

測試:

root--> ./mkfifo_r

no data:

no data:

get data:linuxdba

no data:

no data:

no data:

no data:

no data:

......

root--> ./mkfifo_w linuxdba

root-->

繼續閱讀