How to send signal to server when client has closed connection in C

1.7k Views Asked by At

I want to create single side chat application using c and when reader(client) presses Ctrl+c, writer(server) should be closed.But problem is still I cant figure out how to sent signal to writer when reader presses Ctrl+c.

Please give any suggestion for this...

This is reader side code :

 #include<fcntl.h>
 #include<stdio.h>
 #include<sys/stat.h>
 #include<sys/types.h>
 #include<unistd.h>
 #include<string.h>
 #include<stdlib.h>
 #include<signal.h>
 #define max 1990
 int fu;
 void sigHadeler();

    int main(){
       struct stat sb;


       int fd;
       char* fifo="/home/man/shellScript/fifo";
       char buf[max];
       struct sigaction new_action, old_action;
       new_action.sa_handler = sigHadeler;
       sigemptyset (&new_action.sa_mask);
       new_action.sa_flags = 0; 
           if( sigaction (SIGINT, NULL, &old_action) == -1) 
         perror("Failed to retrieve old handle"); /Ctrl + C */

     if( sigaction (SIGINT, &new_action, NULL) == -1)/* set the new action */
      ("Failed to set new Handle");

             printf("Start conversation....\n");
      while(1){

     while(1){
       stat(fifo,&sb);

       if((sb.st_mode & S_IFMT)==S_IFIFO){

        fd=open(fifo,O_RDONLY);
        int re =read(fd,buf,max);
        buf[re]='\0';
        printf("read: %s\n",buf);

        close(fd);

    break;
    }
     }

      }

    return 0;
   }

    void sigHadeler(){
    char* fifo="/home/man/shellScript/fifo";
    printf("What have you done \n");
    write(fu,"0",strlen("0"));
    close(fu);
    unlink(fifo);
    exit(1);
    }

This is writer side code :

#include<fcntl.h>
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<signal.h>
#define max 1990

int main(){
    int fd;
    char* input;
    input = malloc(sizeof(char)*1000);
    char* fifo="/home/man/shellScript/fifo";
    printf("Enter string :");
    struct stat sb;
    mkfifo(fifo,0666);

        while(1){

        printf("Writing..\n");
        fgets(input,max,stdin);
        input[strlen(input)-1]='\0';
        fd=open(fifo,O_WRONLY| O_NONBLOCK);
        if(fd<=0){printf("Reader is closed or no readers ...\n");
            exit(1);    
        }

        write(fd,input,strlen(input));
        close(fd);
        while(1){
            stat(fifo,&sb);
            if((sb.st_mode & S_IFMT)==S_IFIFO){
            close(fd);
        }
        break;
    }
    }
unlink(fifo);
return 0;
}
0

There are 0 best solutions below