How do I get the return value of a execv?
Question
I am really new to C++ and I am trying to get the output from:
execv("./rdesktop",NULL);
I am programming in C++ and on RHEL 6.
Like a FTP client, I would like to get all the status updates from my external running program. Can someone please tell me how I could do this?
Solution
You can examine the exit status of a child process by calling wait
, waitpid
, wait3
or wait4
.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
pid_t pid = fork();
switch(pid) {
case 0:
// We are the child process
execl("/bin/ls", "ls", NULL);
// If we get here, something is wrong.
perror("/bin/ls");
exit(255);
default:
// We are the parent process
{
int status;
if( waitpid(pid, &status, 0) < 0 ) {
perror("wait");
exit(254);
}
if(WIFEXITED(status)) {
printf("Process %d returned %d\n", pid, WEXITSTATUS(status));
exit(WEXITSTATUS(status));
}
if(WIFSIGNALED(status)) {
printf("Process %d killed: signal %d%s\n",
pid, WTERMSIG(status),
WCOREDUMP(status) ? " - core dumped" : "");
exit(1);
}
}
case -1:
// fork failed
perror("fork");
exit(1);
}
}
OTHER TIPS
execv
replaces the current process, so immediately after executing it what's executing will be whatever executable you specified.
Normally you do a fork
, and then execv
only in the child process. The parent process receives the PID of the new child, which it can use to monitor the child's execution.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow