1
votes

I want to run node.js as a subprocess and feed it input. Using C, here is some sample code of mine that does that.

The issue I have is that although the subprocess's stdout is still directed to the terminal, I see nothing after having fed the subprocess stdin a print 'Hello World' line. Even if I fflush() the pipe, I see nothing on output. However, if I close the pipe's input, then the 'Hello World' appears on the terminal.

The subprocess seems to simply buffer - why is that? I would like to eventually redirect the subprocess stdout to another pipe and read it in from main().

int main(int argc, char* argv[]) {

  int toNode[2];

  pipe(toNode);

  pid_t child_pid = fork();
  if (child_pid == 0) { // child

      // close write end
      close(toNode[1]);
      // connect read end to stdin
      dup2(toNode[0], STDIN_FILENO);


      // run node executable
      char* arg_list[] = { "/usr/bin/node", NULL};
      execvp(arg_list[0], arg_list);

      fprintf(stderr, "process failed to start: %s\n", strerror(errno));
      abort();
   }
   else { // parent

      FILE* stream;

      // close read end
      close(toNode[0]);

      // convert write fd to FILE object
      stream = fdopen(toNode[1], "w");

      fprintf(stream, "console.log('Hello World');\n");
      fflush(stream);

      //close(toNode[1]);


      waitpid(child_pid, NULL, 0);

   }

return 0;   }
1
Although this answer refers to Python, it's the same underlying issue. You must somehow convince the other program to do less buffering. (I have no idea whether node.js can be told to do that, or if you need to resort to pseudo-ttys.) - torek

1 Answers

2
votes

There's no problem with the pipe being read. The problem is that /usr/bin/node only invokes the REPL (read-eval-print loop), by default, if it detects that stdin is interactive. If you have a sufficiently recent version of nodejs, then you can provide the -i or --interactive command line flag, but that will do more than just execute each line as it is read; it also really will act as a console, including inserting ANSI colour sequences into the output and printing the value of each expression.

See this forum thread for more information.