Grabbing the return value from execv()

2019-02-24 18:08发布

问题:

//code for foo (run executable as ./a.out)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/wait.h>

int main (int argc, char **argv) {
pid_t pid;
pid = fork();
int i = 1;
char *parms[] = {"test2", "5", NULL}; //test executable named test2   
if(pid < 0) {
        fprintf(stderr, "Fork failed");
        return 1;
}
else if(pid == 0) {
        printf("Child pid is %d\n", pid);
        i = execv("test2", parms);  //exec call to test with a param of 5
}
else {
        wait(NULL);
}
printf("I is now %d\n", i); //i is still 1 here, why?
return 0;
}

Hey everybody, I am trying to learn a little bit about fork and execv() calls. I make my foo.c program above make a call to a file I have named test.c. I fork a child and have the child make a call to execv, which will just add 10 to the parameter read in. I am unsure of why the variable does not change, at the bottom of my foo.c function. Does the call need to be a pointer or return an address? Any help would be greatly appreciated. Thanks

Code for test.c (executable named test2)

#include <stdio.h>

int main(int argc, char ** argv[]) {
        int i = atoi(argv[1]);
        i = i +10;
        printf("I in test is %d\n", i);
        return i;
}

回答1:

You only call execv() in the child process. The exec() family functions never return if it runs successfully. See evec(3):

The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error.

You printed the value of i in the parent process, it never changed in the parent process.


To get the exit status from the child process, you can make use of wait() or waitpid():

else {
        int waitstatus;
        wait(&waitstatus);
        i = WEXITSTATUS(waitstatus);
}


标签: c exec fork wait