8

I am trying to create an application in userspace that sets affinity of processes. I would like the program to be triggered immediately every time a new pid/tid is spawned by the kernel. I am attempting to write to a file node under /proc from the do_fork() method in the kernel but I feel that it may have too much overhead.

Does anyone know any alternatives to detect a new process creation immediately after it is spawned?

If monitoring do_fork() is the way to go, would a call back to an userspace program via a system call be faster that using a fs node to communicate?

theNoobProgrammer
  • 924
  • 2
  • 15
  • 34

3 Answers3

15

Forkstat is a program that logs process fork() [among other things] Install it:

$ sudo apt-get install forkstat

Use it to log "fork" events:

$ forkstat -e fork
Romain DEQUIDT
  • 792
  • 8
  • 15
  • 5
    Why should the OP "try this"? A **good answer** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer. – Maximilian Ast Nov 10 '16 at 16:32
  • 8
    Thank you for your answer. `forkstat -d` helped to see process names. And OP should "try this" because it's a bloody solution to his (and my) problem. – user619271 Dec 01 '16 at 10:50
7

Use a socket with NETLINK_CONNECTOR. The kernel will tell you about process events, including fork()s and exec()s. You must have CONFIG_CONNECTOR and CONFIG_PROC_EVENTS enabled in your kernel.

Here's a related question with more details:

Detect launching of programs on Linux platform

For a complete socket NETLINK_CONNECTOR example, see:

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

As an aside, Inotify doesn't work. It will not work on /proc/ to detect new processes:

https://bugs.launchpad.net/ubuntu/+source/linux/+bug/454722

Community
  • 1
  • 1
  • I tried running the code in the second link and i receive a "socket: Protocol not supported" error. The code listed seems to be for a userspace application only. In order to properly monitor do_fork(), will I not need to add additional code into the do_fork() method? – theNoobProgrammer Nov 11 '14 at 02:38
1

execsnoop can be a good alternative to show new processes and arguments.

Romain DEQUIDT
  • 792
  • 8
  • 15