我正在使用此脚本运行 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/