in reply to Killing processes

Hello deyaneria,

The logic of the do ... while loop is wrong. If the user answers “N”, the script still asks for a PID and then attempts to kill it! Also, you shouldn’t mix system with backticks (they are two ways of doing the same thing). Try something like this (untested):

sub kill_process { print "Kill processes for the user? (y or n)?\n"; my $ans = <>; while ($ans =~ /^Y/i) { print "Enter pid to kill:\n"; my $pid = <>; chomp $pid; if (is_valid($pid)) { `kill $pid`; print "Process $pid killed\n"; } else { print "Process $pid is invalid\n"; } print "Kill more processes for the user? (y or n)?\n"; my $ans = <>; } }

(You will need to implement sub is_valid too.)

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Killing processes
by deyaneria (Acolyte) on Mar 20, 2015 at 16:17 UTC
    I see what your saying but since I have previously listed all the processes running for the user, you are already pulling the pid from a valid list so I don't see the need for the is_valid, I know the code for that wasn't listed but it was a previous part of the code. So do I still need validate it? I guess i might need to in case of typo?
      I guess i might need to in case of typo?

      Yes, exactly. But since you already have an array of valid PIDs, it might be a better idea to change the logic of the subroutine and present each PID to the user instead. Like this:

      my @pids = ...; ... kill_processes(\@pids); ... sub kill_processes { my $pids = shift; for my $pid (@$pids) { print "Kill process $pid? ([y]es, [n]o, [q]uit)?\n"; my $ans = <>; last if $ans =~ /^Q/i; next unless $ans =~ /^Y/i; `kill $pid`; print "Process $pid killed\n"; } }

      Using this approach there is no possibility of a user-input typo. And as a bonus, the loop logic is simpler.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Thanks you guys are amazing...I love the fact I can ask here when my teacher can't seem to understand the issue:)