954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to get process name from pid in C/C++

Hi there,

I want to get the process name from the process id (pid) in C/C++ program.

Please help me.

I am using linux machine.

kandarpa
Newbie Poster
12 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

You can always use the /proc filesystem which includes entries for all currently running processes.

L7Sqr
Practically a Master Poster
656 posts since Feb 2011
Reputation Points: 201
Solved Threads: 123
 

Steps followed to get the process name:
1. Open the file /proc//status in read mode
2. Read the first line and parse the line and get the string enclosed in braces i.e., ().

Is that correct process to get the process name?
Is there any system call available to get the process information along with name?

Something like a structure which contains the information related to a process which can be identified by a pid.

kandarpa
Newbie Poster
12 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Well you see the thing is when getting process by id, the ID can change when the process restarts or exits depending on if another program already took the id during that interval. Meh Just look at how to Enumerate processes and look here: http://msdn.microsoft.com/en-us/library/ms683215

int isRunning(char *pProcessName)
{
    HANDLE hSnap = INVALID_HANDLE_VALUE;
    HANDLE hProcess = INVALID_HANDLE_VALUE;
    PROCESSENTRY32 ProcessStruct;
    ProcessStruct.dwSize = sizeof(PROCESSENTRY32);
    hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hSnap == INVALID_HANDLE_VALUE)
        return -1;
    if(Process32First(hSnap, &ProcessStruct) == FALSE)
        return -1;
    do
    {
        if(stricmp(strupr(ProcessStruct.szExeFile), pProcessName)==0)
        {
            CloseHandle( hSnap );
            return  ProcessStruct.th32ProcessID;
            break;
        }
    }
    while( Process32Next( hSnap, &ProcessStruct ) );
    CloseHandle( hSnap );
    return -1;
}
triumphost
Posting Whiz
390 posts since Oct 2009
Reputation Points: 57
Solved Threads: 36
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: