Fix a tiny memory-leak when calling vfork
[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 #else // posix
41 #include <sys/types.h>
42 #include <sys/wait.h> /* WNOHANG is part of the exposed API */
43 #endif
44
45 #include <string>
46 #include <pthread.h>
47 #include <signal.h>
48 #include <map>
49
50 #ifdef NOPBD  /* unit-test outside ardour */
51 #include <sigc++/bind.h>
52 #include <sigc++/signal.h>
53 #else
54 #include "pbd/signals.h"
55 #endif
56
57 namespace PBD {
58
59 /** @class: SystemExec
60  *  @brief execute an external command
61  *
62  * This class allows launche an external command-line application
63  * opening a full-duplex connection to its standard I/O.
64  *
65  * In Ardour context it is used to launch xjadeo and ffmpeg.
66  *
67  * The \ref write_to_stdin function provides for injecting data into STDIN
68  * of the child-application while output of the program to STDOUT/STDERR is
69  * forwarded using the \ref ReadStdout signal.
70  * \ref Terminated is sent if the child application exits.
71  *
72  */
73 class LIBPBD_API SystemExec
74 {
75         public:
76                 /** prepare execution of a program with 'execve'
77                  *
78                  * This function takes over the existing environment variable and provides
79                  * an easy way to speciy command-line arguments for the new process.
80                  *
81                  * Note: The argument parser does not interpret quotation-marks and splits
82                  * arugments on whitespace. The argument string can be empty.
83                  * The alternative constructor below allows to specify quoted parameters
84                  * incl. whitespace.
85                  *
86                  * @param c program pathname that identifies the new process image file.
87                  * @param a string of commandline-arguments to be passed to the new program.
88                  */
89                 SystemExec (std::string c, std::string a = "");
90                 /** similar to \ref SystemExec but allows to specify custom arguments
91                  *
92                  * @param c program pathname that identifies the new process image file.
93                  * @param a array of argument strings passed to the new program as 'argv'.
94                  *          it must be terminated by a null pointer (see the 'evecve'
95                  *          POSIX-C documentation for more information)
96                  *          The array must be dynamically allocated using malloc or strdup.
97                  *          Unless they're NULL, the array itself and each of its content
98                  *          memory is freed() in the destructor.
99                  *
100                  */
101                 SystemExec (std::string c, char ** a);
102
103                 /** similar to \ref SystemExec but expects a whole command line, and
104                  * handles some simple escape sequences.
105                  *
106                  * @param command complete command-line to be executed
107                  * @param subs a map of <char, std::string> listing the % substitutions to
108                  *             be made.
109                  *
110                  * creates an argv array from the given command string, splitting into
111                  * parameters at spaces.
112                  * "\ " is non-splitting space, "\\" (and "\" at end of command) as "\",
113                  * for "%<char>", <char> is looked up in subs and the corresponding string
114                  * substituted. "%%" (and "%" at end of command)
115                  * returns an argv array suitable for creating a new SystemExec with
116                  */
117                 SystemExec (std::string command, const std::map<char, std::string> subs);
118
119                 virtual ~SystemExec ();
120
121                 static char* format_key_value_parameter (std::string, std::string);
122
123                 std::string to_s() const;
124
125                 /** fork and execute the given program
126                  *
127                  * @param stderr_mode select what to do with program's standard error
128                  * output:
129                  * '0': keep STDERR; mix it with parent-process' STDERR
130                  * '1': ignore STDERR of child-program
131                  * '2': merge STDERR into STDOUT and send it with the
132                  *      ReadStdout signal.
133                  * @return If the process is already running or was launched successfully
134                  * the function returns zero (0). A negative number indicates an error.
135                  */
136                 int start (int stderr_mode, const char *_vfork_exec_wrapper);
137                 /** kill running child-process
138                  *
139                  * if a child process exists trt to shut it down by closing its STDIN.
140                  * if the program dies not react try SIGTERM and eventually SIGKILL
141                  */
142                 void terminate ();
143                 /** check if the child programm is (still) running.
144                  *
145                  * This function calls waitpid(WNOHANG) to check the state of the
146                  * child-process.
147                  * @return true if the program is (still) running.
148                  */
149                 bool is_running ();
150                 /** call the waitpid system-call with the pid of the child-program
151                  *
152                  * Basically what \ref terminate uses internally.
153                  *
154                  * This function is only useful if you want to control application
155                  * termination yourself (eg timeouts or progress-dialog).
156                  * @param option flags - see waitpid manual
157                  * @return status info from waitpid call (not waitpid's return value)
158                  * or -1 if the child-program is not running.
159                  */
160                 int wait (int options=0);
161                 /** closes both STDIN and STDOUT connections to/from
162                  * the child-program.
163                  * With the output-interposer thread gone, the program
164                  * should terminate.
165                  * used by \ref terminate()
166                  */
167                 void close_stdin ();
168                 /** write into child-program's STDIN
169                  * @param d text to write
170                  * @param len length of data to write, if it is 0 (zero), d.length() is
171                  * used to determine the number of bytes to transmit.
172                  * @return number of bytes written.
173                  */
174                 size_t write_to_stdin (std::string const& d, size_t len=0);
175
176                 /** write into child-program's STDIN
177                  * @param data data to write
178                  * @param bytes length of data to write
179                  * @return number of bytes written.
180                  */
181                 size_t write_to_stdin (const void* d, size_t bytes=0);
182
183                 /** The ReadStdout signal is emitted when the application writes to STDOUT.
184                  * it passes the written data and its length in bytes as arguments to the bound
185                  * slot(s).
186                  */
187 #ifdef NOPBD  /* outside ardour */
188                 sigc::signal<void, std::string,size_t> ReadStdout;
189 #else
190                 PBD::Signal2<void, std::string,size_t> ReadStdout;
191 #endif
192
193                 /** The Terminated signal is emitted when application terminates. */
194 #ifdef NOPBD  /* outside ardour */
195                 sigc::signal<void> Terminated;
196 #else
197                 PBD::Signal0<void> Terminated;
198 #endif
199
200                 /** interposer to emit signal for writes to STDOUT/ERR.
201                  *
202                  * Thread that reads the stdout of the forked
203                  * process and signal-sends it to the main thread.
204                  * It also emits the Terminated() signal once
205                  * the the forked process closes it's stdout.
206                  *
207                  * Note: it's actually 'private' function but used
208                  * by the internal pthread, which only has a pointer
209                  * to this instance and thus can only access public fn.
210                  */
211                 void output_interposer ();
212
213         protected:
214                 std::string cmd; ///< path to command - set when creating the class
215                 int nicelevel; ///< process nice level - defaults to 0
216
217                 void make_argp(std::string);
218                 void make_argp_escaped(std::string command, const std::map<char, std::string> subs);
219                 void make_envp();
220
221                 char **argp;
222                 char **envp;
223
224         private:
225 #ifdef PLATFORM_WINDOWS
226                 PROCESS_INFORMATION *pid;
227                 HANDLE stdinP[2];
228                 HANDLE stdoutP[2];
229                 HANDLE stderrP[2];
230                 char *w_args;
231                 void make_wargs(char **);
232 #else
233                 pid_t pid;
234 # ifndef NO_VFORK
235                 char **argx;
236 # endif
237 #endif
238                 void init ();
239                 pthread_mutex_t write_lock;
240
241                 int pok[2];
242                 int pin[2];
243                 int pout[2];
244
245                 pthread_t      thread_id_tt;
246                 bool           thread_active;
247
248 }; /* end class */
249
250 }; /* end namespace */
251
252 #endif /* _libpbd_system_exec_h_ */