if(!fork) - 这是什么意思?

maz*_*zix 3 c unix fork

这是什么意思if(!fork())?我有点困惑,我不知道我什么时候在父母和孩子的过程中:

if(!fork())
{
  // is it child or parent process?
}else{
  // is it child or parent process?
}
Run Code Online (Sandbox Code Playgroud)

mrb*_*mrb 10

fork(2)联机帮助页:

回报价值

成功时,子进程的PID在父进程中返回,并在子进程中返回0.失败时,在父项中返回-1,不创建子进程,并正确设置errno.

由于fork()返回0给孩子,if子句测试它是否是孩子:

if (!fork()) // same as: if (fork() == 0)
{
  // child
}else{
  // parent
}
Run Code Online (Sandbox Code Playgroud)

  • 唯一的问题是它没有区分父母与错误. (2认同)