多进程并发服务器
#include
#define PORT 8888
#define IP "192168.31.244"
//用于回收僵尸进程
void handler(int signo)
{
if(signo==SIGCHLD)
{
while(waitpid(-1,NULL,WNOHANG)>0);
}
}
int deal_msg(int newfd,struct sockaddr_in cin)
{
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
int res=recv(newfd,rbuf,sizeof(rbuf),0);
}
close(newfd);
return 0;
}
int main(int argc, const char *argv[])
{
//将信号进行绑定
if(signal(SIGCHLD,handler)==SIG_ERR)
{
perror("signal error");
return -1;
}
//创建套接字
int sfd=-1;
if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket error");
return -1;
}
//端口号快速重用
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
//绑定地址信息结构体
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("bind error");
return -1;
}
//开启监听
if(listen(sfd,128)==-1)
{
perror("listen error");
return -1;
}
//接收连接请求
struct sockaddr_in cin;
socklen_t socklen=sizeof(cin);
int newfd=-1;
pid_t pid=-1;
while(1)
{
if((newfd=accept(sfd,(struct sockaddr*)&cin,&socklen))==-1)
{
perror("accept error");
return -1;
}
pid=fork();
if(pid>0)
{
//父进程
close(newfd);
}
else if(pid==0)
{
//子进程
close(sfd);
deal_msg(newfd,cin);//调用函数
exit(EXIT_SUCCESS);
}
else
{
perror("fork error");
return -1;
}
}
close(sfd);
return 0;
}
多线程并发服务器
#include
#define PORT 8888
#define IP "192168.31.244"
struct pthread_ds
{
int newfd;
struct sockaddr_in cin;
};
void *deal_msg(void *arg)
{
int newfd=((struct pthread_ds*)arg)->newfd;
struct sockaddr_in cin=((struct pthread_ds*)arg)->cin;
//收发数据
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
int res=recv(newfd,rbuf,sizeof(rbuf),0);
}
close(newfd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建套接字
int sfd=-1;
if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket error");
return -1;
}
//端口号快速重用
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
//绑定地址信息结构体
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("bind error");
return -1;
}
//开启监听
if(listen(sfd,128)==-1)
{
perror("listen error");
return -1;
}
//接收连接请求
struct sockaddr_in cin;
socklen_t socklen=sizeof(cin);
int newfd=-1;
pthread_t tid=-1;
while(1)
{
if((newfd=accept(sfd,(struct sockaddr*)&cin,&socklen))==-1)
{
perror("accept error");
return -1;
}
struct pthread_ds info={newfd,cin};
if(pthread_create(&tid,NULL,deal_msg,&info)!=0)
{
printf("tid create error\n");
return -1;
}
pthread_detach(tid);//设置成分离态,由系统回收
}
close(sfd);
return 0;
}