linux系統編程之進程(五):exec系列函數(execl,execlp,execle,execv,execvp)使用

來源:互聯網
上載者:User

本節目標:

  • exec替換進程映像
  • exec關聯函數組(execl、execlp、execle、execv、execvp)
一,exec替換進程映像

在進程的建立上Unix採用了一個獨特的方法,它將進程建立與載入一個新進程映象分離。這樣的好處是有更多的餘地對兩種操作進行管理。

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

例如:在shell命令列執行ps命令,實際上是shell進程調用fork複製一個新的子進程,在利用exec系統調用將新產生的子進程完全替換成ps進程。

二,exec系列函數(execl、execlp、execle、execv、execvp)

包含標頭檔<unistd.h>

功能:

    用exec函數可以把當前進程替換為一個新進程,且新進程與原進程有相同的PID。exec名下是由多個關聯函數組成的一個完整系列,

標頭檔<unistd.h>

extern char **environ;

原型:

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[]);

參數:

path參數表示你要啟動程式的名稱包括路徑名

arg參數表示啟動程式所帶的參數,一般第一個參數為要執行命令名,不是帶路徑且arg必須以NULL結束

傳回值:成功返回0,失敗返回-1

註:上述exec系列函數底層都是通過execve系統調用實現:

       #include <unistd.h>

       int execve(const char *filename, char *const argv[],char *const envp[]);

DESCRIPTION:
       execve() executes the program pointed to by filename.  filename must be
       either a binary executable, or a script starting with  a  line  of  the form

以上exec系列函數區別:

1,帶l 的exec函數:execl,execlp,execle,表示後邊的參數以可變參數的形式給出且都以一個null 指標結束。

樣本:

#include <stdio.h><stdlib.h><unistd.h> main(,, 

<stdlib.h><unistd.h> main(,,

結果:

<stdlib.h><unistd.h> main( *argv[] = {,= execvp((ret == -

結果:

<stdlib.h><unistd.h> main( argc, * printf(=execl(, (ret == -

hello.c

#include <unistd.h><stdio.h> ** main( (i=; environ[i]!=NULL; ++ 

結果:

<stdlib.h><unistd.h> main( argc, * * envp[] = {, ret =execle(, (ret == -

hello.c

#include <unistd.h><stdio.h> ** main( (i=; environ[i]!=NULL; ++ 

結果:

<stdlib.h><unistd.h><fcntl.h> main( argc, * ret = fcntl( (ret == -=execlp(, ,(val == -

結果:

1關閉(標準輸出關閉)ls -l無法將結果顯示在標準輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.