溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

linux 命名管道實例詳解

發(fā)布時間:2020-09-04 00:50:06 來源:腳本之家 閱讀:121 作者:魏爾肖 欄目:服務(wù)器

linux進程間通信——命名管道

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

  創(chuàng)建命名管道的系統(tǒng)函數(shù)有兩個:mknod和mkfifo。兩個函數(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)建的種類,它只在創(chuàng)建設(shè)備⽂件時才會⽤到。這兩個函數(shù)調(diào)⽤成功都返回0,失敗都返回-1。下⾯使⽤mknod函數(shù)創(chuàng)建了⼀個命名管道:

umask(0);

if (mknod("/tmp/fifo",S_IFIFO | 0666) == -1)

{

perror("mkfifo error");

exit(1);

} 

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

umask(0);

if (mkfifo("/tmp/fifo",S_IFIFO|0666) == -1)

{


perror("mkfifo error!");

exit(1);

}

下面為一個試?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; 
} 

打開兩個終端:

 linux 命名管道實例詳解linux 命名管道實例詳解

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI