Linux一個(gè)命名管道_Linux教程
命名管道也是按照文件操作流程進(jìn)行的,可以看做特殊文件。
寫(xiě)管道進(jìn)程:打開(kāi)-寫(xiě)-關(guān)閉
讀管道進(jìn)程:打開(kāi)-讀-關(guān)閉
本實(shí)驗(yàn)采用阻塞式讀寫(xiě)管道,一個(gè)程序?qū)懀硪粋(gè)讀。
寫(xiě):
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define MYFIFO "/tmp/myfifo"
#define MAX_BUFFER_SIZE PIPE_BUF
int main(int argc, char* argv[])
{
char buff[MAX_BUFFER_SIZE];
int fd;
int nwrite;
if(argc <= 1)
{
printf("usage: ./write string!\n");
exit(1);
}
sscanf(argv[1], "%s", buff);
fd = open(MYFIFO, O_WRONLY);//打開(kāi)管道,寫(xiě)阻塞方式
if(fd == -1)
{
printf("open fifo file error!\n");
exit(1);
}
if((nwrite = write(fd, buff, MAX_BUFFER_SIZE)) > 0)//寫(xiě)管道
{
printf("write '%s' to FIFO!\n ", buff);
}
close(fd);//關(guān)閉
exit(0);
}
讀:
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define MYFIFO "/tmp/myfifo"
#define MAX_BUFFER_SIZE PIPE_BUF
int main()
{
char buff[MAX_BUFFER_SIZE];
int fd;
int nread;
//判斷管道是否存在,如果不存在則創(chuàng)建
if(access(MYFIFO, F_OK) == -1)
{
if((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST))
{
printf("cannot creat fifo file!\n");
exit(1);
}
}
fd = open(MYFIFO, O_RDONLY);//打開(kāi)管道,只讀阻塞方式
if(fd == -1)
{
printf("open fifo file error!\n");
exit(1);
}
while(1)
{
memset(buff, 0, sizeof(buff));
if((nread = read(fd, buff, MAX_BUFFER_SIZE)) > 0)//讀管道
{
printf("read '%s' from FIFO\n", buff);
}
}
close(fd);//關(guān)閉
exit(0);
}
編譯運(yùn)行,打開(kāi)兩個(gè)終端,一個(gè)寫(xiě),一個(gè)讀。
- Linux系統(tǒng)下TOP命令使用與分析詳解
- 安裝Linux我們需要改變20件事情
- 使用Linux系統(tǒng)架設(shè)VSFTP服務(wù)器
- Linux系統(tǒng)上架設(shè)POP3服務(wù)器
- Linux中“Networking Disabled”的解決方法(解決Ubuntu等系統(tǒng)無(wú)法上網(wǎng))
- ubuntu系統(tǒng)清理磁盤(pán)教程
- linux下搭建pxe自動(dòng)化安裝環(huán)境
- BIOS不支持導(dǎo)致Linux內(nèi)核耗電增加
- Debian GNU/Linux系統(tǒng)卡片
- Linux操作系統(tǒng)開(kāi)機(jī)自行啟動(dòng)項(xiàng)目詳細(xì)解析
- Linux菜鳥(niǎo)入門(mén)級(jí)命令大全
- Linux操作系統(tǒng)中讀取目錄文件信息的過(guò)程
- 相關(guān)鏈接:
- 教程說(shuō)明:
Linux教程-Linux一個(gè)命名管道
。