C - The correct way to close files when using open () and fdopen ()

So, I create Minishell Unix in C and implement input, output, and error redirection and run into a file problem. I open my files in a loop where I find redirection operators and use open (), which returns fd. Then I assign a child fd and call the execute function.

When my shell just exits and finds programs, and executing them with execvp (), I don't have a big problem. The only problem is knowing whether to close () in file descriptors before requesting the next command line. I am worried about fd leak but don't understand how this works.

My real problem is when using the built-in commands. I have a built-in command called "read" that takes one argument, the name of an environment variable (maybe one that doesn't exist yet). Then read the prompts for the value and assign that value to the variable. Here is an example:

% read TESTVAR test value test value test value % echo ${TESTVAR} test value test value test value 

Well let's say that I'm trying something like this:

 % echo here another test value > f1 % read TESTVAR < f1 % echo ${TESTVAR} here another test value 

This works fine, keep in mind that reading is done inside the parent process, I am not invoking reading with execvp from the moment it was created. Reading uses gets, which requires a stream variable, not fd. Therefore, after I spoke several times on irc forums, I was told to use fdopen to get the stream from the file descriptor. So before calling get, I call:

 rdStream = fdopen(inFD, "r"); 

then call

 if(fgets(buffer, envValLen, rdStream) != buffer) { if(inFD) fclose(rdStream); return -1; } if(inFD) fclose(rdStream); 

As you can see, at the moment I am closing the stream with fclose () if it is not equal to stdin (which is 0). It's necessary? Do I need to close the stream? Or just a file descriptor? Or both? I am completely confused about what I have to close, as they both refer to the same file, in a different way. At the moment, I am not closing fd, but I think I definitely should. I just would like someone to help make sure that my shell does not leak into any files, since I want it to be able to execute several thousand commands in one session without memory leak.

Thanks, if you guys want me to post more code, just ask.

+4
source share
2 answers

the standard says:

The fclose () function must execute the close() equivalent on the file descriptor associated with the stream pointed to by the stream.

So calling fclose enough; it will also close the handle.

+4
source

FILE is the buffering object from the C standard library. When you execute fclose (the standard C function), it will eventually call close (the Unix system function), but only after the C library buffers are flushed. So, I would say if you use fopen and fwrite , then you should use fclose , not just close , otherwise you risk losing some data.

+2
source

All Articles