2 Copyright (C) 2010 Paul Davis
3 Author: Robin Gareus <robin@gareus.org>
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.
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.
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.
20 #ifdef WITH_VIDEOTIMELINE
32 #include <sys/types.h>
34 #include <sys/socket.h>
37 #include "system_exec.h"
40 void * interposer_thread (void *arg);
42 SystemExec::SystemExec (std::string c, std::string a)
45 pthread_mutex_init(&write_lock, NULL);
53 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
54 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
55 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
61 SystemExec::SystemExec (std::string c, char **a)
64 pthread_mutex_init(&write_lock, NULL);
71 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
72 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
73 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
79 SystemExec::~SystemExec ()
83 for (int i=0;envp[i];++i) {
89 for (int i=0;argp[i];++i) {
95 if (w_args) free(w_args);
97 pthread_mutex_destroy(&write_lock);
101 interposer_thread (void *arg) {
102 SystemExec *sex = static_cast<SystemExec *>(arg);
103 sex->output_interposer();
108 #ifdef __WIN32__ /* Windows Process */
110 /* HELPER FUNCTIONS */
112 static void create_pipe (HANDLE *pipe, bool in) {
113 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
116 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
117 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
119 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
120 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
122 CloseHandle(tmpHandle);
125 static void destroy_pipe (HANDLE pipe[2]) {
126 if (pipe[0] != INVALID_HANDLE_VALUE) {
127 CloseHandle(pipe[0]);
128 pipe[0] = INVALID_HANDLE_VALUE;
130 if (pipe[1] != INVALID_HANDLE_VALUE) {
131 CloseHandle(pipe[1]);
132 pipe[1] = INVALID_HANDLE_VALUE;
136 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
138 DWORD currentProcId = 0;
139 GetWindowThreadProcessId(hwnd, ¤tProcId);
140 if (currentProcId == (DWORD)procId)
141 PostMessage(hwnd, WM_CLOSE, 0, 0);
148 SystemExec::make_envp() {
149 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
153 SystemExec::make_wargs(char **a) {
154 std::string wa = cmd;
155 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
156 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
158 while (tmp && *tmp) {
164 w_args = strdup(wa.c_str());
168 SystemExec::make_argp(std::string args) {
169 std::string wa = cmd;
170 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
171 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
174 w_args = strdup(wa.c_str());
178 SystemExec::terminate ()
180 ::pthread_mutex_lock(&write_lock);
183 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
184 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
187 TerminateProcess(pid->hProcess, 0xf291);
189 CloseHandle(pid->hThread);
190 CloseHandle(pid->hProcess);
191 destroy_pipe(stdinP);
192 destroy_pipe(stdoutP);
193 destroy_pipe(stderrP);
197 ::pthread_mutex_unlock(&write_lock);
201 SystemExec::wait (int options)
203 while (is_running()) {
204 WaitForSingleObject(pid->hProcess, INFINITE);
211 SystemExec::is_running ()
213 return pid?true:false;
217 SystemExec::start (int stderr_mode)
219 char* working_dir = 0;
221 if (pid) { return 0; }
223 pid = new PROCESS_INFORMATION;
224 memset(pid, 0, sizeof(PROCESS_INFORMATION));
226 create_pipe(stdinP, true);
227 create_pipe(stdoutP, false);
229 if (stderr_mode == 2) {
230 /* merge stout & stderr */
231 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
232 } else if (stderr_mode == 1) {
233 //TODO read/flush this pipe or close it...
234 create_pipe(stderrP, false);
236 //TODO: keep stderr of this process mode.
239 bool success = false;
240 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
241 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
242 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
244 STARTF_USESTDHANDLES,
246 stdinP[0], stdoutP[1], stderrP[1]
249 success = CreateProcess(0, w_args,
250 0, 0, /* bInheritHandles = */ TRUE,
251 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
256 if (stdinP[0] != INVALID_HANDLE_VALUE) {
257 CloseHandle(stdinP[0]);
258 stdinP[0] = INVALID_HANDLE_VALUE;
260 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
261 CloseHandle(stdoutP[1]);
262 stdoutP[1] = INVALID_HANDLE_VALUE;
264 if (stderrP[1] != INVALID_HANDLE_VALUE) {
265 CloseHandle(stderrP[1]);
266 stderrP[1] = INVALID_HANDLE_VALUE;
270 CloseHandle(pid->hThread);
271 CloseHandle(pid->hProcess);
272 destroy_pipe(stdinP);
273 destroy_pipe(stdoutP);
274 destroy_pipe(stderrP);
280 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
292 SystemExec::output_interposer()
297 #if 0 // for non-blocking pipes..
298 DWORD bytesAvail = 0;
299 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
300 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
302 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
303 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
304 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
306 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
308 Terminated();/* EMIT SIGNAL */
312 SystemExec::close_stdin()
314 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
315 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
317 destroy_pipe(stdinP);
321 SystemExec::write_to_stdin(std::string d, size_t len)
326 ::pthread_mutex_lock(&write_lock);
334 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
335 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
339 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
345 ::pthread_mutex_unlock(&write_lock);
350 /* end windows process */
352 /* UNIX/POSIX process */
354 extern char **environ;
356 SystemExec::make_envp() {
358 envp = (char **) calloc(1, sizeof(char*));
359 /* copy current environment */
360 for (i=0;environ[i];++i) {
361 envp[i] = strdup(environ[i]);
362 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
368 SystemExec::make_argp(std::string args) {
373 char *carg = strdup(args.c_str());
375 argp = (char **) malloc((argn + 1) * sizeof(char *));
376 if (argp == (char **) 0) {
381 argp[0] = strdup(cmd.c_str());
383 /* TODO: quotations and escapes
384 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
386 * It's actually not needed. All relevant invocations specify 'argp' directly.
387 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
388 * nor arguments with white-space.
390 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
393 argp[argn++] = strdup(cp1);
395 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
399 argp[argn++] = strdup(cp1);
400 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
402 argp[argn] = (char *) 0;
409 SystemExec::terminate ()
411 ::pthread_mutex_lock(&write_lock);
419 ::fprintf(stderr, "Child process is running. trying SIGTERM\n");
420 ::kill(pid, SIGTERM);
425 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
426 ::kill(pid, SIGKILL);
430 if (thread_active) pthread_join(thread_id_tt, NULL);
431 thread_active = false;
432 ::pthread_mutex_unlock(&write_lock);
436 SystemExec::wait (int options)
439 if (pid==0) return -1;
440 if (pid==::waitpid(pid, &status, options)) {
443 if (errno == ECHILD) {
450 SystemExec::is_running ()
453 if (pid==0) return false;
454 if (::waitpid(pid, &status, WNOHANG)==0) return true;
459 SystemExec::start (int stderr_mode)
462 return 0; // mmh what to return here?
466 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
467 /* Something unexpected went wrong creating a pipe. */
481 /* check if execve was successful. */
485 int n = ::read(pok[0], &buf, 1 );
487 /* child process returned from execve */
496 } else if ( n==-1 ) {
497 if ( errno==EAGAIN || errno==EINTR )
503 /* child started successfully */
506 /* use fork for output-interposer
507 * it will run in a separated process
509 /* catch stdout thread */
517 /* 2nd child process - catch stdout */
526 #else /* use pthread */
529 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
538 return 0; /* all systems go - return to main */
541 /* child process - exec external process */
543 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
546 if (pin[0] != STDIN_FILENO) {
547 ::dup2(pin[0], STDIN_FILENO);
551 if (pout[1] != STDOUT_FILENO) {
552 ::dup2(pout[1], STDOUT_FILENO);
555 if (stderr_mode == 2) {
556 /* merge STDERR into output */
557 if (pout[1] != STDERR_FILENO) {
558 ::dup2(pout[1], STDERR_FILENO);
560 } else if (stderr_mode == 1) {
562 ::close(STDERR_FILENO);
567 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
576 /* chdir to executable dir */
578 directory = strdup(cmd.c_str());
579 if (strrchr(directory, '/') != (char *) 0) {
586 sigset(SIGPIPE, SIG_DFL);
588 signal(SIGPIPE, SIG_DFL);
591 ::execve(argp[0], argp, envp);
592 /* if we reach here something went wrong.. */
594 (void) ::write(pok[1], &buf, 1 );
595 (void) ::close(pok[1]);
601 SystemExec::output_interposer()
606 for (;fcntl(rfd, F_GETFL)!=-1;) {
607 r = read(rfd, buf, sizeof(buf));
608 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
616 std::string rv = std::string(buf,r); // TODO: check allocation strategy
617 ReadStdout(rv, r);/* EMIT SIGNAL */
619 Terminated();/* EMIT SIGNAL */
623 SystemExec::close_stdin()
625 if (pin[1]<0) return;
630 pin[1] = - 1; // mark as closed
634 SystemExec::write_to_stdin(std::string d, size_t len)
638 ::pthread_mutex_lock(&write_lock);
647 r=::write(pin[1], data+c, len-c);
648 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
653 ::pthread_mutex_unlock(&write_lock);
661 ::pthread_mutex_unlock(&write_lock);
665 #endif // end UNIX process
667 #endif /* WITH_VIDEOTIMELINE */