1/*
2 * Copyright 2007, Intel Corporation
3 *
4 * This file is part of PowerTOP
5 *
6 * This program file is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program in a file named COPYING; if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301 USA
20 *
21 * Authors:
22 * 	Arjan van de Ven <arjan@linux.intel.com>
23 */
24
25#include <unistd.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <stdint.h>
30#include <sys/types.h>
31#include <dirent.h>
32#include <sys/types.h>
33#include <signal.h>
34
35#include "powertop.h"
36
37char process_to_kill[1024];
38
39static void fancy_kill(void)
40{
41	FILE *file;
42	char line[2048];
43	char *tokill;
44	int pid = 0;
45	tokill = &process_to_kill[1];
46
47	file = popen(" ps -A -o pid,command", "r");
48	if (!file)
49		return;
50	while (!feof(file)) {
51		memset(line, 0, 2048);
52		if (fgets(line, 2047, file)==NULL)
53			break;
54		if (!strstr(line, tokill))
55			continue;
56		pid = strtoul(line, NULL, 10);
57
58	}
59	pclose(file);
60	if (pid<2)
61		return;
62	kill(pid, SIGTERM);
63}
64
65void do_kill(void)
66{
67	char line[2048];
68
69	if (process_to_kill[0] == '-') {
70		fancy_kill();
71	} else {
72		sprintf(line, "killall %s &> /dev/null", process_to_kill);
73		system(line);
74	}
75}
76
77void suggest_process_death(char *process_match, char *tokill, struct line *slines, int linecount, double minwakeups, char *comment, int weight)
78{
79	int i;
80
81	for (i = 0; i < linecount; i++) {
82		if (slines[i].string && strstr(slines[i].string, process_match)) {
83			char hotkey_string[300];
84			sprintf(hotkey_string, _(" K - kill %s "), tokill);
85			strcpy(process_to_kill, tokill);
86			if (minwakeups < slines[i].count)
87				add_suggestion(comment, weight, 'K' , hotkey_string, do_kill);
88			break;
89		}
90	}
91	fflush(stdout);
92}
93