如何从cmdline(以shell和语言独立的方式)获取当前的Linux进程ID(pid)? [英] How to get current Linux process ID (pid) from cmdline (in shell- and language-independent fashion)?

查看:1206
本文介绍了如何从cmdline(以shell和语言独立的方式)获取当前的Linux进程ID(pid)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Linux cmdline获取当前进程ID(pid)(以shell和语言独立的方式)? pidof(8)似乎没有选项可以获取调用进程pid。 bash当然有 $$ 但是对于我的通用用法,不能依赖shell(bash或其他)。在某些情况下,不能编写脚本或可编译的程序(因此bash,Python,C / C ++等将不起作用)。

How to get one's current process ID (pid) from Linux cmdline (in shell- and language-independent fashion)? pidof(8) appears to have no option to get the calling-processes pid. bash of course has $$ but for my generic usage, can't rely on a shell (bash or otherwise). And in some cases, can't write a script or compilable program (so bash, Python, C/C++, etc will not work).

具体用例:get运行的基于Python-Fabric 的远程ssh进程的pid(以便我可以复制/创建文件/ dirs具有唯一的文件名,如 mkdir / tmp / mydir。$$ ),其中可能想要避免假设bash正在运行。如果我们可以解决Fabric特定的问题,这是有帮助的,但不解决我的长期问题。对于所有未来情况下的通用用途,只需要一个返回 $$ 在bash中传递的cmd。

Specific use case: get the pid of the running, Python-Fabric-based, remote ssh process (so that among other things I can copy/create files/dirs with unique filenames, as in mkdir /tmp/mydir.$$), where one may want to avoid assuming bash is running. If we can solve the Fabric-specific problem, that's helpful, but doesn't solve my long-term problem. For general-purpose usage in all future scenarios, just want a cmd that returns what $$ delivers in bash.

推荐答案

好的答案和评论此处在这里。 Thx全部。将两者合并为一个答案,在POSIX-shell必需的与无POSIX-shell的必需上下文中提供两种选择权衡:

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可用:使用 $$

  2. 常规cmdline:雇佣 cut -d''-f 4 / proc / self / stat

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

示例会话与两种方法(以及其他建议的,非工作方法) a href =http://pastebin.com/yxiiT9HP =nofollow>此处。

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

(不确定如何相关/有用要非常关心shell独立,但是经历了很多次无shell运行系统调用约束,现在尽可能寻求与shell无关的选项。)

(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.)

这篇关于如何从cmdline(以shell和语言独立的方式)获取当前的Linux进程ID(pid)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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