training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

ex-8.7.c (1038B)


      1 /*
      2  * Advanced Programming in the UNIX(r) Environment
      3  *
      4  * Exercise 8.7
      5 */
      6 
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <sys/types.h>
     10 #include <dirent.h>
     11 #include <unistd.h>
     12 #include <fcntl.h>
     13 
     14 void pflags(int fd);
     15 
     16 int
     17 main(void)
     18 {
     19    DIR *dir;
     20    const char *dirname = "/";
     21    int fd;
     22 
     23    /* open the directory stream */
     24    if( (dir = opendir(dirname)) == NULL ) {
     25       perror("opendir");
     26       return EXIT_FAILURE;
     27    }
     28    pflags(dirfd(dir)); /* close-on-exec flag status */
     29 
     30    /* Open the directory for reading */
     31    if( (fd = open(dirname, O_RDONLY)) == -1 ) {
     32       closedir(dir);
     33       perror("open");
     34       return EXIT_FAILURE;
     35    }
     36 
     37    pflags(fd); /* close-on-exec flag status */
     38 
     39    close(fd);     /* close the descriptor */
     40    closedir(dir); /* close the stream */
     41 
     42    return EXIT_SUCCESS; /* Make C compiler happy! */
     43 } /* eof main() */
     44 
     45 void
     46 pflags(int fd)
     47 {
     48    int flags;
     49 
     50    if( (flags = fcntl(fd, F_GETFD)) != -1 )
     51       printf("close-on-exec: %s\n", (flags & FD_CLOEXEC ? "on" : "off"));
     52    
     53 } /* eof pflags() */
     54