spawn()--Spawn Process


  Syntax
 #include <spawn.h>

 pid_t spawn( const char                *path,
              const int                 fd_count,   
              const int                 fd_map[],
              const struct inheritance  *inherit,  
              char * const              argv[],
              char * const              envp[]);

  Service Program Name: QP0ZSPWN

  Default Public Authority: *USE

  Threadsafe: Conditional; see Usage Notes.

The spawn() function creates a child process that inherits specific attributes from the parent. The attributes inherited by the child process are file descriptors, the signal mask, the signal action vector, and environment variables, among others.


Parameters

path
(Input) Specific path to an executable file that will run in the new (child) process. The path name is expected to be in the CCSID of the job.

See QlgSpawn()--Spawn Process (using NLS-enabled path name) for a description and an example of supplying the path in any CCSID.

fd_count
(Input) The number of file descriptors the child process can inherit. It can have a value from zero to the value returned from a call to sysconf(_SC_OPEN_MAX).

fd_map[]
(Input) An array that maps the parent process file descriptor numbers to the child process file descriptor numbers. If this value is NULL, it indicates simple inheritance. Simple inheritance means that the child process inherits all eligible open file descriptors of the parent process. In addition, the file descriptor number in the child process is the same as the file descriptor number in the parent process. Refer to Attributes Inherited for details of file descriptor inheritance.

inherit
(Input) A pointer to an area of type struct inheritance. If the pointer is NULL, an error occurs. The inheritance structure contains control information to indicate attributes the child process should inherit from the parent. The following is an example of the inheritance structure, as defined in the <spawn.h> header file:
struct inheritance {
                    flagset_t  flags;
                    int        pgroup;
                    sigset_t   sigmask;
                    sigset_t   sigdefault;
};

The flags field specifies the manner in which the child process should be created. Only the constants defined in <spawn.h> are allowed; otherwise, spawn() returns -1 with errno set to EINVAL. The allowed constants follow:


argv[]
(Input) An array of pointers to strings that contain the argument list for the executable file. The last element in the array must be the NULL pointer. If this parameter is NULL, an error occurs.

envp[]
(Input) An array of pointers to strings that contain the environment variable lists for the executable file. The last element in the array must be the NULL pointer. If this parameter is NULL, an error occurs.

Authorities

Authorization Required for spawn()



Return Value



Error Conditions

If spawn() is not successful, errno usually indicates one of the following errors. Under some conditions, errno could indicate an error other than those listed here.

[E2BIG]

Argument list too long.

[EACCES]

Permission denied.

An attempt was made to access an object in a way forbidden by its object access permissions.

The thread does not have access to the specified file, directory, component, or path.

If you are accessing a remote file through the Network File System, update operations to file permissions at the server are not reflected at the client until updates to data that is stored locally by the Network File System take place. (Several options on the Add Mounted File System (ADDMFS) command determine the time between refresh operations of local data.) Access to a remote file may also fail due to different mappings of user IDs (UID) or group IDs (GID) on the local and remote systems.

[EAPAR]

Possible APAR condition or hardware failure.

[EBADFUNC]

Function parameter in the signal function is not set.

A given file descriptor or directory pointer is not valid for this operation. The specified descriptor is incorrect, or does not refer to an open file.

[EBADNAME]

The object name specified is not correct.

[ECANCEL]

Operation canceled.

[ECONVERT]

Conversion error.

One or more characters could not be converted from the source CCSID to the target CCSID.

The specified path name is not in the CCSID of the job.

[EFAULT]

The address used for an argument is not correct.

In attempting to use an argument in a call, the system detected an address that is not valid.

While attempting to access a parameter passed to this function, the system detected an address that is not valid.

[EINVAL]

The value specified for the argument is not correct.

A function was passed incorrect argument values, or an operation was attempted on an object and the operation specified is not supported for that type of object.

An argument value is not valid, out of range, or NULL.

