I have a 2-dimensional array of a structure Data
, that has to be initialized. The main program creates 1 server and 4 clients. All the processes should be able to access and modify the data (I already took care of synchronization problems using semaphores). Every part of the program is located in a separate .c file. How can I initialize, share, and access / modify my data (how can I access the fields of the structure, in server()
or client()
) ? I'm currently using System V but could use Posix if more appropriate.
/* project.h */
typedef struct Data {
int fieldA;
int fieldB;
int fieldC;
int fieldD;
} Data;
extern Data data[4][3];
extern int shm;
extern Data *p;
/* main.c */
#include "project.h"
Data *p;
int shm;
void main()
{
int i;
shm = shmget(IPC_PRIVATE, 3*4*sizeof(Data), 0666);
p = (Data *) shmat(shm, NULL, 0);
for (i=1;i<5;i++) {
if (fork() == 0) {
client(i);
}
}
if (fork() == 0) {
server();
}
}
/* server.c */
#include "project.h"
// I only care about the first field of Data when I initialize.
Data data[4][3] = { {{0},{1},{-1}},
{{2},{-1},{-1}},
{{5},{0},{3}},
{{-1},{6},{-1}} };
void server()
{
/* read / modify the data */
}
/* client.c */
#include "project.h"
void client(int i)
{
/* read / modify the data */
}