Skip to content
systemcoding.dev
Mainframe

The Complete Guide to CICS Application Programming in COBOL

A complete guide to CICS programming in COBOL: tasks, BMS screens, VSAM files, queues, program control, error handling, Db2, debugging and operations.

27 min read
Summarize in AI
Flat illustration of a 3270 terminal showing JCL beside a mainframe.

CICS Transaction Server for z/OS is the software that most of the world's online mainframe transactions pass through. When you swipe a card, check an account balance or confirm an insurance claim, there is a decent chance a COBOL program running under CICS answers. This guide teaches you to write those programs. It starts from what a transaction, a task and a program are, then builds up to screens, files, queues, calls between programs, error handling, Db2, debugging and the operational commands you will use every day. It uses CICS Transaction Server for z/OS 6.1, Enterprise COBOL for z/OS 6.4 and z/OS 3.1, and every sample is written carefully against those releases and followed by the exact output it produces for the input shown.

The one-sentence answer: a CICS COBOL program is an ordinary COBOL program with no input or output of its own, which asks CICS to do every terminal, file, queue and program-to-program operation through EXEC CICS commands, and which ends each short task quickly so that one region can serve thousands of users.

Who this guide is for

Read this guide if you know basic COBOL, meaning WORKING-STORAGE, PERFORM, MOVE and IF, and you need to write or maintain online programs. You do not need to know CICS. You should be comfortable submitting JCL, because the build steps use it, and you should have a user ID on a test CICS region where you may define resources.

It is not for you if your task is to run batch jobs only, since nothing here applies to a program that reads SYSIN and writes SYSOUT. Nor is it an administrator's guide: it does not cover installing CICS, sizing regions or writing system initialization tables, which belong to the CICS systems programmer. Where an administrator's choice changes how your program behaves, the guide says so and tells you what to ask.

The ideas to hold in your head

CICS has a small vocabulary, and the rest of the guide leans on it.

A region is the long-running z/OS address space in which CICS runs. A transaction is a kind of request, named by a one-to-four character ID that a user types, such as ORD1. A task is one running instance of a transaction, created for one request, with its own working storage. A program is a compiled load module that a task runs. CICS looks up the transaction ID, creates a task, loads the program if it is not already in storage and starts it. When the program ends with EXEC CICS RETURN, the task ends, recoverable changes are committed and the storage is released.

Two consequences shape everything you write. First, many tasks share one copy of a program, so the program must be reentrant: it must not change its own code or keep per-user data in storage that other tasks share. Ordinary WORKING-STORAGE is safe, because each task gets its own copy. Second, a task must be short. CICS runs most application code on one operating-system thread, switching between tasks when a task waits for something, so a task that holds the processor in a long loop makes every other user wait. Design every task to read a little, change a little and end.

Resources and the CSD

CICS only knows what it has been told. Each program, transaction, file, map set and queue is a resource definition, stored in the CICS system definition data set, the CSD, grouped into groups and installed into the region, either by a CEDA INSTALL or from a startup list. You will define at least a program and a transaction for everything you write, and you will refresh the program with CEMT whenever you recompile it.

Anatomy of a CICS COBOL program

Start with the smallest complete program, which writes a message to the terminal.

HELLOCIC.cblcobol
       IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLOCIC.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  WS-MESSAGE      PIC X(30)
           VALUE 'HELLO FROM CICS COBOL'.
       01  WS-LENGTH       PIC S9(4) COMP VALUE 21.
       PROCEDURE DIVISION.
       MAIN-PARA.
           EXEC CICS SEND TEXT
                FROM(WS-MESSAGE)
                LENGTH(WS-LENGTH)
                ERASE
           END-EXEC.
           EXEC CICS RETURN
           END-EXEC.

There is no OPEN, no READ of the terminal and no STOP RUN. EXEC CICS SEND TEXT asks CICS to write 21 bytes to the user's screen and clear it first. EXEC CICS RETURN ends the task and hands control back. The user sees one line.

Text
HELLO FROM CICS COBOL

The execute interface block

Before the program starts, CICS fills a block of fields called the execute interface block, the EIB, which the translator adds to your program automatically. You never declare it. It tells you about the task and the last command.

FieldHolds
EIBTRNIDThe transaction ID of this task
EIBTRMIDThe terminal ID, blank for a task with no terminal
EIBCALENThe length of the commarea passed in, zero if none
EIBAIDThe key the user pressed, such as Enter or PF3
EIBDATE, EIBTIMEDate and time the task started
EIBRESP, EIBRESP2Result of the last command
EIBFNA code for the last command

You use EIBCALEN and EIBAID in nearly every interactive program, as the next sections show.

Build and define

A CICS program passes through a translator that turns EXEC CICS commands into calls. With Enterprise COBOL you give the compiler the CICS option and it translates and compiles in one pass.

jcl
//COMPILE EXEC PGM=IGYCRCTL,
//        PARM='LIB,CICS,NODYNAM,RENT,OBJECT'
//STEPLIB  DD DISP=SHR,DSN=IGY.SIGYCOMP
//SYSLIB   DD DISP=SHR,DSN=CICSTS61.CICS.SDFHCOB
//SYSIN    DD DISP=SHR,DSN=USER01.COBOL.SOURCE(HELLOCIC)
//SYSLIN   DD DSN=&&LOADSET,DISP=(MOD,PASS),UNIT=SYSDA,
//         SPACE=(TRK,(3,3))
//SYSPRINT DD SYSOUT=*

RENT makes the program reentrant, which CICS requires. The data set names are common defaults and your site's names may differ. The link step includes the CICS interface stub DFHELII and writes the load module to a library in the region's DFHRPL concatenation, the list of libraries CICS searches for programs. Then you define the program and the transaction.

Text
CEDA DEFINE PROGRAM(HELLOCIC) GROUP(MYGRP) LANGUAGE(COBOL)
CEDA DEFINE TRANSACTION(HELO) GROUP(MYGRP) PROGRAM(HELLOCIC)
CEDA INSTALL GROUP(MYGRP)

Clear the screen, type HELO, press Enter, and the message appears. If CICS answers that the transaction is not found, the install did not run. If the task ends with abend APCT, CICS could not find or load the program: check DFHRPL.

Talking to the terminal

Programs talk to a 3270 terminal in one of two ways. SEND TEXT and RECEIVE move plain text and suit messages. Basic Mapping Support, BMS, moves formatted screens with named fields and suits anything that asks the user for input.

Maps

A map is a screen layout written as assembler macros. DFHMSD defines the map set, DFHMDI a map and DFHMDF each field, with its position, length and attributes.

ORDSET.bmsasm
ORDSET   DFHMSD TYPE=&SYSPARM,LANG=COBOL,MODE=INOUT,                   X
               CTRL=(FREEKB,FRSET),TIOAPFX=YES,STORAGE=AUTO
ORDMAP   DFHMDI SIZE=(24,80),LINE=1,COLUMN=1
         DFHMDF POS=(1,28),LENGTH=24,ATTRB=(ASKIP,BRT),                X
               INITIAL='ORDER INQUIRY'
         DFHMDF POS=(3,2),LENGTH=13,ATTRB=ASKIP,                       X
               INITIAL='ORDER NUMBER:'
ORDNO    DFHMDF POS=(3,16),LENGTH=6,ATTRB=(UNPROT,IC,NUM)
         DFHMDF POS=(3,23),LENGTH=0,ATTRB=ASKIP
         DFHMDF POS=(5,2),LENGTH=9,ATTRB=ASKIP,                        X
               INITIAL='CUSTOMER:'
CUSTNM   DFHMDF POS=(5,12),LENGTH=30,ATTRB=(ASKIP,BRT)
         DFHMDF POS=(6,2),LENGTH=7,ATTRB=ASKIP,                        X
               INITIAL='AMOUNT:'
AMTOUT   DFHMDF POS=(6,10),LENGTH=12,ATTRB=(ASKIP,BRT)
MSG      DFHMDF POS=(23,2),LENGTH=60,ATTRB=(ASKIP,BRT)
         DFHMDF POS=(24,2),LENGTH=30,ATTRB=ASKIP,                      X
               INITIAL='ENTER=SEARCH  PF3=EXIT'
         DFHMSD TYPE=FINAL
         END

Each field's attribute byte sits at the position you give, so the visible data begins one column later. An UNPROT field accepts typing, ASKIP is protected and skipped by the cursor, BRT is bright and IC puts the cursor there. The zero-length field after ORDNO ends the input field so the cursor does not run on. The same source is assembled twice, once with SYSPARM(MAP) to build the load module CICS uses and once with SYSPARM(DSECT) to build the COBOL copybook, the symbolic map. Each named field produces L, F, A and I or O items: ORDNOL is the length typed, ORDNOI the input data, ORDNOO the output data, and ORDNOA the attribute byte.

Sending and receiving

SEND MAP writes the screen, and RECEIVE MAP reads the reply.

cobol
           MOVE LOW-VALUES TO ORDMAPO
           MOVE 'ENTER AN ORDER NUMBER' TO MSGO
           EXEC CICS SEND MAP('ORDMAP') MAPSET('ORDSET')
                FROM(ORDMAPO) ERASE
           END-EXEC.

Moving LOW-VALUES to the output area first means untouched fields are not transmitted, so no stale data reaches the screen. When the user presses Enter, a new task starts and the program reads the input.

cobol
           EXEC CICS RECEIVE MAP('ORDMAP') MAPSET('ORDSET')
                INTO(ORDMAPI) RESP(WS-RESP)
           END-EXEC.

If the user presses Enter on an untouched screen, RECEIVE MAP raises the MAPFAIL condition, and a program without a RESP abends with AEI9. Always test it. Test EIBAID before the receive too, because CLEAR and PF3 send no data. The copybook DFHAID names the keys, DFHENTER, DFHPF3 and DFHCLEAR, and the copybook DFHBMSCA names attribute constants such as DFHBMBRY for bright unprotected.

Pseudo-conversational design

A person at a terminal takes seconds to answer a screen. If your task waited for the answer, it would hold its storage and its locks for that whole time. CICS programs therefore end after each screen. The program sends the map and returns, naming the transaction that should start when the user answers.

cobol
           EXEC CICS RETURN
                TRANSID('ORD2')
                COMMAREA(WS-COMMAREA)
                LENGTH(LENGTH OF WS-COMMAREA)
           END-EXEC.

RETURN TRANSID ends the task and tells CICS to start ORD2 at this terminal on the next input. The COMMAREA hands a block of bytes to the next task, which finds it in DFHCOMMAREA in the linkage section. EIBCALEN equal to zero means this is the first time, with nothing passed. So the usual program decides what to do from EIBCALEN and EIBAID, which is a small state machine: first time, send the screen; Enter, process the input; PF3, leave.

The state travels in the commarea, up to 32,500 bytes. Larger or evolving data belongs in channels and containers, which are named blocks of any size passed with PUT CONTAINER, LINK PROGRAM CHANNEL and GET CONTAINER. Because no lock survives from one turn to the next, an update must read the record again at the confirming turn and compare a version or timestamp before rewriting, so that a change made by someone else in between is not overwritten.

A complete inquiry program

This program ties the last three sections together. It shows the order inquiry screen, reads an order by number from a VSAM file, and shows the customer and the amount.

ORDINQ.cblcobol
       IDENTIFICATION DIVISION.
       PROGRAM-ID. ORDINQ.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
           COPY ORDSET.
           COPY DFHAID.
           COPY DFHBMSCA.
       01  WS-RESP          PIC S9(8) COMP.
       01  WS-KEY           PIC X(6).
       01  WS-COMMAREA      PIC X(1) VALUE 'I'.
       01  WS-BYE           PIC X(12) VALUE 'GOODBYE'.
       01  WS-AMOUNT-ED     PIC Z,ZZZ,ZZ9.99.
       01  WS-ORDER-REC.
           05  OR-ID        PIC X(6).
           05  OR-CUST      PIC X(8).
           05  OR-STATUS    PIC X.
           05  OR-AMOUNT    PIC S9(7)V99 COMP-3.
           05  FILLER       PIC X(60).
       LINKAGE SECTION.
       01  DFHCOMMAREA      PIC X(1).
       PROCEDURE DIVISION.
       MAIN-LOGIC.
           EVALUATE TRUE
               WHEN EIBCALEN = 0
                   PERFORM SEND-FIRST
               WHEN EIBAID = DFHPF3 OR EIBAID = DFHCLEAR
                   PERFORM END-SESSION
               WHEN EIBAID = DFHENTER
                   PERFORM GET-ORDER
               WHEN OTHER
                   MOVE 'KEY NOT ACTIVE' TO MSGO
                   PERFORM SEND-DATA
           END-EVALUATE
           EXEC CICS RETURN TRANSID('ORD2')
                COMMAREA(WS-COMMAREA) LENGTH(1)
           END-EXEC.

       SEND-FIRST.
           MOVE LOW-VALUES TO ORDMAPO
           MOVE 'ENTER AN ORDER NUMBER' TO MSGO
           EXEC CICS SEND MAP('ORDMAP') MAPSET('ORDSET')
                FROM(ORDMAPO) ERASE
           END-EXEC.

       SEND-DATA.
           EXEC CICS SEND MAP('ORDMAP') MAPSET('ORDSET')
                FROM(ORDMAPO) DATAONLY CURSOR
           END-EXEC.

       END-SESSION.
           EXEC CICS SEND TEXT FROM(WS-BYE) LENGTH(12) ERASE
           END-EXEC
           EXEC CICS RETURN END-EXEC.

       GET-ORDER.
           EXEC CICS RECEIVE MAP('ORDMAP') MAPSET('ORDSET')
                INTO(ORDMAPI) RESP(WS-RESP)
           END-EXEC
           EVALUATE TRUE
               WHEN WS-RESP = DFHRESP(MAPFAIL)
                   MOVE 'PLEASE ENTER AN ORDER NUMBER' TO MSGO
                   PERFORM SEND-DATA
               WHEN WS-RESP NOT = DFHRESP(NORMAL)
                   MOVE 'SCREEN ERROR, TRY AGAIN' TO MSGO
                   PERFORM SEND-DATA
               WHEN ORDNOL NOT = 6
                   MOVE 'ORDER NUMBER IS SIX DIGITS' TO MSGO
                   MOVE -1 TO ORDNOL
                   PERFORM SEND-DATA
               WHEN OTHER
                   PERFORM READ-ORDER
           END-EVALUATE.

       READ-ORDER.
           MOVE ORDNOI TO WS-KEY
           EXEC CICS READ FILE('ORDFILE')
                INTO(WS-ORDER-REC)
                RIDFLD(WS-KEY)
                RESP(WS-RESP)
           END-EXEC
           EVALUATE WS-RESP
               WHEN DFHRESP(NORMAL)
                   MOVE OR-CUST TO CUSTNMO
                   MOVE OR-AMOUNT TO WS-AMOUNT-ED
                   MOVE WS-AMOUNT-ED TO AMTOUTO
                   MOVE 'ORDER FOUND' TO MSGO
               WHEN DFHRESP(NOTFND)
                   MOVE SPACES TO CUSTNMO AMTOUTO
                   MOVE 'ORDER NOT FOUND' TO MSGO
               WHEN OTHER
                   MOVE 'FILE ERROR, CALL SUPPORT' TO MSGO
           END-EVALUATE
           MOVE -1 TO ORDNOL
           PERFORM SEND-DATA.

The first pass sees EIBCALEN = 0 and sends the screen. After the user types 000042 and presses Enter, the second pass sees DFHENTER, receives the map, checks that exactly six characters arrived, reads the file and fills the output fields. For an order whose customer is C0001234 and whose amount is 1250.75 the screen reads as follows.

Text
                           ORDER INQUIRY

 ORDER NUMBER: 000042

 CUSTOMER: C0001234
 AMOUNT:     1,250.75


 ORDER FOUND

 ENTER=SEARCH  PF3=EXIT

The cursor returns to the order number field because the program set its length to -1 and sent with CURSOR. For an order that does not exist, the customer and amount lines are blank and the message reads ORDER NOT FOUND. Notice the order of the EVALUATE: the MAPFAIL test comes before the length test, because on a MAPFAIL the length field holds nothing useful.

Files

CICS programs do not open files. The region owns each VSAM file as a file resource, defined with the attributes that say which commands are allowed, and a program names it in commands.

READ gets one record by key, with RIDFLD holding the key and INTO receiving the data. Test RESP: NOTFND means the key is not there, NOTOPEN and DISABLED mean the file is unavailable and LENGERR means the area is shorter than the record. To change a record, read it with UPDATE, change the data and REWRITE.

cobol
           EXEC CICS READ FILE('ORDFILE') INTO(WS-ORDER-REC)
                RIDFLD(WS-KEY) UPDATE RESP(WS-RESP)
           END-EXEC
           MOVE 'S' TO OR-STATUS
           EXEC CICS REWRITE FILE('ORDFILE') FROM(WS-ORDER-REC)
                RESP(WS-RESP)
           END-EXEC.

READ ... UPDATE locks the record for the task until it is rewritten, deleted or unlocked, or the task syncpoints. Keep that window short. WRITE adds a record and raises DUPREC for an existing key, and DELETE removes one.

A browse reads a run of records in key order. STARTBR positions, READNEXT fetches and returns the key in RIDFLD, READPREV goes backward, RESETBR repositions and ENDBR finishes. The end of a forward browse is the ENDFILE condition, which is normal. Always issue ENDBR, or the browse holds resources until the task ends. A browse takes no locks, so a screen that pages through results may show a record twice or miss one if others change the file, and the design should tolerate that.

Queues

When data must outlive a task but does not deserve a file, use a queue. Temporary storage queues hold numbered items that any task can read by number or in sequence and that stay until a task deletes the queue. They are the usual home for a paged result list: write all the lines with WRITEQ TS, save the page number in the commarea and read the items for each page with READQ TS ITEM(n). Build the queue name from EIBTRMID so users never share one. Transient data queues are read once and removed, in order. Extrapartition queues write to sequential data sets, which makes them the logging tool, and intrapartition queues carry work between tasks and can start a transaction automatically when items arrive. Both queue kinds can be recoverable, in which case a write becomes visible only at the writer's syncpoint.

Moving between programs

Real applications split into many programs. LINK PROGRAM(name) calls another CICS program and waits for it, as a subroutine, and the called program shares the commarea. XCTL PROGRAM(name) hands control over for good and frees the caller's storage, as one stage of a chain passes to the next. RETURN ends the current level. A COBOL CALL is cheaper for private subroutines that no other transaction uses, since it bypasses CICS.

cobol
           EXEC CICS LINK PROGRAM('PRICECHK')
                COMMAREA(WS-PRICE-AREA)
                LENGTH(LENGTH OF WS-PRICE-AREA)
                RESP(WS-RESP)
           END-EXEC
           IF WS-RESP = DFHRESP(PGMIDERR)
               MOVE 'PRICING SERVICE NOT AVAILABLE' TO MSGO
           END-IF.

PGMIDERR means the program is not defined or is disabled. To pass more than 32,500 bytes, or data with several parts, use a channel in place of the commarea.

For background work, EXEC CICS START TRANSID('ORDC') FROM(...) INTERVAL(...) schedules another task and carries on, and the new task reads its data with RETRIEVE. A START is held until the starter's syncpoint, and a failure in the started task never reaches the caller, so log outcomes where operations can see them.

Handling errors

A command with no RESP abends the task on any condition other than normal, for example AEIM for NOTFND. Add RESP(WS-RESP) to every command, declare WS-RESP as PIC S9(8) COMP and compare with DFHRESP, never with a number.

cobol
           EVALUATE WS-RESP
               WHEN DFHRESP(NORMAL)    PERFORM USE-RECORD
               WHEN DFHRESP(NOTFND)    PERFORM NO-SUCH-ORDER
               WHEN OTHER              PERFORM CICS-ERROR
           END-EVALUATE.

End with a WHEN OTHER that calls one shared error routine, which logs WS-RESP, RESP2, the command code in EIBFN and a program location, then ends the task cleanly. RESP2 gives the detail behind a condition such as INVREQ, and the documentation lists its meanings for each command.

For failures you cannot predict, EXEC CICS HANDLE ABEND LABEL(ABEND-ROUTINE) catches a task abend and lets you read the code with ASSIGN ABCODE, clean up resources, roll back and either end with a message or re-abend with the same code. Never swallow an abend you did not expect.

AbendUsual meaning
ASRAA program check: bad data, such as a data exception, or a bad address
AICAA runaway task: a loop that never waited
AEIxAn unhandled condition, for example AEIM for NOTFND, AEI9 for MAPFAIL
APCTThe program could not be found or loaded
AEY9A needed resource manager, such as Db2, is not connected

Units of work and recovery

A task is a unit of work. Changes to recoverable resources, such as recoverable VSAM files, recoverable queues and Db2, become permanent at a syncpoint: when the task ends normally, or when it issues EXEC CICS SYNCPOINT. If the task abends, or issues SYNCPOINT ROLLBACK, CICS backs them out. Record locks last until the syncpoint, so the length of a unit of work is the length of the locks. Keep it short, and never wait for a user inside one. When a program updates two files and one update fails, issue SYNCPOINT ROLLBACK so both are undone, and tell the user.

Db2 from CICS

A CICS program uses Db2 with the same embedded SQL as batch: EXEC SQL statements, host variables with colons and SQLCODE tests. The differences are around the SQL. The region connects to Db2 once through the CICS Db2 attachment, so the program never connects. A commit is a CICS syncpoint, not EXEC SQL COMMIT, which is rejected with SQLCODE -925. The program links with the stub DSNCLI and not the batch stub, and its package is bound into a plan that the attachment definition names. A -911 means Db2 rolled the unit of work back after a deadlock or timeout, so tell the user to retry.

cobol
           EXEC SQL
               SELECT NAME, BALANCE
                 INTO :NAME, :BALANCE
                 FROM ORDERS.CUSTOMER
                WHERE CUST_ID = :WS-KEY
           END-EXEC
           IF SQLCODE = +100
               MOVE 'CUSTOMER NOT FOUND' TO MSGO
           END-IF.

Keep SQL units of work short, name the columns, always supply the key, and update with a version check in the WHERE clause so a stale screen cannot overwrite a newer row.

Testing and debugging

You have three tools in a test region. CECI runs one EXEC CICS command at a time from the terminal and shows the response and the EIBRESP2 value, which is a fast way to see what a READ really returns. CEDF steps through your program, stopping before and after each command with its options and result shown, and lets you change a response to test an error path. CEMT inspects and changes live resources.

Text
CEMT INQUIRE TASK
CEMT INQUIRE PROGRAM(ORDINQ)
CEMT INQUIRE FILE(ORDFILE)
CEMT SET PROGRAM(ORDINQ) NEWCOPY

The last command matters most to developers. CICS keeps the first loaded copy of a program until told to replace it, so after you recompile, nothing changes until you issue NEWCOPY, which refuses with INUSE while any task is using the program, or PHASEIN, which loads the new copy for new tasks and lets running ones finish. If the old behavior stays after a clean refresh, the library may be under LLA control and need a refresh, or CICS may be finding another copy earlier in DFHRPL.

For a task that failed when you were not looking, use the CICS message log to find the transaction, task number and abend code, then read the trace for that task if it was on, and the transaction dump if one was written. The compile listing's offset tables map a failing offset back to your source line. Add EIBFN, RESP and RESP2 to your error routine's log line, and most failures explain themselves.

Good citizenship in a shared region

A region serves many applications, so a careless program hurts others. Follow these habits.

  • Never loop without a command that can wait. A tight loop holds the processor and stalls every other task until CICS abends it with AICA.

  • End tasks quickly. Use pseudo-conversational design and release locks at each turn.

  • Read only what you need. A browse that reads a whole file to find one record is a region-wide cost.

  • Free what you get: ENDBR after STARTBR, DELETEQ for scratch queues you created and FREEMAIN for storage you obtained.

  • Do not store per-user data in storage that every task shares, such as the common work area, without serializing with ENQ, since newer programs may run on several threads at once.

  • Check every RESP. A program that ignores conditions turns an ordinary missing record into an outage.

Security in a paragraph

Users sign on with CESN, and CICS runs each task under the signed-on user ID. External security, usually RACF, checks whether that user may run a transaction, read a file or use a queue, and a failed check returns NOTAUTH. As a developer, you do not code the check, but you must handle the condition, and you must not put anything in a commarea or a queue that you would not trust a user to alter. Recheck authority where it matters instead of carrying a flag across turns.

A learning path

Learn in this order. Start by building and running the hello program, so the compile, link, define, install and run cycle is routine. Learn CEMT and NEWCOPY before anything else, because you will use them hourly. Then write a BMS map and a program that sends and receives it, handling MAPFAIL and the keys. Add the pseudo-conversational pattern and a commarea. Add VSAM reads and updates with RESP checks, then browse. Add queues, then LINK and XCTL. Add Db2. Learn CEDF early, since stepping through a program teaches you more about the commands than reading the manual. Read the compile listing and the CICS message log for every failure, because they teach you what CICS decided.

A review checklist

Before a program leaves the test region, check the following.

  1. Every EXEC CICS command has RESP, and the response is tested with DFHRESP names and a WHEN OTHER.

  2. The program ends tasks with EXEC CICS RETURN, with TRANSID and a commarea where it is pseudo-conversational, and never uses STOP RUN.

  3. EIBCALEN and EIBAID are tested before the program reads input, and MAPFAIL is handled.

  4. No lock is held across a terminal wait, and every STARTBR has an ENDBR.

  5. The commarea has one layout in a shared copybook, a length that follows the layout and a validated state field.

  6. Output maps are cleared with LOW-VALUES before each send.

  7. Shared storage is not changed without ENQ, and the program is defined threadsafe only after review.

  8. The definitions are in a group that is in the startup list, as well as installed.

  9. Error paths have been provoked and tested: a missing record, a closed file, a bad input and a deliberate abend.

How CICS COBOL differs from batch COBOL

If you come from batch, a few habits must change, and a table shows where.

Batch COBOLCICS COBOL
SELECT and FD for files, OPEN, READ, CLOSEEXEC CICS READ FILE(...), no OPEN or CLOSE
ACCEPT and DISPLAY, or SYSIN and SYSOUTSEND MAP and RECEIVE MAP, or SEND TEXT
STOP RUN or GOBACKEXEC CICS RETURN
CALL for every subprogramLINK or XCTL for CICS programs, CALL for private routines
The program runs for minutesThe task runs for milliseconds
One job, one userThousands of tasks share each program
FILE STATUS checksRESP checks and DFHRESP names
Whole job restarts after a failureThe unit of work is backed out, the task ends and the region carries on
Static storage persists for the runEach task has fresh WORKING-STORAGE, so state must be passed on

The last row is the one that surprises people most. In a batch program, a WORKING-STORAGE field set in one paragraph is still set many minutes later. In a pseudo-conversational CICS program, every turn starts with WORKING-STORAGE at its initial values, because it is a new task. A counter that you expect to survive from one screen to the next must travel in the commarea, a channel or a queue. Many first-week bugs are a flag that was set on screen one and found cleared on screen two.

Another habit is to avoid COBOL features that fight the monitor. Do not use ACCEPT or DISPLAY to talk to a terminal. DISPLAY output goes to a log in a region, not to the user, which makes it a poor debugging aid unless you know where the region writes it. Do not use STOP RUN, since it asks to end the run unit that CICS owns. Do not use native COBOL SORT on CICS files, and do not use INITIAL or COMMON program attributes in ways that assume a fresh load per call. And avoid STATIC data in called non-CICS subprograms that two tasks might use at once.

