C abort()

abort() 函数定义在 stdlib.h 头文件中。它通过触发 SIGABRT 信号来中止程序执行,并直接从调用位置退出。


void abort(void); 

 

abort() 参数: 

abort() 函数不带任何参数。abort() 不会刷新打开的文件缓冲区,也不会调用我们使用 atexit() 安装的任何清理函数。

abort() 返回值

abort() 函数不返回任何参数。abort() 函数会覆盖对 SIGABRT 信号的阻塞或忽略。

abort() 示例

示例 1:C 语言中 abort() 函数的工作原理是什么?


#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *p;
   
   printf("Open myfile.txt\n");
   p = fopen( "myfile.txt","r" );
   if(p == NULL) {
      printf("Abort the program\n");
      abort();
   }
   printf("Close myfile.txt\n");
   fclose(p);
   
   return(0);
}

输出


Open myfile.txt                                                    
Abort the program                                                  
Aborted (core dumped)

示例 2:abort() 在错误情况下如何工作?


#include <stdio.h>
#include <stdlib.h>
int main (){
    FILE *p = fopen("mydata.txt","r");
    if (p == NULL) {
       fprintf(stderr, "Opening file mydata.txt have error in function main()\n");
       abort();
    }
 
    /* Normal processing continues here. */
    fclose(p);
    printf("Normal Return\n");
    return 0;
}

输出


Opening file mydata.txt have error in function main()