The flags field in the inherit parameter contains an invalid value.

[EIO]

Input/output error.

A physical I/O error occurred.

A referenced object may be damaged.

[ELOOP]

A loop exists in the symbolic links.

This error is issued if the number of symbolic links encountered is more than POSIX_SYMLOOP (defined in the limits.h header file). Symbolic links are encountered during resolution of the directory or path name.

[ENAMETOOLONG]

A path name is too long.

A path name is longer than PATH_MAX characters or some component of the name is longer than NAME_MAX characters while _POSIX_NO_TRUNC is in effect. For symbolic links, the length of the name string substituted for a symbolic link exceeds PATH_MAX. The PATH_MAX and NAME_MAX values can be determined using the pathconf() function.

[ENFILE]

Too many open files in the system.

A system limit has been reached for the number of files that are allowed to be concurrently open in the system.

The entire system has too many other file descriptors already open.

[ENOENT]

No such path or directory.

The directory or a component of the path name specified does not exist.

A named file or directory does not exist or is an empty string.

[ENOMEM]

Storage allocation request failed.

A function needed to allocate storage, but no storage is available.

There is not enough memory to perform the requested function.

[ENOTDIR]

Not a directory.

A component of the specified path name existed, but it was not a directory when a directory was expected.

Some component of the path name is not a directory, or is an empty string.

[ENOTSAFE]

Function is not allowed in a job that is running with multiple threads.

[ENOTSUP]

Operation not supported.

The operation, though supported in general, is not supported for the requested object or the requested arguments.

[ETERM]

Operation terminated.

[ENOSYSRSC]

System resources not available to complete request.

The child process failed to start. The maximum active jobs in a subsystem may have been reached. CHGSBSD and CHGJOBQE CL commands can be used to change the maximum active jobs.

[EUNKNOWN]

Unknown system state.

The operation failed because of an unknown system state. See any messages in the job log and correct any errors that are indicated, then retry the operation.


