如何检测Linux上程序的启动?

时间:2011-05-20 16:35:55

标签: c linux pid

我写了一个简单的守护进程。 这个守护进程应该在我运行任何程序时响应。 这该怎么做? 在一个大守护进程循环中:

while(1)
{
   /* function which catches new programm running */
}

当我运行新程序(创建新程序)时,在linux中调用哪些函数?

8 个答案:

答案 0 :(得分:62)

对于Linux,内核中似乎有一个接口。在研究这个问题的同时,我遇到了使用CONFIG_CONNECTOR和CONFIG_PROC_EVENTS内核配置来获取进程死亡事件的人。

更多谷歌和我发现了这个:

http://netsplit.com/2011/02/09/the-proc-connector-and-socket-filters/

  

Proc连接器和插座滤波器   由scott发表于2011年2月9日

     

proc连接器是大多数人很少遇到的有趣的内核功能之一,甚至更少见到文档。同样是套接字过滤器。这是一种耻辱,因为它们都是非常有用的接口,如果能够更好地记录它们,它们可能有多种用途。

     

proc连接器允许您接收进程事件的通知,例如fork和exec调用,以及对进程的uid,gid或sid(会话ID)的更改。这些是通过读取内核头文件中定义的struct proc_event实例,通过基于套接字的接口提供的。

感兴趣的标题是:

#include <linux/cn_proc.h>

我在这里找到了示例代码:

http://bewareofgeek.livejournal.com/2945.html

/* This file is licensed under the GPL v2 (http://www.gnu.org/licenses/gpl2.txt) (some parts was originally borrowed from proc events example)

pmon.c

code highlighted with GNU source-highlight 3.1
*/

#define _XOPEN_SOURCE 700
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
#include <signal.h>
#include <errno.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*
* connect to netlink
* returns netlink socket, or -1 on error
*/
static int nl_connect()
{
int rc;
int nl_sock;
struct sockaddr_nl sa_nl;

nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (nl_sock == -1) {
    perror("socket");
    return -1;
}

sa_nl.nl_family = AF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = getpid();

rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
if (rc == -1) {
    perror("bind");
    close(nl_sock);
    return -1;
}

return nl_sock;
}

/*
* subscribe on proc events (process notifications)
*/
static int set_proc_ev_listen(int nl_sock, bool enable)
{
int rc;
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
    struct nlmsghdr nl_hdr;
    struct __attribute__ ((__packed__)) {
    struct cn_msg cn_msg;
    enum proc_cn_mcast_op cn_mcast;
    };
} nlcn_msg;

memset(&nlcn_msg, 0, sizeof(nlcn_msg));
nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
nlcn_msg.nl_hdr.nlmsg_pid = getpid();
nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;

nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);

nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;

rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
if (rc == -1) {
    perror("netlink send");
    return -1;
}

return 0;
}

/*
* handle a single process event
*/
static volatile bool need_exit = false;
static int handle_proc_ev(int nl_sock)
{
int rc;
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
    struct nlmsghdr nl_hdr;
    struct __attribute__ ((__packed__)) {
    struct cn_msg cn_msg;
    struct proc_event proc_ev;
    };
} nlcn_msg;

while (!need_exit) {
    rc = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
    if (rc == 0) {
    /* shutdown? */
    return 0;
    } else if (rc == -1) {
    if (errno == EINTR) continue;
    perror("netlink recv");
    return -1;
    }
    switch (nlcn_msg.proc_ev.what) {
    case PROC_EVENT_NONE:
        printf("set mcast listen ok\n");
        break;
    case PROC_EVENT_FORK:
        printf("fork: parent tid=%d pid=%d -> child tid=%d pid=%d\n",
            nlcn_msg.proc_ev.event_data.fork.parent_pid,
            nlcn_msg.proc_ev.event_data.fork.parent_tgid,
            nlcn_msg.proc_ev.event_data.fork.child_pid,
            nlcn_msg.proc_ev.event_data.fork.child_tgid);
        break;
    case PROC_EVENT_EXEC:
        printf("exec: tid=%d pid=%d\n",
            nlcn_msg.proc_ev.event_data.exec.process_pid,
            nlcn_msg.proc_ev.event_data.exec.process_tgid);
        break;
    case PROC_EVENT_UID:
        printf("uid change: tid=%d pid=%d from %d to %d\n",
            nlcn_msg.proc_ev.event_data.id.process_pid,
            nlcn_msg.proc_ev.event_data.id.process_tgid,
            nlcn_msg.proc_ev.event_data.id.r.ruid,
            nlcn_msg.proc_ev.event_data.id.e.euid);
        break;
    case PROC_EVENT_GID:
        printf("gid change: tid=%d pid=%d from %d to %d\n",
            nlcn_msg.proc_ev.event_data.id.process_pid,
            nlcn_msg.proc_ev.event_data.id.process_tgid,
            nlcn_msg.proc_ev.event_data.id.r.rgid,
            nlcn_msg.proc_ev.event_data.id.e.egid);
        break;
    case PROC_EVENT_EXIT:
        printf("exit: tid=%d pid=%d exit_code=%d\n",
            nlcn_msg.proc_ev.event_data.exit.process_pid,
            nlcn_msg.proc_ev.event_data.exit.process_tgid,
            nlcn_msg.proc_ev.event_data.exit.exit_code);
        break;
    default:
        printf("unhandled proc event\n");
        break;
    }
}

return 0;
}

static void on_sigint(int unused)
{
need_exit = true;
}

