Skip to content

Commit 98ba4aa

Browse files
refactor: Replace popen with QProcess for process count and kill operations
- Updated `getProcessCountByName` to use `QProcess` for executing the `ps` command, improving reliability and handling of process output. - Refactored `killProcessByName` to utilize `QProcess` for killing processes, enhancing code consistency and error handling. - Improved null and empty string checks for process names in both functions. This change enhances the maintainability and performance of process management in the application.
1 parent 414e16a commit 98ba4aa

1 file changed

Lines changed: 28 additions & 19 deletions

File tree

src/common/utils.cpp

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -748,39 +748,48 @@ void Utils::setChildrenFocus(QWidget *pWidget, Qt::FocusPolicy policy)
748748

749749
int Utils::getProcessCountByName(const char *pstrName)
750750
{
751-
FILE *fp = NULL;
752-
int count = -1;
753-
char command[1024];
751+
qDebug() << "Enter getProcessCountByName, pstrName:" << pstrName;
754752

755753
if (NULL == pstrName || strlen(pstrName) == 0) {
756-
return count;
754+
qDebug() << "pstrName is null";
755+
return -1;
757756
}
758757

759-
memset(command, 0, sizeof(command));
760-
sprintf(command, "ps -ef | grep %s | grep -v grep | wc -l", pstrName);
758+
QProcess process;
759+
process.start("ps", QStringList() << "-ef");
760+
if (!process.waitForFinished(5000)) {
761+
qDebug() << "ps command timeout";
762+
return -1;
763+
}
764+
765+
QString output = process.readAllStandardOutput();
766+
QString processName = QString::fromUtf8(pstrName);
767+
int count = 0;
761768

762-
if ((fp = popen(command, "r")) != NULL) {
763-
char buf[1024];
764-
memset(buf, 0, sizeof(buf));
765-
if ((fgets(buf, sizeof(buf) - 1, fp)) != NULL) {
766-
count = atoi(buf);
769+
for (const QString &line : output.split('\n')) {
770+
if (line.contains(processName)) {
771+
count++;
767772
}
768-
pclose(fp);
769-
} else {
770-
qDebug() << ">>> popen error";
771773
}
772774

775+
qDebug() << "Exit getProcessCountByName, count:" << count;
773776
return count;
774777
}
775778

776779
void Utils::killProcessByName(const char *pstrName)
777780
{
778-
if (pstrName != NULL && strlen(pstrName) > 0) {
779-
char command[1024];
780-
memset(command, 0, sizeof(command));
781-
sprintf(command, "killall %s", pstrName);
782-
system(command);
781+
qDebug() << "Enter killProcessByName, pstrName:" << pstrName;
782+
783+
if (pstrName == NULL || strlen(pstrName) == 0) {
784+
qDebug() << "pstrName is null or empty";
785+
return;
783786
}
787+
788+
QProcess process;
789+
process.start("killall", QStringList() << QString::fromUtf8(pstrName));
790+
process.waitForFinished(5000);
791+
792+
qDebug() << "Exit killProcessByName";
784793
}
785794

786795
QString Utils::getStringMD5Hash(const QString &input)

0 commit comments

Comments
 (0)