Testing C code from the command line: gccrun

I wrote a little utility the other day before I found myself in need of it: it takes its argument, compiles it as the body of a C program, and runs it.

This is way more convenient than you’d think at first glance: it turns out that, for one- or two-line programs where you’re just testing how something works, when 80% of your program is include boilerplate and making a source file and running gcc followed by the program, you’re somewhat disinclined to test small things. When you have a utility like this, you end up using it a lot…

How many file descriptors can I open?

dr-wily:~ geofft$ gccrun 'int fd; while ((fd = open("/dev/null", 0)) > 0) printf("%d\n", fd);' | tail -1
1023

What error does that get me?

dr-wily:~ geofft$ gccrun 'while (open("/dev/null", 0) > 0); perror("open");'
open: Too many open files

Can I go higher by not having things open on lower fds, and just opening something on fd 1024?

dr-wily:~ geofft$ gccrun 'dup2(0, 1023); perror("dup2");'
dup2: Success
dr-wily:~ geofft$ gccrun 'dup2(0, 1024); perror("dup2");'
dup2: Bad file descriptor`

What is errno 2?

dr-wily:~ geofft$ gccrun 'printf("%s\n", strerror(2));'
No such file or directory

What is my “session leader”?

dr-wily:~ geofft$ gccrun 'printf("%d\n", getsid(0));'
18291
dr-wily:~ geofft$ ps 18291
   PID TTY      STAT   TIME COMMAND
 18291 pts/28   Ss     0:00 /bin/bash

This is, of course, no substitute for reading formal docs or writing rigorous tests, but it’s great for getting an intuition about how something works.

gccrun is a very tiny shell script. Most of the convenience comes from it including a bunch of headers by default; recommendations on headers to add, and patches in general, welcome.

23 August 2010
CC-BY-SA