Run an app and forget in a portable way - c++

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

Related

C++ - Play multiple Beeps simultaneously via multi-threading?

Is it possible to play 2 or more beeps (from windows.h) simultaneously? I am very inexperienced when it comes to multi-threading but shouldn't the following do the job?
#include <thread>
#include <windows.h>
#include <iostream>
using namespace std;
void operation1();
void operation2();
int main()
{
thread task1 = thread(operation1);
thread task2 = thread(operation2);
task2.join();
task1.join();
return 0;
}
void operation1()
{
Beep(523, 1000);
}
void operation2()
{
Beep(262, 1000);
}
When I compile and run this the program only plays a beep with a frequency of 262 Hz. Does that mean, that only operation 2 is called or are the two sounds somehow still blocking each other?
The Beep method is actually came from dinosaur era, when PCs had internal speakers.
Guess what? The internal speaker could play only one sound of one frequency at a time.
Nowadays, Windows just simulate that behavior, so that nothing in the system can make Windows play 2 or more BEEPS at a time.
Your code exposes a problem I see very often (usually better hidden, though), which produces unexpected results and leaves the developers hairless. Namely, you fail to take into account lifetime of your threads.
When you start a new thread (no matter how, say, using C++11 std::thread) the starter thread continues executing (in your case, main()). Unless you ask for it, starter thread does not wait for anything to happen to the thread it just started. It just moves on, and than main() returns, and by definition, it means your program stops executing. Nobody gurantees you that the threads you've started had any chance to perform any operation at all!
You need to make a habit of waiting for threads to finish before returning from main - for example, by using thread::join. Actually, c++11 thread class will abort the program in it's destructor unless the thread was either joined, or detached - but I consider detached threads to be a of a bad design choice.

How to stop a running parallel thread with C++ on Mac?

I’ve been looking for an answer, and indeed found some possible ways to stop a running parallel thread with C++, but the solutions would usually apply only on Windows (for instance, the TerminateThread() function ). Is there a way to stop a running parallel thread on Mac (I’m using CodeBlocks) ?
A typical clean/safe setup might be....
std::atomic<bool> exit{false};
std::thread thread([&]{
while (!exit) { /* do stuff */ }
});
// later, when you want to exit:
exit = true;
// `join` before the `thread` object goes out of scope
thread.join();
From this you can probably see there are endless ways to tell your thread to stop running and end cleanly. Just make sure whatever you way you use is thread safe (either atomic or protected by a mutex) and make sure you call thread.join() before the thread object goes out of scope, or any time you wish to block waiting for the thread to finish.

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

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.

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

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