Linux程序之exec族函式

2021-10-09 18:05:45 字數 3273 閱讀 5947

fork函式建立新程序後,經常會在新程序中呼叫exec函式去執行另外乙個程式。當程序呼叫exec函式時,該程序被完全替換為新程式。因為呼叫exec函式並不建立新程序,所以前後程序的id並沒有改變。

原創鏈結

#include

#include

#include

//函式原型:int execl(const char *path, const char *arg, ...);

// 可執行檔案名字 可執行程式所帶的引數,沒有帶路徑且arg必須以null結束

//whereis指令查詢程式的絕對路徑

intmain

(void

)printf

("after execl\n");

//呼叫成功不執行下面**

return0;

}

echoarg.c

#include

intmain

(int argc,

char

*ar**)

return0;

}

execl 執行 ls -l 指令

#include

#include

#include

//函式原型:int execl(const char *path, const char *arg, ...);

intmain

(void

)printf

("after execl\n");

return0;

}

帶l的一類exac函式(l表示list),包括execl、execlp、execle,要求將新程式的每個命令列引數都說明為 乙個單獨的引數。這種參數列以空指標結尾。

#include

#include

#include

//函式原型:int execlp(const char *path, const char *arg, ...);

//上面的exaclp函式帶p,所以能通過環境變數path查詢到可執行檔案ps

//echo ¥path檢視當前環境變數。環境變數作用:系統找到這些路徑底下的可執行程式。

//配置環境變數:1.pwd:顯示當前路徑 2.export path=¥path:... (當前路徑)

intmain

(void

)printf

("after execl\n");

return0;

}

帶p的一類exac函式,包括execlp、execvp、execvpe,如果引數file中包含/,則就將其視為路徑名,否則就按 path環境變數,在它所指定的各目錄中搜尋可執行檔案。舉個例子,path=/bin:/usr/bin

#include

#include

#include

intmain

(void);

if(execv

("/bin/ps"

,ar**)==-

1)printf

("after execl\n");

return0;

}

帶v不帶l的一類exac函式,包括execv、execvp、execve,應先構造乙個指向各引數的指標陣列,然後將該陣列的位址作為這些函式的引數。

#include

#include

#include

intmain

(void);

if(execvp

("ps"

,ar**)==-

1)printf

("after execl\n");

return0;

}

實現:當父程序檢測到輸入為1的時候,建立子程序把配置檔案的字段值修改掉

config檔案

speed=

3leng=

9score=

9level=

5

changedata可執行檔案

#include

#include

#include

#include

#include

#include

#include

intmain

(int argc,

char

**ar**)

fdsrc =

open

(ar**[1]

,o_rdwr)

;int size =

lseek

(fdsrc,0,

seek_end);

lseek

(fdsrc,0,

seek_set);

readbuf =

(char*)

malloc

(sizeof

(char

)*size+8)

;int n_read =

read

(fdsrc,readbuf,size)

;// char *strstr(const char *haystack, const char *needle);

char

*p =

strstr

(readbuf,

"leng=");

if(p ==

null

) p = p +

strlen

("leng=");

*p =

'5';

lseek

(fdsrc,0,

seek_set);

int n_write = write (fdsrc,readbuf,

strlen

(readbuf));

printf

("\n");

close

(fdsrc)

;return0;

}

#include

#include

#include

#include

#include

#include

intmain()

if(pid ==0)

}else

}return0;

}

59 程序之exec族函式

fork建立子程序之後,子程序是乙個新的程式,巨集觀上是並行來處理新的任務的 可以直接在子程序的if pid 0 裡面幹想讓子程序幹的事情 直接寫到if裡面不夠靈活,因為我們只能把子程序的程式 貼上過來執行,這樣必須知道源 太長了也不好控制,比如希望子程序執行ls a,這樣是不行的,因為ls的源 沒...

Linux 程序 exec函式族

其他exec 函式 練習拓展dup2 dup to 函式 一 exec的簡介 1.fork建立程序後執行的是和父程序相同的程式 但有可能執行不同的 分支 子程序往往要呼叫一種exec函式執行另一種程式。當程序呼叫一種exec函式時,該程序的使用者空間 和資料完全被新程式替換,從新程式的啟動例程開始執...

Linux程序 exec族函式

1 為什麼要使用exec族函式 當我們fork乙個子程序就是為了執行乙個新的程式,此時可以呼叫exec族函式,執行已經編譯好的可執行程式或者linux自帶的ls cd等命令。2 exec族函式如何使用 函式原型 include extern char environ intexecl const c...