Also use Objects as part of an operation but as a result don't generate Any operation...
[ACE_TAO.git] / ACE / ace / Process.h
blob1465103ef63959e667b40cee3bd95f6eea208ac0
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 Windows CE, creating a process merely means
39 * instantiating a new process. You can't set the handles (since
40 * there's no stdin, stdout and stderr,) specify process/thread
41 * options, set environment,... So, basically, this class only
42 * set the command line and nothing else.
43 * Notice that on UNIX platforms, if the <setenv> is used, the
44 * <spawn> is using the <execve> system call. It means that the
45 * <command_line> should include a full path to the program file
46 * (<execve> does not search the PATH). If <setenv> is not used
47 * then, the <spawn> is using the <execvp> which searches for the
48 * program file in the PATH variable.
50 class ACE_Export ACE_Process_Options
52 public:
53 enum
55 DEFAULT_COMMAND_LINE_BUF_LEN = 1024,
56 // UNIX process creation flags.
57 #if defined (ACE_WIN32)
58 NO_EXEC = 0
59 #else
60 NO_EXEC = 1
61 #endif /* ACE_WIN32 */
64 protected:
65 // = Default settings not part of public Interface.
67 /// @todo These sizes should be taken from the appropriate
68 /// POSIX/system header files and/or defined dynamically.
69 enum
71 MAX_COMMAND_LINE_OPTIONS = 128,
72 ENVIRONMENT_BUFFER = 16 * 1024, // 16K
73 MAX_ENVIRONMENT_ARGS = 512 //
76 public:
77 /**
78 * If @a inherit_environment == true, the new process will inherit the
79 * environment of the current process. @a command_line_buf_len is the
80 * max strlen for command-line arguments.
82 ACE_Process_Options (bool inherit_environment = true,
83 size_t command_line_buf_len = DEFAULT_COMMAND_LINE_BUF_LEN,
84 size_t env_buf_len = ENVIRONMENT_BUFFER,
85 size_t max_env_args = MAX_ENVIRONMENT_ARGS,
86 size_t max_cmdline_args = MAX_COMMAND_LINE_OPTIONS);
88 /// Destructor.
89 ~ACE_Process_Options (void);
91 // = Methods to set process creation options portably.
93 /**
94 * Set the standard handles of the new process to the respective
95 * handles. If you want to affect a subset of the handles, make
96 * sure to set the others to ACE_INVALID_HANDLE.
98 * @note Any handle passed as ACE_INVALID_HANDLE will be changed to
99 * a duplicate of the current associated handle. For example, passing
100 * ACE_INVALID_HANDLE for @a std_in will cause ACE_STDIN to be
101 * duplicated and set in this object.
103 * @note Windows: The implementation of set_handles() uses DuplicateHandle
104 * on Windows. DuplicateHandle cannot be used to pass a socket handle
105 * on Windows. Socket handles require an alternate mechanism to pass;
106 * see http://msdn.microsoft.com/en-us/library/ms741565(v=VS.85).aspx
108 * @return 0 on success, -1 on failure.
110 int set_handles (ACE_HANDLE std_in,
111 ACE_HANDLE std_out = ACE_INVALID_HANDLE,
112 ACE_HANDLE std_err = ACE_INVALID_HANDLE);
114 /// Release the standard handles previously set with set_handles;
115 void release_handles (void);
117 #ifndef ACE_LACKS_VA_FUNCTIONS
118 /// @param format must be of the form "VARIABLE=VALUE". There can not be
119 /// any spaces between VARIABLE and the equal sign.
120 int setenv (const ACE_TCHAR *format,
121 ...)
122 #if !defined (ACE_USES_WCHAR)
123 ACE_GCC_FORMAT_ATTRIBUTE (printf, 2, 3)
124 #endif /* !ACE_USES_WCHAR */
128 * Set a single environment variable, @a variable_name. Since
129 * different platforms separate each environment variable
130 * differently, you must call this method once for each variable.
131 * @a format can be any printf format string. So options->setenv
132 * ("FOO","one + two = %s", "three") will result in "FOO=one + two =
133 * three".
135 int setenv (const ACE_TCHAR *variable_name,
136 const ACE_TCHAR *format,
137 ...)
138 #if !defined (ACE_USES_WCHAR)
139 ACE_GCC_FORMAT_ATTRIBUTE (printf, 3, 4)
140 #endif /* !ACE_USES_WCHAR */
142 #endif // ACE_LACKS_VA_FUNCTIONS
144 /// Same as above with argv format. @a envp must be null terminated.
145 int setenv (ACE_TCHAR *envp[]);
147 /// Set the working directory for the process. strlen of @a wd must
148 /// be <= MAXPATHLEN.
149 void working_directory (const char *wd);
151 #if defined (ACE_HAS_WCHAR)
152 /// wchar_t version of working_directory
153 void working_directory (const wchar_t *wd);
154 #endif /* ACE_HAS_WCHAR */
156 #ifndef ACE_LACKS_VA_FUNCTIONS
158 * Set the command-line arguments. @a format can use any printf
159 * formats. The first token in @a format should be the path to the
160 * application. This can either be a full path, relative path, or
161 * just an executable name. If an executable name is used, we rely
162 * on the platform's support for searching paths. Since we need a
163 * path to run a process, this method *must* be called! Returns 0
164 * on success, -1 on failure.
166 int command_line (const ACE_TCHAR *format, ...)
167 #if !defined (ACE_USES_WCHAR)
168 ACE_GCC_FORMAT_ATTRIBUTE (printf, 2, 3)
169 #endif /* !ACE_USES_WCHAR */
172 #if defined (ACE_HAS_WCHAR) && !defined (ACE_HAS_WINCE)
173 /// Anti-TChar version of command_line ()
174 int command_line (const ACE_ANTI_TCHAR *format, ...);
175 #endif /* ACE_HAS_WCHAR && !ACE_HAS_WINCE */
176 #endif // ACE_LACKS_VA_FUNCTIONS
178 /// Same as above in argv format. @a argv must be null terminated.
179 int command_line (const ACE_TCHAR * const argv[]);
182 * Specify the full path or relative path, or just the executable
183 * name for the process. If this is set, then @a name will be used to
184 * create the process instead of argv[0] set in the command
185 * line. This is here so that you can supply something other than
186 * executable name as argv[0].
188 void process_name (const ACE_TCHAR *name);
190 /// Return the process_name. If the <process_name(name)> set
191 /// method is not called, this method will return argv[0].
192 const ACE_TCHAR *process_name (void);
194 /// Get the creation flags.
195 u_long creation_flags (void) const;
198 * Set the creation flags to affect how a new process is spawned.
199 * The only ACE-defined flag is @c NO_EXEC which prevents the new process
200 * from executing a new program image; this is a simple POSIX fork().
201 * The @c NO_EXEC option has no affect on Windows; on other platforms where
202 * a POSIX fork is not possible, specifying @c NO_EXEC will cause
203 * ACE_Process::spawn() to fail.
205 * On Windows, the value of creation_flags is passed to the @c CreateProcess
206 * system call as the value of the @c dwCreationFlags parameter.
208 void creation_flags (u_long);
210 /// Current working directory. Returns "" if nothing has been set.
211 ACE_TCHAR *working_directory (void);
213 /// Buffer of command-line options. Returns a pointer to a buffer that
214 /// contains the list of command line options. Prior to a call to
215 /// command_line_argv(), this is a single string of space separated
216 /// arguments independent of which form of command_line() was used to
217 /// create it. After a call to command_line_argv(), this is a list of
218 /// strings each terminated by '\0'. [Note: spawn() will call
219 /// command_line_argv().] The total length of all these strings is the
220 /// same as the single string in the prior case and can be obtained by
221 /// providing max_len. @arg max_len, if non-zero, provides a location
222 /// into which the total length of the command line buffer is returned.
223 ACE_TCHAR *command_line_buf (size_t *max_len = 0);
226 * argv-style command-line options. Parses and modifies the string
227 * created from <command_line_>. All spaces not in quotes ("" or
228 * '') are replaced with null (\0) bytes. An argv array is built
229 * and returned with each entry pointing to the start of
230 * null-terminated string. Returns { 0 } if nothing has been set.
232 ACE_TCHAR * const *command_line_argv (void);
235 * Null-terminated buffer of null terminated strings. Each string
236 * is an environment assignment "VARIABLE=value". This buffer
237 * should end with two null characters.
239 ACE_TCHAR *env_buf (void);
241 /// Get the process group. On UNIX, these methods are used by the
242 /// ACE_Process_Manager to manage groups of processes.
243 pid_t getgroup (void) const;
245 /// Set the process group. On UNIX, these methods are used by the
246 /// ACE_Process_Manager to manage groups of processes.
247 pid_t setgroup (pid_t pgrp);
249 /// Allows disabling of handle inheritance, default is TRUE.
251 /// @remarks @b Windows: the handle_inheritance value is passed as the
252 /// bInheritHandles value to the CreateProcess() system function. Therefore,
253 /// if you redirect standard input, output, or error via
254 /// ACE_Process_Options::set_handles() you must not call
255 /// handle_inheritance(false). Doing so will prevent the duplicated handles
256 /// from surviving in the created process.
257 int handle_inheritance (void);
258 void handle_inheritance (int);
260 /// Cause the specified handle to be passed to a child process
261 /// when it runs a new program image.
263 * The specified handle value will be included in the spawned
264 * process's command line as @arg +H @arg handle, if a new
265 * program is spawned (always on Win32; else if NO_EXEC is not
266 * set in creation flags). The passed handle value will be
267 * duplicated if on Win32 less capable than NT.
268 * @return 0 if success, -1 if failure.
270 int pass_handle (ACE_HANDLE);
272 /// Get a copy of the handles the ACE_Process_Options duplicated
273 /// for the spawned process.
275 * Any handles created through duplication of those passed into
276 * @arg pass_handle are returned in @arg set.
277 * @return 0 if there were no handles to return; 1 if there were.
279 int dup_handles (ACE_Handle_Set &set) const;
281 /// Get a copy of the handles passed to the spawned process. This
282 /// will be the set of handles previously passed to @arg pass_handle().
284 * Any handles previously passed to @arg pass_handle are returned
285 * in @arg set.
286 * @return 0 if there were no handles to return; 1 if there were.
288 int passed_handles (ACE_Handle_Set &set) const;
290 /// Set value for avoid_zombies (has no real effect except on *nix).
291 void avoid_zombies (int);
293 /// Get current value for avoid_zombies.
294 int avoid_zombies (void);
296 /// Enable the use of a Unicode environment. This only makes sense
297 /// for Win32 when ACE_USES_WCHAR is not defined.
298 void enable_unicode_environment (void);
300 /// Disable the use of a Unicode environment.
301 void disable_unicode_environment (void);
303 /// Return the unicode environment status
304 bool use_unicode_environment (void) const;
306 #if defined (ACE_WIN32)
307 // = Non-portable accessors for when you "just have to use them."
309 /// Used for setting and getting.
310 ACE_TEXT_STARTUPINFO *startup_info (void);
312 /// Get the process_attributes. Returns NULL if
313 /// set_process_attributes has not been set.
314 LPSECURITY_ATTRIBUTES get_process_attributes (void) const;
316 /// If this is called, a non-null process attributes is sent to
317 /// CreateProcess.
318 LPSECURITY_ATTRIBUTES set_process_attributes (void);
320 /// Get the thread_attributes. Returns NULL if set_thread_attributes
321 /// has not been set.
322 LPSECURITY_ATTRIBUTES get_thread_attributes (void) const;
324 /// If this is called, a non-null thread attributes is sent to
325 /// CreateProcess.
326 LPSECURITY_ATTRIBUTES set_thread_attributes (void);
328 /// Get user token. Return ACE_INVALID_HANDLE if it has not been set.
329 HANDLE get_user_token (void) const;
331 /// Set user token for creating process as user.
332 /// @param token the user token is passed to \c ::CreateProcessAsUser.
333 /// @param close_token whether to close the user token when destructing.
334 void set_user_token (HANDLE token, bool close_token = false);
336 #else /* All things not WIN32 */
338 /// argv-style array of environment settings.
339 ACE_TCHAR *const *env_argv (void);
341 // = Accessors for the standard handles.
342 ACE_HANDLE get_stdin (void) const;
343 ACE_HANDLE get_stdout (void) const;
344 ACE_HANDLE get_stderr (void) const;
346 // = Set/get real & effective user & group id associated with user.
347 int setreugid (const ACE_TCHAR* user);
348 void setruid (uid_t id);
349 void seteuid (uid_t id);
350 void setrgid (uid_t id);
351 void setegid (uid_t id);
352 uid_t getruid (void) const;
353 uid_t geteuid (void) const;
354 uid_t getrgid (void) const;
355 uid_t getegid (void) const;
358 * Get the inherit_environment flag.
360 bool inherit_environment (void) const;
363 * Set the inherit_environment flag.
365 void inherit_environment (bool nv);
366 #endif /* ACE_WIN32 */
367 protected:
369 #if !defined (ACE_HAS_WINCE)
370 /// Add @a assignment to environment_buf_ and adjust
371 /// environment_argv_. @a len is the strlen of @a assignment.
372 int setenv_i (ACE_TCHAR *assignment, size_t len);
374 /// Whether the child process inherits the current process
375 /// environment.
376 bool inherit_environment_;
377 #endif /* !ACE_HAS_WINCE */
379 /// Default 0.
380 u_long creation_flags_;
382 /// Avoid zombies for spawned processes.
383 int avoid_zombies_;
385 #if defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)
386 /// Helper function to grab win32 environment and stick it in
387 /// environment_buf_ using this->setenv_i.
388 void inherit_environment (void);
390 /// Ensures once only call to inherit environment.
391 int environment_inherited_;
393 ACE_TEXT_STARTUPINFO startup_info_;
395 /// Pointer to security_buf1_.
396 LPSECURITY_ATTRIBUTES process_attributes_;
398 /// Pointer to security_buf2_.
399 LPSECURITY_ATTRIBUTES thread_attributes_;
401 /// Data for process_attributes_.
402 SECURITY_ATTRIBUTES security_buf1_;
404 /// Data for thread_attributes_.
405 SECURITY_ATTRIBUTES security_buf2_;
407 /// User token for \a CreateProcessAsUser
408 HANDLE user_token_;
410 /// Keeps track of whether we need to close user token.
411 bool close_user_token_;
412 #else /* !ACE_WIN32 */
413 ACE_HANDLE stdin_;
414 ACE_HANDLE stdout_;
415 ACE_HANDLE stderr_;
417 // = Real & effective user & group id's.
418 // These should be set to -1 to leave unchanged (default).
419 uid_t ruid_;
420 uid_t euid_;
421 uid_t rgid_;
422 uid_t egid_;
423 #endif /* ACE_WIN32 */
425 /// Default true.
426 bool handle_inheritance_;
428 #if !defined (ACE_HAS_WINCE)
429 /// Is 1 if stdhandles was called.
430 int set_handles_called_;
432 /// Pointer into environment_buf_. This should point to the next
433 /// free spot.
434 size_t environment_buf_index_;
436 /// Pointer to environment_argv_.
437 size_t environment_argv_index_;
439 /// Pointer to buffer of the environment settings.
440 ACE_TCHAR *environment_buf_;
442 /// Size of the environment buffer. Configurable
443 size_t environment_buf_len_;
445 /// Pointers into environment_buf_.
446 ACE_TCHAR **environment_argv_;
448 /// Maximum number of environment variables. Configurable
449 size_t max_environment_args_;
451 /// Maximum index of environment_argv_ buffer
452 size_t max_environ_argv_index_;
454 /// The current working directory.
455 ACE_TCHAR working_directory_[MAXPATHLEN + 1];
456 #endif /* !ACE_HAS_WINCE */
458 /// Ensures command_line_argv is only calculated once.
459 bool command_line_argv_calculated_;
461 /// Pointer to buffer of command-line arguments. E.g., "-f foo -b bar".
462 ACE_TCHAR *command_line_buf_;
464 /// Pointer to copy of command-line arguments, which is needed when
465 /// converting a command-line string into a command-line argv.
466 ACE_TCHAR *command_line_copy_;
468 /// Max length of command_line_buf_
469 size_t command_line_buf_len_;
471 /// Maximum number of command-line arguments. Configurable
472 size_t max_command_line_args_;
474 /// Argv-style command-line arguments.
475 ACE_TCHAR **command_line_argv_;
477 /// Process-group on Unix; unused on Win32.
478 pid_t process_group_;
480 /// Set of handles that were passed in pass_handle ().
481 ACE_Handle_Set handles_passed_;
483 /// Results of duplicating handles passed in pass_handle ().
484 ACE_Handle_Set dup_handles_;
486 /// Pathname for the process. Relative path or absolute path or just
487 /// the program name.
488 ACE_TCHAR process_name_[MAXPATHLEN + 1];
490 /// Indicate if a Unicode environment should be used
491 bool use_unicode_environment_;
494 //class ACE_Process_Manager;
497 * @class ACE_Process
499 * @brief A portable encapsulation for creating and managing new processes.
501 * ACE_Process provides a convenient way to:
502 * - Spawn child processes, with convenient hooks for pre- and post-spawn
503 * actions
504 * - Check if a spawned process is still running
505 * - Kill a spawned child process
506 * - Wait for a spawned child process to exit.
508 * @see ACE_Process_Options because it is used to
509 * pass options when spawning child processes.
511 * @see ACE_Process_Manager for additional ways to manage spawned
512 * processes.
514 class ACE_Export ACE_Process
516 public:
517 friend class ACE_Process_Manager;
519 /// Default construction. Use ACE_Process::spawn() to start a process.
520 ACE_Process (void);
522 /// Destructor.
523 virtual ~ACE_Process (void);
526 * Called back from spawn() just before spawning the child. If this
527 * returns non-zero, the spawn is aborted (and returns ACE_INVALID_PID).
528 * The default returns zero.
530 virtual int prepare (ACE_Process_Options &options);
533 * Launch a new process as described by @a options.
535 * @retval -1 on failure; check @c errno for error code.
536 * @retval 1 on success if the option @c avoid_zombies is set.
537 * @retval other the process id of the newly spawned child.
539 * @note The return value 1 may be changed in future versions of ACE to be
540 * the process id of the child will be returned regardless of the
541 * @c avoid_zombies option.
543 * @note On UNIX platforms, spawn() uses the execvp() system call if
544 * ACE_Process_Options::inherit_environment() returns true (which is the
545 * default) and execve() if not. Since execve() does not search PATH, the
546 * ACE_Process_Options::command_line() should include a full path to the
547 * program file.
549 virtual pid_t spawn (ACE_Process_Options &options);
551 /// Called back from spawn() in the parent's context just after forking,
552 /// if the fork succeeds. The default simply returns.
553 virtual void parent (pid_t child);
556 * Called back from spawn() in the child's context just after forking. The
557 * default does nothing.
559 * @note This function is *not* called on Windows
560 * because the process-creation scheme does not allow it.
562 virtual void child (pid_t parent);
564 /// Called by a ACE_Process_Manager that is removing this object from
565 /// its table of managed processes. Default is to do nothing.
566 virtual void unmanage (void);
569 * Wait for a previously spawned process to exit.
571 * @arg status Points to a location to receive the exit status of the
572 * spawned process. Ignored if the value is 0.
573 * @arg wait_options If @c WNOHANG then return 0 and don't block if the
574 * child process hasn't exited yet.
576 * @retval -1 the wait operation failed; consult @c errno for details.
577 * @retval other the child process id is returned on success.
579 pid_t wait (ACE_exitcode *status = 0,
580 int wait_options = 0);
583 * Timed wait for a previously spawned process to exit.
585 * @arg tv A relative amount of time to wait for the process to exit.
586 * @arg status Points to a location to receive the exit status of the
587 * spawned process. Ignored if the value is 0.
589 * @retval 0 the specified time period elapsed before the process exited.
590 * @retval -1 the wait operation failed; consult @c errno for details.
591 * @retval other the child process id is returned on success.
593 * @note On UNIX platforms this function uses @c ualarm(), i.e., it
594 * overwrites any existing alarm. In addition, it steals all
595 * @c SIGCHLD signals during the timeout period, which will break another
596 * ACE_Process_Manager in the same process that's expecting
597 * @c SIGCHLD to kick off process reaping.
599 pid_t wait (const ACE_Time_Value &tv,
600 ACE_exitcode *status = 0);
602 /// Send the process a signal. This only has an effect on operating
603 /// systems that support signals, such as UNIX/POSIX.
604 int kill (int signum = SIGINT);
607 * Terminate the process abruptly using ACE::terminate_process().
608 * This call doesn't give the process a chance to cleanup, so use it
609 * with caution.
611 int terminate (void);
613 /// Return the process id of the new child process.
614 pid_t getpid (void) const;
616 /// Return the handle of the process, if it has one.
617 ACE_HANDLE gethandle (void) const;
619 /// Return 1 if running; 0 otherwise.
620 int running (void) const;
622 /// Return the process's exit code. This method returns the raw
623 /// exit status returned from system APIs (such as @c wait() or
624 /// @c waitpid() ). This value is system dependent.
625 ACE_exitcode exit_code (void) const;
627 /// Return the process's return value. This method returns the
628 /// actual return value that a child process returns or exits with.
629 int return_value (void) const;
631 /// Close all the handles in the set obtained from the
632 /// @a ACE_Process_Options::dup_handles object used to spawn
633 /// the process.
634 void close_dup_handles (void);
636 /// Close all the passed handles in the set obtained from the
637 /// ACE_Process_Options object used to spawn the process.
638 void close_passed_handles (void);
640 #if defined (ACE_WIN32)
641 PROCESS_INFORMATION process_info (void);
642 #endif /* ACE_WIN32 */
644 private:
646 // Disallow copying and assignment since we don't support this (yet).
647 ACE_Process (const ACE_Process &);
648 void operator= (const ACE_Process &);
650 protected:
651 /// Set this process's exit code. ACE_Process_Manager uses this
652 /// method to set the exit code after successfully waiting for
653 /// this process to exit.
654 void exit_code (ACE_exitcode code);
656 #if defined (ACE_WIN32)
657 PROCESS_INFORMATION process_info_;
658 #else /* ACE_WIN32 */
659 /// Process id of the child.
660 pid_t child_id_;
661 #endif /* ACE_WIN32 */
662 ACE_exitcode exit_code_;
664 /// Set of handles that were passed to the child process.
665 ACE_Handle_Set handles_passed_;
667 /// Handle duplicates made for the child process.
668 ACE_Handle_Set dup_handles_;
670 private:
671 #if defined (ACE_WIN32) && \
672 defined (ACE_HAS_WCHAR) && !defined (ACE_USES_WCHAR) && \
673 !defined (ACE_HAS_WINCE)
674 wchar_t* convert_env_buffer (const char* env) const;
675 #endif
679 * @class ACE_Managed_Process
681 * @brief A process easily managed by ACE_Process_Manager.
683 * @arg ACE_Managed_Process is just an @arg ACE_Process with an
684 * @arg unmanage() method that deletes the instance.
685 * This class is only valid for use as a dynamically-allocated object!
687 class ACE_Export ACE_Managed_Process : public ACE_Process
689 public:
691 /// Cleanup by deleting @c this.
692 virtual void unmanage (void);
694 ACE_ALLOC_HOOK_DECLARE;
696 protected:
698 /// Make sure that we're allocated dynamically!
699 virtual ~ACE_Managed_Process (void);
702 ACE_END_VERSIONED_NAMESPACE_DECL
704 #if defined (__ACE_INLINE__)
705 #include "ace/Process.inl"
706 #endif /* __ACE_INLINE__ */
708 #include /**/ "ace/post.h"
709 #endif /* ACE_PROCESS_H */