bash 有没有办法打印调用我的 C 二进制文件的进程的 PID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12285387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:12:34  来源:igfitidea点击:

Is there a way to print the PID of the process that called my C binary

cbashunixgccsolaris

提问by Awalias

I need to know which perl script is using my C CLI.

我需要知道哪个 perl 脚本正在使用我的 C CLI。

Using bash I can easily print "who" ran a script using:

使用 bash 我可以轻松打印“谁”使用以下脚本运行脚本:

CALLER=$(ps ax | grep "^ *$PPID" | awk '{print $NF}')
echo $CALLER

Up to now I have been using this as a wrapper but it's not ideal. Is there a way to get this information from within C?

到目前为止,我一直在使用它作为包装器,但它并不理想。有没有办法从 C 中获取这些信息?

(I'm running UNIX w/ gcc)

(我正在运行带有 gcc 的 UNIX)

回答by pb2q

Use getppid. See man 2 getppid, here'sthe linux man page.

使用getppid. 看man 2 getppid这里是linux 手册页。

getppid() returns the process ID of the parent of the calling process

getppid() 返回调用进程的父进程ID

Twop's because this is for the “parent process”.

两个p,因为这是针对“父进程”的。

回答by md5

You should look at getpidand getppidfunctions from <unistd.h>.

你应该看看getpid,并getppid从功能<unistd.h>

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int
main(void)
{
    printf("%ld%ld", (long)getpid(), (long)getppid());
    return 0;
}

回答by hmjd

Use getppid()to obtain the process id of a process' parent.

使用getppid()获得进程的父进程ID。