0

I have a cpp project, which executes another program.
Here is my test:

int main() {
    execl("java -jar /pathOfJAR/myjar.jar", NULL);

    return 0;
}

I ran this project and I got nothing.

Then I tried like this:

execl("java", "-jar", "/pathOfJAR/myjar.jar");

I got an error:

Error: Could not find or load main class .pathOfJAR.myjar.jar

However, I can run the command in the terminal:

java -jar /pathOfJAR/myjar.jar

and I can get the right result.

How to use the function execl or I used the wrong function?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 3
    When you say you "got nothing", what was the return value from `execl()`? – Greg Hewgill Jan 04 '16 at 17:20
  • Are you running the cpp project from the same directory as the `java -jar xxx` command? – Andrew Williamson Jan 04 '16 at 17:25
  • By the way, you know, I suppose, that the `exec*` functions don't return to your program after executing the specified command? It's relatively rare that this is what you really want. To execute a command and then continue with your program, `system(3)` is the simplest approach. – Nate Eldredge Jan 04 '16 at 17:50

2 Answers2

4

Try:

execl("/bin/java", "java", "-jar", "/pathOfJAR/myjar.jar", NULL);

Note that "/bin/java" should be replaced with the full path to your java interpreter, most easily determined with which java.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Commonly overlooked first argument being the path to the program. – erip Jan 04 '16 at 17:38
  • 1
    Still needs a `NULL` as the last argument. – Nate Eldredge Jan 04 '16 at 17:46
  • 1
    Also, on Linux systems the `java` executable is unlikely to be in `/bin`. The OP should either look up where it really is, or (better) use `execlp`. – Nate Eldredge Jan 04 '16 at 17:48
  • It works! But I don't understand the second parameter. What does "java" mean here? – Yves Jan 05 '16 at 09:30
  • 1
    The first parameter (the path to the java interpreter) is the executable that is executed. The remaining parameters become the argv that is passed to that executable. The "java" is argv[0] to the java interpreter. Create a program that prints all of its arguments and execute it via execv. The name of the program does not need to be related to argv[0] at all. – William Pursell Jan 05 '16 at 13:56
-1

The error message is from java, not from execl. Make sure the jar file's manifest has Main-Class attribute.

Before invoking from your C++ program, run the jar in the command line and test that it works.

Why do you want to build a C++ wrapper anyways? You may want to consider a shell wrapper as (if you need a wrapper at all).

Vampiro
  • 335
  • 4
  • 15