Linux 調用係統命令並截獲標準輸出(stdout)和錯誤輸出(stderr)
char ret[1024]; char *DoSysCmd(char * cmdline){ FILE *fp; char line[32]; char cmdtmp[256]; memset(cmdtmp,0x00,256); sprintf(cmdtmp,"%s 2>&1",cmdline);//stderr是2,把2轉向1 memset(ret,0x00,sizeof(ret)); fp = popen(cmdtmp, "r"); while ( fgets( line, sizeof(line), fp)) { sprintf(ret ,"%s%s",ret,line); } pclose(fp); return ret; }
使用例子
show_Info("檢查是否存在可移動存儲設備......");
result=DoSysCmd("cat /proc/scsi/scsi");
if (0==strcmp(result,"Attached devices: none/n"))
{
show_Info("對不起,沒有發現任何設備!");
return;
}
最後更新:2017-04-02 00:06:30