使用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此。