r/cprogramming • • 6m ago

Simple connection pool in C

2 Upvotes

Hello, C community, while working on arena allocator for my in-memory database kevue (KEy-ValUE), I came to conclusion that memory management with arenas is not that trivial, in most cases you can't just allocate a big chunk of memory and forget about it. For example, a TCP server is a long running program, it should accept, manage and close connections, allocate and deallocate memory for connection metadata. With standard allocators like malloc, it seems trivial (lol) to manage memory: you malloc on accept and free on connection close, after that, you dont care what happens to freed pointer, everything is managed by magical malloc. With arenas the situation is different: it is you, the programmer, who asks for memory and it is your responsibility to return it back. So, I faced the reality of my previous design not being sutiable for arena allocators because the free operation in arenas simply doesn't exist - we allocate once and dealocate once, all intermediate frees are no-ops. Of course there are ways to fix this "problem" with arena but I prefer to keep it simple until I really need sophisticated solutions.

So, how can we manage connections without having to allocate and deallocate them constantly? Right, we need to create a pool of pre allocated connections to reuse them insted of destroying!

The API of the pool is simple: it will have only four methods:

ConnectionPool *connection_pool_create(Allocator *ma);

Connection *connection_pool_get(ConnectionPool *pool);

bool connection_pool_put(ConnectionPool *pool, Connection *c);

void connection_pool_destroy(ConnectionPool *pool);

The signatures of these functions are self-explanatory: you create some connection storage, get connections from it, put them back, repeat, and when you no longer need this pool (e.g. server is stopped), you destroy it. Sounds very easy but how it works under the hood?

First of all, ConnectionPool structure:

typedef struct ConnectionPool   ConnectionPool;

struct ConnectionPool {
    ConnList        conn_list;
    FreeConnList    free_list;
    u64             chunk_size;
    Allocator       *ma;
};

And other stuff:

struct Connection {
    u64      id;
/* metadata */
};


typedef struct ConnList {
    Connection **ptr;
    u64          len;
    u64          cap;
} ConnList;

typedef struct FreeConnList {
    u64 *ptr;
    u64  len;
    u64  cap;
} FreeConnList;

ConnList stores the list of all connections ever allocated for this pool, FreeConnList stores information about connections currently available for reuse. In my case, both these fields are dynamic arrays (hey, tsoding!). ConnList is an array of pointers to allocated Connection structs, FreeConnList store indexes of these array, but only for free connections. Each connection has an identificator that is also equal to index in connection list array. So far, so good. But what about chunk_size? I forgot to mention that out pool is dynamic meaning that it can grow and maybe even shrink depending on load! The chunk_size is how much the pool size changes, a granularity.

Let's create out connection pool by initializing and populating these structures:

ConnectionPool *connection_pool_create(Allocator *ma){

/* Allocate memory for pool itself */
ConnectionPool *pool = ma->malloc(sizeof(*pool), ...);

/* how many connections we need currently */
u64 chunk_size = 128;
pool->chunk_size = chunk_size;

/* Allocate memory for connection structs */
Connection *conns = ma->malloc(chunk_size * sizeof(*conns), ...);
for (u64 i = 0; i < chunk_size; i++) {
/* Populate structs with data here, set id equal to i */
}

/* Initialize connection list */
dyna_init(ma, &pool->conn_list, pool->chunk_size);

/* Copy connections pointers to dynamic array */
Connection **dst = pool->conn_list.ptr + pool->conn_list.len;
for (u64 i = 0; i < chunk_size; i++) dst[i] = &conns[i];
pool->conn_list.len += chunk_size;

/* The same way init free list and copy indexes, initially all are free */
/* return */
return pool;
}

But wait, why we need to copy pointers to another array, if conns array already has all information? The reason is that we maybe need to grow our pool in the future and all existing connections should remain stable and valid. That means we cant simple reallocate conns especially within our arena. What we do instead is use conn list array is a storage for all future mallocs, it is reallocation but in a centralized place we control, lets see a get operation to understand it:

