vfork() 调用后退出和返回的区别 [英] difference between exit and return after vfork() call

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

问题描述

我有一个行为未定义的程序(vfork() 使用不当):

I have a program with undefined behavior ( vfork() is used inappropriately ):

#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main ( int argc, char *argv[] )
{
    pid_t pid;
    printf("___________befor fork______________.
");
    if((pid=vfork()) < 0)
        perror("fork");
    else if(pid > 0)
        printf("parent
");
    else
        printf("child
");

    printf("pid: %d, ppid: %d
", getpid(), getppid());

    //exit(0);
    return 0;
}

如果我使用 exit(0) 函数而不是返回 - 输出是:

If I use exit(0) function instead return - output is:

___________befor fork______________.
child
pid: 4370, ppid: 4369
parent
pid: 4369, ppid: 2924

如果我使用 return 0 - 我会得到这样的无限输出:

If I use return 0 - I get infinite output like this:

___________befor fork______________.
child
pid: 4455, ppid: 4454
parent
pid: 4454, ppid: 2924
___________befor fork______________.
child
pid: 4456, ppid: 4454
parent
pid: 4454, ppid: 2924
___________befor fork______________.
child
pid: 4457, ppid: 4454
parent
pid: 4454, ppid: 2924
    and so on ...

我知道您不能在 vfork() 函数之后在子级中使用 return.但是我不明白为什么 return 调用后父级没有结束?

I know that you can not use return in the child after the vfork() function. But I don't understand why the parent does not end after return call?

谢谢.

推荐答案

在子函数中返回无效,因为 vfork() 父子共享同一个堆栈并返回子级将弄乱父级的堆栈框架.通常对 main() 的调用(在 start 函数中)之后是对 exit() 或类似的调用,因此对 exit()<的调用子进程中的/code> 将覆盖调用 main() 正在使用的相同堆栈空间(并且仍在父进程中使用).因此,当子进程退出时,父进程将从 vfork() 返回,但堆栈上的返回地址可能会被破坏,因此它可以返回任何地址或执行任何操作.

It is not valid to return from the function in the child, because with vfork() both the parent and child share the same stack and returning in the child will mess up the stack frame for the parent. Usually the call to main() (in the start function) is followed by a call to exit() or similar, so that call to exit() in the child will overwrite the same stack space that the call to main() was using (and is still using in the parent). So when the child does exit, the parent will return from vfork() but the return address on the stack will likely be clobbered so it could return to any address or do anything at all.

另外,在子进程中,如果你不执行,你应该调用 _exit() 而不是 exit().exit() 将刷新 stdio 输出缓冲区,但这些缓冲区由父级管理,而 _exit() 将结束进程.

Also, in the child, if you do not exec you should call _exit() rather than exit(). exit() will flush the stdio output buffers but those same buffers are being managed by the parent, whereas _exit() will just end the process.

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

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