【问题标题】:How to get information in core handler program如何在核心处理程序中获取信息
【发布时间】:2018-09-10 22:21:10
【问题描述】:

我通过Naming of core dump files

此文档说明如何获取进程 ID、主机名等。如果配置如下:

echo "|/var/core_interceptor/bin/hello %P %u %g %s %t %c %e %h %d %E %i %p" > /proc/sys/kernel/core_pattern

echo "|/var/core_interceptor/bin/systemd-coredump %P %u %g %s %t %c %e %h %d %E %i %p" > /proc/sys/kernel/core_pattern 


#include <stdio.h>
#define FILE_NAME "/var/core_interceptor/bin/text.txt"
int main(int argc, char *argv[])
{
   int i = 0;
   FILE* file_ptr = fopen(FILE_NAME, "w");
   for (i = 0; i < argc; i++)
     fprintf(file_ptr, "\n%s", argv[i]);
   fclose(file_ptr);
   return 0;
}

这个hello.c 除了将它写入一个文本文件之外没有做任何事情。当我看到生成的文件时,我看到所有带有值的参数,即我看到实际的 PID 等。

但是,当我像这样配置 python 程序时:

echo "|/var/core_interceptor/bin/pyhandler.py %P %u %g %s %t %c %e %h %d %E %i %p" > /proc/sys/kernel/core_pattern

我在创建的文件中没有得到任何参数。

$ cat pyhandler.py 
#!/usr/bin/python

import sys
f = open("/var/core_interceptor/bin/text1.txt", "w")
f.write("Called")
f.write(sys.argv[0:])
f.close()

这个 py 脚本被调用但不打印参数:

$ cat text1.txt 
Called

为什么我可以在 C 程序中获取 args 而在 python 中却不行?

【问题讨论】:

    标签: python linux coredump


    【解决方案1】:

    您可能已经想到了这一点,但您的程序很可能会抛出异常,因为您将 list 类型的参数提供给需要 str 类型的方法。

    示例程序:

    cat arg_writer.py
    #!/usr/bin/env python3.6
    
    import sys
    
    with open("/tmp/output.txt", "w") as output:
        output.write(sys.argv[0:])
    

    执行:

    ./arg_writer.py
    Traceback (most recent call last):
      File "./arg_writer.py", line 6, in <module>
        output.write(sys.argv[0:])
    TypeError: write() argument must be str, not list
    [crknight@tbs5g-dev-san-02 tmp]$ 
    
    

    如果你在编写之前将列表强制转换为字符串形式,你可能会得到你想要的:

    #!/usr/bin/env python3.6
    
    import sys
    
    with open("/tmp/output.txt", "w") as output:
        output.write(str(sys.argv[0:]))
    

    示例输出:

    cat /tmp/output.txt
    ['./arg_writer.py']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多