Process.java revision 973b4663b0b5ee62006522bf4742af076096e548
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import android.net.LocalSocket; 20import android.net.LocalSocketAddress; 21import android.util.Log; 22 23import com.android.internal.os.Zygote; 24 25import java.io.BufferedWriter; 26import java.io.DataInputStream; 27import java.io.IOException; 28import java.io.OutputStreamWriter; 29import java.util.ArrayList; 30 31import libcore.io.Libcore; 32 33/*package*/ class ZygoteStartFailedEx extends Exception { 34 /** 35 * Something prevented the zygote process startup from happening normally 36 */ 37 38 ZygoteStartFailedEx() {}; 39 ZygoteStartFailedEx(String s) {super(s);} 40 ZygoteStartFailedEx(Throwable cause) {super(cause);} 41} 42 43/** 44 * Tools for managing OS processes. 45 */ 46public class Process { 47 private static final String LOG_TAG = "Process"; 48 49 private static final String ZYGOTE_SOCKET = "zygote"; 50 51 /** 52 * Name of a process for running the platform's media services. 53 * {@hide} 54 */ 55 public static final String ANDROID_SHARED_MEDIA = "com.android.process.media"; 56 57 /** 58 * Name of the process that Google content providers can share. 59 * {@hide} 60 */ 61 public static final String GOOGLE_SHARED_APP_CONTENT = "com.google.process.content"; 62 63 /** 64 * Defines the UID/GID under which system code runs. 65 */ 66 public static final int SYSTEM_UID = 1000; 67 68 /** 69 * Defines the UID/GID under which the telephony code runs. 70 */ 71 public static final int PHONE_UID = 1001; 72 73 /** 74 * Defines the UID/GID for the user shell. 75 * @hide 76 */ 77 public static final int SHELL_UID = 2000; 78 79 /** 80 * Defines the UID/GID for the log group. 81 * @hide 82 */ 83 public static final int LOG_UID = 1007; 84 85 /** 86 * Defines the UID/GID for the WIFI supplicant process. 87 * @hide 88 */ 89 public static final int WIFI_UID = 1010; 90 91 /** 92 * Defines the UID/GID for the mediaserver process. 93 * @hide 94 */ 95 public static final int MEDIA_UID = 1013; 96 97 /** 98 * Defines the UID/GID for the DRM process. 99 * @hide 100 */ 101 public static final int DRM_UID = 1019; 102 103 /** 104 * Defines the UID/GID for the group that controls VPN services. 105 * @hide 106 */ 107 public static final int VPN_UID = 1016; 108 109 /** 110 * Defines the UID/GID for the NFC service process. 111 * @hide 112 */ 113 public static final int NFC_UID = 1027; 114 115 /** 116 * Defines the UID/GID for the Bluetooth service process. 117 * @hide 118 */ 119 public static final int BLUETOOTH_UID = 1002; 120 121 /** 122 * Defines the GID for the group that allows write access to the internal media storage. 123 * @hide 124 */ 125 public static final int MEDIA_RW_GID = 1023; 126 127 /** 128 * Access to installed package details 129 * @hide 130 */ 131 public static final int PACKAGE_INFO_GID = 1032; 132 133 /** 134 * Defines the start of a range of UIDs (and GIDs), going from this 135 * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning 136 * to applications. 137 */ 138 public static final int FIRST_APPLICATION_UID = 10000; 139 140 /** 141 * Last of application-specific UIDs starting at 142 * {@link #FIRST_APPLICATION_UID}. 143 */ 144 public static final int LAST_APPLICATION_UID = 19999; 145 146 /** 147 * First uid used for fully isolated sandboxed processes (with no permissions of their own) 148 * @hide 149 */ 150 public static final int FIRST_ISOLATED_UID = 99000; 151 152 /** 153 * Last uid used for fully isolated sandboxed processes (with no permissions of their own) 154 * @hide 155 */ 156 public static final int LAST_ISOLATED_UID = 99999; 157 158 /** 159 * First gid for applications to share resources. Used when forward-locking 160 * is enabled but all UserHandles need to be able to read the resources. 161 * @hide 162 */ 163 public static final int FIRST_SHARED_APPLICATION_GID = 50000; 164 165 /** 166 * Last gid for applications to share resources. Used when forward-locking 167 * is enabled but all UserHandles need to be able to read the resources. 168 * @hide 169 */ 170 public static final int LAST_SHARED_APPLICATION_GID = 59999; 171 172 /** 173 * Standard priority of application threads. 174 * Use with {@link #setThreadPriority(int)} and 175 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 176 * {@link java.lang.Thread} class. 177 */ 178 public static final int THREAD_PRIORITY_DEFAULT = 0; 179 180 /* 181 * *************************************** 182 * ** Keep in sync with utils/threads.h ** 183 * *************************************** 184 */ 185 186 /** 187 * Lowest available thread priority. Only for those who really, really 188 * don't want to run if anything else is happening. 189 * Use with {@link #setThreadPriority(int)} and 190 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 191 * {@link java.lang.Thread} class. 192 */ 193 public static final int THREAD_PRIORITY_LOWEST = 19; 194 195 /** 196 * Standard priority background threads. This gives your thread a slightly 197 * lower than normal priority, so that it will have less chance of impacting 198 * the responsiveness of the user interface. 199 * Use with {@link #setThreadPriority(int)} and 200 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 201 * {@link java.lang.Thread} class. 202 */ 203 public static final int THREAD_PRIORITY_BACKGROUND = 10; 204 205 /** 206 * Standard priority of threads that are currently running a user interface 207 * that the user is interacting with. Applications can not normally 208 * change to this priority; the system will automatically adjust your 209 * application threads as the user moves through the UI. 210 * Use with {@link #setThreadPriority(int)} and 211 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 212 * {@link java.lang.Thread} class. 213 */ 214 public static final int THREAD_PRIORITY_FOREGROUND = -2; 215 216 /** 217 * Standard priority of system display threads, involved in updating 218 * the user interface. Applications can not 219 * normally change to this priority. 220 * Use with {@link #setThreadPriority(int)} and 221 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 222 * {@link java.lang.Thread} class. 223 */ 224 public static final int THREAD_PRIORITY_DISPLAY = -4; 225 226 /** 227 * Standard priority of the most important display threads, for compositing 228 * the screen and retrieving input events. Applications can not normally 229 * change to this priority. 230 * Use with {@link #setThreadPriority(int)} and 231 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 232 * {@link java.lang.Thread} class. 233 */ 234 public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8; 235 236 /** 237 * Standard priority of audio threads. Applications can not normally 238 * change to this priority. 239 * Use with {@link #setThreadPriority(int)} and 240 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 241 * {@link java.lang.Thread} class. 242 */ 243 public static final int THREAD_PRIORITY_AUDIO = -16; 244 245 /** 246 * Standard priority of the most important audio threads. 247 * Applications can not normally change to this priority. 248 * Use with {@link #setThreadPriority(int)} and 249 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 250 * {@link java.lang.Thread} class. 251 */ 252 public static final int THREAD_PRIORITY_URGENT_AUDIO = -19; 253 254 /** 255 * Minimum increment to make a priority more favorable. 256 */ 257 public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1; 258 259 /** 260 * Minimum increment to make a priority less favorable. 261 */ 262 public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1; 263 264 /** 265 * Default scheduling policy 266 * @hide 267 */ 268 public static final int SCHED_OTHER = 0; 269 270 /** 271 * First-In First-Out scheduling policy 272 * @hide 273 */ 274 public static final int SCHED_FIFO = 1; 275 276 /** 277 * Round-Robin scheduling policy 278 * @hide 279 */ 280 public static final int SCHED_RR = 2; 281 282 /** 283 * Batch scheduling policy 284 * @hide 285 */ 286 public static final int SCHED_BATCH = 3; 287 288 /** 289 * Idle scheduling policy 290 * @hide 291 */ 292 public static final int SCHED_IDLE = 5; 293 294 // Keep in sync with SP_* constants of enum type SchedPolicy 295 // declared in system/core/include/cutils/sched_policy.h, 296 // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value. 297 298 /** 299 * Default thread group - 300 * has meaning with setProcessGroup() only, cannot be used with setThreadGroup(). 301 * When used with setProcessGroup(), the group of each thread in the process 302 * is conditionally changed based on that thread's current priority, as follows: 303 * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND 304 * are moved to foreground thread group. All other threads are left unchanged. 305 * @hide 306 */ 307 public static final int THREAD_GROUP_DEFAULT = -1; 308 309 /** 310 * Background thread group - All threads in 311 * this group are scheduled with a reduced share of the CPU. 312 * Value is same as constant SP_BACKGROUND of enum SchedPolicy. 313 * FIXME rename to THREAD_GROUP_BACKGROUND. 314 * @hide 315 */ 316 public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0; 317 318 /** 319 * Foreground thread group - All threads in 320 * this group are scheduled with a normal share of the CPU. 321 * Value is same as constant SP_FOREGROUND of enum SchedPolicy. 322 * Not used at this level. 323 * @hide 324 **/ 325 private static final int THREAD_GROUP_FOREGROUND = 1; 326 327 /** 328 * System thread group. 329 * @hide 330 **/ 331 public static final int THREAD_GROUP_SYSTEM = 2; 332 333 /** 334 * Application audio thread group. 335 * @hide 336 **/ 337 public static final int THREAD_GROUP_AUDIO_APP = 3; 338 339 /** 340 * System audio thread group. 341 * @hide 342 **/ 343 public static final int THREAD_GROUP_AUDIO_SYS = 4; 344 345 public static final int SIGNAL_QUIT = 3; 346 public static final int SIGNAL_KILL = 9; 347 public static final int SIGNAL_USR1 = 10; 348 349 // State for communicating with zygote process 350 351 static LocalSocket sZygoteSocket; 352 static DataInputStream sZygoteInputStream; 353 static BufferedWriter sZygoteWriter; 354 355 /** true if previous zygote open failed */ 356 static boolean sPreviousZygoteOpenFailed; 357 358 /** 359 * Start a new process. 360 * 361 * <p>If processes are enabled, a new process is created and the 362 * static main() function of a <var>processClass</var> is executed there. 363 * The process will continue running after this function returns. 364 * 365 * <p>If processes are not enabled, a new thread in the caller's 366 * process is created and main() of <var>processClass</var> called there. 367 * 368 * <p>The niceName parameter, if not an empty string, is a custom name to 369 * give to the process instead of using processClass. This allows you to 370 * make easily identifyable processes even if you are using the same base 371 * <var>processClass</var> to start them. 372 * 373 * @param processClass The class to use as the process's main entry 374 * point. 375 * @param niceName A more readable name to use for the process. 376 * @param uid The user-id under which the process will run. 377 * @param gid The group-id under which the process will run. 378 * @param gids Additional group-ids associated with the process. 379 * @param debugFlags Additional flags. 380 * @param targetSdkVersion The target SDK version for the app. 381 * @param seInfo null-ok SELinux information for the new process. 382 * @param zygoteArgs Additional arguments to supply to the zygote process. 383 * 384 * @return An object that describes the result of the attempt to start the process. 385 * @throws RuntimeException on fatal start failure 386 * 387 * {@hide} 388 */ 389 public static final ProcessStartResult start(final String processClass, 390 final String niceName, 391 int uid, int gid, int[] gids, 392 int debugFlags, int mountExternal, 393 int targetSdkVersion, 394 String seInfo, 395 String[] zygoteArgs) { 396 try { 397 return startViaZygote(processClass, niceName, uid, gid, gids, 398 debugFlags, mountExternal, targetSdkVersion, seInfo, zygoteArgs); 399 } catch (ZygoteStartFailedEx ex) { 400 Log.e(LOG_TAG, 401 "Starting VM process through Zygote failed"); 402 throw new RuntimeException( 403 "Starting VM process through Zygote failed", ex); 404 } 405 } 406 407 /** retry interval for opening a zygote socket */ 408 static final int ZYGOTE_RETRY_MILLIS = 500; 409 410 /** 411 * Tries to open socket to Zygote process if not already open. If 412 * already open, does nothing. May block and retry. 413 */ 414 private static void openZygoteSocketIfNeeded() 415 throws ZygoteStartFailedEx { 416 417 int retryCount; 418 419 if (sPreviousZygoteOpenFailed) { 420 /* 421 * If we've failed before, expect that we'll fail again and 422 * don't pause for retries. 423 */ 424 retryCount = 0; 425 } else { 426 retryCount = 10; 427 } 428 429 /* 430 * See bug #811181: Sometimes runtime can make it up before zygote. 431 * Really, we'd like to do something better to avoid this condition, 432 * but for now just wait a bit... 433 */ 434 for (int retry = 0 435 ; (sZygoteSocket == null) && (retry < (retryCount + 1)) 436 ; retry++ ) { 437 438 if (retry > 0) { 439 try { 440 Log.i("Zygote", "Zygote not up yet, sleeping..."); 441 Thread.sleep(ZYGOTE_RETRY_MILLIS); 442 } catch (InterruptedException ex) { 443 // should never happen 444 } 445 } 446 447 try { 448 sZygoteSocket = new LocalSocket(); 449 450 sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET, 451 LocalSocketAddress.Namespace.RESERVED)); 452 453 sZygoteInputStream 454 = new DataInputStream(sZygoteSocket.getInputStream()); 455 456 sZygoteWriter = 457 new BufferedWriter( 458 new OutputStreamWriter( 459 sZygoteSocket.getOutputStream()), 460 256); 461 462 Log.i("Zygote", "Process: zygote socket opened"); 463 464 sPreviousZygoteOpenFailed = false; 465 break; 466 } catch (IOException ex) { 467 if (sZygoteSocket != null) { 468 try { 469 sZygoteSocket.close(); 470 } catch (IOException ex2) { 471 Log.e(LOG_TAG,"I/O exception on close after exception", 472 ex2); 473 } 474 } 475 476 sZygoteSocket = null; 477 } 478 } 479 480 if (sZygoteSocket == null) { 481 sPreviousZygoteOpenFailed = true; 482 throw new ZygoteStartFailedEx("connect failed"); 483 } 484 } 485 486 /** 487 * Sends an argument list to the zygote process, which starts a new child 488 * and returns the child's pid. Please note: the present implementation 489 * replaces newlines in the argument list with spaces. 490 * @param args argument list 491 * @return An object that describes the result of the attempt to start the process. 492 * @throws ZygoteStartFailedEx if process start failed for any reason 493 */ 494 private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args) 495 throws ZygoteStartFailedEx { 496 openZygoteSocketIfNeeded(); 497 498 try { 499 /** 500 * See com.android.internal.os.ZygoteInit.readArgumentList() 501 * Presently the wire format to the zygote process is: 502 * a) a count of arguments (argc, in essence) 503 * b) a number of newline-separated argument strings equal to count 504 * 505 * After the zygote process reads these it will write the pid of 506 * the child or -1 on failure, followed by boolean to 507 * indicate whether a wrapper process was used. 508 */ 509 510 sZygoteWriter.write(Integer.toString(args.size())); 511 sZygoteWriter.newLine(); 512 513 int sz = args.size(); 514 for (int i = 0; i < sz; i++) { 515 String arg = args.get(i); 516 if (arg.indexOf('\n') >= 0) { 517 throw new ZygoteStartFailedEx( 518 "embedded newlines not allowed"); 519 } 520 sZygoteWriter.write(arg); 521 sZygoteWriter.newLine(); 522 } 523 524 sZygoteWriter.flush(); 525 526 // Should there be a timeout on this? 527 ProcessStartResult result = new ProcessStartResult(); 528 result.pid = sZygoteInputStream.readInt(); 529 if (result.pid < 0) { 530 throw new ZygoteStartFailedEx("fork() failed"); 531 } 532 result.usingWrapper = sZygoteInputStream.readBoolean(); 533 return result; 534 } catch (IOException ex) { 535 try { 536 if (sZygoteSocket != null) { 537 sZygoteSocket.close(); 538 } 539 } catch (IOException ex2) { 540 // we're going to fail anyway 541 Log.e(LOG_TAG,"I/O exception on routine close", ex2); 542 } 543 544 sZygoteSocket = null; 545 546 throw new ZygoteStartFailedEx(ex); 547 } 548 } 549 550 /** 551 * Starts a new process via the zygote mechanism. 552 * 553 * @param processClass Class name whose static main() to run 554 * @param niceName 'nice' process name to appear in ps 555 * @param uid a POSIX uid that the new process should setuid() to 556 * @param gid a POSIX gid that the new process shuold setgid() to 557 * @param gids null-ok; a list of supplementary group IDs that the 558 * new process should setgroup() to. 559 * @param debugFlags Additional flags. 560 * @param targetSdkVersion The target SDK version for the app. 561 * @param seInfo null-ok SELinux information for the new process. 562 * @param extraArgs Additional arguments to supply to the zygote process. 563 * @return An object that describes the result of the attempt to start the process. 564 * @throws ZygoteStartFailedEx if process start failed for any reason 565 */ 566 private static ProcessStartResult startViaZygote(final String processClass, 567 final String niceName, 568 final int uid, final int gid, 569 final int[] gids, 570 int debugFlags, int mountExternal, 571 int targetSdkVersion, 572 String seInfo, 573 String[] extraArgs) 574 throws ZygoteStartFailedEx { 575 synchronized(Process.class) { 576 ArrayList<String> argsForZygote = new ArrayList<String>(); 577 578 // --runtime-init, --setuid=, --setgid=, 579 // and --setgroups= must go first 580 argsForZygote.add("--runtime-init"); 581 argsForZygote.add("--setuid=" + uid); 582 argsForZygote.add("--setgid=" + gid); 583 if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) { 584 argsForZygote.add("--enable-jni-logging"); 585 } 586 if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) { 587 argsForZygote.add("--enable-safemode"); 588 } 589 if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) { 590 argsForZygote.add("--enable-debugger"); 591 } 592 if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) { 593 argsForZygote.add("--enable-checkjni"); 594 } 595 if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) { 596 argsForZygote.add("--enable-assert"); 597 } 598 if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER) { 599 argsForZygote.add("--mount-external-multiuser"); 600 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL) { 601 argsForZygote.add("--mount-external-multiuser-all"); 602 } 603 argsForZygote.add("--target-sdk-version=" + targetSdkVersion); 604 605 //TODO optionally enable debuger 606 //argsForZygote.add("--enable-debugger"); 607 608 // --setgroups is a comma-separated list 609 if (gids != null && gids.length > 0) { 610 StringBuilder sb = new StringBuilder(); 611 sb.append("--setgroups="); 612 613 int sz = gids.length; 614 for (int i = 0; i < sz; i++) { 615 if (i != 0) { 616 sb.append(','); 617 } 618 sb.append(gids[i]); 619 } 620 621 argsForZygote.add(sb.toString()); 622 } 623 624 if (niceName != null) { 625 argsForZygote.add("--nice-name=" + niceName); 626 } 627 628 if (seInfo != null) { 629 argsForZygote.add("--seinfo=" + seInfo); 630 } 631 632 argsForZygote.add(processClass); 633 634 if (extraArgs != null) { 635 for (String arg : extraArgs) { 636 argsForZygote.add(arg); 637 } 638 } 639 640 return zygoteSendArgsAndGetResult(argsForZygote); 641 } 642 } 643 644 /** 645 * Returns elapsed milliseconds of the time this process has run. 646 * @return Returns the number of milliseconds this process has return. 647 */ 648 public static final native long getElapsedCpuTime(); 649 650 /** 651 * Returns the identifier of this process, which can be used with 652 * {@link #killProcess} and {@link #sendSignal}. 653 */ 654 public static final int myPid() { 655 return Libcore.os.getpid(); 656 } 657 658 /** 659 * Returns the identifier of this process' parent. 660 * @hide 661 */ 662 public static final int myPpid() { 663 return Libcore.os.getppid(); 664 } 665 666 /** 667 * Returns the identifier of the calling thread, which be used with 668 * {@link #setThreadPriority(int, int)}. 669 */ 670 public static final int myTid() { 671 return Libcore.os.gettid(); 672 } 673 674 /** 675 * Returns the identifier of this process's uid. This is the kernel uid 676 * that the process is running under, which is the identity of its 677 * app-specific sandbox. It is different from {@link #myUserHandle} in that 678 * a uid identifies a specific app sandbox in a specific user. 679 */ 680 public static final int myUid() { 681 return Libcore.os.getuid(); 682 } 683 684 /** 685 * Returns this process's user handle. This is the 686 * user the process is running under. It is distinct from 687 * {@link #myUid()} in that a particular user will have multiple 688 * distinct apps running under it each with their own uid. 689 */ 690 public static final UserHandle myUserHandle() { 691 return new UserHandle(UserHandle.getUserId(myUid())); 692 } 693 694 /** 695 * Returns whether the current process is in an isolated sandbox. 696 * @hide 697 */ 698 public static final boolean isIsolated() { 699 int uid = UserHandle.getAppId(myUid()); 700 return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID; 701 } 702 703 /** 704 * Returns the UID assigned to a particular user name, or -1 if there is 705 * none. If the given string consists of only numbers, it is converted 706 * directly to a uid. 707 */ 708 public static final native int getUidForName(String name); 709 710 /** 711 * Returns the GID assigned to a particular user name, or -1 if there is 712 * none. If the given string consists of only numbers, it is converted 713 * directly to a gid. 714 */ 715 public static final native int getGidForName(String name); 716 717 /** 718 * Returns a uid for a currently running process. 719 * @param pid the process id 720 * @return the uid of the process, or -1 if the process is not running. 721 * @hide pending API council review 722 */ 723 public static final int getUidForPid(int pid) { 724 String[] procStatusLabels = { "Uid:" }; 725 long[] procStatusValues = new long[1]; 726 procStatusValues[0] = -1; 727 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues); 728 return (int) procStatusValues[0]; 729 } 730 731 /** 732 * Returns the parent process id for a currently running process. 733 * @param pid the process id 734 * @return the parent process id of the process, or -1 if the process is not running. 735 * @hide 736 */ 737 public static final int getParentPid(int pid) { 738 String[] procStatusLabels = { "PPid:" }; 739 long[] procStatusValues = new long[1]; 740 procStatusValues[0] = -1; 741 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues); 742 return (int) procStatusValues[0]; 743 } 744 745 /** 746 * Returns the thread group leader id for a currently running thread. 747 * @param tid the thread id 748 * @return the thread group leader id of the thread, or -1 if the thread is not running. 749 * This is same as what getpid(2) would return if called by tid. 750 * @hide 751 */ 752 public static final int getThreadGroupLeader(int tid) { 753 String[] procStatusLabels = { "Tgid:" }; 754 long[] procStatusValues = new long[1]; 755 procStatusValues[0] = -1; 756 Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues); 757 return (int) procStatusValues[0]; 758 } 759 760 /** 761 * Set the priority of a thread, based on Linux priorities. 762 * 763 * @param tid The identifier of the thread/process to change. 764 * @param priority A Linux priority level, from -20 for highest scheduling 765 * priority to 19 for lowest scheduling priority. 766 * 767 * @throws IllegalArgumentException Throws IllegalArgumentException if 768 * <var>tid</var> does not exist. 769 * @throws SecurityException Throws SecurityException if your process does 770 * not have permission to modify the given thread, or to use the given 771 * priority. 772 */ 773 public static final native void setThreadPriority(int tid, int priority) 774 throws IllegalArgumentException, SecurityException; 775 776 /** 777 * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to 778 * throw an exception if passed a background-level thread priority. This is only 779 * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1. 780 * 781 * @hide 782 */ 783 public static final native void setCanSelfBackground(boolean backgroundOk); 784 785 /** 786 * Sets the scheduling group for a thread. 787 * @hide 788 * @param tid The identifier of the thread to change. 789 * @param group The target group for this thread from THREAD_GROUP_*. 790 * 791 * @throws IllegalArgumentException Throws IllegalArgumentException if 792 * <var>tid</var> does not exist. 793 * @throws SecurityException Throws SecurityException if your process does 794 * not have permission to modify the given thread, or to use the given 795 * priority. 796 * If the thread is a thread group leader, that is it's gettid() == getpid(), 797 * then the other threads in the same thread group are _not_ affected. 798 */ 799 public static final native void setThreadGroup(int tid, int group) 800 throws IllegalArgumentException, SecurityException; 801 802 /** 803 * Sets the scheduling group for a process and all child threads 804 * @hide 805 * @param pid The identifier of the process to change. 806 * @param group The target group for this process from THREAD_GROUP_*. 807 * 808 * @throws IllegalArgumentException Throws IllegalArgumentException if 809 * <var>tid</var> does not exist. 810 * @throws SecurityException Throws SecurityException if your process does 811 * not have permission to modify the given thread, or to use the given 812 * priority. 813 * 814 * group == THREAD_GROUP_DEFAULT means to move all non-background priority 815 * threads to the foreground scheduling group, but to leave background 816 * priority threads alone. group == THREAD_GROUP_BG_NONINTERACTIVE moves all 817 * threads, regardless of priority, to the background scheduling group. 818 * group == THREAD_GROUP_FOREGROUND is not allowed. 819 */ 820 public static final native void setProcessGroup(int pid, int group) 821 throws IllegalArgumentException, SecurityException; 822 823 /** 824 * Return the scheduling group of requested process. 825 * 826 * @hide 827 */ 828 public static final native int getProcessGroup(int pid) 829 throws IllegalArgumentException, SecurityException; 830 831 /** 832 * Set the priority of the calling thread, based on Linux priorities. See 833 * {@link #setThreadPriority(int, int)} for more information. 834 * 835 * @param priority A Linux priority level, from -20 for highest scheduling 836 * priority to 19 for lowest scheduling priority. 837 * 838 * @throws IllegalArgumentException Throws IllegalArgumentException if 839 * <var>tid</var> does not exist. 840 * @throws SecurityException Throws SecurityException if your process does 841 * not have permission to modify the given thread, or to use the given 842 * priority. 843 * 844 * @see #setThreadPriority(int, int) 845 */ 846 public static final native void setThreadPriority(int priority) 847 throws IllegalArgumentException, SecurityException; 848 849 /** 850 * Return the current priority of a thread, based on Linux priorities. 851 * 852 * @param tid The identifier of the thread/process to change. 853 * 854 * @return Returns the current priority, as a Linux priority level, 855 * from -20 for highest scheduling priority to 19 for lowest scheduling 856 * priority. 857 * 858 * @throws IllegalArgumentException Throws IllegalArgumentException if 859 * <var>tid</var> does not exist. 860 */ 861 public static final native int getThreadPriority(int tid) 862 throws IllegalArgumentException; 863 864 /** 865 * Set the scheduling policy and priority of a thread, based on Linux. 866 * 867 * @param tid The identifier of the thread/process to change. 868 * @param policy A Linux scheduling policy such as SCHED_OTHER etc. 869 * @param priority A Linux priority level in a range appropriate for the given policy. 870 * 871 * @throws IllegalArgumentException Throws IllegalArgumentException if 872 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy. 873 * @throws SecurityException Throws SecurityException if your process does 874 * not have permission to modify the given thread, or to use the given 875 * scheduling policy or priority. 876 * 877 * {@hide} 878 */ 879 public static final native void setThreadScheduler(int tid, int policy, int priority) 880 throws IllegalArgumentException; 881 882 /** 883 * Determine whether the current environment supports multiple processes. 884 * 885 * @return Returns true if the system can run in multiple processes, else 886 * false if everything is running in a single process. 887 * 888 * @deprecated This method always returns true. Do not use. 889 */ 890 @Deprecated 891 public static final boolean supportsProcesses() { 892 return true; 893 } 894 895 /** 896 * Set the out-of-memory badness adjustment for a process. 897 * 898 * @param pid The process identifier to set. 899 * @param amt Adjustment value -- linux allows -16 to +15. 900 * 901 * @return Returns true if the underlying system supports this 902 * feature, else false. 903 * 904 * {@hide} 905 */ 906 public static final native boolean setOomAdj(int pid, int amt); 907 908 /** 909 * Adjust the swappiness level for a process. 910 * 911 * @param pid The process identifier to set. 912 * @param is_increased Whether swappiness should be increased or default. 913 * 914 * @return Returns true if the underlying system supports this 915 * feature, else false. 916 * 917 * {@hide} 918 */ 919 public static final native boolean setSwappiness(int pid, boolean is_increased); 920 921 /** 922 * Change this process's argv[0] parameter. This can be useful to show 923 * more descriptive information in things like the 'ps' command. 924 * 925 * @param text The new name of this process. 926 * 927 * {@hide} 928 */ 929 public static final native void setArgV0(String text); 930 931 /** 932 * Kill the process with the given PID. 933 * Note that, though this API allows us to request to 934 * kill any process based on its PID, the kernel will 935 * still impose standard restrictions on which PIDs you 936 * are actually able to kill. Typically this means only 937 * the process running the caller's packages/application 938 * and any additional processes created by that app; packages 939 * sharing a common UID will also be able to kill each 940 * other's processes. 941 */ 942 public static final void killProcess(int pid) { 943 sendSignal(pid, SIGNAL_KILL); 944 } 945 946 /** @hide */ 947 public static final native int setUid(int uid); 948 949 /** @hide */ 950 public static final native int setGid(int uid); 951 952 /** 953 * Send a signal to the given process. 954 * 955 * @param pid The pid of the target process. 956 * @param signal The signal to send. 957 */ 958 public static final native void sendSignal(int pid, int signal); 959 960 /** 961 * @hide 962 * Private impl for avoiding a log message... DO NOT USE without doing 963 * your own log, or the Android Illuminati will find you some night and 964 * beat you up. 965 */ 966 public static final void killProcessQuiet(int pid) { 967 sendSignalQuiet(pid, SIGNAL_KILL); 968 } 969 970 /** 971 * @hide 972 * Private impl for avoiding a log message... DO NOT USE without doing 973 * your own log, or the Android Illuminati will find you some night and 974 * beat you up. 975 */ 976 public static final native void sendSignalQuiet(int pid, int signal); 977 978 /** @hide */ 979 public static final native long getFreeMemory(); 980 981 /** @hide */ 982 public static final native long getTotalMemory(); 983 984 /** @hide */ 985 public static final native void readProcLines(String path, 986 String[] reqFields, long[] outSizes); 987 988 /** @hide */ 989 public static final native int[] getPids(String path, int[] lastArray); 990 991 /** @hide */ 992 public static final int PROC_TERM_MASK = 0xff; 993 /** @hide */ 994 public static final int PROC_ZERO_TERM = 0; 995 /** @hide */ 996 public static final int PROC_SPACE_TERM = (int)' '; 997 /** @hide */ 998 public static final int PROC_TAB_TERM = (int)'\t'; 999 /** @hide */ 1000 public static final int PROC_COMBINE = 0x100; 1001 /** @hide */ 1002 public static final int PROC_PARENS = 0x200; 1003 /** @hide */ 1004 public static final int PROC_QUOTES = 0x400; 1005 /** @hide */ 1006 public static final int PROC_OUT_STRING = 0x1000; 1007 /** @hide */ 1008 public static final int PROC_OUT_LONG = 0x2000; 1009 /** @hide */ 1010 public static final int PROC_OUT_FLOAT = 0x4000; 1011 1012 /** @hide */ 1013 public static final native boolean readProcFile(String file, int[] format, 1014 String[] outStrings, long[] outLongs, float[] outFloats); 1015 1016 /** @hide */ 1017 public static final native boolean parseProcLine(byte[] buffer, int startIndex, 1018 int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats); 1019 1020 /** @hide */ 1021 public static final native int[] getPidsForCommands(String[] cmds); 1022 1023 /** 1024 * Gets the total Pss value for a given process, in bytes. 1025 * 1026 * @param pid the process to the Pss for 1027 * @return the total Pss value for the given process in bytes, 1028 * or -1 if the value cannot be determined 1029 * @hide 1030 */ 1031 public static final native long getPss(int pid); 1032 1033 /** 1034 * Specifies the outcome of having started a process. 1035 * @hide 1036 */ 1037 public static final class ProcessStartResult { 1038 /** 1039 * The PID of the newly started process. 1040 * Always >= 0. (If the start failed, an exception will have been thrown instead.) 1041 */ 1042 public int pid; 1043 1044 /** 1045 * True if the process was started with a wrapper attached. 1046 */ 1047 public boolean usingWrapper; 1048 } 1049} 1050