Linux进程控制
1. 进程创建
1.1 fork函数初识

进程调⽤fork,当控制转移到内核中的fork代码后,内核做:
- 分配新的内存块和内核数据结构给⼦进程
- 将⽗进程部分数据结构内容拷⻉⾄⼦进程
- 添加⼦进程到系统进程列表当中
- fork返回,开始调度器调度
1.2 fork函数返回值
- ⼦进程返回0,
- ⽗进程返回的是⼦进程的pid。
1.3 写时拷贝
通常,⽗⼦代码共享,⽗⼦再不写⼊时,数据也是共享的,当任意⼀⽅试图写⼊,便以写时拷⻉的⽅
式各⾃⼀份副本。具体⻅下图:

因为有写时拷⻉技术的存在,所以⽗⼦进程得以彻底分离离!完成了进程独⽴性的技术保证!写时拷⻉,是⼀种延时申请技术,可以提⾼整机内存的使⽤率。
1.4 fork常规用法
- ⼀个⽗进程希望复制⾃⼰,使⽗⼦进程同时执⾏不同的代码段。例如,⽗进程等待客⼾端请求,⽣成⼦进程来处理请求。
- ⼀个进程要执⾏⼀个不同的程序。例如⼦进程从fork返回后,调⽤exec函数。
1.5 fork调用失败
- 系统中有太多的进程
- 实际⽤⼾的进程数超过了限制
2.进程终止
进程终⽌的本质是释放系统资源,就是释放进程申请的相关内核数据结构和对应的数据和代码。
2.1进程退出场景
- 代码运⾏完毕,结果正确
- 代码运⾏完毕,结果不正确
- 代码异常终⽌
2.2进程常见退出方法
正常终⽌(可以通过 echo $? 查看进程退出码):
- 从main函数返回
- 调用exit
- _exit
异常退出:
- ctrl + c,信号终⽌
2.2.1 退出码
退出码(退出状态)可以告诉我们最后⼀次执⾏的命令的状态。在命令结束以后,我们可以知道命令是成功完成的还是以错误结束的。其基本思想是,程序返回退出代码 0 时表⽰执⾏成功,没有问题。代码 1 或 0 以外的任何代码都被视为不成功。
Linux Shell 中的主要退出码:

下面我们可以打印所有的错误码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include<string.h>
int main() {
printf("Error Code | Error Message\n");
for (int i = 0; i < 200; ++i) {
const char* message = strerror(i);
if (message == NULL) {
message = "Unknown error";
}
printf("%d | %s\n", i, message);
}
return 0;
}
2.2.2 _exit函数

exit最后也会调⽤_exit, 但在调⽤_exit之前,还做了其他⼯作:
-
执⾏⽤⼾通过 atexit或on_exit定义的清理函数。
-
关闭所有打开的流,所有的缓存数据均被写⼊
-
调⽤_exit

3.进程等待
3.1进程等待的必要性
- 之前讲过,⼦进程退出,⽗进程如果不管不顾,就可能造成‘僵⼫进程’的问题,进⽽造成内存泄漏。
- 另外,进程⼀旦变成僵⼫状态,那就⼑枪不⼊,“杀⼈不眨眼”的kill -9 也⽆能为⼒,因为谁也没有办法杀死⼀个已经死去的进程。
- 最后,⽗进程派给⼦进程的任务完成的如何,我们需要知道。如,⼦进程运⾏完成,结果对还是不对,或者是否正常退出。
- ⽗进程通过进程等待的⽅式,回收⼦进程资源,获取⼦进程退出信息
3.2进场等待的方法
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;
如果设置了选项WNOHANG,⽽调⽤中waitpid发现没有已退出的⼦进程可收集,则返回0;
如果调⽤中出错,则返回-1,这时errno会被设置成相应的值以指⽰错误所在;
参数:
pid:
Pid=-1,等待任⼀个⼦进程。与wait等效。
Pid>0.等待其进程ID与pid相等的⼦进程。
status: 输出型参数
WIFEXITED(status): 若为正常终⽌⼦进程返回的状态,则为真。(查看进程是否是正常退出)
WEXITSTATUS(status): 若WIFEXITED⾮零,提取⼦进程退出码。(查看进程的退出码)
options:默认为0,表⽰阻塞等待
WNOHANG: 若pid指定的⼦进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该⼦进程的ID。

3.2 获取子进程status
- wait和waitpid,都有⼀个status参数,该参数是⼀个输出型参数,由操作系统填充。
- 如果传递NULL,表⽰不关⼼⼦进程的退出状态信息。
- 否则,操作系统会根据该参数,将⼦进程的退出信息反馈给⽗进程。
- status不能简单的当作整形来看待,可以当作位图来看待,具体细节如下图(只研究status低16⽐特位):

