28
Sun, Apr
1 New Articles

TechTip: Using Qshell from RPG to Compare Two Files

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

Most recently, I had a need to write some unit test scripts in RPG to compare a dynamically generated XML file to an existing XML document to determine whether or not they were exactly the same. I could have gone the route of coding everything in RPG using the IFS APIs, but I decided against that as the functionality already exists in Qshell's cmp (compare) command. By using the cmp command, I was able to interface with an API that has been tested by thousands of other developers, thus giving me a high level of confidence that the API will appropriately compare one file to another. Reusing what already exists is true SOA in action and is what we developers need to do to retain investment in our machines and take them to the next level in a fraction of the time.

All right! Enough intro. Let's see some code!

An obvious approach to using the Qshell APIs would be to first wrap them in an RPG program for ease of use. The example program below shows different parameters used to invoke the QSH_cmpSame RPG subprocedure.

 

     H bnddir('GENBND') dftactgrp(*no)

      /copy mcpress,QSHCp

     D result          s               n
      /free

       result =
         QSH_cmpSame('/home/aaron/compare1.txt': '/home/aaron/compare2.txt');

       result =
         QSH_cmpSame('/home/aaron/compare1.txt': '/home/aaron/compare3.txt');

       result =
         QSH_cmpSame(
           '/qsys.lib/aaronlib.lib/mcpress.file/compare1.mbr':
           '/qsys.lib/aaronlib.lib/mcpress.file/compare2.mbr');

       result =
         QSH_cmpSame(
           '/qsys.lib/aaronlib.lib/mcpress.file/compare1.mbr':
           '/qsys.lib/aaronlib.lib/mcpress.file/compare3.mbr');

       *inlr = *on;

      /end-free

 

 

The first line of interest is the /copy, where we bring in the prototype to make the call to QSH_cmpSame. The result variable is declared as a Boolean and will hold the result of each call to QSH_cmpSame.

Moving on to the mainline, we can see that both IFS files and source members can be compared. I didn't think this would work with the source members, but I couldn't pass up the opportunity to try! And work it did! See the code below for the contents of compare1.txt, compare2.txt, compare3.txt, compare1.mbr, compare2.mbr, and compare3.mbr. You will notice that they are incredibly small files and source members, and they are such because it serves the purpose of brevity and example. Note that compare1.txt and compare2.txt are exactly the same, so we could show an example of an exact match. On the flip side, compare1.txt and compare3.txt are slightly different and will produce the *OFF result. The .mbr files follow this same approach.

 

/home/aaron/compare1.txt:
<xml>sometext</xml>

/home/aaron/compare2.txt:
<xml>sometext</xml>

/home/aaron/compare3.txt:
<xml>sometext and some more</xml>


/qsys.lib/aaronlib.lib/mcpress.file/compare1.mbr:
     D var             s             10a 

/qsys.lib/aaronlib.lib/mcpress.file/compare2.mbr:
     D var             s             10a 

/qsys.lib/aaronlib.lib/mcpress.file/compare3.mbr:
     D var             s             20a

