So what we want to do is locate the process and kill()
it. It's not so hard. It's just very long because the executable isn't minecraft
, it's java
, so we look for the .jar
file.
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
void kill_minecraft()
{
char buf[8192];
DIR *dir = opendir("/proc");
struct dirent *dirent;
while ((dirent = readdir(dir)))
{
pid_t pid = atol(dirent->d_name);
if (pid > 0)
{
sprintf(buf, "/proc/%s/cmdline", dirent->d_name);
FILE *in = fopen(buf, "r");
if (in)
{
size_t nmem = fread(buf, 1, 8192, in);
fclose(in);
buf[8192] = 0;
// Recognize minecraft's jar in the command line
if (nmem > 0 && (char *ptr = (char*)memmem(buf, "minecraft/versions/", nmem)))
{
char *p1 = (char*)strstr(ptr, ":");
char *p2 = (char*)strstr(ptr, ".jar");
if (p2 && (!p1 || p1 > p2))
{
// Match! Goodbye!
kill(pid, 9);
}
}
fclose(in);
}
}
}
closedir(dir);
}
Whew. Let's break this down. This function iterates over all running processes and reads in its command line. Once having done so, it checks the command line for minecraft's pattern; that is having a command line argument of minecraft/versions/something/something.jar. In java, the jar arguments are glommed together separated by :
characters, so it handles that. On getting a match, it calls kill
.
Scheduling this function is left as an exercise for the reader. See time()
and sleep()
functions. As for running it, the lazy way is to stick a call to it into /etc/rc.local
.
You can do this with pkill -f
in a loop, but that regex is hard to write and I don't want to figure it out.