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

I can't understand the result of this chatting program

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

我的问题是:当我键入一条包含 space 的消息时,接收进程运行了几次字数。

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

当我输入要发送的内容时,进程将 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" 中的 space,这意味着它也会忽略输入开头的任何白色 space。因此,当它通过循环读取下一个 运行 上的 Server 时,这会使其忽略 HelloServer 之间的 space。结果循环了五次,每次的消息分别是HelloServerthisisclient

相反,您可以使用 getline:

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

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

scanf(" %99s", msg);

例如,对于大小为 100 的缓冲区,这意味着只能读入 99 char,外加一个空终止符。这样您就可以避免在用户将输入一个对您的缓冲区来说太大的字符串。