Skip to content

Instantly share code, notes, and snippets.

@otya128
Last active August 29, 2015 13:57
Show Gist options
  • Save otya128/9895912 to your computer and use it in GitHub Desktop.
Save otya128/9895912 to your computer and use it in GitHub Desktop.
watch

Watch

プロセスを監視する<●><●>

build

gcc watch.c -o watch

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
int main(int argc, char **argv){
if(argc <= 1)
{
printf("usage:%s WatchTarget\n",argv[0]);
return 1;
}
pid_t pid;
pid = fork();
#ifdef _DEBUG
printf("DEBUG%d\t%d\t%sargv[1]\n",pid,getpid(),argv[1]);
#endif
if(pid == 0)
{
execvp(argv[1], (char**)(&argv[1]));
}
else
{
if(pid != -1)
{
int count = 0;
struct rlimit rlim;
struct rusage usage;
rlim.rlim_cur = 4194304;
rlim.rlim_max = 4194304;
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = 1;
rlim.rlim_max = 1;
setrlimit(RLIMIT_NOFILE, &rlim);
rlim.rlim_cur = 4000000;
rlim.rlim_max = 4000000;
setrlimit(RLIMIT_CPU, &rlim);
while(1)
{
int r = waitpid(pid, NULL, WNOHANG);//kill(pid,0);
getrusage(RUSAGE_SELF, &usage);
if(usage.ru_maxrss >= 4194304)
{
kill(pid, SIGINT);
break;
}
if(r == pid || r == -1)
{
break;
}
if(count >= 4000000)
{
kill(pid, SIGINT);
break;
}
count += 10000;
usleep(10000);//0.001秒毎に監視
}
wait(NULL);
}
//int status = 0;
//wait(&status);
return 0;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment