Java Process Builder: Parent-Child Process and Pipe Implementation

Classified in Design and Engineering

Written on in English with a size of 3.25 KB

public static void main(String[] args) {

if(args.length >= 2) {

System.out.println("Inicio padre");

//Variables

ProcessBuilder pb = null;

Process p = null;

String[] args_alt = new String[args.length-1];

File path = null;

String line = "";

InputStream is = null;

InputStreamReader isr = null;

BufferedReader br = null;

for(int i=0; i<args_alt.length; i++) {

args_alt[i] = args[i];

}

pb = new ProcessBuilder(args_alt);

path = new File(args[args.length-1]);

pb.directory(path);

if(path.exists() && path.isDirectory()) {

try {

p = pb.start();

} catch (IOException e) {

System.out.println("Error al crear el proceso");

}

is = p.getInputStream();

isr = new InputStreamReader(is);

br = new BufferedReader(isr);

try {

while((line = br.readLine()) != null) {

System.out.println(line);

}

} catch (IOException e) {

System.out.println("Error al leer la salida del proceso hijo");

}

}else {

System.out.println("El directorio no existe");

}

System.out.println("Fin padre");

}else {

System.out.println("Error en el numero de parametros");

System.out.println("Ejemplo de ejecucion: java -jar 'NombreDeTuProcesoHijo'.jar 2 11 /home/'tuUsuario'/Escritorio ");

}

}




public static void main(String[] args) {

if(args.length >= 3) {

boolean pipe = false;

int posPipe = 0;

int nPosArgs = args.length-1;

int totalPosC2 = 0;

String entradaP2 = "";

Process p1 = null;
Process p2 = null;

ProcessBuilder pb1 = null;
ProcessBuilder pb2 = null;

String[] command1 = null;
String[] command2 = null;

for(int i=0; i<args.length && !pipe; i++) {

if(args[i].equals("|")) {

pipe = true;

posPipe = i;

}

}

if(pipe) {

command1 = new String[posPipe];

totalPosC2 = nPosArgs - posPipe;

command2 = new String[totalPosC2];

if(!args[nPosArgs].equals("|") && !args[0].equals("|")) {

for(int i=0; i<posPipe; i++) {

command1[i] = args[i];

}

for(int i=0; i<totalPosC2; i++) {

command2[i] = args[posPipe+1];

posPipe++;

}

pb1 = new ProcessBuilder(command1);

pb2 = new ProcessBuilder(command2);

try {

p1 = pb1.start();

} catch (IOException e) {

System.out.println("Error al crear el primer proceso.");

System.out.println("Ejemplo de ejecucion: java Crear_Multiprocesos ls | wc -l -c \n");

}

try {

p2 = pb2.start();

} catch (IOException e1) {

System.out.println("Error al crear el segundo proceso.");

System.out.println("Ejemplo de ejecucion: java Crear_Multiprocesos ls | wc -l -c \n");

}

try {

entradaP2 = obtenerSalidaProceso1(p1);

}catch(NullPointerException e1) {

System.out.println("El primer comando no funciona");

System.out.println("Ejemplo de ejecucion: java Crear_Multiprocesos ls | wc -l -c \n");

}

try {

pasarEntradaProceso2(p2, entradaP2);

imprimirSalidaProceso2(p2);

}catch() {

Related entries: