1. 程式人生 > >管道實驗(二)

管道實驗(二)

編寫程式實現以下功能:
利用匿名管道實現兄弟程序間通訊,要求兄程序傳送字串“This is elder brother ,pid is (兄程序程序號)”給弟程序;
弟程序收到兄程序傳送的資料後,給兄程序回覆“This is younger brother ,pid is(弟程序程序號)”;
 

我們都知道利用fork函式能建立一個子程序,但是如何利用fork函式建立兄弟程序呢?

我們可以利用fork函式先建立一個子程序,在子程序中,將要傳送的資訊寫入管道,然後再在父程序中再次呼叫fork函式,那麼父程序裡建立的子程序就是先前建立的程序的弟程序。我們可以讓子程序將自己的父程序的pid列印,驗證兩程序是否是兄弟程序。

程式如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
	int fd1[2],fd2[2];
	pipe(fd1);
	pipe(fd2);

	int pid;
	pid = fork();
	if(pid == 0)
	{
		printf("This is the elder brother!\n");
		printf("The elder's father's pid is: %d\n",getppid());

		close(fd1[1]);
		close(fd2[0]);
		char str1[64],str2[64];
		sprintf(str1,"This is the elder brother,pid is %d",getpid());
		
		if(write(fd2[1],str1,64) < 0)
		  perror("write");
		
		if(read(fd1[0],str2,64) < 0)
		  perror("read");
		else
		  printf("The news from younger is: %s\n",str2);

	}
	else
	{
		if(fork() == 0)
		{
			printf("This is the younger brother!\n");
			printf("The younger's father's pid is: %d\n",getppid());

			close(fd1[0]);
			close(fd2[1]);
			char buf1[64],buf2[64];
			if(read(fd2[0],buf1,64) > 0)
			{
				printf("The news form elder is: %s\n",buf1);
				sprintf(buf2,"This is the younger brother,pid is %d",getpid());

				if(write(fd1[1],buf2,64) < 0)
					perror("write");
			}
			else
			  perror("read");
		}
	}
}

執行結果如下: 

通過實驗結果我們可以發現,兩個程序的父程序並不相同。但是通過在ubuntu的環境下,測試成功。