Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <time.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 qregister(int queue) {
- pid_t pid = getpid();
- struct message buf = {MSGJOINQ, pid, ""};
- char greetings[MSGSIZE];
- struct message hi = {MSG_TYPE_DATA, pid, ""};
- sprintf(hi.mtext, "hi from %d!", pid);
- if(msgsnd(queue, &buf, sizeof(pid_t), NO_FLAGS) == ERRCODE) {
- perror("msgsnd");
- return EXIT_FAILURE;
- }
- if(msgsnd(queue, &hi, strlen(hi.mtext) + 1 + sizeof(pid_t), NO_FLAGS) == ERRCODE) {
- perror("msgsnd");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int qleave(int queue) {
- pid_t pid = getpid();
- struct message buf = {MSGLEAVEQ, pid, ""};
- struct message bye = {MSG_TYPE_DATA, pid, "bye!"};
- if(msgsnd(queue, &bye, strlen(bye.mtext) + 1 + sizeof(pid_t), NO_FLAGS) == ERRCODE) {
- perror("msgsnd");
- return EXIT_FAILURE;
- }
- if(msgsnd(queue, &buf, sizeof(pid_t), NO_FLAGS) == ERRCODE) {
- perror("msgsnd");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int msggen(char *buf) {
- int length = rand() % (MSGSIZE - 2) + 1; //length from 1 to MSGSIZE-1
- int i;
- for(i = 0; i < length; ++i) {
- buf[i] = (char)(rand() % (END_CHAR - START_CHAR) + START_CHAR);
- }
- buf[length] = '\0';
- ++length;
- return length;
- }
- int qsndmsg(int queue) {
- pid_t pid = getpid();
- struct message buf = {MSG_TYPE_DATA, pid, ""};
- int i;
- printf("I'm %d\n", pid);
- int length;
- for(i = 0; i < COUNT_MESSAGES; ++i) {
- length = msggen(buf.mtext);
- if (length == 0){
- break;
- }
- printf("Send message: %s\n", buf.mtext);
- if(msgsnd(queue, &buf, length + sizeof(pid_t), NO_FLAGS) == ERRCODE) {
- perror("msgsnd");
- return EXIT_FAILURE;
- }
- sleep(SLEEP_TIME);
- }
- return EXIT_SUCCESS;
- }
- int main() {
- srand(time(NULL));
- key_t queueKey = ftok("master.c", PROJECT_PREFIX);
- if(queueKey == ERRCODE) {
- perror("ftok");
- return EXIT_FAILURE;
- }
- int queue;
- queue = msgget(queueKey, NO_FLAGS);
- if(queue == ERRCODE) {
- perror("msgget");
- return EXIT_FAILURE;
- }
- printf("Connected to queue\n");
- if(qregister(queue) != EXIT_SUCCESS) {
- return EXIT_FAILURE;
- }
- if(qsndmsg(queue) != EXIT_SUCCESS) {
- qleave(queue);
- return EXIT_FAILURE;
- }
- if(qleave(queue) != EXIT_SUCCESS) {
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement