尽管替换了标准输入,为什么我的管道没有在 printf 中读取? [英] Why is it that my pipe does not read in the printf despite replacing stdin?

查看:75
本文介绍了尽管替换了标准输入,为什么我的管道没有在 printf 中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是使用 dup、dup2 和管道在父进程和子进程之间进行通信.只是为了了解如何使用 dup 和管道.由子进程调用的函数 multby 将一个数字作为参数 (3) 并将其与用户输入(在本例中为 5 打印在父进程中)相乘以获得产品.(应该是 15)

The objective is to use dup, dup2 and pipe to communicate between parent and child processes. Just to get a feel of how to use dup and pipes. The function multby, called in by the child process, takes a number as an argument (3) and multiply it with a user input (in this case 5 as printed in parent) to get a product. (which should be 15)

#include <stdio.h> 
#include <unistd.h> 

void main(int argv, char *argc) { 
    int testpipe[2]; 
    pipe(testpipe); 
    int PID = fork(); 
    if (PID == 0) { 
        dup2(testpipe[0], 0); 
        close(testpipe[1]); 
        execl("./multby", "multby", "3", NULL); 
        close(testpipe[0]); 
        close(0); 
    } else { 
        dup2(testpipe[1], 1); 
        close(testpipe[0]); 
        printf("5"); 
        close(1); 
        close(testpipe[1]); 
        wait(NULL); 
    }  
}

这是multby的代码.我还添加了一些 fprintf 语句来进行故障排除.特别是,它打印出要相乘的 2 个数字(应该是上面提到的 3 和 5).

Here is the code for multby. I also added some fprintf statement to troubleshoot. In particular, it prints out the 2 numbers to be multiplied (which should be 3 and 5 as mentioned above).

#include <stdio.h>

int main(int argv, char *argc[]) {
  fprintf(stderr,"exec successful\n");
  if (argv < 2) {
    fprintf(stderr, "Usage: %s <factor>\n", argc[0]);
    return 1;
  }      

  size_t a, b;
  sscanf(argc[1], "%zu", &a);
  fprintf(stderr, "a: %zu\n", a);

  if (scanf("%zu", &b) != 1) {
    fprintf(stderr, "No input %zu\n", a);
    return 1; 
  } 
  fprintf(stderr, "b: %zu\n", b);
  printf("%zu", a*b);
  fprintf(stderr, "multby successful\n");
  return 0;
}

然而,这是我的结果:执行成功一:3无输入 3

However, this is my result: exec successful a: 3 No input 3

5 未从管道的读取端注册.

5 was not registered from the read end of the pipe.

有人能告诉我我做错了什么吗?

Could someone please advise me on what I am doing wrong?

推荐答案

您使用 printf(5"); 将数据中继到子进程,但标准输出至少是行缓冲的所以在发送换行符之前不会写入任何内容(或 fflush(stdout)).然后你 close(1); 关闭标准输出,它不会刷新标准 I/O 缓冲区.所以什么都没有发送给孩子.使用 fclose(stdout); 将 5 发送给孩子.

You use printf("5"); to relay the data to the child, but standard output is at least line-buffered so nothing is written until a newline is sent (or fflush(stdout)). Then you close(1); to close standard output, which does not flush the standard I/O buffers. So nothing is sent to the child. Use fclose(stdout); to get the 5 sent to the child.

这篇关于尽管替换了标准输入,为什么我的管道没有在 printf 中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