home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / historic / v941.tgz / icon.v941src.tar / icon.v941src / ipl / procs / popen.icn < prev    next >
Text File  |  2000-07-29  |  2KB  |  87 lines

  1. ############################################################################
  2. #    
  3. #    File:     popen.icn
  4. #    
  5. #    Subject:  Procedures for pipes
  6. #    
  7. #    Author:   Ronald Florence
  8. #
  9. #    Date:     September 28, 1992
  10. #
  11. ############################################################################
  12. #
  13. #   This file is in the public domain.
  14. #
  15. ############################################################################
  16. #
  17. #    Version:  1.0
  18. #
  19. ############################################################################
  20. #
  21. #  Contents:
  22. #
  23. #  popen(command, mode)
  24. #    mode == "w" writes to a pipe
  25. #    mode == "r" reads from a pipe
  26. #
  27. #  pclose(pipe)
  28. #
  29. #  On systems without real pipes (ms-dos), popen and pclose imitate
  30. #  pipes; pclose must be called after popen.  The code should run
  31. #  faster on ms-dos if dir in tempfile() points to a directory on a
  32. #  virtual disk.
  33. #
  34. #  On systems with real pipes, popen & pclose open and close a pipe.
  35. ############################################################################
  36.  
  37. global PIPE_cmd, PIPE_fname
  38.  
  39. procedure popen(cmd, mode)
  40.   local tfn, p
  41.  
  42.   initial ("pipes" == &features) | {
  43.     PIPE_cmd := table()
  44.     PIPE_fname := table()
  45.   }
  46.   (type(PIPE_fname) ~== "table") & return open(cmd, mode || "p")
  47.   tfn := tempfile("pipe.")
  48.   upto('r', mode) & system(cmd || " > " || tfn)
  49.   p := open(tfn, mode)
  50.   PIPE_fname[p] := tfn
  51.   upto('w', mode) & PIPE_cmd[p] := cmd
  52.   return p
  53. end
  54.  
  55.  
  56. procedure pclose(pipe)
  57.   local status
  58.  
  59.   (type(PIPE_fname) ~== "table") & return close(pipe)
  60.   if \PIPE_cmd[pipe] then {
  61.     close(pipe) 
  62.     PIPE_cmd[pipe] ||:= " < " || PIPE_fname[pipe]
  63.     status := system(PIPE_cmd[pipe])
  64.   }
  65.   else status := close(pipe)
  66.   remove(PIPE_fname[pipe])
  67.   PIPE_cmd[pipe] := PIPE_fname[pipe] := &null
  68.   return status
  69. end
  70.  
  71.     # Richard Goerwitz's ever-useful generator.
  72.  
  73. procedure tempfile(template)
  74.   local temp_name
  75.   static dir
  76.  
  77.   initial {
  78.     if "UNIX" == &features then dir := "/tmp/"
  79.     else dir := ""
  80.   }
  81.   every temp_name := dir || template || right(1 to 999,3,"0") do {
  82.     close(open(temp_name)) & next
  83.     suspend \temp_name
  84.   }
  85. end
  86.