Skip to content

Instantly share code, notes, and snippets.

@leyyce
Created November 2, 2024 05:34
Show Gist options
  • Select an option

  • Save leyyce/ee210efa9d4d754a492e8c75284576c5 to your computer and use it in GitHub Desktop.

Select an option

Save leyyce/ee210efa9d4d754a492e8c75284576c5 to your computer and use it in GitHub Desktop.
#include <linux/limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define READ_BUFFER_SIZE 1024
#define BASE_PATH "/proc/"
#define CMDLINE "cmdline"
#define BASE_PATH_FORMAT BASE_PATH "%s"
char buffer[READ_BUFFER_SIZE];
void print_from_descriptor_file(char *file_name) {
FILE *file = fopen(file_name, "r");
if (!file) {
fprintf(stderr, "Failed to open %s file\n", file_name);
exit(EXIT_FAILURE);
}
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, READ_BUFFER_SIZE, file)) > 0) {
for (size_t i = 0; i < bytesRead; ) {
if (buffer[i] == '\0') {
putchar(' ');
i++;
} else {
while (i < bytesRead && buffer[i] != '\0') {
putchar(buffer[i]);
i++;
}
}
}
}
if (ferror(file)) {
fprintf(stderr, " \nError reading file %s\n", file_name);
fclose(file);
exit(EXIT_FAILURE);
}
fclose(file);
}
void search_and_print_from_descriptor_file(char *file_name, char *searchterm, int offset) {
FILE *file = fopen(file_name, "r");
if (!file) {
fprintf(stderr, "Failed to open %s file\n", file_name);
exit(EXIT_FAILURE);
}
while (fgets(buffer, sizeof(buffer), file) != NULL) {
if (strstr(buffer, searchterm) != NULL) {
for (size_t i = 0; i < offset; i++) {
if (fgets(buffer, sizeof(buffer), file) == NULL) {
fprintf(stderr, "Failed to find %s in %s\n", searchterm, file_name);
return;
}
}
printf("%s\n%s", searchterm, buffer);
fclose(file);
return;
}
}
fprintf(stderr, "Failed to read from %s file\n", file_name);
fclose(file);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
perror("Missing PID argument\n");
return EXIT_FAILURE;
}
char *pid = argv[1];
if (strlen(BASE_PATH) + strlen(pid) + strlen(CMDLINE) > PATH_MAX)
{
perror("Path longer than PATH_MAX, aborting...\n");
return EXIT_FAILURE;
}
char proc_path[PATH_MAX];
sprintf(proc_path, BASE_PATH_FORMAT, pid);
if (chdir(proc_path) != 0) {
perror("PID doesn't exist. Aborting...\n");
return EXIT_FAILURE;
}
print_from_descriptor_file(CMDLINE);
puts("\n");
search_and_print_from_descriptor_file("smaps", "stack", 1);
putchar('\n');
search_and_print_from_descriptor_file("smaps", "heap", 1);
putchar('\n');
search_and_print_from_descriptor_file("status", "Threads", 0);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment