Преглед на файлове

implemented a very simple malloc using mmap only

max преди 8 години
родител
ревизия
c96e6aa6f6
променени са 3 файла, в които са добавени 38 реда и са изтрити 6 реда
  1. 34 0
      src/myco-memory.c
  2. 2 4
      test/mycoagent.c
  3. 2 2
      test/worker.c

+ 34 - 0
src/myco-memory.c

@@ -16,14 +16,48 @@
 
 #include "myco-memory.h"
 
+#include <assert.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/mman.h>
+
 void *myco_malloc(size_t size) {
+    if (size == 0) {
+        return NULL;
+    }
+    size_t *pointer;
+    size_t length = size + sizeof(size);
+
+    pointer = mmap(0, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
+
+    *pointer = length;
+    return (void*)(&pointer[1]);
+
+/*
+    // Default malloc
     void *ptr;
     ptr = malloc(size);
     return ptr;
+*/
 }
 
 void myco_free(void *ptr) {
+    if (ptr == NULL) {
+        return;
+    }
+    size_t *pointer = (size_t*)ptr;
+    size_t length;
+
+    pointer--;
+    length = *pointer;
+
+    munmap((void*)pointer, length);
+
+/*
+    // Default free
     return free(ptr);
+*/
 }
 
 void *myco_calloc(size_t nmeb, size_t size) {

+ 2 - 4
test/mycoagent.c

@@ -20,14 +20,12 @@ int main() {
     while (myco_worker_is_running(worker_pid) == 0) {
             printf("%d is still alive.\n", worker_pid);
 
-
             // check for messages
             msg = myco_receive(message_queue_id);
-            printf("%s\n", msg.message);
-
-            myco_worker_terminate(worker_pid);
+            printf("%s", msg.message);
 
             sleep(1);
+
     }
 
     myco_agent_unregister_resource(message_queue_id, "RESOURCE_1");

+ 2 - 2
test/worker.c

@@ -28,8 +28,8 @@ int main(int argc, char **argv) {
 
 
     myco_free(resource_pointer);
-    while (1)
-        sleep(1);
+    sprintf(msg.message, "FREED MEMORY AT %p\n", resource_pointer);
+    myco_send(message_queue_id, msg);
 
     printf("Worker is shutting down\n");