1.进程终止

进程终止指的就是程序执行结束了,进程退出的场景有三种

.代码运行完毕且结果正确

.代码运行完毕但结果不正确

.代码异常终止

1.1 main函数的返回值

学c/c++时,main函数就是入口函数

上面提到,进程终止退出的场景有三种:

.代码运行完毕且结果正确

.代码运行完毕但结果不正确

.代码异常终止

        返回值为0,表示进程代码跑完,结果是否正确? 通常我们用0表示正确,用非0表示不正确(因为正确的原因只有一种,而不正确的原因有很多种)

所以,写main 函数无脑返回0是不正确的,准确来说应该要给不同的值.


1.2 进程退出码和错误码

我们把main函数的返回值称之为 进程退出码。进程退出是非常重要的 ,进程退出码表示进程退出的信息,它是要给父进程读取的。

这里之所以会第一次执行echo &?得到7,后面在输入得到0,原因如下:

$?表示在bash 中,最近一次执行完毕时,对应进程的退出码,这里我们第一次运行test得到的退出码是7,echo $?,也是一个进程,这里它的退出码是0

所以我们再来试试使用ls指令后输入echo $?

这里ls打开一个没有的文件,退出码是2?为什么这样设计呢?


我们先看看错误码:

首先,失败的非零值是可以自定义的,我们可以看看系统对于不同数字默认的 错误码 是什么含义。C 语言当中有个的 string.h 中有一个 strerror 接口,是最经典的、将错误码表述打印出来的接口,我们可以在写个代码去把这些错误码给打印出来:(这里有133个,往后面打都是不知道的错误了)

0是成功, 1表示权限不允许,2表示找不到文件或目录......输出错误原因定义归纳整理如下:(这里先不用记,记也记不下来,可以看看前十个)

#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Argument list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* Nomedium found */
#define EMEDIUMTYEP 124 /*Wrongmedium found */
#define ECANCELED 125 /* Operation Canceled */
#define ENOKEY 126 /* Required key not available */
#define EKEYEXPIRED 127 /* Key has expired */
#define EKEYREVOKED 128 /* Key has been revoked */
#define EKEYREJECTED 129 /* Key was rejected by service */
#define EOWNERDEAD 130 /* Owner died */
#define ENOTRECOVERABLE 131 /* State not recoverable */
#define ERFKILL 132 /* Operation not possible due to RF-kill */
#define EHWPOISON 133 /* Memory page has hardware error */

错误退出码可以对应不同的错误原因,方便我们定位问题在哪里。


1.3进程终止的常见方法

进程终止的常见方法:1.在main函数return 2.调用exit  3.调用_exit

问题一:

在mian 函数return (为什么其他函数不行)?:

只有在main函数return 才叫进程退出,其他函数调return 叫函数返回。

问题二:

为什么在代码任意地点中,调用 exit 都可以做到进程退出?

exit:想必大家并不陌生,exit 并不是一个系统调用,而是用c语言写的其头文件是stdlib.h

在main 函数调用了 func函数,进去打印后执行了exit,最后进程没有返回直接在函数内部直接终止进程,这就叫调exit 直接终止进程,此时我们echo $?得到的结果是7.

exit当然也是可以在main 函数里使用,这里就不作演示了,如果以后想终止一个进程,只需要在任意地点调用exit去代表进程退出


下面我们来讲讲 _exit函数,_exit也是一个系统调用,也是可以用来终止进程的

exit和_exit是调用和被调用的区别,exit调用了_exit的。区别:_exit()是系统调用而exit()是库函数。exit()会清理缓冲区,关闭流等操作,而_exit()什么都不做,直接终止:

根据上面演示所以我们以后直接用exit就行了


2.进程等待

进程等待是一种状态,是父进程等待子进程退出的一种状态

2.1 进程等待的原因

  子进程退出,父进程不管子进程,子进程就要处于僵尸状态,从而导致内存泄漏。所以我们必须让其从 Z 状态变为 X 状态,进而允许操作系统能去释放它。

        上面我们讲的实际上就是我们需要进程等待的一个原因:解决内存泄露问题 。然而不仅仅这一个原因,我们还需要进程等待来 获取子进程的退出状态

        获取子进程的退出状态是否需要将曾经子进程的退出信息保存起来,然后被恢复、读取呢?这和我们刚才讲的进程退出有着很大的关系,我们知道了进程退出是有退出码的。我们需要让子进程退出时它的 return 结果或者 exit 的结果是需要被父进程读到的。

        父进程创建了子进程,是要让子进程办事的,那么子进程把任务完成的怎么样了父进程需要关心吗?如果需要,如何得知?如果不需要,该怎么处理?

