1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h>
#define BUFFER_SIZE 2048
int main () { pid_t pid; int shmid; char *shm_addr; char flag[] = "WROTE"; char buff[BUFFER_SIZE] = {0};
if ((shmid = shmget (IPC_PRIVATE, BUFFER_SIZE, 0666)) < 0) { perror ("shmget"); exit (1); } else { printf ("Creat shared-memory: %d\n", shmid); }
system ("ipcs -m");
pid = fork ();
if (pid == -1) { perror ("fork"); exit (1); } else if (pid == 0) { if ( (shm_addr = shmat (shmid, 0, 0)) == (void*) -1) { perror ("Child: shmat"); exit (1); } else { printf ("Child: Attach shared-memory: %p\n", shm_addr); } system ("ipcs -m");
while (strncmp (shm_addr, flag, strlen (flag))) { printf ("Child: Wait for enable data...\n"); sleep (5); }
strcpy (buff, shm_addr + strlen (flag)); printf ("Child: Shared-memory : %s\n", buff);
if ((shmdt (shm_addr)) < 0) { perror ("Child: shmdt"); exit(1); } else { printf ("Child: Deattach shared-memory\n"); } system ("ipcs -m"); } else { if ( (shm_addr = shmat (shmid, 0, 0)) == (void*) -1) { perror ("Parent: shmat"); exit (1); } else { printf ("Parent: Attach shared-memory: %p\n", shm_addr); } sleep (1); printf ("\nInput some string:\n"); fgets (buff, BUFFER_SIZE, stdin); strncpy (shm_addr + strlen (flag), buff, strlen (buff)); strncpy (shm_addr, flag, strlen (flag));
if ((shmdt (shm_addr)) < 0) { perror ("Parent: shmdt"); exit(1); } else { printf ("Parent: Deattach shared-memory\n"); } system ("ipcs -m");
waitpid(pid, NULL, 0);
if (shmctl (shmid, IPC_RMID, NULL) == -1) { perror ("shmctl"); exit(1); } else { printf ("Delete shared-memory\n"); } system ("ipcs -m");
printf ("Finished\n"); }
exit (0); }
C
|