View difference between Paste ID: CN8iTqry and AXEwe9sC
SHOW: | | - or go back to the newest paste.
1
#include <sys/types.h>
2-
#include <sys/ipc.h>
2+
3
#include <unistd.h>
4
#include <stdio.h>
5
#include <stdlib.h>
6
#include <signal.h>
7-
#include <string.h>
7+
8
 
9
struct message{
10
    long mtype;
11
    pid_t pid;
12
    char mtext[MSG_SZ_MAX];
13
};
14
 
15
int descr;
16
struct message sendMsg, recieveMsg;
17
 
18
static void sigHandle(int signum);
19
 
20
 
21
void main(){
22
    descr = msgget(10, IPC_CREAT|0666);
23
    if(descr==-1){
24
        perror("msgget");
25
    }
26
    
27
    printf("descriptor : %d\n", descr);
28
    pid_t myPID = getpid();
29
    printf("PID : %d\n", myPID);
30
 
31
    if(signal(SIGINT, sigHandle) == SIG_ERR){
32
        perror("Can't handle a signal SIGINT.");
33
        exit(1);
34
    }
35
    if(signal(SIGUSR1, sigHandle) == SIG_ERR){
36
        perror("Can't handle a signal SIGUSR1.");
37
        exit(1);
38
    }
39
    if(signal(SIGTERM, sigHandle) == SIG_ERR){
40
        perror("Can't handle a signal SIGTERM.");
41
        exit(1);
42
    }
43
   
44
    //WHERE TO SEND
45
    printf("Receiver's PID : ");
46
    pid_t receiverPID;
47
    scanf("%d", &receiverPID);
48
 
49
    //setting sending msg metainfo
50
    sendMsg.mtype = receiverPID;
51
    sendMsg.pid = myPID;
52
 
53
    //setting recieve msg metainfo
54-
54+
55
   
56
   
57
    fflush(stdout);
58
    if(fork() == 0){
59
        //printf("child's pid = %d\n", getpid());
60
        while(1){
61
            //printf("pid=%d,sending...\n", getpid());
62
 
63
            char buf[MSG_SZ_MAX];
64-
64+
65
            sprintf(sendMsg.mtext, "[%d] : %s", myPID, buf);
66
     
67
            if(msgsnd(descr, &sendMsg, sizeof(struct message), 0) == -1){
68
                perror("msgsnd");
69
                exit(2);
70
            }
71
        }
72
    } else {
73
        //printf("parent's pid = %d\n", getpid());
74
        while(1){
75
            //printf("pid=%d,receiving...\n", getpid());
76
 
77
            if(msgrcv(descr, &recieveMsg, sizeof(struct message), myPID, IPC_NOWAIT) >= 1){
78-
78+
79-
            if(msgrcv(descr, &recieveMsg, sizeof(struct message), myPID, IPC_NOWAIT) != -1){
79+
80
        }
81
    }
82
}
83
 
84
static void sigHandle(int signum){
85
    if(signum == SIGUSR1){
86
        printf("\nOther process has been terminated.\n");
87
        msgctl(descr, IPC_RMID, 0);
88
        exit(0);
89
    }
90
    if(signum == SIGINT){
91
        kill(recieveMsg.pid, SIGUSR1);
92
        msgctl(descr, IPC_RMID, 0);
93
        exit(0);
94
    }
95
}