父进程通过进程等待的方式,回收子进程资源,获得子进程退出信息。


需要进程等待的原因:(1)解决内存泄漏问题 (2)获取子进程的退出状态 

进程终止退出的场景有三种:

(1) 代码运行完毕且结果正确

(2) 代码运行完毕且结果不正确

  (3)代码异常终止


2.2 wait 函数

先来介绍一下wait函数。第一种方式,就是让父进程调用wait即可。

wait()可以解决回收子进程Z状态,让子进程进入 X 状态

#include <sys/types.h>
#include <sys/wait.h>
 
pid_t wait(int* status);

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

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

验证: 调用wait函数让父进程等待子进程

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
    pid_t id = fork();
    if (id == 0)
    {
        int cnt = 5;
        while (cnt--) 
        {
            printf("我是子进程%d,我在运行,Pid: %d\n", cnt,getpid());
            sleep(1);
        }
        exit(0); // 退出子进程
    }
    else
    {
        printf("我是父进程: 我在等待子进程,pid: %d,\n", getpid());
        sleep(7);
        pid_t ret = wait(NULL);  // 阻塞式等待,暂且将status参数设置为NULL
        if (ret < 0)
        {
            printf("等待失败!\n");
        }
        else 
        {
            printf("等待成功!\n");   // 此时 Z → X
        }
        while (1) // 阻塞式等待不会走到这
        {
            printf("我是父进程,我在运行,Pid: %d\n", getpid());
            sleep(1);
        }
    }
    return 0;
}

      为了观察进程状态,在右边开一会话,写一段监控脚本(注意这里grep test是我生成的可执行文件名字test),做到每隔一秒就监控一下进程,右边输入:

while :; do ps ajx | head -1 && ps ajx | grep test| grep -v grep; echo "-------------------------------------------"; sleep 1; done

左边编译运行:

右边看到了两秒的僵尸进程Z:

成功验证了父进程等待子进程。通过wait()的方案,我们可以解决回收子进程的 Z僵尸态,让子进程进入X死亡态


2.3 waitpid 函数

刚才讲的 wait 其功能比较简单,在进程等待时用的更多的是 waitpid。

waitpid 可以把 wait 完全包含,wait 是 waitpid 的一个子功能。

wait/waitpid 都可以回收子进程的僵尸状态。

#include <sys/types.h>
#include <sys/wait.h>
 
pid_t waitpid(pid_t pid, int* status, int options);

返回值:

如果pid_t >0:等待子进程成功,返回值就是子进程的pid;

如果pid_t<0:等待失败。


        在非阻塞等待中,没有等待失败,如果 pid_t=0;如果子进程没有终止,那么返回0,如果终止且等待成功,返回子进程pid值。


参数 pid_t pid:

设置参数pid>0:是几,是几,就代表等待哪一个子进程,比如 pid=1122,指定等待进程号为112的子进程

设置参数 pid=-1;等待任意进程 (wait就是等待任意进程)


参数int*ststus:和wait一样,输出型参数,获取子进程退出状态,不关心则设置为NULL


参数int optios:0为阻塞等待(wait就是阻塞等待),1为非阻塞等待,

非阻塞等待一般传WNOHANG(这个宏就直接定义为1了)

在使用wait的代码的基础上,参数这样改就和wait一样了:

编译运行+监控:

while :; do ps ajx | head -1 && ps ajx | grep test| grep -v grep; echo "-------------------------------------------"; sleep 1; done


2.4 int*ststus 参数

     wait 和 waitpid,都有这个 status 参数,我们刚才演示 wait 的时候传的是 NULL,如果传递 NULL,则表示不关心子进程的退出状态信息。否则,操作系统会根据该参数,将子进程的退出信息反馈给父进程。

        该参数是一个 输出型参数 (即通过调用该函数,从函数内部拿出来特定的数据)。并且,status 参数是由操作系统填充的,是一个整数,该整数就是下面我们要详细研究的。

        它虽然是一个 int 型整数,但不能简单的当作整形来看待,可以当作位图来看待,具体细节如下图(只研究status低16比特位):

core dump 指的是 核心转储,也可以称之为 "吐核"。

        它是操作系统在进程收到某些信号而终止运行时,将此时进程地址空间的内容以及有关进程状态的其他信息写出的一个磁盘文件。目前只需要知道,该信息是用于调试的。

现在上面的代码改一点,使用 waitpid 的 int*ststus参数

验证:通过提取 status 的次低8位,拿到子进程的退出码:

      status 右移八位再按位与上 0xFF(255->0000 0000 1111 1111),即 (status >>8)&0xFF ,就可以提取到 status 的次低八位(这里应该得到子进程里exit(77)的77),编译运行:

