进程管理(3.1)
本课学习如何创建进程以及进程的执行顺序
一 进程控制
1.创建进程创建进程;
函数执行后,系统会创建一个与原进程几乎相同的进程,之后父子进程都继续执行
#include <unistd.h> pid_t fork(void);
返回值说明:
成功:返回两个值,子进程创建成功后,原程序会被复制,就有了两个fork函数。父进程的fork函数会返回子进程的pid,子进程的fork函数会返回0.
不成功:若子进程创建失败,原程序不会复制,父进程的fork函数返回-1。
---使用fork函数创建一个进程,创建成功后父子进程分别执行不同的功能---
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
多次执行test_fork会发现,child process后输出的ppid不等于parent process的pid,而等于1。
是因为父进程先于子进程终止,子进程变成“孤儿进程”,后面由init进程来接收。
2.创建多个进程
int i; for(i = 0; i < 2; i ++){ tempPid = fork(); }//of for i
如下代码有以下问题:
子进程的编号不是递增的;
终端提示符后面仍然有子进程信息打印,而命令提示符在最后一行的开头闪烁。
原因:
在Linux系统中,子进程应由父进程回收,但是当子进程被创建后,它与它的父进程及其它进程共同竞争系统资源,所以父子进程执行的顺序是不确定的,终止的先后顺序也是不确定的。
Shell命令提示符也是1个进程,它需要和新建进程一起竞争CPU。
test_fork2.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 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
二:进程的执行顺序
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
利用sleep函数 暂缓进程执行