file.txt" program? I am very new to Linux and so. I can not get the script to work. I just g...">

What happened to my under-linux c: "ls -al | tr az AZ> file.txt" program?

I am very new to Linux and so. I can not get the script to work. I just guess that the program pauses while executing the 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 stream execlp("tr", "tr", "az", "AZ", NULL); } return 0; } 
+4
source share
1 answer

A classic mistake, therefore, is a good question.

You need to close the unused descriptors of the pipe file in both the parent and the child.

Reading a process from a pipe has (itself) a write end with an open end, so the pipe never closes completely, therefore it never delivers EOF.

In addition, wait(2) causes a dead end, the program does not include <sys/wait.h> , and there is no required argument to the wait(2) call. Since the shell will wait for the completion of the parent process, but will not be a child, it would be nice if there was a call to wait(2) . But in the current dual-processor design, you have nowhere to put this because you do not control the parent execlp(2) . One way to fix this would be to have parent fork () again, and the original PID does nothing but wait (2) in the loop until all the children have finished.

Here is the working version, also pay attention to changing the output file mode.

 #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); // chaining std_out to pipes_out close(pdesc[1]); close(pdesc[0]); execlp("ls", "ls", "-l", "-a", NULL); } else { //parent int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644); dup2(pdesc[0], 0); // chaning std_in to pipes_in dup2(file1, 1); // chaning std_out to file stream close(pdesc[0]); close(pdesc[1]); close(file1); execlp("tr", "tr", "az", "AZ", NULL); } return 0; } 
+6
source

Source: https://habr.com/ru/post/1443839/


All Articles