dup return error (c programming in linux) -


i'm trying create simple program simulates "ls -l | tail -n 2" call in terminal. i'm using "fork" , "execvp" purpose. well, here code:

int main(int argc, char *argv[]) {     int pipefd[2];     pid_t child1;     pid_t child2;     char* com1[] = {"ls", "-l",null};     char* com2[] = {"tail", "-n","2",null};      if (!(child1 = fork()))      {         close(stdout);        dup(pipefd[1]);         close(pipefd[1]);         execvp (com1[0], com1);        _exit(exit_success);     }     else     {         close(pipefd[1]);         if (!(child2 = fork()))          {              close(stdin);             dup(pipefd[0]); /* dupwr holds lowest fd available, meaning stdout's */             perror("dup 2");             close(pipefd[0]); /* reader see eof */             execvp (com2[0], com2);             _exit(exit_success);         }         else         {             close(pipefd[0]);             waitpid(child2,0,0);         }         waitpid(child1,0,0);     }       return 0; } 

i these errors:

dup 2: bad file descriptor tail: cannot fstat `standard input': bad file descriptor tail: -: bad file descriptor 

it seems me there problem in synchronization. in fact, if declare: com2[] = {"ls", "-l",null}; works fine (i mean in normal shell). moreover, found second "dup" in second "fork" returns error. why that? don't know problem code. please help!

edit: added code (forgot create pipes):

if (pipe(pipefd) == -1) {     perror("pipe");     exit(exit_failure); } 

thanks, useless!

close(stdout); dup(pipefd[1]);  close(pipefd[1]);  

since dup returns new file descriptor, , don't use return value, you're discarding it.

did want replace stdout instead, so?

dup2(pipefd[1], stdout_fileno); 

if so, pipefd[] should initialized first. did mean call pipe somewhere?


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -