fork函数初用
了解了进程的相关概念后,我们来最简单的试用以下进程。
查看手册,fork函数
可以看到,调用fork后,会立刻创建一个子进程,我们简单看看效果,打印一下自己的进程号。
int main(){
pid_t pyd;
pid_t qinyu;
pyd=getpid();
printf("befor getpid is : %d\n",pyd);
fork();
qinyu=getpid();
printf("aftere getpid is : %d\n",qinyu);
if(pyd==qinyu){
printf("the is father getpid\n");
}
else{
printf("the is person getpid,have is : %d\n",qinyu);
}
getpid() //获取自身进程
调用fork()后形成又一个进程,程序又从fork开始又走一遍
befor getpid is : 18337
aftere getpid is : 18337
the is father getpid
CLC@Embed_Learn:~/proceed$ aftere getpid is : 18338
the is person getpid,have is : 18338
使用fork函数创建一个进程
pid_t fork(void);
fork函数调用成功,返回两次
返回值为0, 代表当前进程是子进程
返回值非负数,代表当前进程为父进程
pid_t pyd;
printf("father getpid is : %d\n",getpid());
fork();
if(pyd>0){
printf("the is father getpid\n",getpid());
}
else if(pyd==0){
printf("the is person getpid,have is : %d\n",getpid());
}
return 0;
father getpid is : 18419
the is person getpid,have is : 18419
CLC@Embed_Learn:~/proceed$ the is person getpid,have is : 18420
调用失败,返回-1
父进程和字进程一目了然了