Created
August 22, 2012 11:59
-
-
Save fengxx/3424849 to your computer and use it in GitHub Desktop.
run script and cp stdin and stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo x - ScriptRunner.java | |
cat >ScriptRunner.java <<'!Funky!Stuff!' | |
import java.io.*; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
/** | |
* | |
* @author Ted | |
*/ | |
public class ScriptRunner { | |
public static void main(String[] args) throws Exception { | |
if (args.length == 0) { | |
System.err.println("Usage: ScriptRunner myscript parameter..."); | |
} | |
ScriptRunner runner = new ScriptRunner(); | |
runner.run(args); | |
} | |
public int run(String[] args) throws Exception { | |
Process child = new ProcessBuilder(args).redirectErrorStream(true).start(); | |
//subprocess reads input from a pipe via the output stream returned by Process.getOutputStream() | |
Thread readIn=plugTogether(System.in, child.getOutputStream()); | |
Thread writeOut=plugTogether(child.getInputStream(), System.out); | |
int returnValule = child.waitFor(); | |
if (returnValule != 0) //failed | |
{ | |
System.err.println("failed with exit value: " + returnValule); | |
}else{ | |
System.out.println("Script successfully finished\n"); | |
} | |
//stop the threads | |
writeOut.interrupt(); | |
readIn.interrupt(); | |
return returnValule; | |
} | |
private Thread plugTogether(InputStream fin, OutputStream fout) throws Exception { | |
Thread workThread = new CopyWorker(fin, fout); | |
workThread.start(); | |
return workThread; | |
} | |
class CopyWorker extends Thread { | |
final InputStream in; | |
final OutputStream out; | |
public CopyWorker(InputStream in, OutputStream out) { | |
this.in = in; | |
this.out = out; | |
} | |
public void run() { | |
Thread thisThread = Thread.currentThread(); | |
int c; | |
try { | |
while (!thisThread.isInterrupted() && (c=in.read()) !=-1) { | |
out.write(c); | |
out.flush(); | |
thisThread.sleep(2); | |
} | |
} catch (IOException ex) { | |
Logger.getLogger(ScriptRunner.class.getName()).log(Level.SEVERE, null, ex); | |
}catch (InterruptedException ex){ | |
System.out.println("cancel thread"); | |
} | |
} | |
} | |
} | |
!Funky!Stuff! | |
echo x - choice.sh | |
cat >choice.sh <<'!Funky!Stuff!' | |
echo "continue?" | |
choices="yes no" | |
select name in $choices | |
do | |
if [ "$name" = "yes" ]; then | |
echo "working .." | |
echo "continue?" | |
else | |
echo "exit." | |
break | |
fi | |
done | |
!Funky!Stuff! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment