summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGiampaolo Rodola <g.rodola@gmail.com>2015-08-26 01:56:49 -0700
committerGiampaolo Rodola <g.rodola@gmail.com>2015-08-26 01:56:49 -0700
commit3091db092c10b60a3f37ca228f274d66815f846a (patch)
tree6d7300c65f855abc085fb194c112f4741eb8a80f
parent1521790760c439b1cc370fb9ff65bceff24734fc (diff)
parentd8416fbe84b039564920fc896c3fb163b205091d (diff)
downloadpsutil-3091db092c10b60a3f37ca228f274d66815f846a.tar.gz
Merge branch 'master' into 655-windows-unicode
-rw-r--r--.ci/README3
-rw-r--r--.ci/appveyor/README (renamed from .appveyor/README)0
-rw-r--r--.ci/appveyor/install.ps1 (renamed from .appveyor/install.ps1)0
-rw-r--r--.ci/appveyor/run_with_compiler.cmd (renamed from .appveyor/run_with_compiler.cmd)0
-rw-r--r--.ci/travis/README2
-rwxr-xr-x.ci/travis/install.sh51
-rwxr-xr-x.ci/travis/run.sh18
-rw-r--r--.coveragerc1
-rw-r--r--.travis.yml47
-rw-r--r--CREDITS19
-rw-r--r--DEVGUIDE.rst13
-rw-r--r--HISTORY.rst14
-rw-r--r--MANIFEST.in3
-rw-r--r--README.rst12
-rw-r--r--appveyor.yml4
-rw-r--r--docs/index.rst29
-rwxr-xr-x[-rw-r--r--]examples/ifconfig.py2
-rwxr-xr-x[-rw-r--r--]examples/ps.py0
-rwxr-xr-x[-rw-r--r--]examples/pstree.py0
-rw-r--r--psutil/__init__.py30
-rw-r--r--psutil/_common.py2
-rw-r--r--psutil/_pslinux.py4
-rw-r--r--psutil/_psutil_bsd.c142
-rw-r--r--psutil/_psutil_linux.c57
-rw-r--r--psutil/_psutil_osx.c110
-rw-r--r--psutil/_psutil_posix.c53
-rw-r--r--psutil/_psutil_sunos.c63
-rw-r--r--psutil/_psutil_windows.c268
-rw-r--r--psutil/arch/bsd/process_info.c15
-rw-r--r--psutil/arch/osx/process_info.c18
-rw-r--r--psutil/arch/windows/inet_ntop.c19
-rw-r--r--psutil/arch/windows/ntextapi.h6
-rw-r--r--psutil/arch/windows/process_handles.c27
-rw-r--r--psutil/arch/windows/process_handles.h6
-rw-r--r--psutil/arch/windows/process_info.c21
-rw-r--r--psutil/arch/windows/security.c9
-rw-r--r--test/_bsd.py26
-rw-r--r--test/_linux.py14
-rw-r--r--test/_osx.py66
-rw-r--r--test/test_memory_leaks.py5
-rw-r--r--test/test_psutil.py126
41 files changed, 702 insertions, 603 deletions
diff --git a/.ci/README b/.ci/README
new file mode 100644
index 00000000..86b72afb
--- /dev/null
+++ b/.ci/README
@@ -0,0 +1,3 @@
+This directory contains support scripts for Travis and Appveyor continuous
+integration services.
+Travis is used to run tests on Linux and OSX, Appveyor runs tests on Windows.
diff --git a/.appveyor/README b/.ci/appveyor/README
index 2e092a07..2e092a07 100644
--- a/.appveyor/README
+++ b/.ci/appveyor/README
diff --git a/.appveyor/install.ps1 b/.ci/appveyor/install.ps1
index 3f056282..3f056282 100644
--- a/.appveyor/install.ps1
+++ b/.ci/appveyor/install.ps1
diff --git a/.appveyor/run_with_compiler.cmd b/.ci/appveyor/run_with_compiler.cmd
index 3a472bc8..3a472bc8 100644
--- a/.appveyor/run_with_compiler.cmd
+++ b/.ci/appveyor/run_with_compiler.cmd
diff --git a/.ci/travis/README b/.ci/travis/README
new file mode 100644
index 00000000..d9d5f65a
--- /dev/null
+++ b/.ci/travis/README
@@ -0,0 +1,2 @@
+This directory contains support files for Travis, a continuous integration
+service which runs tests on Linux and Windows on every push.
diff --git a/.ci/travis/install.sh b/.ci/travis/install.sh
new file mode 100755
index 00000000..23d9ce04
--- /dev/null
+++ b/.ci/travis/install.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+set -e
+set -x
+
+if [[ "$(uname -s)" == 'Darwin' ]]; then
+ brew update || brew update
+ brew outdated pyenv || brew upgrade pyenv
+ brew install pyenv-virtualenv
+
+ if which pyenv > /dev/null; then
+ eval "$(pyenv init -)"
+ fi
+
+ case "${PYVER}" in
+ py26)
+ pyenv install 2.6.9
+ pyenv virtualenv 2.6.9 psutil
+ ;;
+ py27)
+ pyenv install 2.7.10
+ pyenv virtualenv 2.7.10 psutil
+ ;;
+ py32)
+ pyenv install 3.2.6
+ pyenv virtualenv 3.2.6 psutil
+ ;;
+ py33)
+ pyenv install 3.3.6
+ pyenv virtualenv 3.3.6 psutil
+ ;;
+ py34)
+ pyenv install 3.4.3
+ pyenv virtualenv 3.4.3 psutil
+ ;;
+ esac
+ pyenv rehash
+ pyenv activate psutil
+fi
+
+if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]] || [[ $PYVER == 'py26' ]]; then
+ pip install -U ipaddress unittest2 mock==1.0.1
+elif [[ $TRAVIS_PYTHON_VERSION == '2.7' ]] || [[ $PYVER == 'py27' ]]; then
+ pip install -U ipaddress mock
+elif [[ $TRAVIS_PYTHON_VERSION == '3.2' ]] || [[ $PYVER == 'py32' ]]; then
+ pip install -U ipaddress mock
+elif [[ $TRAVIS_PYTHON_VERSION == '3.3' ]] || [[ $PYVER == 'py33' ]]; then
+ pip install -U ipaddress
+fi
+
+pip install coverage coveralls flake8 pep8 \ No newline at end of file
diff --git a/.ci/travis/run.sh b/.ci/travis/run.sh
new file mode 100755
index 00000000..41167aa8
--- /dev/null
+++ b/.ci/travis/run.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+set -e
+set -x
+
+if [[ "$(uname -s)" == 'Darwin' ]]; then
+ if which pyenv > /dev/null; then
+ eval "$(pyenv init -)"
+ fi
+ pyenv activate psutil
+fi
+
+python setup.py build
+python setup.py install
+coverage run test/test_psutil.py --include="psutil/*" --omit="test/*,*setup*"
+python test/test_memory_leaks.py
+flake8
+pep8
diff --git a/.coveragerc b/.coveragerc
index 918f1c5d..f023909b 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -12,6 +12,7 @@ exclude_lines =
pragma: no cover
if __name__ == .__main__.:
if sys.platform.startswith
+ if _WINDOWS:
import enum
if enum is not None:
if enum is None:
diff --git a/.travis.yml b/.travis.yml
index 2c549b21..d883c653 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,27 +1,30 @@
-language: python
sudo: false
-python:
- - 2.6
- - 2.7
- - 3.2
- - 3.3
- - 3.4
- # - pypy
+language: python
+matrix:
+ include:
+ - python: 2.6
+ - python: 2.7
+ - python: 3.2
+ - python: 3.3
+ - python: 3.4
+ - language: generic
+ os: osx
+ env: PYVER=py26
+ - language: generic
+ os: osx
+ env: PYVER=py27
+ - language: generic
+ os: osx
+ env: PYVER=py32
+ - language: generic
+ os: osx
+ env: PYVER=py33
+ - language: generic
+ os: osx
+ env: PYVER=py34
install:
- - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -U ipaddress unittest2 mock==1.0.1; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -U ipaddress mock; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -U ipaddress mock; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -U ipaddress; fi
- - pip install coverage coveralls flake8 pep8
+ - ./.ci/travis/install.sh
script:
- - python setup.py build
- - python setup.py install
- - coverage run test/test_psutil.py --include="psutil/*" --omit="test/*,*setup*"
- - python test/test_memory_leaks.py
- - flake8
- - pep8
-os:
- - linux
- - osx # currently not supported by travis
+ - ./.ci/travis/run.sh
after_success:
- coveralls # upload reports to coveralls.io
diff --git a/CREDITS b/CREDITS
index 170751b0..98adf16c 100644
--- a/CREDITS
+++ b/CREDITS
@@ -29,6 +29,10 @@ E: jloden@gmail.com
D: original co-author, initial design/bootstrap and occasional bug fixes
W: http://www.jayloden.com
+N: Jeff Tang
+W: https://github.com/mrjefftang
+I: 340, 529, 616, 653, 654, 648, 641
+
N: Jeremy Whitlock
E: jcscoobyrs@gmail.com
D: great help with OSX C development.
@@ -253,10 +257,6 @@ N: msabramo
E: msabramo@gmail.com
I: 492
-N: Jeff Tang
-W: https://github.com/mrjefftang
-I: 340, 529, 616, 653, 654
-
N: Yaolong Huang
E: airekans@gmail.com
W: http://airekans.github.io/
@@ -267,8 +267,9 @@ W: https://github.com/anders-chrigstrom
I: 496
N: spacewander
+W: https://github.com/spacewander
E: spacewanderlzx@gmail.com
-I: 561
+I: 561, 603
N: Sylvain Mouquet
E: sylvain.mouquet@gmail.com
@@ -308,3 +309,11 @@ N: Árni Már Jónsson
E: Reykjavik, Iceland
E: https://github.com/arnimarj
I: 634
+
+N: Bart van Kleef
+W: https://github.com/bkleef
+I: 664
+
+N: Steven Winfield
+W: https://github.com/stevenwinfield
+I: 672
diff --git a/DEVGUIDE.rst b/DEVGUIDE.rst
index d8df9434..cfbc1789 100644
--- a/DEVGUIDE.rst
+++ b/DEVGUIDE.rst
@@ -74,15 +74,18 @@ All of the services listed below are automatically run on ``git push``.
Tests
-----
-Tests are automatically run on push on Linux and Windows by using:
+Tests are automatically run for every GIT push on **Linux**, **OSX** and
+**Windows** by using:
-- `Travis <https://travis-ci.org/giampaolo/psutil>`_ (Linux)
+- `Travis <https://travis-ci.org/giampaolo/psutil>`_ (Linux, OSX)
- `Appveyor <https://ci.appveyor.com/project/giampaolo/psutil>`_ (Windows)
-Test files controlling these are `.travis.yml <https://github.com/giampaolo/psutil/blob/master/.travis.yml>`_
-and `appveyor.yml <https://github.com/giampaolo/psutil/blob/master/appveyor.yml>`_.
+Test files controlling these are
+`.travis.yml <https://github.com/giampaolo/psutil/blob/master/.travis.yml>`_
+and
+`appveyor.yml <https://github.com/giampaolo/psutil/blob/master/appveyor.yml>`_.
Both services run psutil test suite against all supported python version
-(2.6 - 3.5).
+(2.6 - 3.4).
Two icons in the home page (README) always show the build status:
.. image:: https://api.travis-ci.org/giampaolo/psutil.png?branch=master
diff --git a/HISTORY.rst b/HISTORY.rst
index d6e81e08..b4405f2b 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -3,9 +3,22 @@ Bug tracker at https://github.com/giampaolo/psutil/issues
3.1.2 - XXXX-XX-XX
==================
+**Enhancements**
+
+- #648: CI test integration for OSX. (patch by Jeff Tang)
+- #663: net_if_addrs() now returns point-to-point addresses (for VPNs).
+
**Bug fixes**
+- #513: [Linux] fixed integer overflow for RLIM_INFINITY.
+- #641: [Windows] fixed many compilation warnings. (patch by Jeff Tang)
- #659: [Linux] compilation error on Suse 10.
+- #664: [Linux] compilation error on Alpine Linux. (patch by Bart van Kleef)
+
+**Bug fixes**
+
+- #672: [Windows] compilation fails if using Windows SDK v8.0. (patch by
+ Steven Winfield)
3.1.1 - 2015-07-15
@@ -13,6 +26,7 @@ Bug tracker at https://github.com/giampaolo/psutil/issues
**Bug fixes**
+- #603: [Linux] ionice_set value range is incorrect. (patch by spacewander)
- #645: [Linux] psutil.cpu_times_percent() may produce negative results.
- #656: 'from psutil import *' does not work.
diff --git a/MANIFEST.in b/MANIFEST.in
index 175cf79f..a95f32f4 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,6 +2,7 @@ include .coveragerc
include .git-pre-commit
include .gitignore
include .travis.yml
+include appveyor.yml
include CREDITS
include HISTORY.rst
include INSTALL.rst
@@ -14,7 +15,7 @@ include setup.py
include TODO
include tox.ini
recursive-exclude docs/_build *
-recursive-include .appveyor/*
+recursive-include .ci/*
recursive-include docs *
recursive-include examples *.py
recursive-include psutil *.py *.c *.h
diff --git a/README.rst b/README.rst
index 56465614..3979924d 100644
--- a/README.rst
+++ b/README.rst
@@ -166,12 +166,12 @@ Network
...]
>>>
>>> psutil.net_if_addrs()
- {'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1'),
- snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None),
- snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00')],
- 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255'),
- snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None),
- snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff')]}
+ {'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
+ snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
+ snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
+ 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
+ snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
+ snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>>
>>> psutil.net_if_stats()
{'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
diff --git a/appveyor.yml b/appveyor.yml
index 752ec887..10080c79 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -4,7 +4,7 @@ environment:
# SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
# /E:ON and /V:ON options are not enabled in the batch script intepreter
# See: http://stackoverflow.com/a/13751649/163740
- WITH_COMPILER: "cmd /E:ON /V:ON /C .\\.appveyor\\run_with_compiler.cmd"
+ WITH_COMPILER: "cmd /E:ON /V:ON /C .\\.ci\\appveyor\\run_with_compiler.cmd"
matrix:
# Pre-installed Python versions, which Appveyor may upgrade to
@@ -48,7 +48,7 @@ init:
- "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
install:
- - "powershell .appveyor\\install.ps1"
+ - "powershell .ci\\appveyor\\install.ps1"
# - ps: (new-object net.webclient).DownloadFile('https://raw.github.com/pypa/pip/master/contrib/get-pip.py', 'C:/get-pip.py')
# - "%PYTHON%/python.exe C:/get-pip.py"
# - "%PYTHON%/python.exe -m pip install ..."
diff --git a/docs/index.rst b/docs/index.rst
index 44301922..4a2a5b94 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -410,28 +410,36 @@ Network
Return the addresses associated to each NIC (network interface card)
installed on the system as a dictionary whose keys are the NIC names and
value is a list of namedtuples for each address assigned to the NIC.
- Each namedtuple includes 4 fields:
+ Each namedtuple includes 5 fields:
- **family**
- **address**
- **netmask**
- **broadcast**
+ - **ptp**
*family* can be either
`AF_INET <http://docs.python.org//library/socket.html#socket.AF_INET>`__,
`AF_INET6 <http://docs.python.org//library/socket.html#socket.AF_INET6>`__
or :const:`psutil.AF_LINK`, which refers to a MAC address.
- *address* is the primary address, *netmask* and *broadcast* may be ``None``.
+ *address* is the primary address and it is always set.
+ *netmask*, *broadcast* and *ptp* may be ``None``.
+ *ptp* stands for "point to point" and references the destination address on a
+ point to point interface (tipically a VPN).
+ *broadcast* and *ptp* are mutually exclusive.
+ *netmask*, *broadcast* and *ptp* are not supported on Windows and are set to
+ ``None``.
+
Example::
>>> import psutil
>>> psutil.net_if_addrs()
- {'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1'),
- snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None),
- snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00')],
- 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255'),
- snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None),
- snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff')]}
+ {'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
+ snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
+ snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
+ 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
+ snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
+ snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>>
See also `examples/ifconfig.py <https://github.com/giampaolo/psutil/blob/master/examples/ifconfig.py>`__
@@ -444,8 +452,13 @@ Network
.. note:: you can have more than one address of the same family associated
with each interface (that's why dict values are lists).
+ .. note:: *netmask*, *broadcast* and *ptp* are not supported on Windows and
+ are set to ``None``.
+
*New in 3.0.0*
+ *Changed in 3.1.2:* *ptp* field was added.
+
.. function:: net_if_stats()
Return information about each NIC (network interface card) installed on the
diff --git a/examples/ifconfig.py b/examples/ifconfig.py
index e7a436cc..1f1ee985 100644..100755
--- a/examples/ifconfig.py
+++ b/examples/ifconfig.py
@@ -71,6 +71,8 @@ def main():
print(" broadcast : %s" % addr.broadcast)
if addr.netmask:
print(" netmask : %s" % addr.netmask)
+ if addr.ptp:
+ print(" p2p : %s" % addr.ptp)
print("")
diff --git a/examples/ps.py b/examples/ps.py
index 2b67bd18..2b67bd18 100644..100755
--- a/examples/ps.py
+++ b/examples/ps.py
diff --git a/examples/pstree.py b/examples/pstree.py
index 1bf8c9c0..1bf8c9c0 100644..100755
--- a/examples/pstree.py
+++ b/examples/pstree.py
diff --git a/psutil/__init__.py b/psutil/__init__.py
index 1444425b..385b80a4 100644
--- a/psutil/__init__.py
+++ b/psutil/__init__.py
@@ -158,7 +158,7 @@ __all__ = [
]
__all__.extend(_psplatform.__extra__all__)
__author__ = "Giampaolo Rodola'"
-__version__ = "3.1.1"
+__version__ = "3.1.2"
version_info = tuple([int(num) for num in __version__.split('.')])
AF_LINK = _psplatform.AF_LINK
_TOTAL_PHYMEM = None
@@ -486,8 +486,8 @@ class Process(object):
try:
# Checking if PID is alive is not enough as the PID might
# have been reused by another process: we also want to
- # check process identity.
- # Process identity / uniqueness over time is greanted by
+ # verify process identity.
+ # Process identity / uniqueness over time is guaranteed by
# (PID + creation time) and that is verified in __eq__.
return self == Process(self.pid)
except NoSuchProcess:
@@ -1023,7 +1023,7 @@ class Process(object):
if err.errno == errno.ESRCH:
self._gone = True
raise NoSuchProcess(self.pid, self._name)
- if err.errno == errno.EPERM:
+ if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
@@ -1248,7 +1248,10 @@ def process_iter():
# Process creation time can't be determined hence there's
# no way to tell whether the pid of the cached process
# has been reused. Just return the cached version.
- yield proc
+ if proc is None and pid in _pmap:
+ yield _pmap[pid]
+ else:
+ raise
def wait_procs(procs, timeout=None, callback=None):
@@ -1746,17 +1749,22 @@ def net_if_addrs():
"""Return the addresses associated to each NIC (network interface
card) installed on the system as a dictionary whose keys are the
NIC names and value is a list of namedtuples for each address
- assigned to the NIC. Each namedtuple includes 4 fields:
+ assigned to the NIC. Each namedtuple includes 5 fields:
- family
- address
- netmask
- broadcast
+ - ptp
'family' can be either socket.AF_INET, socket.AF_INET6 or
psutil.AF_LINK, which refers to a MAC address.
- 'address' is the primary address, 'netmask' and 'broadcast'
- may be None.
+ 'address' is the primary address and it is always set.
+ 'netmask' and 'broadcast' and 'ptp' may be None.
+ 'ptp' stands for "point to point" and references the destination
+ address on a point to point interface (tipically a VPN).
+ 'broadcast' and 'ptp' are mutually exclusive.
+
Note: you can have more than one address of the same family
associated with each interface.
"""
@@ -1766,7 +1774,7 @@ def net_if_addrs():
rawlist = _psplatform.net_if_addrs()
rawlist.sort(key=lambda x: x[1]) # sort by family
ret = collections.defaultdict(list)
- for name, fam, addr, mask, broadcast in rawlist:
+ for name, fam, addr, mask, broadcast, ptp in rawlist:
if has_enums:
try:
fam = socket.AddressFamily(fam)
@@ -1779,7 +1787,7 @@ def net_if_addrs():
# We re-set the family here so that repr(family)
# will show AF_LINK rather than AF_PACKET
fam = _psplatform.AF_LINK
- ret[name].append(_common.snic(fam, addr, mask, broadcast))
+ ret[name].append(_common.snic(fam, addr, mask, broadcast, ptp))
return dict(ret)
@@ -1823,7 +1831,7 @@ def users():
return _psplatform.users()
-def test():
+def test(): # pragma: no cover
"""List info of all currently running processes emulating ps aux
output.
"""
diff --git a/psutil/_common.py b/psutil/_common.py
index e9acf595..9f5c06f2 100644
--- a/psutil/_common.py
+++ b/psutil/_common.py
@@ -215,7 +215,7 @@ suser = namedtuple('suser', ['name', 'terminal', 'host', 'started'])
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
'status', 'pid'])
# psutil.net_if_addrs()
-snic = namedtuple('snic', ['family', 'address', 'netmask', 'broadcast'])
+snic = namedtuple('snic', ['family', 'address', 'netmask', 'broadcast', 'ptp'])
# psutil.net_if_stats()
snicstats = namedtuple('snicstats', ['isup', 'duplex', 'speed', 'mtu'])
diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py
index 7eb25f51..573944fc 100644
--- a/psutil/_pslinux.py
+++ b/psutil/_pslinux.py
@@ -1065,9 +1065,9 @@ class Process(object):
if not PY3 and not isinstance(value, (int, long)):
msg = "value argument is not an integer (gor %r)" % value
raise TypeError(msg)
- if not 0 <= value <= 8:
+ if not 0 <= value <= 7:
raise ValueError(
- "value argument range expected is between 0 and 8")
+ "value argument range expected is between 0 and 7")
if ioclass in (IOPRIO_CLASS_NONE, None):
if value:
diff --git a/psutil/_psutil_bsd.c b/psutil/_psutil_bsd.c
index 7b6e5617..402b9fe8 100644
--- a/psutil/_psutil_bsd.c
+++ b/psutil/_psutil_bsd.c
@@ -69,8 +69,7 @@
* Utility function which fills a kinfo_proc struct based on process pid
*/
static int
-psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc)
-{
+psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc) {
int mib[4];
size_t size;
mib[0] = CTL_KERN;
@@ -110,8 +109,7 @@ psutil_raise_ad_or_nsp(long pid) {
* Return a Python list of all the PIDs running on the system.
*/
static PyObject *
-psutil_pids(PyObject *self, PyObject *args)
-{
+psutil_pids(PyObject *self, PyObject *args) {
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
@@ -157,8 +155,7 @@ error:
* seconds since the epoch.
*/
static PyObject *
-psutil_boot_time(PyObject *self, PyObject *args)
-{
+psutil_boot_time(PyObject *self, PyObject *args) {
// fetch sysctl "kern.boottime"
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval boottime;
@@ -176,8 +173,7 @@ psutil_boot_time(PyObject *self, PyObject *args)
* Return process name from kinfo_proc as a Python string.
*/
static PyObject *
-psutil_proc_name(PyObject *self, PyObject *args)
-{
+psutil_proc_name(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -194,8 +190,7 @@ psutil_proc_name(PyObject *self, PyObject *args)
* http://fxr.googlebit.com/source/usr.bin/procstat/procstat_bin.c?v=8-CURRENT
*/
static PyObject *
-psutil_proc_exe(PyObject *self, PyObject *args)
-{
+psutil_proc_exe(PyObject *self, PyObject *args) {
long pid;
char pathname[PATH_MAX];
int error;
@@ -230,8 +225,7 @@ psutil_proc_exe(PyObject *self, PyObject *args)
* Return process cmdline as a Python list of cmdline arguments.
*/
static PyObject *
-psutil_proc_cmdline(PyObject *self, PyObject *args)
-{
+psutil_proc_cmdline(PyObject *self, PyObject *args) {
long pid;
PyObject *arglist = NULL;
@@ -253,8 +247,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args)
* Return process parent pid from kinfo_proc as a Python integer.
*/
static PyObject *
-psutil_proc_ppid(PyObject *self, PyObject *args)
-{
+psutil_proc_ppid(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -269,8 +262,7 @@ psutil_proc_ppid(PyObject *self, PyObject *args)
* Return process status as a Python integer.
*/
static PyObject *
-psutil_proc_status(PyObject *self, PyObject *args)
-{
+psutil_proc_status(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -286,8 +278,7 @@ psutil_proc_status(PyObject *self, PyObject *args)
* as a Python tuple.
*/
static PyObject *
-psutil_proc_uids(PyObject *self, PyObject *args)
-{
+psutil_proc_uids(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -306,8 +297,7 @@ psutil_proc_uids(PyObject *self, PyObject *args)
* as a Python tuple.
*/
static PyObject *
-psutil_proc_gids(PyObject *self, PyObject *args)
-{
+psutil_proc_gids(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -326,8 +316,7 @@ psutil_proc_gids(PyObject *self, PyObject *args)
* as a Python tuple.
*/
static PyObject *
-psutil_proc_tty_nr(PyObject *self, PyObject *args)
-{
+psutil_proc_tty_nr(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -342,8 +331,7 @@ psutil_proc_tty_nr(PyObject *self, PyObject *args)
* Return the number of context switches performed by process as a tuple.
*/
static PyObject *
-psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
-{
+psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -360,8 +348,7 @@ psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
* Return number of threads used by process as a Python integer.
*/
static PyObject *
-psutil_proc_num_threads(PyObject *self, PyObject *args)
-{
+psutil_proc_num_threads(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -380,8 +367,7 @@ psutil_proc_num_threads(PyObject *self, PyObject *args)
* procstat_threads.c?v=8-CURRENT
*/
static PyObject *
-psutil_proc_threads(PyObject *self, PyObject *args)
-{
+psutil_proc_threads(PyObject *self, PyObject *args) {
long pid;
int mib[4];
struct kinfo_proc *kip = NULL;
@@ -458,8 +444,7 @@ error:
* Return a Python tuple (user_time, kernel_time)
*/
static PyObject *
-psutil_proc_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_times(PyObject *self, PyObject *args) {
long pid;
double user_t, sys_t;
struct kinfo_proc kp;
@@ -479,8 +464,7 @@ psutil_proc_cpu_times(PyObject *self, PyObject *args)
* XXX this could be shared with OSX
*/
static PyObject *
-psutil_cpu_count_logical(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_logical(PyObject *self, PyObject *args) {
int mib[2];
int ncpu;
size_t len;
@@ -501,8 +485,7 @@ psutil_cpu_count_logical(PyObject *self, PyObject *args)
* physical CPU cores in the system.
*/
static PyObject *
-psutil_cpu_count_phys(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_phys(PyObject *self, PyObject *args) {
void *topology = NULL;
size_t size = 0;
PyObject *py_str;
@@ -535,8 +518,7 @@ error:
* seconds since the epoch.
*/
static PyObject *
-psutil_proc_create_time(PyObject *self, PyObject *args)
-{
+psutil_proc_create_time(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -552,8 +534,7 @@ psutil_proc_create_time(PyObject *self, PyObject *args)
* seconds since the epoch.
*/
static PyObject *
-psutil_proc_io_counters(PyObject *self, PyObject *args)
-{
+psutil_proc_io_counters(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -573,8 +554,7 @@ psutil_proc_io_counters(PyObject *self, PyObject *args)
* Return extended memory info for a process as a Python tuple.
*/
static PyObject *
-psutil_proc_memory_info(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_info(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -594,8 +574,7 @@ psutil_proc_memory_info(PyObject *self, PyObject *args)
* Return virtual memory usage statistics.
*/
static PyObject *
-psutil_virtual_mem(PyObject *self, PyObject *args)
-{
+psutil_virtual_mem(PyObject *self, PyObject *args) {
unsigned int total, active, inactive, wired, cached, free;
size_t size = sizeof(total);
struct vmtotal vm;
@@ -653,8 +632,7 @@ error:
* Return swap memory stats (see 'swapinfo' cmdline tool)
*/
static PyObject *
-psutil_swap_mem(PyObject *self, PyObject *args)
-{
+psutil_swap_mem(PyObject *self, PyObject *args) {
kvm_t *kd;
struct kvm_swap kvmsw[1];
unsigned int swapin, swapout, nodein, nodeout;
@@ -700,8 +678,7 @@ sbn_error:
* Return a Python tuple representing user, kernel and idle CPU times
*/
static PyObject *
-psutil_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_cpu_times(PyObject *self, PyObject *args) {
long cpu_time[CPUSTATES];
size_t size;
@@ -738,8 +715,7 @@ psutil_cpu_times(PyObject *self, PyObject *args)
* https://github.com/giampaolo/psutil/issues/595
*/
static PyObject *
-psutil_proc_open_files(PyObject *self, PyObject *args)
-{
+psutil_proc_open_files(PyObject *self, PyObject *args) {
long pid;
int i, cnt;
struct kinfo_file *freep = NULL;
@@ -790,8 +766,7 @@ error:
* Return files opened by process as a list of (path, fd) tuples
*/
static PyObject *
-psutil_proc_num_fds(PyObject *self, PyObject *args)
-{
+psutil_proc_num_fds(PyObject *self, PyObject *args) {
long pid;
int cnt;
@@ -818,8 +793,7 @@ psutil_proc_num_fds(PyObject *self, PyObject *args)
* Return process current working directory.
*/
static PyObject *
-psutil_proc_cwd(PyObject *self, PyObject *args)
-{
+psutil_proc_cwd(PyObject *self, PyObject *args) {
long pid;
PyObject *path = NULL;
struct kinfo_file *freep = NULL;
@@ -868,8 +842,7 @@ error:
// The tcplist fetching and walking is borrowed from netstat/inet.c.
static char *
-psutil_fetch_tcplist(void)
-{
+psutil_fetch_tcplist(void) {
char *buf;
size_t len;
@@ -893,8 +866,7 @@ psutil_fetch_tcplist(void)
}
static int
-psutil_sockaddr_port(int family, struct sockaddr_storage *ss)
-{
+psutil_sockaddr_port(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
@@ -909,8 +881,7 @@ psutil_sockaddr_port(int family, struct sockaddr_storage *ss)
}
static void *
-psutil_sockaddr_addr(int family, struct sockaddr_storage *ss)
-{
+psutil_sockaddr_addr(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
@@ -925,8 +896,7 @@ psutil_sockaddr_addr(int family, struct sockaddr_storage *ss)
}
static socklen_t
-psutil_sockaddr_addrlen(int family)
-{
+psutil_sockaddr_addrlen(int family) {
if (family == AF_INET)
return (sizeof(struct in_addr));
else
@@ -935,8 +905,7 @@ psutil_sockaddr_addrlen(int family)
static int
psutil_sockaddr_matches(int family, int port, void *pcb_addr,
- struct sockaddr_storage *ss)
-{
+ struct sockaddr_storage *ss) {
if (psutil_sockaddr_port(family, ss) != port)
return (0);
return (memcmp(psutil_sockaddr_addr(family, ss), pcb_addr,
@@ -944,8 +913,7 @@ psutil_sockaddr_matches(int family, int port, void *pcb_addr,
}
static struct tcpcb *
-psutil_search_tcplist(char *buf, struct kinfo_file *kif)
-{
+psutil_search_tcplist(char *buf, struct kinfo_file *kif) {
struct tcpcb *tp;
struct inpcb *inp;
struct xinpgen *xig, *oxig;
@@ -997,8 +965,7 @@ static int PSUTIL_CONN_NONE = 128;
* Return connections opened by process.
*/
static PyObject *
-psutil_proc_connections(PyObject *self, PyObject *args)
-{
+psutil_proc_connections(PyObject *self, PyObject *args) {
long pid;
int i, cnt;
@@ -1158,8 +1125,7 @@ error:
* Return a Python list of tuple representing per-cpu times
*/
static PyObject *
-psutil_per_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_per_cpu_times(PyObject *self, PyObject *args) {
static int maxcpus;
int mib[2];
int ncpu;
@@ -1237,8 +1203,7 @@ void remove_spaces(char *str) {
* 'procstat' cmdline utility has been used as an example.
*/
static PyObject *
-psutil_proc_memory_maps(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_maps(PyObject *self, PyObject *args) {
long pid;
int ptrwidth;
int i, cnt;
@@ -1349,8 +1314,7 @@ error:
* for all partitions mounted on the system.
*/
static PyObject *
-psutil_disk_partitions(PyObject *self, PyObject *args)
-{
+psutil_disk_partitions(PyObject *self, PyObject *args) {
int num;
int i;
long len;
@@ -1456,8 +1420,7 @@ error:
* Return a Python list of named tuples with overall network I/O information
*/
static PyObject *
-psutil_net_io_counters(PyObject *self, PyObject *args)
-{
+psutil_net_io_counters(PyObject *self, PyObject *args) {
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
@@ -1547,8 +1510,7 @@ error:
* Return a Python dict of tuples for disk I/O information
*/
static PyObject *
-psutil_disk_io_counters(PyObject *self, PyObject *args)
-{
+psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i;
struct statinfo stats;
@@ -1618,8 +1580,7 @@ error:
* Return currently connected users as a list of tuples.
*/
static PyObject *
-psutil_users(PyObject *self, PyObject *args)
-{
+psutil_users(PyObject *self, PyObject *args) {
PyObject *ret_list = PyList_New(0);
PyObject *tuple = NULL;
@@ -1703,8 +1664,7 @@ static struct xfile *psutil_xfiles;
static int psutil_nxfiles;
int
-psutil_populate_xfiles()
-{
+psutil_populate_xfiles() {
size_t len;
if ((psutil_xfiles = malloc(len = sizeof *psutil_xfiles)) == NULL) {
@@ -1731,8 +1691,7 @@ psutil_populate_xfiles()
}
int
-psutil_get_pid_from_sock(int sock_hash)
-{
+psutil_get_pid_from_sock(int sock_hash) {
struct xfile *xf;
int hash, n;
for (xf = psutil_xfiles, n = 0; n < psutil_nxfiles; ++n, ++xf) {
@@ -1749,8 +1708,7 @@ psutil_get_pid_from_sock(int sock_hash)
// Reference:
// https://gitorious.org/freebsd/freebsd/source/
// f1d6f4778d2044502209708bc167c05f9aa48615:usr.bin/sockstat/sockstat.c
-int psutil_gather_inet(int proto, PyObject *py_retlist)
-{
+int psutil_gather_inet(int proto, PyObject *py_retlist) {
struct xinpgen *xig, *exig;
struct xinpcb *xip;
struct xtcpcb *xtp;
@@ -1890,8 +1848,7 @@ error:
}
-int psutil_gather_unix(int proto, PyObject *py_retlist)
-{
+int psutil_gather_unix(int proto, PyObject *py_retlist) {
struct xunpgen *xug, *exug;
struct xunpcb *xup;
const char *varname = NULL;
@@ -1993,8 +1950,7 @@ error:
* Return system-wide open connections.
*/
static PyObject*
-psutil_net_connections(PyObject* self, PyObject* args)
-{
+psutil_net_connections(PyObject* self, PyObject* args) {
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
@@ -2025,8 +1981,7 @@ error:
* Reference: http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
*/
static PyObject*
-psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args)
-{
+psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args) {
long pid;
int ret;
int i;
@@ -2071,8 +2026,7 @@ error:
* Reference: http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
*/
static PyObject *
-psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
long pid;
int i;
int seq_len;
@@ -2125,8 +2079,8 @@ error:
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
+
// --- per-process functions
{"proc_name", psutil_proc_name, METH_VARARGS,
diff --git a/psutil/_psutil_linux.c b/psutil/_psutil_linux.c
index 7c10a0c4..697c81b0 100644
--- a/psutil/_psutil_linux.c
+++ b/psutil/_psutil_linux.c
@@ -59,14 +59,12 @@ enum {
#endif
static inline int
-ioprio_get(int which, int who)
-{
+ioprio_get(int which, int who) {
return syscall(__NR_ioprio_get, which, who);
}
static inline int
-ioprio_set(int which, int who, int ioprio)
-{
+ioprio_set(int which, int who, int ioprio) {
return syscall(__NR_ioprio_set, which, who, ioprio);
}
@@ -82,8 +80,7 @@ ioprio_set(int which, int who, int ioprio)
* Return a (ioclass, iodata) Python tuple representing process I/O priority.
*/
static PyObject *
-psutil_proc_ioprio_get(PyObject *self, PyObject *args)
-{
+psutil_proc_ioprio_get(PyObject *self, PyObject *args) {
long pid;
int ioprio, ioclass, iodata;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -103,8 +100,7 @@ psutil_proc_ioprio_get(PyObject *self, PyObject *args)
* or 0. iodata goes from 0 to 7 depending on ioclass specified.
*/
static PyObject *
-psutil_proc_ioprio_set(PyObject *self, PyObject *args)
-{
+psutil_proc_ioprio_set(PyObject *self, PyObject *args) {
long pid;
int ioprio, ioclass, iodata;
int retval;
@@ -127,8 +123,7 @@ psutil_proc_ioprio_set(PyObject *self, PyObject *args)
* 'soft' and 'hard' args must be provided.
*/
static PyObject *
-psutil_linux_prlimit(PyObject *self, PyObject *args)
-{
+psutil_linux_prlimit(PyObject *self, PyObject *args) {
long pid;
int ret, resource;
struct rlimit old, new;
@@ -186,8 +181,7 @@ psutil_linux_prlimit(PyObject *self, PyObject *args)
* mount point and filesystem type
*/
static PyObject *
-psutil_disk_partitions(PyObject *self, PyObject *args)
-{
+psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file = NULL;
struct mntent *entry;
PyObject *py_retlist = PyList_New(0);
@@ -237,8 +231,7 @@ error:
* A wrapper around sysinfo(), return system memory usage statistics.
*/
static PyObject *
-psutil_linux_sysinfo(PyObject *self, PyObject *args)
-{
+psutil_linux_sysinfo(PyObject *self, PyObject *args) {
struct sysinfo info;
if (sysinfo(&info) != 0)
@@ -264,8 +257,7 @@ psutil_linux_sysinfo(PyObject *self, PyObject *args)
#ifdef CPU_ALLOC
static PyObject *
-psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
int cpu, ncpus, count, cpucount_s;
long pid;
size_t setsize;
@@ -331,8 +323,7 @@ error:
* Alternative implementation in case CPU_ALLOC is not defined.
*/
static PyObject *
-psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
cpu_set_t cpuset;
unsigned int len = sizeof(cpu_set_t);
long pid;
@@ -373,8 +364,7 @@ error:
* Set process CPU affinity; expects a bitmask
*/
static PyObject *
-psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
cpu_set_t cpu_set;
size_t len;
long pid;
@@ -428,8 +418,7 @@ error:
* Return currently connected users as a list of tuples.
*/
static PyObject *
-psutil_users(PyObject *self, PyObject *args)
-{
+psutil_users(PyObject *self, PyObject *args) {
PyObject *ret_list = PyList_New(0);
PyObject *tuple = NULL;
PyObject *user_proc = NULL;
@@ -478,8 +467,7 @@ error:
* http://www.i-scream.org/libstatgrab/
*/
static PyObject*
-psutil_net_if_stats(PyObject* self, PyObject* args)
-{
+psutil_net_if_stats(PyObject* self, PyObject* args) {
char *nic_name;
int sock = 0;
int ret;
@@ -518,7 +506,7 @@ psutil_net_if_stats(PyObject* self, PyObject* args)
// duplex and speed
memset(&ethcmd, 0, sizeof ethcmd);
ethcmd.cmd = ETHTOOL_GSET;
- ifr.ifr_data = (caddr_t)&ethcmd;
+ ifr.ifr_data = (void *)&ethcmd;
ret = ioctl(sock, SIOCETHTOOL, &ifr);
if (ret != -1) {
@@ -556,8 +544,8 @@ error:
* Define the psutil C module methods and initialize the module.
*/
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
+
// --- per-process functions
#if PSUTIL_HAVE_IOPRIO
@@ -650,7 +638,6 @@ void init_psutil_linux(void)
PyModule_AddIntConstant(module, "version", PSUTIL_VERSION);
#if PSUTIL_HAVE_PRLIMIT
- PyModule_AddIntConstant(module, "RLIM_INFINITY", RLIM_INFINITY);
PyModule_AddIntConstant(module, "RLIMIT_AS", RLIMIT_AS);
PyModule_AddIntConstant(module, "RLIMIT_CORE", RLIMIT_CORE);
PyModule_AddIntConstant(module, "RLIMIT_CPU", RLIMIT_CPU);
@@ -662,6 +649,20 @@ void init_psutil_linux(void)
PyModule_AddIntConstant(module, "RLIMIT_NPROC", RLIMIT_NPROC);
PyModule_AddIntConstant(module, "RLIMIT_RSS", RLIMIT_RSS);
PyModule_AddIntConstant(module, "RLIMIT_STACK", RLIMIT_STACK);
+
+ PyObject *v;
+#if defined(HAVE_LONG_LONG)
+ if (sizeof(RLIM_INFINITY) > sizeof(long)) {
+ v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
+ } else
+#endif
+ {
+ v = PyLong_FromLong((long) RLIM_INFINITY);
+ }
+ if (v) {
+ PyModule_AddObject(module, "RLIM_INFINITY", v);
+ }
+
#ifdef RLIMIT_MSGQUEUE
PyModule_AddIntConstant(module, "RLIMIT_MSGQUEUE", RLIMIT_MSGQUEUE);
#endif
diff --git a/psutil/_psutil_osx.c b/psutil/_psutil_osx.c
index 3ebf8ff2..2b876e76 100644
--- a/psutil/_psutil_osx.c
+++ b/psutil/_psutil_osx.c
@@ -48,8 +48,7 @@
* A wrapper around host_statistics() invoked with HOST_VM_INFO.
*/
int
-psutil_sys_vminfo(vm_statistics_data_t *vmstat)
-{
+psutil_sys_vminfo(vm_statistics_data_t *vmstat) {
kern_return_t ret;
mach_msg_type_number_t count = sizeof(*vmstat) / sizeof(integer_t);
mach_port_t mport = mach_host_self();
@@ -69,8 +68,7 @@ psutil_sys_vminfo(vm_statistics_data_t *vmstat)
* Return a Python list of all the PIDs running on the system.
*/
static PyObject *
-psutil_pids(PyObject *self, PyObject *args)
-{
+psutil_pids(PyObject *self, PyObject *args) {
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
@@ -116,8 +114,7 @@ error:
* Return process name from kinfo_proc as a Python string.
*/
static PyObject *
-psutil_proc_name(PyObject *self, PyObject *args)
-{
+psutil_proc_name(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -132,8 +129,7 @@ psutil_proc_name(PyObject *self, PyObject *args)
* Return process current working directory.
*/
static PyObject *
-psutil_proc_cwd(PyObject *self, PyObject *args)
-{
+psutil_proc_cwd(PyObject *self, PyObject *args) {
long pid;
struct proc_vnodepathinfo pathinfo;
@@ -153,8 +149,7 @@ psutil_proc_cwd(PyObject *self, PyObject *args)
* Return path of the process executable.
*/
static PyObject *
-psutil_proc_exe(PyObject *self, PyObject *args)
-{
+psutil_proc_exe(PyObject *self, PyObject *args) {
long pid;
char buf[PATH_MAX];
int ret;
@@ -176,8 +171,7 @@ psutil_proc_exe(PyObject *self, PyObject *args)
* Return process cmdline as a Python list of cmdline arguments.
*/
static PyObject *
-psutil_proc_cmdline(PyObject *self, PyObject *args)
-{
+psutil_proc_cmdline(PyObject *self, PyObject *args) {
long pid;
PyObject *arglist = NULL;
@@ -194,8 +188,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args)
* Return process parent pid from kinfo_proc as a Python integer.
*/
static PyObject *
-psutil_proc_ppid(PyObject *self, PyObject *args)
-{
+psutil_proc_ppid(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -210,8 +203,7 @@ psutil_proc_ppid(PyObject *self, PyObject *args)
* Return process real uid from kinfo_proc as a Python integer.
*/
static PyObject *
-psutil_proc_uids(PyObject *self, PyObject *args)
-{
+psutil_proc_uids(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -229,8 +221,7 @@ psutil_proc_uids(PyObject *self, PyObject *args)
* Return process real group id from ki_comm as a Python integer.
*/
static PyObject *
-psutil_proc_gids(PyObject *self, PyObject *args)
-{
+psutil_proc_gids(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -248,8 +239,7 @@ psutil_proc_gids(PyObject *self, PyObject *args)
* Return process controlling terminal number as an integer.
*/
static PyObject *
-psutil_proc_tty_nr(PyObject *self, PyObject *args)
-{
+psutil_proc_tty_nr(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -265,8 +255,7 @@ psutil_proc_tty_nr(PyObject *self, PyObject *args)
* 'procstat' cmdline utility has been used as an example.
*/
static PyObject *
-psutil_proc_memory_maps(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_maps(PyObject *self, PyObject *args) {
char buf[PATH_MAX];
char addr_str[34];
char perms[8];
@@ -406,8 +395,8 @@ error:
* XXX this could be shared with BSD.
*/
static PyObject *
-psutil_cpu_count_logical(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_logical(PyObject *self, PyObject *args) {
+ /*
int mib[2];
int ncpu;
size_t len;
@@ -419,6 +408,14 @@ psutil_cpu_count_logical(PyObject *self, PyObject *args)
Py_RETURN_NONE; // mimic os.cpu_count()
else
return Py_BuildValue("i", ncpu);
+ */
+ int num;
+ size_t size = sizeof(int);
+
+ if (sysctlbyname("hw.logicalcpu", &num, &size, NULL, 2))
+ Py_RETURN_NONE; // mimic os.cpu_count()
+ else
+ return Py_BuildValue("i", num);
}
@@ -426,8 +423,7 @@ psutil_cpu_count_logical(PyObject *self, PyObject *args)
* Return the number of physical CPUs in the system.
*/
static PyObject *
-psutil_cpu_count_phys(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_phys(PyObject *self, PyObject *args) {
int num;
size_t size = sizeof(int);
@@ -444,8 +440,7 @@ psutil_cpu_count_phys(PyObject *self, PyObject *args)
* Return a Python tuple (user_time, kernel_time)
*/
static PyObject *
-psutil_proc_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_times(PyObject *self, PyObject *args) {
long pid;
struct proc_taskinfo pti;
@@ -464,8 +459,7 @@ psutil_proc_cpu_times(PyObject *self, PyObject *args)
* seconds since the epoch.
*/
static PyObject *
-psutil_proc_create_time(PyObject *self, PyObject *args)
-{
+psutil_proc_create_time(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -480,8 +474,7 @@ psutil_proc_create_time(PyObject *self, PyObject *args)
* Return extended memory info about a process.
*/
static PyObject *
-psutil_proc_memory_info(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_info(PyObject *self, PyObject *args) {
long pid;
struct proc_taskinfo pti;
@@ -508,8 +501,7 @@ psutil_proc_memory_info(PyObject *self, PyObject *args)
* Return number of threads used by process as a Python integer.
*/
static PyObject *
-psutil_proc_num_threads(PyObject *self, PyObject *args)
-{
+psutil_proc_num_threads(PyObject *self, PyObject *args) {
long pid;
struct proc_taskinfo pti;
@@ -525,8 +517,7 @@ psutil_proc_num_threads(PyObject *self, PyObject *args)
* Return the number of context switches performed by process.
*/
static PyObject *
-psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
-{
+psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) {
long pid;
struct proc_taskinfo pti;
@@ -545,8 +536,7 @@ psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
* Return system virtual memory stats
*/
static PyObject *
-psutil_virtual_mem(PyObject *self, PyObject *args)
-{
+psutil_virtual_mem(PyObject *self, PyObject *args) {
int mib[2];
uint64_t total;
@@ -557,6 +547,7 @@ psutil_virtual_mem(PyObject *self, PyObject *args)
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
+ // This is also available as sysctlbyname("hw.memsize").
if (sysctl(mib, 2, &total, &len, NULL, 0)) {
if (errno != 0)
PyErr_SetFromErrno(PyExc_OSError);
@@ -584,8 +575,7 @@ psutil_virtual_mem(PyObject *self, PyObject *args)
* Return stats about swap memory.
*/
static PyObject *
-psutil_swap_mem(PyObject *self, PyObject *args)
-{
+psutil_swap_mem(PyObject *self, PyObject *args) {
int mib[2];
size_t size;
struct xsw_usage totals;
@@ -619,8 +609,7 @@ psutil_swap_mem(PyObject *self, PyObject *args)
* Return a Python tuple representing user, kernel and idle CPU times
*/
static PyObject *
-psutil_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_cpu_times(PyObject *self, PyObject *args) {
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
kern_return_t error;
host_cpu_load_info_data_t r_load;
@@ -648,8 +637,7 @@ psutil_cpu_times(PyObject *self, PyObject *args)
* Return a Python list of tuple representing per-cpu times
*/
static PyObject *
-psutil_per_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_per_cpu_times(PyObject *self, PyObject *args) {
natural_t cpu_count;
processor_info_array_t info_array;
mach_msg_type_number_t info_count;
@@ -713,8 +701,7 @@ error:
* seconds since the epoch.
*/
static PyObject *
-psutil_boot_time(PyObject *self, PyObject *args)
-{
+psutil_boot_time(PyObject *self, PyObject *args) {
// fetch sysctl "kern.boottime"
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval result;
@@ -735,8 +722,7 @@ psutil_boot_time(PyObject *self, PyObject *args)
* for all partitions mounted on the system.
*/
static PyObject *
-psutil_disk_partitions(PyObject *self, PyObject *args)
-{
+psutil_disk_partitions(PyObject *self, PyObject *args) {
int num;
int i;
long len;
@@ -857,8 +843,7 @@ error:
* Return process status as a Python integer.
*/
static PyObject *
-psutil_proc_status(PyObject *self, PyObject *args)
-{
+psutil_proc_status(PyObject *self, PyObject *args) {
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
@@ -873,8 +858,7 @@ psutil_proc_status(PyObject *self, PyObject *args)
* Return process threads
*/
static PyObject *
-psutil_proc_threads(PyObject *self, PyObject *args)
-{
+psutil_proc_threads(PyObject *self, PyObject *args) {
long pid;
int err, j, ret;
kern_return_t kr;
@@ -984,8 +968,7 @@ error:
* - /usr/include/sys/proc_info.h
*/
static PyObject *
-psutil_proc_open_files(PyObject *self, PyObject *args)
-{
+psutil_proc_open_files(PyObject *self, PyObject *args) {
long pid;
int pidinfo_result;
int iterations;
@@ -1101,8 +1084,7 @@ static int PSUTIL_CONN_NONE = 128;
* - /usr/include/sys/proc_info.h
*/
static PyObject *
-psutil_proc_connections(PyObject *self, PyObject *args)
-{
+psutil_proc_connections(PyObject *self, PyObject *args) {
long pid;
int pidinfo_result;
int iterations;
@@ -1309,8 +1291,7 @@ error:
* Return number of file descriptors opened by process.
*/
static PyObject *
-psutil_proc_num_fds(PyObject *self, PyObject *args)
-{
+psutil_proc_num_fds(PyObject *self, PyObject *args) {
long pid;
int pidinfo_result;
int num;
@@ -1343,8 +1324,7 @@ psutil_proc_num_fds(PyObject *self, PyObject *args)
* Return a Python list of named tuples with overall network I/O information
*/
static PyObject *
-psutil_net_io_counters(PyObject *self, PyObject *args)
-{
+psutil_net_io_counters(PyObject *self, PyObject *args) {
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
@@ -1431,8 +1411,7 @@ error:
* Return a Python dict of tuples for disk I/O information
*/
static PyObject *
-psutil_disk_io_counters(PyObject *self, PyObject *args)
-{
+psutil_disk_io_counters(PyObject *self, PyObject *args) {
CFDictionaryRef parent_dict;
CFDictionaryRef props_dict;
CFDictionaryRef stats_dict;
@@ -1606,8 +1585,7 @@ error:
* Return currently connected users as a list of tuples.
*/
static PyObject *
-psutil_users(PyObject *self, PyObject *args)
-{
+psutil_users(PyObject *self, PyObject *args) {
struct utmpx *utx;
PyObject *ret_list = PyList_New(0);
PyObject *tuple = NULL;
@@ -1649,8 +1627,8 @@ error:
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
+
// --- per-process functions
{"proc_name", psutil_proc_name, METH_VARARGS,
diff --git a/psutil/_psutil_posix.c b/psutil/_psutil_posix.c
index 183dab0e..241b9d59 100644
--- a/psutil/_psutil_posix.c
+++ b/psutil/_psutil_posix.c
@@ -12,7 +12,9 @@
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/socket.h>
+#include <sys/ioctl.h>
#include <ifaddrs.h>
+#include <net/if.h>
#ifdef __linux
#include <netdb.h>
@@ -36,8 +38,7 @@
* Given a PID return process priority as a Python integer.
*/
static PyObject *
-psutil_posix_getpriority(PyObject *self, PyObject *args)
-{
+psutil_posix_getpriority(PyObject *self, PyObject *args) {
long pid;
int priority;
errno = 0;
@@ -55,8 +56,7 @@ psutil_posix_getpriority(PyObject *self, PyObject *args)
* Given a PID and a value change process priority.
*/
static PyObject *
-psutil_posix_setpriority(PyObject *self, PyObject *args)
-{
+psutil_posix_setpriority(PyObject *self, PyObject *args) {
long pid;
int priority;
int retval;
@@ -75,8 +75,7 @@ psutil_posix_setpriority(PyObject *self, PyObject *args)
* Return None if address family is not AF_INET* or AF_PACKET.
*/
static PyObject *
-psutil_convert_ipaddr(struct sockaddr *addr, int family)
-{
+psutil_convert_ipaddr(struct sockaddr *addr, int family) {
char buf[NI_MAXHOST];
int err;
int addrlen;
@@ -153,8 +152,7 @@ psutil_convert_ipaddr(struct sockaddr *addr, int family)
* TODO: on Solaris we won't get any MAC address.
*/
static PyObject*
-psutil_net_if_addrs(PyObject* self, PyObject* args)
-{
+psutil_net_if_addrs(PyObject* self, PyObject* args) {
struct ifaddrs *ifaddr, *ifa;
int family;
@@ -163,6 +161,7 @@ psutil_net_if_addrs(PyObject* self, PyObject* args)
PyObject *py_address = NULL;
PyObject *py_netmask = NULL;
PyObject *py_broadcast = NULL;
+ PyObject *py_ptp = NULL;
if (py_retlist == NULL)
return NULL;
@@ -185,20 +184,34 @@ psutil_net_if_addrs(PyObject* self, PyObject* args)
py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family);
if (py_netmask == NULL)
goto error;
-#ifdef __linux
- py_broadcast = psutil_convert_ipaddr(ifa->ifa_ifu.ifu_broadaddr, family);
-#else
- py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family);
-#endif
- if (py_broadcast == NULL)
+
+ if (ifa->ifa_flags & IFF_BROADCAST) {
+ py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family);
+ Py_INCREF(Py_None);
+ py_ptp = Py_None;
+ }
+ else if (ifa->ifa_flags & IFF_POINTOPOINT) {
+ py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family);
+ Py_INCREF(Py_None);
+ py_broadcast = Py_None;
+ }
+ else {
+ Py_INCREF(Py_None);
+ Py_INCREF(Py_None);
+ py_broadcast = Py_None;
+ py_ptp = Py_None;
+ }
+
+ if ((py_broadcast == NULL) || (py_ptp == NULL))
goto error;
py_tuple = Py_BuildValue(
- "(siOOO)",
+ "(siOOOO)",
ifa->ifa_name,
family,
py_address,
py_netmask,
- py_broadcast
+ py_broadcast,
+ py_ptp
);
if (! py_tuple)
@@ -209,6 +222,7 @@ psutil_net_if_addrs(PyObject* self, PyObject* args)
Py_DECREF(py_address);
Py_DECREF(py_netmask);
Py_DECREF(py_broadcast);
+ Py_DECREF(py_ptp);
}
freeifaddrs(ifaddr);
@@ -222,6 +236,7 @@ error:
Py_XDECREF(py_address);
Py_XDECREF(py_netmask);
Py_XDECREF(py_broadcast);
+ Py_XDECREF(py_ptp);
return NULL;
}
@@ -378,8 +393,7 @@ int psutil_get_nic_speed(int ifm_active) {
* http://www.i-scream.org/libstatgrab/
*/
static PyObject *
-psutil_net_if_stats(PyObject *self, PyObject *args)
-{
+psutil_net_if_stats(PyObject *self, PyObject *args) {
char *nic_name;
int sock = 0;
int ret;
@@ -452,8 +466,7 @@ error:
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
{"getpriority", psutil_posix_getpriority, METH_VARARGS,
"Return process priority"},
{"setpriority", psutil_posix_setpriority, METH_VARARGS,
diff --git a/psutil/_psutil_sunos.c b/psutil/_psutil_sunos.c
index 0cb6978f..e98d90c4 100644
--- a/psutil/_psutil_sunos.c
+++ b/psutil/_psutil_sunos.c
@@ -51,8 +51,7 @@
* Read a file content and fills a C structure with it.
*/
int
-psutil_file_to_struct(char *path, void *fstruct, size_t size)
-{
+psutil_file_to_struct(char *path, void *fstruct, size_t size) {
int fd;
size_t nbytes;
fd = open(path, O_RDONLY);
@@ -81,8 +80,7 @@ psutil_file_to_struct(char *path, void *fstruct, size_t size)
* as a Python tuple.
*/
static PyObject *
-psutil_proc_basic_info(PyObject *self, PyObject *args)
-{
+psutil_proc_basic_info(PyObject *self, PyObject *args) {
int pid;
char path[100];
psinfo_t info;
@@ -109,8 +107,7 @@ psutil_proc_basic_info(PyObject *self, PyObject *args)
* Return process name and args as a Python tuple.
*/
static PyObject *
-psutil_proc_name_and_args(PyObject *self, PyObject *args)
-{
+psutil_proc_name_and_args(PyObject *self, PyObject *args) {
int pid;
char path[100];
psinfo_t info;
@@ -128,8 +125,7 @@ psutil_proc_name_and_args(PyObject *self, PyObject *args)
* Return process user and system CPU times as a Python tuple.
*/
static PyObject *
-psutil_proc_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_times(PyObject *self, PyObject *args) {
int pid;
char path[100];
pstatus_t info;
@@ -150,8 +146,7 @@ psutil_proc_cpu_times(PyObject *self, PyObject *args)
* Return process uids/gids as a Python tuple.
*/
static PyObject *
-psutil_proc_cred(PyObject *self, PyObject *args)
-{
+psutil_proc_cred(PyObject *self, PyObject *args) {
int pid;
char path[100];
prcred_t info;
@@ -171,8 +166,7 @@ psutil_proc_cred(PyObject *self, PyObject *args)
* Return process uids/gids as a Python tuple.
*/
static PyObject *
-psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
-{
+psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) {
int pid;
char path[100];
prusage_t info;
@@ -198,8 +192,7 @@ psutil_proc_num_ctx_switches(PyObject *self, PyObject *args)
* ...they should be meaningless anyway.
*
static PyObject*
-proc_io_counters(PyObject* self, PyObject* args)
-{
+proc_io_counters(PyObject* self, PyObject* args) {
int pid;
char path[100];
prusage_t info;
@@ -228,8 +221,7 @@ proc_io_counters(PyObject* self, PyObject* args)
* Return information about a given process thread.
*/
static PyObject *
-psutil_proc_query_thread(PyObject *self, PyObject *args)
-{
+psutil_proc_query_thread(PyObject *self, PyObject *args) {
int pid, tid;
char path[100];
lwpstatus_t info;
@@ -249,8 +241,7 @@ psutil_proc_query_thread(PyObject *self, PyObject *args)
* Return information about system virtual memory.
*/
static PyObject *
-psutil_swap_mem(PyObject *self, PyObject *args)
-{
+psutil_swap_mem(PyObject *self, PyObject *args) {
// XXX (arghhh!)
// total/free swap mem: commented out as for some reason I can't
// manage to get the same results shown by "swap -l", despite the
@@ -345,8 +336,7 @@ psutil_swap_mem(PyObject *self, PyObject *args)
* Return users currently connected on the system.
*/
static PyObject *
-psutil_users(PyObject *self, PyObject *args)
-{
+psutil_users(PyObject *self, PyObject *args) {
struct utmpx *ut;
PyObject *ret_list = PyList_New(0);
PyObject *tuple = NULL;
@@ -391,8 +381,7 @@ error:
* mount point and filesystem type.
*/
static PyObject *
-psutil_disk_partitions(PyObject *self, PyObject *args)
-{
+psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file;
struct mnttab mt;
PyObject *py_retlist = PyList_New(0);
@@ -437,8 +426,7 @@ error:
* Return system-wide CPU times.
*/
static PyObject *
-psutil_per_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_per_cpu_times(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
cpu_stat_t cs;
@@ -490,8 +478,7 @@ error:
* Return disk IO statistics.
*/
static PyObject *
-psutil_disk_io_counters(PyObject *self, PyObject *args)
-{
+psutil_disk_io_counters(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
kstat_io_t kio;
@@ -549,8 +536,7 @@ error:
* Return process memory mappings.
*/
static PyObject *
-psutil_proc_memory_maps(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_maps(PyObject *self, PyObject *args) {
int pid;
int fd = -1;
char path[100];
@@ -684,8 +670,7 @@ error:
* Return a list of tuples for network I/O statistics.
*/
static PyObject *
-psutil_net_io_counters(PyObject *self, PyObject *args)
-{
+psutil_net_io_counters(PyObject *self, PyObject *args) {
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
@@ -796,8 +781,7 @@ static int PSUTIL_CONN_NONE = 128;
* cmd-inet/usr.bin/netstat/netstat.c
*/
static PyObject *
-psutil_net_connections(PyObject *self, PyObject *args)
-{
+psutil_net_connections(PyObject *self, PyObject *args) {
long pid;
int sd = 0;
mib2_tcpConnEntry_t *tp = NULL;
@@ -1082,8 +1066,7 @@ error:
static PyObject *
-psutil_boot_time(PyObject *self, PyObject *args)
-{
+psutil_boot_time(PyObject *self, PyObject *args) {
float boot_time = 0.0;
struct utmpx *ut;
@@ -1108,8 +1091,7 @@ psutil_boot_time(PyObject *self, PyObject *args)
* Return the number of physical CPU cores on the system.
*/
static PyObject *
-psutil_cpu_count_phys(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_phys(PyObject *self, PyObject *args) {
kstat_ctl_t *kc;
kstat_t *ksp;
int ncpus = 0;
@@ -1150,8 +1132,7 @@ error:
* http://www.i-scream.org/libstatgrab/
*/
static PyObject*
-psutil_net_if_stats(PyObject* self, PyObject* args)
-{
+psutil_net_if_stats(PyObject* self, PyObject* args) {
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *knp;
@@ -1257,8 +1238,8 @@ error:
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
+
// --- process-related functions
{"proc_basic_info", psutil_proc_basic_info, METH_VARARGS,
"Return process ppid, rss, vms, ctime, nice, nthreads, status and tty"},
@@ -1297,7 +1278,7 @@ PsutilMethods[] =
{"net_if_stats", psutil_net_if_stats, METH_VARARGS,
"Return NIC stats (isup, duplex, speed, mtu)"},
-{NULL, NULL, 0, NULL}
+ {NULL, NULL, 0, NULL}
};
diff --git a/psutil/_psutil_windows.c b/psutil/_psutil_windows.c
index 3e0f7a7c..d3faf50e 100644
--- a/psutil/_psutil_windows.c
+++ b/psutil/_psutil_windows.c
@@ -138,7 +138,6 @@ typedef struct _MIB_UDP6TABLE_OWNER_PID {
MIB_UDP6ROW_OWNER_PID table[ANY_SIZE];
} MIB_UDP6TABLE_OWNER_PID, *PMIB_UDP6TABLE_OWNER_PID;
-
PIP_ADAPTER_ADDRESSES
psutil_get_nic_addresses() {
// allocate a 15 KB buffer to start with
@@ -188,8 +187,7 @@ psutil_get_nic_addresses() {
* since the epoch.
*/
static PyObject *
-psutil_boot_time(PyObject *self, PyObject *args)
-{
+psutil_boot_time(PyObject *self, PyObject *args) {
double uptime;
time_t pt;
FILETIME fileTime;
@@ -225,8 +223,7 @@ psutil_boot_time(PyObject *self, PyObject *args)
* Return 1 if PID exists in the current process list, else 0.
*/
static PyObject *
-psutil_pid_exists(PyObject *self, PyObject *args)
-{
+psutil_pid_exists(PyObject *self, PyObject *args) {
long pid;
int status;
@@ -244,8 +241,7 @@ psutil_pid_exists(PyObject *self, PyObject *args)
* Return a Python list of all the PIDs running on the system.
*/
static PyObject *
-psutil_pids(PyObject *self, PyObject *args)
-{
+psutil_pids(PyObject *self, PyObject *args) {
DWORD *proclist = NULL;
DWORD numberOfReturnedPIDs;
DWORD i;
@@ -284,8 +280,7 @@ error:
* Kill a process given its PID.
*/
static PyObject *
-psutil_proc_kill(PyObject *self, PyObject *args)
-{
+psutil_proc_kill(PyObject *self, PyObject *args) {
HANDLE hProcess;
long pid;
@@ -322,8 +317,7 @@ psutil_proc_kill(PyObject *self, PyObject *args)
* Wait for process to terminate and return its exit code.
*/
static PyObject *
-psutil_proc_wait(PyObject *self, PyObject *args)
-{
+psutil_proc_wait(PyObject *self, PyObject *args) {
HANDLE hProcess;
DWORD ExitCode;
DWORD retVal;
@@ -382,8 +376,7 @@ psutil_proc_wait(PyObject *self, PyObject *args)
* Return a Python tuple (user_time, kernel_time)
*/
static PyObject *
-psutil_proc_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_times(PyObject *self, PyObject *args) {
long pid;
HANDLE hProcess;
FILETIME ftCreate, ftExit, ftKernel, ftUser;
@@ -433,8 +426,7 @@ psutil_proc_cpu_times(PyObject *self, PyObject *args)
* seconds since the epoch.
*/
static PyObject *
-psutil_proc_create_time(PyObject *self, PyObject *args)
-{
+psutil_proc_create_time(PyObject *self, PyObject *args) {
long pid;
long long unix_time;
DWORD exitCode;
@@ -502,8 +494,7 @@ psutil_proc_create_time(PyObject *self, PyObject *args)
* Return the number of logical CPUs.
*/
static PyObject *
-psutil_cpu_count_logical(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_logical(PyObject *self, PyObject *args) {
SYSTEM_INFO system_info;
system_info.dwNumberOfProcessors = 0;
@@ -519,8 +510,7 @@ psutil_cpu_count_logical(PyObject *self, PyObject *args)
* Return the number of physical CPU cores.
*/
static PyObject *
-psutil_cpu_count_phys(PyObject *self, PyObject *args)
-{
+psutil_cpu_count_phys(PyObject *self, PyObject *args) {
LPFN_GLPI glpi;
DWORD rc;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
@@ -683,8 +673,7 @@ psutil_proc_name(PyObject *self, PyObject *args) {
* Return process memory information as a Python tuple.
*/
static PyObject *
-psutil_proc_memory_info(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_info(PyObject *self, PyObject *args) {
HANDLE hProcess;
DWORD pid;
#if (_WIN32_WINNT >= 0x0501) // Windows XP with SP2
@@ -751,8 +740,7 @@ psutil_proc_memory_info(PyObject *self, PyObject *args)
* Alternative implementation of the one above but bypasses ACCESS DENIED.
*/
static PyObject *
-psutil_proc_memory_info_2(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_info_2(PyObject *self, PyObject *args) {
DWORD pid;
PSYSTEM_PROCESS_INFORMATION process;
PVOID buffer;
@@ -806,8 +794,7 @@ psutil_proc_memory_info_2(PyObject *self, PyObject *args)
* in bytes.
*/
static PyObject *
-psutil_virtual_mem(PyObject *self, PyObject *args)
-{
+psutil_virtual_mem(PyObject *self, PyObject *args) {
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
@@ -829,8 +816,7 @@ psutil_virtual_mem(PyObject *self, PyObject *args)
* sum of the designated times across all processors.
*/
static PyObject *
-psutil_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_cpu_times(PyObject *self, PyObject *args) {
float idle, kernel, user, system;
FILETIME idle_time, kernel_time, user_time;
@@ -856,8 +842,7 @@ psutil_cpu_times(PyObject *self, PyObject *args)
* Same as above but for all system CPUs.
*/
static PyObject *
-psutil_per_cpu_times(PyObject *self, PyObject *args)
-{
+psutil_per_cpu_times(PyObject *self, PyObject *args) {
float idle, kernel, user;
typedef DWORD (_stdcall * NTQSI_PROC) (int, PVOID, ULONG, PULONG);
NTQSI_PROC NtQuerySystemInformation;
@@ -878,8 +863,7 @@ psutil_per_cpu_times(PyObject *self, PyObject *args)
NtQuerySystemInformation = (NTQSI_PROC)GetProcAddress(
hNtDll, "NtQuerySystemInformation");
- if (NtQuerySystemInformation != NULL)
- {
+ if (NtQuerySystemInformation != NULL) {
// retrives number of processors
GetSystemInfo(&si);
@@ -888,8 +872,7 @@ psutil_per_cpu_times(PyObject *self, PyObject *args)
sppi = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \
malloc(si.dwNumberOfProcessors * \
sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION));
- if (sppi != NULL)
- {
+ if (sppi != NULL) {
// gets cpu time informations
if (0 == NtQuerySystemInformation(
SystemProcessorPerformanceInformation,
@@ -950,8 +933,7 @@ error:
*/
static PyObject *
-psutil_proc_cwd(PyObject *self, PyObject *args)
-{
+psutil_proc_cwd(PyObject *self, PyObject *args) {
long pid;
HANDLE processHandle = NULL;
PVOID pebAddress;
@@ -1083,8 +1065,7 @@ error:
* Resume or suspends a process
*/
int
-psutil_proc_suspend_or_resume(DWORD pid, int suspend)
-{
+psutil_proc_suspend_or_resume(DWORD pid, int suspend) {
// a huge thanks to http://www.codeproject.com/KB/threads/pausep.aspx
HANDLE hThreadSnap = NULL;
THREADENTRY32 te32 = {0};
@@ -1152,8 +1133,7 @@ psutil_proc_suspend_or_resume(DWORD pid, int suspend)
static PyObject *
-psutil_proc_suspend(PyObject *self, PyObject *args)
-{
+psutil_proc_suspend(PyObject *self, PyObject *args) {
long pid;
int suspend = 1;
@@ -1166,8 +1146,7 @@ psutil_proc_suspend(PyObject *self, PyObject *args)
static PyObject *
-psutil_proc_resume(PyObject *self, PyObject *args)
-{
+psutil_proc_resume(PyObject *self, PyObject *args) {
long pid;
int suspend = 0;
@@ -1180,8 +1159,7 @@ psutil_proc_resume(PyObject *self, PyObject *args)
static PyObject *
-psutil_proc_threads(PyObject *self, PyObject *args)
-{
+psutil_proc_threads(PyObject *self, PyObject *args) {
HANDLE hThread;
THREADENTRY32 te32 = {0};
long pid;
@@ -1286,8 +1264,7 @@ error:
static PyObject *
-psutil_proc_open_files(PyObject *self, PyObject *args)
-{
+psutil_proc_open_files(PyObject *self, PyObject *args) {
long pid;
HANDLE processHandle;
DWORD access = PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION;
@@ -1313,8 +1290,7 @@ psutil_proc_open_files(PyObject *self, PyObject *args)
If no match is found return an empty string.
*/
static PyObject *
-psutil_win32_QueryDosDevice(PyObject *self, PyObject *args)
-{
+psutil_win32_QueryDosDevice(PyObject *self, PyObject *args) {
LPCTSTR lpDevicePath;
TCHAR d = TEXT('A');
TCHAR szBuff[5];
@@ -1341,8 +1317,7 @@ psutil_win32_QueryDosDevice(PyObject *self, PyObject *args)
* Return process username as a "DOMAIN//USERNAME" string.
*/
static PyObject *
-psutil_proc_username(PyObject *self, PyObject *args)
-{
+psutil_proc_username(PyObject *self, PyObject *args) {
long pid;
HANDLE processHandle;
HANDLE tokenHandle;
@@ -1463,8 +1438,7 @@ psutil_proc_username(PyObject *self, PyObject *args)
* Return a list of network connections opened by a process
*/
static PyObject *
-psutil_net_connections(PyObject *self, PyObject *args)
-{
+psutil_net_connections(PyObject *self, PyObject *args) {
static long null_address[4] = { 0, 0, 0, 0 };
unsigned long pid;
@@ -1690,8 +1664,7 @@ psutil_net_connections(PyObject *self, PyObject *args)
addressBufferLocal,
BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort));
}
- else
- {
+ else {
addressTupleLocal = PyTuple_New(0);
}
@@ -1714,8 +1687,7 @@ psutil_net_connections(PyObject *self, PyObject *args)
addressBufferRemote,
BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort));
}
- else
- {
+ else {
addressTupleRemote = PyTuple_New(0);
}
@@ -1837,8 +1809,7 @@ psutil_net_connections(PyObject *self, PyObject *args)
{
udp6Table = table;
- for (i = 0; i < udp6Table->dwNumEntries; i++)
- {
+ for (i = 0; i < udp6Table->dwNumEntries; i++) {
if (pid != -1) {
if (udp6Table->table[i].dwOwningPid != pid) {
continue;
@@ -1903,8 +1874,7 @@ error:
* Get process priority as a Python integer.
*/
static PyObject *
-psutil_proc_priority_get(PyObject *self, PyObject *args)
-{
+psutil_proc_priority_get(PyObject *self, PyObject *args) {
long pid;
DWORD priority;
HANDLE hProcess;
@@ -1930,8 +1900,7 @@ psutil_proc_priority_get(PyObject *self, PyObject *args)
* Set process priority.
*/
static PyObject *
-psutil_proc_priority_set(PyObject *self, PyObject *args)
-{
+psutil_proc_priority_set(PyObject *self, PyObject *args) {
long pid;
int priority;
int retval;
@@ -1962,8 +1931,7 @@ psutil_proc_priority_set(PyObject *self, PyObject *args)
* Get process IO priority as a Python integer.
*/
static PyObject *
-psutil_proc_io_priority_get(PyObject *self, PyObject *args)
-{
+psutil_proc_io_priority_get(PyObject *self, PyObject *args) {
long pid;
HANDLE hProcess;
PULONG IoPriority;
@@ -1975,9 +1943,8 @@ psutil_proc_io_priority_get(PyObject *self, PyObject *args)
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
hProcess = psutil_handle_from_pid(pid);
- if (hProcess == NULL) {
+ if (hProcess == NULL)
return NULL;
- }
NtQueryInformationProcess(
hProcess,
@@ -1995,8 +1962,7 @@ psutil_proc_io_priority_get(PyObject *self, PyObject *args)
* Set process IO priority.
*/
static PyObject *
-psutil_proc_io_priority_set(PyObject *self, PyObject *args)
-{
+psutil_proc_io_priority_set(PyObject *self, PyObject *args) {
long pid;
int prio;
HANDLE hProcess;
@@ -2011,13 +1977,11 @@ psutil_proc_io_priority_set(PyObject *self, PyObject *args)
return NULL;
}
- if (! PyArg_ParseTuple(args, "li", &pid, &prio)) {
+ if (! PyArg_ParseTuple(args, "li", &pid, &prio))
return NULL;
- }
hProcess = psutil_handle_from_pid_waccess(pid, PROCESS_ALL_ACCESS);
- if (hProcess == NULL) {
+ if (hProcess == NULL)
return NULL;
- }
NtSetInformationProcess(
hProcess,
@@ -2036,8 +2000,7 @@ psutil_proc_io_priority_set(PyObject *self, PyObject *args)
* Return a Python tuple referencing process I/O counters.
*/
static PyObject *
-psutil_proc_io_counters(PyObject *self, PyObject *args)
-{
+psutil_proc_io_counters(PyObject *self, PyObject *args) {
DWORD pid;
HANDLE hProcess;
IO_COUNTERS IoCounters;
@@ -2045,9 +2008,8 @@ psutil_proc_io_counters(PyObject *self, PyObject *args)
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
hProcess = psutil_handle_from_pid(pid);
- if (NULL == hProcess) {
+ if (NULL == hProcess)
return NULL;
- }
if (! GetProcessIoCounters(hProcess, &IoCounters)) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
@@ -2065,8 +2027,7 @@ psutil_proc_io_counters(PyObject *self, PyObject *args)
* Return process CPU affinity as a bitmask
*/
static PyObject *
-psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
DWORD pid;
HANDLE hProcess;
DWORD_PTR proc_mask;
@@ -2096,8 +2057,7 @@ psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args)
* Set process CPU affinity
*/
static PyObject *
-psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args)
-{
+psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
DWORD pid;
HANDLE hProcess;
DWORD dwDesiredAccess = \
@@ -2113,9 +2073,8 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args)
return NULL;
}
hProcess = psutil_handle_from_pid_waccess(pid, dwDesiredAccess);
- if (hProcess == NULL) {
+ if (hProcess == NULL)
return NULL;
- }
if (SetProcessAffinityMask(hProcess, mask) == 0) {
CloseHandle(hProcess);
@@ -2132,8 +2091,7 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args)
* suspended status.
*/
static PyObject *
-psutil_proc_is_suspended(PyObject *self, PyObject *args)
-{
+psutil_proc_is_suspended(PyObject *self, PyObject *args) {
DWORD pid;
ULONG i;
PSYSTEM_PROCESS_INFORMATION process;
@@ -2161,8 +2119,7 @@ psutil_proc_is_suspended(PyObject *self, PyObject *args)
* Return path's disk total and free as a Python tuple.
*/
static PyObject *
-psutil_disk_usage(PyObject *self, PyObject *args)
-{
+psutil_disk_usage(PyObject *self, PyObject *args) {
BOOL retval;
ULARGE_INTEGER _, total, free;
char *path;
@@ -2200,9 +2157,7 @@ return_:
* Return a Python list of named tuples with overall network I/O information
*/
static PyObject *
-psutil_net_io_counters(PyObject *self, PyObject *args)
-{
- char ifname[MAX_PATH];
+psutil_net_io_counters(PyObject *self, PyObject *args) {
DWORD dwRetVal = 0;
MIB_IFROW *pIfRow = NULL;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
@@ -2248,9 +2203,8 @@ psutil_net_io_counters(PyObject *self, PyObject *args)
if (!py_nic_info)
goto error;
- sprintf_s(ifname, MAX_PATH, "%wS", pCurrAddresses->FriendlyName);
- py_nic_name = PyUnicode_Decode(
- ifname, _tcslen(ifname), Py_FileSystemDefaultEncoding, "replace");
+ py_nic_name = PyUnicode_FromWideChar(pCurrAddresses->FriendlyName,
+ wcslen(pCurrAddresses->FriendlyName));
if (py_nic_name == NULL)
goto error;
@@ -2282,8 +2236,7 @@ error:
* Return a Python dict of tuples for disk I/O information
*/
static PyObject *
-psutil_disk_io_counters(PyObject *self, PyObject *args)
-{
+psutil_disk_io_counters(PyObject *self, PyObject *args) {
DISK_PERFORMANCE_WIN_2008 diskPerformance;
DWORD dwSize;
HANDLE hDevice = NULL;
@@ -2292,9 +2245,8 @@ psutil_disk_io_counters(PyObject *self, PyObject *args)
int devNum;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
- if (py_retdict == NULL) {
+ if (py_retdict == NULL)
return NULL;
- }
// Apparently there's no way to figure out how many times we have
// to iterate in order to find valid drives.
@@ -2306,9 +2258,8 @@ psutil_disk_io_counters(PyObject *self, PyObject *args)
hDevice = CreateFile(szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
- if (hDevice == INVALID_HANDLE_VALUE) {
+ if (hDevice == INVALID_HANDLE_VALUE)
continue;
- }
if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
&diskPerformance, sizeof(diskPerformance),
&dwSize, NULL))
@@ -2352,8 +2303,7 @@ error:
}
-static char *psutil_get_drive_type(int type)
-{
+static char *psutil_get_drive_type(int type) {
switch (type) {
case DRIVE_FIXED:
return "fixed";
@@ -2384,8 +2334,7 @@ static char *psutil_get_drive_type(int type)
* (drive_letter, drive_letter, type, "")
*/
static PyObject *
-psutil_disk_partitions(PyObject *self, PyObject *args)
-{
+psutil_disk_partitions(PyObject *self, PyObject *args) {
DWORD num_bytes;
char drive_strings[255];
char *drive_letter = drive_strings;
@@ -2407,9 +2356,8 @@ psutil_disk_partitions(PyObject *self, PyObject *args)
// see https://github.com/giampaolo/psutil/issues/264
SetErrorMode(SEM_FAILCRITICALERRORS);
- if (! PyArg_ParseTuple(args, "O", &py_all)) {
+ if (! PyArg_ParseTuple(args, "O", &py_all))
goto error;
- }
all = PyObject_IsTrue(py_all);
Py_BEGIN_ALLOW_THREADS
@@ -2458,20 +2406,16 @@ psutil_disk_partitions(PyObject *self, PyObject *args)
SetLastError(0);
}
else {
- if (pflags & FILE_READ_ONLY_VOLUME) {
+ if (pflags & FILE_READ_ONLY_VOLUME)
strcat_s(opts, _countof(opts), "ro");
- }
- else {
+ else
strcat_s(opts, _countof(opts), "rw");
- }
- if (pflags & FILE_VOLUME_IS_COMPRESSED) {
+ if (pflags & FILE_VOLUME_IS_COMPRESSED)
strcat_s(opts, _countof(opts), ",compressed");
- }
}
- if (strlen(opts) > 0) {
+ if (strlen(opts) > 0)
strcat_s(opts, _countof(opts), ",");
- }
strcat_s(opts, _countof(opts), psutil_get_drive_type(type));
py_tuple = Py_BuildValue(
@@ -2505,8 +2449,7 @@ error:
* Return a Python dict of tuples for disk I/O information
*/
static PyObject *
-psutil_users(PyObject *self, PyObject *args)
-{
+psutil_users(PyObject *self, PyObject *args) {
HANDLE hServer = NULL;
LPTSTR buffer_user = NULL;
LPTSTR buffer_addr = NULL;
@@ -2529,9 +2472,8 @@ psutil_users(PyObject *self, PyObject *args)
PyObject *py_address = NULL;
PyObject *py_buffer_user_encoded = NULL;
- if (py_retlist == NULL) {
+ if (py_retlist == NULL)
return NULL;
- }
hInstWinSta = LoadLibraryA("winsta.dll");
WinStationQueryInformationW = (PWINSTATIONQUERYINFORMATIONW) \
@@ -2552,12 +2494,10 @@ psutil_users(PyObject *self, PyObject *args)
py_address = NULL;
py_tuple = NULL;
sessionId = sessions[i].SessionId;
- if (buffer_user != NULL) {
+ if (buffer_user != NULL)
WTSFreeMemory(buffer_user);
- }
- if (buffer_addr != NULL) {
+ if (buffer_addr != NULL)
WTSFreeMemory(buffer_addr);
- }
buffer_user = NULL;
buffer_addr = NULL;
@@ -2569,9 +2509,8 @@ psutil_users(PyObject *self, PyObject *args)
PyErr_SetFromWindowsErr(0);
goto error;
}
- if (bytes == 1) {
+ if (bytes == 1)
continue;
- }
// address
bytes = 0;
@@ -2641,21 +2580,16 @@ error:
Py_XDECREF(py_address);
Py_DECREF(py_retlist);
- if (hInstWinSta != NULL) {
+ if (hInstWinSta != NULL)
FreeLibrary(hInstWinSta);
- }
- if (hServer != NULL) {
+ if (hServer != NULL)
WTSCloseServer(hServer);
- }
- if (sessions != NULL) {
+ if (sessions != NULL)
WTSFreeMemory(sessions);
- }
- if (buffer_user != NULL) {
+ if (buffer_user != NULL)
WTSFreeMemory(buffer_user);
- }
- if (buffer_addr != NULL) {
+ if (buffer_addr != NULL)
WTSFreeMemory(buffer_addr);
- }
return NULL;
}
@@ -2664,8 +2598,7 @@ error:
* Return the number of handles opened by process.
*/
static PyObject *
-psutil_proc_num_handles(PyObject *self, PyObject *args)
-{
+psutil_proc_num_handles(PyObject *self, PyObject *args) {
DWORD pid;
HANDLE hProcess;
DWORD handleCount;
@@ -2673,9 +2606,8 @@ psutil_proc_num_handles(PyObject *self, PyObject *args)
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
hProcess = psutil_handle_from_pid(pid);
- if (NULL == hProcess) {
+ if (NULL == hProcess)
return NULL;
- }
if (! GetProcessHandleCount(hProcess, &handleCount)) {
CloseHandle(hProcess);
return PyErr_SetFromWindowsErr(0);
@@ -2699,8 +2631,7 @@ psutil_proc_num_handles(PyObject *self, PyObject *args)
* - io counters (fallback)
*/
static PyObject *
-psutil_proc_info(PyObject *self, PyObject *args)
-{
+psutil_proc_info(PyObject *self, PyObject *args) {
DWORD pid;
PSYSTEM_PROCESS_INFORMATION process;
PVOID buffer;
@@ -2761,8 +2692,7 @@ psutil_proc_info(PyObject *self, PyObject *args)
}
-static char *get_region_protection_string(ULONG protection)
-{
+static char *get_region_protection_string(ULONG protection) {
switch (protection & 0xff) {
case PAGE_NOACCESS:
return "";
@@ -2790,8 +2720,7 @@ static char *get_region_protection_string(ULONG protection)
* Return a list of process's memory mappings.
*/
static PyObject *
-psutil_proc_memory_maps(PyObject *self, PyObject *args)
-{
+psutil_proc_memory_maps(PyObject *self, PyObject *args) {
DWORD pid;
HANDLE hProcess = NULL;
MEMORY_BASIC_INFORMATION basicInfo;
@@ -2803,16 +2732,13 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args)
PyObject *py_list = PyList_New(0);
PyObject *py_tuple = NULL;
- if (py_list == NULL) {
+ if (py_list == NULL)
return NULL;
- }
- if (! PyArg_ParseTuple(args, "l", &pid)) {
+ if (! PyArg_ParseTuple(args, "l", &pid))
goto error;
- }
hProcess = psutil_handle_from_pid(pid);
- if (NULL == hProcess) {
+ if (NULL == hProcess)
goto error;
- }
GetSystemInfo(&system_info);
maxAddr = system_info.lpMaximumApplicationAddress;
@@ -2823,9 +2749,8 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args)
sizeof(MEMORY_BASIC_INFORMATION)))
{
py_tuple = NULL;
- if (baseAddress > maxAddr) {
+ if (baseAddress > maxAddr)
break;
- }
if (GetMappedFileNameA(hProcess, baseAddress, mappedFileName,
sizeof(mappedFileName)))
{
@@ -2861,8 +2786,7 @@ error:
* Return a {pid:ppid, ...} dict for all running processes.
*/
static PyObject *
-psutil_ppid_map(PyObject *self, PyObject *args)
-{
+psutil_ppid_map(PyObject *self, PyObject *args) {
PyObject *pid = NULL;
PyObject *ppid = NULL;
PyObject *py_retdict = PyDict_New();
@@ -2911,14 +2835,12 @@ error:
*/
static PyObject *
-psutil_net_if_addrs(PyObject *self, PyObject *args)
-{
+psutil_net_if_addrs(PyObject *self, PyObject *args) {
unsigned int i = 0;
ULONG family;
PCTSTR intRet;
char *ptr;
char buff[100];
- char ifname[MAX_PATH];
DWORD bufflen = 100;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
@@ -2928,6 +2850,7 @@ psutil_net_if_addrs(PyObject *self, PyObject *args)
PyObject *py_tuple = NULL;
PyObject *py_address = NULL;
PyObject *py_mac_address = NULL;
+ PyObject *py_nic_name = NULL;
if (py_retlist == NULL)
return NULL;
@@ -2939,7 +2862,12 @@ psutil_net_if_addrs(PyObject *self, PyObject *args)
while (pCurrAddresses) {
pUnicast = pCurrAddresses->FirstUnicastAddress;
- sprintf_s(ifname, MAX_PATH, "%wS", pCurrAddresses->FriendlyName);
+
+ py_nic_name = NULL;
+ py_nic_name = PyUnicode_FromWideChar(pCurrAddresses->FriendlyName,
+ wcslen(pCurrAddresses->FriendlyName));
+ if (py_nic_name == NULL)
+ goto error;
// MAC address
if (pCurrAddresses->PhysicalAddressLength != 0) {
@@ -2968,13 +2896,15 @@ psutil_net_if_addrs(PyObject *self, PyObject *args)
Py_INCREF(Py_None);
Py_INCREF(Py_None);
+ Py_INCREF(Py_None);
py_tuple = Py_BuildValue(
- "(siOOO)",
- ifname,
+ "(OiOOOO)",
+ py_nic_name,
-1, // this will be converted later to AF_LINK
py_mac_address,
- Py_None,
- Py_None
+ Py_None, // netmask (not supported)
+ Py_None, // broadcast (not supported)
+ Py_None // ptp (not supported on Windows)
);
if (! py_tuple)
goto error;
@@ -3020,13 +2950,15 @@ psutil_net_if_addrs(PyObject *self, PyObject *args)
Py_INCREF(Py_None);
Py_INCREF(Py_None);
+ Py_INCREF(Py_None);
py_tuple = Py_BuildValue(
- "(siOOO)",
- ifname,
+ "(OiOOOO)",
+ py_nic_name,
family,
py_address,
- Py_None,
- Py_None
+ Py_None, // netmask (not supported)
+ Py_None, // broadcast (not supported)
+ Py_None // ptp (not supported on Windows)
);
if (! py_tuple)
@@ -3039,7 +2971,7 @@ psutil_net_if_addrs(PyObject *self, PyObject *args)
pUnicast = pUnicast->Next;
}
}
-
+ Py_DECREF(py_nic_name);
pCurrAddresses = pCurrAddresses->Next;
}
@@ -3052,6 +2984,7 @@ error:
Py_DECREF(py_retlist);
Py_XDECREF(py_tuple);
Py_XDECREF(py_address);
+ Py_XDECREF(py_nic_name);
return NULL;
}
@@ -3062,8 +2995,7 @@ error:
'full duplex')
*/
static PyObject *
-psutil_net_if_stats(PyObject *self, PyObject *args)
-{
+psutil_net_if_stats(PyObject *self, PyObject *args) {
int i;
DWORD dwSize = 0;
DWORD dwRetVal = 0;
@@ -3176,8 +3108,8 @@ error:
// ------------------------ Python init ---------------------------
static PyMethodDef
-PsutilMethods[] =
-{
+PsutilMethods[] = {
+
// --- per-process functions
{"proc_cmdline", psutil_proc_cmdline, METH_VARARGS,
diff --git a/psutil/arch/bsd/process_info.c b/psutil/arch/bsd/process_info.c
index 4d739240..a895a436 100644
--- a/psutil/arch/bsd/process_info.c
+++ b/psutil/arch/bsd/process_info.c
@@ -33,8 +33,7 @@
* On error, the function returns a BSD errno value.
*/
int
-psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount)
-{
+psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
int err;
struct kinfo_proc *result;
int done;
@@ -113,8 +112,7 @@ psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount)
char
-*psutil_get_cmd_path(long pid, size_t *pathsize)
-{
+*psutil_get_cmd_path(long pid, size_t *pathsize) {
int mib[4];
char *path;
size_t size = 0;
@@ -161,8 +159,7 @@ char
* 1 for insufficient privileges.
*/
char
-*psutil_get_cmd_args(long pid, size_t *argsize)
-{
+*psutil_get_cmd_args(long pid, size_t *argsize) {
int mib[4], argmax;
size_t size = sizeof(argmax);
char *procargs = NULL;
@@ -204,8 +201,7 @@ char
// returns the command line as a python list object
PyObject *
-psutil_get_arg_list(long pid)
-{
+psutil_get_arg_list(long pid) {
char *argstr = NULL;
int pos = 0;
size_t argsize = 0;
@@ -249,8 +245,7 @@ error:
* Return 1 if PID exists in the current process list, else 0.
*/
int
-psutil_pid_exists(long pid)
-{
+psutil_pid_exists(long pid) {
int kill_ret;
if (pid < 0)
diff --git a/psutil/arch/osx/process_info.c b/psutil/arch/osx/process_info.c
index b6dd5bb9..e0a908e3 100644
--- a/psutil/arch/osx/process_info.c
+++ b/psutil/arch/osx/process_info.c
@@ -27,8 +27,7 @@
* Return 1 if PID exists in the current process list, else 0.
*/
int
-psutil_pid_exists(long pid)
-{
+psutil_pid_exists(long pid) {
int kill_ret;
// save some time if it's an invalid PID
@@ -53,8 +52,7 @@ psutil_pid_exists(long pid)
* On error, the function returns a BSD errno value.
*/
int
-psutil_get_proc_list(kinfo_proc **procList, size_t *procCount)
-{
+psutil_get_proc_list(kinfo_proc **procList, size_t *procCount) {
// Declaring mib as const requires use of a cast since the
// sysctl prototype doesn't include the const modifier.
static const int mib3[3] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
@@ -116,8 +114,7 @@ psutil_get_proc_list(kinfo_proc **procList, size_t *procCount)
// Read the maximum argument size for processes
int
-psutil_get_argmax()
-{
+psutil_get_argmax() {
int argmax;
int mib[] = { CTL_KERN, KERN_ARGMAX };
size_t size = sizeof(argmax);
@@ -130,8 +127,7 @@ psutil_get_argmax()
// return process args as a python list
PyObject *
-psutil_get_arg_list(long pid)
-{
+psutil_get_arg_list(long pid) {
int mib[3];
int nargs;
int len;
@@ -226,8 +222,7 @@ error:
int
-psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp)
-{
+psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp) {
int mib[4];
size_t len;
mib[0] = CTL_KERN;
@@ -258,8 +253,7 @@ psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp)
* A thin wrapper around proc_pidinfo()
*/
int
-psutil_proc_pidinfo(long pid, int flavor, void *pti, int size)
-{
+psutil_proc_pidinfo(long pid, int flavor, void *pti, int size) {
int ret = proc_pidinfo((int)pid, flavor, 0, pti, size);
if (ret == 0) {
if (! psutil_pid_exists(pid)) {
diff --git a/psutil/arch/windows/inet_ntop.c b/psutil/arch/windows/inet_ntop.c
index b9fffd1c..50dfb6ae 100644
--- a/psutil/arch/windows/inet_ntop.c
+++ b/psutil/arch/windows/inet_ntop.c
@@ -3,13 +3,10 @@
// From: https://memset.wordpress.com/2010/10/09/inet_ntop-for-win32/
PCSTR
WSAAPI
-inet_ntop(
- __in INT Family,
- __in PVOID pAddr,
- __out_ecount(StringBufSize) PSTR pStringBuf,
- __in size_t StringBufSize
- )
-{
+inet_ntop(__in INT Family,
+ __in PVOID pAddr,
+ __out_ecount(StringBufSize) PSTR pStringBuf,
+ __in size_t StringBufSize) {
DWORD dwAddressLength = 0;
struct sockaddr_storage srcaddr;
struct sockaddr_in *srcaddr4 = (struct sockaddr_in*) &srcaddr;
@@ -31,11 +28,11 @@ inet_ntop(
}
if (WSAAddressToString((LPSOCKADDR) &srcaddr,
- dwAddressLength,
- 0,
- pStringBuf,
+ dwAddressLength,
+ 0,
+ pStringBuf,
(LPDWORD) &StringBufSize) != 0) {
return NULL;
}
return pStringBuf;
-} \ No newline at end of file
+}
diff --git a/psutil/arch/windows/ntextapi.h b/psutil/arch/windows/ntextapi.h
index d10432a3..7f86c57a 100644
--- a/psutil/arch/windows/ntextapi.h
+++ b/psutil/arch/windows/ntextapi.h
@@ -186,7 +186,7 @@ typedef enum _PROCESSINFOCLASS2 {
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
- ProcessDebugPort,
+ _ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation,
@@ -207,7 +207,7 @@ typedef enum _PROCESSINFOCLASS2 {
ProcessForegroundInformation,
_ProcessWow64Information,
/* added after XP+ */
- ProcessImageFileName,
+ _ProcessImageFileName,
ProcessLUIDDeviceMapsEnabled,
ProcessBreakOnTermination,
ProcessDebugObjectHandle,
@@ -224,5 +224,7 @@ typedef enum _PROCESSINFOCLASS2 {
#define PROCESSINFOCLASS PROCESSINFOCLASS2
#define ProcessBasicInformation _ProcessBasicInformation
#define ProcessWow64Information _ProcessWow64Information
+#define ProcessDebugPort _ProcessDebugPort
+#define ProcessImageFileName _ProcessImageFileName
#endif // __NTEXTAPI_H__
diff --git a/psutil/arch/windows/process_handles.c b/psutil/arch/windows/process_handles.c
index b3f480af..2ddfa504 100644
--- a/psutil/arch/windows/process_handles.c
+++ b/psutil/arch/windows/process_handles.c
@@ -23,14 +23,13 @@ PVOID g_fiber = NULL;
PVOID
-GetLibraryProcAddress(PSTR LibraryName, PSTR ProcName)
-{
+GetLibraryProcAddress(PSTR LibraryName, PSTR ProcName) {
return GetProcAddress(GetModuleHandleA(LibraryName), ProcName);
}
+
PyObject *
-psutil_get_open_files(long dwPid, HANDLE hProcess)
-{
+psutil_get_open_files(long dwPid, HANDLE hProcess) {
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
@@ -44,9 +43,9 @@ psutil_get_open_files(long dwPid, HANDLE hProcess)
return psutil_get_open_files_getmappedfilename(dwPid, hProcess);
}
+
VOID
-psutil_get_open_files_init(BOOL threaded)
-{
+psutil_get_open_files_init(BOOL threaded) {
if (g_initialized == TRUE)
return;
@@ -65,9 +64,9 @@ psutil_get_open_files_init(BOOL threaded)
g_initialized = TRUE;
}
+
PyObject *
-psutil_get_open_files_ntqueryobject(long dwPid, HANDLE hProcess)
-{
+psutil_get_open_files_ntqueryobject(long dwPid, HANDLE hProcess) {
NTSTATUS status;
PSYSTEM_HANDLE_INFORMATION_EX pHandleInfo = NULL;
DWORD dwInfoSize = 0x10000;
@@ -273,9 +272,9 @@ cleanup:
return pyListFiles;
}
+
DWORD
-psutil_NtQueryObject()
-{
+psutil_NtQueryObject() {
DWORD dwWait = 0;
if (g_hThread == NULL)
@@ -312,9 +311,9 @@ psutil_NtQueryObject()
return dwWait;
}
+
void
-psutil_NtQueryObjectThread()
-{
+psutil_NtQueryObjectThread() {
// Prevent the thread stack from leaking when this
// thread gets terminated due to NTQueryObject hanging
g_fiber = ConvertThreadToFiber(NULL);
@@ -332,9 +331,9 @@ psutil_NtQueryObjectThread()
}
}
+
PyObject *
-psutil_get_open_files_getmappedfilename(long dwPid, HANDLE hProcess)
-{
+psutil_get_open_files_getmappedfilename(long dwPid, HANDLE hProcess) {
NTSTATUS status;
PSYSTEM_HANDLE_INFORMATION_EX pHandleInfo = NULL;
DWORD dwInfoSize = 0x10000;
diff --git a/psutil/arch/windows/process_handles.h b/psutil/arch/windows/process_handles.h
index 4cf4023e..ea5fbdbe 100644
--- a/psutil/arch/windows/process_handles.h
+++ b/psutil/arch/windows/process_handles.h
@@ -48,8 +48,7 @@ typedef NTSTATUS (NTAPI *_NtQueryObject)(
// Undocumented FILE_INFORMATION_CLASS: FileNameInformation
static const SYSTEM_INFORMATION_CLASS SystemExtendedHandleInformation = (SYSTEM_INFORMATION_CLASS)64;
-typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
-{
+typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX {
PVOID Object;
HANDLE UniqueProcessId;
HANDLE HandleValue;
@@ -60,8 +59,7 @@ typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
ULONG Reserved;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;
-typedef struct _SYSTEM_HANDLE_INFORMATION_EX
-{
+typedef struct _SYSTEM_HANDLE_INFORMATION_EX {
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
diff --git a/psutil/arch/windows/process_info.c b/psutil/arch/windows/process_info.c
index a59cce47..b925b05f 100644
--- a/psutil/arch/windows/process_info.c
+++ b/psutil/arch/windows/process_info.c
@@ -26,8 +26,7 @@
* Return a process handle or NULL.
*/
HANDLE
-psutil_handle_from_pid_waccess(DWORD pid, DWORD dwDesiredAccess)
-{
+psutil_handle_from_pid_waccess(DWORD pid, DWORD dwDesiredAccess) {
HANDLE hProcess;
DWORD processExitCode = 0;
@@ -70,8 +69,7 @@ psutil_handle_from_pid(DWORD pid) {
// fetch the PEB base address from NtQueryInformationProcess()
PVOID
-psutil_get_peb_address(HANDLE ProcessHandle)
-{
+psutil_get_peb_address(HANDLE ProcessHandle) {
_NtQueryInformationProcess NtQueryInformationProcess =
(_NtQueryInformationProcess)GetProcAddress(
GetModuleHandleA("ntdll.dll"), "NtQueryInformationProcess");
@@ -121,8 +119,7 @@ psutil_get_pids(DWORD *numberOfReturnedPIDs) {
int
-psutil_pid_is_running(DWORD pid)
-{
+psutil_pid_is_running(DWORD pid) {
HANDLE hProcess;
DWORD exitCode;
@@ -171,8 +168,7 @@ psutil_pid_is_running(DWORD pid)
int
-psutil_pid_in_proclist(DWORD pid)
-{
+psutil_pid_in_proclist(DWORD pid) {
DWORD *proclist = NULL;
DWORD numberOfReturnedPIDs;
DWORD i;
@@ -195,8 +191,7 @@ psutil_pid_in_proclist(DWORD pid)
// Check exit code from a process handle. Return FALSE on an error also
// XXX - not used anymore
int
-handlep_is_running(HANDLE hProcess)
-{
+handlep_is_running(HANDLE hProcess) {
DWORD dwCode;
if (NULL == hProcess)
@@ -214,8 +209,7 @@ handlep_is_running(HANDLE hProcess)
* with given pid or NULL on error.
*/
PyObject *
-psutil_get_arg_list(long pid)
-{
+psutil_get_arg_list(long pid) {
int nArgs, i;
LPWSTR *szArglist = NULL;
HANDLE hProcess = NULL;
@@ -365,8 +359,7 @@ const int STATUS_BUFFER_TOO_SMALL = 0xC0000023L;
*/
int
psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess,
- PVOID *retBuffer)
-{
+ PVOID *retBuffer) {
static ULONG initialBufferSize = 0x4000;
NTSTATUS status;
PVOID buffer;
diff --git a/psutil/arch/windows/security.c b/psutil/arch/windows/security.c
index 3aabffd0..331d9622 100644
--- a/psutil/arch/windows/security.c
+++ b/psutil/arch/windows/security.c
@@ -108,8 +108,7 @@ psutil_has_system_privilege(HANDLE hProcess) {
BOOL
-psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege)
-{
+psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) {
TOKEN_PRIVILEGES tp;
LUID luid;
TOKEN_PRIVILEGES tpPrevious;
@@ -159,8 +158,7 @@ psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege)
int
-psutil_set_se_debug()
-{
+psutil_set_se_debug() {
HANDLE hToken;
if (! OpenThreadToken(GetCurrentThread(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
@@ -198,8 +196,7 @@ psutil_set_se_debug()
int
-psutil_unset_se_debug()
-{
+psutil_unset_se_debug() {
HANDLE hToken;
if (! OpenThreadToken(GetCurrentThread(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
diff --git a/test/_bsd.py b/test/_bsd.py
index e4a3225d..da08383a 100644
--- a/test/_bsd.py
+++ b/test/_bsd.py
@@ -16,7 +16,7 @@ import time
import psutil
from psutil._compat import PY3
-from test_psutil import (TOLERANCE, BSD, sh, get_test_subprocess, which,
+from test_psutil import (MEMORY_TOLERANCE, BSD, sh, get_test_subprocess, which,
retry_before_failing, reap_children, unittest)
@@ -155,37 +155,37 @@ class BSDSpecificTestCase(unittest.TestCase):
def test_vmem_active(self):
syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().active, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_inactive(self):
syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().inactive, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_wired(self):
syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().wired, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_cached(self):
syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().cached, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_free(self):
syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE
self.assertAlmostEqual(psutil.virtual_memory().free, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_buffers(self):
syst = sysctl("vfs.bufspace")
self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
def test_cpu_count_logical(self):
syst = sysctl("hw.ncpu")
@@ -203,42 +203,42 @@ class BSDSpecificTestCase(unittest.TestCase):
def test_active(self):
num = muse('Active')
self.assertAlmostEqual(psutil.virtual_memory().active, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
@retry_before_failing()
def test_inactive(self):
num = muse('Inactive')
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
@retry_before_failing()
def test_wired(self):
num = muse('Wired')
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
@retry_before_failing()
def test_cached(self):
num = muse('Cache')
self.assertAlmostEqual(psutil.virtual_memory().cached, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
@retry_before_failing()
def test_free(self):
num = muse('Free')
self.assertAlmostEqual(psutil.virtual_memory().free, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
@retry_before_failing()
def test_buffers(self):
num = muse('Buffer')
self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
def main():
diff --git a/test/_linux.py b/test/_linux.py
index c1927ea8..c9e04a53 100644
--- a/test/_linux.py
+++ b/test/_linux.py
@@ -26,7 +26,7 @@ try:
except ImportError:
import mock # requires "pip install mock"
-from test_psutil import POSIX, TOLERANCE, TRAVIS, LINUX
+from test_psutil import POSIX, MEMORY_TOLERANCE, TRAVIS, LINUX
from test_psutil import (skip_on_not_implemented, sh, get_test_subprocess,
retry_before_failing, get_kernel_version, unittest,
which, call_until)
@@ -131,28 +131,28 @@ class LinuxSpecificTestCase(unittest.TestCase):
lines = sh('free').split('\n')[1:]
used = int(lines[0].split()[2]) * 1024
self.assertAlmostEqual(used, psutil.virtual_memory().used,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_free(self):
lines = sh('free').split('\n')[1:]
free = int(lines[0].split()[3]) * 1024
self.assertAlmostEqual(free, psutil.virtual_memory().free,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_buffers(self):
lines = sh('free').split('\n')[1:]
buffers = int(lines[0].split()[5]) * 1024
self.assertAlmostEqual(buffers, psutil.virtual_memory().buffers,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_cached(self):
lines = sh('free').split('\n')[1:]
cached = int(lines[0].split()[6]) * 1024
self.assertAlmostEqual(cached, psutil.virtual_memory().cached,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
def test_swapmem_total(self):
lines = sh('free').split('\n')[1:]
@@ -164,14 +164,14 @@ class LinuxSpecificTestCase(unittest.TestCase):
lines = sh('free').split('\n')[1:]
used = int(lines[2].split()[2]) * 1024
self.assertAlmostEqual(used, psutil.swap_memory().used,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_swapmem_free(self):
lines = sh('free').split('\n')[1:]
free = int(lines[2].split()[3]) * 1024
self.assertAlmostEqual(free, psutil.swap_memory().free,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@unittest.skipIf(TRAVIS, "unknown failure on travis")
def test_cpu_times(self):
diff --git a/test/_osx.py b/test/_osx.py
index 6e6e4380..2375a483 100644
--- a/test/_osx.py
+++ b/test/_osx.py
@@ -15,8 +15,9 @@ import time
import psutil
from psutil._compat import PY3
-from test_psutil import (TOLERANCE, OSX, sh, get_test_subprocess,
- reap_children, retry_before_failing, unittest)
+from test_psutil import (MEMORY_TOLERANCE, OSX, sh, get_test_subprocess,
+ reap_children, retry_before_failing, unittest,
+ TRAVIS)
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
@@ -47,6 +48,33 @@ def vm_stat(field):
return int(re.search('\d+', line).group(0)) * PAGESIZE
+# http://code.activestate.com/recipes/578019/
+def human2bytes(s):
+ SYMBOLS = {
+ 'customary': ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
+ }
+ init = s
+ num = ""
+ while s and s[0:1].isdigit() or s[0:1] == '.':
+ num += s[0]
+ s = s[1:]
+ num = float(num)
+ letter = s.strip()
+ for name, sset in SYMBOLS.items():
+ if letter in sset:
+ break
+ else:
+ if letter == 'k':
+ sset = SYMBOLS['customary']
+ letter = letter.upper()
+ else:
+ raise ValueError("can't interpret %r" % init)
+ prefix = {sset[0]: 1}
+ for i, s in enumerate(sset[1:]):
+ prefix[s] = 1 << (i+1)*10
+ return int(num * prefix[letter])
+
+
@unittest.skipUnless(OSX, "not an OSX system")
class OSXSpecificTestCase(unittest.TestCase):
@@ -97,35 +125,44 @@ class OSXSpecificTestCase(unittest.TestCase):
if abs(usage.used - used) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % usage.used, used)
+ def test_cpu_count_logical(self):
+ num = sysctl("sysctl hw.logicalcpu")
+ self.assertEqual(num, psutil.cpu_count(logical=True))
+
+ def test_cpu_count_physical(self):
+ num = sysctl("sysctl hw.physicalcpu")
+ self.assertEqual(num, psutil.cpu_count(logical=False))
+
# --- virtual mem
def test_vmem_total(self):
sysctl_hwphymem = sysctl('sysctl hw.memsize')
self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)
+ @unittest.skipIf(TRAVIS, "")
@retry_before_failing()
def test_vmem_free(self):
num = vm_stat("free")
self.assertAlmostEqual(psutil.virtual_memory().free, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_active(self):
num = vm_stat("active")
self.assertAlmostEqual(psutil.virtual_memory().active, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_inactive(self):
num = vm_stat("inactive")
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_wired(self):
num = vm_stat("wired")
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
- delta=TOLERANCE)
+ delta=MEMORY_TOLERANCE)
# --- swap mem
@@ -138,15 +175,13 @@ class OSXSpecificTestCase(unittest.TestCase):
self.assertEqual(psutil.swap_memory().sout, num)
def test_swapmem_total(self):
- tot1 = psutil.swap_memory().total
- tot2 = 0
- # OSX uses multiple cache files:
- # http://en.wikipedia.org/wiki/Paging#OS_X
- for name in os.listdir("/var/vm/"):
- file = os.path.join("/var/vm", name)
- if os.path.isfile(file):
- tot2 += os.path.getsize(file)
- self.assertEqual(tot1, tot2)
+ out = sh('sysctl vm.swapusage')
+ out = out.replace('vm.swapusage: ', '')
+ total, used, free = re.findall('\d+.\d+\w', out)
+ psutil_smem = psutil.swap_memory()
+ self.assertEqual(psutil_smem.total, human2bytes(total))
+ self.assertEqual(psutil_smem.used, human2bytes(used))
+ self.assertEqual(psutil_smem.free, human2bytes(free))
def main():
@@ -155,6 +190,7 @@ def main():
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
return result.wasSuccessful()
+
if __name__ == '__main__':
if not main():
sys.exit(1)
diff --git a/test/test_memory_leaks.py b/test/test_memory_leaks.py
index 6f02dc0a..c95734c8 100644
--- a/test/test_memory_leaks.py
+++ b/test/test_memory_leaks.py
@@ -34,7 +34,7 @@ else:
LOOPS = 1000
-TOLERANCE = 4096
+MEMORY_TOLERANCE = 4096
SKIP_PYTHON_IMPL = True
@@ -65,7 +65,7 @@ class Base(unittest.TestCase):
rss2 = call_many_times()
difference = rss2 - rss1
- if difference > TOLERANCE:
+ if difference > MEMORY_TOLERANCE:
# This doesn't necessarily mean we have a leak yet.
# At this point we assume that after having called the
# function so many times the memory usage is stabilized
@@ -419,6 +419,7 @@ class TestModuleFunctionsLeaks(Base):
@unittest.skipIf(LINUX,
"not worth being tested on Linux (pure python)")
+ @unittest.skipIf(OSX and os.getuid() != 0, "need root access")
def test_net_connections(self):
self.execute('net_connections')
diff --git a/test/test_psutil.py b/test/test_psutil.py
index 3043e662..3d02a307 100644
--- a/test/test_psutil.py
+++ b/test/test_psutil.py
@@ -72,7 +72,7 @@ else:
# conf for retry_before_failing() decorator
NO_RETRIES = 10
# bytes tolerance for OS memory related tests
-TOLERANCE = 500 * 1024 # 500KB
+MEMORY_TOLERANCE = 500 * 1024 # 500KB
# the timeout used in functions which have to wait
GLOBAL_TIMEOUT = 3
@@ -451,7 +451,9 @@ def retry_before_failing(ntimes=None):
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
- for x in range(ntimes or NO_RETRIES):
+ times = ntimes or NO_RETRIES
+ assert times, times
+ for x in range(times):
try:
return fun(*args, **kwargs)
except AssertionError:
@@ -587,6 +589,14 @@ class TestSystemAPIs(unittest.TestCase):
p.wait()
self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])
+ with mock.patch('psutil.Process',
+ side_effect=psutil.NoSuchProcess(os.getpid())):
+ self.assertEqual(list(psutil.process_iter()), [])
+ with mock.patch('psutil.Process',
+ side_effect=psutil.AccessDenied(os.getpid())):
+ with self.assertRaises(psutil.AccessDenied):
+ list(psutil.process_iter())
+
def test_wait_procs(self):
def callback(p):
l.append(p.pid)
@@ -968,6 +978,8 @@ class TestSystemAPIs(unittest.TestCase):
try:
os.stat(disk.mountpoint)
except OSError as err:
+ if TRAVIS and OSX and err.errno == errno.EIO:
+ continue
# http://mail.python.org/pipermail/python-dev/
# 2012-June/120787.html
if err.errno not in (errno.EPERM, errno.EACCES):
@@ -1068,13 +1080,19 @@ class TestSystemAPIs(unittest.TestCase):
s = socket.socket(af, socktype, proto)
with contextlib.closing(s):
s.bind(sa)
- for ip in (addr.address, addr.netmask, addr.broadcast):
+ for ip in (addr.address, addr.netmask, addr.broadcast,
+ addr.ptp):
if ip is not None:
# TODO: skip AF_INET6 for now because I get:
# AddressValueError: Only hex digits permitted in
# u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
if addr.family != AF_INET6:
check_ip_address(ip, addr.family)
+ # broadcast and ptp addresses are mutually exclusive
+ if addr.broadcast:
+ self.assertIsNone(addr.ptp)
+ elif addr.ptp:
+ self.assertIsNone(addr.broadcast)
if BSD or OSX or SUNOS:
if hasattr(socket, "AF_LINK"):
@@ -1493,6 +1511,55 @@ class TestProcess(unittest.TestCase):
with self.assertRaises(ValueError):
p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5))
+ @unittest.skipUnless(LINUX and RLIMIT_SUPPORT,
+ "only available on Linux >= 2.6.36")
+ def test_rlimit(self):
+ p = psutil.Process()
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
+ try:
+ p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
+ with open(TESTFN, "wb") as f:
+ f.write(b"X" * 1024)
+ # write() or flush() doesn't always cause the exception
+ # but close() will.
+ with self.assertRaises(IOError) as exc:
+ with open(TESTFN, "wb") as f:
+ f.write(b"X" * 1025)
+ self.assertEqual(exc.exception.errno if PY3 else exc.exception[0],
+ errno.EFBIG)
+ finally:
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
+ self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
+
+ @unittest.skipUnless(LINUX and RLIMIT_SUPPORT,
+ "only available on Linux >= 2.6.36")
+ def test_rlimit_infinity(self):
+ # First set a limit, then re-set it by specifying INFINITY
+ # and assume we overridden the previous limit.
+ p = psutil.Process()
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
+ try:
+ p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
+ p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard))
+ with open(TESTFN, "wb") as f:
+ f.write(b"X" * 2048)
+ finally:
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
+ self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))
+
+ @unittest.skipUnless(LINUX and RLIMIT_SUPPORT,
+ "only available on Linux >= 2.6.36")
+ def test_rlimit_infinity_value(self):
+ # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really
+ # big number on a platform with large file support. On these
+ # platforms we need to test that the get/setrlimit functions
+ # properly convert the number to a C long long and that the
+ # conversion doesn't raise an error.
+ p = psutil.Process()
+ soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
+ self.assertEqual(psutil.RLIM_INFINITY, hard)
+ p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
+
def test_num_threads(self):
# on certain platforms such as Linux we might test for exact
# thread number, since we always have with 1 thread per process,
@@ -1644,22 +1711,31 @@ class TestProcess(unittest.TestCase):
# Test that name(), exe() and cmdline() correctly handle programs
# with funky chars such as spaces and ")", see:
# https://github.com/giampaolo/psutil/issues/628
- funky_name = "/tmp/foo bar )"
- _, c_file = tempfile.mkstemp(prefix='psutil-', suffix='.c', dir="/tmp")
- self.addCleanup(lambda: safe_remove(c_file))
- self.addCleanup(lambda: safe_remove(funky_name))
+ # funky_path = os.path.join(tempfile.gettempdir(), "foo bar )")
+ if OSX:
+ tmpdir = "/private/tmp"
+ else:
+ tmpdir = "/tmp"
+ fd, funky_path = tempfile.mkstemp(
+ prefix='psutil-', suffix='foo bar )', dir=tmpdir)
+ os.close(fd)
+ fd, c_file = tempfile.mkstemp(
+ prefix='psutil-', suffix='.c', dir=tmpdir)
+ os.close(fd)
+ self.addCleanup(safe_remove, c_file)
+ self.addCleanup(safe_remove, funky_path)
with open(c_file, "w") as f:
f.write("void main() { pause(); }")
- subprocess.check_call(["gcc", c_file, "-o", funky_name])
+ subprocess.check_call(["gcc", c_file, "-o", funky_path])
sproc = get_test_subprocess(
- [funky_name, "arg1", "arg2", "", "arg3", ""])
+ [funky_path, "arg1", "arg2", "", "arg3", ""])
p = psutil.Process(sproc.pid)
# ...in order to try to prevent occasional failures on travis
wait_for_pid(p.pid)
- self.assertEqual(p.name(), "foo bar )")
- self.assertEqual(p.exe(), "/tmp/foo bar )")
+ self.assertEqual(p.name(), os.path.basename(funky_path))
+ self.assertEqual(p.exe(), funky_path)
self.assertEqual(
- p.cmdline(), ["/tmp/foo bar )", "arg1", "arg2", "", "arg3", ""])
+ p.cmdline(), [funky_path, "arg1", "arg2", "", "arg3", ""])
@unittest.skipUnless(POSIX, 'posix only')
def test_uids(self):
@@ -2130,6 +2206,15 @@ class TestProcess(unittest.TestCase):
if not isinstance(d['connections'], list):
self.assertEqual(d['connections'], 'foo')
+ with mock.patch('psutil.getattr', create=True,
+ side_effect=NotImplementedError):
+ # By default APIs raising NotImplementedError are
+ # supposed to be skipped.
+ self.assertEqual(p.as_dict(), {})
+ # ...unless the user explicitly asked for some attr.
+ with self.assertRaises(NotImplementedError):
+ p.as_dict(attrs=["name"])
+
def test_halfway_terminated_process(self):
# Test that NoSuchProcess exception gets raised in case the
# process dies after we create the Process object.
@@ -2145,7 +2230,8 @@ class TestProcess(unittest.TestCase):
# if WINDOWS:
# wait_for_pid(p.pid)
self.assertFalse(p.is_running())
- self.assertFalse(p.pid in psutil.pids())
+ # self.assertFalse(p.pid in psutil.pids(), msg="retcode = %s" %
+ # retcode)
excluded_names = ['pid', 'is_running', 'wait', 'create_time']
if LINUX and not RLIMIT_SUPPORT:
@@ -2689,6 +2775,12 @@ class TestMisc(unittest.TestCase):
self.assertIn("pid=%s" % p.pid, r)
self.assertIn("terminated", r)
self.assertNotIn("name=", r)
+ with mock.patch.object(psutil.Process, "name",
+ side_effect=psutil.AccessDenied(os.getpid())):
+ p = psutil.Process()
+ r = func(p)
+ self.assertIn("pid=%s" % p.pid, r)
+ self.assertNotIn("name=", r)
def test_process__str__(self):
self.test_process__repr__(func=str)
@@ -2926,6 +3018,14 @@ class TestExampleScripts(unittest.TestCase):
self.fail('no test defined for %r script'
% os.path.join(EXAMPLES_DIR, name))
+ @unittest.skipUnless(POSIX, "UNIX only")
+ def test_executable(self):
+ for name in os.listdir(EXAMPLES_DIR):
+ if name.endswith('.py'):
+ path = os.path.join(EXAMPLES_DIR, name)
+ if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]:
+ self.fail('%r is not executable' % path)
+
def test_disk_usage(self):
self.assert_stdout('disk_usage.py')