【问题标题】:Grabbing the return value from execv()从 execv() 获取返回值
【发布时间】:2026-02-02 02:05:01
【问题描述】:
//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;
}

大家好,我正在尝试学习一些关于 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;
}

【问题讨论】:

  • 如果要从子进程中获取返回值,可以使用IPC方法(管道套接字等),甚至可以尝试通过读写文件来交换数据。
  • 我也有同样的文件想法哈哈哈这就是我回答交换数据的问题:)

标签: c exec fork wait


【解决方案1】:

您只能在子进程中调用execv()。如果成功运行,exec() 系列函数将永远不会返回。见evec(3)

exec() 函数仅在发生错误时返回。返回值为-1,设置errno表示错误。

您在父进程中打印了i 的值,它在父进程中从未改变。


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

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

【讨论】:

  • 我阅读了 exec,谢谢。有没有办法从 exec 创建的另一个程序中获取返回值?我想我可以将值读取并正确写入文件,但这似乎对 CPU 来说很昂贵。
  • 成功了!谢谢!我认为 WEXITSTATUS 只会根据它是否退出返回 1 或 0,但我错了。