gpt4 book ai didi

c - 为什么从管道读取会产生垃圾值?

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

// Some code for initialization

int fd[2];
pipe(fd);
int k = fork();

if (k == 0) { // Child
dup2(fd[1], fileno(stdout));
execl("someExecutable", NULL); // The executable just printfs one line
}
else if (k > 0) { // Parent
wait(&status);
while (read(fd[0], buffer, 1) > 0) {
printf("%s", buffer);
}
}

我省略了错误检查。

首先,如果我的可执行文件有 printf("some line\n");,我在屏幕上的输出看起来像 s?9o?9m?9e?9 ?9l?9i? 9n?9e?9。为什么中间会有这些随机字符?

其次,我的阅读永无止境。当可执行文件结束时,管道的读取端应该已经关闭了吗?

谢谢。

最佳答案

您正在打印二进制数据。以下

 while (read(fd[0], buffer, 1) > 0) {
printf("%s", buffer);
}

将打印直到它得到 NULL 即 '\0'。试试这个吧

 while (read(fd[0], buffer, 1) > 0) {
printf("%.*s", 1, buffer);
}

此代码可能有助于说明有关 printf 和空终止字符串的要点...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void) {
srand(time(NULL));
size_t n = 0;
//First we create some random data.
//Lets assume this is our binary stream
char *str_cpy = malloc(1024);
n = 0;
while(n++ < 1024) {
str_cpy[n] = rand() % 255;
}
//We have a known string we want to print
const char *str = "foobar";
printf("%s\n", str);
memcpy(str_cpy, str, 6);//Ooops: forgot to copy the null terminator
size_t str_len = strlen(str_cpy);
// This is unlikely to print 6
printf("%zu\n", str_len);
//This is undefined behavior
printf("%s\n", str_cpy);
free(str_cpy);
return 0;
}

关于c - 为什么从管道读取会产生垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36049707/

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