gpt4 book ai didi

c - 如何在输入端检测破损的管道?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:49 24 4
gpt4 key购买 nike

我有一个程序,它通过管道在标准输入上输入数据; 一些应用程序 |我的程序

我希望 read 在破损的管道上返回一个负值;似乎并非如此。主循环看起来像这样:

    int rdsum = 0;
int rdsize = 0;

do
{
rdsize = read(STDIN_FILENO, buf, BUFSIZE);
if(rdsize > 0)
{
//[operations on the buffer]
rdsum += rdsize;
}
else if(rdsize == 0)
{
usleep(100000);
}
else return 0;
}
while(rdsum < blocksize);

return 0; 后,程序直接退出。或者至少它会,如果它发生了......

如果 someappsomeapp | myprogram 结束,或者被杀死,myprog 还活着,出现在ps 列表中。检测馈送应用程序死亡/结束/被杀死并在这种情况下退出的正确方法是什么?

最佳答案

来自 man 2 read:

On success, the number of bytes read is returned (zero indicates end of file)

因此,您的正确行为是返回 rdsize == 0

-1 的返回值仅用于错误(或 errno == EAGAIN 如果文件描述符设置为非阻塞),当发生这种情况时你应该

perror("read"); // print an error message
abort(); // abort the process or do other error handling

像这样:

int rdsum = 0;
int rdsize = 0;

do
{
rdsize = read(STDIN_FILENO, buf, BUFSIZE);
if(rdsize > 0)
{
//[operations on the buffer]
rdsum += rdsize;
}
else if(rdsize == 0)
{
return 0;
}
else if (errno == EAGAIN || errno == EWOULDBLOCK) { // #include <errno.h>
usleep(100000);
} else {
perror("read"); // print an error message
abort(); // exit and core dump
}
}
while(rdsum < blocksize);

关于c - 如何在输入端检测破损的管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27102712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com