管道在Mac上无法正常工作

时间:2014-12-29 17:26:21

标签: c macos pipe

我有两个名为Csender的{​​{1}}个程序 gettersender上打印了两个字符串"Hello\n""it works\n" 并且stdoutgetter读取字符串并在stdin上打印读取的数据。

NOT 意味着要合作。但是,我尝试在MacBook Pro上使用stdoutsender getter stdout sender连接到stdin

sender.c:

getter

getter.c:

pipe

预期输出:

#include <stdio.h>
int main(int argc, char **argv) {
    fputs("Hello\n", stdout);
    fputs("it works\n", stdout);
    fflush(stdout);
    return 0;
}  

实际输出:

#include <stdio.h>
int main(int argc, char **argv) {
    char msg[80];
    while(fscanf(stdin, "%[^\0]s", msg) != -1) // Keep reading unless the length of string is -1
        fprintf(stdout, "--> %s\n", msg);   /* Point worth noting. 
                                               Every string read from stdin is prepended with 
                                               a "-->" to indicate that it's the getter program 
                                               printing the string and not the sender program.
                                             */

    fflush(stdin);

    return 0;
}  
  • 为什么会这样?为什么我的--> Hello --> it works 计划无法从--> Hello it works // You can see that "-->" is missing here. Which clearly means that it's the sender program printing this on the terminal and not the getter. 阅读getter
  • 为什么我的"it works\n"程序会在终端窗口上打印sender,如果sender已连接到"it works\n"的getter?
  • 我怎么能得到预期的输出?

提前致谢!

1 个答案:

答案 0 :(得分:0)

fgets()读取直到换行符\n并将其包含到读取该行的缓冲区中。因此,在您的情况下,发件人已在每行末尾添加换行符

所以

while(fgets(msg,sizeof(msg),stdin) != NULL)

确保您的字符串以NULL结尾。如果要计算成功读取的行数而不是在while循环中递增count

相关问题