假期作业8

线程和进程服务器

线程

#include 

#define SIP "192.168.0.114"
#define SPORT 8888

void *task(void *arg){
	printf("客户端连接\n");
	sleep(1);
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	int sfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sfd == -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_addr.s_addr = inet_addr(SIP);
	sin.sin_port = htons(SPORT);
	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);
	while(1){
		int newfd = accept(sfd, (struct sockaddr*)&cin, &socklen);
		pthread_t tid;
		if(pthread_create(&tid, NULL, task, NULL) != 0){
			printf("pthread_create error\n");
			return -1;
		}
		pthread_detach(tid);
	}

	return 0;
}

进程

#include 

#define SIP "192.168.0.114"
#define SPORT 8888

int main(int argc, const char *argv[])
{
	int sfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sfd == -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_addr.s_addr = inet_addr(SIP);
	sin.sin_port = htons(SPORT);
	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);
	while(1){
		int newfd = accept(sfd, (struct sockaddr*)&cin, &socklen);
		pid_t pid = fork();
		if(pid == -1){
			perror("fork error");
			return -1;
		}
		if(pid == 0){
			printf("[%s %d]:已连接\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port));
			close(newfd);
			raise(SIGKILL);
		}
	}

	return 0;
}

你可能感兴趣的:(c语言)