Linux-2——关于fork()函数
参考:
https://www.cnblogs.com/dongguolei/p/8086346.html
理解下列代码:
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
// An highlighted block
#include <unistd.h>
#include <stdio.h>
int main ()
{
pid_t fpid; //fpid表示fork函数返回的值
int count=0;
fpid=fork();
if (fpid < 0)
printf("error in fork!");
else if (fpid == 0) {
printf("i am the child process, my process id is %d/n",getpid());
printf("我是爹的儿子/n");//对某些人来说中文看着更直白。
count++;
}
else {
printf("i am the parent process, my process id is %d/n",getpid());
printf("我是孩子他爹/n");
count++;
}
printf("统计结果是: %d/n",count);
return 0;
}
运行结果是:
i am the child process, my process id is 5574
我是爹的儿子
统计结果是: 1
i am the parent process, my process id is 5573
我是孩子他爹
统计结果是: 1
要点
1.调用fork()是创建一个新进程,与当前进程基本一致,且继续执行剩余部分。
2.fork() 在父进程中返回子进程的进程ID,在子进程中返回0,创建失败时返回负值。可理解为子进程没有子进程了所以返回0。
3.getpid()返回当前进程的ID。
4.子进程与父进程没有固定的执行顺序关系,哪个进程先执行要看系统的调度策略。