Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

close all file descriptors using fork

Status
Not open for further replies.

scienzia

Programmer
Feb 21, 2002
160
IT
Hi,

I have an application that uses a fork and and the execv function to start an application.

The problem is that I don't want the child process to inherit the open files of the parent.
I found out that the child is able to access the files opened by the parent before the fork.

Is there a way to close all the files opened in the child process before launching the execv?

Is there another way to solve this problem?

Thanks in advance.
 
you have to start your child process by closing all the file descriptors. I think there is not option, because the fork function duplicates the program context, which includes the file descriptors.

Code:
   ...
   FILE *fd;
   fd=fopen(filename, "r");
   ...
   if (Fork() == 0) {  //child process
      Close(fd); /* child closes its file descriptor*/

      ...
      // process to be done by the child

      exit(0);         /* child exits */

    } else{ //parent process

     ...
      // process to be done by the parent

    }

if not, you can use threads ...
 
Hi,

thanks for the response.

I found the solution:

Code:
fcntl(fd_gpio, F_SETFD, FD_CLOEXEC);

This makes the file close as soon as you make an exec function.

Thankyou anyway.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top