我调用execvp运行Java时发生错误

问题描述

我使用chdir()切换目录,然后使用execvp()执行“ java Main”。我确定有Main.class,但是出了点问题。我想知道为什么。

#include <cstdio>
#include <unistd.h>
using namespace std;
int main(){
    char buf[80];
    getcwd(buf,sizeof(buf));
    printf("current working directory: %s\n",buf);
    chdir("/home/keane/Judge/temp");
    getcwd(buf,buf);
    char *array[3];
    array[0] = "java";
    array[1] = "Main";
    array[2] = NULL;
    execvp("java",array);
    return 0;
}

错误Could not find the main class,我可以在该目录中运行java Main

让我发疯的是我不能使用system("java Main"),而错误Error: Could not find or load main class Main,就像我的计算机上这样

更新:

#include <unistd.h>
#include <cstdlib>
int main(){
    chdir("/home/keane/Judge/temp");
    system("pwd");
    system("ls");
    system("java Main");
    return 0;
}

控制台上的输出为:

/home/keane/Judge/temp
1.out  3.out  5.out   Main.class  stdout_spj.txt
2.out  4.out  ce.txt  Main.java
Error: Could not find or load the main class Main

我的最终解决方案是重新启动计算机,并将-cp .添加到java命令。 尽管我不明白为什么有必要。 谢谢大家!

解决方法

这在我的系统上可以正常工作,也许您需要向Java调用中添加-cp .

编辑:详细说明:-cp(对于 classpath )告诉java在哪里寻找用户提供的.class文件。默认情况下,这不一定包括当前工作目录。

,

execvp() 的执行是非阻塞的,并且拥有调用方的所有权,这意味着,如果程序结束得太快,则在启动时,您将永远不会能够看到结果,要解决此问题,我使用fork()。等待只是为了避免像我一开始那样使用睡眠。全部在c。

#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <sys/wait.h>

int main(int argc,char** argv){
    char buf[80];
    getcwd(buf,sizeof(buf));
    printf("current working directory: %s\n",buf);
    chdir("/home/");
    getcwd(buf,buf);
    char *array[3] = {"java","Main",NULL};
    if(fork() == 0) {
        if(execvp("java",array) < 0) {
            fprintf(stderr,"Error spawning command: %s\n",strerror(errno));
        }
    } else {
        printf("Command spawned\n");
        wait(NULL); // Wait to the forked process to end (avoid using sleep)
    }
    return 0;
}
,

我认为您不能运行.class文件。您应该寻找.jar。基本上就是“ java可执行文件”。它通常应在编译Java项目时出现。