There may be a way to achieve a "safe kill" on windows. There is an API OpenProcess that allows (with appropriate privalege) one process to obtain a system handle to another running process.
In my experiments, if one process (the killer) obtains a handle to another process (the killee), whilst it does not stop the latter dieing or being killed, it seems to prevent the process id for that process being re-used before the killer relingishes it's grip on the system handle returned by the API.
You'll understand this is a bit vague. Verifying that this is true is very difficult. My attempt was:
I started a copy of perl, found out it's pid.
Ran the following script to obtain and hold onto a system handle to that pid.
#! perl -slw use strict; use Win32::API::Prototype; use constant PROCESS_TERMINATE => 1; ApiLink( 'Kernel32', 'HANDLE OpenProcess( DWORD dwDesiredAccess, BOOL bInheritHandle, D +WORD dwProcessId )' ) or die $^E; ApiLink( 'Kernel32', 'BOOL TerminateProcess( HANDLE hProcess, UINT uExitCode )' ) or die $^E; if( my $hProc = OpenProcess( PROCESS_TERMINATE, 0, $ARGV[ 0 ] ) ) { print "Got handle to process; Can you kill it?"; die 'Drat' if <STDIN> =~ m[^y]i; print "I'll try"; print TerminateProcess( $hProc, -1 ) ? 'It sleeps with da fishies!' : 'Double drat!'; } else { print "OpenProcess failed: $^E"; }
I then killed the first copy of perl and left the second holding the handle.
I started a third copy of perl that constantly spawned new processes (I created a tiny dummy executable int main () { return 0; } for speed), that recorded and yelled if the process id of the first process had, was reused:
do{ my $pid = open my $in, "p:/test/dummy.exe |" or die $!; $pid{ $pid }++; printf "\r%7d : $pid ", scalar keys %pid; print " Reused\n\n" if $pid == 65992 ## The first pid } for 1 .. 1_000_000;
I allowed this to run whilst I watch a movie. The pid was never re-used. I then killed the second process that was holding the system handle to the defunct first process. It's pid was then re-used twice within less than a minute.
14281 : 65992 Reused 19112 : 65992 Reused 19112 : 60132 Terminating on signal SIGINT(2)
Far from definitive proof, and if it is true, it isn't the complete picture as there still remains the task of ensuring that the pid to which you obtained the handle is the same process as it was when you obtained the PID in the first place...
In reply to Re: atomic operations
by BrowserUk
in thread atomic operations
by kcella
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |