first version
This commit is contained in:
parent
b73771ad92
commit
5b5b54dd31
79
src/main.c
79
src/main.c
@ -0,0 +1,79 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <getopt.h>
|
||||
#include "users.h"
|
||||
#include "processes.h"
|
||||
#include "logging.h"
|
||||
#include "error_handling.h"
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
int opt;
|
||||
char *log_file = NULL;
|
||||
char *error_file = NULL;
|
||||
int show_users = 0, show_processes = 0;
|
||||
FILE *log_fp = stdout, *err_fp = stderr;
|
||||
|
||||
// Early processing of error redirection to avoid losing messages
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
struct option long_options[] = {
|
||||
{"users", no_argument, 0, 'u'},
|
||||
{"processes", no_argument, 0, 'p'},
|
||||
{"log", required_argument, 0, 'l'},
|
||||
{"errors", required_argument, 0, 'e'},
|
||||
{"help", no_argument, 0, 'h'},
|
||||
{0, 0, 0, 0}
|
||||
};
|
||||
|
||||
while ((opt = getopt_long(argc, argv, "upl:e:h", long_options, NULL)) != -1) {
|
||||
switch (opt) {
|
||||
case 'u': show_users = 1; break;
|
||||
case 'p': show_processes = 1; break;
|
||||
case 'l': log_file = optarg; break;
|
||||
case 'h':
|
||||
printf("Usage: %s [options]\n", argv[0]);
|
||||
printf(" -u, --users List users and home directories\n");
|
||||
printf(" -p, --processes List running processes\n");
|
||||
printf(" -l, --log PATH Redirect output to a file\n");
|
||||
printf(" -e, --errors PATH Redirect errors to a file\n");
|
||||
printf(" -h, --help Show this help message\n");
|
||||
return 0;
|
||||
default:
|
||||
fprintf(stderr, "Unknown option. Use -h for help.\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (log_file && !(log_fp = open_log_file(log_file))) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (show_users) {
|
||||
list_users(log_fp);
|
||||
}
|
||||
if (show_processes) {
|
||||
list_processes(log_fp);
|
||||
}
|
||||
|
||||
if (log_fp != stdout) fclose(log_fp);
|
||||
if (err_fp != stderr) fclose(err_fp);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user