APUE练习------进程相关之fork函数的使用

案例:

创建一个子进程并且分别打印子进程和父进程的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个子进程

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值