程序文件存儲(chǔ)在磁盤上,當(dāng)系統(tǒng)需要執(zhí)行程序時(shí)將其加載至內(nèi)存中形成進(jìn)程。我們程序員可以通過一些調(diào)用,使進(jìn)程能以全新的程序來替換當(dāng)前運(yùn)行的程序。
exec()函數(shù)族
Linux環(huán)境下使用exec()函數(shù)執(zhí)行一個(gè)新的程序,該函數(shù)在文件系統(tǒng)中搜索指定路徑的文件,并將該文件內(nèi)容復(fù)制到調(diào)用exec()函數(shù)的地址空間,取代原進(jìn)程的內(nèi)容。
exec()函數(shù)原型,如下(其實(shí)有很多,其實(shí)大部分使用方式都是大同小異的...)
#include <unistd.h>
int execl(const char *pathname,const char *arg0,···);
int execlp(const char *filename,const char * arg0, ···);
參數(shù)其實(shí)很簡(jiǎn)單,一個(gè)要pathname也就是要執(zhí)行的程序的環(huán)境變量后面是這個(gè)程序的參數(shù)(系統(tǒng)自帶的可執(zhí)行程序如,ls,cp,cat 等),另一個(gè)是要filename也就是要執(zhí)行的程序的文件名后面是這個(gè)程序的參數(shù)。
測(cè)試代碼
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;
}