linux fork函数(创建一个与原来进程几乎完全相同的进程)学习实例
一、fork函数简介
1、linux中,可以通过fork函数创建一个与原来进程几乎完全相同的进程,叫子进程,原来的进程叫父进程。
2、man 2 fork,fork() creates a new process by duplicating the calling process.
3、系统函数fork调用成功,会创建一个新的进程,它几乎会调用差不多完全一样的fork进程。
4、子进程的pid和父进程不一样,是新分配的。子进程的ppid会设置为父进程的pid,也就是说子进程和父进程各自的“父进程”是不一样的。
5、返回值,执行成功子进程的pid返回给父进程,0返回给子进程;出现返回-1,错误,执行失败唯一的情况是内存不够或者id号用完了,很少出现这种情况。
二、实例测试
1、C语言代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
/*
* @brief main For the understanding of the fork()
*
* @param argc
* @param argv[]
*
* @return 在父进程中返回子进程的进程号;在子进程中返回0。
*/
int main(int argc, char *argv[])
{
pid_t pid;
int cnt = 0;
printf("\nmain process id is %d\n",getpid());
pid = fork();
if (pid == -1) {
perror("fork error");
exit(1);
}
else if (pid == 0) {//返回子进程0,返回值等于0返回给子进程 getpid() returns the process ID of the calling process.
printf("The child returned value is %d, My PID is %d,The child ppid is %d\n",pid, getpid(),getppid());
cnt++;
printf("child_process cnt=%d\n",cnt);
}
else {//返回给父进程子进程号,返回值大于0 //getppid() returns the process ID of the parent of the calling process.
printf("The father returned value is %d,My PID is %d,The father ppid is %d\n",pid, getpid(),getppid());
cnt++;
sleep(10);
printf("father process=%d\n",cnt);
cnt++;
}
printf("cnt = %d\n", cnt);
return 0;
}
2、编译&执行,分析父进程和子进程的getpid()和getppid()就可以很清楚的理解他们之间的关系。注意一下变量cnt的最终值,一个进程是1,一个进程是2,并不是两者相加起来。