linux c (4) 进程终止-exit和_exit函数

程序正常结束时会调用exit进行一些清理工作,即使你没有显示地调用它。

void exit (int STATUS)

传入的STATUS可以用来表示程序的执行情况,按照惯例,0表示程序正常结束,其他情况可自定义。

 

exit的执行过程是:

(1)调用atexit或on_exit中注册了的函数,来执行用户定义的操作

(2)关闭流,清除tmpfile创建的临时文件,输出缓冲区记录(如stdout)

(3)执行_exit函数

所以如果直接调用_exit函数将导致一些信息没来得及从缓冲区中输出。

printf在遇到换行符时从缓冲区中读取记录,看下面的例子:

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    pid_t rt;
    rt=fork();
   
    if(rt==-1)
    {
        perror("failed to create a new process/n");
        exit(0);
    }
    else if(rt==0)/*子进程中fork返回的是0*/
    {
        printf("test termination function _exit() /n");
        printf("this is subprocess.");
        _exit(0);
    }
    else/*父进程中fork返回的子进程的进程号,大于0*/
    {
        printf("test termination function exit() /n");
        printf("this is parent process.");
        exit(0);
    }
}

 

执行结果如下:

yaojun@linux-zv38:~/programs/linuxc> gcc 6.5.c -o 6.5
yaojun@linux-zv38:~/programs/linuxc> 6.5
test termination function _exit()
test termination function exit()
this is parent process.
可见子进程中没有加/n的那一行没有输出。

 

详细说明如下:

25.6.1 Normal Termination
-------------------------

A process terminates normally when its program signals it is done by
calling `exit'.  Returning from `main' is equivalent to calling `exit',
and the value that `main' returns is used as the argument to `exit'.

 -- Function: void exit (int STATUS)
     The `exit' function tells the system that the program is done,
     which causes it to terminate the process.

     STATUS is the program's exit status, which becomes part of the
     process' termination status.  This function does not return.

   Normal termination causes the following actions:

  1. Functions that were registered with the `atexit' or `on_exit'
     functions are called in the reverse order of their registration.
     This mechanism allows your application to specify its own
     "cleanup" actions to be performed at program termination.
     Typically, this is used to do things like saving program state
     information in a file, or unlocking locks in shared data bases.

  2. All open streams are closed, writing out any buffered output data.
     See *note Closing Streams::.  In addition, temporary files opened
     with the `tmpfile' function are removed; see *note Temporary
     Files::.

  3. `_exit' is called, terminating the program.  *Note Termination
     Internals::.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值