Chinaunix

标题: pipe [打印本页]

作者: creatory    时间: 2008-12-12 19:27
标题: pipe
/*the parent and child process comminucates through the pipe
the child process write data to pipe
the parent process read data from pipe
*/
#include
#include
#include
#include
#include
#include
#include
#define BUF_SIZE  511
int main(int argc,char **argv)
{
char buffer[BUF_SIZE+1];
int fd[2];/*pipe file descriptor*/
if(argc!=2)
{
fprintf(stderr,"Usage:%s string\n",argv[0]);
return 0;
}
/*create pipe
fd[0]:for read
fd[1]:for write
*/
if(pipe(fd)!=0)
{
fprintf(stderr,"Create pipe error:%s\n",strerror(errno));
return 0;
}
/*fork child process*/
if(fork()==0)/*child process*/
{
close(fd[0]); /*close read*/
printf("Child[%ld] write data [%s] to pipe.\n",getpid(),argv[1]);
snprintf(buffer,BUF_SIZE,"%s",argv[1]);
buffer[BUF_SIZE+1]='\0';
write(fd[1],buffer,strlen(buffer));
printf("Child[%ld] quit.\n",getpid());
exit(0);/*child process exit*/
}
else /*parent process*/
{
close(fd[1]);/*close write*/
memset(buffer,0,BUF_SIZE+1);
read(fd[0],buffer,BUF_SIZE);
buffer[BUF_SIZE+1]='\0';
printf("Parent[%ld] read data [%s] from pipe.\n",getpid(),buffer);
printf("Parent[%ld] quit.\n",getpid());
exit(1);
}
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/56374/showart_1716507.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2