vfork_exec.c 716 B

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