1. 程式人生 > >多程序程式設計——管道

多程序程式設計——管道

程序間通訊有四種方式:訊號量、管道、訊息佇列、共享記憶體

  我們以前已經介紹過了訊號量,今天我們著重介紹一下管道。

  管道可以分為有名管道和無名管道。

有名管道

   有名管道利用管道檔案實現程序間通訊,管道檔案僅僅是磁碟上的一個檔案標識,其真實資料儲存在記憶體上。

1.命令:mkfifo  filename

2.函式:int   mkfifo();

對於管道檔案的開啟操作,必須是有讀有寫的。否則,open函式會阻塞。

對於管道檔案指向的記憶體中的資料,一旦被讀,則資料就“不存在”了 。

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

int main()
{
	int fda=open("./FIFO",O_WRONLY);
	assert(fda!=-1);
	char buff[128];
	int n=0;
	while(1)
	{
		printf("Input sentence:");
		scanf("%s",buff);
		n=write(fda,buff,strlen(buff)+1);
		if(n <= 0 || !strncmp(buff,"end",3))
		{
			break;
		}
	}
	close(fda);
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<assert.h>

int main()
{
	int fdb=open("./FIFO",O_RDONLY);
	assert(fdb!=-1);
	char buff[128];
	while(1)
	{
		int n = read(fdb,buff,127);
		if(n<=0)
		{
			break;
		}
		printf("%s\n",buff);
	}
	close(fdb);
}

執行結果: 

 

無名管道   

  無名管道相對於有名管道而言,其不存在管道檔案。

  限制:無名管道能完成程序間通訊,必須藉助於父子程序共享fork開的檔案描述符。所以,無名管道只能應用於父子間程序之間的通訊。

  int   pipe(int   fd[2]);        提示使用者無名管道創建於開啟函式pipe只需要接收兩個元素的整型陣列即可。

  fd[0]——讀         fd[1]——寫

管道(有名&無名)   都是半雙工通訊。       資料流向同時時刻是單向的

其中,父程序關閉讀端,子程序關閉寫端,父程序只負責寫,子程序只負責讀。

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

int main()
{
	int fd[2]={-1,-1};
	pipe(fd);
	pid_t n=fork();
    if(n==0)
    {
		char buff[128];
		int n=0;
		close(fd[1]);
		n=read(fd[0],buff,127);
		int i=0;
		printf("Output:");
		printf("%s\n",buff);
		close(fd[0]);
	}
	else
	{
		close(fd[0]);
		write(fd[1],"Hello World",sizeof("Hello World"));
		close(fd[1]);
		waitpid(n,NULL,0);
	}
}

執行結果: