
 
Startseite




Kontakt

Impressum |  Knowledge base - C

C | | Semkill.c | | Für das Entfernen von verwaisten Semaphoren :
C-Code zum Download : semkill.c
Source :
#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <dirent.h>
// #define DEBUG
void usage(const char *progname) { fprintf(stdout, "nusage: %s <semid>nn", progname); }
int main(int argc, char **argv) { int semid, pid; int count;
if ( argc != 2 ) { usage(argv[0]); exit(EXIT_FAILURE); }
#ifdef DEBUG fprintf(stdout, "argv[1] = >>%s<<n", argv[1]); #endif
semid = atoi(argv[1]);
#ifdef DEBUG fprintf(stdout, "argv[1] nach atoi: %dn", semid); #endif
if ( semid < 1 ) { fprintf(stderr, "Ungültige semid: %dn", semid); exit(EXIT_FAILURE); }
pid = semctl(semid, 0, GETPID, NULL); if ( pid < 0 ) { perror("semctl"); exit(EXIT_FAILURE);
count = semctl(semid, 0, GETNCNT, NULL); if ( count < 0 ) { perror("semctl"); exit(EXIT_FAILURE); }
if ( count == 0 ) { // Kein Prozess mehr vorhanden? Semaphore löschen... if ( pid == 0 ) { int rc = semctl(semid, 0, IPC_RMID, NULL); if ( rc < 0 ) { perror("semctl"); exit(EXIT_FAILURE); } fprintf(stdout, "Semaphore %d gelöscht.n", semid); } else // PID noch gesetzt { DIR *proc_pid = NULL; char pid_pfad[48];
// Pfad zusammenbauen snprintf(pid_pfad, sizeof(pid_pfad), "/proc/%d", pid);
// Ist der Besitzer-Prozess noch am Leben? proc_pid = opendir(pid_pfad); if ( proc_pid == NULL ) { // Prozess nicht mehr vorhanden if ( errno == ENOENT ) { // Semaphore löschen int rc = semctl(semid, 0, IPC_RMID, NULL); if ( rc < 0 ) { perror("semctl"); exit(EXIT_FAILURE); } fprintf(stdout, "PID %d has tits up, Semaphore %d gelöscht.n", pid, semid); } } else // Prozess lebt noch { closedir(proc_pid); #ifdef DEBUG fprintf(stdout, "Semaphore in Benutzung: PID = %d; Count = %dn", pid, count); #endif } } } else // count > 0 { #ifdef DEBUG fprintf(stdout, "Semaphore in Benutzung: PID = %d; Count = %dn", pid, count); #endif }
exit(EXIT_SUCCESS); } | |

Knowledge base wurde zuletzt bearbeitet am 12.07.13 durch Frank
| |