简体   繁体   中英

Get data from shared memory after getting signal from child process

int *sharedmem(key_t *key,char k,int size){
  int shmid;
  int *segptr;
  *key=ftok('.',k);
  if((shmid=shmget(*key,size,IPC_CREAT|IPC_EXCL|0666))==-1){
    printf("Shared memory segment exists - opening as client\n");
    if((shmid = shmget(*key, size, 0)) == -1){
      perror("bad shmget");
      exit(1);
    }
  }
  else
    printf("Creating new shared memory segment\n");
  if((segptr = shmat(shmid, 0, 0)) == NULL){
    perror("bad shmat");
    exit(1);
  }
  return segptr;
}
int main(){
  ...
  mem=sharedmem(&key,'a',2);
  fpid=getpid();
  signal(SIGHUP,sighup);
  if(pid=fork()==0){
    ...
    mem[0]=1;
    kill(fpid,SIGHUP);
  }
  else {//parent
     //read data from mem[0] when receiving the signal.
  }

How can I read the data from mem[0] in parent upon receiving the signal from the child process? I want to notify the parent that the data has been written to the shared memory and the parent can read it.

In your parent, you can just read the shared data within the signal handler. However, depending on what you want to do with this data, you might want to adopt a different strategy. For instance:

  • Increment a global static variable in your signal handler (make it a volatile sig_atomic_t ). Then in them main loop of your program test this, and take action appropriately.

  • Nicer, use a self pipe . Explanation here . In essence create a non-blocking pipe() and write a character to it from your signal handler. select() on the read side of the pipe in the normal way in your main loop.

  • If your parent process is multithreaded, consider abandoning the signal handler and use semaphores or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM