如何从命令行获取与外壳无关,与语言无关的当前Linux进程ID [英] How to get the current Linux process ID from the command line a in shell-agnostic, language-agnostic way

查看:78
本文介绍了如何从命令行获取与外壳无关,与语言无关的当前Linux进程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Linux命令行中以与shell无关的,与语言无关的方式获取其当前进程ID(pid)?

pidof(8) 似乎没有选择权来获取调用进程'. Bash当然具有$$-但是对于我的一般用法,我不能依赖Shell(Bash或其他方式).而且在某些情况下,我无法编写脚本或可编译程序,因此Bash/Python/C/C ++(等等)将无法工作.

这是一个特定的用例:我想获取基于基于Python-Fabric 的运行中的pid,远程SSH进程(可能希望避免假设正在运行bash),以便除其他外,我可以复制和/或创建具有唯一文件名的文件和/或目录(如mkdir /tmp/mydir.$$所示).

如果我们可以解决特定于Fabric的问题,那会有所帮助-但这不能解决我的长期问题.对于将来所有情况下的通用用途,我只需要一个返回$$在Bash中提供的内容的命令.

解决方案

好的答案+评论此处此处.谢谢.将两者结合在一起,在需要POSIX-shell的情况和没有POSIX-shell的情况下提供两种折衷方案:

  1. 可用的POSIX shell:使用 $$
  2. 常规cmdline:使用 cut -d ' ' -f 4 /proc/self/stat

此处中显示了这两种方法(以及其他建议的非工作方法)的示例会话.. >

(不确定与shell无关会多么相关/有用,但是已经经历了很多次无壳运行系统"约束,现在都尽可能地寻求与shell无关的选项了.)

How does one get their current process ID (pid) from the Linux command line in a shell-agnostic, language-agnostic way?

pidof(8) appears to have no option to get the calling process' pid. Bash, of course, has $$ - but for my generic usage, I can't rely on a shell (Bash or otherwise). And in some cases, I can't write a script or compilable program, so Bash / Python / C / C++ (etc.) will not work.

Here's a specific use case: I want to get the pid of the running, Python-Fabric-based, remote SSH process (where one may want to avoid assuming bash is running), so that among other things I can copy and/or create files and/or directories with unique filenames (as in mkdir /tmp/mydir.$$).

If we can solve the Fabric-specific problem, that's helpful - but it doesn't solve my long-term problem. For general-purpose usage in all future scenarios, I just want a command that returns what $$ delivers in Bash.

解决方案

Great answers + comments here and here. Thx all. Combining both into one answer, providing two options with tradeoffs in POSIX-shell-required vs no-POSIX-shell-required contexts:

  1. POSIX shell available: use $$
  2. General cmdline: employ cut -d ' ' -f 4 /proc/self/stat

Example session with both methods (along with other proposed, non-working methods) shown here.

(Not sure how pertinent/useful it is to be so concerned with being shell independent, but have simply experienced many times the "run system call without shell" constraint that now seek shell-independent options whenever possible.)

这篇关于如何从命令行获取与外壳无关,与语言无关的当前Linux进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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