如果pipe道stream闲置一段时间,如何closures程序?
比如说:
someprogram | closeidlepipe -t 500 | otherprogram
有一些程序closeidlepipe
可以closures,如果闲置一段时间( -t 500
)?
timeout
可以在一段时间后closures,但不能与“空闲”区分。
UPDATE
需要注意的是, someprogram
输出的是二进制数据的层出不穷。 数据可能包含空字符\0
,应逐字input。
这是一个程序的核心的一般形式,这样做。
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
如果超过500秒后超时, while
循环将退出,管道的中间部分关闭。 someprogram
在下次尝试写入该管道的末端时会收到一个SIGCHLD
信号,允许它退出。