Forking a new process in C++ and executing a .jar file

人盡茶涼 提交于 2019-12-24 06:34:42

问题


I am attempting to write a program that will read the output from a java .jar file and also give it input from time to time. Basically I am hoping to make a program that will execute certain functions when certain output is encountered.

The .jar file wasn't created by me, and I don't have the source code, so I have to use it as-is. After doing some research I decided using fork() and execl() in conjunction with pipes was the method I would need to use and I created a small program that successfully does this with a hello world program. Just as I was getting ready to modify it to run the .jar program I realized that the .jar isn't executable on its own, I have to execute it through java and so now I'm unable to figure out how to make execl() work with the .jar.

I have tried to figure out how to make execl() run java and use an argument that specifies the jar file to execute like so:

execl("java","java","jar myprog.jar",NULL);

I don't know if this method will work, though. If it will I don't know what path to use. I have seen some people recommend using JNI for similar purposes, but none of them seemed to quite fit with what I was doing and after researching it a bit I'm not totally sure that would be the best way to go. popen() seems like another possibility, but I have yet to find anything that explains how to use it well.

Any advice would be greatly appreciated.


回答1:


For finding the java executable: if you want to find it in PATH you can use execlp instead of execl. Otherwise you can make it configurable (configuration file or env. variable). For the jar file you can look for it in the current directory or again a configurable location.

E.g., for java in PATH and myprog.jar in the current working directory:

ret = execlp("java", "java", "-jar", "myprog.jar", (char *)0);




回答2:


You would start it with:

java -jar myprog.jar

Since that's the command line, you would need ...

execl("java", "java", "-jar", "myprog.jar", NULL);

(Provided java is in your path. If it's not you'll need the full path to java.)




回答3:


If you want to call various Java functions from within a C++ environment, you will need to use JNI. Create a Java virtual machine inside your C++ program and use it to load the jar. You can then call functions that jar exposes.

Here is a decent summary. http://www.codeproject.com/KB/cpp/CJniJava.aspx



来源:https://stackoverflow.com/questions/5270083/forking-a-new-process-in-c-and-executing-a-jar-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!