0
int main()
{
int fd=open("/dev/pts/0",O_RDWR);
if(fd==-1){
  printf("Error");
  exit(1);
}
dup2(fd,0);
char c[20];
printf("reading from file\n");
scanf("%s",c);
}

在上面的代码"/dev/pts/0"中设置为 stdin.scanf 行为正常。但是当我设置为文件名时,"inp.txt"它不会等待直接读取它找到的任何内容。为什么会这样?如果我想让它等待怎么办?

4

1 回答 1

3

When you read from a file, the data is already there, so why would scanf() wait? Or any other way of reading the file?

/dev/pts/<i>N</i> are Unix 98 pseudoterminals, which by their very nature are interactive. A blocking read from one waits for interactive input. A nonblocking read would just tell you that there is no data to read right now.

If you create a pipe between processes, associate the read end with an stdio FILE handle via fdopen(), you can use scanf() to scan data from the pipe. That, too, will wait for input, unless all write ends of the pipe are closed (then the scanf will fail with end-of-input). So, there is nothing special about the pseudoterminals in this respect.

于 2021-02-22T11:11:58.747 回答