forked from PKD667/cutils
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fixing the exec function that weirdly was empty
- Loading branch information
Showing
2 changed files
with
41 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |