I'm a C newbie. My eventual goal is to create an Apache module that returns the Apache user account's crontab as JSON.
Baby steps first though. I've successfully followed tutorials at the two following locations to output "hello world" and variations thereof from an Apache module (and I actually own Nick Kew's book):
I've modified the examples slightly to output JSON as follows:
ap_rputs("{'hello': {'to': 'world', 'from': '?'}}", r);
I'd like to substitute the '?' above with output from the Linux system's 'whoami' command (eventually I want to run the linux command 'crontab -lu username'). As a C newbie though I am overwhelmed by the choices as to how to go about this, I've tried a few things, and don't seem to be close to getting anything right. I do seem to be able to trap the output from whoami, or at least my code compiles and runs ;)
FILE *sysp = popen("whoami","r");
But am I even doing the above right? And what is a good next step? I thought I might try to determine the length of the output from above, then create a char array of the same length, rewind the file handle, and grab the output. But I don't seem to be obtaining the length properly, and maybe this is a sub-optimal approach? When I run the following (I've left out a couple of lines I know might be necessary, i.e. rewind, fclose) the output I get is -1:
fseek(sysp, 0L, SEEK_END);
long len = ftell(sysp);
char buf[2];
sprintf(buf, "%d", (int)len);
ap_rputs(buf, r);
Any pointers specifically as to how to better approach outputting the result from the system command "whoami" would be appreciated.
The FILE *
in this case refers to a pipe, which may not really be seekable. Ideally, you should get the information you are looking for directly from the system, rather than invoking an external program; I think the getuid()
and getpwent()
functions will come in handy here.
As getpwent()
may block (just as your method using popen()
, it is not safe to use your module with any MPM that does not use at least a single thread per request.