Backed out changesets 1ad8a6674785 and ed0b6a11532d (bug 908296) for OSX mach bustage.
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 23 Aug 2013 12:18:18 -0400
changeset 144119 31aa3eb1a40d8d3e90782b7f57a1738aa219e4fa
parent 144118 954a7a7a505108988f843e1d89a740075caebe45
child 144120 e5667b1c2ad3a20457c3bb8e178b8af3fd6b5b7a
push id1
push userroot
push dateMon, 20 Oct 2014 17:29:22 +0000
bugs908296
milestone26.0a1
backs out1ad8a6674785c40cac52fe88d2e615fadc955683
ed0b6a11532d2905ce3c5c55f230b0e89b8971dd
Backed out changesets 1ad8a6674785 and ed0b6a11532d (bug 908296) for OSX mach bustage.
build/virtualenv/populate_virtualenv.py
python/psutil/CREDITS
python/psutil/HISTORY
python/psutil/MANIFEST.in
python/psutil/PKG-INFO
python/psutil/README
python/psutil/TODO
python/psutil/examples/disk_usage.py
python/psutil/examples/free.py
python/psutil/examples/iotop.py
python/psutil/examples/killall.py
python/psutil/examples/meminfo.py
python/psutil/examples/netstat.py
python/psutil/examples/nettop.py
python/psutil/examples/pmap.py
python/psutil/examples/process_detail.py
python/psutil/examples/top.py
python/psutil/examples/who.py
python/psutil/psutil/__init__.py
python/psutil/psutil/_common.py
python/psutil/psutil/_compat.py
python/psutil/psutil/_error.py
python/psutil/psutil/_psbsd.py
python/psutil/psutil/_pslinux.py
python/psutil/psutil/_psmswindows.py
python/psutil/psutil/_psosx.py
python/psutil/psutil/_psposix.py
python/psutil/psutil/_pssunos.py
python/psutil/psutil/_psutil_bsd.c
python/psutil/psutil/_psutil_bsd.h
python/psutil/psutil/_psutil_common.c
python/psutil/psutil/_psutil_common.h
python/psutil/psutil/_psutil_linux.c
python/psutil/psutil/_psutil_linux.h
python/psutil/psutil/_psutil_mswindows.c
python/psutil/psutil/_psutil_mswindows.h
python/psutil/psutil/_psutil_osx.c
python/psutil/psutil/_psutil_osx.h
python/psutil/psutil/_psutil_posix.c
python/psutil/psutil/_psutil_posix.h
python/psutil/psutil/_psutil_sunos.c
python/psutil/psutil/_psutil_sunos.h
python/psutil/psutil/error.py
python/psutil/setup.cfg
python/psutil/setup.py
python/psutil/test/__init__.py
python/psutil/test/_bsd.py
python/psutil/test/_linux.py
python/psutil/test/_osx.py
python/psutil/test/_posix.py
python/psutil/test/_sunos.py
python/psutil/test/_windows.py
python/psutil/test/test_memory_leaks.py
python/psutil/test/test_psutil.py
--- a/build/virtualenv/populate_virtualenv.py
+++ b/build/virtualenv/populate_virtualenv.py
@@ -1,16 +1,16 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This file contains code for populating the virtualenv environment for
 # Mozilla's build system. It is typically called as part of configure.
 
-from __future__ import print_function, unicode_literals
+from __future__ import print_function, unicode_literals, with_statement
 
 import distutils.sysconfig
 import os
 import shutil
 import subprocess
 import sys
 
 
--- a/python/psutil/CREDITS
+++ b/python/psutil/CREDITS
@@ -1,56 +1,53 @@
+
 Intro
 =====
 
 We would like to recognize some of the people who have been instrumental in the
 development of psutil.
 I'm sure we are forgetting some people (feel free to email us), but here is a
 short list.
 It's modeled after the Linux CREDITS file where the fields are:
 name (N), e-mail (E), web-address (W), country (C), description (D), (I) issues
 (issue tracker is at http://code.google.com/p/psutil/issues/list).
 Really thanks to all of you.
 
-Author
-======
+
+Maintainers
+===========
 
 N: Giampaolo Rodola'
 C: Italy
 E: g.rodola@gmail.com
 W: http://www.linkedin.com/in/grodola
 
-Contributors
-============
-
 N: Jay Loden
 C: NJ, USA
 E: jloden@gmail.com
-D: original co-author, initial design/bootstrap and continuing bug fixes
 W: http://www.jayloden.com
 
+
+Contributors
+============
+
 N: Jeremy Whitlock
 E: jcscoobyrs@gmail.com
 I: 125, 150, 174, 206
 
 N: wj32
 E: wj32.64@gmail.com
 D: process username() and get_connections() on Windows
 I: 114, 115
 
 N: Yan Raber
 C: Bologna, Italy
 E: yanraber@gmail.com
 D: help on Windows development
 
-N: Justin Venus
-E: justin.venus@gmail.com
-D: Solaris support
-I: 18
-
 N: Dave Daeschler
 C: USA
 E: david.daeschler@gmail.com
 D: initial design/bootstrap and continuing bug fixes
 
 N: cjgohlke
 E: cjgohlke@gmail.com
 D: Windows 64 bit support
@@ -160,23 +157,8 @@ I: 351
 
 N: John Baldwin
 E: jhb@FreeBSD.org
 I: 370
 
 N: Jan Beich
 E: jbeich@tormail.org
 I: 325
-
-N: floppymaster
-E: floppymaster@gmail.com
-I: 380
-
-N: Arfrever.FTA
-E: Arfrever.FTA@gmail.com
-I: 369, 404
-
-N: danudey
-E: danudey@gmail.com
-I: 386
-
-N: Adrien Fallou
-I: 224
--- a/python/psutil/HISTORY
+++ b/python/psutil/HISTORY
@@ -1,47 +1,10 @@
 Bug tracker at http://code.google.com/p/psutil/issues
 
-
-1.0.1 - 2013-07-12
-------------------
-
-BUG FIXES
-
- * #405: network_io_counters(pernic=True) no longer works as intended in 1.0.0.
-
-
-1.0.0 - 2013-07-10
-------------------
-
-NEW FEATURES
-
- * #18:  Solaris support (yay!)  (thanks Justin Venus)
- * #367: Process.get_connections() 'status' strings are now constants.
- * #380: test suite exits with non-zero on failure.  (patch by floppymaster)
- * #391: extensively use unittest2 module in unit tests and provide
-         workarounds if this is not installed on python < 2.7.
-
-BUG FIXES
-
- * #374: [Windows] negative memory usage reported when processes use a lot of
-         memory.
- * #379: [Linux] Process.get_memory_maps() may raise ValueError.
- * #394: [OSX] Mapped memory regions report incorrect file name.
- * #404: [Linux] sched_*affinity() are implicitly declared.  (patch by Arfrever)
-
-API CHANGES
-
- * Process.get_connections() 'status' field is no longer a string but a constant
-   object (psutil.CONN_*).
- * Process.get_connections() 'local_address' and 'remote_address' fields renamed
-   to 'laddr' and 'raddr'.
- * psutil.network_io_counters() renamed to psutil.net_io_counters().
-
-
 0.7.1 - 2013-05-03
 ------------------
 
 BUG FIXES:
 
  * #325: [BSD] psutil.virtual_memory() can raise SystemError.
          (patch by Jan Beich)
  * #370: [BSD] Process.get_connections() requires root.  (patch by John Baldwin)
--- a/python/psutil/MANIFEST.in
+++ b/python/psutil/MANIFEST.in
@@ -1,10 +1,9 @@
 include CREDITS
 include HISTORY
 include LICENSE
 include MANIFEST.in
 include README
-include TODO
 include setup.py
 recursive-include psutil *.py *.c *.h
 recursive-include test *.py
 recursive-include examples *.py
--- a/python/psutil/PKG-INFO
+++ b/python/psutil/PKG-INFO
@@ -1,17 +1,17 @@
 Metadata-Version: 1.1
 Name: psutil
-Version: 1.0.1
+Version: 0.7.1
 Summary: A process and system utilities module for Python
 Home-page: http://code.google.com/p/psutil/
 Author: Giampaolo Rodola
 Author-email: g.rodola <at> gmail <dot> com
 License: License :: OSI Approved :: BSD License
-Download-URL: http://psutil.googlecode.com/files/psutil-1.0.1.tar.gz
+Download-URL: http://psutil.googlecode.com/files/psutil-0.7.1.tar.gz
 Description: ===========
         Quick links
         ===========
         
         * `Home page <http://code.google.com/p/psutil>`_
         * `Download <http://code.google.com/p/psutil/downloads/list>`_
         * `Documentation <http://code.google.com/p/psutil/wiki/Documentation>`_
         
@@ -20,55 +20,47 @@ Description: ===========
         =======
         
         psutil is a module providing an interface for retrieving information on all
         running processes and system utilization (CPU, memory, disks, network, users) in
         a portable way by using Python, implementing many functionalities offered by
         command line tools such as:  **ps, top, df, kill, free, lsof, free, netstat,
         ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
         
-        It currently supports **Linux**, **Windows**, **OSX**, **FreeBSD**,
-        **Sun Solaris** both **32-bit** and **64-bit** with Python versions from **2.4**
-        to **3.3** by using a single code base.
+        It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
+        **32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
+        a single code base.
         
         ==============
         Example usages
         ==============
         
         CPU
         ===
         
         >>> import psutil
         >>> psutil.cpu_times()
         cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
-                 iowait=629.509, irq=0.0, softirq=19.422, steal=0.0, guest=0, nice=0.0)
+                 iowait=629.509, irq=0.0, softirq=19.422)
         >>>
         >>> for x in range(3):
         ...     psutil.cpu_percent(interval=1)
         ...
         4.0
         5.9
         3.8
         >>>
         >>> for x in range(3):
         ...     psutil.cpu_percent(interval=1, percpu=True)
         ...
         [4.0, 6.9]
         [7.0, 8.5]
         [1.2, 9.0]
         >>>
-        >>> for x in range(3):
-        ...     psutil.cpu_times_percent(interval=1, percpu=False)
-        ...
-        cpupercent(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0,
-                   softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
-        cpupercent(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0,
-                   softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
-        cpupercent(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0,
-                   softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+        
         
         Memory
         ======
         
         >>> psutil.virtual_memory()
         vmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L,
              free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L,
              cached=1251086336)
@@ -92,32 +84,31 @@ Description: ===========
         iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
                write_bytes=24081764352, read_time=5023392, write_time=63199568)
         >>>
         
         
         Network
         =======
         
-        >>> psutil.net_io_counters(pernic=True)
+        >>> psutil.network_io_counters(pernic=True)
         {'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
                       packets_sent=453698, packets_recv=453698),
          'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
                         packets_sent=3605828, packets_recv=4096685)}
         >>>
         
-        Other system info
-        =================
+        
+        Users
+        =====
         
         >>> psutil.get_users()
         [user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
          user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
         >>>
-        >>> psutil.get_boot_time()
-        1365519115.0
         
         
         Process management
         ==================
         
         >>> import psutil
         >>> psutil.get_pid_list()
         [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
@@ -176,24 +167,24 @@ Description: ===========
         >>>
         >>> p.get_io_counters()
         io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
         >>>
         >>> p.get_open_files()
         [openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
         >>>
         >>> p.get_connections()
-        [connection(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776),
-                    raddr=('93.186.135.91', 80), status='ESTABLISHED'),
-         connection(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761),
-                    raddr=('72.14.234.100', 80), status='CLOSING'),
-         connection(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759),
-                    raddr=('72.14.234.104', 80), status='ESTABLISHED'),
-         connection(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314),
-                    raddr=('72.14.234.83', 443), status='SYN_SENT')]
+        [connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
+                    remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
+         connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
+                    remote_address=('72.14.234.100', 80), status='CLOSING'),
+         connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
+                    remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
+         connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
+                    remote_address=('72.14.234.83', 443), status='SYN_SENT')]
         >>>
         >>> p.get_num_threads()
         4
         >>> p.get_num_fds()
         8
         >>> p.get_threads()
         [thread(id=5234, user_time=22.5, system_time=9.2891),
          thread(id=5235, user_time=0.0, system_time=0.0),
@@ -230,17 +221,16 @@ Platform: Platform Independent
 Classifier: Development Status :: 5 - Production/Stable
 Classifier: Environment :: Console
 Classifier: Operating System :: MacOS :: MacOS X
 Classifier: Operating System :: Microsoft
 Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
 Classifier: Operating System :: POSIX
 Classifier: Operating System :: POSIX :: Linux
 Classifier: Operating System :: POSIX :: BSD :: FreeBSD
-Classifier: Operating System :: POSIX :: SunOS/Solaris
 Classifier: Operating System :: OS Independent
 Classifier: Programming Language :: C
 Classifier: Programming Language :: Python
 Classifier: Programming Language :: Python :: 2
 Classifier: Programming Language :: Python :: 2.4
 Classifier: Programming Language :: Python :: 2.5
 Classifier: Programming Language :: Python :: 2.6
 Classifier: Programming Language :: Python :: 2.7
--- a/python/psutil/README
+++ b/python/psutil/README
@@ -11,55 +11,47 @@ Summary
 =======
 
 psutil is a module providing an interface for retrieving information on all
 running processes and system utilization (CPU, memory, disks, network, users) in
 a portable way by using Python, implementing many functionalities offered by
 command line tools such as:  **ps, top, df, kill, free, lsof, free, netstat,
 ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
 
-It currently supports **Linux**, **Windows**, **OSX**, **FreeBSD**,
-**Sun Solaris** both **32-bit** and **64-bit** with Python versions from **2.4**
-to **3.3** by using a single code base.
+It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
+**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
+a single code base.
 
 ==============
 Example usages
 ==============
 
 CPU
 ===
 
 >>> import psutil
 >>> psutil.cpu_times()
 cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
-         iowait=629.509, irq=0.0, softirq=19.422, steal=0.0, guest=0, nice=0.0)
+         iowait=629.509, irq=0.0, softirq=19.422)
 >>>
 >>> for x in range(3):
 ...     psutil.cpu_percent(interval=1)
 ...
 4.0
 5.9
 3.8
 >>>
 >>> for x in range(3):
 ...     psutil.cpu_percent(interval=1, percpu=True)
 ...
 [4.0, 6.9]
 [7.0, 8.5]
 [1.2, 9.0]
 >>>
->>> for x in range(3):
-...     psutil.cpu_times_percent(interval=1, percpu=False)
-...
-cpupercent(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0,
-           softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
-cpupercent(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0,
-           softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
-cpupercent(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0,
-           softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+
 
 Memory
 ======
 
 >>> psutil.virtual_memory()
 vmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L,
      free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L,
      cached=1251086336)
@@ -83,32 +75,31 @@ usage(total=21378641920, used=4809781248
 iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
        write_bytes=24081764352, read_time=5023392, write_time=63199568)
 >>>
 
 
 Network
 =======
 
->>> psutil.net_io_counters(pernic=True)
+>>> psutil.network_io_counters(pernic=True)
 {'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
               packets_sent=453698, packets_recv=453698),
  'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
                 packets_sent=3605828, packets_recv=4096685)}
 >>>
 
-Other system info
-=================
+
+Users
+=====
 
 >>> psutil.get_users()
 [user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
  user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
 >>>
->>> psutil.get_boot_time()
-1365519115.0
 
 
 Process management
 ==================
 
 >>> import psutil
 >>> psutil.get_pid_list()
 [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
@@ -167,24 +158,24 @@ meminfo(rss=9662464, vms=49192960, share
 >>>
 >>> p.get_io_counters()
 io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
 >>>
 >>> p.get_open_files()
 [openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
 >>>
 >>> p.get_connections()
-[connection(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776),
-            raddr=('93.186.135.91', 80), status='ESTABLISHED'),
- connection(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761),
-            raddr=('72.14.234.100', 80), status='CLOSING'),
- connection(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759),
-            raddr=('72.14.234.104', 80), status='ESTABLISHED'),
- connection(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314),
-            raddr=('72.14.234.83', 443), status='SYN_SENT')]
+[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
+            remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
+ connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
+            remote_address=('72.14.234.100', 80), status='CLOSING'),
+ connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
+            remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
+ connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
+            remote_address=('72.14.234.83', 443), status='SYN_SENT')]
 >>>
 >>> p.get_num_threads()
 4
 >>> p.get_num_fds()
 8
 >>> p.get_threads()
 [thread(id=5234, user_time=22.5, system_time=9.2891),
  thread(id=5235, user_time=0.0, system_time=0.0),
deleted file mode 100644
--- a/python/psutil/TODO
+++ /dev/null
@@ -1,95 +0,0 @@
-TODO
-====
-
-A collection of ideas and notes about stuff to implement in future versions.
-"#NNN" occurrences refer to bug tracker issues at:
-https://code.google.com/p/psutil/issues/list
-
-
-HIGHER PRIORITY
-===============
-
- * #387: system-wide connections (netstat).
- * OpenBSD support.
-
- * #371: CPU temperature (apparently OSX and Linux only; on Linux it requires
-   lm-sensors lib).
-
- * #250: net ifaces speed.
-
- * (Linux) resource limit get/set - see man prlimit.
-
- * Process.name on Windows is slow:
-   http://stackoverflow.com/questions/6587036/
-
- * Windows binary for Python 3.3 64-bit.
-
- * #269: expose network ifaces RX/TW queues.
-
-
-LOWER PRIORITY
-==============
-
- * #355: Android support.
-
- * #276: GNU/Hurd support.
-
- * NetBSD support?
-
- * DranflyBSD support?
-
- * AIX support?
-
- * examples/pidof.py (same as 'pidof' cli tool)
-
- * examples/pstree.py (same as 'pstree' cli tool)
-    * get_threads() should also return thread names in order to implement it
-
- * examples/taskmgr-gui.py (using tk).
-
- * system-wide # open file descriptors:
-    * https://jira.hyperic.com/browse/SIGAR-30
-    * http://www.netadmintools.com/part295.html
-
- * Number of system threads.
-    * Windows: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684824(v=vs.85).aspx
-
- * #357: what CPU a process is on.
-
- * thread names:
-    * https://code.google.com/p/plcrashreporter/issues/detail?id=65
-
-
-DEBATABLE
-=========
-
- * [Linux]: process cgroups (http://en.wikipedia.org/wiki/Cgroups). They look
-   similar to prlimit() in terms of functionality but uglier (they should allow
-   limiting per-process network IO resources though, which is great). Needs
-   further reading.
-
- * cpu_percent(): current default interval is 0.1 so that by default it will
-   produce a meaningful value. It represents a trap in case the user iterates
-   over multiple processes though, as it introduces a big slowdown.
-   Should it default to 0.0?
-
- * Rename connection ntuple's fields 'local_address', 'remote_address' to
-   'laddr', 'raddr'  (note in accordance with http://bugs.python.org/issue17675)
-
- * Process per-cpus percent (XXX Windows only?), see:
-   https://groups.google.com/forum/?fromgroups#!topic/psutil/ErrKTxAbu50
-
- * Should we expose OS constants (psutil.WINDOWS, psutil.OSX etc.)?
-
- * Python 3.3. exposed different sched.h functions:
-   http://docs.python.org/dev/whatsnew/3.3.html#os
-   http://bugs.python.org/issue12655
-   http://docs.python.org/dev/library/os.html#interface-to-the-scheduler
-   It might be worth to take a look and figure out whether we can include some
-   of those in psutil.
-   Also, we can probably reimplement wait_pid() on POSIX which is currently
-   implemented as a busy-loop.
-
- * Certain systems (XXX figure out which ones exactly) provide CPU times about
-   process children. On those systems Process.get_cpu_times() might return
-   a (user, system, user_children, system_children) ntuple.
--- a/python/psutil/examples/disk_usage.py
+++ b/python/psutil/examples/disk_usage.py
@@ -1,20 +1,19 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 List all mounted disk partitions a-la "df -h" command.
 """
 
 import sys
-import os
 import psutil
 from psutil._compat import print_
 
 def bytes2human(n):
     # http://code.activestate.com/recipes/578019
     # >>> bytes2human(10000)
     # '9.8K'
     # >>> bytes2human(100001221)
@@ -29,19 +28,16 @@ def bytes2human(n):
             return '%.1f%s' % (value, s)
     return "%sB" % n
 
 
 def main():
     templ = "%-17s %8s %8s %8s %5s%% %9s  %s"
     print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
     for part in psutil.disk_partitions(all=False):
-        if os.name == 'nt' and 'cdrom' in part.opts:
-            # may raise ENOENT if there's no cd-rom in the drive
-            continue
         usage = psutil.disk_usage(part.mountpoint)
         print_(templ % (part.device,
                         bytes2human(usage.total),
                         bytes2human(usage.used),
                         bytes2human(usage.free),
                         int(usage.percent),
                         part.fstype,
                         part.mountpoint))
--- a/python/psutil/examples/free.py
+++ b/python/psutil/examples/free.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'free' cmdline utility.
 """
 
 import psutil
--- a/python/psutil/examples/iotop.py
+++ b/python/psutil/examples/iotop.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of iotop (http://guichaz.free.fr/iotop/) showing real time
 disk I/O statistics.
 
 It works on Linux only (FreeBSD and OSX are missing support for IO
--- a/python/psutil/examples/killall.py
+++ b/python/psutil/examples/killall.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Kill a process by name.
 """
 
 import os
--- a/python/psutil/examples/meminfo.py
+++ b/python/psutil/examples/meminfo.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Print system memory information.
 """
 
 import psutil
--- a/python/psutil/examples/netstat.py
+++ b/python/psutil/examples/netstat.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'netstat'.
 """
 
 import socket
@@ -28,24 +28,22 @@ def main():
                     "Program name"))
     for p in psutil.process_iter():
         name = '?'
         try:
             name = p.name
             cons = p.get_connections(kind='inet')
         except psutil.AccessDenied:
             print_(templ % (AD, AD, AD, AD, p.pid, name))
-        except psutil.NoSuchProcess:
-            continue
         else:
             for c in cons:
                 raddr = ""
-                laddr = "%s:%s" % (c.laddr)
-                if c.raddr:
-                    raddr = "%s:%s" % (c.raddr)
+                laddr = "%s:%s" % (c.local_address)
+                if c.remote_address:
+                    raddr = "%s:%s" % (c.remote_address)
                 print_(templ % (proto_map[(c.family, c.type)],
                                 laddr,
                                 raddr,
                                 str(c.status),
                                 p.pid,
                                 name[:15]))
 
 if __name__ == '__main__':
--- a/python/psutil/examples/nettop.py
+++ b/python/psutil/examples/nettop.py
@@ -1,13 +1,13 @@
 #!/usr/bin/env python
 #
 # $Id: iotop.py 1160 2011-10-14 18:50:36Z g.rodola@gmail.com $
 #
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Shows real-time network statistics.
 
 Author: Giampaolo Rodola' <g.rodola@gmail.com>
 """
@@ -67,22 +67,22 @@ def bytes2human(n):
     for s in reversed(symbols):
         if n >= prefix[s]:
             value = float(n) / prefix[s]
             return '%.2f %s' % (value, s)
     return '%.2f B' % (n)
 
 def poll(interval):
     """Retrieve raw stats within an interval window."""
-    tot_before = psutil.net_io_counters()
-    pnic_before = psutil.net_io_counters(pernic=True)
+    tot_before = psutil.network_io_counters()
+    pnic_before = psutil.network_io_counters(pernic=True)
     # sleep some time
     time.sleep(interval)
-    tot_after = psutil.net_io_counters()
-    pnic_after = psutil.net_io_counters(pernic=True)
+    tot_after = psutil.network_io_counters()
+    pnic_after = psutil.network_io_counters(pernic=True)
     return (tot_before, tot_after, pnic_before, pnic_after)
 
 
 def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
     """Print stats on screen."""
     global lineno
 
     # totals
--- a/python/psutil/examples/pmap.py
+++ b/python/psutil/examples/pmap.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'pmap' utility on Linux, 'vmmap' on OSX and 'procstat -v' on BSD.
 Report memory map of a process.
 """
 
--- a/python/psutil/examples/process_detail.py
+++ b/python/psutil/examples/process_detail.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 Print detailed information about a process.
 
 Author: Giampaolo Rodola' <g.rodola@gmail.com>
 """
@@ -50,42 +50,40 @@ def run(pid):
         if p.parent:
             parent = '(%s)' % p.parent.name
         else:
             parent = ''
     except psutil.Error:
         parent = ''
     started = datetime.datetime.fromtimestamp(pinfo['create_time']
                                                 ).strftime('%Y-%M-%d %H:%M')
-    io = pinfo.get('io_counters', ACCESS_DENIED)
+    io = pinfo.get('io_counters', None)
     mem = '%s%% (resident=%s, virtual=%s) ' % (
                                       round(pinfo['memory_percent'], 1),
                                       convert_bytes(pinfo['memory_info'].rss),
                                       convert_bytes(pinfo['memory_info'].vms))
     children = p.get_children()
 
     print_('pid', pinfo['pid'])
     print_('name', pinfo['name'])
     print_('exe', pinfo['exe'])
     print_('parent', '%s %s' % (pinfo['ppid'], parent))
     print_('cmdline', ' '.join(pinfo['cmdline']))
     print_('started', started)
     print_('user', pinfo['username'])
-    if os.name == 'posix' and pinfo['uids'] and pinfo['gids']:
+    if os.name == 'posix':
         print_('uids', 'real=%s, effective=%s, saved=%s' % pinfo['uids'])
-    if os.name == 'posix' and pinfo['gids']:
         print_('gids', 'real=%s, effective=%s, saved=%s' % pinfo['gids'])
-    if os.name == 'posix':
         print_('terminal', pinfo['terminal'] or '')
     if hasattr(p, 'getcwd'):
         print_('cwd', pinfo['cwd'])
     print_('memory', mem)
     print_('cpu', '%s%% (user=%s, system=%s)' % (pinfo['cpu_percent'],
-                                    getattr(pinfo['cpu_times'], 'user', '?'),
-                                    getattr(pinfo['cpu_times'], 'system', '?')))
+                                                 pinfo['cpu_times'].user,
+                                                 pinfo['cpu_times'].system))
     print_('status', pinfo['status'])
     print_('niceness', pinfo['nice'])
     print_('num threads', pinfo['num_threads'])
     if io != ACCESS_DENIED:
         print_('I/O', 'bytes-read=%s, bytes-written=%s' % \
                                                (convert_bytes(io.read_bytes),
                                                 convert_bytes(io.write_bytes)))
     if children:
@@ -107,21 +105,21 @@ def run(pid):
         print_('open connections', '')
         for conn in pinfo['connections']:
             if conn.type == socket.SOCK_STREAM:
                 type = 'TCP'
             elif conn.type == socket.SOCK_DGRAM:
                 type = 'UDP'
             else:
                 type = 'UNIX'
-            lip, lport = conn.laddr
-            if not conn.raddr:
+            lip, lport = conn.local_address
+            if not conn.remote_address:
                 rip, rport = '*', '*'
             else:
-                rip, rport = conn.raddr
+                rip, rport = conn.remote_address
             print_('',  '%s:%s -> %s:%s type=%s status=%s' \
                          % (lip, lport, rip, rport, type, conn.status))
 
 def main(argv=None):
     if argv is None:
         argv = sys.argv
     if len(argv) == 1:
         sys.exit(run(os.getpid()))
--- a/python/psutil/examples/top.py
+++ b/python/psutil/examples/top.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of top / htop.
 
 Author: Giampaolo Rodola' <g.rodola@gmail.com>
 """
@@ -162,22 +162,18 @@ def refresh_window(procs, procs_status):
         else:
             ctime = ''
         if p.dict['memory_percent'] is not None:
             p.dict['memory_percent'] = round(p.dict['memory_percent'], 1)
         else:
             p.dict['memory_percent'] = ''
         if p.dict['cpu_percent'] is None:
             p.dict['cpu_percent'] = ''
-        if p.dict['username']:
-            username = p.dict['username'][:8]
-        else:
-            username = ""
         line = templ % (p.pid,
-                        username,
+                        p.dict['username'][:8],
                         p.dict['nice'],
                         bytes2human(getattr(p.dict['memory_info'], 'vms', 0)),
                         bytes2human(getattr(p.dict['memory_info'], 'rss', 0)),
                         p.dict['cpu_percent'],
                         p.dict['memory_percent'],
                         ctime,
                         p.dict['name'] or '',
                         )
--- a/python/psutil/examples/who.py
+++ b/python/psutil/examples/who.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A clone of 'who' command; print information about users who are
 currently logged in.
 """
 
--- a/python/psutil/psutil/__init__.py
+++ b/python/psutil/psutil/__init__.py
@@ -1,44 +1,41 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """psutil is a module providing convenience functions for managing
 processes and gather system information in a portable way by using
 Python.
 """
 
 from __future__ import division
 
-__version__ = "1.0.1"
+__version__ = "0.7.1"
 version_info = tuple([int(num) for num in __version__.split('.')])
 
 __all__ = [
     # exceptions
     "Error", "NoSuchProcess", "AccessDenied", "TimeoutExpired",
     # constants
     "NUM_CPUS", "TOTAL_PHYMEM", "BOOT_TIME",
     "version_info", "__version__",
     "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
     "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
     "STATUS_WAKING", "STATUS_LOCKED",
-    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
-    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
-    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
     # classes
     "Process", "Popen",
     # functions
     "pid_exists", "get_pid_list", "process_iter",                   # proc
     "virtual_memory", "swap_memory",                                # memory
     "cpu_times", "cpu_percent", "cpu_times_percent",                # cpu
-    "net_io_counters",                                              # network
+    "network_io_counters",                                          # network
     "disk_io_counters", "disk_partitions", "disk_usage",            # disk
     "get_users", "get_boot_time",                                   # others
     ]
 
 import sys
 import os
 import time
 import signal
@@ -57,22 +54,17 @@ from psutil._compat import (property, ca
 from psutil._common import (deprecated as _deprecated,
                             nt_disk_iostat as _nt_disk_iostat,
                             nt_net_iostat as _nt_net_iostat,
                             nt_sysmeminfo as _nt_sysmeminfo,
                             isfile_strict as _isfile_strict)
 from psutil._common import (STATUS_RUNNING, STATUS_IDLE, STATUS_SLEEPING,
                             STATUS_DISK_SLEEP, STATUS_STOPPED,
                             STATUS_TRACING_STOP, STATUS_ZOMBIE, STATUS_DEAD,
-                            STATUS_WAKING, STATUS_LOCKED,
-                            #
-                            CONN_ESTABLISHED, CONN_SYN_SENT, CONN_SYN_RECV,
-                            CONN_FIN_WAIT1, CONN_FIN_WAIT2, CONN_TIME_WAIT,
-                            CONN_CLOSE, CONN_CLOSE_WAIT, CONN_LAST_ACK,
-                            CONN_LISTEN, CONN_CLOSING, CONN_NONE)
+                            STATUS_WAKING, STATUS_LOCKED)
 
 # import the appropriate module for our platform only
 if sys.platform.startswith("linux"):
     import psutil._pslinux as _psplatform
     from psutil._pslinux import (phymem_buffers,
                                  cached_phymem,
                                  IOPRIO_CLASS_NONE,
                                  IOPRIO_CLASS_RT,
@@ -83,30 +75,24 @@ if sys.platform.startswith("linux"):
 
 elif sys.platform.startswith("win32"):
     import psutil._psmswindows as _psplatform
     from psutil._psmswindows import (ABOVE_NORMAL_PRIORITY_CLASS,
                                      BELOW_NORMAL_PRIORITY_CLASS,
                                      HIGH_PRIORITY_CLASS,
                                      IDLE_PRIORITY_CLASS,
                                      NORMAL_PRIORITY_CLASS,
-                                     REALTIME_PRIORITY_CLASS,
-                                     CONN_DELETE_TCB)
+                                     REALTIME_PRIORITY_CLASS)
 
 elif sys.platform.startswith("darwin"):
     import psutil._psosx as _psplatform
 
 elif sys.platform.startswith("freebsd"):
     import psutil._psbsd as _psplatform
 
-elif sys.platform.startswith("sunos"):
-    import psutil._pssunos as _psplatform
-    from psutil._pssunos import (CONN_IDLE,
-                                 CONN_BOUND)
-
 else:
     raise NotImplementedError('platform %s is not supported' % sys.platform)
 
 __all__.extend(_psplatform.__extra__all__)
 
 NUM_CPUS = _psplatform.NUM_CPUS
 BOOT_TIME = _psplatform.BOOT_TIME
 TOTAL_PHYMEM = _psplatform.TOTAL_PHYMEM
@@ -309,21 +295,19 @@ class Process(object):
     def exe(self):
         """The process executable path. May also be an empty string."""
         def guess_it(fallback):
             # try to guess exe from cmdline[0] in absence of a native
             # exe representation
             cmdline = self.cmdline
             if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                 exe = cmdline[0]  # the possible exe
-                # Attempt to guess only in case of an absolute path.
-                # It is not safe otherwise as the process might have
-                # changed cwd.
-                if os.path.isabs(exe) and os.path.isfile(exe) \
-                and os.access(exe, os.X_OK):
+                rexe = os.path.realpath(exe)  # ...in case it's a symlink
+                if os.path.isabs(rexe) and os.path.isfile(rexe) \
+                and os.access(rexe, os.X_OK):
                     return exe
             if isinstance(fallback, AccessDenied):
                 raise fallback
             return fallback
 
         try:
             exe = self._platform_impl.get_process_exe()
         except AccessDenied:
@@ -1233,17 +1217,17 @@ def disk_io_counters(perdisk=False):
         return rawdict
     else:
         return _nt_disk_iostat(*[sum(x) for x in zip(*rawdict.values())])
 
 # =====================================================================
 # --- network related functions
 # =====================================================================
 
-def net_io_counters(pernic=False):
+def network_io_counters(pernic=False):
     """Return network I/O statistics as a namedtuple including
     the following attributes:
 
      - bytes_sent:   number of bytes sent
      - bytes_recv:   number of bytes received
      - packets_sent: number of packets sent
      - packets_recv: number of packets received
      - errin:        total number of errors while receiving
@@ -1252,17 +1236,17 @@ def net_io_counters(pernic=False):
      - dropout:      total number of outgoing packets which were dropped
                      (always 0 on OSX and BSD)
 
     If pernic is True return the same information for every
     network interface installed on the system as a dictionary
     with network interface names as the keys and the namedtuple
     described above as the values.
     """
-    rawdict = _psplatform.net_io_counters()
+    rawdict = _psplatform.network_io_counters()
     if not rawdict:
         raise RuntimeError("couldn't find any network interface")
     if pernic:
         for nic, fields in rawdict.items():
             rawdict[nic] = _nt_net_iostat(*fields)
         return rawdict
     else:
         return _nt_net_iostat(*[sum(x) for x in zip(*rawdict.values())])
@@ -1328,33 +1312,28 @@ def total_virtmem():
 @_deprecated("psutil.virtmem_usage().used")
 def used_virtmem():
     return virtmem_usage().used
 
 @_deprecated("psutil.virtmem_usage().free")
 def avail_virtmem():
     return virtmem_usage().free
 
-@_deprecated("psutil.net_io_counters()")
-def network_io_counters(pernic=False):
-    return net_io_counters(pernic)
-
 def test():
     """List info of all currently running processes emulating ps aux
     output.
     """
     import datetime
     from psutil._compat import print_
 
     today_day = datetime.date.today()
     templ = "%-10s %5s %4s %4s %7s %7s %-13s %5s %7s  %s"
-    attrs = ['pid', 'get_cpu_percent', 'get_memory_percent', 'name',
+    attrs = ['pid', 'username', 'get_cpu_percent', 'get_memory_percent', 'name',
              'get_cpu_times', 'create_time', 'get_memory_info']
     if os.name == 'posix':
-        attrs.append('uids')
         attrs.append('terminal')
     print_(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "START",
                     "TIME", "COMMAND"))
     for p in sorted(process_iter(), key=lambda p: p.pid):
         try:
             pinfo = p.as_dict(attrs, ad_value='')
         except NoSuchProcess:
             pass
@@ -1363,28 +1342,17 @@ def test():
                 ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
                 if ctime.date() == today_day:
                     ctime = ctime.strftime("%H:%M")
                 else:
                     ctime = ctime.strftime("%b%d")
             else:
                 ctime = ''
             cputime = time.strftime("%M:%S", time.localtime(sum(pinfo['cpu_times'])))
-            try:
-                user = p.username
-            except KeyError:
-                if os.name == 'posix':
-                    if pinfo['uids']:
-                        user = str(pinfo['uids'].real)
-                    else:
-                        user = ''
-                else:
-                    raise
-            except Error:
-                user = ''
+            user = pinfo['username']
             if os.name == 'nt' and '\\' in user:
                 user = user.split('\\')[1]
             vms = pinfo['memory_info'] and \
                   int(pinfo['memory_info'].vms / 1024) or '?'
             rss = pinfo['memory_info'] and \
                   int(pinfo['memory_info'].rss / 1024) or '?'
             memp = pinfo['memory_percent'] and \
                    round(pinfo['memory_percent'], 1) or '?'
--- a/python/psutil/psutil/_common.py
+++ b/python/psutil/psutil/_common.py
@@ -1,11 +1,11 @@
 #/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Common objects shared by all _ps* modules."""
 
 from __future__ import division
 import sys
 import os
@@ -127,29 +127,16 @@ STATUS_TRACING_STOP = constant(4, "traci
 STATUS_ZOMBIE = constant(5, "zombie")
 STATUS_DEAD = constant(6, "dead")
 STATUS_WAKE_KILL = constant(7, "wake kill")
 STATUS_WAKING = constant(8, "waking")
 STATUS_IDLE = constant(9, "idle")  # BSD
 STATUS_LOCKED = constant(10, "locked")  # BSD
 STATUS_WAITING = constant(11, "waiting")  # BSD
 
-CONN_ESTABLISHED = constant(0, "ESTABLISHED")
-CONN_SYN_SENT = constant(1, "SYN_SENT")
-CONN_SYN_RECV = constant(2, "SYN_RECV")
-CONN_FIN_WAIT1 = constant(3, "FIN_WAIT1")
-CONN_FIN_WAIT2 = constant(4, "FIN_WAIT2")
-CONN_TIME_WAIT = constant(5, "TIME_WAIT")
-CONN_CLOSE = constant(6, "CLOSE")
-CONN_CLOSE_WAIT = constant(7, "CLOSE_WAIT")
-CONN_LAST_ACK = constant(8, "LAST_ACK")
-CONN_LISTEN = constant(9, "LISTEN")
-CONN_CLOSING = constant(10, "CLOSING")
-CONN_NONE = constant(20, "NONE")
-
 # --- Process.get_connections() 'kind' parameter mapping
 
 import socket
 from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
 AF_INET6 = getattr(socket, 'AF_INET6', None)
 AF_UNIX = getattr(socket, 'AF_UNIX', None)
 
 conn_tmap = {
@@ -189,30 +176,15 @@ nt_net_iostat = namedtuple('iostat',
     'bytes_sent bytes_recv packets_sent packets_recv errin errout dropin dropout')
 nt_disk_iostat = namedtuple('iostat', 'read_count write_count read_bytes write_bytes read_time write_time')
 nt_user = namedtuple('user', 'name terminal host started')
 
 # processes
 nt_meminfo = namedtuple('meminfo', 'rss vms')
 nt_cputimes = namedtuple('cputimes', 'user system')
 nt_openfile = namedtuple('openfile', 'path fd')
+nt_connection = namedtuple('connection', 'fd family type local_address remote_address status')
 nt_thread = namedtuple('thread', 'id user_time system_time')
 nt_uids = namedtuple('user', 'real effective saved')
 nt_gids = namedtuple('group', 'real effective saved')
 nt_io = namedtuple('io', 'read_count write_count read_bytes write_bytes')
 nt_ionice = namedtuple('ionice', 'ioclass value')
 nt_ctxsw = namedtuple('amount', 'voluntary involuntary')
-
-class nt_connection(namedtuple('connection',
-                               'fd family type laddr raddr status')):
-        __slots__ = ()
-
-        @property
-        def local_address(self):
-            warnings.warn("'local_address' field is deprecated; use 'laddr'" \
-                          "instead", category=DeprecationWarning, stacklevel=2)
-            return self.laddr
-
-        @property
-        def remote_address(self):
-            warnings.warn("'remote_address' field is deprecated; use 'raddr'" \
-                          "instead", category=DeprecationWarning, stacklevel=2)
-            return self.raddr
--- a/python/psutil/psutil/_compat.py
+++ b/python/psutil/psutil/_compat.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Module which provides compatibility with older Python versions."""
 
 __all__ = ["PY3", "int", "long", "xrange", "exec_", "callable",
            "namedtuple", "property", "defaultdict"]
 
--- a/python/psutil/psutil/_error.py
+++ b/python/psutil/psutil/_error.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """psutil exception classes.
 Not supposed to be used / imported directly.
 Instead use psutil.NoSuchProcess, etc.
 """
 
--- a/python/psutil/psutil/_psbsd.py
+++ b/python/psutil/psutil/_psbsd.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """FreeBSD platform implementation."""
 
 import errno
 import os
 import sys
@@ -133,17 +133,17 @@ def get_system_users():
             continue  # reboot or shutdown
         nt = nt_user(user, tty or None, hostname, tstamp)
         retlist.append(nt)
     return retlist
 
 get_pid_list = _psutil_bsd.get_pid_list
 pid_exists = _psposix.pid_exists
 get_disk_usage = _psposix.get_disk_usage
-net_io_counters = _psutil_bsd.get_net_io_counters
+network_io_counters = _psutil_bsd.get_network_io_counters
 disk_io_counters = _psutil_bsd.get_disk_io_counters
 
 
 def wrap_exceptions(fun):
     """Decorator which translates bare OSError exceptions into
     NoSuchProcess and AccessDenied.
     """
     @wraps(fun)
@@ -164,30 +164,16 @@ def wrap_exceptions(fun):
     _psutil_bsd.SSLEEP : STATUS_SLEEPING,
     _psutil_bsd.SRUN : STATUS_RUNNING,
     _psutil_bsd.SIDL : STATUS_IDLE,
     _psutil_bsd.SWAIT : STATUS_WAITING,
     _psutil_bsd.SLOCK : STATUS_LOCKED,
     _psutil_bsd.SZOMB : STATUS_ZOMBIE,
 }
 
-_conn_status_map = {_psutil_bsd.TCPS_ESTABLISHED : CONN_ESTABLISHED,
-                    _psutil_bsd.TCPS_SYN_SENT : CONN_SYN_SENT,
-                    _psutil_bsd.TCPS_SYN_RECEIVED : CONN_SYN_RECV,
-                    _psutil_bsd.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
-                    _psutil_bsd.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
-                    _psutil_bsd.TCPS_TIME_WAIT : CONN_TIME_WAIT,
-                    _psutil_bsd.TCPS_CLOSED : CONN_CLOSE,
-                    _psutil_bsd.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
-                    _psutil_bsd.TCPS_LAST_ACK : CONN_LAST_ACK,
-                    _psutil_bsd.TCPS_LISTEN : CONN_LISTEN,
-                    _psutil_bsd.TCPS_CLOSING : CONN_CLOSING,
-                    _psutil_bsd.PSUTIL_CONN_NONE : CONN_NONE,
-                    }
-
 
 class Process(object):
     """Wrapper class around underlying C implementation."""
 
     __slots__ = ["pid", "_process_name"]
 
     def __init__(self, pid):
         self.pid = pid
@@ -307,24 +293,18 @@ class Process(object):
     def get_connections(self, kind='inet'):
         """Return etwork connections opened by a process as a list of
         namedtuples.
         """
         if kind not in conn_tmap:
             raise ValueError("invalid %r kind argument; choose between %s"
                              % (kind, ', '.join([repr(x) for x in conn_tmap])))
         families, types = conn_tmap[kind]
-        rawlist = _psutil_bsd.get_process_connections(self.pid, families, types)
-        ret = []
-        for item in rawlist:
-            fd, fam, type, laddr, raddr, status = item
-            status = _conn_status_map[status]
-            nt = nt_connection(fd, fam, type, laddr, raddr, status)
-            ret.append(nt)
-        return ret
+        ret = _psutil_bsd.get_process_connections(self.pid, families, types)
+        return [nt_connection(*conn) for conn in ret]
 
     @wrap_exceptions
     def process_wait(self, timeout=None):
         try:
             return _psposix.wait_pid(self.pid, timeout)
         except TimeoutExpired:
             raise TimeoutExpired(self.pid, self._process_name)
 
--- a/python/psutil/psutil/_pslinux.py
+++ b/python/psutil/psutil/_pslinux.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Linux platform implementation."""
 
 from __future__ import division
 
 import os
@@ -20,24 +20,18 @@ import warnings
 import _psutil_posix
 import _psutil_linux
 from psutil import _psposix
 from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
 from psutil._common import *
 from psutil._compat import PY3, xrange, long, namedtuple, wraps
 
 __extra__all__ = [
-    # io prio constants
     "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
     "IOPRIO_CLASS_IDLE",
-    # connection status constants
-    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
-    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
-    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING",
-    # other
     "phymem_buffers", "cached_phymem"]
 
 
 def get_system_boot_time():
     """Return the system boot time expressed in seconds since the epoch."""
     f = open('/proc/stat', 'r')
     try:
         for line in f:
@@ -110,27 +104,27 @@ except Exception:
 
 # ioprio_* constants http://linux.die.net/man/2/ioprio_get
 IOPRIO_CLASS_NONE = 0
 IOPRIO_CLASS_RT = 1
 IOPRIO_CLASS_BE = 2
 IOPRIO_CLASS_IDLE = 3
 
 # http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
-_TCP_STATES_TABLE = {"01" : CONN_ESTABLISHED,
-                     "02" : CONN_SYN_SENT,
-                     "03" : CONN_SYN_RECV,
-                     "04" : CONN_FIN_WAIT1,
-                     "05" : CONN_FIN_WAIT2,
-                     "06" : CONN_TIME_WAIT,
-                     "07" : CONN_CLOSE,
-                     "08" : CONN_CLOSE_WAIT,
-                     "09" : CONN_LAST_ACK,
-                     "0A" : CONN_LISTEN,
-                     "0B" : CONN_CLOSING
+_TCP_STATES_TABLE = {"01" : "ESTABLISHED",
+                     "02" : "SYN_SENT",
+                     "03" : "SYN_RECV",
+                     "04" : "FIN_WAIT1",
+                     "05" : "FIN_WAIT2",
+                     "06" : "TIME_WAIT",
+                     "07" : "CLOSE",
+                     "08" : "CLOSE_WAIT",
+                     "09" : "LAST_ACK",
+                     "0A" : "LISTEN",
+                     "0B" : "CLOSING"
                      }
 
 # --- system memory functions
 
 nt_virtmem_info = namedtuple('vmem', ' '.join([
     # all platforms
     'total', 'available', 'percent', 'used', 'free',
     # linux specific
@@ -329,17 +323,17 @@ def get_pid_list():
     """Returns a list of PIDs currently running on the system."""
     pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
     return pids
 
 def pid_exists(pid):
     """Check For the existence of a unix pid."""
     return _psposix.pid_exists(pid)
 
-def net_io_counters():
+def network_io_counters():
     """Return network I/O statistics for every network interface
     installed on the system as a dict of raw tuples.
     """
     f = open("/proc/net/dev", "r")
     try:
         lines = f.readlines()
     finally:
         f.close()
@@ -394,17 +388,16 @@ def disk_io_counters():
     #
     retdict = {}
     f = open("/proc/diskstats", "r")
     try:
         lines = f.readlines()
     finally:
         f.close()
     for line in lines:
-        # http://www.mjmwired.net/kernel/Documentation/iostats.txt
         _, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \
             line.split()[:11]
         if name in partitions:
             rbytes = int(rbytes) * SECTOR_SIZE
             wbytes = int(wbytes) * SECTOR_SIZE
             reads = int(reads)
             writes = int(writes)
             rtime = int(rtime)
@@ -628,30 +621,21 @@ class Process(object):
             f = open("/proc/%s/smaps" % self.pid)
             first_line = f.readline()
             current_block = [first_line]
 
             def get_blocks():
                 data = {}
                 for line in f:
                     fields = line.split(None, 5)
-                    if not fields[0].endswith(':'):
-                        # new block section
+                    if len(fields) >= 5:
                         yield (current_block.pop(), data)
                         current_block.append(line)
                     else:
-                        try:
-                            data[fields[0]] = int(fields[1]) * 1024
-                        except ValueError:
-                            if fields[0].startswith('VmFlags:'):
-                                # see issue #369
-                                continue
-                            else:
-                                raise ValueError("don't know how to interpret" \
-                                                 " line %r" % line)
+                        data[fields[0]] = int(fields[1]) * 1024
                 yield (current_block.pop(), data)
 
             if first_line:  # smaps file can be empty
                 for header, data in get_blocks():
                     hfields = header.split(None, 5)
                     try:
                         addr, perms, offset, dev, inode, path = hfields
                     except ValueError:
@@ -686,17 +670,17 @@ class Process(object):
             raise
         except:
             if f is not None:
                 f.close()
             raise
         f.close()
 
     if not os.path.exists('/proc/%s/smaps' % os.getpid()):
-        def get_memory_maps(self, ext):
+        def get_shared_libs(self, ext):
             msg = "couldn't find /proc/%s/smaps; kernel < 2.6.14 or CONFIG_MMU " \
                   "kernel configuration option is not enabled" % self.pid
             raise NotImplementedError(msg)
 
     @wrap_exceptions
     def get_process_cwd(self):
         # readlink() might return paths containing null bytes causing
         # problems when used with other fs-related functions (os.*,
@@ -942,34 +926,34 @@ class Process(object):
                         _, laddr, raddr, status, _, _, _, _, _, inode = \
                                                                 line.split()[:10]
                         if inode in inodes:
                             laddr = self._decode_address(laddr, family)
                             raddr = self._decode_address(raddr, family)
                             if type_ == socket.SOCK_STREAM:
                                 status = _TCP_STATES_TABLE[status]
                             else:
-                                status = CONN_NONE
+                                status = ""
                             fd = int(inodes[inode])
                             conn = nt_connection(fd, family, type_, laddr,
                                                  raddr, status)
                             retlist.append(conn)
                     elif family == socket.AF_UNIX:
                         tokens = line.split()
                         _, _, _, _, type_, _, inode = tokens[0:7]
                         if inode in inodes:
 
                             if len(tokens) == 8:
                                 path = tokens[-1]
                             else:
                                 path = ""
                             fd = int(inodes[inode])
                             type_ = int(type_)
                             conn = nt_connection(fd, family, type_, path,
-                                                 None, CONN_NONE)
+                                                 None, "")
                             retlist.append(conn)
                     else:
                         raise ValueError(family)
                 return retlist
             finally:
                 f.close()
 
         tcp4 = ("tcp" , socket.AF_INET , socket.SOCK_STREAM)
@@ -996,16 +980,23 @@ class Process(object):
                              % (kind, ', '.join([repr(x) for x in tmap])))
         ret = []
         for f, family, type_ in tmap[kind]:
             ret += process("/proc/net/%s" % f, family, type_)
         # raise NSP if the process disappeared on us
         os.stat('/proc/%s' % self.pid)
         return ret
 
+
+#    --- lsof implementation
+#
+#    def get_connections(self):
+#        lsof = _psposix.LsofParser(self.pid, self._process_name)
+#        return lsof.get_process_connections()
+
     @wrap_exceptions
     def get_num_fds(self):
        return len(os.listdir("/proc/%s/fd" % self.pid))
 
     @wrap_exceptions
     def get_process_ppid(self):
         f = open("/proc/%s/status" % self.pid)
         try:
--- a/python/psutil/psutil/_psmswindows.py
+++ b/python/psutil/psutil/_psmswindows.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Windows platform implementation."""
 
 import errno
 import os
 import sys
@@ -16,20 +16,17 @@ import _psutil_mswindows
 from _psutil_mswindows import ERROR_ACCESS_DENIED
 from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
 from psutil._common import *
 from psutil._compat import PY3, xrange, long, wraps
 
 # Windows specific extended namespace
 __extra__all__ = ["ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
                   "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
-                  "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
-                  #
-                  "CONN_DELETE_TCB",
-                  ]
+                  "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS"]
 
 
 # --- module level constants (gets pushed up to psutil module)
 
 # Since these constants get determined at import time we do not want to
 # crash immediately; instead we'll set them to None and most likely
 # we'll crash later as they're used for determining process CPU stats
 # and creation_time
@@ -44,35 +41,18 @@ except Exception:
     BOOT_TIME = None
     warnings.warn("couldn't determine platform's BOOT_TIME", RuntimeWarning)
 try:
     TOTAL_PHYMEM = _psutil_mswindows.get_virtual_mem()[0]
 except Exception:
     TOTAL_PHYMEM = None
     warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
 
-CONN_DELETE_TCB = constant(11, "DELETE_TCB")
 WAIT_TIMEOUT = 0x00000102 # 258 in decimal
 ACCESS_DENIED_SET = frozenset([errno.EPERM, errno.EACCES, ERROR_ACCESS_DENIED])
-TCP_STATES_TABLE = {
-    _psutil_mswindows.MIB_TCP_STATE_ESTAB : CONN_ESTABLISHED,
-    _psutil_mswindows.MIB_TCP_STATE_SYN_SENT : CONN_SYN_SENT,
-    _psutil_mswindows.MIB_TCP_STATE_SYN_RCVD : CONN_SYN_RECV,
-    _psutil_mswindows.MIB_TCP_STATE_FIN_WAIT1 : CONN_FIN_WAIT1,
-    _psutil_mswindows.MIB_TCP_STATE_FIN_WAIT2 : CONN_FIN_WAIT2,
-    _psutil_mswindows.MIB_TCP_STATE_TIME_WAIT : CONN_TIME_WAIT,
-    _psutil_mswindows.MIB_TCP_STATE_CLOSED : CONN_CLOSE,
-    _psutil_mswindows.MIB_TCP_STATE_CLOSE_WAIT : CONN_CLOSE_WAIT,
-    _psutil_mswindows.MIB_TCP_STATE_LAST_ACK : CONN_LAST_ACK,
-    _psutil_mswindows.MIB_TCP_STATE_LISTEN : CONN_LISTEN,
-    _psutil_mswindows.MIB_TCP_STATE_CLOSING : CONN_CLOSING,
-    _psutil_mswindows.MIB_TCP_STATE_DELETE_TCB : CONN_DELETE_TCB,
-    _psutil_mswindows.PSUTIL_CONN_NONE : CONN_NONE,
-}
-
 
 # process priority constants:
 # http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
 from _psutil_mswindows import (ABOVE_NORMAL_PRIORITY_CLASS,
                                BELOW_NORMAL_PRIORITY_CLASS,
                                HIGH_PRIORITY_CLASS,
                                IDLE_PRIORITY_CLASS,
                                NORMAL_PRIORITY_CLASS,
@@ -170,17 +150,17 @@ def get_system_users():
     for item in rawlist:
         user, hostname, tstamp = item
         nt = nt_user(user, None, hostname, tstamp)
         retlist.append(nt)
     return retlist
 
 get_pid_list = _psutil_mswindows.get_pid_list
 pid_exists = _psutil_mswindows.pid_exists
-net_io_counters = _psutil_mswindows.get_net_io_counters
+network_io_counters = _psutil_mswindows.get_network_io_counters
 disk_io_counters = _psutil_mswindows.get_disk_io_counters
 
 # --- decorator
 
 def wrap_exceptions(fun):
     """Decorator which translates bare OSError and WindowsError
     exceptions into NoSuchProcess and AccessDenied.
     """
@@ -381,25 +361,18 @@ class Process(object):
         return retlist
 
     @wrap_exceptions
     def get_connections(self, kind='inet'):
         if kind not in conn_tmap:
             raise ValueError("invalid %r kind argument; choose between %s"
                              % (kind, ', '.join([repr(x) for x in conn_tmap])))
         families, types = conn_tmap[kind]
-        rawlist = _psutil_mswindows.get_process_connections(self.pid, families,
-                                                            types)
-        ret = []
-        for item in rawlist:
-            fd, fam, type, laddr, raddr, status = item
-            status = TCP_STATES_TABLE[status]
-            nt = nt_connection(fd, fam, type, laddr, raddr, status)
-            ret.append(nt)
-        return ret
+        ret = _psutil_mswindows.get_process_connections(self.pid, families, types)
+        return [nt_connection(*conn) for conn in ret]
 
     @wrap_exceptions
     def get_process_nice(self):
         return _psutil_mswindows.get_process_priority(self.pid)
 
     @wrap_exceptions
     def set_process_nice(self, value):
         return _psutil_mswindows.set_process_priority(self.pid, value)
--- a/python/psutil/psutil/_psosx.py
+++ b/python/psutil/psutil/_psosx.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """OSX platform implementation."""
 
 import errno
 import os
 import sys
@@ -39,30 +39,16 @@ except Exception:
 try:
     TOTAL_PHYMEM = _psutil_osx.get_virtual_mem()[0]
 except Exception:
     TOTAL_PHYMEM = None
     warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
 
 _PAGESIZE = os.sysconf("SC_PAGE_SIZE")
 _cputimes_ntuple = namedtuple('cputimes', 'user nice system idle')
-# http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
-_TCP_STATES_TABLE = {_psutil_osx.TCPS_ESTABLISHED : CONN_ESTABLISHED,
-                     _psutil_osx.TCPS_SYN_SENT : CONN_SYN_SENT,
-                     _psutil_osx.TCPS_SYN_RECEIVED : CONN_SYN_RECV,
-                     _psutil_osx.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
-                     _psutil_osx.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
-                     _psutil_osx.TCPS_TIME_WAIT : CONN_TIME_WAIT,
-                     _psutil_osx.TCPS_CLOSED : CONN_CLOSE,
-                     _psutil_osx.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
-                     _psutil_osx.TCPS_LAST_ACK : CONN_LAST_ACK,
-                     _psutil_osx.TCPS_LISTEN : CONN_LISTEN,
-                     _psutil_osx.TCPS_CLOSING : CONN_CLOSING,
-                     _psutil_osx.PSUTIL_CONN_NONE : CONN_NONE,
-                     }
 
 # --- functions
 
 get_system_boot_time = _psutil_osx.get_system_boot_time
 
 nt_virtmem_info = namedtuple('vmem', ' '.join([
     # all platforms
     'total', 'available', 'percent', 'used', 'free',
@@ -127,17 +113,17 @@ def get_system_users():
         nt = nt_user(user, tty or None, hostname or None, tstamp)
         retlist.append(nt)
     return retlist
 
 
 get_pid_list = _psutil_osx.get_pid_list
 pid_exists = _psposix.pid_exists
 get_disk_usage = _psposix.get_disk_usage
-net_io_counters = _psutil_osx.get_net_io_counters
+network_io_counters = _psutil_osx.get_network_io_counters
 disk_io_counters = _psutil_osx.get_disk_io_counters
 
 # --- decorator
 
 def wrap_exceptions(fun):
     """Decorator which translates bare OSError exceptions into
     NoSuchProcess and AccessDenied.
     """
@@ -269,24 +255,18 @@ class Process(object):
     def get_connections(self, kind='inet'):
         """Return etwork connections opened by a process as a list of
         namedtuples.
         """
         if kind not in conn_tmap:
             raise ValueError("invalid %r kind argument; choose between %s"
                              % (kind, ', '.join([repr(x) for x in conn_tmap])))
         families, types = conn_tmap[kind]
-        rawlist = _psutil_osx.get_process_connections(self.pid, families, types)
-        ret = []
-        for item in rawlist:
-            fd, fam, type, laddr, raddr, status = item
-            status = _TCP_STATES_TABLE[status]
-            nt = nt_connection(fd, fam, type, laddr, raddr, status)
-            ret.append(nt)
-        return ret
+        ret = _psutil_osx.get_process_connections(self.pid, families, types)
+        return [nt_connection(*conn) for conn in ret]
 
     @wrap_exceptions
     def get_num_fds(self):
         if self.pid == 0:
             return 0
         return _psutil_osx.get_process_num_fds(self.pid)
 
     @wrap_exceptions
--- a/python/psutil/psutil/_psposix.py
+++ b/python/psutil/psutil/_psposix.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Routines common to all posix systems."""
 
 import os
 import errno
 import psutil
deleted file mode 100644
--- a/python/psutil/psutil/_pssunos.py
+++ /dev/null
@@ -1,481 +0,0 @@
-#!/usr/bin/env python
-
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Sun OS Solaris platform implementation."""
-
-import errno
-import os
-import struct
-import subprocess
-import socket
-
-import _psutil_sunos
-import _psutil_posix
-from psutil import _psposix
-from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
-from psutil._compat import namedtuple, PY3
-from psutil._common import *
-
-
-__extra__all__ = ["CONN_IDLE", "CONN_BOUND"]
-
-PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
-NUM_CPUS = os.sysconf("SC_NPROCESSORS_ONLN")
-BOOT_TIME = _psutil_sunos.get_process_basic_info(0)[3]
-TOTAL_PHYMEM = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
-
-CONN_IDLE = constant(11, "IDLE")
-CONN_BOUND = constant(12, "BOUND")
-
-_PAGESIZE = os.sysconf("SC_PAGE_SIZE")
-_cputimes_ntuple = namedtuple('cputimes', 'user system idle iowait')
-
-disk_io_counters = _psutil_sunos.get_disk_io_counters
-net_io_counters = _psutil_sunos.get_net_io_counters
-get_disk_usage = _psposix.get_disk_usage
-get_system_boot_time = lambda: _psutil_sunos.get_process_basic_info(0)[3]
-
-nt_virtmem_info = namedtuple('vmem', ' '.join([
-    # all platforms
-    'total', 'available', 'percent', 'used', 'free']))
-
-def virtual_memory():
-    # we could have done this with kstat, but imho this is good enough
-    total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
-    # note: there's no difference on Solaris
-    free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
-    used = total - free
-    percent = usage_percent(used, total, _round=1)
-    return nt_virtmem_info(total, avail, percent, used, free)
-
-def swap_memory():
-    sin, sout = _psutil_sunos.get_swap_mem()
-
-    # XXX
-    # we are supposed to get total/free by doing so:
-    # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/swap/swap.c
-    # ...nevertheless I can't manage to obtain the same numbers as 'swap'
-    # cmdline utility, so let's parse its output (sigh!)
-    p = subprocess.Popen(['swap', '-l', '-k'], stdout=subprocess.PIPE)
-    stdout, stderr = p.communicate()
-    if PY3:
-        stdout = stdout.decode(sys.stdout.encoding)
-    if p.returncode != 0:
-        raise RuntimeError("'swap -l -k' failed (retcode=%s)" % retcode)
-
-    lines = stdout.strip().split('\n')[1:]
-    if not lines:
-        raise RuntimeError('no swap device(s) configured')
-    total = free = 0
-    for line in lines:
-        line = line.split()
-        t, f = line[-2:]
-        t = t.replace('K', '')
-        f = f.replace('K', '')
-        total += int(int(t) * 1024)
-        free += int(int(f) * 1024)
-    used = total - free
-    percent = usage_percent(used, total, _round=1)
-    return nt_swapmeminfo(total, used, free, percent,
-                          sin * _PAGESIZE, sout * _PAGESIZE)
-
-def get_pid_list():
-    """Returns a list of PIDs currently running on the system."""
-    return [int(x) for x in os.listdir('/proc') if x.isdigit()]
-
-def pid_exists(pid):
-    """Check for the existence of a unix pid."""
-    return _psposix.pid_exists(pid)
-
-def get_system_cpu_times():
-    """Return system-wide CPU times as a named tuple"""
-    ret = _psutil_sunos.get_system_per_cpu_times()
-    return _cputimes_ntuple(*[sum(x) for x in zip(*ret)])
-
-def get_system_per_cpu_times():
-    """Return system per-CPU times as a list of named tuples"""
-    ret = _psutil_sunos.get_system_per_cpu_times()
-    return [_cputimes_ntuple(*x) for x in ret]
-
-def get_system_users():
-    """Return currently connected users as a list of namedtuples."""
-    retlist = []
-    rawlist = _psutil_sunos.get_system_users()
-    localhost = (':0.0', ':0')
-    for item in rawlist:
-        user, tty, hostname, tstamp, user_process = item
-        # note: the underlying C function includes entries about
-        # system boot, run level and others.  We might want
-        # to use them in the future.
-        if not user_process:
-            continue
-        if hostname in localhost:
-            hostname = 'localhost'
-        nt = nt_user(user, tty, hostname, tstamp)
-        retlist.append(nt)
-    return retlist
-
-def disk_partitions(all=False):
-    """Return system disk partitions."""
-    # TODO - the filtering logic should be better checked so that
-    # it tries to reflect 'df' as much as possible
-    retlist = []
-    partitions = _psutil_sunos.get_disk_partitions()
-    for partition in partitions:
-        device, mountpoint, fstype, opts = partition
-        if device == 'none':
-            device = ''
-        if not all:
-            # Differently from, say, Linux, we don't have a list of
-            # common fs types so the best we can do, AFAIK, is to
-            # filter by filesystem having a total size > 0.
-            if not get_disk_usage(mountpoint).total:
-                continue
-        ntuple = nt_partition(device, mountpoint, fstype, opts)
-        retlist.append(ntuple)
-    return retlist
-
-
-def wrap_exceptions(callable):
-    """Call callable into a try/except clause and translate ENOENT,
-    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
-    """
-    def wrapper(self, *args, **kwargs):
-        try:
-            return callable(self, *args, **kwargs)
-        except EnvironmentError:
-            # ENOENT (no such file or directory) gets raised on open().
-            # ESRCH (no such process) can get raised on read() if
-            # process is gone in meantime.
-            err = sys.exc_info()[1]
-            if err.errno in (errno.ENOENT, errno.ESRCH):
-                raise NoSuchProcess(self.pid, self._process_name)
-            if err.errno in (errno.EPERM, errno.EACCES):
-                raise AccessDenied(self.pid, self._process_name)
-            raise
-    return wrapper
-
-
-_status_map = {
-    _psutil_sunos.SSLEEP : STATUS_SLEEPING,
-    _psutil_sunos.SRUN : STATUS_RUNNING,
-    _psutil_sunos.SZOMB : STATUS_ZOMBIE,
-    _psutil_sunos.SSTOP : STATUS_STOPPED,
-    _psutil_sunos.SIDL : STATUS_IDLE,
-    _psutil_sunos.SONPROC : STATUS_RUNNING,  # same as run
-    _psutil_sunos.SWAIT : STATUS_WAITING,
-}
-
-_conn_status_map = {_psutil_sunos.TCPS_ESTABLISHED : CONN_ESTABLISHED,
-                    _psutil_sunos.TCPS_SYN_SENT : CONN_SYN_SENT,
-                    _psutil_sunos.TCPS_SYN_RCVD : CONN_SYN_RECV,
-                    _psutil_sunos.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
-                    _psutil_sunos.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
-                    _psutil_sunos.TCPS_TIME_WAIT : CONN_TIME_WAIT,
-                    _psutil_sunos.TCPS_CLOSED : CONN_CLOSE,
-                    _psutil_sunos.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
-                    _psutil_sunos.TCPS_LAST_ACK : CONN_LAST_ACK,
-                    _psutil_sunos.TCPS_LISTEN : CONN_LISTEN,
-                    _psutil_sunos.TCPS_CLOSING : CONN_CLOSING,
-                    _psutil_sunos.PSUTIL_CONN_NONE : CONN_NONE,
-                    _psutil_sunos.TCPS_IDLE : CONN_IDLE,  # sunos specific
-                    _psutil_sunos.TCPS_BOUND : CONN_BOUND,  # sunos specific
-                    }
-
-
-class Process(object):
-    """Wrapper class around underlying C implementation."""
-
-    __slots__ = ["pid", "_process_name"]
-
-    def __init__(self, pid):
-        self.pid = pid
-        self._process_name = None
-
-    @wrap_exceptions
-    def get_process_name(self):
-        # note: max len == 15
-        return _psutil_sunos.get_process_name_and_args(self.pid)[0]
-
-    @wrap_exceptions
-    def get_process_exe(self):
-        # Will be guess later from cmdline but we want to explicitly
-        # invoke cmdline here in order to get an AccessDenied
-        # exception if the user has not enough privileges.
-        self.get_process_cmdline()
-        return ""
-
-    @wrap_exceptions
-    def get_process_cmdline(self):
-        return _psutil_sunos.get_process_name_and_args(self.pid)[1].split(' ')
-
-    @wrap_exceptions
-    def get_process_create_time(self):
-        return _psutil_sunos.get_process_basic_info(self.pid)[3]
-
-    @wrap_exceptions
-    def get_process_num_threads(self):
-        return _psutil_sunos.get_process_basic_info(self.pid)[5]
-
-    @wrap_exceptions
-    def get_process_nice(self):
-        # For some reason getpriority(3) return ESRCH (no such process)
-        # for certain low-pid processes, no matter what (even as root).
-        # The process actually exists though, as it has a name,
-        # creation time, etc.
-        # The best thing we can do here appears to be raising AD.
-        # Note: tested on Solaris 11; on Open Solaris 5 everything is
-        # fine.
-        try:
-            return _psutil_posix.getpriority(self.pid)
-        except EnvironmentError:
-            err = sys.exc_info()[1]
-            if err.errno in (errno.ENOENT, errno.ESRCH):
-                if pid_exists(self.pid):
-                    raise AccessDenied(self.pid, self._process_name)
-            raise
-
-    @wrap_exceptions
-    def set_process_nice(self, value):
-        if self.pid in (2, 3):
-            # Special case PIDs: internally setpriority(3) return ESRCH
-            # (no such process), no matter what.
-            # The process actually exists though, as it has a name,
-            # creation time, etc.
-            raise AccessDenied(self.pid, self._process_name)
-        return _psutil_posix.setpriority(self.pid, value)
-
-    @wrap_exceptions
-    def get_process_ppid(self):
-        return _psutil_sunos.get_process_basic_info(self.pid)[0]
-
-    @wrap_exceptions
-    def get_process_uids(self):
-        real, effective, saved, _, _, _ = _psutil_sunos.get_process_cred(self.pid)
-        return nt_uids(real, effective, saved)
-
-    @wrap_exceptions
-    def get_process_gids(self):
-        _, _, _, real, effective, saved = _psutil_sunos.get_process_cred(self.pid)
-        return nt_uids(real, effective, saved)
-
-    @wrap_exceptions
-    def get_cpu_times(self):
-        user, system = _psutil_sunos.get_process_cpu_times(self.pid)
-        return nt_cputimes(user, system)
-
-    @wrap_exceptions
-    def get_process_terminal(self):
-        hit_enoent = False
-        tty = wrap_exceptions(_psutil_sunos.get_process_basic_info(self.pid)[0])
-        if tty != _psutil_sunos.PRNODEV:
-            for x in (0, 1, 2, 255):
-                try:
-                    return os.readlink('/proc/%d/path/%d' % (self.pid, x))
-                except OSError:
-                    err = sys.exc_info()[1]
-                    if err.errno == errno.ENOENT:
-                        hit_enoent = True
-                        continue
-                    raise
-        if hit_enoent:
-            # raise NSP if the process disappeared on us
-            os.stat('/proc/%s' % self.pid)
-
-    @wrap_exceptions
-    def get_process_cwd(self):
-        # /proc/PID/path/cwd may not be resolved by readlink() even if
-        # it exists (ls shows it). If that's the case and the process
-        # is still alive return None (we can return None also on BSD).
-        # Reference: http://goo.gl/55XgO
-        try:
-            return os.readlink("/proc/%s/path/cwd" % self.pid)
-        except OSError:
-            err = sys.exc_info()[1]
-            if err.errno == errno.ENOENT:
-                os.stat("/proc/%s" % self.pid)
-                return None
-            raise
-
-    @wrap_exceptions
-    def get_memory_info(self):
-        ret = _psutil_sunos.get_process_basic_info(self.pid)
-        rss, vms = ret[1] * 1024, ret[2] * 1024
-        return nt_meminfo(rss, vms)
-
-    # it seems Solaris uses rss and vms only
-    get_ext_memory_info = get_memory_info
-
-    @wrap_exceptions
-    def get_process_status(self):
-        code = _psutil_sunos.get_process_basic_info(self.pid)[6]
-        if code in _status_map:
-            return _status_map[code]
-        return constant(-1, "?")
-
-    @wrap_exceptions
-    def get_process_threads(self):
-        ret = []
-        tids = os.listdir('/proc/%d/lwp' % self.pid)
-        hit_enoent = False
-        for tid in tids:
-            tid = int(tid)
-            try:
-                utime, stime = _psutil_sunos.query_process_thread(self.pid, tid)
-            except EnvironmentError:
-                # ENOENT == thread gone in meantime
-                err = sys.exc_info()[1]
-                if err.errno == errno.ENOENT:
-                    hit_enoent = True
-                    continue
-                raise
-            else:
-                nt = nt_thread(tid, utime, stime)
-                ret.append(nt)
-        if hit_enoent:
-            # raise NSP if the process disappeared on us
-            os.stat('/proc/%s' % self.pid)
-        return ret
-
-    @wrap_exceptions
-    def get_open_files(self):
-        retlist = []
-        hit_enoent = False
-        pathdir = '/proc/%d/path' % self.pid
-        for fd in os.listdir('/proc/%d/fd' % self.pid):
-            path = os.path.join(pathdir, fd)
-            if os.path.islink(path):
-                try:
-                    file = os.readlink(path)
-                except OSError:
-                    # ENOENT == file which is gone in the meantime
-                    err = sys.exc_info()[1]
-                    if err.errno == errno.ENOENT:
-                        hit_enoent = True
-                        continue
-                    raise
-                else:
-                    if isfile_strict(file):
-                        retlist.append(nt_openfile(file, int(fd)))
-        if hit_enoent:
-            # raise NSP if the process disappeared on us
-            os.stat('/proc/%s' % self.pid)
-        return retlist
-
-    def _get_unix_sockets(self, pid):
-        """Get UNIX sockets used by process by parsing 'pfiles' output."""
-        # TODO: rewrite this in C (...but the damn netstat source code
-        # does not include this part! Argh!!)
-        cmd = "pfiles %s" % pid
-        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
-                                              stderr=subprocess.PIPE)
-        stdout, stderr = p.communicate()
-        if PY3:
-            stdout, stderr = [x.decode(sys.stdout.encoding)
-                              for x in (stdout, stderr)]
-        if p.returncode != 0:
-            if 'permission denied' in stderr.lower():
-                raise AccessDenied(self.pid, self._process_name)
-            if 'no such process' in stderr.lower():
-                raise NoSuchProcess(self.pid, self._process_name)
-            raise RuntimeError("%r command error\n%s" % (cmd, stderr))
-
-        lines = stdout.split('\n')[2:]
-        for i, line in enumerate(lines):
-            line = line.lstrip()
-            if line.startswith('sockname: AF_UNIX'):
-                path = line.split(' ', 2)[2]
-                type = lines[i-2].strip()
-                if type == 'SOCK_STREAM':
-                    type = socket.SOCK_STREAM
-                elif type == 'SOCK_DGRAM':
-                    type = socket.SOCK_DGRAM
-                else:
-                    type = -1
-                yield (-1, socket.AF_UNIX, type, path, "", CONN_NONE)
-
-    @wrap_exceptions
-    def get_connections(self, kind='inet'):
-        if kind not in conn_tmap:
-            raise ValueError("invalid %r kind argument; choose between %s"
-                             % (kind, ', '.join([repr(x) for x in conn_tmap])))
-        families, types = conn_tmap[kind]
-        rawlist = _psutil_sunos.get_process_connections(self.pid, families, types)
-        # The underlying C implementation retrieves all OS connections
-        # and filters them by PID.  At this point we can't tell whether
-        # an empty list means there were no connections for process or
-        # process is no longer active so we force NSP in case the PID
-        # is no longer there.
-        if not rawlist:
-            os.stat('/proc/%s' % self.pid)  # will raise NSP if process is gone
-
-        ret = []
-        for item in rawlist:
-            fd, fam, type, laddr, raddr, status = item
-            if fam not in families:
-                continue
-            if type not in types:
-                continue
-            status = _conn_status_map[status]
-            nt = nt_connection(fd, fam, type, laddr, raddr, status)
-            ret.append(nt)
-
-        # UNIX sockets
-        if socket.AF_UNIX in families:
-            ret.extend([nt_connection(*conn) for conn in \
-                        self._get_unix_sockets(self.pid)])
-        return ret
-
-    nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
-    nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
-
-    @wrap_exceptions
-    def get_memory_maps(self):
-        def toaddr(start, end):
-            return '%s-%s' % (hex(start)[2:].strip('L'), hex(end)[2:].strip('L'))
-
-        retlist = []
-        rawlist = _psutil_sunos.get_process_memory_maps(self.pid)
-        hit_enoent = False
-        for item in rawlist:
-            addr, addrsize, perm, name, rss, anon, locked = item
-            addr = toaddr(addr, addrsize)
-            if not name.startswith('['):
-                try:
-                    name = os.readlink('/proc/%s/path/%s' % (self.pid, name))
-                except OSError:
-                    err = sys.exc_info()[1]
-                    if err.errno == errno.ENOENT:
-                        # sometimes the link may not be resolved by
-                        # readlink() even if it exists (ls shows it).
-                        # If that's the case we just return the
-                        # unresolved link path.
-                        # This seems an incosistency with /proc similar
-                        # to: http://goo.gl/55XgO
-                        name = '/proc/%s/path/%s' % (self.pid, name)
-                        hit_enoent = True
-                    else:
-                        raise
-            retlist.append((addr, perm, name, rss, anon, locked))
-        if hit_enoent:
-            # raise NSP if the process disappeared on us
-            os.stat('/proc/%s' % self.pid)
-        return retlist
-
-    @wrap_exceptions
-    def get_num_fds(self):
-       return len(os.listdir("/proc/%s/fd" % self.pid))
-
-    @wrap_exceptions
-    def get_num_ctx_switches(self):
-        return nt_ctxsw(*_psutil_sunos.get_process_num_ctx_switches(self.pid))
-
-    @wrap_exceptions
-    def process_wait(self, timeout=None):
-        try:
-            return _psposix.wait_pid(self.pid, timeout)
-        except TimeoutExpired:
-            raise TimeoutExpired(self.pid, self._process_name)
--- a/python/psutil/psutil/_psutil_bsd.c
+++ b/python/psutil/psutil/_psutil_bsd.c
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * FreeBSD platform-specific module methods for _psutil_bsd
  */
 
 
 #include <Python.h>
@@ -988,20 +988,16 @@ psutil_search_tcplist(char *buf, struct 
                 continue;
         }
 
         return (tp);
     }
     return NULL;
 }
 
-
-// a signaler for connections without an actual status
-static int PSUTIL_CONN_NONE = 128;
-
 /*
  * Return connections opened by process.
  */
 static PyObject*
 get_process_connections(PyObject* self, PyObject* args)
 {
     long pid;
     int i, cnt;
@@ -1044,19 +1040,20 @@ get_process_connections(PyObject* self, 
 
     tcplist = psutil_fetch_tcplist();
     if (tcplist == NULL) {
         PyErr_SetFromErrno(0);
         goto error;
     }
 
     for (i = 0; i < cnt; i++) {
-        int lport, rport, state;
+        int lport, rport;
         char lip[200], rip[200];
         char path[PATH_MAX];
+        char *state;
         int inseq;
         tuple = NULL;
         laddr = NULL;
         raddr = NULL;
 
         kif = &freep[i];
         if (kif->kf_type == KF_TYPE_SOCKET)
         {
@@ -1073,21 +1070,21 @@ get_process_connections(PyObject* self, 
             if (inseq == 0) {
                 continue;
             }
 
             // IPv4 / IPv6 socket
             if ((kif->kf_sock_domain == AF_INET) ||
                 (kif->kf_sock_domain == AF_INET6)) {
                 // fill status
-                state = PSUTIL_CONN_NONE;
+                state = "";
                 if (kif->kf_sock_type == SOCK_STREAM) {
                     tcp = psutil_search_tcplist(tcplist, kif);
                     if (tcp != NULL)
-                        state = (int)tcp->t_state;
+                        state = get_connection_status((int)tcp->t_state);
                 }
 
                 // build addr and port
                 inet_ntop(kif->kf_sock_domain,
                     psutil_sockaddr_addr(kif->kf_sock_domain, &kif->kf_sa_local),
                     lip, sizeof(lip));
                 inet_ntop(kif->kf_sock_domain,
                     psutil_sockaddr_addr(kif->kf_sock_domain, &kif->kf_sa_peer),
@@ -1104,17 +1101,17 @@ get_process_connections(PyObject* self, 
                 if (rport != 0) {
                     raddr = Py_BuildValue("(si)", rip, rport);
                 }
                 else {
                     raddr = Py_BuildValue("()");
                 }
                 if (!raddr)
                     goto error;
-                tuple = Py_BuildValue("(iiiNNi)", kif->kf_fd,
+                tuple = Py_BuildValue("(iiiNNs)", kif->kf_fd,
                                                   kif->kf_sock_domain,
                                                   kif->kf_sock_type,
                                                   laddr,
                                                   raddr,
                                                   state);
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
@@ -1125,22 +1122,22 @@ get_process_connections(PyObject* self, 
             else if (kif->kf_sock_domain == AF_UNIX) {
                 struct sockaddr_un *sun;
 
                 sun = (struct sockaddr_un *)&kif->kf_sa_local;
                 snprintf(path, sizeof(path), "%.*s",
                         (sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
                          sun->sun_path);
 
-                tuple = Py_BuildValue("(iiisOi)", kif->kf_fd,
+                tuple = Py_BuildValue("(iiisOs)", kif->kf_fd,
                                                   kif->kf_sock_domain,
                                                   kif->kf_sock_type,
                                                   path,
                                                   Py_None,
-                                                  PSUTIL_CONN_NONE);
+                                                  "");
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
                     goto error;
                 Py_DECREF(tuple);
                 Py_INCREF(Py_None);
             }
         }
@@ -1462,17 +1459,17 @@ error:
     return NULL;
 }
 
 
 /*
  * Return a Python list of named tuples with overall network I/O information
  */
 static PyObject*
-get_net_io_counters(PyObject* self, PyObject* args)
+get_network_io_counters(PyObject* self, PyObject* args)
 {
     char *buf = NULL, *lim, *next;
     struct if_msghdr *ifm;
     int mib[6];
     size_t len;
     PyObject* py_retdict = PyDict_New();
     PyObject* py_ifc_info = NULL;
     if (py_retdict == NULL)
@@ -1771,17 +1768,17 @@ PsutilMethods[] =
      {"get_system_per_cpu_times", get_system_per_cpu_times, METH_VARARGS,
          "Return system per-cpu times as a list of tuples"},
 #endif
      {"get_system_boot_time", get_system_boot_time, METH_VARARGS,
          "Return the system boot time expressed in seconds since the epoch."},
      {"get_disk_partitions", get_disk_partitions, METH_VARARGS,
          "Return a list of tuples including device, mount point and "
          "fs type for all partitions mounted on the system."},
-     {"get_net_io_counters", get_net_io_counters, METH_VARARGS,
+     {"get_network_io_counters", get_network_io_counters, METH_VARARGS,
          "Return dict of tuples of networks I/O information."},
      {"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
          "Return a Python dict of tuples for disk I/O information"},
      {"get_system_users", get_system_users, METH_VARARGS,
         "Return currently connected users as a list of tuples"},
 
      {NULL, NULL, 0, NULL}
 };
@@ -1834,37 +1831,23 @@ PyInit__psutil_bsd(void)
 void init_psutil_bsd(void)
 #endif
 {
 #if PY_MAJOR_VERSION >= 3
     PyObject *module = PyModule_Create(&moduledef);
 #else
     PyObject *module = Py_InitModule("_psutil_bsd", PsutilMethods);
 #endif
-    // process status constants
     PyModule_AddIntConstant(module, "SSTOP", SSTOP);
     PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
     PyModule_AddIntConstant(module, "SRUN", SRUN);
     PyModule_AddIntConstant(module, "SIDL", SIDL);
     PyModule_AddIntConstant(module, "SWAIT", SWAIT);
     PyModule_AddIntConstant(module, "SLOCK", SLOCK);
     PyModule_AddIntConstant(module, "SZOMB", SZOMB);
-    // connection status constants
-    PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
-    PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
-    PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
-    PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
-    PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
-    PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
-    PyModule_AddIntConstant(module, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
-    PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
-    PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
-    PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
 
     if (module == NULL) {
         INITERROR;
     }
 #if PY_MAJOR_VERSION >= 3
     return module;
 #endif
 }
--- a/python/psutil/psutil/_psutil_bsd.h
+++ b/python/psutil/psutil/_psutil_bsd.h
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * BSD platform-specific module methods for _psutil_bsd
  */
 
 #include <Python.h>
 
@@ -40,11 +40,11 @@ static PyObject* get_num_cpus(PyObject* 
 static PyObject* get_virtual_mem(PyObject* self, PyObject* args);
 static PyObject* get_swap_mem(PyObject* self, PyObject* args);
 static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);
 #if defined(__FreeBSD_version) && __FreeBSD_version >= 800000
 static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
 #endif
 static PyObject* get_system_boot_time(PyObject* self, PyObject* args);
 static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
-static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
+static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_system_users(PyObject* self, PyObject* args);
--- a/python/psutil/psutil/_psutil_common.c
+++ b/python/psutil/psutil/_psutil_common.c
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Routines common to all platforms.
  */
 
 #include <Python.h>
 
--- a/python/psutil/psutil/_psutil_common.h
+++ b/python/psutil/psutil/_psutil_common.h
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  */
 
 #include <Python.h>
 
 PyObject* NoSuchProcess(void);
 PyObject* AccessDenied(void);
--- a/python/psutil/psutil/_psutil_linux.c
+++ b/python/psutil/psutil/_psutil_linux.c
@@ -1,17 +1,16 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Linux-specific functions.
  */
 
-#define _GNU_SOURCE
 #include <Python.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <mntent.h>
 #include <utmp.h>
 #include <sched.h>
 #include <sys/syscall.h>
 #include <sys/sysinfo.h>
--- a/python/psutil/psutil/_psutil_linux.h
+++ b/python/psutil/psutil/_psutil_linux.h
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * LINUX specific module methods for _psutil_linux
  */
 
 #include <Python.h>
 
--- a/python/psutil/psutil/_psutil_mswindows.c
+++ b/python/psutil/psutil/_psutil_mswindows.c
@@ -605,100 +605,89 @@ get_process_memory_info(PyObject* self, 
     }
 
 #if (_WIN32_WINNT >= 0x0501)
     private = cnt.PrivateUsage;
 #endif
 
     CloseHandle(hProcess);
 
-// PROCESS_MEMORY_COUNTERS values are defined as SIZE_T which on 64bits
-// is an (unsigned long long) and on 32bits is an (unsigned int).
-// "_WIN64" is defined if we're running a 64bit Python interpreter not
-// exclusively if the *system* is 64bit.
-#if defined(_WIN64)
-    return Py_BuildValue("(kKKKKKKKKK)",
-                            cnt.PageFaultCount,  // unsigned long
-        (unsigned long long)cnt.PeakWorkingSetSize,
-        (unsigned long long)cnt.WorkingSetSize,
-        (unsigned long long)cnt.QuotaPeakPagedPoolUsage,
-        (unsigned long long)cnt.QuotaPagedPoolUsage,
-        (unsigned long long)cnt.QuotaPeakNonPagedPoolUsage,
-        (unsigned long long)cnt.QuotaNonPagedPoolUsage,
-        (unsigned long long)cnt.PagefileUsage,
-        (unsigned long long)cnt.PeakPagefileUsage,
-        (unsigned long long)private);
-#else
+// py 2.4
+#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION <= 4)
     return Py_BuildValue("(kIIIIIIIII)",
-                      cnt.PageFaultCount,    // unsigned long
+        cnt.PageFaultCount,
         (unsigned int)cnt.PeakWorkingSetSize,
         (unsigned int)cnt.WorkingSetSize,
         (unsigned int)cnt.QuotaPeakPagedPoolUsage,
         (unsigned int)cnt.QuotaPagedPoolUsage,
         (unsigned int)cnt.QuotaPeakNonPagedPoolUsage,
         (unsigned int)cnt.QuotaNonPagedPoolUsage,
         (unsigned int)cnt.PagefileUsage,
         (unsigned int)cnt.PeakPagefileUsage,
         (unsigned int)private);
+#else
+// py >= 2.5
+    return Py_BuildValue("(knnnnnnnnn)",
+        cnt.PageFaultCount,
+        cnt.PeakWorkingSetSize,
+        cnt.WorkingSetSize,
+        cnt.QuotaPeakPagedPoolUsage,
+        cnt.QuotaPagedPoolUsage,
+        cnt.QuotaPeakNonPagedPoolUsage,
+        cnt.QuotaNonPagedPoolUsage,
+        cnt.PagefileUsage,
+        cnt.PeakPagefileUsage,
+        private);
 #endif
 }
 
 
 /*
  * Alternative implementation of the one above but bypasses ACCESS DENIED.
  */
 static PyObject*
 get_process_memory_info_2(PyObject* self, PyObject* args)
 {
     DWORD pid;
     PSYSTEM_PROCESS_INFORMATION process;
     PVOID buffer;
-    SIZE_T private;
+    ULONG m0;
+    SIZE_T m1, m2, m3, m4, m5, m6, m7, m8, m9;
 
     if (! PyArg_ParseTuple(args, "l", &pid)) {
         return NULL;
     }
     if (! get_process_info(pid, &process, &buffer)) {
         return NULL;
     }
-
+    m0 = process->PageFaultCount;
+    m1 = process->PeakWorkingSetSize;
+    m2 = process->WorkingSetSize;
+    m3 = process->QuotaPeakPagedPoolUsage;
+    m4 = process->QuotaPagedPoolUsage;
+    m5 = process->QuotaPeakNonPagedPoolUsage;
+    m6 = process->QuotaNonPagedPoolUsage;
+    m7 = process->PagefileUsage;
+    m8 = process->PeakPagefileUsage;
 #if (_WIN32_WINNT >= 0x0501)
-    private = process->PrivatePageCount;
+    m9 = process->PrivatePageCount;  // private me
 #else
-    private = 0;
+    m9 = 0;
 #endif
-
-// SYSTEM_PROCESS_INFORMATIONvalues are defined as SIZE_T which on 64
-// bits is an (unsigned long long) and on 32bits is an (unsigned int).
-// "_WIN64" is defined if we're running a 64bit Python interpreter not
-// exclusively if the *system* is 64bit.
-#if defined(_WIN64)
-    return Py_BuildValue("(kKKKKKKKKK)",
-                            process->PageFaultCount,  // unsigned long
-        (unsigned long long)process->PeakWorkingSetSize,
-        (unsigned long long)process->WorkingSetSize,
-        (unsigned long long)process->QuotaPeakPagedPoolUsage,
-        (unsigned long long)process->QuotaPagedPoolUsage,
-        (unsigned long long)process->QuotaPeakNonPagedPoolUsage,
-        (unsigned long long)process->QuotaNonPagedPoolUsage,
-        (unsigned long long)process->PagefileUsage,
-        (unsigned long long)process->PeakPagefileUsage,
-        (unsigned long long)private);
+    free(buffer);
+
+// py 2.4
+#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION <= 4)
+    return Py_BuildValue("(kIIIIIIIII)",
+        (unsigned int)m0, (unsigned int)m1, (unsigned int)m2, (unsigned int)m3,
+        (unsigned int)m4, (unsigned int)m5, (unsigned int)m6, (unsigned int)m7,
+        (unsigned int)m8, (unsigned int)m9);
 #else
-    return Py_BuildValue("(kIIIIIIIII)",
-                      process->PageFaultCount,    // unsigned long
-        (unsigned int)process->PeakWorkingSetSize,
-        (unsigned int)process->WorkingSetSize,
-        (unsigned int)process->QuotaPeakPagedPoolUsage,
-        (unsigned int)process->QuotaPagedPoolUsage,
-        (unsigned int)process->QuotaPeakNonPagedPoolUsage,
-        (unsigned int)process->QuotaNonPagedPoolUsage,
-        (unsigned int)process->PagefileUsage,
-        (unsigned int)process->PeakPagefileUsage,
-        (unsigned int)private);
+    return Py_BuildValue("(knnnnnnnnn)",
+        m0, m1, m2, m3, m4, m5, m6, m7, m8, m9);
 #endif
 }
 
 
 /*
  * Return a Python integer indicating the total amount of physical memory
  * in bytes.
  */
@@ -1382,16 +1371,49 @@ get_process_username(PyObject* self, PyO
 }
 
 #define BYTESWAP_USHORT(x) ((((USHORT)(x) << 8) | ((USHORT)(x) >> 8)) & 0xffff)
 
 #ifndef AF_INET6
 #define AF_INET6 23
 #endif
 
+static char *state_to_string(ULONG state)
+{
+    switch (state)
+    {
+    case MIB_TCP_STATE_CLOSED:
+        return "CLOSE";
+    case MIB_TCP_STATE_LISTEN:
+        return "LISTEN";
+    case MIB_TCP_STATE_SYN_SENT:
+        return "SYN_SENT";
+    case MIB_TCP_STATE_SYN_RCVD:
+        return "SYN_RECV";
+    case MIB_TCP_STATE_ESTAB:
+        return "ESTABLISHED";
+    case MIB_TCP_STATE_FIN_WAIT1:
+        return "FIN_WAIT1";
+    case MIB_TCP_STATE_FIN_WAIT2:
+        return "FIN_WAIT2";
+    case MIB_TCP_STATE_CLOSE_WAIT:
+        return "CLOSE_WAIT";
+    case MIB_TCP_STATE_CLOSING:
+        return "CLOSING";
+    case MIB_TCP_STATE_LAST_ACK:
+        return "LAST_ACK";
+    case MIB_TCP_STATE_TIME_WAIT:
+        return "TIME_WAIT";
+    case MIB_TCP_STATE_DELETE_TCB:
+        return "DELETE_TCB";
+    default:
+        return "";
+    }
+}
+
 /* mingw support */
 #ifndef _IPRTRMIB_H
 typedef struct _MIB_TCP6ROW_OWNER_PID
 {
     UCHAR           ucLocalAddr[16];
     DWORD           dwLocalScopeId;
     DWORD           dwLocalPort;
     UCHAR           ucRemoteAddr[16];
@@ -1452,20 +1474,16 @@ typedef struct _MIB_UDP6TABLE_OWNER_PID
 } MIB_UDP6TABLE_OWNER_PID, *PMIB_UDP6TABLE_OWNER_PID;
 
 
 #define ConnDecrefPyObjs() Py_DECREF(_AF_INET); \
                            Py_DECREF(_AF_INET6);\
                            Py_DECREF(_SOCK_STREAM);\
                            Py_DECREF(_SOCK_DGRAM);
 
-// a signaler for connections without an actual status
-static int PSUTIL_CONN_NONE = 128;
-
-
 /*
  * Return a list of network connections opened by a process
  */
 static PyObject*
 get_process_connections(PyObject* self, PyObject* args)
 {
     static long null_address[4] = { 0, 0, 0, 0 };
 
@@ -1618,23 +1636,23 @@ get_process_connections(PyObject* self, 
                 else
                 {
                     addressTupleRemote = PyTuple_New(0);
                 }
 
                 if (addressTupleRemote == NULL)
                     goto error;
 
-                connectionTuple = Py_BuildValue("(iiiNNi)",
+                connectionTuple = Py_BuildValue("(iiiNNs)",
                     -1,
                     AF_INET,
                     SOCK_STREAM,
                     addressTupleLocal,
                     addressTupleRemote,
-                    tcp4Table->table[i].dwState
+                    state_to_string(tcp4Table->table[i].dwState)
                     );
                 if (!connectionTuple)
                     goto error;
                 if (PyList_Append(connectionsList, connectionTuple))
                     goto error;
                 Py_DECREF(connectionTuple);
             }
         }
@@ -1706,23 +1724,23 @@ get_process_connections(PyObject* self, 
                 else
                 {
                     addressTupleRemote = PyTuple_New(0);
                 }
 
                 if (addressTupleRemote == NULL)
                     goto error;
 
-                connectionTuple = Py_BuildValue("(iiiNNi)",
+                connectionTuple = Py_BuildValue("(iiiNNs)",
                     -1,
                     AF_INET6,
                     SOCK_STREAM,
                     addressTupleLocal,
                     addressTupleRemote,
-                    tcp6Table->table[i].dwState
+                    state_to_string(tcp6Table->table[i].dwState)
                     );
                 if (!connectionTuple)
                     goto error;
                 if (PyList_Append(connectionsList, connectionTuple))
                     goto error;
                 Py_DECREF(connectionTuple);
             }
         }
@@ -1773,23 +1791,23 @@ get_process_connections(PyObject* self, 
                 else
                 {
                     addressTupleLocal = PyTuple_New(0);
                 }
 
                 if (addressTupleLocal == NULL)
                     goto error;
 
-                connectionTuple = Py_BuildValue("(iiiNNi)",
+                connectionTuple = Py_BuildValue("(iiiNNs)",
                     -1,
                     AF_INET,
                     SOCK_DGRAM,
                     addressTupleLocal,
                     PyTuple_New(0),
-                    PSUTIL_CONN_NONE
+                    ""
                     );
                 if (!connectionTuple)
                     goto error;
                 if (PyList_Append(connectionsList, connectionTuple))
                     goto error;
                 Py_DECREF(connectionTuple);
             }
         }
@@ -1840,23 +1858,23 @@ get_process_connections(PyObject* self, 
                 else
                 {
                     addressTupleLocal = PyTuple_New(0);
                 }
 
                 if (addressTupleLocal == NULL)
                     goto error;
 
-                connectionTuple = Py_BuildValue("(iiiNNi)",
+                connectionTuple = Py_BuildValue("(iiiNNs)",
                     -1,
                     AF_INET6,
                     SOCK_DGRAM,
                     addressTupleLocal,
                     PyTuple_New(0),
-                    PSUTIL_CONN_NONE
+                    ""
                     );
                 if (!connectionTuple)
                     goto error;
                 if (PyList_Append(connectionsList, connectionTuple))
                     goto error;
                 Py_DECREF(connectionTuple);
             }
         }
@@ -2192,30 +2210,30 @@ get_disk_usage(PyObject* self, PyObject*
     return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
 }
 
 
 /*
  * Return a Python list of named tuples with overall network I/O information
  */
 static PyObject*
-get_net_io_counters(PyObject* self, PyObject* args)
+get_network_io_counters(PyObject* self, PyObject* args)
 {
     int attempts = 0;
     int outBufLen = 15000;
-    char ifname[2000];
     DWORD dwRetVal = 0;
     MIB_IFROW *pIfRow = NULL;
     ULONG flags = 0;
     ULONG family = AF_UNSPEC;
     PIP_ADAPTER_ADDRESSES pAddresses = NULL;
     PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
 
     PyObject* py_retdict = PyDict_New();
     PyObject* py_nic_info = NULL;
+    PyObject* py_pre_nic_name = NULL;
     PyObject* py_nic_name = NULL;
 
     if (py_retdict == NULL) {
         return NULL;
     }
     do {
         pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
         if (pAddresses == NULL) {
@@ -2238,16 +2256,17 @@ get_net_io_counters(PyObject* self, PyOb
 
     if (dwRetVal != NO_ERROR) {
         PyErr_SetString(PyExc_RuntimeError,  "GetAdaptersAddresses() failed.");
         goto error;
     }
 
     pCurrAddresses = pAddresses;
     while (pCurrAddresses) {
+        py_pre_nic_name = NULL;
         py_nic_name = NULL;
         py_nic_info = NULL;
         pIfRow = (MIB_IFROW *) malloc(sizeof(MIB_IFROW));
 
         if (pIfRow == NULL) {
             PyErr_NoMemory();
             goto error;
         }
@@ -2266,33 +2285,39 @@ get_net_io_counters(PyObject* self, PyOb
                                     pIfRow->dwInUcastPkts,
                                     pIfRow->dwInErrors,
                                     pIfRow->dwOutErrors,
                                     pIfRow->dwInDiscards,
                                     pIfRow->dwOutDiscards);
         if (!py_nic_info)
             goto error;
 
-        sprintf(ifname, "%wS", pCurrAddresses->FriendlyName);
-        py_nic_name = Py_BuildValue("s", ifname);
+        py_pre_nic_name = PyUnicode_FromWideChar(
+                                pCurrAddresses->FriendlyName,
+                                wcslen(pCurrAddresses->FriendlyName));
+        if (py_pre_nic_name == NULL)
+            goto error;
+        py_nic_name = PyUnicode_FromObject(py_pre_nic_name);
         if (py_nic_name == NULL)
             goto error;
         if (PyDict_SetItem(py_retdict, py_nic_name, py_nic_info))
             goto error;
+        Py_XDECREF(py_pre_nic_name);
         Py_XDECREF(py_nic_name);
         Py_XDECREF(py_nic_info);
 
         free(pIfRow);
         pCurrAddresses = pCurrAddresses->Next;
     }
 
     free(pAddresses);
     return py_retdict;
 
 error:
+    Py_XDECREF(py_pre_nic_name);
     Py_XDECREF(py_nic_name);
     Py_XDECREF(py_nic_info);
     Py_DECREF(py_retdict);
     if (pAddresses != NULL)
         free(pAddresses);
     if (pIfRow != NULL)
         free(pIfRow);
     return NULL;
@@ -2948,17 +2973,17 @@ PsutilMethods[] =
     {"get_system_boot_time", get_system_boot_time, METH_VARARGS,
         "Return the system boot time expressed in seconds since the epoch."},
     {"get_virtual_mem", get_virtual_mem, METH_VARARGS,
         "Return the total amount of physical memory, in bytes"},
     {"get_system_cpu_times", get_system_cpu_times, METH_VARARGS,
         "Return system per-cpu times as a list of tuples"},
     {"get_disk_usage", get_disk_usage, METH_VARARGS,
         "Return path's disk total and free as a Python tuple."},
-    {"get_net_io_counters", get_net_io_counters, METH_VARARGS,
+    {"get_network_io_counters", get_network_io_counters, METH_VARARGS,
         "Return dict of tuples of networks I/O information."},
     {"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
          "Return dict of tuples of disks I/O information."},
     {"get_system_users", get_system_users, METH_VARARGS,
         "Return a list of currently connected users."},
     {"get_disk_partitions", get_disk_partitions, METH_VARARGS,
         "Return disk partitions."},
 
@@ -3028,61 +3053,31 @@ struct module_state {
 
     st = GETSTATE(module);
     st->error = PyErr_NewException("_psutil_mswindow.Error", NULL, NULL);
     if (st->error == NULL) {
         Py_DECREF(module);
         INITERROR;
     }
 
-    // process status constants
+    // Public constants
     // http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx
     PyModule_AddIntConstant(module, "ABOVE_NORMAL_PRIORITY_CLASS",
                                      ABOVE_NORMAL_PRIORITY_CLASS);
     PyModule_AddIntConstant(module, "BELOW_NORMAL_PRIORITY_CLASS",
                                      BELOW_NORMAL_PRIORITY_CLASS);
     PyModule_AddIntConstant(module, "HIGH_PRIORITY_CLASS",
                                      HIGH_PRIORITY_CLASS);
     PyModule_AddIntConstant(module, "IDLE_PRIORITY_CLASS",
                                      IDLE_PRIORITY_CLASS);
     PyModule_AddIntConstant(module, "NORMAL_PRIORITY_CLASS",
                                      NORMAL_PRIORITY_CLASS);
     PyModule_AddIntConstant(module, "REALTIME_PRIORITY_CLASS",
                                      REALTIME_PRIORITY_CLASS);
-    // connection status constants
-    // http://msdn.microsoft.com/en-us/library/cc669305.aspx
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSED",
-                                     MIB_TCP_STATE_CLOSED);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSING",
-                                     MIB_TCP_STATE_CLOSING);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSE_WAIT",
-                                     MIB_TCP_STATE_CLOSE_WAIT);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_LISTEN",
-                                     MIB_TCP_STATE_LISTEN);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_ESTAB",
-                                     MIB_TCP_STATE_ESTAB);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_SYN_SENT",
-                                     MIB_TCP_STATE_SYN_SENT);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_SYN_RCVD",
-                                     MIB_TCP_STATE_SYN_RCVD);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_FIN_WAIT1",
-                                     MIB_TCP_STATE_FIN_WAIT1);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_FIN_WAIT2",
-                                     MIB_TCP_STATE_FIN_WAIT2);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_LAST_ACK",
-                                     MIB_TCP_STATE_LAST_ACK);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_TIME_WAIT",
-                                     MIB_TCP_STATE_TIME_WAIT);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_TIME_WAIT",
-                                     MIB_TCP_STATE_TIME_WAIT);
-    PyModule_AddIntConstant(module, "MIB_TCP_STATE_DELETE_TCB",
-                                     MIB_TCP_STATE_DELETE_TCB);
-    PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE",
-                                     PSUTIL_CONN_NONE);
-    // ...for internal use in _psutil_mswindows.py
+    // private constants
     PyModule_AddIntConstant(module, "INFINITE", INFINITE);
     PyModule_AddIntConstant(module, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED);
     SetSeDebug();
 
 #if PY_MAJOR_VERSION >= 3
     return module;
 #endif
 }
--- a/python/psutil/psutil/_psutil_mswindows.h
+++ b/python/psutil/psutil/_psutil_mswindows.h
@@ -54,17 +54,17 @@ static PyObject* kill_process(PyObject* 
 static PyObject* get_pid_list(PyObject* self, PyObject* args);
 static PyObject* get_num_cpus(PyObject* self, PyObject* args);
 static PyObject* get_system_boot_time(PyObject* self, PyObject* args);
 static PyObject* get_virtual_mem(PyObject* self, PyObject* args);
 static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);
 static PyObject* pid_exists(PyObject* self, PyObject* args);
 static PyObject* get_disk_usage(PyObject* self, PyObject* args);
 static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
-static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
+static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_system_users(PyObject* self, PyObject* args);
 
 // --- windows API bindings
 
 static PyObject* win32_QueryDosDevice(PyObject* self, PyObject* args);
 
 // --- internal
--- a/python/psutil/psutil/_psutil_osx.c
+++ b/python/psutil/psutil/_psutil_osx.c
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * OS X platform-specific module methods for _psutil_osx
  */
 
 #include <Python.h>
 #include <assert.h>
@@ -279,17 +279,17 @@ static PyObject*
 get_process_memory_maps(PyObject* self, PyObject* args)
 {
     char buf[PATH_MAX];
     char addr_str[34];
     char perms[8];
     int pagesize = getpagesize();
     long pid;
     kern_return_t err = KERN_SUCCESS;
-    mach_port_t task = MACH_PORT_NULL;
+    mach_port_t task;
     uint32_t depth = 1;
     vm_address_t address = 0;
     vm_size_t size = 0;
 
     PyObject* py_tuple = NULL;
     PyObject* py_list = PyList_New(0);
 
     if (py_list == NULL)
@@ -338,16 +338,18 @@ get_process_memory_maps(PyObject* self, 
             sprintf(perms, "%c%c%c/%c%c%c",
                     (info.protection & VM_PROT_READ) ? 'r' : '-',
                     (info.protection & VM_PROT_WRITE) ? 'w' : '-',
                     (info.protection & VM_PROT_EXECUTE) ? 'x' : '-',
                     (info.max_protection & VM_PROT_READ) ? 'r' : '-',
                     (info.max_protection & VM_PROT_WRITE) ? 'w' : '-',
                     (info.max_protection & VM_PROT_EXECUTE) ? 'x' : '-');
 
+            address += size;
+
             err = proc_regionfilename(pid, address, buf, sizeof(buf));
 
             if (info.share_mode == SM_COW && info.ref_count == 1) {
                 // Treat single reference SM_COW as SM_PRIVATE
                 info.share_mode = SM_PRIVATE;
             }
 
             if (strlen(buf) == 0) {
@@ -393,19 +395,16 @@ get_process_memory_maps(PyObject* self, 
                 info.shadow_depth                         // shadow depth
             );
             if (!py_tuple)
                 goto error;
             if (PyList_Append(py_list, py_tuple))
                 goto error;
             Py_DECREF(py_tuple);
         }
-
-        //increment address for the next map/file
-        address += size;
     }
 
     if (task != MACH_PORT_NULL)
         mach_port_deallocate(mach_task_self(), task);
 
     return py_list;
 
 error:
@@ -883,20 +882,20 @@ get_process_status(PyObject* self, PyObj
  */
 static PyObject*
 get_process_threads(PyObject* self, PyObject* args)
 {
     long pid;
     int err, j, ret;
     kern_return_t kr;
     unsigned int info_count = TASK_BASIC_INFO_COUNT;
-    mach_port_t task = MACH_PORT_NULL;
+    mach_port_t task;
     struct task_basic_info tasks_info;
     thread_act_port_array_t thread_list = NULL;
-    thread_info_data_t thinfo_basic;
+    thread_info_data_t thinfo;
     thread_basic_info_t basic_info_th;
     mach_msg_type_number_t thread_count, thread_info_count;
 
     PyObject* retList = PyList_New(0);
     PyObject* pyTuple = NULL;
 
     if (retList == NULL)
         return NULL;
@@ -937,25 +936,25 @@ get_process_threads(PyObject* self, PyOb
         PyErr_Format(PyExc_RuntimeError, "task_threads() failed");
         goto error;
     }
 
     for (j = 0; j < thread_count; j++) {
         pyTuple = NULL;
         thread_info_count = THREAD_INFO_MAX;
         kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
-                         (thread_info_t)thinfo_basic, &thread_info_count);
+                         (thread_info_t)thinfo, &thread_info_count);
         if (kr != KERN_SUCCESS) {
-            PyErr_Format(PyExc_RuntimeError, "thread_info() with flag THREAD_BASIC_INFO failed");
+            PyErr_Format(PyExc_RuntimeError, "thread_info() failed");
             goto error;
         }
-
-        basic_info_th = (thread_basic_info_t)thinfo_basic;
-        pyTuple = Py_BuildValue("Iff",
-                    j+1,
+        basic_info_th = (thread_basic_info_t)thinfo;
+        // XXX - thread_info structure does not provide any process id;
+        // the best we can do is assigning an incremental bogus value
+        pyTuple = Py_BuildValue("Iff", j + 1,
                     (float)basic_info_th->user_time.microseconds / 1000000.0,
                     (float)basic_info_th->system_time.microseconds / 1000000.0
                   );
         if (!pyTuple)
             goto error;
         if (PyList_Append(retList, pyTuple))
             goto error;
         Py_DECREF(pyTuple);
@@ -1098,18 +1097,50 @@ error:
     }
     else {
         // exception has already been set earlier
         return NULL;
     }
 }
 
 
-// a signaler for connections without an actual status
-static int PSUTIL_CONN_NONE = 128;
+/*
+ * mathes Linux net/tcp_states.h:
+ * http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
+ */
+static char *
+get_connection_status(int st) {
+    switch (st) {
+        case TCPS_CLOSED:
+            return "CLOSE";
+        case TCPS_CLOSING:
+            return "CLOSING";
+        case TCPS_CLOSE_WAIT:
+            return "CLOSE_WAIT";
+        case TCPS_LISTEN:
+            return "LISTEN";
+        case TCPS_ESTABLISHED:
+            return "ESTABLISHED";
+        case TCPS_SYN_SENT:
+            return "SYN_SENT";
+        case TCPS_SYN_RECEIVED:
+            return "SYN_RECV";
+        case TCPS_FIN_WAIT_1:
+            return "FIN_WAIT_1";
+        case TCPS_FIN_WAIT_2:
+            return "FIN_WAIT_2";
+        case TCPS_LAST_ACK:
+            return "LAST_ACK";
+        case TCPS_TIME_WAIT:
+            return "TIME_WAIT";
+        default:
+            return "";
+    }
+}
+
 
 /*
  * Return process TCP and UDP connections as a list of tuples.
  * References:
  * - lsof source code: http://goo.gl/SYW79 and http://goo.gl/wNrC0
  * - /usr/include/sys/proc_info.h
  */
 static PyObject*
@@ -1197,18 +1228,19 @@ get_process_connections(PyObject* self, 
             if (nb < sizeof(si)) {
                 PyErr_Format(PyExc_RuntimeError,
                  "proc_pidinfo(PROC_PIDFDVNODEPATHINFO) failed (buffer mismatch)");
                 goto error;
             }
             // --- /errors checking
 
             //
-            int fd, family, type, lport, rport, state;
+            int fd, family, type, lport, rport;
             char lip[200], rip[200];
+            char *state;
             int inseq;
             PyObject* _family;
             PyObject* _type;
 
             fd = (int)fdp_pointer->proc_fd;
             family = si.psi.soi_family;
             type = si.psi.soi_type;
 
@@ -1255,50 +1287,51 @@ get_process_connections(PyObject* self, 
                 if (errno != 0) {
                     PyErr_SetFromErrno(PyExc_OSError);
                     goto error;
                 }
 
                 lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
                 rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
                 if (type == SOCK_STREAM) {
-                    state = (int)si.psi.soi_proto.pri_tcp.tcpsi_state;
+                    state = get_connection_status((int)si.psi.soi_proto.pri_tcp.tcpsi_state);
                 }
+
                 else {
-                    state = PSUTIL_CONN_NONE;
+                    state = "";
                 }
 
                 laddr = Py_BuildValue("(si)", lip, lport);
                 if (!laddr)
                     goto error;
                 if (rport != 0) {
                     raddr = Py_BuildValue("(si)", rip, rport);
                 }
                 else {
                     raddr = Py_BuildValue("()");
                 }
                 if (!raddr)
                     goto error;
 
                 // construct the python list
-                tuple = Py_BuildValue("(iiiNNi)", fd, family, type, laddr, raddr,
+                tuple = Py_BuildValue("(iiiNNs)", fd, family, type, laddr, raddr,
                                                   state);
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
                     goto error;
                 Py_DECREF(tuple);
             }
             else if (family == AF_UNIX) {
                 // construct the python list
-                tuple = Py_BuildValue("(iiissi)",
+                tuple = Py_BuildValue("(iiisss)",
                     fd, family, type,
                     si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path,
                     si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path,
-                    PSUTIL_CONN_NONE);
+                    "");
                 if (!tuple)
                     goto error;
                 if (PyList_Append(retList, tuple))
                     goto error;
                 Py_DECREF(tuple);
             }
         }
     }
@@ -1364,17 +1397,17 @@ get_process_num_fds(PyObject* self, PyOb
     return Py_BuildValue("i", num);
 }
 
 
 /*
  * Return a Python list of named tuples with overall network I/O information
  */
 static PyObject*
-get_net_io_counters(PyObject* self, PyObject* args)
+get_network_io_counters(PyObject* self, PyObject* args)
 {
     char *buf = NULL, *lim, *next;
     struct if_msghdr *ifm;
     int mib[6];
     size_t len;
     PyObject* py_retdict = PyDict_New();
     PyObject* py_ifc_info = NULL;
 
@@ -1534,22 +1567,17 @@ get_disk_io_counters(PyObject* self, PyO
                                     CFSTR(kIOBlockStorageDriverStatisticsKey));
 
             if (stats_dict == NULL) {
                 PyErr_SetString(PyExc_RuntimeError, "Unable to get disk stats.");
                 goto error;
             }
 
             CFNumberRef number;
-            int64_t reads = 0;
-            int64_t writes = 0;
-            int64_t read_bytes = 0;
-            int64_t write_bytes = 0;
-            int64_t read_time = 0;
-            int64_t write_time = 0;
+            int64_t reads, writes, read_bytes, write_bytes, read_time, write_time = 0;
 
             /* Get disk reads/writes */
             if ((number = (CFNumberRef)CFDictionaryGetValue(
                             stats_dict,
                             CFSTR(kIOBlockStorageDriverStatisticsReadsKey))))
             {
                 CFNumberGetValue(number, kCFNumberSInt64Type, &reads);
             }
@@ -1722,17 +1750,17 @@ PsutilMethods[] =
          "Return system cpu times as a tuple (user, system, nice, idle, irc)"},
      {"get_system_per_cpu_times", get_system_per_cpu_times, METH_VARARGS,
          "Return system per-cpu times as a list of tuples"},
      {"get_system_boot_time", get_system_boot_time, METH_VARARGS,
          "Return the system boot time expressed in seconds since the epoch."},
      {"get_disk_partitions", get_disk_partitions, METH_VARARGS,
          "Return a list of tuples including device, mount point and "
          "fs type for all partitions mounted on the system."},
-     {"get_net_io_counters", get_net_io_counters, METH_VARARGS,
+     {"get_network_io_counters", get_network_io_counters, METH_VARARGS,
          "Return dict of tuples of networks I/O information."},
      {"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
          "Return dict of tuples of disks I/O information."},
      {"get_system_users", get_system_users, METH_VARARGS,
         "Return currently connected users as a list of tuples"},
 
      {NULL, NULL, 0, NULL}
 };
@@ -1795,29 +1823,16 @@ init_psutil_osx(void)
 #endif
     // process status constants, defined in:
     // http://fxr.watson.org/fxr/source/bsd/sys/proc.h?v=xnu-792.6.70#L149
     PyModule_AddIntConstant(module, "SIDL", SIDL);
     PyModule_AddIntConstant(module, "SRUN", SRUN);
     PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
     PyModule_AddIntConstant(module, "SSTOP", SSTOP);
     PyModule_AddIntConstant(module, "SZOMB", SZOMB);
-    // connection status constants
-    PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
-    PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
-    PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
-    PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
-    PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
-    PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
-    PyModule_AddIntConstant(module, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
-    PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
-    PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
-    PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
 
     if (module == NULL) {
         INITERROR;
     }
 #if PY_MAJOR_VERSION >= 3
     return module;
 #endif
 }
--- a/python/psutil/psutil/_psutil_osx.h
+++ b/python/psutil/psutil/_psutil_osx.h
@@ -32,11 +32,11 @@ static PyObject* get_process_memory_maps
 static PyObject* get_pid_list(PyObject* self, PyObject* args);
 static PyObject* get_num_cpus(PyObject* self, PyObject* args);
 static PyObject* get_virtual_mem(PyObject* self, PyObject* args);
 static PyObject* get_swap_mem(PyObject* self, PyObject* args);
 static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);
 static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
 static PyObject* get_system_boot_time(PyObject* self, PyObject* args);
 static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
-static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
+static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
 static PyObject* get_system_users(PyObject* self, PyObject* args);
--- a/python/psutil/psutil/_psutil_posix.c
+++ b/python/psutil/psutil/_psutil_posix.c
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * Functions specific to all POSIX compliant platforms.
  */
 
 #include <Python.h>
 #include <errno.h>
@@ -122,8 +122,11 @@ void init_psutil_posix(void)
 #endif
     if (module == NULL) {
         INITERROR;
     }
 #if PY_MAJOR_VERSION >= 3
     return module;
 #endif
 }
+
+
+
--- a/python/psutil/psutil/_psutil_posix.h
+++ b/python/psutil/psutil/_psutil_posix.h
@@ -1,10 +1,10 @@
 /*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+ * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file.
  *
  * POSIX specific module methods for _psutil_posix
  */
 
 #include <Python.h>
 
deleted file mode 100644
--- a/python/psutil/psutil/_psutil_sunos.c
+++ /dev/null
@@ -1,1194 +0,0 @@
-/*
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * Functions specific to Sun OS Solaris platforms.
- *
- * Thanks to Justin Venus who originally wrote a consistent part of
- * this in Cython which I later on translated in C.
- */
-
-#include <Python.h>
-
-// fix for "Cannot use procfs in the large file compilation environment"
-// error, see:
-// http://sourceware.org/ml/gdb-patches/2010-11/msg00336.html
-#undef _FILE_OFFSET_BITS
-#define _STRUCTURED_PROC 1
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/proc.h>
-#include <sys/swap.h>
-#include <sys/sysinfo.h>
-#include <sys/mntent.h>  // for MNTTAB
-#include <sys/mnttab.h>
-#include <sys/procfs.h>
-#include <fcntl.h>
-#include <utmpx.h>
-#include <kstat.h>
-#include <sys/ioctl.h>
-#include <sys/tihdr.h>
-#include <stropts.h>
-#include <inet/tcp.h>
-#include <arpa/inet.h>
-
-#include "_psutil_sunos.h"
-
-
-#define TV2DOUBLE(t)   (((t).tv_nsec * 0.000000001) + (t).tv_sec)
-
-/*
- * Read a file content and fills a C structure with it.
- */
-int
-psutil_file_to_struct(char *path, void *fstruct, size_t size)
-{
-    int fd;
-    size_t nbytes;
-    fd = open(path, O_RDONLY);
-    if (fd == -1) {
-        PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
-        return 0;
-    }
-    nbytes = read(fd, fstruct, size);
-    if (nbytes <= 0) {
-        close(fd);
-        PyErr_SetFromErrno(PyExc_OSError);
-        return 0;
-    }
-    if (nbytes != size) {
-        close(fd);
-        PyErr_SetString(PyExc_RuntimeError, "structure size mismatch");
-        return 0;
-    }
-    close(fd);
-    return nbytes;
-}
-
-
-/*
- * Return process ppid, rss, vms, ctime, nice, nthreads, status and tty
- * as a Python tuple.
- */
-static PyObject*
-get_process_basic_info(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    psinfo_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid))
-        return NULL;
-    sprintf(path, "/proc/%i/psinfo", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    return Py_BuildValue("ikkdiiik",
-                         info.pr_ppid,              // parent pid
-                         info.pr_rssize,            // rss
-                         info.pr_size,              // vms
-                         TV2DOUBLE(info.pr_start),  // create time
-                         info.pr_lwp.pr_nice,       // nice
-                         info.pr_nlwp,              // no. of threads
-                         info.pr_lwp.pr_state,      // status code
-                         info.pr_ttydev             // tty nr
-                         );
-}
-
-
-/*
- * Return process name and args as a Python tuple.
- */
-static PyObject*
-get_process_name_and_args(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    psinfo_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid))
-        return NULL;
-    sprintf(path, "/proc/%i/psinfo", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    return Py_BuildValue("ss", info.pr_fname,
-                               info.pr_psargs);
-}
-
-
-/*
- * Return process user and system CPU times as a Python tuple.
- */
-static PyObject*
-get_process_cpu_times(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    pstatus_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid))
-        return NULL;
-    sprintf(path, "/proc/%i/status", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    // results are more precise than os.times()
-    return Py_BuildValue("dd", TV2DOUBLE(info.pr_utime),
-                               TV2DOUBLE(info.pr_stime));
-}
-
-
-/*
- * Return process uids/gids as a Python tuple.
- */
-static PyObject*
-get_process_cred(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    prcred_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid))
-        return NULL;
-    sprintf(path, "/proc/%i/cred", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    return Py_BuildValue("iiiiii", info.pr_ruid, info.pr_euid, info.pr_suid,
-                                   info.pr_rgid, info.pr_egid, info.pr_sgid);
-}
-
-
-/*
- * Return process uids/gids as a Python tuple.
- */
-static PyObject*
-get_process_num_ctx_switches(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    prusage_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid))
-        return NULL;
-    sprintf(path, "/proc/%i/usage", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    return Py_BuildValue("kk", info.pr_vctx, info.pr_ictx);
-}
-
-
-/*
- * Process IO counters.
- *
- * Commented out and left here as a reminder.  Apparently we cannot
- * retrieve process IO stats because:
- * - 'pr_ioch' is a sum of chars read and written, with no distinction
- * - 'pr_inblk' and 'pr_oublk', which should be the number of bytes
- *    read and written, hardly increase and according to:
- *    http://www.brendangregg.com/Perf/paper_diskubyp1.pdf
- *    ...they should be meaningless anyway.
- *
-static PyObject*
-get_process_io_counters(PyObject* self, PyObject* args)
-{
-    int pid;
-    char path[100];
-    prusage_t info;
-
-    if (! PyArg_ParseTuple(args, "i", &pid)) {
-        return NULL;
-    }
-    sprintf(path, "/proc/%i/usage", pid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) {
-        return NULL;
-    }
-
-    // On Solaris we only have 'pr_ioch' which accounts for bytes read
-    // *and* written.
-    // 'pr_inblk' and 'pr_oublk' should be expressed in blocks of
-    // 8KB according to:
-    // http://www.brendangregg.com/Perf/paper_diskubyp1.pdf  (pag. 8)
-    return Py_BuildValue("kkkk", info.pr_ioch,
-                                 info.pr_ioch,
-                                 info.pr_inblk,
-                                 info.pr_oublk);
-}
- */
-
-
-/*
- * Return information about a given process thread.
- */
-static PyObject*
-query_process_thread(PyObject* self, PyObject* args)
-{
-    int pid, tid;
-    char path[100];
-    lwpstatus_t info;
-
-    if (! PyArg_ParseTuple(args, "ii", &pid, &tid))
-        return NULL;
-    sprintf(path, "/proc/%i/lwp/%i/lwpstatus", pid, tid);
-    if (! psutil_file_to_struct(path, (void *)&info, sizeof(info)))
-        return NULL;
-    return Py_BuildValue("dd", TV2DOUBLE(info.pr_utime),
-                               TV2DOUBLE(info.pr_stime));
-}
-
-
-/*
- * Return information about system virtual memory.
- */
-static PyObject*
-get_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
-// code below is exactly the same as:
-// http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/swap/swap.c
-// We're going to parse "swap -l" output from Python (sigh!)
-
-/*
-    struct swaptable     *st;
-    struct swapent    *swapent;
-    int    i;
-    struct stat64 statbuf;
-    char *path;
-    char fullpath[MAXPATHLEN+1];
-    int    num;
-
-    if ((num = swapctl(SC_GETNSWP, NULL)) == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        return NULL;
-    }
-    if (num == 0) {
-        PyErr_SetString(PyExc_RuntimeError, "no swap devices configured");
-        return NULL;
-    }
-    if ((st = malloc(num * sizeof(swapent_t) + sizeof (int))) == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "malloc failed");
-        return NULL;
-    }
-    if ((path = malloc(num * MAXPATHLEN)) == NULL) {
-        PyErr_SetString(PyExc_RuntimeError, "malloc failed");
-        return NULL;
-    }
-    swapent = st->swt_ent;
-    for (i = 0; i < num; i++, swapent++) {
-        swapent->ste_path = path;
-        path += MAXPATHLEN;
-    }
-    st->swt_n = num;
-    if ((num = swapctl(SC_LIST, st)) == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        return NULL;
-    }
-
-    swapent = st->swt_ent;
-    long t = 0, f = 0;
-    for (i = 0; i < num; i++, swapent++) {
-        int diskblks_per_page =(int)(sysconf(_SC_PAGESIZE) >> DEV_BSHIFT);
-        t += (long)swapent->ste_pages;
-        f += (long)swapent->ste_free;
-    }
-
-    free(st);
-    return Py_BuildValue("(kk)", t, f);
-*/
-
-    kstat_ctl_t    *kc;
-    kstat_t        *k;
-    cpu_stat_t    *cpu;
-    int            cpu_count = 0;
-    int         flag = 0;
-    uint_t      sin = 0;
-    uint_t      sout = 0;
-
-    kc = kstat_open();
-    if (kc == NULL) {
-        return PyErr_SetFromErrno(PyExc_OSError);;
-    }
-
-    k = kc->kc_chain;
-      while (k != NULL) {
-        if((strncmp(k->ks_name, "cpu_stat", 8) == 0) && \
-            (kstat_read(kc, k, NULL) != -1) )
-        {
-            flag = 1;
-            cpu = (cpu_stat_t*) k->ks_data;
-            sin += cpu->cpu_vminfo.pgswapin;    // num pages swapped in
-            sout += cpu->cpu_vminfo.pgswapout;  // num pages swapped out
-        }
-        cpu_count += 1;
-        k = k->ks_next;
-    }
-    kstat_close(kc);
-    if (!flag) {
-        PyErr_SetString(PyExc_RuntimeError, "no swap device was found");
-        return NULL;
-    }
-    return Py_BuildValue("(II)", sin, sout);
-}
-
-
-/*
- * Return users currently connected on the system.
- */
-static PyObject*
-get_system_users(PyObject* self, PyObject* args)
-{
-    struct utmpx *ut;
-    PyObject *ret_list = PyList_New(0);
-    PyObject *tuple = NULL;
-    PyObject *user_proc = NULL;
-
-    if (ret_list == NULL)
-        return NULL;
-
-    while (NULL != (ut = getutxent())) {
-        if (ut->ut_type == USER_PROCESS)
-            user_proc = Py_True;
-        else
-            user_proc = Py_False;
-        tuple = Py_BuildValue("(sssfO)",
-            ut->ut_user,              // username
-            ut->ut_line,              // tty
-            ut->ut_host,              // hostname
-            (float)ut->ut_tv.tv_sec,  // tstamp
-            user_proc                 // (bool) user process
-        );
-        if (tuple == NULL)
-            goto error;
-        if (PyList_Append(ret_list, tuple))
-            goto error;
-        Py_DECREF(tuple);
-    }
-    endutent();
-
-    return ret_list;
-
-error:
-    Py_XDECREF(tuple);
-    Py_DECREF(ret_list);
-    if (ut != NULL)
-        endutent();
-    return NULL;
-}
-
-
-/*
- * Return disk mounted partitions as a list of tuples including device,
- * mount point and filesystem type.
- */
-static PyObject*
-get_disk_partitions(PyObject* self, PyObject* args)
-{
-    FILE *file;
-    struct mnttab mt;
-    PyObject* py_retlist = PyList_New(0);
-    PyObject* py_tuple = NULL;
-
-    if (py_retlist == NULL)
-        return NULL;
-
-    file = fopen(MNTTAB, "rb");
-    if (file == NULL) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-
-    while (getmntent(file, &mt) == 0) {
-        py_tuple = Py_BuildValue("(ssss)", mt.mnt_special,  // device
-                                           mt.mnt_mountp,     // mount point
-                                           mt.mnt_fstype,    // fs type
-                                           mt.mnt_mntopts);   // options
-        if (py_tuple == NULL)
-            goto error;
-        if (PyList_Append(py_retlist, py_tuple))
-            goto error;
-        Py_DECREF(py_tuple);
-
-    }
-    fclose(file);
-    return py_retlist;
-
-error:
-    Py_XDECREF(py_tuple);
-    Py_DECREF(py_retlist);
-    if (file != NULL)
-        fclose(file);
-    return NULL;
-}
-
-
-/*
- * Return system-wide CPU times.
- */
-static PyObject*
-get_system_per_cpu_times(PyObject* self, PyObject* args)
-{
-    kstat_ctl_t *kc;
-    kstat_t *ksp;
-    cpu_stat_t cs;
-    int numcpus;
-    int i;
-    PyObject* py_retlist = PyList_New(0);
-    PyObject* py_cputime = NULL;
-
-    if (py_retlist == NULL)
-        return NULL;
-
-    kc = kstat_open();
-    if (kc == NULL) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-
-    numcpus = sysconf(_SC_NPROCESSORS_ONLN) - 1;
-    for (i=0; i<=numcpus; i++) {
-        ksp = kstat_lookup(kc, "cpu_stat", i, NULL);
-        if (ksp == NULL) {
-            PyErr_SetFromErrno(PyExc_OSError);
-            goto error;
-        }
-        if (kstat_read(kc, ksp, &cs) == -1) {
-            PyErr_SetFromErrno(PyExc_OSError);
-            goto error;
-        }
-
-        py_cputime = Py_BuildValue("ffff",
-                                   (float)cs.cpu_sysinfo.cpu[CPU_USER],
-                                   (float)cs.cpu_sysinfo.cpu[CPU_KERNEL],
-                                   (float)cs.cpu_sysinfo.cpu[CPU_IDLE],
-                                   (float)cs.cpu_sysinfo.cpu[CPU_WAIT]);
-        if (py_cputime == NULL)
-            goto error;
-        if (PyList_Append(py_retlist, py_cputime))
-            goto error;
-        Py_DECREF(py_cputime);
-
-    }
-
-    kstat_close(kc);
-    return py_retlist;
-
-error:
-    Py_XDECREF(py_cputime);
-    Py_DECREF(py_retlist);
-    if (kc != NULL)
-        kstat_close(kc);
-    return NULL;
-}
-
-
-/*
- * Return disk IO statistics.
- */
-static PyObject*
-get_disk_io_counters(PyObject* self, PyObject* args)
-{
-    kstat_ctl_t *kc;
-    kstat_t *ksp;
-    kstat_io_t kio;
-    PyObject* py_retdict = PyDict_New();
-    PyObject* py_disk_info = NULL;
-
-    if (py_retdict == NULL)
-        return NULL;
-    kc = kstat_open();
-    if (kc == NULL) {
-        PyErr_SetFromErrno(PyExc_OSError);;
-        goto error;
-    }
-    ksp = kc->kc_chain;
-    while (ksp != NULL) {
-        if (ksp->ks_type == KSTAT_TYPE_IO) {
-            if (strcmp(ksp->ks_class, "disk") == 0) {
-                if (kstat_read(kc, ksp, &kio) == -1) {
-                    kstat_close(kc);
-                    return PyErr_SetFromErrno(PyExc_OSError);;
-                }
-                py_disk_info = Py_BuildValue("(IIKKLL)",
-                     kio.reads,
-                     kio.writes,
-                     kio.nread,
-                     kio.nwritten,
-                     kio.rtime / 1000 / 1000,  // from nano to milli secs
-                     kio.wtime / 1000 / 1000   // from nano to milli secs
-                );
-
-                if (!py_disk_info)
-                    goto error;
-                if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_disk_info))
-                    goto error;
-                Py_DECREF(py_disk_info);
-            }
-        }
-        ksp = ksp->ks_next;
-    }
-    kstat_close(kc);
-
-    return py_retdict;
-
-error:
-    Py_XDECREF(py_disk_info);
-    Py_DECREF(py_retdict);
-    if (kc != NULL)
-        kstat_close(kc);
-    return NULL;
-}
-
-
-/*
- * Return process memory mappings.
- */
-static PyObject*
-get_process_memory_maps(PyObject* self, PyObject* args)
-{
-    int pid;
-    int fd = -1;
-    char path[100];
-    char perms[10];
-    char *name;
-    struct stat st;
-    pstatus_t status;
-
-    prxmap_t *xmap = NULL, *p;
-    off_t size;
-    size_t nread;
-    int nmap;
-    uintptr_t pr_addr_sz;
-    uintptr_t stk_base_sz, brk_base_sz;
-
-    PyObject* pytuple = NULL;
-    PyObject* py_retlist = PyList_New(0);
-
-    if (py_retlist == NULL) {
-        return NULL;
-    }
-    if (! PyArg_ParseTuple(args, "i", &pid)) {
-        goto error;
-    }
-
-    sprintf(path, "/proc/%i/status", pid);
-    if (! psutil_file_to_struct(path, (void *)&status, sizeof(status))) {
-        goto error;
-    }
-
-    sprintf(path, "/proc/%i/xmap", pid);
-    if (stat(path, &st) == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-
-    size = st.st_size;
-
-    fd = open(path, O_RDONLY);
-    if (fd == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-
-    xmap = (prxmap_t *)malloc(size);
-    if (xmap == NULL) {
-        PyErr_NoMemory();
-        goto error;
-    }
-
-    nread = pread(fd, xmap, size, 0);
-    nmap = nread / sizeof(prxmap_t);
-    p = xmap;
-
-    while (nmap) {
-        nmap -= 1;
-        if (p == NULL) {
-            p += 1;
-            continue;
-        }
-
-        perms[0] = '\0';
-        pr_addr_sz = p->pr_vaddr + p->pr_size;
-
-        // perms
-        sprintf(perms, "%c%c%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-',
-                                       p->pr_mflags & MA_WRITE ? 'w' : '-',
-                                       p->pr_mflags & MA_EXEC ? 'x' : '-',
-                                       p->pr_mflags & MA_SHARED ? 's' : '-',
-                                       p->pr_mflags & MA_NORESERVE ? 'R' : '-',
-                                       p->pr_mflags & MA_RESERVED1 ? '*' : ' ');
-
-        // name
-        if (strlen(p->pr_mapname) > 0) {
-            name = p->pr_mapname;
-        }
-        else {
-            if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) {
-                name = "[shmid]";
-            }
-            else {
-                stk_base_sz = status.pr_stkbase + status.pr_stksize;
-                brk_base_sz = status.pr_brkbase + status.pr_brksize;
-
-                if ((pr_addr_sz > status.pr_stkbase) && (p->pr_vaddr < stk_base_sz)) {
-                    name = "[stack]";
-                }
-                else if ((p->pr_mflags & MA_ANON) && \
-                         (pr_addr_sz > status.pr_brkbase) && \
-                         (p->pr_vaddr < brk_base_sz)) {
-                    name = "[heap]";
-                }
-                else {
-                    name = "[anon]";
-                }
-            }
-        }
-
-        pytuple = Py_BuildValue("iisslll",
-                                    p->pr_vaddr,
-                                    pr_addr_sz,
-                                    perms,
-                                    name,
-                                    (long)p->pr_rss * p->pr_pagesize,
-                                    (long)p->pr_anon * p->pr_pagesize,
-                                    (long)p->pr_locked * p->pr_pagesize);
-        if (!pytuple)
-            goto error;
-        if (PyList_Append(py_retlist, pytuple))
-            goto error;
-        Py_DECREF(pytuple);
-
-        // increment pointer
-        p += 1;
-    }
-
-    close(fd);
-    free(xmap);
-    return py_retlist;
-
-error:
-    if (fd != -1)
-        close(fd);
-    Py_XDECREF(pytuple);
-    Py_DECREF(py_retlist);
-    if (xmap != NULL)
-        free(xmap);
-    return NULL;
-}
-
-
-/*
- * Return a list of tuples for network I/O statistics.
- */
-static PyObject*
-get_net_io_counters(PyObject* self, PyObject* args)
-{
-    kstat_ctl_t    *kc = NULL;
-    kstat_t *ksp;
-    kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
-
-    PyObject* py_retdict = PyDict_New();
-    PyObject* py_ifc_info = NULL;
-
-    if (py_retdict == NULL)
-        return NULL;
-    kc = kstat_open();
-    if (kc == NULL)
-        goto error;
-
-    ksp = kc->kc_chain;
-    while (ksp != NULL) {
-        if (ksp->ks_type != KSTAT_TYPE_NAMED)
-            goto next;
-        if (strcmp(ksp->ks_class, "net") != 0)
-            goto next;
-        /*
-        // XXX "lo" (localhost) interface makes kstat_data_lookup() fail
-        // (maybe because "ifconfig -a" says it's a virtual interface?).
-        if ((strcmp(ksp->ks_module, "link") != 0) &&
-            (strcmp(ksp->ks_module, "lo") != 0)) {
-            goto skip;
-        */
-        if ((strcmp(ksp->ks_module, "link") != 0)) {
-            goto next;
-        }
-
-        if (kstat_read(kc, ksp, NULL) == -1) {
-            errno = 0;
-            continue;
-        }
-
-        rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
-        wbytes = (kstat_named_t *)kstat_data_lookup(ksp, "obytes");
-        rpkts = (kstat_named_t *)kstat_data_lookup(ksp, "ipackets");
-        wpkts = (kstat_named_t *)kstat_data_lookup(ksp, "opackets");
-        ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors");
-        oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors");
-
-        if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) ||
-            (wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL))
-        {
-            PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed");
-            goto error;
-        }
-
-#if defined(_INT64_TYPE)
-        py_ifc_info = Py_BuildValue("(KKKKkkii)", rbytes->value.ui64,
-                                                  wbytes->value.ui64,
-                                                  rpkts->value.ui64,
-                                                  wpkts->value.ui64,
-                                                  ierrs->value.ui32,
-                                                  oerrs->value.ui32,
-#else
-        py_ifc_info = Py_BuildValue("(kkkkkkii)", rbytes->value.ui32,
-                                                  wbytes->value.ui32,
-                                                  rpkts->value.ui32,
-                                                  wpkts->value.ui32,
-                                                  ierrs->value.ui32,
-                                                  oerrs->value.ui32,
-#endif
-                                                  0,  // dropin not supported
-                                                  0   // dropout not supported
-                                    );
-        if (!py_ifc_info)
-            goto error;
-        if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
-            goto error;
-        Py_DECREF(py_ifc_info);
-        goto next;
-
-        next:
-            ksp = ksp->ks_next;
-    }
-
-    kstat_close(kc);
-    return py_retdict;
-
-error:
-    Py_XDECREF(py_ifc_info);
-    Py_DECREF(py_retdict);
-    if (kc != NULL)
-        kstat_close(kc);
-    return NULL;
-}
-
-
-#define EXPER_IP_AND_ALL_IRES   (1024+4)
-
-// a signaler for connections without an actual status
-static int PSUTIL_CONN_NONE = 128;
-
-/*
- * Return TCP and UDP connections opened by process.
- *
- * Thanks to:
- * https://github.com/DavidGriffith/finx/blob/master/nxsensor-3.5.0-1/src/sysdeps/solaris.c
- * ...and:
- * https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/cmd-inet/usr.bin/netstat/netstat.c
- */
-static PyObject*
-get_process_connections(PyObject* self, PyObject* args)
-{
-    long pid;
-    int sd = NULL;
-    mib2_tcpConnEntry_t *tp = NULL;
-    mib2_udpEntry_t     *ude;
-#if defined(AF_INET6)
-    mib2_tcp6ConnEntry_t *tp6;
-    mib2_udp6Entry_t     *ude6;
-#endif
-    char buf[512];
-    int i, flags, getcode, num_ent, state;
-    char lip[200], rip[200];
-    int lport, rport;
-    struct strbuf ctlbuf, databuf;
-    struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf;
-    struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf;
-    struct T_error_ack   *tea = (struct T_error_ack *)buf;
-    struct opthdr        *mibhdr;
-
-    PyObject *py_retlist = PyList_New(0);
-    PyObject *py_tuple = NULL;
-    PyObject *py_laddr = NULL;
-    PyObject *py_raddr = NULL;
-    PyObject *af_filter = NULL;
-    PyObject *type_filter = NULL;
-
-    if (py_retlist == NULL)
-        return NULL;
-    if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter))
-        goto error;
-    if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
-        PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
-        goto error;
-    }
-
-    sd = open("/dev/arp", O_RDWR);
-    if (sd == -1) {
-        PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp");
-        goto error;
-    }
-
-    /*
-    XXX - These 2 are used in ifconfig.c but they seem unnecessary
-    ret = ioctl(sd, I_PUSH, "tcp");
-    if (ret == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-    ret = ioctl(sd, I_PUSH, "udp");
-    if (ret == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-    */
-
-    // OK, this mess is basically copied and pasted from nxsensor project
-    // which copied and pasted it from netstat source code, mibget()
-    // function.  Also see:
-    // http://stackoverflow.com/questions/8723598/
-    tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
-    tor->OPT_offset = sizeof (struct T_optmgmt_req);
-    tor->OPT_length = sizeof (struct opthdr);
-    tor->MGMT_flags = T_CURRENT;
-    mibhdr = (struct opthdr *)&tor[1];
-    mibhdr->level = EXPER_IP_AND_ALL_IRES;
-    mibhdr->name  = 0;
-    mibhdr->len   = 0;
-
-    ctlbuf.buf = buf;
-    ctlbuf.len = tor->OPT_offset + tor->OPT_length;
-    flags = 0;  // request to be sent in non-priority
-
-    if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
-        PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
-    }
-
-    mibhdr = (struct opthdr *)&toa[1];
-    ctlbuf.maxlen = sizeof (buf);
-
-    for (;;) {
-        flags = 0;
-        getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
-
-        if (getcode != MOREDATA ||
-            ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
-            toa->PRIM_type != T_OPTMGMT_ACK ||
-            toa->MGMT_flags != T_SUCCESS)
-        {
-             break;
-        }
-        if (ctlbuf.len >= sizeof (struct T_error_ack) &&
-            tea->PRIM_type == T_ERROR_ACK)
-        {
-            PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK");
-            goto error;
-        }
-        if (getcode == 0 &&
-            ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
-            toa->PRIM_type == T_OPTMGMT_ACK &&
-            toa->MGMT_flags == T_SUCCESS)
-        {
-            PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK");
-            goto error;
-        }
-
-        databuf.maxlen = mibhdr->len;
-        databuf.len = 0;
-        databuf.buf = (char *)malloc((int)mibhdr->len);
-        if (!databuf.buf) {
-            //perror("malloc");
-            //break;
-            PyErr_NoMemory();
-            goto error;
-        }
-
-        flags = 0;
-        getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
-        if (getcode < 0) {
-            PyErr_SetFromErrno(PyExc_OSError);
-            goto error;
-        }
-
-        // TCPv4
-        if (mibhdr->level == MIB2_TCP && mibhdr->name == MIB2_TCP_13) {
-            tp = (mib2_tcpConnEntry_t *)databuf.buf;
-            num_ent = mibhdr->len / sizeof(mib2_tcpConnEntry_t);
-            for (i = 0; i < num_ent; i++, tp++) {
-                // check PID
-                if (tp->tcpConnCreationProcess != pid)
-                    continue;
-                // construct local/remote addresses
-                inet_ntop(AF_INET, &tp->tcpConnLocalAddress, lip, sizeof(lip));
-                inet_ntop(AF_INET, &tp->tcpConnRemAddress, rip, sizeof(rip));
-                lport = tp->tcpConnLocalPort;
-                rport = tp->tcpConnRemPort;
-
-                // contruct python tuple/list
-                py_laddr = Py_BuildValue("(si)", lip, lport);
-                if (!py_laddr)
-                    goto error;
-                if (rport != 0) {
-                    py_raddr = Py_BuildValue("(si)", rip, rport);
-                }
-                else {
-                    py_raddr = Py_BuildValue("()");
-                }
-                if (!py_raddr)
-                    goto error;
-                state = tp->tcpConnEntryInfo.ce_state;
-
-                // add item
-                py_tuple = Py_BuildValue("(iiiNNi)", -1, AF_INET, SOCK_STREAM,
-                                                     py_laddr, py_raddr, state);
-                if (!py_tuple) {
-                    goto error;
-                }
-                if (PyList_Append(py_retlist, py_tuple))
-                    goto error;
-                Py_DECREF(py_tuple);
-            }
-        }
-#if defined(AF_INET6)
-        // TCPv6
-        else if (mibhdr->level == MIB2_TCP6 && mibhdr->name == MIB2_TCP6_CONN) {
-            tp6 = (mib2_tcp6ConnEntry_t *)databuf.buf;
-            num_ent = mibhdr->len / sizeof(mib2_tcp6ConnEntry_t);
-
-            for (i = 0; i < num_ent; i++, tp6++) {
-                // check PID
-                if (tp6->tcp6ConnCreationProcess != pid)
-                    continue;
-                // construct local/remote addresses
-                inet_ntop(AF_INET6, &tp6->tcp6ConnLocalAddress, lip, sizeof(lip));
-                inet_ntop(AF_INET6, &tp6->tcp6ConnRemAddress, rip, sizeof(rip));
-                lport = tp6->tcp6ConnLocalPort;
-                rport = tp6->tcp6ConnRemPort;
-
-                // contruct python tuple/list
-                py_laddr = Py_BuildValue("(si)", lip, lport);
-                if (!py_laddr)
-                    goto error;
-                if (rport != 0) {
-                    py_raddr = Py_BuildValue("(si)", rip, rport);
-                }
-                else {
-                    py_raddr = Py_BuildValue("()");
-                }
-                if (!py_raddr)
-                    goto error;
-                state = tp6->tcp6ConnEntryInfo.ce_state;
-
-                // add item
-                py_tuple = Py_BuildValue("(iiiNNi)", -1, AF_INET6, SOCK_STREAM,
-                                                     py_laddr, py_raddr, state);
-
-                if (!py_tuple) {
-                    goto error;
-                }
-                if (PyList_Append(py_retlist, py_tuple))
-                    goto error;
-                Py_DECREF(py_tuple);
-            }
-        }
-#endif
-        else if (mibhdr->level == MIB2_UDP || mibhdr->level == MIB2_UDP_ENTRY) {
-            ude = (mib2_udpEntry_t *)databuf.buf;
-            num_ent = mibhdr->len / sizeof(mib2_udpEntry_t);
-            for (i = 0; i < num_ent; i++, ude++) {
-                // check PID
-                if (ude->udpCreationProcess != pid)
-                    continue;
-                inet_ntop(AF_INET, &ude->udpLocalAddress, lip, sizeof(lip));
-                lport = ude->udpLocalPort;
-                py_laddr = Py_BuildValue("(si)", lip, lport);
-                if (!py_laddr)
-                    goto error;
-                py_raddr = Py_BuildValue("()");
-                if (!py_raddr)
-                    goto error;
-                py_tuple = Py_BuildValue("(iiiNNi)", -1, AF_INET, SOCK_DGRAM,
-                                                     py_laddr, py_raddr,
-                                                     PSUTIL_CONN_NONE);
-                if (!py_tuple) {
-                    goto error;
-                }
-                if (PyList_Append(py_retlist, py_tuple))
-                    goto error;
-                Py_DECREF(py_tuple);
-            }
-        }
-#if defined(AF_INET6)
-        else if (mibhdr->level == MIB2_UDP6 || mibhdr->level == MIB2_UDP6_ENTRY) {
-            ude6 = (mib2_udp6Entry_t *)databuf.buf;
-            num_ent = mibhdr->len / sizeof(mib2_udp6Entry_t);
-            for (i = 0; i < num_ent; i++, ude6++) {
-                // check PID
-                if (ude6->udp6CreationProcess != pid)
-                    continue;
-                inet_ntop(AF_INET6, &ude6->udp6LocalAddress, lip, sizeof(lip));
-                lport = ude6->udp6LocalPort;
-                py_laddr = Py_BuildValue("(si)", lip, lport);
-                if (!py_laddr)
-                    goto error;
-                py_raddr = Py_BuildValue("()");
-                if (!py_raddr)
-                    goto error;
-                py_tuple = Py_BuildValue("(iiiNNi)", -1, AF_INET6, SOCK_DGRAM,
-                                                     py_laddr, py_raddr,
-                                                     PSUTIL_CONN_NONE);
-                if (!py_tuple) {
-                    goto error;
-                }
-                if (PyList_Append(py_retlist, py_tuple))
-                    goto error;
-                Py_DECREF(py_tuple);
-            }
-        }
-#endif
-        free(databuf.buf);
-    }
-
-    close(sd);
-    return py_retlist;
-
-error:
-    Py_XDECREF(py_tuple);
-    Py_XDECREF(py_laddr);
-    Py_XDECREF(py_raddr);
-    Py_DECREF(py_retlist);
-    // TODO : free databuf
-    if (sd != NULL)
-        close(sd);
-    return NULL;
-}
-
-
-/*
- * define the psutil C module methods and initialize the module.
- */
-static PyMethodDef
-PsutilMethods[] =
-{
-     // --- process-related functions
-     {"get_process_basic_info", get_process_basic_info, METH_VARARGS,
-        "Return process ppid, rss, vms, ctime, nice, nthreads, status and tty"},
-     {"get_process_name_and_args", get_process_name_and_args, METH_VARARGS,
-        "Return process name and args."},
-     {"get_process_cpu_times", get_process_cpu_times, METH_VARARGS,
-        "Return process user and system CPU times."},
-     {"get_process_cred", get_process_cred, METH_VARARGS,
-        "Return process uids/gids."},
-     {"query_process_thread", query_process_thread, METH_VARARGS,
-        "Return info about a process thread"},
-     {"get_process_memory_maps", get_process_memory_maps, METH_VARARGS,
-        "Return process memory mappings"},
-     {"get_process_num_ctx_switches", get_process_num_ctx_switches, METH_VARARGS,
-        "Return the number of context switches performed by process"},
-     {"get_process_connections", get_process_connections, METH_VARARGS,
-        "Return TCP and UDP connections opened by process."},
-
-     // --- system-related functions
-     {"get_swap_mem", get_swap_mem, METH_VARARGS,
-        "Return information about system swap memory."},
-     {"get_system_users", get_system_users, METH_VARARGS,
-        "Return currently connected users."},
-     {"get_disk_partitions", get_disk_partitions, METH_VARARGS,
-        "Return disk partitions."},
-     {"get_system_per_cpu_times", get_system_per_cpu_times, METH_VARARGS,
-        "Return system per-CPU times."},
-     {"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
-        "Return a Python dict of tuples for disk I/O statistics."},
-     {"get_net_io_counters", get_net_io_counters, METH_VARARGS,
-        "Return a Python dict of tuples for network I/O statistics."},
-
-     {NULL, NULL, 0, NULL}
-};
-
-
-struct module_state {
-    PyObject *error;
-};
-
-#if PY_MAJOR_VERSION >= 3
-#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
-#else
-#define GETSTATE(m) (&_state)
-#endif
-
-#if PY_MAJOR_VERSION >= 3
-
-static int
-psutil_sunos_traverse(PyObject *m, visitproc visit, void *arg) {
-    Py_VISIT(GETSTATE(m)->error);
-    return 0;
-}
-
-static int
-psutil_sunos_clear(PyObject *m) {
-    Py_CLEAR(GETSTATE(m)->error);
-    return 0;
-}
-
-static struct PyModuleDef
-moduledef = {
-    PyModuleDef_HEAD_INIT,
-    "psutil_sunos",
-    NULL,
-    sizeof(struct module_state),
-    PsutilMethods,
-    NULL,
-    psutil_sunos_traverse,
-    psutil_sunos_clear,
-    NULL
-};
-
-#define INITERROR return NULL
-
-PyObject *
-PyInit__psutil_sunos(void)
-
-#else
-#define INITERROR return
-
-void init_psutil_sunos(void)
-#endif
-{
-#if PY_MAJOR_VERSION >= 3
-    PyObject *module = PyModule_Create(&moduledef);
-#else
-    PyObject *module = Py_InitModule("_psutil_sunos", PsutilMethods);
-#endif
-    PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
-    PyModule_AddIntConstant(module, "SRUN", SRUN);
-    PyModule_AddIntConstant(module, "SZOMB", SZOMB);
-    PyModule_AddIntConstant(module, "SSTOP", SSTOP);
-    PyModule_AddIntConstant(module, "SIDL", SIDL);
-    PyModule_AddIntConstant(module, "SONPROC", SONPROC);
-    PyModule_AddIntConstant(module, "SWAIT", SWAIT);
-
-    PyModule_AddIntConstant(module, "PRNODEV", PRNODEV);  // for process tty
-
-    PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
-    PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
-    PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
-    PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
-    PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
-    PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
-    PyModule_AddIntConstant(module, "TCPS_SYN_RCVD", TCPS_SYN_RCVD);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
-    PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
-    PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
-    PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
-    PyModule_AddIntConstant(module, "TCPS_IDLE", TCPS_IDLE);  // sunos specific
-    PyModule_AddIntConstant(module, "TCPS_BOUND", TCPS_BOUND);  // sunos specific
-    PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
-
-    if (module == NULL) {
-        INITERROR;
-    }
-#if PY_MAJOR_VERSION >= 3
-    return module;
-#endif
-}
deleted file mode 100644
--- a/python/psutil/psutil/_psutil_sunos.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * $Id$
- *
- * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * Sun OS specific module functions for _psutil_sunos extension
- */
-
-#include <Python.h>
-
-// processes
-static PyObject* query_process_thread(PyObject* self, PyObject* args);
-static PyObject* get_process_basic_info(PyObject* self, PyObject* args);
-static PyObject* get_process_name_and_args(PyObject* self, PyObject* args);
-static PyObject* get_process_cpu_times(PyObject* self, PyObject* args);
-static PyObject* get_process_cred(PyObject* self, PyObject* args);
-static PyObject* get_process_memory_maps(PyObject* self, PyObject* args);
-static PyObject* get_process_num_ctx_switches(PyObject* self, PyObject* args);
-static PyObject* get_process_connections(PyObject* self, PyObject* args);
-
-// system
-static PyObject* get_swap_mem(PyObject* self, PyObject* args);
-static PyObject* get_system_users(PyObject* self, PyObject* args);
-static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
-static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
-static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
-static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
--- a/python/psutil/psutil/error.py
+++ b/python/psutil/psutil/error.py
@@ -1,11 +1,11 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """This module is deprecated as exceptions are defined in _error.py
 and are supposed to be accessed from 'psutil' namespace as in:
 - psutil.NoSuchProcess
 - psutil.AccessDenied
 - psutil.TimeoutExpired
deleted file mode 100644
--- a/python/psutil/setup.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-[egg_info]
-tag_build = 
-tag_date = 0
-tag_svn_revision = 0
-
--- a/python/psutil/setup.py
+++ b/python/psutil/setup.py
@@ -1,46 +1,22 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009 Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 import sys
 import os
-import shutil
-import fnmatch
 try:
     from setuptools import setup, Extension
 except ImportError:
     from distutils.core import setup, Extension
 
 
-def clean():
-    """'python setup.py clean' custom command."""
-    def rglob(path, pattern):
-        return [os.path.join(dirpath, f)
-            for dirpath, dirnames, files in os.walk(path)
-            for f in fnmatch.filter(files, pattern)]
-
-    for dirname in ('build', 'dist'):
-        if os.path.isdir(dirname):
-            sys.stdout.write('removing directory: %s\n' % dirname)
-            shutil.rmtree(dirname)
-
-    for dirpath, dirnames, files in os.walk('.'):
-        if dirpath.endswith(('__pycache__', '.egg-info')):
-            sys.stdout.write('removing directory %s\n' % dirpath)
-            shutil.rmtree(dirpath)
-
-    for pattern in ['*.py[co]', '*.s[ol]', '*~', '*.orig', '*.rej', '*.swp']:
-        for x in rglob('.', pattern):
-           sys.stdout.write('removing file %s\n' % x)
-           os.remove(x)
-
 def get_version():
     INIT = os.path.abspath(os.path.join(os.path.dirname(__file__),
                            'psutil', '__init__.py'))
     f = open(INIT, 'r')
     try:
         for line in f:
             if line.startswith('__version__'):
                 ret = eval(line.strip().split(' = ')[1])
@@ -109,63 +85,49 @@ elif sys.platform.startswith("freebsd"):
                             ),
                   posix_extension]
 # Linux
 elif sys.platform.startswith("linux"):
     extensions = [Extension('_psutil_linux',
                             sources=['psutil/_psutil_linux.c'],
                             ),
                   posix_extension]
-# Solaris
-elif sys.platform.lower().startswith('sunos'):
-    extensions = [Extension('_psutil_sunos',
-                            sources=['psutil/_psutil_sunos.c'],
-                            libraries=['kstat', 'nsl'],
-                            ),
-                  posix_extension]
 else:
     sys.exit('platform %s is not supported' % sys.platform)
 
 
 def main():
-    # "python setup.py clean" custom command
-    if len(sys.argv) > 1 and sys.argv[1] == 'clean':
-        return clean()
-
     setup_args = dict(
         name='psutil',
         version=VERSION,
         download_url="http://psutil.googlecode.com/files/psutil-%s.tar.gz" \
                      % VERSION,
         description='A process and system utilities module for Python',
         long_description=get_description(),
         keywords=['ps', 'top', 'kill', 'free', 'lsof', 'netstat', 'nice',
                   'tty', 'ionice', 'uptime', 'taskmgr', 'process', 'df',
                   'iotop', 'iostat', 'ifconfig', 'taskset', 'who', 'pidof',
                   'pmap', 'smem', 'monitoring',],
-        author='Giampaolo Rodola',
+        author='Giampaolo Rodola, Jay Loden',
         author_email='psutil@googlegroups.com',
         maintainer='Giampaolo Rodola',
         maintainer_email='g.rodola <at> gmail <dot> com',
         url='http://code.google.com/p/psutil/',
         platforms='Platform Independent',
         license='License :: OSI Approved :: BSD License',
         packages=['psutil'],
-        test_suite='test.test_psutil',
-        # see: python setup.py register --list-classifiers
         classifiers=[
               'Development Status :: 5 - Production/Stable',
               'Environment :: Console',
               'Operating System :: MacOS :: MacOS X',
               'Operating System :: Microsoft',
               'Operating System :: Microsoft :: Windows :: Windows NT/2000',
               'Operating System :: POSIX',
               'Operating System :: POSIX :: Linux',
               'Operating System :: POSIX :: BSD :: FreeBSD',
-              'Operating System :: POSIX :: SunOS/Solaris',
               'Operating System :: OS Independent',
               'Programming Language :: C',
               'Programming Language :: Python',
               'Programming Language :: Python :: 2',
               'Programming Language :: Python :: 2.4',
               'Programming Language :: Python :: 2.5',
               'Programming Language :: Python :: 2.6',
               'Programming Language :: Python :: 2.7',
deleted file mode 100644
--- a/python/psutil/test/_bsd.py
+++ b/python/psutil/test/_bsd.py
@@ -1,30 +1,33 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """BSD specific tests.  These are implicitly run by test_psutil.py."""
 
 import unittest
 import subprocess
 import time
 import re
 import sys
 import os
 
 import psutil
 
 from psutil._compat import PY3
-from test_psutil import *
+from test_psutil import DEVNULL
+from test_psutil import (reap_children, get_test_subprocess, sh, which,
+                         skipUnless)
 
 
 PAGESIZE = os.sysconf("SC_PAGE_SIZE")
+TOLERANCE = 200 * 1024  # 200 KB
 MUSE_AVAILABLE = which('muse')
 
 
 def sysctl(cmdline):
     """Expects a sysctl command with an argument and parse the result
     returning only the value of interest.
     """
     result = sh("sysctl " + cmdline)
@@ -48,16 +51,24 @@ def muse(field):
 class BSDSpecificTestCase(unittest.TestCase):
 
     def setUp(self):
         self.pid = get_test_subprocess().pid
 
     def tearDown(self):
         reap_children()
 
+    def assert_eq_w_tol(self, first, second, tolerance):
+        difference = abs(first - second)
+        if difference <= tolerance:
+            return
+        msg = '%r != %r within %r delta (%r difference)' \
+              % (first, second, tolerance, difference)
+        raise AssertionError(msg)
+
     def test_BOOT_TIME(self):
         s = sysctl('sysctl kern.boottime')
         s = s[s.find(" sec = ") + 7:]
         s = s[:s.find(',')]
         btime = int(s)
         self.assertEqual(btime, psutil.BOOT_TIME)
 
     def test_process_create_time(self):
@@ -114,103 +125,74 @@ class BSDSpecificTestCase(unittest.TestC
                 self.assertEqual(fields[10], map.path)
 
     # --- virtual_memory(); tests against sysctl
 
     def test_vmem_total(self):
         syst = sysctl("sysctl vm.stats.vm.v_page_count") * PAGESIZE
         self.assertEqual(psutil.virtual_memory().total, syst)
 
-    @retry_before_failing()
     def test_vmem_active(self):
         syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE
-        self.assertAlmostEqual(psutil.virtual_memory().active, syst,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().active, syst, 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)
+        self.assert_eq_w_tol(psutil.virtual_memory().inactive, syst, 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)
+        self.assert_eq_w_tol(psutil.virtual_memory().wired, syst, 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)
+        self.assert_eq_w_tol(psutil.virtual_memory().cached, syst, 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)
+        self.assert_eq_w_tol(psutil.virtual_memory().free, syst, TOLERANCE)
 
-    @retry_before_failing()
     def test_vmem_buffers(self):
         syst = sysctl("vfs.bufspace")
-        self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().buffers, syst, TOLERANCE)
 
     # --- virtual_memory(); tests against muse
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
+    @skipUnless(MUSE_AVAILABLE)
     def test_total(self):
         num = muse('Total')
         self.assertEqual(psutil.virtual_memory().total, num)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_active(self):
         num = muse('Active')
-        self.assertAlmostEqual(psutil.virtual_memory().active, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().active, num, TOLERANCE)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_inactive(self):
         num = muse('Inactive')
-        self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().inactive, num, TOLERANCE)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_wired(self):
         num = muse('Wired')
-        self.assertAlmostEqual(psutil.virtual_memory().wired, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().wired, num, TOLERANCE)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_cached(self):
         num = muse('Cache')
-        self.assertAlmostEqual(psutil.virtual_memory().cached, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().cached, num, TOLERANCE)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_free(self):
         num = muse('Free')
-        self.assertAlmostEqual(psutil.virtual_memory().free, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().free, num, TOLERANCE)
 
-    @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
-    @retry_before_failing()
+    @skipUnless(MUSE_AVAILABLE)
     def test_buffers(self):
         num = muse('Buffer')
-        self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().buffers, num, TOLERANCE)
 
 
-def test_main():
+if __name__ == '__main__':
     test_suite = unittest.TestSuite()
     test_suite.addTest(unittest.makeSuite(BSDSpecificTestCase))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
--- a/python/psutil/test/_linux.py
+++ b/python/psutil/test/_linux.py
@@ -1,34 +1,42 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Linux specific tests.  These are implicitly run by test_psutil.py."""
 
 from __future__ import division
 import unittest
 import subprocess
 import sys
 import time
 import os
 import re
 
-from test_psutil import *
+from test_psutil import sh, get_test_subprocess
 from psutil._compat import PY3
 import psutil
 
 
+TOLERANCE = 200 * 1024  # 200 KB
+
+
 class LinuxSpecificTestCase(unittest.TestCase):
 
-    @unittest.skipIf(POSIX and not hasattr(os, 'statvfs'),
-            reason="os.statvfs() function not available on this platform")
-    @skip_on_not_implemented()
+    def assert_eq_w_tol(self, first, second, tolerance):
+        difference = abs(first - second)
+        if difference <= tolerance:
+            return
+        msg = '%r != %r within %r delta (%r difference)' \
+              % (first, second, tolerance, difference)
+        raise AssertionError(msg)
+
     def test_disks(self):
         # test psutil.disk_usage() and psutil.disk_partitions()
         # against "df -a"
         def df(path):
             out = sh('df -P -B 1 "%s"' % path).strip()
             lines = out.split('\n')
             lines.pop(0)
             line = lines.pop(0)
@@ -66,85 +74,68 @@ class LinuxSpecificTestCase(unittest.Tes
             # test only rwx chars, ignore 's' and 'p'
             self.assertEqual(mode[:3], this.perms[:3])
 
     def test_vmem_total(self):
         lines = sh('free').split('\n')[1:]
         total = int(lines[0].split()[1]) * 1024
         self.assertEqual(total, psutil.virtual_memory().total)
 
-    @retry_before_failing()
     def test_vmem_used(self):
         lines = sh('free').split('\n')[1:]
         used = int(lines[0].split()[2]) * 1024
-        self.assertAlmostEqual(used, psutil.virtual_memory().used,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(used, psutil.virtual_memory().used, 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)
+        self.assert_eq_w_tol(free, psutil.virtual_memory().free, 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)
+        self.assert_eq_w_tol(buffers, psutil.virtual_memory().buffers, 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)
+        self.assert_eq_w_tol(cached, psutil.virtual_memory().cached, TOLERANCE)
 
     def test_swapmem_total(self):
         lines = sh('free').split('\n')[1:]
         total = int(lines[2].split()[1]) * 1024
         self.assertEqual(total, psutil.swap_memory().total)
 
-    @retry_before_failing()
     def test_swapmem_used(self):
         lines = sh('free').split('\n')[1:]
         used = int(lines[2].split()[2]) * 1024
-        self.assertAlmostEqual(used, psutil.swap_memory().used,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(used, psutil.swap_memory().used, 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)
+        self.assert_eq_w_tol(free, psutil.swap_memory().free, TOLERANCE)
 
     def test_cpu_times(self):
         fields = psutil.cpu_times()._fields
         kernel_ver = re.findall('\d.\d.\d', os.uname()[2])[0]
         kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
         # steal >= 2.6.11
         # guest >= 2.6.24
         # guest_nice >= 3.2.0
         if kernel_ver_info >= (2, 6, 11):
-            self.assertIn('steal', fields)
+            assert 'steal' in fields, fields
         else:
-            self.assertNotIn('steal', fields)
+            assert 'steal' not in fields, fields
         if kernel_ver_info >= (2, 6, 24):
-            self.assertIn('guest', fields)
+            assert 'guest' in fields, fields
         else:
-            self.assertNotIn('guest', fields)
+            assert 'guest' not in fields, fields
         if kernel_ver_info >= (3, 2, 0):
-            self.assertIn('guest_nice', fields)
+            assert 'guest_nice' in fields, fields
         else:
-            self.assertNotIn('guest_nice', fields)
+            assert 'guest_nice' not in fields, fields
 
 
-def test_main():
+if __name__ == '__main__':
     test_suite = unittest.TestSuite()
     test_suite.addTest(unittest.makeSuite(LinuxSpecificTestCase))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
--- a/python/psutil/test/_osx.py
+++ b/python/psutil/test/_osx.py
@@ -1,30 +1,31 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """OSX specific tests.  These are implicitly run by test_psutil.py."""
 
 import unittest
 import subprocess
 import time
 import sys
 import os
 import re
 
 import psutil
 
 from psutil._compat import PY3
-from test_psutil import *
+from test_psutil import reap_children, get_test_subprocess, sh
 
 
 PAGESIZE = os.sysconf("SC_PAGE_SIZE")
+TOLERANCE = 500 * 1024  # 500 KB
 
 
 def sysctl(cmdline):
     """Expects a sysctl command with an argument and parse the result
     returning only the value of interest.
     """
     p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
     result = p.communicate()[0].strip().split()[1]
@@ -49,16 +50,24 @@ def vm_stat(field):
 class OSXSpecificTestCase(unittest.TestCase):
 
     def setUp(self):
         self.pid = get_test_subprocess().pid
 
     def tearDown(self):
         reap_children()
 
+    def assert_eq_w_tol(self, first, second, tolerance):
+        difference = abs(first - second)
+        if difference <= tolerance:
+            return
+        msg = '%r != %r (tolerance=%r, difference=%s)' \
+              % (first, second, tolerance, difference)
+        raise AssertionError(msg)
+
     def test_process_create_time(self):
         cmdline = "ps -o lstart -p %s" %self.pid
         p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
         output = p.communicate()[0]
         if PY3:
             output = str(output, sys.stdout.encoding)
         start_ps = output.replace('STARTED', '').strip()
         start_psutil = psutil.Process(self.pid).create_time
@@ -94,39 +103,31 @@ class OSXSpecificTestCase(unittest.TestC
                 self.fail("psutil=%s, df=%s" % usage.used, used)
 
     # --- virtual mem
 
     def test_vmem_total(self):
         sysctl_hwphymem = sysctl('sysctl hw.memsize')
         self.assertEqual(sysctl_hwphymem, psutil.TOTAL_PHYMEM)
 
-    @retry_before_failing()
     def test_vmem_free(self):
         num = vm_stat("free")
-        self.assertAlmostEqual(psutil.virtual_memory().free, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().free, num, TOLERANCE)
 
-    @retry_before_failing()
     def test_vmem_active(self):
         num = vm_stat("active")
-        self.assertAlmostEqual(psutil.virtual_memory().active, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().active, num, TOLERANCE)
 
-    @retry_before_failing()
     def test_vmem_inactive(self):
         num = vm_stat("inactive")
-        self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().inactive, num, TOLERANCE)
 
-    @retry_before_failing()
     def test_vmem_wired(self):
         num = vm_stat("wired")
-        self.assertAlmostEqual(psutil.virtual_memory().wired, num,
-                               delta=TOLERANCE)
+        self.assert_eq_w_tol(psutil.virtual_memory().wired, num, TOLERANCE)
 
     # --- swap mem
 
     def test_swapmem_sin(self):
         num = vm_stat("Pageins")
         self.assertEqual(psutil.swap_memory().sin, num)
 
     def test_swapmem_sout(self):
@@ -140,17 +141,12 @@ class OSXSpecificTestCase(unittest.TestC
         # 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)
 
 
-def test_main():
+if __name__ == '__main__':
     test_suite = unittest.TestSuite()
     test_suite.addTest(unittest.makeSuite(OSXSpecificTestCase))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
--- a/python/psutil/test/_posix.py
+++ b/python/psutil/test/_posix.py
@@ -1,44 +1,42 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """POSIX specific tests.  These are implicitly run by test_psutil.py."""
 
 import unittest
 import subprocess
 import time
 import sys
 import os
 import datetime
 
 import psutil
 
 from psutil._compat import PY3
-from test_psutil import *
+from test_psutil import (get_test_subprocess, reap_children, PYTHON, LINUX, OSX,
+                         BSD, skip_on_access_denied, sh, skipIf)
 
 
 def ps(cmd):
     """Expects a ps command with a -o argument and parse the result
     returning only the value of interest.
     """
     if not LINUX:
         cmd = cmd.replace(" --no-headers ", " ")
-    if SUNOS:
-        cmd = cmd.replace("-o command", "-o comm")
-        cmd = cmd.replace("-o start", "-o stime")
     p = subprocess.Popen(cmd, shell=1, stdout=subprocess.PIPE)
     output = p.communicate()[0].strip()
     if PY3:
         output = str(output, sys.stdout.encoding)
     if not LINUX:
-        output = output.split('\n')[1].strip()
+        output = output.split('\n')[1]
     try:
         return int(output)
     except ValueError:
         return output
 
 
 class PosixSpecificTestCase(unittest.TestCase):
     """Compare psutil results against 'ps' command line utility."""
@@ -93,26 +91,23 @@ class PosixSpecificTestCase(unittest.Tes
     def test_process_name(self):
         # use command + arg since "comm" keyword not supported on all platforms
         name_ps = ps("ps --no-headers -o command -p %s" %self.pid).split(' ')[0]
         # remove path if there is any, from the command
         name_ps = os.path.basename(name_ps).lower()
         name_psutil = psutil.Process(self.pid).name.lower()
         self.assertEqual(name_ps, name_psutil)
 
-    @unittest.skipIf(OSX or BSD,
-                    'ps -o start not available')
+    @skipIf(OSX or BSD)
     def test_process_create_time(self):
         time_ps = ps("ps --no-headers -o start -p %s" %self.pid).split(' ')[0]
         time_psutil = psutil.Process(self.pid).create_time
-        if SUNOS:
-            time_psutil = round(time_psutil)
-        time_psutil_tstamp = datetime.datetime.fromtimestamp(
+        time_psutil = datetime.datetime.fromtimestamp(
                         time_psutil).strftime("%H:%M:%S")
-        self.assertEqual(time_ps, time_psutil_tstamp)
+        self.assertEqual(time_ps, time_psutil)
 
     def test_process_exe(self):
         ps_pathname = ps("ps --no-headers -o command -p %s" %self.pid).split(' ')[0]
         psutil_pathname = psutil.Process(self.pid).exe
         try:
             self.assertEqual(ps_pathname, psutil_pathname)
         except AssertionError:
             # certain platforms such as BSD are more accurate returning:
@@ -122,117 +117,65 @@ class PosixSpecificTestCase(unittest.Tes
             # We do not want to consider this difference in accuracy
             # an error.
             adjusted_ps_pathname = ps_pathname[:len(ps_pathname)]
             self.assertEqual(ps_pathname, adjusted_ps_pathname)
 
     def test_process_cmdline(self):
         ps_cmdline = ps("ps --no-headers -o command -p %s" %self.pid)
         psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline)
-        if SUNOS:
-            # ps on Solaris only shows the first part of the cmdline
-            psutil_cmdline = psutil_cmdline.split(" ")[0]
         self.assertEqual(ps_cmdline, psutil_cmdline)
 
-    @retry_before_failing()
     def test_get_pids(self):
         # Note: this test might fail if the OS is starting/killing
         # other processes in the meantime
-        if SUNOS:
-            cmd = ["ps", "ax"]
-        else:
-            cmd = ["ps", "ax", "-o", "pid"]
-        p = get_test_subprocess(cmd, stdout=subprocess.PIPE)
+        p = get_test_subprocess(["ps", "ax", "-o", "pid"], stdout=subprocess.PIPE)
         output = p.communicate()[0].strip()
         if PY3:
             output = str(output, sys.stdout.encoding)
+        output = output.replace('PID', '')
+        p.wait()
         pids_ps = []
-        for line in output.split('\n')[1:]:
-            if line:
-                pid = int(line.split()[0].strip())
-                pids_ps.append(pid)
+        for pid in output.split('\n'):
+            if pid:
+                pids_ps.append(int(pid.strip()))
         # remove ps subprocess pid which is supposed to be dead in meantime
         pids_ps.remove(p.pid)
         pids_psutil = psutil.get_pid_list()
         pids_ps.sort()
         pids_psutil.sort()
 
         # on OSX ps doesn't show pid 0
         if OSX and 0 not in pids_ps:
             pids_ps.insert(0, 0)
 
         if pids_ps != pids_psutil:
             difference = [x for x in pids_psutil if x not in pids_ps] + \
                          [x for x in pids_ps if x not in pids_psutil]
             self.fail("difference: " + str(difference))
 
-    # for some reason ifconfig -a does not report differente interfaces
-    # psutil does
-    @unittest.skipIf(SUNOS, "test not reliable on SUNOS")
     def test_nic_names(self):
         p = subprocess.Popen("ifconfig -a", shell=1, stdout=subprocess.PIPE)
         output = p.communicate()[0].strip()
         if PY3:
             output = str(output, sys.stdout.encoding)
-        for nic in psutil.net_io_counters(pernic=True).keys():
+        for nic in psutil.network_io_counters(pernic=True).keys():
             for line in output.split():
                 if line.startswith(nic):
                     break
             else:
                 self.fail("couldn't find %s nic in 'ifconfig -a' output" % nic)
 
     def test_get_users(self):
         out = sh("who")
         lines = out.split('\n')
         users = [x.split()[0] for x in lines]
         self.assertEqual(len(users), len(psutil.get_users()))
         terminals = [x.split()[1] for x in lines]
         for u in psutil.get_users():
             self.assertTrue(u.name in users, u.name)
             self.assertTrue(u.terminal in terminals, u.terminal)
 
-    def test_fds_open(self):
-        # Note: this fails from time to time; I'm keen on thinking
-        # it doesn't mean something is broken
-        def call(p, attr):
-            attr = getattr(p, name, None)
-            if attr is not None and callable(attr):
-                ret = attr()
-            else:
-                ret = attr
 
-        p = psutil.Process(os.getpid())
-        attrs = []
-        failures = []
-        for name in dir(psutil.Process):
-            if name.startswith('_') \
-            or name.startswith('set_') \
-            or name in ('terminate', 'kill', 'suspend', 'resume', 'nice',
-                        'send_signal', 'wait', 'get_children', 'as_dict'):
-                continue
-            else:
-                try:
-                    num1 = p.get_num_fds()
-                    for x in range(2):
-                        call(p, name)
-                    num2 = p.get_num_fds()
-                except psutil.AccessDenied:
-                    pass
-                else:
-                    if abs(num2 - num1) > 1:
-                        fail = "failure while processing Process.%s method " \
-                               "(before=%s, after=%s)" % (name, num1, num2)
-                        failures.append(fail)
-        if failures:
-            self.fail('\n' + '\n'.join(failures))
-
-
-
-
-def test_main():
+if __name__ == '__main__':
     test_suite = unittest.TestSuite()
     test_suite.addTest(unittest.makeSuite(PosixSpecificTestCase))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
deleted file mode 100644
--- a/python/psutil/test/_sunos.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env python
-
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Sun OS specific tests.  These are implicitly run by test_psutil.py."""
-
-import psutil
-from test_psutil import *
-
-
-class SunOSSpecificTestCase(unittest.TestCase):
-
-    def test_swap_memory(self):
-        out = sh('swap -l -k')
-        lines = out.strip().split('\n')[1:]
-        if not lines:
-            raise ValueError('no swap device(s) configured')
-        total = free = 0
-        for line in lines:
-            line = line.split()
-            t, f = line[-2:]
-            t = t.replace('K', '')
-            f = f.replace('K', '')
-            total += int(int(t) * 1024)
-            free += int(int(f) * 1024)
-        used = total - free
-
-        psutil_swap = psutil.swap_memory()
-        self.assertEqual(psutil_swap.total, total)
-        self.assertEqual(psutil_swap.used, used)
-        self.assertEqual(psutil_swap.free, free)
-
-
-def test_main():
-    test_suite = unittest.TestSuite()
-    test_suite.addTest(unittest.makeSuite(SunOSSpecificTestCase))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
--- a/python/psutil/test/_windows.py
+++ b/python/psutil/test/_windows.py
@@ -1,46 +1,48 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Windows specific tests.  These are implicitly run by test_psutil.py."""
 
 import os
 import unittest
 import platform
 import signal
 import time
+import warnings
+import atexit
 import sys
 import subprocess
 import errno
 import traceback
 
 import psutil
 import _psutil_mswindows
 from psutil._compat import PY3, callable, long
-from test_psutil import *
-
+from test_psutil import reap_children, get_test_subprocess, wait_for_pid, warn
 try:
     import wmi
 except ImportError:
     err = sys.exc_info()[1]
-    register_warning("Couldn't run wmi tests: %s" % str(err))
+    atexit.register(warn, "Couldn't run wmi tests: %s" % str(err))
     wmi = None
 try:
     import win32api
     import win32con
 except ImportError:
     err = sys.exc_info()[1]
-    register_warning("Couldn't run pywin32 tests: %s" % str(err))
+    atexit.register(warn, "Couldn't run pywin32 tests: %s" % str(err))
     win32api = None
 
 
+
 class WindowsSpecificTestCase(unittest.TestCase):
 
     def setUp(self):
         sproc = get_test_subprocess()
         wait_for_pid(sproc.pid)
         self.pid = sproc.pid
 
     def tearDown(self):
@@ -71,17 +73,17 @@ class WindowsSpecificTestCase(unittest.T
         p = psutil.Process(self.pid)
         self.assertRaises(ValueError, p.send_signal, signal.SIGINT)
 
     def test_nic_names(self):
         p = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE)
         out = p.communicate()[0]
         if PY3:
             out = str(out, sys.stdout.encoding)
-        nics = psutil.net_io_counters(pernic=True).keys()
+        nics = psutil.network_io_counters(pernic=True).keys()
         for nic in nics:
             if "pseudo-interface" in nic.replace(' ', '-').lower():
                 continue
             if nic not in out:
                 self.fail("%r nic wasn't found in 'ipconfig /all' output" % nic)
 
     def test_exe(self):
         for p in psutil.process_iter():
@@ -142,18 +144,16 @@ class WindowsSpecificTestCase(unittest.T
             wmic_create = str(w.CreationDate.split('.')[0])
             psutil_create = time.strftime("%Y%m%d%H%M%S",
                                           time.localtime(p.create_time))
             self.assertEqual(wmic_create, psutil_create)
 
 
         # --- psutil namespace functions and constants tests
 
-        @unittest.skipUnless(hasattr(os, 'NUMBER_OF_PROCESSORS'),
-                             'NUMBER_OF_PROCESSORS env var is not available')
         def test_NUM_CPUS(self):
             num_cpus = int(os.environ['NUMBER_OF_PROCESSORS'])
             self.assertEqual(num_cpus, psutil.NUM_CPUS)
 
         def test_TOTAL_PHYMEM(self):
             w = wmi.WMI().Win32_ComputerSystem()[0]
             self.assertEqual(int(w.TotalPhysicalMemory), psutil.TOTAL_PHYMEM)
 
@@ -289,41 +289,39 @@ class TestDualProcessImplementation(unit
         # NtQuerySystemInformation() which gets called as fallback in
         # case the first fails because of limited permission error.
         # Here we test that the two methods return the exact same value,
         # see:
         # http://code.google.com/p/psutil/issues/detail?id=304
         def assert_ge_0(obj):
             if isinstance(obj, tuple):
                 for value in obj:
-                    self.assertGreaterEqual(value, 0)
+                    assert value >= 0, value
             elif isinstance(obj, (int, long, float)):
-                self.assertGreaterEqual(obj, 0)
+                assert obj >= 0, obj
             else:
                 assert 0  # case not handled which needs to be fixed
 
         def compare_with_tolerance(ret1, ret2, tolerance):
             if ret1 == ret2:
                 return
             else:
                 if isinstance(ret2, (int, long, float)):
                     diff = abs(ret1 - ret2)
-                    self.assertLessEqual(diff, tolerance)
+                    assert diff <= tolerance, diff
                 elif isinstance(ret2, tuple):
                     for a, b in zip(ret1, ret2):
                         diff = abs(a - b)
-                        self.assertLessEqual(diff, tolerance)
+                        assert diff <= tolerance, diff
 
         failures = []
         for name, tolerance in self.fun_names:
             meth1 = wrap_exceptions(getattr(_psutil_mswindows, name))
             meth2 = wrap_exceptions(getattr(_psutil_mswindows, name + '_2'))
             for p in psutil.process_iter():
-                if name == 'get_process_memory_info' and p.pid == os.getpid():
-                    continue
                 #
                 try:
                     ret1 = meth1(p.pid)
                 except psutil.NoSuchProcess:
                     continue
                 except psutil.AccessDenied:
                     ret1 = None
                 #
@@ -356,18 +354,13 @@ class TestDualProcessImplementation(unit
         # test that NPS is raised by the 2nd implementation in case a
         # process no longer exists
         ZOMBIE_PID = max(psutil.get_pid_list()) + 5000
         for name, _ in self.fun_names:
             meth = wrap_exceptions(getattr(_psutil_mswindows, name))
             self.assertRaises(psutil.NoSuchProcess, meth, ZOMBIE_PID)
 
 
-def test_main():
+if __name__ == '__main__':
     test_suite = unittest.TestSuite()
     test_suite.addTest(unittest.makeSuite(WindowsSpecificTestCase))
     test_suite.addTest(unittest.makeSuite(TestDualProcessImplementation))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
-
-if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
--- a/python/psutil/test/test_memory_leaks.py
+++ b/python/psutil/test/test_memory_leaks.py
@@ -1,33 +1,34 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
 A test script which attempts to detect memory leaks by calling C
 functions many times and compare process memory usage before and
 after the calls.  It might produce false positives.
 """
 
 import os
 import gc
 import unittest
 import time
 import socket
 import threading
 import types
-import sys
 
 import psutil
 import psutil._common
 from psutil._compat import PY3, callable, xrange
-from test_psutil import *
+from test_psutil import POSIX, LINUX, WINDOWS, OSX, BSD, TESTFN
+from test_psutil import (reap_children, skipUnless, skipIf, supports_ipv6,
+                         safe_remove, get_test_subprocess)
 
 # disable cache for Process class properties
 psutil._common.cached_property.enabled = False
 
 LOOPS = 1000
 TOLERANCE = 4096
 
 
@@ -87,19 +88,17 @@ class TestProcessObjectLeaks(Base):
 
     def __init__(self, *args, **kwargs):
         Base.__init__(self, *args, **kwargs)
         # skip tests which are not supported by Process API
         supported_attrs = dir(psutil.Process)
         for attr in [x for x in dir(self) if x.startswith('test')]:
             if attr[5:] not in supported_attrs:
                 meth = getattr(self, attr)
-                name = meth.__func__.__name__.replace('test_', '')
-                @unittest.skipIf(True,
-                                 "%s not supported on this platform" % name)
+                @skipIf(True)
                 def test_(self):
                     pass
                 setattr(self, attr, types.MethodType(test_, self))
 
     def setUp(self):
         gc.collect()
 
     def tearDown(self):
@@ -179,17 +178,17 @@ class TestProcessObjectLeaks(Base):
         self.execute('get_memory_info')
 
     def test_get_ext_memory_info(self):
         self.execute('get_ext_memory_info')
 
     def test_terminal(self):
         self.execute('terminal')
 
-    @unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
+    @skipUnless(WINDOWS)
     def test_resume(self):
         self.execute('resume')
 
     def test_getcwd(self):
         self.execute('getcwd')
 
     def test_get_cpu_affinity(self):
         self.execute('get_cpu_affinity')
@@ -202,22 +201,22 @@ class TestProcessObjectLeaks(Base):
         safe_remove(TESTFN)  # needed after UNIX socket test has run
         f = open(TESTFN, 'w')
         try:
             self.execute('get_open_files')
         finally:
             f.close()
 
     # OSX implementation is unbelievably slow
-    @unittest.skipIf(OSX, "OSX implementation is too slow")
+    @skipIf(OSX)
     def test_get_memory_maps(self):
         self.execute('get_memory_maps')
 
     # Linux implementation is pure python so since it's slow we skip it
-    @unittest.skipIf(LINUX, "not worth being tested on Linux (pure python)")
+    @skipIf(LINUX)
     def test_get_connections(self):
         def create_socket(family, type):
             sock = socket.socket(family, type)
             sock.bind(('', 0))
             if type == socket.SOCK_STREAM:
                 sock.listen(1)
             return sock
 
@@ -228,24 +227,18 @@ class TestProcessObjectLeaks(Base):
             socks.append(create_socket(socket.AF_INET6, socket.SOCK_STREAM))
             socks.append(create_socket(socket.AF_INET6, socket.SOCK_DGRAM))
         if hasattr(socket, 'AF_UNIX'):
             safe_remove(TESTFN)
             s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
             s.bind(TESTFN)
             s.listen(1)
             socks.append(s)
-        kind = 'all'
-        # TODO: UNIX sockets are temporarily implemented by parsing
-        # 'pfiles' cmd  output; we don't want that part of the code to
-        # be executed.
-        if SUNOS:
-            kind = 'inet'
         try:
-            self.execute('get_connections', kind=kind)
+            self.execute('get_connections', kind='all')
         finally:
             for s in socks:
                 s.close()
 
 
 p = get_test_subprocess()
 DEAD_PROC = psutil.Process(p.pid)
 DEAD_PROC.kill()
@@ -281,60 +274,54 @@ class TestModuleFunctionsLeaks(Base):
     def setUp(self):
         gc.collect()
 
     def call(self, function, *args, **kwargs):
         obj = getattr(psutil, function)
         if callable(obj):
             retvalue = obj(*args, **kwargs)
 
-    @unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
+    @skipIf(POSIX)
     def test_pid_exists(self):
         self.execute('pid_exists', os.getpid())
 
     def test_virtual_memory(self):
         self.execute('virtual_memory')
 
-    # TODO: remove this skip when this gets fixed
-    @unittest.skipIf(SUNOS,
-                     "not worth being tested on SUNOS (uses a subprocess)")
     def test_swap_memory(self):
         self.execute('swap_memory')
 
     def test_cpu_times(self):
         self.execute('cpu_times')
 
     def test_per_cpu_times(self):
         self.execute('cpu_times', percpu=True)
 
-    @unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
+    @skipUnless(WINDOWS)
     def test_disk_usage(self):
         self.execute('disk_usage', '.')
 
     def test_disk_partitions(self):
         self.execute('disk_partitions')
 
-    def test_net_io_counters(self):
-        self.execute('net_io_counters')
+    def test_network_io_counters(self):
+        self.execute('network_io_counters')
 
     def test_disk_io_counters(self):
         self.execute('disk_io_counters')
 
     # XXX - on Windows this produces a false positive
-    @unittest.skipIf(WINDOWS,
-                     "XXX produces a false positive on Windows")
+    @skipIf(WINDOWS)
     def test_get_users(self):
         self.execute('get_users')
 
 
 def test_main():
     test_suite = unittest.TestSuite()
     tests = [TestProcessObjectLeaksZombie,
              TestProcessObjectLeaks,
              TestModuleFunctionsLeaks,]
     for test in tests:
         test_suite.addTest(unittest.makeSuite(test))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
 
 if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    test_main()
--- a/python/psutil/test/test_psutil.py
+++ b/python/psutil/test/test_psutil.py
@@ -1,95 +1,69 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """
-psutil test suite (you can quickly run it with "python setup.py test").
+psutil test suite.
 
 Note: this is targeted for both python 2.x and 3.x so there's no need
 to use 2to3 tool first.
-
-If you're on Python < 2.7 it is recommended to install unittest2 module
-from: https://pypi.python.org/pypi/unittest2
 """
 
 from __future__ import division
+import unittest
 import os
 import sys
 import subprocess
 import time
 import signal
 import types
 import traceback
 import socket
 import warnings
 import atexit
 import errno
 import threading
 import tempfile
 import stat
 import collections
 import datetime
-try:
-    import unittest2 as unittest  # pyhon < 2.7 + unittest2 installed
-except ImportError:
-    import unittest
-try:
-    import ast  # python >= 2.6
-except ImportError:
-    ast = None
 
 import psutil
 from psutil._compat import PY3, callable, long, wraps
 
 
-# ===================================================================
-# --- Constants
-# ===================================================================
-
-# conf for retry_before_failing() decorator
-NO_RETRIES = 10
-# bytes tolerance for OS memory related tests
-TOLERANCE = 500 * 1024  # 500KB
-
 PYTHON = os.path.realpath(sys.executable)
 DEVNULL = open(os.devnull, 'r+')
 TESTFN = os.path.join(os.getcwd(), "$testfile")
-EXAMPLES_DIR = os.path.abspath(os.path.join(os.path.dirname(
-                               os.path.dirname(__file__)), 'examples'))
 POSIX = os.name == 'posix'
 LINUX = sys.platform.startswith("linux")
 WINDOWS = sys.platform.startswith("win32")
 OSX = sys.platform.startswith("darwin")
 BSD = sys.platform.startswith("freebsd")
-SUNOS = sys.platform.startswith("sunos")
 
 
-# ===================================================================
-# --- Utility functions
-# ===================================================================
-
 _subprocesses_started = set()
 
 def get_test_subprocess(cmd=None, stdout=DEVNULL, stderr=DEVNULL, stdin=DEVNULL,
                         wait=False):
     """Return a subprocess.Popen object to use in tests.
     By default stdout and stderr are redirected to /dev/null and the
     python interpreter is used as test process.
     If 'wait' is True attemps to make sure the process is in a
     reasonably initialized state.
     """
     if cmd is None:
         pyline = ""
         if wait:
             pyline += "open(r'%s', 'w'); " % TESTFN
-        pyline += "import time; time.sleep(2);"
+        pyline += "import time; time.sleep(3600);"
         cmd_ = [PYTHON, "-c", pyline]
     else:
         cmd_ = cmd
     sproc = subprocess.Popen(cmd_, stdout=stdout, stderr=stderr, stdin=stdin)
     if wait:
         if cmd is None:
             stop_at = time.time() + 3
             while stop_at > time.time():
@@ -98,23 +72,19 @@ def get_test_subprocess(cmd=None, stdout
                 time.sleep(0.001)
             else:
                 warn("couldn't make sure test file was actually created")
         else:
             wait_for_pid(sproc.pid)
     _subprocesses_started.add(sproc.pid)
     return sproc
 
-def warn(msg):
+def warn(msg, warntype=RuntimeWarning):
     """Raise a warning msg."""
-    warnings.warn(msg, UserWarning)
-
-def register_warning(msg):
-    """Register a warning which will be printed on interpreter exit."""
-    atexit.register(lambda: warn(msg))
+    warnings.warn(msg, warntype)
 
 def sh(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
     """run cmd in a subprocess and return its output.
     raises RuntimeError on error.
     """
     p = subprocess.Popen(cmdline, shell=True, stdout=stdout, stderr=stderr)
     stdout, stderr = p.communicate()
     if p.returncode != 0:
@@ -186,17 +156,16 @@ def check_ip_address(addr, family):
     if family == socket.AF_INET:
         ip = list(map(int, ip.split('.')))
         assert len(ip) == 4, ip
         for num in ip:
             assert 0 <= num <= 255, ip
     assert 0 <= port <= 65535, port
 
 def safe_remove(fname):
-    """Deletes a file and does not exception if it doesn't exist."""
     try:
         os.remove(fname)
     except OSError:
         err = sys.exc_info()[1]
         if err.args[0] != errno.ENOENT:
             raise
 
 def call_until(fun, expr, timeout=1):
@@ -206,73 +175,65 @@ def call_until(fun, expr, timeout=1):
     stop_at = time.time() + timeout
     while time.time() < stop_at:
         ret = fun()
         if eval(expr):
             return ret
         time.sleep(0.001)
     raise RuntimeError('timed out (ret=%r)' % ret)
 
-def retry_before_failing(ntimes=None):
-    """Decorator which runs a test function and retries N times before
-    actually failing.
+
+def skipIf(condition, reason="", warn=False):
+    """Decorator which skip a test under if condition is satisfied.
+    This is a substitute of unittest.skipIf which is available
+    only in python 2.7 and 3.2.
+    If 'reason' argument is provided this will be printed during
+    tests execution.
+    If 'warn' is provided a RuntimeWarning will be shown when all
+    tests are run.
     """
-    def decorator(fun):
-        @wraps(fun)
-        def wrapper(*args, **kwargs):
-            for x in range(ntimes or NO_RETRIES):
-                try:
-                    return fun(*args, **kwargs)
-                except AssertionError:
-                    err = sys.exc_info()[1]
-            raise
-        return wrapper
-    return decorator
+    def outer(fun, *args, **kwargs):
+        def inner(self):
+            if condition:
+                sys.stdout.write("skipped-")
+                sys.stdout.flush()
+                if warn:
+                    objname = "%s.%s" % (self.__class__.__name__, fun.__name__)
+                    msg = "%s was skipped" % objname
+                    if reason:
+                        msg += "; reason: " + repr(reason)
+                    atexit.register(warn, msg)
+                return
+            else:
+                return fun(self, *args, **kwargs)
+        return inner
+    return outer
+
+def skipUnless(condition, reason="", warn=False):
+    """Contrary of skipIf."""
+    if not condition:
+        return skipIf(True, reason, warn)
+    return skipIf(False)
 
 def skip_on_access_denied(only_if=None):
     """Decorator to Ignore AccessDenied exceptions."""
     def decorator(fun):
         @wraps(fun)
         def wrapper(*args, **kwargs):
             try:
                 return fun(*args, **kwargs)
             except psutil.AccessDenied:
                 if only_if is not None:
                     if not only_if:
                         raise
-                msg = "%r was skipped because it raised AccessDenied" \
-                      % fun.__name__
-                self = args[0]
-                if hasattr(self, 'skip'):  # python >= 2.7
-                    self.skip(msg)
-                else:
-                    register_warning(msg)
+                atexit.register(warn, "%r was skipped because it raised " \
+                                      "AccessDenied" % fun.__name__)
         return wrapper
     return decorator
 
-def skip_on_not_implemented(only_if=None):
-    """Decorator to Ignore NotImplementedError exceptions."""
-    def decorator(fun):
-        @wraps(fun)
-        def wrapper(*args, **kwargs):
-            try:
-                return fun(*args, **kwargs)
-            except NotImplementedError:
-                if only_if is not None:
-                    if not only_if:
-                        raise
-                msg = "%r was skipped because it raised NotImplementedError" \
-                      % fun.__name__
-                self = args[0]
-                if hasattr(self, 'skip'):  # python >= 2.7
-                    self.skip(msg)
-                else:
-                    register_warning(msg)
-        return wrapper
-    return decorator
 
 def supports_ipv6():
     """Return True if IPv6 is supported on this platform."""
     if not socket.has_ipv6 or not hasattr(socket, "AF_INET6"):
         return False
     sock = None
     try:
         try:
@@ -319,212 +280,116 @@ class ThreadTask(threading.Thread):
     def stop(self):
         """Stop thread execution and and waits until it is stopped."""
         if not self._running:
             raise ValueError("already stopped")
         self._running = False
         self.join()
 
 
-# ===================================================================
-# --- Support for python < 2.7 in case unittest2 is not installed
-# ===================================================================
-
-if not hasattr(unittest, 'skip'):
-    register_warning("unittest2 module is not installed; a serie of pretty " \
-                     "darn ugly workarounds will be used")
-
-    class SkipTest(Exception):
-        pass
-
-    class TestCase(unittest.TestCase):
-
-        def _safe_repr(self, obj):
-            MAX_LENGTH = 80
-            try:
-                result = repr(obj)
-            except Exception:
-                result = object.__repr__(obj)
-            if len(result) < MAX_LENGTH:
-                return result
-            return result[:MAX_LENGTH] + ' [truncated]...'
-
-        def _fail_w_msg(self, a, b, middle, msg):
-            self.fail(msg or '%s %s %s' % (self._safe_repr(a), middle,
-                                           self._safe_repr(b)))
-
-        def skip(self, msg):
-            raise SkipTest(msg)
-
-        def assertIn(self, a, b, msg=None):
-            if a not in b:
-                self._fail_w_msg(a, b, 'not found in', msg)
-
-        def assertNotIn(self, a, b, msg=None):
-            if a in b:
-                self._fail_w_msg(a, b, 'found in', msg)
-
-        def assertGreater(self, a, b, msg=None):
-            if not a > b:
-                self._fail_w_msg(a, b, 'not greater than', msg)
-
-        def assertGreaterEqual(self, a, b, msg=None):
-            if not a >= b:
-                self._fail_w_msg(a, b, 'not greater than or equal to', msg)
-
-        def assertLess(self, a, b, msg=None):
-            if not a < b:
-                self._fail_w_msg(a, b, 'not less than', msg)
-
-        def assertLessEqual(self, a, b, msg=None):
-            if not a <= b:
-                self._fail_w_msg(a, b, 'not less or equal to', msg)
-
-        def assertIsInstance(self, a, b, msg=None):
-            if not isinstance(a, b):
-                self.fail(msg or '%s is not an instance of %r' \
-                        % (self._safe_repr(a), b))
-
-        def assertAlmostEqual(self, a, b, msg=None, delta=None):
-            if delta is not None:
-                if abs(a - b) <= delta:
-                    return
-                self.fail(msg or '%s != %s within %s delta' \
-                                  % (self._safe_repr(a), self._safe_repr(b),
-                                     self._safe_repr(delta)))
-            else:
-                self.assertEqual(a, b, msg=msg)
-
-
-    def skipIf(condition, reason):
-        def decorator(fun):
-            @wraps(fun)
-            def wrapper(*args, **kwargs):
-                self = args[0]
-                if condition:
-                    sys.stdout.write("skipped-")
-                    sys.stdout.flush()
-                    if warn:
-                        objname = "%s.%s" % (self.__class__.__name__,
-                                             fun.__name__)
-                        msg = "%s was skipped" % objname
-                        if reason:
-                            msg += "; reason: " + repr(reason)
-                        register_warning(msg)
-                    return
-                else:
-                    return fun(*args, **kwargs)
-            return wrapper
-        return decorator
-
-    def skipUnless(condition, reason):
-        if not condition:
-            return unittest.skipIf(True, reason)
-        return unittest.skipIf(False, reason)
-
-    unittest.TestCase = TestCase
-    unittest.skipIf = skipIf
-    unittest.skipUnless = skipUnless
-    del TestCase, skipIf, skipUnless
-
-
-# ===================================================================
-# --- System-related API tests
-# ===================================================================
-
-class TestSystemAPIs(unittest.TestCase):
-    """Tests for system-related APIs."""
+class TestCase(unittest.TestCase):
 
     def setUp(self):
         safe_remove(TESTFN)
 
     def tearDown(self):
         reap_children()
 
+    if not hasattr(unittest.TestCase, "assertIn"):
+        def assertIn(self, member, container, msg=None):
+            if member not in container:
+                self.fail(msg or \
+                        '%s not found in %s' % (repr(member), repr(container)))
+
+    def assert_eq_w_tol(self, first, second, tolerance):
+        difference = abs(first - second)
+        if difference <= tolerance:
+            return
+        msg = '%r != %r within %r delta (%r difference)' \
+              % (first, second, tolerance, difference)
+        raise AssertionError(msg)
+
+    # ============================
+    # tests for system-related API
+    # ============================
+
     def test_process_iter(self):
-        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
+        assert os.getpid() in [x.pid for x in psutil.process_iter()]
         sproc = get_test_subprocess()
-        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
+        assert sproc.pid in [x.pid for x in psutil.process_iter()]
         p = psutil.Process(sproc.pid)
         p.kill()
         p.wait()
-        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])
+        assert sproc.pid not in [x.pid for x in psutil.process_iter()]
 
     def test_TOTAL_PHYMEM(self):
         x = psutil.TOTAL_PHYMEM
-        self.assertIsInstance(x, (int, long))
-        self.assertGreater(x, 0)
+        assert isinstance(x, (int, long))
+        assert x > 0
         self.assertEqual(x, psutil.virtual_memory().total)
 
     def test_BOOT_TIME(self, arg=None):
         x = arg or psutil.BOOT_TIME
-        self.assertIsInstance(x, float)
-        self.assertGreater(x, 0)
-        self.assertLess(x, time.time())
+        assert isinstance(x, float), x
+        assert x > 0, x
+        assert x < time.time(), x
 
     def test_get_boot_time(self):
         self.test_BOOT_TIME(psutil.get_boot_time())
         if WINDOWS:
             # work around float precision issues; give it 1 secs tolerance
             diff = abs(psutil.get_boot_time() - psutil.BOOT_TIME)
-            self.assertLess(diff, 1)
+            assert diff < 1, diff
         else:
             self.assertEqual(psutil.get_boot_time(), psutil.BOOT_TIME)
 
     def test_NUM_CPUS(self):
         self.assertEqual(psutil.NUM_CPUS, len(psutil.cpu_times(percpu=True)))
-        self.assertGreaterEqual(psutil.NUM_CPUS, 1)
+        assert psutil.NUM_CPUS >= 1, psutil.NUM_CPUS
 
-    @unittest.skipUnless(POSIX, 'posix only')
+    @skipUnless(POSIX)
     def test_PAGESIZE(self):
         # pagesize is used internally to perform different calculations
         # and it's determined by using SC_PAGE_SIZE; make sure
         # getpagesize() returns the same value.
         import resource
         self.assertEqual(os.sysconf("SC_PAGE_SIZE"), resource.getpagesize())
 
     def test_deprecated_apis(self):
-        s = socket.socket()
-        s.bind(('localhost', 0))
-        s.listen(1)
         warnings.filterwarnings("error")
         p = psutil.Process(os.getpid())
         try:
+            self.assertRaises(DeprecationWarning, __import__, 'psutil.error')
             self.assertRaises(DeprecationWarning, psutil.virtmem_usage)
             self.assertRaises(DeprecationWarning, psutil.used_phymem)
             self.assertRaises(DeprecationWarning, psutil.avail_phymem)
             self.assertRaises(DeprecationWarning, psutil.total_virtmem)
             self.assertRaises(DeprecationWarning, psutil.used_virtmem)
             self.assertRaises(DeprecationWarning, psutil.avail_virtmem)
             self.assertRaises(DeprecationWarning, psutil.phymem_usage)
             self.assertRaises(DeprecationWarning, psutil.get_process_list)
-            self.assertRaises(DeprecationWarning, psutil.network_io_counters)
+            self.assertRaises(DeprecationWarning, psutil.get_process_list)
             if LINUX:
                 self.assertRaises(DeprecationWarning, psutil.phymem_buffers)
                 self.assertRaises(DeprecationWarning, psutil.cached_phymem)
             try:
                 p.nice
             except DeprecationWarning:
                 pass
             else:
                 self.fail("p.nice didn't raise DeprecationWarning")
-            ret = call_until(p.get_connections, "len(ret) != 0", timeout=1)
-            self.assertRaises(DeprecationWarning,
-                              getattr, ret[0], 'local_address')
-            self.assertRaises(DeprecationWarning,
-                              getattr, ret[0], 'remote_address')
         finally:
-            s.close()
             warnings.resetwarnings()
 
     def test_deprecated_apis_retval(self):
         warnings.filterwarnings("ignore")
         p = psutil.Process(os.getpid())
         try:
             self.assertEqual(psutil.total_virtmem(), psutil.swap_memory().total)
+            self.assertEqual(psutil.get_process_list(), list(psutil.process_iter()))
             self.assertEqual(p.nice, p.get_nice())
         finally:
             warnings.resetwarnings()
 
     def test_virtual_memory(self):
         mem = psutil.virtual_memory()
         assert mem.total > 0, mem
         assert mem.available > 0, mem
@@ -537,17 +402,17 @@ class TestSystemAPIs(unittest.TestCase):
                 if not value >= 0:
                     self.fail("%r < 0 (%s)" % (name, value))
                 if value > mem.total:
                     self.fail("%r > total (total=%s, %s=%s)" \
                               % (name, mem.total, name, value))
 
     def test_swap_memory(self):
         mem = psutil.swap_memory()
-        assert mem.total >= 0, mem
+        assert mem.total > 0, mem
         assert mem.used >= 0, mem
         assert mem.free > 0, mem
         assert 0 <= mem.percent <= 100, mem
         assert mem.sin >= 0, mem
         assert mem.sout >= 0, mem
 
     def test_pid_exists(self):
         sproc = get_test_subprocess(wait=True)
@@ -590,18 +455,18 @@ class TestSystemAPIs(unittest.TestCase):
         finally:
             sys.stdout = stdout
 
     def test_sys_cpu_times(self):
         total = 0
         times = psutil.cpu_times()
         sum(times)
         for cp_time in times:
-            self.assertIsInstance(cp_time, float)
-            self.assertGreaterEqual(cp_time, 0.0)
+            assert isinstance(cp_time, float)
+            assert cp_time >= 0.0, cp_time
             total += cp_time
         self.assertEqual(total, sum(times))
         str(times)
 
     def test_sys_cpu_times2(self):
         t1 = sum(psutil.cpu_times())
         time.sleep(0.1)
         t2 = sum(psutil.cpu_times())
@@ -609,18 +474,18 @@ class TestSystemAPIs(unittest.TestCase):
         if not difference >= 0.05:
             self.fail("difference %s" % difference)
 
     def test_sys_per_cpu_times(self):
         for times in psutil.cpu_times(percpu=True):
             total = 0
             sum(times)
             for cp_time in times:
-                self.assertIsInstance(cp_time, float)
-                self.assertGreaterEqual(cp_time, 0.0)
+                assert isinstance(cp_time, float)
+                assert cp_time >= 0.0, cp_time
                 total += cp_time
             self.assertEqual(total, sum(times))
             str(times)
         self.assertEqual(len(psutil.cpu_times(percpu=True)[0]),
                          len(psutil.cpu_times(percpu=False)))
 
     def test_sys_per_cpu_times2(self):
         tot1 = psutil.cpu_times(percpu=True)
@@ -632,19 +497,19 @@ class TestSystemAPIs(unittest.TestCase):
         for t1, t2 in zip(tot1, tot2):
             t1, t2 = sum(t1), sum(t2)
             difference = t2 - t1
             if difference >= 0.05:
                 return
         self.fail()
 
     def _test_cpu_percent(self, percent):
-        self.assertIsInstance(percent, float)
-        self.assertGreaterEqual(percent, 0.0)
-        self.assertLessEqual(percent, 100.0)
+        assert isinstance(percent, float), percent
+        assert percent >= 0.0, percent
+        assert percent <= 100.0, percent
 
     def test_sys_cpu_percent(self):
         psutil.cpu_percent(interval=0.001)
         for x in range(1000):
             self._test_cpu_percent(psutil.cpu_percent(interval=None))
 
     def test_sys_per_cpu_percent(self):
         self.assertEqual(len(psutil.cpu_percent(interval=0.001, percpu=True)),
@@ -668,18 +533,16 @@ class TestSystemAPIs(unittest.TestCase):
                          psutil.NUM_CPUS)
         for x in range(1000):
             cpus = psutil.cpu_times_percent(interval=None, percpu=True)
             for cpu in cpus:
                 for percent in cpu:
                     self._test_cpu_percent(percent)
                 self._test_cpu_percent(sum(cpu))
 
-    @unittest.skipIf(POSIX and not hasattr(os, 'statvfs'),
-                     "os.statvfs() function not available on this platform")
     def test_disk_usage(self):
         usage = psutil.disk_usage(os.getcwd())
         assert usage.total > 0, usage
         assert usage.used > 0, usage
         assert usage.free > 0, usage
         assert usage.total > usage.used, usage
         assert usage.total > usage.free, usage
         assert 0 <= usage.percent <= 100, usage.percent
@@ -691,68 +554,50 @@ class TestSystemAPIs(unittest.TestCase):
             psutil.disk_usage(fname)
         except OSError:
             err = sys.exc_info()[1]
             if err.args[0] != errno.ENOENT:
                 raise
         else:
             self.fail("OSError not raised")
 
-    @unittest.skipIf(POSIX and not hasattr(os, 'statvfs'),
-                     "os.statvfs() function not available on this platform")
     def test_disk_partitions(self):
-        # all = False
         for disk in psutil.disk_partitions(all=False):
             if WINDOWS and 'cdrom' in disk.opts:
                 continue
-            if not POSIX:
-                assert os.path.exists(disk.device), disk
-            else:
-                # we cannot make any assumption about this, see:
-                # http://goo.gl/p9c43
-                disk.device
-            if SUNOS:
-                # on solaris apparently mount points can also be files
-                assert os.path.exists(disk.mountpoint), disk
-            else:
-                assert os.path.isdir(disk.mountpoint), disk
+            assert os.path.exists(disk.device), disk
+            assert os.path.isdir(disk.mountpoint), disk
             assert disk.fstype, disk
-            self.assertIsInstance(disk.opts, str)
-
-        # all = True
+            assert isinstance(disk.opts, str)
         for disk in psutil.disk_partitions(all=True):
             if not WINDOWS:
                 try:
                     os.stat(disk.mountpoint)
                 except OSError:
                     # http://mail.python.org/pipermail/python-dev/2012-June/120787.html
                     err = sys.exc_info()[1]
                     if err.errno not in (errno.EPERM, errno.EACCES):
                         raise
                 else:
-                    if SUNOS:
-                        # on solaris apparently mount points can also be files
-                        assert os.path.exists(disk.mountpoint), disk
-                    else:
-                        assert os.path.isdir(disk.mountpoint), disk
-            self.assertIsInstance(disk.fstype, str)
-            self.assertIsInstance(disk.opts, str)
+                    assert os.path.isdir(disk.mountpoint), disk.mountpoint
+            assert isinstance(disk.fstype, str)
+            assert isinstance(disk.opts, str)
 
         def find_mount_point(path):
             path = os.path.abspath(path)
             while not os.path.ismount(path):
                 path = os.path.dirname(path)
             return path
 
         mount = find_mount_point(__file__)
         mounts = [x.mountpoint for x in psutil.disk_partitions(all=True)]
         self.assertIn(mount, mounts)
         psutil.disk_usage(mount)
 
-    def test_net_io_counters(self):
+    def test_network_io_counters(self):
         def check_ntuple(nt):
             self.assertEqual(nt[0], nt.bytes_sent)
             self.assertEqual(nt[1], nt.bytes_recv)
             self.assertEqual(nt[2], nt.packets_sent)
             self.assertEqual(nt[3], nt.packets_recv)
             self.assertEqual(nt[4], nt.errin)
             self.assertEqual(nt[5], nt.errout)
             self.assertEqual(nt[6], nt.dropin)
@@ -761,19 +606,19 @@ class TestSystemAPIs(unittest.TestCase):
             assert nt.bytes_recv >= 0, nt
             assert nt.packets_sent >= 0, nt
             assert nt.packets_recv >= 0, nt
             assert nt.errin >= 0, nt
             assert nt.errout >= 0, nt
             assert nt.dropin >= 0, nt
             assert nt.dropout >= 0, nt
 
-        ret = psutil.net_io_counters(pernic=False)
+        ret = psutil.network_io_counters(pernic=False)
         check_ntuple(ret)
-        ret = psutil.net_io_counters(pernic=True)
+        ret = psutil.network_io_counters(pernic=True)
         assert ret != []
         for key in ret:
             assert key
             check_ntuple(ret[key])
 
     def test_disk_io_counters(self):
         def check_ntuple(nt):
             self.assertEqual(nt[0], nt.read_count)
@@ -797,41 +642,31 @@ class TestSystemAPIs(unittest.TestCase):
         for key in ret:
             assert key, key
             check_ntuple(ret[key])
             if LINUX and key[-1].isdigit():
                 # if 'sda1' is listed 'sda' shouldn't, see:
                 # http://code.google.com/p/psutil/issues/detail?id=338
                 while key[-1].isdigit():
                     key = key[:-1]
-                self.assertNotIn(key, ret.keys())
+                assert key not in ret, (key, ret.keys())
 
     def test_get_users(self):
         users = psutil.get_users()
         assert users
         for user in users:
             assert user.name, user
             user.terminal
             user.host
             assert user.started > 0.0, user
             datetime.datetime.fromtimestamp(user.started)
 
-
-# ===================================================================
-# --- psutil.Process class tests
-# ===================================================================
-
-class TestProcess(unittest.TestCase):
-    """Tests for psutil.Process class."""
-
-    def setUp(self):
-        safe_remove(TESTFN)
-
-    def tearDown(self):
-        reap_children()
+    # ====================
+    # Process object tests
+    # ====================
 
     def test_kill(self):
         sproc = get_test_subprocess(wait=True)
         test_pid = sproc.pid
         p = psutil.Process(test_pid)
         name = p.name
         p.kill()
         p.wait()
@@ -901,22 +736,22 @@ class TestProcess(unittest.TestCase):
         sproc = get_test_subprocess()
         p = psutil.Process(sproc.pid)
         p.name
         self.assertRaises(psutil.TimeoutExpired, p.wait, 0.01)
 
         # timeout < 0 not allowed
         self.assertRaises(ValueError, p.wait, -1)
 
-    @unittest.skipUnless(POSIX, '')  # XXX why is this skipped on Windows?
+    @skipUnless(POSIX)
     def test_wait_non_children(self):
         # test wait() against processes which are not our children
         code = "import sys;"
         code += "from subprocess import Popen, PIPE;"
-        code += "cmd = ['%s', '-c', 'import time; time.sleep(2)'];" %PYTHON
+        code += "cmd = ['%s', '-c', 'import time; time.sleep(10)'];" %PYTHON
         code += "sp = Popen(cmd, stdout=PIPE);"
         code += "sys.stdout.write(str(sp.pid));"
         sproc = get_test_subprocess([PYTHON, "-c", code], stdout=subprocess.PIPE)
 
         grandson_pid = int(sproc.stdout.read())
         grandson_proc = psutil.Process(grandson_pid)
         try:
             self.assertRaises(psutil.TimeoutExpired, grandson_proc.wait, 0.01)
@@ -949,38 +784,37 @@ class TestProcess(unittest.TestCase):
         self.assertFalse(p.is_running())
 
     def test_cpu_percent(self):
         p = psutil.Process(os.getpid())
         p.get_cpu_percent(interval=0.001)
         p.get_cpu_percent(interval=0.001)
         for x in range(100):
             percent = p.get_cpu_percent(interval=None)
-            self.assertIsInstance(percent, float)
-            self.assertGreaterEqual(percent, 0.0)
+            assert isinstance(percent, float)
+            assert percent >= 0.0, percent
             if os.name != 'posix':
-                self.assertLessEqual(percent, 100.0)
+                assert percent <= 100.0, percent
             else:
-                self.assertGreaterEqual(percent, 0.0)
+                assert percent >= 0.0, percent
 
     def test_cpu_times(self):
         times = psutil.Process(os.getpid()).get_cpu_times()
         assert (times.user > 0.0) or (times.system > 0.0), times
         # make sure returned values can be pretty printed with strftime
         time.strftime("%H:%M:%S", time.localtime(times.user))
         time.strftime("%H:%M:%S", time.localtime(times.system))
 
     # Test Process.cpu_times() against os.times()
     # os.times() is broken on Python 2.6
     # http://bugs.python.org/issue1040026
     # XXX fails on OSX: not sure if it's for os.times(). We should
     # try this with Python 2.7 and re-enable the test.
 
-    @unittest.skipUnless(sys.version_info > (2, 6, 1) and not OSX,
-                         'os.times() is not reliable on this Python version')
+    @skipUnless(sys.version_info > (2, 6, 1) and not OSX)
     def test_cpu_times2(self):
         user_time, kernel_time = psutil.Process(os.getpid()).get_cpu_times()
         utime, ktime = os.times()[:2]
 
         # Use os.times()[:2] as base values to compare our results
         # using a tolerance  of +/- 0.1 seconds.
         # It will fail if the difference between the values is > 0.1s.
         if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
@@ -1001,27 +835,23 @@ class TestProcess(unittest.TestCase):
         difference = abs(create_time - now)
         if difference > 2:
             self.fail("expected: %s, found: %s, difference: %s"
                       % (now, create_time, difference))
 
         # make sure returned value can be pretty printed with strftime
         time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time))
 
-    @unittest.skipIf(WINDOWS, 'windows only')
+    @skipIf(WINDOWS)
     def test_terminal(self):
-        terminal = psutil.Process(os.getpid()).terminal
-        if sys.stdin.isatty():
-            self.assertEqual(terminal, sh('tty'))
-        else:
-            assert terminal, repr(terminal)
+        tty = sh('tty')
+        p = psutil.Process(os.getpid())
+        self.assertEqual(p.terminal, tty)
 
-    @unittest.skipIf(not hasattr(psutil.Process, 'get_io_counters'),
-                     'not available on this platform')
-    @skip_on_not_implemented(only_if=LINUX)
+    @skipIf(OSX, warn=False)
     def test_get_io_counters(self):
         p = psutil.Process(os.getpid())
         # test reads
         io1 = p.get_io_counters()
         f = open(PYTHON, 'rb')
         f.read()
         f.close()
         io2 = p.get_io_counters()
@@ -1040,18 +870,17 @@ class TestProcess(unittest.TestCase):
         f.close()
         io2 = p.get_io_counters()
         assert io2.write_count >= io1.write_count, (io1, io2)
         assert io2.write_bytes >= io1.write_bytes, (io1, io2)
         assert io2.read_count >= io1.read_count, (io1, io2)
         assert io2.read_bytes >= io1.read_bytes, (io1, io2)
 
     # Linux and Windows Vista+
-    @unittest.skipUnless(hasattr(psutil.Process, 'get_ionice'),
-                         'Linux and Windows Vista only')
+    @skipUnless(hasattr(psutil.Process, 'get_ionice'))
     def test_get_set_ionice(self):
         if LINUX:
             from psutil import (IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT,
                                 IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE)
             self.assertEqual(IOPRIO_CLASS_NONE, 0)
             self.assertEqual(IOPRIO_CLASS_RT, 1)
             self.assertEqual(IOPRIO_CLASS_BE, 2)
             self.assertEqual(IOPRIO_CLASS_IDLE, 3)
@@ -1105,21 +934,21 @@ class TestProcess(unittest.TestCase):
         try:
             step2 = p.get_num_threads()
             self.assertEqual(step2, step1 + 1)
             thread.stop()
         finally:
             if thread._running:
                 thread.stop()
 
-    @unittest.skipUnless(WINDOWS, 'Windows only')
+    @skipUnless(WINDOWS)
     def test_get_num_handles(self):
         # a better test is done later into test/_windows.py
         p = psutil.Process(os.getpid())
-        self.assertGreater(p.get_num_handles(), 0)
+        assert p.get_num_handles() > 0
 
     def test_get_threads(self):
         p = psutil.Process(os.getpid())
         step1 = p.get_threads()
 
         thread = ThreadTask()
         thread.start()
 
@@ -1141,28 +970,28 @@ class TestProcess(unittest.TestCase):
                 thread.stop()
 
     def test_get_memory_info(self):
         p = psutil.Process(os.getpid())
 
         # step 1 - get a base value to compare our results
         rss1, vms1 = p.get_memory_info()
         percent1 = p.get_memory_percent()
-        self.assertGreater(rss1, 0)
-        self.assertGreater(vms1, 0)
+        assert rss1 > 0
+        assert vms1 > 0
 
         # step 2 - allocate some memory
         memarr = [None] * 1500000
 
         rss2, vms2 = p.get_memory_info()
         percent2 = p.get_memory_percent()
         # make sure that the memory usage bumped up
-        self.assertGreater(rss2, rss1)
-        self.assertGreaterEqual(vms2, vms1)  # vms might be equal
-        self.assertGreater(percent2, percent1)
+        assert rss2 > rss1
+        assert vms2 >= vms1  # vms might be equal
+        assert percent2 > percent1
         del memarr
 
 #    def test_get_ext_memory_info(self):
 #       # tested later in fetch all test suite
 
     def test_get_memory_maps(self):
         p = psutil.Process(os.getpid())
         maps = p.get_memory_maps()
@@ -1184,22 +1013,22 @@ class TestProcess(unittest.TestCase):
         for nt in ext_maps:
             for fname in nt._fields:
                 value = getattr(nt, fname)
                 if fname == 'path':
                     continue
                 elif fname in ('addr', 'perms'):
                     assert value, value
                 else:
-                    self.assertIsInstance(value, (int, long))
+                    assert isinstance(value, (int, long))
                     assert value >= 0, value
 
     def test_get_memory_percent(self):
         p = psutil.Process(os.getpid())
-        self.assertGreater(p.get_memory_percent(), 0.0)
+        assert p.get_memory_percent() > 0.0
 
     def test_pid(self):
         sproc = get_test_subprocess()
         self.assertEqual(psutil.Process(sproc.pid).pid, sproc.pid)
 
     def test_is_running(self):
         sproc = get_test_subprocess(wait=True)
         p = psutil.Process(sproc.pid)
@@ -1225,66 +1054,54 @@ class TestProcess(unittest.TestCase):
                 # ...instead of:
                 # "/usr/local/bin/python"
                 # We do not want to consider this difference in accuracy
                 # an error.
                 ver = "%s.%s" % (sys.version_info[0], sys.version_info[1])
                 self.assertEqual(exe.replace(ver, ''), PYTHON.replace(ver, ''))
 
     def test_cmdline(self):
-        cmdline = [PYTHON, "-c", "import time; time.sleep(2)"]
-        sproc = get_test_subprocess(cmdline, wait=True)
-        self.assertEqual(' '.join(psutil.Process(sproc.pid).cmdline),
-                         ' '.join(cmdline))
+        sproc = get_test_subprocess([PYTHON, "-E"], wait=True)
+        self.assertEqual(psutil.Process(sproc.pid).cmdline, [PYTHON, "-E"])
 
     def test_name(self):
         sproc = get_test_subprocess(PYTHON, wait=True)
         name = psutil.Process(sproc.pid).name.lower()
         pyexe = os.path.basename(os.path.realpath(sys.executable)).lower()
         assert pyexe.startswith(name), (pyexe, name)
 
-    @unittest.skipUnless(POSIX, 'posix only')
-    def test_uids(self):
-        p = psutil.Process(os.getpid())
-        real, effective, saved = p.uids
-        # os.getuid() refers to "real" uid
-        self.assertEqual(real, os.getuid())
-        # os.geteuid() refers to "effective" uid
-        self.assertEqual(effective, os.geteuid())
-        # no such thing as os.getsuid() ("saved" uid), but starting
-        # from python 2.7 we have os.getresuid()[2]
-        if hasattr(os, "getresuid"):
-            self.assertEqual(saved, os.getresuid()[2])
+    if os.name == 'posix':
+
+        def test_uids(self):
+            p = psutil.Process(os.getpid())
+            real, effective, saved = p.uids
+            # os.getuid() refers to "real" uid
+            self.assertEqual(real, os.getuid())
+            # os.geteuid() refers to "effective" uid
+            self.assertEqual(effective, os.geteuid())
+            # no such thing as os.getsuid() ("saved" uid), but starting
+            # from python 2.7 we have os.getresuid()[2]
+            if hasattr(os, "getresuid"):
+                self.assertEqual(saved, os.getresuid()[2])
 
-    @unittest.skipUnless(POSIX, 'posix only')
-    def test_gids(self):
-        p = psutil.Process(os.getpid())
-        real, effective, saved = p.gids
-        # os.getuid() refers to "real" uid
-        self.assertEqual(real, os.getgid())
-        # os.geteuid() refers to "effective" uid
-        self.assertEqual(effective, os.getegid())
-        # no such thing as os.getsuid() ("saved" uid), but starting
-        # from python 2.7 we have os.getresgid()[2]
-        if hasattr(os, "getresuid"):
-            self.assertEqual(saved, os.getresgid()[2])
+        def test_gids(self):
+            p = psutil.Process(os.getpid())
+            real, effective, saved = p.gids
+            # os.getuid() refers to "real" uid
+            self.assertEqual(real, os.getgid())
+            # os.geteuid() refers to "effective" uid
+            self.assertEqual(effective, os.getegid())
+            # no such thing as os.getsuid() ("saved" uid), but starting
+            # from python 2.7 we have os.getresgid()[2]
+            if hasattr(os, "getresuid"):
+                self.assertEqual(saved, os.getresgid()[2])
 
-    def test_nice(self):
-        p = psutil.Process(os.getpid())
-        self.assertRaises(TypeError, p.set_nice, "str")
-        if os.name == 'nt':
-            try:
-                self.assertEqual(p.get_nice(), psutil.NORMAL_PRIORITY_CLASS)
-                p.set_nice(psutil.HIGH_PRIORITY_CLASS)
-                self.assertEqual(p.get_nice(), psutil.HIGH_PRIORITY_CLASS)
-                p.set_nice(psutil.NORMAL_PRIORITY_CLASS)
-                self.assertEqual(p.get_nice(), psutil.NORMAL_PRIORITY_CLASS)
-            finally:
-                p.set_nice(psutil.NORMAL_PRIORITY_CLASS)
-        else:
+        def test_nice(self):
+            p = psutil.Process(os.getpid())
+            self.assertRaises(TypeError, p.set_nice, "str")
             try:
                 try:
                     first_nice = p.get_nice()
                     p.set_nice(1)
                     self.assertEqual(p.get_nice(), 1)
                     # going back to previous nice value raises AccessDenied on OSX
                     if not OSX:
                         p.set_nice(0)
@@ -1292,16 +1109,30 @@ class TestProcess(unittest.TestCase):
                 except psutil.AccessDenied:
                     pass
             finally:
                 try:
                     p.set_nice(first_nice)
                 except psutil.AccessDenied:
                     pass
 
+    if os.name == 'nt':
+
+        def test_nice(self):
+            p = psutil.Process(os.getpid())
+            self.assertRaises(TypeError, p.set_nice, "str")
+            try:
+                self.assertEqual(p.get_nice(), psutil.NORMAL_PRIORITY_CLASS)
+                p.set_nice(psutil.HIGH_PRIORITY_CLASS)
+                self.assertEqual(p.get_nice(), psutil.HIGH_PRIORITY_CLASS)
+                p.set_nice(psutil.NORMAL_PRIORITY_CLASS)
+                self.assertEqual(p.get_nice(), psutil.NORMAL_PRIORITY_CLASS)
+            finally:
+                p.set_nice(psutil.NORMAL_PRIORITY_CLASS)
+
     def test_status(self):
         p = psutil.Process(os.getpid())
         self.assertEqual(p.status, psutil.STATUS_RUNNING)
         self.assertEqual(str(p.status), "running")
 
     def test_status_constants(self):
         # STATUS_* constants are supposed to be comparable also by
         # using their str representation
@@ -1316,42 +1147,39 @@ class TestProcess(unittest.TestCase):
         self.assertTrue(psutil.STATUS_RUNNING != 'sleeping')
 
     def test_username(self):
         sproc = get_test_subprocess()
         p = psutil.Process(sproc.pid)
         if POSIX:
             import pwd
             self.assertEqual(p.username, pwd.getpwuid(os.getuid()).pw_name)
-        elif WINDOWS and 'USERNAME' in os.environ:
+        elif WINDOWS:
             expected_username = os.environ['USERNAME']
             expected_domain = os.environ['USERDOMAIN']
             domain, username = p.username.split('\\')
             self.assertEqual(domain, expected_domain)
             self.assertEqual(username, expected_username)
         else:
             p.username
 
-    @unittest.skipUnless(hasattr(psutil.Process, "getcwd"),
-                         'not available on this platform')
+    @skipIf(not hasattr(psutil.Process, "getcwd"))
     def test_getcwd(self):
         sproc = get_test_subprocess(wait=True)
         p = psutil.Process(sproc.pid)
         self.assertEqual(p.getcwd(), os.getcwd())
 
-    @unittest.skipIf(not hasattr(psutil.Process, "getcwd"),
-                     'not available on this platform')
+    @skipIf(not hasattr(psutil.Process, "getcwd"))
     def test_getcwd_2(self):
-        cmd = [PYTHON, "-c", "import os, time; os.chdir('..'); time.sleep(2)"]
+        cmd = [PYTHON, "-c", "import os, time; os.chdir('..'); time.sleep(10)"]
         sproc = get_test_subprocess(cmd, wait=True)
         p = psutil.Process(sproc.pid)
         call_until(p.getcwd, "ret == os.path.dirname(os.getcwd())", timeout=1)
 
-    @unittest.skipIf(not hasattr(psutil.Process, "get_cpu_affinity"),
-                     'not available on this platform')
+    @skipIf(not hasattr(psutil.Process, "get_cpu_affinity"))
     def test_cpu_affinity(self):
         p = psutil.Process(os.getpid())
         initial = p.get_cpu_affinity()
         all_cpus = list(range(len(psutil.cpu_percent(percpu=True))))
         #
         for n in all_cpus:
             p.set_cpu_affinity([n])
             self.assertEqual(p.get_cpu_affinity(), [n])
@@ -1372,17 +1200,17 @@ class TestProcess(unittest.TestCase):
         call_until(p.get_open_files, "len(ret) != %i" % len(files))
         filenames = [x.path for x in p.get_open_files()]
         self.assertIn(TESTFN, filenames)
         f.close()
         for file in filenames:
             assert os.path.isfile(file), file
 
         # another process
-        cmdline = "import time; f = open(r'%s', 'r'); time.sleep(2);" % TESTFN
+        cmdline = "import time; f = open(r'%s', 'r'); time.sleep(100);" % TESTFN
         sproc = get_test_subprocess([PYTHON, "-c", cmdline], wait=True)
         p = psutil.Process(sproc.pid)
         for x in range(100):
             filenames = [x.path for x in p.get_open_files()]
             if TESTFN in filenames:
                 break
             time.sleep(.01)
         else:
@@ -1407,139 +1235,115 @@ class TestProcess(unittest.TestCase):
         # test positions
         ntuple = p.get_open_files()[0]
         self.assertEqual(ntuple[0], ntuple.path)
         self.assertEqual(ntuple[1], ntuple.fd)
         # test file is gone
         fileobj.close()
         self.assertTrue(fileobj.name not in p.get_open_files())
 
-    def test_connection_constants(self):
-        ints = []
-        strs = []
-        for name in dir(psutil):
-            if name.startswith('CONN_'):
-                num = getattr(psutil, name)
-                str_ = str(num)
-                assert str_.isupper(), str_
-                assert str_ not in strs, str_
-                assert num not in ints, num
-                ints.append(num)
-                strs.append(str_)
-        if SUNOS:
-            psutil.CONN_IDLE
-            psutil.CONN_BOUND
-        if WINDOWS:
-            psutil.CONN_DELETE_TCB
-
     def test_get_connections(self):
         arg = "import socket, time;" \
               "s = socket.socket();" \
               "s.bind(('127.0.0.1', 0));" \
               "s.listen(1);" \
               "conn, addr = s.accept();" \
-              "time.sleep(2);"
+              "time.sleep(100);"
         sproc = get_test_subprocess([PYTHON, "-c", arg])
         p = psutil.Process(sproc.pid)
         for x in range(100):
-            if p.get_connections():
-                # give the subprocess some more time to bind()
-                time.sleep(.01)
-                cons = p.get_connections()
+            cons = p.get_connections()
+            if cons:
                 break
             time.sleep(.01)
         self.assertEqual(len(cons), 1)
         con = cons[0]
         self.assertEqual(con.family, socket.AF_INET)
         self.assertEqual(con.type, socket.SOCK_STREAM)
-        self.assertEqual(con.status, psutil.CONN_LISTEN, str(con.status))
-        ip, port = con.laddr
+        self.assertEqual(con.status, "LISTEN")
+        ip, port = con.local_address
         self.assertEqual(ip, '127.0.0.1')
-        self.assertEqual(con.raddr, ())
-        if WINDOWS or SUNOS:
+        self.assertEqual(con.remote_address, ())
+        if WINDOWS:
             self.assertEqual(con.fd, -1)
         else:
             assert con.fd > 0, con
         # test positions
         self.assertEqual(con[0], con.fd)
         self.assertEqual(con[1], con.family)
         self.assertEqual(con[2], con.type)
-        self.assertEqual(con[3], con.laddr)
-        self.assertEqual(con[4], con.raddr)
+        self.assertEqual(con[3], con.local_address)
+        self.assertEqual(con[4], con.remote_address)
         self.assertEqual(con[5], con.status)
         # test kind arg
         self.assertRaises(ValueError, p.get_connections, 'foo')
 
-    @unittest.skipUnless(supports_ipv6(), 'IPv6 is not supported')
+    @skipUnless(supports_ipv6())
     def test_get_connections_ipv6(self):
         s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
         s.bind(('::1', 0))
         s.listen(1)
         cons = psutil.Process(os.getpid()).get_connections()
         s.close()
         self.assertEqual(len(cons), 1)
-        self.assertEqual(cons[0].laddr[0], '::1')
+        self.assertEqual(cons[0].local_address[0], '::1')
 
-    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'AF_UNIX is not supported')
+    @skipUnless(hasattr(socket, 'AF_UNIX'))
     def test_get_connections_unix(self):
         # tcp
         safe_remove(TESTFN)
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
         sock.bind(TESTFN)
         conn = psutil.Process(os.getpid()).get_connections(kind='unix')[0]
-        if conn.fd != -1:  # != sunos and windows
-            self.assertEqual(conn.fd, sock.fileno())
+        self.assertEqual(conn.fd, sock.fileno())
         self.assertEqual(conn.family, socket.AF_UNIX)
         self.assertEqual(conn.type, socket.SOCK_STREAM)
-        self.assertEqual(conn.laddr, TESTFN)
-        self.assertTrue(not conn.raddr)
-        self.assertEqual(conn.status, psutil.CONN_NONE, str(conn.status))
+        self.assertEqual(conn.local_address, TESTFN)
+        self.assertTrue(not conn.remote_address)
+        self.assertTrue(not conn.status)
         sock.close()
         # udp
         safe_remove(TESTFN)
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
         sock.bind(TESTFN)
         conn = psutil.Process(os.getpid()).get_connections(kind='unix')[0]
         self.assertEqual(conn.type, socket.SOCK_DGRAM)
         sock.close()
 
-    @unittest.skipUnless(hasattr(socket, "fromfd"),
-                         'socket.fromfd() is not availble')
-    @unittest.skipIf(WINDOWS or SUNOS,
-                     'connection fd available on this platform')
+    @skipUnless(hasattr(socket, "fromfd") and not WINDOWS)
     def test_connection_fromfd(self):
         sock = socket.socket()
         sock.bind(('localhost', 0))
         sock.listen(1)
         p = psutil.Process(os.getpid())
         for conn in p.get_connections():
             if conn.fd == sock.fileno():
                 break
         else:
             sock.close()
             self.fail("couldn't find socket fd")
         dupsock = socket.fromfd(conn.fd, conn.family, conn.type)
         try:
-            self.assertEqual(dupsock.getsockname(), conn.laddr)
+            self.assertEqual(dupsock.getsockname(), conn.local_address)
             self.assertNotEqual(sock.fileno(), dupsock.fileno())
         finally:
             sock.close()
             dupsock.close()
 
     def test_get_connections_all(self):
         tcp_template = "import socket;" \
                        "s = socket.socket($family, socket.SOCK_STREAM);" \
                        "s.bind(('$addr', 0));" \
                        "s.listen(1);" \
                        "conn, addr = s.accept();"
 
         udp_template = "import socket, time;" \
                        "s = socket.socket($family, socket.SOCK_DGRAM);" \
                        "s.bind(('$addr', 0));" \
-                       "time.sleep(2);"
+                       "time.sleep(100);"
 
         from string import Template
         tcp4_template = Template(tcp_template).substitute(family=socket.AF_INET,
                                                           addr="127.0.0.1")
         udp4_template = Template(udp_template).substitute(family=socket.AF_INET,
                                                           addr="127.0.0.1")
         tcp6_template = Template(tcp_template).substitute(family=socket.AF_INET6,
                                                           addr="::1")
@@ -1561,82 +1365,77 @@ class TestProcess(unittest.TestCase):
         all_kinds = ("all", "inet", "inet4", "inet6", "tcp", "tcp4", "tcp6",
                      "udp", "udp4", "udp6")
         for p in psutil.Process(os.getpid()).get_children():
             for conn in p.get_connections():
                 # TCP v4
                 if p.pid == tcp4_proc.pid:
                     self.assertEqual(conn.family, socket.AF_INET)
                     self.assertEqual(conn.type, socket.SOCK_STREAM)
-                    self.assertEqual(conn.laddr[0], "127.0.0.1")
-                    self.assertEqual(conn.raddr, ())
-                    self.assertEqual(conn.status, psutil.CONN_LISTEN,
-                                    str(conn.status))
+                    self.assertEqual(conn.local_address[0], "127.0.0.1")
+                    self.assertEqual(conn.remote_address, ())
+                    self.assertEqual(conn.status, "LISTEN")
                     for kind in all_kinds:
                         cons = p.get_connections(kind=kind)
                         if kind in ("all", "inet", "inet4", "tcp", "tcp4"):
                             assert cons != [], cons
                         else:
                             self.assertEqual(cons, [], cons)
                 # UDP v4
                 elif p.pid == udp4_proc.pid:
                     self.assertEqual(conn.family, socket.AF_INET)
                     self.assertEqual(conn.type, socket.SOCK_DGRAM)
-                    self.assertEqual(conn.laddr[0], "127.0.0.1")
-                    self.assertEqual(conn.raddr, ())
-                    self.assertEqual(conn.status, psutil.CONN_NONE,
-                                     str(conn.status))
+                    self.assertEqual(conn.local_address[0], "127.0.0.1")
+                    self.assertEqual(conn.remote_address, ())
+                    self.assertEqual(conn.status, "")
                     for kind in all_kinds:
                         cons = p.get_connections(kind=kind)
                         if kind in ("all", "inet", "inet4", "udp", "udp4"):
                             assert cons != [], cons
                         else:
                             self.assertEqual(cons, [], cons)
                 # TCP v6
                 elif p.pid == getattr(tcp6_proc, "pid", None):
                     self.assertEqual(conn.family, socket.AF_INET6)
                     self.assertEqual(conn.type, socket.SOCK_STREAM)
-                    self.assertIn(conn.laddr[0], ("::", "::1"))
-                    self.assertEqual(conn.raddr, ())
-                    self.assertEqual(conn.status, psutil.CONN_LISTEN,
-                                     str(conn.status))
+                    self.assertIn(conn.local_address[0], ("::", "::1"))
+                    self.assertEqual(conn.remote_address, ())
+                    self.assertEqual(conn.status, "LISTEN")
                     for kind in all_kinds:
                         cons = p.get_connections(kind=kind)
                         if kind in ("all", "inet", "inet6", "tcp", "tcp6"):
                             assert cons != [], cons
                         else:
                             self.assertEqual(cons, [], cons)
                 # UDP v6
                 elif p.pid == getattr(udp6_proc, "pid", None):
                     self.assertEqual(conn.family, socket.AF_INET6)
                     self.assertEqual(conn.type, socket.SOCK_DGRAM)
-                    self.assertIn(conn.laddr[0], ("::", "::1"))
-                    self.assertEqual(conn.raddr, ())
-                    self.assertEqual(conn.status, psutil.CONN_NONE,
-                                     str(conn.status))
+                    self.assertIn(conn.local_address[0], ("::", "::1"))
+                    self.assertEqual(conn.remote_address, ())
+                    self.assertEqual(conn.status, "")
                     for kind in all_kinds:
                         cons = p.get_connections(kind=kind)
                         if kind in ("all", "inet", "inet6", "udp", "udp6"):
                             assert cons != [], cons
                         else:
                             self.assertEqual(cons, [], cons)
 
-    @unittest.skipUnless(POSIX, 'posix only')
+    @skipUnless(POSIX)
     def test_get_num_fds(self):
         p = psutil.Process(os.getpid())
         start = p.get_num_fds()
         file = open(TESTFN, 'w')
         self.assertEqual(p.get_num_fds(), start + 1)
         sock = socket.socket()
         self.assertEqual(p.get_num_fds(), start + 2)
         file.close()
         sock.close()
         self.assertEqual(p.get_num_fds(), start)
 
-    @skip_on_not_implemented(only_if=LINUX)
     def test_get_num_ctx_switches(self):
         p = psutil.Process(os.getpid())
         before = sum(p.get_num_ctx_switches())
         for x in range(500000):
             after = sum(p.get_num_ctx_switches())
             if after > before:
                 return
         self.fail("num ctx switches still the same after 50.000 iterations")
@@ -1665,19 +1464,19 @@ class TestProcess(unittest.TestCase):
             self.assertEqual(children[0].pid, sproc.pid)
             self.assertEqual(children[0].ppid, os.getpid())
 
     def test_get_children_recursive(self):
         # here we create a subprocess which creates another one as in:
         # A (parent) -> B (child) -> C (grandchild)
         s =  "import subprocess, os, sys, time;"
         s += "PYTHON = os.path.realpath(sys.executable);"
-        s += "cmd = [PYTHON, '-c', 'import time; time.sleep(2);'];"
+        s += "cmd = [PYTHON, '-c', 'import time; time.sleep(3600);'];"
         s += "subprocess.Popen(cmd);"
-        s += "time.sleep(2);"
+        s += "time.sleep(3600);"
         get_test_subprocess(cmd=[PYTHON, "-c", s])
         p = psutil.Process(os.getpid())
         self.assertEqual(len(p.get_children(recursive=False)), 1)
         # give the grandchild some time to start
         stop_at = time.time() + 1.5
         while time.time() < stop_at:
             children = p.get_children(recursive=True)
             if len(children) > 1:
@@ -1742,17 +1541,17 @@ class TestProcess(unittest.TestCase):
         if not isinstance(d['connections'], list):
             self.assertEqual(d['connections'], 'foo')
 
     def test_zombie_process(self):
         # Test that NoSuchProcess exception gets raised in case the
         # process dies after we create the Process object.
         # Example:
         #  >>> proc = Process(1234)
-        #  >>> time.sleep(2)  # time-consuming task, process dies in meantime
+        #  >>> time.sleep(5)  # time-consuming task, process dies in meantime
         #  >>> proc.name
         # Refers to Issue #15
         sproc = get_test_subprocess()
         p = psutil.Process(sproc.pid)
         p.kill()
         p.wait()
 
         for name in dir(p):
@@ -1762,18 +1561,16 @@ class TestProcess(unittest.TestCase):
                         'nice'):
                 continue
             try:
                 meth = getattr(p, name)
                 if callable(meth):
                     meth()
             except psutil.NoSuchProcess:
                 pass
-            except NotImplementedError:
-                pass
             else:
                 self.fail("NoSuchProcess exception not raised for %r" % name)
 
         # other methods
         try:
             if os.name == 'posix':
                 p.set_nice(1)
             else:
@@ -1799,60 +1596,53 @@ class TestProcess(unittest.TestCase):
             self.assertIn(os.path.basename(PYTHON), str(p))
         sproc = get_test_subprocess()
         p = psutil.Process(sproc.pid)
         p.kill()
         p.wait()
         self.assertIn(str(sproc.pid), str(p))
         self.assertIn("terminated", str(p))
 
-    @unittest.skipIf(LINUX, 'PID 0 not available on Linux')
+    @skipIf(LINUX)
     def test_pid_0(self):
         # Process(0) is supposed to work on all platforms except Linux
         p = psutil.Process(0)
         self.assertTrue(p.name)
 
         if os.name == 'posix':
-            try:
-                self.assertEqual(p.uids.real, 0)
-                self.assertEqual(p.gids.real, 0)
-            except psutil.AccessDenied:
-                pass
+            self.assertEqual(p.uids.real, 0)
+            self.assertEqual(p.gids.real, 0)
 
         self.assertIn(p.ppid, (0, 1))
         #self.assertEqual(p.exe, "")
-        p.cmdline
+        self.assertEqual(p.cmdline, [])
         try:
             p.get_num_threads()
         except psutil.AccessDenied:
             pass
 
         try:
             p.get_memory_info()
         except psutil.AccessDenied:
             pass
 
         # username property
-        try:
-            if POSIX:
-                self.assertEqual(p.username, 'root')
-            elif WINDOWS:
-                self.assertEqual(p.username, 'NT AUTHORITY\\SYSTEM')
-            else:
-                p.username
-        except psutil.AccessDenied:
-            pass
+        if POSIX:
+            self.assertEqual(p.username, 'root')
+        elif WINDOWS:
+            self.assertEqual(p.username, 'NT AUTHORITY\\SYSTEM')
+        else:
+            p.username
 
         self.assertIn(0, psutil.get_pid_list())
         self.assertTrue(psutil.pid_exists(0))
 
     def test__all__(self):
         for name in dir(psutil):
-            if name in ('callable', 'defaultdict', 'error', 'namedtuple',
-                        'test'):
+            if name in ('callable', 'defaultdict', 'error', 'namedtuple'):
                 continue
             if not name.startswith('_'):
                 try:
                     __import__(name)
                 except ImportError:
                     if name not in psutil.__all__:
                         fun = getattr(psutil, name)
                         if fun is None:
@@ -1860,37 +1650,40 @@ class TestProcess(unittest.TestCase):
                         if 'deprecated' not in fun.__doc__.lower():
                             self.fail('%r not in psutil.__all__' % name)
 
     def test_Popen(self):
         # Popen class test
         # XXX this test causes a ResourceWarning on Python 3 because
         # psutil.__subproc instance doesn't get propertly freed.
         # Not sure what to do though.
-        cmd = [PYTHON, "-c", "import time; time.sleep(2);"]
+        cmd = [PYTHON, "-c", "import time; time.sleep(3600);"]
         proc = psutil.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
         try:
             proc.name
             proc.stdin
             self.assertTrue(hasattr(proc, 'name'))
             self.assertTrue(hasattr(proc, 'stdin'))
             self.assertRaises(AttributeError, getattr, proc, 'foo')
         finally:
             proc.kill()
             proc.wait()
 
 
-# ===================================================================
-# --- Featch all processes test
-# ===================================================================
-
 class TestFetchAllProcesses(unittest.TestCase):
     # Iterates over all running processes and performs some sanity
     # checks against Process API's returned values.
 
+    # Python 2.4 compatibility
+    if not hasattr(unittest.TestCase, "assertIn"):
+        def assertIn(self, member, container, msg=None):
+            if member not in container:
+                self.fail(msg or \
+                        '%s not found in %s' % (repr(member), repr(container)))
+
     def setUp(self):
         if POSIX:
             import pwd
             pall = pwd.getpwall()
             self._uids = set([x.pw_uid for x in pall])
             self._usernames = set([x.pw_name for x in pall])
 
     def test_fetch_all(self):
@@ -1916,20 +1709,16 @@ class TestFetchAllProcesses(unittest.Tes
                 try:
                     try:
                         attr = getattr(p, name, None)
                         if attr is not None and callable(attr):
                             ret = attr()
                         else:
                             ret = attr
                         valid_procs += 1
-                    except NotImplementedError:
-                        register_warning("%r was skipped because not "
-                            "implemented" % (self.__class__.__name__ + \
-                                             '.test_' + name))
                     except (psutil.NoSuchProcess, psutil.AccessDenied):
                         err = sys.exc_info()[1]
                         if isinstance(err, psutil.NoSuchProcess):
                             if psutil.pid_exists(p.pid):
                                 # XXX race condition; we probably need
                                 # to try figuring out the process
                                 # identity before failing
                                 self.fail("PID still exists but fun raised " \
@@ -1966,17 +1755,17 @@ class TestFetchAllProcesses(unittest.Tes
         # special cases.
         self.assertTrue(valid_procs > 0)
 
     def cmdline(self, ret):
         pass
 
     def exe(self, ret):
         if not ret:
-            self.assertEqual(ret, '')
+            assert ret == ''
         else:
             assert os.path.isabs(ret), ret
             # Note: os.stat() may return False even if the file is there
             # hence we skip the test, see:
             # http://stackoverflow.com/questions/3112546/os-path-exists-lies
             if POSIX:
                 assert os.path.isfile(ret), ret
                 if hasattr(os, 'access') and hasattr(os, "X_OK"):
@@ -1987,18 +1776,18 @@ class TestFetchAllProcesses(unittest.Tes
         self.assertTrue(ret >= 0)
 
     def name(self, ret):
         self.assertTrue(isinstance(ret, str))
         self.assertTrue(ret)
 
     def create_time(self, ret):
         self.assertTrue(ret > 0)
-        # this can't be taken for granted on all platforms
-        #self.assertGreaterEqual(ret, psutil.BOOT_TIME)
+        if not WINDOWS:
+            assert ret >= psutil.BOOT_TIME, (ret, psutil.BOOT_TIME)
         # make sure returned value can be pretty printed
         # with strftime
         time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
 
     def uids(self, ret):
         for uid in ret:
             self.assertTrue(uid >= 0)
             self.assertIn(uid, self._uids)
@@ -2064,47 +1853,43 @@ class TestFetchAllProcesses(unittest.Tes
             assert ret.peak_nonpaged_pool >= ret.nonpaged_pool, ret
             assert ret.peak_pagefile >= ret.pagefile, ret
 
     def get_open_files(self, ret):
         for f in ret:
             if WINDOWS:
                 assert f.fd == -1, f
             else:
-                self.assertIsInstance(f.fd, int)
+                assert isinstance(f.fd, int), f
             assert os.path.isabs(f.path), f
             assert os.path.isfile(f.path), f
 
     def get_num_fds(self, ret):
         self.assertTrue(ret >= 0)
 
     def get_connections(self, ret):
         # all values are supposed to match Linux's tcp_states.h states
         # table across all platforms.
         valid_conn_states = ["ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1",
                              "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT",
-                             "LAST_ACK", "LISTEN", "CLOSING", "NONE"]
-        if SUNOS:
-            valid_conn_states += ["IDLE", "BOUND"]
-        if WINDOWS:
-            valid_conn_states += ["DELETE_TCB"]
+                             "LAST_ACK", "LISTEN", "CLOSING", ""]
         for conn in ret:
             self.assertIn(conn.type, (socket.SOCK_STREAM, socket.SOCK_DGRAM))
             self.assertIn(conn.family, (socket.AF_INET, socket.AF_INET6))
-            check_ip_address(conn.laddr, conn.family)
-            check_ip_address(conn.raddr, conn.family)
+            check_ip_address(conn.local_address, conn.family)
+            check_ip_address(conn.remote_address, conn.family)
             if conn.status not in valid_conn_states:
-                self.fail("%s is not a valid status" % conn.status)
+                self.fail("%s is not a valid status" %conn.status)
             # actually try to bind the local socket; ignore IPv6
             # sockets as their address might be represented as
             # an IPv4-mapped-address (e.g. "::127.0.0.1")
             # and that's rejected by bind()
             if conn.family == socket.AF_INET:
                 s = socket.socket(conn.family, conn.type)
-                s.bind((conn.laddr[0], 0))
+                s.bind((conn.local_address[0], 0))
                 s.close()
 
             if not WINDOWS and hasattr(socket, 'fromfd'):
                 dupsock = None
                 try:
                     try:
                         dupsock = socket.fromfd(conn.fd, conn.family, conn.type)
                     except (socket.error, OSError):
@@ -2154,180 +1939,91 @@ class TestFetchAllProcesses(unittest.Tes
                 if fname == 'path':
                     if not value.startswith('['):
                         assert os.path.isabs(nt.path), nt.path
                         # commented as on Linux we might get '/foo/bar (deleted)'
                         #assert os.path.exists(nt.path), nt.path
                 elif fname in ('addr', 'perms'):
                     self.assertTrue(value)
                 else:
-                    self.assertIsInstance(value, (int, long))
+                    assert isinstance(value, (int, long))
                     assert value >= 0, value
 
     def get_num_handles(self, ret):
         if WINDOWS:
-            self.assertGreaterEqual(ret, 0)
+            assert ret >= 0
         else:
-            self.assertGreaterEqual(ret, 0)
+            assert ret > 0
 
     def get_nice(self, ret):
         if POSIX:
             assert -20 <= ret <= 20, ret
         else:
             priorities = [getattr(psutil, x) for x in dir(psutil)
                           if x.endswith('_PRIORITY_CLASS')]
             self.assertIn(ret, priorities)
 
     def get_num_ctx_switches(self, ret):
         self.assertTrue(ret.voluntary >= 0)
         self.assertTrue(ret.involuntary >= 0)
 
-
-# ===================================================================
-# --- Limited user tests
-# ===================================================================
-
-if hasattr(os, 'getuid') and os.getuid() == 0:
-    class LimitedUserTestCase(TestProcess):
+if hasattr(os, 'getuid'):
+    class LimitedUserTestCase(TestCase):
         """Repeat the previous tests by using a limited user.
         Executed only on UNIX and only if the user who run the test script
         is root.
         """
         # the uid/gid the test suite runs under
         PROCESS_UID = os.getuid()
         PROCESS_GID = os.getgid()
 
         def __init__(self, *args, **kwargs):
-            TestProcess.__init__(self, *args, **kwargs)
+            TestCase.__init__(self, *args, **kwargs)
             # re-define all existent test methods in order to
             # ignore AccessDenied exceptions
             for attr in [x for x in dir(self) if x.startswith('test')]:
                 meth = getattr(self, attr)
                 def test_(self):
                     try:
                         meth()
                     except psutil.AccessDenied:
                         pass
                 setattr(self, attr, types.MethodType(test_, self))
 
         def setUp(self):
             os.setegid(1000)
             os.seteuid(1000)
-            TestProcess.setUp(self)
+            TestCase.setUp(self)
 
         def tearDown(self):
             os.setegid(self.PROCESS_UID)
             os.seteuid(self.PROCESS_GID)
-            TestProcess.tearDown(self)
+            TestCase.tearDown(self)
 
         def test_nice(self):
             try:
                 psutil.Process(os.getpid()).set_nice(-1)
             except psutil.AccessDenied:
                 pass
             else:
                 self.fail("exception not raised")
 
 
-# ===================================================================
-# --- Example script tests
-# ===================================================================
-
-class TestExampleScripts(unittest.TestCase):
-    """Tests for scripts in the examples directory."""
-
-    def assert_stdout(self, exe, args=None):
-        exe = os.path.join(EXAMPLES_DIR, exe)
-        if args:
-            exe = exe + ' ' + args
-        try:
-            out = sh(sys.executable + ' ' + exe).strip()
-        except RuntimeError:
-            err = sys.exc_info()[1]
-            if 'AccessDenied' in str(err):
-                return str(err)
-            else:
-                raise
-        assert out, out
-        return out
-
-    def assert_syntax(self, exe, args=None):
-        exe = os.path.join(EXAMPLES_DIR, exe)
-        f = open(exe, 'r')
-        try:
-            src = f.read()
-        finally:
-            f.close()
-        ast.parse(src)
-
-    def test_check_presence(self):
-        # make sure all example scripts have a test method defined
-        meths = dir(self)
-        for name in os.listdir(EXAMPLES_DIR):
-            if name.endswith('.py'):
-                if 'test_' + os.path.splitext(name)[0] not in meths:
-                    #self.assert_stdout(name)
-                    self.fail('no test defined for %r script' \
-                              % os.path.join(EXAMPLES_DIR, name))
-
-    def test_disk_usage(self):
-        self.assert_stdout('disk_usage.py')
-
-    def test_free(self):
-        self.assert_stdout('free.py')
-
-    def test_meminfo(self):
-        self.assert_stdout('meminfo.py')
-
-    def test_process_detail(self):
-        self.assert_stdout('process_detail.py')
-
-    def test_who(self):
-        self.assert_stdout('who.py')
-
-    def test_netstat(self):
-        self.assert_stdout('netstat.py')
-
-    def test_pmap(self):
-        self.assert_stdout('pmap.py', args=str(os.getpid()))
-
-    @unittest.skipIf(ast is None,
-                     'ast module not available on this python version')
-    def test_killall(self):
-        self.assert_syntax('killall.py')
-
-    @unittest.skipIf(ast is None,
-                     'ast module not available on this python version')
-    def test_nettop(self):
-        self.assert_syntax('nettop.py')
-
-    @unittest.skipIf(ast is None,
-                     'ast module not available on this python version')
-    def test_top(self):
-        self.assert_syntax('top.py')
-
-    @unittest.skipIf(ast is None,
-                     'ast module not available on this python version')
-    def test_iotop(self):
-        self.assert_syntax('iotop.py')
-
-
 def cleanup():
     reap_children(search_all=True)
     DEVNULL.close()
     safe_remove(TESTFN)
 
 atexit.register(cleanup)
 safe_remove(TESTFN)
 
 def test_main():
     tests = []
     test_suite = unittest.TestSuite()
-    tests.append(TestSystemAPIs)
-    tests.append(TestProcess)
+    tests.append(TestCase)
     tests.append(TestFetchAllProcesses)
 
     if POSIX:
         from _posix import PosixSpecificTestCase
         tests.append(PosixSpecificTestCase)
 
     # import the specific platform test suite
     if LINUX:
@@ -2335,29 +2031,23 @@ def test_main():
     elif WINDOWS:
         from _windows import WindowsSpecificTestCase as stc
         from _windows import TestDualProcessImplementation
         tests.append(TestDualProcessImplementation)
     elif OSX:
         from _osx import OSXSpecificTestCase as stc
     elif BSD:
         from _bsd import BSDSpecificTestCase as stc
-    elif SUNOS:
-        from _sunos import SunOSSpecificTestCase as stc
     tests.append(stc)
 
     if hasattr(os, 'getuid'):
-        if 'LimitedUserTestCase' in globals():
+        if os.getuid() == 0:
             tests.append(LimitedUserTestCase)
         else:
-            register_warning("LimitedUserTestCase was skipped (super-user "
-                             "privileges are required)")
-
-    tests.append(TestExampleScripts)
+            atexit.register(warn, "Couldn't run limited user tests ("
+                                  "super-user privileges are required)")
 
     for test_class in tests:
         test_suite.addTest(unittest.makeSuite(test_class))
-    result = unittest.TextTestRunner(verbosity=2).run(test_suite)
-    return result.wasSuccessful()
+    unittest.TextTestRunner(verbosity=2).run(test_suite)
 
 if __name__ == '__main__':
-    if not test_main():
-        sys.exit(1)
+    test_main()