使用system()
在这种情况下是不必要的复杂,因为它实际上将给定的命令字符串传递给(分叉)sh -c <command>
。这意味着,你不得不处理可能形成的命令字符串时的参数等报价:
% sh -c 'ls asdf asdf'
ls: cannot access 'asdf': No such file or directory
ls: cannot access 'asdf': No such file or directory
% sh -c 'ls "asdf asdf"'
ls: cannot access 'asdf asdf': No such file or directory
注未加引号,并引述版本之间的差异。
我建议使用execve()
,如果执行python命令是你的C程序的唯一目的,因为exec函数家族不会成功返回。这需要常量数组的指针为char作为新ARGV,这使得操作更简单的参数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PYTHON "/usr/bin/python3"
#define SCRIPT "script.py"
int
main(int argc, char *argv[])
{
/* Reserve enough space for "python3", "script.py", argv[1..] copies
* and a terminating NULL, 1 + 1 + (argc - 1) + 1 */
int newargvsize = argc + 2;
/* VLA could be used here as well. */
char **newargv = malloc(newargvsize * sizeof(*newargv));
char *newenv[] = { NULL };
newargv[0] = PYTHON;
newargv[1] = SCRIPT;
/* execve requires a NULL terminated argv */
newargv[newargvsize - 1] = NULL;
/* Copy over argv[1..] */
memcpy(&newargv[2], &argv[1], (argc - 1) * sizeof(*newargv));
/* execve does not return on success */
execve(PYTHON, newargv, newenv);
perror("execve");
exit(EXIT_FAILURE);
}
正如其他人所指出的,您还是应该在所有可能使用official APIs此。