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