src/HOL/Tools/ATP/watcher.ML
author paulson
Fri Sep 02 15:25:44 2005 +0200 (2005-09-02)
changeset 17231 f42bc4f7afdf
parent 17216 df66d8feec63
child 17234 12a9393c5d77
permissions -rw-r--r--
tidying up the Isabelle/ATP interface
     1 (*  Title:      Watcher.ML
     2     ID:         $Id$
     3     Author:     Claire Quigley
     4     Copyright   2004  University of Cambridge
     5  *)
     6 
     7  (***************************************************************************)
     8  (*  The watcher process starts a resolution process when it receives a     *)
     9 (*  message from Isabelle                                                  *)
    10 (*  Signals Isabelle, puts output of child into pipe to Isabelle,          *)
    11 (*  and removes dead processes.  Also possible to kill all the resolution  *)
    12 (*  processes currently running.                                           *)
    13 (*  Hardwired version of where to pick up the tptp files for the moment    *)
    14 (***************************************************************************)
    15 
    16 (*use "Proof_Transfer";
    17 use "VampireCommunication";
    18 use "SpassCommunication";*)
    19 (*use "/homes/clq20/Jia_Code/TransStartIsar";*)
    20 
    21 
    22 structure Watcher: WATCHER =
    23   struct
    24 
    25 open ReconPrelim Recon_Transfer
    26 
    27 val goals_being_watched = ref 0;
    28 
    29 (*****************************************)
    30 (*  The result of calling createWatcher  *)
    31 (*****************************************)
    32 
    33 datatype proc = PROC of {
    34         pid : Posix.Process.pid,
    35         instr : TextIO.instream,
    36         outstr : TextIO.outstream
    37       };
    38 
    39 (*****************************************)
    40 (*  The result of calling executeToList  *)
    41 (*****************************************)
    42 
    43 datatype cmdproc = CMDPROC of {
    44         prover: string,             (* Name of the resolution prover used, e.g. Vampire, SPASS *)
    45         cmd:  string,              (* The file containing the goal for res prover to prove *)     
    46         thmstring: string,         (* string representation of subgoal after negation, skolemization*) 
    47         goalstring: string,         (* string representation of subgoal*) 
    48         proc_handle : (TextIO.instream,TextIO.outstream) Unix.proc,
    49         instr : TextIO.instream,   (*  Input stream to child process *)
    50         outstr : TextIO.outstream  (*  Output stream from child process *)
    51       };
    52 
    53 type signal = Posix.Signal.signal
    54 datatype exit_status = datatype Posix.Process.exit_status
    55 
    56 val fromStatus = Posix.Process.fromStatus
    57 
    58 
    59 fun reap(pid, instr, outstr) =
    60         let
    61 		val u = TextIO.closeIn instr;
    62 	        val u = TextIO.closeOut outstr;
    63 	
    64 		val (_, status) =
    65 			Posix.Process.waitpid(Posix.Process.W_CHILD pid, [])
    66 	in
    67 		status
    68 	end
    69 
    70 fun fdReader (name : string, fd : Posix.IO.file_desc) =
    71 	  Posix.IO.mkTextReader {initBlkMode = true,name = name,fd = fd };
    72 
    73 fun fdWriter (name, fd) =
    74           Posix.IO.mkTextWriter {
    75 	      appendMode = false,
    76               initBlkMode = true,
    77               name = name,  
    78               chunkSize=4096,
    79               fd = fd
    80             };
    81 
    82 fun openOutFD (name, fd) =
    83 	  TextIO.mkOutstream (
    84 	    TextIO.StreamIO.mkOutstream (
    85 	      fdWriter (name, fd), IO.BLOCK_BUF));
    86 
    87 fun openInFD (name, fd) =
    88 	  TextIO.mkInstream (
    89 	    TextIO.StreamIO.mkInstream (
    90 	      fdReader (name, fd), ""));
    91 
    92 fun killChild child_handle = Unix.reap child_handle 
    93 
    94 fun childInfo (PROC{pid,instr,outstr }) = (pid,(instr,outstr));
    95 
    96 fun cmdstreamsOf (CMDPROC{instr,outstr,...}) = (instr, outstr);
    97 
    98 fun cmdInStream (CMDPROC{instr,outstr,...}) = (instr);
    99 
   100 fun cmdchildInfo (CMDPROC{prover,cmd,thmstring,proc_handle,goalstring,instr,outstr}) = (prover,(cmd, (instr,outstr)));
   101 
   102 fun cmdchildHandle (CMDPROC{prover,cmd,thmstring,goalstring,proc_handle,instr,outstr})  = proc_handle;
   103 
   104 fun cmdProver (CMDPROC{prover,cmd,thmstring,goalstring,proc_handle,instr,outstr})  = (prover);
   105 
   106 fun cmdThm (CMDPROC{prover,cmd,thmstring,goalstring,proc_handle,instr,outstr})  = (thmstring);
   107 
   108 fun cmdGoal (CMDPROC{prover,cmd,thmstring,goalstring,proc_handle,instr,outstr})  = (goalstring);
   109 
   110 fun sendOutput (outstr,str) = (TextIO.outputSubstr (outstr, (Substring.all str));TextIO.flushOut outstr);
   111 
   112 (********************************************************************************************)
   113 (*  takes a list of arguments and sends them individually to the watcher process by pipe    *)
   114 (********************************************************************************************)
   115 
   116 fun outputArgs (toWatcherStr, []) = ()
   117 |   outputArgs (toWatcherStr, (x::xs)) = (TextIO.output (toWatcherStr, x); 
   118                                           TextIO.flushOut toWatcherStr;
   119                                          outputArgs (toWatcherStr, xs))
   120 
   121 (********************************************************************************)
   122 (*    gets individual args from instream and concatenates them into a list      *)
   123 (********************************************************************************)
   124 
   125 fun getArgs (fromParentStr, toParentStr,ys) =  let 
   126                                        val thisLine = TextIO.input fromParentStr
   127                                     in
   128                                         ((ys@[thisLine]))
   129                                     end
   130 
   131 (********************************************************************************)
   132 (*  Remove the \n character from the end of each filename                       *)
   133 (********************************************************************************)
   134 
   135 (*fun getCmd cmdStr = let val backList = ((rev(explode cmdStr))) 
   136                     in
   137                         if (String.isPrefix "\n"  (implode backList )) 
   138                         then (implode (rev ((tl backList))))
   139                         else cmdStr
   140                     end*)
   141                             
   142 (********************************************************************************)
   143 (*  Send request to Watcher for a vampire to be called for filename in arg      *)
   144 (********************************************************************************)
   145                     
   146 fun callResProver (toWatcherStr,  arg) = 
   147       (sendOutput (toWatcherStr, arg^"\n"); 
   148        TextIO.flushOut toWatcherStr)
   149 
   150 (*****************************************************************************************)
   151 (*  Send request to Watcher for multiple provers to be called for filenames in arg       *)
   152 (*  need to do the dfg stuff in the watcher, not here! send over the clasimp and stuff files too*)
   153 (*****************************************************************************************)
   154 
   155     
   156 (* need to modify to send over hyps file too *)
   157 fun callResProvers (toWatcherStr,  []) = 
   158       (sendOutput (toWatcherStr, "End of calls\n");  TextIO.flushOut toWatcherStr)
   159 |   callResProvers (toWatcherStr,
   160                     (prover,thmstring,goalstring, proverCmd,settings,clasimpfile, 
   161                      axfile, hypsfile,probfile)  ::  args) =
   162       let val _ = File.write (File.tmp_path (Path.basic "tog_comms"))
   163                              (prover^thmstring^goalstring^proverCmd^settings^
   164                               clasimpfile^hypsfile^probfile)
   165       in sendOutput (toWatcherStr,    
   166             (prover^"$"^thmstring^"$"^goalstring^"$"^proverCmd^"$"^
   167              settings^"$"^clasimpfile^"$"^hypsfile^"$"^probfile^"\n"));
   168          goals_being_watched := (!goals_being_watched) + 1;
   169 	 TextIO.flushOut toWatcherStr;
   170 	 callResProvers (toWatcherStr,args)
   171       end   
   172                                                 
   173 
   174 (*
   175 fun callResProversStr (toWatcherStr,  []) =  "End of calls\n" 
   176                                      
   177 |   callResProversStr (toWatcherStr,(prover,thmstring,goalstring, proverCmd,settings,clasimpfile, axfile, hypsfile, probfile)::args) =
   178                                             ((prover^"*"^thmstring^"*"^goalstring^"*"^proverCmd^"*"^settings^"*"^clasimpfile^"*"^axfile^"*"^hypsfile^"*"^probfile^"\n")
   179                                             
   180      *)                                      
   181  
   182 (**************************************************************)
   183 (* Send message to watcher to kill currently running vampires *)
   184 (**************************************************************)
   185 
   186 fun callSlayer (toWatcherStr) = (sendOutput (toWatcherStr, "Kill vampires\n"); 
   187                             TextIO.flushOut toWatcherStr)
   188 
   189 
   190 
   191 (**************************************************************)
   192 (* Remove \n token from a vampire goal filename and extract   *)
   193 (* prover, proverCmd, settings and file from input string     *)
   194 (**************************************************************)
   195 
   196 
   197  fun takeUntil ch [] res  = (res, [])
   198  |   takeUntil ch (x::xs) res = 
   199         if   x = ch then (res, xs)
   200 	else takeUntil ch xs (res@[x])
   201 
   202  fun getSettings [] settings = settings
   203 |    getSettings (xs) settings = 
   204        let val (set, rest ) = takeUntil "%" xs []
   205        in
   206 	   getSettings rest (settings@[(implode set)])
   207        end
   208 
   209 fun separateFields str =
   210   let val  outfile = TextIO.openAppend(*("sep_field")*)(File.platform_path(File.tmp_path (Path.basic "sep_field")))                                                                         
   211       val _ = TextIO.output (outfile,("In separateFields, str is: "^(implode str)^"\n\n") )
   212       val _ =  TextIO.closeOut outfile
   213       val (prover, rest) = takeUntil "$" str []
   214       val prover = implode prover
   215 
   216       val (thmstring, rest) =  takeUntil "$" rest []
   217       val thmstring = implode thmstring
   218 
   219       val (goalstring, rest) =  takeUntil "$" rest []
   220       val goalstring = implode goalstring
   221 
   222       val (proverCmd, rest ) =  takeUntil "$" rest []
   223       val proverCmd = implode proverCmd
   224       
   225       val (settings, rest) =  takeUntil "$" rest []
   226       val settings = getSettings settings []
   227 
   228       val (clasimpfile, rest ) =  takeUntil "$" rest []
   229       val clasimpfile = implode clasimpfile
   230       
   231       val (hypsfile, rest ) =  takeUntil "$" rest []
   232       val hypsfile = implode hypsfile
   233 
   234       val (file, rest) =  takeUntil "$" rest []
   235       val file = implode file
   236 
   237       val _ = File.append (File.tmp_path (Path.basic "sep_comms"))                                                                                
   238                   ("Sep comms are: "^(implode str)^"**"^
   239                    prover^" thmstring: "^thmstring^"\n goalstr:  "^goalstring^" \n provercmd: "^proverCmd^" \n  clasimp "^clasimpfile^" \n hyps "^hypsfile^"\n prob  "^file^"\n\n")
   240   in
   241      (prover,thmstring,goalstring, proverCmd, settings, clasimpfile, hypsfile, file)
   242   end
   243 
   244                       
   245 (***********************************************************************************)
   246 (* do tptp2x and cat to turn clasimpfile, hypsfile and probfile into one .dfg file *)
   247 (***********************************************************************************)
   248 
   249 fun formatCmd (prover,thmstring,goalstring, proverCmd, settings, clasimpfile, hypsfile ,probfile) = 
   250   let
   251     (*** want to cat clasimp ax hyps prob, then send the resulting file to tptp2x ***)
   252     val probID = List.last(explode probfile)
   253     val wholefile = File.tmp_path (Path.basic ("ax_prob_" ^ probID))
   254     
   255     (*** only include problem and clasimp for the moment, not sure 
   256 	 how to refer to hyps/local axioms just now ***)
   257     val whole_prob_file = Unix.execute("/bin/cat", 
   258 	     [clasimpfile,(*axfile, hypsfile,*)probfile,  ">",
   259 	      File.platform_path wholefile])
   260     
   261     val dfg_dir = File.tmp_path (Path.basic "dfg"); 
   262     val dfg_path = File.platform_path dfg_dir;
   263     
   264     (*** want to cat clasimp ax hyps prob, then send the resulting file to tptp2x ***)
   265     val probID = List.last(explode probfile)
   266     val wholefile = File.tmp_path (Path.basic ("ax_prob_"^probID))
   267 
   268     (*** only include problem and clasimp for the moment, not sure how to refer to ***)
   269     (*** hyps/local axioms just now                                                ***)
   270     val whole_prob_file = Unix.execute("/bin/cat", [clasimpfile,(*axfile, hypsfile,*)probfile,  ">", (File.platform_path wholefile)])
   271 
   272     (* if using spass prob_n already contains whole DFG file, otherwise need to mash axioms*)
   273     (* from clasimpset onto problem file *)
   274     val newfile =   if !SpassComm.spass 
   275 		    then probfile
   276                     else (File.platform_path wholefile)
   277 
   278     val _ =  File.append (File.tmp_path (Path.basic"thmstring_in_watcher"))
   279 	       (thmstring^"\n goals_watched"^(string_of_int(!goals_being_watched))^newfile^"\n")
   280   in
   281     (prover,thmstring,goalstring, proverCmd, settings,newfile)	
   282   end;
   283 
   284 
   285 
   286 (* remove \n from end of command and put back into tuple format *)
   287              
   288 
   289 (*  val cmdStr = "spass*((ALL xa. (~ P x | P xa) & (~ P xa | P x)) & (P xa | (ALL x. P x)) & ((ALL x. ~ P x) | ~ P xb) [.])*(EX x. ALL y. P x = P y) --> (EX x. P x) = (ALL y. P y)*/homes/clq20/bin/SPASS*-DocProof*/local/scratch/clq20/27023/clasimp*/local/scratch/clq20/27023/hyps*/local/scratch/clq20/27023/prob_1\n"
   290 
   291 val cmdStr = "vampire*(length (rev xs) = length xs  [.]) & (length (rev (a # xs)) ~= length (a # xs) [.])*length (rev []) = length []*/homes/jm318/Vampire8/vkernel*-t 300%-m 100000*/local/scratch/clq20/23523/clasimp*/local/scratch/clq20/23523/hyps*/local/scratch/clq20/23523/prob_1\n"
   292  *)
   293 
   294 (*FIX:  are the two getCmd procs getting confused?  Why do I have two anyway? *)
   295 
   296  fun getCmd cmdStr = 
   297        let val backList = rev(explode cmdStr)
   298 	   val _ = File.append (File.tmp_path (Path.basic"cmdStr")) cmdStr
   299        in
   300 	   if (String.isPrefix "\n"  (implode backList )) 
   301 	   then 
   302 	       let val newCmdStr = (rev(tl backList))
   303 	       in  File.write (File.tmp_path (Path.basic"backlist")) 
   304 	                      ("about to call sepfields with "^(implode newCmdStr));
   305 		   formatCmd (separateFields newCmdStr)
   306 	       end
   307 	   else formatCmd (separateFields (explode cmdStr))
   308        end
   309                       
   310 
   311 fun getProofCmd (a,b,c,d,e,f) = d
   312 
   313                         
   314 (**************************************************************)
   315 (* Get commands from Isabelle                                 *)
   316 (**************************************************************)
   317 (* FIX: or perhaps do the tptp2x stuff here - so it's get commands and then format them, before passing them to spass *)
   318 
   319 fun getCmds (toParentStr,fromParentStr, cmdList) = 
   320   let val thisLine = TextIO.inputLine fromParentStr 
   321       val _ = File.append (File.tmp_path (Path.basic "parent_comms")) thisLine
   322   in
   323      if (thisLine = "End of calls\n") 
   324      then cmdList
   325      else if (thisLine = "Kill children\n") 
   326      then 
   327 	 (   TextIO.output (toParentStr,thisLine ); 
   328 	     TextIO.flushOut toParentStr;
   329 	   (("","","","Kill children",[],"")::cmdList)
   330 	  )
   331      else  let val thisCmd = getCmd (thisLine) 
   332 	       (*********************************************************)
   333 	       (* thisCmd = (prover,thmstring,proverCmd, settings, file)*)
   334 	       (* i.e. put back into tuple format                       *)
   335 	       (*********************************************************)
   336 	   in
   337 	     (*TextIO.output (toParentStr, thisCmd); 
   338 	       TextIO.flushOut toParentStr;*)
   339 	       getCmds (toParentStr,fromParentStr, (thisCmd::cmdList))
   340 	   end
   341   end
   342 	    
   343                                                                   
   344 (**************************************************************)
   345 (*  Get Io-descriptor for polling of an input stream          *)
   346 (**************************************************************)
   347 
   348 fun getInIoDesc someInstr = 
   349     let val (rd, buf) = TextIO.StreamIO.getReader(TextIO.getInstream someInstr)
   350         val _ = TextIO.output (TextIO.stdOut, buf)
   351         val ioDesc = 
   352 	    case rd
   353 	      of TextPrimIO.RD{ioDesc = SOME iod, ...} =>SOME iod
   354 	       | _ => NONE
   355      in (* since getting the reader will have terminated the stream, we need
   356 	 * to build a new stream. *)
   357 	TextIO.setInstream(someInstr, TextIO.StreamIO.mkInstream(rd, buf));
   358 	ioDesc
   359     end
   360 
   361 
   362 (*************************************)
   363 (*  Set up a Watcher Process         *)
   364 (*************************************)
   365 
   366 fun setupWatcher (thm,clause_arr, num_of_clauses) = 
   367   let
   368     (** pipes for communication between parent and watcher **)
   369     val p1 = Posix.IO.pipe ()
   370     val p2 = Posix.IO.pipe ()
   371     fun closep () = (
   372 	  Posix.IO.close (#outfd p1); 
   373 	  Posix.IO.close (#infd p1);
   374 	  Posix.IO.close (#outfd p2); 
   375 	  Posix.IO.close (#infd p2)
   376 	)
   377     (***********************************************************)
   378     (****** fork a watcher process and get it set up and going *)
   379     (***********************************************************)
   380     fun startWatcher (procList) =
   381 	     (case  Posix.Process.fork() (***************************************)
   382 	   of SOME pid =>  pid           (* parent - i.e. main Isabelle process *)
   383 					 (***************************************)
   384 
   385 					   (*************************)
   386 	    | NONE => let                  (* child - i.e. watcher  *)
   387 		val oldchildin = #infd p1  (*************************)
   388 		val fromParent = Posix.FileSys.wordToFD 0w0
   389 		val oldchildout = #outfd p2
   390 		val toParent = Posix.FileSys.wordToFD 0w1
   391 		val fromParentIOD = Posix.FileSys.fdToIOD fromParent
   392 		val fromParentStr = openInFD ("_exec_in_parent", fromParent)
   393 		val toParentStr = openOutFD ("_exec_out_parent", toParent)
   394 		val sign = sign_of_thm thm
   395 		val prems = prems_of thm
   396 		val prems_string =  Meson.concat_with_and (map (Sign.string_of_term sign) prems) 
   397 		val _ = (warning ("subgoals forked to startWatcher: "^prems_string));
   398 	       (* tracing *)
   399 	      (*val tenth_ax = fst( Array.sub(clause_arr, 1))  
   400 		val tenth_ax_thms = memo_find_clause (tenth_ax, clause_tab)
   401 		val clause_str = Meson.concat_with_and (map string_of_thm tenth_ax_thms)
   402 		val _ = (warning ("tenth axiom in array in watcher is: "^tenth_ax))         
   403 		val _ = (warning ("tenth axiom in table in watcher is: "^clause_str))         
   404 		val _ = (warning ("num_of_clauses in watcher is: "^(string_of_int (num_of_clauses))) )       
   405 			 *)
   406 		(*val goalstr = string_of_thm (the_goal)
   407 		 val  outfile = TextIO.openOut(File.platform_path(File.tmp_path (Path.basic "goal_in_watcher")));  
   408 		val _ = TextIO.output (outfile,goalstr )
   409 		val _ =  TextIO.closeOut outfile*)
   410 		fun killChildren [] = ()
   411 	     |      killChildren  (child_handle::children) = (killChild child_handle; killChildren children)
   412 
   413 	      (*************************************************************)
   414 	      (* take an instream and poll its underlying reader for input *)
   415 	      (*************************************************************)
   416 
   417 	      fun pollParentInput () = 
   418 		 let val pd = OS.IO.pollDesc (fromParentIOD)
   419 		 in 
   420 		   if (isSome pd ) then 
   421 		       let val pd' = OS.IO.pollIn (valOf pd)
   422 			   val pdl = OS.IO.poll ([pd'], SOME (Time.fromMilliseconds 2000)) 
   423 			   val _ = File.append (File.tmp_path (Path.basic "parent_poll")) 
   424 			     ("In parent_poll\n")	
   425 		       in
   426 			  if null pdl 
   427 			  then
   428 			     NONE
   429 			  else if (OS.IO.isIn (hd pdl)) 
   430 			       then SOME (getCmds (toParentStr, fromParentStr, []))
   431 			       else NONE
   432 		       end
   433 		     else NONE
   434 		 end
   435 		      
   436 	       fun pollChildInput (fromStr) = 
   437 		 let val _ = File.append (File.tmp_path (Path.basic "child_poll")) 
   438 			       ("In child_poll\n")
   439 		     val iod = getInIoDesc fromStr
   440 		 in 
   441 		   if isSome iod 
   442 		   then 
   443 		     let val pd = OS.IO.pollDesc (valOf iod)
   444 		     in 
   445 		     if (isSome pd ) then 
   446 			 let val pd' = OS.IO.pollIn (valOf pd)
   447 			     val pdl = OS.IO.poll ([pd'], SOME (Time.fromMilliseconds 2000)) 
   448 			 in
   449 			    if null pdl 
   450 			    then
   451 			      ( File.append (File.tmp_path (Path.basic "child_poll_res")) 
   452 			       ("Null pdl \n");NONE)
   453 			    else if (OS.IO.isIn (hd pdl)) 
   454 				 then
   455 				     (let val inval =  (TextIO.inputLine fromStr)
   456 					  val _ = File.append (File.tmp_path (Path.basic "child_poll_res")) (inval^"\n")
   457 				      in
   458 					    SOME inval
   459 				      end)
   460 				 else
   461 				       ( File.append (File.tmp_path (Path.basic "child_poll_res")) 
   462 			       ("Null pdl \n");NONE)
   463 			 end
   464 		       else  NONE
   465 		       end
   466 		   else NONE
   467 	     end
   468 
   469 
   470 	     (****************************************************************************)
   471 	     (* Check all vampire processes currently running for output                 *)
   472 	     (****************************************************************************) 
   473 							(*********************************)
   474 	      fun checkChildren ([], toParentStr) = []  (*** no children to check ********)
   475 							(*********************************)
   476 	      |   checkChildren ((childProc::otherChildren), toParentStr) = 
   477 		    let val _ = File.append (File.tmp_path (Path.basic "child_check")) 
   478 			           ("In check child, length of queue:"^(string_of_int (length (childProc::otherChildren)))^"\n")
   479                         val (childInput,childOutput) =  cmdstreamsOf childProc
   480 			val child_handle= cmdchildHandle childProc
   481 			(* childCmd is the .dfg file that the problem is in *)
   482 			val childCmd = fst(snd (cmdchildInfo childProc))
   483                         val _ = File.append (File.tmp_path (Path.basic "child_command")) 
   484 			           (childCmd^"\n")
   485 			(* now get the number of the subgoal from the filename *)
   486 			val sg_num = (*if (!SpassComm.spass )
   487 				     then 
   488 					int_of_string(ReconOrderClauses.get_nth 5 (rev(explode childCmd)))
   489 				     else*)
   490 					int_of_string(hd (rev(explode childCmd)))
   491 
   492 			val childIncoming = pollChildInput childInput
   493  			val _ = File.append (File.tmp_path (Path.basic "child_check_polled")) 
   494 			           ("finished polling child \n")
   495 			val parentID = Posix.ProcEnv.getppid()
   496 			val prover = cmdProver childProc
   497 			val thmstring = cmdThm childProc
   498 			val sign = sign_of_thm thm
   499 			val prems = prems_of thm
   500 			val prems_string =  Meson.concat_with_and (map (Sign.string_of_term sign) prems) 
   501 			val _ = warning("subgoals forked to checkChildren: "^prems_string)
   502 			val goalstring = cmdGoal childProc							
   503 			val _ = File.append (File.tmp_path (Path.basic "child_comms")) 
   504 			           (prover^thmstring^goalstring^childCmd^"\n")
   505 		    in 
   506 		      if (isSome childIncoming) 
   507 		      then 
   508 			  (* check here for prover label on child*)
   509 			  let val _ = File.write (File.tmp_path (Path.basic "child_incoming")) 
   510 			             ("subgoals forked to checkChildren:"^
   511 			             prems_string^prover^thmstring^goalstring^childCmd) 
   512 		              val childDone = (case prover of
   513 	                          "vampire" => (VampComm.checkVampProofFound(childInput, toParentStr, parentID,thmstring,goalstring, childCmd, thm, sg_num,clause_arr, num_of_clauses) )                                              
   514                                  |"spass" => (SpassComm.checkSpassProofFound(childInput, toParentStr, parentID,thmstring,goalstring, childCmd, thm, sg_num,clause_arr, num_of_clauses)     ) )
   515 			   in
   516 			    if childDone      (**********************************************)
   517 			    then (* child has found a proof and transferred it *)
   518 			       (* Remove this child and go on to check others*)
   519 			       (**********************************************)
   520 			       (Unix.reap child_handle;
   521 				checkChildren(otherChildren, toParentStr))
   522 			    else 
   523 			       (**********************************************)
   524 			       (* Keep this child and go on to check others  *)
   525 			       (**********************************************)
   526 			      (childProc::(checkChildren (otherChildren, toParentStr)))
   527 			 end
   528 		       else
   529 			 (File.append (File.tmp_path (Path.basic "child_incoming")) "No child output ";
   530 			  childProc::(checkChildren (otherChildren, toParentStr)))
   531 		    end
   532 
   533 	     
   534 	  (********************************************************************)                  
   535 	  (* call resolution processes                                        *)
   536 	  (* settings should be a list of strings                             *)
   537 	  (* e.g. ["-t 300", "-m 100000"]         (TextIO.input instr)^                            *)
   538 	  (* takes list of (string, string, string list, string)list proclist *)
   539 	  (********************************************************************)
   540 
   541 
   542 (*** add subgoal id num to this *)
   543 	     fun execCmds  [] procList = procList
   544 	     |   execCmds  ((prover, thmstring,goalstring,proverCmd,settings,file)::cmds) procList  =             let val _ = File.append (File.tmp_path (Path.basic "pre_exec_child"))  ("\nAbout to execute command for goal:\n"^goalstring^proverCmd^(concat settings)^file^" at "^(Date.toString(Date.fromTimeLocal(Time.now()))))
   545 	       in 
   546 		 if (prover = "spass") 
   547 		 then 
   548 		   let val childhandle:(TextIO.instream,TextIO.outstream) Unix.proc  = 
   549 		            (Unix.execute(proverCmd, (["-FullRed=0"]@settings@[file])))
   550 		       val (instr, outstr) = Unix.streamsOf childhandle
   551 		       val newProcList =    (((CMDPROC{
   552 					    prover = prover,
   553 					    cmd = file,
   554 					    thmstring = thmstring,
   555 					    goalstring = goalstring,
   556 					    proc_handle = childhandle,
   557 					    instr = instr,
   558 					    outstr = outstr })::procList))
   559 			val _ = File.append (File.tmp_path (Path.basic "exec_child"))  
   560 			     ("\nexecuting command for goal:\n"^
   561 			      goalstring^proverCmd^(concat settings)^file^" at "^(Date.toString(Date.fromTimeLocal(Time.now()))))
   562 		   in
   563 		      Posix.Process.sleep (Time.fromSeconds 1);execCmds cmds newProcList
   564 		   end
   565 		 else 
   566 		   let val childhandle:(TextIO.instream,TextIO.outstream) Unix.proc  = 
   567 		            (Unix.execute(proverCmd, (settings@[file])))
   568 		       val (instr, outstr) = Unix.streamsOf childhandle
   569 		       
   570 		       val newProcList = (CMDPROC{
   571 					    prover = prover,
   572 					    cmd = file,
   573 					    thmstring = thmstring,
   574 					    goalstring = goalstring,
   575 					    proc_handle = childhandle,
   576 					    instr = instr,
   577 					    outstr = outstr }) :: procList
   578 	  
   579 		       val _ = File.append (File.tmp_path (Path.basic "exec_child")) 
   580 		                 ("executing command for goal:\n"^
   581 		                  goalstring^proverCmd^(concat settings)^file^
   582 		                  " at "^(Date.toString(Date.fromTimeLocal(Time.now()))))
   583 		   in
   584 		     Posix.Process.sleep (Time.fromSeconds 1); execCmds cmds newProcList
   585 		   end
   586 		end
   587 
   588 
   589 	  (****************************************)                  
   590 	  (* call resolution processes remotely   *)
   591 	  (* settings should be a list of strings *)
   592 	  (* e.g. ["-t 300", "-m 100000"]         *)
   593 	  (****************************************)
   594 
   595 	   (*  fun execRemoteCmds  [] procList = procList
   596 	     |   execRemoteCmds ((prover, thmstring,goalstring,proverCmd ,settings,file)::cmds) procList  =  
   597 				       let val  newProcList =  mySshExecuteToList ("/usr/bin/ssh",([prover,thmstring,goalstring,"-t", "shep"]@[proverCmd]@settings@[file]), procList)
   598 					   in
   599 						execRemoteCmds  cmds newProcList
   600 					   end
   601 *)
   602 
   603 	     fun printList (outStr, []) = ()
   604 	     |   printList (outStr, (x::xs)) = (TextIO.output (outStr, x);TextIO.flushOut outStr; printList (outStr,xs))                  
   605 
   606 
   607 	  (**********************************************)                  
   608 	  (* Watcher Loop                               *)
   609 	  (**********************************************)
   610 
   611 	      fun keepWatching (toParentStr, fromParentStr,procList) = 
   612 		let fun loop (procList) =  
   613 		     let val cmdsFromIsa = pollParentInput ()
   614 			 fun killchildHandler (n:int)  = 
   615 			       (TextIO.output(toParentStr, "Killing child proof processes!\n");
   616 				TextIO.flushOut toParentStr;
   617 				killChildren (map (cmdchildHandle) procList);
   618 				())
   619 		     in 
   620 			(*Signal.signal (Posix.Signal.usr2, Signal.SIG_HANDLE killchildHandler);*)
   621 									   (**********************************)
   622 			if (isSome cmdsFromIsa) 
   623 			then (*  deal with input from Isabelle *)
   624 			  if (getProofCmd(hd(valOf cmdsFromIsa)) = "Kill children" )
   625 			  then 
   626 			    let val child_handles = map cmdchildHandle procList 
   627 			    in
   628 			       killChildren child_handles;
   629 			       (*Posix.Process.kill(Posix.Process.K_PROC (Posix.ProcEnv.getppid()), Posix.Signal.usr2);*)    
   630 			       loop ([])
   631 			    end
   632 			  else
   633 			    if ((length procList)<10)    (********************)
   634 			    then                        (* Execute locally  *)
   635 			      let 
   636 				val newProcList = execCmds (valOf cmdsFromIsa) procList
   637 				val parentID = Posix.ProcEnv.getppid()
   638 				   val _ = (File.append (File.tmp_path (Path.basic "prekeep_watch")) "Just execed a child\n ")
   639 				val newProcList' =checkChildren (newProcList, toParentStr) 
   640 
   641 				val _ = warning("off to keep watching...")
   642 			       val _ = (File.append (File.tmp_path (Path.basic "keep_watch")) "Off to keep watching...\n ")
   643 			      in
   644 				(*Posix.Process.sleep (Time.fromSeconds 1);*)
   645 				loop (newProcList') 
   646 			      end
   647 			    else  (* Execute remotely              *)
   648                                   (* (actually not remote for now )*)
   649 			      let 
   650 				val newProcList = execCmds (valOf cmdsFromIsa) procList
   651 				val parentID = Posix.ProcEnv.getppid()
   652 				val newProcList' =checkChildren (newProcList, toParentStr) 
   653 			      in
   654 				(*Posix.Process.sleep (Time.fromSeconds 1);*)
   655 				loop (newProcList') 
   656 			      end
   657 			else (* No new input from Isabelle *)
   658 			  let val newProcList = checkChildren ((procList), toParentStr)
   659 			  in
   660 			    (*Posix.Process.sleep (Time.fromSeconds 1);*)
   661 			   (File.append (File.tmp_path (Path.basic "keep_watch")) "Off to keep watching.2..\n ");
   662 			    loop (newProcList)
   663 			  end
   664 		      end
   665 		in  
   666 		    loop (procList)
   667 		end
   668 		
   669     
   670 		in
   671 		 (***************************)
   672 		 (*** Sort out pipes ********)
   673 		 (***************************)
   674 
   675 		  Posix.IO.close (#outfd p1);
   676 		  Posix.IO.close (#infd p2);
   677 		  Posix.IO.dup2{old = oldchildin, new = fromParent};
   678 		  Posix.IO.close oldchildin;
   679 		  Posix.IO.dup2{old = oldchildout, new = toParent};
   680 		  Posix.IO.close oldchildout;
   681 
   682 		  (***************************)
   683 		  (* start the watcher loop  *)
   684 		  (***************************)
   685 		  keepWatching (toParentStr, fromParentStr, procList);
   686 		  (****************************************************************************)
   687    (* fake return value - actually want the watcher to loop until killed *)
   688 		  (****************************************************************************)
   689 		  Posix.Process.wordToPid 0w0
   690 		end);
   691 	  (* end case *)
   692 
   693 
   694     val _ = TextIO.flushOut TextIO.stdOut
   695 
   696     (*******************************)
   697     (***  set watcher going ********)
   698     (*******************************)
   699 
   700     val procList = []
   701     val pid = startWatcher (procList)
   702     (**************************************************)
   703     (* communication streams to watcher               *)
   704     (**************************************************)
   705 
   706     val instr = openInFD ("_exec_in", #infd p2)
   707     val outstr = openOutFD ("_exec_out", #outfd p1)
   708     
   709     in
   710      (*******************************)
   711      (* close the child-side fds    *)
   712      (*******************************)
   713       Posix.IO.close (#outfd p2);
   714       Posix.IO.close (#infd p1);
   715       (* set the fds close on exec *)
   716       Posix.IO.setfd (#infd p2, Posix.IO.FD.flags [Posix.IO.FD.cloexec]);
   717       Posix.IO.setfd (#outfd p1, Posix.IO.FD.flags [Posix.IO.FD.cloexec]);
   718        
   719      (*******************************)
   720      (* return value                *)
   721      (*******************************)
   722       PROC{pid = pid,
   723 	instr = instr,
   724 	outstr = outstr
   725       }
   726    end;
   727 
   728 
   729 
   730 (**********************************************************)
   731 (* Start a watcher and set up signal handlers             *)
   732 (**********************************************************)
   733 
   734 fun killWatcher pid= Posix.Process.kill(Posix.Process.K_PROC pid, Posix.Signal.kill);
   735 
   736 fun reapWatcher(pid, instr, outstr) =
   737   let val u = TextIO.closeIn instr;
   738       val u = TextIO.closeOut outstr;
   739       val (_, status) = Posix.Process.waitpid(Posix.Process.W_CHILD pid, [])
   740   in
   741 	  status
   742   end
   743 
   744 fun createWatcher (thm,clause_arr, ( num_of_clauses:int)) =
   745  let val mychild = childInfo (setupWatcher(thm,clause_arr,  num_of_clauses))
   746      val streams = snd mychild
   747      val childin = fst streams
   748      val childout = snd streams
   749      val childpid = fst mychild
   750      val sign = sign_of_thm thm
   751      val prems = prems_of thm
   752      val prems_string =  Meson.concat_with_and (map (Sign.string_of_term sign) prems) 
   753      val _ = (warning ("subgoals forked to createWatcher: "^prems_string));
   754      fun vampire_proofHandler (n) =
   755 	(Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   756 	 VampComm.getVampInput childin; Pretty.writeln(Pretty.str (oct_char "361")))               
   757      fun spass_proofHandler (n) = (
   758        let val  outfile = TextIO.openAppend(File.platform_path(File.tmp_path (Path.basic "foo_signal1")));
   759 	   val _ = TextIO.output (outfile, ("In signal handler now\n"))
   760 	   val _ =  TextIO.closeOut outfile
   761 	   val (reconstr, goalstring, thmstring) = SpassComm.getSpassInput childin
   762 	   val  outfile = TextIO.openAppend(File.platform_path(File.tmp_path (Path.basic "foo_signal")));
   763    
   764 	   val _ = TextIO.output (outfile, ("In signal handler  "^reconstr^thmstring^goalstring^"goals_being_watched is: "^(string_of_int (!goals_being_watched))))
   765 	   val _ =  TextIO.closeOut outfile
   766        in (* if a proof has been found and sent back as a reconstruction proof *)
   767 	 if substring (reconstr, 0,1) = "["
   768 	 then (Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   769 	       Recon_Transfer.apply_res_thm reconstr goalstring;
   770 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   771 	       
   772 	       goals_being_watched := ((!goals_being_watched) - 1);
   773        
   774 	       if (!goals_being_watched) = 0
   775 	       then 
   776 		  let val _ = File.write (File.tmp_path (Path.basic "foo_reap_found"))
   777                                    ("Reaping a watcher, goals watched is: "^
   778                                     (string_of_int (!goals_being_watched))^"\n")
   779 		   in
   780 		       killWatcher (childpid); reapWatcher (childpid,childin, childout); ()
   781 		   end
   782 		else () )
   783 	 (* if there's no proof, but a message from Spass *)
   784 	 else if substring (reconstr, 0,5) = "SPASS"
   785 	 then (goals_being_watched := (!goals_being_watched) -1;
   786 	       Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   787 	       Pretty.writeln(Pretty.str ((Recon_Transfer.restore_linebreaks goalstring)^reconstr));
   788 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   789 	       if (!goals_being_watched = 0)
   790 	       then (File.write (File.tmp_path (Path.basic "foo_reap_comp"))
   791 	              ("Reaping a watcher, goals watched is: " ^
   792 	                 (string_of_int (!goals_being_watched))^"\n");
   793 	             killWatcher (childpid); reapWatcher (childpid,childin, childout); ())
   794 		else () ) 
   795 	(* print out a list of rules used from clasimpset*)
   796 	 else if substring (reconstr, 0,5) = "Rules"
   797 	 then (goals_being_watched := (!goals_being_watched) -1;
   798 	       Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   799 	       Pretty.writeln(Pretty.str (goalstring^reconstr));
   800 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   801 	       if (!goals_being_watched = 0)
   802 	       then (File.write (File.tmp_path (Path.basic "foo_reap_comp"))
   803 	              ("Reaping a watcher, goals watched is: " ^
   804 	                 (string_of_int (!goals_being_watched))^"\n");
   805 	             killWatcher (childpid);  reapWatcher (childpid,childin, childout);()
   806 		     )
   807 	       else () )
   808 	  (* if proof translation failed *)
   809 	 else if substring (reconstr, 0,5) = "Proof"
   810 	 then (goals_being_watched := (!goals_being_watched) -1;
   811 	       Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   812 	       Pretty.writeln(Pretty.str (goalstring^(Recon_Transfer.restore_linebreaks reconstr)));
   813 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   814 	       if (!goals_being_watched = 0)
   815 	       then (File.write (File.tmp_path (Path.basic "foo_reap_comp"))
   816 	              ("Reaping a watcher, goals watched is: " ^
   817 	                 (string_of_int (!goals_being_watched))^"\n");
   818 	             killWatcher (childpid);  reapWatcher (childpid,childin, childout);()
   819 		     )
   820 	       else () )
   821 
   822 	 else if substring (reconstr, 0,1) = "%"
   823 	 then (goals_being_watched := (!goals_being_watched) -1;
   824 	       Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   825 	       Pretty.writeln(Pretty.str (goalstring^(Recon_Transfer.restore_linebreaks reconstr)));
   826 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   827 	       if (!goals_being_watched = 0)
   828 	       then (File.write (File.tmp_path (Path.basic "foo_reap_comp"))
   829 	              ("Reaping a watcher, goals watched is: " ^
   830 	                 (string_of_int (!goals_being_watched))^"\n");
   831 	             killWatcher (childpid);  reapWatcher (childpid,childin, childout);()
   832 		     )
   833 	       else () )
   834 
   835 	 else  (* add something here ?*)
   836 	      (goals_being_watched := (!goals_being_watched) -1;
   837 	       Pretty.writeln(Pretty.str ( (concat[(oct_char "360"), (oct_char "377")])));
   838 	       Pretty.writeln(Pretty.str ("Ran out of options in handler"));
   839 	       Pretty.writeln(Pretty.str  (oct_char "361"));
   840 	       if (!goals_being_watched = 0)
   841 	       then (File.write (File.tmp_path (Path.basic "foo_reap_comp"))
   842 		     ("Reaping a watcher, goals watched is: " ^
   843 			(string_of_int (!goals_being_watched))^"\n");
   844 		    killWatcher (childpid);  reapWatcher (childpid,childin, childout);()
   845 		    )
   846 	       else () )
   847        end)
   848 
   849  in IsaSignal.signal (IsaSignal.usr1, IsaSignal.SIG_HANDLE vampire_proofHandler);
   850     IsaSignal.signal (IsaSignal.usr2, IsaSignal.SIG_HANDLE spass_proofHandler);
   851     (childin, childout, childpid)
   852 
   853   end
   854 
   855 end (* structure Watcher *)