Implicit system calls in UNIX commands

I've been studying UNIX and system calls and I came across a low-level and tricky questions. The question asks what system calls are called for this command:

grep word1 word2 > file.txt

I did some research and I was unable to find a huge number of resources on the underlying UNIX calls. However, it seems to me that the answer would be open (to open and the file descriptor for the file file.txt ), then dup2 (to change the STDOUT of grep to the file descriptor of open ), then write to write the STDOUT of grep (which is now the file descriptor of file.txt ), and finally close() , to close the file descriptor of file.txt ... However, I have no idea if I am right or on the correct path, can anyone with experience in UNIX enlighten me on this topic?


You are on correct direction in your research. This command is very helpful to trace system calls in any program:

strace

On my PC it shows output (without stream redirection):

$ strace grep abc ss.txt
execve("/bin/grep", ["grep", "abc", "ss.txt"], [/* 237 vars */]) = 0
brk(0)                                  = 0x13de000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f1785694000
close(3)                                = 0
ioctl(1, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0
stat("ss.txt", {st_mode=S_IFREG|0644, st_size=13, ...}) = 0
open("ss.txt", O_RDONLY)                = 3
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, 0x7fffa0e4f370) = -1 ENOTTY (Inappropriate ioctl for device)
read(3, "abcn123n321nn", 32768)     = 13
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 2), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f178568c000
write(1, "abcn", 4abc
)                    = 4
read(3, "", 32768)                      = 0
close(3)                                = 0
close(1)                                = 0
munmap(0x7f178568c000, 4096)            = 0
close(2)                                = 0
exit_group(0)                           = ?
链接地址: http://www.djcxy.com/p/78006.html

上一篇: 递归地查找具有特定扩展名的文件

下一篇: UNIX命令中的隐式系统调用