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
Related
I have the code below which I am calling it asynchronously for downloading a file, I want to terminate the thread ? How to achieive this ?
std::future<BOOL> fut = std::async(std::launch::async,&download::downloadBlob2File,&t_oftcdownload,stol(blocksize), downldUrl, token,name, path, ID);
std::chrono::hours span (2);
int t_iResult = -1;
if (fut.wait_for(span)==std::future_status::timeout)
{
t_iResult=0;
}
You can do it, but only in the sense that you can write the code yourself. You can build a mechanism to communicate to the other thread that you want it to halt, and that thread can frequently check this mechanism to see if it is being told to abort.
There is no mechanism built into async to help you do this. C++20 has the std::stop_source and std::stop_token types, which are such a communication mechanism. But you have to pass a stop_token to the asynchronous function, and it must be written to manually check this mechanism periodically to see if it should stop.
C++ has no mechanism to force a thread to stop; stopping a thread is something the target thread has to agree to do, and thus it has to be designed to do it.
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
How can I call a function in C++ after a certain period of time or at a particular time?
I searched in Google and in Stackoverflow. I only found way to do this through SIGALARM handler.
Update 1:
P.S. I use Linux.
P.P.S. I haven't got any written code, because I want to know how to do that, before writing.<
You'd probably want to do that in another throwaway thread, as waiting in the main thread would block your app. You can add the delay in that thread by using std::this_thread::sleep_for.
I.e.
using namespace std;
thread([]{this_thread::sleep_for(chrono::milliseconds(1000)); foo(); }).detach();
The POSIX way of doing it in C is through setting a signal handler with SIGALARM and having in it the function that you want to be called. In this scenario, you give to the operative system (kind of) the responsibility to call you once the time has come.
The C++11 way of doing it is through std::thread and std::chrono. A very simple, and may be not complete example:
std::chrono::milliseconds duration( 2000 );
auto deferred_task = [duration] () { std::this_thread::sleep_for(duration); call_task(); }
std::thread t(deferred_task);
In this barebone exmple your program is multithreading, and one thread is responsible to make the deferred call (in another thread). You may want to join, to catch a return value, and whatever you want, synchronously or asynchronously.
You want to have a multithread application or do you require a single-thread signal C behaviour? This is quite critical and it will be your main constraint on your code style from here.
Try the answer to this question if you have access to the Boost libraries. You can either call your function periodically or as a one-off.
Try to use timer. Or in linux use epoll. And something like waitforsingleobject in Windows.
You can actually do it in a super simple way:
void example(void (*f)()) {
struct defer {
void (*f)();
~defer() { f(); }
} _[[maybe_unused]] { f };
}
I have a program that uses boost threads. The program has start and stop functionality. When the program is started I create a boost thread that does some processing. When the program is stopped I call join on this thread and delete the thread's pointer. My program starts and stops correctly the first time; however, when I try to start my program a second time I fail an assertion inside of boost (when newing the processing thread) and the following is output on my screen
/root/src/boost.cmake/libs/thread/src/pthread/once.cpp:46: unsigned long &boost::detail::get_once_per_thread_epoch(): Assertion`!pthread_setspecific(epoch_tss_key,data)' failed.
I know that my join is working correctly because when the processing thread exits I output a message to my console. Does anyone know why this might happen?
An extra note... I have played around with my code a little bit and the methodology that I am using to clean up my boost threads appears to work in other parts of my program (for example, if I create the boost::thread in the parent class). However, it fails every time in the child class (which is an abstract class).
My start and stop methods looks like this...
void ThreadMethod()
{
while(_runningThread)
{
}
}
void Start()
{
_runningThread = true;
_thread = boost::make_shared<boost::thread>(&TestChildVirtualClass::ThreadMethod, this);
};
void Stop()
{
_runningThread = false;
_thread->join();
if( _thread )
{
_thread.reset();
}
};
However, I am having trouble recreating this issue in a test program (although it occurs every time in my actual program).
The error could be a bug on Boost.Thread as there are some holes in the call_once implementation (#5752 boost::call_once() is unreliable on some platforms - see https://svn.boost.org/trac/boost/ticket/5752). This of course depends on which platform you are running your program.
Of course I maybe wrong.
You should also protect the access to _runningThread.
I am using ZThreads to illustrate the question but my question applies to PThreads, Boost Threads and other such threading libraries in C++.
class MyClass: public Runnable
{
public:
void run()
{
while(1)
{
}
}
}
I now launch this as follows:
MyClass *myClass = new MyClass();
Thread t1(myClass);
Is it now possible to kill (violently if necessary) this thread? I can do this for sure instead of the infinite loop I had a Thread::Sleep(100000) that is, if it is blocking. But can I kill a spinning thread (doing computation). If yes, how? If not, why not?
As far as Windows goes (from MSDN):
TerminateThread is a dangerous function that should only be used in
the most extreme cases. You should call TerminateThread only if you
know exactly what the target thread is doing, and you control all of
the code that the target thread could possibly be running at the time
of the termination. For example, TerminateThread can result in the
following problems:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
Boost certainly doesn't have a thread-killing function.
A general solution to the kind of question posted can be found in Herb Sutter article:
Prefer Using Active Objects Instead of Naked Threads
This permits you to have something like this (excerpt from article):
class Active {
public:
typedef function<void()> Message;
private:
Active( const Active& ); // no copying
void operator=( const Active& ); // no copying
bool done; // le flag
message_queue<Message> mq; // le queue
unique_ptr<thread> thd; // le thread
void Run() {
while( !done ) {
Message msg = mq.receive();
msg(); // execute message
} // note: last message sets done to true
}
In the active object destructor you can have then:
~Active() {
Send( [&]{ done = true; } ); ;
thd->join();
}
This solution promotes a clean thread function exist, and avoids all other issues related to an unclean thread termination.
It is possible to terminate a thread forcefully, but the call to do it is going to be platform specific. For example, under Windows you could do it with the TerminateThread function.
Keep in mind that if you use TerminateThread, the thread will not get a chance to release any resources it is using until the program terminates.
If you need to kill a thread, consider using a process instead.
Especially if you tell us that your "thread" is a while (true) loop that may sleep for a long period of time performing operations that are necessarily blocking. To me, that indicate a process-like behavior.
Processes can be terminated in a various number of ways at almost any time and always in a clean way. They may also offer more reliability in case of a crash.
Modern operating systems offer an array of interprocess communications facilities: sockets, pipes, shared memory, memory mapped files ... They may even exchange file descriptors.
Good OSes have copy-on-write mechanism, so processes are cheap to fork.
Note that if your operations can be made in a non-blocking way, then you should use a poll-like mechanism instead. Boost::asio may help there.
You can with TerminateThread() API, but it is not recommended.
More details at:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx
As people already said, there is no portable way to kill a thread, and in some cases not possible at all. If you have control over the code (i.e. can modify it) one of the simplest ways is to have a boolean variable that the thread checks in regular intervals, and if set then terminate the thread as soon as possible.
Can't you do add something like below
do {
//stuff here
} while (!abort)
And check the flag once in a while between computations if they are small and not too long (as in the loop above) or in the middle and abort the computation if it is long?
Not sure of the other libraries but in pthread library pthread_kill function is available pthread_kill
Yes,
Define keepAlive variable as an int .
Initially set the value of keepAlive=1 .
class MyClass: public Runnable
{
public:
void run()
{
while(keepAlive)
{
}
}
}
Now, when every you want to kill thread just set the value of keepAlive=0 .
Q. How this works ?
A. Thread will be live until the execution of the function continuous . So it's pretty simple to Terminate a function . set the value of variable to 0 & it breaks which results in killing of thread . [This is the safest way I found till date] .