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

使用popen时必须关闭流

发布时间:2020-12-16 09:31:03 所属栏目:百科 来源:网络整理
导读:正如标题所说,我不确定是否应关闭使用popen打开的流. 我不确定的原因是因为每次我在使用popen打开的流上调用pclose时,我得到一个-1返回代码. 如果我之后打电话给perror,我收到以下消息. pclose: No Child Processes 我在下面使用的代码基本上是运行一个命令
正如标题所说,我不确定是否应关闭使用popen打开的流.

我不确定的原因是因为每次我在使用popen打开的流上调用pclose时,我得到一个-1返回代码.

如果我之后打电话给perror,我收到以下消息.

pclose: No Child Processes

我在下面使用的代码基本上是运行一个命令并捕获它的输出.我从最后一行得到错误(返回pclose(fileListingStream);)

int executeCommand(char *command) {
    //The Stream to read that will contain the output of the command
    FILE *fileListingStream;
    char path[PATH_MAX];

    //Run the commmand in read mode
    fileListingStream = popen(command,"r");

    //Ensure that its not null before continuing
    if (fileListingStream == NULL)
        return EXIT_FAILURE;

    //Get the data from the stream and then print to the the console
    while (fgets(path,PATH_MAX,fileListingStream) != NULL)
        printf("%s",path);

    //Close the stream and return its return code
    return pclose(fileListingStream);
}

解决方法

是的你应该.有关pclose()内部工作原理的说明,请参见 this answer.此外,您应该注意,wait4()中的错误可能是pclose()中明显失败的原因.

Update0

如果FILE *有效(在内部这表示文件描述符不是-1),如果出现错误,pclose()和fclose()将不会导致泄漏.值得注意的是,如果FILE *无效,那么无论如何都无需清理.正如我在链接中所讨论的那样,pclose()有额外的行为,即从proc文件链中删除FILE *,然后等待子进程终止.内部等待实际上是pclose()完成的第二件事,此时已经清理了所有内容.在等待之后,立即删除FILE的内容以表示其无效,无论waitpid()中是否有任何错误,都会发生这种情况.

鉴于您收到的错误,ECHILD,我可以明确地说,eglibc-2.11.1下的pclose()没有内存泄漏,并且可能至少在过去1 – 4年内任何glibc派生的库.

如果您希望完全确定,只需在valgrind下运行程序,然后触发ECHILD错误.如果有任何泄露,Valgrind会通知您.

(编辑:李大同)

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

    推荐文章
      热点阅读