2012-11-08 19 views
2

即时尝试管道读入,但它保持第二次输入后的段失效。我究竟做错了什么?提前致谢。管道到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.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; 
} 

`

+3

您需要检查大部分库调用的返回码。 'read()'尝试读取多达4096个字节,因此在第一次调用时会消耗整个输入 - 它不会简单地读取第一行。因此,你对read()的第二次调用没有任何意义,并且你有一堆你没有检查的假设,导致你复制和操纵那些不是你认为它们的“字符串”。 – twalberg

+1

不要使用'strncpy',[它可能不会null-终止字符串](http://stackoverflow.com/questions/1453876/why-does-strncpy-not-null-terminate)。 –

回答

4

read不知道串什么,所以它只是愉快地读取sizeof(buf)个字符而没有NUL终止buf。调用puts(buf)会导致未定义的行为。

你不应该使用简单的字符串这样的低级函数I/O;改为使用getline。如果你想使用read,那么读取更小的块,检查每次调用的返回值并使用它;它告诉你读了多少。