Document return values
[ACE_TAO.git] / ACE / ace / Process.h
blob70aa7c2f0d306b3f6e6c48da8bf51622d20ef7ad
1 // -*- C++ -*-
3 //=============================================================================
4 /**
5 * @file Process.h
7 * @author Tim Harrison <harrison@cs.wustl.edu>
8 */
9 //=============================================================================
11 #ifndef ACE_PROCESS_H
12 #define ACE_PROCESS_H
14 #include /**/ "ace/pre.h"
16 #include /**/ "ace/ACE_export.h"
18 #if !defined (ACE_LACKS_PRAGMA_ONCE)
19 # pragma once
20 #endif /* ACE_LACKS_PRAGMA_ONCE */
22 #include "ace/Handle_Set.h"
23 #include "ace/Global_Macros.h"
24 #include "ace/os_include/sys/os_types.h"
26 ACE_BEGIN_VERSIONED_NAMESPACE_DECL
28 // Forward declaration
29 class ACE_Time_Value;
31 /**
32 * @class ACE_Process_Options
34 * @brief Process Options
36 * This class controls the options passed to <CreateProcess> (or <fork>
37 * and <exec>).
38 * Notice that on UNIX platforms, if the <setenv> is used, the
39 * <spawn> is using the <execve> system call. It means that the
40 * <command_line> should include a full path to the program file
41 * (<execve> does not search the PATH). If <setenv> is not used
42 * then, the <spawn> is using the <execvp> which searches for the
43 * program file in the PATH variable.
45 class ACE_Export ACE_Process_Options
47 public:
48 enum
50 DEFAULT_COMMAND_LINE_BUF_LEN = 1024,
51 // UNIX process creation flags.
52 #if defined (ACE_WIN32)
53 NO_EXEC = 0
54 #else
55 NO_EXEC = 1
56 #endif /* ACE_WIN32 */
59 protected:
60 // = Default settings not part of public Interface.
62 /// @todo These sizes should be taken from the appropriate
63 /// POSIX/system header files and/or defined dynamically.
64 enum
66 MAX_COMMAND_LINE_OPTIONS = 128,
67 ENVIRONMENT_BUFFER = 16 * 1024, // 16K
68 MAX_ENVIRONMENT_ARGS = 512 //
71 public:
72 /**
73 * If @a inherit_environment == true, the new process will inherit the
74 * environment of the current process. @a command_line_buf_len is the
75 * max strlen for command-line arguments.
77 ACE_Process_Options (bool inherit_environment = true,
78 size_t command_line_buf_len = DEFAULT_COMMAND_LINE_BUF_LEN,
79 size_t env_buf_len = ENVIRONMENT_BUFFER,
80 size_t max_env_args = MAX_ENVIRONMENT_ARGS,
81 size_t max_cmdline_args = MAX_COMMAND_LINE_OPTIONS);
83 /// Destructor.
84 ~ACE_Process_Options ();
86 // = Methods to set process creation options portably.
88 /**
89 * Set the standard handles of the new process to the respective
90 * handles. If you want to affect a subset of the handles, make
91 * sure to set the others to ACE_INVALID_HANDLE.
93 * @note Any handle passed as ACE_INVALID_HANDLE will be changed to
94 * a duplicate of the current associated handle. For example, passing
95 * ACE_INVALID_HANDLE for @a std_in will cause ACE_STDIN to be
96 * duplicated and set in this object.
98 * @note Windows: The implementation of set_handles() uses DuplicateHandle
99 * on Windows. DuplicateHandle cannot be used to pass a socket handle
100 * on Windows. Socket handles require an alternate mechanism to pass;
101 * see http://msdn.microsoft.com/en-us/library/ms741565(v=VS.85).aspx
103 * @return 0 on success, -1 on failure.
105 int set_handles (ACE_HANDLE std_in,
106 ACE_HANDLE std_out = ACE_INVALID_HANDLE,
107 ACE_HANDLE std_err = ACE_INVALID_HANDLE);
109 /// Release the standard handles previously set with set_handles;
110 void release_handles ();
112 #ifndef ACE_LACKS_VA_FUNCTIONS
113 /// @param format must be of the form "VARIABLE=VALUE". There can not be
114 /// any spaces between VARIABLE and the equal sign.
115 int setenv (const ACE_TCHAR *format,
116 ...)
117 #if !defined (ACE_USES_WCHAR)
118 ACE_GCC_FORMAT_ATTRIBUTE (printf, 2, 3)
119 #endif /* !ACE_USES_WCHAR */
123 * Set a single environment variable, @a variable_name. Since
124 * different platforms separate each environment variable
125 * differently, you must call this method once for each variable.
126 * @a format can be any printf format string. So options->setenv
127 * ("FOO","one + two = %s", "three") will result in "FOO=one + two =
128 * three".
130 int setenv (const ACE_TCHAR *variable_name,
131 const ACE_TCHAR *format,
132 ...)
133 #if !defined (ACE_USES_WCHAR)
134 ACE_GCC_FORMAT_ATTRIBUTE (printf, 3, 4)
135 #endif /* !ACE_USES_WCHAR */
137 #endif // ACE_LACKS_VA_FUNCTIONS
139 /// Same as above with argv format. @a envp must be null terminated.
140 int setenv (ACE_TCHAR *envp[]);
142 /// Set the working directory for the process. strlen of @a wd must
143 /// be <= MAXPATHLEN.
144 void working_directory (const char *wd);
146 #if defined (ACE_HAS_WCHAR)
147 /// wchar_t version of working_directory
148 void working_directory (const wchar_t *wd);
149 #endif /* ACE_HAS_WCHAR */
151 #ifndef ACE_LACKS_VA_FUNCTIONS
153 * Set the command-line arguments. @a format can use any printf
154 * formats. The first token in @a format should be the path to the
155 * application. This can either be a full path, relative path, or
156 * just an executable name. If an executable name is used, we rely
157 * on the platform's support for searching paths. Since we need a
158 * path to run a process, this method *must* be called! Returns 0
159 * on success, -1 on failure.
161 int command_line (const ACE_TCHAR *format, ...)
162 #if !defined (ACE_USES_WCHAR)
163 ACE_GCC_FORMAT_ATTRIBUTE (printf, 2, 3)
164 #endif /* !ACE_USES_WCHAR */
167 #if defined (ACE_HAS_WCHAR)
168 /// Anti-TChar version of command_line ()
169 int command_line (const ACE_ANTI_TCHAR *format, ...);
170 #endif /* ACE_HAS_WCHAR */
171 #endif // ACE_LACKS_VA_FUNCTIONS
173 /// Same as above in argv format. @a argv must be null terminated.
174 int command_line (const ACE_TCHAR * const argv[]);
177 * Specify the full path or relative path, or just the executable
178 * name for the process. If this is set, then @a name will be used to
179 * create the process instead of argv[0] set in the command
180 * line. This is here so that you can supply something other than
181 * executable name as argv[0].
183 void process_name (const ACE_TCHAR *name);
185 /// Return the process_name. If the <process_name(name)> set
186 /// method is not called, this method will return argv[0].
187 const ACE_TCHAR *process_name ();
189 /// Get the creation flags.
190 u_long creation_flags () const;
193 * Set the creation flags to affect how a new process is spawned.
194 * The only ACE-defined flag is @c NO_EXEC which prevents the new process
195 * from executing a new program image; this is a simple POSIX fork().
196 * The @c NO_EXEC option has no affect on Windows; on other platforms where
197 * a POSIX fork is not possible, specifying @c NO_EXEC will cause
198 * ACE_Process::spawn() to fail.
200 * On Windows, the value of creation_flags is passed to the @c CreateProcess
201 * system call as the value of the @c dwCreationFlags parameter.
203 void creation_flags (u_long);
205 /// Current working directory. Returns "" if nothing has been set.
206 ACE_TCHAR *working_directory ();
208 /// Buffer of command-line options. Returns a pointer to a buffer that
209 /// contains the list of command line options. Prior to a call to
210 /// command_line_argv(), this is a single string of space separated
211 /// arguments independent of which form of command_line() was used to
212 /// create it. After a call to command_line_argv(), this is a list of
213 /// strings each terminated by '\0'. [Note: spawn() will call
214 /// command_line_argv().] The total length of all these strings is the
215 /// same as the single string in the prior case and can be obtained by
216 /// providing max_len. @arg max_len, if non-zero, provides a location
217 /// into which the total length of the command line buffer is returned.
218 ACE_TCHAR *command_line_buf (size_t *max_len = 0);
221 * argv-style command-line options. Parses and modifies the string
222 * created from <command_line_>. All spaces not in quotes ("" or
223 * '') are replaced with null (\0) bytes. An argv array is built
224 * and returned with each entry pointing to the start of
225 * null-terminated string. Returns { 0 } if nothing has been set.
227 ACE_TCHAR * const *command_line_argv ();
230 * Null-terminated buffer of null terminated strings. Each string
231 * is an environment assignment "VARIABLE=value". This buffer
232 * should end with two null characters.
234 ACE_TCHAR *env_buf ();
236 /// Get the process group. On UNIX, these methods are used by the
237 /// ACE_Process_Manager to manage groups of processes.
238 pid_t getgroup () const;
240 /// Set the process group. On UNIX, these methods are used by the
241 /// ACE_Process_Manager to manage groups of processes.
242 pid_t setgroup (pid_t pgrp);
244 /// Allows disabling of handle inheritance, default is TRUE.
246 /// @remarks @b Windows: the handle_inheritance value is passed as the
247 /// bInheritHandles value to the CreateProcess() system function. Therefore,
248 /// if you redirect standard input, output, or error via
249 /// ACE_Process_Options::set_handles() you must not call
250 /// handle_inheritance(false). Doing so will prevent the duplicated handles
251 /// from surviving in the created process.
252 int handle_inheritance ();
253 void handle_inheritance (int);
255 /// Cause the specified handle to be passed to a child process
256 /// when it runs a new program image.
258 * The specified handle value will be included in the spawned
259 * process's command line as @arg +H @arg handle, if a new
260 * program is spawned (always on Win32; else if NO_EXEC is not
261 * set in creation flags). The passed handle value will be
262 * duplicated if on Win32 less capable than NT.
263 * @return 0 if success, -1 if failure.
265 int pass_handle (ACE_HANDLE);
267 /// Get a copy of the handles the ACE_Process_Options duplicated
268 /// for the spawned process.
270 * Any handles created through duplication of those passed into
271 * @arg pass_handle are returned in @arg set.
272 * @return 0 if there were no handles to return; 1 if there were.
274 int dup_handles (ACE_Handle_Set &set) const;
276 /// Get a copy of the handles passed to the spawned process. This
277 /// will be the set of handles previously passed to @arg pass_handle().
279 * Any handles previously passed to @arg pass_handle are returned
280 * in @arg set.
281 * @return 0 if there were no handles to return; 1 if there were.
283 int passed_handles (ACE_Handle_Set &set) const;
285 /// Set value for avoid_zombies (has no real effect except on *nix).
286 void avoid_zombies (int);
288 /// Get current value for avoid_zombies.
289 int avoid_zombies ();
291 /// Enable the use of a Unicode environment. This only makes sense
292 /// for Win32 when ACE_USES_WCHAR is not defined.
293 void enable_unicode_environment ();
295 /// Disable the use of a Unicode environment.
296 void disable_unicode_environment ();
298 /// Return the unicode environment status
299 bool use_unicode_environment () const;
301 #if defined (ACE_WIN32)
302 // = Non-portable accessors for when you "just have to use them."
304 /// Used for setting and getting.
305 ACE_TEXT_STARTUPINFO *startup_info ();
307 /// Get the process_attributes. Returns NULL if
308 /// set_process_attributes has not been set.
309 LPSECURITY_ATTRIBUTES get_process_attributes () const;
311 /// If this is called, a non-null process attributes is sent to
312 /// CreateProcess.
313 LPSECURITY_ATTRIBUTES set_process_attributes ();
315 /// Get the thread_attributes. Returns NULL if set_thread_attributes
316 /// has not been set.
317 LPSECURITY_ATTRIBUTES get_thread_attributes () const;
319 /// If this is called, a non-null thread attributes is sent to
320 /// CreateProcess.
321 LPSECURITY_ATTRIBUTES set_thread_attributes ();
323 /// Get user token. Return ACE_INVALID_HANDLE if it has not been set.
324 HANDLE get_user_token () const;
326 /// Set user token for creating process as user.
327 /// @param token the user token is passed to \c ::CreateProcessAsUser.
328 /// @param close_token whether to close the user token when destructing.
329 void set_user_token (HANDLE token, bool close_token = false);
331 #else /* All things not WIN32 */
333 /// argv-style array of environment settings.
334 ACE_TCHAR *const *env_argv ();
336 // = Accessors for the standard handles.
337 ACE_HANDLE get_stdin () const;
338 ACE_HANDLE get_stdout () const;
339 ACE_HANDLE get_stderr () const;
341 // = Set/get real & effective user & group id associated with user.
342 int setreugid (const ACE_TCHAR* user);
343 void setruid (uid_t id);
344 void seteuid (uid_t id);
345 void setrgid (gid_t id);
346 void setegid (gid_t id);
347 uid_t getruid () const;
348 uid_t geteuid () const;
349 gid_t getrgid () const;
350 gid_t getegid () const;
353 * Get the inherit_environment flag.
355 bool inherit_environment () const;
358 * Set the inherit_environment flag.
360 void inherit_environment (bool nv);
361 #endif /* ACE_WIN32 */
362 protected:
363 /// Add @a assignment to environment_buf_ and adjust
364 /// environment_argv_. @a len is the strlen of @a assignment.
365 int setenv_i (ACE_TCHAR *assignment, size_t len);
367 /// Whether the child process inherits the current process
368 /// environment.
369 bool inherit_environment_;
371 /// Default 0.
372 u_long creation_flags_;
374 /// Avoid zombies for spawned processes.
375 int avoid_zombies_;
377 #if defined (ACE_WIN32)
378 /// Helper function to grab win32 environment and stick it in
379 /// environment_buf_ using this->setenv_i.
380 void inherit_environment ();
382 /// Ensures once only call to inherit environment.
383 int environment_inherited_;
385 ACE_TEXT_STARTUPINFO startup_info_;
387 /// Pointer to security_buf1_.
388 LPSECURITY_ATTRIBUTES process_attributes_;
390 /// Pointer to security_buf2_.
391 LPSECURITY_ATTRIBUTES thread_attributes_;
393 /// Data for process_attributes_.
394 SECURITY_ATTRIBUTES security_buf1_;
396 /// Data for thread_attributes_.
397 SECURITY_ATTRIBUTES security_buf2_;
399 /// User token for \a CreateProcessAsUser
400 HANDLE user_token_;
402 /// Keeps track of whether we need to close user token.
403 bool close_user_token_;
404 #else /* !ACE_WIN32 */
405 ACE_HANDLE stdin_;
406 ACE_HANDLE stdout_;
407 ACE_HANDLE stderr_;
409 // = Real & effective user & group id's.
410 // These should be set to -1 to leave unchanged (default).
411 uid_t ruid_;
412 uid_t euid_;
413 gid_t rgid_;
414 gid_t egid_;
415 #endif /* ACE_WIN32 */
417 /// Default true.
418 bool handle_inheritance_;
420 /// Is 1 if stdhandles was called.
421 int set_handles_called_;
423 /// Pointer into environment_buf_. This should point to the next
424 /// free spot.
425 size_t environment_buf_index_;
427 /// Pointer to environment_argv_.
428 size_t environment_argv_index_;
430 /// Pointer to buffer of the environment settings.
431 ACE_TCHAR *environment_buf_;
433 /// Size of the environment buffer. Configurable
434 size_t environment_buf_len_;
436 /// Pointers into environment_buf_.
437 ACE_TCHAR **environment_argv_;
439 /// Maximum number of environment variables. Configurable
440 size_t max_environment_args_;
442 /// Maximum index of environment_argv_ buffer
443 size_t max_environ_argv_index_;
445 /// The current working directory.
446 ACE_TCHAR working_directory_[MAXPATHLEN + 1];
448 /// Ensures command_line_argv is only calculated once.
449 bool command_line_argv_calculated_;
451 /// Pointer to buffer of command-line arguments. E.g., "-f foo -b bar".
452 ACE_TCHAR *command_line_buf_;
454 /// Pointer to copy of command-line arguments, which is needed when
455 /// converting a command-line string into a command-line argv.
456 ACE_TCHAR *command_line_copy_;
458 /// Max length of command_line_buf_
459 size_t command_line_buf_len_;
461 /// Maximum number of command-line arguments. Configurable
462 size_t max_command_line_args_;
464 /// Argv-style command-line arguments.
465 ACE_TCHAR **command_line_argv_;
467 /// Process-group on Unix; unused on Win32.
468 pid_t process_group_;
470 /// Set of handles that were passed in pass_handle ().
471 ACE_Handle_Set handles_passed_;
473 /// Results of duplicating handles passed in pass_handle ().
474 ACE_Handle_Set dup_handles_;
476 /// Pathname for the process. Relative path or absolute path or just
477 /// the program name.
478 ACE_TCHAR process_name_[MAXPATHLEN + 1];
480 /// Indicate if a Unicode environment should be used
481 bool use_unicode_environment_;
484 //class ACE_Process_Manager;
487 * @class ACE_Process
489 * @brief A portable encapsulation for creating and managing new processes.
491 * ACE_Process provides a convenient way to:
492 * - Spawn child processes, with convenient hooks for pre- and post-spawn
493 * actions
494 * - Check if a spawned process is still running
495 * - Kill a spawned child process
496 * - Wait for a spawned child process to exit.
498 * @see ACE_Process_Options because it is used to
499 * pass options when spawning child processes.
501 * @see ACE_Process_Manager for additional ways to manage spawned
502 * processes.
504 class ACE_Export ACE_Process
506 public:
507 friend class ACE_Process_Manager;
509 /// Default construction. Use ACE_Process::spawn() to start a process.
510 ACE_Process ();
512 /// Destructor.
513 virtual ~ACE_Process ();
516 * Called back from spawn() just before spawning the child. If this
517 * returns non-zero, the spawn is aborted (and returns ACE_INVALID_PID).
518 * The default returns zero.
520 virtual int prepare (ACE_Process_Options &options);
523 * Launch a new process as described by @a options.
525 * @retval -1 on failure; check @c errno for error code.
526 * @retval 1 on success if the option @c avoid_zombies is set.
527 * @retval other the process id of the newly spawned child.
529 * @note The return value 1 may be changed in future versions of ACE to be
530 * the process id of the child will be returned regardless of the
531 * @c avoid_zombies option.
533 * @note On UNIX platforms, spawn() uses the execvp() system call if
534 * ACE_Process_Options::inherit_environment() returns true (which is the
535 * default) and execve() if not. Since execve() does not search PATH, the
536 * ACE_Process_Options::command_line() should include a full path to the
537 * program file.
539 virtual pid_t spawn (ACE_Process_Options &options);
541 /// Called back from spawn() in the parent's context just after forking,
542 /// if the fork succeeds. The default simply returns.
543 virtual void parent (pid_t child);
546 * Called back from spawn() in the child's context just after forking. The
547 * default does nothing.
549 * @note This function is *not* called on Windows
550 * because the process-creation scheme does not allow it.
552 virtual void child (pid_t parent);
554 /// Called by a ACE_Process_Manager that is removing this object from
555 /// its table of managed processes. Default is to do nothing.
556 virtual void unmanage ();
559 * Wait for a previously spawned process to exit.
561 * @arg status Points to a location to receive the exit status of the
562 * spawned process. Ignored if the value is 0.
563 * @arg wait_options If @c WNOHANG then return 0 and don't block if the
564 * child process hasn't exited yet.
566 * @retval -1 the wait operation failed; consult @c errno for details.
567 * @retval other the child process id is returned on success.
569 pid_t wait (ACE_exitcode *status = 0,
570 int wait_options = 0);
573 * Timed wait for a previously spawned process to exit.
575 * @arg tv A relative amount of time to wait for the process to exit.
576 * @arg status Points to a location to receive the exit status of the
577 * spawned process. Ignored if the value is 0.
579 * @retval 0 the specified time period elapsed before the process exited.
580 * @retval -1 the wait operation failed; consult @c errno for details.
581 * @retval other the child process id is returned on success.
583 * @note On UNIX platforms this function uses @c ualarm(), i.e., it
584 * overwrites any existing alarm. In addition, it steals all
585 * @c SIGCHLD signals during the timeout period, which will break another
586 * ACE_Process_Manager in the same process that's expecting
587 * @c SIGCHLD to kick off process reaping.
589 pid_t wait (const ACE_Time_Value &tv,
590 ACE_exitcode *status = 0);
592 /// Send the process a signal. This only has an effect on operating
593 /// systems that support signals, such as UNIX/POSIX.
594 int kill (int signum = SIGINT);
597 * Terminate the process abruptly using ACE::terminate_process().
598 * This call doesn't give the process a chance to cleanup, so use it
599 * with caution.
601 int terminate ();
603 /// Return the process id of the new child process.
604 pid_t getpid () const;
606 /// Return the handle of the process, if it has one.
607 ACE_HANDLE gethandle () const;
609 /// Return 1 if running; 0 otherwise.
610 int running () const;
612 /// Return the process's exit code. This method returns the raw
613 /// exit status returned from system APIs (such as @c wait() or
614 /// @c waitpid() ). This value is system dependent.
615 ACE_exitcode exit_code () const;
617 /// Return the process's return value. This method returns the
618 /// actual return value that a child process returns or exits with.
619 int return_value () const;
621 /// Close all the handles in the set obtained from the
622 /// @a ACE_Process_Options::dup_handles object used to spawn
623 /// the process.
624 void close_dup_handles ();
626 /// Close all the passed handles in the set obtained from the
627 /// ACE_Process_Options object used to spawn the process.
628 void close_passed_handles ();
630 #if defined (ACE_WIN32)
631 PROCESS_INFORMATION process_info ();
632 #endif /* ACE_WIN32 */
634 private:
635 ACE_Process (const ACE_Process &) = delete;
636 void operator= (const ACE_Process &) = delete;
637 ACE_Process (ACE_Process &&) = delete;
638 void operator= (ACE_Process &&) = delete;
640 protected:
641 /// Set this process's exit code. ACE_Process_Manager uses this
642 /// method to set the exit code after successfully waiting for
643 /// this process to exit.
644 void exit_code (ACE_exitcode code);
646 #if defined (ACE_WIN32)
647 PROCESS_INFORMATION process_info_;
648 #else /* ACE_WIN32 */
649 /// Process id of the child.
650 pid_t child_id_;
651 #endif /* ACE_WIN32 */
652 ACE_exitcode exit_code_;
654 /// Set of handles that were passed to the child process.
655 ACE_Handle_Set handles_passed_;
657 /// Handle duplicates made for the child process.
658 ACE_Handle_Set dup_handles_;
660 private:
661 #if defined (ACE_WIN32) && defined (ACE_HAS_WCHAR) && !defined (ACE_USES_WCHAR)
662 wchar_t* convert_env_buffer (const char* env) const;
663 #endif
667 * @class ACE_Managed_Process
669 * @brief A process easily managed by ACE_Process_Manager.
671 * @arg ACE_Managed_Process is just an @arg ACE_Process with an
672 * @arg unmanage() method that deletes the instance.
673 * This class is only valid for use as a dynamically-allocated object!
675 class ACE_Export ACE_Managed_Process : public ACE_Process
677 public:
678 /// Cleanup by deleting @c this.
679 void unmanage () override;
681 ACE_ALLOC_HOOK_DECLARE;
683 protected:
684 ~ACE_Managed_Process () override = default;
687 ACE_END_VERSIONED_NAMESPACE_DECL
689 #if defined (__ACE_INLINE__)
690 #include "ace/Process.inl"
691 #endif /* __ACE_INLINE__ */
693 #include /**/ "ace/post.h"
694 #endif /* ACE_PROCESS_H */