
Wie kann ich die Gesamtzahl der von einem Benutzer in Linux verwendeten Prozessoren ermitteln? Beispiel: Benutzer „X“ führt 2 (oder mehr) Prozesse aus, die insgesamt 3 Prozessoren verwenden. Wie kann ich das herausfinden? Wenn dies nicht möglich ist, wie kann ich dann herausfinden, wie viele Prozessoren ein Benutzer verwenden kann? Beispiel: Benutzer „X“ hat eine Sitzung mit 2 Prozessoren (von 8 möglichen) geöffnet.
Ich muss eine Perl-Funktion schreiben, die den Benutzernamen (z. B. „root“) abruft und einen Skalarwert zurückgibt – einen der folgenden Werte: 1. Gesamtzahl der vom Benutzer verwendeten Prozessoren (z. B. 2 von 8) 2. Gesamtzahl der vom Benutzer verwendeten Kerne 3. Für den Benutzer verfügbare Prozessoren. In meinem Fall führt der Benutzer einen (vielleicht mehr, aber nicht viel) großen Prozess aus, der einige Tage läuft, und ich möchte wissen, wie die Prozesse (eines speziellen Benutzers) die Maschine auslasten … Denn wenn er zu viele Ressourcen verwendet, muss ich ihn stoppen …
Antwort1
It is not possible to tell what cores a given program has used. The CPU assigns threads to cores invisibly and automatically based on a large number of factors, and performs a great deal of slight of hand to make it appear that everything is running synchronously, even if there is some time-slicing in how it assigns processing time to each thread.
what it comes down to, is that a session can't be mapped to a set of cores. you can map a session to the use of programs that run threads on one or more cores, but that's strictly as needed based on the current state of all processes.
its not like you assign 2 cores to sally, 2 cores to bob, and 4 cores to tom, causing you to 'run out' of them. sally's, Bob's, and Tom's programs can all use up to 8 cores, and the system will decide how to best assign the threads to a processing facility.
Antwort2
You can use sched_getaffinity and sched_setaffinity to look up on what core's a users process is allowed to run. However, that does not mean it will be running on all of them.
You can limit the cores a process can run on by starting it in a cpuset (a particular part of a cgroup)
e.g. See this guide on how to add a process to a cgroup in Red Hat 6 and this guide on how to effectively make a per-group (or thus, per user) division of cpu and memory.
If you are just interested in getting the cpu% a specific user is using you can use this oneliner:
top -b -n 1 -u <username> | awk 'NR>7 { sum += $9; } END { print sum; }'