简体   繁体   English

从apache模块输出Linux系统whoami的C代码

[英]C code to output linux system whoami from apache module

I'm a C newbie. 我是C新手。 My eventual goal is to create an Apache module that returns the Apache user account's crontab as JSON. 我最终的目标是创建一个Apache模块,该模块将Apache用户帐户的crontab返回为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): 我已经成功地遵循了以下两个位置的教程,以从Apache模块输出“ hello world”及其变体(并且我实际上是Nick Kew的书):

I've modified the examples slightly to output JSON as follows: 我对示例进行了一些修改,以输出JSON,如下所示:

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'). 上面带有Linux系统的“ whoami”命令的输出(最终我想运行linux命令“ 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. 作为一名C新手,尽管我不知如何选择,但我已经尝试了一些方法,而且似乎还没有做好任何准备。 I do seem to be able to trap the output from whoami, or at least my code compiles and runs ;) 我似乎确实能够捕获whoami的输出,或者至少我的代码可以编译和运行;)

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. 我以为我可以尝试从上面确定输出的长度,然后创建一个相同长度的char数组,倒退文件句柄,然后获取输出。 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, ie rewind, fclose) the output I get is -1: 当我运行以下命令(我省略了几行我知道可能有必要,即快退,fclose)时,我得到的输出是-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. 任何关于如何更好地从系统命令“ whoami”输出结果的指示都将受到赞赏。

The FILE * in this case refers to a pipe, which may not really be seekable. 在这种情况下, FILE *指的是管道,它可能实际上并不是可搜索的。 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. 我认为getuid()getpwent()函数在这里会派上用场。

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. 由于getpwent()可能会阻塞(就像您使用popen()方法一样,将模块与任何不至少每个请求使用单个线程的MPM一起使用是不安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM