- 论坛徽章:
- 0
|
以下程序 是在程序内读写pipe ,而我需要在进程之间通过pipe进行数据传输,如何获得另一个进程放入管道pipe中的数据
例如 ls | myprog
#include <sys/types.h>;
int main()
{
int p[2];
char buf[80];
pid_t pid;
if (pipe(p))
{
perror("pipe failed" ;
return 1;
}
if ((pid=fork()) == 0)
{
/* in child process */
close(p[0]); /*close unused read */
*side of the pipe */
sprintf(buf,"%d",getpid());
/*construct data */
/*to send */
write(p[1],buf,strlen(buf)+1);
/*write it out, including
/*null byte */
exit(0);
}
/*in parent process*/
close(p[1]); /*close unused write side of pipe */
read(p[0],buf,sizeof(buf)); /*read the pipe*/
printf("Child process said: %s/n", buf);
/*display the result */
return 1;
} |
|