linux的C獲取shell執行返回的結果

2022-04-02 10:23:09 字數 776 閱讀 9188

linux下通過c執行命令的時候一半都是使用system()方法,但是該方法執行命令返回的值是-1或0,而有時候我們需要得到執行命令後的結果。可以使用管道實現

輸出到檔案流的函式是popen(),例如

file *isr;

isr = popen("ls -l","r"); ls -l命令的輸出通過管道讀取("r"引數)到isr

下面是演示例子,列出當前可用的loop裝置,(必須是root許可權才可以執行losetup -f)

#include #include 

#include

#include

#include

char* cmd_system(const

char*command);

intmain()

;char* result = cmd_system("

losetup -f");

//通過該方法可以將char*轉換為char陣列

//strcpy(str,result);

printf("

the result:%s\n

",result);

return0;

}char* cmd_system(const

char*command)

if(fpread!=null)

pclose(fpread);

return

result;

}

執行結果:

the result:/dev/loop0

linux的C獲取shell執行返回的結果

linux下通過c執行命令的時候一半都是使用system 方法,但是該方法執行命令返回的值是 1或0,而有時候我們需要得到執行命令後的結果。可以使用管道實現 輸出到檔案流的函式是popen 例如 file isr isr popen ls l r ls l命令的輸出通過管道讀取 r 引數 到isr ...

Linux運維筆記 shell基礎命令

注 實驗系統為red hat enterprise linux server release 7.1 maipo 李哥 shell是核心的 保鏢 kiosk foundation0 desktop gnome terminal 用命令列開啟乙個shell kiosk 開啟shell的使用者 分隔符 ...

2月5號 linux運維shell

一.linux裡可以用man檢視命令,裝置檔案等資訊.其中每個命令都有屬於自身的 級別 下面比較 1.使用者命令.這個就是提供給使用者的外部介面命令用來管理系統的.最常見的就是ls,cat等.2.系統呼叫.這個理解為系統提供的函式.3.常用的庫函式.4.特殊檔案.linux所有東西都要看成檔案,當然...