popen() 对所有命令都是成功的

popen() is successfull for all commands

无论在 popen() 中传递什么 "cmd" 字符串,对我来说都不会失败

所以即使对于随机 "cmd" 字符串,fp 也永远不会为 NULL。

FILE *fp;
char path[1035];
char cmd = "randomrandomrandom";
fp = popen(cmd, "r");

if (fp == NULL) {
    //Handle Error
    exit(1);
}
while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
}
pclose(fp);

它的行为似乎符合预期: http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html

如您所见,popen 仅在其内部 pipe 命令失败时失败——无法打开流。例如,所有文件描述符都在使用中

popen 运行 shell 的实例。启动 shell 通常会成功。您需要确定它是否已 终止 成功。 popen 本身不能这样做,但是 pclose 可以:它 return 是子进程的状态(如果发生另一个错误,则为 -1)。

因此,为了验证命令是否已成功执行,需要检查 popenpclose 的 return 值。