管道---

本文介绍了Linux系统中的管道概念,包括无名管道和有名管道的创建与使用,以及它们的特点。通过实例展示了如何利用管道在不同进程间传递数据,强调了管道作为半双工通信方式在进程通信中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.管道

管道可以用来在两个进程之间传递数据,如: ps -ef | grep “bash”, 其中‘|’就是管道,其作用就是将ps 命令的结果写入管道文件,然后 grep 再从管道文件中读出该数据进行过滤。

2.有名管道

有名管道可以在任意两个进程之间通信有名管道的创建:

1>命令创建: mkfifo FIFO

2>系统调用创建

#include <sys/types.h>
#include <sys/stat.h>

//filename 是管道名 mode 是创建的文件访问权限
int mkfifo(const char *filename, mode_t mode);
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>

int main()
{
	int fd = open("FIFO", O_WRONLY);
	assert(fd != -1);
	printf("open FIFO success\n");
	while(1)
	{
		printf("please input: ");
		char buff[128] = {0};

		fgets(buff, 128, stdin);
		write(fd, buff, strlen(buff) - 1);

		if(strncmp(buff, "end", 3) == 0)
		{
			break;
		}
	}
	close(fd);
	exit(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>

int main()
{	
	int fd = open("FIFO", O_RDONLY);
	assert(fd != -1);
	printf("open FIFO success\n");
	while(1)
	{
		char buff[128] = {0};
		int n = read(fd, buff, 127);
		if(n <= 0 || 0 == strncmp(buff, "end", 3))
		{
			break;
		}
		printf("%s\n", buff);
	}

	close(fd);
    exit(0);
}

3.无名管道

无名管道主要应用于父子进程间的通信

创建:

#include<unistd.h>
/*
pipe()成功返回0,失败返回-1
fds[0]是管道读端的描述符
fds[1]是管道写端的描述符
*/
int pipe(int fds[2]);

演示:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <asscrt.h>
#include <stringh>
int main()
{
	int fd[2];
	int res = pipe(fd);
	asser(res!=-1);
	pid_ t pid = fork0; 
	assert( pid!=-1 ); .
	if(pid==0)
	{
		char buff[128] = {0};
		read(fd[0], buff, 127); 
		prinf("child read: %s\n", buff);
    }
	else
    {
		write(fd[1], "hello", 5);
	}
	close(fd[0]);
	close(fd[1);
	exit(0);
}

4.管道的特点

1>无论有名还是无名,写入管道的数据都在内存中

2>管道是一种半双工通信方式(通信方式有单工、半双工、全双工)

3>有名和无名管道的区别:有名可以在任意进程间使用,而无名主要在父子进程间

图13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值