任务: 写一个程序,主程序向管道读数据,子进程向管道从终端设备上写数据。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char* argv[]){
int pipe_id[2];
pid_t child_pid;
int return_val;
char write_buff[1024];
char read_buff[1024];
int return_n_write;
int return_n_read;
/*1、创建管道*/
return_val = pipe(pipe_id);
/*1)判断管道是否创建成功*/
if(return_val == -1){
perror("pipe create
");
return -1;
}
child_pid = fork();
if(child_pid == -1){
perror("process create
");
}
else if(child_pid == 0)
{
/*子进程:写,关闭读端*/
close(pipe_id[0]);
while(1){/*子进程开始向管道写数据*/
/*向标准输入中写入数据,写到缓冲区中*/
fgets(write_buff,sizeof(write_buff),stdin);
/*把写缓冲区的内容写到管道了里面*/
return_n_write = write(pipe_id[1],write_buff,1024);
/*判断是否向管道写入成功*/
if(return_n_write == -1){
perror("write error
");
return -1;
}
}
}
else if((child_pid > 0))
{
/*主进程,读取管道内容*/
close(pipe_id[1]);
while(1)
{
return_n_read = read(pipe_id[0],read_buff,1024);
if(return_n_read == -1){
printf("read from write buff error
");
return -1;
}
/*从管道读数据成功,将读到的数据打印到终端设备上*/
printf("Read from pipe: %s
",read_buff);
if(!(strncmp(write_buff,"quit",4)))
break;
}
/*判断输入的是不是quit,如果是的话,结束子进程*/
}
return 0;
}