Advertisement
anechka_ne_plach

Untitled

Apr 13th, 2022 (edited)
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. 12 │ int mysystem(const char* str) {
  2. 13 │ int argc = 0, sz = 0;
  3. 14 │ char** argv = NULL;
  4. 15 │
  5. 16 │ int n = strlen(str);
  6. 17 │ int L = 0;
  7. 18 │ while (L < n) {
  8. 19 │ if (isspace(str[L])) {
  9. 20 │ ++L;
  10. 21 │ continue;
  11. 22 │ }
  12. 23 │ int R = L;
  13. 24 │ while (R < n && !isspace(str[R])) {
  14. 25 │ ++R;
  15. 26 │ }
  16. 27 │
  17. 28 │ if (argc + 1 >= sz) {
  18. 29 │ if (!(sz *= 2)) {
  19. 30 │ sz = 64;
  20. 31 │ }
  21. 32 │ argv = realloc(argv, sz * sizeof(argv[0]));
  22. 33 │ }
  23. 34 │ argv[argc] = malloc(R - L + 1);
  24. 35 │ memcpy(argv[argc], str + L, R - L);
  25. 36 │ argv[argc][R - L] = '\0';
  26. 37 │ // printf("argv[%d] = \"%s\"\n", argc, argv[argc]);
  27. 38 │ ++argc;
  28. 39 │ L = R + 1;
  29. 40 │ }
  30. 41 │ if (argc == 0) {
  31. 42 │ return -1;
  32. 43 │ }
  33. 44 │
  34. 45 │ argv[argc] = NULL;
  35. 46 │ int pid = fork();
  36. 47 │ if (pid < 0) {
  37. 48 │ return -1;
  38. 49 │ }
  39. 50 │ if (!pid) {
  40. 51 │ execvp(argv[0], argv);
  41. 52 │ _exit(1);
  42. 53 │ }
  43. 54 │ int status;
  44. 55 │ while (waitpid(pid, &status, 0) > 0) {}
  45. 56 │ if (WIFEXITED(status)) {
  46. 57 │ return WEXITSTATUS(status);
  47. 58 │ } else if (WIFSIGNALED(status)) {
  48. 59 │ return 1024 + WTERMSIG(status);
  49. 60 │ } else {
  50. 61 │ return 1;
  51. : 63 │ }
  52. 64 │
  53. 65 │ // int main(int argc, char* argv[]) {
  54. 66 │ // if (argc != 2) {
  55. 67 │ // return 1;
  56. 68 │ // }
  57. 69 │ // printf("exited with code %d\n", mysystem(argv[1]));
  58. 70 │ // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement