The following code fragment, taken from the ctfirst.c migration example program, illustrates Client-Library initialization and cleanup.
The fragment installs error handlers for CS-Library and Client-Library, as well as a Client-Library server message callback. For examples of a Client-Library error handler and a server message handler, see the “Callbacks” topics page in the Open Client Client-Library/C Reference Manual. For an example CS-Library error handler, see the Open Client/Server Common Libraries Reference Manual.
#define NORMAL_EXIT (0) #define ERROR_EXIT (-1) CS_CONTEXT *context = (CS_CONTEXT *) NULL; CS_CONNECTION *conn; CS_RETCODE ret;
/* ** Step 1. ** Allocate a CS_CONTEXT structure and initialize Client-Libary. -- if (dbinit() == FAIL) -- exit(ERREXIT); */
ret = cs_ctx_alloc(CS_VERSION_125, &context); EXIT_ON_FAIL(context, ret, "Could not allocate context."); ret = ct_init(context, CS_VERSION_125); EXIT_ON_FAIL(context, ret, "Client-Library initialization failed.");
/* ** Step 2. ** Install callback handlers for CS-Library errors, Client- ** Library errors, and CS-Library errors. ** -- dberrhandle(err_handler); -- dbmsghandle(msg_handler); */ /* ** cs_config() installs a handler for CS-Library errors. */ ret = cs_config(context, CS_SET, CS_MESSAGE_CB, (CS_VOID *) cserror_cb, CS_UNUSED, NULL); EXIT_ON_FAIL(context, ret, "Could not install CS-Library error handler.");
/* ** ct_callback() installs handlers for Client-Library errors and ** server messages. ** ** ct_callback() lets you install handlers in the context or the ** connection. Here, we install them in the context so that they ** are inherited by connections that are allocated using this ** context. */ ret = ct_callback(context, NULL, CS_SET, CS_CLIENTMSG_CB, (CS_VOID *) clientmsg_cb); EXIT_ON_FAIL(context,ret, "Could not install Client-Library error handler.");
ret = ct_callback(context, NULL, CS_SET, CS_SERVERMSG_CB, (CS_VOID *) servermsg_cb); EXIT_ON_FAIL(context,ret, "Could not install server message handler.");
... deleted code that connects and interacts with the server ...
/* ** Clean up Client-Library. ** ** ct_exit(context, CS_UNUSED) requests an "orderly" exit. ** This call fails if we have open connections. If it fails, ** EXIT_ON_FAIL() calls ct_exit(context, CS_FORCE_EXIT) to ** force cleanup of Client-Library. */ ret = ct_exit(context, CS_UNUSED); EXIT_ON_FAIL(context, ret, "ct_exit(CS_UNUSED) failed.");
/* ** Clean up CS-Library. cs_ctx_drop() always fails if ct_init() ** succeeded on the context but ct_exit() did not (or if ** ct_exit() was not called at all). */ (CS_VOID) cs_ctx_drop(context); context = (CS_CONTEXT *) NULL; exit(NORMAL_EXIT);