出力に予期しない親プロセス ID があります

出力に予期しない親プロセス ID があります

私のコードはプロセスをフォークし、各プロセスの PID と PPID を出力します。子の PPID が親の PID と同じになることを期待していましたが、そのようにはなりません。

Ubuntu 14.04を使用しています。

#include <stdio.h>
#include <sys/wait.h>

int main(){
    int pid;
    pid = fork();
    if(pid==0){
        printf("\nI am the child and my parent id is %d and my id %d\n", getppid(), getpid());
    }
    else
        printf("\nI am the parent and my pid is %d and my parent id is %d\n", getpid(), getppid());

    return 0;
}

得られた出力は次のとおりです:

I am the parent and my pid is 29229 and my parent id is 27087
I am the child and my parent id is 1135 and my id is 29230

答え1

私の推測では、親が子より先に返され、子が孤立した状態になったと考えられます。PID 1135 は、プロセスの新しい親になったユーザー init プロセスである必要があります (Ubuntu ユーザー セッションには 2 つのサブリーパーがあります)。

$ ps -ef | grep init
you    1135    ...    init --user

親が子を待つようにしたい場合は、 を使用しますwait。実際には、 がincludeすでにあります。

#include <stdio.h>
#include <sys/wait.h>

int main(){
    int pid;
    pid = fork();
    if(pid == 0)
        printf("\nI am the child and my parent id is - %d and mine id %d\n",getppid(),getpid());
    else{
       printf("\nI am the parent and my pid is %d and my parent id is %d\n",getpid(),getppid());
       wait(NULL);
    }
    return 0;
}

これにより、親が子より先に終了することがなくなりますprintf。いくつかのsleep()呼び出しをあちこちに挿入して、どのような順序で処理が行われるかを確認することで、この動作をより明確に確認できます。

サブリーパーの詳細については、こちらをご覧ください

関連情報