首页 > 代码库 > linux c 进程 pipe 通信代码分析
linux c 进程 pipe 通信代码分析
[root@luozhonghua 04]# cat ex04-3-pipe02.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void){
int result=-1;
int fd[2],nbytes;
pid_t pid;
char string[]="hello,pipe";
char readbuffer[80];
int *write_fd = &fd[1]; //可写
int *read_fd = &fd[0]; //read
result = pipe(fd); //create pipe
if(-1 == result){
printf("create pipe faile");
return -1;
}
pid=fork(); //分叉程序
if(-1 == pid){
printf("fork 进程失败\n");
return -1;
}
if(0 == pid ){
close(*read_fd);
/*向管道端写入字符*/
result=write(*write_fd,string,strlen(string));
}else{
close(*write_fd);
/* read pipe data */
nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
printf("接收到%d 个数据,内容:%s \n",nbytes,readbuffer);
printf("sizeof(readbuffer) = %d\n",sizeof(readbuffer));
}
return 0;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void){
int result=-1;
int fd[2],nbytes;
pid_t pid;
char string[]="hello,pipe";
char readbuffer[80];
int *write_fd = &fd[1]; //可写
int *read_fd = &fd[0]; //read
result = pipe(fd); //create pipe
if(-1 == result){
printf("create pipe faile");
return -1;
}
pid=fork(); //分叉程序
if(-1 == pid){
printf("fork 进程失败\n");
return -1;
}
if(0 == pid ){
close(*read_fd);
/*向管道端写入字符*/
result=write(*write_fd,string,strlen(string));
}else{
close(*write_fd);
/* read pipe data */
nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
printf("接收到%d 个数据,内容:%s \n",nbytes,readbuffer);
printf("sizeof(readbuffer) = %d\n",sizeof(readbuffer));
}
return 0;
}
--------------测试结果
[root@luozhonghua 04]# ./ex04-3-pipe02
接收到10 个数据,内容:hello,pipe
sizeof(readbuffer) = 80
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。