Open1

[C言語] fork した子プロセスで exit() するか _exit() するか

junkawajunkawa

https://www.jpcert.or.jp/sc-rules/c-err04-c.html

個人的には _exit() を使う。

_exit の場合

_exit() の場合
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  printf("Hello\nWorld");

  pid_t pid;
  pid = fork();
  if (pid < 0) {
    perror("fork");
    exit(EXIT_FAILURE);
  }
  if (pid == 0) {
    /* child */
    _exit(EXIT_SUCCESS);
  } else {
    /* parent */
    int ret;
    ret = wait(NULL);
    if (ret < 0) {
      perror("wait");
      exit(EXIT_FAILURE);
    }
  }

  return EXIT_SUCCESS;
}
実行結果
Hello
World

親プロセスの出力だけ表示される。
子プロセスはバッファを書き出さない。

exit の場合

exit() の場合
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  printf("Hello\nWorld");

  pid_t pid;
  pid = fork();
  if (pid < 0) {
    perror("fork");
    exit(EXIT_FAILURE);
  }
  if (pid == 0) {
    /* child */
    exit(EXIT_SUCCESS);
  } else {
    /* parent */
    int ret;
    ret = wait(NULL);
    if (ret < 0) {
      perror("wait");
      exit(EXIT_FAILURE);
    }
  }

  return EXIT_SUCCESS;
}
実行結果
Hello
WorldWorld

親プロセスの出力に加え、子プロセスのバッファ(World)が表示される。