我有一个要求,我想在 C 中满足条件后启动我的 Nodejs 脚本。 我正在使用系统(“Node/path_to_file/sample.js”) 这是执行nodejs脚本的正确方法还是任何其他方法?
最佳答案
您可以使用 execve
(man 2 execve)
以及所有 execvp
系列从 C 程序执行程序和脚本 (man 3 execvp)
。如果您使用这些调用,您的程序将在调用后被终止,为避免这种情况,您需要 fork()
(man 2 fork)
这是它如何工作的一个小示例(它将在您的/目录上启动 ls -l):
int main(int ac, char **av, char **env)
{
pid_t pid;
char *arg[3];
arg[0] = "/bin/ls";
arg[1] = "-l";
arg[2] = "/";
pid = fork(); //Here start the new process;
if (pid == 0)
{
//You are in the child;
if (execve(arg[0], arg, env) == -1)
exit(EXIT_FAILURE);
//You need to exit to kill your child process
exit(EXIT_SUCCESS);
}
else
{
//You are in your main process
//Do not forget to waitpid (man 2 waitpid) if you don't want to have any zombies)
}
}
fork()
可能是一个难以理解的系统调用,但它是一个非常强大且重要的学习调用
关于从 C 函数调用/执行 node.js 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298957/