×
Namespaces

Variants
Actions

Get PID from Application Name

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to get process ID from the application name on a Linux system, such as Maemo/MeeGo


Article Metadata
Compatibility
Platform(s): Maemo/Harmattan/MeeGo
Device(s): Nokia N900, Nokia N950, Nokia N9
Article
Keywords: pid, linux application name
Created: ()
Last edited: hamishwillee (13 Jun 2012)

Introduction

Sometime developers want to know if an application (usually daemons/services) is running in background. Linux. as well as Maemo/MeeGo do not provide any API for such task. The list of processes running on a linux system can be retrieved with several command line utilities, but the question is how to implement such feature in your Harmattan application.

This article is going to show you the function I used to get the PID of my daemon from the name.

Code

In this section I show you the function you can add to your class to reach the goal. The code doesn't make use of Qt but it has been written in plain C code in order to be re-used in non Qt apps. In-line comments illustrate the way this code works.

unsigned int getProcessID(char *p_processname) {
DIR *dir_p;
struct dirent *dir_entry_p;
char dir_name[40]; // ??? buffer overrun potential
char target_name[252]; // ??? buffer overrun potential
int target_result;
char exe_link[252];
int errorcount;
int result;
 
errorcount=0;
result=0;
dir_p = opendir("/proc/"); // Open /proc/ directory
while(NULL != (dir_entry_p = readdir(dir_p))) { // Reading /proc/ entries
if (strspn(dir_entry_p->d_name, "0123456789") == strlen(dir_entry_p->d_name)) { // Checking for numbered directories
strcpy(dir_name, "/proc/");
strcat(dir_name, dir_entry_p->d_name);
strcat(dir_name, "/"); // Obtaining the full-path eg: /proc/24657/
exe_link[0] = 0;
strcat(exe_link, dir_name);
strcat(exe_link, "exe"); // Getting the full-path of that exe link
target_result = readlink(exe_link, target_name, sizeof(target_name)-1); // Getting the target of the exe ie to which binary it points to
if (target_result > 0) {
target_name[target_result] = 0;
if (strstr(target_name, p_processname) != NULL) { // Searching for process name in the target name -- ??? could be a better search !!!
result = atoi(dir_entry_p->d_name);
printf("getProcessID(%s) :Found. id = %d\n", p_processname, result);
closedir(dir_p);
return result;
}
}
}
}
closedir(dir_p);
printf("getProcessID(%s) : id = 0 (could not find process)\n", p_processname);
return result;
}
This page was last modified on 13 June 2012, at 13:53.
68 page views in the last 30 days.