Completely restart program.

Hello,

I am new to this forum and still quite a beginner in C.

My Problem:
I am working on a console program in C.
OS: Windows XP SP3, with Dev-C++ and MinGW.
At a specific point it is necessary to restart the program.

What I have already tried:
1
2
3
4
[...]
system("Program.exe");
exit(0);
[...]


But this method relies on the fact, that the programs name is the one specified in the source code.
So if someone wants to rename it afterwards, it wouldn't work anymore.

Also, have I searched the web. But everything I get is that one should use a while or do...while loop.
I don't want to solve this Problem with loops, I want a full restart of the program.

Thanks in advance for your replies.

Greez,
Last edited on
You should listen to the internet and use a loop.

But, if you really want to have problems, argv[0] is what you're looking for:

1
2
3
4
5
6
7
8
#include <iostream>

int main( int argc, char* argv[] )
{
  std::cout << "Hello from " << argv[0] << '\n';
  system( argv[0] );
  return 0;
}


When I ran this, the program crashed after 234 iterations.
Last edited on
Protip: The program's name is available to your program at runtime, even if you change the name of the file after you compile it! Try this out:

1
2
3
4
5
#include <iostream>
int main(int argc, char* argv[])
{
  std::cout << argv[0];
}


Also note that instead of using system calls, you could create processes via windows commands. This is the preferred method as there are security risks associated with system() commands as discussed here:
http://www.cplusplus.com/forum/beginner/1988/
I don know if you did that on purpose or not, but because of the content of this thread you repeating yourself was pretty funny. Usually the first character array passed to main from the console is the fully qualified path to the binary so just putting: system(Argv[0]); would be good enough. However in an effort to discourage the use of the system function, although I don't see how anyone could say that this would be an invalid use, I would suggest using GetStartupInfo() from the WinAPI.
Thanks to all of you for the replies.

I have understood the problem Lowest0ne mentioned.
If I don't terminate the old program, the process tree would grow each time I tried to restart.

I think I have to find something like exec() for Windows...

Greez,
MacC
@ OP: That would be "CreateProcess()" from the WinAPI: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

The documentation on this one is useful, if you have time give it a read instead of just copy+pasting the example given.
Thanks a lot.

I carefully read through the MSDN-Documentation and CreateProcess() does just what I wanted.
As expected a new process with a new PID is being started, so the Process tree doesn't grow.
Topic archived. No new replies allowed.