基于LinuxC语言实现的TCP多线程/进程服务器

多进程并发服务器

设计流程

框架一(使用信号回收僵尸进程)

void handler(int sig)
{
    while(waitpid(-1, NULL, WNOHANG) > 0);
}

int main()
{
    //回收僵尸进程
    siganl(17, handler);
    //创建服务器监听套接字 server
    server = socket();
    //给服务器地址信息结构体赋值,并绑定
    bind();
    //监听指定端口,设置监听队列
    listen();
    
    while(1)
    {
        //创建与客户端通信的套接字
        client = accept();
        //创建子进程
        if(fork() == 0)
        {
            //关闭拷贝的服务器套接字
            close(server);
            while(1)
            {
                //接收消息
                recv();
                //发送消息
                send();
            }
            //通信结束关闭套接字
            close(client);
            //退出进程
            exit(0);
        }
        //关闭父进程的通信套接字
        close(client);
    }
    
    //服务器关闭
    close(server);
}

实例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <time.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <errno.h>

#define LOG(s) printf("[%s] {%s:%d} %s \n", __DATE__, __FILE__, __LINE__, s);

void cil(int client, struct sockaddr_in caddr);

void handler(int sig)
{
	while(waitpid(-1, NULL, WNOHANG) > 0);
}

int main(int argc, char *argv[])
{

	//回收僵尸进程
	signal(17, handler);
	//创建服务器
	int server = -1;
	if((server = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		LOG("socket error");
		return -1;
	}

	//给服务器地址信息结构体赋值,并绑定
	struct sockaddr_in saddr = {0};
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8888);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if(bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == -1)
	{
		LOG("bind error");
		return -1;
	}

	//监听指定端口,设置监听队列
	if(listen(server, 5) == -1)
	{
		LOG("listen error");
		return -1;
	}

	puts("Tcp server start success");

	int client = -1;
	struct sockaddr_in caddr = {0};
	socklen_t len = sizeof(caddr);
	pid_t pid = -1;
	while(1)
	{
		//创建与客户端通信的套接字
		if((client = accept(server, (struct sockaddr*)&caddr, &len)) == -1)
		{
			LOG("accpet error");
			return -1;
		}

		printf("[%s/%d] client已上线\n", inet_ntoa(caddr.sin_addr), ntohl(caddr.sin_port));
		//创建子进程
		if((pid = fork()) < 0)
		{
			LOG("fork error");
			return -1;
		}
		else if(pid == 0)
		{
			cil(client, caddr);
			exit(0);
		}
		close(client);
	}

	close(server);

    return 0;
}

void cil(int client, struct sockaddr_in caddr)
{
	char buf[128] = "";
	int res = 0;
	while(1)
	{
		bzero(buf, sizeof(buf));
		if((res = read(client, buf, sizeof(buf))) < 0)
		{
			LOG("read error");
			break;
		}
		else if(res == 0)
		{
			printf("[%s/%d] client已下线\n", inet_ntoa(caddr.sin_addr), ntohl(caddr.sin_port));
			close(client);
			break;
		}
		printf("[%s/%d] client: %s\n", inet_ntoa(caddr.sin_addr), ntohl(caddr.sin_port), buf);
		
		bzero(buf, sizeof(buf));
		strcpy(buf, "ok");
		if(write(client, buf, sizeof(buf)) < 0)
		{
			LOG("write error");
			break;
		}
	}

}

框架二(使用孤儿进程机制避免僵尸进程产生)

int main()
{
    //创建服务器监听套接字 server
    server = socket();
    //给服务器地址信息结构体赋值,并绑定
    bind();
    //监听指定端口,设置监听队列
    listen();
    
    while(1)
    {
        //创建子进程
        if((pid = fork()) == 0)
        {
            //子进程创建用于与客户端通信的client
            client = accept();
            
            //创建孙进程
            if(pid = fork() == 0)
            {
                while(1)
                {
                    //孙进程负责与客户端通信
                    recv();
                    send();
                }
                //通信结束关闭套接字
                close(client);
                //退出进程
                exit(0);
            }
            //子进程
            else if(pid > 0)
            {
                //关闭多余的文件描述符
                close(server);
                close(client);
                //退出子进程
                exit(0);
            }
        }
        //父进程
        else if(pid > 0)
        {
            //回收子进程
            while(waitpid() == pid)
        }
    }
    //关闭文件描述符
    close(server);
}

实例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <time.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <errno.h>

#define LOG(s) printf("[%s] {%s:%d} %s\n", __DATE__, __FILE__, __LINE__, s);

void deal_cil_msg(int client, struct sockaddr_in caddr);

