How to start a process in Java inside symlink directory?

I need to run my own process from Java inside the symlink directory. Let the following directory structure:

guido@Firefly:~/work$ tree
.
└── path
    └── to
        └── symlink -> /home/guido/work

3 directories, 0 files

I am starting a Java application from a directory ~/workand want to start my own process in the directory ~/work/path/to/symlink.

However, if I use the following Java code, the symlink working directory resolves the real path . Instead, I would like to run the command in an absolute way .

(Please note that the command pwdis for illustration purposes only and should be replaced with a “real” one (for example, go buildin my case)).

File baseDir = new File("/home/guido/work");
File link = new File(baseDir, "path/to/symlink");
Files.createSymbolicLink(link.toPath(), baseDir.toPath());

Process process = new ProcessBuilder()
            .command("pwd")
            .directory(link)
            .start();

String output = getOutput(process);
System.out.println(output); // Prints: /home/guido/work

, , . , .

String[] cmd = {"/bin/sh", "-c", "cd " + link + " && pwd"};
Process process = Runtime.getRuntime().exec(cmd);

String output = getOutput(process);
System.out.println(output); // Prints: /home/guido/work/path/to/symlink

unit test gist .

+4
3

, , , , , . . . https://unix.stackexchange.com/questions/198590/what-is-a-bind-mount https://backdrift.org/how-to-use-bind-mounts-in-linux. :

mkdir -p /path/to
mount -o bind /home/guido/work /path/to/symlink

. Java . , root, . , , , ?

+1

This was able to satisfy my needs with the following workaround, but it's silly to run a shell to be able to run a simple process in a specific directory. In addition, I am losing platform independence.

String[] cmd = {"/bin/sh", "-c", "cd " + link + " && pwd"};
Process process = Runtime.getRuntime().exec(cmd);

String output = getOutput(process);
System.out.println(output); // Prints: /home/guido/work/path/to/symlink

https://gist.github.com/sw-samuraj/2c09157b8175b5a2365ae4c843690de0

0
source

Source: https://habr.com/ru/post/1695688/


All Articles