改变正在运行的进程的环境

改变正在运行的进程的环境

如何改变env已经运行的进程中的某些变量,例如通过/proc/PID/environ?That“file”is read-only

需要更改或取消设置长时间运行的批处理作业的 DISPLAY 变量而不终止它。

答案1

如果没有令人讨厌的 hacks,你就无法做到这一点 - 没有 API 可以做到这一点,没有办法通知进程它的环境已经改变(因为无论如何这实际上是不可能的)。
即使您确实设法做到了这一点,也无法确保它会产生任何效果 - 该过程很可能已经缓存了您试图戳的环境变量(因为没有什么可以改变它) )。

如果您确实想这样做,并且准备好在出现问题时收拾残局,则可以使用调试器。例如,参见这个 Stack Overflow 问题:
有没有办法改变另一个进程的环境变量?

本质上:

(gdb) attach process_id
(gdb) call putenv ("DISPLAY=your.new:value")
(gdb) detach

您可以尝试调用的其他可能的函数是setenvunsetenv

请务必记住,如果您的目标进程对其环境块做了“有趣”的事情,这可能不起作用,或者会产生可怕的后果。首先要在非关键进程上进行测试,但要确保这些测试进程尽可能接近您要测试的进程。

答案2

如果我将 gdb 连接到当前 shell 并尝试设置 env 变量,它保持不变(或不存在):

$] sudo gdb -p $$
(gdb) call putenv("TEST=1234")
$1 = 0
(gdb) call (char*) getenv("TEST")
$2 = 0x0
(gdb) detach
(gdb) quit
$] echo "TEST=$TEST"
TEST=

我发现普特恩夫不起作用,但是设置环境变量做:

$] sudo gdb -p $$
(gdb) call (int) setenv("TEST", "1234", 1)
$1 = 0
(gdb) call (char*) getenv("TEST")
$2 = 0x55f19ff5edc0 "1234"
(gdb) detach
(gdb) quit
$] echo "TEST=$TEST"
TEST=1234

答案3

如果批处理作业可以从文件系统读取数据来检索更改,则无需这样做。只需使用临时唯一目录的路径运行作业,并将相同的路径传递给子 shell 脚本即可。脚本将锁定该目录中的文件,并在锁定文件附近写入具有新值的文件。作业脚本有时会锁定同一文件,解析并从值文件中读回更改。要了解如何在 Unix shell 中创建锁,只需搜索unix shell lock filebash lock file,已经有很多解决方案。

该解决方案的好处:

  • 几乎可以在任何操作系统(如 Windows 或 Unix)之间移植
  • 只要值文件保持简单,就不需要为每个解释器(unix/windows/etc)编写和复制复杂的解析器来从文件中读回值

实施中存在的问题如下:

  • 实现依赖于 shell 重定向阶段的文件锁(flock在Linux中实现排除效果,在Windows中有内置的排除)
  • 变量的每个值都是单行值(而不是多行)

实现存储在这里:https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/std https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/bash/tacklelib

实施bash

set_vars_from_locked_file_pair.sh

#!/bin/bash

# Another variant of a configuration file variables read and set script.
# The script must stay as simple as possible, so for this task it uses these parameters:
# 1. path where to lock a lock file
# 2. path where to read a file with variable names (each per line)
# 3. path where to read a file with variable values (each per line, must be the same quantity of lines with the variable names file)

# Script can be ONLY included by "source" command.
if [[ -n "$BASH" && (-z "$BASH_LINENO" || ${BASH_LINENO[0]} -gt 0) ]]; then 

