有名管道(FIFO)
有名管道是持久穩定的。
它們存在於文件系統中。
FIFO比無名管道作用更大,因為他們能讓無關聯的進程之間交換數據。
管道文件一般用於交換數據。
shell命令創建管道
一個shell命令可以建立有名管道
--mkfifo [option] name
--mkfifo創建一個名為name的有名管道
--mkfifo fifo1 創建一個有名管道fifo1
--mkfifo -m 666 fifo2 創建一個帶權限的管道文件
--cat < fifo1 通過cat命令從fifo1中讀取數據。
--ls > fifo1 將ls命令輸出的結果寫入fifo1中
代碼創建管道fifo
mkfifo()函數是C語言庫函數
int mkfifo(const char * pathname,mode_t mode);
參數pathname是文件名稱,
參數mode是文件讀寫權限(讀寫權限是一位八進制數,例如0777(0表示八進制)表示當前用戶,組用戶,其他用戶都擁有對該文件的可讀,可寫,可執行權限)
函數執行成功返回0,否則返回-1,並設置變量errno。
代碼刪除管道
int unlink(const char *pathname);
unlink()函數是系統函數
函數執行成功返回0,否則返回-1,並設置變量errno。
//代碼創建有名管道
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int arg, char * args[])
{
if(arg<2)
{
printf("請輸入一個參數!\n");
return -1;
}
int no=0;
//創建有名管道
no=mkfifo(args[1],0444);
if(no==-1)
{
printf("創建管道失敗!\n");
return -1;
}
return 0;
}
//代碼刪除有名管道
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int arg, char * args[])
{
if(arg<2)
{
printf("請輸入一個參數!\n");
return -1;
}
int no=0;
//刪除有名管道
no=unlink(args[1]);
if(no==-1)
{
printf("刪除管道失敗!\n");
return -1;
}
return 0;
}
打開和關閉FIFO
int open(const char * pathname,int flags);
int close(int fd);
Linux的一切都是文件這一抽象概念的優勢,打開和關閉FIFO和打開關閉一個普通文件操作是一樣的。
FIFO的兩端使用前都必須打開 open中如果參數flags為O_RDONLY將阻塞open調用,一直到另一個進程為寫入數據打開FIFO為止。 相同的,O_WRONLY也導致阻塞一直到為讀出數據打開FIFO為止。
//有名管道讀文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int arg, char *args[])
{
if (arg < 2)
{
printf("請輸入一個參數!\n");
return -1;
}
int fd = 0;
char buf[100] = { 0 };
//打開管道文件
fd = open(args[1], O_RDONLY);
if (fd == -1)
{
printf("open the file failed ! error message : %s\n", strerror(errno));
return -1;
}
while (read(fd, buf, sizeof(buf)) > 0)
{
printf("%s", buf);
memset(buf, 0, sizeof(buf));
}
//close the file stream
close(fd);
return 0;
}
//管道寫文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int arg,char * args[])
{
if(arg<2)
{
printf("請輸入一個參數!\n");
return -1;
}
int fd=0;
char buf[100]={0};
fd=open(args[1],O_WRONLY);
if(fd==-1)
{
printf("open the file failed ! error message :%s\n",strerror(errno));
return -1;
}
while(1)
{
//從鍵盤上讀取數據
read(STDIN_FILENO,buf,sizeof(buf));
if(buf[0]=='0')
{
break;
}
//寫入管道文件中
write(fd,buf,strlen(buf));
memset(buf,0,sizeof(buf));
}
//close the file stream
close(fd);
return 0;
}
