I’m very new with linux and so. I can’t get my script working. I’m just guessing, that the program is getting suspended at executing tr function.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int pdesc[2];
pipe(pdesc);
int a = fork();
if (a == 0) // child
{
dup2(pdesc[1],1); // chaning std_out to pipes_out
execlp("ls", "ls", "-l", "-a", NULL);
}
else //parent
{
wait();
int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC,0777);
dup2(pdesc[0], 0); // chaning std_in to pipes_in
dup2(file1, 1); // chaning std_out to file's stream
execlp("tr", "tr", "a-z", "A-Z", NULL);
}
return 0;
}
Classic mistake, so, good question.
You need to close the unused pipe file descriptors in both the parent and the child.
The process reading from the pipe has (itself) an open pipe write end, so the pipe never gets completely closed, so it never delivers an EOF.
Also, the
wait(2)is causing a deadlock, the program doesn’t include<sys/wait.h>, and the call towait(2)is missing a required argument. Because the shell will wait for the parent to finish but not the child, it would be nice, actually, to have await(2)call in here somewhere. But in the current two-process design you have no place to put it, because you aren’t in control after the parent’sexeclp(2). One way to fix that would be to have the parent fork() again, and have the original PID do nothing except wait(2) in a loop until all children have finished.Here is a working version, note also the change to the output file mode.