資源簡介
操作系統課程項目,在linux下用c語言實現了多線程web服務器。可以選擇不同的調度算法,來執行web請求,有FCFS, SJF。采用線程池設計思想實現。
代碼片段和文件信息
#include
#include
#include
#include
#include
#include“myhttpd.h“
#include“queue.h“
#include“schedule.h“
#include“process.h“
#include“option.h“
control* initializeControl?(?);
void releaseResource?(?control*?cntl?);
void??usage?(?void?);
int?main(int?argc?char*?argv[])
{
choose(&argc?argv);
int?ret?i;
gClientSockfd?=?0;
if(option.help?==?1)
{
usage();
exit(0);
}
if(option.debug?==?1)
{
option.log?=?0;
}
else
{ /*?make?the?process?daemon?*/
pid_t p;
p?=?fork();
if?(?p?0?)
printError?(?“cannot?fork?new?process“?);
else?if?(?p?!=?0?)
exit?(?0?);
setsid?(?);
chdir?(?option.rootDirectory?);
umask?(?0?);
}
if?(?option.log?==?1)
{
/*?the?log?file?should?be?in?the?log?directory?which?is?the?source?file?directory*/
strcat?(?option.logDirectory?“/“?);
strcat?(?option.logDirectory?option.logFilename?);
}
?? /*?initialize?the?global?control?struct?*/
control* cntl?=?initializeControl?();
/*?setup?the?server?sock?*/
gSockfd?=?socket(?AF_INET?SOCK_STREAM?0?);
if?(?gSockfd?0?)
printError(“printError?opening?socket“);
??
struct?sockaddr_in serverAddr;
bzero(?(char*?)?&serverAddr?sizeof(serverAddr)?);
serverAddr.sin_family?=?AF_INET;
serverAddr.sin_addr.s_addr?=?INADDR_ANY;
serverAddr.sin_port?=?htons(option.port);
ret?=?1;
setsockopt?(?gSockfd?SOL_SOCKET?SO_REUSEADDR?&ret?sizeof(ret)?);
if?(?bind(?gSockfd?(struct?sockaddr?*)?&serverAddr?sizeof(serverAddr)?)?0?)
printError(“cannot?bind“);
listen?(?gSockfd?10?);
pthread_t exeThread[option.threadNum];
pthread_t queueThread;
pthread_t schedThread;
/*?create?execution?thread?*/
for?(?i?=?0?;?i? {
ret?=?pthread_create(?&exeThread[i]?NULL?execute?cntl?);
if?(?0?!=?ret?)
printf(“cannot?create?execution?thread?No.%d“?i?);
}
/*?create?queue?thread?and?schedule?thread?*/
cntl->queueLength++;
ret?=?pthread_create(?&queueThread?NULL?queue?cntl?);
if?(?0?!=?ret?)
printError(“cannot?create?queuing?thread“);
sleep?(?option.queuingTime?);
cntl->queueLength--;
ret?=?pthread_create(?&schedThread?NULL?schedule?cntl?);
if?(?0?!=?ret?)
printError(“cannot?create?scheduling?thread“);
?? /*?release?request?queue?*/
if?(?option.debug?)
{
char final[20];
scanf?(?“%s“?final?);
if?(?0?==?strncmp?(?final?“exit“?4?)?)
{
close?(?gSockfd?);
releaseResource?(?cntl?);
return?0;
}?
}
else
{
/*?wait?for?the?other?threads?to?complete?*/
pthread_join?(?queueThread?NULL?);
pthread_join?(?schedThread?NULL?);
for?(?i?=?0?;?i? pthread_join?(?exeThread[i]?NULL?);
}
}
/*print?error?message?and?exit*/
void?printError(const?char*?msg)
{
perror(msg);
exit(1);
}
void?getTime?(?char*?str?)
{
char ntime[64];
struct?tm* now;
time_t tm;
time?(?&tm?);
now?=?gmtime?(?&tm?);
strftime?(?ntime?sizeof(ntime)?“[?%d/%b/%Y:%H:%M:%S??-0400]“?now?);
strcpy(?str?ntim
- 上一篇:基于Qt的2048游戲實現
- 下一篇:橢圓曲線密碼ECC算法實現源碼C++
評論
共有 條評論