总结: - 进程正常退出: status的8到15比特位表示退出状态,0到7比特位为0。
- 被信号所杀:status的8到15比特位没有用为0,0到6比特位表示被那个信号所杀,7比特位就是core dump标志
3.3 阻塞与⾮阻塞等待
- 阻塞等待
#include<stdio.h> #include <sys/types.h>
#include <sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int status = 0;
int id = fork();
if (id == 0)
{
sleep(5);
exit(2);
}
//is parent
waitpid(id, &status, 0);
if (WIFEXITED(status))//
{
printf("wait success!!!\n");
// printf("status=%d\n",WEXITSTATUS(status));
printf("status=%d\n", (status >> 8) & 0X00000FF);
}
return 0;
}
- 非阻塞等待
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<unistd.h>
typedef void(*ptr)(); ptr arr[7] = { 0 };
void test01()
{
printf("%s\n", "this is test01");
}
void test02()
{
printf("%s\n", "this is test02");
}
void load() {
int index = 0;
arr[index++] = test01;
arr[index++] = test02;
}
int main()
{
load();
pid_t id = fork();
int cnt = 10; if (id == 0)
{
while (cnt--)
{
printf("I am a child process!!!\n");
sleep(1);
}
exit(7);
}
int status = 0;
while (1)
{
pid_t ans = waitpid(id, &status, WNOHANG);
if (ans == id)
{
sleep(1);
printf("wait success!exit code=%d,exit sign=%d\n", (status >> 8) & 0x000000FF, status & 0x0000007F);
exit(1);
}
else if (ans == 0)
{
//
for (int i = 0; i < 2; i++)
{
arr[i]();
sleep(1);
}
printf("calling is over,child process is running\n ");
sleep(1);
}
else
{
printf("wait failre!exit code=%d,exit sign=%d\n", (status >> 8) & 0x000000FF, status & 0x0000007F);
sleep(1);
}
}
}

