Advertisement
Briotar

Untitled

Apr 29th, 2021
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <netdb.h>
  5. #include <memory.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <signal.h>
  10. #include <pthread.h>
  11.  
  12. #define SRV_PORT 13002 //порт сервера
  13. #define BUF_SIZE 128
  14.  
  15. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  16.  
  17. struct thread_arg
  18. {
  19. int s_client;
  20. char buf[128];
  21. };
  22.  
  23.  
  24. void* calculation(void *arg)
  25. {
  26. int from_len;
  27. char buf[128];
  28.  
  29. pthread_mutex_lock(&lock);
  30. struct thread_arg parg = *(struct thread_arg*)(arg);
  31. pthread_mutex_unlock(&lock);
  32.  
  33. static char* output;
  34. int new_socket = parg.s_client;
  35. //output = parg.buf;
  36.  
  37. from_len = recv(new_socket, buf, BUF_SIZE, 0);
  38.  
  39. sleep(10);
  40. pthread_mutex_lock(&lock);
  41. FILE *result = popen (buf,"r");
  42. fread(buf,sizeof(char), 256, result);
  43. printf("%s\n",buf);
  44. pthread_mutex_unlock(&lock);
  45. send(new_socket, buf, 256, 0);
  46. //buf[0]='\0';
  47. //shutdown(new_socket, 0);
  48. //close(new_socket);
  49. }
  50.  
  51. int main()
  52. {
  53. int s, s_client;
  54. int from_len;
  55. char buf[BUF_SIZE];
  56. int len_buf;
  57.  
  58. char output[128];
  59. pthread_t thread;
  60. pthread_t tid[50];
  61.  
  62. struct sockaddr_in sin, from_sin;
  63.  
  64. s = socket(AF_INET, SOCK_STREAM, 0);
  65. memset((char*)&sin, '\0', sizeof(sin));
  66. sin.sin_family = AF_INET; // так как используем TCP/IP
  67. sin.sin_addr.s_addr = INADDR_ANY; //привязываем сокет к номеру локального узла сети
  68. sin.sin_port = SRV_PORT; //номер порта сервера
  69. bind (s, (struct sockaddr *)&sin, sizeof(sin)); //связываем сокет
  70. listen(s, 50); // ждем 1 запроса
  71. while(1)
  72. {
  73. struct thread_arg arg;
  74. from_len = sizeof(from_sin);
  75. s_client = accept(s, (struct sockaddr *)&from_sin, &from_len);
  76.  
  77. int i = 0;
  78. arg.s_client = s_client;
  79. //strcpy(arg.buf,buf);
  80. if (pthread_create(&tid[i++],NULL, calculation, &arg) != 0)
  81. {
  82. printf("cannot create thread");
  83. }
  84. if(i >= 50)
  85. {
  86. i = 0;
  87. while(i < 50)
  88. {
  89. pthread_join(tid[i++], NULL);
  90. }
  91. i = 0;
  92. }
  93. }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement