#include /*define a function pid_printf*/
void pid_printf(char *format, ...)
{
va_list ap;
va_start(ap, format);
printf("[%d]%d:", getpid(),__LINE__);
vprintf(format, ap);
}
/*chile write data to pipe*/
void child_process(int pfd[2])
{
close(pfd[0]); //close unused read fd
char buf[256];
pid_printf("child process is ready.\n");
pid_printf("enter message(ctrl+d to exit):");
fflush(stdout);
while(fgets(buf, sizeof(buf), stdin) != NULL)
{
pid_printf("Transmitting message:%s",buf);
write(pfd[1], buf, strlen(buf));
}
pid_printf("child process exiting.\n");
close(pfd[1]);
_exit(EXIT_SUCCESS);
}
/*parent read data from pipe*/
void parent_process(int pfd[2])
{
char buf[256] = {0};
int count;
int status;
/*close unused write fd*/
close(pfd[1]);
pid_printf("parent process is ready.\n");
while(1)
{
count = 0;
while(count < sizeof(buf)-1)
{
status = read(pfd[0], buf+count, 1);
if(status < 1)
{
pid_printf("read eof, parent exiting\n");
close(pfd[0]);
return;
}
if(buf[count] == '\n')
break;
count ++;
}
pid_printf("receive message:%s\n", buf);
}
pid_printf("no more data , parent exiting\n");
close(pfd[0]);
}
int main(int argc, char *argv[])
{
int pfd[2];
pid_t pid;
if(pipe(pfd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if(pid == 0)
{
child_process(pfd);
}
else if(pid!=-1)
{
parent_process(pfd);
}
return 0;
}
/*管道主要是使用pipe()函数*/