0

I have a requirement where I want to start my nodejs script after I hit a condition in C. I am using system("node /path_to_file/sample.js") Is this the right way to do or any other way to execute nodejs script?

1 Answers1

0

you can execute programs and script from a C program by using execve (man 2 execve) and all the family of execvp (man 3 execvp) . If you use these call, your programm will be killed after the call, to avoid this you'll need to fork() (man 2 fork)

This is a little example of how it work (it will launch ls -l on your / directory):

 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() may be a difficult system call to understand, but it his a really powerfull and important call to learn

drumz
  • 65
  • 7