Re: exec problem is JDK 1.7.0_21
On Sun, 21 Apr 2013 19:47:39 +0000, Martin Gregorie wrote:
...though this script doesn't honour spaces within arguments.
This niggled me, so here's a replacement for 'testscript' which *does*
honour quoted command line arguments:
$ cat testscript
#!/bin/bash
i=0
echo "$# arguments"
for f in "$@"
do
echo "arg[$i]=$f"
i=$(expr $i + 1)
done
exit $i
$
Tested and shown to work in my version of the SSCE:
$ java TestProcessBuilder testscript a cat and "a mouse in its hole"
4 arguments
arg[0]=a
arg[1]=cat
arg[2]=and
arg[3]=a mouse in its hole
exitValue=4
$
The fix was changing echo ' for f in $* ' to ' for f in "$@" '.
For completeness, here's my version of the ProcessBuilder SSCE. As well
as grabbing the ProcessBuilder constructor arguments from the command
line, I made Exception trapping explicit so where they're issued is
unambiguous and made the Runnable class into a named class:
import java.io.*;
public class TestProcessBuilder
{
public static void main(String[] args) throws Exception
{
try
{
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
Process p = pb.start();
Thread t = new Thread(new TestRunnable(p.getInputStream()));
t.start();
t.join();
print("exitValue=%d", p.exitValue());
}
catch(NullPointerException e)
{
print("ProcessBuilder.start() threw NullPointerException %s",
e.getMessage());
}
catch(IndexOutOfBoundsException e)
{
print("ProcessBuilder.start() threw IndexOutBoundsException %s",
e.getMessage());
}
catch(IOException e)
{
print("ProcessBuilder.start() threw IOException %s",
e.getMessage());
}
}
private static void print(String format, String value)
{
System.out.println(String.format(format, value));
}
private static void print(String format, int value)
{
System.out.println(String.format(format, value));
}
}
import java.io.*;
public class TestRunnable implements Runnable
{
private InputStream is;
public TestRunnable(InputStream is)
{
this.is = is;
}
public void run()
{
int n;
try
{
while ((n = is.read()) != -1)
System.out.print((char)n);
}
catch (IOException ioe)
{
System.out.println("IOException in TestRunnable");
ioe.printStackTrace();
}
}
}
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |