人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

linux 命名管道實例詳解

發(fā)布日期:2022-07-05 12:46 | 文章來源:腳本之家

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

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

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

#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); 

函數mknod參數中path為創(chuàng)建的命名管道的全路徑名:mod為創(chuàng)建的命名管道的模式,指明其存取權限;dev為設備值,該值取決于⽂件創(chuàng)建的種類,它只在創(chuàng)建設備⽂件時才會⽤到。這兩個函數調⽤成功都返回0,失敗都返回-1。下⾯使⽤mknod函數創(chuàng)建了⼀個命名管道:

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

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

umask(0);
if (mkfifo("/tmp/fifo",S_IFIFO|0666) == -1)
{

perror("mkfifo error!");
exit(1);
}

下面為一個試例:

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; 
} 

打開兩個終端:

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

香港服務器租用

版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯系alex-e#qq.com處理。

實時開通

自選配置、實時開通

免備案

全球線路精選!

全天候客戶服務

7x24全年不間斷在線

專屬顧問服務

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務熱線

關注
微信

關注官方微信
頂部