0
我有一個要求,在我打C中的條件後啓動我的nodejs腳本。我使用system(「node /path_to_file/sample.js」) 這是做正確的方式或任何其他方式來執行nodejs腳本?從C函數調用/執行node.js腳本
我有一個要求,在我打C中的條件後啓動我的nodejs腳本。我使用system(「node /path_to_file/sample.js」) 這是做正確的方式或任何其他方式來執行nodejs腳本?從C函數調用/執行node.js腳本
您可以使用execve
(man 2 execve)
和execvp
(man 3 execvp)
的所有系列從C程序執行程序和腳本。如果你使用這些電話,你的程序將在通話後被殺死,爲避免這種情況,你需要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()
可能是一個艱難的系統調用來理解,但他的一個非常強大和重要的電話,瞭解
你讀過嗎? https://stackoverflow.com/questions/3736210/how-to-execute-a-shell-script-from-c-in-linux – CIsForCookies