4.进程程序替换
4.1替换原理
⽤fork创建⼦进程后执⾏的是和⽗进程相同的程序(但有可能执⾏不同的代码分⽀),⼦进程往往要调⽤⼀种exec函数以执⾏另⼀个程序。当进程调⽤⼀种exec函数时,该进程的⽤⼾空间代码和数据完全被新程序替换,从新程序的启动例程开始执⾏。调⽤exec并不创建新进程,所以调⽤exec前后该进程的id并未改变。在子进程执行exec函数是没有创建新的进程只是把exec函数中要执行的代码和数据覆盖了原来的代码和数据,也就是说当程序替换成功就是原始代码后面的全都被新的代码覆盖。
4.2exec系列函数
//返回值:替换成功无返回值,失败返回-1
//path就是你要执行的工具比如ls
//arg就是你想怎样执行比如 ls -a -l
//假如创建子进程进行程序替换,此时子进程的环境变量就是替换后的子
//进程的环境变量(因为程序替换不会创建新进程,而环境变量就是位
//于进程地址空间里面的全局位置。因为不创建新进程那么程序替换后的
//环境变量就还是子进程的),程序替换不会创建新的进程,而是覆盖
//把代码数据覆盖写入。
#include <unistd.h>
//带l的调用就是 "ls" "-l" "-a" "NULL"
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[]);
//exec系列函数带p代表回去PATH路径下找你要执行的东西不用带路径
int execvp(const char *file, char *const argv[]);
//系统调用
int execve(const char *path, char *const argv[], char *const envp[]);
5.自主shell编写
思路:
- 获取命令⾏
- 解析命令⾏
- 建⽴⼀个⼦进程(fork)
- 替换⼦进程(execvp)
- ⽗进程等待⼦进程退出(wait)
源码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
#define COMDSIZE 1024
#define envsize 1024
#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3
string filename;
int falg = 0;
char pwd[1024];
char tem[1024];
char *g_env[envsize];
int g_envs = 0;
int lastexitcode = 0;
char *g_argc[1024];
int g_argcs = 0;
void Initenv()
{
memset(g_env, 0, sizeof(g_env));
extern char **environ;
for (int i = 0; environ[i]; i++)
{
g_env[g_envs] = (char *)malloc(strlen(environ[i])+1);
strcpy(g_env[g_envs], environ[i]);
g_envs++;
}
// this is my envc
// g_env[g_envs++] = (char *)"test=10000";
g_env[g_envs] = NULL;
for (int i = 0; g_env[i]; i++)
{
putenv(g_env[i]);
}
environ = g_env;
}
const char *GetHOME()
{
return getenv("LOGNAME");
}
const char *GetHOSTNAME()
{
const char *ret = getenv("HOSTNAME");
return ret;
}
const char *Getpwd()
{
const char *ret = getcwd(pwd, sizeof(pwd));
if (ret)
{
snprintf(tem, sizeof(tem), "PWD=%s", pwd);
putenv(tem);
}
return ret;
}
const char * DirName(const char* pwd)
{
#define SLASH "/"
std::string dir = pwd;
if (dir == SLASH) return SLASH;
auto pos = dir.rfind(SLASH);
if (pos == std::string::npos) return "BUG?";
return dir.substr(pos + 1).c_str();
}
void GetCommand(char *buffer, int size)
{
#define format "[%s@%s %s]# "
snprintf(buffer, size, format, GetHOME(), GetHOSTNAME(),DirName(Getpwd()));
}
void PrintCommandPrompt()
{
char buffer[COMDSIZE];
GetCommand(buffer, sizeof(buffer));
printf("%s", buffer);
fflush(stdout);
}
bool GetCommandLine(char buffer[], int size)
{
char *ret = fgets(buffer, size, stdin);
int index=strlen(buffer)-1;
buffer[index]=0;
int lengrh=strlen(buffer);
if(lengrh<=0) return false;
else return true;
}
int SkipSpace(char arr[], int cur,int n)
{
while (cur <= n && isspace(arr[cur]))
cur++;
if (cur > n)
return -1;
else
return cur;
}
void RedirCheck(char comd[])
{
int begin = 0;
int end = strlen(comd) - 1;
int len=end;
if(!filename.empty())
filename.clear();
falg = NONE_REDIR;
// ls -a -l >
while (begin < end)
{
char tem = comd[end];
if (tem == '<')
{
comd[end]=0;
falg = INPUT_REDIR;
int index = SkipSpace(comd, end + 1,len);
if (index == -1)
filename = "";
else
filename = comd + index;
}
else if (tem == '>')
{
if (comd[end - 1] == '>')
{
comd[end-1]=0;
falg = APPEND_REDIR;
int index = SkipSpace(comd, end + 1,len);
if (index == -1)
filename = "";
else
filename = comd + index;
}
else
{
comd[end]=0;
falg = OUTPUT_REDIR;
int index = SkipSpace(comd, end + 1,len);
if (index == -1)
filename = "";
else
filename = comd + index;
}
}
else
{
end--;
}
}
if(filename=="") filename="bug?";
}
bool CommandParse(char cmd[])
{
memset(g_argc, 0, sizeof(g_argc));
g_argcs = 0;
char *ret = NULL;
const char *ep = (const char *)" ";
for (ret = strtok(cmd, ep); ret != NULL; ret = strtok(NULL, ep))
{
g_argc[g_argcs++] = ret;
}
g_argc[g_argcs] = NULL;
return g_argcs == 0 ? false : true;
}
void Cd()
{
string where;
if (g_argcs == 1)
{
where = pwd;
}
else
{
where = g_argc[1];
if (where == string("~"))
{
where = "/home/";
where += GetHOME();
where += "/";
}
else if (where == string(".."))
{
}
else if (where == string("."))
{
}
else if (where == string("-"))
{
where = "/home/";
where += GetHOME();
where += "/";
}
}
chdir(where.c_str());
}
void Pwd()
{
printf("%s\n",pwd);
}
void ECHO()
{
}
bool CheckAndExecBuiltin()
{
char *tem = g_argc[0];
if (strcmp(tem, "cd") == 0)
{
Cd();
return true;
}
else if (strcmp(tem, "pwd") == 0)
{
Pwd();
return true;
}
else if (strcmp(tem, "echo") == 0)
{
ECHO();
return true;
}
else
{
return false;
}
}
void Execute()
{
int id = fork();
if (id == 0)
{
if (falg != NONE_REDIR)
{
if (falg == INPUT_REDIR)
{
int fd = open(filename.c_str(), O_RDONLY);
if (fd < 0)
exit(1);
dup2(fd, 0);
close(fd);
}
else if (falg == OUTPUT_REDIR)
{
umask(0);
int fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd < 0)
exit(1);
dup2(fd, 1);
close(fd);
}
else
{
umask(0);
int fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
if (fd < 0)
exit(1);
dup2(fd, 1);
close(fd);
}
}
execvp(g_argc[0], g_argc);
exit(1);
}
// parent
int status = 0;
pid_t ans1 = waitpid(id, &status, 0);
if (ans1 == id)
{
lastexitcode = WEXITSTATUS(status);
}
}
int main()
{
Initenv();
while (1)
{
// 1.
PrintCommandPrompt();
// 2.GetCommandLine
char buffer[COMDSIZE];
if (!GetCommandLine(buffer, sizeof(buffer)))
continue;
// 3. RedirCheck(commandline);
RedirCheck(buffer);
// 4.
if (!CommandParse(buffer))
continue;
// 5.
if (CheckAndExecBuiltin())
continue;
// 6.
Execute();
}
return 0;
}
1560

被折叠的 条评论
为什么被折叠?



