Job control in a console application

Example

This example program shows how a console application can receive a Windows job control notification from the LSF system.

Catching the notification messages involves:

  • Registering the windows messages for the signals that you want to receive (in this case, SIGINT and SIGTERM).

  • Creating a message queue by calling PeekMessage (this is how Microsoft suggests console applications should create message queues).

  • Look for the message you want to catch enter a GetMessage loop.

Tip:

Do not DispatchMessage here, since you do not have a window to dispatch to.

This program sits in the message loop. It is waiting for SIGINT and SIGTERM, and displays messages when those signals are received. A real application would do clean-up and exit if it received either of these signals.

/* CONJCNTL.C */
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    DWORD pid = GetCurrentProcessId();
    DWORD tid = GetCurrentThreadId();
    UINT msgSigInt = RegisterWindowMessage("SIGINT");
    UINT msgSigTerm = RegisterWindowMessage("SIGTERM");
    MSG msg;
/* Make a message queue -- this is the method suggested by MS */
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    printf("My process id: %d\n", pid);
    printf("My thread id: %d\n", tid);
    printf("SIGINT message id: %d\n", msgSigInt);
    printf("SIGTERM message id: %d\n", msgSigTerm);
    printf("Entering loop...\n");
    fflush(stdout);
    while (GetMessage(&msg, NULL, 0, 0)) {
        printf("Received message: %d\n", msg.message);
        if (msg.message == msgSigInt) {
            printf("SIGINT received, continuing.\n");
        } else if (msg.message == msgSigTerm) {
            printf("SIGTERM received, continuing.\n");
        }
        fflush(stdout);
    }
    printf("Exiting.\n");
    fflush(stdout);
    return EXIT_SUCCESS;
}