进程退出函数exit()

来源:互联网 发布:买域名和空间 编辑:程序博客网 时间:2024/05/16 08:47

在多进程编程中(这里讲Linux平台),某个进程函数退出时调用exit()函数。它是属于标准库的函数,原型

void exit(int status);

参数status是退出状态码,它可由用户自定义。为避免子进程成为僵尸进程,父进程是调用wait()或者waitpid()来获取子进程的退出状态。父进程的wait()(或者waitpid())结合子进程的exit()可以得到:
1) 子进程是否正常退出
2) 子进程是否被kill -9 杀死的
3) 用户自定义的状态码

#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>#include <unistd.h>int main(void){    int status;    pid_t pid;    pid = fork();    if (pid == 0)    {        printf("child: pid = %d, ppid = %d\n", getpid(), getppid());        getchar();        exit(162);    }    wait(&status);    printf("WEXITSTATUS(status) = %d\n", WEXITSTATUS(status)); //获取退出值    printf("WIFEXITED(status) = %d\n", WIFEXITED(status));     //判断是否正常推出    printf("WIFSIGNALED(status) = %d\n", WIFSIGNALED(status)); //判断是否被杀死    return 0;}

运行结果:
(1) 运行后键入回车
这里写图片描述

(2) 运行后在另一种端调用命令”kill -9 进程号”杀死子进程
这里写图片描述

注意,子进程的exit()的自定义参数只能是0~255,即两个字节。虽然status参数虽然int型占据4字节,但是这个参数不单单是用来保存退出状态码,还有是否正常退出等信息。看WEXITSTATUS宏的定义(/usr/include/bits/waitstatus.h):
这里写图片描述
它只是占据4字节中的第2字节而已,所以自定义的状态码只能是0-255。

另外,标准库还定义两个宏分别表示进程退出的状态码:

EXIT_SUCCESS   //0, 执行成功EXIT_FAILURE   //1, 执行失败
0 0