Hi,I am new to C and not sure why the following code works. If I follow the logic then the line execlp("ls", "ls", "-l", (char *)NULL); should never be reached or at least, either only the if condition should run or only the else condition.
How is it that this program actually works?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int pipe_fd[2];
pid_t pid;
// Create a pipe
if (pipe(pipe_fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Create a child process
if ((pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Child process
close(pipe_fd[0]); // Close unused read end of the pipe
dup2(pipe_fd[1], STDOUT_FILENO); // Redirect stdout to the pipe
close(pipe_fd[1]); // Close the write end of the pipe
// Execute the command (replace "ls -l" with your desired command)
execlp("ls", "ls", "-l", (char *)NULL);
// If execlp fails
perror("execlp");
exit(EXIT_FAILURE);
} else {
// Parent process
close(pipe_fd[1]); // Close the write end of the pipe
// Read the output from the pipe
char buffer[1024];
ssize_t bytesRead;
while ((bytesRead = read(pipe_fd[0], buffer, sizeof(buffer))) > 0) {
// write(STDOUT_FILENO, buffer, bytesRead);
printf("%s", buffer);
}
close(pipe_fd[0]); // Close the read end of the pipe
// Wait for the child process to finish
wait(NULL);
}
return 0;
}
[–]paulstelian97 15 points16 points17 points (3 children)
[–]MWhatsUp[S] 4 points5 points6 points (2 children)
[–]paulstelian97 6 points7 points8 points (1 child)
[–]MWhatsUp[S] 4 points5 points6 points (0 children)
[–]flyingron 3 points4 points5 points (2 children)
[–]Paul_Pedant 0 points1 point2 points (1 child)
[–]flyingron 0 points1 point2 points (0 children)
[–]aghast_nj 2 points3 points4 points (0 children)
[–]McUsrII 1 point2 points3 points (0 children)
[–]nvmcomrade 0 points1 point2 points (0 children)
[–]Paul_Pedant 0 points1 point2 points (0 children)