gpt4 book ai didi

c - 我无法理解这个聊天程序的结果

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:36 25 4
gpt4 key购买 nike

所以我做了一个简单的服务器-客户端程序,可以使用 fifo 文件 (msgfifo) 相互通信。

我的问题是:当我键入包含空格的消息时,接收进程会根据字数运行多次。

这不是我所期望的,因为我希望将它作为一个完整的句子打印出来,但它没有,我想知道为什么。

当我输入要发送的内容时,进程会向另一个发送 SIGUSR1 信号。

/* receive msg part */
/* added this using sigset(SIGUSR1, receiveSIGUSR1) */

void receiveSIGUSR1()
{
char* msg = "\nIncoming Message from client...";
char* msg2 = "\nClient : ";
char buf[max_of_msg];
int fd;
write(1, msg, strlen(msg)+1);
fflush(stdin);
if( (fd = open("./msgpipe", O_RDONLY)) < 0)
{ perror("open"); exit(1); }
read(fd, buf, max_of_msg);
close(fd);
write(1, msg2, strlen(msg2)+1);
write(1, buf, strlen(buf)+1);
flag = 0;
}

/*send msg part*/

while(1)
{
flag = -1;
printf("\nType what u want to send : ");
scanf(" %s", msg);
if(flag == 0) continue;
printf("msgtaken\n");
fflush(stdin);
if( (fd = open("./msgpipe", O_RDWR)) < 0)
{ perror("exit"); exit(1); }
kill(clpid, 30);
sleep(2);
printf("Send message to Client..\n");
write(fd, msg, max_of_msg);
printf("Message Sent...\n");
}

预期:

Client : Hello Server this is client

实际:/* 服务器 */


Incoming Message from client...
Hello
Incoming Message from client...
this
Incoming Message from client...
is
Incoming Message from client...
client

Type what u want to send :

/客户/


Type what u want to send : Hello Server This is client
msgtaken
Send message to server..
Message sent

Type what u want to send : msgtaken
Send message to server..
Message sent

Type what u want to send : msgtaken
Send message to server..
Message sent

Type what u want to send : msgtaken
Send message to server..
Message sent

Type what u want to send : msgtaken
Send message to server..
Message sent


Type what u want to send :

最佳答案

那是因为这是它接受输入的方式:

scanf(" %s", msg);

让我们看一下scanf的文档(强调我的):

s: Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.

这就是当您发送 Hello Server this is client 时它在 Hello 之后停止的原因。还要注意 "%s" 中的空格,这意味着它还将忽略输入开头的任何空格。因此,当它在下一次运行循环时读取 Server 时,它会忽略 HelloServer 之间的空格。结果循环了五次,每次的消息是Hello, Server, this, isclient

相反,您可以使用 getline :

char *message = NULL;
size_t length;
getline(&message, &length, stdin);
// use message
free(message);

一点注意事项:为了使您的 scanf 调用更安全,您可以指定字符串输入的最大大小:

scanf(" %99s", msg);

例如,对于大小为 100 的缓冲区,这意味着只有 99 个 char 可以被读入,外加一个空终止符。这样你可以避免未定义的行为,如果用户会输入一个对您的缓冲区来说太大的字符串。

关于c - 我无法理解这个聊天程序的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56793025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com