Practical Usage Guide
Shell Interaction with Status Codes
Checking Return Status
$ ./myprogram
$ echo $? ## Prints the last program's exit status
Error Handling Strategies
Custom Error Codes
#define SUCCESS 0
#define FILE_ERROR 10
#define NETWORK_ERROR 20
int main() {
if (file_operation_fails()) {
return FILE_ERROR;
}
if (network_connection_fails()) {
return NETWORK_ERROR;
}
return SUCCESS;
}
Status Code Workflow
graph TD
A[Program Execution] --> B{Status Code}
B --> |0| C[Shell: Continue]
B --> |Non-zero| D[Shell: Handle Error]
Scripting Integration
Bash Error Handling
#!/bin/bash
./myprogram
if [ $? -ne 0 ]; then
echo "Program failed with error"
## Additional error handling
fi
Best Practices
Practice |
Description |
Example |
Use Meaningful Codes |
Define specific error states |
#define DB_CONNECTION_FAILED 50 |
Document Codes |
Explain each status code |
Comments explaining error conditions |
Consistent Mapping |
Standardize error handling |
Use predefined error ranges |
LabEx Recommendation
When developing on LabEx, create a centralized error code header:
// error_codes.h
#ifndef ERROR_CODES_H
#define ERROR_CODES_H
#define SUCCESS 0
#define INVALID_INPUT 1
#define MEMORY_ALLOCATION_FAILED 2
// Add more specific error codes
#endif
Advanced Error Reporting
#include <stdio.h>
#include <stdlib.h>
enum ErrorCodes {
SUCCESS = 0,
FILE_NOT_FOUND = 10,
PERMISSION_DENIED = 11
};
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (!file) {
perror("Error opening file");
return FILE_NOT_FOUND;
}
return SUCCESS;
}
Key Takeaways
- Status codes provide a communication mechanism
- Use specific, meaningful return values
- Integrate with shell scripting
- Document and standardize error codes