File: sched.c

package info (click to toggle)
trx 0.5-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 152 kB
  • sloc: ansic: 770; makefile: 32
file content (80 lines) | stat: -rw-r--r-- 1,620 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * Copyright (C) 2020 Mark Hills <mark@xwax.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 2 for more details.
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

#include <sched.h>
#include <stdio.h>
#include <unistd.h>

#include "sched.h"

#define REALTIME_PRIORITY 80

int go_realtime(void)
{
	int max_pri;
	struct sched_param sp;

	if (sched_getparam(0, &sp)) {
		perror("sched_getparam");
		return -1;
	}

	max_pri = sched_get_priority_max(SCHED_FIFO);
	sp.sched_priority = REALTIME_PRIORITY;

	if (sp.sched_priority > max_pri) {
		fprintf(stderr, "Invalid priority (maximum %d)\n", max_pri);
		return -1;
	}

	if (sched_setscheduler(0, SCHED_FIFO, &sp)) {
		perror("sched_setscheduler");
		return -1;
	}

	return 0;
}

int go_daemon(const char *pid_file)
{
	FILE *f;

	if (daemon(0, 0) == -1) {
		perror("daemon");
		return -1;
	}

	if (!pid_file)
		return 0;

	f = fopen(pid_file, "w");
	if (!f) {
		perror("fopen");
		return -1;
	}

	fprintf(f, "%d", getpid());

	if (fclose(f) != 0) {
		perror("fclose");
		return -1;
	}

	return 0;
}