我有一个像blow这样的程序:
int main()
{
char * const args[2]={"a", "b",};
int pid = fork();
if ( pid == 0 ) {
execv("./printargs", args);
}
return 0;
}
当我从终端运行它时。 execv() 执行 printargs 并打印 agrs[] 的所有值。这样程序就可以正常运行了。
但是当我稍微改变程序以接受输入并重新编写程序时,如下所示:
int main()
{
char * args[2];
args[0] = (char*)malloc(sizeof(char)*10);
args[1] = (char*)malloc(sizeof(char)*10);
scanf("%s", args[0]);
scanf("%s", args[1]);
int pid = fork();
if ( pid == 0 ) {
execv("./printargs", args);
}
return 0;
}
然后 execv() 不起作用&我不明白问题是什么
但我需要通过从输入中获取值来动态传递参数。
提前感谢您的帮助。
最佳答案
所以正如我所说,您遇到以下问题:
-
execv
需要一个以 NULL 结尾的数组作为第二个参数(因此最后一个值必须是 NULL 值) - 此参数也以“程序名称”开头,因此真正的第一个参数(如您所愿)是
args[1]
而不是args[0]
- 您还应该检查错误并检查返回值
- 请注意
%10s
意味着scanf
最多读取 10 个字符 + 添加前导\0
之后,可能是 11 个字符!使用%9s
或增加您的分配大小
下面是一个执行效果基本相同的示例代码(使用 /bin/echo
命令而不是 ./prinargs
):
int main()
{
char * args[4]; // 1 for bin name, 2 for args, 1 for NULL
args[0] = "/bin/echo"; // you may put what you want here, in fact
args[1] = (char*)malloc(sizeof(char)*10);
args[2] = (char*)malloc(sizeof(char)*10);
args[3] = NULL; // NULL-terminated
scanf("%9s", args[1]); // read 9 (+1 for \0)
scanf("%9s", args[2]);
int pid = fork();
if (pid == -1) { // handle fork() error
perror("fork"); // print out the reason
exit(1); // and leave
} else if (pid == 0) {
// child
execv("/bin/echo", args);
perror("execv"); // we are here only if execv failed
exit(1); // so print out error and exit
}
// here you should wait for your child to get returned value
// see wait() and similar functions
return 0;
}
大多数时候最好等待 child (使用 wait()
family),这样父亲就不会在 child (ren)之前结束,并且您还可以获得其返回状态(即命令的返回)如果 exit()
失败,您将执行或执行您的 execv()
值。
关于c - execv() 在传递 ( char * ) 而不是 ( char * const ) 时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583686/