Linux C中呼叫shell命令

2021-06-18 10:00:40 字數 529 閱讀 7561

很多時候我們需要在我們所編寫的c程式當中,呼叫一行命令,在命令列執行的命令,比如ifconfig,ls,或者是其他需要的命令如mpirun -machinefile host -np * ./*(mpi並行程式)等等,這就要求我們能夠在linux下呼叫shell命令。

linux的c就為我們提供了乙個可以呼叫shell命令的函式,它就是system()。

system函式呼叫/bin/sh,執行特定的shell命令,阻塞當前的程序直到shell命令執行完畢,才重新回到當前程序。呼叫它的格式為:

#include

int system(const char *command);//command就是我們要執行的各種命令,例如「mpirun -np 2 ./cpi」

執行system實際上是呼叫了fork函式(產生新程序)、exec函式(在新程序中執行新任務)、waitpid函式(等待新程序結束)。

我們給出乙個簡單的system函式舉例:

#include

int main(int argc,char **argv)

linux C程式中呼叫shell終端的命令

使用popen 在學習unix程式設計的過程中,發現系統還提供了乙個popen函式,可以非常簡單的處理呼叫shell,其函式原型如下 file popen const char command,const char type 該函式的作用是建立乙個管道,fork乙個程序,然後執行shell,而she...

Python基礎 呼叫shell和cmd命令

啟動 catcmd adb s tvip 5555 logcat v time logpath printcatcmd self lcprocess subprocess.popen catcmd stdout subprocess.pipe stderr subprocess.pipe shell...

linux C程式中獲取shell指令碼輸出

本文使用docbook書寫,您可以在這裡獲得xml 檔案 abstract 本文描述了從linux程式中執行 shell 程式 指令碼 並獲得輸出結果的方法。table of contents 1.前言 2.使用臨時檔案 3.使用匿名管道 4.使用popen 5.小結 unix界有一句名言 一行sh...