马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
设计两个历程,历程A申请一块共享内存,并向内存中写入数据,历程B从共享内存中读取数据并输出- /********************************************************************************
- *
- *
- * 共享内存练习
- * author:jindouliu2024@163.com
- * date:2025.5.8
- *
- * Copyright (c) 2024-2025 jindouliu2024@163.com All right Reserved
- * *****************************************************************************/
复制代码- //进程A
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/wait.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <time.h>
- #include <sys/ipc.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- int main()
- {
- //设置键值
- key_t key = ftok(".",2);
- //创建一块共享内存空间
- int shm_id = shmget(key,256,IPC_CREAT|IPC_EXCL|0644);
- if(shm_id == -1){
- printf("shmget error\n");
- return 1;
- }
- //连接映射空间,并写入数据
- char *shm_map = (char *)shmat(shm_id,NULL,0);
- sprintf(shm_map,"this is shm_a process,id = %d\n",getpid());
- while(1);
- return 0;
- }
复制代码- //进程B
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/wait.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <time.h>
- #include <sys/ipc.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- int main()
- {
- //设置键值
- key_t key = ftok(".",2);
- //创建一块共享内存空间
- int shm_id = shmget(key,256,IPC_CREAT|IPC_EXCL|0644);
- if(shm_id == -1){
- printf("shmget error\n");
- shm_id = shmget(key,256,0644);
-
- }
- //连接映射空间,并读取数据
- char *shm_map = (char *)shmat(shm_id,NULL,0);
- printf("%s\n",shm_map);
- //解除映射
- shmdt(shm_map);
- return 0;
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |