我几乎完成了一个简单的分叉程序,其中一个进程使用 mq_send 和 mq_receive 向其父进程发送一个字符数组,并输出反转的字符串。但是,由于某种原因,当我有时输入要发送的字符串时,程序的接收端已为其添加了字符。更重要的是,这似乎是随机的,因为再次发送相同的字符串会给出正确的输出。
这是整个代码,以及之后的示例输出。
#include <stdio.h> /* printf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* get_pid */
#include <stdlib.h> /* exit, EXIT_FAILURE */
#include <sys/wait.h> /* wait */
#include <mqueue.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#define MAX_STR_LEN 500
void reverse(char s[]);
void clientFunction(const char *msgqname);
void serverFunction(const char *msgqname);
int main(void)
{
//A
char msgQName[] = "/queue";
//B
pid_t pid;
pid = fork();
if (pid == 0){
clientFunction(msgQName);
}
else {
usleep(10L);
serverFunction(msgQName);
}
return(0);
}
void clientFunction(const char *msgqname){
//C
mqd_t mqident = mq_open(msgqname, O_WRONLY|O_CREAT , 0666, NULL);
//D
if (mqident == -1){
printf("Error opening message queue. Exiting program. \n");
exit(0);
}
char str[MAX_STR_LEN]; //Keep the string that has been read from input and written on the pipe
memset(str,0,strlen(str));
while(1){
printf("Enter an string:");
gets(str); //Reads the string from input
printf("%i\n",strlen(str));
unsigned len = (unsigned) strlen(str); //Finds the length of the string
int sent = mq_send(mqident,str,len,0);
if (sent == -1){
printf("Error sending message. Exiting program. \n");
exit (0);
}
usleep(10L);
memset(str,0,strlen(str));
}
}
void serverFunction(const char *msgqname){
//F
mqd_t mqident = mq_open (msgqname,O_RDONLY|O_CREAT , 0666, NULL);
if (mqident == -1){
printf("Error opening message queue. Exiting program. \n");
printf( "Error : %s\n", strerror( errno ) );
exit(0);
}
char str1[MAX_STR_LEN];
memset(str1,0,strlen(str1));
struct mq_attr attr;
while(1){
//G
mq_getattr(mqident,&attr);
//H
ssize_t receive = mq_receive(mqident,str1,attr.mq_msgsize,0);
if (receive == -1){
printf("Error receiving message. Exiting program. \n");
exit(0);
}
printf("%i, %i\n",strlen(str1), attr.mq_msgsize);
reverse(str1);
printf("What you wrote in reverse was:%s\n", str1);
memset(str1,0,strlen(str1));
}
}
void reverse(char s[])
{
int length = strlen(s) ;
int c, i, j;
for (i = 0, j = length - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
示例输出,当在终端中使用带有 -o 和 -lrt 的 gcc 编译时
Enter an string:tester 1234567890
17
21
What you wrote in reverse was:1��0987654321 retset
Enter an string:tester 1234567890
17
17
What you wrote in reverse was:0987654321 retset
Enter an string:
输出中的两个整数值是我用来检查长度的,第一个是发送字符串的 strlen,第二个是接收字符串的 strlen。
我确保在初始化和 printf 之后立即清空字符串,所以我不知道这些神秘字符来自哪里。