/ / Piping nella mia shell C - c, shell, pipe

Piping nella mia shell C - c, shell, pipe

Ho implementato l'inizio di una shell C comesotto. Finora ho il mio reindirizzamento funzionante e ho pensato di implementarlo | in modo simile ma sto avendo difficoltà. Qualcuno può aiutare? Vorrei iniziare controllando l'operatore di pipe, quindi salvando sa [i-1] e sa [i + 1] come i due comandi separati, ma non sono sicuro di come fork () ed exec () correttamente dopo questo .

int startProcess (StringArray sa)
{
int pid;
int status;
int fd1;
int fd2;
int current_in;
int current_out;
int fd0;
int fd00;
int in = 0;
int out = 0;
char input[64]="";
char output[64]="";
char cmd1[64] ="";
char cmd2[64] ="";
int fd[2];
int pipe = 0;

switch( pid = fork()){
case -1://This is an error
perror("Failure of child.");
return 1;
case 0: // This is the child
// Redirection


/* finds where "<" or ">" occurs and make that sa[i] = NULL ,
to ensure that command wont" read that*/

for(int i=0;sa[i]!="";i++)
{
if(strcmp(sa[i],"<")==0)
{
sa[i]=NULL;
strcpy(input,sa[i+1]);
in=2;
}

if(strcmp(sa[i],">")==0)
{
sa[i]=NULL;
strcpy(output,sa[i+1]);
out=2;
}

}

//if "<" char was found in string inputted by user
if(in)
{

// fdo is file-descriptor
int fd0;
if ((fd0 = open(input, O_RDONLY, 0)) < 0) {
perror("Couldn"t open input file");
exit(0);
}
// dup2() copies content of fdo in input of preceeding file
dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0

close(fd0); // necessary
}

//if ">" char was found in string inputted by user
if (out)
{

int fd00 ;
if ((fd00 = creat(output , 0644)) < 0) {
perror("Couldn"t open the output file");
exit(0);
}

dup2(fd00, STDOUT_FILENO); // 1 here can be replaced by STDOUT_FILENO
close(fd00);
}


execvp(sa[0], sa);
perror("execvp");
_exit(1);


printf("Could not execute "%s"n", sa[0]);
default:// This is the parent
wait(&status);
return (status == 0) ? 0: 1;
}
}

risposte:

1 per risposta № 1
  1. Fai una pipa.
  2. fork().
  3. Nel genitore imposta il descrittore di file STDOUT (1) all'ingresso della tua pipe.
  4. Nel figlio imposta il descrittore di file STDIN (0) sull'output della tua pipe.
  5. exec() sia nel genitore che nel bambino.

Fai tutto questo nel bambino dopo di te fork(), proprio come per il reindirizzamento.