Created
November 4, 2015 15:06
-
-
Save masami256/cc8cc3aef32b1e5dca3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sched.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#define SCHED_LIFO 7 | |
#define GET_CURRENT_POLICY 9999 | |
#define error_exit(msg) \ | |
do { \ | |
perror(msg); \ | |
exit(-1); \ | |
} while(0); | |
static void usage(char *name) | |
{ | |
fprintf(stderr, "usage: %s [orflg] -- command line to run at chaild process\n", name); | |
exit(-1); | |
} | |
static int get_policy(int argc, char **argv) | |
{ | |
int opt, policy; | |
while ((opt = getopt(argc, argv, "orflg")) != -1) { | |
switch (opt) { | |
case 'o': | |
policy = SCHED_OTHER; | |
break; | |
case 'r': | |
policy = SCHED_RR; | |
break; | |
case 'f': | |
policy = SCHED_FIFO; | |
break; | |
case 'l': | |
policy = SCHED_LIFO; | |
break; | |
case 'g': | |
policy = GET_CURRENT_POLICY; | |
break; | |
default: | |
usage(argv[0]); | |
} | |
} | |
return policy; | |
} | |
static int get_current_scheduler(pid_t pid) | |
{ | |
int ret = sched_getscheduler(pid); | |
if (ret < 0) | |
error_exit("sched_getscheduler"); | |
return ret; | |
} | |
static void show_current_policy(void) | |
{ | |
printf("current policy is %d\n", get_current_scheduler(getpid())); | |
exit(0); | |
} | |
int main(int argc, char **argv) | |
{ | |
int policy = get_policy(argc, argv); | |
if (policy == GET_CURRENT_POLICY) | |
show_current_policy(); | |
pid_t pid; | |
pid = fork(); | |
if (!pid) { // child | |
pid_t my_pid = getpid(); | |
struct sched_param param = { 0 }; | |
if (policy != SCHED_OTHER) | |
param.sched_priority = policy; | |
printf("current schedulering policy is %d\n", get_current_scheduler(my_pid)); | |
int ret = sched_setscheduler(my_pid, policy, ¶m); | |
if (ret) | |
error_exit("sched_setscheduler"); | |
printf("schedulering policy set to %d\n", get_current_scheduler(my_pid)); | |
extern int optind; | |
char **cmdline = argv + optind; | |
ret = execve(cmdline[0], cmdline, NULL); | |
if (ret) | |
error_exit("execve"); | |
} else if (pid > 0) { // parent | |
waitpid(pid, NULL, 0); | |
} else { | |
error_exit("fork"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment