管道通信——Pipeline communication

//using pipe the communication between f proccess and c proc
//
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFSIZE1024

int main()
{
int ret,retw;
pid_t pid;
char buf[BUFSIZE] = {'\0'};
int pd[2];

// pipe() creates a pair of file descriptors,pointing to a pipe inode,and places them in the
// array pointed to by filedes. filedes[0] is for reading,filedes[1] is for writing.

if(pipe(pd) < 0)
{
perror("pipe()");
exit(1);
}

pid = fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}

if(pid == 0)//child read
{
close(pd[1]);//prevent the error
ret = read(pd[0],buf,BUFSIZE);
puts(buf);
close(pd[0]);
exit(0);
}
else// parent write
{
close(pd[0]);
retw = write(pd[1],"Hello",5);
close(pd[1]);
wait(NULL);
exit(0);
}

exit(0); }

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...