FIFO管道/命名管道(半雙工)

特點:

可以是非親緣進程之間;

讀寫必須同時進行,否則阻塞。

創建命名管道:

int mkfifo(pathname,mode);

參數:

pathname:

文件路徑(文件必須不存在)。

mode:

模式。

返回值:

0 成功

非0 失敗

創建FIFO管道代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(){
	if(-1 == mkfifo("/tmp/test",0644)){//0表示8進制;6表示所有者可讀(4)寫(2);4表示同組成員可讀;4表示其他組成員可讀。
		perror("mkfifo error");
		return 1;
	}
}


管道使用P來表示的。

打開FIFO文件:

int open(const char* path, int mode);

參數:

path:

文件路徑。

返回值:

-1 失敗

其他 文件描述符

mode:

O_RDONLY 阻塞只讀

O_RDONLY|O_NONBLOCK 非阻塞只讀

O_WRONLY 阻塞只寫

O_WRONLY|O_NONBLOCK 非阻塞只寫

阻塞讀寫代碼:

阻塞只寫代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(){
	int fd = open("/tmp/test",O_WRONLY);
	if(-1 == fd){
		perror("open error");
		return 1;
	}
	char str[] = "Hello fifo";
	write(fd,str,sizeof(str));
	printf("write:%s\n",str);
}

阻塞只讀代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(){
	int fd = open("/tmp/test",O_RDONLY);
	if(-1 == fd){
		perror("open error");
		return 1;
	}
	char buf[BUFSIZ];
	bzero(buf,BUFSIZ);
	read(fd,buf,BUFSIZ);
	printf("read:%s\n",buf);
}

注意:

fifowrite與fiforead要同時執行,纔會數據傳遞。否則會阻塞。

非阻塞讀寫代碼:

非阻塞讀:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>



int main(){

	int fd = open("/tmp/test",O_RDONLY|O_NONBLOCK);

	if(-1 == fd){

		perror("open error");

		return 1;

	}

	char buf[BUFSIZ];

	bzero(buf,BUFSIZ);

	read(fd,buf,BUFSIZ);

	printf("read:%s\n",buf);

}

非阻塞寫:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>



int main(){

	int fd = open("/tmp/test",O_WRONLY|O_NONBLOCK);

	if(-1 == fd){

		perror("open error");

		return 1;

	}

	char str[] = "Hello fifo";

	write(fd,str,sizeof(str));

	printf("write:%s\n",str);

}


注意:

fcntl(fd,F_SETFL,O_NONBLOCK)不能控制命名管道讀寫阻塞問題。必須在open命名管道時,指定非阻塞打開。

刪除命名管道代碼:

#include <unistd.h>

int main(){
	unlink("/tmp/test");
}




發佈了93 篇原創文章 · 獲贊 44 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章