简体   繁体   English

在没有fork / exec,popen()和system()的情况下获取Linux信息

[英]Getting linux information without fork/exec, popen(), and system()

I want to know how to get the following linux system information from C++ without using fork/exec, popen(), and system() : 我想知道如何在不使用fork / exec,popen()和system()的情况下从C ++获取以下linux系统信息:

  1. Get the command string (name) that started the process for a given process id. 获取启动给定进程ID的进程的命令字符串(名称)。
  2. Send a signal to a process 向过程发送信号
  3. Catch and display all the signals my program receives 捕获并显示我的程序收到的所有信号
  4. Get the process id(s) for any given process name 获取任何给定进程名称的进程ID

Any hints would be appreciated. 任何提示将不胜感激。

Thank you so much for your time! 非常感谢您的参与!

I believe the info for 1) is contained in /proc/PID/cmdline 我相信1)的信息包含在/ proc / PID / cmdline中

If you want the current process you can use /proc/self/ - handy when you don't know pid. 如果您需要当前进程,则可以使用/ proc / self /-当您不知道pid时很方便。 I don't know much about C++ but in C you can use open and read syscalls to do it, which avoids forking. 我对C ++不太了解,但是在C中,您可以使用open和read syscall来做到这一点,从而避免了分叉。

I think a lot of the other answers you can probably do by manipulating /proc entries as well. 我认为您还可以通过处理/ proc条目来完成许多其他答案。 I beleive /proc/PID/status tells you about signals that have been caught blocked and ignored by the specified PID as well. 我相信/ proc / PID / status也会告诉您有关被指定PID阻塞和忽略的信号。

edit: Thinking a bit more for 4) you can recursively loop through the pid entries in /proc to look up your given process name - this is only way I can think of without forking (calling "ps" from within code as other suggested requires a fork/exec). 编辑:为4考虑更多点,您可以递归地循环遍历/ proc中的pid条目以查找给定的进程名称-这是我可以想到的唯一方法,无需分叉(根据建议的其他方式从代码中调用“ ps”分叉/执行)。 Is there a particular reason you are avoiding fork? 您有避免叉的特殊原因吗?

  1. main function of a process receives that bit 进程的主要功能接收该位
  2. kill - ie http://man7.org/linux/man-pages/man2/kill.2.html 杀死-即http://man7.org/linux/man-pages/man2/kill.2.html
  3. See 2 见2
  4. Tricky.Requires me thinking 棘手的需要我思考
  1. From main, you may print argv[0]. 您可以从main打印argv [0]。 But that won't help always as the starting program may get replaced by a new due to call to fork/exec. 但这并不能总是有帮助,因为调用fork / exec可能会使启动程序替换为新程序。
  2. You need to use kill command line program or kill system call 您需要使用kill命令行程序或kill系统调用
  3. Check the man page for sigaction 检查手册页是否正确
  4. I am assuming you are meaning executable name. 我假设您的意思是可执行文件名称。 You may do the below, may not work on all Unix systems, but should work on Linux. 您可以执行以下操作,可能无法在所有Unix系统上使用,但应在Linux上使用。

    ps -ef | ps -ef | grep " program-name" | grep“程序名” | awk ' { print $2 } ' awk'{打印$ 2}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM