popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
实例:
fp = popen("TZ=`cat /etc/TZ`;export TZ;date \"+%Y-%m-%d %H:%M:%S\"", "r"); // 将shell命令的执行结果通过管道输出给FILE *fp文件指针
if(!fp)
{
userLog("get current time error\n");
return 0;
}
fgets(time_buf, 64, fp); // 读取结果到time_buf中,方便后面使用
pclose(fp);
通过这种方法可以很方便的获得 shell命令执行的结果,今天第一次见到这个函数,记录一下。