Usage Notes

  1. spawn() is threadsafe, except this function will fail and errno ENOTSAFE will be set if it is called in any of the following ways:

    • From a multithreaded process and path refers to a shell script that does not exist in a threadsafe file system.

  2. There are performance considerations when using spawn() and spawnp() concurrently among threads in the same process. spawn() and spawnp() serialize against other spawn() and spawnp() calls from other threads in the same process.

  3. The child process is enabled for signals. A side effect of this function is that the parent process is also enabled for signals if it was not enabled for signals before this function was called.

  4. If this function is called from a program running in user state and it specifies a system-domain program as the executable program for the child process, an exception occurs. In this case, spawn() returns the process ID of the child process. On a subsequent call to wait() or waitpid(), the status information returned indicates that an exception occurred in the child process.

  5. The program that will be run in the child process must be either a program object in the QSYS.LIB file system or an independent ASP QSYS.LIB file system (*PGM object) or a shell script (see About Shell Scripts). The syntax of the name of the file to run must be the proper syntax for the file system in which the file resides. For example, if the program MYPROG resides in the QSYS.LIB file system and in library MYLIB, the specification for spawn(). would be the following:
       /QSYS.LIB/MYLIB.LIB/MYPROG.PGM
    

    See QlgSpawn()--Spawn Process (using NLS-enabled path name) for an example specifying the program using the Qlg_Path_Name_T structure. The Qlg_Path_Name_T structure is supported by QlgSpawn() and allows the program name to be specified in any CCSID.

    Note: For more information about path syntaxes for the different file systems, see the Integrated file system information in the Files and file systems topic.

  6. Spawned child processes are batch jobs or prestart jobs. As such, they do not have the ability to do 5250-type interactive I/O.

  7. Spawned child processes that are IBM i prestart jobs are similar to batch jobs. Due to the nature of prestart jobs, only the following IBM i-specific attributes are explicitly inherited in a child process when you use prestart jobs:

    • Library list
    • Language identifier
    • Country or region identifier
    • Coded character set identifier
    • Default coded character set identifier
    • Locale (as specified in the user profile)

    The child process has the same user profile as the calling thread. However, the IBM i job attributes come from the job description specified for the prestart job entry, and the run attributes come from the class that is associated with the IBM i subsystem used for the prestart job entry.

    Notes:

    1. The prestart job entry QP0ZSPWP is used with prestart jobs that will not be creating threads. The prestart job entry QP0ZSPWT is used with prestart jobs that will allow multiple threads. Both types of prestart jobs may be used in the same subsystem. The prestart job entry must be defined for the subsystem that the spawn() parent process runs under in order for it to be used.

    2. The following example defines a prestart job entry (QP0ZSPWP) for use by spawn() under the subsystem QINTER. The spawn() API must have the SPAWN_SETPJ_NP flag set (but not SPAWN_SETTHREAD_NP) in order to use these prestart jobs:
      ADDPJE SBSD(QSYS/QINTER) PGM(QSYS/QP0ZSPWP)
             INLJOBS(20) THRESHOLD(5) ADLJOBS(5)
             JOBD(QGPL/QDFTJOBD) MAXUSE(1)
             CLS(QGPL/QINTER)
      
    3. The following example defines a prestart job entry (QP0ZSPWT) that will create prestart jobs that are multithread capable for use by spawn() under the subsystem QINTER. The spawn() API must have both SPAWN_SETPJ_NP and SPAWN_SETTHREAD_NP flags set in order to use these prestart jobs. Also, the JOBD parameter must be a job description that allows multiple threads as follows:
      ADDPJE SBSD(QSYS/QINTER) PGM(QSYS/QP0ZSPWT)
             INLJOBS(20) THRESHOLD(5) ADLJOBS(5)
             JOBD(QSYS/QAMTJOBD) MAXUSE(1)
             CLS(QGPL/QINTER)
      

    Refer to the Work Management topic for complete details on prestart jobs.

  8. Shell scripts are allowed for the child process. If a shell script is specified, the appropriate shell interpreter program is called. The shell script must be a text file and must contain the following format on the first line of the file:
       #!interpreter_path <options>
    

    where interpreter_path is the path to the shell interpreter program.

    If the calling process is multithreaded, path (the first parameter to spawn()) must reference a threadsafe file system.

    spawn() calls the shell interpreter, passing in the shell options and the arguments passed in as a parameter to spawn(). The argument list passed into the shell interpreter will look like Arguments to Shell Interpreter.

    Arguments to Shell Interpreter
    Arguments to Shell Interpreter

    See About Shell Scripts for an example using spawn() and shell scripts.

  9. Only programs that expect arguments as null-terminated character strings can be spawned. The program that is run in the child process is called at it's initial entry point. The arguments explicitly passed to the program start with element argv[1] of the argv[] parameter that was specified during the call to spawn(). The program language type determines how the arguments passed are seen by that program. For example, if the program language type is ILE C or ILE C++, the linkage can be described as:
      int main(int argc, char *argv[])
      {
      }
    

    where the following are true:

    • argc is the number of arguments in argv[].
    • argv[] is an array of arguments represented as null-terminated character strings.
    • The last entry in the array is NULL.
    • The first element in the array, argv[0], is automatically set to the name of the program. Any value specified for argv[0] during the call to spawn() will be overwritten.
    • The remaining argv[] elements, if any, will correspond directly to the argv[] elements specified during the call to spawn().

    The maximum number of arguments that can be specified is dependent on the following:

    • The maximum number of parameters allowed for the program that is run in the child process, as seen by the DSPPGM CL command. Some programs allow up to 65 535 parameters, while others may only allow up to 255 parameters. The value of SPAWN_MAX_NUM_ARGS is 255, in order to maintain compatibility with programs that only allow up to 255 parameters. If the maximum number is exceeded, spawn() returns -1 with errno set to E2BIG.
    • The total size required for containing the arguments, which includes the array of pointers to strings, and the total size of all the strings. The total size is limited to approximately 16 500 000 bytes. If the total size is exceeded, spawn() returns -1 with errno set to ENOMEM.

  10. The child process does not inherit any of the environment variables of the parent process. That is, the default environment variable environment is empty. If the child process is to inherit all the parent process' environment variables, the extern variable environ can be used as the value for envp[] when spawn() is called. If a specific set of environment variables is required in the child process, the user must build the envp[] array with the "name=value" strings. In the child process, spawn() does the equivalent of a putenv() on each element of the envp[] array. Then the extern variable environ will be set and available to the child process' program.

    Note: If the user of spawn() specifies the extern variable environ as the envp[] parameter, the user must successfully call one of the following APIs before calling spawn():

    • getenv()
    • putenv()
    • Qp0zGetEnv()
    • Qp0zInitEnv()
    • Qp0zPutEnv()

    The extern variable environ is not initialized until one of these APIs is called in the current activation group. If environ is used in a call to spawn() without first calling one of these APIs, spawn() returns an error.

  11. IBM i handles stdin, stdout, and stderr differently than most UNIX® systems. On most UNIX systems, stdin, stdout, and stderr have file descriptors 0, 1, and 2 reserved and allocated for them. On IBM i, this is not the case. There are two ramifications of this difference:

    1. File descriptor 0, 1, and 2 are allocated to the first three files that have descriptors allocated to them. If an application writes to file descriptor 1 assuming it is stdout, the result will not be as expected.

    2. Any API that assumes stdin, stdout, and stderr are file descriptors 0, 1, and 2 will not behave as expected.

    Users and applications can enable descriptor-based standard I/O for child processes by setting environment variable QIBM_USE_DESCRIPTOR_STDIO to the value Y in the child process. This can be accomplished on the call to spawn() by either of the following:

    1. Specifying the extern variable environ as the envp[] parameter. This assumes that the QIBM_USE_DESCRIPTOR_STDIO environment variable exists in the calling process.

      The environment variable can be set by using one of the following:

      • API putenv("QIBM_USE_DESCRIPTOR_STDIO=Y");
      • Command ADDENVVAR ENVVAR(QIBM_USE_DESCRIPTOR_STDIO) VALUE(Y)
      • Command CHGENVVAR ENVVAR(QIBM_USE_DESCRIPTOR_STDIO) VALUE(Y)

    2. Explicitly include "QIBM_USE_DESCRIPTOR_STDIO=Y" in the user-defined envp[] array with the "name=value" strings.

    If you enable descriptor-based standard I/O for child processes, file descriptors 0, 1, and 2 are automatically used for stdin, stdout, and stderr, respectively. However, spawn() must be called using a fd_map that has file descriptors 0, 1, and 2 properly allocated. See About Shell Scripts for an example that enables descriptor-based standard I/O for a child process. Refer to the WebSphere® Development Studio: ILE C/C++ Programmer's GuideLink to PDF for complete details on this support.

  12. Spawn users have a facility to aid in debugging child processes.

    To help the user start a debug session (when spawn() is the mechanism used to start the process), the user sets the environment variable QIBM_CHILD_JOB_SNDINQMSG.

    If the environment variable is assigned a numerical value, it indicates the number of descendent levels that will be enabled for debugging. This support can be used to debug applications that create children, grandchildren, great-grandchildren, and so forth. When the environment variable has a value of 1, it enables debugging of all subsequent child processes. A value of 2 enables debugging of all subsequent child processes and grandchild processes.

    When the environment variable has a value less than or equal to 0, or any non-numerical value, debugging will not occur.

    Here are the steps a user would take to debug an application by using spawn():

    Assume the user wants to debug child processes in an application called CHILDAPP found in library MYAPPLIB.

    • Set the QIBM_CHILD_JOB_SNDINQMSG environment variable to 1.

      The environment variable can be set by using one of the following:

      • API putenv("QIBM_CHILD_JOB_SNDINQMSG=1");
      • Command ADDENVVAR ENVVAR(QIBM_CHILD_JOB_SNDINQMSG) VALUE(1)
      • Command CHGENVVAR ENVVAR(QIBM_CHILD_JOB_SNDINQMSG) VALUE(1)

    • Call or run the application that specifies /QSYS.LIB/MYAPPLIB.LIB/CHILDAPP.PGM as the pathon the spawn() invocation. CHILDAPP will start running, send a CPAA980 *INQUIRY message to the user's message queue, and then will block, waiting for a reply to the message. Issue a Work with Active Jobs (WRKACTJOB) command and find the CHILDAPP in a MSGW job status. Option 7 (Display message) performed against this job will display the CPAA980 *INQUIRY message that was sent. As part of this message, the Qualified Job Name will be displayed in the proper format to pass to the Start Service Job (STRSRVJOB) command (for example, 145778/RANDYR/CHILDAPP).

      Note: Alternatively, a Display Messages (DSPMSG) command can be issued for the user, and the output searched for the specific CPAA980 *INQUIRY message.

      Note: If the job's inquiry message reply specifies using the default message reply, the child process will not block since the default reply for the CPAA980 *INQUIRY message is G.

    • Issue a Start Service Job against the child process: STRSRVJOB JOB(145778/RANDYR/CHILDAPP).

    • Issue a Start Debug Command: STRDBG PGM(MYAPPLIB/CHILDAPP).

    • Set whatever breakpoints are needed in CHILDAPP. When ready to continue, find the CPAA980 message and reply with G. This will unblock CHILDAPP, which allows it to run until a breakpoint is reached, at which time CHILDAPP will again stop.

      Note: If you reply with C to the CPAA980 message, the child process is ended before the child process' program ever receives control. In this case, on a subsequent call to wait() or waitpid(), the status information returned indicates WIFEXCEPTION(), which evaluates to a nonzero value, and WEXCEPTNUMBER() will evaluate to 0.

    • The application is now stopped at a breakpoint and debugging can proceed.

  13. By default, the child's IBM i simple job name is derived directly from the path parameter. If path is a symbolic link to another object, the IBM i simple job name is derived from the symbolic link itself. For example, if path was set to /QSYS.LIB/MYLIB.LIB/CHILD.PGM, the child's IBM i simple job name would be CHILD. If /usr/bin/daughter was a symbolic link to /QSYS.LIB/MYLIB.LIB/CHILD.PGM and path was set to /usr/bin/daughter, the child's IBM i simple job name would be DAUGHTER.

    If SPAWN_SETJOBNAMEPARENT_NP is set in inherit.flags, the child's IBM i simple job name would be the same as the parent's IBM i simple job name.

    If SPAWN_SETJOBNAMEARGV_NP is set in inherit.flags, the null-terminated character string represented by argv[0] of the argv[] parameter will be used to derive the child's IBM i simple job name. The name can be up to 10 characters, must be uppercase, and must contain only those characters allowed for an IBM i job name. However, a period (.) is not considered a valid character. For example, if path was set to /QSYS.LIB/MYLIB.LIB/CHILD.PGM, SPAWN_SETJOBNAMEARGV_NP was set ON, and argv[0] was set to SON, the child's IBM i simple job name would be SON. If the first character of the name is invalid, the path will be used. If any of the remaining characters of the name are invalid, the valid characters up to that point will be used.

  14. The _NP used at the end of certain flag names, that can be specified for the flags field of the inherit parameter, indicate the flag is a non-standard, IBM i-platform-specific extension to the inheritance structure. Applications that wish to avoid using platform-specific extensions should not use these flags.
  15. The child process has an associated process ID, which uses system resources. Those resources will remain in use, even after the child process has ended. In order to ensure those resources are reclaimed, the parent process should either successfully call wait() or waitpid(), or the parent process should end.

