如果管道流空閒一段時間,如何關閉程序?Bash:如果管道IO空閒,請關閉
例如說:
someprogram | closeidlepipe -t 500 | otherprogram
有一些程序closeidlepipe
可以關閉,如果閒置一段(-t 500
)?
timeout
可以在一段時間後關閉,但不能與「空閒」區分。
UPDATE
需要注意的是someprogram
輸出二進制數據的層出不窮是很重要的。數據可能包含空字符\0
,應該逐字輸入。
如果管道流空閒一段時間,如何關閉程序?Bash:如果管道IO空閒,請關閉
例如說:
someprogram | closeidlepipe -t 500 | otherprogram
有一些程序closeidlepipe
可以關閉,如果閒置一段(-t 500
)?
timeout
可以在一段時間後關閉,但不能與「空閒」區分。
UPDATE
需要注意的是someprogram
輸出二進制數據的層出不窮是很重要的。數據可能包含空字符\0
,應該逐字輸入。
這是一個程序的核心的一般形式,這樣做。
while(1) {
struct timeval tv;
tv.m_sec = 0;
tv.m_usec = 500000;
int marker = 1;
select(1, &marker, NULL, NULL, &tv);
if (marker == 0) exit(1);
char buf[8192];
int n = read(0, buf, 8192);
if (n < 0) exit(2);
char *b = buf;
while (n)
{
int l = write(1, b, n);
if (l <= 0) exit(3);
b += l;
n -= l;
}
}
內置read
有一個超時選項-t
。
someprogram |
while :; do
IFS= read -d'' -r -t 500 line
res=$?
if [[ $res -eq 0 ||)); then
# Normal read up to delimiter
printf '%s\0' "$line"
else
# Either read timed out without reading another null
# byte, or there was some other failure meaning we
# should break. In neither case did we read a trailing null byte
# that read discarded.
[[ -n $line ]] && printf '%s' "$line"
break
fi
done |
otherprogram
如果read
時間從500個秒鐘後,while
循環將退出與管道的中間部分關閉。 someprogram
將在下一次嘗試寫入該管道的末端時收到SIGCHLD
信號,從而允許其退出。
man 3 select;應該是一個小時的編碼。 – Joshua