- /*****************************
- 写入数据到共享内存,后再得到另一个进程pid
- 向其发送SIGUSR1信号,另一个进程
- 收到后退出
- ***************************/
- #include<sys/shm.h>
- #include<sys/ipc.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<signal.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<string.h>
- #include<errno.h>
- #define SIZE 1024
- int main(void)
- {
- sleep(2);
- char *addr;
- char buf[50];
- int shmid;
- printf("please input string to share memory\n");
- fgets(buf,100,stdin);
- key_t key;
- key = ftok(".",'a');
- printf("key = %d\n",(int)key);
- if((shmid = shmget(key,SIZE,0666|IPC_CREAT)) < 0)
- perror("shmget");
- else{
- printf("get share memory success\n");
- printf("shmid = %d\n",shmid);
- }
- addr = shmat(shmid,NULL,0);
- if( addr == (void *)(-1))
- perror("shmat");
- else{
- printf("get addr success\n");
- printf("addr = %p\n",addr);
- }
- strcpy(addr+4,buf);
- pid_t pid;
- strncpy(&pid,addr,4);
- kill(pid,SIGUSR1);
- if(shmdt(addr) < 0)
- perror("shmdt");
- else
- printf("detached share memory\n");
- return 0;
- }
- /************************
- 先写入自己的pid 对方写完数据后
- 向 自己 发送一SIGUSR1信号,收到
- 信号后,读数据后退出.
- **********************/
- #include<sys/shm.h>
- #include<sys/ipc.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<signal.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<string.h>
- #include<errno.h>
- #define SIZE 1024
- void get(int sig);
- int main(void)
- {
- char *addr;
- char buf[50];
- int shmid;
- signal(SIGUSR1,get);
- key_t key;
- key = ftok(".",'a');
- printf("key = %d\n",key);
- shmid = shmget(key,SIZE,0666|IPC_CREAT);
- if(shmid < 0)
- perror("shmget");
- else{
- printf("get share memory success\n");
- printf("shmid = %d\n",shmid);
- }
- addr = shmat(shmid,NULL,0);
- if(addr == (void *)(-1))
- perror("shmat");
- else{
- printf("get addr success\n");
- printf("addr = %p\n",addr);
- }
- pid_t pid = getpid();
- strncpy(addr,&pid,4);
- pause();
- strcpy(buf,addr+4);
- fprintf(stdout,"get message from shm:\n%s\n",buf);
- if(shmdt(addr)<0)
- perror("shmdt");
- else
- printf("detached share memory success\n");
- if (shmctl(shmid, IPC_RMID, NULL) == -1)
- perror("Child: shmctl(IPC_RMID)\n");
- else
- printf("Delete shared-memory\n");
- return 0;
- }
- void get(int sig)
- {
- }