计算机操作系统第四次实验 匿名管道通信

1.实验目的

学习使用匿名管道在两进程间建立通信。

2.实验软硬件环境

  • 安装Windows XP的计算机
  • VirtualBox软件,以及在其上安装的Ubuntu虚拟机

3.实验内容

    在Linux下创建匿名管道,父进程写管道,子进程读管道。实现利用匿名管道在进程间通信。

    使用函数:

  • int  pipe(int fd[2])    返回值:成功0,失败-1。管道两端可分别用描述字fd[0]以及fd[1]来描述,需要注意的是,管道的两端是固定了任务的。即一端只能用于读,由描述字fd[0]表示,称其为管道读端;另一端则只能用于写,由描述字fd[1]来表示,称其为管道写端。如果试图从管道写端读取数据,或者向管道读端写入数据都将导致错误发生。一般文件的I/O函数都可以用于管道,如close、read、write等等。 
  • int close(int fd)     当操作完成以后,就关闭文件,fd为要关闭的文件描述符。
  • unsigned sleep(unsigned milliseconds)执行挂起一段时间,单位是毫秒
  • ssize_t read(int fd , const void *buf , size_t length);ssize_t write(int fd , const void *buf , size_t length);       其中参数fd是有效文件描述符,参数buf为指向缓冲区的指针,length为缓冲区的大小(以字节为单位)。函数read()实现从文件描述符fd所指定的文件中读取length个字节到buf所指向的缓冲区中,返回值为实际读取的字节数。函数write实现把length个字节从buf指向的缓冲区中写到文件描述符fd所指向的文件中,返回值为实际写入的字节数。 

4.实验程序及分析

实验程序:

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



void main()
{
	int fd[2];
	int status = pipe(fd);
	if(status == 0)
	{
		int pid = fork();
		if (pid == 0)
		{
			puts("\nin child");
			close(fd[1]);
			sleep(1);
			char s2[100];
			read (fd[0],s2,100);
			puts("\n\treading from pipe ...");
			printf("\t");puts(s2);
			puts("\tread success");
			close(fd[0]);
			puts("child end\n");
			exit(0);
		}
		else if(pid>0)
		{
			
			puts("\n\nin parent");
			close(fd[0]);
			puts("\twritting to pipe ...\n\tcontent:hello thank you");
			char s[]="\n\thello thank you\n";
			puts("\twrite success");
			write(fd[1],s,100);
			close(fd[1]);
			puts("parent end\n");
			exit(0);
		}
		else
		{
			puts("failed to create a child process\n");
		}

	}
	else
		puts("failed to create a pipe");
}

分析:

首先用pipe()创建管道。fd[0]表示读端,fd[1]表示写端。用fork()创建进程后,由于子进程有sleep()函数,故父进程先执行。父进程用write()函数对管道写端进行写操作,之后子进程用read()函数对管道读端进行读操作。将结果输出在终端上。

5.实验截图

6.实验心得体会

此次实验让我理解了管道通信在Linux的实现,并对管道通信机制有了更深的了解。

发布了47 篇原创文章 · 获赞 28 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41122796/article/details/80396829