1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/perl
my @pids;
my $current;
sub refresh{
	@pids = grep(/Window 0x/, split(/\n/, `xlsclients -l`));
	for(my $x = 0; $x < $#pids+1; $x++){
		$pids[$x] =~ s/Window (0x[\da-f]+):/$1/i;
		`xprop -id $pids[$x]`=~m/PID.+ = (\d+)/i;
		$pids[$x] = $1;
	}
	`xprop -root` =~ m/_NET_ACTIVE_WINDOW.+ window id # (0x[\da-f]+)/i;
	$current = $1;
	`xprop -id $current`=~m/PID.+ = (\d+)/i;
	$current = $1;
}

sub fast_refresh{
	`xprop -root` =~ m/_NET_ACTIVE_WINDOW.+ window id # (0x[\da-f]+)/i;
	$current = $1;
	`xprop -id $current`=~m/PID.+ = (\d+)/i;
	$current = $1;
}

sub set_priority{
	my $pid = $_[0];
	if($_[1] == 0){ #high priority
		`ionice -c2 -p $pid`; #set IO priority to "best-effort"
		my $curnice = `ps -o nice -p $pid | grep -Po "[-\d]+"`;
		$curnice = 0 - $curnice;
		`renice -n $curnice $pid`; #change nice to 0
	} else {
		`ionice -c3 -p $pid`; #set IO priority to "idle"
		my $curnice = `ps -o nice -p $pid | grep -Po "[-\d]+"`;
		$curnice = 5 - $curnice;
		`renice -n $curnice $pid`; #change nice to 5
	}
}

refresh();

print join("\n", @pids);
print "\n\n$current";

for($x = 0; $x < $#pids+1; $x++){
	if($pids[$x] == $current){
		#nice and ionice up
		set_priority($pids[$x], 0);
	} else {
		#nice and ionice down
		set_priority($pids[$x], 1);
	}
}
my $count = 0;
while(1){
	$cout++;
	sleep 2; #update every 2 seconds
	
	if($cout%20 == 0){
		refresh();
		for($x = 0; $x < $#pids+1; $x++){
			if($pids[$x] == $current){
				#nice and ionice up
				set_priority($pids[$x], 0);
			} else {
				#nice and ionice down
				set_priority($pids[$x], 1);
			}
		}
	} else {
		my $old = $current;
		fast_refresh();
		if($old != $current){
			#nice and ionce down $old
			set_priority($old, 1);
			#nice and ionce up $current
			set_priority($current, 0);
		}
	}
	print "\n\n$current";
}