mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 13:28:11 +00:00

This mimics the shell's path resolution to locate the executable that would execute if typing it as a command.
29 lines
644 B
C++
29 lines
644 B
C++
#include <AK/AKString.h>
|
|
#include <AK/Vector.h>
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
if (argc < 2) {
|
|
printf("usage: which <executable>\n");
|
|
return 0;
|
|
}
|
|
|
|
char* filename = argv[1];
|
|
|
|
String path = getenv("PATH");
|
|
if (path.is_empty())
|
|
path = "/bin:/usr/bin";
|
|
|
|
auto parts = path.split(':');
|
|
for (auto& part : parts) {
|
|
auto candidate = String::format("%s/%s", part.characters(), filename);
|
|
if(access(candidate.characters(), X_OK) == 0) {
|
|
printf("%s\n", candidate.characters());
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|