User:Vcdhanesh/My Sandbox

From Wikibooks, open books for an open world
Jump to navigation Jump to search

C programming standard library function . It is used in programming process or environment to stop the program or process abnormally. It deletes buffers and closes all open files before ending the program.

Abort (C Standard Library)[edit | edit source]

' abort()' is standard C library function ,used to terminate program abnormally . This function is required in the program when wrong condition gets encountered in program execution then to come out of process this function is useful.

Description[edit | edit source]

This standard C library function causes abnormal termination of program.Then it returns control to host environment.Apparantly this function behaves as exit() function. It deletes buffers and closes open files before ending the program, all open streams are closed and flushed.

Header file & Syntax[edit | edit source]

<stdio.h>
void abort(void);

Return Value[edit | edit source]

This function does not return any value i.e. it is of void datatype.

Thread safety[edit | edit source]

It is one of the thread safe functions from standard c library.i.e. function can be called by different threads without any problem.

Example[edit | edit source]

This example tests for successful opening of the file myfile. If an error occurs, an error message is printed, and the program ends with a call to the abort() function.

#include <stdio.h>
#include <stdlib.h>
 int main(void)
{    FILE *stream;
     if ((stream = fopen("mylib/myfile", "r")) == NULL)
     {      perror("Could not open data file");
           abort();
     }
}

System code for UNIX[edit | edit source]

#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)abort.c	8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: abort.c,v 1.12.38.1 2009/02/02 22:07:40 snj Exp $");
#endif
#endif /* LIBC_SCCS and not lint */

#include "namespace.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

extern void (*__cleanup) __P((void));
static int aborting = 0;

void
abort()
{
	sigset_t mask;

	sigfillset(&mask);
	/*
	 * don't block SIGABRT to give any handler a chance; we ignore
	 * any errors -- X311J doesn't allow abort to return anyway.
	 */
	sigdelset(&mask, SIGABRT);
	(void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);

	/* 
	 * POSIX.1 requires that stdio buffers be flushed on abort.
	 * We ensure the cleanup routines are only called once in
	 * case the user calls abort() in a SIGABRT handler.
	 */
	if (!aborting) {
		aborting = 1;

		if (__cleanup)
			(*__cleanup)();
	}

	(void)raise(SIGABRT);

	/*
	 * if SIGABRT ignored, or caught and the handler returns, do
	 * it again, only harder.
	 */
	(void)signal(SIGABRT, SIG_DFL);
	(void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
	(void)raise(SIGABRT);
	_exit(1);
}

See Also[edit | edit source]

References[edit | edit source]