Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <signal.h>
- #include <termios.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #define MSGSIZE 100
- #define STRUCTMSGSIZE (MSGSIZE + sizeof(pid_t))
- #define ERRCODE -1
- #define NO_FLAGS 0
- #define MSGJOINQ 1
- #define MSGLEAVEQ 2
- #define MSG_TYPE_DATA 3
- #define MSG_ALL_TYPES 0
- #define QUEUE_RIGHTS 0600
- #define PROJECT_PREFIX 97
- #define COUNT_MESSAGES 10
- #define START_CHAR 32
- #define END_CHAR 127
- #define SLEEP_TIME 1
- struct message {
- long mtype;
- pid_t pid;
- char mtext[MSGSIZE];
- };
- int qclose(int queue) {
- if(msgctl(queue,IPC_RMID,NULL) == ERRCODE) {
- perror("msgctl");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int qrecv(int queue) {
- struct message buf;
- int count = 0;
- do {
- ssize_t length;
- if((length = msgrcv(queue, &buf, STRUCTMSGSIZE, MSG_ALL_TYPES, NO_FLAGS)) == ERRCODE) {
- perror("msgrcv");
- return EXIT_FAILURE;
- }
- switch(buf.mtype) {
- case MSGJOINQ:
- ++count;
- printf("new sender %d\n", buf.pid);
- break;
- case MSGLEAVEQ:
- --count;
- printf("del sender %d\n", buf.pid);
- break;
- default:
- printf("process %d: %s\n", buf.pid, buf.mtext);
- }
- } while (count > 0);
- return EXIT_SUCCESS;
- }
- int main() {
- key_t queueKey = ftok("master.c", PROJECT_PREFIX);
- if(queueKey == ERRCODE) {
- perror("ftok");
- return EXIT_FAILURE;
- }
- int queue;
- queue = msgget(queueKey, IPC_CREAT | QUEUE_RIGHTS);
- if(queue == ERRCODE) {
- perror("msgget");
- return EXIT_FAILURE;
- }
- printf("Queue was created\n");
- if(qrecv(queue) != EXIT_SUCCESS) {
- qclose(queue);
- return EXIT_FAILURE;
- }
- if(qclose(queue) != EXIT_SUCCESS) {
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement