Fri, Jul
4 New Articles

TechTip: Lock and Lock

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Create your own utility to lock what the Allocate Object (ALCOBJ) command does not allow you to lock.

The Allocate Object (ALCOBJ) command is used to acquire one or more lock states on each of a list of objects. The lock states are allocated to the requesting thread, its containing job (i.e., MI process), or a lock space (i.e., an MI transaction control structure (TCS) object). Generally, the ALCOBJ command and its partner, the Deallocate Object (DLCOBJ) command, can achieve tasks similar to the Lock Object (LOCK) and Unlock Object (UNLOCK) MI instructions. But not exactly.

The ALCOBJ command does not allow the user to lock specific object types—for example, the User Profile (*USRPRF) objects (with MI object type code hex 08), and it can't lock internal objects (MI objects that are not visible at the operation system level). ALCOBJ also adds many limitations on what kinds of lock states can be allocated on specific object types. For example, ALCOBJ forbids allocating an *EXCL lock state on a Library (*LIB) object or a Device Description (*DEVD) object. Also, lock states except *EXCL can't be allocated on a Subsystem Description (*SBSD) object via ALCOBJ. These restrictions are also true for the DLCOBJ command.

However, the ability to allocate or deallocate any kind of lock state on any kind of MI object is sometimes necessary for an IBM i developer or administrator. For example, allocating a *SHRRD lock on a *SBSD object can prevent accidental deletion of the *SBSD object. Actually, that's the method used by the system to protect the subsystem descriptions of active subsystems. (Try issuing a Work with Object Lock (WRKOBJLCK) command upon the *SBSD of an active subsystem.)

This TechTip shows you how to create your own utility to lock/unlock what the ALCOBJ/DCLOBJ commands do not allow.

The LCKLCK Program

The example program called LCKLCK implements the tasks mentioned above. The working mechanism of the LCKLCK program is quite simple—issuing the LOCK or the UNLOCK MI instruction on an MI object on behalf of its caller. The LCKLCK program accepts the following parameters:

  • A system pointer to the target MI object to lock/unlock
  • CHAR(1) requested lock state
  • CHAR(1) flag that indicates whether a LOCK or UNLOCK MI instruction is to be issued on the target MI object

The source program (lcklck.rpgle) of LCKLCK is the following:


     * @file lcklck.rpgle


     * Lock/Unlock an MI object idendified by a system pointer.

     * @param [in] SYSPTR to the MI object

     * @param [in] Requested lock state

     * @param [in] Flag. 'U' = Unlock, anything else = Lock


     h dftactgrp(*no) actgrp('LCKLCK')

     d lock_request   ds                 qualified

     d       num_requests...

     d                               10i 0 inz(1)

     d       offset_lock_state...

     d                              5i 0 inz(32)

     d       time_out                 20u 0

     d       lock_opt                   2a     inz(x'4200')

     d       obj@                       *

     d       lock_state                 1a

     d                               15a

     * Lock request option related constants


     d                 c                   x'0000'


     d                 c                   x'4000'


   d                 c                   x'8000'

     d LOCK_WAIT_4EVER...

     d                 c                   x'0200'


     d                 c                   x'0000'


     d                  c                   x'0080'


     d                 c                   x'0000'


     d                 c                   x'0040'

     * The Lock Object (LOCK) MI instruction

     d lockobj         pr                 extproc('_LOCK')

     d       lock_request...

     d                                       likeds(lock_request)

     * The Unlock Object (UNLOCK) MI instruction

     d unlockobj       pr                 extproc('_UNLOCK')

     d       unlock_request...

     d                                       likeds(lock_request)

     * Prototype of the LCKLCK program

     d i_main         pr                 extpgm('LCKLCK')

     d       object                     *

     d    lock_state                 1a

     d       flag                       1a

     d i_main         pi

     d       object@                     *

     d       lock_state                 1a

     d       flag                       1a


           lock_request.lock_opt = %bitor(


             : LOCK_WAIT_4EVER

             : LOCK_SCOPED_TO_OBJ

             : LOCK_SCOPE_OBJ_MI_PROCESS );

           lock_request.obj@ = object@;

           lock_request.lock_state = lock_state;

           if flag = 'U';





           *inlr = *on;


An OMI version of the LCKLCK program (lcklck.emi) is also available as follows:


* @file lcklck.emi


* Lock/Unlock an MI object idendified by a system pointer.

* @param [in] SYSPTR to the MI object

* @param [in] Requested lock state

* @param [in] Flag. 'U' = Unlock, anything else = Lock


dcl spcptr obj@@ parm           ;

dcl spcptr lck-sts@ parm       ;

dcl spcptr flag@ parm           ;

dcl ol pl-main (




) parm ext                     ;

entry i-main(pl-main) ext       ;

dcl sysptr p-obj@ bas(obj@@)     ;

dcl dd p-lck-sts char(1) bas(lck-sts@) ;

dcl dd flag char(1) bas(flag@)       ;

dcl spcptr tmpl@ auto init(tmpl) ;

dcl dd tmpl char(64) auto       ;

       dcl dd num-requests bin(4) def(tmpl) pos(1) init(1) ;

       dcl dd off-lck-sts bin(2) def(tmpl) pos(5) init(32) ;

       dcl dd lck-opt char(2) def(tmpl) pos(15) init(x'4200') ; /* 01000010,00000000b */

         /* Lock request type = '01'. Synchronous request- Wait until all locks can be granted. */

         /* Time-out option = '1'. Wait indefinitely */

         /* Template extension specified = '0'. No template extension */

         /* Lock scope = '0'. Lock is scoped to the lock scope object type. */

         /* Lock scope object type = '0'. Process containing the current thread. */

       dcl sysptr obj@ def(tmpl) pos(17) ;

       dcl dd lck-sts char(1) def(tmpl) pos(33) ;

       cpybwp obj@, p-obj@   ;

       cpybla lck-sts, p-lck-sts ;

       cmpbla(b) flag, 'U' / neq(=+3) ;

       unlock tmpl@                 ;

        b         =+2                   ;

