Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <memory.h>
- #include <dirent.h>
- #include <string.h>
- #include <signal.h>
- #include <ctype.h>
- int exit_signal;
- char *killing_name;
- void fail(char *str)
- {
- free(killing_name);
- fprintf(stderr, "killall: process is ended: %s\n", str);
- exit(EXIT_FAILURE);
- }
- void cant_kill(char *str, int pid)
- {
- fprintf(stderr, "Can't kill process %s with pid = %d\n", str, pid);
- }
- void *safe_malloc(int size)
- {
- void* res = malloc(size);
- if (res == NULL)
- fail("Out of memory");
- return res;
- }
- void *safe_realloc(void* adress, int new_size)
- {
- void* temp = realloc(adress, new_size);
- if (temp == NULL)
- fail("Out of memory");
- return temp;
- }
- void parser(int argc, char **argv)
- {
- if (argc != 3)
- fail("Wrong params");
- int i = 0;
- char *end;
- exit_signal = strtoul(argv[1], &end, 10);
- if (*end == 0)
- fail("Wrong params");
- sprintf(killing_name, "(%s)", argv[2]);
- }
- int max(int a, int b)
- {
- return a > b? a: b;
- }
- char is_process(char str[256])
- {
- int i = 0;
- while (i != 256 && str[i] != '\0')
- {
- if (!isdigit(str[i]))
- return 0;
- i++;
- }
- return 1;
- }
- char *get_stat(char* process_name)
- {
- char *result = safe_malloc(strlen(process_name) + 15);
- sprintf(result, "/proc/%s/stat", process_name);
- return result;
- }
- void killall(int code, char* name)
- {
- DIR *dir = opendir("/proc");
- FILE* file;
- struct dirent *curr;
- char *file_name, *buf;
- char process_name[256];
- int pid;
- char result_of_killing;
- while ((curr = readdir(dir)) != NULL)
- {
- if (is_process(curr->d_name))
- {
- file_name = get_stat(curr->d_name);
- //getting pid and name
- file = fopen(file_name, "r");
- if (file != NULL)
- {
- fscanf(file, "%d\n%s\n", &pid, process_name);
- if (strcmp(process_name, killing_name) == 0)
- {
- result_of_killing = kill(pid, exit_signal);
- if (result_of_killing == 0)
- cant_kill(process_name, pid);
- }
- fclose(file);
- }
- }
- }
- }
- void allocating_memory(int argc, char **argv)
- {
- int i, j, size = 0;
- for (i = 1; i < argc; i++)
- {
- j = 0;
- while (argv[i][j] != '\0')
- j++;
- size = max(size, j);
- }
- killing_name = safe_malloc(size * sizeof(char) + 3);// +'(' + ')' + '\0'
- }
- int main(int argc, char **argv)
- {
- allocating_memory(argc, argv);
- parser(argc, argv);
- killall(exit_signal, killing_name);
- free(killing_name);
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment