Skip to content

Instantly share code, notes, and snippets.

@zuzzas
Created May 14, 2018 11:25
Show Gist options
  • Save zuzzas/ea31a227dc5bd82ef967ff2460e1e1e6 to your computer and use it in GitHub Desktop.
Save zuzzas/ea31a227dc5bd82ef967ff2460e1e1e6 to your computer and use it in GitHub Desktop.
Revised snippet from prlimit(2)
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/resource.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
int
main(int argc, char *argv[])
{
struct rlimit old, new;
struct rlimit *newp;
char *limit;
int reslimit;
pid_t pid;
if (!(argc == 3 || argc == 5)) {
fprintf(stderr, "Usage: %s <LIMIT_TYPE> <pid> [<new-soft-limit> "
"<new-hard-limit>]\n", argv[0]);
exit(EXIT_FAILURE);
}
limit = argv[1];
pid = atoi(argv[2]); /* PID of target process */
if (strcmp(limit, "NOFILE") == 0)
{
reslimit = RLIMIT_NOFILE;
}
else if (strcmp(limit, "AS") == 0)
{
reslimit = RLIMIT_AS;
}
else if (strcmp(limit, "CORE") == 0)
{
reslimit = RLIMIT_CORE;
}
else if (strcmp(limit, "CPU") == 0)
{
reslimit = RLIMIT_CPU;
}
else if (strcmp(limit, "DATA") == 0)
{
reslimit = RLIMIT_DATA;
}
else if (strcmp(limit, "FSIZE") == 0)
{
reslimit = RLIMIT_FSIZE;
}
else if (strcmp(limit, "LOCKS") == 0)
{
reslimit = RLIMIT_LOCKS;
}
else if (strcmp(limit, "MEMLOCK") == 0)
{
reslimit = RLIMIT_MEMLOCK;
}
else if (strcmp(limit, "MSGQUEUE") == 0)
{
reslimit = RLIMIT_MSGQUEUE;
}
else if (strcmp(limit, "NICE") == 0)
{
reslimit = RLIMIT_NICE;
}
else if (strcmp(limit, "NPROC") == 0)
{
reslimit = RLIMIT_NPROC;
}
else if (strcmp(limit, "RSS") == 0)
{
reslimit = RLIMIT_RSS;
}
else if (strcmp(limit, "RTPRIO") == 0)
{
reslimit = RLIMIT_RTPRIO;
}
else if (strcmp(limit, "RTTIME") == 0)
{
reslimit = RLIMIT_RTTIME;
}
else if (strcmp(limit, "SIGPENDING") == 0)
{
reslimit = RLIMIT_SIGPENDING;
}
else if (strcmp(limit, "STACK") == 0)
{
reslimit = RLIMIT_STACK;
}
newp = NULL;
if (argc == 5) {
new.rlim_cur = atoi(argv[3]);
new.rlim_max = atoi(argv[4]);
newp = &new;
}
if (prlimit(pid, reslimit, newp, &old) == -1)
errExit("prlimit-1");
printf("Previous limits: soft=%lld; hard=%lld\n",
(long long) old.rlim_cur, (long long) old.rlim_max);
if (prlimit(pid, reslimit, NULL, &old) == -1)
errExit("prlimit-2");
printf("New limits: soft=%lld; hard=%lld\n",
(long long) old.rlim_cur, (long long) old.rlim_max);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment