trafgen: Added option to pass macro/define for C preprocessor
[netsniff-ng.git] / proc.c
blobb0c577cd1612768fb801b8c32aa75e3c79e5126a
1 #define _GNU_SOURCE
2 #include <sched.h>
3 #include <sys/wait.h>
4 #include <sys/types.h>
5 #include <sys/resource.h>
6 #include <unistd.h>
7 #include <string.h>
8 #include <errno.h>
10 #include "proc.h"
11 #include "die.h"
13 void cpu_affinity(int cpu)
15 int ret;
16 cpu_set_t cpu_bitmask;
18 CPU_ZERO(&cpu_bitmask);
19 CPU_SET(cpu, &cpu_bitmask);
21 ret = sched_setaffinity(getpid(), sizeof(cpu_bitmask),
22 &cpu_bitmask);
23 if (ret)
24 panic("Can't set this cpu affinity!\n");
27 int set_proc_prio(int priority)
29 int ret = setpriority(PRIO_PROCESS, getpid(), priority);
30 if (ret)
31 panic("Can't set nice val to %i!\n", priority);
33 return 0;
36 int set_sched_status(int policy, int priority)
38 int ret, min_prio, max_prio;
39 struct sched_param sp;
41 max_prio = sched_get_priority_max(policy);
42 min_prio = sched_get_priority_min(policy);
44 if (max_prio == -1 || min_prio == -1)
45 printf("Cannot determine scheduler prio limits!\n");
46 else if (priority < min_prio)
47 priority = min_prio;
48 else if (priority > max_prio)
49 priority = max_prio;
51 memset(&sp, 0, sizeof(sp));
52 sp.sched_priority = priority;
54 ret = sched_setscheduler(getpid(), policy, &sp);
55 if (ret) {
56 printf("Cannot set scheduler policy!\n");
57 return -EINVAL;
60 ret = sched_setparam(getpid(), &sp);
61 if (ret) {
62 printf("Cannot set scheduler prio!\n");
63 return -EINVAL;
66 return 0;
69 ssize_t proc_get_cmdline(unsigned int pid, char *cmdline, size_t len)
71 ssize_t ret;
72 char path[1024];
74 snprintf(path, sizeof(path), "/proc/%u/exe", pid);
75 ret = readlink(path, cmdline, len - 1);
76 if (ret < 0)
77 cmdline[0] = '\0';
78 else
79 cmdline[ret] = '\0';
81 return ret;
84 int proc_exec(const char *proc, char *const argv[])
86 int status;
87 pid_t pid;
89 pid = fork();
90 if (pid < 0) {
91 perror("fork");
92 return -1;
93 } else if (pid == 0) {
94 if (execvp(proc, argv) < 0)
95 fprintf(stderr, "Failed to exec: %s\n", proc);
96 _exit(1);
99 if (waitpid(pid, &status, 0) < 0) {
100 perror("waitpid");
101 return -2;
104 if (!WIFEXITED(status))
105 return -WEXITSTATUS(status);
107 return 0;