klonuj(1) pobierz
  1. #include <stdio.h>
  2. #include <sys/ipc.h>
  3. #include <sys/shm.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6.  
  7. int main() {
  8. int shmid;
  9. key_t key = ftok("shmfile", 65);
  10. char *str;
  11.  
  12. // Create shared memory
  13. shmid = shmget(key, 1024, 0666 | IPC_CREAT);
  14.  
  15. // Attach shared memory
  16. str = (char*) shmat(shmid, NULL, 0);
  17.  
  18. if (fork() == 0) {
  19. // Child Process (Reader)
  20. sleep(1); // wait for parent to write
  21. printf("Child Process Reading Data:\n");
  22. printf("Message: %s\n", str);
  23.  
  24. // Detach
  25. shmdt(str);
  26. } else {
  27. // Parent Process (Writer)
  28. printf("Parent Process Writing Data:\n");
  29. printf("Enter message: ");
  30. fgets(str, 100, stdin);
  31.  
  32. sleep(2); // ensure child reads after write
  33.  
  34. // Detach
  35. shmdt(str);
  36.  
  37. // Delete shared memory
  38. shmctl(shmid, IPC_RMID, NULL);
  39. }
  40.  
  41. return 0;
  42. }
Sukces #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
Child Process Reading Data:
Message: 
Parent Process Writing Data:
Enter message: