vfork() 系统调用的返回值

发布于 2025-01-06 14:39:17 字数 509 浏览 4 评论 0原文

考虑下面的代码:

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木森分化 2025-01-13 14:39:17

没有2本。当您调用 vfork 时,父级会冻结,而子级则执行其操作(直到它调用 _exit(2)execve(2))。因此,在任何时刻,都只有一个 pid 变量。

顺便说一句,你所做的事情是不安全的。 标准清楚地说明了这一点:

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


作为第二个旁注,vfork 已从 SUSv4 中删除 - 使用它确实没有意义。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文