toolbox.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #define TOOL(name) int name##_main(int, char**);
  7. #include "tools.h"
  8. #undef TOOL
  9. static struct {
  10. const char* name;
  11. int (*func)(int, char**);
  12. } tools[] = {
  13. #define TOOL(name) { #name, name##_main },
  14. #include "tools.h"
  15. #undef TOOL
  16. { 0, 0 },
  17. };
  18. static void SIGPIPE_handler(int signal) {
  19. // Those desktop Linux tools that catch SIGPIPE seem to agree that it's
  20. // a successful way to exit, not a failure. (Which makes sense --- we were
  21. // told to stop by a reader, rather than failing to continue ourselves.)
  22. _exit(0);
  23. }
  24. int main(int argc, char** argv) {
  25. // Let's assume that none of this code handles broken pipes. At least ls,
  26. // ps, and top were broken (though I'd previously added this fix locally
  27. // to top). We exit rather than use SIG_IGN because tools like top will
  28. // just keep on writing to nowhere forever if we don't stop them.
  29. signal(SIGPIPE, SIGPIPE_handler);
  30. char* cmd = strrchr(argv[0], '/');
  31. char* name = cmd ? (cmd + 1) : argv[0];
  32. for (size_t i = 0; tools[i].name; i++) {
  33. if (!strcmp(tools[i].name, name)) {
  34. return tools[i].func(argc, argv);
  35. }
  36. }
  37. printf("%s: no such tool\n", argv[0]);
  38. return 127;
  39. }
  40. int toolbox_main(int argc, char** argv) {
  41. // "toolbox foo ..." is equivalent to "foo ..."
  42. if (argc > 1) {
  43. return main(argc - 1, argv + 1);
  44. }
  45. // Plain "toolbox" lists the tools.
  46. for (size_t i = 1; tools[i].name; i++) {
  47. printf("%s%c", tools[i].name, tools[i+1].name ? ' ' : '\n');
  48. }
  49. return 0;
  50. }