gpt4 book ai didi

c - 解释 STRACE 输出——管道和分支

转载 作者:太空狗 更新时间:2023-10-29 12:02:48 25 4
gpt4 key购买 nike

我有以下用 C 编写的代码,摘自 https://beej.us/guide/bgipc/html/multi/pipes.html :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
int pfds[2];

pipe(pfds);

if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
execlp("/bin/ls", "ls", NULL);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
execlp("/usr/bin/wc", "wc", "-l", NULL);
}

return 0;
}

当使用 strace 在终端中编译和运行此代码时,我得到以下输出:

execve("./forks", ["./forks"], [/* 55 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f2b0e498700) = 0
pipe([3, 4]) = 0
clone(Process 7304 attached
child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2b0e4989d0) = 7304
[pid 7303] execve("/usr/bin/wc", ["wc", "-l"], [/* 55 vars */] <unfinished ...>
[pid 7304] execve("/bin/ls", ["ls"], [/* 55 vars */] <unfinished ...>
[pid 7303] <... execve resumed> ) = 0
[pid 7304] <... execve resumed> ) = 0
[pid 7303] arch_prctl(ARCH_SET_FS, 0x7f558acde700) = 0
[pid 7304] arch_prctl(ARCH_SET_FS, 0x7f4bef4f67c0) = 0
[pid 7304] exit_group(0) = ?
Process 7304 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
21
exit_group(0)

任何人都可以逐行解释 strace 输出中发生了什么吗?我试图研究如何解释 strace 输出,但没有任何运气。

提前致谢。

最佳答案

execve("./forks", ["./forks"], [/* 55 vars */]) = 0

Shell 使用您的可执行文件和 ./forks 作为 argv[0] 调用 execve/* 55 vars */是从shell继承的环境变量。

arch_prctl(ARCH_SET_FS, 0x7f2b0e498700) = 0

可能为新启动的进程设置线程本地存储。

pipe([3, 4])

pipe 系统调用返回一对描述符,34。这些数字是这样的,因为到目前为止,除了 0 (stdin)、1 (stdout) 和 2 (stderr) 之外,没有其他描述符被分配给过程。

clone(Process 7304 attached child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2b0e4989d0) = 7304

clone 系统调用对应于对 fork 的调用,生成一个新进程。尽管 fork 通常被称为系统调用,尤其是在 Linux 上,它包装了对 clone(2) 的调用。

[pid  7303] execve("/usr/bin/wc", ["wc", "-l"], [/* 55 vars */] <unfinished ...>
[pid 7304] execve("/bin/ls", ["ls"], [/* 55 vars */] <unfinished ...>
[pid 7303] <... execve resumed> ) = 0
[pid 7304] <... execve resumed> ) = 0
[pid 7303] arch_prctl(ARCH_SET_FS, 0x7f558acde700) = 0
[pid 7304] arch_prctl(ARCH_SET_FS, 0x7f4bef4f67c0) = 0
[pid 7304] exit_group(0)

在父进程和子进程中,启动了两个新的可执行文件。子进程以 [pid 7304] exit_group(0) 退出,父进程立即收到 SIGCHLD 信号,表明子进程已更改其状态。

关于c - 解释 STRACE 输出——管道和分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28767414/

25 4 0