Sometimes it's useful to be able to get a list of the environment variables that have been set in a job. For example, when a program crashes, you might have a routine that dumps diagnostic information, such as the job log and a program dump. When you do that, it's often useful to also list the environment variables and their current settings. This is especially true in a CGI program in which environment variables control how the program is used.
Although IBM provides the WRKENVVAR command to let you see the variables interactively, IBM doesn't provide a command that retrieves all the variables that have been set. However, it's possible to get the list of variables by using a bit of pointer logic.
The key thing to understand is that IBM provides a pointer named "environ" that is used to keep track of the environment variables. This environ variable is simply an export from one of the service programs that IBM provides with the OS. You can easily import the value of this variable into your own RPG programs.
Another key thing to understand is that environment variables may (or may not) already be initialized in a given job. This depends on whether your program is the first one in the job to use them. Fortunately, IBM provides an API called Qp0zInitEnv() that you can use to initialize the environment if it hasn't already been initialized. Here's a simple example of retrieving the environment variables in a job from an RPG program:
H DFTACTGRP(*NO) ACTGRP(*NEW)
D QUILNGTX PR ExtPgm('QUILNGTX')
D text 65535a const options(*varsize)
D length 10i 0 const
D msgid 7a const
D qualmsgf 20a const
D errorCode 20i 0 const
D Qp0zInitEnv pr 10i 0 extproc('Qp0zInitEnv')
D environ s * import('environ')
D env s * dim(32767)
D based(environ)
D x s 10i 0
D data s 65535a varying
/free
Qp0zInitEnv();
for x = 1 to %elem(env);
if env(x) = *null;
leave;
endif;
data = %str(env(x));
QUILNGTX( data: %len(Data): *blanks: *blanks: 0);
endfor;
*inlr = *on;
/end-free
The QUILNGTX API is not related to environment variables—it's just a simple API that brings up a little "message window" on a 5250 display and shows you some text. I like to use it when I'm writing a simple proof-of-concept or test program, since it's an easy way to put a message on the screen.
A few key points about the code above:
In your situation, you might want to write the output to a file or to the spool instead of using QUILNGTX to display the variable. But hopefully you now understand the technique and can modify my code to write the output any way you like.
Good luck!