How to make tcl interpreter not to continue after exit command? - c++

static int
MyReplacementExit(ClientData unused, Tcl_Interp *interp, int argc, const char *argv[])
{
// Tcl_DeleteInterp(interp);
// Tcl_Finalize();
return TCL_OK;
}
int main() {
Tcl_Interp *interp = Tcl_CreateInterp();
Tcl_CreateCommand(interp, "exit", MyReplacementExit, NULL, NULL);
Tcl_Eval(interp, "exit ; puts 11111111");
std::cout << "22222222222" << std::endl;
return 0;
}
I need to handle exit command evaluation of tcl interpreter. By default it tries to delete itself and also calls std::exit which closes whole program.It is not what I want so I am trying to replace it by custom proc. I dont need to delete interpreter in exit handler proc(I can do it later), only need it to not continue evaluating commands after exit command.
In this code I need to change MyReplacementExit proc somehow, so 11111111 doesn't be printed but
22222222222 does printed.
It can be achieved by returning TCL_ERROR from MyReplacementExit proc, but then I can't distinguish other error situations from this.

Make your replacement for exit delete the interpreter (which stops further commands from being executed, but doesn't actually immediately delete the data structure as it is still in use) and, important, wrap the call to Tcl_Eval with calls to Tcl_Preserve and Tcl_Release. Don't call Tcl_Finalize if you can possibly avoid it; that is for when you're about to unload the Tcl library from memory and can be quite tricky (it's easier to just quit the process, frankly).
Here's how to do it with your code (adapted):
static int
MyReplacementExit(ClientData unused, Tcl_Interp *interp, int argc, const char *argv[])
{
Tcl_DeleteInterp(interp); // <------------------
return TCL_OK;
}
int main() {
Tcl_Interp *interp = Tcl_CreateInterp();
Tcl_CreateCommand(interp, "exit", MyReplacementExit, NULL, NULL);
Tcl_Preserve(interp); // <------------------
Tcl_Eval(interp, "exit ; puts 11111111");
Tcl_Release(interp); // <------------------
std::cout << "22222222222" << std::endl;
return 0;
}
Be aware that you should not access the interpreter at all after the Tcl_Release as it might've been destroyed (as in, the memory released and scribbled over with random junk) at that point. If you need to retrieve results and use them (e.g., printing them out) do so beforehand.
Note that in this specific case, you don't need the preserve/release pair; your code isn't actually touching the interpreter after the Tcl_Eval (which does its own preserve/release internally).
If you don't want the interpreter to terminate, that's much trickier. The cleanest way in 8.4 is probably to throw a custom exception code (i.e., anything greater than TCL_CONTINUE) but there's no guarantee that it will work for arbitrary code as Tcl's catch command can still trap it. If you're really in that situation, it's actually easier to create an interpreter, run the arbitrary code in the sub-interp, and tear it down at the end of the script; you can then drop that interpreter without losing much context. Indeed, you could do:
Tcl_Preserve(interp);
if (Tcl_Eval(interp, theScriptToEval) != TCL_OK)
// Handle unexpected errors here
if (!Tcl_InterpDeleted(interp))
Tcl_DeleteInterp(interp);
Tcl_Release(interp);
Yes, this will mean you want to keep the amount of work you do to set up the interpreter fairly small; you probably won't want to try to call this every millisecond on an interrupt…

Related

Thread is not getting Destroyed

