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

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

问题描述

考虑以下代码:

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

vfork()的情况下,父进程和子进程使用的地址空间相同,所以变量pid的单个副本应该在那里.现在我无法理解这个 pid 变量如何具有 vfork() 返回的两个值,即子级为零,父级非零?

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 ?

fork() 的情况下,地址空间也会被复制,并且每个孩子和父母都有两个 pid 变量的副本,所以我可以理解在这种情况下,两个不同的副本可以有不同的值fork() 返回,但在 vfork() 的情况下无法理解 pid 如何具有 vfork() 返回的两个值?p>

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()?

推荐答案

没有2份.当您调用 vfork 时,父级冻结,而子级执行它的操作(直到它调用 _exit(2)execve(2)).所以在任何时候,只有一个 pid 变量.

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:

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

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.

作为第二个说明,vfork 已从 SUSv4 中删除 - 使用它真的没有意义.

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

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

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