Attributes Inherited

The child process inherits the following POSIX attributes from the parent:

  1. File descriptor table (mapped according to fd_map).

    Note: The following file descriptor table information does not apply to any of the scan descriptors which are created by the thread executing one of the scan-related exit programs (or any of its created threads). See Integrated File System Scan on Open Exit Programs and Integrated File System Scan on Close Exit Programs for more information.

    • If fd_map is NULL, all file descriptors are inherited without being reordered.

      Note: File descriptors that have the FD_CLOEXEC file descriptor flag set are not inherited. File descriptors that are created as a result of the opendir() API (to implement open directory streams) are not inherited.

    • If fd_map is not NULL, it is a mapping from the file descriptor table of the parent process to the file descriptor table of the child process. fd_count specifies the number of file descriptors the child process will inherit. Except for those file descriptors designated by SPAWN_FDCLOSED, file descriptor i in the child process is specified by fd_map[i]. For example, fd_map[5]= 7 sets the child process' file descriptor 5 to the parent process' file descriptor 7. File descriptors fd_count through OPEN_MAX are closed in the child process, as are any file descriptors designated by SPAWN_FDCLOSED.

      Note: File descriptors that are specified in the fd_map array are inherited even if they have the FD_CLOEXEC file descriptor flag set. After inheritance, the FD_CLOEXEC flag in the child process' file descriptor is cleared.

    • For files descriptors that remain open, no attributes are changed.

    • If a file descriptor refers to an open instance in a file system that does not support file descriptors in two different processes pointing to the same open instance of a file, the file descriptor is closed in the child process.

      Only open files managed by the Root, QOpenSys, or user-defined file systems support inheritance of their file descriptors. All other file systems will have their file descriptors closed in the child process.

  2. Process group ID

    • If inherit.flags is set to SPAWN_SETPGROUP, the child process group ID is set to the value in inherit.pgroup.

      Note: IBM i does not support the ability to set the process group ID for the child process to a user-specified group ID. This is a deviation from the POSIX standard.

    • If inherit.pgroup is set to SPAWN_NEWPGROUP, the child process is put in a new process group with a process group ID equal to the process ID.

    • If inherit.pgroup is not set to SPAWN_NEWPGROUP, the child process inherits the process group of the parent process.

    If the process group that the child process is attempting to join has received the SIGKILL signal, the child process is ended.

  3. Real user ID of the calling thread.

  4. Real group ID of the calling thread.

  5. Supplementary group IDs (group profile list) of the calling thread.

  6. Current working directory of the parent process.

  7. Root directory of the parent process.

  8. File mode creation mask of the parent process.

  9. Signal mask of the calling thread, except if the SPAWN_SETSIGMASK flag is set in inherit.flags. Then the child process will initially have the signal mask specified in inherit.mask.

  10. Signal action vector, as determined by the following:

    • If the SPAWN_SETSIGDEF flag is set in inherit.flags, the signal specified in inherit.sigdefault is set to the default actions in the child process. Signals set to the default action in the parent process are set to the default action in the child process.

    • Signals set to be caught in the parent process are set to the default action in the child process.

    • Signals set to be ignored in the parent process are set to ignore in the child process, unless set to default by the above rules.

  11. Priority of the parent process.

    Note: IBM i prestart jobs do not inherit priority.

  12. Scheduling policy (the IBM i scheduling policy) of the parent process.

  13. IBM i-specific attributes of the parent, such as job attributes, run attributes, library list, and user profile.

    Note: IBM i prestart jobs inherit a subset of IBM i-specific attributes.

  14. Resource limits of the parent process.


Related Information


Example

For an example of using this function, see Example: Using process-related APIs in the Examples: APIs and exit programs topic.


API introduced: V3R6

[ Back to top | UNIX-Type APIs | APIs by category ]