Question

/* myloggerd.c * Source file for thread-lab * Creates a server to log messages sent from...

/* 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"

// 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

   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
  
   // permit message connections
          
   // 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
  
   // close the listener
  
   // close the log file

   return 0;
}

USE THIS MESSAGE-LIB LIBRARY

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/un.h>
#include <unistd.h>
#include "message-lib.h"

Prototypes

int accept_next_connection( int listener );
void close_connection( int connection );
void close_listener( int listener );
int permit_connections( char UDS_name[] );
int read_msg( int connection, char buffer[], int buffer_size );
int request_connection( char UDS_name[] );
int write_msg( int connection, char msg[] );

int accept_next_connection( int listener ){
   int clientfd= accept( listener, NULL, NULL );
   if ( clientfd == -1 )
       perror( "accept" );
   char buffer[9];
   char stop_msg[]= "--STOP--";
   int number= read_msg( clientfd, buffer, 8 );
   if ( strlen( stop_msg ) < number )
       number= strlen( stop_msg );
   if ( number > 0 ){
       if ( strncmp( buffer, stop_msg, number ) == 0 ){
           close( clientfd );
           return -1;
       }
   }
   return clientfd;
}

void close_connection( int connection ){
   close( connection );
}

void close_listener( int listener ){
   close( listener );
}

int permit_connections(char UDS_name[] ){
   int listenfd= socket( AF_UNIX, SOCK_STREAM, 0 );
   if ( listenfd == -1 ){
       perror( "socket failed" );
       return -1;
   }
   struct sockaddr_un addr;
   memset( &addr, 0, sizeof(addr) );
   addr.sun_family= AF_UNIX;
   strncpy( addr.sun_path, UDS_name, sizeof(addr.sun_path) - 1 );
   //printf( "Unlinking %s...\n", addr.sun_path );
   unlink( addr.sun_path );
   if ( bind( listenfd, (struct sockaddr *)&addr, sizeof(addr) ) == -1 ){
       perror( "bind failed" );
       close( listenfd );
       return -1;
   }
   // listen
   if ( listen( listenfd, SOMAXCONN ) == -1 ){
       perror( "listen failed" );
       close( listenfd );
       return -1;
   }
   return listenfd;
}

int read_msg( int connection, char buffer[], int buffer_size ){
   int number_bytes_received= recv( connection, buffer, buffer_size, 0 );
   if ( number_bytes_received == -1 )
       perror( "recv" );
   return number_bytes_received;
}

int request_connection( char UDS_name[] ){
   int clientfd= socket( AF_UNIX, SOCK_STREAM, 0 );
   if ( clientfd == -1 ){
       perror( "socket failed" );
       return -1;
   }
      
   struct sockaddr_un addr;
   memset( &addr, 0, sizeof(addr) );
   addr.sun_family= AF_UNIX;
   strncpy( addr.sun_path, UDS_name, sizeof(addr.sun_path) - 1 );
   //printf( "Connecting to uds:%s...\n", addr.sun_path );
   if ( connect( clientfd, (struct sockaddr *)&addr, sizeof(addr) ) == -1 ){
       perror( "connected failed" );
       return -1;
   }
   //write_msg( clientfd, "new" );
   char new_msg[]= "--NEW --";
   send( clientfd, new_msg, strlen(new_msg), 0 );
   return clientfd;
}

int write_msg( int connection, char msg[] ){
   return send( connection, msg, strlen(msg), 0 );  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

#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>

// forward declarations
int error_msg( char * msg );
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

// file descriptor for the client connection
int clientfd;
// variable for the size of the message received from the client connection
int read_size;
// char buffer for message from the client
char client_message[4000];
// struct for socket address and size
struct sockaddr_un socketname;
// socket file descriptor
int socketfd;

// Error logging helper function
int error_msg( char * msg ) {
printf( "%s\n", msg );
return -1;
}

// Helper function that accepts a client connection as an argument
void * recv_log_msgs( void * arg ) {
// loops to receive messages from a client;
// when the connection is closed by the client,
// close the socket
  
// get the client file descriptor from arguments
int clientfd= *((int *)arg);
  
// While there are still bytes to be read from the client, write the client message to the log
while( (read_size = recv(clientfd , client_message , 4000 , 0)) > 0 ) {
write(log_fd , client_message , strlen(client_message));
}

// print out message when client connection is closed
if(read_size == 0) {
puts("Connection Terminated");
}
// if there is a problem with the connection, call the error message helper function
else if(read_size == -1) {
return error_msg("Connection Failed");
}
  
// close client connection file description
close( clientfd );
return NULL;
}

// helper function for printing the usage information
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) {
// return usage if arguments aren't satisfactory
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);
  
// If there is a problem opening the file, call the error handling function
if ( log_fd == -1 ) {
error_msg("No such file");
return error_msg(argv[1]);

}

// create a server socket
// domain (i.e., family) is AF_UNIX
// type is SOCK_STREAM  
char * socketpath = argv[2];

// sets the domain to be AF_UNIX
socketname.sun_family = AF_UNIX;
strncpy(socketname.sun_path, (char *)socketpath, sizeof(socketname.sun_path));
// creates socket file descriptor
socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
  
// unlink the UDS path
unlink(socketpath);
  
// bind the server socket
bind(socketfd, (struct sockaddr *) &socketname, sizeof(struct sockaddr_un));
  
// listen
listen(socketfd , 3);
  
  
// loop to wait for 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

// forward declare the thread for the client connection
pthread_t client_thread;
  
// loop and wait for connections
while(1){
  
printf( "Waiting for a connection on UDS path %s...\n", argv[2] );
  
// accept connections from the client
clientfd = accept(socketfd, NULL, NULL);  
  
// create a new thread for each connection that comes in and call the helper function
pthread_create( &client_thread, NULL, recv_log_msgs, &clientfd );
}
  
  
// when the loop ends, close the listening socket
close(socketfd);
// close the log file
close(log_fd);

return 0;
}

Add a comment
Know the answer?
Add Answer to:
/* myloggerd.c * Source file for thread-lab * Creates a server to log messages sent from...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Modify the client server system program given below so that instead of sendto() and recvfrom(), you...

    Modify the client server system program given below so that instead of sendto() and recvfrom(), you use connect() and un-addresssed write() and read() calls. //Server.c #include #include #include #include #include #include #include #include #include #include # define PortNo 4567 # define BUFFER 1024 int main(int argc, char ** argv) { int ssd; int n; socklen_t len; char msg[BUFFER]; char clientmsg[BUFFER]; struct sockaddr_in server; struct sockaddr_in client; int max_iterations = 0; int count = 0, totalChar = 0, i = 0;...

  • IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two...

    IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two arguments (IP add & port no. of the concurrent Server with thread - conServThread.c). Similarly, modify the Server (conServThread.c) program to accept an argument which is the port number of the server to bind and listen to. Try these two updated programs (server and client) with a port number (e.g., hhmm6) with current time where hh is hours in 24-hour format and mm is...

  • C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in...

    C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in the comments. * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <strings.h> #define BUFFERT 512 #define BACKLOG 1 int create_server_socket (int port); struct sockaddr_in sock_serv,sock_clt; int main(int argc, char** argv){ int sfd, fd; unsigned int length = sizeof(struct sockaddr_in); long int n, m, count...

  • Run the code in Linux and provide the screenshot of the output and input #include <signal.h>...

    Run the code in Linux and provide the screenshot of the output and input #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> static void cleanup(); static void docleanup(int signum); static const char *SERVER_ADDR = "127.0.0.1"; static const int SERVER_PORT = 61234; static int cfd = -1; int main(int argc, char *argv[]) { struct sockaddr_in saddr; char buf[128]; int bufsize = 128, bytesread; struct sigaction sigact; printf("client starts running ...\n"); atexit(cleanup); sigact.sa_handler =...

  • For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will...

    For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will modifiy echoServer.c and echoClient.c programs (for the server's port# not fixed). (1) Modify echoServer.c program to take one argument (a port number) to be used for its listening port when it starts. (2) Modify echoClient.c program to take two arguments (server's IP address and Port number) to be used for its connection. (3) Find a port free for the server using netstat (see...

  • Modify the programs so that each program can both receive and send messages alternatively. Note that when you run the two programs, you should run them in two different windows ( terminals). Y...

    Modify the programs so that each program can both receive and send messages alternatively. Note that when you run the two programs, you should run them in two different windows ( terminals). You should be able to send messages from one to the other and terminate them by entering "end" //msgl.cpp / Here's the receiver program. / #include #include #include #1nclude #include <stdlib.h> <stdio.h> <string.h> <errno.h> <unistd.h> #include <sys/types.h> #include <sys/ipc.h> Winclude <sys/msg.h> struct my msg st f long int...

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • In C using the following 2 files to create a 3rd file that uses multiple threads...

    In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...

  • Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h>...

    Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> void do_ls(char []); int main(int argc,char *argv[]) { if(argc == 1) do_ls("."); else while(--argc){ printf("%s:\n",*++argv); do_ls(*argv); } } void do_ls(char dirname[]) { DIR *dir_ptr; struct dirent *direntp; if((dir_ptr = opendir(dirname)) == NULL) fprintf(stderr,"ls1:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) printf("%s\n",direntp->d_name); closedir(dir_ptr); } } ____________________________ code 2: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> void show_stat_info(char *,...

  • Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically...

    Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically what each line actually does? whats the function? whats the point? Don't tell me what the program does as a whole, I need to understand what each line does in this program. #include #include #include #include #include #define SERVER_PORT 5432 #define MAX_LINE 256 int main(int argc, char * argv[]) {    FILE *fp;    struct hostent *hp;    struct sockaddr_in sin;    char *host;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT