fclose()/pclose() may block on some file pointers

fclose()和pclose()在某些情况下可能会阻塞,特别是当它们用于popen()返回的文件指针时。这是因为pclose()会等待子进程结束以获取退出状态。手动关闭管道并使用文件描述符可以避免这个问题。fclose()实际上调用了pclose(),因此也会引起等待。在UNIX中,FILE *通常指向包含操作函数指针的数组,popen()返回的FILE *的关闭函数指针会等待子进程结束。正确的做法是使用pclose()关闭popen()返回的描述符,而不要使用fclose()。
摘要由CSDN通过智能技术生成

fclose()/pclose() may block on some file pointers

来自stackoverflow

病例样本:

Calling fclose() here after dup()ing its file descriptor blocks until the child process has ended (presumably because the stream has ended).

FILE *f = popen("./output", "r");
int d = dup(fileno(f));
fclose(f);

However by manually performing the pipe(), fork(), execvp() of the popen(), and then dup()ing the pipe's read file descriptor, closing the original does not block.

int p[2];
pipe(p);
switch (fork()) {
    
    case 0: {
    
        char *argv[] = {
    "./output", NULL};
        close(p[0]);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值