int main(int argc, const char *argv[])
{
int nl_sock;
int rc = EXIT_SUCCESS;

signal(SIGINT, &on_sigint);
siginterrupt(SIGINT, true);

nl_sock = nl_connect();
if (nl_sock == -1)
    exit(EXIT_FAILURE);

rc = set_proc_ev_listen(nl_sock, true);
if (rc == -1) {
    rc = EXIT_FAILURE;
    goto out;
}

rc = handle_proc_ev(nl_sock);
if (rc == -1) {
    rc = EXIT_FAILURE;
    goto out;
}

    set_proc_ev_listen(nl_sock, false);

out:
close(nl_sock);
exit(rc);
}

我发现此代码需要以root身份运行才能收到通知。

答案 1 :(得分:19)

我有兴趣试图在没有投票的情况下弄清楚如何做到这一点。 inotify()似乎不适用于/ proc,所以这个想法已经出来了。

但是,任何动态链接的程序都会在启动时访问某些文件,例如动态链接器。这对于安全目的来说是无用的,因为它不会触发静态链接的程序,但可能仍然有意义:

#include <stdio.h>
#include <sys/inotify.h>
#include <assert.h>
int main(int argc, char **argv) {
    char buf[256];
    struct inotify_event *event;
    int fd, wd;
    fd=inotify_init();
    assert(fd > -1);
    assert((wd=inotify_add_watch(fd, "/lib/ld-linux.so.2", IN_OPEN)) > 0);
    printf("Watching for events, wd is %x\n", wd);
    while (read(fd, buf, sizeof(buf))) {
      event = (void *) buf;
      printf("watch %d mask %x name(len %d)=\"%s\"\n",
         event->wd, event->mask, event->len, event->name);
    }
    inotify_rm_watch(fd, wd);
    return 0;
}

打印出的事件不包含任何有趣的信息 - 触发过程的pid似乎不是由inotify提供的。但是它可以用来唤醒并触发重新扫描/ proc

还要注意,短暂的程序可能会在这个东西醒来并完成扫描/触发之前再次消失 - 大概你会知道它们已经存在,但却无法了解它们是什么。当然,任何人都可以继续向dyanmic链接器打开和关闭fd,让你淹没在噪音中。

答案 2 :(得分:10)

看看Sebastian Krahmer撰写的this little program,它以资源有效的方式和非常简单的代码完全按照您的要求进行。

确实需要您的内核启用了CONFIG_PROC_EVENTS,例如最新的Amazon Linux Image(2012.09)就不是这种情况。

更新:在request to Amazon之后,Amazon Linux Image内核现在支持PROC_EVENTS

答案 3 :(得分:9)

使用forkstat,它是proc事件最完整的客户端:

sudo forkstat -e exec,comm,core

打包在Ubuntu,Debian和AUR中。


在此之前,有cn_proc

 bzr branch lp:~kees/+junk/cn_proc

Makefile需要进行一些小改动(LDLIBS而不是LDFLAGS)。

cn_proc和exec-notify.c(Arnaud发布的)共享一个共同的祖先; cn_proc处理更多事件并具有更清晰的输出,但在进程快速退出时不具备弹性。


哦,找到了另一个exec-notify的分支,extrace。 这个缩进子进程在其父进程下面(使用pid_depth启发式)。

答案 4 :(得分:3)

您选择的搜索机器的关键字是“进程事件连接器”。

我找到了两个使用它们的工具,exec-notifycn_proc

我更喜欢后者,但他们的工作都非常好。

答案 5 :(得分:1)

我不知道是否存在更好的方法,但您可以定期扫描/proc文件系统。

例如,/proc/<pid>/exe是进程可执行文件的符号链接。

在我的系统(Ubuntu / RedHat)上,/proc/loadavg包含正在运行的进程数(正斜杠后的数字)以及最近启动的进程的pid。如果您的守护程序轮询该文件,那么对这两个数字中的任何一个进行的任何更改都将告诉它何时需要重新扫描/proc以查找新进程。

这绝不是防弹,但却是我能想到的最合适的机制。

答案 6 :(得分:0)

您可以扫描操作系统以查找符合条件的程序,也可以等待程序向您的守护程序报告自己。您选择哪种技术将在很大程度上取决于您对非守护程序的控制程度。

扫描可以通过内核系统调用,或通过读取用户空间公布的内核详细信息(与/ proc文件系统一样)来完成。请注意,扫描不能保证您可以找到任何特定程序,就好像程序设法在扫描周期之间启动和终止一样,它根本不会被检测到。

更复杂的过程检测技术是可能的,但它们也需要更复杂的实现。在开始寻找异国情调的解决方案(插入内核驱动程序等)之前,了解真正需要的是非常重要的,因为您所做的一切并不独立于您正在监控的系统;你实际上是通过观察它来改变环境,而观察环境的一些方法可能会不恰当地改变它。

答案 7 :(得分:0)

CONFIG_FTRACECONFIG_KPROBESbrendangregg/perf-tools

git clone https://github.com/brendangregg/perf-tools.git
cd perf-tools
git checkout 98d42a2a1493d2d1c651a5c396e015d4f082eb20
sudo ./execsnoop

在另一个shell上:

while true; do sleep 1; date; done

第一个shell显示格式数据:

Tracing exec()s. Ctrl-C to end.                                                        
Instrumenting sys_execve                                                               
   PID   PPID ARGS 
 20109   4336 date                                                                                       
 20110   4336 sleep 1                                                                                    
 20111   4336 date                                                                                                                                                                                                 
 20112   4336 sleep 1                                                                                    
 20113   4336 date                                                                                       
 20114   4336 sleep 1                                                                                    
 20115   4336 date                                                                                       
 20116   4336 sleep 1