Linux进程控制

进程创建

fork函数

创建一个新进程,新的进程为子进程,原进程为父进程。

#include <unistd.h>

pid_t fork(void);

返回值:自进程中返回0,父进程返回子进程id,出错返回-1

进程调用fork,当控制转移到内核中的fork代码后,内核做:

  • 分配新的内存块和内核数据结构给子进程
  • 将父进程部分数据结构内容拷贝至子进程
  • 添加子进程到系统进程列表
  • 当中 fork返回,开始调度器调度

当一个进程调用fork之后,就有两个二进制代码相同的进程。而且它们都运行到相同的地方。但每个进程都将可以 开始它们自己的旅程,看如下程序。

int main()
  6 {
  7  pid_t pid;
  8  printf("Before: pid is %d\n", getpid());
  9  if ( (pid=fork()) == -1 )perror("fork()"),exit(1);
 10  printf("After:pid is %d, fork return %d\n", getpid(), pid);
 11  sleep(1);
 12  return 0;
 13 }

fork函数返回值

  • 子进程返回0
  • 父进程返回的是子进程的pid

为什么父进程返回的是子进程的PID,而给子进程返回的是0呢?

外面为了让父进程方便对子进程进行标识,进而进行管理

写时拷贝

通常,父子代码共享父子再不写入时,数据也是共享的,当任意一方试图写入,便以写时拷贝的方式各自一份副本。具体见下图:

fork常规用法

  • 一个父进程希望复制自己,使父进程同时执行不同的代码段。例如,父进程等待客服端请求,生成子进程来处理请求。
  • 一个进程要执行一个不同的程序。例如,子进程从fork返回后,调用exec函数。

fork调用失败的原因

  • 系统中有太多的进程
  • 实际用户的进程数超过了限制

进程终止

1.想明白:终止是在干什么?

  1. 释放曾经的代码和数据所占据的空间
  2. 释放内核数据结构(task_struct,解决Z僵尸模式)

2.进程终止的3种情况

  1. 代码跑完,结果正确
  2. 代码跑完,结果不正确
  3. 代码执行时,出现了异常,提前退出了

衡量一个进程退出,我们只需要两个数字:退出码,退出信号!!!

退出码

对于前两种情况,可以通过退出码来决定!!

 int main()
 {
      printf("I am process,pid:%d,ppid:%d\n",getpid(),getppid());                                                                                                    
      return 100;
 }

  • echo $?表示的是获得最近一次进程的退出码,这里可以获取我们return的数字。
  • 在我们写程序的时候,main函数中的return后面带的这个数字表示的就是一个退出码,是告诉父进程我们任务完成得怎么样,如果为0,表示成功,如果为非0,表示为失败。
  • 对于非0的值,一方面表示失败,一方面也表示失败的原因,可以通过该值找到对应的原因。
  • 上面运行的结果中,ppid:12461表示为bash父进程,父进程bash为什么要得到子进程的退出码呢?
  • 原因就是要知道子进程退出的情况(成功、失败,失败的原因是什么?),都是为了为用户负责!

退出信号

对于第三种情况,当进程出异常,本质是因为进程收到了OS发给进程的退出信号,OS提前终止了进程。

意义:

我们可以看进程退出的时候,退出信号是什么,就可以判断我的进程为什么异常了!!!

3.如何终止?

正常终止

(可以通过echo $?查看进程退出码)

  1. main函数return,表示进程终止(非main函数的return只是表示函数结束)
  2. 代码调用exit函数(注意:任意位置调用exit都表示进程退出)
  3. 调用_exit函数(系统调用)

异常退出

  • ctrl + c,信号终止

_exit函数

#include <unistd.h>

void _exit ( int status);

参数:status定义了进程的终止状态,父进程通过wait来获取该值

  • 说明:虽然status是int,但是仅有低8位可以被父进程所用。所以_exit(-1)时,在终端执行$?发现返回值 是255。

exit函数

#include <unistd.h>

void exit(int status);

exit最后也会调用_exit, 但在调用_exit之前,还做了其他工作:

  1. 执行用户通过 atexit或on_exit定义的清理函数。
  2. 关闭所有打开的流,所有的缓存数据均被写入
  3. 调用_exit

注:也就是exit会清理缓冲区,而_exit不会。

int main()

{

        printf("hello");

         exit(0);

}

运行结果:

[root@localhost linux]# ./a.out hello

[root@localhost linux]

# int main()

{        

        printf("hello");

         _exit(0);

}

运行结果:

[root@localhost linux]# ./a.out

[root@localhost linux]#

return退出

return是一种更常见的退出进程方法。执行return n等同于执行exit(n),因为调用main的运行时函数会将main的返 回值当做 exit的参数。

进程等待

进程等待的必要性

  • 子进程退出,父进程如果不管不顾,就可能造成‘僵尸进程’的问题,进而造成内存泄漏。
  • 进程一旦变成僵尸状态,那就刀枪不入,“杀人不眨眼”的kill -9 也无能为力,因为谁也没有办法 杀死一个已经死去的进程。
  • 父进程派给子进程的任务完成的如何,我们需要知道。如,子进程运行完成,结果对还是不对, 或者是否正常退出。
  • 父进程通过进程等待的方式,回收子进程资源,获取子进程退出信息,解决进程退出的僵尸问题

总结:任何子进程,在退出的情况下,一般必须要被父进程进行等待,进程在退出的时候,如果父进程不管不顾,退出进程,就会有Z(僵尸状态),内存泄漏的危害。

我们c语言经常用到的scanf()函数中,如果子进程没有退出,父进程其实一直在进行阻塞等待!--->子进程本身结束软件,父进程本质是在等待某种软件条件的就绪。

进程等待的方法

解决子进程僵尸问题->阻塞等待:把父进程设为s状态,联入到子进程的pcb中,等待子进程结束被os唤醒

wait方法

#include <sys/types.h>

#include <sys/wait.h>

pid_t  wait (int*status);

返回值: 成功返回被等待进程pid,失败返回-1。

参数: 输出型参数,获取子进程退出状态,不关心则可以设置成为NULL

waitpid方法

pid_t waitpid(pid_t pid,int *status,int options)

返回值:

        当正常返回的时候waitpid返回收集到子进程的ID;

        如果设置了选项(options)为WNOHANG,而调用中waitpid发现没有已退出的子进程可手机,则返回0;

        如果调用中出错,则返回-1,这时errno会被设置成相应的值以指示错误所在。

参数:

        pid:

               pid == -1,等待任一个子进程,与wait等效。

               pid > 0 ,等待其进程ID与pid相等的子进程(等待其输入pid的进程返回)。

        status:

                WIFEXITED(status):若为正常终止子进程返回的状态,则为真。(查看进程是否正常退出)

                WEXITSTATUS(status):如若WIFEXITED非零,提取子进程退出码。(查看进程的退出码)

        option:

                 WNOHANG:若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待;若正常结束,则返回该子进程的ID。(非阻塞等待)

  • 如果子进程已经退出,调用wait/waitpid的时候,wait/waitpid会立即返回,并且释放资源,获得子进程退出信息。
  • 如果在任意时刻调用wait/waitpid,子进程存在且正常运行,则进程可能阻塞。
  • 如果不存在该进程,则立即出错返回。

获取子进程status

  • wait和waitpid,都有一个status参数,该参数是一个输出型参数,由操作系统填充。
  • 如果传递NULL,表示不关心子进程的退出状态信息。
  • 否则,操作系统会根据该参数,将子进程的退出信息反馈给父进程。
  • status不能简单的当作整形来看待,具体细节如下图(只研究status低16比特位)

#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>


