fork_exec.c 697 B

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