exit(EXIT_FAILURE) : the Tcl C API equivalent

80 Views Asked by At

I have this function :

Tcl_Obj* cFuncTcl (Tcl_Interp* interp, Tcl_Obj* obj) {
    Tcl_Obj *listObj = Tcl_NewListObj (0,NULL);
    const char* var = Tcl_GetString(obj);

    if (strcmp(var, "foo")) {
        fprintf(stderr, "error\n");
        exit(EXIT_FAILURE);
    } else {
        // Do something
    }

    return listObj;
}

I use return Tcl_ERROR; when my function returns an integer to report an error, but here my function returns an obj.

My question: Is there an API C Tcl equivalent to exit(EXIT_FAILURE)?

2

There are 2 best solutions below

0
Clifford On BEST ANSWER

I use return Tcl_ERROR; when my function returns an integer to report an error,

Reporting an error via its return value is not the same a exit() which terminates the process. No TCL API is required to terminate the process, how would that be any different than exit()?

If you want to return from this function with an error indication rather then abort, then simply return NULL - the return value is a pointer or an object, not an object itself, so returning NULL is the idiomatic way of indicating failure.

Tcl_Obj* cFuncTcl (Tcl_Interp* interp, Tcl_Obj* obj) 
{
    Tcl_Obj *listObj = Tcl_NewListObj (0,NULL);
    const char* var = Tcl_GetString(obj);

    if (strcmp(var, "foo")) 
    {
        fprintf(stderr, "error\n");
        return NULL ;
    } 
    else 
    {
        // Do something
    }

    return listObj;
}

Is there an API C Tcl equivalent to exit(EXIT_FAILURE)?

The API is fully documented and there is process termination API that includes Tcl_Exit(), but it is not clear that is what you actually need in this case. You seem to be conflating process termination with a function returning an error status. Nonetheless:

Tcl_Obj* cFuncTcl (Tcl_Interp* interp, Tcl_Obj* obj) 
{
    Tcl_Obj *listObj = Tcl_NewListObj (0,NULL);
    const char* var = Tcl_GetString(obj);

    if (strcmp(var, "foo")) 
    {
        fprintf(stderr, "error\n");
        Tcl_Exit( Tcl_ERROR ) ;
    } 
    else 
    {
        // Do something
    }

    return listObj;
}
2
Donal Fellows On

If you're talking about a Tcl command implementation, return TCL_ERROR; signals that things went wrong (and TCL_OK would be if it worked). At the Tcl script level, that becomes a thrown error (with an error message in the interpreter result) that you handle with catch or try. It's up to the code that ultimately called Tcl_Eval() or Tcl_EvalFile() to decide what to do if the error bubbles up that far; in tclsh, the error stack unwinding trace is printed and the process exits... but that is really just the simplest option.

At the whole process level, use Tcl_Exit(EXIT_FAILURE); in C. Or exit 1 in a script. Does what it says on the tin (after running critical exit handlers to do things like flushing I/O buffers).