Connection *connection_pool_get(ConnectionPool *pool)
{
 /* happy path, we found connection in a free list 0(1) complexity */
    if (pool->free_list.len > 0) {
        u64 cidx = dyna_pop(&pool->free_list);
        return pool->conn_list.ptr[cidx];
    }
/* if free list is empty, that means we need more connections right now! */
u64 chunk_size = pool->chunk_size;

/* increase connection list array by another chunk size */
dyna_expand(pool->ma, &pool->conn_list, chunk_size);

/ * malloc new connections */
Connection *conns = pool->ma->malloc(chunk_size * sizeof(*conns), ...);

/* save new index */
u64 last_idx = pool->conn_list.len;

/* Populate structs with data here, set id equal to i + last_idx */

/ * populate dynamic arrays like we did during create but now starting from last_idx */

/* return connection from newly allocated list */
return c;
}

So, we allocated a new chunk of connecitons, added them to lists, and returned connection to caller. On next get we again on happy path.

Now let's look at put opetation (it surprasingly very simple):

bool connection_pool_put(ConnectionPool *pool, Connection *c)
{
    if (c->id >= pool->conn_list.len) return false;
    dyna_append(pool->ma, &pool->free_list, c->id);
    return true;
}

Just append connection id (index) to free list, thats it.

Now destroy:

void connection_pool_destroy(ConnectionPool *pool)
{
    for (u64 i = 0; i < pool->conn_list.len; i += pool->chunk_size) {
        pool->ma->free(pool->conn_list.ptr[i], ...);
    }
   dyna_deinit(pool->ma, &pool->free_list);
   dyna_deinit(pool->ma, &pool->conn_list);
   pool->ma->free(pool, pool->ma->ctx);
}

It looks simple except for the first for loop: here we deallocate only starts of all allocated conns, and we know where these starts are just by adding chunk size, standard malloc will be happy.

So, now we have get and put with O(1) complexity and need no worry to individually manage connections. The only missing part is shrinkage of the pool, in the current design it only grows and doesn't take into accout load fluctuations. The simplest approach would be to assume that someday all connections will return to free list and we will have an opportunity to deallocate chunks, see below:

bool connection_pool_put(ConnectionPool *pool, Connection *c)
{
    if (c->id >= pool->conn_list.len) return false;
    dyna_append(pool->ma, &pool->free_list, c->id);
    if (pool->conn_list.len > pool->chunk_size && pool->free_list.len == pool->conn_list.len) {
/ * deallocate all chunks but very first, shrink arena, etc */
}
    return true;
}

We check for conn_list length first because it doesn't make sense to destroy first chunk of pointers, but all other can be freed.

This is connection pool is not thread safe but adding locks around each operation should help. In my case I think i dont need thread safety because each thread in my server has separate connection pool and even separate allocator, only accesses to hashmap are thread safe.

Suggestions and corrections are welcome, as a beginner in C I obviously can't be very smart or efficient and the design presented here is not new, I basically was looking for simple solution and rediscovered it based on my current needs, who knows may be someone wil find it helpful Thanks!


r/cprogramming • • 3h ago

Borrow Cpp

0 Upvotes

Hey everyone!

I've been working on an open-source C++ library called borrow++.

The goal is to explore safer and more convenient memory management in modern C++, with a focus on ownership and borrowing concepts.

It's still an early project, and I'd love to get feedback from other C++ developers.

If you're interested, here's the repository:

https://github.com/aberamaneza/borrow.cpp

Any feedback, suggestions, or criticism are welcome!


r/cprogramming • • 23h ago

Coding a satisfying animation in C / Raylib

Thumbnail
youtu.be
8 Upvotes

Tons of YouTube channels are making really nice physics animations. Most of them look quite similar, and I suppose everyone's vibecoding them. Anyways, vibecoding or not, I love these animations, and I want to learn how to code them myself.

The problem is that most of these channels don't really share the implementation details.

