Skip to content

Commit

Permalink
fixing the exec function that weirdly was empty
Browse files Browse the repository at this point in the history
  • Loading branch information
palkh committed Jul 25, 2024
1 parent 47235b9 commit fa38903
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
Binary file modified cutils.a
Binary file not shown.
49 changes: 41 additions & 8 deletions src/exec.c
Original file line number Diff line number Diff line change
@@ -1,20 +1,53 @@
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <limits.h>

#include "../cutils.h"

char* exec(const char* cmd)
{
// Open the command for reading
// Function to execute a command and capture its output
char* exec(const char* cmd) {

// Open the command for reading and capture its output
FILE* fp = popen(cmd, "r");

// Check if the command execution failed
if (fp == NULL) {
// Print an error message if execution fails
printf("Failed to run command");
exit(1);
}
char* result = calloc(1024,sizeof(char));
exit(1); // Exit the program with an error code
}
// Read the output a line at a time and store it
char line[PATH_MAX];

// Initialize a result buffer to store the command's output
char* result = (char*)calloc(2048, sizeof(char));

// Read the output from the command and append it to the result buffer
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s\n", line);
// Calculate the current size of the result buffer
size_t result_size = malloc_usable_size(result) / sizeof(char);

// Calculate the current length of the result
size_t result_len = strlen(result);


// Close
// Calculate the length of the current line of output
size_t path_len = strlen(line);

// Check if the result buffer needs to be resized to accommodate the output
if (result_len + path_len + 1 > result_size) {
// Resize the result buffer to ensure it can hold the entire output
result = (char*)realloc(result, result_len + path_len + 1);
}

// Append the current line of output to the result
strcat(result, line);
}

// Close the command execution
pclose(fp);

// Return the captured output
return result;
}

0 comments on commit fa38903

Please sign in to comment.