程序文件存儲在磁盤上,當系統(tǒng)需要執(zhí)行程序時將其加載至內(nèi)存中形成進程。我們程序員可以通過一些調(diào)用,使進程能以全新的程序來替換當前運行的程序。
exec()函數(shù)族
Linux環(huán)境下使用exec()函數(shù)執(zhí)行一個新的程序,該函數(shù)在文件系統(tǒng)中搜索指定路徑的文件,并將該文件內(nèi)容復制到調(diào)用exec()函數(shù)的地址空間,取代原進程的內(nèi)容。
exec()函數(shù)原型,如下(其實有很多,其實大部分使用方式都是大同小異的...)
#include <unistd.h>
int execl(const char *pathname,const char *arg0,···);
int execlp(const char *filename,const char * arg0, ···);
參數(shù)其實很簡單,一個要pathname也就是要執(zhí)行的程序的環(huán)境變量后面是這個程序的參數(shù)(系統(tǒng)自帶的可執(zhí)行程序如,ls,cp,cat 等),另一個是要filename也就是要執(zhí)行的程序的文件名后面是這個程序的參數(shù)。
測試代碼
execlp():
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
pid_t pid = fork();
if(pid == -1){
perror("fork error");
exit(1);
}else if(pid == 0){
execlp("ls","ls","-l","-h",NULL);
perror("execlp is error");
exit(1);
}else if(pid > 0){
sleep(1);
printf("i am the parent my id is %d \n",getpid());
}
return 0;
}
execl()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t pid = fork();
if(pid < 0){
perror("fork fail");
exit(1);
}else if(pid == 0){
execl("./a.out","./a.out",NULL);
perror("execl fail");
exit(1);
}else if(pid > 0){
sleep(1);
printf("i am the parent my id is %d \n",getpid());
}
return 0;
}