Well... in this video, I'm building one from scratch. So, if you want to learn how to program these kinds of animations, I'm providing the clean source code and the full coding session so you can follow along.

AI Disclaimer:
I didn't use AI

Full project:
https://github.com/FractalCodeRicardo/dopamine-programming/tree/main/squares-balls

Code:

#include <raylib.h>
#include <raymath.h>
#include <stdbool.h>
#include "time.h"

#define screenSize 800.0
#define gridSize  25.0

typedef struct{ 
  Vector2 pos;
  Vector2 dir;
  Color color;
} Ball;

typedef struct{ 
  Vector2 pos;
  Color color;
  bool empty;
  int life;
} Square;

typedef struct{ 
  Ball items[2500];
  int size;
} Balls;

typedef struct{ 
  Square items[2500];
  int size;
} Squares;

Squares squares;
Balls balls;

float squareSize;
float ballSize;

Sound sound;

Color RandomColor() {
  Color colors[] = {
    GREEN, YELLOW, RED, BLUE, PURPLE,
    ORANGE, BROWN, SKYBLUE, DARKPURPLE, MAGENTA
  };

  int index = GetRandomValue(0, 9);
  return colors[index];
}

Vector2 RandomDir() {
  float sign[] = {1 , -1};

  float x = GetRandomValue(5, 10) / 10.0;
  float y = GetRandomValue(5, 10) / 10.0;
  
  x = x * sign[GetRandomValue(0, 1)];
  y = y * sign[GetRandomValue(0, 1)];

  return (Vector2) {
    x, y
  };
}

void InitSquares() {
  squareSize = screenSize / gridSize;
  
  int center = gridSize / 2;
  for(int y = 0; y < gridSize; y++) {
    for(int x = 0; x < gridSize; x++) {

      bool empty = false;
      if (x >= center - 2 && x <= center + 2)
        if (y >= center - 2 && y <= center + 2)
          empty = true;


      int i = y * gridSize + x;

      squares.items[i] = (Square) {
        (Vector2) { 
          x * squareSize,
          y * squareSize
        } ,
        RandomColor(),
        empty,
        5
      };

      squares.size++;
    }
  }
}

void InitBalls() {
  ballSize = (screenSize / gridSize) / 2;
  
  float center = screenSize / 2;
  for(int i = 0; i < 4; i++) {
    balls.items[i] = (Ball) {
      (Vector2) { center, center} ,
      RandomDir(),
      RandomColor()
    };

    balls.size++;
  }

}

void Init() {
  InitSquares();
  InitBalls();
}

void DrawSquares() {
  for (int i = 0; i <squares.size; i++) {
    Square s = squares.items[i];

    if (s.empty)
      continue;
    
    DrawRectangle(
        s.pos.x + 1,
        s.pos.y + 1,
        squareSize - 1, 
        squareSize - 1, 
        s.color);
  }
}

void DrawBalls() {
  for (int i = 0; i <balls.size; i++) {
    Ball b = balls.items[i];
    
    DrawCircle(
        b.pos.x ,
        b.pos.y,
        ballSize / 2,
        b.color
        );
  }
}

void Draw() {
  DrawSquares();
  DrawBalls();
}

void ChangeSquareColor(Square *s) {
  s -> color.a = s -> color.a - 10;
}

void AddBall(Vector2 pos) {
  if (balls.size >= 1000)
    return;

  balls.items[balls.size] = (Ball) {
    pos ,
    RandomDir(),
    RandomColor()
  };

  balls.size ++;
}

void HandleCollision(Ball *b) {

  Rectangle ballRect = (Rectangle) {
    b -> pos.x - ballSize/2,
    b -> pos.y - ballSize/2,
    ballSize,
    ballSize,
  };

  for(int i = 0; i < squares.size; i++) {
    Square *s = &squares.items[i];

    if (s -> empty)
      continue;

    Rectangle squareRect = (Rectangle) {
      s -> pos.x,
      s -> pos.y,
      squareSize,
      squareSize,
    };

    Rectangle collision = GetCollisionRec(ballRect, squareRect);

    if (collision.width <= 0 ||
        collision.height <= 0)
      continue;

    if (collision.width < collision.height)
      b -> dir.x *= -1;
    else
      b -> dir.y *= -1;

    s -> life--;
    ChangeSquareColor(s);

    if (s -> life <= 0) {
      s -> empty = true;
      AddBall(b -> pos);
    }

    PlaySound(sound);

    return;

  }
}

