linux c管道的使用方法,Linux C 管道的应用(标准输入输出)

子进程的处理程序:

/*计算两个数的和*/

cal.c

#include

int main()

{

int a, b;

while(1)

{

scanf("%d %d", &a, &b);

printf("a + b = %d/n", a + b);

/*将结果写入stdout文件,这样父进程才可以读到*/

fflush(stdout);

}

return 0;

}

父进程:

io.c

#include

#include

#include

#include

#include

#include

#include

int main()

{

pid_t pid;

int pipe_fdr[2];

int pipe_fdw[2];

if (pipe(pipe_fdr) == -1)

{

perror("pipe failed!/n");

exit(0);

}

if (pipe(pipe_fdw) == -1)

{

perror("fork failed!/n");

exit(0);

}

pid = fork();

if (pid == 0)

{/*子进程操作*/

/*关闭标准输出描述符(自动),并复制pipe_fdr[0]到标准输出描述符,返回值为最小及尚未使用的文件描述符*/

if (dup2(pipe_fdr[0], 0) == -1)

{

perror("dup failed!/n");

exit(0);

}

//*关掉多于的管道*/

close(pipe_fdr[0]);

close(pipe_fdr[1]);

/*关闭标准输入(自动,并把pipe_fdw[1]复制到标准输入描述符*/

if (dup2(pipe_fdw[1], 1) == -1)

{

perror("dup failed!/n");

exit(0);

}

/*关闭多于的管道*/

close(pipe_fdw[0]);

close(pipe_fdw[1]);

if (execl("./cal", "cal", NULL) < 0)

{

printf("Error!!/n");

}

else

{

printf("cal success/n");

}

}

else

{

/*关闭多于的文件描述符*/

close(pipe_fdr[0]);

close(pipe_fdw[1]);

while (1)

{

FILE* in = fdopen(pipe_fdr[1], "w");

FILE* out = fdopen(pipe_fdw[0], "r");

char line[4096];

fgets(line, 4096, stdin);

fprintf(in, line);

/*把缓冲区的内容强行写入in文件*/

fflush(in);

/*读取cal的计算结果*/

fgets(line, 4096, out);

printf(line);

}

/*等待子进程结束*/

wait(NULL);

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值