このプログラムでは、子プロセスの印刷が間違っているのはなぜですか?子プロセスが間違ったppid()を印刷します
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void childprocess()
{
printf("Child: Hi I am the child process\n");
printf("Child: My process id is %d\n", getpid());
printf("Child: My parent is %d\n", getppid());
printf("Child: I am exiting\n");
}
void parentprocess()
{
printf("Parent: Hi I am the parent process\n");
printf("Parent: My process id is %d\n", getpid());
printf("Parent: My parent is %d\n", getppid());
printf("Parent: I am exiting\n");
}
int main()
{
pid_t n = fork();
if(n<0)
{
perror("fork failed:");
exit(EXIT_FAILURE);
}
else if(n==0)
childprocess();
else
parentprocess();
}
出力:
Parent: Hi I am the parent process
Parent: My process id is 21550
Parent: My parent is 7452
Parent: I am exiting
Child: Hi I am the child process
Child: My process id is 21551
Child: My parent is 1810
Child: I am exiting
私は場合は再実行してください。時々出力は私が期待しているものであり、時には予期せぬものです。
some sleep();を追加しようとしています。親プロセスでは、あなたはあなたが期待しているものを得るだろうと思います。問題は次のようなものです。https://en.wikipedia.org/wiki/Orphan_process –