void MoveBalls() {
  for(int i = 0; i < balls.size; i++) {
    Ball *b = &balls.items[i];
    b -> pos = Vector2Add(b -> pos, b -> dir);
    HandleCollision(b);
  }
}

void Update() {
  MoveBalls();
}

int main() {
  SetRandomSeed(time(NULL));
  Init();
  SetTargetFPS(200);
  InitAudioDevice();
  sound = LoadSound("jump.wav");
  SetSoundVolume(sound, 0.1f);
  InitWindow(screenSize, screenSize, "Squares/Balls");

  while(!WindowShouldClose()) {
    BeginDrawing();
    ClearBackground(BLACK);
    Draw();
    Update();
    EndDrawing();
  }
  CloseWindow();
}

r/cprogramming • • 23h ago

ភាសា​ C++ Part4: 6 String Exercises .

Thumbnail
youtube.com
0 Upvotes

r/cprogramming • • 1d ago

Help with seed generation for RNG.

Thumbnail reddit.com
1 Upvotes

r/cprogramming • • 1d ago

Thoughts on safe-c

10 Upvotes

Has anyone here come across the safe-c project? If so, what do you think of it? If not, do you think a project like this could actually make C (and C++) safer and more attractive in certain fields? Curious to hear what people think.


r/cprogramming • • 3d ago

HimitsuObfuscator: Whitelist-driven C/C++ obfuscator with LLVM 17

Thumbnail
github.com
1 Upvotes

r/cprogramming • • 4d ago

Good ways to crashcourse C quickly?

20 Upvotes

I am in the first semester of university and I have to take a C programming Class. the first test is in about 2 1/2 weeks and I just cant understand C for the life of me.(Its a first of two chances but still,It'd be great to have less worries in January/February)

I had fallen behind due to the fact the class moved very quickly since basically everyone already knew how to code and having to shift my focus for math tests.

I dont even know why, I just go blank once I see the empty page infront of me. I know which loops i should use when--technically-- and the datatyps for the most but from Arrays on It just didn't click anymore for some reason.

I know this sounds pathetic and Im not sure if this is the right place to ask but Is there any way to like get yourself to finally absorb the syntax and stuff?

I always get told its "just practice,keep coding stuff and make yourself easy programs and build from there" but then after I look at the assignments i was given and it feels like i studied 2+2=4 for a Real Analysis exam.

Are there any Books,videos, anything I could binge?

I always see how people "Learn C in only Xy hours" online but cant find any media that makes that seem humanly possible.

Any help is appreciated,thanks!


r/cprogramming • • 3d ago

Added a built-in test runner (flint test) to my C/C++ build system & package manager

Thumbnail
github.com
6 Upvotes

I’ve been working on flint, a lightweight, Git-native C/C++ build system and package manager written in pure C. Just shipped a new update that adds a native test engine so you don't need extra build scripts or external runners just to compile and run unit tests.

How it works:

  • Drop your C/C++ test files into a tests/ directory and prefix them with test_ (e.g., test_math.c, test_parser.cpp).

  • Run flint test to automatically discover, compile, and execute each test file one by one.

  • Standard executable and library builds automatically ignore tests/test_*, keeping production builds clean without manual exclusions.

my-project/

    src/

         main.c

    tests/

        test_math.c

        test_utils.cpp

Repo: https://github.com/mainak55512/flint


r/cprogramming • • 3d ago

How can i start c language

0 Upvotes

I am not a complete beginner. I have some knowledge later i stopped due to some reasons now i want to start please give some advice.


r/cprogramming • • 4d ago

I built CLAP to make it easier to compile a C file on Windows

4 Upvotes

I maintain CLAP, an open-source command-line frontend for C and C++. The use case is a small C program on a fresh Windows machine. With Python installed, you can install CLAP with `python -m pip install clap-compiler` and build a local `main.c` with `clap build main.c -o hello`. If needed, CLAP downloads a pinned Zig/Clang toolchain on the first build. It also supports multi-file projects and CMake.

I’d like feedback from people who teach or learn C on Windows. What would you expect a tool like this to show when the first build fails, and what would make the compiler setup easier to understand?

Source and examples (MIT): https://github.com/BRATAN-CORP/clap


r/cprogramming • • 4d ago

I Coded a classic Kaleidoscope using C, Raylib and GLSL

Thumbnail
youtu.be
6 Upvotes

I follow these steps:

  1. First, I split the screen into slices (like a pizza) using polar coordinates.
  2. Then, I create a well-known pattern in fractal shaders: sin(x) * sin(y), inside each slice.
  3. Next, I add a color palette to generate some nice colors.
  4. Finally, I use time as a parameter in different parts of the shader to animate both the pattern and the colors.

Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/kaleidoscope

C part

#include <raylib.h>

#define size 800

float time = 0.0;
int main() {

  InitWindow(size, size, "Kaleidoscope");
  
  Shader shader = LoadShader(0, "kaleidoscope.glsl");
  int timeLoc = GetShaderLocation(shader, "time");
  
  while(!WindowShouldClose()) {
    
    time = GetTime();
    SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);

    BeginDrawing();
      ClearBackground(BLACK);
      BeginShaderMode(shader);
        DrawRectangle(0, 0, size, size, BLACK);
      EndShaderMode();
    EndDrawing();
  }

  CloseWindow();
}

Shader part

#version 330

out vec4 color;
uniform float time;

vec3 palette(float t) {
  vec3 a = vec3(0.5, 0.5, 0.5);
  vec3 b = vec3(0.5, 0.5, 0.5);
  vec3 c = vec3(1, 1, 1);
  vec3 d = vec3(0.0, 0.33, 0.67);

  return a + b*cos( 6.283185*(c*t+d) );
}

void main() {
  float pi = 3.1416;

  vec2 uv = gl_FragCoord.xy / 800;
  uv = uv - 0.5;

  float angle = atan(uv.y, uv.x) * time * 0.3;
  float radius = length(uv);

  float slices = 3;
  float size = pi * 2 / slices;
  float internal_angle = mod(angle, size);
  internal_angle = abs(internal_angle - size /2.0);
  
  vec2 internal_point= radius *
    vec2(
        cos(internal_angle) * radius,
        sin(internal_angle) * radius
        );

  float pattern = 
    sin(internal_point.x * time *10 * 0.5) * 
    sin(internal_point.y * time *10 * 0.5);

  vec3 c = palette(pattern + time * 0.5);

  color = vec4(c, 1);
}

r/cprogramming • • 5d ago

Why is the -fsanitize flag increasing the memory my binary uses

14 Upvotes

I heard that `-fsanitize` flag can detect memory errors so I used it with on my project. `-fsanitize=address,undefined`, but when I looked in my system monitor, I saw that the the memory it used kept increasing.

I reviewed my code to see if the code had any memory leaks, but it didn't.

I compiled the project without that flag and now the memory usage didn't increase and it used only half the memory it used with the flags, which is fair

Is this common behavior?


r/cprogramming • • 5d ago

Private leaderboard for humans using C

Thumbnail
reddit.com
1 Upvotes

Advent of Code is an interesting way to test your C programming skills. Every day there will be a puzzle consisting of two parts, where the first part is usually easier than the second part.


r/cprogramming • • 7d ago

Coding a Moiré Fractal with C, Raylib and GLSL

Thumbnail
youtu.be
3 Upvotes

I created a simple moiré fractal using C, raylib and GLSL shaders.

The idea is quite simple: start with two nearby centers and generate concentric circles around each one, gradually increasing their radius.

