Skip to content

Instantly share code, notes, and snippets.

@d3x0r
Created October 28, 2018 02:11
Show Gist options
  • Save d3x0r/eeb225d17b79d74bfad1eca72aac279a to your computer and use it in GitHub Desktop.
Save d3x0r/eeb225d17b79d74bfad1eca72aac279a to your computer and use it in GitHub Desktop.
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
typedef struct process_node {
int key;
char process_command[64];
} process_node;
typedef struct process_table {
int max_size;
int count;
process_node **nodes;
} process_table;
process_table *t;
// Return simple hash for placing key in table.
int hash(int key)
{
return key % t->max_size;
}
// Creates shared memory with mmap
void* create_shared_memory(size_t size)
{
// Readable and writable.
int protection = PROT_READ | PROT_WRITE;
// ANONYMOUS: Only child process can access memory (no third parties).
// SHARED : Other processes can access it.
int visibility = MAP_SHARED | MAP_ANONYMOUS;
return mmap(NULL, size, protection, visibility, 0, 0);
}
// Creates new process table
process_table *process_table_create(void)
{
process_table *tmp = (process_table *)create_shared_memory(sizeof(process_table));
tmp->max_size = 128;
tmp->count = 0;
tmp->nodes = (process_node **)create_shared_memory(sizeof(process_table *) * tmp->max_size);
return tmp;
}
// Initialize process table and assign it to global var.
void process_table_init(void)
{
t = process_table_create();
}
// Creates new process node
process_node *process_node_init(int key, char *process_command)
{
process_node *n = (process_node *)create_shared_memory(sizeof(process_node));
n->key = key;
strncpy(n->process_command, process_command, 64);
return n;
}
// Inserts process node into process table.
void process_table_insert(process_node *n)
{
int index = hash(n->key);
while(t->nodes[index] != 0 && t->nodes[index]->key != -1) {
index++;
index %= t->max_size;
}
t->count++;
t->nodes[index] = n;
}
// Print process table.
void process_table_print(void)
{
int i;
for(i = 0; i < t->max_size; i++) {
if(t->nodes[i] != NULL) {
printf("%d %s\n", t->nodes[i]->key, t->nodes[i]->process_command);
}
}
}
void process_table_clean(void)
{
int i;
for(int i = 0; i < t->max_size; i++) {
if(t->nodes[i] != 0) {
munmap(t->nodes[i], sizeof(t->nodes[i]));
}
}
munmap(t->nodes, sizeof(t));
munmap(t, sizeof(t));
}
int main()
{
t = create_shared_memory(sizeof(process_table));
process_table_init();
process_table_insert( process_node_init(1, "hello") );
printf("%d \n", getpid());
int pid = fork();
if (pid == 0) {
process_table_print();
process_table_insert( process_node_init(2, "world") );
exit(0);
} else {
sleep(3);
process_table_print();
}
process_table_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment