本文主要是介绍假期作业8,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
线程和进程服务器
线程
#include <myhead.h>#define SIP "192.168.0.114"
#define SPORT 8888void *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 <myhead.h>#define SIP "192.168.0.114"
#define SPORT 8888int 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;
}
这篇关于假期作业8的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!