Then, using the radius as input to a sin function, I generate alternating light and dark values. By applying this to the colors, the two circle patterns interact and produce the characteristic moiré effect.

Complete coding session:

https://youtu.be/7MmUcDiOJDc

Source code:

https://github.com/FractalCodeRicardo/hangover-programming/tree/main/moire-shaders

C / Raylib

#include <raylib.h>
#define size 800

float time = 0.0;

int main() {
  
  InitWindow(size, size, "Moire Circles");

  Shader shader = LoadShader(0, "moire.glsl");
  
  int timeLoc = GetShaderLocation(shader, "time");
  while (!WindowShouldClose()) {

    time = GetTime();
    SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);

    BeginDrawing();
      BeginShaderMode(shader);
        DrawRectangle(0, 0, size, size, BLACK);
      EndShaderMode();
    EndDrawing();
  }

  CloseWindow();
}

Glsl
#version 330

out vec4 color;

uniform float time;

void main() {
  vec2 uv = gl_FragCoord.xy / 800;
  uv = uv - 0.5;
  
  float a = 30;

  vec2 center1 = vec2(0.1, 0.0);
  vec2 center2 = vec2(-0.1, 0.0);
  
  float d1 = distance(center1, uv);
  float d2 = distance(center2, uv);

  vec4 color1 = vec4(
      0.0 * sin(a * time*d1),
      0.8 * sin(a * time*d1),
      0.8 * sin(a * time*d1),
      1
  );

  vec4 color2 = vec4(
      1 * sin(a * time*d2),
      0.2 * sin(a * time*d2),
      1 * sin(a * time*d2),
      1
  );
  
  color = mix(color1, color2, 0.5);
}

AI Disclaimer:

I did not use AI to code the fractal.


r/cprogramming • • 7d ago

[lex/yacc] portability of jockeying yyin mid-parsing and potential concerns?

2 Upvotes

Working with a file-format that has include directives (effectively inlining the referenced file), my plan has been to have lex push/pop the top FILE* into a stack, open the included-file, set it to yyin to that new FILE*, continue lexing based on that new file (effectively recursing into any included files there), then close the included file, pop the original file's FILE* off the stack, and resume where it left off.

