Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* myloggerd.c
- * Source file for thread-lab
- * Creates a server to log messages sent from various connections
- * in real time.
- *
- * Student:
- */
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include "message-lib.h"
- #define BUFSIZE 512
- // forward declarations
- int usage( char name[] );
- // a function to be executed by each thread
- void * recv_log_msgs( void * arg );
- // globals
- int log_fd; // opened by main() but accessible by each thread
- void * recv_log_msgs( void * arg ){
- // loops to receive messages from a connection;
- // when read_msg returns zero, terminate the loop
- // and close the connection
- printf("Thread launched");
- int c;
- char buf[BUFSIZE];
- int connection = *((int *) arg);
- while((c = read_msg(connection, buf, BUFSIZE)) > 0){
- write(log_fd, buf, c);
- }
- close_connection((long) arg);
- return NULL;
- }
- int usage( char name[] ){
- printf( "Usage:\n" );
- printf( "\t%s <log-file-name> <UDS path>\n", name );
- return 1;
- }
- int main( int argc, char * argv[] )
- {
- if ( argc != 3 )
- return usage( argv[0] );
- // open the log file for appending
- log_fd = open(argv[1], O_RDWR | O_APPEND| O_CREAT, 0666);
- //Having a pre-existing udslogger file sometimes makes the program not work properly
- unlink(argv[2]);
- // permit message connections
- int listener = permit_connections( argv[2] );
- pthread_t tid;
- // loop to accept message connections;
- // as each connection is accepted,
- // launch a new thread that calls
- // recv_log_msgs(), which receives
- // messages and writes them to the log file
- // when accept_next_connection returns -1, terminate the loop
- int connection;
- while((connection = accept_next_connection(listener)) != -1){
- pthread_create(&tid, NULL, recv_log_msgs, &connection);
- }
- // close the listener
- close(listener);
- // close the log file
- close(log_fd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement