[英]Why I call fork() in C but make sys_clone() syscall instead? Why not sys_fork() syscall?
Here is my source code test.c:这是我的源代码test.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
pid_t pid;
pid=fork();
if(pid==0){
printf("new process\n");
}else{
printf("old process\n");
}
return 0;
}
I compiled it by:我通过以下方式编译它:
gcc test.c -o fork
And I found it make sys_clone() syscall instead of sys_fork() by strace.我发现它通过 strace 使 sys_clone() 系统调用而不是 sys_fork()。
$strace -o my ./fork
new process
old process
$cat my | grep clone
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f459f17d810) = 4415
$cat my | grep fork
execve("./fork", ["./fork"], 0x7ffc76ccbf00 /* 52 vars */) = 0
see clone() in the scripts?看到脚本中的克隆()? why not fork?
为什么不分叉?
clone(2)
is a Linux specific system call that superseded fork(2)
system call. clone(2)
是一个 Linux 特定的系统调用,它取代了fork(2)
系统调用。 So clone
is used for creating all the "process-like" entities (for creating threads, implementing vfork, posix_spawn and so on) on Linux.因此,
clone
用于在 Linux 上创建所有“类似进程”的实体(用于创建线程、实现 vfork、posix_spawn 等)。 Basically, fork
is equivalent to clone
with specific flags.基本上,
fork
等同于带有特定标志的clone
。 So that's why you see clone
under strace
.这就是为什么您在
strace
下看到clone
的原因。
Of course, the POSIX fork
isn't deprecated and isn't going to disappear.当然, POSIX
fork
并没有被弃用,也不会消失。 So use of fork
isn't an issue.所以使用
fork
不是问题。 Just that C library implementations on Linux use clone
system call to implement fork
.只是 Linux 上的 C 库实现使用
clone
系统调用来实现fork
。
In some versions of several C libraries for Linux (eg GNU libc or musl-libc ), the fork
function is actually implemented by a call to clone
在 Linux 的几个C 库的某些版本中(例如GNU libc或musl-libc ),
fork
function 实际上是通过调用clone
实现的
Since these libraries are open source, you could download their source code and study it (or even improve that source code)由于这些库是开源的,您可以下载它们的源代码并进行研究(甚至改进该源代码)
See also ldd(1) , syscalls(2) , fork(2) , clone(2) , uname(2) , errno(3) , execve(2) , elf(5) , credentials(7) , ld.so(8) etc.... and read Advanced Linux Programming另请参见ldd(1) 、 syscalls(2) 、 fork(2) 、 clone(2) 、 uname(2) 、 errno(3) 、 execve(2) 、 elf(5) 、 credentials(7) 、 ld.so (8)等等......并阅读Advanced Linux Programming
Perhaps some C libraries are using clone
or fork
depending of the result of some initial call to uname(2)也许一些 C 库正在使用
clone
或fork
,具体取决于对uname(2)的一些初始调用的结果
Read also some good textbook on operating systems .还可以阅读一些关于操作系统的好教科书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.