Ejercicio resuelto: Comunicación entre procesos

Código del ejercicio resuelto

Método main()

public static void main(String[] args) throws IOException, InterruptedException {
// write your code here
    int n1 = Integer.parseInt(args[0]);
    int n2 = Integer.parseInt(args[1]);
    float salto = (n2 - (n1 - 1)) / Float.valueOf(NUM_PROCESOS);
    System.out.println("salto: " + salto);
    long sumaTotal;
    int inferior;
    float superior;

    inferior = n1;
    superior = n1 - 1 + salto;
    for (int i  = 1; i <= NUM_PROCESOS; i ++) {
        System.out.println("n1: " + n1);            
        System.out.println("n2: " + (int)(superior));
        // System.out.println("superior: " + superior);
        lanzarSumador(inferior , (int)(superior), PREFIJO_FICHEROS + String.valueOf(i));
        inferior = (int)(superior) + 1;
        superior = superior + salto;
        System.out.println("Suma lanzada  . . .");
    }

    Thread.sleep(1000);
    sumaTotal = getSumaTotal(NUM_PROCESOS);
    System.out.println("La suma total es: " + sumaTotal);
}

Ejecución en el IDE Idea:

public static void lanzarSumador(int n1, int n2, String ficheroResultados) throws IOException {
    String comando;
    //comando = "Sumador";
    comando = "com.company.Sumador";
    File carpeta;
    //carpeta = new File("./");
    // ComunicacionProcesos es el nombre del proyecto
    carpeta = new File("./out/production/ComunicacionProcesos/");





}

 

Mejora: Controlar la terminación de los diferentes procesos y esperar a que terminen todos (usando el método waitFor()) para leer los ficheros de resultados, en lugar de esperar 1.000 ms.

lanzarSumador

public static Process lanzarSumador(int n1, int n2, String ficheroResultados) throws IOException {
    String comando;
    //comando = "Sumador";
    comando = "com.company.Sumador";
    File carpeta;
    //carpeta = new File("./");
    carpeta = new File("./out/production/ComunicacionProcesos/");
    File fichero = new File(ficheroResultados);
    File errores = new File("errores.txt");
    ProcessBuilder pb;
    Process process;

    pb = new ProcessBuilder("java",
            comando,
            String.valueOf(n1),
            String.valueOf(n2) );
    pb.directory(carpeta);
    pb.redirectOutput(fichero);
    pb.redirectError(errores);
    process = pb.start();

    return  process;
}

Main

import java.io.*;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.

// nombre del proyecto: Sumador24

public class Main {

    static final int NUM_PROCESOS = 4;
    static final String PREFIJO_FICHEROS = "fichero";

    public static Process lanzarSumador(int n1, int n2, String ficheroResultados) throws IOException {
        String comando;
        comando = "Sumador";
        File carpeta;
        //carpeta = new File("./");
        carpeta = new File("./out/production/Sumador24");
        File fichero = new File(ficheroResultados);
        File errores = new File("errores.txt");
        ProcessBuilder pb;
        Process process;

        pb = new ProcessBuilder("java",
                comando,
                String.valueOf(n1),
                String.valueOf(n2) );
        pb.directory(carpeta);
        pb.redirectOutput(fichero);
        pb.redirectError(errores);
        process = pb.start();

        return process;
    }

    public static int getResultadoFichero(String nombreFichero){
        int suma = 0;
        try {
            FileInputStream fis = new FileInputStream(nombreFichero);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String linea = br.readLine();
            suma = Integer.valueOf(linea);
        } catch (FileNotFoundException e) {
            System.out.println("No se pudo abrir " + nombreFichero);
        } catch (IOException e) {
            System.out.println("No hay nada en " + nombreFichero);
        } finally {
            return suma;
        }
    }

    public static long getSumaTotal(int n){
        long sumaTotal = 0;

        for (int i = 1; i <= n; i ++){
            sumaTotal += getResultadoFichero(PREFIJO_FICHEROS + String.valueOf(i) );
        }
        return sumaTotal;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        // write your code here
        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        float salto = (n2 - (n1 - 1)) / Float.valueOf(NUM_PROCESOS);
        System.out.println("salto: " + salto);
        long sumaTotal;
        int inferior;
        float superior;
        Process procesos[];
        procesos = new Process[NUM_PROCESOS];

        inferior = n1;
        superior = n1 - 1 + salto;
        for (int i  = 1; i <= NUM_PROCESOS; i ++) {
            System.out.println("n1: " + inferior);
            System.out.println("n2: " + (int)(superior));
            // System.out.println("superior: " + superior);
            procesos[i - 1] = lanzarSumador(inferior , (int)(superior), PREFIJO_FICHEROS + String.valueOf(i));
            inferior = (int)(superior) + 1;
            superior = superior + salto;
            System.out.println("Suma lanzada  . . .");
        }

        // Thread.sleep(1000);
        for (int i = 0; i < NUM_PROCESOS; i ++) {
            procesos[i].waitFor();
            System.out.println("proceso " + (i + 1) + " terminado");
        }

        sumaTotal = getSumaTotal(NUM_PROCESOS);
        System.out.println("La suma total es: " + sumaTotal);
    }
}

 

Realización del ejercicio en el IDE Idea:

Código del proyecto Sumador24 (IDE Idea)

 

Deja una respuesta