1 /* 2 * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.foreign.Libraries; 25 import java.foreign.Library; 26 import java.foreign.NativeTypes; 27 import java.foreign.Scope; 28 import java.foreign.memory.Array; 29 import java.foreign.memory.Pointer; 30 import java.lang.invoke.MethodHandles; 31 import org.testng.annotations.Test; 32 import test.jextract.lp.libproc; 33 34 import static org.testng.Assert.fail; 35 36 /* 37 * @test 38 * @library .. 39 * @requires (os.family == "mac") 40 * @run driver JtregJextract -t test.jextract.lp -lproc -rpath /usr/lib -- /usr/include/libproc.h 41 * @run testng LibprocTest 42 */ 43 public class LibprocTest { 44 private static final int NAME_BUF_MAX = 256; 45 46 @Test 47 public void libprocTest() { 48 libproc lp = Libraries.bind(MethodHandles.lookup(), libproc.class); 49 50 // Scope for native allocations 51 try (Scope s = Scope.newNativeScope()) { 52 // get the number of processes 53 int numPids = lp.proc_listallpids(Pointer.nullPointer(), 0); 54 // allocate an array 55 Array<Integer> pids = s.allocateArray(NativeTypes.INT32, numPids); 56 // list all the pids into the native array 57 lp.proc_listallpids(pids.elementPointer(), numPids); 58 // convert native array to java array 59 int[] jpids = pids.toArray(num -> new int[num]); 60 // buffer for process name 61 Pointer<Byte> nameBuf = s.allocate(NativeTypes.INT8, NAME_BUF_MAX); 62 for (int i = 0; i < jpids.length; i++) { 63 int pid = jpids[i]; 64 // get the process name 65 lp.proc_name(pid, nameBuf, NAME_BUF_MAX); 66 String procName = Pointer.toString(nameBuf); 67 // print pid and process name 68 System.out.printf("%d %s\n", pid, procName); 69 } 70 } 71 } 72 }