blob: 9a686e5a46e7d347f23747c30d60963a7bb29357 [file] [log] [blame]
Shinichiro Hamaji1d545aa2015-06-23 15:29:13 +09001// Copyright 2015 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
Fumitoshi Ukai744bb2b2015-06-25 00:10:52 +090015// +build ignore
16
Shinichiro Hamaji776ca302015-06-06 03:52:48 +090017#include "fileutil.h"
18
19#include <errno.h>
20#include <limits.h>
21#include <sys/stat.h>
Shinichiro Hamaji94d6f2a2015-07-05 05:32:25 +090022#include <sys/types.h>
23#include <sys/wait.h>
Shinichiro Hamaji776ca302015-06-06 03:52:48 +090024#include <unistd.h>
25
26#include "log.h"
27
28bool Exists(StringPiece filename) {
29 CHECK(filename.size() < PATH_MAX);
Shinichiro Hamaji776ca302015-06-06 03:52:48 +090030 struct stat st;
Shinichiro Hamajifda79432015-07-05 03:17:34 +090031 if (stat(filename.as_string().c_str(), &st) < 0) {
Shinichiro Hamaji776ca302015-06-06 03:52:48 +090032 return false;
33 }
34 return true;
35}
Shinichiro Hamajifda79432015-07-05 03:17:34 +090036
37double GetTimestamp(StringPiece filename) {
38 CHECK(filename.size() < PATH_MAX);
39 struct stat st;
40 if (stat(filename.as_string().c_str(), &st) < 0) {
41 return -2.0;
42 }
43 return st.st_mtime;
44}
Shinichiro Hamaji94d6f2a2015-07-05 05:32:25 +090045
46int RunCommand(const string& shell, const string& cmd, bool redirect_stderr,
47 string* s) {
48 int pipefd[2];
49 if (pipe(pipefd) != 0)
50 PERROR("pipe failed");
51 int pid;
52 if ((pid = vfork())) {
53 int status;
54 close(pipefd[1]);
55 while (true) {
56 int result = waitpid(pid, &status, WNOHANG);
57 if (result < 0)
58 PERROR("waitpid failed");
59
60 while (true) {
61 char buf[4096];
62 ssize_t r = read(pipefd[0], buf, 4096);
63 if (r < 0)
64 PERROR("read failed");
65 if (r == 0)
66 break;
67 s->append(buf, buf+r);
68 }
69
70 if (result != 0) {
71 break;
72 }
73 }
74 close(pipefd[0]);
75
76 return status;
77 } else {
78 close(pipefd[0]);
79 if (redirect_stderr) {
80 if (dup2(pipefd[1], 2) < 0)
81 PERROR("dup2 failed");
82 }
83 if (dup2(pipefd[1], 1) < 0)
84 PERROR("dup2 failed");
85 close(pipefd[1]);
86
87 const char* argv[] = {
88 shell.c_str(), "-c", cmd.c_str(), NULL
89 };
90 execvp(argv[0], const_cast<char**>(argv));
91 }
92 abort();
93}