syp
syp

Reputation: 61

run a process with c++, filtering output AND get result code AND get system errors, all together

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?

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

Upvotes: 2

Views: 542

Answers (2)

Slava
Slava

Reputation: 44258

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.

Upvotes: 1

ulidtko
ulidtko

Reputation: 15560

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);

Upvotes: 1

Related Questions