develooper Front page | perl.perl5.porters | Postings from January 2011

fcntl() and FD_CLOEXEC

Thread Next
January 28, 2011 13:11
fcntl() and FD_CLOEXEC
Message ID:
The following is based on Perl 5.12.3 code source but the assumption 
goes back to at least 5.8.4 (the oldest tarball I have).

In 11 places in the Perl core source:
- pp_sys.c 6
- perl.c   2
- doio.c   2
- toke.c   1
there is an assumption when using fcntl() with F_SETFD that it always 
takes a third parameter of 1 or 0; for at least one OS, in my case 
NetWare, it has a value other than 1. In all cases that I am aware of 
(including NetWare) the close-on-exec value is defined by the symbolic 
constant FD_CLOEXEC in fcntl.h.

Hence, a more correct rendering of the F_SETFD command would, in Perl's 
case, look more like (f.e):

--- fcntl(fd, F_SETFD, fd > PL_maxsysfd);
+++ fcntl(fd, F_SETFD, (fd > PL_maxsysfd ? FD_CLOEXEC : 0));

In the case of the 2 places in perl.c:

--- fcntl(PerlIO_fileno(*rsfpp),F_SETFD,1);
+++ fcntl(PerlIO_fileno(*rsfpp),F_SETFD,FD_CLOEXEC);

In the case of doio.c (in 1 place) there is:

> #if defined(HAS_FCNTL) && defined(F_SETFD)
> 		/* Assume if we have F_SETFD we have F_GETFD */
>                 int coe = fcntl(ofd,F_GETFD);
> #endif
>                 PerlIO_close(fp);
>                 PerlLIO_dup2(dupfd,ofd);
> #if defined(HAS_FCNTL) && defined(F_SETFD)
> 		/* The dup trick has lost close-on-exec on ofd */
> 		fcntl(ofd,F_SETFD, coe);
> #endif

 From my readings the only flag returned by F_GETFD is the close-on-exec 
flag, and if the intent of this block is only to set this flag for 'ofd' 
then it could be more easily done using FD_CLOEXEC and remove the need 
of the 'int coe'.

Lastly, near the top of pp_sys.c there is the following:

#if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
#  define FD_CLOEXEC 1		/* NeXT needs this */

I don't doubt '1' is the most likely but if the above changes should be 
implemented perhaps this 'define' could be moved to perl.h after all 
potential includes of fcntl.h, to better serve the above 4 .c likely to 
be affected.

For your consideration.

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About