They ask me to do a function that first ls the current directory and store it in a file (tmp) and then read that file, grep -c and return the value in the return. I can not get the correct value back to me correctly in int, yes as char.
int do_nfiles (char *pattern)
{
t_string s;
int fd[2],fd2[2];
char buf[100];
int val = 10;
delay ();
pipe(fd);
int pid = fork();
/*Proceso hijo*/
if(pid == 0){
fd[0] = open("tmp", O_WRONLY|O_CREAT, 0666);
dup2(fd[0],STDOUT_FILENO);
close(fd[0]);
execlp("ls","ls", NULL);
}
else{
pipe(fd2);
pid = fork();
if(pid == 0){
fd2[0] = open("tmp", O_RDONLY);
dup2(fd2[0],STDIN_FILENO);
dup2(fd2[1],STDOUT_FILENO);
close(fd2[0]);
execlp("grep","grep","-c",pattern, NULL);
}
read(fd2[0], &val, sizeof(val));
sprintf (s, "[%d] num %d\n", getpid (), val);
return (val);
}
return 0;
}
If I modify the function and put this:
read(fd2[0],buf,3);
It returns the correct value in char, not int.