|
| 1 | +#include <stdlib.h> |
| 2 | +#include <stdio.h> |
| 3 | +#include <string.h> |
| 4 | +#include <time.h> |
| 5 | +#include <unistd.h> |
| 6 | +#include <sys/stat.h> |
| 7 | +#include <sys/types.h> |
| 8 | +#include <errno.h> |
| 9 | +#include <mqueue.h> |
| 10 | + |
| 11 | +#define Q_NAME "/ch6_ipc" |
| 12 | +#define MAX_SIZE 1024 |
| 13 | +#define M_EXIT "done" |
| 14 | +#define SRV_FLAG "-producer" |
| 15 | + |
| 16 | +int main(int argc, char *argv[]) |
| 17 | +{ |
| 18 | + if (argc < 2) |
| 19 | + { |
| 20 | + producer(); |
| 21 | + } |
| 22 | + else if (argc >= 2 && 0 == strncmp(argv[1], SRV_FLAG, strlen(SRV_FLAG))) |
| 23 | + { |
| 24 | + producer(); |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + consumer(); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +int producer() |
| 33 | +{ |
| 34 | + mqd_t mq; |
| 35 | + struct mq_attr attr; |
| 36 | + char buffer[MAX_SIZE]; |
| 37 | + int msg, i; |
| 38 | + |
| 39 | + attr.mq_flags = 0; |
| 40 | + attr.mq_maxmsg = 10; |
| 41 | + attr.mq_msgsize = MAX_SIZE; |
| 42 | + attr.mq_curmsgs = 0; |
| 43 | + |
| 44 | + mq = mq_open(Q_NAME, O_CREAT | O_WRONLY, 0644, &attr); |
| 45 | + |
| 46 | + /* seed random */ |
| 47 | + srand(time(NULL)); |
| 48 | + |
| 49 | + i = 0; |
| 50 | + while (i < 500) |
| 51 | + { |
| 52 | + msg = rand() % 256; |
| 53 | + memset(buffer, 0, MAX_SIZE); |
| 54 | + sprintf(buffer, "%x", msg); |
| 55 | + printf("Produced: %s\n", buffer); |
| 56 | + fflush(stdout); |
| 57 | + mq_send(mq, buffer, MAX_SIZE, 0); |
| 58 | + i=i+1; |
| 59 | + } |
| 60 | + memset(buffer, 0, MAX_SIZE); |
| 61 | + sprintf(buffer, M_EXIT); |
| 62 | + mq_send(mq, buffer, MAX_SIZE, 0); |
| 63 | + |
| 64 | + mq_close(mq); |
| 65 | + mq_unlink(Q_NAME); |
| 66 | + return 0; |
| 67 | +} |
| 68 | + |
| 69 | +int consumer() |
| 70 | +{ |
| 71 | + struct mq_attr attr; |
| 72 | + char buffer[MAX_SIZE + 1]; |
| 73 | + ssize_t bytes_read; |
| 74 | + mqd_t mq = mq_open(Q_NAME, O_RDONLY); |
| 75 | + if ((mqd_t)-1 == mq) { |
| 76 | + printf("Either the producer has not been started or maybe I cannot access the same memory...\n"); |
| 77 | + exit(1); |
| 78 | + } |
| 79 | + do { |
| 80 | + bytes_read = mq_receive(mq, buffer, MAX_SIZE, NULL); |
| 81 | + buffer[bytes_read] = '\0'; |
| 82 | + printf("Consumed: %s\n", buffer); |
| 83 | + } while (0 != strncmp(buffer, M_EXIT, strlen(M_EXIT))); |
| 84 | + |
| 85 | + mq_close(mq); |
| 86 | + return 0; |
| 87 | +} |
0 commit comments