本文介绍了读取过程在写入过程之前终止时的Unix/Linux管道行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

$ ls -lh file
-rw-r--r-- 1 ankur root 181M Sep 23 20:09 file

$ head -6 file

z
abc
abc
abc
abc
abc

$ cat file | grep -m 1 z
z

问题:

为什么最后一行中的cat命令行没有因SIGPIPE而过早死去?我认为这应该发生,因为grep立即终止,而cat file则占用了183MB的文件.随着读取过程的结束,cat将尝试写入损坏的管道,并且应该因SIGPIPE而死.

Why is the cat command line in the last line not dying prematurely with SIGPIPE? I think this should happen because grep terminates in no time compared to cat file that cats 183MB of file. With reading process gone cat will try to write to a broken pipe and should die with SIGPIPE.

更新:

我最终写了这个:readstdin.c

I ended up writing this: readstdin.c

# include <unistd.h>
# include <stdio.h>

int main() {

    ssize_t n ;        
    char a[5];        
    n = read(0, a, 3);
    printf("read %zd bytes\n", n);
    return(0);

}

我这样使用它:

$ cat file | ./readstdin
$ yes | ./readstdin

catyes仍然不会过早死亡.我希望是这样,因为在编写过程完成之前,阅读过程终止了.

But still cat or yes does not die prematurely. I expect it to because by reading process is terminating before writing process is done writing.

推荐答案

如果某些管道(2)关闭( 2) -ed,进一步 write(2)将会得到SIGPIPE signal(7).另请阅读 pipe(7).

If the read end of some pipe(2) is close(2)-ed, further write(2)s will get a SIGPIPE signal(7). Read also pipe(7).

yes | ./readstdin命令中,yes命令获得一个SIGPIPE信号.只需在终端中尝试yes,它会无限期地吐出一些恶作剧内容,直到您将其杀死为止.

In the yes | ./readstdin command, the yes command gets a a SIGPIPE signal. Just try yes in a terminal, it spits some output indefinitely ad nauseam till you kill it.

cat file | ./readstdin命令中,可能会发生(特别是如果file很小,小于sysconf(_POSIX_PIPE_BUF)字节,可能是4096字节),则cat命令是close(2)- STDOUT_FILENO描述符,并且管道仍未满.那么cat可能不会得到任何SIGPIPE.

In the cat file | ./readstdin command, it could happen (notably if file is quite small, less that sysconf(_POSIX_PIPE_BUF) bytes, which might be 4096 bytes), that the cat command is close(2)-ing the STDOUT_FILENO descriptor and that the pipe is still not full. Then cat may not get any SIGPIPE.

这篇关于读取过程在写入过程之前终止时的Unix/Linux管道行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:17