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

有名管道mkfifo

int   mkfifo(const char *pathname, mode_t mode)

pathname: FIFO文件名

mode: 屬性

一旦創建了了FIFO,就可open去打開它,可以使用openreadclose等去操作FIFO

當打開FIFO時,非阻塞標誌(O_NONBLOCK)將會對讀寫產生如下影響:

1、沒有使用O_NONBLOCK:訪問要求無法滿足時進程將阻塞。如試圖讀取空的FIFO,將導致進程阻塞;

2、使用O_NONBLOCK:訪問要求無法滿足時不阻塞,立即出錯返回,errnoENXIO

示例:

讀管道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-->

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章