Linux(本笔记基于的版本为Ubuntu 14.04)- 24 管道

进程间通信又简称IPC (inter process communication)

1 IPC

2 管道

ps:

linux中的文件类型:

  • 真正占用磁盘存储的,l (L的小写)记录的是文件的路径,当路径不太长时就直接存放在inode里。
    • - 文件
    • d 目录
    • l 符号链接
  • 伪文件(不是真正的文件,不占用磁盘存储):
    • s 套接字
    • b 块设备
    • c 字符设备
    • p 管道

管道就是内核创建的一个缓冲区,有大小,可以使用ulimit -a查看。

pipe (应用在有血缘关系的进程)

pipe函数:

示例代码1:
 

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

int main(void)
{
	int fd[2];
	pid_t pid;

	int ret = pipe(fd);
	if(ret == -1)
	{
		perror("pipe error!");
		exit(1);
	}

	pid = fork();
	if(pid == -1)
	{
		perror("fork error!");
		exit(1);
	}else if(pid == 0)  // child-process  read. so close write
	{
		close(fd[1]);
		char buf[1024];   // the container for data from reading
		ret = read(fd[0], buf, sizeof(buf));
		if(ret == 0 ) // if to the end of file ,then ret is zeno
		{
			printf("----\n");
		}
		write(STDOUT_FILENO, buf, ret);
		
	}else // parent-process write. so close read
	{
		close(fd[0]);
	//	char* str = "hello pipe\n";
		write(fd[1], "hello pipe\n", strlen("hello pipe\n"));

	}
	return 0;
}

示例代码2 (父进程等一秒再写):
 

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

int main(void)
{
	int fd[2];
	pid_t pid;

	int ret = pipe(fd);
	if(ret == -1)
	{
		perror("pipe error!");
		exit(1);
	}

	pid = fork();
	if(pid == -1)
	{
		perror("fork error!");
		exit(1);
	}else if(pid == 0)  // child-process  read. so close write
	{
		close(fd[1]);
		char buf[1024];   // the container for data from reading
		ret = read(fd[0], buf, sizeof(buf));
		if(ret == 0 ) // if to the end of file ,then ret is zeno
		{
			printf("----\n");
		}
		write(STDOUT_FILENO, buf, ret);
		
	}else // parent-process write. so close read
	{
		close(fd[0]);
	//	char* str = "hello pipe\n";
		sleep(1);
		write(fd[1], "hello pipe\n", strlen("hello pipe\n"));

	}
	return 0;
}

示例代码1和示例代码2的输出结果都是一样的。

那为什么示例代码2中,父进程等一秒后再写时

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值