bssolver/slave.c

62 lines
2.1 KiB
C

/*
This is a personal academic project. Dear PVS-Studio, please check it.
PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/
#define _POSIX_C_SOURCE 2
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "error.h"
#define MAX_SIZE 300
#define COMMAND_MAX_SIZE 400
void runCommand(char *, char *);
void printOutput(char *, char *);
int main(int argc, char *argv[]) {
if (setvbuf(stdout, NULL, _IONBF, 0) != 0)
printSystemError("setvbuf() -- ERROR");
char output[MAX_SIZE], input[MAX_SIZE];
int readChars;
while ((readChars = read(STDIN_FILENO, input, MAX_SIZE - 1)) != 0) {
if (readChars < 0)
printSystemError("slave.c -- read()");
input[readChars] = '\0';
char * inputLine = strtok(input, "\n");
while (inputLine != NULL) {
runCommand(inputLine, output);
printOutput(output, inputLine);
inputLine = strtok(NULL, "\n");
}
}
return EXIT_SUCCESS;
}
void runCommand(char * inputLine, char * output) {
char command[COMMAND_MAX_SIZE];
sprintf(command, "minisat %s | grep -o -e \"Number of .*[0-9]\\+\" -e \"CPU time.*\" -e \".*SATISFIABLE\" | awk '{if (NR == 1) {printf \"Cantidad de variables: \" $4 \" - \"} ; if (NR == 2) {printf \"Cantidad de clausulas: \" $4 \" - \"} ; if (NR == 3) {printf \"Tiempo de procesamiento: \" $4 $5 \" - \"} ; if (NR == 4) {printf \"Resultado: \" $1}}'", inputLine);
// Pequeña ayuda para popen: https://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output
FILE * fp = popen(command, "r");
if (fp == NULL)
printSystemError("slave.c -- popen()");
size_t outputLength = fread(output, sizeof(char), MAX_SIZE - 1, fp);
output[outputLength] = '\0';
if (ferror(fp))
printSystemError("slave.c -- ferror()");
if (pclose(fp) < 0)
printSystemError("slave.c -- pclose()");
}
void printOutput(char * output, char * fileName) {
printf("Nombre del archivo: %s - %s - Id del esclavo: %d\n", fileName, output, getpid());
}