The C$CHAIN routine replaces the running program and runtime system with another program.
CALL "C$CHAIN" USING PROG-NAME
|PROG-NAME PIC X(n)||Contains an operating system command line to execute.|
This routine functions in the same manner as the SYSTEM library routine, except that there is no return to the running program. Instead, the current program shuts down (like a STOP RUN) and the runtime system then replaces itself with the passed program. This is similar to the CHAIN verb except that the called program is not a COBOL program; it is any program available on the host machine.
The usual reason for calling this routine is to make more memory available to the called program. The runtime system can occupy a significant amount of memory that may be needed by the called program. Calling C$CHAIN ensures that the runtime system is removed from memory along with the various COBOL programs that have been active.
Often it is desirable to return from the called program to the caller. One way to do this is to use an operating system script to re-execute the calling program. You can control the script with various exit statuses--for a description of the runtime's exit statuses, see the entry for the STOP Statement in the ACUCOBOL-GT Reference Manual. Usually the script will sit in a loop calling the ACUCOBOL-GT runtime system until it receives a special exit status. You can use the STOP RUN statement to pass that special status back to the script when you want to shut down. You should remember that when the runtime system chains to another program, the script sees the exit status of the called program as the exit status of the runtime system.
For example, suppose on a UNIX system that you have a program (called main) that executes the C$CHAIN routine. After the called program terminates, you want to re-execute the caller. You decide to use exit value "100" to indicate that the program should terminate. You could use the following "sh" script:
runcbl main while test $? != 100; do runcbl main; done
This script runs main once, and then continues to run it until it executes a STOP RUN 100 statement. Writing the script this way allows the program that is called by C$CHAIN to have a non-zero exit value without stopping the entire run.
You may want to distinguish between the first execution of the calling program and subsequent executions. For example, you may want to display copyright information on the first execution. You can do this by using a SPECIAL-NAMES switch to distinguish between the first execution and subsequent ones. For instance, in the preceding example you could add -1 to the second runcbl command to set SWITCH-1 for the subsequent executions. Your program can then test the value of this switch to determine what to do.