summaryrefslogtreecommitdiffstats
path: root/kdeprint/signal_proc.c
blob: 8ff30e56e9303ad9e5146cf9ec289e072675acfe (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

void commandFromPid(int pid, char *name)
{
	char	buf[256], c;
	FILE	*f;
	int	i;

	name[0] = 0;
	snprintf(buf, 256, "/proc/%d/stat", pid);
	f = fopen(buf, "r");
	if (f == NULL)
		return;
	while ((c = fgetc(f)) != '(') ;
	i = 0;
	while ((c = fgetc(f)) != ')')
		name[i++] = c;
	name[i] = 0;
}

int findPid(const char *progname)
{
	char	name[256];
	DIR	*dir;
	int	pid = -1;
	struct dirent	*ds;

	dir = opendir("/proc");
	if (dir == NULL)
		return -1;
	while ((ds = readdir(dir)) !=NULL )
	{
		pid = -1;
		pid = atoi(ds->d_name);
		if (pid != -1)
		{
			commandFromPid(pid, name);
			if (strcmp(progname, name) == 0)
				return pid;
		}
	}

	return -1;
}

void usage()
{
	printf("usage: signal_proc [ -s signal_number ] [ -l ] -p <progname>\n");
}

int main(int argc, char **argv)
{
	int	pid = -1;
	char	progname[128] = {0};
	int	signal_number = -1, i, list_only = 0;

	for (i = 1; i < argc; i++)
	{
		if (argv[i][0] != '-')
		{
			usage();
			return(-1);
		}
		
		switch (argv[i][1])
		{
			case 'p':
				strncpy(progname, argv[++i], 128);
                                progname[127]='\0';
				break;
			case 's':
				signal_number = atoi(argv[++i]);
				break;
			case 'l':
				list_only = 1;
				break;
			default:
				usage();
				return -1;
		}
	}

	if (progname[0] == 0)
	{
		usage();
		return -1;
	}

	pid = findPid(progname);
	if (pid == -1)
	{
		fprintf(stderr, "no such program: %s\n", progname);
		return -1;
	}
	if (list_only)
	{
		fprintf(stdout, "PID: %d\n", pid);
		return 0;
	}

	if (signal_number != -1)
	{
		int	result;

		result = kill(pid, signal_number);
		if (result == -1)
		{
			if (errno == EPERM)
			{
				char	buf[256];

				fprintf(stderr, "operation not authorized, switching to root\n");
				snprintf(buf, 256, "kill -%d %d", signal_number, pid);
				if (execlp("tdesu", "tdesu", "-c", buf, (void *)0) == -1)
				{
					fprintf(stderr, "operation failed: %s\n", strerror(errno));
					return -1;
				}
			}
			else
			{
				fprintf(stderr, "operation failed (invalid signal or no such process)\n");
				return -1;
			}
		}
	}
	else
	{
		fprintf(stderr, "only signal sending is currently supported\n");
		return -1;
	}
	return 0;
}