验证: 通过提取 status 的最低7位,得到子进程的退出信号:

   status 的低八位用于表示处理异常的地方,其中有 1 位是 core dump,最上面简单知道就行了。除去 core dump,剩余七位用于进程中的退出信号,这就是 最低七位。

        进程退出,如果异常退出,是因为这个进程收到了特定的信号。我们虽然还没有开始讲解信号,但是我们前几张就介绍了 kill -9 这样的杀进程操作。

这个 -9 我们当时说了,就是一个信号,发送该信号也确实可以终止进程。

   刚才我们讲的 wait/waitpid 和次低八位的时侯,都是关于进程的正常退出。如果进程异常退出呢?我们来模拟一下进程的异常退出(就是使用kill -9)。

代码演示:模拟异常退出的情况,这里把子进程改成死循环,父进程一直等。

  此时我们讲父进程打印的消息再增添一个 "退出信号",也就是提取 status 的最低7位,我们想让低7位保留,高25位清0,让 status 按位与上 0x7F 即可(177-> 0111 1111)

编译运行+监控:

while :; do ps ajx | head -1 && ps ajx | grep test| grep -v grep; echo "-------------------------------------------"; sleep 1; done

   这里一直阻塞式等待的父进程等待到子进程退出后也开始运行,并且成功打印退出信号。代码跑完结果是什么已经不重要了,我们最关心的是因为什么原因退出的。

        当进程收到信号时,就代表进程异常了。进程程出,如果是异常退出,是因为该进程收到了特定的信号。其实除了 9 号信号还有很多信号,输入 kill -l 就可以查看这些:

    实际上,我们在编程学习中遇到的程序崩溃,程序一崩溃程序就退出了,今天在我们操作系统的角度来看,这就是进程终止。

        其实是因为错误而导致了软硬件错误,操作系统通过发送信号的方式把进程杀掉了。至于操作系统凭什么可以终止, 又是怎么发信号的?又是如何终止的?详细的过程是什么?这些问题后面也会讲。

    打印子进程ID和退出信号还要进行位运算,这么麻烦是不是有点挫?所以Linux 已经给我们提供了一些宏供我们直接调用。它们是 WEXITSTATUS 和 WIFEXITED,实现就是和上面位运算一样的

WIFEXITED(status):若为正常终止子进程返回的状态,则为真(查看进程是否是正常退出)。(w是wait,w if exited )
WEXITSTATUS(status):若WIFEXITED非零,提取子进程退出码(查看进程的退出码)。(w是wait,w exit status)

  先思考一个问题:一个进程退出时,可以拿到退出码和退出信号,我们先看谁?

        一旦程序发现异常,我们只关心退出信号,退出码没有任何意义。所以,我们先关注退出信号,如果有异常了我们再去关注退出码。


2.5 int options非阻塞等待

     waitpid的第三个参数就是决定进程等待的方式的。

        我们上面演示的就是阻塞式等待,此时第三个参数是0。所谓阻塞等待就是父进程什么也不干,就在等子进程终止,终止以后父进程继续执行,来回收子进程资源并且获取它的退出信息。

        非阻塞等待是和阻塞等待相反的,在等待子进程终止期间,父进程还可以干它自己的事情,此时第三个参数是WNOHANG(这个宏定义就直接定义为了1,Wait NO HANG夯住了(停了))。

将等待方式设定为非阻塞等待:

waitpid返回值:

如果 pid_t > 0:等待子进程成功,返回值就是子进程的 pid;
如果 pid_t < 0:等待失败。
如果 pid_t  = 0:在非阻塞等待中,如果子进程没有终止,返回0。

  这里有一个问题,是进行了非阻塞等待,但是子进程终止了,父进程也没有进行资源回收和退出信息获取啊,因为并没有打印子进程退出的信息。

        所以这也就是对子进程只询问了一次,发现子进程没有结束父进程就干自己的事了,之后也没有再询问。这样的逻辑执行一次就被叫做非阻塞等待。

        而将这部分代码放在一个while循环中,就会进行多次非阻塞等待,也会对子进程进行多次询问,此时叫做轮询:(此时父进程处理的事应该是可以处理完的,处理完会再一次询问,等待成功后应该跳出循环)

  此时在子进程执行的过程中,父进程在干自己的事之前都会等待一次子进程,当子进程终止以后,父进程在干完自己手头的事情发现子进程终止了,然后获取到了子进程的退出信息。

非阻塞等待的好处就是不会占用父进程的所有时间,父进程可以在轮询期间干自己的事情。


本章完

下一章:Linux_6(进程程序替换)-CSDN博客

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