1 // Copyright (c) 2008 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "base/process.h" 6 7 #include <errno.h> 8 #include <sys/resource.h> 9 10 #include "base/logging.h" 11 12 namespace base { 13 14 const int kPriorityAdjustment = 5; 15 IsProcessBackgrounded() const16bool Process::IsProcessBackgrounded() const { 17 DCHECK(process_); 18 return saved_priority_ == kUnsetProcessPriority; 19 } 20 SetProcessBackgrounded(bool background)21bool Process::SetProcessBackgrounded(bool background) { 22 DCHECK(process_); 23 24 if (background) { 25 // We won't be able to raise the priority if we don't have the right rlimit. 26 // The limit may be adjusted in /etc/security/limits.conf for PAM systems. 27 struct rlimit rlim; 28 if (getrlimit(RLIMIT_NICE, &rlim) != 0) { 29 // Call to getrlimit failed, don't background. 30 return false; 31 } 32 errno = 0; 33 int current_priority = GetPriority(); 34 if (errno) { 35 // Couldn't get priority. 36 return false; 37 } 38 // {set,get}priority values are in the range -20 to 19, where -1 is higher 39 // priority than 0. But rlimit's are in the range from 0 to 39 where 40 // 1 is higher than 0. 41 if ((20 - current_priority) > static_cast<int>(rlim.rlim_cur)) { 42 // User is not allowed to raise the priority back to where it is now. 43 return false; 44 } 45 int result = 46 setpriority( 47 PRIO_PROCESS, process_, current_priority + kPriorityAdjustment); 48 if (result == -1) { 49 LOG(ERROR) << "Failed to lower priority, errno: " << errno; 50 return false; 51 } 52 saved_priority_ = current_priority; 53 return true; 54 } else { 55 if (saved_priority_ == kUnsetProcessPriority) { 56 // Can't restore if we were never backgrounded. 57 return false; 58 } 59 int result = setpriority(PRIO_PROCESS, process_, saved_priority_); 60 // If we can't restore something has gone terribly wrong. 61 DPCHECK(result == 0); 62 saved_priority_ = kUnsetProcessPriority; 63 return true; 64 } 65 } 66 67 } // namespace base 68