ioops: Add mkostemp_or_die() wrapper for mkostemp(3)
[netsniff-ng-new.git] / proc.c
blob76e3c9337f1ed8c92f9019c67f9b2b2a9a6ba234
1 #ifndef _GNU_SOURCE
2 # define _GNU_SOURCE
3 #endif
4 #include <sched.h>
5 #include <sys/wait.h>
6 #include <sys/types.h>
7 #include <sys/resource.h>
8 #include <unistd.h>
9 #include <string.h>
10 #include <errno.h>
12 #include "proc.h"
13 #include "die.h"
15 void cpu_affinity(int cpu)
17 int ret;
18 cpu_set_t cpu_bitmask;
20 CPU_ZERO(&cpu_bitmask);
21 CPU_SET(cpu, &cpu_bitmask);
23 ret = sched_setaffinity(getpid(), sizeof(cpu_bitmask),
24 &cpu_bitmask);
25 if (ret)
26 panic("Can't set this cpu affinity!\n");
29 int set_proc_prio(int priority)
31 int ret = setpriority(PRIO_PROCESS, getpid(), priority);
32 if (ret)
33 panic("Can't set nice val to %i!\n", priority);
35 return 0;
38 int set_sched_status(int policy, int priority)
40 int ret, min_prio, max_prio;
41 struct sched_param sp;
43 max_prio = sched_get_priority_max(policy);
44 min_prio = sched_get_priority_min(policy);
46 if (max_prio == -1 || min_prio == -1)
47 printf("Cannot determine scheduler prio limits!\n");
48 else if (priority < min_prio)
49 priority = min_prio;
50 else if (priority > max_prio)
51 priority = max_prio;
53 memset(&sp, 0, sizeof(sp));
54 sp.sched_priority = priority;
56 ret = sched_setscheduler(getpid(), policy, &sp);
57 if (ret) {
58 printf("Cannot set scheduler policy!\n");
59 return -EINVAL;
62 ret = sched_setparam(getpid(), &sp);
63 if (ret) {
64 printf("Cannot set scheduler prio!\n");
65 return -EINVAL;
68 return 0;
71 ssize_t proc_get_cmdline(unsigned int pid, char *cmdline, size_t len)
73 ssize_t ret;
74 char path[1024];
76 snprintf(path, sizeof(path), "/proc/%u/exe", pid);
77 ret = readlink(path, cmdline, len - 1);
78 if (ret < 0)
79 cmdline[0] = '\0';
80 else
81 cmdline[ret] = '\0';
83 return ret;
86 int proc_exec(const char *proc, char *const argv[])
88 int status;
89 pid_t pid;
91 pid = fork();
92 if (pid < 0) {
93 perror("fork");
94 return -1;
95 } else if (pid == 0) {
96 if (execvp(proc, argv) < 0)
97 fprintf(stderr, "Failed to exec: %s\n", proc);
98 _exit(1);
101 if (waitpid(pid, &status, 0) < 0) {
102 perror("waitpid");
103 return -2;
106 if (!WIFEXITED(status))
107 return -WEXITSTATUS(status);
109 return 0;