A second example: updating a record safely

An update screen is where the unit-of-work rules matter. This sequence shows the optimistic pattern that avoids holding a lock while the user thinks. On the first turn, the program reads the order without locking and saves a version marker in the commarea. On the confirming turn it reads again with UPDATE, compares and rewrites only if nothing changed.

cobol
       01  WS-COMMAREA.
           05  CA-STATE         PIC X.
               88  CA-AWAIT-CONFIRM  VALUE 'C'.
           05  CA-ORDER-ID      PIC X(6).
           05  CA-STATUS        PIC X.
       ...
       SHOW-ORDER.
           EXEC CICS READ FILE('ORDFILE') INTO(WS-ORDER-REC)
                RIDFLD(CA-ORDER-ID) RESP(WS-RESP)
           END-EXEC
           IF WS-RESP = DFHRESP(NORMAL)
               MOVE OR-STATUS TO CA-STATUS
               SET CA-AWAIT-CONFIRM TO TRUE
               MOVE 'PRESS ENTER TO SHIP THIS ORDER' TO MSGO
           END-IF.

       CONFIRM-SHIP.
           EXEC CICS READ FILE('ORDFILE') INTO(WS-ORDER-REC)
                RIDFLD(CA-ORDER-ID) UPDATE RESP(WS-RESP)
           END-EXEC
           IF WS-RESP NOT = DFHRESP(NORMAL)
               PERFORM FILE-PROBLEM
           ELSE
               IF OR-STATUS NOT = CA-STATUS
                   EXEC CICS UNLOCK FILE('ORDFILE') END-EXEC
                   MOVE 'ORDER CHANGED, PLEASE REVIEW' TO MSGO
               ELSE
                   MOVE 'S' TO OR-STATUS
                   EXEC CICS REWRITE FILE('ORDFILE')
                        FROM(WS-ORDER-REC) RESP(WS-RESP)
                   END-EXEC
                   MOVE 'ORDER SHIPPED' TO MSGO
               END-IF
           END-IF.

Here the order's status field plays the role of the version marker. If another user shipped or cancelled the order between the two turns, the second read shows a different status, the program releases the lock with UNLOCK and tells the user to look again. If nothing changed, it sets the status to S and rewrites. The lock exists only from the READ UPDATE to the REWRITE, which is a few statements and a few milliseconds, instead of the length of a conversation. A real application would use a timestamp or a counter on the record, since a status can change and change back, but the structure is the same.

A third example: paging a result list

Many screens show a list too long for one page. The standard design combines a temporary storage queue and the commarea. A search task reads the matching records and writes one item per line to a queue named for the terminal, then shows page one. The commarea holds the queue name and the current page number.

cobol
       BUILD-LIST.
           MOVE 0 TO WS-COUNT
           EXEC CICS DELETEQ TS QUEUE(WS-QNAME) RESP(WS-RESP)
           END-EXEC
           EXEC CICS STARTBR FILE('ORDFILE') RIDFLD(WS-KEY)
                GTEQ RESP(WS-RESP)
           END-EXEC
           PERFORM UNTIL WS-RESP NOT = DFHRESP(NORMAL)
               EXEC CICS READNEXT FILE('ORDFILE')
                    INTO(WS-ORDER-REC) RIDFLD(WS-KEY)
                    RESP(WS-RESP)
               END-EXEC
               IF WS-RESP = DFHRESP(NORMAL)
                   PERFORM FORMAT-LINE
                   EXEC CICS WRITEQ TS QUEUE(WS-QNAME)
                        FROM(WS-LINE) LENGTH(LENGTH OF WS-LINE)
                   END-EXEC
                   ADD 1 TO WS-COUNT
               END-IF
           END-PERFORM
           EXEC CICS ENDBR FILE('ORDFILE') END-EXEC.

The first DELETEQ clears any list left from an earlier search, and its response is ignored on purpose, since QIDERR for a queue that does not exist is not an error here. Each page is then read by item number. Page n shows items (n - 1) * 10 + 1 to n * 10, so a page change is a calculation and a READQ TS ITEM(...) for ten lines. The user presses PF8 for the next page, PF7 for the previous and PF3 to leave, and the PF3 branch deletes the queue so nothing accumulates. The design costs one browse and one queue write per line for the first screen, and then each page is a cheap read. For a list the user pages through several times, that is a good trade. For a list they will glance at once, a browse on each page, restarting from the saved last key, avoids the queue.

Two cautions complete the pattern. The list is a snapshot, so a record added after the search does not appear and a record deleted still does. And a queue named for the terminal is shared by every transaction at that terminal, so choose a prefix that belongs to this application.

Reading the first-week errors

Most failures you will meet in the first week are one of a short list. Learn to recognize them from the symptom.

SymptomLikely causeFirst check
TRANSACTION 'XXXX' NOT FOUNDThe definition is not installed in this regionCEDA INSTALL GROUP, then CEMT INQUIRE TRANSACTION
Abend APCTThe program is missing, disabled or not in DFHRPLCEMT INQUIRE PROGRAM, library concatenation
Abend ASRAA program check inside your codeThe offset in the message against the compile listing
Abend AEI9MAPFAIL with no RESPAdd RESP and test it
Abend AEIMNOTFND with no RESPAdd RESP and handle a missing key
Abend AICAA loop that never waitedLook for a PERFORM with no CICS command in it
Old behavior after a recompileThe old copy is still loadedCEMT SET PROGRAM NEWCOPY, then check LLA
Screen shows old dataThe output map was not clearedMOVE LOW-VALUES TO the output map first
LENGERR on a readThe INTO area is shorter than the recordMatch the structure to the file's record length
A field is always blank on turn twoState kept in WORKING-STORAGE, not the commareaMove it to DFHCOMMAREA

Each row has a one-minute check, and most failures end there. When none fits, the next step is CEDF, which shows the exact command and response where the program went wrong.

Operating tips for developers

A developer on a CICS test region uses a small set of inquiry commands all day. CEMT INQUIRE TASK lists tasks with their transaction, program and state, and a task that has been running for a long time points to a loop or a lock wait. CEMT INQUIRE FILE(ORDFILE) shows whether the file is open, enabled and how many requests it has served, and CEMT SET FILE(ORDFILE) CLOSED and OPEN let you provoke the NOTOPEN path in a test. CEMT INQUIRE TSQUEUE(name) lists the temporary storage queues and CEMT INQUIRE TDQUEUE(name) the transient data queues, with item counts, and a queue that keeps growing means a reader is down. CEMT INQUIRE UOW lists units of work, which is how you find a task that is holding locks.

The master terminal transaction can change things as well as show them, and in a shared region you must be careful. Setting a file closed stops every program that uses it, and purging a task backs out its work. Know whose region you are in and what the change control rules are before you issue a SET. Prefer inquiry commands, and ask the region's owner when you need a change.

Finally, learn where your region writes its messages. The CICS message log, usually a transient data queue routed to a data set or a log stream, records resource installs, abends with their task numbers and program names, and file and connection events. It is the first place to look for an abend you did not see. Learn the format of one DFHAC abend message, which names the transaction, the program, the abend code and the task number, because every incident starts there.

Testing a CICS program

A CICS program is easier to test when you plan for it. Keep the logic that decides things, such as validation, calculation and the choice of what to show, in paragraphs that do not issue CICS commands. Then you can exercise them with a small driver transaction that fills the inputs from constants, performs the paragraph and shows the result with SEND TEXT. The paragraphs that do issue commands stay thin, and you test those with CEDF, watching each command and its response, and with CECI for the commands you want to try on real data first.

Plan a test script for every transaction with at least these cases: the first entry with no commarea; a normal entry that finds data; a key that does not exist; an empty screen with Enter pressed; an invalid input in each field; each of the keys you handle and one you do not; and a deliberate failure, such as closing the file with CEMT SET FILE CLOSED, to see the error path. Write down the expected screen and message for each, and run the script after every change. Because screens are slow to retype, keep a list of test keys and values beside the script.

Test with two terminals when the program updates data. Start an update on the first, leave it at the confirm screen, change the record from the second and then confirm on the first. This is the only way to prove that the optimistic check works, and it is the test that most teams forget until a user reports a lost update.

Test the failure of dependencies as well. If the program links to another, define that program as disabled with CEMT SET PROGRAM(...) DISABLED and run the transaction, to see that your PGMIDERR handler produces a clear message. If it uses a queue, delete the queue between turns to test QIDERR. These are cheap to provoke in a test region and expensive to meet for the first time in production.

Standards that keep a team consistent

A team writing CICS programs benefits from a short list of shared rules, written down and checked in code review. Agree on names: a prefix for each application, a pattern for programs, transactions, map sets and queues, and a register that lists them so two teams never take the same four-character transaction ID. Agree on the template: one skeleton program with the EIB handling, the commarea check, the shared error routine and the RETURN already in place, copied for each new transaction, so every program fails and logs the same way. Agree on the copybooks: one for each commarea layout and each record layout, with the record layouts owned by the team that owns the file.

Agree on messages. A short list of standard user messages, with the wording and the abend codes your operations team recognizes, saves a great deal of time at three in the morning, because an operator can search for a code instead of reading a program. And agree on the promotion path: how a program moves from your test region to the integration test and then production, who refreshes the program, and who adds the group to the list. A clear path turns the NEWCOPY and list mistakes in this guide into rare events.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.