写2段C++程序,第一个程序是生成动态随即数字数据并以共存內享的形式发布,第二个程序是读取第一个程序生成的数据的共享内存
时间: 2023-05-27 09:08:03 浏览: 56
第一个程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
int shmid;
key_t key = 1234;
int *shm;
shmid = shmget(key, sizeof(int), IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
shm = shmat(shmid, NULL, 0);
if (shm == (int *) -1) {
perror("shmat");
exit(1);
}
srand(time(NULL));
int num = rand() % 1000;
*shm = num;
printf("Generated random number: %d\n", num);
shmdt(shm);
return 0;
}
第二个程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
int shmid;
key_t key = 1234;
int *shm;
shmid = shmget(key, sizeof(int), 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
shm = shmat(shmid, NULL, 0);
if (shm == (int *) -1) {
perror("shmat");
exit(1);
}
printf("Read random number: %d\n", *shm);
shmdt(shm);
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)