C library - exit() function



The C stdlib library exit() function allows us to terminate or exit the calling process immediately. The exit() function closes all open file descriptors belonging to the process and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.

The 'SIGCHLD' signal is used for managing child processes, allowing the parent to handle their termination and collect exit statuses.

Syntax

Following is the C library syntax of the exit() function −

void exit(int status)

Parameters

This function accepts a single parameters −

  • status − It represents the status value or exit code returned to the parent process.

  • 0 or EXIT_SUCCESS: 0 or EXIT_SUCCESS represents program has been successfully executed without encountering any error.
  • 1 or EXIT_FAILURE: 1 or EXIT_FAILURE represents program has encountered an error and could be executed successfully.

Return Value

This function does not returns any values.

Example 1: exit() with status "EXIT_FAILURE"

Let's create a basic c program to demonstrate the use of exit() function.

#include <stdio.h>
#include <stdlib.h>
int main() {
   FILE *fp;

   printf("Opening the tutorialspoint.txt\n");
   // open the file in read mode
   fp = fopen("tutorialspoint.txt", "r");
   
   if (fp == NULL) {
      printf("Error opening file\n");
      // Terminate the program with an error code
      exit(EXIT_FAILURE);
   }
   fclose(fp);
   // Terminate the program successfully
   exit(EXIT_SUCCESS);
}

Output

Following is the output −

Open the tutorialspoint.txt
Error opening file

Example 2

In this example, we use the exit() function to terminate the process immediately when the 'i' will reach 5.

#include <stdio.h> 
#include <stdlib.h>
int main(){
   // print number from 0 to 5
   int i;
   for(i=0;i<=7;i++){
      // if i is equals to 5 then terminates
      if(i==5){
         exit(0);
      }	     
      else{
         printf("%d\n",i);
      }         
   }
   return 0;
}

Output

Following is the output −

0
1
2
3
4

Example 3

Here is the another program that takes the user details. If the user details match the if condition, then 'exit(EXIT_SUCCESS)' will work. Otherwise 'exit(EXIT_FAILURE)'.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
   const char *username = "tutorialspoint";
   const char *password = "tp1234";

   // Check the credentials
   if (strcmp(username, "tutorialspoint") == 0 && strcmp(password, "tp1234") == 0){
      printf("Login successful!\n");
      // if user details match exit
      exit(EXIT_SUCCESS); 
   } else {
      fprintf(stderr, "Invalid credentials!\n");
      // if user details not match exit
      exit(EXIT_FAILURE); 
   }
   return 0;
}

Output

Following is the output −

Login successful!
Advertisements