int main(int argc, char *argv[])
{
	//创建服务器socket
	int server = 0;
	if((server = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		LOG("socket error");
		return -1;
	}

	//绑定服务器IP和端口号
	//给地址信息结构体赋值
	struct sockaddr_in saddr = {0};
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8888);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == -1)
	{
		LOG("bind error");
		return -1;
	}

	//监听对应的端口号
	if(listen(server, 5) == -1)
	{
		LOG("listen error");
		return -1;
	}

	puts("server start success");

	//创建用于与客户端通信的socket
	struct sockaddr_in caddr = {0};
	int client = 0;
	socklen_t asize = sizeof(caddr);


	pid_t pid = -1;
	int status = 0;
	while(1)
	{
		//父进程只负责生儿子
		pid = fork();
		if(pid < 0)
		{
			LOG("fork error");
			return -1;
		}
		//子进程负责创建通信socket
		if(pid == 0)
		{
			//创建用于与客户端通信的socket
			if((client = accept(server, (struct sockaddr*)&caddr, &asize)) == -1)
			{
				LOG("accept error");
				return -1;
			}
			printf("[%s/%d]client已上线\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));

			//孙进程负责通信
			pid = fork();
			if(pid < 0)
			{
				LOG("fork error");
				return -1;
			}
			else if(pid == 0)
			{
				deal_cil_msg(client, caddr);
				close(client);
				exit(0);
			}
			else if(pid > 0)
			{
				close(server);
				close(client);
				//退出子进程
				exit(0);
			}
		}
		else if(pid > 0)
		{
			printf("wait child = %d\n", pid);
			//父进程等待子进程结束,准备收尸
			while(waitpid(pid, &status, 0) == pid)
			{
				printf("Parent is over - child: %d, status = %x\n", pid, status);
			}
		}
	}

	//关闭文件描述符
	close(server);
	
	return 0;
}


void deal_cil_msg(int client, struct sockaddr_in caddr)
{
	//接收消息
	char buf[128] = " ";

	while(1)
	{
		int len = 0;
		bzero(buf, sizeof(buf));
		if((len = recv(client, buf, sizeof(buf), 0)) < 0)
		{	
			LOG("recv error");
		}
		else if(len == 0)
		{
			printf("[%s/%d]client已下线\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
			break;
		}
		printf("[%s/%d]client: %s\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port), buf);

		bzero(buf, sizeof(buf));
		//发送消息
		strcpy(buf, "ok");
		write(client, buf, len);

	}


}

多线程并发服务器

设计流程

//线程参数结构体
typedef struct
{
	int client;
	struct sockaddr_in caddr;
} Client_msg;

int main()
{
    //创建服务器监听套接字 server
    server = socket();
    //给服务器地址信息结构体赋值,并绑定
    bind();
    //监听指定端口,设置监听队列
    listen();
    
    while(1)
    {
        //创建用于与客户端通信的套接字
        client = accpet();
        //创建线程
        pthread_create();
        while(1)
        {
            //读写
            //关闭文件描述符
            //退出线程
        }
        //解离线程
        pthread_detach();
    }
    //关闭文件描述符
    close(server);
}

实例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <time.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <errno.h>

#define LOG(s) printf("[%s] {%s:%d} %s \n", __DATE__, __FILE__, __LINE__, s);

void* cil(void* arg);

//线程参数结构体
typedef struct
{
	int client;
	struct sockaddr_in caddr;
} Cli_msg;

int main(int argc, char *argv[])
{
	//创建服务器监听分套接字 server
	int server = -1;
	if((server = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		LOG("socket error");
		return -1;
	}

	//给服务器地址信息结构体赋值,并绑定
	struct sockaddr_in saddr = {0};
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8899);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == -1)
	{
		LOG("bind error");
		return -1;
	}

	//监听端口
	if(listen(server, 5) == -1)
	{
		LOG("listen error");
		return -1;
	}
	
	puts("tcp server start success");

	struct sockaddr_in caddr = {0};
	socklen_t len = sizeof(caddr);
	pthread_t tid = -1;
	int client = -1;
	Cli_msg cli_msg;
	while(1)
	{
		//创建用于与客户端通信的套接字 client
		if((client = accept(server, (struct sockaddr*)&caddr, &len)) == -1)
		{
			LOG("accept error");
			return -1;
		}

		printf("[%s/%d]client已上线\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
		cli_msg.client = client;
		cli_msg.caddr = caddr;
		//创建线程
		if(pthread_create(&tid, NULL, cil, &cli_msg) != 0)
		{
			LOG("pthread_create error");
			return -1;
		}
		pthread_detach(tid);
	}

	close(server);
	return 0;
}

void* cil(void* arg)
{
	int client = ((Cli_msg*)arg)->client;
	struct sockaddr_in caddr = ((Cli_msg*)arg)->caddr;

	char buf[128] = "";
	int res = 0;

	while(1)
	{
		bzero(buf, sizeof(buf));
		if((res = read(client, buf, sizeof(buf))) < 0)
		{
			LOG("read error");
			break;
		}
		else if(res == 0)
		{
			printf("[%s/%d]client已下线\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
			close(client);
			pthread_exit(NULL);
		}
		printf("[%s/%d]client: %s\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port), buf);

		bzero(buf, sizeof(buf));
		strcpy(buf, "ok");

		if(write(client, buf, sizeof(buf)) < 0)
		{
			LOG("write error");
			break;
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值