update forking example

This commit is contained in:
Rokas Puzonas 2024-01-06 21:09:38 +02:00
parent ea173678f2
commit 48e0a65413
3 changed files with 18 additions and 61 deletions

View File

@ -4,10 +4,9 @@ pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
{
const exe = b.addExecutable(.{
.name = "forking-simple",
.root_source_file = .{ .path = "simple.c" },
.name = "forking-example",
.root_source_file = .{ .path = "main.c" },
.optimize = optimize,
.target = target
});
@ -19,20 +18,3 @@ pub fn build(b: *std.build.Builder) void {
b.installArtifact(exe);
}
{
const exe = b.addExecutable(.{
.name = "forking-mutexes",
.root_source_file = .{ .path = "mutexes.c" },
.optimize = optimize,
.target = target
});
exe.linkLibC();
const run_cmd = b.addRunArtifact(exe);
const run_step = b.step("run-mutexes", "Run mutexes program");
run_step.dependOn(&run_cmd.step);
b.installArtifact(exe);
}
}

View File

@ -8,15 +8,12 @@
#include <stdbool.h>
#include <time.h>
// WARNING: This example does not work, I couldn't figure out why the lock does not work correcly.
// The final counter result should not change, but it does.
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
void run(const char *name, struct shared_data *data) {
void increment_counter(const char *name, struct shared_data *data) {
for (int i = 0; i < 10000; i++) {
if (pthread_mutex_lock(&data->mutex) != 0) {
perror("pthread_mutex_lock");
@ -36,8 +33,11 @@ int main() {
perror("mmap");
return -1;
}
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&shared_data->mutex, NULL) < 0) {
if (pthread_mutex_init(&shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
@ -47,11 +47,11 @@ int main() {
int pid = fork();
if (pid == 0) {
srand(time(NULL)+1);
run("Child ", shared_data);
increment_counter("Child ", shared_data);
return 0;
} else {
srand(time(NULL)+2);
run("Parent", shared_data);
increment_counter("Parent", shared_data);
}
int child_status;

View File

@ -1,25 +0,0 @@
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main() {
char parent_message[] = "hello";
char child_message[] = "goodbye";
void* shmem = mmap(NULL, 128, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
memcpy(shmem, parent_message, sizeof(parent_message));
int pid = fork();
if (pid == 0) {
printf("Child read: %s\n", (char*)shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", (char*)shmem);
} else {
printf("Parent read: %s\n", (char*)shmem);
sleep(1);
printf("After 1s, parent read: %s\n", (char*)shmem);
}
}