进程通信-无名管道PIPE

进程间通信方式:

古老方式:
无名管道:PIPE
有名管道:FIFO  named pipe
信号:signal

系统IPC(进程间通信)
信号量(sem)
共享内存(shm)
消息队列(msg)

BSD:
套接字:socket


先说无名管道PIPE

PIPE:无名管道
原型:int pipe(int pipefd[2]);头文件为unistd.h
参数:两个文件描述符
说明:pipe()创建一个管道,一个单向数据通道,可用于进程间通信,pipefd用于返回两个文件描述符指管端.
         pipefd[0]指管道的读端,pipefd[1]指管道的写端.写入管道的写入端的数据被内核缓冲,直到从管道
         的读取端读取.
     适用于亲缘关系的进程中,随进程结束而结束,先申请管道,在创建进程,最后完成读写操作.
返回值:成功返回0,失败返回-1

测试代码:

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include <fcntl.h> 
void main(){
	int pipefd[2];
	pid_t fd;
	char test[]="pipe test is runing";
	char reader[24]={0};
	
	if(pipe(pipefd)==-1){
		printf("create pipe error!\n");
		exit(0);
	}

	fd=fork();
	if(fd==-1){
		printf("fork error!\n");
		exit(0);
	}
	//getpid返回当前进程标识,getppid返回父进程的标识
	if(fd==0){
		printf("child process:getpid:%d,getppid:%d,pid:%d\n",getpid(),getppid(),fd);
		close(pipefd[0]);//关闭读  完成写
		write(pipefd[1],test,strlen(test));
	}
	else{
		printf("parent process:getpid:%d,getppid:%d,pid:%d\n",getpid(),getppid(),fd);
		close(pipefd[1]);
		read(pipefd[0],reader,strlen(test));
		printf("reader is:%s\n",reader);
	}	
	return;
}
测试结果:

[root@libmaster zxd]# ./a.out 
parent process:getpid:1206,getppid:601,pid:1207
child process:getpid:1207,getppid:1206,pid:0
reader is:pipe test is runing




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值