C++'s "system" without wait (Win32) - c++

I have got a program which checks if there's a version update on the server. Now I have to do something like
if(update_avail) {
system("updater.exe");
exit(0);
}
but without waiting for "updater.exe" to complete. Otherwise I can't replace my main program because it is running. So how to execute "updater.exe" and immediately exit? I know the *nix way with fork and so on, how to do this in Windows?

Use CreateProcess(), it runs asynchronously. Then you would only have to ensure that updater.exe can write to the original EXE, which you can do by waiting or retrying until the original process has ended. (With a grace interval of course.)

There is no fork() in Win32. The API call you are looking for is called ::CreateProcess(). This is the underlying function that system() is using. ::CreateProcess() is inherently asynchronous: unless you are specifically waiting on the returned process handle, the call is non-blocking.
There is also a higher-level function ::ShellExecute(), that you could use if you are not redirecting process standard I/O or doing the waiting on the process. This has an advantage of searching the system PATH for the executable file, as well as the ability to launch batch files and even starting a program associated with a document file.

You need a thread for that
Look here: http://msdn.microsoft.com/en-us/library/y6h8hye8(v=vs.80).aspx
You are currently writing your code in the "main thread" (which usually is also your frame code).
So if you run something that takes time to complete it will halt the execution of your main thread, if you run it in a second thread your main thread will continue.
Update:
I've missed the part that you want to exit immediately.
execl() is likely what you want.
#include <unistd.h>
int main(){
execl("C:\\path\\to\\updater.exe", (const char *) 0);
return 0;
}
The suggested CreateProcess() can be used as well but execl is conforming to POSIX and would keep your code more portable (if you care at all).
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
Update:
tested on Win-7 using gcc as compiler

Related

Run an app and forget in a portable way

I am writing a small updater utility that is being called from the main program. The main program terminates right after the call and lets the updater copy all the updated files and then it should re-launch the main program. However that last bit is starting to give me a headache.
I can run the program with std::system (I know, unsafe, but portable) just fine but then the updater just hangs there waiting for the main program to finish. I was searching for ways to make the call fire & forget and the threads seems like the best idea.
However this:
std::system("app");
hangs the updater as it waits for return from system. Whereas this:
std::thread(std::system, "app").detach();
nor variant
std::thread t(std::system, "app");
t.detach();
seem to do anything. But when I join the thread with:
std::thread t(std::system, "app");
t.join();
it does run the app but still waits for its return just like in the original code. Why can't the detached thread run the app?
Any thread, whether detached or not, will die if its process finishes(on most systems). Give some time before the updater end execution, and the thread may be able to actually make the call:
#include <chrono>
#include <cstdlib>
#include <thread>
void do_app() {
std::system("app");
}
int main() {
std::thread(do_app).detach();
std::this_thread::sleep_for(std::chrono::seconds(2));
}
I would just use ifdef blocks around the different implementations. For Windows you can use CreateProcess, linux (and probably Mac) supports POSIX popen / fork methods.
std::system does not really make your program portable, usually the syntax for invoking things on the shell differs slightly from platform to platform and you end up with platform dependent code anyways.
Here is a detailed tutorial on how to do it in Linux:
http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
And for Windows:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

Simple C++ cross-platform way to execute an external program

What is a simple, elegant, and effective cross-platform way to execute an external program in C++ and get the return code from it?
int execute(std::string const &path, std::vector<std::string> const &arguments = {})
{
//...
}
Since we're waiting for the called program to finish before continuing execution, the called program should use our program's input/output/error streams. If, for any number of reasons, path isn't executable, just throw an exception (e.g. std::invalid_argument).
Obviously, don't use system().
If it is just one single program you need to execute, spawn a worker thread and have that thread call system:
void executeProgram(std::string programName) {
system(programName.c_str());
}
void execute() {
string programName = "test.cpp";
std::thread worker (executeProgram, programName);
worker.join(); //wait for the worker to complete
}
If you need to be able to spawn many programs, a thread pool class to delegate worker threads and join them upon completion might make more sense.
At least for command-line applications, I solved this issue using popen.On windows is _popen but that is easily solved with a define

Reading or getting a command from console thread

