popen and system
popen與system都可在C語言代碼中實現shell命令的執行。
popen是不堵塞的,也就是說不會等待子進程的結束并殺死子進程,即不會管理進程。這樣就需要我們認為的去殺死或忽略子進程等操作。還有就是popen會將執行的結果返回到buf中。
system是堵塞的,會自動對進程進行管理,無需我們再去對進程進行管理。另外,system不會返回執行的結果,只是會返回執行是否成功。
若想要獲取system的執行結果,可參考如下代碼:
int system_result(char *cmd,char *result)
{
char buf[1024*10]={0};
FILE *fp=NULL;
if(buf != NULL)
{
memset(buf,0,sizeof(buf));
sprintf(buf,"%s > /tmp/cmd.txt 2>&1",cmd);
system(buf);
fp=fopen("/tmp/cmd.txt","r");
if(fp == NULL) return -1;
if(fread(result,1024,1,fp) < 0) return -1;
if(fclose(fp) == -1) return -1;
if(system("rm -fR /tmp/cmd.txt")) return -1;
}else return -1;
return 0;
}

浙公網安備 33010602011771號