2

I want to run another program from c++, redirecting its output to a file and return its result code. But if I fail to run the program (incorrect path etc.) I want to know.

Here is my problem, how can I: redirect a file, get the result code of the program, get the errors of the system, all at once?

  • System(): returns the result and is easy to redirect, but there is no way to know if the result is a system error or the application result
  • posix_spawn(): I know if there is a system error, but how to get the application result code ?

Note that I don't control the code of the executed application It's easy with Windows (sorry...) OpenProcess() function, what I need is OpenProcess() under linux.

Thanks

Bernie
  • 1,489
  • 1
  • 16
  • 27
syp
  • 61
  • 2

2 Answers2

1

You will need to use the posix_spawn function.

The waitpid system call will help you to get the exit code.

See this question.

pid_t waitpid(pid_t pid, int *status, int options);
Community
  • 1
  • 1
ulidtko
  • 14,740
  • 10
  • 56
  • 88
1

What you need to do is pretty match standard fork-exec call plus file redirection:

int pid = fork();
if( pid == -1 ) {
   // process error here
}

if( pid == 0 ) {
   int fd = open( "path/to/redirected/output", ... );
   ::close( 1 );
   dup2( fd, 1 );
   ::close( fd );
   exec...( "path to executable", ... );
   // if we are here there is a problem
   exit(123);
}
int status = 0;
waitpid( pid, &status, 0 );
// you get exit status in status

By exec... I mean one of the exec functions family (type "man 3 exec" for information), choose one that fits you better. If you need to redirect error output do the same, but use descriptor 2. You may want to put waitpid() in the loop and check if it is not interrupted by signal.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • great ! waitpid is the function I need thank you - Im more confortable with Windows and miss some linux basics ;) – syp Mar 06 '13 at 23:12