【问题标题】:Is there a way to print the PID of the process that called my C binary有没有办法打印调用我的 C 二进制文件的进程的 PID
【发布时间】:2012-09-05 15:58:25
【问题描述】:

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

使用 bash,我可以轻松地打印“谁”运行了一个脚本:

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

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

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

【问题讨论】:

    标签: c bash unix gcc solaris


    【解决方案1】:

    您应该查看来自<unistd.h>getpidgetppid 函数。

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int
    main(void)
    {
        printf("%ld%ld", (long)getpid(), (long)getppid());
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      使用getppid。请参阅man 2 getppidhere's linux 手册页。

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2010-10-23
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 2020-07-20
          • 1970-01-01
          • 2016-11-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多