开发者

Catching sys.exit

Hi to all =) I've a little curiosity If I've the following function, that close the program calling sys.exit:

void stop(int state){
    std::exit(state);
}

Now, I want to call this function, but without exit the progra开发者_高级运维m. So, I want to "catch" the std::exit command... is there a method to do it?


You can't do this, because exit is guaranteed to never return. As a result the compiler can take advantage of this and generate code that doesn't have any execution path after exit. If exit returns by some hackery, you'll get undefined-behavior. So there is no standard way for this.


Do the same as with tail recursion: Have the offending function call always be the last statement in the execution path, or not occur at all:

void stop(int state)
{
  const bool exitReally = DecideWhetherToExit();
  if (exitReally)
    std::exit(state);
}

This function will never do anything after calling std::exit, but might also not call it at all, decided after evaluating whatever you want in another function, for example.


As far as I know, you can't call exit and then further prevent the application from terminating.

Can you not just pass in another parameter to stop so that it doesn't call exit ?

E.g.

void stop(int state, bool exit)
{
    if(exit)
        std::exit(state);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