libshmemq/examples/raw_sender.c

120 lines
2.9 KiB
C
Raw Normal View History

2020-12-12 11:40:16 +00:00
#include "raw.h"
#define _POSIX_C_SOURCE 200809L
#include <shmemq.h>
2020-12-12 11:40:16 +00:00
#include <assert.h>
#include <fcntl.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
static const char nullstr[] = "Hello, World!";
int main()
{
printf("Create queue.\n");
2020-12-12 11:40:16 +00:00
2020-12-13 17:39:02 +00:00
enum ShmemqError shmemq_error;
2020-12-13 15:51:28 +00:00
Shmemq shmemq = shmemq_new("/buffer1", false, &shmemq_error);
2020-12-12 11:40:16 +00:00
assert(shmemq_error == SHMEMQ_ERROR_NONE);
assert(shmemq != NULL);
2020-12-12 11:40:16 +00:00
struct Queue *const queue = (void*)shmemq->buffer;
2020-12-12 11:40:16 +00:00
printf("Initialize queues.\n");
2020-12-12 18:26:29 +00:00
size_t buffer1_offset = queue->read_offset;
2020-12-12 11:40:16 +00:00
for (;;) {
2020-12-12 17:25:41 +00:00
const struct Message *const message = (struct Message*)queue->data + buffer1_offset;
2020-12-12 11:40:16 +00:00
if (message->magic != BUFFER1_MAGIC) break;
2020-12-12 17:25:41 +00:00
if (message->size > BUFFER1_SIZE - sizeof(struct Queue)) {
2020-12-12 11:40:16 +00:00
printf("Message too big.\n");
goto finalize;
}
2020-12-12 17:25:41 +00:00
if (message->size > BUFFER1_SIZE - sizeof(struct Queue) - buffer1_offset) {
2020-12-12 11:40:16 +00:00
printf("Buffer return.\n");
buffer1_offset = 0;
continue;
}
buffer1_offset += message->size;
}
printf(
"REPL commands:\n"
" x - exit\n"
" f - send finish message\n"
" 1 - send 1 byte\n"
" 0 - send null-terminated string\n"
);
printf("REPL.\n");
for (;;) {
const char chr = getchar();
if (chr == '\n') continue;
if (chr == 'x') {
printf("Command: exit.\n");
break;
}
2020-12-12 17:25:41 +00:00
struct Message *message = (struct Message*)queue->data + buffer1_offset;
2020-12-12 11:40:16 +00:00
switch (chr) {
case 'f':
{
const size_t size = sizeof(*message);
buffer1_offset += size;
message->type = FINISH;
message->size = size;
message->magic = BUFFER1_MAGIC;
}
break;
case '1':
{
const size_t size = sizeof(*message) + sizeof(unsigned char);
buffer1_offset += size;
*(unsigned char*)message->data = 123;
message->type = ONEBYTE;
message->size = size;
message->magic = BUFFER1_MAGIC;
}
break;
case '0':
{
const size_t size = sizeof(*message) + strlen(nullstr) + 1;
buffer1_offset += size;
strcpy((char*)message->data, nullstr);
message->type = NULLSTR;
message->size = size;
message->magic = BUFFER1_MAGIC;
}
break;
default:
printf("Unknown command: '%c'\n", chr);
}
}
finalize:
printf("Destroy queue.\n");
2020-12-12 11:40:16 +00:00
2020-12-13 17:33:08 +00:00
shmemq_delete(shmemq, NULL);
2020-12-12 11:40:16 +00:00
return 0;
}