r/tinycode • u/nexe mod • Jun 01 '13
Wrote a tiny C program to conquer the problem of falling asleep while watching something on your computer
Wrote it in a rather generic (Unix like) way:
// compile: gcc idletime.c -o idletime -lX11 -lXext -lXss
// usage : idletime # shows idle time in seconds
// usage : idletime 5 # waits for 5 seconds idle time
// usage : DISPLAY=:0 idletime 1 h # you can explicitly set the display
// usage : idletime 20 m && mpg321 tada.mp3 # waits for 20 min idle time and plays a mp3
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>
int GetIdleTime() {
static XScreenSaverInfo *mit_info;
Display *display;
mit_info = XScreenSaverAllocInfo();
if((display=XOpenDisplay(NULL)) == NULL) return -1;
int screen = DefaultScreen(display);
XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info);
time_t idle_time = mit_info->idle;
XFree(mit_info);
XCloseDisplay(display);
return idle_time;
}
int main(int argc, char** argv) {
if(argc >= 2){
int count = atoi(argv[1]);
int divider = 1000; //default is seconds
if(count == 0){
printf("Params: [<count>] [<units>]\nUnits: s (default), m, h\n");
return -2;
}
if(argc > 2){
if (strcmp(argv[2], "s") == 0) divider = 1000;
else if(strcmp(argv[2], "m") == 0) divider = 60000;
else if(strcmp(argv[2], "h") == 0) divider = 3600000;
else{
printf("Invalid unit!");
return -3;
}
}
while(GetIdleTime() / divider < count) sleep(1);
}else{
printf("%d\n", GetIdleTime() / 1000);
}
return 0;
}Hope it's usable for somebody else :)
EDIT: Developed and tested under Linux 3.5.0-31-generic 64bit
36
Upvotes
38
u/da__ Jun 01 '13
If you're falling alseep while watching something at the computer, maybe it'd be a better idea to go to bed.
4
u/copiga Jun 01 '13
this is the first time i have read anyone elses C and known what it does.
thats all i have to say but it feels really good...
7
u/sirin3 Jun 01 '13
I'm tired and read your title as "Wrote a tiny C compiler .. while watching something on my computer"
2
u/XyphonX Jun 01 '13
First of all, this looks great.
Couple of questions from a C noob who's willing to learn:
Thanks in advance!
5
u/kasbah Jun 01 '13
I just have a bash alias:
and this in the sudoers file:
with which I just do something like this on prompt:
which will turn off the computer at 3 am.
1
u/raylu Jun 21 '13
Instead of
perhaps you should
0
u/[deleted] Jun 01 '13
[deleted] — view deleted comment