fork_exec.c 1019 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. int main (int argc, char * const * argv, const char * const * envp)
  11. {
  12. char fds[2] = { dup(1), 0 };
  13. int outfd = dup(1);
  14. if (argc > 1) {
  15. argv++;
  16. } else {
  17. char ** new_argv = malloc(sizeof(const char *) * 3);
  18. new_argv[0] = "./exec_victim";
  19. new_argv[1] = fds;
  20. new_argv[2] = NULL;
  21. argv = new_argv;
  22. }
  23. setenv("IN_EXECVE", "1", 1);
  24. int pid = fork();
  25. if (pid == 0) {
  26. close(outfd);
  27. execv(argv[0], argv);
  28. }
  29. wait(NULL);
  30. FILE * out = fdopen(outfd, "a");
  31. if (!out) {
  32. printf("cannot open file descriptor\n");
  33. return -1;
  34. }
  35. fprintf(out, "Goodbye world!\n");
  36. return 0;
  37. }