From 43e39d6b7da8e3d455e03432e4e3073c2bf0251a Mon Sep 17 00:00:00 2001 From: Filippo Mutta Date: Wed, 12 Jun 2024 17:54:06 +0200 Subject: [PATCH] Working examples --- examples/xlink_client_local.cpp | 29 +++++++++++++++++++++++++++++ examples/xlink_server_local.cpp | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/examples/xlink_client_local.cpp b/examples/xlink_client_local.cpp index 3865623..27d729c 100644 --- a/examples/xlink_client_local.cpp +++ b/examples/xlink_client_local.cpp @@ -1,5 +1,12 @@ #include #include +#include +#include +#include +#include +#include +#include +#include #include "XLink/XLink.h" #include "XLink/XLinkPublicDefines.h" @@ -27,5 +34,27 @@ int main(int argc, const char** argv){ printf("Connecting wasn't successful\n"); return 1; } + + streamPacketDesc_t *packet; + + auto s = XLinkOpenStream(0, "test", 1024); + assert(s != INVALID_STREAM_ID); + auto r = XLinkReadData(s, &packet); + assert(r == X_LINK_SUCCESS); + + long received_fd = *(long*)packet->data; + printf("Received fd: %d\n", received_fd); + + // Map the shared memory + void *shared_mem_addr = + mmap(NULL, 4096, PROT_READ, MAP_SHARED, received_fd, 0); + if (shared_mem_addr == MAP_FAILED) { + perror("mmap"); + return 1; + } + + // Read and print the message from shared memory + printf("Message from Process A: %s\n", static_cast(shared_mem_addr)); + return 0; } diff --git a/examples/xlink_server_local.cpp b/examples/xlink_server_local.cpp index d9be841..a5a4126 100644 --- a/examples/xlink_server_local.cpp +++ b/examples/xlink_server_local.cpp @@ -1,5 +1,11 @@ #include #include +#include +#include +#include +#include +#include +#include #include "XLink/XLink.h" #include "XLink/XLinkPublicDefines.h" @@ -28,5 +34,32 @@ int main(int argc, const char** argv){ return 1; } + const char *shm_name = "/my_shared_memory"; + long shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666); + if (shm_fd < 0) { + perror("shm_open"); + return 1; + } + ftruncate(shm_fd, 4096); + + void *addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); + if (addr == MAP_FAILED) { + perror("mmap"); + close(shm_fd); + shm_unlink(shm_name); + return 1; + } + + // Write a message to the shared memory + const char *message = "Hello from Process A!"; + memcpy(addr, message, strlen(message) + 1); + + printf("Shm FD: %d\n", shm_fd); + + auto s = XLinkOpenStream(0, "test", 1024); + assert(s != INVALID_STREAM_ID); + auto w = XLinkWriteFd(s, &shm_fd); + assert(w == X_LINK_SUCCESS); + return 0; }