Advertisement
Guest User

Untitled

a guest
May 19th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. /* myloggerd.c
  2. * Source file for thread-lab
  3. * Creates a server to log messages sent from various connections
  4. * in real time.
  5. *
  6. * Student:
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. #include <sys/socket.h>
  15. #include <sys/un.h>
  16. #include <stdlib.h>
  17. #include <pthread.h>
  18. #include "message-lib.h"
  19. #define BUFSIZE 512
  20.  
  21. // forward declarations
  22. int usage( char name[] );
  23. // a function to be executed by each thread
  24. void * recv_log_msgs( void * arg );
  25.  
  26. // globals
  27. int log_fd; // opened by main() but accessible by each thread
  28.  
  29. void * recv_log_msgs( void * arg ){
  30.  
  31. // loops to receive messages from a connection;
  32. // when read_msg returns zero, terminate the loop
  33. // and close the connection
  34. printf("Thread launched");
  35. int c;
  36. char buf[BUFSIZE];
  37. int connection = *((int *) arg);
  38. while((c = read_msg(connection, buf, BUFSIZE)) > 0){
  39. write(log_fd, buf, c);
  40. }
  41. close_connection((long) arg);
  42. return NULL;
  43. }
  44.  
  45. int usage( char name[] ){
  46. printf( "Usage:\n" );
  47. printf( "\t%s <log-file-name> <UDS path>\n", name );
  48. return 1;
  49. }
  50.  
  51. int main( int argc, char * argv[] )
  52. {
  53. if ( argc != 3 )
  54. return usage( argv[0] );
  55. // open the log file for appending
  56. log_fd = open(argv[1], O_RDWR | O_APPEND| O_CREAT, 0666);
  57. //Having a pre-existing udslogger file sometimes makes the program not work properly
  58. unlink(argv[2]);
  59. // permit message connections
  60. int listener = permit_connections( argv[2] );
  61. pthread_t tid;
  62. // loop to accept message connections;
  63. // as each connection is accepted,
  64. // launch a new thread that calls
  65. // recv_log_msgs(), which receives
  66. // messages and writes them to the log file
  67. // when accept_next_connection returns -1, terminate the loop
  68. int connection;
  69. while((connection = accept_next_connection(listener)) != -1){
  70. pthread_create(&tid, NULL, recv_log_msgs, &connection);
  71. }
  72. // close the listener
  73. close(listener);
  74. // close the log file
  75. close(log_fd);
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement