So, I have a server process that forks for every client that connects. I keep a list of connected clients that I want each fork process to have. Of course, when the process forks the child only has what it had when the fork occurred. For the solution to this, I decided to use shared memory. For simplicities sake (and because this is my main issue I'm dealing with right now) I'll illustrate how I've attempted to pass an integer from the parent to child processes.
Parent process:
key_t key_numentries;
int shmid_numentries;
char *shm_numentries, *shm1;
char buf[];
//Key for numentries is 2345
key_numentries = 2345;
//Create the shared memory segment
if((shmid_numentries = shmget(key_numentries, 8, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
//Attach shared memory to dataspace
if((shm1 = shmat(shmid_numentries, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
//did this because I wasn't sure how to send an int over the shm
//numentries does contain the right value, I've tested it.
sprintf (buf,"%d",numentries);
//not sure if this would work, but a printf(%s) with &shm1[0] printed
//the correct value
shm1 = buf;
//pretty sure the code below fork is irrelevant
if(!fork()){
close(socket_in);
recievecmds(new_fd);
close(new_fd);
exit(0);}
Child process:
int shmid_numentries;
key_t key_numentries;
char *shm_numentries, *shm1;
//set key to 2345
key_numentries = 2345;
//locate the segment
if ((shmid_numentries = shmget(key_numentries, 8, 0666)) < 0) {
perror("shmget");
exit(1);
}
//attach the segment to our data space
if ((shm1 = shmat(shmid_numentries, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
// I have no idea what to do here... here are some of the things I've tried
//send # of entries to client
//char c = (char)&shm1;
//printf("got this from the parent too %s\n",c);
//printf("in SHM buf: %s\n",&shm1[0]);
numentries = (int)&shm1[0];
//numentries = strtol(&shm1[0],NULL,0);
for (; shm1 != NULL; shm1++)
putchar(*shm1);
putchar('\n');
heres where I'm not sure what to do... how do I get the data from the pointer? Everything I've tried is either nothing or it's a bunch of random gibberish that obviously I didn't store in the pointer... so I'm afraid the memory space isn't actually being shared. Can anyone point me in the right direction here? I am BRAND NEW to shared memory to be honest. Haven't dealt with forks that much either.
Thanks in advance! Please let me know if I need to clarify anything.