gpt4 book ai didi

c - 简单的 30 个字符缓冲区 PIPE 打印不可打印的字符,不知道为什么

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:34 24 4
gpt4 key购买 nike

我使用一个简单的 fork() 来模拟客户端/服务器,然后使用一个非常简单的管道来发送/接收最大长度为 30 的字符缓冲区,但它最终打印出不可打印的字符(小“?”和一个带有 4 的框ones 和 zeroes) AFTER 所需的单词。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>

int main () {
int pipefd[2];
int cpid;
char buf[31];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE)
}
cpid = fork();
if (cpid == -1) P
perror("cpid");
exit(EXIT_FAILURE);
}
if (cpid == 0) { // child reads from pipe
close (pipefd[1]); // close unused write end
read (pipefd[0], &buf, 30); // if I use 30 instead of strlen(buf) it prints Server transmit: Server receives. It does not wait for write. Makes no sense
printf ("Server receives: %s", buf);
close (pipefd[0])l
exit (EXIT_SUCCESS);
}
else { // parent writes to pipe
close (pipefd[0]); // closing unused read end;
char buf2[30];
printf("Server transmits: ");
scanf ("%s", buf2);
write (pipefd[1], buf2, strlen(buf2));
close(pipefd[1]);
wait(NULL);
exit(EXIT_SUCCESS);
}
return 0;
}

此外,如果我写了多个单词,它会忘记第二个单词。在 C++ 中,我使用了 getline (cin, string) 但这不是这里的选项。

还使用了 read (pipefd[0], &buf, sizeof(buf));,现在它以正确的顺序打印(不知道为什么 strlen 不起作用)但我仍然无法打印字符在最后。

最佳答案

当您编写 (pipefd[1], buf2, strlen(buf2)); 时,您忽略了将 '\0' 放入流中。将其更改为:

write (pipefd[1], buf2, strlen(buf2)+1);

并且您的字符串现在将包含空终止符,以防止末尾出现垃圾。

使用 read (pipefd[0], &buf, strlen(buf)) 无效,因为 buf 未初始化。 strlen 是一个简单的函数,它在字符串的末尾查找终止 null,在找到时停止。与 C++ vector 的 length 函数不同,C 函数无法访问内存元数据。 (sizeof是一个运算符)

关于c - 简单的 30 个字符缓冲区 PIPE 打印不可打印的字符,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942926/

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