However, I have concerns whether monkeying with yyin like this is something that can be done portably, especially if lex implementations buffer the content read from the file (meaning that changing the yyin might not impact the next characters/tokens because they're already buffered, meaning lex sees the buffered next tokens from the first file rather than the tokens from the new/included file, which I understand flex might do). Similarly pushing items back (ungetc()/unput()) after an include directive might result in enqueuing a character from the including-file where I really want the next characters to come from the included-file.

Are there best practices for reliably switching the input streams provided to lex?

FWIW, the dev environment is FreeBSD/OpenBDS with their implementations of lex, not GNU flex out of the gate.


r/cprogramming • • 7d ago

Cortex: A Cargo/uv-inspired package manager and build tool for C and C++

Thumbnail
github.com
0 Upvotes

Hello!

I’ve been working on cortex (cx), a C/C++ package manager and build tool inspired by Rust’s Cargo and Python’s uv, and I’d love to share it with you and get some feedback.

Why another tool?

Setting up a C++ project with clean dependency management, lockfiles, features, and workspaces often requires gluing together multiple tools and boilerplate CMakeLists.txt files. With cx, you describe your package in a single cx.toml file, it resolves and locks dependencies, generates the underlying CMake project, and drives the build automatically.

Quick example

cx new hello
cd hello
cx add nlohmann_json --git https://github.com --tag v3.12.0
cx run

Key Features

Zero-boilerplate builds: Sources, tests, benchmarks, and examples are discovered by convention (src, tests, benches, examples). Supports mixed C (C90–C23) and C++ (C++98–C++26), including C++20 modules (.cppm, .ixx).

Flexible dependency management: Pull dependencies from registries, Git repos, local paths, system packages (find_package), or vcpkg. Any existing CMake, Autotools, or SCons project works out of the box as a Git or path dependency.

PubGrub version resolution & lockfiles: Uses the PubGrub solver (like uv and pub) for clear conflict explanations, and pins exact versions, Git commits, and SHA-256 hashes in cx.lock.

Cargo-style features & workspaces: Supports optional dependencies, feature flags (exposed via CX_FEATURE_ macros), and multi-package workspaces sharing a single lockfile and target/ directory.

Built-in developer workflows: Comes with cx test, cx bench, cx fmt (clang-format), cx lint (clang-tidy), cx doc (Doxygen), cx vendor for offline builds, and built-in sanitizer/LTO build profiles.

IDE & CI friendly: Generates standard CMake projects (cx generate) and JSON metadata (cx metadata) so your existing IDE setup works seamlessly, plus --locked and --offline flags for CI.

Current Status & Caveats

First Release & Self-Hosting: This is the very first release. Right now the repo still includes its bootstrapping CMake files, which will be removed in the next release now that cx can build itself.

OS Support: Works on Linux and macOS. Windows (MSVC) support is newly added and passing in CI, though it hasn't been battle-tested in the wild yet.

Public Registry: There isn't a central public registry yet, though cx works directly with Git repositories, local paths, vcpkg, system packages, and includes a lightweight self-hosted registry server (cx-registry).

Links

GitHub Repository

The cx Book (Documentation)

You can install prebuilt binaries via the install script in the README or build it from source with CMake 3.28+ and a C++23 compiler. 

I’d really appreciate any feedback, bug reports, or thoughts on what would make this genuinely useful for your C/C++ workflows!

Thanks


r/cprogramming • • 7d ago

Deep diving into low level with c any suggestions.

0 Upvotes

I know c fundamental, and understanding other things


r/cprogramming • • 8d ago

Semtimedop, loop with alarm and msgop, signal handler with flag variable - is it good practice or just a bad workaround?

4 Upvotes

Hello, everyone. This is a school project so I'm not allowed to share my code, but it shouldn't be a big problem since my question is more...general.

In my programs I have several semops and msgops. I had to change my SIGTERM's handler and, with what I've been told (here, too) and I've read, I only put a flag variable in it, which I'll have to check continuously on. I have managed to find a way around if my msgops get interrupted, however, the main problem would have been my processes waiting on a semop or message that would never come (signal comes right before the syscall, it changes the variable and returns, main program continues where it left off).

I figured I'd have the processes enter loops where they wait on the syscall and, if the time allocated runs out, it checks the flag variable. If it's been changed, it proceeds a certain way; otherwise, the loop continues.

It's important to say that SIGTERM will always be sent to all my processes after the right amount of time has passed.

Is this good practice? Or a bad workaround to my problem? In case it is good practice: the simulation can last for about 8 minutes, while the processes usually work with nanoseconds (sometimes seconds). Is it ok to have the processes check for said variable every 2-5 seconds? The processes will be taking note of the waiting time. My main goals here are to avoid active waiting and increase concurrency between processes.

Thank you in advance!

Edit: I'm sorry, I should have specified we're only allowed to use SystemV IPC


r/cprogramming • • 8d ago

Hi! I am using visual studio but it doesn't work. error: "missing filename after '-o'" what should i do?

Thumbnail reddit.com
0 Upvotes

r/cprogramming • • 9d ago Bravo

AWSM: the stupid fantasy console

Thumbnail
codeberg.org
10 Upvotes

Hey guys! So, I'm a masochist, and when I saw that fantasy consoles like pico 8 use... Lua <eugh>, I decided to make my own infinitely worse version. It definitely segfaults on some edge cases, the assembly isn't perfect or even great, and it only works on linux (maybe all posix?) And that too with a jank build script.

Would appreciate feedback!


r/cprogramming • • 9d ago

Revealed vs. Opaque structs for Libraries

Thumbnail reddit.com
2 Upvotes

r/cprogramming • • 9d ago

How should I learn c language?

Thumbnail reddit.com
0 Upvotes