標籤:linux pipe 進程通訊
[[email protected] 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;
}
--------------測試結果
[[email protected] 04]# ./ex04-3-pipe02
接收到10 個資料,內容:hello,pipe
sizeof(readbuffer) = 80