c - Using fork() and execlp to count lines -


i'm trying read file, count lines of file, , present result in end. got working out great problem execlp command, have no idea how work with.

the code following:

#include <stdio.h> #include <sys/types.h>  #include <sys/stat.h>  #include <fcntl.h>  #include <unistd.h>  #include <stdlib.h>  #define exit_on_error(s,m) if (s < 0) { perror(m); exit(1); }   int main(int argc, char *argv[]){     int i, status, total=0, f, n=0;      for(i=1; i<argc; i++){         if(fork()==0){             f=open(argv[i], o_rdonly);             exit_on_error(f,"erro na abertura ficheiro");             if(fork()==0)             {                 wait();                  // ?????????????                                                    execlp("wc", "wc", "-l", null);             }             close (f);             return (0);         }         else{             wait(&status);             total += status >> 8;         }     }       for(i=1; i<argc; i++){         printf("pid=(%d), ficheiro %s\n", getpid(), argv[i]);     }     for(i=1; i<argc; i++){         printf("numero de linhas ficheiro %s: [%d]\n", argv[i], n);     }     printf("ficheiros: [%d]---erros: [%d]\n", --argc, total);  } 

and shows this: name of program 2.c

./2 phonecontacts.txt ddd

erro na abertura ficheiro: no such file or directory

pid=(3565), ficheiro phonecontact.txt (file containing 20 lines)

pid=(3565), ficheiro ddd (this 1 doesn't exist)

numero de linhas ficheiro phonecontact.txt: [0] (it supposed show 20 lines here)

numero de linhas ficheiro ddd: [0] (this 1 doesn't exist)

ficheiros: [2]---erros[1]

wc: standard input: input/output error 0

after messing little bit managed solve problem:

int main(int argc, char *argv[]){         int i, status, total=0, f;          for(i=1; i<argc; i++){                 if(fork()==0){                         close(0);                         f=open(argv[i], o_rdonly);                         exit_on_error(f,"erro na abertura ficheiro");                         if(fork())                         {                                 printf("numero de linhas ficheiro %s: \n", arg$                                 execlp("wc", "wc", "-l", null);                         }                         close (f);                         return (0);                 }                 else{                         wait(&status);                         total += status >> 8;                 }                 printf("pid=(%d), ficheiro %s\n", getpid(), argv[i]);         }         printf("ficheiros: [%d]---erros: [%d]\n", --argc, total); } 

this code functional.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -