Advertisement
Guest User

SCZR

a guest
Nov 20th, 2019
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 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. void * drukuj1(void * arg)
  20. {
  21. size_t len=0;
  22. while(1) {
  23. pthread_mutex_lock(&lock);
  24. //printf("reading:\n");
  25. getline(&shared_string, &len,stdin);
  26.  
  27. pthread_mutex_unlock(&lock);
  28. sleep(1);
  29. }
  30.  
  31. }
  32.  
  33. void * drukuj2(void * arg)
  34. {
  35.  
  36. while(1) {
  37. pthread_mutex_lock(&lock);
  38. //printf("writing:\n");
  39. // printf("%s\n",shared_string);
  40. send(new_socket , shared_string, strlen(shared_string), 0 );
  41.  
  42. pthread_mutex_unlock(&lock);
  43. sleep(1);
  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. // Forcefully attaching socket to the port 8080
  59. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
  60. &opt, sizeof(opt)))
  61. {
  62. printf("setsockopt");
  63. exit(EXIT_FAILURE);
  64. }
  65. address.sin_family = AF_INET;
  66. address.sin_addr.s_addr = INADDR_ANY;
  67. address.sin_port = htons( PORT );
  68.  
  69. // Forcefully attaching socket to the port 8080
  70. if (bind(server_fd, (struct sockaddr *)&address,
  71. sizeof(address))<0)
  72. {
  73. printf("bind failed");
  74. exit(EXIT_FAILURE);
  75. }
  76. if (listen(server_fd, 3) < 0)
  77. {
  78. printf("listen");
  79. exit(EXIT_FAILURE);
  80. }
  81.  
  82. new_socket = accept(server_fd, (struct sockaddr *)&address,
  83. (socklen_t*)&addrlen);
  84.  
  85.  
  86. pthread_mutex_init(&lock, NULL) ;
  87. shared_string=(char*)malloc(SIZE*sizeof(char));
  88. printf("Nawiazano polaczenie\n");
  89. pthread_create(&pid1,NULL,drukuj1,NULL);
  90. pthread_create(&pid2,NULL,drukuj2,NULL);
  91. pthread_join(pid1,NULL);
  92. pthread_join(pid2,NULL);
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement