mian process 使用getpid()函数获取自己的进程号
创建子进程:fork()函数创建一个与父进程一模一样的进程,
返回值:父进程中返回子进程的pid 子进程中返回0 -1:err
使用getpid():获得自己的进程号 getppid():获得父进程的pid
exit(aa) 进程调用exit退出进程 并向父进程传递状态 返回自杀进程的pid
exit之后,进程还有一点点残余留在内存中, 僵尸进程
父进程调用wait,阻塞等待任意子进程结束,一旦子进程结束,wait立马返回,
获取孩子的进程号和死亡状态,并完成收尸
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
printf("main process pid=%d\n",getpid());
pid_t pid = fork();
if(pid<0){
perror("fork err");
return -3;
}
if(pid==0){
printf("1sub process pid=%d ppid=%d\n",getpid(),getppid());
int n=5;
while(1){
n--;
if(n==0){ exit( 11 );} //自杀,向父亲传递一个值
printf("I am 11st subprocess \n");
sleep(1);
}
}
//下面一定是父亲.
//再次生一个孩子
pid = fork();
if(pid<0){
perror("fork err");
return -3;
}
if(pid==0){
printf("2sub process pid=%d ppid=%d\n",getpid(),getppid());
int n=8;
while(1){
n--;
if(n==0){ exit( 8 );} //自杀,向父亲传递一个值
printf("I am 2st subprocess \n");
sleep(1);
}
}
/*
父进程调用wait,阻塞(卡在那里)的等待 任意子进程结束,
一旦某个子进程结束,wait立马返回,获取孩子的进程号和死亡状态,并完成收尸过程
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
status存放 子进程exit()传参
exit的传参是一个 char数据,存放在了 wait参数的8-15bit
返回值: 死亡孩子的pid
用法: 一般当父进程想自我了解的时候,最后一步调用wait ,当所有子进程结束,父进程结束.
*/
int n=2;
while(n--){
int dead_stat;
pid_t subpid = wait(&dead_stat);
printf("find subprocess %d stat=%d\n",subpid, (dead_stat&0xFF00)>>8);
}
return 0;
}
注:(dead_stat&0xFF00)>>8 因为exit函数返回的值存放再wait函数的低8bit所以需要右移八位
通过以上操作可以创建与父进程一摸一样的进程,但实战中我们不会用两个进程去执行一摸一样的任务,execl:子进程调用该函数就可以去到另一个空间执行自己的任务
父进程:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("I am main process %d\n",getpid());
pid_t pid=fork();
if(pid==0){
printf("I am sub process %d\n",getpid());
//后面自由世界,子进程想执行的是 sub.out
execl("./sub.out",NULL);
}else if(pid>0){
printf("I am father pid=%d\n",getpid());
while(1){
printf("I am father\n");
sleep(2);
}
}
return 0;
}
子进程执行的任务
int main()
{
printf("I am sub.out pid=%d\n",getpid());
while(1){
printf("I am sub.out \n");
sleep(1);
}
return 0;
}