Updated for new file_handling

This commit is contained in:
gandc 2025-02-27 20:29:50 +03:00
parent cb20bd27b4
commit 1216c17b87
Signed by: gandc
GPG Key ID: 9F77B03D43C42CB4

View File

@ -5,40 +5,35 @@
#include <string.h>
#include "users.h"
#include "processes.h"
#include "logging.h"
#include "error_handling.h"
#include "file_handling.h"
void setup_error_redirection(char *error_file, FILE **err_fp) {
if (error_file) {
FILE *temp_err_fp = fopen(error_file, "w");
if (!temp_err_fp) {
perror("Failed to open error log file");
*err_fp = open_file(error_file, "w", "Failed to open error log file");
if (!(*err_fp)) {
exit(1);
}
fflush(stderr); // Ensure all previous stderr output is flushed
if (dup2(fileno(temp_err_fp), STDERR_FILENO) == -1) {
fflush(stderr);
if (dup2(fileno(*err_fp), STDERR_FILENO) == -1) {
perror("Failed to redirect stderr to file");
fclose(temp_err_fp);
fclose(*err_fp);
exit(1);
}
*err_fp = temp_err_fp;
}
}
void setup_log_redirection(char *log_file, FILE **log_fp) {
if (log_file) {
FILE *temp_log_fp = fopen(log_file, "w");
if (!temp_log_fp) {
perror("Failed to open log file");
*log_fp = open_file(log_file, "w", "Failed to open log file");
if (!(*log_fp)) {
exit(1);
}
fflush(stdout);
if (dup2(fileno(temp_log_fp), STDOUT_FILENO) == -1) {
if (dup2(fileno(*log_fp), STDOUT_FILENO) == -1) {
perror("Failed to redirect stdout to file");
fclose(temp_log_fp);
fclose(*log_fp);
exit(1);
}
*log_fp = temp_log_fp;
}
}
@ -49,7 +44,6 @@ int main(int argc, char *argv[]) {
int show_users = 0, show_processes = 0;
FILE *log_fp = stdout, *err_fp = stderr;
// Early error redirection handling to ensure stderr is set up before parsing arguments
for (int i = 1; i < argc; i++) {
if ((strcmp(argv[i], "-e") == 0 || strcmp(argv[i], "--errors") == 0) && i + 1 < argc) {
error_file = argv[i + 1];
@ -86,7 +80,6 @@ int main(int argc, char *argv[]) {
}
}
// Ensure log redirection is handled after argument parsing
setup_log_redirection(log_file, &log_fp);
if (show_users) {