Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 14 Jun 2000 20:04:51 -0700 (PDT)
From:      Shawn Workman <shawn@holdenz.com>
To:        freebsd-questions@freebsd.org
Subject:   Programming problem, Shared Memory
Message-ID:  <200006150304.UAA47231@holdennt.holdenz.com>

next in thread | raw e-mail | index | archive | help
Please help me with the simple 'Shared Memory' example.. I cant use fork, many different
applications may speaking to one 'server' application..

This small function can run as the memory server (pass bogus parameters) and as a client
in another terminal (dont pass any parameters) I can read from the server the int and
string but not the server allocated string..

What am I doing worng??

Please examine: (yes -- very new to NOT USING WINDOWS OS's)


file://FreeBSD 4.0

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <machine/param.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

struct SharedMemBlock
{
 char *APtr; // To be allocated
 int AInt; // A simple set
 char AStr[40]; // A simple Set
};

SharedMemBlock *SMB = NULL;

int main (int argc, char *argv[])
{

 key_t KeyToIt = ftok(".",'8');

 int shmid;

 if (argc > 2) // Any passed junk -- just tell is to be a 'server'
 {
  if ((shmid = shmget(KeyToIt, sizeof (struct SharedMemBlock),IPC_CREAT|IPC_EXCL|0666))
== -1)
  {
   printf("Already exists -- Please shutdown originating server");
  }
  else
  {

   SMB = (struct SharedMemBlock *)shmat(shmid,0,0);

   SMB->AInt = 97; // A simple set
   strcpy(SMB->AStr,"Hello how are you"); // A simple set

   if ((SMB->APtr = (char *)malloc(100) ) != NULL)
   {
    printf("APtr Allocated");
    strcpy(SMB->APtr,"WOW IT WORKED");
   }
   else
   {
    printf("No APtr Allocated");
   }

   // OK, the 'server' is up, now with another xterm run this same
   // program again WITHOUT passing any parameters.. that is the 'Client'
   // You can run the client as many times as you wish.. Util the Server's
   // getchar() is satisfied....

   getchar();

   if (SMB->APtr != NULL)
   {
    free(SMB->APtr);
    SMB->APtr = NULL;
   }
  }
 }
 else
 {
  // This is the client who wants to read the servers memory....

  if ((shmid = shmget(KeyToIt, sizeof (struct SharedMemBlock),IPC_EXCL|0666)) == -1)
  {
   printf("Please Start Server (Same but pass params)");
  }
  else
  {
   SMB = (struct SharedMemBlock *) shmat(shmid,0,0);

   printf("---%d\n%s\n\n\n", SMB->AInt,SMB->AStr);

   if (SMB->APtr != NULL) // The problem is RIGHT HERE!!!!
    printf("Now trying allocated server pointer\n[%s]", SMB->APtr);
   else
    printf("No allocated server pointer");
   }
 }
 return(0);
}



To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200006150304.UAA47231>