Kill not killing forked process after sleep in perl

Viewed 54

there. I'm trying to do the following:

  • Fork.
  • Launched a desktop application.
  • Wait for 2 secs.
  • Kill the desktop application.

This is what I have:

#!/usr/bin/perl

use utf8;
use strict;
use warnings;

my @cmd = ('calc.exe');

my $pid = fork();
die "fork() failed: $!" unless defined $pid;

if ($pid) {
    system @cmd;    
}

sleep 2;
kill 'TERM' => $pid;

The application is launched correctly but it doesn't kill after the two seconds. I know I missing something, I hope someone can point me to the right direction. Right know I'm testing this code in windows 7 SP1 with perl 5.32.1 bundled with msys2.

1 Answers

You have up to four processes here: Parent, child, shell, app. You're killing the child, not the app. Use exec instead of system and use the exec BLOCK LIST form to avoid a shell.

Even then, that may not work. It depends on how well msys2 emulates fork and exec. A better solution might be to use the Windows system calls (CreateProcess and ExitProcess) instead of emulations of unix system calls.

Related