我在C中编写一个小型Web服务器,它应该使用进程池为多个客户端请求提供服务。在添加共享内存组件以存储服务器发送的流量数之前,进程池工作正常。所有请求之前都由不同的进程处理。现在它们都由同一个过程处理。我没有将代码更改为fork()子进程,这让我很困惑..
typedef struct {
long int traffic;
pthread_mutex_t muxlock;
} shmem;
/*Creating the shared memory and,setting its size, closing | Initializing the mutex*/
shm_unlink("/sum_traffic");
int shmfd = shm_open("/sum_traffic", O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); //Creates the shared memory
ftruncate(shmfd,sizeof(int)*8+sizeof(shmem)); //Sets the size of the shared memory
shmem *memptr = mmap(NULL, (sizeof(int)*8+sizeof(shmem)), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0); //Maps a pointer for us to work with
pthread_mutex_init(&(*memval).muxlock,NULL); //Initialize the mutex lock
//Forking 10 worker processes
int i;
for(i=0; i<11;i++){
if(pid>0){
pid=fork();
}
}
if(pid < 0){
fprintf(stderr, "Error forking, error: %d\n",errno);
exit(EXIT_FAILURE);
}
//Worker-processes
while(1)
if(pid == 0){
//Accept connection on list_s
if((conn_s = accept(list_s, NULL, NULL)) < 0){
fprintf(stderr , "Error calling accept \n");
exit(EXIT_FAILURE);
}
httpRequest request;
request = parseRequest(getMessage(conn_s)); //Parses the http GET request
headertraffic=selectHeader(conn_s,request.returncode); //Selects a Header file to send
currenttraffic=printFile(conn_s,request.filename); //Serves the requested file
pthread_mutex_lock(&(*memval).muxlock); //Lock the mutex to write to shared memory
(*memval).traffic=((*memval).traffic+currentdata+headerdata);
pthread_mutex_unlock(&(*memval).muxlock); // Unlock mutex
printf("PID: %d\n",getpid());
(void)close(conn_s);
}
非常感谢帮助!
答案 0 :(得分:2)
不确定这是否是您的真实代码,但有些错误检查会有所帮助。
这可能不是您的问题,但一个促成因素是您没有将互斥锁设置为由多个进程共享。您无法使用pthread_mutex_init()
中的默认属性。您必须使用pthread_mutexattr_init()and then call
pthread_mutexattr_setpshared()and then call
pthread_mutex_init()`来初始化互斥锁属性。