[英]shared memory in c, question about the output
我试图用 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;
好的,所以grade
是指向字符的指针类型,但指向一个整数。 不知道你为什么要这样做,但好吧。
sprintf(ptr_ta, "%d", grade);
你告诉sprintf
打印一个整数,但你传递了一个指向一个指向整数的字符的指针。 sprintf
函数当然不知道如何处理这种不匹配的指针,尤其是当你告诉它你要传递一个整数时。
为什么不:
sprintf(ptr_ta, "%d", studentGrade);
如果你告诉它你要给它一个整数,也许给它一个整数。
——
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);
}
现在, ptr_ta
是指向您打印的字符串的指针。
printf("The grade assigned by the TA is %d\n", ptr_ta); // student receives a grade
你告诉printf
你要传递一个整数,但你传递了一个指向字符串的指针。 这应该如何工作?
我会改变很多东西,但这是一个开始:
printf("The grade assigned by the TA is %s\n", (char *) ptr_ta); // student receives a grade
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.