Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Unix/Linux 行程詳解:fork、exec 與 wait 的實作演練

範例一:exec 家族的用法

#include <iostream>
#include <vector>
#include <cstdint>
#include <cstring>
#include <error.h>
#include <unistd.h>
using namespace std;

int main() {
  //system("ps aux &");   // 在背景執行
  char *const ps_argv[] = {"ps", "ax", 0};
  char *const ps_envp[] = {"PATH=/bin:/usr/bin", "TERM=console", 0};

  // 以下為 exec 家族的各種變形,一次只會有一種生效
  // execl("/bin/ps", "ps", "ax", 0);       // 假設 ps 在 /bin
  // execlp("ps", "ps", "ax", 0);           // 假設 /bin 在 PATH 中
  execle("/bin/ps", "ps", "ax", 0, ps_envp); // 傳入自訂環境變數
  // execv("/bin/ps", ps_argv);
  // execvp("ps", ps_argv);
  // execve("/bin/ps", ps_argv, ps_envp);

  pid_t new_pid;
  new_pid = fork();
  new_pid = getpid();
  cout << new_pid << endl;

  switch (new_pid) {
    case -1: break;
    case 0:  break;
    default: break;
  }
  cout << "errx" << endl;
  return 0;
}
Unix/Linux 行程詳解:fork、exec 與 wait 的實作演練

範例二:父子行程交錯輸出

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
using namespace std;

int main() {
  pid_t pid;
  string message;
  int n;

  pid = fork();
  switch (pid) {
    case -1:
      perror("fork failed");
      exit(1);
    case 0:
      message = "this is the child";
      n = 5;
      break;
    default:
      message = "this is the parent";
      n = 3;
      break;
  }

  for (; n > 0; n--) {
    cout << message << endl;
    sleep(1);
  }
  return 0;
}

輸出會是父子交錯的:

this is the parent
this is the child
this is the parent
this is the child
this is the parent
this is the child
$ this is the child
this is the child

這說明了 fork 之後父子行程各自獨立運行,由核心排程決定誰先跑。

範例三:用 wait 回收子行程並取得結束碼

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main() {
  pid_t pid;
  string message;
  int n;
  int exit_code;

  pid = fork();
  switch (pid) {
    case -1:
      perror("fork failed");
      exit(1);
    case 0:
      message = "this is the child";
      n = 5;
      exit_code = 37;      // 刻意給一個結束碼
      break;
    default:
      message = "this is the parent";
      exit_code = 0;
      n = 3;
      break;
  }

  for (; n > 0; n--) {
    cout << message << ", which pid:" << getpid() << endl;
    sleep(1);
  }

  if (pid != 0) {
    int stat_val;
    pid_t child_pid = wait(&stat_val);
    printf("child has finished: PID = %d\n", child_pid);
    if (WIFEXITED(stat_val))
      printf("child exited with code %d\n", WEXITSTATUS(stat_val));
    else
      printf("child terminated abnormally\n");
  }
  exit(exit_code);
}
Unix/Linux 行程詳解:fork、exec 與 wait 的實作演練

三個範例合起來正好把行程的核心觀念串起來:fork 複製出子行程,exec 系列用新程式映像取代目前的行程,wait 則讓父行程回收子行程並取得其結束狀態——少了 wait,子行程結束後就會變成僵屍。

Copyright © Linux教程網 All Rights Reserved