linux 簡單的命名管道

命名管道,使用雙向通信,要麼分時複用,要麼創建2個管道一個專業收,一個接。


1.使用mkfifo函數創管道;

2.使用open函數打開管道;

3.使用read,write讀寫管道,不要兩個程序同時對一個管道進行寫,這樣會阻塞的;

4.使用close關閉打開的文件描述符。

下面使用一個簡單的例程實現兩個程序之間的通信,大致流程如下:第一個文件爲w.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
	int fd_w = -1;
	int fd_r = -1;
	int i = 0;
	unsigned char val[128];

	memset(val,0,128);
	unlink("/tmp/read");
	unlink("/tmp/write");
	
	mkfifo("/tmp/read",0777);
	mkfifo("/tmp/write",0777);
	
	fd_r = open("/tmp/read",O_RDWR);
	fd_w = open("/tmp/write",O_RDWR);
	printf("start read and write\n");
	
	for (i = 0; i < 100; i++)
	{
		write(fd_w,"hwllo world",12);
		read(fd_r,val,12);	
		printf("receive data : %s\n",val);
		sleep(1);
	}

	close(fd_w);
	close(fd_r);
	unlink("/tmp/read");
	unlink("/tmp/write");
	return 0;
}

第二個程序 r.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
	int fd_w = -1;
	int fd_r = -1;
	int i = 0;
	unsigned char val[128];

	memset(val,0,128);
	
	fd_w = open("/tmp/read",O_RDWR);
	fd_r = open("/tmp/write",O_RDWR);

	printf("start read and write\n");
	
	for (i = 0; i < 100; i++)
	{
		write(fd_w,"hiboy world",12);
		read(fd_r,val,12);	
		printf("receive data : %s\n",val);
		sleep(1);
	}

	close(fd_w);
	close(fd_r);
	unlink("/tmp/read");
	unlink("/tmp/write");
	return 0;
}

編譯上面兩個程序:

#gcc w.c -o  w
#gcc r.c  -o  r
執行上面程序,首先執行w,然後執行r。因爲管道是在w程序中創建的。

#./w &
#./r

看控制檯是否有信息輸出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章