File: tjprocess.cpp

package info (click to toggle)
odin 2.0.5-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,196 kB
  • sloc: cpp: 62,638; sh: 4,541; makefile: 779
file content (462 lines) | stat: -rw-r--r-- 12,513 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#include "tjprocess.h"
#include "tjtest.h"
#include "tjlog_code.h"

#ifndef NO_PROCESSHANDLING

#ifdef USING_WIN32

// Win-style process handling
#include <process.h>
#include <fcntl.h>
#include <windows.h>
#include <io.h>

#else // USING_WIN32

#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_SYS_TYPES_H) && defined(HAVE_UNISTD_H) && defined(HAVE_SIGNAL_H)

// Unix-style process handling
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#define USING_UNIX_PROCESSES

#else // unix headers

#warning "no process handling style selected"

#endif // unix headers

#endif // USING_WIN32

#endif // NO_PROCESSHANDLING

///////////////////////////////////////////////////////////

const char* ProcessComponent::get_compName() {return "Process";}
LOGGROUNDWORK(ProcessComponent)

///////////////////////////////////////////////////////////

// quick hack to kill pending cc1plus process
void kill_additional_procs(const svector& extra_kill) {
  Log<ProcessComponent> odinlog("","kill_additional_procs");

#ifdef USING_UNIX_PROCESSES
  if(!extra_kill.size()) return;

  STD_string pslist;
  STD_string stderrstr;

  Process ps;
  if(!ps.start("ps")) return;
  int retval;
  if(!ps.finished(retval, pslist, stderrstr, true)) return;

  ODINLOG(odinlog,normalDebug) << "pslist=" << pslist << STD_endl;

  svector toks(tokens(pslist));

  if(toks.size()<8) return;

  for(unsigned int i=4; i<toks.size(); i++) {
    for(unsigned int iextra=0; iextra<extra_kill.size(); iextra++) {
      if(toks[i]==extra_kill[iextra]) {
        int pspid=atoi(toks[i-3].c_str());
        kill(pspid,SIGKILL);
      }
    }
  }
#endif
}

///////////////////////////////////////////////////////////


bool Process::start(const STD_string& cmdline, bool block_till_finished, bool log_std_streams) {
  Log<ProcessComponent> odinlog("Process","start");

#ifdef NO_PROCESSHANDLING
  ODINLOG(odinlog,errorLog) << "NO_PROCESSHANDLING defined" << STD_endl;
  return false;
#endif

  svector cmdtoks(tokens(cmdline));
  unsigned int ntoks=cmdtoks.size();
  if(!ntoks) {
    ODINLOG(odinlog,errorLog) << "empty cmdline" << STD_endl;
    return false;
  }

  // kill previously started process
  kill(); // will reset pid, stdout/stderr_child

#ifndef HAVE_READ
  if(log_std_streams) {
    ODINLOG(odinlog,errorLog) << "Cannot log_std_streams without read" << STD_endl;
    return false;
  }
#endif

  int pipefd_stdout[2]; // pair of file descriptors for stdout pipe
  int pipefd_stderr[2]; // pair of file descriptors for stderr pipe

  if(log_std_streams) {
    bool pipeerror=false;
#ifdef USING_UNIX_PROCESSES
    if(pipe(pipefd_stdout)==-1) pipeerror=true;
    if(pipe(pipefd_stderr)==-1) pipeerror=true;
#endif
#ifdef USING_WIN32
    if(_pipe( pipefd_stdout, 10000,  O_NOINHERIT | O_BINARY)==-1) pipeerror=true;
    if(_pipe( pipefd_stderr, 10000,  O_NOINHERIT | O_BINARY)==-1) pipeerror=true;
#endif
    if(pipeerror) {
      ODINLOG(odinlog,errorLog) << "pipe: " << lasterr() << STD_endl;
      return false;
    }
  }

#ifdef USING_UNIX_PROCESSES
  pid = ::fork();
#endif

#ifdef USING_WIN32
  const char* args[100];
  if(ntoks>=100) {
    ODINLOG(odinlog,errorLog) << "too many args" << STD_endl;
    return false;
  }
  STD_string prog(replaceStr(cmdtoks[0],"\"",""));
  ODINLOG(odinlog,normalDebug) << "prog=" << prog << STD_endl;
  for(unsigned int itok=0; itok<ntoks; itok++) {
    args[itok]=cmdtoks[itok].c_str();
    ODINLOG(odinlog,normalDebug) << "args[" << itok << "]=" << args[itok] << STD_endl;
  }
  args[ntoks]=NULL;


  int fdStdOut=-1;
  int fdStdErr=-1;
  if(log_std_streams) {
    // the following code is taken from MSDN manual page for _pipe
    // Duplicate stdout/stderr file descriptor (next line will close original)
    fdStdOut = _dup(_fileno(stdout));
    fdStdErr = _dup(_fileno(stderr));

    // Duplicate write end of pipe to stdout/stderr file descriptor
    if(_dup2(pipefd_stdout[1], _fileno(stdout))) {
      ODINLOG(odinlog,errorLog) << "_dup2(pre,stdout): " << lasterr() << STD_endl;
      return false;
    }
    if(_dup2(pipefd_stderr[1], _fileno(stderr))) {
      ODINLOG(odinlog,errorLog) << "_dup2(pre,stderr): " << lasterr() << STD_endl;
      return false;
    }

    // Close original write end of pipe
    close(pipefd_stdout[1]);
    close(pipefd_stderr[1]);

    stdout_child=pipefd_stdout[0]; // store for later use
    stderr_child=pipefd_stderr[0]; // store for later use
  }


  // Spawn process
  pid = _spawnv( _P_NOWAIT, prog.c_str(), args );


  if(log_std_streams) {
    // Duplicate copy of original stdout back into stdout
    if(_dup2(fdStdOut, _fileno(stdout))) {
      ODINLOG(odinlog,errorLog) << "_dup2(post,stdout): " << lasterr() << STD_endl;
      return false;
    }
    if(_dup2(fdStdErr, _fileno(stderr))) {
      ODINLOG(odinlog,errorLog) << "_dup2(post,stderr): " << lasterr() << STD_endl;
      return false;
    }

    // Close duplicate copy of original stdout
    close(fdStdOut);
    close(fdStdErr);
  }

#endif  // ifdef USING_WIN32

  if (pid == -1) {
    ODINLOG(odinlog,errorLog) << lasterr() << STD_endl;
    pid=0;
    return false;
  }


#ifdef USING_UNIX_PROCESSES
  if (pid == 0) {
    ODINLOG(odinlog,normalDebug) << "in child, pid=" << pid << STD_endl;

    if(log_std_streams) {
      close(pipefd_stdout[0]); // Close unused read end
      close(pipefd_stderr[0]); // Close unused read end
      dup2(pipefd_stdout[1], STDOUT_FILENO); // Make stdout become the write end of the pipe
      dup2(pipefd_stderr[1], STDERR_FILENO); // Make stderr become the write end of the pipe
    }

    // Use shell so that cmdline args are passed properly, i.e. we do not have to tokenize them ourselves
    char *argv[4];
    argv[0] = (char*)"sh";
    argv[1] = (char*)"-c";
    argv[2] = (char*)cmdline.c_str();  // arggg!
    argv[3] = 0;
    execv("/bin/sh", argv);

    // Error has occurred at this point

    ODINLOG(odinlog,errorLog) << "execv: " << lasterr() << STD_endl;

    if(log_std_streams) {
      close(pipefd_stdout[1]); // Close write end
      close(pipefd_stderr[1]); // Close write end
    }

    exit(-1);

  } else {
    ODINLOG(odinlog,normalDebug) << "in parent, pid=" << pid << STD_endl;
    if(log_std_streams) {
      stdout_child=pipefd_stdout[0]; // Store for later use
      stderr_child=pipefd_stderr[0]; // Store for later use
      close(pipefd_stdout[1]); // Close unused write end
      close(pipefd_stderr[1]); // Close unused write end
    }
  }

#endif

  if(block_till_finished) {
    int retval=0;
    Process::finished(retval, true); // Wait till process is done
  }

  return true;
}


bool Process::finished(int& proc_return_value, STD_string& stdout_result, STD_string& stderr_result, bool block_till_finished) {
  Log<ProcessComponent> odinlog("Process","finished");

  proc_return_value=0;
  stdout_result="";
  stderr_result="";

  int childstat=0;
#ifdef USING_UNIX_PROCESSES
  int options=0;
  if(!block_till_finished) options=WNOHANG;
  int status=0;
  childstat=waitpid(pid, &status, options);
  if( (childstat==-1) && (errno!=EINTR) ) {
    ODINLOG(odinlog,errorLog) << "waitpid(" << pid << ") failed " << STD_endl;
    return true;
  }
  proc_return_value=WEXITSTATUS(status);
  ODINLOG(odinlog,normalDebug) << "childstat/proc_return_value=" << childstat << "/" << proc_return_value << STD_endl;
#endif

#ifdef USING_WIN32
  childstat=1;
  DWORD timeout=0;
  if(block_till_finished) timeout=INFINITE;
  ODINLOG(odinlog,normalDebug) << "pid=" << pid << STD_endl;
  DWORD dw=WaitForSingleObject((HANDLE)int(pid),timeout);
  ODINLOG(odinlog,normalDebug) << "dw=" << dw << STD_endl;
  if(dw==WAIT_TIMEOUT) childstat=0; // still running
  if(dw==WAIT_ABANDONED) {
    ODINLOG(odinlog,errorLog) << "WaitForSingleObject(" << pid << ") failed " << STD_endl;
    proc_return_value=-1;
    return true;
  }
  ODINLOG(odinlog,normalDebug) << "childstat=" << childstat << STD_endl;
  if(childstat) {
    unsigned long status_l;
    if(!GetExitCodeProcess((HANDLE)int(pid),&status_l)) {
      ODINLOG(odinlog,errorLog) << "GetExitCodeProcess(" << pid << ") failed " << STD_endl;
      proc_return_value=-1;
      return true;
    }
    proc_return_value=status_l;
  }
#endif


  // Get stdout/stderr of child process if finished, i.e. if childstat!=0
  if(childstat) {
    pid=0;

    ODINLOG(odinlog,normalDebug) << "stdout_child/stderr_child=" << stdout_child << "/" << stderr_child << STD_endl;

    // Get output if available
    if(stdout_child!=-1) {read_pipe(stdout_child, stdout_result); stdout_child=-1;}
    if(stderr_child!=-1) {read_pipe(stderr_child, stderr_result); stderr_child=-1;}

    return true;
  }

  return false;
}


