exec替換進程印象,exec替換進程

來源:互聯網
上載者:User

exec替換進程印象,exec替換進程

概述

在進程的建立上UNIX/Linux採用了一個獨特的方法,它將進程建立與載入一個新進程映象分離(system系統調用則將這兩種操作合并)。這樣的好處是有更多的餘地對兩種操作進行管理。

當我們建立了一個進程之後,通常將子進程替換成新的進程映象,這可以用exec系列的函數來進行。當然,exec系列的函數也可以將當前進程替換掉(不調用fork,直接調用exec)。

 

函數族[map page]資訊
       #include <unistd.h>       extern char **environ;       int execl(const char *path, const char *arg, ...);  //L:命令列表       int execlp(const char *file, const char *arg, ...);  //p:在當前環境變數PATH下進行       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 execvpe(const char *file, char *const argv[],                   char *const envp[]);       int execve(const char *filename, char *const argv[],                  char *const envp[]);

說明:

    execl,execlp,execle(都帶“l”)的參數個數是可變的,參數以必須一個null 指標結束。

    execv和execvp的第二個參數是一個字串數組(“v”代表“vector”,字串數組必須以NULL結尾),新程式在啟動時會把在argv數組中給定的參數傳遞到main。

    名字最後一個字母是“p”的函數會搜尋PATH環境變數去尋找新程式的可執行檔。如果可執行檔不在PATH定義的路徑上,就必須把包括子目錄在內的絕對檔案名稱做為一個參數傳遞給這些函數

 

    /*總結:l代表可變參數列表,p代表在path環境變數中搜尋file檔案。envp代表環境變數*/

 

 

樣本execlp
#include <unistd.h>#include <iostream>using namespace std;int main(){    execlp("/bin/pwd","/bin/pwd",NULL);    //execlp("ls","ls","-l",NULL);    cout << "After fork..." << endl;    return 0;}

樣本execve
int main(){    char *const args[] =    {        (char *)"/bin/date",        (char *)"+%F",        NULL    };    execve("/bin/date",args,NULL);    cout << "After fork..." << endl;    return 0;}

樣本execle
//main.cpp#include <unistd.h>#include <iostream>using namespace std;int main(){    cout << "In main, pid = " << getpid() << endl;    char *const environ[] =    {        "AA=11",        "BB=22",        "CC=33",        NULL    };    execle("./hello","./hello",NULL,environ);//當environ填為NULL時,則什麼都不傳遞    cout << "After fork..." << endl;    return 0;}//hello.cpp#include <unistd.h>#include <iostream>using namespace std;extern char **environ;int main(){    cout << "In hello, pid = " << getpid() << endl;    cout << "environ:" << endl;    for (int i = 0; environ[i] != NULL; ++i)    {        cout << "\t" << environ[i] << endl;    }}

/*In main, pid = 3572//PID保持不變In hello, pid = 3572environ:AA=11BB=22CC=33*/


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.