2021-05-09 13:15:17 +08:00
|
|
|
#include "selfdrive/common/util.h"
|
|
|
|
|
2020-10-18 03:40:01 +08:00
|
|
|
#include <errno.h>
|
|
|
|
|
2021-05-09 13:15:17 +08:00
|
|
|
#include <sstream>
|
2021-03-09 11:17:46 +08:00
|
|
|
|
2020-01-18 03:01:02 +08:00
|
|
|
#ifdef __linux__
|
|
|
|
#include <sys/prctl.h>
|
|
|
|
#include <sys/syscall.h>
|
2020-10-18 03:40:01 +08:00
|
|
|
#ifndef __USE_GNU
|
2020-06-06 05:09:41 +08:00
|
|
|
#define __USE_GNU
|
2020-01-18 03:01:02 +08:00
|
|
|
#endif
|
2020-10-18 03:40:01 +08:00
|
|
|
#include <sched.h>
|
2021-05-09 13:15:17 +08:00
|
|
|
#endif // __linux__
|
2020-01-18 03:01:02 +08: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
|
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
#else
|
|
|
|
return -1;
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
2020-06-06 05:09:41 +08:00
|
|
|
int set_core_affinity(int core) {
|
2020-09-02 23:52:41 +08:00
|
|
|
#ifdef __linux__
|
2020-06-06 05:09:41 +08:00
|
|
|
long tid = syscall(SYS_gettid);
|
|
|
|
cpu_set_t rt_cpu;
|
|
|
|
|
|
|
|
CPU_ZERO(&rt_cpu);
|
|
|
|
CPU_SET(core, &rt_cpu);
|
|
|
|
return sched_setaffinity(tid, sizeof(rt_cpu), &rt_cpu);
|
|
|
|
#else
|
|
|
|
return -1;
|
|
|
|
#endif
|
|
|
|
}
|
2021-04-14 02:43:43 +08:00
|
|
|
|
|
|
|
namespace util {
|
|
|
|
|
|
|
|
std::string read_file(const std::string& fn) {
|
|
|
|
std::ifstream ifs(fn, std::ios::binary | std::ios::ate);
|
|
|
|
if (ifs) {
|
|
|
|
std::ifstream::pos_type pos = ifs.tellg();
|
2021-04-14 04:56:08 +08:00
|
|
|
if (pos != std::ios::beg) {
|
|
|
|
std::string result;
|
|
|
|
result.resize(pos);
|
|
|
|
ifs.seekg(0, std::ios::beg);
|
|
|
|
ifs.read(result.data(), pos);
|
|
|
|
if (ifs) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
2021-04-14 02:43:43 +08:00
|
|
|
}
|
2021-04-14 05:40:40 +08:00
|
|
|
ifs.close();
|
|
|
|
|
|
|
|
// fallback for files created on read, e.g. procfs
|
|
|
|
std::ifstream f(fn);
|
|
|
|
std::stringstream buffer;
|
|
|
|
buffer << f.rdbuf();
|
|
|
|
return buffer.str();
|
2021-04-14 02:43:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int write_file(const char* path, const void* data, size_t size, int flags, mode_t mode) {
|
|
|
|
int fd = open(path, flags, mode);
|
|
|
|
if (fd == -1) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
ssize_t n = write(fd, data, size);
|
|
|
|
close(fd);
|
|
|
|
return (n >= 0 && (size_t)n == size) ? 0 : -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace util
|