利用管道进行进程的通信示例

这里用到了 pipe 管道函数: 
int pipe(int file_descriptor[2]); 
函数 pipe 填充的两个整数的含义是两个文件描述符,任何向 file_descriptor[1] 写入的数据,可以从 file_descriptor[0] 中读取,并且写入的数据符合先入先出的规则. 

例 pipe.c: 

#include  
#include  
#include  
#include  

int main() 

int data_processed; 
int file_pipes[2]; 
const char some_data[]="123"; 
char buffer[BUFSIZ+1]; 
int fork_result; 

memset(buffer,'\\0',sizeof(buffer)); 

if(pipe(file_pipes)==0){ 
fork_result=fork(); /* 设置进程 */ 
if (fork_result==-1){ 
/* 判断设置进程是否出错 */ 
fprintf(stderr,"Fork failure"); 
exit(EXIT_FAILURE); 


/* 下面判断,若是是子进程则读管道数据,父进程则向管道写数据 */ 

if(fork_result==0){ 
/* 判断是否子进程 */ 
data_processed=read(file_pipes[0],buffer,BUFSIZ); 
/* 从管道读数据 */ 
printf("Read %d bytes:%s\n",data_processed,buffer); 
exit(EXIT_SUCCESS); 
} else { 
/* 父进程 */ 
data_processed=write(file_pipes[1],some_data,strlen(some_data)); 
/* 向管道写数据 */ 
printf("Wrote %d bytes\n",data_processed); 


exit(EXIT_SUCCESS); 


程序运行:./pipe 
执行结果: 
Wrote 3 bytes 
Read 3 bytes:123 
利用管道进行通信成功!^o^
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值