[Ilugc] C coding tricks on UNIX

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Tue, 26 Jun 2012 21:05:02 +0530

On UNIX C is fun because C programs are meant to be run on UNIX.

And over time it evolved to run on everything.

Still UNIX is fun.

What I like most about C is its economy of expression.

Like Sanskrit. You say what you want to say in minimum words.

No beating around the bush.

And it has no library. The libc that you definitely need without which the
OS cannot run(as most applications are dynamically linked)  is very
very small.

You have to write mostly by hand.

And you have many macros in header files and header file inclusion order counts.

In C everything counts. A comma, a ; and so on.

That is true with other languages; for instance in Python, whitespace
counts. Ugh.

In C, the library that comes bundled allows few string functions, few
OS routines and
 few math functions. That is mostly it.

Now for the tricks part.

$ cat s.c
#include <stdio.h>

int
main() {
            alarm(5);
            while(1) {
                   sleep(1);
            }
}

I am not sure, you may have to include some header.

This will exit in 5 seconds since you are not handling the SIGALRM.

You also have interval timers. For instance,

$ cat it.c

 #include <stdio.h>
#include <signal.h>
#include <sys/time.h>


void sigcb(int sig) {
        printf(" 5 sec Interval...\n");
}

int
main() {
        struct itimerval itvl;

        signal(SIGALRM, sigcb);

        itvl.it_interval.tv_sec = 5;
        itvl.it_interval.tv_usec = 0;
        itvl.it_value.tv_sec = 5;
        itvl.it_value.tv_usec = 0;

        setitimer(ITIMER_REAL, &itvl, NULL);
        while(1)
                pause();

}

-Girish
-- 
Gayatri Hitech
http://gayatri-hitech.com

Other related posts: