Execing Processes in COBOL

Our example demonstrates how to execute external processes in COBOL, similar to the exec function in Unix-like operating systems. In COBOL, we don’t have a direct equivalent to exec, but we can use the CALL statement to run external programs.

IDENTIFICATION DIVISION.
PROGRAM-ID. EXEC-PROCESS.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT COMMAND-OUTPUT ASSIGN TO "command-output.txt"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD COMMAND-OUTPUT.
01 OUTPUT-LINE PIC X(80).

WORKING-STORAGE SECTION.
01 WS-COMMAND PIC X(100).
01 WS-RETURN-CODE PIC 9(4).

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    MOVE "ls -a -l -h" TO WS-COMMAND.
    
    CALL "SYSTEM" USING WS-COMMAND
                  GIVING WS-RETURN-CODE.
    
    IF WS-RETURN-CODE NOT = 0
        DISPLAY "Error executing command. Return code: " WS-RETURN-CODE
        STOP RUN
    END-IF.

    OPEN INPUT COMMAND-OUTPUT.
    PERFORM DISPLAY-OUTPUT UNTIL 1 = 2.
    CLOSE COMMAND-OUTPUT.
    
    STOP RUN.

DISPLAY-OUTPUT.
    READ COMMAND-OUTPUT
        AT END
            EXIT PERFORM
    END-READ.
    DISPLAY OUTPUT-LINE.

In this COBOL program:

  1. We use the CALL "SYSTEM" statement to execute the ls -a -l -h command. This is similar to using exec.LookPath("ls") and syscall.Exec in the original example.

  2. The command and its arguments are combined into a single string (WS-COMMAND), unlike in the original example where they were separate.

  3. We capture the return code of the command execution in WS-RETURN-CODE.

  4. The output of the command is redirected to a file (command-output.txt), which we then read and display.

  5. We don’t have direct access to environment variables like in the original example (os.Environ()). The system call will use the current environment.

To run this program:

$ cobc -x exec-process.cob
$ ./exec-process

This will execute the ls -a -l -h command and display its output.

Note that COBOL doesn’t offer a direct equivalent to Unix’s fork function. The CALL statement in COBOL is typically used for executing subprograms or system commands, which covers many use cases for process execution in COBOL applications.