Questions about putenv() and setenv()

前端 未结 5 1581
太阳男子
太阳男子 2020-12-03 00:49

I have been thinking a little about environment variables and have a few questions/observations.

  • putenv(char *string);

    This call seems

5条回答
  •  温柔的废话
    2020-12-03 01:24

    I would highly recommend against using either of these functions. Either can be used safely and without leaks, as long as you're careful and only one part of your code is responsible for modifying the environment, but it's hard to get right and dangerous if any code might be using threads and might read the environment (e.g. for timezone, locale, dns config, etc. purposes).

    The only two purposes I can think of for modifying the environment are to change the timezone at runtime, or to pass a modified environment to child processes. For the former, you probably have to use one of these functions (setenv/putenv), or you could walk environ manually to change it (this might be safer if you're worried other threads could try to read the environment at the same time). For the latter use (child processes), use one of the exec-family functions that lets you specify your own environment array, or simply clobber environ (the global) or use setenv/putenv in the child process after fork but before exec, in which case you don't have to care about memory-leaks or thread-safety because there are no other threads and you're about to destroy your address space and replace it with a new process image.

提交回复
热议问题