- 论坛徽章:
- 0
|
/* pipe02.c */
#include unistd.h>
#include stdio.h>
#include stdlib.h>
#include fcntl.h>
#include limits.h>
int main (void)
{
int fd[2];
int fdin;
char read_pipe_buf[PIPE_BUF];
char read_file_buf[PIPE_BUF];
pid_t pid;
int read_pipe_len;
int read_file_len;
/* creat a pipe */
if ((pipe(fd)) 0){
perror("pipe error");
exit(1);
}
pid = fork();
if (pid 0){
perror("fork error");
exit(1);
}
/* child */
if (0 == pid){
close(fd[1]); /* close wite pipe */
while((read_pipe_len = read(fd[0], read_pipe_buf, PIPE_BUF)) > 0){
read_pipe_buf[read_pipe_len] = '\0';
printf("read %d bytes\n", read_pipe_len);
printf("%s\n", read_pipe_buf);
}
close(fd[0]);
}
/* parent */
if (pid > 0){
close(fd[0]);
fdin = open("pipe01.c", O_RDONLY);
if (fdin 0){
perror("open error");
exit(1);
}
}
read_file_len = read(fdin, read_file_buf, PIPE_BUF);
if (read_file_len > 0){
write(fd[1], read_file_buf, read_file_len);
}
close(fdin);
close(fd[1]);
waitpid(pid, NULL, 0); /* wait for child */
exit(0);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/103542/showart_2138540.html |
|