fork download
  1. #include "sys/ipc.h"
  2. #include "sys/shm.h"
  3.  
  4. #include "unistd.h"
  5. #include "sys/types.h"
  6. #include "sys/wait.h"
  7.  
  8. #include "stdio.h"
  9. #include "stdlib.h"
  10.  
  11. int main(){
  12. key_t key = 0x12345678;
  13. int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666);
  14. if (fork() != 0){
  15. int * ptr = (int *) shmat(shmid, 0, 0);
  16. printf("shmid parent = %d\n", shmid);
  17. *ptr = 6;
  18. shmdt(ptr);
  19. wait(NULL);
  20. shmctl(shmid, IPC_RMID, NULL);
  21. }
  22. else{
  23. printf("shmid child = %d\n", shmid);
  24. int * ptr = (int *) shmat(shmid, 0, 0); // Works as expected
  25. printf("ptr address = %p\n", ptr);
  26. shmdt(ptr);
  27. printf("Now child can exit normally\n");
  28. }
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0.01s 5532KB
stdin
Standard input is empty
stdout
shmid child = 0
ptr address = 0x1552f8de6000
Now child can exit normally
shmid parent = 0