📄 s1.c
字号:
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <pthread.h>#include <semaphore.h>void *Client(void *arg);void *thread_function(void *arg);int count=0;sem_t mutex;pthread_t a_thread; int server_sockfd, client_sockfd; int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address;main(){ sem_init(&mutex,0,1); server_sockfd = socket( AF_INET , SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(9734); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); listen(server_sockfd, 5); while(1){pthread_create(&a_thread,NULL,thread_function,NULL);pthread_join(a_thread,NULL); }}void *thread_function(void *arg){ printf("server waiting\n"); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address, &client_len); printf("accept request\n");pthread_create(&a_thread,NULL,Client,(void *)&client_sockfd);}void *Client(void *arg){char ch;int a,b,re; int client_sockfd = ((int *)arg)[0];sem_wait(&mutex);count++;sem_post(&mutex); read(client_sockfd, &ch, 1);write(client_sockfd, &count, 4);read(client_sockfd, &a, 4);read(client_sockfd, &b, 4);if(ch=='1')re=a+b;if(ch=='2')re=a-b;if(ch=='3')re=a*b;if(ch=='4')re=a/b; write(client_sockfd, &re, 4); printf("processing finish\n"); close(client_sockfd);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -