#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
main(void)
{
int fd[2];
pid_t child;
char s[] = "pipe is good!";
char buf[20];
if (pipe(fd) < 0)
{
printf("create pipe error:%s\n",strerror(errno));
exit(1);
}
if((child = fork()) < 0)
{
printf("fork error:%s\n",strerror(errno));
exit(1);
}
if(0 == child)
{
close(fd[1]); //close another one
sleep(2); // must have this
printf("child read...\n");
if(read(fd[0],buf,sizeof(s)) < 0)
{
printf("read error:%s\n", strerror(errno));
exit(1);
}
printf("\nread:%s\n", buf);
close(fd[0]); //remember to close
// exit(0); // no needed
}
else
{
close(fd[0]);
printf("father process:write...\n");
if(write(fd[1],s,sizeof(s)) < 0)
{
printf("write error:%s\n", strerror(errno));
exit(1);
}
printf("write ok!\n");
close(fd[1]);
waitpid(child, NULL, 0); // must have! compare difference form without
// exit(0); // why need this?
}
}
|