:       lock     tmpl@                 ;

:       rtx       *                     ;

pend                                   ;

Finally, to avoid the Object Domain or Hardware Storage Protection Violation (hex 4401) exception at security level 40 or above when locking/unlocking system domain objects, change the compiled LCKLCK program to system state by changing the program state field in the program header of LCKLCK from user state (hex 0001) to system state (hex 0080). At V5R4, the program state field is at offset hex 5C from the start of the program header.

Experiment with the LCKLCK Program

Now let's do a couple of experiments with the LCKLCK program. As a lock-anything utility, you will surely find more uses of the LCKLCK program. The following tiny ILE C program (oo08t1.c) accepts the name of a library (i.e., a context object) and then calls the LCKLCK program to acquire an *EXCL (i.e., LENR) lock state on the library.


* @file oo08t1.c


* Test of the LCKLCK program.


# include <stdlib.h>

# include <string.h>

# pragma linkage(LCKLCK, OS)

void LCKLCK(void **obj, char *lock_state, char *flag);

# pragma linkage(_RSLVSP2, builtin)

void _RSLVSP2(void**, void*);

int main(int argc, char *argv[]) {

void *ctx = NULL;

char lck_sts = 0x9;

char flag = 'L';

char rt[34] = {0};

char *lib = NULL;

if(argc < 2) {

   return -1;


lib = argv[1];

memcpy(rt, "\x04\x01", 2);

memset(rt + 2, 0x40, 30);

memcpy(rt + 2, lib, strlen(lib));

_RSLVSP2(&ctx, rt);

LCKLCK(&ctx, &lck_sts, &flag);

return 0;


Compile the OO08T1 program and call it to lock the LIBA library in job JOBA. Then try to move an object (say, *DTAQ #0A01#1) into LIBA in another job (say, JOBB) via a MOVOBJ command.



Now the Work with Object Locks display of a WRKOBJLCK #0A01#1 *DTAQ command issued from JOBA might look like the following:

Opt   Job         User         Lock     Status         Scope     Thread  

     JOBB         LJL         *SHRUPD   WAIT           *THREAD   00000966

     JOBA         LJL         *EXCL     HELD         *JOB            

This tells us that the Move Object (MOVOBJ) command (or more exactly, the Command Processing Program (CPP) of MOVOBJ, QSYS/QLIMVOBJ) requests a *SHRUPD (i.e., LSUP) lock state synchronously before actually moving an object from its containing library to a new library.

Now let's do another experiment to protect a subsystem description object from being deleted by other jobs. The following ILE C program (oo08t2.c) allocates a *SHRRD (i.e., LSRD) lock state on a specified *SBSD.


* @file oo08t2.c


* Test of LCKLCK program.


# include <stdlib.h>

# include <string.h>

# pragma linkage(LCKLCK, OS)

void LCKLCK(void **obj, char *lock_state, char *flag);

# pragma linkage(_RSLVSP2, builtin)

void _RSLVSP2(void**, void*);

int main(int argc, char *argv[]) {

void *spc1909 = NULL;

char lck_sts = 0x81;

char flag = 'L';

char rt[34] = {0};

char *sbsd = NULL;

if(argc < 2) {

   return -1;


sbsd = argv[1];

memcpy(rt, "\x19\x09", 2);

memset(rt + 2, 0x40, 30);

memcpy(rt + 2, sbsd, strlen(sbsd));

_RSLVSP2(&spc1909, rt);

LCKLCK(&spc1909, &lck_sts, &flag);

return 0;


Compile the OO08T2 program and call it to allocate a *SHRRD (LSRD) lock state on a *SBSD (say, DEC) in job JOBA. Then try to delete DEC in job JOBB via a DLTSBSD command.



Now the Work with Object Locks display of a WRKOBJLCK DEC *SBSD command issued from JOBA might look like the following:

Opt   Job         User         Lock     Status         Scope     Thread  

     JOBB         LJL         *EXCL     WAIT           *THREAD   00000966

     JOBA         LJL         *SHRRD     HELD           *JOB            

This tells us that the DLTSBSD command (the CPP of which is QSYS/QLIDLOB) needs to acquire an *EXCL (i.e., LENR) lock state before destroying the *SBSD. And the *EXCL lock state requested by JOBB will not be granted due to the *SHRRD lock stated allocated on the *SBSD object by JOBA. The DLTSBD command issued from JOBB will fail after a wait time-out interval.


Junlei Li

Junlei Li is a programmer from Tianjin, China, with 10 years of experience in software design and programming. Junlei Li began programming under i5/OS (formerly known as AS/400, iSeries) in late 2005. He is familiar with most programming languages available on i5/OS—from special-purpose languages such as OPM/ILE RPG to CL to general-purpose languages such as C, C++, Java; from strong-typed languages to script languages such as QShell and REXX. One of his favorite programming languages on i5/OS is machine interface (MI) instructions, through which one can discover some of the internal behaviors of i5/OS and some of the highlights of i5/OS in terms of operating system design.


Junlei Li's Web site is http://i5toolkit.sourceforge.net/, where his open-source project i5/OS Programmer's Toolkit (https://sourceforge.net/projects/i5toolkit/) is documented.



Support MC Press Online

$0.00 Raised:

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: