Linux-管道

今天来说一下linux管道

进程间通信:

1.普通文件:俩个进程访问同一个文件 先后顺序

2.文件映射虚拟内存: 父子之间

3.管道

4.信号

5.IPC 共享内存

6.IPC 消息队列

7.IPC 信号量

8.网络通信

现在说一下管道

一 管道:管道是个文件  FIFO First In First Out

(1)匿名管道:没有名字,父子进程之间

                  直接用文件描述符

                 fds[0]用来读

                 fds[1]用来写

          1.创建文件描述符号  int fds[2];

          2.把文件描述符号变成管道  pipe

          3.使用管道进行通信

           4.关闭 close

(2)有名管道:有名字

         可以在同一主机上不同进程之间操作   有具体文件

         1.创建管道文件(mkfifo)

          2.打开管道文件

          3.使用管道文件读/写

          4.关闭

          5.删除管道文件

二:匿名管道代码:

#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
	int fds[2];    
	pipe(fds);     //把文件描述符号变成管道
	if(fork())
	{    //使用管道通信
		char temp[1024];
		int r;
		while(1)
		{
			r=read(fds[0],temp,1023);//读数据
			if(r>0)
			{
			   temp[r] = 0;
			   printf(">> %s\n",temp);
		    }
	    }
	}
	else
	{
		char temp[1024];
		while(1)
		{
		   memset(temp,0,1024);
		   printf("发送啥:");
		   scanf("%s",temp);
		   write(fds[1],temp,strlen(temp));
		}
	}
	close(fds[0]);
	close(fds[1]);
	return 0;
}

三:有名管道代码

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
int main()
{
	//创建管道文件(mkfifo)
	int r = mkfifo("test.pipe",0666);
	if(0 == r)
	{
		printf("创建管道文件:%m\n");
	}
	else 
	{
		printf("创建管道文件失败:%m\n");
		exit(-1);
	}
	//打开管道文件
	int fd = open("test.pipe",O_WRONLY);
	if(-1 == fd)printf("打开管道文件失败:%m\n"),unlink("test.pipe"),exit(-1);
	printf("打开管道文件成功\n");
	//使用管道文件 写
    int n=0;
    char buff[56];
    while(1){
    	memset(buff,0,56);
    	sprintf(buff,"玩游戏:%d",++n);
    	write(fd,buff,strlen(buf));
    	sleep(1);
    }
	//关闭
    close(fd);
	//删除
    unlink("test.pipe");
	return
}
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<stdlib.h>
int main()
{
	int fd = open("test.pipe",O_RDONLY);
	if(-1 == fd) 
		{ 
		    printf("打开管道文件失败:%m\n");
	        exit(-1);
	    }
	printf("打开管道文件成功\n");

     char buff[56];
     int r;
    while(1){
    	memset(buff,0,56);
 
    	r=read(fd,buff,55);
    	if(r>0)
    	{
    		buff[r] = 0;
    		printf(">>%s\n",buff);
    	}
    }
	close(fd);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值