在的vfork()系统调用的返回值 [英] return value in vfork() system call

查看:268
本文介绍了在的vfork()系统调用的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的code:

  INT的main()
{
  INT PID;
  PID =的vfork();
  如果(PID == 0)
     的printf(子\\ n);
  其他
     的printf(父\\ n);
  返回0;
  }

在的情况下,的vfork()按父进程和子进程使用的ADRESS空间是一样的,可变的pid这样单拷贝应该在那里。现在我无法理解该PID变量如何通过有返回两个值的的vfork()即零的儿童及非零父?

在的情况下的叉()的ADRESS空间也将被复制,并有在每个孩子和家长的PID可变两个副本,所以我可以理解在这种情况下,两个不同的副本可以有不同的值通过返回的叉()但在的vfork()如何PID必须通过返回两个值的的vfork()

解决方案

有没有2份。当你CAL 的vfork 父冻结,而孩子做它的事(直到它调用 _exit(2)的execve(2))。因此,在任何一个时刻,只能有一个单一的 PID 变量。

作为一个方面说明,你在做什么是不安全的。 明确阐述它的标准是:


  

在了vfork()函数应等同于fork()的,除了
  行为是未定义
如果vfork的创建过程中()或者
  修改比类型的变量之外的任何数据将为pid_t用于存储
  从了vfork(),或返回从函数的返回值,在其
  了vfork()被调用,或之前成功调用任何其他函数
  调用_exit()或函数的exec系列之一。


作为第二个方面说明,的vfork 已经从 SUSv4 删除 - 有真正使用它是没有意义的。

Considering the below code :

int main()
{
  int pid;
  pid=vfork();
  if(pid==0)
     printf("child\n");
  else
     printf("parent\n");
  return 0;
  }

In case of vfork() the adress space used by parent process and child process is same, so single copy of variable pid should be there. Now i cant understand how this pid variable can have two values returned by vfork() i.e. zero for child and non zero for parent ?

In case of fork() the adress space also gets copied and there are two copy of pid variable in each child and parent, so I can understand in this case two different copies can have different values returned by fork() but can't understand in case of vfork() how pid have two values returned by vfork()?

解决方案

There aren't 2 copies. When you cal vfork the parent freezes while the child does its thing (until it calls _exit(2) or execve(2)). So at any single moment, there's only a single pid variable.

As a side note, what you are doing is unsafe. The standard spells it clearly:

The vfork() function shall be equivalent to fork(), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.

As a second side note, vfork has been removed from SUSv4 - there's really no point in using it.

这篇关于在的vfork()系统调用的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