-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
500 lines (426 loc) · 14.8 KB
/
Copy pathmain.cpp
File metadata and controls
500 lines (426 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <libproc.h>
#include <map>
#include <print>
#include <sstream>
#include <string>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <thread>
#include <unistd.h>
#include <vector>
// ANSI color codes
const std::string COLOR_RESET = "\033[0m";
const std::string COLOR_BLUE = "\033[34m";
const std::string COLOR_GREEN = "\033[32m";
const std::string COLOR_YELLOW = "\033[33m";
const std::string COLOR_CYAN = "\033[36m";
const std::string COLOR_MAGENTA = "\033[35m";
const std::string COLOR_BOLD = "\033[1m";
const std::string COLOR_DIM = "\033[2m";
struct FileInfo {
std::string path;
off_t size;
off_t position;
int fd;
std::chrono::steady_clock::time_point lastUpdate;
off_t lastPosition;
double speed; // bytes per second
};
struct ProcessInfo {
pid_t pid;
std::string name;
std::string path;
};
bool containsAlpha(const std::string &str) {
return std::any_of(str.begin(), str.end(),
[](char c) { return std::isalpha(c); });
}
std::vector<ProcessInfo> findProcessesByName(const std::string &searchTerm) {
std::vector<ProcessInfo> matchingProcesses;
// Get list of all processes
int numPids = proc_listpids(PROC_ALL_PIDS, 0, nullptr, 0);
if (numPids <= 0)
return matchingProcesses;
std::vector<pid_t> pids(numPids);
int actualSize =
proc_listpids(PROC_ALL_PIDS, 0, pids.data(), numPids * sizeof(pid_t));
if (actualSize <= 0)
return matchingProcesses;
int actualNumPids = actualSize / sizeof(pid_t);
for (int i = 0; i < actualNumPids; ++i) {
if (pids[i] <= 0)
continue;
char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
int pathLen = proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
if (pathLen > 0) {
std::string fullPath(pathBuffer);
std::string processName = fullPath.substr(fullPath.find_last_of('/') + 1);
// Case-insensitive search
std::string lowerProcessName = processName;
std::string lowerSearchTerm = searchTerm;
std::transform(lowerProcessName.begin(), lowerProcessName.end(),
lowerProcessName.begin(), ::tolower);
std::transform(lowerSearchTerm.begin(), lowerSearchTerm.end(),
lowerSearchTerm.begin(), ::tolower);
if (lowerProcessName.find(lowerSearchTerm) != std::string::npos) {
ProcessInfo procInfo;
procInfo.pid = pids[i];
procInfo.name = processName;
procInfo.path = fullPath;
matchingProcesses.push_back(procInfo);
}
}
}
return matchingProcesses;
}
std::string formatBytes(uint64_t bytes) {
const char *units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
const int numUnits = sizeof(units) / sizeof(units[0]);
if (bytes == 0)
return "0 B";
int unitIndex = 0;
double size = static_cast<double>(bytes);
while (size >= 1024.0 && unitIndex < numUnits - 1) {
size /= 1024.0;
unitIndex++;
}
std::ostringstream oss;
if (unitIndex == 0) {
oss << static_cast<uint64_t>(size) << " " << units[unitIndex];
} else {
oss << std::fixed << std::setprecision(1) << size << " "
<< units[unitIndex];
}
return oss.str();
}
std::string formatTime(double seconds) {
if (seconds < 0 || std::isinf(seconds) || std::isnan(seconds)) {
return "--:--";
}
int hours = static_cast<int>(seconds) / 3600;
int minutes = (static_cast<int>(seconds) % 3600) / 60;
int secs = static_cast<int>(seconds) % 60;
if (hours > 0) {
return std::to_string(hours) + "h " + std::to_string(minutes) + "m";
} else if (minutes > 0) {
return std::to_string(minutes) + "m " + std::to_string(secs) + "s";
} else {
return std::to_string(secs) + "s";
}
}
int getTerminalWidth() {
struct winsize w;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) {
return w.ws_col;
}
return 80; // Default fallback width
}
std::string getProgressBarColor(double progress) {
if (progress < 0.3)
return COLOR_YELLOW;
if (progress < 0.7)
return COLOR_BLUE;
return COLOR_GREEN;
}
void printProgressBar(const FileInfo &fileInfo) {
int terminalWidth = getTerminalWidth();
// Calculate space needed for non-progress-bar elements
std::string filename =
fileInfo.path.substr(fileInfo.path.find_last_of('/') + 1);
if (filename.length() > 25) {
filename = filename.substr(0, 22) + "...";
}
// Estimate space for: filename(25) + " [" + "] " + percentage(7) + " (" +
// sizes + ") | " + speed + " | ETA: " + eta
int fixedWidth = 25 + 2 + 2 + 7 + 3 + 20 + 3 + 15 + 8 + 10; // Rough estimate
int progressBarWidth = std::max(
20, terminalWidth - fixedWidth); // Minimum 20 chars for progress bar
progressBarWidth =
std::min(progressBarWidth, 60); // Maximum 60 chars to keep it reasonable
if (fileInfo.size <= 0) {
std::cout << filename << ": [Unknown size]" << std::endl;
return;
}
double progress = static_cast<double>(fileInfo.position) / fileInfo.size;
int filled = static_cast<int>(progress * progressBarWidth);
std::print("{}{:<25}{} [", COLOR_CYAN, filename, COLOR_RESET);
std::string barColor = getProgressBarColor(progress);
std::print("{}", barColor);
for (int i = 0; i < progressBarWidth; ++i) {
std::print("{}", (i < filled) ? "█" : "░");
}
std::print("{}", COLOR_RESET);
std::print("] {}{:>6.1f}%{} ({}{}/{}{})", COLOR_BOLD, progress * 100,
COLOR_RESET, COLOR_MAGENTA, formatBytes(fileInfo.position),
formatBytes(fileInfo.size), COLOR_RESET);
// Show speed and ETA
if (fileInfo.speed > 0) {
std::print("{} │ {}{}/s{}", COLOR_DIM, COLOR_GREEN,
formatBytes(static_cast<uint64_t>(fileInfo.speed)), COLOR_RESET);
double remainingBytes = fileInfo.size - fileInfo.position;
double eta = remainingBytes / fileInfo.speed;
std::print("{} │ {}ETA: {}{}{}", COLOR_DIM, COLOR_RESET, COLOR_YELLOW,
formatTime(eta), COLOR_RESET);
} else {
std::print("{} │ {}--/s{} │ {}ETA: --:--", COLOR_DIM, COLOR_RESET,
COLOR_DIM, COLOR_RESET);
}
std::println("");
}
std::string getProcessCommand(pid_t pid) {
#ifdef __APPLE__
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
char command[1024];
int ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
if (ret > 0) {
FILE *pipe =
popen(("ps -p " + std::to_string(pid) + " -o command=").c_str(), "r");
if (pipe) {
if (fgets(command, sizeof(command), pipe) != nullptr) {
command[strcspn(command, "\n")] = 0;
pclose(pipe);
return std::string(command);
}
pclose(pipe);
}
}
return "";
#else
std::string cmdPath = "/proc/" + std::to_string(pid) + "/cmdline";
std::ifstream cmdFile(cmdPath);
std::string cmd;
if (cmdFile.is_open()) {
std::getline(cmdFile, cmd);
cmdFile.close();
return cmd;
}
return "";
#endif
}
std::vector<FileInfo> getOpenFiles(pid_t pid) {
std::vector<FileInfo> files;
// Get file descriptor info
int bufferSize = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nullptr, 0);
if (bufferSize <= 0)
return files;
std::vector<proc_fdinfo> fdInfos(bufferSize / sizeof(proc_fdinfo));
int actualSize =
proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fdInfos.data(), bufferSize);
if (actualSize <= 0)
return files;
int numFds = actualSize / sizeof(proc_fdinfo);
for (int i = 0; i < numFds; ++i) {
if (fdInfos[i].proc_fdtype == PROX_FDTYPE_VNODE) {
vnode_fdinfowithpath vnodeInfo;
int result =
proc_pidfdinfo(pid, fdInfos[i].proc_fd, PROC_PIDFDVNODEPATHINFO,
&vnodeInfo, sizeof(vnodeInfo));
if (result == sizeof(vnodeInfo)) {
FileInfo fileInfo;
fileInfo.path = vnodeInfo.pvip.vip_path;
fileInfo.fd = fdInfos[i].proc_fd;
fileInfo.position = vnodeInfo.pfi.fi_offset;
// Get file size using stat
struct stat fileStat;
if (stat(fileInfo.path.c_str(), &fileStat) == 0) {
fileInfo.size = fileStat.st_size;
} else {
fileInfo.size = 0;
}
// Only include regular files that are readable
if (!fileInfo.path.empty() && fileInfo.size > 0 &&
S_ISREG(fileStat.st_mode)) {
// Initialize timing info
fileInfo.lastUpdate = std::chrono::steady_clock::now();
fileInfo.lastPosition = fileInfo.position;
fileInfo.speed = 0.0;
files.push_back(fileInfo);
}
}
}
}
return files;
}
bool hasShownFiles = false;
void showProgress(const std::vector<pid_t> &pids, int intervalMs = 1000) {
std::print("\033[2J\033[H"); // Clear screen and move cursor to top
std::println("{}{}{} for {}{} process(es){}", COLOR_BOLD,
"File Progress Monitor", COLOR_RESET, COLOR_CYAN, pids.size(),
COLOR_RESET);
std::println("{}{}{}", COLOR_DIM, "Press Ctrl+C to exit\n", COLOR_RESET);
std::map<pid_t, std::map<std::string, FileInfo>> previousFiles;
while (true) {
std::map<pid_t, std::vector<FileInfo>> allFiles;
auto currentTime = std::chrono::steady_clock::now();
// Collect files from all processes
for (pid_t pid : pids) {
allFiles[pid] = getOpenFiles(pid);
}
// Calculate speed and display progress for each process
std::print("\033[3;1H"); // Move cursor to line 3
bool hasFiles = false;
for (const auto &[pid, files] : allFiles) {
if (!files.empty()) {
hasFiles = true;
hasShownFiles = true;
std::string cmd = getProcessCommand(pid);
std::println("[PID {}{}{}{}] {}{}{}", COLOR_BOLD, COLOR_CYAN, pid,
COLOR_RESET, COLOR_DIM, cmd, COLOR_RESET);
// Top border
std::println("+{}{}+{}", COLOR_DIM,
std::string(std::min(118, getTerminalWidth() - 2), '-'),
COLOR_RESET);
for (auto file : files) {
auto &prevFiles = previousFiles[pid];
auto it = prevFiles.find(file.path);
if (it != prevFiles.end()) {
auto timeDiff =
std::chrono::duration_cast<std::chrono::milliseconds>(
currentTime - it->second.lastUpdate)
.count();
if (timeDiff > 0) {
off_t positionDiff = file.position - it->second.lastPosition;
file.speed =
(static_cast<double>(positionDiff) * 1000.0) / timeDiff;
if (it->second.speed > 0) {
file.speed = 0.7 * it->second.speed + 0.3 * file.speed;
}
}
}
file.lastUpdate = currentTime;
file.lastPosition = file.position;
printProgressBar(file);
}
// Bottom border
std::println("+{}{}+{}", COLOR_DIM,
std::string(std::min(118, getTerminalWidth() - 2), '-'),
COLOR_RESET);
std::cout << std::endl;
}
// Update previous files for this process
previousFiles[pid].clear();
for (const auto &file : files) {
previousFiles[pid][file.path] = file;
}
}
if (hasShownFiles && !hasFiles) {
// clear screen:
std::print("\033[2J\033[H");
// exit process:
exit(0);
}
if (!hasFiles) {
std::println("No regular files currently open by any monitored process.");
}
std::this_thread::sleep_for(std::chrono::milliseconds(intervalMs));
}
}
void showUsage(const char *progName) {
std::println(
"Usage: {} [--progress|-p] [--interval|-i <ms>] <pid|process_name>",
progName);
std::println("\nOptions:");
std::println(" --progress, -p Show real-time progress of open files");
std::println(" --interval, -i <ms> Update interval in milliseconds "
"(default: 2000, min: 100)");
std::println("\nExamples:");
std::println(" {} 1234 # Show disk I/O statistics for PID 1234",
progName);
std::println(" {} chrome # Find and show stats for processes "
"containing 'chrome'",
progName);
std::println(" {} --progress 1234 # Monitor file progress for PID 1234",
progName);
std::println(" {} --progress zstd # Monitor file progress for processes "
"containing 'zstd'",
progName);
}
int main(int argc, char *argv[]) {
bool progressMode = false;
int intervalMs = 1000; // Default 2 seconds
std::string input;
// Parse command line arguments
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "--progress" || arg == "-p") {
progressMode = true;
} else if (arg == "--interval" || arg == "-i") {
if (i + 1 < argc) {
intervalMs = std::atoi(argv[++i]);
if (intervalMs < 100) {
intervalMs = 100; // Clamp to minimum 100ms
}
} else {
std::cerr << "Error: --interval requires a value in milliseconds"
<< std::endl;
return 1;
}
} else {
input = arg;
}
}
if (input.empty()) {
showUsage(argv[0]);
return 1;
}
std::vector<pid_t> targetPids;
// Check if input contains alphabetic characters (process name search)
if (containsAlpha(input)) {
std::vector<ProcessInfo> processes = findProcessesByName(input);
if (processes.empty()) {
std::println("No processes found containing '{}'", input);
return 1;
}
std::println("Found {} process(es) containing '{}':", processes.size(),
input);
std::println("{}", std::string(80, '-'));
for (const auto &proc : processes) {
targetPids.push_back(proc.pid);
std::println("{:>8} {}", proc.pid, proc.name);
}
std::println("{}", std::string(80, '-'));
} else {
// Numeric PID
pid_t pid = std::atoi(input.c_str());
if (pid <= 0) {
std::println("Error: Invalid PID. Please provide a positive integer or "
"process name.");
return 1;
}
targetPids.push_back(pid);
}
if (progressMode) {
showProgress(targetPids, intervalMs);
return 0;
}
// Show disk I/O statistics for all matching processes
for (size_t i = 0; i < targetPids.size(); ++i) {
pid_t pid = targetPids[i];
rusage_info_current rusage;
int result = proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage);
if (result != 0) {
std::println("Error: Failed to get resource usage for PID {}", pid);
std::println(
"Make sure the process exists and you have permission to access it.");
continue;
}
if (targetPids.size() > 1) {
std::println("\nDisk I/O Statistics for PID {}:", pid);
} else {
std::println("Disk I/O Statistics for PID {}:", pid);
}
std::println("Bytes Read: {} ({} bytes)",
formatBytes(rusage.ri_diskio_bytesread),
rusage.ri_diskio_bytesread);
std::println("Bytes Written: {} ({} bytes)",
formatBytes(rusage.ri_diskio_byteswritten),
rusage.ri_diskio_byteswritten);
}
return 0;
}