Process.h

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 
00003 //=============================================================================
00004 /**
00005  *  @file    Process.h
00006  *
00007  *  $Id: Process.h 78923 2007-07-17 18:22:51Z shuston $
00008  *
00009  *  @author Tim Harrison <harrison@cs.wustl.edu>
00010  */
00011 //=============================================================================
00012 
00013 #ifndef ACE_PROCESS_H
00014 #define ACE_PROCESS_H
00015 
00016 #include /**/ "ace/pre.h"
00017 
00018 #include /**/ "ace/ACE_export.h"
00019 
00020 #if !defined (ACE_LACKS_PRAGMA_ONCE)
00021 # pragma once
00022 #endif /* ACE_LACKS_PRAGMA_ONCE */
00023 
00024 #include "ace/Handle_Set.h"
00025 #include "ace/Global_Macros.h"
00026 #include "ace/os_include/sys/os_types.h"
00027 
00028 ACE_BEGIN_VERSIONED_NAMESPACE_DECL
00029 
00030 // Forward declaration
00031 class ACE_Time_Value;
00032 
00033 /**
00034  * @class ACE_Process_Options
00035  *
00036  * @brief Process Options
00037  *
00038  * This class controls the options passed to <CreateProcess> (or <fork>
00039  * and <exec>).
00040  * Notice that on Windows CE, creating a process merely means
00041  * instantiating a new process.  You can't set the handles (since
00042  * there's no stdin, stdout and stderr,) specify process/thread
00043  * options, set environment,...  So, basically, this class only
00044  * set the command line and nothing else.
00045  * Notice that on UNIX platforms, if the <setenv> is used, the
00046  * <spawn> is using the <execve> system call. It means that the
00047  * <command_line> should include a full path to the program file
00048  * (<execve> does not search the PATH).  If <setenv> is not used
00049  * then, the <spawn> is using the <execvp> which searches for the
00050  * program file in the PATH variable.
00051  */
00052 class ACE_Export ACE_Process_Options
00053 {
00054 public:
00055   enum
00056   {
00057     DEFAULT_COMMAND_LINE_BUF_LEN = 1024,
00058     // UNIX process creation flags.
00059 #if defined (ACE_WIN32)
00060     NO_EXEC = 0
00061 #else
00062     NO_EXEC = 1
00063 #endif /* ACE_WIN32 */
00064   };
00065 
00066 protected:
00067   // = Default settings not part of public Interface.
00068   //
00069   // @@todo These sizes should be taken from the appropriate
00070   // POSIX/system header files and/or defined dynamically.
00071   enum
00072   {
00073     MAX_COMMAND_LINE_OPTIONS = 128,
00074     ENVIRONMENT_BUFFER = 16 * 1024, // 16K
00075     MAX_ENVIRONMENT_ARGS = 512 //
00076   };
00077 
00078 public:
00079   /**
00080    * If @a inherit_environment == 1, the new process will inherit the
00081    * environment of the current process.  @a command_line_buf_len is the
00082    * max strlen for command-line arguments.
00083    */
00084   ACE_Process_Options (int inherit_environment = 1,
00085                        int command_line_buf_len = DEFAULT_COMMAND_LINE_BUF_LEN,
00086                        int env_buf_len = ENVIRONMENT_BUFFER,
00087                        int max_env_args = MAX_ENVIRONMENT_ARGS);
00088 
00089   /// Destructor.
00090   ~ACE_Process_Options (void);
00091 
00092   // = Methods to set process creation options portably.
00093 
00094   /**
00095    * Set the standard handles of the new process to the respective
00096    * handles.  If you want to affect a subset of the handles, make
00097    * sure to set the others to ACE_INVALID_HANDLE.  Returns 0 on
00098    * success, -1 on failure.
00099    */
00100   int set_handles (ACE_HANDLE std_in,
00101                    ACE_HANDLE std_out = ACE_INVALID_HANDLE,
00102                    ACE_HANDLE std_err = ACE_INVALID_HANDLE);
00103 
00104   /// Release the standard handles previously set with set_handles;
00105   void release_handles (void);
00106 
00107   /// @param format must be of the form "VARIABLE=VALUE".  There can not be
00108   /// any spaces between VARIABLE and the equal sign.
00109   int setenv (const ACE_TCHAR *format,
00110               ...);
00111 
00112   /**
00113    * Set a single environment variable, @a variable_name.  Since
00114    * different platforms separate each environment variable
00115    * differently, you must call this method once for each variable.
00116    * <format> can be any printf format string.  So options->setenv
00117    * ("FOO","one + two = %s", "three") will result in "FOO=one + two =
00118    * three".
00119    */
00120   int setenv (const ACE_TCHAR *variable_name,
00121               const ACE_TCHAR *format,
00122               ...);
00123 
00124   /// Same as above with argv format.  @a envp must be null terminated.
00125   int setenv (ACE_TCHAR *envp[]);
00126 
00127   /// Set the working directory for the process.  strlen of @a wd must
00128   /// be <= MAXPATHLEN.
00129   void working_directory (const char *wd);
00130 
00131 #if defined (ACE_HAS_WCHAR)
00132   /// wchar_t version of working_directory
00133   void working_directory (const wchar_t *wd);
00134 #endif /* ACE_HAS_WCHAR */
00135 
00136   /**
00137    * Set the command-line arguments.  @a format can use any printf
00138    * formats.  The first token in @a format should be the path to the
00139    * application.  This can either be a full path, relative path, or
00140    * just an executable name.  If an executable name is used, we rely
00141    * on the platform's support for searching paths.  Since we need a
00142    * path to run a process, this method *must* be called!  Returns 0
00143    * on success, -1 on failure.
00144    */
00145   int command_line (const ACE_TCHAR *format, ...);
00146 
00147 #if defined (ACE_HAS_WCHAR) && !defined (ACE_HAS_WINCE)
00148   /// Anti-TChar version of command_line ()
00149   int command_line (const ACE_ANTI_TCHAR *format, ...);
00150 #endif /* ACE_HAS_WCHAR && !ACE_HAS_WINCE */
00151 
00152   /// Same as above in argv format.  @a argv must be null terminated.
00153   int command_line (const ACE_TCHAR * const argv[]);
00154 
00155   /**
00156    * Specify the full path or relative path, or just the executable
00157    * name for the process. If this is set, then @a name will be used to
00158    * create the process instead of argv[0] set in the command
00159    * line. This is here so that you can supply something other than
00160    * executable name as argv[0].
00161    */
00162   void process_name (const ACE_TCHAR *name);
00163 
00164   /// Return the process_name.  If the <process_name(name)> set
00165   /// method is not called, this method will return argv[0].
00166   const ACE_TCHAR *process_name (void);
00167 
00168   /// Get the creation flags.
00169   u_long creation_flags (void) const;
00170 
00171   /**
00172    * Set the creation flags to affect how a new process is spawned.
00173    * The only ACE-defined flag is @c NO_EXEC which prevents the new process
00174    * from executing a new program image; this is a simple POSIX fork().
00175    * The @c NO_EXEC option has no affect on Windows; on other platforms where
00176    * a POSIX fork is not possible, specifying @c NO_EXEC will cause
00177    * ACE_Process::spawn() to fail.
00178    *
00179    * On Windows, the value of creation_flags is passed to the @c CreateProcess
00180    * system call as the value of the @c dwCreationFlags parameter.
00181    */
00182   void creation_flags (u_long);
00183 
00184   /// Current working directory.  Returns "" if nothing has been set.
00185   ACE_TCHAR *working_directory (void);
00186 
00187   /// Buffer of command-line options.  Returns a pointer to a buffer that
00188   /// contains the list of command line options.  Prior to a call to
00189   /// command_line_argv(), this is a single string of space separated
00190   /// arguments independent of which form of command_line() was used to
00191   /// create it.  After a call to command_line_argv(), this is a list of
00192   /// strings each terminated by '\0'.  [Note: spawn() will call
00193   /// command_line_argv().]  The total length of all these strings is the
00194   /// same as the single string in the prior case and can be obtained by
00195   /// providing max_len. @arg max_len, if non-zero, provides a location
00196   /// into which the total length of the command line buffer is returned.
00197   ACE_TCHAR *command_line_buf (int *max_len = 0);
00198 
00199   /**
00200    * argv-style command-line options.  Parses and modifies the string
00201    * created from <command_line_>.  All spaces not in quotes ("" or
00202    * '') are replaced with null (\0) bytes.  An argv array is built
00203    * and returned with each entry pointing to the start of
00204    * null-terminated string.  Returns { 0 } if nothing has been set.
00205    */
00206   ACE_TCHAR * const *command_line_argv (void);
00207 
00208   /**
00209    * Null-terminated buffer of null terminated strings.  Each string
00210    * is an environment assignment "VARIABLE=value".  This buffer
00211    * should end with two null characters.
00212    */
00213   ACE_TCHAR *env_buf (void);
00214 
00215   /// Get the process group.  On UNIX, these methods are used by the
00216   /// ACE_Process_Manager to manage groups of processes.
00217   pid_t getgroup (void) const;
00218 
00219   /// Set the process group.  On UNIX, these methods are used by the
00220   /// ACE_Process_Manager to manage groups of processes.
00221   pid_t setgroup (pid_t pgrp);
00222 
00223   /// Allows disabling of handle inheritence, default is TRUE.
00224   int handle_inheritence (void);
00225   void handle_inheritence (int);
00226 
00227   /// Cause the specified handle to be passed to a child process
00228   /// when it runs a new program image.
00229   /**
00230    * The specified handle value will be included in the spawned
00231    * process's command line as @arg +H @arg handle, if a new
00232    * program is spawned (always on Win32; else if NO_EXEC is not
00233    * set in creation flags).  The passed handle value will be
00234    * duplicated if on Win32 less capable than NT.
00235    * @return 0 if success, -1 if failure.
00236    */
00237   int pass_handle (ACE_HANDLE);
00238 
00239   /// Get a copy of the handles the ACE_Process_Options duplicated
00240   /// for the spawned process.
00241   /**
00242    * Any handles created through duplication of those passed into
00243    * @arg pass_handle are returned in @arg set.
00244    * @return 0 if there were no handles to return; 1 if there were.
00245    */
00246   int dup_handles (ACE_Handle_Set &set) const;
00247 
00248   /// Get a copy of the handles passed to the spawned process. This
00249   /// will be the set of handles previously passed to @arg pass_handle().
00250   /**
00251    * Any handles previously passed to @arg pass_handle are returned
00252    * in @arg set.
00253    * @return 0 if there were no handles to return; 1 if there were.
00254    */
00255   int passed_handles (ACE_Handle_Set &set) const;
00256 
00257   /// Set value for avoid_zombies (has no real effect except on *nix).
00258   void avoid_zombies (int);
00259 
00260   /// Get current value for avoid_zombies.
00261   int avoid_zombies (void);
00262 
00263 #if defined (ACE_WIN32)
00264   // = Non-portable accessors for when you "just have to use them."
00265 
00266   /// Used for setting and getting.
00267   ACE_TEXT_STARTUPINFO *startup_info (void);
00268 
00269   /// Get the process_attributes.  Returns NULL if
00270   /// set_process_attributes has not been set.
00271   LPSECURITY_ATTRIBUTES get_process_attributes (void) const;
00272 
00273   /// If this is called, a non-null process attributes is sent to
00274   /// CreateProcess.
00275   LPSECURITY_ATTRIBUTES set_process_attributes (void);
00276 
00277   /// Get the thread_attributes.  Returns NULL if set_thread_attributes
00278   /// has not been set.
00279   LPSECURITY_ATTRIBUTES get_thread_attributes (void) const;
00280 
00281   /// If this is called, a non-null thread attributes is sent to
00282   /// CreateProcess.
00283   LPSECURITY_ATTRIBUTES set_thread_attributes (void);
00284 
00285 #else /* All things not WIN32 */
00286 
00287   /// argv-style array of environment settings.
00288   ACE_TCHAR *const *env_argv (void);
00289 
00290   // = Accessors for the standard handles.
00291   ACE_HANDLE get_stdin (void) const;
00292   ACE_HANDLE get_stdout (void) const;
00293   ACE_HANDLE get_stderr (void) const;
00294 
00295   // = Set/get real & effective user & group id associated with user.
00296   int setreugid (const ACE_TCHAR* user);
00297   void setruid (uid_t id);
00298   void seteuid (uid_t id);
00299   void setrgid (uid_t id);
00300   void setegid (uid_t id);
00301   uid_t getruid (void) const;
00302   uid_t geteuid (void) const;
00303   uid_t getrgid (void) const;
00304   uid_t getegid (void) const;
00305 
00306   /**
00307    * Get the inherit_environment flag.
00308    */
00309   int inherit_environment (void) const;
00310 
00311   /**
00312    * Set the inherit_environment flag.
00313    */
00314   void inherit_environment (int nv);
00315 #endif /* ACE_WIN32 */
00316 protected:
00317 
00318 #if !defined (ACE_HAS_WINCE)
00319   /// Add @a assignment to environment_buf_ and adjust
00320   /// environment_argv_.  @a len is the strlen of @a assignment.
00321   int setenv_i (ACE_TCHAR *assignment, size_t len);
00322 
00323   /// Whether the child process inherits the current process
00324   /// environment.
00325   int inherit_environment_;
00326 #endif /* !ACE_HAS_WINCE */
00327 
00328   /// Default 0.
00329   u_long creation_flags_;
00330 
00331   /// Avoid zombies for spawned processes.
00332   int avoid_zombies_;
00333 
00334 #if defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)
00335   /// Helper function to grab win32 environment and stick it in
00336   /// environment_buf_ using this->setenv_i.
00337   void inherit_environment (void);
00338 
00339   /// Ensures once only call to inherit environment.
00340   int environment_inherited_;
00341 
00342   ACE_TEXT_STARTUPINFO startup_info_;
00343 
00344   /// Default TRUE.
00345   BOOL handle_inheritence_;
00346 
00347   /// Pointer to security_buf1_.
00348   LPSECURITY_ATTRIBUTES process_attributes_;
00349 
00350   /// Pointer to security_buf2_.
00351   LPSECURITY_ATTRIBUTES thread_attributes_;
00352 
00353   /// Data for process_attributes_.
00354   SECURITY_ATTRIBUTES security_buf1_;
00355 
00356   /// Data for thread_attributes_.
00357   SECURITY_ATTRIBUTES security_buf2_;
00358 
00359 #else /* !ACE_WIN32 */
00360   ACE_HANDLE stdin_;
00361   ACE_HANDLE stdout_;
00362   ACE_HANDLE stderr_;
00363 
00364   // = Real & effective user & group id's.
00365   //   These should be set to -1 to leave unchanged (default).
00366   uid_t ruid_;
00367   uid_t euid_;
00368   uid_t rgid_;
00369   uid_t egid_;
00370 #endif /* ACE_WIN32 */
00371 
00372 #if !defined (ACE_HAS_WINCE)
00373   /// Is 1 if stdhandles was called.
00374   int set_handles_called_;
00375 
00376   /// Pointer into environment_buf_.  This should point to the next
00377   /// free spot.
00378   size_t environment_buf_index_;
00379 
00380   /// Pointer to environment_argv_.
00381   int environment_argv_index_;
00382 
00383   /// Pointer to buffer of the environment settings.
00384   ACE_TCHAR *environment_buf_;
00385 
00386   /// Size of the environment buffer. Configurable
00387   size_t environment_buf_len_;
00388 
00389   /// Pointers into environment_buf_.
00390   ACE_TCHAR **environment_argv_;
00391 
00392   /// Maximum number of environment variables. Configurable
00393   int max_environment_args_;
00394 
00395   /// Maximum index of environment_argv_ buffer
00396   int max_environ_argv_index_;
00397 
00398   /// The current working directory.
00399   ACE_TCHAR working_directory_[MAXPATHLEN + 1];
00400 #endif /* !ACE_HAS_WINCE */
00401 
00402   /// Ensures command_line_argv is only calculated once.
00403   int command_line_argv_calculated_;
00404 
00405   /// Pointer to buffer of command-line arguments.  E.g., "-f foo -b bar".
00406   ACE_TCHAR *command_line_buf_;
00407 
00408   /// Pointer to copy of command-line arguments, which is needed when
00409   /// converting a command-line string into a command-line argv.
00410   ACE_TCHAR *command_line_copy_;
00411 
00412   /// Max length of command_line_buf_
00413   int command_line_buf_len_;
00414 
00415   /// Argv-style command-line arguments.
00416   ACE_TCHAR *command_line_argv_[MAX_COMMAND_LINE_OPTIONS];
00417 
00418   /// Process-group on Unix; unused on Win32.
00419   pid_t process_group_;
00420 
00421   /// Set of handles that were passed in pass_handle ().
00422   ACE_Handle_Set handles_passed_;
00423 
00424   /// Results of duplicating handles passed in pass_handle ().
00425   ACE_Handle_Set dup_handles_;
00426 
00427   /// Pathname for the process. Relative path or absolute path or just
00428   /// the program name.
00429   ACE_TCHAR process_name_[MAXPATHLEN + 1];
00430 };
00431 
00432 //class ACE_Process_Manager;
00433 
00434 /**
00435  * @class ACE_Process
00436  *
00437  * @brief Process
00438  *
00439  * A Portable encapsulation for creating new processes.
00440  * Notice that on UNIX platforms, if the <setenv> is used, the
00441  * <spawn> is using the <execve> system call. It means that the
00442  * <command_line> should include a full path to the program file
00443  * (<execve> does not search the PATH).  If <setenv> is not used
00444  * then, the <spawn> is using the <execvp> which searches for the
00445  * program file in the PATH variable.
00446  */
00447 class ACE_Export ACE_Process
00448 {
00449 public:
00450   friend class ACE_Process_Manager;
00451 
00452   /// Default construction.  Must use <ACE_Process::spawn> to start.
00453   ACE_Process (void);
00454 
00455   /// Destructor.
00456   virtual ~ACE_Process (void);
00457 
00458   /**
00459    * Called just before <ACE_OS::fork> in the <spawn>.  If this
00460    * returns non-zero, the <spawn> is aborted (and returns
00461    * ACE_INVALID_PID).  The default simply returns zero.
00462    */
00463   virtual int prepare (ACE_Process_Options &options);
00464 
00465   /**
00466    * Launch a new process as described by @a options. On success,
00467    * returns 1 if the option avoid_zombies is set, else returns the
00468    * process id of the newly spawned child. Returns -1 on
00469    * failure. This will be fixed in the future versions of ACE when
00470    * the process id of the child will be returned regardless of the option.
00471    */
00472   virtual pid_t spawn (ACE_Process_Options &options);
00473 
00474   /// Called just after <ACE_OS::fork> in the parent's context, if the
00475   /// <fork> succeeds.  The default is to do nothing.
00476   virtual void parent (pid_t child);
00477 
00478   /**
00479    * Called just after <ACE_OS::fork> in the child's context.  The
00480    * default does nothing.  This function is *not* called on Win32
00481    * because the process-creation scheme does not allow it.
00482    */
00483   virtual void child (pid_t parent);
00484 
00485   /// Called by a <Process_Manager> that is removing this Process from
00486   /// its table of managed Processes.  Default is to do nothing.
00487   virtual void unmanage (void);
00488 
00489   /**
00490    * Wait for the process we've created to exit.  If <status> != 0, it
00491    * points to an integer where the function store the exit status of
00492    * child process to.  If <wait_options> == <WNOHANG> then return 0
00493    * and don't block if the child process hasn't exited yet.  A return
00494    * value of -1 represents the <wait> operation failed, otherwise,
00495    * the child process id is returned.
00496    */
00497   pid_t wait (ACE_exitcode *status = 0,
00498               int wait_options = 0);
00499 
00500   /**
00501    * Timed wait for the process we've created to exit.  A return value
00502    * of -1 indicates that the something failed; 0 indicates that a
00503    * timeout occurred.  Otherwise, the child's process id is returned.
00504    * If <status> != 0, it points to an integer where the function
00505    * stores the child's exit status.
00506    *
00507    * @note On UNIX platforms this function uses <ualarm>, i.e., it
00508    * overwrites any existing alarm.  In addition, it steals all
00509    * <SIGCHLD>s during the timeout period, which will break another
00510    * <ACE_Process_Manager> in the same process that's expecting
00511    * <SIGCHLD> to kick off process reaping.
00512    */
00513   pid_t wait (const ACE_Time_Value &tv,
00514               ACE_exitcode *status = 0);
00515 
00516   /// Send the process a signal.  This is only portable to operating
00517   /// systems that support signals, such as UNIX/POSIX.
00518   int kill (int signum = SIGINT);
00519 
00520   /**
00521    * Terminate the process abruptly using <ACE::terminate_process>.
00522    * This call doesn't give the process a chance to cleanup, so use it
00523    * with caution...
00524    */
00525   int terminate (void);
00526 
00527   /// Return the process id of the new child process.
00528   pid_t getpid (void) const;
00529 
00530   /// Return the handle of the process, if it has one.
00531   ACE_HANDLE gethandle (void) const;
00532 
00533   /// Return 1 if running; 0 otherwise.
00534   int running (void) const;
00535 
00536   /// Return the Process' exit code.  This method returns the raw
00537   /// exit status returned from system APIs (such as <wait> or
00538   /// <waitpid>).  This value is system dependent.
00539   ACE_exitcode exit_code (void) const;
00540 
00541   /// Return the Process' return value.  This method returns the
00542   /// actual return value that a child process returns or <exit>s.
00543   int return_value (void) const;
00544 
00545   /// Close all the handles in the set obtained from the
00546   /// @arg ACE_Process_Options::dup_handles object used to spawn
00547   /// the process.
00548   void close_dup_handles (void);
00549 
00550   /// Close all the handles in the set obtained from the
00551   /// @arg ACE_Process_Options::passed_handles object used to spawn
00552   /// the process.
00553   void close_passed_handles (void);
00554 
00555 #if defined (ACE_WIN32)
00556   PROCESS_INFORMATION process_info (void);
00557 #endif /* ACE_WIN32 */
00558 
00559 private:
00560 
00561   // Disallow copying and assignment since we don't support this (yet).
00562   ACE_Process (const ACE_Process &);
00563   void operator= (const ACE_Process &);
00564 
00565 protected:
00566   /// Set this process' <exit_code_>.  ACE_Process_Manager uses this
00567   /// method to set the <exit_code_> after successfully waiting for
00568   /// this process to exit.
00569   void exit_code (ACE_exitcode code);
00570 
00571 #if defined (ACE_WIN32)
00572   PROCESS_INFORMATION process_info_;
00573 #else /* ACE_WIN32 */
00574   /// Process id of the child.
00575   pid_t child_id_;
00576 #endif /* ACE_WIN32 */
00577   ACE_exitcode exit_code_;
00578 
00579   /// Set of handles that were passed to the child process.
00580   ACE_Handle_Set handles_passed_;
00581   /// Handle duplicates made for the child process.
00582   ACE_Handle_Set dup_handles_;
00583 
00584 };
00585 
00586 
00587 /**
00588  * @class ACE_Managed_Process
00589  *
00590  * @brief A process easily managed by ACE_Process_Manager.
00591  *
00592  * @arg ACE_Managed_Process is just an @arg ACE_Process with an
00593  * @arg unmanage() method that deletes the instance.
00594  * This class is only valid for use as a dynamically-allocated object!
00595  */
00596 class ACE_Export ACE_Managed_Process : public ACE_Process
00597 {
00598 public:
00599 
00600   /// Cleanup by deleting @c this.
00601   virtual void unmanage (void);
00602 
00603 protected:
00604 
00605   /// Make sure that we're allocated dynamically!
00606   virtual ~ACE_Managed_Process (void);
00607 
00608 };
00609 
00610 ACE_END_VERSIONED_NAMESPACE_DECL
00611 
00612 #if defined (__ACE_INLINE__)
00613 #include "ace/Process.inl"
00614 #endif /* __ACE_INLINE__ */
00615 
00616 #include /**/ "ace/post.h"
00617 #endif /* ACE_PROCESS_H */

Generated on Sun Jan 27 12:05:35 2008 for ACE by doxygen 1.3.6