int main()
{
   pid_t pid = fork();                                                                                                                                          
   if(pid==-1)
   {
     perror("fork");
     exit(1);
   }
   else if(pid==0)
   {
     sleep(20);
     exit(10);
   }
   else
   {
     int status;
     int ret=waitpid(pid,&status,0);
     if(ret>0&& (status & 0x7F )==0) //正常退出
     {
       printf("child exit code :%d\n",(status>>8)&0xFF);
     }
     else if(ret>0)//异常退出
     {
       printf("sig code: %d\n",status & 0x7F);
     }

 }

测试结果:

        [lin@VM-12-15-centos test_5_14]$ ./test.exe  //等待20秒退出

        child exit code : 10

        [lin@VM-12-15-centos test_5_14]$ ./test.exe  //在其他终端上kill掉

        sig code : 9

具体代码实现

进程的阻塞等待方法

int main()
{
	pid_t pid;
	pid = fork();
	if (pid < 0) {
		printf("%s fork error\n", __FUNCTION__);
		return 1;
	}
	else if (pid == 0) { //child
		printf("child is run, pid is : %d\n", getpid());
		sleep(5);
		exit(257);
	}
	else {
		int status = 0;
		pid_t ret = waitpid(-1, &status, 0);//阻塞式等待,等待5S
		printf("this is test for wait\n");
		if (WIFEXITED(status) && ret == pid) {
			printf("wait child 5s success, child return code is :%d.\n", WEXITSTATUS(status));
		}
		else {
			printf("wait child failed, return.\n");
			return 1;
		}
	}
	return 0;
}

运行结果:

[root@localhost linux]# ./a.out

child is run, pid is : 45110

this is test for wait

wait child 5s success, child return code is :1.

进程的非阻塞等待方法

#include <stdio.h> 
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
	pid_t pid;

	pid = fork();
	if (pid < 0) {
		printf("%s fork error\n", __FUNCTION__);
		return 1;
	}
	else if (pid == 0) { //child
		printf("child is run, pid is : %d\n", getpid());
		sleep(5);
		exit(1);
	}
	else {
		int status = 0;
		pid_t ret = 0;
		do
		{
			ret = waitpid(-1, &status, WNOHANG);//非阻塞式等待
			if (ret == 0) {
				printf("child is running\n");
			}
			sleep(1);
		} while (ret == 0);

		if (WIFEXITED(status) && ret == pid) {
			printf("wait child 5s success, child return code is :%d.\n", WEXITSTATUS(status));
		}
		else {
			printf("wait child failed, return.\n");
			return 1;
		}
	}
	return 0;
}

进程程序替换

替换原理

在原有的进程基础上,把当前的代码和数据替换成新的代码和数据,不会创建新进程

用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数 以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动 例程开始执行调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。(用老进程的盒子执行新进程的代码)

替换函数

#include <unistd.h>

// 库函数的调用
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ...,char *const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);

//系统调用

int execve(const char * path,char* const argv[],char* const envp[]);

库函数的调用底层都是通过系统系统调用接口实现,编写这些库函数是为了满足多种调用需求。

函数解释

  • 这些函数如果调用成功则加载新的程序从启动代码开始执行,不再返回。
  • 如果调用出错则返回 -1
  • 所有exec函数只有出错的返回值而没有成功的返回值

 命名理解

  • l(list) : 表示参数采用列表
  • v(vector) :参数采用数组
  • p(path):有p自动搜索环境变量PATH
  • e(env):表示自己维护环境变量

exec调用举例如下:
#include <unistd.h>
int main()
{
	char* const argv[] = { "ps", "-ef", NULL };
	char* const envp[] = { "PATH=/bin:/usr/bin", "TERM=console", NULL };

	execl("/bin/ps", "ps", "-ef", NULL);

	// 带p的,可以使用环境变量PATH,无需写全路径
	execlp("ps", "ps", "-ef", NULL);

	// 带e的,需要自己组装环境变量
	execle("ps", "ps", "-ef", NULL, envp);

	execv("/bin/ps", argv);

	// 带p的,可以使用环境变量PATH,无需写全路径
	execvp("ps", argv);

	// 带e的,需要自己组装环境变量
	execve("/bin/ps", argv, envp);

	exit(0);
}

事实上,只有execve是真正的系统调用,其它五个函数最终都调用 execve,所以execve在man手册 第2节,其它函数在 man手册第3节。这些函数之间的关系如下图所示。

下图exec函数族 一个完整的例子:

我们可以综合前面的知识,做一个简易的shell

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/wait.h>

#define SIZE 512
#define NUM 32
#define SEP " "
#define ZERO '\0'
#define SkipPath(p) do{ p+=(strlen(p)-1);while(*p!='/') p--; }while(0)

char* gArgv[NUM];
char cwd[SIZE*2];
int lastcode=0;

const char* GetHome()
{
  const char* home=getenv("HOME");
  if(home==NULL) return "/";
  return home;
}

const char* GetUserName()
{
  const char* name=getenv("USER");
  if(name==NULL) return "None";
  return name;
}

const char* GetHostName()
{
  const char* hostname=getenv("HOSTNAME");
  if(hostname==NULL) return "None";
  return hostname;
}
const char* GetCwd()
{
  const char* cwd=getenv("PWD");
  if(cwd==NULL) return "None";
  return cwd;
}


void MakeCommandLineAndPrint()
{
  char line[SIZE];
  const char* user=GetUserName();
  const char* hostname=GetHostName();
  const char* cwd=GetCwd();
  
  SkipPath(cwd);
  snprintf(line,sizeof(line),"[%s@%s %s]> ",user,hostname,strlen(cwd)==1?"/":cwd+1);
  printf("%s",line);
  fflush(stdout);
}


int GetUserCommand(char command[],size_t n)
{
  
  char* s=fgets(command,n,stdin);
  if(s==NULL) return -1;
  command[strlen(command)-1]=ZERO;
  return strlen(command);
}

void SplitCommand(char command[],size_t n)
{
  (void)n;
   gArgv[0]=strtok(command,SEP);
   int index=1;
   while((gArgv[index++]=strtok(NULL,SEP)));
}

void ExecuteCommand()
{
  pid_t id=fork();
  if(id<0)
  {
    exit(-1);
  }
  else if(id==0)
  {
    execvp(gArgv[0],gArgv);
    exit(errno);
  }
  else
  {
    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
      lastcode=WEXITSTATUS(status);
      if(lastcode!=0)
        printf("%s:%s:%d\n",gArgv[0],strerror(lastcode),lastcode);
    }
  }
}

void Cd()
{
  const char* path=gArgv[1];
  if(path==NULL) path=GetHome();
  chdir(path);
  
  //刷新环境变量
  char temp[SIZE*2];
  getcwd(temp,sizeof(temp));
  snprintf(cwd,sizeof(cwd),"PWD=%s",temp);
  putenv(cwd);

}
  
int CheckBuildin()
{
  int yes=0;
  const char* enter_cmd=gArgv[0];
  if(strcmp(enter_cmd,"cd")==0)
  {
    yes=1;
    Cd();
  }
  else if(strcmp(enter_cmd,"echo")==0&&strcmp(gArgv[1],"$?")==0)
  {
    yes=1;
    printf("%d\n",lastcode);
    lastcode=0;
  }

  return yes;
}

int main()
{
  int quit=0;
  while(!quit)
  {
     //1.我们需要自己输出一个命令
     MakeCommandLineAndPrint();
     //2.获取用户命令字符
     char usercommand[SIZE];
     int n=GetUserCommand(usercommand,sizeof(usercommand));
     if(n<=0) return 1;

     //3.分割用户命令字符
     SplitCommand(usercommand,sizeof(usercommand));

     //4.检查是否是内建命令
     int ret=CheckBuildin();
     if(ret) continue;
     //5.执行命令
     ExecuteCommand();
  }
  return 0;
}


















  • 27
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值