Linux系統(tǒng)編程之程序的執(zhí)行(exec函數(shù)族)

程序文件存儲(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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容