Welcome to our guide on C Exit Status! In this tutorial, we'll dive deep into understanding how C programs handle exit status and how to use it effectively in your projects.
When a C program ends, it leaves an exit status. This status can be a value that the program sets before termination and is used by the operating system or parent process to determine if the program has finished successfully or encountered an error.
The C function exit() is used to terminate a program and set the exit status. The argument to the exit() function is the exit status value.
Here's a simple example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(10 * sizeof(int)); // Allocate memory for 10 integers
if (!ptr) { // Check if memory allocation failed
printf("Memory allocation failed!\n");
exit(EXIT_FAILURE); // Set exit status to indicate failure
}
// Perform operations on the allocated memory...
free(ptr); // Free the allocated memory
return EXIT_SUCCESS; // Set exit status to indicate success
}In the above example, we're checking if memory allocation is successful. If it fails, we set the exit status to EXIT_FAILURE (a predefined constant) to indicate that the program failed. If memory allocation is successful, we perform operations and then free the memory before setting the exit status to EXIT_SUCCESS (another predefined constant) to indicate that the program ran successfully.
EXIT_SUCCESS: 0, indicates the program ran successfully.EXIT_FAILURE: non-zero, indicates the program encountered an error.#define.What is the exit status set to when a C program runs successfully?
Understanding and using exit status correctly can help you write robust C programs. Here's an example of using exit status in a simple shell script:
#!/bin/bash
./my_c_program
if [ $? -eq EXIT_SUCCESS ]; then
echo "My C program ran successfully."
else
echo "My C program encountered an error."
fiIn this script, we're executing a C program named my_c_program. If the exit status of my_c_program is EXIT_SUCCESS, the script prints "My C program ran successfully." Otherwise, it prints "My C program encountered an error."
Remember, practice is key! Experiment with exit status in your own C programs and shell scripts to solidify your understanding.
Happy coding! 💡