[英]Piping to unistd.h read segfault
im trying to pipe into read but it keeps segfaulting after the second input. 我试图通过管道读取,但在第二次输入后仍然保持段错误。 what am i doing wrong?
我究竟做错了什么? Thanks in advance.
提前致谢。
$ ./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)
I attached the code of read as a reference, the important part is the read() 我附上了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
doesn't know anything about strings, so it just happily reads sizeof(buf)
characters without ever NUL-terminating buf
. read
对字符串一无所知,因此它很乐意读取sizeof(buf)
字符而无需使用NUL终止buf
。 Calling puts(buf)
then causes undefined behavior. 调用
puts(buf)
会导致未定义的行为。
You shouldn't be using such low-level functions for simple string I/O; 您不应该对简单的字符串I / O使用这样的低级函数。 prefer
getline
instead. 更喜欢使用
getline
。 If you do want to use read
, then read smaller chunks, check the return value on every call and use it; 如果确实要使用
read
,则读取较小的块,检查每个调用的返回值并使用它; it tells you how much was read. 它告诉您读了多少书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.