Linux系统级程序设计(二 ):进程管理

1.创建单个进程

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

参数说明:无

返回值说明:

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

子进程创建失败,原程序不会复制,父进程的fork函数返回-1。

代码1

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    pid_t pid = 0;   
    pid = fork();    //创建进程
    if(pid == -1){          //fork()返回值为-1,调用失败
        perror("fork error.\n");
        exit(-1);
    }
    else if(pid > 0){
        printf("parent process, pid = %d, ppid = %d.\n", getpid(), getppid());     //getpid():获取当前进程的进程号
    }
    else if(pid == 0){            //fork()返回值为0,则该进程是子进程
        printf("child process, pid = %d, ppid = %d.\n", getpid(), getppid());           // getppid():获取父进程的进程号
    }
    printf("finish by liukun\n");
    return 0;
 
}

在这里插入图片描述

创建多个进程

每次调用fork函数,系统会复制原程序
i=0,第一次循环,会有两份test_fork文件
i=1,第二次循环,第一份test_fork文件又会有两份test_fork文件,第二份test_fork文件也会有两份
每一次循环,进程的总数是当前进程数量的两倍,2次循环则为 2^2 = 4个进程。
在Linux系统中,子进程应由父进程回收,但是当子进程被创建后,它与它的父进程及其它进程共同竞争系统资源,所以父子进程执行的顺序是不确定的,终止的先后顺序也是不确定的。
Shell命令提示符也是1个进程,它需要和新建进程一起竞争CPU。

代码2

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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 = %d\n", getpid(), getppid());
	}else{ //child
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	} //of if
	printf("finish by liukun);
	return 0;
} //of mains

在这里插入图片描述

进程的执行顺序:sleep函数

功能: 执行挂起一段时间

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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 = %d\n", getpid(), getppid());
	}else{ //child
		sleep(i);
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	} //of if
	printf("finish by liukun");
	return 0;
} //of mains

在这里插入图片描述

总结

学会了fork()的基本用法,对父进程和子进程有了更加清楚的认识,
了解了Linux终端的进阶用法,对程序的运行优先级和进程管理有了更深的认识。
fork()函数遵循“读时共享,写时复制”的原则;fork()仅仅被调用一次,却能够返回两次。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值