【发布时间】:2019-11-26 21:06:41
【问题描述】:
我试图用 C 实现共享内存,但我的输出出现了问题。
我尝试让一个名为 TA 的线程将成绩放入共享内存空间,并让“学生”线程输出成绩。
在 TA 线程中:
const int SIZE = 4096;
const char *name_ta = "Students_Information_ta";
int studentGrade = (int)((random() % (100 - 80 + 1)) + 80); // TA gives out a grade to a student
char *grade = (char *)&studentGrade;
/* shared memory file descriptor */
int shm_fd_ta;
/* pointer to shared memory object */
void *ptr_ta;
/* create the shared memory segment of ta */
shm_fd_ta = shm_open(name_ta, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory segment of ta*/
ftruncate(shm_fd_ta, SIZE);
/* map the shared memory segment of ta in the address space of the process */
ptr_ta = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd_ta, 0);
if (ptr_ta == MAP_FAILED)
{
printf("Map failed\n");
return -1;
}
/* write to the shared memory region */
sprintf(ptr_ta, "%d", grade);
ptr_ta += strlen(grade);
这是学生线程中的输出句子:
/* name of shared memory object */
const char *name_ta = "Students_Information_ta";
/* size of shared memory object in bytes */
const int SIZE = 4096;
int shm_fd_ta;
void *ptr_ta;
/* open the shared memory segment of ta */
shm_fd_ta = shm_open(name_ta, O_RDWR, 0666);
if (shm_fd_ta == -1)
{
printf("shared memory failed\n");
exit(-1);
}
/* map the shared memory segment of ta in the address space of the process */
ptr_ta = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd_ta, 0);
if (ptr_ta == MAP_FAILED)
{
printf("Map failed\n");
exit(-1);
}
printf("The grade assigned by the TA is %d\n", ptr_ta); // student receives a grade
我以为它应该给我80到100之间的数字的等级,但实际上输出的是一些非常大的数字,比如251142144。也许它已经输出了地址。我该如何解决这个错误?
【问题讨论】:
-
你认为这是做什么的:
char *grade = (char *)&studentGrade;?
标签: c pointers shared-memory