我写了这个程序
main()
{
int pid;
pid=fork();
if(pid==0)
printf("\nI am child\n");
else
printf("\nI am parent\n");
return 0;
}
执行时的输出是
./a.out
I am parent
I am child
当我使用 strace 程序运行时,输出是 [Last part]
arch_prctl(ARCH_SET_FS, 0x7fd1bbf52700) = 0
mprotect(0x7fd1bbd47000, 16384, PROT_READ) = 0
mprotect(0x7fd1bbf70000, 4096, PROT_READ) = 0
munmap(0x7fd1bbf54000, 103886) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fd1bbf529d0) = 5109
I am child
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
--- SIGCHLD (Child exited) @ 0 (0) ---
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd1bbf6d000
write(1, "\n", 1
) = 1
write(1, "I am parent\n", 12I am parent
) = 12
exit_group(13) = ?
输出显示 parent 首先运行,但 strace 输出似乎显示 child 先运行,因为它首先打印。
规则是什么?