Originally Posted by
smokeyangel
Ok. Perhaps pid is getting corrupted somehow. What does your whole function look like now?
Can you add some fprintfs to check the value of pid after the fork and before the dup2? You should see the parent and child's pids, so should be able to see if the child pid isn't 0.
Code:
fprintf(STDERR, "\npid: %d", pid);
else if (pid==0)
{
fprintf(STDERR, "\npid: %d", pid);
dup2(fd[1],1);
printf("son\n");
Ah. That's not right.
pipe(2): create pipe - Linux man page
So the all the child's standard output will go to the pipe, To read it you need to read from fd[0].
My whole function right now looks like this :
Code:
void map(char* cmd, char* arg){
int i;
int d=0;
int pid = fork();
FILE *stream;
int status;
char buffer[1000];
stream = fopen("merdas.txt","a");
int fd[2];
if(pipe(fd)==-1){perror("demo");exit(1);}
if (pid == -1) {perror("demo"); exit(1);}
fprintf(STDERR, "\npid: %d", pid);
else if (pid==0)
{
fprintf(STDERR, "\npid: %d", pid);
dup2(fd[1],1);
printf("son\n");
int a = execlp(cmd,cmd,arg,NULL);
perror("demo");
}
else
{
printf("pai\n");
while((d=read(fd[0],buffer,1000))>0) {
buffer[d] = '\0';
printf("<<<<%s\n",buffer);
}
waitpid(pid, &status, 0);
}
}
I've changed the value '1' to fd[0] on read, thanks for pointing that out.
About the fprintf's, I won't be able to get the value from the second fprintf since when I run my program it never enters the (pid==0) section.
I'm not being able to use that first printf aswell because I get this error :
soluis2.c:142: error: expected expression before ‘else’
Thanks!