Advertisement
Guest User

we

a guest
Nov 20th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <sys/socket.h>
  4. #include <stdlib.h>
  5. #include <netinet/in.h>
  6. #include <string.h>
  7. #include <pthread.h>
  8. #define PORT 1000
  9. #define SIZE 32
  10.  
  11. int koniec = 0;
  12. pthread_t pid1, pid2;
  13. char * shared_string;
  14. pthread_mutex_t lock;
  15. int new_socket;
  16. int server_fd, valread;
  17. struct sockaddr_in address;
  18. int opt = 1;
  19.  
  20. void * drukuj1(void * arg)
  21. {
  22. size_t len=0;
  23. while(1)
  24. {
  25. pthread_mutex_lock(&lock);
  26. getline(&shared_string, &len,stdin);
  27. pthread_mutex_unlock(&lock);
  28. sleep(1);
  29. }
  30.  
  31. }
  32.  
  33. void * drukuj2(void * arg)
  34. {
  35.  
  36. while(1)
  37. {
  38. pthread_mutex_lock(&lock);
  39. //printf("writing:\n");
  40. send(new_socket , shared_string, strlen(shared_string), 0 );
  41. pthread_mutex_unlock(&lock);
  42. sleep(1);
  43. }
  44.  
  45. }
  46.  
  47. int main(int argc, char *argv[])
  48. {
  49.  
  50. int addrlen = sizeof(address);
  51. // Creating socket file descriptor
  52. if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
  53. {
  54. printf("socket failed");
  55. exit(EXIT_FAILURE);
  56. }
  57.  
  58.  
  59. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
  60. {
  61. printf("setsockopt");
  62. exit(EXIT_FAILURE);
  63. }
  64. address.sin_family = AF_INET;
  65. address.sin_addr.s_addr = INADDR_ANY;
  66. address.sin_port = htons( PORT );
  67.  
  68. if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
  69. {
  70. printf("bind failed");
  71. exit(EXIT_FAILURE);
  72. }
  73.  
  74. if (listen(server_fd, 3) < 0)
  75. {
  76. printf("listen");
  77. exit(EXIT_FAILURE);
  78. }
  79.  
  80. new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
  81.  
  82. pthread_mutex_init(&lock, NULL) ;
  83. shared_string=(char*)malloc(SIZE*sizeof(char));
  84. printf("Nawiazano polaczenie\n");
  85. pthread_create(&pid1,NULL,drukuj1,NULL);
  86. pthread_create(&pid2,NULL,drukuj2,NULL);
  87. pthread_join(pid1,NULL);
  88. pthread_join(pid2,NULL);
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement