【发布时间】: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方法(管道套接字等),甚至可以尝试通过读写文件来交换数据。
-
我也有同样的文件想法哈哈哈这就是我回答交换数据的问题:)