home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2351 / psif.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-12-28  |  2.0 KB  |  100 lines

  1. /* psif.c */
  2.  
  3. #ifndef lint
  4. static char rcsid[] = "$Header: /usr/jjc/lprps/RCS/psif.c,v 1.2 90/12/18 09:59:45 jjc Rel $";
  5. #endif
  6.  
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <memory.h>
  10. #include <sys/types.h>
  11. #include <sys/file.h>
  12. #include <sys/stat.h>
  13.  
  14. long lseek();
  15.  
  16. #ifndef TEXT_FILTER
  17. #define TEXT_FILTER "/usr/local/lib/psif-text"
  18. #endif /* not TEXT_FILTER */
  19.  
  20. #ifndef PS_FILTER
  21. #define PS_FILTER "/usr/local/lib/psif-ps"
  22. #endif /* not PS_FILTER */
  23.  
  24. #ifndef ERROR_EXIT_CODE
  25. #define ERROR_EXIT_CODE 1
  26. #endif /* not ERROR_EXIT_CODE */
  27.  
  28. char *prog;
  29.  
  30. void sys_error(s)
  31. char *s;
  32. {
  33.   if (prog)
  34.     (void)fprintf(stderr, "%s: ", prog);
  35.   perror(s);
  36.   exit(ERROR_EXIT_CODE);
  37. }
  38.  
  39. /* ARGSUSED */
  40. main(argc, argv)
  41. int argc;
  42. char **argv;
  43. {
  44.   char buf[BUFSIZ];
  45.   char *command;
  46.   int nread;
  47.   struct stat statb;
  48.   prog = argv[0];
  49.   if ((nread = read(0, buf, 2)) < 0)
  50.     sys_error("read");
  51.   if (nread != 2 || buf[0] != '%' || buf[1] != '!')
  52.     command = TEXT_FILTER;
  53.   else
  54.     command = PS_FILTER;
  55.   if (fstat(0, &statb) < 0)
  56.     sys_error("fstat");
  57.   if ((statb.st_mode & S_IFMT) != S_IFREG) {
  58.     /* this happens with lpr -p */
  59.     int pid;
  60.     int fd[2];
  61.     if (pipe(fd) < 0)
  62.       sys_error("pipe");
  63.     if ((pid = fork()) < 0)
  64.       sys_error("fork");
  65.     else if (pid == 0) {
  66.       /* in the child */
  67.       int d;
  68.       if (close(fd[0]) < 0)
  69.     sys_error("close");
  70.       d = fd[1];
  71.       if (nread != 0) {
  72.     if (write(d, buf, nread) < 0)
  73.       sys_error("write");
  74.     while ((nread = read(0, buf, sizeof(buf))) > 0)
  75.       if (write(d, buf, nread) < 0)
  76.         sys_error("write");
  77.     if (nread < 0)
  78.       sys_error("read");
  79.       }
  80.       if (close(d) < 0)
  81.     sys_error("close");
  82.       exit(0);
  83.     }
  84.     if (close(fd[1]) < 0)
  85.       sys_error("close");
  86.     if (close(0) < 0)
  87.       sys_error("close");
  88.     if (dup(fd[0]) < 0)
  89.       sys_error("dup");
  90.     if (close(fd[0]) < 0)
  91.       sys_error("close");
  92.   }
  93.   else {
  94.     if (lseek(0, (off_t)0, L_SET) < 0)
  95.       sys_error("lseek");
  96.   }
  97.   execv(command, argv);
  98.   sys_error("execv");
  99. }
  100.