c - 从 execv 运行 mysql 导入

标签 c execv

pid_t childPid = fork ();
if (childPid == (pid_t) 0)//zero success
{
    const char *path = "/usr/local/mysql/bin/mysql";
    //doesn't work
    //char * const parmList[] = {"--user=root", "test_db", NULL};
    //does work
    char * const parmList[] = {"", "--user=root", "test_db", NULL};
    execv(path, parmList);
    printf("ERROR:\tFork failed.\n");   
}
else if (childPid < (pid_t) 0)// -1 failure
{
    /* The fork failed. */
    printf("ERROR:\tFork failed.\n");   
    return EXIT_FAILURE;
}
else
{
    while (true) {
        //stay alive
        sleep(1);
    }
}
printf("done");
exit(0);

我在使用 execv 导入 sql 转储时遇到问题。您可以看到我无法使用第一个 paramList 登录,但第二个可以正常工作。无论如何,如果我添加到参数列表:

char * const parmList[] = {"", "--user=root", "test_db", "<", "/Users/joelsaltzman/Desktop/dump.sql", NULL};

输出显示了命令行参数的 mysql 帮助,就像我输入了错误的内容一样。 有人知道如何让它工作吗?

最佳答案

第一个paramList不正确,因为第一个元素应该是您要执行的程序的文件名:

The argument argv is an array of character pointers to null-terminated strings. The application shall ensure that the last member of this array is a null pointer. These strings shall constitute the argument list available to the new process image. The value in argv[0] should point to a filename that is associated with the process being started by one of the exec functions.

输入重定向 <不起作用,因为这不是内核的功能(您使用 execv 调用),而是通常的 Unix shell 的功能。 system图书馆电话是你要找的。 (它也只使用来自 exec 系列的调用,但使用您的命令调用 shell,然后它将支持 <。)

请务必阅读联机帮助页 system(3)并考虑输入验证,如果您要向它传递一个可能会受到恶意用户影响的字符串。

关于c - 从 execv 运行 mysql 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9243554/

相关文章:

c++ - 如何在指定文件路径上的程序中使用 ls?

c++ - 使用 execv 从 C++ 启动服务

c - Lua - 数字到字符串的行为

c# - 打印断言错误后使应用程序正常关闭

C: undefined reference `dlopen`/`dlsym` 尽管添加了 `-ldl` 标志

c - 在子进程中执行文件

linux - 执行后,管道缓冲区中的内容消失

C 套接字 - 使用参数时无法访问网络

c - C 中 *ptr += 1 和 *ptr++ 的区别

c - 管道未接收子进程的所有输出