Quipex icon

signalqueue

Quipex | PRO | 05/12/17 10:10:18 PM UTC | 0 ⭐ | 319 👁️ | Never ⏰ | []
C |

2.26 KB

|

None

|

0 👍

/

0 👎

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#define MSG_SZ_MAX 255
 
struct message{
    long mtype;
    pid_t pid;
    char mtext[MSG_SZ_MAX];
};
 
int descr;
struct message sendMsg, recieveMsg;
 
static void sigHandle(int signum);
 
 
void main(){
    descr = msgget(10, IPC_CREAT|0666);
    printf("descriptor : %d\n", descr);
    printf("PID : %d\n", getpid());
 
    if(signal(SIGINT, sigHandle) == SIG_ERR){
        perror("Can't handle a signal SIGINT.");
        exit(1);
    }
    if(signal(SIGUSR1, sigHandle) == SIG_ERR){
        perror("Can't handle a signal SIGUSR1.");
        exit(1);
    }
    if(signal(SIGTERM, sigHandle) == SIG_ERR){
        perror("Can't handle a signal SIGTERM.");
        exit(1);
    }
 
    printf("Receiver's PID : ");
    pid_t pidRes;
    scanf("%d", &pidRes);
 
    sendMsg.mtype = pidRes;
    sendMsg.pid = getpid();
    recieveMsg.mtype = getpid();
    
 
    if(descr==-1){
        perror("msgget");
    }
 
    while(1){
        
        strcpy(sendMsg.mtext, "[");
        //strcat(sendMsg.mtext, (char*)getpid);
        char senderpid[10];
        snprintf(senderpid, 10, "%ld", (long)getpid());
        strcat(sendMsg.mtext, senderpid);
        strcat(sendMsg.mtext, "] : ");
 
        /*
        *sendMsg.mtext += sprintf(sendMsg.mtext, "%s", "[");
        *sendMsg.mtext += sprintf(sendMsg.mtext, "%ld", (long)getpid());
        *sendMsg.mtext += sprintf(sendMsg.mtext, "%s", "] : ");*/
 
        char buf[MSG_SZ_MAX];
        /**
        *INPUT
        */
        scanf("%s", buf);
        strcat(sendMsg.mtext, buf);
        //fgets(buf, MSG_SZ_MAX, stdin);
        //*sendMsg.mtext += sprintf(sendMsg.mtext, "%s", buf);
 
        if(msgsnd(descr, &sendMsg, sizeof(struct message), 0) == -1){
            perror("msgsnd");
            exit(2);
        }
 
        while(1){
            if(msgrcv(descr, &recieveMsg, sizeof(struct message), getpid(), IPC_NOWAIT) != -1){
                printf("%s\n", recieveMsg.mtext);
            } else break;
        }
    }
}
 
static void sigHandle(int signum){
    if(signum == SIGUSR1){
        printf("\nOther process has been terminated.\n");
        exit(0);
    }
    if(signum == SIGINT){
        kill(recieveMsg.pid, SIGUSR1);
        msgctl(descr, IPC_RMID, 0);
        exit(0);
    }
    if(signum == SIGTERM){
        printf("\nSIGTERM has been received, terminated.\n");
        kill(recieveMsg.pid, SIGUSR1);
        msgctl(descr, IPC_RMID, 0);
        exit(0);
    }
}

Comments