Advertisement
MikeWalkerMRU

Untitled

May 25th, 2020
942
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  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.  
  27.     if (pipe(pipefd) == -1)
  28.     {
  29.         perror("pipe");
  30.         return 1;
  31.     }
  32.  
  33.     pid_t pid = fork();
  34.     if (pid == -1) // Parent
  35.         perror("fork()");
  36.  
  37.     if (pid == 0) // child
  38.     {
  39.         int out_fd = dup2(pipefd[WRITE], STDOUT_FILENO);
  40.         if (out_fd < 0)
  41.             perror("dup2");
  42.  
  43.         close(pipefd[WRITE]);
  44.         fflush(stdout);
  45.         printf("child wrote here!");
  46.  
  47.         // if (write(pipefd[WRITE], "child wrote here", sizeof("child wrote here")) < 0)
  48.         //     perror("write");
  49.  
  50.         // execv("/bin/sh", argv);
  51.         // perror("execve failed!");
  52.         // _exit(123);
  53.     }
  54.  
  55.     int wstatus;
  56.  
  57.     if (pid != wait(&wstatus) || !WIFEXITED(wstatus))
  58.         perror("Divorsed");
  59.  
  60.     if (read(pipefd[READ], buf, sizeof(buf)) < 0)
  61.         perror("read");
  62.  
  63.     printf("%s\n", buf);
  64.  
  65.     return pid;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement