linux - 获取进程的pid
如何在 Linux 上使用 C++ 获取名为 abc
的服务的 PID,而不使用系统调用?如果您愿意提供任何示例,我将不胜感激。
How can I get the PID of a service called abc
using C++ on Linux without using a system call? I would appreciate any examples that you care to offer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于长期以来不鼓励使用 sysctl ,因此推荐的方法是检查
/proc
并读取每个文件夹中的comm
文件。对于您的示例,如果该文件的内容是abc\n
,那么这就是您要查找的进程。我不太会说 C++,但这里有 POSIX C89 中的一种可能的解决方案:
警告:如果有多个正在运行的进程具有您正在查找的名称,则此代码将仅返回一个。如果您要更改此设置,请注意,在编写简单的 glob 时,您还将检查
/proc/self/comm
,这可能会导致重复条目。如果有多个进程具有相同的名称,则实际上没有一种方法可以确保您获得正确的进程。出于这个原因,许多守护进程都能够将其 pid 保存到文件中;检查你的文档。
Since use of
sysctl
has been discouraged for ages now, the recommended way of doing this is by examining each of the process entries in/proc
and reading thecomm
file in each folder. If, for your example, the contents of that file areabc\n
, that's the process you're looking for.I don't really speak C++, but here's a possible solution in POSIX C89:
Caveat: if there are multiple running processes with the name you're looking for, this code will only return one. If you're going to change that, be aware that with the naive glob written, you'll also examine
/proc/self/comm
, which could potentially lead to a duplicate entry.If there are multiple processes with the same name, there isn't really a way to ensure you got the right one. Many daemons have the ability to save their pids to a file for this reason; check your documentation.
谷歌已经涵盖了这个:)
http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html
虽然它确实使用了sysctl,这是一个系统调用!
它是 C,但在 C++ 中应该同样有效
Google has this covered :)
http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html
Although it does use sysctl, which is a system call!
It's C but should work just as well in C++