【问题标题】:C - Execv - incompatible pointer typeC - Execv - 不兼容的指针类型
【发布时间】:2021-11-23 08:43:55
【问题描述】:

所以我要做的是通过 Execv 发送一个简单的 ping 命令并在终端上打印。

我的原始问题有一组未知参数的字符串。 a[n][50] 将根据用户输入在整个过程执行过程中填充。 我无法使用“execv”,我不断收到“不兼容的指针类型”。 为了说明问题,我只做了一个简单的“ping”“google.com”

int main(int argc, char const *argv[])
{

    //That's what I have...
    char a[3][50];
    strcpy(a[0], "ping");
    strcpy(a[1], "google.com");
    
    //First try
    a[2] = NULL;
    execv(a[0], a);    
    
    //Second time, trying to fix, also didnt work 
    char *pointer[3];
    pointer[0] = a[0];
    pointer[1] = a[1];
    pointer[2] = NULL;

    execv(pointer[0], pointer);

    return 0;
}

是否有任何解决方法而无需更改 a[n][50] 格式来保存字符串?

【问题讨论】:

  • 二维数组与指针数组不同。
  • a[2] = NULL; 无效。 a[2] 是数组,不能赋值给数组。
  • 使用execvp(),因为你需要在$PATH中找到ping
  • 或者将a[0]改成ping程序的完整路径。
  • 为了将来参考,在execv 后面加上一个perror("execv failed"); 以便在exec 调用失败时得到一些反馈。

标签: c unix


【解决方案1】:

第二个版本可以使用,但您需要使用execvp() 而不是execv,因为第一个参数不是ping 程序的完整路径。

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    相关资源
    最近更新 更多