Open1
[C言語] fork した子プロセスで exit() するか _exit() するか
個人的には _exit() を使う。
-
_exit()
- バッファを書き出さない
Open streams shall not be flushed.
https://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html -
exit()
- バッファを書き出す
The exit() function shall then flush all open streams with unwritten buffered data and close all open streams.
https://pubs.opengroup.org/onlinepubs/9699919799/functions/exit.html
_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)が表示される。