0

I have a question regarding multiprocess programming in C, I have several reader processes that will be reading from a file into a shared buffer and several writer processes reading from the buffer and into another file, what type of semaphores will we need to use for this. and how can we use shared memory with the semaphores.

2
  • 1
    What operating system? Are you using any multiprocessing specific libraries? Commented Jun 20, 2011 at 16:07
  • linux here are all the headers I included in the file, #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <fcntl.h> #include <semaphore.h> #include <string.h> #include <sys/shm.h> #include <time.h> hope this helps Commented Jun 20, 2011 at 17:35

1 Answer 1

1

If you're on linux, one easy option is to use pshared mutexes and condition variables. A recet version of glibc will be necessary. Essentially inside your shared memory segment you will have something like:

struct shmem_head { pthread_mutex_t mutex; }; 

To initialize:

void init_shmem_head(struct shmem_head *head) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED ); pthread_mutex_init(&head->mutex, &attr); pthread_mutexattr_destroy(&head->mutex); } 

You now have a mutex, shared by all processes with the shared memory segment open. You can simply use pthread_mutex_lock to lock and pthread_mutex_unlock to unlock as normal. There's also a similar pthread_condattr_setpshared if you want condition variables as well.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.