子進程往往要調用一種exec函數以執行另一個程序。當進程調用一種exec函數時,該進程的
用戶空間代碼和數據完全被新程序替換,從新程序的啓動例程開始執行。調用exec並不創建
新進程,所以調用exec前後該進程的id並未改變。
其實有六種以exec開頭的函數,統稱exec函數:
#include <unistd.h>
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ..., char *const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
這些函數原型看起來很容易混,但只要掌握了規律就很好記。
1.不帶字母p(表示path)的exec函數第一個參數必須是程序的相對路徑或絕對路徑,例如“/bin/ls”或“./
a.out”,而不能是“ls”或“a.out”。對於帶字母p的函數:
2.如果參數中包含/,則將其視爲路徑名。否則視爲不帶路徑的程序名,在PATH環境變量的目錄列表中搜索這個程序。
以execlp、execvp、和execle講解
path參數表示你要啓動程序的名稱包括路徑名
arg參數表示啓動程序所帶的參數
返回值:成功返回0,失敗返回-1
execl,execlp,execle(都帶“l”)的參數個數是可變的,參數以一個空指針結束。
execv和execvp
第二個參數是一個字符串數組,新程序在啓動時會把在argv數組中給定的參數傳遞到main
這些函數通常都是用execve實現的,這是一種約定俗成的做法,並不是非這樣不可。
這些函數當中名字最後一個字母是“p”的函數會搜索PATH環境變量去查找新程序的可執行文件。如果可執行文件不在PATH定義的路徑上,就必須把包括子目錄在內的絕對文件名做爲一個參數傳遞給這些函數
總結:l代表可變參數列表,p代表在path環境變量中搜索file文件。envp代表環境變量。
案例:
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
if ((pid = fork()) == 0)
{
char *s[]={"echo", "Hello World\n", NULL};
execv("/bin/echo", s);
}
if ((pid = fork()) == 0)
{
execl("/bin/ls", "ls", "-l", NULL);
}
if ((pid = fork()) == 0)
{
execlp("ps", "ps", "-a", NULL);
}
if ((pid = fork()) == 0)
{
char *s[] = {"PATH=/bin:/usr/bin", "Hello Silence\n", NULL};
execvp("echo", s);
}
if( fork() == 0 )
{
execle("/bin/ls", "ls", "-a", NULL, NULL);
}
return EXIT_SUCCESS;
}
Hello World ----execv函數輸出結果
Hello Silence ----execvp函數輸出結果
-------execle函數輸出結果
. .. a a.c a.o b.c c c.c command file
makefile silence.h sort.c
-------execl函數輸出結果
total 72
-rwxrwxr-x 1 17848 12月 5 15:41 a
-rw-rw-r-- 1 569 12月 5 15:41 a.c
-rw-rw-r-- 1 4816 12月 5 15:41 a.o
-rw-rw-r-- 1 604 12月 4 10:17 b.c
-rwxrwxr-x 1 8808 12月 4 10:54 c
-rw-rw-r-- 1 269 12月 4 10:54 c.c
drwxrwxr-x 2 4096 12月 5 15:41 command
drwxrwxr-x 2 4096 12月 1 14:36 file
-rw------- 1 232 12月 5 14:50 makefile
-rw-rw-r-- 1 131 12月 1 14:14 silence.h
-rw-rw-r-- 1 537 11月 30 13:43 sort.c
--------execlp函數輸出結果
PID TTY TIME CMD
4073 pts/4 00:00:00 ps