加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用popen和pclose时的问题

发布时间:2020-12-15 21:32:52 所属栏目:安全 来源:网络整理
导读:我有一个使用popen和pclose的程序: #include stdio.h#include stdlib.h#include errno.h#include sys/wait.hint main(void){ FILE *fp = NULL; int ret_val = 0; fp = popen("ls *","r"); if (NULL == fp) { printf("popen errorn"); return 1; } ret_val
我有一个使用popen和pclose的程序:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main(void)
{
    FILE *fp = NULL;
    int ret_val = 0;

    fp = popen("ls *","r");
    if (NULL == fp)
    {
        printf("popen errorn");
        return 1;
    }

    ret_val = pclose(fp);
    if (-1 == ret_val)
    {
        printf("pclose errorn");
        return 1;
    }
    else
    {
        printf("%d,%d,%dn",ret_val,WIFEXITED(ret_val),WEXITSTATUS(ret_val));
    }
    return 0;
}

该计划的输出是:

./test
Broken Pipe
36096,1,141

我的问题是:

>为什么会出现“破管”?
>为什么退出状态码为141?我认为“ls *”已经执行了
因此,退出状态应为0.

解决方法

>“断管”由ls显示,因为SIGPIPE信号是
提高.
>提出了SIGPIPE,因为ls正在尝试输出到已关闭的管道.
>管道已关闭,因为您的程序在popen()之后立即调用pclose().

通过阅读the documentation可以进一步理解pclose的这种行为.基本上,pclose将:

>关闭popen()调用打开的流.
>等待命令终止.
>返回命令的终止状态.

由于它关闭了流然后等待命令终止,因此ls有时会在关闭后尝试写入流,从而导致提到的场景.

另外,正如kingsindian所指出的那样,SIGPIPE可能永远不会被提升.这是因为在主进程调用pclose()之前,命令实际上可以完成其工作.由于这种行为是不可预测的,我建议实现一些同步.您总是想知道您的计划始终处于什么状态.

另外,管道是用于进程间通信的.如果您的主进程只是打开并关闭管道,那么最好使用fork()和exec().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读