I am working on a Multithreaded system here's my code
class demo is defined in .h file
when the loop from the main function is executed second time the COMMENT1 below takes the previous value
doesn't closing handle closes the thread?
int threadentry(void* data)
{
demo* inst=(demo*) data;
cout << "Value of inst "<<hex << &inst<< endl;
string request;
cin>>request;
if(request==play)
{
inst->play;
cout << "Value of inst "<<hex << &inst<< endl;
// COMMENT1 here when the thread is executed second time from the main it is taking previous value
}
}
int main()
{
while(1)
{
demo* inst=new demo();
cout << "Value of inst "<<hex << &inst<< endl; //value is coming different from above
HANDLE threads;
DWORD threadId1;
if ((threads = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadentry,
(void *)inst, 0, &threadId1)) == NULL)
return -1;
//here is some Processing of data and after processing I close the handle
CloseHandle(threads);
delete inst;
system("pause");
}
}
No -- closing a handle to a thread does not destroy the thread itself. The thread should exit (either by calling ExitThread or by just returning from the thread function) when it's finished doing its job.
In emergencies, you can use TerminateThread to kill a thread, but that should be reserved for true emergencies -- it can leave the process in an unstable state, so it should generally be avoided, and if you have to use it, you probably want to shut down the process as soon afterwards as possible.
Also note that in a program that uses the standard library, it's not really safe to use CreateThread directly -- you should call _beginthread or _beginthreadex instead. These do some setup to allow thread-safe use of standard library functions that use static storage (e.g., strtok and mktime, but there are quite a few more).
Drop all those "(type)foo" casts, they are forcing the compiler to accept things that in reality don't fit. You will have to fix a few errors there by replacing things with the proper type. For the context pointer passed to the thread, the conversion from demo* to void* is implicit. The correct cast to reverse this is static_cast<demo*>(data). If you want, you can use the a static cast for the implicit conversion, too. There are missing return values in functions, too, the only case that is allowed is in main(). The reason I mention th s is that formally, anything can happen in your program, because these things cause undefined behaviour.
Then, you are outputting the "value of inst" but actually outputting the address of local variables called "inst", which is something different. This probably just adds to your confusion.
Now, coming to your problem, CloseHandle() does not stop the thread. It only releases your handle. What you want is WaitForSingleObject() or one of its brethren instead.

DeleteInterpProc called with active evals

I am writing a program which executes tcl scripts. When the script has exit command, the program crashes with this error
DeleteInterpProc called with active evals
Aborted
I am calling Tcl_EvalFile(m_interpreter, script.c_str()) where script is the file name.
Also I have tried Tcl_Eval with arguments interpreter and "source filename". Result is the same. Other tcl comands (eg. puts) interpreter executes normally. How this can be fixed?
#include <tcl.h>
#include <iostream>
int main() {
Tcl_Interp *interp = Tcl_CreateInterp();
//Tcl_Preserve(interp);
Tcl_Eval (interp, "exit");
//Tcl_Release(interp);
std::cout << "11111111111" << std::endl;
return 0;
}
This is the simple case. "11111111111" are not printed. As I understand whole program is exited when calling Tcl_Eval (interp, "exit");. The result is same after adding Tcl_Preserve and Tcl_Release.
The problem is that the interpreter, the execution context for Tcl code, is getting its feet deleted out from under itself; this makes it very confused! At least you're getting a clean panic/abort rather than a disgusting hard-to-reproduce crash.
The easiest fix is probably to do:
Tcl_Preserve(m_interpreter);
// Your code that calls Tcl_EvalFile(m_interpreter, script.c_str())
// and deals with the results.
Tcl_Release(m_interpreter);
Be aware that after the Tcl_Release, the Tcl_Interp handle may refer to deleted memory.
(Yes, wrapping the Tcl_Preserve/Tcl_Release in RAII goodness is reasonable.)
If you want instead to permit your code to run after the script does an exit, you have to take additional steps. In particular, the standard Tcl exit command is not designed to cause a return to the calling context: it will cause the process to call the _exit(2) system call. To change it's behavior, replace it:
// A callback function that implements the replacement
static int
MyReplacementExit(ClientData unused, Tcl_Interp *interp, int argc, const char *argv[])
{
// We ought to check the argument count... but why bother?
Tcl_DeleteInterp(interp);
return TCL_OK;
}
int main() {
Tcl_Interp *interp = Tcl_CreateInterp();
// Install that function over the standard [exit]
Tcl_CreateCommand(interp, "exit", MyReplacementExit, NULL, NULL);
// Important; need to keep the *handle* live until we're finished
Tcl_Preserve(interp);
// Or run whatever code you want here...
Tcl_Eval(interp, "exit");
// Important piece of cleanup code
if (!Tcl_InterpDeleted(interp))
Tcl_DeleteInterp(interp);
Tcl_Release(interp);
// After this point, you *MUST NOT* use interp
std::cout << "11111111111" << std::endl;
return 0;
}
The rules for doing memory management in these sorts of scenarios are laid out in the manual page for Tcl_CreateInterp. (That's the 8.6 manual page, but the relevant rules have been true since at least Tcl 7.0, which is over 2 decades ago.) Once an interpreter is deleted, you can no longer count on executing any commands or accessing any variables in it; the Tcl library handles the state unwinding for you.
It might be better to replace (hide) the exit command and create your own exit command that exit your program gracefully. I'm not that good with C and the Tcl C Api, but I hope this can help you.
Eggdrop for example uses the die command to exit gracefully.

c++ winapi threads

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.
See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.
If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

Why isn't setjmp saving the stack?

Why isn't setjmp saving the stack?
Consider the following code:
#include <iostream>
jmp_buf Buf;
jmp_buf Buf2;
void MyFunction()
{
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
if(!setjmp(Buf))
longjmp(Buf2, 1);
}
}
int main (int argc, const char * argv[])
{
while(true)
{
if(!setjmp(Buf2))
{
MyFunction();
break;
}
longjmp(Buf, 1);
}
return 0;
}
What I except is that the code will jump back and forth from main to the function and back printing increasing number every time.
What actually happens is that it prints 0 and then 1 infinite number of times. it is as if when it jumps back into the function the stack is reset to defaults. why is it doing it? is there any way I can make it save the stack too?
I know setjmp and longjmp are even worse than goto when it comes to coding style and readable code, but I am experimenting right now, and this code will probably never see the light of a usable application.
Because unfortunately thats not how setjmp works. setjmp copies the current instruction pointer and register set into the jump buffer but it does not copy the stack (obviously be cause the stack is huge). It looks like you want to use some kind of coroutine based techniques. If you want to do this yourself checkout the ucontext procedured (ucontext.h) http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?ucontext.h+3 they will help you to allocate and manage additionaly thread stacks.
or you could use something like Russ Cox's libtask (http://swtch.com/libtask/) which will help do this for you. Or if you want to do it yourself you should take a look at the libtask code (also available through that link). It's pretty easy to read so its a good resource.

