进程间通信方式(IPC)和管道

进程间通信方式

image
进程间之所以可以进行通信,是应为都在内核区,缓冲区的大小一般为4096字节image

管道

imageimage

管道使用函数

imageimage

/*************************************************************************
	> File Name: pipe_test.c
	> Author: shaozheming
	> Mail: 957510530@qq.com
	> Created Time: 2022年02月27日 星期日 11时19分51秒
 ************************************************************************/

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

void sys_err(const char *str)
{
    perror(str);
    exit(1);
}

int main(int argc, char* argv[])
{
	int fd[2];
	int ret;
	pid_t pid;
	char *str = "hello pipe!\r\n";
	char buf[1024];

	ret = pipe(fd); //创建管道,一个读端一个写端 fd[0]是读,fd[1]是写
	if(ret == -1){
		sys_err("pipe error\r\n");
	}
	
	pid = fork();
	if(pid > 0){
		//父进程
		close(fd[0]); //关闭读端,也就是写
		write(fd[1], str, strlen(str));
		close(fd[1]); //关闭读端,也就是写
	}else if(pid == 0){
		//子进程
		close(fd[1]); //关闭写端,也就是读
		sleep(1);
		ret = read(fd[0], buf, sizeof(buf));
		write(STDOUT_FILENO, buf, ret);
		close(fd[0]);
	}else {
		sys_err("pid error\r\n");
	}
    return 0;
}

管道读写行为

image

使用管道实现ls | wc-l

此命令是实现ls出来的文件的行数或个数

/*************************************************************************
	> File Name: pipe_test.c
	> Author: shaozheming
	> Mail: 957510530@qq.com
	> Created Time: 2022年02月27日 星期日 11时19分51秒
 ************************************************************************/

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

void sys_err(const char *str)
{
    perror(str);
    exit(1);
}

int main(int argc, char* argv[])
{
	int fd[2];
	int ret;
	pid_t pid;

	ret = pipe(fd); //创建管道,一个读端一个写端 fd[0]是读,fd[1]是写
	if(ret == -1){
		sys_err("pipe error\r\n");
	}
	
	pid = fork();
	if(pid > 0){	//父进程
		close(fd[0]); //关闭读端,也就是写
		
		dup2(fd[1], STDOUT_FILENO); //将标准输出指向写端
		execlp("ls", "ls", NULL);
	
	//	close(fd[1]); 不能close,execlp之后就不会回来了
	}else if(pid == 0){		//子进程
		close(fd[1]); //关闭写端,也就是读

		dup2(fd[0], STDIN_FILENO);
		execlp("wc", "wc", "-l", NULL);
	}else {
		sys_err("pid error\r\n");
	}
    return 0;
}

管道总结

image

命名管道fifo

imageimageimageimage

文件通信

使用文件也可以进行IPC通信,不过已经过时了image

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值