SHARE
TWEET

Untitled

MikeWalkerMRU May 25th, 2020 754 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.         if (write(pipefd[WRITE], "child wrote here", sizeof("child wrote here")) < 0)
  39.             perror("write");
  40.         // execv("/bin/sh", argv);
  41.         // perror("execve failed!");
  42.         _exit(123);
  43.     }
  44.  
  45.     int wstatus;
  46.  
  47.     if (pid != wait(&wstatus) || !WIFEXITED(wstatus))
  48.         perror("Divorsed");
  49.  
  50.     if (read(pipefd[WRITE], buf, sizeof(buf)) < 0)
  51.         perror("read");
  52.  
  53.     printf("%s\n", buf);
  54.  
  55.     return pid;
  56. }
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