fastcgi c++使用
#include <fcgi_stdio.h>
#include <stdlib.h>
int main() {
int count = 0;
while (FCGI_Accept() >= 0) {
printf("Content-type: text/html\r\n"
"\r\n"
""
"FastCGI Hello!"
"Request number %d running on host%s "
"Process ID: %d\n", ++count, getenv("SERVER_NAME"), getpid());
}
return 0;
}
g++ demo.cc -o demo -lfcgi
GET
char buff[1024] = {0};
strncpy(buff,getenv("QUERY_STRING"),sizeof(buff));
printf("Content-Type=text\r\n\r\n");
printf("User Data = %s\r\n",buff);
POST
fread(buff,1,sizeof(buff),stdin);
printf("Content-Type=text\r\n\r\n");
printf("Secess: %s\r\n",buff);
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <fcgi_stdio.h>
char* memstr(char* full_data,int full_data_len,char* substr)
{
// 匹配子串的长度
int sublen = strlen(substr);
int i;
char* cur = full_data;
int last_possible = full_data_len-sublen +1;
for (i = 0; i < last_possible; ++i) {
if(*cur == *substr)
{
if(memcmp(cur,substr,sublen) == 0)
{
return cur;
}
}
cur++;
}
return NULL;
}
void readFile(char* begin,int num,char* filename)
{
int fd = 0;
fd = open(filename,O_CREAT|O_WRONLY,0644);
ftruncate(fd,num);
write(fd,begin,num);
close(fd);
}
int main()
{
while(FCGI_Accept() >= 0)
{
printf("Content-Type=text\r\n\r\n");
char* contentLength = getenv("CONTENT_LENGTH");
if(NULL == contentLength)
{
printf("Error: Content-Length is NULL\r\n");
break;
break;
}
long len = atol(contentLength);
char* file_buf= new char[len];
fread(file_buf,1,len,stdin);
✹ int ret = 0;
char *begin = NULL;
char *p,*q,*k;
char content_text[1024]={0}; //文件头部信息
char boundary[1024] = {0}; //分界线信息
char filename[1024] = {0};
//-------------开始处理
begin = file_buf; //内存起点
p = begin;
//get boundary 得到分界线, ------WebKitFormBoundary88asdgewtgewx
p = strstr(begin,"\r\n");
strncpy(boundary,begin,p-begin);
boundary[p-begin] = '\0'; // 字符串结束符
p += 2; //\r\n
// 已经处理了p-begin的长度
len -= (p-begin);
begin = p;
//get content text head
p = strstr(begin,"\r\n");
strncpy(content_text,begin,p-begin);
content_text[p-begin] = '\0';
p += 2;
len -= (p-begin);
//-------------------获取文件信息
q = begin;
q = strstr(begin,"filename=");
q += strlen("filename=");
q++; // 跳过一个双引号
k = strchr(q,'"');
strncpy(filename,q,k-q);
filename[k-q] = '\0';
begin = p;
//--------------------获取文件信息结束
p = strstr(begin,"\r\n");
p += 4; //\r\n\r\n
len -= (p-begin);
begin = p;
// 下面才是真正的内容
p = memstr(begin,len,boundary);
p -= 2;
// 写入文件
readFile(begin,(p-begin),filename);
delete [] file_buf;
printf("%s\r\n",filename);
}
return 0;
}
浙公网安备 33010602011771号