The following code shows the contents of QSH_cmpSame. The first thing that needs to happen is the redirecting of what's called standard input, standard output, and standard error. Subroutine SetupIO opens files with specific descriptors to do the Qshell redirection. (Go to the LiveFireLabs site for a good, concise tutorial of UNIX file descriptors.) You could think of the redirecting being similar to an OVRDBF used to alter the member used when accessing a PF for I/O.

 

      //----------------------------------------------------------------------
      // Author: Aaron Bartell
      // Copyright 2007 MowYourLawn.com All Rights Reserved.
      //
      // Compile:
      //  CRTRPGMOD
      //    MODULE(MYLIB/QSHFN)
      //    SRCFILE(MYLIB/MCPRESS)
      //    SRCMBR(QSHFN)
      //
      //  CRTSRVPGM
      //    SRVPGM(MYLIB/QSHSV)
      //    MODULE(MYLIB/QSHFN)
      //    SRCFILE(MYLIB/MCPRESS)
      //
      // After creating the service program you will need to add it to the
      // binding directory of your choice and then reference that binding
      // directory below (i.e. replacing GENBND).
      //----------------------------------------------------------------------
     H nomain bnddir('QC2LE': 'GENBND')

      /copy mcpress,QSHCp

     D QzshSystem      PR            10I 0 extproc('QzshSystem')
     D   command                       *   value options(*string)

     D close           PR            10I 0 extproc('close')
     D  handle                       10I 0 value

     D unlink          PR            10i 0 extproc('unlink')
     D   path                          *   Value options(*string)

     D open            PR            10I 0 extproc('open')
     D  filename                       *   value options(*string)
     D  openflags                    10I 0 value
     D  mode                         10U 0 value options(*nopass)
     D  codepage                     10U 0 value options(*nopass)

     D stat            pr            10i 0 extproc('stat')
     D  filename                       *   value options(*string)
     D  statStruct                     *   value

     D                SDS
     D  dsJobNo              264    269A

     D stsBuff         ds                  align inz qualified
     D  perms                        10u 0
     D  fileID                       10u 0
     D  linkCount                     5u 0
     D  userIDNbr                    10u 0
     D  groupIdNbr                   10u 0
     D  bytesInFile                  10i 0
     D  timeLastAcc                  10i 0
     D  timeLastChg                  10i 0
     D  timeStsLastChg...
     D                               10i 0
     D  fileSysID                    10u 0
     D  blockSize                    10u 0
     D  allocBytes                   10u 0
     D  objectType                   11
     D  codePage                      5u 0
     D                               62
     D  generationID                 10u 0


      //------------------------------------------------------------------------
      // QSH_cmpSame
      //------------------------------------------------------------------------
     P QSH_cmpSame     B                   export
     D QSH_cmpSame     PI             1n
     D   pFile1                    1024a   varying const
     D   pFile2                    1024a   varying const

     D O_RDONLY        C                   1
     D O_WRONLY        C                   2
     D O_CREAT         C                   8
     D O_TRUNC         C                   64

     D cmd             S           2053A   varying
     D msg             S             52A
     D x               S             10I 0
     D rc1             s             10i 0
     D rc2             s             10i 0
     D result          s               n
     D stsBuff1        ds                  likeds(stsBuff)
     D stsBuff2        ds                  likeds(stsBuff)
      /FREE

       result = *off;
       exsr setupRedirect;

       if msg <> *blanks;
         return *off;
       endif;

       cmd = 'CMP ' + %trim(pFile1) + ' ' + %trim(pFile2);
       rc1 = QzshSystem(cmd);

       // Success is anything greater than -1.
       if rc1 < 0;
         return *off;
       endif;


       rc1 = stat('/tmp/stdout-'+dsJobNo: %addr(stsBuff1));
       rc2 = stat('/tmp/stderr-'+dsJobNo: %addr(stsBuff2));

       exsr closeRedirect;

       if stsBuff1.bytesInFile > 0 or
          stsBuff2.bytesInFile > 0 or
          rc1 < 0 or
          rc2 < 0;
         result = *off;
       else;
         result = *on;
       endif;

       return result;

       //------------------------------------------------------------------------
       // File descriptors 0, 1 & 2 are used by unix-environments for
       // stdin, stdout & stderr. Redirect those 3 descriptors to stream files.
       //------------------------------------------------------------------------
       begsr setupRedirect;
         for x = 0 to 2;
           callp close(x);
         endfor;

         msg = *blanks;

         // open up 0, 1, 2 as files.
         if open('/dev/qsh-stdin-null': O_RDONLY) <> 0;
           msg = 'Unable to redirect STDIN';
         endif;

         if open('/tmp/stdout-'+dsJobNo: O_WRONLY+O_CREAT+O_TRUNC: 511) <> 1;
           msg = 'Unable to redirect STDOUT';
         endif;

         if open('/tmp/stderr-'+dsJobNo: O_WRONLY+O_CREAT+O_TRUNC: 511) <> 2;
           msg = 'Unable to redirect STDERR';
         endif;

         // Error occurred!!!
         if msg <> *blanks;
           dsply '' ' ' msg;
           exsr closeRedirect;
         endif;

       endsr;

       //------------------------------------------------------------------------
       //  Close the descriptors opened by setupIO
       //------------------------------------------------------------------------
       begsr closeRedirect;

         for x = 0 to 2;
           callp close(x);
         endfor;

         unlink('/tmp/stdout-'+dsJobNo);
         unlink('/tmp/stderr-'+dsJobNo);

       endsr;
      /END-FREE

     P                 e

The second piece of interesting code is the composing of the CMP command and the subsequent calling of QzshSystem to process it. Exhaustive information on the QzshSystem API can be found here. But for the sake of layman conversation, it's simply an enabler of sorts that allows the execution of commands you would traditionally enter into a Qshell prompt interactively. To run an interactive Qshell session, simply enter STRQSH on the command line. You can find detailed information about the CMP here, but essentially, it simply does a byte-for-byte binary comparison of two files; and as I found out, it can also work in the QSYS.LIB side of the IFS.

The way this program determines success is by checking to see if any errors appeared in the standard out files or error files that were redirected to it earlier. This is done using the stat IFS API. If either file has content, then we know something out of the ordinary occurred during the comparison and *OFF should be returned. Run this program through debug and you can see what's in those files using DSPF '/tmp/stderr-999999', where 999999 is the job number.

The last order of action is to close all of the Qshell file descriptor redirects by executing sub routine CloseIO.

Additional References

Article: "TechTip: Qshell vs. PASE"
Article: "TechTip: Link Up with Qshell"
Article: "Exploring iSeries QSHELL"
Presentation:
"Qshell and OpenSSH for IBM System i"
IBM Information Center Web Page:
Using Qshell

Aaron Bartell

Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open-source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications andwww.litmis.comWith a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today's leading technologies, including Ruby on Rails, Node.js, Git for RPG source change management, and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today's modern application developers. Connect with Aaron via email atThis email address is being protected from spambots. You need JavaScript enabled to view it..

Aaron lives with his wife and five children in southern Minnesota. He enjoys the vast amounts of laughter that having a young family brings, along with camping and music. He believes there's no greater purpose than to give of our life and time to help others.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

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: