2 // Name : launch_process
3 // Author : Chris Koeritz
4 /******************************************************************************
5 * Copyright (c) 1994-$now By Author. This program is free software; you can *
6 * redistribute it and/or modify it under the terms of the GNU General Public *
7 * License as published by the Free Software Foundation; either version 2 of *
8 * the License or (at your option) any later version. This is online at: *
9 * http://www.fsf.org/copyleft/gpl.html *
10 * Please send any updates to: fred@gruntose.com *
11 \*****************************************************************************/
13 #include "launch_process.h"
15 #include <application/windoze_helper.h>
16 #include <basis/utf_conversion.h>
17 #include <basis/mutex.h>
18 #include <configuration/application_configuration.h>
19 #include <loggers/critical_events.h>
20 #include <loggers/program_wide_logger.h>
21 #include <structures/set.h>
22 #include <timely/time_control.h>
27 #include <sys/types.h>
38 //#define DEBUG_LAUNCH_PROCESS
39 // uncomment for noisier debugging info.
41 using namespace basis;
42 using namespace configuration;
43 using namespace loggers;
44 using namespace structures;
45 using namespace timely;
48 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s);
52 //hmmm: some of these should probably be safe statics.
54 mutex &__process_synchronizer() {
55 static mutex __hidden_synch;
56 return __hidden_synch;
59 int_set __our_kids() {
60 static int_set __hidden_kids;
66 bool launch_process::event_poll(MSG &message)
72 if (!PeekMessage(&message, NULL_POINTER, 0, 0, PM_REMOVE))
74 TranslateMessage(&message);
75 DispatchMessage(&message);
81 #define SUPPORT_SHELL_EXECUTE
82 // if this is not commented out, then the ShellExecute version of launch_
83 // -process() is available. when commented out, ShellExecute is turned off.
84 // disabling this support is the most common because the ShellExecute method
85 // in win32 was only supported for wk203 and wxp, that is only after
86 // windows2000 was already available. since nt and w2k don't support this,
87 // we just usually don't mess with it. it didn't answer a single one of our
88 // issues on windows vista (wfista) anyway, so it's not helping.
90 //const int MAXIMUM_COMMAND_LINE = 32 * KILOBYTE;
91 // maximum command line that we'll deal with here.
94 void launch_process::exiting_child_signal_handler(int sig_num)
96 FUNCDEF("exiting_child_signal_handler");
97 if (sig_num != SIGCHLD) {
98 // uhhh, this seems wrong.
100 auto_synchronizer l(__process_synchronizer());
101 for (int i = 0; i < __our_kids().length(); i++) {
103 pid_t exited = waitpid(__our_kids()[i], &status, WNOHANG);
104 if ( (exited == -1) || (exited == __our_kids()[i]) ) {
105 // negative one denotes an error, which we are going to assume means the
106 // process has exited via some other method than our wait. if the value
107 // is the same as the process we waited for, that means it exited.
108 __our_kids().zap(i, i);
110 } else if (exited != 0) {
111 // zero would be okay; this result we do not understand.
112 #ifdef DEBUG_LAUNCH_PROCESS
113 LOG(a_sprintf("unknown result %d waiting for process %d", exited, __our_kids()[i]));
120 //hmmm: this doesn't seem to account for quoting properly at all?
121 char_star_array launch_process::break_line(astring &app, const astring ¶meters)
123 FUNCDEF("break_line");
124 char_star_array to_return;
127 // find the positions of the spaces and count them.
128 for (int j = 0; j < parameters.length(); j++) {
129 if (parameters[j] == ' ') {
134 // first, add the app name to the list of parms.
135 to_return += new char[app.length() + 1];
136 app.stuff(to_return[0], app.length());
138 // now add each space-separated parameter to the list.
139 for (int i = 0; i < num; i++) {
140 int len = posns[i] - last_posn;
141 to_return += new char[len + 1];
142 parameters.substring(last_posn, posns[i] - 1).stuff(to_return[i + 1], len);
143 last_posn = posns[i] + 1;
145 // catch anything left after last separator.
146 if (last_posn < parameters.length() - 1) {
147 int len = parameters.length() - last_posn;
148 to_return += new char[len + 1];
149 parameters.substring(last_posn, parameters.length() - 1)
150 .stuff(to_return[to_return.last()], len);
152 // add the sentinel to the list of strings.
153 to_return += NULL_POINTER;
154 #ifdef DEBUG_LAUNCH_PROCESS
155 for (int q = 0; to_return[q]; q++) {
156 LOG(a_sprintf("%d: %s\n", q, to_return[q]));
159 // now a special detour; fix the app name to remove quotes, which are
160 // not friendly to pass to exec.
161 if (app[0] == '"') app.zap(0, 0);
162 if (app[app.end()] == '"') app.zap(app.end(), app.end());
166 basis::un_int launch_process::run(const astring &app_name_in, const astring &command_line,
167 int flag, basis::un_int &child_id)
169 #ifdef DEBUG_LAUNCH_PROCESS
173 astring app_name = app_name_in;
174 if (app_name[0] != '"')
175 app_name.insert(0, "\"");
176 if (app_name[app_name.end()] != '"')
178 //#if defined(__UNIX__) || defined(__GNU_WINDOWS__)
179 // unix / linux implementation.
180 if (flag & RETURN_IMMEDIATELY) {
181 // they want to get back right away.
182 pid_t kid_pid = fork();
183 #ifdef DEBUG_LAUNCH_PROCESS
184 LOG(a_sprintf("launch fork returned %d\n", kid_pid));
187 // this is the child; we now need to launch into what we were asked for.
188 #ifdef DEBUG_LAUNCH_PROCESS
189 LOG(a_sprintf("process %d execing ", application_configuration::process_id()) + app_name
190 + " parms " + command_line + "\n");
192 char_star_array parms = break_line(app_name, command_line);
193 execv(app_name.s(), parms.observe());
194 // oops. failed to exec if we got to here.
195 #ifdef DEBUG_LAUNCH_PROCESS
196 LOG(a_sprintf("child of fork (pid %d) failed to exec, error is ",
197 application_configuration::process_id())
198 + critical_events::system_error_text(critical_events::system_error())
201 exit(0); // leave since this is a failed child process.
203 // this is the parent. let's see if the launch worked.
206 basis::un_int to_return = critical_events::system_error();
207 #ifdef DEBUG_LAUNCH_PROCESS
208 LOG(a_sprintf("parent %d is returning after failing to create, "
209 "error is ", application_configuration::process_id())
210 + critical_events::system_error_text(to_return)
215 // yes, launch worked okay.
218 auto_synchronizer l(__process_synchronizer());
219 __our_kids() += kid_pid;
221 // hook in our child exit signal handler.
222 signal(SIGCHLD, exiting_child_signal_handler);
224 #ifdef DEBUG_LAUNCH_PROCESS
225 LOG(a_sprintf("parent %d is returning after successfully "
226 "creating %d ", application_configuration::process_id(), kid_pid) + app_name
227 + " parms " + command_line + "\n");
233 // assume they want to wait.
234 return system((app_name + " " + command_line).s());
237 #elif defined(_MSC_VER)
239 //checking on whether we have admin rights for the launch.
240 //if (IsUserAnAdmin()) {
241 // MessageBox(0, (astring("IS admin with ") + app_name_in + " " + command_line).s(), "launch process", MB_OK);
243 // MessageBox(0, (astring("NOT admin for ") + app_name_in + " " + command_line).s(), "launch process", MB_OK);
246 PROCESS_INFORMATION process_info;
247 ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
249 #ifdef SUPPORT_SHELL_EXECUTE
250 if (flag & SHELL_EXECUTE) {
251 // new code for using shell execute method--required on vista for proper
252 // launching with the right security tokens.
254 if (flag & HIDE_APP_WINDOW) {
255 // magic that hides a console window for mswindows.
258 show_cmd = SW_SHOWNORMAL;
261 SHELLEXECUTEINFO exec_info;
262 ZeroMemory(&exec_info, sizeof(SHELLEXECUTEINFO));
263 exec_info.cbSize = sizeof(SHELLEXECUTEINFO);
264 exec_info.fMask = SEE_MASK_NOCLOSEPROCESS // get the process info.
265 | SEE_MASK_FLAG_NO_UI; // turn off any visible error dialogs.
266 exec_info.hwnd = GetDesktopWindow();
267 //hmmm: is get desktop window always appropriate?
268 to_unicode_persist(temp_verb, "open");
269 //does "runas" work on xp also? or anywhere?
270 exec_info.lpVerb = temp_verb;
271 to_unicode_persist(temp_file, app_name);
272 exec_info.lpFile = temp_file;
273 to_unicode_persist(temp_parms, command_line);
274 exec_info.lpParameters = temp_parms;
275 exec_info.nShow = show_cmd;
276 // exec_info.hProcess = &process_info;
278 BOOL worked = ShellExecuteEx(&exec_info);
280 return critical_events::system_error();
281 // copy out the returned process handle.
282 process_info.hProcess = exec_info.hProcess;
283 process_info.dwProcessId = GetProcessId(exec_info.hProcess);
286 // standard windows implementation using CreateProcess.
287 STARTUPINFO startup_info;
288 ZeroMemory(&startup_info, sizeof(STARTUPINFO));
289 startup_info.cb = sizeof(STARTUPINFO);
291 if (flag & HIDE_APP_WINDOW) {
292 // magic that hides a console window for mswindows.
293 // version ver = portable::get_OS_version();
294 // version vista_version(6, 0);
295 // if (ver < vista_version) {
296 // // we suspect that this flag is hosing us in vista.
297 create_flag = CREATE_NO_WINDOW;
300 astring parms = app_name + " " + command_line;
301 bool success = CreateProcess(NULL_POINTER, to_unicode_temp(parms), NULL_POINTER, NULL_POINTER, false,
302 create_flag, NULL_POINTER, NULL_POINTER, &startup_info, &process_info);
304 return critical_events::system_error();
305 // success then, merge back into stream.
307 #ifdef SUPPORT_SHELL_EXECUTE
311 // common handling for CreateProcess and ShellExecuteEx.
312 child_id = process_info.dwProcessId;
313 basis::un_long retval = 0;
314 if (flag & AWAIT_VIA_POLLING) {
315 // this type of waiting is done without blocking on the process.
319 // check if the process is gone yet.
320 BOOL ret = GetExitCodeProcess(process_info.hProcess, &retval);
324 // if they aren't saying it's still active, then we will leave.
325 if (retval != STILL_ACTIVE)
328 time_control::sleep_ms(14);
330 } else if (flag & AWAIT_APP_EXIT) {
331 // they want to wait for the process to exit.
332 WaitForInputIdle(process_info.hProcess, INFINITE);
333 WaitForSingleObject(process_info.hProcess, INFINITE);
334 GetExitCodeProcess(process_info.hProcess, &retval);
336 // drop the process and thread handles.
337 if (process_info.hProcess)
338 CloseHandle(process_info.hProcess);
339 if (process_info.hThread)
340 CloseHandle(process_info.hThread);
341 return (basis::un_int)retval;
343 #pragma error("hmmm: launch_process: no implementation for this OS.")