I have a program in c++ with several threads in it. I want one of the threads to be able to read/get commands from the console while others continue running, for example: "play", "stop", "pause",...
something like:
while (1)
{
std::string str;
getline(std::cin, str);
/* do something */
}
Will it work? Any suggestions?
Thanks in advance.
Short Answer: Yes.
Long Answer: It depends of what you call 'work', there is nothing that prevent you from calling a blocking function/method from a thread while other threads are running.
However, threads share memory and resources. On an UNIX machine (and it's more or less the same on Windows), stdin and stdout are shared between threads. std::cin will manipulate stdin under the hood at some point, and you should ensure that only one thread can manipulate a given resource at a time.
You can do that by either make sure that only one thread can reach code using std::cin, or use synchronization, with a mutex/semaphore.

Can I interrupt function if it is executed for too long?

I a have third party function which I use in my program. I can't replace it; it's in a dynamic library, so I also can't edit it. The problem is that it sometimes runs for too long.
So, can I do anything to stop this function from running if it runs more than 10 seconds for example? (It's OK to close program in this scenario.)
PS. I have Linux, and this program won't have to be ported anywhere else.
What I want is something like this:
#include <stdio.h>
#include <stdlib.h>
void func1 (void) // I can not change contents of this.
{
int i; // random
while (i % 2 == 0);
}
int main ()
{
setTryTime(10000);
timeTry{
func1();
} catchTime {
puts("function executed too long, aborting..");
}
return 0;
}
Sure. And you'd do it just the way you suggested in your title: "signals".
Specifically, an "alarm" signal:
http://linux.die.net/man/2/alarm
http://beej.us/guide/bgipc/output/html/multipage/signals.html
If you really have to do this, you probably want to spawn a process that does nothing but invoke the function and return its result to the caller. If it runs too long, you can kill that process.
By putting it into its own process, you stand a decent (not great, but decent) chance of cleaning up at least most of what it was doing so when it dies unexpectedly it probably won't make a complete mess of things that will lead to later problem.
The potential problem with forcefully cancelling a running function is that it may "own" resources that it intended to return later. The kind of resources that can be problems include:
heap memory allocations (free store)
shared memory segments
threads
sockets
file handles
locks
Some of these resources are managed on a per-process basis, so letting the function run in a different process (perhaps using fork) makes it easier to kill cleanly. Other resources can outlive a process, and really must be cleaned up explicitly. Depending on your operating system, it's also possible that the function may be part-way through interacting with some hardware driver or device, and killing it unexpectedly may leave that driver or device in a bizarre state such that it won't work until after a restart.
If you happen to know that the function doesn't use any of these kind of resources, then you can kill it confidently. But, it's hard to guarantee that: in a large system with many such decisions - which the compiler can't check - evolution of code in functions like func1() is likely to introduce dependencies on such resources.
If you must do this, I'd suggest running it in a different process or thread, and using kill() for processes, pthread_kill if func1() has some support for terminating when a flag is set asynchronously, or the non-portable pthread_cancel if there's really no other choice.

Basic signal handling in C++

This is a pretty basic scenario but I'm not finding too many helpful resources. I have a C++ program running in Linux that does file processing. Reads lines, does various transformations, writes data into a database. There's certain variables (stored in the database) that affect the processing which I'm currently reading at every iteration because I want processing to be as up to date as possible, but a slight lag is OK. But those variables change pretty rarely, and the reads are expensive over time (10 million plus rows a day). I could space out the reads to every n iterations or simply restart the program when a variable changes, but those seem hackish.
What I would like to do instead is have the program trigger a reread of the variables when it receives a SIGHUP. Everything I'm reading about signal handling is talking about the C signal library which I'm not sure how to tie in to my program's classes. The Boost signal libraries seem to be more about inter-object communication rather than handling OS signals.
Can anybody help? It seems like this should be incredibly simple, but I'm pretty rusty with C++.
I would handle it just like you might handle it in C. I think it's perfectly fine to have a stand-alone signal handler function, since you'll just be posting to a semaphore or setting a variable or some such, which another thread or object can inspect to determine if it needs to re-read the settings.
#include <signal.h>
#include <stdio.h>
/* or you might use a semaphore to notify a waiting thread */
static volatile sig_atomic_t sig_caught = 0;
void handle_sighup(int signum)
{
/* in case we registered this handler for multiple signals */
if (signum == SIGHUP) {
sig_caught = 1;
}
}
int main(int argc, char* argv[])
{
/* you may also prefer sigaction() instead of signal() */
signal(SIGHUP, handle_sighup);
while(1) {
if (sig_caught) {
sig_caught = 0;
printf("caught a SIGHUP. I should re-read settings.\n");
}
}
return 0;
}
You can test sending a SIGHUP by using kill -1 `pidof yourapp`.
I'd recommend checking out this link which gives the details on registering a signal.
Unless I'm mistaken, one important thing to remember is that any function inside an object expects a referent parameter, which means non-static member functions can't be signal handlers. I believe you'll need to register it either to a static member function, or some kind of global function. From there, if you have a specific object function you want to take care of your update, you'll need a way to reference that object.
There are several possibilities; it would not necessarily be overkill to implement all of them:
Respond to a specific signal, just like C does. C++ works the same way. See the documentation for signal().
Trigger on the modification timestamp of some file changing, like the database if it is stored in a flat file.
Trigger once per hour, or once per day (whatever makes sense).
You can define a Boost signal corresponding to the OS signal and tie the Boost signal to your slot to invoke the respective handler.