Linux进程控制
进程概念:
一个具有一定独立功能的程序关于某个数据集合的一次运行活动,是系统进行资源分配和调度运行的基本单位
进程三态:就绪、执行、阻塞
进程ID(PID):标识进程的唯一数字
父进程ID:PPID
启动进程的用户ID:UID
进程互斥:
当有若干进程都要使用某一共享资源时,任何时刻最多允许一个进程使用,其他要使用该资源的进程必须等待,直到占用该资源的者释放了该资源
临界区:
进程中访问临界资源的那段程序代码称为临界区
进程同步:
一组并发进程按一定的顺序执行的过程称为进程间的同步,具有同步关系的一组并发进程称为合作进
程,合作进程间互相发送的信号称为消息或事件
进程调度:
按一定算法,从一组带运行的进程中选出一个来咱有CPU运行
调度方式:
抢占式、非抢占式
调度算法:
先来先服务调度算法、短进程优先调度算法、高优先级有线调度算法、时间片轮转法
死锁:
多个进程因竞争资源形成的一种僵局,若无外力这些进程将永远不能再向前推进
子进程:另一进程所创建的进程。
父进程:创建子进程的进程叫做父进程
进程控制编程:
获取ID:
#include <sys/types.h>
#include <unistd.h>
/*获取本进程ID*/
pid_t getpid(void)
/*获取父进程ID*/
pid_t getppid(void)
功能:获取本进程或者父进程ID
sys_getpid.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
printf("PID=%d\n",getpid());
printf("PPID=%d\n",getppid());
return 0;
}
运行结果
创建子进程:
#include <unistd.h>
pid_t fork(void)
#include <unistd.h>
pid_t vfork(void)
功能:创建子进程
返回值:
1、在父进程中,fork返回新创建子进程的PID
2、在子进程中,fork返回0
3、如果出现错误,fork返回一个负值
区别:
1、fork:子进程拷贝父进程的数据段
vfork:子进程与父进程共享数据段
2、fork:父、子进程的执行次序不确定
vfork:子进程先运行,父进程后运行
sys_fork.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
int count=0;
pid = fork();
count++;
printf("count = %d\n",count);
return 0;
}
运行结果
sys_vfork.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int count=0;
pid = vfork();
count++;
printf("count = %d\n",count);
exit(0);
}
运行结果
exec函数族:
用被执行的程序替换调用他的程序:
区别:
fork:创建一个新的进程,产生一个新的PID
exec:启动一个新程序,替换原有的进程,因此进程的PID不会改变
#include <unistd.h>
int execl(const char *path,const char *arg1,...)
path:被执行程序名(含完整路径)
arg1-argn:被执行程序所需的命令行参数,含程序名。空指针(NULL)结束。
sys_exec_execl.c
#include <stdio.h>
#include <unistd.h>
void main()
{
execl("/bin/ls","ls","-al","/etc/passwd",(char *)0);
}
运行结果
#include <unistd.h>
int execlp(const char *path,const char *arg1,...)
path:被执行程序名(不含整路径,将从path环境变量中查找该程序)
arg1-argn:被执行程序所需的命令行参数,含程序名。空 指针(NULL)结束
sys_exec_execlp.c
#include <unistd.h>
void main()
{
execlp("ls","ls","-al","/etc/passwd",(char *)0);
}
运行结果
#include<unistd.h>
int execv(const char *path,char * const argv[])
path:被执行程序名(含完整路径)
argv[]:被执行程序所需的命令行参数数组
sys_exec_execv.c
#include <unistd.h>
void main()
{
char *argv[]={"ls","-al","/etc/passwd",(char*)0};
execv("/bin/ls",argv);
}
运行结果
#include <stdlib.h>
int system(const char *string)
功能:调用fork产生子进程,由子进程来调用/bin/sh -c string来执行所代表的命令。
sys_exec_system.c
#include <stdlib.h>
void main()
{
system("ls -al /etc/passwd");
}
运行结果
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status)
功能:阻塞该进程,直到其某个子进程退出
sys_wait.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
pid_t pc,pr;
pc=fork();
if(pc==0){/*如果是子进程*/
printf("This is child process with pid of %d\n",getpid());
sleep(10);
}
else if(pc>0){/*如果是父进程*/
pr=wait(NULL);//等待
printf("I catched a child process with pid of %d\n",pr);
}
exit(0);
}
运行结果