vfork_exec.c 709 B

123456789101112131415161718192021222324252627282930313233
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. int main(int argc, const char** argv, const char** envp) {
  9. int newfd = dup(1), outfd = dup(1);
  10. char fd_argv[4];
  11. snprintf(fd_argv, 4, "%d", newfd);
  12. char* const new_argv[] = {"./exec_victim", fd_argv, NULL};
  13. setenv("IN_EXECVE", "1", 1);
  14. int pid = vfork();
  15. if (pid == 0) {
  16. close(outfd);
  17. execv(new_argv[0], new_argv);
  18. }
  19. wait(NULL);
  20. FILE* out = fdopen(outfd, "a");
  21. if (!out) {
  22. printf("cannot open file descriptor\n");
  23. return -1;
  24. }
  25. fprintf(out, "Goodbye world!\n");
  26. return 0;
  27. }