MCPcopy Create free account
hub / github.com/apache/brpc / read_proc_status

Function read_proc_status

src/bvar/default_variables.cpp:76–132  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

74};
75
76static bool read_proc_status(ProcStat &stat) {
77 stat = ProcStat();
78 errno = 0;
79#if defined(OS_LINUX)
80 // Read status from /proc/self/stat. Information from `man proc' is out of date,
81 // see http://man7.org/linux/man-pages/man5/proc.5.html
82 butil::ScopedFILE fp("/proc/self/stat", "r");
83 if (NULL == fp) {
84 static bool ever_printed_stat_err = false;
85 if (!ever_printed_stat_err) {
86 fprintf(stderr, "WARNING: Fail to open /proc/self/stat, errno=%d. "
87 "Process status related bvars will be unavailable.\n", errno);
88 ever_printed_stat_err = true;
89 }
90 return false;
91 }
92 if (fscanf(fp, "%d %*s %c "
93 "%d %d %d %d %d "
94 "%u %lu %lu %lu "
95 "%lu %lu %lu %lu %lu "
96 "%ld %ld %ld",
97 &stat.pid, &stat.state,
98 &stat.ppid, &stat.pgrp, &stat.session, &stat.tty_nr, &stat.tpgid,
99 &stat.flags, &stat.minflt, &stat.cminflt, &stat.majflt,
100 &stat.cmajflt, &stat.utime, &stat.stime, &stat.cutime, &stat.cstime,
101 &stat.priority, &stat.nice, &stat.num_threads) != 19) {
102 fprintf(stderr, "WARNING: Fail to fscanf /proc/self/stat, errno=%d. "
103 "Process status related bvars will be unavailable.\n", errno);
104 return false;
105 }
106 return true;
107#elif defined(OS_MACOSX)
108 // TODO(zhujiashun): get remaining state in MacOS.
109 memset(&stat, 0, sizeof(stat));
110 static pid_t pid = getpid();
111 std::ostringstream oss;
112 char cmdbuf[128];
113 snprintf(cmdbuf, sizeof(cmdbuf),
114 "ps -p %ld -o pid,ppid,pgid,sess"
115 ",tpgid,flags,pri,nice | tail -n1", (long)pid);
116 if (butil::read_command_output(oss, cmdbuf) != 0) {
117 LOG(ERROR) << "Fail to read stat";
118 return false;
119 }
120 const std::string& result = oss.str();
121 if (sscanf(result.c_str(), "%d %d %d %d"
122 "%d %u %ld %ld",
123 &stat.pid, &stat.ppid, &stat.pgrp, &stat.session,
124 &stat.tpgid, &stat.flags, &stat.priority, &stat.nice) != 8) {
125 PLOG(WARNING) << "Fail to sscanf";
126 return false;
127 }
128 return true;
129#else
130 return false;
131#endif
132}
133

Callers 1

operator()Method · 0.85

Calls 4

ProcStatClass · 0.85
snprintfFunction · 0.85
read_command_outputFunction · 0.85
c_strMethod · 0.45

Tested by

no test coverage detected