function set_vars_from_locked_file_pair()
{
  # the lock file directory must already exist
  if [[ ! -d "${1%[/\\]*}" ]]; then
    echo "$0: error: lock file directory does not exist: \`${1%[/\\]*}\`" >&2
    return 1
  fi

  if [[ ! -f "${2//\\//}" ]]; then
    echo "$0: error: variable names file does not exist: \`$2\`" >&2
    return 2
  fi

  if [[ ! -f "${3//\\//}" ]]; then
    echo "$0: error: variable values file does not exist: \`$3\`" >&2
    return 3
  fi

  function LocalMain()
  {
    # open file for direct reading by the `read` in the same shell process
    exec 7< "$2"
    exec 8< "$3"

    # cleanup on return
    trap "rm -f \"$1\" 2> /dev/null; exec 8>&-; exec 7>&-; trap - RETURN" RETURN

    local __VarName
    local __VarValue

    # shared acquire of the lock file
    while :; do
      # lock via redirection to file
      {
        flock -s 9

        # simultaneous iteration over 2 lists in the same time
        while read -r -u 7 __VarName; do
          read -r -u 8 __VarValue
          # drop line returns
          __VarName="${__VarName//[$'\r\n']}"
          __VarValue="${__VarValue//[$'\r\n']}"
          # instead of `declare -gx` because `-g` is introduced only in `bash-4.2-alpha`
          export $__VarName="$__VarValue"
          (( ${4:-0} )) && echo "$__VarName=\`$__VarValue\`"
        done

        break

        # return with previous code
      } 9> "$1" 2> /dev/null # has exclusive lock been acquired?

      # busy wait
      sleep 0.02
    done
  }

  LocalMain "${1//\\//}" "${2//\\//}" "${3//\\//}" "${4:-0}"
}

fi

testlock.sh

#!/bin/bash

{
  flock -x 9 2> /dev/null
  read -n1 -r -p "Press any key to continue..."
  echo >&2
} 9> "lock"

在 Windows 上也是如此(作为可移植性的示例):

set_vars_from_locked_file_pair.bat

@echo off

rem Another variant of a configuration file variables read and set script.
rem The script must stay as simple as possible, so for this task it uses these parameters:
rem 1. path where to lock a lock file
rem 2. path where to read a file with variable names (each per line)
rem 3. path where to read a file with variable values (each per line, must be the same quantity of lines with the variable names file)

rem disable alternative variables expansion to avoid `!` character consumption
setlocal DISABLEDELAYEDEXPANSION

set "FILE_LOCK_PATH=%~1"
set "FILE_VAR_NAMES_PATH=%~2"
set "FILE_VAR_VALUES_PATH=%~3"
set "PRINT_VARS_SET=%~4"

set "FILE_LOCK_DIR=%~d1"

rem the lock file directory must already exist
if not exist "%FILE_LOCK_DIR%" (
  echo.%~nx0: error: FILE_LOCK_DIR does not exist: "%FILE_LOCK_DIR%"
  exit /b 1
) >&2

if not exist "%FILE_VAR_NAMES_PATH%" (
  echo.%~nx0: error: FILE_VAR_NAMES_PATH does not exist: "%FILE_VAR_NAMES_PATH%"
  exit /b 2
) >&2

if not exist "%FILE_VAR_VALUES_PATH%" (
  echo.%~nx0: error: FILE_VAR_VALUES_PATH does not exist: "%FILE_VAR_VALUES_PATH%"
  exit /b 3
) >&2

rem The endlocal works only in the same call context
endlocal

rem exclusive acquire of the lock file
:REPEAT_LOCK_LOOP

(
  (
    rem if lock is acquired, then we are in...
    call :MAIN "%%~2" "%%~3" "%%~4"
    call set "LASTERROR=%%ERRORLEVEL%%"

    rem exit with return code from the MAIN
  ) 9> "%~1" && (del /F /Q /A:-D "%~1" & goto EXIT)
) 2>nul

rem Busy wait: with external call significantly reduces CPU consumption while in a waiting state
pathping localhost -n -q 1 -p 20 >nul 2>&1
goto REPEAT_LOCK_LOOP

:EXIT
exit /b %LASTERROR%

:MAIN
rem drop last error
type nul>nul

if %~30 NEQ 0 goto SET_WITH_PRINT

rem trick with simultaneous iteration over 2 lists in the same time
(
  for /f "usebackq eol=# tokens=* delims=" %%i in ("%~1") do (
    set /p "%%i="
  )
) < "%~2"

exit /b 0

:SET_WITH_PRINT
rem trick with simultaneous iteration over 2 lists in the same time
(
  for /f "usebackq eol=# tokens=* delims=" %%i in ("%~1") do (
    set /p "%%i="
    rem to filter out wrong matches of a variable from the `set "%%i"`
    for /f "usebackq eol=# tokens=1,* delims==" %%j in (`set "%%i"`) do if /i "%%j" == "%%i" echo.%%i=%%k
  )
) < "%~2"

exit /b 0

测试锁.bat

@echo off

(
  pause
) 9> ./lock

要写入文件,只需以相同的方式锁定您的代码即可。

相关内容