Is it possible to restart a program from inside a program?

C++Application Restart

C++ Problem Overview


I am developing a C++ program and it would be useful to use some function, script or something that makes the program restart. It's a big program so restarting all the variables manually will take me long time...

I do not know if there is any way to achieve this or if it is possible.

C++ Solutions


Solution 1 - C++

If you really need to restart the whole program (i.e. to "close" and "open" again), the "proper" way would be to have a separate program with the sole purpose of restarting your main one. AFAIK a lot of applications with auto-update feature work this way. So when you need to restart your main program, you simply call the "restarter" one, and exit.

Solution 2 - C++

You can use a loop in your main function:

int main()
{
	while(!i_want_to_exit_now) {
		// code
	}
}

Or, if you want to actually restart the program, run it from a harness:

program "$@"
while [ $? -e 42 ]; do
    program "$@"
done

where 42 is a return code meaning "restart, please".

Then inside the program your restart function would look like this:

void restart() {
    std::exit(42);
}

Solution 3 - C++

On Unicies, or anywhere else you have execve and it works like the man page specifies, you can just...kill me for using atoi, because it's generally awful, except for this sort of case.

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

int main (int argc, char** argv) {

  (void) argc;

  printf("arg: %s\n", argv[1]);
  int count = atoi(argv[1]);

  if ( getchar() == 'y' ) {

    ++count;

    char buf[20];
    sprintf(buf, "%d", count);

    char* newargv[3];
    newargv[0] = argv[0];
    newargv[1] = buf;
    newargv[2] = NULL;

    execve(argv[0], newargv, NULL);
  }

  return count;
}

Example:

$ ./res 1
arg: 1
y
arg: 2
y
arg: 3
y
arg: 4
y
arg: 5
y
arg: 6
y
arg: 7
n

7 | $

(7 was the return code).

It neither recurses nor explicitly loops -- instead, it just calls itself, replacing its own memory space with a new version of itself.

In this way, the stack will never overflow, though all previous variables will be redeclared, just like with any reinvocation -- the getchar call prevents 100% CPU utilisation.

In the case of a self-updating binary, since the entire binary (at least, on Unix-likes, I don't know about Windows) will be copied into memory at runtime, then if the file changes on disk before the execve(argv[0], ... call, the new binary found on disk, not the same old one, will be run instead.

As @CarstenS and @bishop point out in the comments, due to the unique way in which Unix was designed, open file descriptors are kept across fork/exec, and as a result in order to avoid leaking open file descriptors across calls to execve, you should either close them before execve or open them with e, FD_CLOEXEC / O_CLOEXEC in the first place -- more information can be found on Dan Walsh's blog.

Solution 4 - C++

This is a very OS-specific question. In Windows you can use the Application Restart API or MFC Restart Manager. In Linux you could do an exec()

However most of the time there is a better solution. You're likely better off using a loop, as suggested in other answers.

Solution 5 - C++

This sounds like the wrong approach, like all your state is global and so the only clear-cut method you have of resetting everything (other than to manually assign "default" values to each variable) is to restart the whole program.

Instead, your state should be held in objects (of class type, or whatever). You are then free to create and destroy these objects whenever you like. Each new object has a fresh state with "default" values.

Don't fight C++; use it!

Solution 6 - C++

You probably need a loop:

int main()
{
    while (true)
    {
        //.... Program....
    }
}

Every time you need to restart, call continue; within the loop, and to end your program, use break;.

Solution 7 - C++

When I develop realtime systems my approach is normally a "derived main()" where I write all code called from a real main(), something like:

The main.cpp program:

int main (int argc, char *argv[])
{
   while (true)
   {
       if (programMain(argc, argv) == 1)
           break;
   }
}

The programmain.cpp, where all code is written:

int programMain(int argc, char *argv[])
{
    // Do whatever - the main logic goes here

    // When you need to restart the program, call
    return 0;

    // When you need to exit the program, call
    return 1;
}

In that way, every time we decide to exit the program the program will be restarted.

Detail: all variables, globals and logic must be written inside programMain()- nothing inside "main()" except the restart control.

This approach works in both Linux and Windows systems.

Solution 8 - C++

It sounds to me like you're asking the wrong question because you don't know enough about coding to ask the right question.

What it sounds like you're asking for is how to write some code where, on a missed call, it loops back round to the initial state and restarts the whole call/location sequence. In which case you need to use a state machine. Look up what that is, and how to write one. This is a key software concept, and you should know it if your teachers were any good at their job.

As a side note, if your program takes 5s to initialise all your variables, it's still going to take 5s when you restart it. You can't shortcut that. So from that it should be clear that you don't actually want to kill and restart your program, because then you'll get exactly the behaviour you don't want. With a state machine you could have one initialisation state for cold startup where the system has only just been turned on, and a second initialisation state for a warm restart.

Oh, and 6 threads is not very many! :)

Solution 9 - C++

Depending on what you mean by "restarting" the program, I can see few simple solutions.

One is to embed your whole program in some "Program" class, that essentially provides some loop that has your proper program. When you need to restart the program, you call static public method "Restart" that starts the loop again.

You could also try to make system-specific call that would start your program again, and exit. As suggested in other answer, you could create a wrapper program for this sole purpose(and check return code to know whether to quit or restart).

The other simple option is to use goto. I know that people will hate me for even mentioning it, but let's face it: we want to make simple program, not use beautiful boilerplate. Goto going back guarantees destruction, so you could create a program with a label in the beginning, and some function "Restart" that just goes back to the beginning.

Whatever option you choose, document it well, so others(or you in the future) will use one WTF less.

PS. As mentioned by alain, goto will not destroy global nor static objects, same would go for enclosing class. Therefore any approach that does not include starting new program in place of the current one should either refrain from using global/static variables, or take proper actions to re-set them(although that might be tedious, as with addition of each static/global, you need to modify the restart routine).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJulen UrangaView Question on Stackoverflow
Solution 1 - C++SingerOfTheFallView Answer on Stackoverflow
Solution 2 - C++krzaqView Answer on Stackoverflow
Solution 3 - C++catView Answer on Stackoverflow
Solution 4 - C++BlueRaja - Danny PflughoeftView Answer on Stackoverflow
Solution 5 - C++Lightness Races in OrbitView Answer on Stackoverflow
Solution 6 - C++Arnav BorborahView Answer on Stackoverflow
Solution 7 - C++MendesView Answer on Stackoverflow
Solution 8 - C++GrahamView Answer on Stackoverflow
Solution 9 - C++MatthewRockView Answer on Stackoverflow