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.

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

Steps followed to get the process name:
1. Open the file /proc/<process-id>/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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.