Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

exec 函式族實例解析

fork() 函式透過系統呼叫建立一個與原程序(父程序)幾乎完全相同的程序(子程序是父程序的副本,會取得父程序資料空間、堆、堆疊等資源的複本)。請注意,子程序持有的是這些儲存空間的「複本」,代表父子程序間並不共享這些空間;Linux 會把父程序的位址空間內容複製給子程序,因此子程序擁有了獨立的位址空間,兩者做完全相同的事。

若在 fork 後的子程序中使用 exec 函式族,就能載入並運行其他程式——也就是讓子程序替換原有程序,與父程序做不同的事。

fork 建立新程序會產生新的 PID;exec 則啟動新程式並替換原有程序,因此被 exec 執行的程序 PID 不會改變(與呼叫 exec 的程序相同)。

exec 函式族:

#include <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[]);
 int execve(const char *file, char *const argv[], char *const envp[]);

exec 函式族會載入並運行 path/file,將參數 arg0(arg1、arg2、argv[]、envp[])傳給子程式,出錯時回傳 -1。後綴 l、v、p、e 各自代表不同的操作能力:

後綴 操作能力
l 接收以逗號分隔、並以 NULL 指標結尾的參數列表
v 接收一個以 NULL 結尾的字串陣列指標
p 為以 NULL 結尾的字串陣列指標,函式可依 PATH 變數搜尋子程式檔案
e 傳遞指定的 envp,允許改變子程序的環境;無後綴 e 時,子程序沿用目前程式的環境

具體範例:

#ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
 int main(int argc, char *argv[])
 {
  char *arg[] = {"ls", "-a", NULL};
  //建立子程序並呼叫 execl(以逗號分隔、NULL 結尾)
  if( fork() == 0 )
  {
    printf( "1------------execl------------\n" );
    if( execl( "/bin/ls", "ls","-a", NULL ) == -1 ) { perror( "execl error " ); exit(1); }
  }
  //建立子程序並呼叫 execv(以 NULL 結尾的字串陣列指標)
  if( fork() == 0 )
  {
    printf("2------------execv------------\n");
    if( execv( "/bin/ls",arg) < 0) { perror("execv error "); exit(1); }
  }
  //建立子程序並呼叫 execlp(可從 PATH 搜尋)
  if( fork() == 0 )
  {
    printf("3------------execlp------------\n");
    if( execlp( "ls", "ls", "-a", NULL ) < 0 ) { perror( "execlp error " ); exit(1); }
  }
  //建立子程序並呼叫 execvp
  if( fork() == 0 )
  {
    printf("4------------execvp------------\n");
    if( execvp( "ls", arg ) < 0 ) { perror( "execvp error " ); exit( 1 ); }
  }
  //建立子程序並呼叫 execle(可改變環境)
  if( fork() == 0 )
  {
    printf("5------------execle------------\n");
    if( execle("/bin/ls", "ls", "-a", NULL, NULL) == -1 ) { perror("execle error "); exit(1); }
  }
  //建立子程序並呼叫 execve
  if( fork() == 0 )
  {
    printf("6------------execve-----------\n");
    if( execve( "/bin/ls", arg, NULL ) == 0) { perror("execve error "); exit(1); }
  }
  return EXIT_SUCCESS;
 }

Linux 下的運行結果如下,六個分支分別列出目錄內容:

------------execl------------
.  ..  .deps  exec  exec.o  .libs  Makefile
------------execv------------
.  ..  .deps  exec  exec.o  .libs  Makefile
------------execlp------------
.  ..  .deps  exec  exec.o  .libs  Makefile
------------execvp------------
.  ..  .deps  exec  exec.o  .libs  Makefile
------------execle------------
.  ..  .deps  .libs  Makefile  exec  exec.o
------------execve-----------
.  ..  .deps  .libs  Makefile  exec  exec.o
按 Enter 繼續!

Copyright © Linux教程網 All Rights Reserved