为什么fork()返回errno = 22

时间:2016-07-19 22:08:11

标签: c linux process fork

我有一个简单的程序,如下所示: -

int main(int argc, const char * argv[]) 
{
  printf ("Before Fork [%d][%d:%s]\n",getpid(),errno,strerror(errno));
  pid_t pid = fork();

  if (!pid) //CHILD PROCESS
  {
    printf ("In Child Process [%d  [%d:%s]\n",getpid(),errno,strerror(errno));
  }
  else 
  {
   while(1);
  }
}

这会产生输出: -

Before Fork [50083][0:Undefined error: 0]
In Child Process [50084][22:Invalid argument]

有没有人知道为什么操作系统在FORK之后立即抛出INVALID ARGUMENT错误?

1 个答案:

答案 0 :(得分:-1)

这只是猜测,但可能是因为fork成为系统调用clone()(看一个strace):

6952  write(1, "Before Fork [6952][0:Success]\n", 30) = 30
6952  clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f55f10e19d0) = 6953
6953  write(1, "In Child Process [6953  [0:Succe"..., 36) = 36

并且clone(2)manpage说:

  

EINVAL指定零值时由clone()返回   for child_stack。

我没有浏览内核代码,但也许是因为child_stack=0而设置了errno,但是因为标志而完成了子代的创建而没有错误。

然后......由于SIGCHLD无法作为克隆标志,因此可以搞砸了。

相关问题