【问题标题】:When there is no output on the left side of the pipe, what happened on the right side of the pipe?当管道左侧没有输出时,管道右侧发生了什么?
【发布时间】:2022-01-08 16:05:59
【问题描述】:

当我在管道左边放了一个无输出程序时,如:

// program a
int main() {
    char s[255];
    scanf("%s", s);
    return 0;
}

还有一个右侧有输入输出的程序:

// program b
int main() {
    char s[255];
    scanf("%s", s);
    for(char *c = s; *(c) != '\0'; c++) printf("%d ", *c);
    return 0;
}

当我尝试用管道连接它们时:

$ ./a | ./b

不管输入是什么,我的电脑里总是得到两个ASCII码:64 & 3,即使我知道'a'没有输出。

我想知道这是因为我的程序,还是因为 shell,还是因为管道,或者其他什么...

【问题讨论】:

  • 在执行scanf 之前,您是否尝试将s 初始化为全零(可能最容易通过编写static char s[255]; 来完成?
  • @user1934428 谢谢!!!有用!非常简单但无法检测到的错误:(
  • 如果你曾经在真实的应用程序中尝试过这样的事情,请永远不要以这种方式使用scanf,否则你将在下一次代码审查中被烤...

标签: linux shell pipe stdout stdin


【解决方案1】:

管道的意思是“运行程序 a,并将其输出用作程序 b 的输入”。两个程序都被执行。

有趣的是例如cat 进来的地方,它只接受输入并输出它:

$ ls
file  README-cloudshell.txt  terraform.tfstate  test.php
$ ls | cat
file
README-cloudshell.txt
terraform.tfstate
test.php

这也解释了为什么这里没有打印“你好”:

$ echo hallo | ls
file  README-cloudshell.txt  terraform.tfstate  test.php

【讨论】:

  • 我已经大致知道我的问题出在哪里了:scanf 返回EOF,这意味着fd[1] 由于上一个程序的终止而被关闭。但我仍然想知道为什么它给出了两个固定的 ascii 代码:64 & 3,意思是“@”和“文本结尾”。这是管道的某种机制吗?
  • 好的,您期待问题的解决方案还是解释?
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2014-07-30
  • 1970-01-01
相关资源
最近更新 更多