python - 通过管道传输到 unistd.h 读取段错误

标签 python c linux piping unistd.h

我试图通过管道读取,但在第二次输入后它仍然出现段错误。我究竟做错了什么?提前致谢。

 $ ./read < <(python -c 'print "BBA\nBBADD\n",')
 Please enter your first name: 
 buf=
 BBA
 BBA
 Please enter your last name: 
 buf=
 Segmentation fault (core dumped)

我附上了read的代码作为引用,重要的部分是read()

//read.c
#include <stdio.h>
#include <string.h>

void prompt_name(char *name, char *msg){
    char buf[4096];

    puts(msg);

    read(0, buf, sizeof buf);
puts("buf=");
puts(buf);
    *strchr(buf, '\n') = 0;

puts(buf);
    strncpy(name, buf, 20);
puts(name);
}

void prompt_full_name(char *fullname) {
    char last[20];
    char first[20];

    prompt_name(first, "Please enter your first name: ");
    prompt_name(last, "Please enter your last name: ");

    strcpy(fullname, first);
    strcat(fullname, " ");
    strcat(fullname, last);
}


int main(int argc, char **argv){
    char fullname[42];

    prompt_full_name(fullname);
    printf("Welcome, %s\n", fullname);

    return 0;
}

`

最佳答案

read 对字符串一无所知,因此它只是愉快地读取 sizeof(buf) 字符,而不会以 NUL 结尾 buf。调用 puts(buf) 会导致未定义的行为。

您不应该将此类低级函数用于简单的字符串 I/O;更喜欢 getline 。如果您确实想使用read,则读取较小的 block ,检查每次调用的返回值并使用它;它告诉您阅读了多少内容。

关于python - 通过管道传输到 unistd.h 读取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13291199/

相关文章:

python - 在循环内保留过滤器输出

javascript - 使用从 Django 中的某个 URL 获取的附加文件预填写表单

c - 尝试替换由 C 中链表中的节点组成的单词

c - 在 C 中将参数从 ComboBox 传递到 GTKTreeView

linux - 如何在 Oracle Linux 中将内核版本从 6.8 降级到 6.7

c - 在一行中输出 C 语言中的 system()

python - 在Python中使用Structure和char数组

python - 在布局内的小部件内循环小部件

c - 宏如何输出双引号

linux - 如何使用导出使 LLVM_SRC_ROOT 等于/llvm