linux学习:进程间通信—管道

Posted blfbuaa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux学习:进程间通信—管道相关的知识,希望对你有一定的参考价值。

1、进程间通信当中一种比較简单的方法是管道操作

/*
 ============================================================================
 Name        : Test.c
 Author      : wangchuan
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

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

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

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

int main(int argc,char* argv[]) {
	int fd[2],cld_pid,len;
	char buf[200];
	if(pipe(fd) == -1){
		perror("创建管道出错");
		exit(1);
	}
	if((cld_pid=fork()) == 0){
		close(fd[1]);
		len = read(fd[0],buf,sizeof(buf));
		buf[len] = 0;
		printf("子进程从管道中读取的数据是:%s ",buf);
		exit(0);//结束子进程
	}
	else{
		close(fd[0]);
		sprintf(buf,"父进程为子进程(PID=%d)创建该数据",cld_pid);
		write(fd[1],buf,strlen(buf));
		exit(0);//结束父进程
	}
	return 0;
}

编译执行输出例如以下:

子进程从管道中读取的数据是:父进程为子进程(PID=7309)创建该数据


以上是关于linux学习:进程间通信—管道的主要内容,如果未能解决你的问题,请参考以下文章

linux学习:进程间通信—管道

[ Linux ] 进程间通信介绍 管道

Linux学习_IPC进程间通信

2019-2020-1 20175313 《信息安全系统设计基础》第十周学习总结

Linux进程间通信--进程,信号,管道,消息队列,信号量,共享内存

概述Linux进程间通信方式