天天看點

fcgi與c++伺服器demo示例fcgi與c++建構多線程伺服器demo示例

fcgi與c++建構多線程伺服器demo示例

須安裝fcgi庫

yum -y install fcgi;

yum -y install spawn-fcgi;

源碼demo.cpp

#include "fcgi_stdio.h"
#include <pthread.h>
#include <stdlib.h>

# define THREAD_NUM 1

void * thread_function(void *)
{
    int rc;
    FCGX_Request request;
    FCGX_InitRequest(&request,0,0);
    for(;;)
    {
	    static pthread_mutex_t req_locker = PTHREAD_MUTEX_INITIALIZER;
	    pthread_mutex_lock(&req_locker);
        rc = FCGX_Accept_r(&request);
        phtread_mutex_unlock(&req_locker);
        if(rc <0)
            break;
        FCGX_FPrintF(request.out,"Content-type: text/html\r\n"
        "\r\n"
        "<title>FastCGI Hello!</title>"
        "<h1>FastCGI Hello!</h1>");
        FCGX_Finish_r(&request);
    }
}


int main(void)
{
    pthread_t tid[THREAD_NUM];
    FCGX_Init();

    for(int i = 0;i <THREAD_NUM;i++)
    {
        pthread_create(&tid[i],NULL,thread_function,NULL);
    }

    for(int i = 0;i <THREAD_NUM;i++)
    {
        pthread_join(tid[i],NULL);
    }
    return 0;
}
           

編譯:g++ demo.cpp -o demo -lpthread -lfcgi

執行腳本start.sh

#!/bin/bash
program=`basename $0`

if [ $# != 1 ]
then
	echo "Usage: {$program} <program_name> [kill],kill is optional agrument"
	exit -1
fi

killall -q -9 $1
killall -q -9 spawn-fcgi

if [ "$2"  == "kill" ] 
then
	exit 0
fi

SPAWNFCGI=/usr/bin/spawn-fcgi
EXEC=$1

$SPAWNFCGI -p 12345 -F 4 -- $EXEC