参考文章:(11条消息) Linux编程基础 3.1:进程管理-1_HenrySmale的博客-CSDN博客
指导老师:张恒汝
1 进程控制
本节课所学函数如下;
fork() 创建子进程
exec函数族
wait()
exit()
1.1 创建进程
pid指当前进程的进程ID,ppid为父进程的进程id
运行如下代码发现pid!=ppid,原因父进程先于子进程终止,导致子进程编程孤儿进程。
函数案例
test_fork.c
#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
结果:
1.3 进程的执行顺序:利用sleep函数,暂缓进程执行
test_fork3.c
#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
结果: