我在下面的代码中编写了服务器从套接字上的客户端获取请求并为每个客户端创建一个线程的代码。然后每个客户端线程写入所有线程共有的文件。open
该文件在 main 启动时已被编辑,因此每个线程都使用相同的 fd。在这种情况下,我试图在一个线程写入文件时实现对文件的锁定。由于线程属于同一进程,因此flock
不能简单地锁定文件,因此mutex
使用。
/*Logging function*/
void write_to_file(int op_fd,char *name)
{
flock(op_fd,LOCK_EX);
pthread_mutex_lock(&f_lck);
write(op_fd,name,20);
pthread_mutex_unlock(&f_lck);
flock(op_fd,LOCK_UN);
}
/*Client thread function*/
void *clnt_thread(void * arg)
{
int this_fd=*(int *)arg;
/*str is a continuous memory array of the size of the dat_com struct.This will be filled up initially on receive as a normal array
, but then it'll typecasted to point to struct dat_com object*/
char str[sizeof(dat_com)],str_send[25];
memset(&str,'\0',sizeof(str));
dat_com *incm_dat; // struct to contain the incoming data from client .
while(1)
{
read(this_fd,str,sizeof(str));
/*typecast to struct dat_com so that it is ready to be inserted into linked list or file.*/
incm_dat=(dat_com *)&str;
if(strncmp(str,"quit",4)==0)
break;
/*Call write to file function*/
write_to_file(o_fd,incm_dat->name);
fprintf(stderr,"Client said: %s",incm_dat->name);
/*client wants to close connection?*/
sprintf(str_send,"%s",incm_dat->name);
send(this_fd,str_send,sizeof(incm_dat->name),MSG_NOSIGNAL);
}
close(this_fd);
return 0;
}
目前这正在按预期工作。这是以这种方式锁定的好习惯吗?还是有其他最佳做法?如果我必须将此代码投入生产,我需要进行哪些非标准做法的更改?我知道理想情况下这应该在codereview
现场,所以我已经在 3 天前发布了它,但没有任何评论。