Files
dragonpilot/selfdrive/common/util.c

60 lines
1.0 KiB
C
Raw Normal View History

2017-05-11 12:41:17 -07:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
2018-07-12 18:52:06 -07:00
#include <unistd.h>
2017-05-11 12:41:17 -07:00
2017-09-30 03:07:27 -07:00
#ifdef __linux__
#include <sys/prctl.h>
2018-07-12 18:52:06 -07:00
#include <sys/syscall.h>
#include <sched.h>
2017-09-30 03:07:27 -07:00
#endif
2017-05-11 12:41:17 -07:00
void* read_file(const char* path, size_t* out_len) {
FILE* f = fopen(path, "r");
if (!f) {
return NULL;
}
fseek(f, 0, SEEK_END);
long f_len = ftell(f);
rewind(f);
2017-07-28 01:24:39 -07:00
char* buf = calloc(f_len + 1, 1);
2017-05-11 12:41:17 -07:00
assert(buf);
2017-07-28 01:24:39 -07:00
2017-05-11 12:41:17 -07:00
size_t num_read = fread(buf, f_len, 1, f);
fclose(f);
2017-07-28 01:24:39 -07:00
if (num_read != 1) {
2019-05-16 13:20:29 -07:00
free(buf);
2017-07-28 01:24:39 -07:00
return NULL;
}
2017-05-11 12:41:17 -07:00
if (out_len) {
*out_len = f_len + 1;
}
return buf;
}
2017-09-30 03:07:27 -07:00
void set_thread_name(const char* name) {
#ifdef __linux__
// pthread_setname_np is dumb (fails instead of truncates)
prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
#endif
}
2018-07-12 18:52:06 -07:00
int set_realtime_priority(int level) {
#ifdef __linux__
long tid = syscall(SYS_gettid);
// should match python using chrt
struct sched_param sa;
memset(&sa, 0, sizeof(sa));
sa.sched_priority = level;
return sched_setscheduler(tid, SCHED_FIFO, &sa);
#endif
}