title: c shared memory attach/detach/deallocate
body: <p>I have question regarding shared memory segmentation in c using POSIX system calls. Is it right that I am detaching and removing segment from client and server or i just need to remove from server?</p>
  
  <p>Consider I have 2 programmes</p>
  
  <p>One for server and one for client</p>
  
  <pre><code>the steps for the server
  
  1)create memory segment
  2)attach
  3)detach
  4)remove
  
  steps for the client
  
  1)create
  2)attach
  3)detach
  4)remove
  </code></pre>
  
  <p>this is my code:</p>
  
  <pre><code>//server
  
  #include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  #include&lt;sys/ipc.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;sys/wait.h&gt;
  #include&lt;sys/shm.h&gt;
  
  #define SHMSZ 100
  int main()
  {
  
  key_t key;
  char c;
  int shmid;
  char *shm;
  
  key=1025;
  
  //locate
  if((shmid=shmget(key,SHMSZ,0666 | IPC_CREAT))&lt;0)
  {
  perror("shmget");
  exit(-1);
  }
  
  
  
  //attach
  if((shm=shmat(shmid,NULL,0))==(char*)-1)
  {
  perror("shmat");
  exit(-1);
  }
  
  
  sprintf(shm,"Hi there");
  
  //shm="Hi There";
  
  while(*shm!='*');
  sleep(1);
  
  //detach
  shmctl(shmid,IPC_RMID,NULL);
  return 0;
  }
  </code></pre>
  
  <p>this is client side</p>
  
  <pre><code>//client
  
  #include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  #include&lt;sys/ipc.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;sys/wait.h&gt;
  #include&lt;sys/shm.h&gt;
  
  #define SHMSZ 100
  
  int main()
  {
  
  
  key_t key;
  int shmid;
  char c;
  char *shm, *s;
  
  key=1025;
  //locate
  if((shmid=shmget(key,SHMSZ,0666 | IPC_CREAT))&lt;0)
  {
  perror("shmget");
  exit(-1);
  }
  
  //attach
  if((shm=shmat(shmid,NULL,0))==(char*)-1)
  {
  perror("shmat");
  exit(-1);
  }
  
  printf("%s\n",shm);
  
  *shm='*';
  
  shmdt(&amp;shmid);
  shmctl(shmid, IPC_RMID,NULL);
  
  return 0;
  }
  </code></pre>