Linux系統編程_9_進程式控制制之exec 函數,_9exec
exec函數
當進程調用exec函數時,該進程的執行程式完全的替換為新程式。新程式從它的main函數開始執行;
使用fork函數建立一個子進程後,子進程往往會使用exec函數去執行另一個程式。
注意:調用exec函數並不會建立新進程,所以建立前後的進程ID不會改變,exec只是用一個全新的程式替換了當前正在啟動並執行程式的程式碼片段、資料區段、堆、棧。
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
int execv(const char *path, char *const argv[]);
int execle(const char *path, const char *arg, ..., char * const envp[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execlp(const char *filename, const char *arg, ...);
int execvp(const char *filename, char *const argv[]);
這麼多函數如何記憶?
帶有字母p的,代表第一個參數是filename,並根據PATH環境變數搜尋可執行檔;
帶有字母l的,代表函數取一個參數表;(與字母v互斥;希望接收以逗號分隔的參數列表,列表以NULL指標作為結束標誌)
帶有字母v的,代表函數取一個argv[]; (希望接收到一個以NULL結尾的字串數組的指標)
帶有字母e的,代表函數取一個envp[]數組;(函數傳遞指定參數envp,允許改變子進程的環境,無尾碼e時,子進程使用當前程式的環境)
下面是例子:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(){ pid_t pid; int status; char *arg[] = {"ps" "-l", NULL}; // execl pid = fork(); if(-1 == pid) { printf("Fork error!\n"); return -1; } else if(0 == pid) { if(-1 == execl("/bin/ls", "ls", "-a", NULL)) { perror("execl error!"); exit(-1); } } waitpid(pid, &status, 0); // execv if(0 == (pid=fork())) { if(-1 == execv("/bin/ps", arg)) { perror("execv error!"); exit(-1); } } waitpid(pid, &status, 0); // execle if(0 == (pid=fork())) { if(-1 == execle("/bin/ps", "ps", "-l", NULL, NULL)) { perror("execle error!"); exit(-1); } } waitpid(pid, &status, 0); // execve if(0 == (pid=fork())) { if(-1 == execve("/bin/ps", arg, NULL)) { perror("execve error!"); exit(-1); } } waitpid(pid, &status, 0); // execlp if(0 == (pid=fork())) { if(-1 == execlp("ps", "ps", "-l", NULL)) { perror("execle error!"); exit(-1); } } waitpid(pid, &status, 0); return 0;}
運行結果:
. .. echo.sh main
PID TTY TIME CMD
11120 pts/1 00:00:01 bash
20964 pts/1 00:00:00 main
20966 pts/1 00:00:00 ps
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 506 11120 11119 0 80 0 - 1745 - pts/1 00:00:01 bash
0 S 506 20964 11120 0 80 0 - 459 - pts/1 00:00:00 main
0 R 506 20967 20964 0 80 0 - 694 - pts/1 00:00:00 ps
PID TTY TIME CMD
11120 pts/1 00:00:01 bash
20964 pts/1 00:00:00 main
20968 pts/1 00:00:00 ps
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 506 11120 11119 0 80 0 - 1745 - pts/1 00:00:01 bash
0 S 506 20964 11120 0 80 0 - 459 - pts/1 00:00:00 main
0 R 506 20969 20964 3 80 0 - 1618 - pts/1 00:00:00 ps