00001 #ifndef __exec_h__ 00002 #define __exec_h__ 00003 00004 #include <iostream> 00005 #include <vector> 00006 #include <string> 00007 00008 #ifdef HAVE_SYS_TYPES_H 00009 #include <sys/types.h> 00010 #endif 00011 #ifdef HAVE_UNISTD_H 00012 #include <unistd.h> 00013 #endif 00014 #ifdef HAVE_SIGNAL_H 00015 #include <signal.h> 00016 #endif 00017 00018 #include "asserts.h" 00019 00020 /** Fork a child process or execute an external program */ 00021 class execute 00022 { 00023 public: 00024 execute(); 00025 ~execute(); 00026 00027 void fork(void); 00028 void clear(void); 00029 bool is_child(void); 00030 bool is_parent(void); 00031 pid_t my_pid(void); 00032 00033 // Child-specific functions: 00034 void exit(int code = 0); // For child, exit with code 00035 void reroute_stdio(void); // Re-route stdin/out/err to parent 00036 00037 // Parent-specific functions: 00038 pid_t child_pid(void); // PID of child process 00039 void signal_child(int signal_no); // Send signal to child 00040 void hup_child(void); // Send child HUP signal 00041 void kill_child(void); // Send child KILL signal 00042 void wait(void); // Wait for child to exit 00043 bool child_started(void) const; // True if child has been started 00044 bool child_running(void); // True if child is still running 00045 bool child_exited(void); // True if child has exited 00046 bool child_exited_normally(void); // Exit code = 0, signal = ? 00047 bool child_signaled(void); // Exit code = ?, signal = yes 00048 bool child_exited_success(void); // Exit code = 0, signal = no 00049 int child_exit_code(void); // Child's exit code 00050 int child_signal_no(void); // Child's uncaught signal 00051 00052 // Command execution 00053 void exec(const std::string command); 00054 void exec(const std::string binary, const std::vector<std::string> argv); 00055 00056 int in_fd(void); 00057 int out_fd(void); 00058 int err_fd(void); 00059 bool in_ready(void); 00060 bool out_ready(void); 00061 bool err_ready(void); 00062 00063 bool in_eof(void); 00064 bool out_eof(void); 00065 bool err_eof(void); 00066 int in_read(char* buf, const int len); 00067 int in_write(const char* buf, const int len); 00068 int out_read(char* buf, const int len); 00069 int out_write(const char* buf, const int len); 00070 int err_read(char* buf, const int len); 00071 int err_write(const char* buf, const int len); 00072 00073 void print(std::ostream& out); 00074 00075 private: 00076 int m_fd1[2]; 00077 int m_fd2[2]; 00078 int m_fd3[2]; 00079 pid_t m_pid; 00080 int m_status; 00081 bool m_in_eof; 00082 bool m_out_eof; 00083 bool m_err_eof; 00084 bool m_child_started; 00085 00086 pid_t check_child_(void); 00087 bool check_write_ready_(int fd); 00088 bool check_read_ready_(int fd); 00089 }; 00090 00091 std::ostream& operator << (std::ostream& out, execute& exe); 00092 00093 #endif