进程间通讯IPC随笔

方式1:信号(signal)

  亲缘进程和非亲缘进程都可以, 也可以进程自己给自己递送信号。另开单章,写不下。

方式2:管道(一般用不到)
  只允许亲缘进程间的通讯。

管道是UNIX IPC的最老形式,并且所有U N I X系统都提供此种通信机制,管道有两种限制;
(1) 它们是半双工的。数据只能在一个方向上流动。
(2) 它们只能在具有公共祖先的进程之间使用。通常,一个管道由一个进程创建,然后该进程调用f o r k,此后父、子进程之间就可应用该管道。


管道的写和读有两个特性:
(1) 数据写入时,放在管道的结尾。
(2) 数据读取时,从管道的头开始读取。
一句话概括:先发过去的,对方先收到。

一般调用这函数:int pipe(int filedes[2]);

参数filedes返回两个文件描述符: filedes[0]为读而打开,filedes[1]为写而打开。filedes[1]的输出是filedes[0]的输入。

由于管道是单向的,所以通常一个进程需要关闭写端或者读端,而另一个进程则关闭相应的读端或写端。
写端不存在时,读端会收到文件结束符。读端不存在时,写端会收到SIGPIPE信号。如果忽略该信号或者捕捉该信号并从其处理程 序返回,则w r i t e出错返回,e r r n o设置为EPIPE
成功返回0,失败返回-1.

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


void Child(int fd[])
{
	int size;
	close (fd[1]);
	char buf[1024];
	memset(buf,0,sizeof(buf));
	size = read(fd[0],buf,sizeof(buf));
	if(size <=0)
	{
		perror("read");
		return ;
	}
	printf("child %d read:%s\n",getpid(),buf);
	close (fd[0]);
}
int main ()
{
	int fd[2];
	int size;
	pid_t pid;
	if(0!= pipe(fd))	//create pipe
	{
		perror("create pipe");
		return -1;
	}

	pid = fork();
	if(pid ==0)
	{
		Child(fd);
		exit(0);
	}
	close(fd[0]);

	size = (write(fd[1],"hello doubi",11));
	printf("%d write: %d\n",getpid(),11);
	close (fd[1]);
	getchar();
	exit(0);
	
}
方式3:命名管道(FIFO)
  除了亲缘进程可以通讯外,非亲缘进程也可以通讯。

F I F O有时被称为命名管道。管道只能由相关进程使用,它们共同的祖先进程创建了管道。但是,通过F I F O,不相关的进程也能交换数据。创建F I F O类似于创建文件,F I F O的路径名存在于文件系统中,创建的FIFO文件就在当前目录下。

int mkfifo(const char *pathname, mode_t mode) ; 返回0成功,返回-1失败
m k f i f o函数中m o de参数的规格说明与o p e n函数中的m o d e相同。

一旦已经用m k f i f o创建了一个F I F O,就可用o p e n打开它。确实,一般的文件I / O函数(open、close、read、write、unlink 等)都可用于F I F O。
F I F O有两种用途:
(1) FIFO由s h e l l命令使用以便将数据从一条管道线传送到另一条,为此无需创建中间临时文件。
(2) FIFO用于客户机-服务器应用程序中,以在客户机和服务器之间传递数据

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

void Clild()
{
	sleep(1);
	char buff[1024];
	memset(buff,0,sizeof(buff));
	int fd1 = open("pathfifo",O_RDONLY);
	if(fd1 ==-1)
	{
		perror("open");
		exit(0);
	}
	read(fd1,buff,sizeof(buff));
	printf("%d read %s \n",getpid(),buff);
}
int main ()
{
	pid_t pid;
	char buf[5] = "hello";
	int res= mkfifo("pathfifo",0666);
	if(res!=0)
	{
		perror("mkfifo");
		return -1;

	}
	pid = fork();
	if(pid ==0)
	{
		Clild();
		exit(0);
	}
	int fd = open("pathfifo",O_WRONLY);
	if(fd ==-1)
	{
		perror("open");
		return -1;
	}
	write(fd,buf,5);
	printf("%d write %s \n",getpid(),buf);
	getchar();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值