国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 服務(wù)器 > Linux服務(wù)器 > 正文

linux 命名管道實(shí)例詳解

2024-09-05 23:04:01
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

linux進(jìn)程間通信——命名管道

  FIFO(命名管道)不同于匿名管道之處在于它提供?個(gè)路徑名與之關(guān)聯(lián),以FIFO的?件形式存儲(chǔ)于?件系統(tǒng)中。命名管道是?個(gè)設(shè)備?件,因此,即使進(jìn)程與創(chuàng)建FIFO的進(jìn)程不存在親緣關(guān)系,只要可以訪(fǎng)問(wèn)該路徑,就能夠通過(guò)FIFO相互通信。值得注意的是,F(xiàn)IFO(first input first output)總是按照先進(jìn)先出的原則?作,第?個(gè)被寫(xiě)?的數(shù)據(jù)將?先從管道中讀出。

  創(chuàng)建命名管道的系統(tǒng)函數(shù)有兩個(gè):mknod和mkfifo。兩個(gè)函數(shù)均定義在頭?件sys/stat.h,函數(shù)原型如下:

#include <sys/types.h> #include <sys/stat.h> int mknod(const char *path,mode_t mod,dev_t dev); int mkfifo(const char *path,mode_t mode); 

   函數(shù)mknod參數(shù)中path為創(chuàng)建的命名管道的全路徑名:mod為創(chuàng)建的命名管道的模式,指明其存取權(quán)限;dev為設(shè)備值,該值取決于?件創(chuàng)建的種類(lèi),它只在創(chuàng)建設(shè)備?件時(shí)才會(huì)?到。這兩個(gè)函數(shù)調(diào)?成功都返回0,失敗都返回-1。下?使?mknod函數(shù)創(chuàng)建了?個(gè)命名管道:

umask(0);if (mknod("/tmp/fifo",S_IFIFO | 0666) == -1){perror("mkfifo error");exit(1);} 

 函數(shù)mkfifo前兩個(gè)參數(shù)的含義和mknod相同。下?是使?mkfifo的?例代碼:

umask(0);if (mkfifo("/tmp/fifo",S_IFIFO|0666) == -1){perror("mkfifo error!");exit(1);}

下面為一個(gè)試?yán)?/span>

read端

#include<stdlib.h> #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<errno.h> #define PATH "./fifo" #define SIZE 128 int main() {  umask(0);  if (mkfifo (PATH,0666|S_IFIFO) == -1)  {  perror ("mkefifo error");  exit(0);  }  int fd = open (PATH,O_RDONLY);  if (fd<0)  {   printf("open fd is error/n");   return 0;  }   char Buf[SIZE];  while(1){  ssize_t s = read(fd,Buf,sizeof(Buf));  if (s<0)  {   perror("read error");   exit(1);  }  else if (s == 0)  {   printf("client quit! i shoud quit!/n");   break;  }  else  {   Buf[s] = '/0';   printf("client# %s ",Buf);   fflush(stdout);  }  }  close (fd);  return 3; } 

下面為weite端:

#include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<string.h> #include<errno.h> #include<fcntl.h>  #define PATH "./fifo" #define SIZE 128 int main() {  int fd = open(PATH,O_WRONLY);  if (fd < 0)  {   perror("open error");   exit(0);  }   char Buf[SIZE];  while(1)  {   printf("please Enter#:");   fflush(stdout);   ssize_t s = read(0,Buf,sizeof(Buf));   if (s<0)   {    perror("read is failed");    exit(1);   }   else if(s==0)   {    printf("read is closed!");    return 1;   }   else{    Buf[s]= '/0';    write(fd,Buf,strlen(Buf));   }  }  return 0; } 

打開(kāi)兩個(gè)終端:

 linux,命名管道,命名管道詳解linux,命名管道,命名管道詳解

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 益阳市| 武宣县| 京山县| 马龙县| 临泉县| 奉贤区| 石城县| 内江市| 新泰市| 阳城县| 辛集市| 玉山县| 新宾| 平凉市| 山阴县| 新巴尔虎左旗| 东乌珠穆沁旗| 远安县| 广丰县| 竹北市| 平谷区| 江华| 长葛市| 寿阳县| 大姚县| 卢氏县| 隆安县| 沙田区| 启东市| 大埔县| 日土县| 清流县| 广德县| 渝北区| 元阳县| 卢氏县| 海南省| 宜良县| 桦南县| 马鞍山市| 南昌县|