非亲缘进程间的共享内存与信号通信
来源:互联网 发布:什么是优化教育 编辑:程序博客网 时间:2024/05/16 10:52
-
-
-
-
-
-
-
-
- #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;
-
- }
-
-
-
-
-
-
-
- #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)
- {
- }