SHARE
TWEET

Untitled

MikeWalkerMRU May 25th, 2020 817 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define _GNU_SOURCE
  2.  
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <stdio.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <sys/wait.h>
  10.  
  11. #define READ 0
  12. #define WRITE 1
  13.  
  14. pid_t spawn(char *cmdstring);
  15.  
  16. int main(int argc, char *argv[])
  17. {
  18.     pid_t childpid = spawn("man 2 open");
  19.     return 0;
  20. }
  21.  
  22. pid_t spawn(char *cmdstring)
  23. {
  24.     int pipefd[2];
  25.     char buf[32], *argv[] = {"/bin/sh", "-c", cmdstring, NULL};
  26.     pid_t pid = fork();
  27.  
  28.     if (pipe(pipefd) == -1)
  29.     {
  30.         perror("pipe");
  31.         return 1;
  32.     }
  33.  
  34.     if (pid == -1) // Parent
  35.         perror("fork()");
  36.     if (pid == 0) // child
  37.     {
  38.         int out_fd = dup2(pipefd[WRITE], STDOUT_FILENO);
  39.         if (out_fd < 0)
  40.             perror("dup2");
  41.  
  42.         fflush(stdout);
  43.         close(pipefd[WRITE]);
  44.         printf("child wrote here!\n");
  45.  
  46.         // if (write(pipefd[WRITE], "child wrote here", sizeof("child wrote here")) < 0)
  47.         //     perror("write");
  48.  
  49.         // execv("/bin/sh", argv);
  50.         // perror("execve failed!");
  51.         // _exit(123);
  52.     }
  53.  
  54.     int wstatus;
  55.  
  56.     if (pid != wait(&wstatus) || !WIFEXITED(wstatus))
  57.         perror("Divorsed");
  58.  
  59.     if (read(pipefd[READ], buf, sizeof(buf)) < 0)
  60.         perror("read");
  61.  
  62.     printf("%s\n", buf);
  63.  
  64.     return pid;
  65. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top