您的位置:首页 > 其它

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

2016-06-26 11:09 295 查看
这里用到了 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^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: