为什么msgrcv()将垃圾字符馈送到缓冲区
Why is msgrcv() feeding garbage characters into the buffer?
现在,我正在尝试输出buf.mtext的内容,以便在继续我的程序之前确保输入正确。除了一件事外,一切似乎都很好;msgrcv((将垃圾字符放入缓冲区,接收进程输出垃圾字符。
这是我的发件人流程:
int main (void)
{
int i; // loop counter
int status_01; // result status
int msqid_01; // message queue ID (#1)
key_t msgkey_01; // message-queue key (#1)
unsigned int rand_num;
float temp_rand;
unsigned char eight_bit_num;
unsigned char counter = 0;
unsigned char even_counter = 0;
unsigned char odd_counter = 0;
srand(time(0));
struct message {
long mtype;
char mtext[BUFFER_SIZE];
} buf_01;
msgkey_01 = MSG_key_01; // defined at top of file
msqid_01 = msgget(msgkey_01, 0666 | IPC_CREAT)
if ((msqid_01 <= -1) { exit(1); }
/* wait for a key stroke at the keyboard ---- */
eight_bit_num = getchar();
buf_01.mtype = 1;
/* send one eight-bit number, one at a time ------------ */
for (i = 0; i < NUM_REPEATS; i++)
{
temp_rand = ((float)rand()/(float)RAND_MAX)*255.0;
rand_num = (int)temp_rand;
eight_bit_num = (unsigned char)rand_num;
if ((eight_bit_num % 2) == 0)
{
printf("Even number: %dn", eight_bit_num);
even_counter = even_counter + eight_bit_num;
}
else
{
printf("Odd number: %dn", eight_bit_num);
odd_counter = odd_counter + eight_bit_num;
}
/* update the counters ------------------------------ */
counter = counter + eight_bit_num;
if((eight_bit_num % 2) == 0) { even_counter = even_counter + eight_bit_num; }
else { odd_counter = odd_counter + eight_bit_num; }
buf_01.mtext[0] = eight_bit_num; // copy the 8-bit number
buf_01.mtext[1] = ' '; // null-terminate it
status_01 = msgsnd(msqid_01, (struct msgbuf *)&buf_01, sizeof(buf_01.mtext), 0);
status_01 = msgctl(msqid_01, IPC_RMID, NULL);
}
这是我的接收器过程:
int main() {
struct message {
long mtype;
char mtext[BUFFER_SIZE];
} buf;
int msqid;
key_t msgkey;
msgkey = MSG_key_01;
msqid = msgget(msgkey, 0666); // connect to message queue
if (msqid < 0) {
printf("Failedn");
exit(1);
}
else {
printf("Connectedn");
}
if (msgrcv(msqid, &buf, BUFFER_SIZE, 0, 0) < 0) { // read message into buf
perror("msgrcv");
exit(1);
}
printf("Data received is: %s n", buf.mtext);
printf("Done receiving messages.n");
return 0;
}
输出通常如下所示:
Data received is: ▒
Done receiving messages.
我已经确保每次运行发送方和接收方进程后都清除我的消息队列,因为我发现这可能会导致问题。提前感谢您的帮助。
事实证明,正如我所怀疑的那样,建议的解决方案都不是问题所在;发送方进程实际上运行得很好。问题是我试图打印buf.mtext,而不是buf.mtext[0],它不是一个实际的整数值。我通过这样做解决了这个问题:
int temp_num = buf.mtext[0];
printf("Data recieved is %d n", temp_num);
相关文章:
- C++字符*缓冲区的大小
- 将字符缓冲区强制转换为函数指针
- 来自无符号字符缓冲区的虚拟输出
- 如何在C++中将无符号字符缓冲区转换为双精度?
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 将字符缓冲区转换为字符串
- 读取文件时字符缓冲区溢出
- 来自字符缓冲区的恐惧
- 为什么在我的测试程序中,从字符缓冲区读取一个int时,"std::copy"5x(!)比"
- C/C++ 从字符缓冲区读取以填充结构
- 具有输入无符号字符缓冲区C++的设备 IoControl
- 如何从字符 * 缓冲区中的位置 y 读取 x 个字符
- 从字符 * 缓冲区到 wchar_t * 缓冲区的内存
- 如何将字符 * 缓冲区转换为无符号的短 int * bufferSh
- 将windows BITMAP转换为PIX(无符号字符缓冲区)
- RAII字符缓冲区
- MFC-传递带有PostMessage From DLL的字符缓冲区
- 如何使用Gstreamer播放原始字符*缓冲区
- 在 Win32 中解析巨大的字符* 缓冲区
- 分配字符缓冲区以保存浮点的文本表示形式