1 /* $NetBSD: dup2_pass_on_exec.c,v 1.1.1.1 2009/06/23 10:08:59 tron Exp $ */ 2 3 /*++ 4 /* NAME 5 /* dup2_pass_on_exec 1 6 /* SUMMARY 7 /* dup2 close-on-exec behaviour test program 8 /* SYNOPSIS 9 /* dup2_pass_on_exec 10 /* DESCRIPTION 11 /* dup2_pass_on_exec sets the close-on-exec flag on its 12 /* standard input and then dup2() to duplicate it. 13 /* Posix-1003.1 specifies in section 6.2.1.2 that dup2(o,n) should behave 14 /* as: close(n); n = fcntl(o, F_DUPFD, n); as long as o is a valid 15 /* file-descriptor, n!=o, and 0<=n<=[OPEN_MAX]. 16 /* Section 6.5.2.2 states that the close-on-exec flag of the result of a 17 /* successful fcntl(o, F_DUPFD, n) is cleared. 18 /* 19 /* At least Ultrix4.3a does not clear the close-on-exec flag of n on 20 /* dup2(o, n). 21 /* DIAGNOSTICS 22 /* Problems are reported to the standard error stream. 23 /* LICENSE 24 /* .ad 25 /* .fi 26 /* The Secure Mailer license must be distributed with this software. 27 /* AUTHOR(S) 28 /* Christian von Roques <roques@pond.sub.org> 29 /* Forststrasse 71 30 /* 76131 Karlsruhe, GERMANY 31 /*--*/ 32 33 #include <stdio.h> 34 #include <fcntl.h> 35 #include <unistd.h> 36 #include <stdlib.h> 37 38 #define DO(s) if (s < 0) { perror(#s); exit(1); } 39 40 int main(int unused_argc, char **unused_argv) 41 { 42 int res; 43 44 printf("Setting the close-on-exec flag of file-descriptor 0.\n"); 45 DO(fcntl(0, F_SETFD, 1)); 46 47 printf("Duplicating file-descriptor 0 to 3.\n"); 48 DO(dup2(0, 3)); 49 50 printf("Testing if the close-on-exec flag of file-descriptor 3 is set.\n"); 51 DO((res = fcntl(3, F_GETFD, 0))); 52 if (res & 1) 53 printf( 54 "Yes, a newly dup2()ed file-descriptor has the close-on-exec \ 55 flag cloned.\n\ 56 THIS VIOLATES Posix1003.1 section 6.2.1.2 or 6.5.2.2!\n\ 57 You should #define DUP2_DUPS_CLOSE_ON_EXEC in sys_defs.h \ 58 for your OS.\n"); 59 else 60 printf( 61 "No, a newly dup2()ed file-descriptor has the close-on-exec \ 62 flag cleared.\n\ 63 This complies with Posix1003.1 section 6.2.1.2 and 6.5.2.2!\n"); 64 65 return 0; 66 } 67