c - 如何让程序在没有内容可读时自行终止

标签 c bash unix

我正在使用此脚本运行 C 程序:

tail -f -n +1 input | ./output

我的程序是:

#include <stdio.h>
int main()
{
    printf("Hello world!");
    return 0;
}

它应该在运行后立即终止,因为该程序中没有任何内容可读取。

但是发生的情况是,除非我向我用来重定向到程序的输入提供一些输入,否则它确实会终止。

为什么我会有这种行为?

最佳答案

Why, I am having this behaviour?

tail -f input 持续读取input 并且不关闭管道。当您的程序完成时,管道将损坏,因为其读取端被关闭(由您的程序)。

如果tail尝试写入管道,它将收到SIGPIPE并被杀死。否则 tails 会挂起。

<小时/>

首先,尝试在 stdin 上单独运行 tail -f -n +1:

$ tail -f -n +1
tail: warning: following standard input indefinitely is ineffective

通过查看 tail 手册页中的选项 -f:

-f, --follow[={name|descriptor}] output appended data as the file grows;

因此,只需从 tail 命令中删除 -f 选项即可:

tail -n +1 input | ./output

关于c - 如何让程序在没有内容可读时自行终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195786/

相关文章:

c++ - 在 C 中,将函数指针赋值给适当类型的变量给出 "cannot convert ... in assignment"

c - 有没有适合替代C宏的推荐代码生成方式?

bash - BASH 脚本中的 export 关键字

c++ - Linux TCP 服务器 - 在 C++ 中监听多个端口

C:我传递的字符串错了吗?

c - "CONST func(arg);"在C语言中是什么意思?

c++ - 如何将整数参数传递给 shell 脚本,然后将其传递给程序?

linux - 通过 bash 将一个大变量传递给 diff 命令

regex - 结合删除标签正则表达式和删除 sed 中的空行 - Unix

linux - 为什么 cat 0>file 不起作用