bool Process::finished(int& proc_return_value, bool block_till_finished) {
  Log<ProcessComponent> odinlog("Process","finished");

  bool console_log= ( stdout_child==-1 || stderr_child==-1 ); // Check before calling finish()

  STD_string coutstr;
  STD_string cerrstr;
  bool result=Process::finished(proc_return_value,coutstr,cerrstr,block_till_finished);

  if(console_log) { // We are logging directly to the console
    STD_cout << coutstr;
    STD_cerr << cerrstr;
  } else {
    if(coutstr.length()) {
      ODINLOG(odinlog,infoLog) << coutstr; // dump stdout result of child process
    }
    if(cerrstr.length()) {
      ODINLOG(odinlog,errorLog) << cerrstr; // dump stderr result of child process
    }
  }
  return result;
}


bool Process::read_pipe(int fd, STD_string& result) {
  Log<ProcessComponent> odinlog("Process","read_pipe");
  char buff[ODIN_MAXCHAR+1];
  result="";
  while(true) {
    int nbytes=0;
#ifdef HAVE_READ
    nbytes=read(fd, (void*)buff, ODIN_MAXCHAR);
#else
    ODINLOG(odinlog,errorLog) << "read missing"<< STD_endl;
    return false;
#endif
    if(nbytes<0) {
      ODINLOG(odinlog,errorLog) << "read: " << lasterr() << STD_endl;
      return false;
    }
    if(!nbytes) break;
    buff[nbytes]='\0';
    result+=buff;
  }

#if defined(USING_UNIX_PROCESSES) || defined(USING_WIN32)
  close(fd);
#endif

  return true;
}




bool Process::kill(const svector& extra_kill) {
  Log<ProcessComponent> odinlog("Process","kill");
  ODINLOG(odinlog,normalDebug) << "pid=" << pid << STD_endl;

  if(pid) {
    ODINLOG(odinlog,normalDebug) << "Sending SIGKILL to process " << pid << STD_endl;
#ifdef USING_UNIX_PROCESSES
    ::kill(pid,SIGKILL);
#endif
#ifdef USING_WIN32
    TerminateProcess((HANDLE)int(pid),0);
#endif
  }
  kill_additional_procs(extra_kill);

  reset();

  return true;
}


int Process::system(const STD_string& cmdline, STD_string& stdout_result, STD_string& stderr_result) {

  Process proc;

  if(!proc.start(cmdline)) return -1;

  int proc_return_value=-1;
  if(!proc.finished(proc_return_value, stdout_result, stderr_result, true)) return -1;

  return proc_return_value;
}



////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

#ifndef NO_UNIT_TEST


class ProcessTest : public UnitTest {

 public:
  ProcessTest() : UnitTest("process") {}

 private:

  bool check() const {
    Log<UnitTest> odinlog(this,"check");

//#ifdef USING_UNIX_PROCESSES // stdout_result not implemented yet for win32

    Process proc;

//    STD_string cmd("ping -c 1 localhost");
    STD_string cmd("echo teststring");

#ifdef USING_WIN32
//    cmd=STD_string(getenv_nonnull("WINDIR"))+SEPARATOR_STR+"system32"+SEPARATOR_STR+"ping.exe -n 1 localhost";
    cmd=STD_string(getenv_nonnull("WINDIR"))+SEPARATOR_STR+"system32"+SEPARATOR_STR+"cmd.exe /C \"echo teststring\"";
#endif

    if(!proc.start(cmd)) {
      ODINLOG(odinlog,errorLog) << "start failed, cmd=" << cmd << STD_endl;
      return false;
    }

    int proc_return_value;
    STD_string stdout_result;
    STD_string stderr_result;
    if(!proc.finished(proc_return_value, stdout_result, stderr_result, true)) {
      ODINLOG(odinlog,errorLog) << "finished failed" << STD_endl;
      return false;
    }
    if(proc_return_value) {
      ODINLOG(odinlog,errorLog) << "proc_return_value=" << proc_return_value << STD_endl;
      return false;
    }

//    if(stdout_result.find("127.0.0.1")==STD_string::npos) {
    if(stdout_result.find("teststring")==STD_string::npos) {
      ODINLOG(odinlog,errorLog) << "stdout_result=>" << stdout_result << "<";
      return false;
    }
//#endif

    return true;
  }

};


void alloc_ProcessTest() {new ProcessTest();} // create test instance
#endif