日期:2014-05-16  浏览次数:20654 次

Linux中进程的深入学习

进程


进程是在系统中能够独立运行的活动实体。由(机器指令)PCB,数据,堆栈组成。
引入进程的目的:为了使多个程序能够并发的执行,提高系统的吞吐量。

进程调度方式:
<1>非抢占式方式
<2>抢占式方式:优先权原则,短作业优先,时间片原则。

进程调度算法:
<1>先来先服务调度算法
<2>短作业优先调度算法
<3>高优先权调度算法
<4>基于时间片轮转调度算法

Linux系统中的进程类型
<1>交互进程:由shell控制和运行,可以在前台或后台运行。
<2>批处理进程:该进程被提交到队列中顺序执行。
<3>守护进程:该进程在后台运行。

Linux运行状态
<1>运行态
<2>等待态
<3>停止态
<4>死亡态

调度进程
ps    查看系统中的进程 aux-->显示该进程所有信息 elf  ajx
top   动态显示系统进程  q结束
kill  结束进程
bg    将挂起的进程放到后台执行
fg    把后台的进程放到前台运行

===================================================================
进程创建:fork()
头文件:#include <sys/types.h>
 #include <unistd.h>
函数体:pid_t fork(void);
返回值:0--->子进程  子进程的PID---->父进程   -1---->出错

例:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>

extern int errno;

int main()
{
 int a=10;
 pid_t pid;
 if(0 > (pid = fork()))
 {
  fprintf(stderr,"error :%s",strerror(errno));
  return -1;
 }
 else if(0 == pid)
 {
  a=100;
  printf("this is child %d\n",getpid());
  printf("this is parent %d\n",getppid());
  printf("a===%d\n",a);
 }
 else
 {
  sleep(2);
  printf("this is my child PID %d\n",pid);
  printf("this is myself PID %d\n",getpid());
  printf("a---%d\n",a);
 }
 printf("==================\n");
 return 0;
}

【注意】:
<1>父进程先exit(),子进程成为孤儿进程由init回收。
<2>子进程先exit(),变为等待父进程回收资源,如果父进程不退出,子进程变成僵尸进程。

exec()函数族
exec()用途:如果某个进程想同时执行另一个程序,他就可以调用fork()函数创建子进程,然后在子进程中调用任何一个exec()函数,就可以让子进程执行新的程序。

头文件: #include <unistd.h>
函数体: int execl(const char *path,const char *arg,...);
                int execv(const char *path,char *argv[]);
                int execle(const char *path,char *arg,...char *envp[]);
                int ececve(const char *path,char *argv[],chr *envp[]);
                int execlp(cosnt char *file,char *arg);
                int execvp(const char *file,char *argv[]);

例子:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
extern int errno;

int main()
{
 pid_t pid;

 if(0 > (pid = fork()))
 {
  fprintf(stderr,"e