-1

Can we achieve starting a nodejs/phantomjs script from java rest api?

I have tried this:

rt = Runtime.getRuntime();                                                    
p = rt.exec("node /extra/POC/index.js 14");
p.waitFor();

It is able to start but my java process is keep running until my script execution completes as using p.waitFor(); my script internally has conditions to do process.exit(); and i don't want java to wait till this script execution completed.

Java should just invoke the script and leave it and let index.js script will take care of remaining job.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
snofty
  • 70
  • 7

2 Answers2

2

The Java doc of Process.waitFor

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

So remove this statement to let the process keep going (and end). Also from the doc, you can see what happen when the Process is ready to be "Garbage collected".

The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.

Not sure what happened when the Main Thread is over though. But this thread seems to answer it. How can I cause a child process to exit when the parent does?

Community
  • 1
  • 1
AxelH
  • 14,325
  • 2
  • 25
  • 55
  • @GhostCat that's a first ;) I lost time commenting first ;) – AxelH May 08 '17 at 12:23
  • yes as tested in standard java program, process getting terminated on main method ends and i need to from jersey rest api to start sub process of running node js script, so if i client calls my rest api then i should respond with status 'Success' running node js script. will test this part. Thank you for inputs. – snofty May 08 '17 at 12:28
  • @GhostCat This advice I will follow ! – AxelH May 08 '17 at 12:29
  • @snofty I am not sure I understand everything, but this should be fine. It would be easy to check with a simple script (.bat or .sh) creating a file after a few seconds. Java would just start this and end. – AxelH May 08 '17 at 12:31
2

Your code does what you are telling it to do - to wait for the child process to exit.

If you only care about triggering a "sub process"; then simply remove the call to waitFor(). Then the parent process will continue doing "its thing"; without waiting for anything.

The only thing to keep in mind: if your parent process (the JVM) ends before the child process, the ending parent process might end the child process, too.

GhostCat
  • 137,827
  • 25
  • 176
  • 248