#include #include #include #include #include #include #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); if(descr==-1){ perror("msgget"); } printf("descriptor : %d\n", descr); pid_t myPID = getpid(); printf("PID : %d\n", myPID); 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); } //WHERE TO SEND printf("Receiver's PID : "); pid_t receiverPID; scanf("%d", &receiverPID); //setting sending msg metainfo sendMsg.mtype = receiverPID; sendMsg.pid = myPID; //setting recieve msg metainfo recieveMsg.mtype = myPID; fflush(stdout); if(fork() == 0){ //printf("child's pid = %d\n", getpid()); while(1){ //printf("pid=%d,sending...\n", getpid()); char buf[MSG_SZ_MAX]; scanf("%s", buf); sprintf(sendMsg.mtext, "[%d] : %s", myPID, buf); if(msgsnd(descr, &sendMsg, sizeof(struct message), 0) == -1){ perror("msgsnd"); exit(2); } } } else { //printf("parent's pid = %d\n", getpid()); while(1){ //printf("pid=%d,receiving...\n", getpid()); if(msgrcv(descr, &recieveMsg, sizeof(struct message), myPID, IPC_NOWAIT) >= 1){ printf("%s\n", recieveMsg.mtext); } } } } static void sigHandle(int signum){ if(signum == SIGUSR1){ printf("\nOther process has been terminated.\n"); msgctl(descr, IPC_RMID, 0); exit(0); } if(signum == SIGINT){ kill(recieveMsg.pid, SIGUSR1); msgctl(descr, IPC_RMID, 0); exit(0); } }