As the title says , I am unsure if I should close a stream that was opened using popen.
The reason I am unsure is because every time i call pclose on a stream that was opened using popen I get a -1 return code.
If I make a call to perror after that I get the following message.
pclose: No Child Processes
The code that I am using below is basically to run a command and capture its output.I get the error from the last line (return pclose(fileListingStream);)
int executeCommand(char *command) {
//The Stream to read that will contain the output of the command
FILE *fileListingStream;
char path[PATH_MAX];
//Run the commmand in read mode
fileListingStream = popen(command,"r");
//Ensure that its not null before continuing
if (fileListingStream == NULL)
return EXIT_FAILURE;
//Get the data from the stream and then print to the the console
while (fgets(path, PATH_MAX, fileListingStream) != NULL)
printf("%s", path);
//Close the stream and return its return code
return pclose(fileListingStream);
}