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