in reply to Read STDOUT from Win32::Job while process is running
Win32::Job is fine when you don't need to do anything with the processes it spawns for you, but it limited otherwise.
The following Inline::C code will form a job from any pids you give, including those return by the forking open and system 1, ...; etc.
This example starts a perl one-liner that in turn start the windows calculator and notepad. 10 seconds after the jobs are started, they will disappear. The final sleep is there to show you that the closeHandle() worked:
#! perl -slw use strict; use Inline C => Config => BUILD_NOISY => 1; use Inline C => <<'END_C', NAME => 'JobObject', CLEAN_AFTER_BUILD => +0; #include <windows.h> int createJobObject( char *name ) { HANDLE job; JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0, }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_J +OB_CLOSE; job = (int)CreateJobObjectA( NULL, name ); SetInformationJobObject( job, 9, &jeli, sizeof(jeli) ); return job; } int assignProcessToJobObject( int job, int pid ) { HANDLE hProc = OpenProcess( PROCESS_SET_QUOTA |PROCESS_TERMINATE, +0, pid ); return (int)AssignProcessToJobObject( job, hProc ); } int closeHandle( int handle ) { return (int)CloseHandle( (HANDLE)handle ); } END_C my $job = createJobObject( 'fred' ); print $job; my $pid = open O, q[\perl64\bin\perl.exe -E"system 1, 'calc.exe'; syst +em 1, 'notepad.exe'; sleep 100" |] or die $^E; print assignProcessToJobObject( $job, $pid ); sleep 10; print closeHandle( $job ); # kill 21, $pid; sleep 10
You call createJobObject() with a name to get a job handle; assignProcessToJobObject(), with that job handle and the pid for each process you want added to the job; and call closeHandle( $job ) when you want the job to terminate all the processes it includes.
You can also use kill on the process(es) you started and all their children will also die.
However, if you allow your script to end without killing the kids or closing the job handle, you process will block until the kids go away of their own accord.
That could probably be worked up into a module if there was any demand for it.
|
|---|