Public feed #721291

driver.c

public text v1 · immutable
Raw Edit
·published 2007-10-01 03:41 UTC
rendered paste body
#include <sys/wait.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>

#define BUFSIZE 1024
#define INPUT 0
#define OUTPUT 1

int main(int argc, char *argv[])
{
  /* initialization variables */
  int fd_in;
  int fd_out;
  int pfd[2];
  int status;
  char buf[BUFSIZE];
  char buf2[BUFSIZE];
  int n_read;
  int n_written;
  fd_in = open(argv[1], O_RDONLY);
  if(fd_in < 0)
  {
    perror("can't open %s for input", argv[1]);
    return 1;
  }
  fd_out = creat(argv[2], 0644);
  if(fd_out < 0)
  {
    perror("can't open %s for output", argv[2]);
    return 1;
  }
  close(INPUT);
  dup(fd_in);
  close(OUTPUT);
  dup2(fd_out);
  n_read = read(fd_in, buf, BUFSIZE);
  pipe(pfd);
  if(fork() != 0)
  {
    if(fork() != 0) /* parent */
    {
      wait(&status);
      wait(&status);
    }
    else  /* child2 */
    {
      /* setup for writing */
      close(pfd[0]);
      close(OUTPUT);
      if(dup(pfd[1]) == -1)
      {
      	perror("dup2 failed");
      }
      close(pfd[1]);
      execl("convert", "convert", buf, (char *) 0);
    }
  }
  else { /* child1 */
    /* setup for reading */
    close(pfd[1]);
    close(INPUT);
    if(dup(pfd[0]) == -1)
    {
      perror("dup2 failed");
    }
    close(pfd[0]);
    /* get stdin, which should be output from child2 */
    scanf("%s", buf2);
    execl("count", "count", buf2, (char *) 0); 
  }
  close(fd_in);
  close(fd_out);
}