私はフォーク5回呼び出していますので、私は合計5子プロセスと1つの親プロセスを期待して、このCコードこのCプログラムのフォーク出力が不正ですか?
/* SIGCHLD handler. */
static void sigchld_hdl (int sig)
{
/* Wait for all dead processes.
* We use a non-blocking call to be sure this signal handler will not
* block if a child was cleaned up in another part of the program. */
//printf("Inside handler: \n");
while (waitpid(-1, NULL, WNOHANG) > 0) {
printf("reaped\n");
}
//printf("Outside handler: \n");
}
int main (int argc, char *argv[])
{
struct sigaction act;
int i;
memset (&act, 0, sizeof(act));
act.sa_handler = sigchld_hdl;
if (sigaction(SIGCHLD, &act, 0)) {
perror ("sigaction");
return 1;
}
/* Make some children. */
for (i = 0; i < 5; i++) {
switch (fork()) {
case -1:
perror ("fork");
return 1;
case 0:
exit(0);
return 0;
default:
//printf("inside parent\n");
printf("Created child %d\n", i);
}
}
/* Wait until we get a sleep() call that is not interrupted by a signal. */
while (sleep(1)) {
printf("inside parent while loop\n");
}
return 0;
}
を持っています。このコードを実行すると、この出力が得られます
Created child 0
Created child 1
reaped
reaped
Created child 2
Created child 3
Created child 3
reaped
reaped
Created child 4
reaped
inside parent while loop
なぜ私はchild3を2回見ているのか分かりません。すべての反復で増分しているので、私は重複があってはいけません。
なぜ私はchild3を2回見ているのですか?
私はそれを再現できません。シグナルハンドラで 'printf()'を呼び出すべきではありません。多分それが問題です。 – Barmar
@Barmarハンドラでprintfを呼び出すべきではありません。あなたはそれを再生するには数時間それを実行する必要があります。 – Dude
これは非同期セーフではありません。 http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler – Barmar