linux进程间通信之管道通信

 

一、命名管道通信

管道通信分为:无名管道和有名管道

无名管道是用于父子孙进程,之间有血缘关系

有名管道:用于任意两个进程

 

无名管道:

1、创建:int pipe(int filedis[2]); 它会创建两个文件描述符 filedis[0] 用于读管道

filedis[1] 用于写管道

(通常先创建一个管道,再通过fork函数创建一个子进程,该子进程会继承父进程所创建的管道。必须在系统调用fork()前调用pipe(),否则子进程将不会继承文件描述符)

 

2、关闭:close(filedis[0]),close(filedis[1])

 

 

//利用无名管道进行进程间通信,父进程write,子进程read
//所需要用到的函数pipe,fork,write,read,memset,strcmp

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

void Write(int fd)
{
    char buf[32] = {0};
    memset(buf,0,sizeof(buf));
    printf("please input what you would write:\n");
    fgets(buf,sizeof(buf),stdin);
    int ret = write(fd,buf,sizeof(buf));
    if(-1 == ret)
    {
        perror("write");
        exit(1);
    }
}

void Read(int fd)
{
    char buf[32] = {0};
    memset(buf,0,sizeof(buf));
    int ret = read(fd,buf,sizeof(buf));
    if(-1 == ret)
    {
        perror("read");
        exit(1);
    }
    printf("read from pipe:%s\n",buf);
}

int main()
{
	int ret,fd[2] = {0};
	pid_t pid;

	ret = pipe(fd);//创建一个无名管道
	if(-1 == ret)
	{
		perror("pipe");
		exit(1);
	}

	pid = fork();
	if(-1 == pid)
	{
		perror("fork");
		exit(1);
	}
	else if(0 == pid)//子进程,read
	{
		close(fd[1]);
		Read(fd[0]);
	}
	else//父进程,write
	{
		close(fd[0]);
		Write(fd[1]);
		
	}	
	return 0;
}

二、命名管道

fifo_read.c

//应用有名管道进行不同进程之间的通信,其实是在磁盘上打开一个tmp文件进行读写
//所要应用到的函数:mkfifo,open,read,close,unlink,strcmp
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	int fd,ret;
	char buf[32];

	mkfifo("1.tmp",777);
	fd = open("1.tmp",O_RDONLY);
	if(-1 == fd)
	{
		perror("open");
		exit(1);
	}	

	while(1)
	{
		ret = read(fd,buf,sizeof(buf));
		if(-1 == ret)
		{
			perror("read");
			exit(1);
		}
		printf("read from 1.tmp :%s\n",buf);
		if(!strcmp(buf,"bye\n"))
		{
			break;
		}
		memset(buf,0,sizeof(buf));
	}
	close(fd);
	unlink("1.tmp");
	
	return 0;
}

fifo_write.c

//有名管道写进程
//open,write,strcmp,close
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	int fd,ret;
	char buf[32] = {0};

	fd = open("1.tmp",O_WRONLY);
	if(-1 == fd)
	{
		perror("open");
		exit(1);
	}

	while(1)
	{
		printf("please input what you would to write :\n");
		fgets(buf,sizeof(buf),stdin);
		ret = write(fd,buf,strlen(buf));
		if(-1 == ret)
		{
			perror("write");
			exit(1);
		}
		
		if(!strcmp(buf,"bye\n"))
		{
			break;
		}
		memset(buf,0,sizeof(buf));
		
	}

	close(fd);

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值