Last active
December 22, 2015 13:09
-
-
Save maliubiao/6477087 to your computer and use it in GitHub Desktop.
a little timer.
"usage: timer [-f s] [-r s] -c shell-command\n\ -f s , timer expires once in s microseconds\n\ -r s, timer expires every s microseconds\n\ -c shell-command, execute this command via sh -c\n";
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 <stdio.h> | |
#include <signal.h> | |
#include <sys/time.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <string.h> | |
#define CMDLEN 1024 | |
char command[CMDLEN]; | |
char usage[] = "usage: timer [-f s] [-r s] -c shell-command\n\ | |
-f s , timer expires once in s microseconds\n\ | |
-r s, timer expires every s microseconds\n\ | |
-c shell-command, execute this command via sh -c\n"; | |
char nocmdmsg[] = "no command specified."; | |
int got_alarm = 0; | |
static void signal_handler(int sig) | |
{ | |
got_alarm = 1; | |
} | |
int main(int argc, char **argv) | |
{ | |
extern char *optarg; | |
struct sigaction sa; | |
struct itimerval new; | |
struct itimerval old; | |
int c = 0; | |
int interval=0; | |
int initial=0; | |
int tosecond = 1000000; | |
char *pc = &command[0]; | |
memset(command, '\x00', CMDLEN); | |
if (argc < 4) { | |
printf(usage); | |
exit(0); | |
} | |
c = getopt(argc, argv, "f:r:c:h"); | |
while(c != -1) { | |
switch (c) { | |
case 'f': | |
initial = atoi(optarg); | |
if (initial < 0) { | |
printf("-f s is not a number\n"); | |
return 0; | |
} | |
break; | |
case 'r': | |
interval = atoi(optarg); | |
if (interval < 0) { | |
printf("-r s is not a number\n"); | |
return 0; | |
} | |
break; | |
case 'c': | |
memcpy(command, optarg, 8 * strlen(optarg)); | |
if (!command[0]) { | |
pc = &nocmdmsg[0]; | |
} | |
break; | |
case 'h': | |
case '?': | |
printf(usage); | |
return 0; | |
} | |
c = getopt(argc, argv, "f:r:c:h"); | |
} | |
new.it_interval.tv_sec = interval / tosecond; | |
new.it_interval.tv_usec = interval % tosecond; | |
if (initial == 0) { | |
new.it_value.tv_sec = 0; | |
new.it_value.tv_usec = 1; | |
} else { | |
new.it_value.tv_sec = initial / tosecond; | |
new.it_value.tv_usec = initial % tosecond; | |
} | |
sigemptyset(&sa.sa_mask); | |
sa.sa_flags = 0; | |
sa.sa_handler = signal_handler; | |
if (sigaction(SIGALRM, &sa, NULL) == -1) { | |
perror("sigaction"); | |
return 0; | |
} | |
if (setitimer(ITIMER_REAL, &new, &old) < 0) { | |
perror("setitimer"); | |
return 0; | |
} | |
while(1) { | |
if (got_alarm == 1) { | |
printf("#%s\n", pc); | |
system(command); | |
got_alarm = 0; | |
} | |
sleep(3600); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment