Ninja
browse.cc
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "browse.h"
16 
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 
21 #include "../build/browse_py.h"
22 
23 void RunBrowsePython(State* state, const char* ninja_command,
24  const char* initial_target) {
25  // Fork off a Python process and have it run our code via its stdin.
26  // (Actually the Python process becomes the parent.)
27  int pipefd[2];
28  if (pipe(pipefd) < 0) {
29  perror("ninja: pipe");
30  return;
31  }
32 
33  pid_t pid = fork();
34  if (pid < 0) {
35  perror("ninja: fork");
36  return;
37  }
38 
39  if (pid > 0) { // Parent.
40  close(pipefd[1]);
41  do {
42  if (dup2(pipefd[0], 0) < 0) {
43  perror("ninja: dup2");
44  break;
45  }
46 
47  // exec Python, telling it to run the program from stdin.
48  const char* command[] = {
49  NINJA_PYTHON, "-", ninja_command, initial_target, NULL
50  };
51  execvp(command[0], (char**)command);
52  perror("ninja: execvp");
53  } while (false);
54  _exit(1);
55  } else { // Child.
56  close(pipefd[0]);
57 
58  // Write the script file into the stdin of the Python process.
59  ssize_t len = write(pipefd[1], kBrowsePy, sizeof(kBrowsePy));
60  if (len < (ssize_t)sizeof(kBrowsePy))
61  perror("ninja: write");
62  close(pipefd[1]);
63  exit(0);
64  }
65 }
void RunBrowsePython(State *state, const char *ninja_command, const char *initial_target)
Run in "browse" mode, which execs a Python webserver.
Definition: browse.cc:23
Global state (file status, loaded rules) for a single run.
Definition: state.h:83