Skip to content

Instantly share code, notes, and snippets.

@RMPR
Created July 18, 2020 21:06
Show Gist options
  • Save RMPR/4ae36d3963f69fcf0781b4b951287baf to your computer and use it in GitHub Desktop.
Save RMPR/4ae36d3963f69fcf0781b4b951287baf to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Take a PID and close all of the file descriptors */
int main(int argc, char **argv){
FILE *fp;
char* path;
pid_t file_descriptor;
char command[100] = "/usr/bin/lsof -p ";
if ( !argv[1]) {
printf("\nPlease enter a PID \n");
return 0;
}
strcat(command, argv[1]);
strcat(command, " | /usr/bin/awk ' $8 ~ /^-?[0-9]+\\.?[0-9]*$/ {print $8} ' ");
printf("Looking for file descriptors... \n");
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
while (fgets(path, sizeof(path), fp) != NULL) {
file_descriptor = (pid_t) atoi(path);
if (file_descriptor)
if (close(file_descriptor))
printf("\n Something wrong happened when trying to close this fd %d \n", file_descriptor);
else
printf("\n File descriptor closed successfully: %d \n", file_descriptor);
}
pclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment