Skip to content

Instantly share code, notes, and snippets.

@peterbean410
Created October 17, 2024 04:54
Show Gist options
  • Save peterbean410/3fe6e616a9f8f776b7254e7568bd9df0 to your computer and use it in GitHub Desktop.
Save peterbean410/3fe6e616a9f8f776b7254e7568bd9df0 to your computer and use it in GitHub Desktop.
self_delete.c
#include <stdio.h>
#include <unistd.h>
#include <dirent.h> // For directory handling
#include <stdlib.h> // For exit()
void ls() {
// Open the directory
DIR *dir = opendir(".");
if (dir == NULL) {
perror("Unable to open directory");
exit(EXIT_FAILURE);
}
// Read and print directory entries
struct dirent *entry;
printf("######################\n");
printf("Directory contents:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// Close the directory
closedir(dir);
printf("######################\n");
}
int main() {
// Get the full path of the current executable
char path[1024];
ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len == -1) {
perror("readlink");
return 1;
}
path[len] = '\0'; // Null-terminate the string
printf("######################\n");
printf("Executable path: %s\n", path);
printf("######################\n");
printf("Program is running...\n");
printf("######################\n");
ls();
// Now attempt to delete the executable
if (remove(path) == 0) {
printf("######################\n");
printf("Executable deleted successfully.\n");
printf("######################\n");
ls();
} else {
perror("Failed to delete executable");
return 1;
}
printf("######################\n");
// Sleep for 5 seconds
printf("Sleep for 5 seconds.\n");
sleep(5);
printf("5 seconds have passed.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment