<- Back | |
bsleep - Breakable sleep in C | |
============================= | |
A couple of days ago I stumbled upon an improvised breakable sleep. | |
I wrote about in another post: | |
2024-06-25 - bsleep (bashism) | |
Since I generally strife to get independant from the use of bashisms, I | |
decided to rewrite bsleep in C. | |
And here we go... | |
Breakable sleep in C. The button 'b' breaks the sleep. This can be used | |
to chain two tasks on the commandline, with the second task only waiting | |
for you to press 'b'. | |
git clone git://kroovy.de/bsleep | |
Build dependencies | |
- C compiler | |
- libc | |
This program is meant to help people complete tasks on the commandline. | |
Also the source code can be studied as a simple approach to forking a | |
process in C. | |
#include <signal.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
int | |
main(void) | |
{ | |
int i,in,pid; | |
pid = fork(); | |
if (pid == 0) { | |
/* child */ | |
for (i=1;;i++) { | |
printf("%d ", i); fflush(stdout); /* comment out if you prefe… | |
sleep(1); | |
} | |
return 0; | |
} else if (pid > 0) { | |
/* parent */ | |
system ("/bin/stty raw"); | |
while ((in = getchar()) != 'b') { | |
printf("%c ", in); | |
} | |
system ("/bin/stty cooked"); | |
printf("\n"); | |
kill(pid, SIGKILL); /* kill child */ | |
return 0; | |
} else { | |
return -1; | |
} | |
return 0; | |
} | |
asciinema |