#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>
int descr;
struct message m,k;
struct message{
long mtype;
pid_t pid;
char mtext[100];
};
static void sigHandle(int signum);
void main(){
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);
}
m.mtype = 1;
m.pid = getpid();
k.mtype = 2;
descr = msgget(100,IPC_CREAT|0666);
printf("descriptor : %d\n", descr);
printf("PID : %d\n", getpid());
if(descr==-1){
printf("msgget");
}
while(1){
strcpy(m.mtext, "[msg1] : ");
char buf[100];
scanf("%s", buf);
strcat(m.mtext, buf);
int res1=msgsnd(descr,&m,sizeof(struct message),0);
if(res1==-1){
printf("msgsnd");
}
int res2;
do{
res2=msgrcv(descr,&k,sizeof(struct message),2,IPC_NOWAIT);
if(res2!=-1){
printf("%s\n",k.mtext);
}
}while(res2!=-1);
}
}
static void sigHandle(int signum){
if(signum == SIGUSR1){
printf("Other pal has quited.\n");
exit(0);
}
if(signum == SIGINT){
printf("\nSIGINT has been received, terminated.\n");
kill(k.pid, SIGUSR1);
msgctl(descr, IPC_RMID, 0);
exit(0);
}
};
Comments