I am trying to run wc linux command from a C program but I am not getting the desired output.
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("Error forking process");
exit(EXIT_FAILURE);
} else if (pid == 0) {
int fid = open("testtxt.txt", O_RDONLY);
if (fid == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
close(0);
dup2(fid, STDIN_FILENO);
close(fid);
execlp("wc", "wc", (char *)NULL);
} else {
wait(NULL);
}
return 0;
}
As per my understanding I am creating a child process using fork() and in the pid==0 else if block I am setting the stdin for the child process as texttxt.txt file. Then I am using execlp to run the wc command on the file. And as the stdout is still the terminal it should print the word count of the provided file on the terminal. I have wait(NULL) in the else clause to stop the parent process during the execution of child process.
But the output I get on terminal is not what I expect.
The output I get is 1 14 78
Can someone please explain me where I am going wrong?
>Solution :
You do not test for execlp() failure, which is very likely as its first argument must point to an executable file… but you are probably not running your program from the /usr/bin directory that contains the wc program. Change the line to
execlp("/usr/bin/wc", "wc", (char *)NULL);