Quipex

msg1

May 12th, 2017
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/ipc.h>
  3. #include <sys/msg.h>
  4. #include <unistd.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <signal.h>
  9.  
  10. int descr;
  11. struct message m,k;
  12.  
  13. struct message{
  14.     long mtype;
  15.     pid_t pid;
  16.     char mtext[100];
  17. };
  18.  
  19. static void sigHandle(int signum);
  20.  
  21. void main(){
  22.     if(signal(SIGINT, sigHandle) == SIG_ERR){
  23.         perror("Can't handle a signal SIGINT.");
  24.         exit(1);
  25.     }
  26.     if(signal(SIGUSR1, sigHandle) == SIG_ERR){
  27.         perror("Can't handle a signal SIGUSR1.");
  28.         exit(1);
  29.     }
  30.     m.mtype = 1;
  31.     m.pid = getpid();
  32.     k.mtype = 2;
  33.     descr = msgget(100,IPC_CREAT|0666);
  34.     printf("descriptor : %d\n", descr);
  35.     printf("PID : %d\n", getpid());
  36.     if(descr==-1){
  37.         printf("msgget");
  38.     }
  39.     while(1){
  40.         strcpy(m.mtext, "[msg1] : ");
  41.         char buf[100];
  42.         scanf("%s", buf);
  43.         strcat(m.mtext, buf);
  44.         int res1=msgsnd(descr,&m,sizeof(struct message),0);
  45.         if(res1==-1){
  46.             printf("msgsnd");
  47.         }
  48.         int res2;
  49.         do{
  50.             res2=msgrcv(descr,&k,sizeof(struct message),2,IPC_NOWAIT);
  51.             if(res2!=-1){
  52.                 printf("%s\n",k.mtext);
  53.             }
  54.         }while(res2!=-1);
  55.     }
  56. }
  57.  
  58. static void sigHandle(int signum){
  59.     if(signum == SIGUSR1){
  60.         printf("Other pal has quited.\n");
  61.         exit(0);
  62.     }
  63.     if(signum == SIGINT){
  64.         printf("\nSIGINT has been received, terminated.\n");
  65.         kill(k.pid, SIGUSR1);
  66.         msgctl(descr, IPC_RMID, 0);
  67.         exit(0);
  68.     }
  69. };
Advertisement
Add Comment
Please, Sign In to add comment