spawn_faction_addopen.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright (C) 2000, 2009-2023 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. This file is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as
  5. published by the Free Software Foundation; either version 2.1 of the
  6. License, or (at your option) any later version.
  7. This file is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <spawn.h>
  16. #include <errno.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <unistd.h>
  20. #if !_LIBC
  21. # define __sysconf(open_max) getdtablesize ()
  22. #endif
  23. #if REPLACE_POSIX_SPAWN
  24. # include "spawn_int.h"
  25. #endif
  26. /* Add an action to FILE-ACTIONS which tells the implementation to call
  27. 'open' for the given file during the 'spawn' call. */
  28. int
  29. posix_spawn_file_actions_addopen (posix_spawn_file_actions_t *file_actions,
  30. int fd, const char *path, int oflag,
  31. mode_t mode)
  32. #undef posix_spawn_file_actions_addopen
  33. {
  34. int maxfd = __sysconf (_SC_OPEN_MAX);
  35. /* Test for the validity of the file descriptor. */
  36. if (fd < 0 || fd >= maxfd)
  37. return EBADF;
  38. #if !REPLACE_POSIX_SPAWN
  39. return posix_spawn_file_actions_addopen (file_actions, fd, path, oflag, mode);
  40. #else
  41. {
  42. /* Copy PATH, because the caller may free it before calling posix_spawn()
  43. or posix_spawnp(). */
  44. char *path_copy = strdup (path);
  45. if (path_copy == NULL)
  46. return ENOMEM;
  47. /* Allocate more memory if needed. */
  48. if (file_actions->_used == file_actions->_allocated
  49. && __posix_spawn_file_actions_realloc (file_actions) != 0)
  50. {
  51. /* This can only mean we ran out of memory. */
  52. free (path_copy);
  53. return ENOMEM;
  54. }
  55. {
  56. struct __spawn_action *rec;
  57. /* Add the new value. */
  58. rec = &file_actions->_actions[file_actions->_used];
  59. rec->tag = spawn_do_open;
  60. rec->action.open_action.fd = fd;
  61. rec->action.open_action.path = path_copy;
  62. rec->action.open_action.oflag = oflag;
  63. rec->action.open_action.mode = mode;
  64. /* Account for the new entry. */
  65. ++file_actions->_used;
  66. return 0;
  67. }
  68. }
  69. #endif
  70. }