Search code examples
javanamed-pipesnosuchfileexception

Cannot delete a named pipe from Java


I'm creating a named pipe in Java, which is working with the following code:

final String [] mkfifo = {"/bin/sh", "-c", "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"};

Process p = Runtime.getRuntime().exec(mkfifo);

But now I'm getting a NoSuchFileException when I try to delete it with this code:

Path fifoPath = Paths.get("~/myFifo");

try {
    Files.delete(fifoPath);
} catch (Exception e) {
    System.err.println(e);
}

I have verified that the file is, indeed, being created by issuing an ls ~ during execution of the program, and ~/myFifo still remains after the exception is thrown and execution of the program ends.

I assumed the ... && tail ... may cause some problems in case that it is somehow blocking, so I made the change to creating the named pipe with this:

final String [] mkfifo = {"/bin/sh", "-c", "mkfifo ~/myFifo"};

Process p = Runtime.getRuntime().exec(mkfifo);

The pipe is still created, which is fine. I've also attempted to remove the pipe in a less-native Java way, via exec:

final String [] rmfifo = { "/bin/rm ~/myFifo" };

Runtime.getRuntime().exec(rmfifo);

None of these seem to work. Any ideas?

Thanks, erip


Solution

  • The problem is the ~/myFifo.

    Java isn't understanding the ~

    I ran the following code.

    Path fifoPath = Paths.get("/home/russell/myFifo");
    try {
        Files.delete(fifoPath);
    } catch (Exception ex) {
        System.err.println(ex);
    }
    

    And it ran perfectly.

    String home = System.getProperty("user.home");
    Path fifoPath = Paths.get(home + "/myFifo");
    try {
        Files.delete(fifoPath);
    } catch (Exception ex) {
        System.err.println(ex);
    }
    

    The above code also works on my system.

    ~/ is a shell thing, so java won't pick it up.

    The reason it's actually creating the file in the first place is because you're using /bin/sh to run the mkfifo command, and sh translates the ~/.