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

2021-08-09 08:24:38 字數 630 閱讀 2588

使用popen

在學習unix程式設計的過程中,發現系統還提供了乙個popen函式,可以非常簡單的處理呼叫shell,其函式原型如下:

file *popen(const char *command, const char *type);

該函式的作用是建立乙個管道,fork乙個程序,然後執行shell,而shell的輸出可以採用讀取檔案的方式獲得。採用這種方法,既避免了建立臨時檔案,又不受輸出字元數的限制,推薦使用。

popen使用fifo管道執行外部程式。

#include

file *popen(const char *command, const char *type);

int pclose(file *stream);

popen 通過type是r還是w確定command的輸入/輸出方向,r和w是相對command的管道而言的。r表示command從管道中讀入,w表示 command通過管道輸出到它的stdout,popen返回fifo管道的檔案流指標。pclose則用於使用結束後關閉這個指標。

#include

#include

#include

#include

#include

int main( void )

Linux C中呼叫shell命令

很多時候我們需要在我們所編寫的c程式當中,呼叫一行命令,在命令列執行的命令,比如ifconfig,ls,或者是其他需要的命令如mpirun machinefile host np mpi並行程式 等等,這就要求我們能夠在linux下呼叫shell命令。linux的c就為我們提供了乙個可以呼叫shel...

linux C程式呼叫外部程式的幾種方法

1 system 執行shell 命令 相關函式 fork,execve,waitpid,popen 表頭檔案 include 定義函式 int system const char string 函式說明 system 會呼叫fork 產生子程序,由子程序來呼叫 bin sh c string來執行...

Android initrc中執行shell指令碼

由於initrc中支援的命令有限 不能支援system bin下所有命令 而且不適合寫比較複雜的邏輯 如傳參 函式塊 通常把這些功能放在shell指令碼裡來執行,但是shell指令碼又需要放在initrc中來呼叫執行。因為隨著android版本更新,selinux的限制越來越多,在initrc中執行...