分类: C/C++
2013-12-17 15:53:13
static int pfd1[2],pfd2[2];
void err_sys(char *str)
{
printf("%s\n",str);
exit(1);
}
void err_quit(char *str)
{
printf("%s\n",str);
exit(0);
}
void TELL_WAIT(void)
{
if(pipe(pfd1)<0||pipe(pfd2)<0)
err_sys("pipe error");
}
void TELL_PARENT(pid_t pid)
{
if(write(pfd2[1],"c",1)!=1)
err_sys("write error");
}
void WAIT_PARENT(void)
{
char c;
if(read(pfd1[0],&c,1)!=1)
err_sys("read error");
if(c!='p')
err_quit("WAIT_PARENT:incorrect data");
else
printf("parent is %c\n",c);
}
void TELL_CHILD(pid_t pid)
{
if(write(pfd1[1],"p",1)!=1)
err_sys("write error");
}
void WAIT_CHILD(void)
{
char c;
if(read(pfd2[0],&c,1)!=1)
err_sys("read error");
if(c!='c')
err_quit("WAIT_CHILD: incorrect data");
else
printf("child is %c\n",c);
}
int main(void)
{
pid_t pid;
TELL_WAIT();
pid=fork();
if(pid<0)
err_sys("fork failed");
else if(pid>0){
close(pfd2[0]);
TELL_PARENT(pid);
close(pfd1[1]);
WAIT_PARENT();
}else{
close(pfd1[0]);
TELL_CHILD(pid);
close(pfd2[1]);
WAIT_CHILD();
}
return 0;
}