c中的共享内存,关于输出的问题

shared memory in c, question about the output

我试图用 C 实现共享内存,但我的输出出现了问题。

我试图让一个名为 TA 的线程将成绩放入共享内存 space 并让 "student" 线程输出成绩。

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