amend d814acb - SystemExec/Export debugging
[ardour.git] / libs / pbd / pbd / system_exec.h
1 /*
2     Copyright (C) 2010 Paul Davis
3     Copyright (C) 2010-2014 Robin Gareus <robin@gareus.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20 #ifndef _libpbd_system_exec_h_
21 #define _libpbd_system_exec_h_
22
23 #ifndef STDIN_FILENO
24 #define STDIN_FILENO 0
25 #endif
26 #ifndef STDOUT_FILENO
27 #define STDOUT_FILENO 1
28 #endif
29 #ifndef STDERR_FILENO
30 #define STDERR_FILENO 2
31 #endif
32
33 #ifdef PLATFORM_WINDOWS
34 #include <windows.h>
35
36 #ifdef interface
37 #undef interface // VKamyshniy: to avoid "include/giomm-2.4/giomm/dbusmessage.h:270:94: error: expected ',' or '...' before 'struct'"
38 #endif
39
40 #endif
41
42 #include <string>
43 #include <pthread.h>
44 #include <signal.h>
45 #include <map>
46
47 #ifdef NOPBD  /* unit-test outside ardour */
48 #include <sigc++/bind.h>
49 #include <sigc++/signal.h>
50 #else
51 #include "pbd/signals.h"
52 #endif
53
54 namespace PBD {
55
56 /** @class: SystemExec
57  *  @brief execute an external command
58  *
59  * This class allows launche an external command-line application
60  * opening a full-duplex connection to its standard I/O.
61  *
62  * In Ardour context it is used to launch xjadeo and ffmpeg.
63  *
64  * The \ref write_to_stdin function provides for injecting data into STDIN
65  * of the child-application while output of the program to STDOUT/STDERR is
66  * forwarded using the \ref ReadStdout signal.
67  * \ref Terminated is sent if the child application exits.
68  *
69  */
70 class LIBPBD_API SystemExec
71 {
72         public:
73                 /** prepare execution of a program with 'execve'
74                  *
75                  * This function takes over the existing environment variable and provides
76                  * an easy way to speciy command-line arguments for the new process.
77                  *
78                  * Note: The argument parser does not interpret quotation-marks and splits
79                  * arugments on whitespace. The argument string can be empty.
80                  * The alternative constructor below allows to specify quoted parameters
81                  * incl. whitespace.
82                  *
83                  * @param c program pathname that identifies the new process image file.
84                  * @param a string of commandline-arguments to be passed to the new program.
85                  */
86                 SystemExec (std::string c, std::string a = "");
87                 /** similar to \ref SystemExec but allows to specify custom arguments
88                  *
89                  * @param c program pathname that identifies the new process image file.
90                  * @param a array of argument strings passed to the new program as 'argv'.
91                  *          it must be terminated by a null pointer (see the 'evecve'
92                  *          POSIX-C documentation for more information)
93                  *          The array must be dynamically allocated using malloc or strdup.
94                  *          Unless they're NULL, the array itself and each of its content
95                  *          memory is freed() in the destructor.
96                  *
97                  */
98                 SystemExec (std::string c, char ** a);
99
100                 /** similar to \ref SystemExec but expects a whole command line, and
101                  * handles some simple escape sequences.
102                  *
103                  * @param command complete command-line to be executed
104                  * @param subs a map of <char, std::string> listing the % substitutions to
105                  *             be made.
106                  *
107                  * creates an argv array from the given command string, splitting into
108                  * parameters at spaces.
109                  * "\ " is non-splitting space, "\\" (and "\" at end of command) as "\",
110                  * for "%<char>", <char> is looked up in subs and the corresponding string
111                  * substituted. "%%" (and "%" at end of command)
112                  * returns an argv array suitable for creating a new SystemExec with
113                  */
114                 SystemExec (std::string command, const std::map<char, std::string> subs);
115
116                 virtual ~SystemExec ();
117
118                 std::string to_s() const;
119
120                 /** fork and execute the given program
121                  *
122                  * @param stderr_mode select what to do with program's standard error
123                  * output:
124                  * '0': keep STDERR; mix it with parent-process' STDERR
125                  * '1': ignore STDERR of child-program
126                  * '2': merge STDERR into STDOUT and send it with the
127                  *      ReadStdout signal.
128                  * @return If the process is already running or was launched successfully
129                  * the function returns zero (0). A negative number indicates an error.
130                  */
131                 int start (int stderr_mode, const char *_vfork_exec_wrapper);
132                 /** kill running child-process
133                  *
134                  * if a child process exists trt to shut it down by closing its STDIN.
135                  * if the program dies not react try SIGTERM and eventually SIGKILL
136                  */
137                 void terminate ();
138                 /** check if the child programm is (still) running.
139                  *
140                  * This function calls waitpid(WNOHANG) to check the state of the
141                  * child-process.
142                  * @return true if the program is (still) running.
143                  */
144                 bool is_running ();
145                 /** call the waitpid system-call with the pid of the child-program
146                  *
147                  * Basically what \ref terminate uses internally.
148                  *
149                  * This function is only useful if you want to control application
150                  * termination yourself (eg timeouts or progress-dialog).
151                  * @param option flags - see waitpid manual
152                  * @return status info from waitpid call (not waitpid's return value)
153                  * or -1 if the child-program is not running.
154                  */
155                 int wait (int options=0);
156                 /** closes both STDIN and STDOUT connections to/from
157                  * the child-program.
158                  * With the output-interposer thread gone, the program
159                  * should terminate.
160                  * used by \ref terminate()
161                  */
162                 void close_stdin ();
163                 /** write into child-program's STDIN
164                  * @param d data to write
165                  * @param len length of data to write, if it is 0 (zero), d.length() is
166                  * used to determine the number of bytes to transmit.
167                  * @return number of bytes written.
168                  */
169                 int write_to_stdin (std::string d, size_t len=0);
170
171                 /** The ReadStdout signal is emitted when the application writes to STDOUT.
172                  * it passes the written data and its length in bytes as arguments to the bound
173                  * slot(s).
174                  */
175 #ifdef NOPBD  /* outside ardour */
176                 sigc::signal<void, std::string,size_t> ReadStdout;
177 #else
178                 PBD::Signal2<void, std::string,size_t> ReadStdout;
179 #endif
180
181                 /** The Terminated signal is emitted when application terminates. */
182 #ifdef NOPBD  /* outside ardour */
183                 sigc::signal<void> Terminated;
184 #else
185                 PBD::Signal0<void> Terminated;
186 #endif
187
188                 /** interposer to emit signal for writes to STDOUT/ERR.
189                  *
190                  * Thread that reads the stdout of the forked
191                  * process and signal-sends it to the main thread.
192                  * It also emits the Terminated() signal once
193                  * the the forked process closes it's stdout.
194                  *
195                  * Note: it's actually 'private' function but used
196                  * by the internal pthread, which only has a pointer
197                  * to this instance and thus can only access public fn.
198                  */
199                 void output_interposer ();
200
201         protected:
202                 std::string cmd; ///< path to command - set when creating the class
203                 int nicelevel; ///< process nice level - defaults to 0
204
205                 void make_argp(std::string);
206                 void make_argp_escaped(std::string command, const std::map<char, std::string> subs);
207                 void make_envp();
208
209                 char **argp;
210                 char **envp;
211
212         private:
213 #ifdef PLATFORM_WINDOWS
214                 PROCESS_INFORMATION *pid;
215                 HANDLE stdinP[2];
216                 HANDLE stdoutP[2];
217                 HANDLE stderrP[2];
218                 char *w_args;
219                 void make_wargs(char **);
220 #else
221                 pid_t pid;
222 #endif
223                 void init ();
224                 pthread_mutex_t write_lock;
225
226                 int pok[2];
227                 int pin[2];
228                 int pout[2];
229
230                 pthread_t      thread_id_tt;
231                 bool           thread_active;
232
233 }; /* end class */
234
235 }; /* end namespace */
236
237 #endif /* _libpbd_system_exec_h_ */