如果你使用Linux而不是裸机来控制GPIO与传感器通信,你可能会遇到时序乱掉的情况,这是因为传感器的发送时序间隙是微秒级,而Linux作为一个非实时的多任务系统,如果你的进程时间片用完,那么就会被调度出去等待其它进程运行,这样我们就没有办法精确操控时间,如果错过了某段电平,就可能会读出错误的数据甚至整个程序陷入死循环,为了能让一个进程不被打断的运行完,需要设置一下进程的优先级。
API
sched_setscheduler
#include <sched.h>
int sched_setscheduler(pid_t pid, int policy,
const struct sched_param *param);
功能:为进程号为pid的进程设置调度策略
参数:
pid:需要设置优先级的进程的进程号
policy:优先级
SCHED_OTHER the standard round-robin time-sharing policy;
SCHED_BATCH for "batch" style execution of processes; and
SCHED_IDLE for running very low priority background jobs.
For each of the above policies, param->sched_priority must be 0.
SCHED_FIFO a first-in, first-out policy; and
SCHED_RR a round-robin policy.
For each of the above policies, param->sched_priority specifies a scheduling priority for the thread. This is a number in the range returned by calling sched_get_priority_min(2) and sched_get_priority_max(2) with the specified policy. On Linux, these system calls return, respectively, 1 and 99
返回值:
成功:0
失败:-1,errno被设置
例程:
#include <sched.h>
int main(int argc,char *argv[])
{
struct sched_param param;
int maxpri;
maxpri = sched_get_priority_max(SCHED_FIFO);
if(maxpri == -1)
{
perror("sched_get_priority_max() failed");
exit(1);
}
param.sched_priority = maxpri;
if (sched_setscheduler(getpid(), SCHED_FIFO, ¶m) == -1)
{
perror("sched_setscheduler() failed");
exit(1);
}
}