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/