目录
前言
本节课学习了进程控制,主要包含了如何利用fork()函数创建单个进程,多个进程,以及如何利用sleep()函数暂缓进程执行。
一、进程控制
fork()
exec函数族
wait()
exit()
二、创建单个进程
1.创建单个进程
#include <unistd.h>
pid_t fork(void);
- 功能:函数执行后,系统会创建一个与原进程几乎相同的进程,之后父子进程都继续执行。
- 返回值: 成功:返回两个值,子进程创建成功后,原程序会被复制,就有了两个fork函数。父进程的fork函数会返回子进程的pid,子进程的fork函数会返回0. 不成功:若子进程创建失败,原程序不会复制,父进程的fork函数返回-1。
1.1.案例:
使用fork函数创建一个进程,创建成功后父子进程分别执行不同的功能。
代码如下(示例):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t tempPid;
tempPid = fork();
if(tempPid == -1){
perror("fork error");
}else if(tempPid > 0){//parent
printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
}else{//child
printf("child process, pid = %d, ppid = %d\n", getpid(), getppid());
}//of if
printf("......finish......");
return 0;
}//of main
执行后结果如下:
2.创建多个进程
在Linux系统中,子进程应由父进程回收,但是当子进程被创建后,它与它的父进程及其它进程共同竞争系统资源,所以父子进程执行的顺序是不确定的,终止的先后顺序也是不确定的。
Shell命令提示符也是1个进程,它需要和新建进程一起竞争CPU。
2.1.案例:
#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......");
return 0;
}//of main
执行结果如下:
3.进程的执行顺序:sleep函数
功 能: 执行挂起一段时间
3.1案例:
#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......");
return 0;
}//of main