Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 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 <time.h>
  8. #include <signal.h>
  9. #include <stdio.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include <unistd.h>
  13. #include <errno.h>
  14.  
  15. #define PORT 1300
  16.  
  17. void strdate(char *buffer, int len)
  18. {
  19. time_t now = time(NULL);
  20. struct tm *ptm = localtime(&now);
  21.  
  22. if (ptm == NULL) {
  23.  
  24. puts("The localtime() function failed");
  25. return;
  26. }
  27.  
  28. strftime(buffer, len, "%c\n", ptm);
  29.  
  30. }
  31.  
  32. void fimDeFilho(){
  33. int p=wait(NULL);
  34. printf("%d\n",p);
  35. }
  36.  
  37. int main(int argc, char const *argv[])
  38. {
  39. int server_fd, new_socket;
  40. struct sockaddr_in address;
  41.  
  42. int opt = 1; // for setsockopt() SO_REUSEADDR, below
  43. int addrlen = sizeof(address);
  44. char buffer[256];
  45.  
  46. // Creating socket file descriptor
  47. if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
  48. {
  49. perror("socket failed");
  50. exit(EXIT_FAILURE);
  51. }
  52.  
  53. // Forcefully attaching socket to the port 1300
  54. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
  55. &opt, sizeof(opt)))
  56. {
  57. perror("setsockopt failed");
  58. exit(EXIT_FAILURE);
  59. }
  60. address.sin_family = AF_INET;
  61. address.sin_addr.s_addr = INADDR_ANY;
  62. address.sin_port = htons( PORT );
  63.  
  64. // Bind the socket to the network address and port
  65. if ( bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0 )
  66. {
  67. perror("bind failed");
  68. exit(EXIT_FAILURE);
  69. }
  70. if (listen(server_fd, 3) < 0)
  71. {
  72. perror("listen failed");
  73. exit(EXIT_FAILURE);
  74. }
  75.  
  76. struct sigaction sa;
  77. sa.sa_sigaction=fimDeFilho;
  78. if(sigaction(SIGCHLD,&sa,NULL)==-1){
  79. perror("sigaction");
  80. }
  81. // Wait for a connection
  82. while(1){
  83. if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
  84. (socklen_t*)&addrlen))<0)
  85. {
  86. perror("accept failed");
  87. if(errno==EINTR){
  88. printf("interrupt by signal\n");
  89. continue;
  90. }
  91. else{
  92. exit(EXIT_FAILURE);
  93. }
  94. }
  95. int pid=fork();
  96.  
  97. if(pid==0){
  98. printf("Client connected.\n");
  99. sleep(10);
  100. strdate(buffer, 256);
  101. send(new_socket, buffer, strlen(buffer), 0 );
  102. printf("Date sent to client\n");
  103. return 0;
  104. }
  105. close(new_socket);
  106.  
  107. }
  108. return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement