Home
   DIR <- Back
       
       bsleep - Breakable sleep in C
       =============================
       
       A couple of days ago I stumbled upon an improvised breakable sleep.
       I wrote about in another post:
   DIR 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 prefer silent */
                         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;
             }
       
  HTML asciinema
       
       Footnote:
       The invocation of the operating system command "/bin/stty" via system()
       is not the most elegant. At the moment this needed to read the character
       without the need to press Enter.
       If possible I will try to replace the call system("/bin/stty ...") in the
       future.
   DIR 2024-06-30 - bsleep (rewritten in C)