OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2011 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 "chrome/browser/mac/launchd.h" |
| 6 |
| 7 #include <launch.h> |
| 8 #include <signal.h> |
| 9 |
| 10 #include "base/logging.h" |
| 11 #include "chrome/browser/mac/scoped_launch_data.h" |
| 12 |
| 13 namespace launchd { |
| 14 |
| 15 namespace { |
| 16 |
| 17 // MessageForJob sends a single message to launchd with a simple dictionary |
| 18 // mapping |operation| to |job_label|, and returns the result of calling |
| 19 // launch_msg to send that message. On failure, returns NULL. The caller |
| 20 // assumes ownership of the returned launch_data_t object. |
| 21 launch_data_t MessageForJob(const std::string& job_label, |
| 22 const char* operation) { |
| 23 // launch_data_alloc returns something that needs to be freed. |
| 24 ScopedLaunchData message(launch_data_alloc(LAUNCH_DATA_DICTIONARY)); |
| 25 if (!message) { |
| 26 LOG(ERROR) << "launch_data_alloc"; |
| 27 return NULL; |
| 28 } |
| 29 |
| 30 // launch_data_new_string returns something that needs to be freed, but |
| 31 // the dictionary will assume ownership when launch_data_dict_insert is |
| 32 // called, so put it in a scoper and .release() it when given to the |
| 33 // dictionary. |
| 34 ScopedLaunchData job_label_launchd(launch_data_new_string(job_label.c_str())); |
| 35 if (!job_label_launchd) { |
| 36 LOG(ERROR) << "launch_data_new_string"; |
| 37 return NULL; |
| 38 } |
| 39 |
| 40 if (!launch_data_dict_insert(message, |
| 41 job_label_launchd.release(), |
| 42 operation)) { |
| 43 return NULL; |
| 44 } |
| 45 |
| 46 return launch_msg(message); |
| 47 } |
| 48 |
| 49 // Returns the process ID for |job_label|, or -1 on error. |
| 50 pid_t PIDForJob(const std::string& job_label) { |
| 51 ScopedLaunchData response(MessageForJob(job_label, LAUNCH_KEY_GETJOB)); |
| 52 if (!response) { |
| 53 return -1; |
| 54 } |
| 55 |
| 56 if (launch_data_get_type(response) != LAUNCH_DATA_DICTIONARY) { |
| 57 LOG(ERROR) << "PIDForJob: expected dictionary"; |
| 58 return -1; |
| 59 } |
| 60 |
| 61 launch_data_t pid_data = launch_data_dict_lookup(response, |
| 62 LAUNCH_JOBKEY_PID); |
| 63 if (!pid_data) { |
| 64 LOG(ERROR) << "PIDForJob: no pid"; |
| 65 return -1; |
| 66 } |
| 67 |
| 68 if (launch_data_get_type(pid_data) != LAUNCH_DATA_INTEGER) { |
| 69 LOG(ERROR) << "PIDForJob: expected integer"; |
| 70 return -1; |
| 71 } |
| 72 |
| 73 return launch_data_get_integer(pid_data); |
| 74 } |
| 75 |
| 76 } // namespace |
| 77 |
| 78 void SignalJob(const std::string& job_name, int signal) { |
| 79 pid_t pid = PIDForJob(job_name); |
| 80 if (pid <= 0) { |
| 81 return; |
| 82 } |
| 83 |
| 84 kill(pid, signal); |
| 85 } |
| 86 |
| 87 } // namespace launchd |
OLD | NEW |