C 中 fork() 和 exec() 的區別


這裡我們來看看在 C 中 fork() 和 exec() 系統呼叫的效果。fork 用於透過複製呼叫程序來建立新程序。新程序為子程序。參見以下屬性。

  • 子程序擁有自己唯一的程序 ID。
  • 子程序的父程序 ID 與呼叫程序的程序 ID 相同。
  • 子程序不會繼承父程序的記憶體鎖和訊號量。

fork() 返回子程序的 PID。如果值為非零,則該值為父程序的 ID,如果為 0,則為子程序的 ID。

exec() 系統呼叫用於用新程序映像替換當前程序映像。它將程式載入到當前空間,並從入口點執行程式。

因此,fork() 和 exec() 之間的主要區別在於 fork 開始的新程序是主程序的副本。exec() 用新的程序映像替換當前程序映像,父程序和子程序同時執行。

示例

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main() {
   pid_t process_id;
   int return_val = 1;
   int state;
   process_id = fork();
   if (process_id == -1) { //when process id is negative, there is an error, unable to fork
      printf("can't fork, error occured
");          exit(EXIT_FAILURE);    } else if (process_id == 0) { //the child process is created       printf("The child process is (%u)
",getpid());          char * argv_list[] = {"ls","-lart","/home",NULL};       execv("ls",argv_list); // the execv() only return if error occured.       exit(0);    } else { //for the parent process       printf("The parent process is (%u)
",getppid());       if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state          if (WIFEXITED(state) && !WEXITSTATUS(state))             printf("program is executed successfully
");          else if (WIFEXITED(state) && WEXITSTATUS(state)) {             if (WEXITSTATUS(state) == 127) {                printf("Execution failed
");             } else                printf("program terminated with non-zero status
");          } else             printf("program didn't terminate normally
");       }       else {          printf("waitpid() function failed
");       }       exit(0);    }    return 0; }

輸出

The parent process is (8627)
The child process is (8756)
program is executed successfully

更新日期: 2019 年 7 月 30 日

3K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得證書

開始學習
廣告
© . All rights reserved.