案例:
创建一个子进程并且分别打印子进程和父进程的id号
代码实现
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
//创建子进程
int main(int argc,char* argv[]){
//定义pid
pid_t pid;
printf("this is befor function\n");
pid=fork();
//返回-1说明进程创建失败
if(pid == -1){
perror("fork");
exit(1);
}
//如果返回0说明子进程成功创建
else if(pid == 0){
printf("now child has been creat success\n pid is %d\n",getpid());
printf("my father is not run ,son is run\n pid of father is %d\n",getppid());
}
//非零整数为父进程id
else{
//此处为父进程执行
printf("father is run\n pid is %d\n",getpid());
printf("father is run\n pid of grand father is %d\n",getppid());
sleep(1);
}
return 0;
}
结果图
案例:
循环创建5个子进程,在命令行输入指定个数,即创建此个数,否则默认创建5个子进程
代码实现
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char* argv[]){
//判断输入格式
int n =5,i;
//如果用户指定个数则fork指定个数的进程,否则默认新建5个进程
if(argc == 2){
n = atoi(argv[1]);
}
for(i = 0;i < n;i++){
int fk = fork();
if(fk==-1){
perror("fork");
}
//如果是0,说明子进程成功创建(并且退出)
if(fk == 0){
break;
}
}
//i<创建的子进程个数时时子进程退出
if(i < n){
sleep(i);
printf("i am %d child ,my pid is %d, my father id is %d\n",i+1,getpid(),getppid());
}
else{
sleep(i);
printf("i am father , my pid is %d,my father pid is %d\n",getpid(),getppid());
}
return 0;
}
效果图
输入创建指定子进程个数
默认创建5个子进程