栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux编程基础 3.1:进程管理-1

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux编程基础 3.1:进程管理-1

1 进程控制

fork()
exec函数族
wait()
exit()

1.1 创建进程
#include 
pid_t fork(void);

功能:创建进程;函数执行后,系统会创建一个与原进程几乎相同的进程,之后父子进程都继续执行,如图所示:

图 fork函数创建子进程

参数说明:无

返回值说明

  • 成功:返回两个值,子进程创建成功后,原程序会被复制,就有了两个fork函数。父进程的fork函数会返回子进程的pid,子进程的fork函数会返回0.
  • 不成功:若子进程创建失败,原程序不会复制,父进程的fork函数返回-1。

【案例 1】使用fork函数创建一个进程,创建成功后父子进程分别执行不同的功能。

test_fork.c
#include 
#include 
#include 
int main(){
	pid_t tempPid;
	tempPid = fork();
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		printf("parent process, pid = %d, ppid = %dn", getpid(), getppid());
	}else{//child
		printf("child process, pid = %d, ppid = %dn", getpid(), getppid());
	}//of if
	printf("......finish......");
	return 0;
}//of main

【思考 1】多次执行test_fork会发现,child process后输出的ppid不等于parent process的pid,而等于1。请说明原因。
【提示】出现这种情况,是因为父进程先于子进程终止,子进程变成“孤儿进程”,后面由init进程来接收。

1.2 创建多个进程

上面的案例是创建一个子进程,如果要创建多个子进程呢?
可否对上面的案例进行修改,进行简单的循环即可:

int i;
for(i = 0; i < 2; i ++){
	tempPid = fork();
}//of for i

分析如下:

  • 每次调用fork函数,系统会复制原程序
  • i=0,第一次循环,会有两份test_fork文件
  • i=1,第二次循环,第一份test_fork文件又会有两份test_fork文件,第二份test_fork文件也会有两份
  • 每一次循环,进程的总数是当前进程数量的两倍,2次循环则为 2 2 = 4 2^2 = 4 22=4个进程。

【解决方法】:如果只希望父进程可以创建新进程,则在for循环中添加一个判断:若当前进程不是父进程,则跳出循环。

【案例 2】

test_fork2.c
#include 
#include 
#include 
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		}//of if
	}//of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		printf("parent process, pid = %d, ppid = %dn", getpid(), getppid());
	}else{//child
		printf("I am child process = %d, pid = %d, ppid = %dn", i + 1, getpid(), getppid());
	}//of if
	printf("......finish......");
	return 0;
}//of main

【思考 2】:案例2的输出结果有如下问题:
(1)子进程的编号不是递增的;
(2)终端提示符后面仍然有子进程信息打印,而命令提示符在最后一行的开头闪烁。
这是为什么?


提示:
在Linux系统中,子进程应由父进程回收,但是当子进程被创建后,它与它的父进程及其它进程共同竞争系统资源,所以父子进程执行的顺序是不确定的,终止的先后顺序也是不确定的。
Shell命令提示符也是1个进程,它需要和新建进程一起竞争CPU。

1.3 进程的执行顺序:利用sleep函数,暂缓进程执行

【案例 3】

test_fork3.c
#include 
#include 
#include 
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		}//of if
	}//of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		sleep(2);
		printf("parent process, pid = %d, ppid = %dn", getpid(), getppid());
	}else{//child
	 	sleep(i);
		printf("I am child process = %d, pid = %d, ppid = %dn", i + 1, getpid(), getppid());
	}//of if
	printf("......finish......");
	return 0;
}//of main
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/860916.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号