Do streams have to be closed when using popen
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 (file开发者_C百科ListingStream == 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);
}
Yes you should. See this answer for an explanation on the inner workings of pclose()
. Furthermore you should note that errors in wait4()
can be the cause of an apparent failure in pclose()
.
Update0
If the FILE *
is valid (internally this is signified by the file descriptor not being -1
), pclose()
and fclose()
will not cause leaks if there is an error. It's worth noting that if the FILE *
is not valid, there's nothing to clean up anyway. As discussed in the answer I linked to, there is extra behaviour for pclose()
, namely removing the FILE *
from the proc file chain, and then waiting for the child to terminate. The internal wait is actually the second last thing done for a pclose()
, everything has already been cleaned up by this point. Immediately after waiting, the contents of the FILE
are trashed to signify its invalidity, this occurs regardless of any error in waitpid()
.
Given the error you are receiving, ECHILD
, I can definitively say that there is no memory leak for pclose()
under eglibc-2.11.1, and likely any glibc-derived library for at least the past 1-4 years.
If you wish to be completely certain, just run your program under valgrind, and trigger the ECHILD
error. Valgrind will inform you if anything was leaked.
If your application modify the disposition of SIGCHLD
, it could interfere with popen()'s ability to wait for the shell to exit.
That error is ECHILD - meaning that waitpid returned an error, it could not get the return status of the child process. That can be caused by what 'command' actually int erms of process creation.
As every one else mentioned you should pclose, because it leaves a 'dangling' file descriptor, and can cause child processes not to be cleaned up promptly.
精彩评论