Last active
December 30, 2015 06:09
-
-
Save flaviocdc/7787571 to your computer and use it in GitHub Desktop.
Trabalho 5 de SO2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <dirent.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <sys/stat.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#include <unistd.h> | |
#include <signal.h> | |
#define TAM_LINHA 256 | |
static bool done = false; | |
static FILE* logFile = NULL; | |
void catch_sigterm(int param) { | |
fprintf(logFile, "Terminating...\n"); | |
done = true; | |
} | |
int detect_zombies(void) { | |
DIR* procDir = opendir("/proc"); | |
struct dirent* cur = NULL; | |
while ((cur = readdir(procDir)) != NULL) { | |
/* monta no do diretorio */ | |
char* buf = (char*) calloc(strlen("/proc/") + strlen(cur->d_name) + 1, sizeof(char)); | |
strcat(buf, "/proc/"); | |
strcat(buf, cur->d_name); | |
/* verifica se eh diretorio */ | |
struct stat pidDir; | |
if (stat(buf, &pidDir) == -1) { | |
perror("stat"); | |
return 1; | |
} | |
free(buf); | |
if (!S_ISDIR(pidDir.st_mode)) { | |
continue; | |
} | |
/* converte o nome do diretorio para pid_t */ | |
pid_t pid = strtol(cur->d_name, NULL, 10); | |
if (pid == 0 || errno == ERANGE) { | |
continue; | |
} | |
/* ler o arquivo status e ver se eh zombie */ | |
buf = (char *) calloc(strlen("/proc/") + strlen(cur->d_name) + strlen("/status"), sizeof(char)); | |
strcat(buf, "/proc/"); | |
strcat(buf, cur->d_name); | |
strcat(buf, "/status"); | |
FILE* statusFile = fopen(buf, "r"); | |
if (statusFile == NULL) { | |
perror("fopen"); | |
return 1; | |
} | |
char linha[TAM_LINHA]; | |
bool isZombie = false; | |
pid_t ppid = 0; | |
char name[TAM_LINHA]; | |
while (fgets(linha, TAM_LINHA, statusFile) != NULL) { | |
if (strstr(linha, "Z (zombie)") != NULL) { | |
isZombie = true; | |
} | |
if (strstr(linha, "PPid") != NULL) { | |
sscanf(linha, "PPid: %d", &ppid); | |
} | |
if (strstr(linha, "Name") != NULL) { | |
sscanf(linha, "Name: %s", name); | |
} | |
} | |
fclose(statusFile); | |
if (isZombie) { | |
fprintf (logFile, "%d \t %d \t %s\n", pid, ppid, name); | |
} | |
} | |
closedir(procDir); | |
return 0; | |
} | |
int main(void) { | |
signal(SIGTERM, catch_sigterm); | |
logFile = fopen("./daemon.log", "w+"); | |
fprintf(logFile, "PID \t PPID \t Programa\n"); | |
while (!done) { | |
fprintf(logFile, "=========================\n"); | |
detect_zombies(); | |
fprintf(logFile, "=========================\n"); | |
sleep(3); | |
fflush(logFile); | |
} | |
fclose(logFile); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment