1.fork() 和vfork()都是创建一个新的进程.但是存在区别: fork()新创建出来的子进程和父进程对调度器而言是平等的,不能知道哪个进程先执行,由调度器决定. 而vfork()创建的子进程一定比父进程先执行. 实例如下:
test.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
pid_t pid = 0;
pid = fork();
if(pid < 0)
{
printf("fork error \n");
exit(1);
}
else if(pid == 0)
{
printf("Child process \n");
exit(0);
}
printf("Parent process \n");
return 0;
}
运行结果:
./test
Parent process
Child process
我的调度器优先调用了父进程执行.
test1.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
pid_t pid = 0;
pid = fork();
if(pid < 0)
{
printf("fork error \n");
exit(1);
}
else if(pid == 0)
{
printf("Child process \n");
exit(0);
}
sleep(3);
printf("Parent process \n");
return 0;
}
让父进程先休眠3秒,子进程优先被调度.
运行结果:
./test1
Child process
Parent process
test2.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
pid_t pid = 0;
pid = vfork();
if(pid < 0)
{
printf("fork error \n");
exit(1);
}
else if(pid == 0)
{
printf("Child process \n");
exit(0);
}
printf("Parent process \n");
return 0;
}
使用vfork() 后,不用父进程休眠,子进程也会被优先调度.
运行结果:
./test2
Child process
Parent process

本文详细介绍了fork()和vfork()这两种用于创建子进程的函数,解释了它们之间的主要区别,并通过代码示例展示了如何使用它们。通过对比不同场景下的运行结果,帮助读者理解何时选择使用fork(),何时使用vfork(),以及它们对调度器的影响。
3288

被折叠的 条评论
为什么被折叠?



