c - execv() 在传递 ( char * ) 而不是 ( char * const ) 时不起作用

标签 c

我有一个像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/

相关文章:

c - 是否应该为所有整数类型提供函数变体?

检查初始化器和终结器是否保证在 block 范围内逻辑配对

c - 使用 dup2 使 C 程序执行诸如 'ls/bin | grep grep | grep b' 之类的命令时出现问题

c++ - 函数 int86 编译错误 : "Stray 302",

c - 使用指针进行内存管理

c++ - 在 Visual Studio 中编译和链接第 3 方库

c# - 通过以太网发送位图,然后再返回(c# 和 c)

c - 多维数组 : incompatible type assignment

无法弄清楚为什么我得到奇怪的输出

c - 程序在运行过程中丢失内存引用