Skip to content

Commit

Permalink
Working examples
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMutta committed Jun 12, 2024
1 parent 685245b commit 43e39d6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/xlink_client_local.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
#include <cstring>
#include <cstddef>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cassert>

#include "XLink/XLink.h"
#include "XLink/XLinkPublicDefines.h"
Expand Down Expand Up @@ -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<char *>(shared_mem_addr));

return 0;
}
33 changes: 33 additions & 0 deletions examples/xlink_server_local.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#include <cstring>
#include <cstddef>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cassert>

#include "XLink/XLink.h"
#include "XLink/XLinkPublicDefines.h"
Expand Down Expand Up @@ -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;
}

0 comments on commit 43e39d6

Please sign in to comment.