How do I make a C++ console program exit?

Is there a line of code that will terminate the program?
Something like python's sys.exit()?
While you can call exit() (and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main():
int main()
{
// do whatever your program does
} // function returns and exits program
When you call exit(), objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.
#include <cstdlib>
...
exit( exit_code );
There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.
int main()
{
f();
return 0;
}
As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.
If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.
struct stop_now_t { };
void f()
{
// ...
if (some_condition())
throw stop_now_t();
// ...
}
int main()
{
try {
f();
} catch (stop_now_t& stop) {
return 1;
}
return 0;
}
This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.
If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.
Yes! exit(). It's in <cstdlib>.
Allowing the execution flow to leave main by returning a value or allowing execution to reach the end of the function is the way a program should terminate except under unrecoverable circumstances. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESS found in cstdlib (a platform-specific value that indicates the program executed successfully).
#include <cstdlib>
int main(int argc, char *argv[]) {
...
return EXIT_SUCCESS;
}
If, however, your program reaches an unrecoverable state, it should throw an exception. It's important to realise the implications of doing so, however. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.
For example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. If a second exception is thrown, terminate is called and your program will halt without any further clean-up having been performed. You can use uncaught_exception to determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor.
While it's generally always possible for functions you call but didn't write to throw exceptions (for example, new will throw std::bad_alloc if it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution.
#include <stdexcept>
#include <cstdlib>
#include <iostream>
int foo(int i) {
if (i != 5) {
throw std::runtime_error("foo: i is not 5!");
}
return i * 2;
}
int main(int argc, char *argv[]) {
try {
foo(3);
}
catch (const std::exception &e) {
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
exit is a hold-over from C and may result in objects with automatic storage to not be cleaned up properly. abort and terminate effectively causes the program to commit suicide and definitely won't clean up resources.
Whatever you do, don't use exceptions, exit, or abort/terminate as a crutch to get around writing a properly structured program. Save them for exceptional situations.
if you are in the main you can do:
return 0;
or
exit(exit_code);
The exit code depends of the semantic of your code. 1 is error 0 e a normal exit.
In some other function of your program:
exit(exit_code)
will exit the program.
This SO post provides an answer as well as explanation why not to use exit(). Worth a read.
In short, you should return 0 in main(), as it will run all of the destructors and do object cleanup. Throwing would also work if you are exiting from an error.
In main(), there is also:
return 0;
#include <cstdlib>
...
/*wherever you want it to end, e.g. in an if-statement:*/
if (T == 0)
{
exit(0);
}
throw back to main which should return EXIT_FAILURE,
or std::terminate() if corrupted.
(from Martin York's comment)
else if(Decision >= 3)
{
exit(0);
}
exit(0); // at the end of main function before closing curly braces
simple enough..
exit ( 0 );
}//end of function
Make sure there is a space on both sides of the 0. Without spaces, the program will not stop.