在進行輸入重定向時,shell 在“<”右側打開檔案描述符為 0 的檔案,但在 heredoc 的情況下,沒有要打開的檔案,我想知道 shell 在這種情況下到底做了什么。
cat > file.txt << EOF
line1
line2
EOF
uj5u.com熱心網友回復:
在 bash 5.0 和更早版本中,它會創建一個臨時檔案,寫入 heredoc 內容,然后將該檔案重定向到標準輸入。
我們可以看到發生了這種情況strace,它顯示了系統呼叫。以下是用行內注釋注釋的相關部分:
$ strace -f bash -c $'cat > file.txt << EOF\nline1\nline2\nEOF'
# Open a temporary file `/tmp/sh-thd-1641928925`.
[pid 8292] open("/tmp/sh-thd-1641928925", O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600) = 3
# Write the heredoc contents to the file.
[pid 8292] dup(3) = 4
[pid 8292] write(4, "line1\nline2\n", 12) = 12
[pid 8292] close(4) = 0
# Open the file read-only.
[pid 8292] open("/tmp/sh-thd-1641928925", O_RDONLY) = 4
# Close the original file and unlink it so there's no filesystem
# reference. The file will be fully deleted once all fds are closed.
[pid 8292] close(3) = 0
[pid 8292] unlink("/tmp/sh-thd-1641928925") = 0
# Redirect the file to stdin.
[pid 8292] dup2(4, 0) = 0
[pid 8292] close(4) = 0
# Execute `cat`.
[pid 8292] execve("/usr/bin/cat", ["cat"], 0x187c160 /* 113 vars */) = 0
uj5u.com熱心網友回復:
直到bash 5.1,它將 here-document 的內容復制到一個臨時檔案,然后將輸入重定向到該檔案。
從 5.1 開始,這取決于 here-document 的大小。如果它適合管道緩沖區,它會打開創建一個管道并將 here-document 的內容寫入管道。如果它太大,它會恢復到臨時檔案方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408875.html
標籤:
