#include <ctype.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int should_be_daemon = 0;
void set_daemonize(int set) {
should_be_daemon = set;
}
int should_daemonize() {
return should_be_daemon;
}
void kill_running_joymap() {
char *home = getenv("HOME");
char pid_file[1024];
char exe_link[1024];
char exe_file[1024];
char digits[10];
FILE *f;
int i, count;
int pid = 0;
if (home == NULL) {
return;
}
sprintf(pid_file, "%s/.joymap.pid", home);
f = fopen(pid_file, "r");
if (f != NULL) {
count = fread(digits, 1, 10, f);
fclose(f);
for (i=0; i<count && isdigit(digits[i]); i++) {
pid = pid * 10;
pid = pid + digits[i] - '0';
}
}
if (pid == 0) {
return;
}
sprintf(exe_link, "/proc/%d/exe", pid);
if ((count = readlink(exe_link, exe_file, 1023)) < 0) {
return;
}
if (strncmp(exe_file + count - 7, "loadmap", 7) != 0) {
return;
}
kill(pid, SIGTERM);
sleep(1);
}
void write_pid_file() {
char *home = getenv("HOME");
char pid_file[1024];
FILE *f;
if (home != NULL) {
sprintf(pid_file, "%s/.joymap.pid", home);
f = fopen(pid_file, "w");
if (f != NULL) {
fprintf(f, "%d", getpid());
fclose(f);
}
}
}
void daemonize() {
if (fork() == 0) {
write_pid_file();
} else {
sleep(1);
exit(0);
}
}