从execv()中获取返回值

whe*_*ies 3 c fork exec wait

//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;
}
Run Code Online (Sandbox Code Playgroud)

嘿大家,我正在尝试学习一些关于fork和execv()的调用.我上面的foo.c程序调用了一个名为test.c的文件.我分叉一个孩子并让孩子调用execv,这只会在读入的参数中加上10个.我不知道为什么变量没有改变,在我的foo.c函数的底部.呼叫需要是指针还是返回地址?任何帮助将不胜感激.谢谢

test.c的代码(可执行文件名为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;
}
Run Code Online (Sandbox Code Playgroud)

Yu *_*Hao 5

您只能execv()在子进程中调用.该exec()如果运行成功,家庭功能不会再回来.见evec(3):

exec()只有在发生错误时才会返回这些函数.返回值是-1,并errno设置为指示错误.

您打印了i父进程中的值,它在父进程中从未更改过.


要从子进程获取退出状态,您可以使用wait()waitpid():

else {
        int waitstatus;
        wait(&waitstatus);
        i = WEXITSTATUS(waitstatus);
}
Run Code Online (Sandbox Code Playgroud)