iob*_*der 7 unix linux command-line grep
如果我尝试将输出重定向grep到它正在读取的同一文件,如下所示:
$ grep stuff file.txt > file.txt
Run Code Online (Sandbox Code Playgroud)
我收到错误消息grep: input file 'file.txt' is also the output.怎么grep判断这个?
根据GNU grep源代码,grep检查输入和输出的i节点:
if (!out_quiet && list_files == 0 && 1 < max_count
&& S_ISREG (out_stat.st_mode) && out_stat.st_ino
&& SAME_INODE (st, out_stat)) /* <------------------ */
{
if (! suppress_errors)
error (0, 0, _("input file %s is also the output"), quote (filename));
errseen = 1;
goto closeout;
}
Run Code Online (Sandbox Code Playgroud)
将out_stat通过调用充满fstat对抗STDOUT_FILENO.
if (fstat (STDOUT_FILENO, &tmp_stat) == 0 && S_ISREG (tmp_stat.st_mode))
out_stat = tmp_stat;
Run Code Online (Sandbox Code Playgroud)