Linux一個命名管道_Linux教程
命名管道也是按照文件操作流程進行的,可以看做特殊文件。
寫管道進程:打開-寫-關(guān)閉
讀管道進程:打開-讀-關(guān)閉
本實驗采用阻塞式讀寫管道,一個程序?qū)懀硪粋讀。
寫:
#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);//打開管道,寫阻塞方式
if(fd == -1)
{
printf("open fifo file error!\n");
exit(1);
}
if((nwrite = write(fd, buff, MAX_BUFFER_SIZE)) > 0)//寫管道
{
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);//打開管道,只讀阻塞方式
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);
}
編譯運行,打開兩個終端,一個寫,一個讀。
- 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ǎng))
- ubuntu系統(tǒng)清理磁盤教程
- linux下搭建pxe自動化安裝環(huán)境
- BIOS不支持導(dǎo)致Linux內(nèi)核耗電增加
- Debian GNU/Linux系統(tǒng)卡片
- Linux操作系統(tǒng)開機自行啟動項目詳細(xì)解析
- Linux菜鳥入門級命令大全
- Linux操作系統(tǒng)中讀取目錄文件信息的過程
- 相關(guān)鏈接:
- 教程說明:
Linux教程-Linux一個命名管道。