在GDB中调试程序时如何获取程序环境 [英] How to get environment of a program while debugging it in GDB

查看:99
本文介绍了在GDB中调试程序时如何获取程序环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Linux上的GDB中调试程序。我正在使用 getenv setenv 调用来读取和设置环境变量。例如,我调用 setenv( TZ, UTC,1); 设置时区的TZ环境变量。

I am debugging a program in GDB on linux. I am using getenv and setenv calls to read and set environment variables. For example I am calling setenv("TZ", "UTC", 1); to set the TZ environment variable for timezone.

要检查是否设置了env变量,我正在使用GDB命令 show environment 。这将打印所有环境变量及其值。但是它不会显示 TZ 被设置。

To check if the env variable is set I am using GDB command show environment. This prints all the environment variables and their values. But it dose not show TZ being set.

甚至命令显示环境TZ 未定义环境变量 TZ。

它们是检查环境的另一种方法

Is their another way to check the environment of the debugged program?

p *(char *)getenv( TZ)返回正确值 UTC

推荐答案

gdb命令 show environment 显示的环境属于 gdb [请参见注释],而不是正在调试的程序的环境。

The gdb command show environment shows an environment which belongs to gdb [see note], not the environment of the program being debugged.

调用 getenv 似乎是打印运行程序环境的完全合理的方法。

Calling getenv seems like a totally reasonable approach to printing the running program's environment.

Gdb维护一个环境数组,该数组最初从其自己的环境复制而来,用于启动每个新的子进程。 显示环境设置环境在此环境下有效,因此设置环境将在您下次启动正在调试的程序的下一次中更改环境变量。程序启动后,加载程序会将环境复制到程序的地址空间,并且使用 setenv 进行的任何更改都将应用于该阵列,而不是由<$维护的阵列。 c $ c> gdb 。

Gdb maintains an environment array, initially copied from its own environment, which it uses to start each new child process. show environment and set environment work on this environment, so set environment will change an environment variable for the next time you start the program being debugged. Once the program is started, the loader will have copied the environment into the program's address space, and any changes made with setenv apply to that array, not the one maintained by gdb.

在Linux上,每个进程的环境可以通过伪文件 / proc / PID / environ 获得,其中 PID 被进程的pid代替。该文件的值是一个以null终止的字符串的列表,因此将其打印出来需要进行少量工作。

On Linux, every process's environment is available through the pseudofile /proc/PID/environ, where PID is replaced by the pid of the process. The value of that file is a list of null-terminated strings, so printing it out takes a small amount of work.

在gdb内部,一旦开始运行要调试的程序,您可以使用 info proc 获取其pid,然后使用它来打印整个环境:

Inside gdb, once you've started running the program to be debugged, you can get its pid with info proc and then use that to print the entire environment:

(gdb) info proc
process 6074
...
(gdb) shell xargs -0 printf %s\\n < /proc/6074/environ
XDG_VTNR=7
KDE_MULTIHEAD=false
...

当然,我可以在gdb之外,从另一个终端轻松地做到这一点。

Of course, I could have done that just as easily outside of gdb, from a different terminal.

这篇关于在GDB中调试程序时如何获取程序环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