next verison

This commit is contained in:
gandc 2025-02-23 00:52:58 +03:00
parent 5b5b54dd31
commit 15348b640e
Signed by: gandc
GPG Key ID: 9F77B03D43C42CB4

View File

@ -7,6 +7,40 @@
#include "logging.h"
#include "error_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");
exit(1);
}
fflush(stderr); // Ensure all previous stderr output is flushed
if (dup2(fileno(temp_err_fp), STDERR_FILENO) == -1) {
perror("Failed to redirect stderr to file");
fclose(temp_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");
exit(1);
}
fflush(stdout);
if (dup2(fileno(temp_log_fp), STDOUT_FILENO) == -1) {
perror("Failed to redirect stdout to file");
fclose(temp_log_fp);
exit(1);
}
*log_fp = temp_log_fp;
}
}
int main(int argc, char *argv[]) {
int opt;
char *log_file = NULL;
@ -14,22 +48,11 @@ int main(int argc, char *argv[]) {
int show_users = 0, show_processes = 0;
FILE *log_fp = stdout, *err_fp = stderr;
// Early processing of error redirection to avoid losing messages
// 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];
FILE *temp_err_fp = fopen(error_file, "w");
if (!temp_err_fp) {
perror("Failed to open error log file");
exit(1);
}
fflush(stderr); // Ensure all previous stderr output is flushed
if (dup2(fileno(temp_err_fp), STDERR_FILENO) == -1) {
perror("Failed to redirect stderr to file");
fclose(temp_err_fp);
exit(1);
}
err_fp = temp_err_fp;
setup_error_redirection(error_file, &err_fp);
}
}
@ -47,6 +70,7 @@ int main(int argc, char *argv[]) {
case 'u': show_users = 1; break;
case 'p': show_processes = 1; break;
case 'l': log_file = optarg; break;
case 'e': error_file = optarg; break;
case 'h':
printf("Usage: %s [options]\n", argv[0]);
printf(" -u, --users List users and home directories\n");
@ -61,9 +85,8 @@ int main(int argc, char *argv[]) {
}
}
if (log_file && !(log_fp = open_log_file(log_file))) {
return 1;
}
// Ensure log redirection is handled after argument parsing
setup_log_redirection(log_file, &log_fp);
if (show_users) {
list_users(log_fp);