@paddyがすでに述べたように、1つの方法はCGIとして実行することです。ただし、プログラムの実行時間は遅く、起動時間が長くなります。
もう1つの方法は、FastCGIを使用して実行することです。それははるかに高速になります。たとえば、CGIとして機能させるには、コードにいくつかの変更を加えるだけです。
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
time_t timer;
char time_str[25];
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(time_str, sizeof(time_str), "%Y/%m/%d %H:%M:%S", tm_info);
/* Without this line, you will get 500 error */
puts("Content-type: text/html\n");
puts("<!DOCTYPE html>");
puts("<head>");
puts(" <meta charset=\"utf-8\">");
puts("</head>");
puts("<body>");
puts(" <h3>Hello world!</h3>");
printf(" <p>%s</p>\n", time_str);
puts("</body>");
puts("</html>");
return 0;
}
コンパイルします:
$ # 'cgi-bin' path may be different than yours
$ sudo gcc example.c -o /usr/lib/cgi-bin/example
$ wget -q -O - http://localhost/cgi-bin/example
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3>Hello world!</h3>
<p>2013/01/30 08:07:29</p>
</body>
</html>
$
FastCGIの使用:
#include <fcgi_stdio.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
time_t timer;
char time_str[25];
struct tm* tm_info;
while(FCGI_Accept() >= 0) {
time(&timer);
tm_info = localtime(&timer);
strftime(time_str, sizeof(time_str), "%Y/%m/%d %H:%M:%S", tm_info);
/* Without this line, you will get 500 error */
puts("Content-type: text/html\n");
puts("<!DOCTYPE html>");
puts("<head>");
puts(" <meta charset=\"utf-8\">");
puts("</head>");
puts("<body>");
puts(" <h3>Hello world!</h3>");
printf(" <p>%s</p>\n", time_str);
puts("</body>");
puts("</html>");
}
return 0;
}
コンパイルします:
$ # Install the development fastcgi package, I'm running Debian
$ sudo apt-get install libfcgi-dev
...
$
$ # Install Apache mod_fcgid (not mod_fastcgi)
$ sudo apt-get install libapache2-mod-fcgid
...
$
$ # Compile the fastcgi version with .fcgi extension
$ sudo gcc example.c -lfcgi -o /usr/lib/cgi-bin/example.fcgi
$ # Restart Apache
$ sudo /etc/init.d/apache2 restart
Restarting web server: apache2 ... waiting .
$
$ # You will notice how fast it is
$ wget -q -O - http://localhost/cgi-bin/example.fcgi
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3>Hello world!</h3>
<p>2013/01/30 08:15:23</p>
</body>
</html>
$
$ # Our fastcgi script process
$ ps aux | grep \.fcgi
www-data 2552 0.0 0.1 1900 668 ? S 08:15 0:00 /usr/lib/cgi-bin/example.fcgi
$
pothプログラムには、次のものがあります。
puts("Content-type: text/html\n");
これにより、次のように出力されます。
Content-type: text/html[new line]
[new line]
これがないと、Apacheは500サーバーの内部エラーをスローします。