- 论坛徽章:
- 0
|
- #include <sys/types.h>
- #include <sys/shm.h>
- #include <sys/ipc.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define TOKEN 'r'
- void destroy_shm(int shmid)
- {
- struct shmid_ds buf;
- shmctl(shmid, IPC_STAT, &buf);
- if (buf.shm_nattch == 0)
- shmctl(shmid, IPC_RMID, NULL);
- }
- int main(void)
- {
- int shmid = shmget(IPC_PRIVATE, 32, IPC_CREAT | 0600);
- if (shmid == -1)
- {
- perror("shmget");
- exit(1);
- }
- pid_t pid = fork();
- if (pid == -1)
- {
- destroy_shm(shmid);
- perror("fork");
- exit(1);
- }
- if (pid == 0)
- {
- sleep(5);
- char *ptr = (char *)shmat(shmid, NULL, 0);
- strcpy(ptr, "rHello world!aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
- shmdt(ptr);
- exit(0);
- }
- char *ptr = (char *)shmat(shmid, NULL, 0);
- if (ptr)
- {
- while (1)
- {
- if (*ptr == 'r')
- {
- printf("%s\n", ptr+1);
- break;
- } else
- usleep(1);
- }
- }
- shmdt(ptr);
- destroy_shm(shmid);
- exit(0);
- }
复制代码 |
|