comparison lib/lib.c @ 1523:e5b52720f539 draft

Use O_CLOEXEC instead of O_RDONLY to signal loopfiles_rw() to close filehandles.
author Rob Landley <rob@landley.net>
date Tue, 14 Oct 2014 14:16:34 -0500
parents d7be3d62a5cb
children 95cb37adb024
comparison
equal deleted inserted replaced
1522:fc2200f927af 1523:e5b52720f539
419 // Iterate through an array of files, opening each one and calling a function 419 // Iterate through an array of files, opening each one and calling a function
420 // on that filehandle and name. The special filename "-" means stdin if 420 // on that filehandle and name. The special filename "-" means stdin if
421 // flags is O_RDONLY, stdout otherwise. An empty argument list calls 421 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
422 // function() on just stdin/stdout. 422 // function() on just stdin/stdout.
423 // 423 //
424 // Note: read only filehandles are automatically closed when function() 424 // Note: pass O_CLOEXEC to automatically close filehandles when function()
425 // returns, but writeable filehandles must be close by function() 425 // returns, otherwise filehandles must be closed by function()
426 void loopfiles_rw(char **argv, int flags, int permissions, int failok, 426 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
427 void (*function)(int fd, char *name)) 427 void (*function)(int fd, char *name))
428 { 428 {
429 int fd; 429 int fd;
430 430
439 perror_msg("%s", *argv); 439 perror_msg("%s", *argv);
440 toys.exitval = 1; 440 toys.exitval = 1;
441 continue; 441 continue;
442 } 442 }
443 function(fd, *argv); 443 function(fd, *argv);
444 if (flags == O_RDONLY) close(fd); 444 if (flags & O_CLOEXEC) close(fd);
445 } while (*++argv); 445 } while (*++argv);
446 } 446 }
447 447
448 // Call loopfiles_rw with O_RDONLY and !failok (common case). 448 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
449 void loopfiles(char **argv, void (*function)(int fd, char *name)) 449 void loopfiles(char **argv, void (*function)(int fd, char *name))
450 { 450 {
451 loopfiles_rw(argv, O_RDONLY, 0, 0, function); 451 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
452 } 452 }
453 453
454 // Slow, but small. 454 // Slow, but small.
455 455
456 char *get_rawline(int fd, long *plen, char end) 456 char *get_rawline(int fd, long *plen, char end)