popen可以找出是否安装了某些应用程序?

kat*_*ang -3 c++

我想找出我的C++程序,安装了.pdf浏览器.我希望使用popen,但即使这个代码也会返回一个nun-NULL

FILE *fp;
fp = popen("abracadabraxx ", "r");
Run Code Online (Sandbox Code Playgroud)

我希望如果没有安装应用程序,就无法分叉.我误解了什么吗?

Lig*_*ica 6

popen打开一根烟斗.和:

如果fork(2)或pipe(2)调用失败,或者函数无法分配内存,则返回NULL.

这些条件都与您打开管道的过程无关.它们与管道本身有关.

要确定该过程是否成功,您需要进入该pclose阶段并:

pclose():成功时,返回命令的退出状态; 如果wait4(2)返回错误,或者检测到其他错误,则返回-1.

您正在尝试捕获shell返回退出代码127的事件,您可以通过该代码获取WEXITSTATUS.

例:

#include <cstdio>
#include <iostream>
#include <sys/wait.h>

int main()
{
    FILE* fd = popen("nonexistingfoobar", "r");
    const int res = pclose(fd);
    printf("%d\n", WEXITSTATUS(res));
}
Run Code Online (Sandbox Code Playgroud)

(现场演示)

请务必阅读文档!