#include<stdio.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<unistd.h>

char* get_md5(char*);

int main(int argc, char* argv[]){
  if( argc < 2){
    fprintf(stderr, "dammi un nome\n");
    return 1;
  }

  fprintf(stderr, "checksum for %s\n", argv[1]);

  char* cs = get_md5(argv[1]);
  if( !cs )
    perror("error");

  fprintf(stderr, "checksum: %s\n", cs);

  return 0;
}


/*
 *  This function fork() and exec 'md5sum' on the src file
 *  and sends result to other side pipe.
 *
 *  Since uses a static buffer is not reentrant!!!
 *
 *
 *  return value: 1 in success case, 0 otherwise.
 */
#define MD5SIZE 32
char* get_md5(char* filename){
  pid_t pid;
  int pipes[2];/*communication pipe between process*/
  static char md5string[ MD5SIZE + 1 ];

  if( socketpair(AF_UNIX, SOCK_STREAM, 0, pipes) < 0 )
    return NULL;

  pid = fork();
  if( pid == -1 )
    return NULL;

  if( pid == 0 ){/*son side*/
    /*
     *  son writes in pipes[0] and father reads from pipes[1]
     */
    close(pipes[1]);
    dup2(pipes[0], STDOUT_FILENO);
    if( execlp("md5sum", "md5sum", filename, NULL) < 0 )
      perror("execl");
  }
  close(pipes[0]);
  waitpid(pid, NULL, 0);
  if( read(pipes[1], md5string, MD5SIZE) < MD5SIZE )
    return NULL;

  /*null terminated string REMEMBER!!!*/
  md5string[ MD5SIZE ] = '\0';

  return md5string;
}