C/Pipefork

From Attie's Wiki
Revision as of 16:08, 14 February 2013 by Attie (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This simple C function will fork a process, and wire up stdout and stdin to a pipe.

fd[] is a 2 element array of file descriptors
command is the command to pass to execv()
*args[] is the array of args to pass to execv(), and ultimately the executed process
int pipefork(int fd[], char *command, char *args[]) {
  pid_t child;
  int status;
 
  child = vfork();
  if (child == -1) {
    perror("vfork()");
    return 1;
  } else if (!child) {
    int ret;
    if (dup2(fd[0],fileno(stdin)) == -1) {
      perror("dup2(stdin)");
      exit(1);
    }
    if (dup2(fd[1],fileno(stdout)) == -1) {
      perror("dup2(stdout)");
      exit(1);
    }
    /* read from fd[0] */
    /* write to fd[1] */
    ret = execv(command,args);
    if (ret == -1) {
      perror("execv()");
      exit(1);
    }
    exit(WEXITSTATUS(ret));
  }
 
  /* wait for child to finish... */
  waitpid(child,&status,0);
  if (!WIFEXITED(status) || WEXITSTATUS(status)) {
    fprintf(stderr,"pipefork(): executing `%s` failed...\n",command);
    return 1;
  }
  return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox