Search code examples
javacygwin

How to invoke cygwin through java shell?


I have a code meant for Linux which execute .sh files on the unix shell.

I wanted to run the same code for windows. I was told that I should install cygwin for windows. I did that but now how do I redirect the commands to cygwin shell?

Here is a part of my code:

public void compile() {
    try {
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dir + "/" + file)));
        out.write(contents);
        out.close();
        // create the compiler script
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dir + "\\compile.sh")));
        out.write("cd \"" + dir +"\"\n");
        out.write("gcc -lm " + file + " 2> err.txt");

        Runtime r = Runtime.getRuntime();
        Process p = r.exec( dir + "\\compile.sh");
        p.waitFor();
        p = r.exec(dir + "\\compile.sh"); // execute the compiler script
        TimedShell shell = new TimedShell(this, p, timeout);
        shell.start();
        p.waitFor();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

How do I redirect to cygwin shell and the run the shell scripts?


Solution

  • Exec C:/cygwin/bin/bash.exe (or C:/cygwin/bin/sh.exe, or whatever the path to your Cygwin /bin/<shell>.exe is), and then pass the script as an argument.

    There's one more wrinkle though. There isn't a full-featured JVM that is Cygwin-native, so you'll probably be using the JVM installed and used by Windows. This means that the value of 'PATH' and other environment variables may not be what you expect when you start the shell, and you may need to use cygpath to convert any paths passed by Java from Windows paths to Cygwin paths, possibly including the value of $0.