简体   繁体   中英

How to properly apply for a second time dup2()?

Goal: having a program alterna that, according to an integer, particularly reads from STDIN_FILENO and writes on STDOUT_FILENO, write a program that accepts 3 arguments: a text file, two integers r1 and r2. The program generates two child processes that comunicate with a pipe. The first one executes alterna with r1 by reading from the text file given as argument, the second one executes alterna with r2 by reading from the output of the first child process. My solution is this, I just don't know how to properly write the second child process (blank), and I just wanted to apply some other dup s, but it didn't work:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>

int main(int argc, void *argv[]){
  if(argc != 4)
    write(STDOUT_FILENO, "Inviare al programma il file di testo, r1 ed r2.\n", 49), exit(0);
  int input_file;
  size_t file_len;
  if((input_file = open(argv[1], O_RDWR)) < 0)
    perror("open"), exit(1);
  if((file_len = lseek(input_file, 0, SEEK_END)) < 0)
    perror("lseek"), exit(1);
  if((lseek(input_file, 0, SEEK_SET)) < 0)
    perror("lseek"), exit(1);
  char *r1 = argv[2];
  char *r2 = argv[3];
  char *buffer = malloc(sizeof(char) * file_len);
  pid_t pid_p, pid_q;
  int status = 0;
  int fd[2];
  if((pipe(fd)) < 0)
    perror("pipe"), exit(1);
  if((pid_p = fork()) < 0)
    perror("fork"), exit(1);
  if(pid_p == 0){
    close(fd[0]);
    dup2(input_file, STDIN_FILENO);
    dup2(fd[1], STDOUT_FILENO);
    execl("alterna", "alterna", r1, (char *) NULL);
    perror("execl"), exit(1);
  }
  else{
    waitpid(pid_p, &status, 0);
    if(!WIFEXITED(status))
      perror("p1"), exit(1);
    if((pid_q = fork()) < 0)
      perror("fork"), exit(1);
    if(pid_q == 0){
      close(fd[1]);

      /* BLANK */
      /*
      TODO:
      execute alterna by reading from fd[0]
      */

    }
    else{
      waitpid(pid_q, &status, 0);
      if(!WIFEXITED(status))
        perror("p2"), exit(1);
    }
  }
}

Your TODO will look basically like your first clause:

dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
execl("alterna", "alterna", r2, (char *) NULL);
perror("execl");
exit(1);

but you want to do this before the parent wait s on the first child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM