I'm trying to get a process id by name but I don't know if it's related with my pc or if I'm missing something. I've been trying for a while on changing methods but everytime I get this excpetion.
Exception thrown at 0x00007FFFC6083C0F (user32.dll) in application.exe: 0xC0000005: Access violation while reading path 0x00000000FFFFFFFF.
int getProcIdByName(string procName)
{
int pid = -1;
// Open the /proc directory
DIR* dp = opendir("/proc");
if (dp != NULL)
{
// Enumerate all entries in directory until process found
struct dirent* dirp;
while (pid < 0 && (dirp = readdir(dp)))
{
// Skip non-numeric entries
int id = atoi(dirp->d_name);
if (id > 0)
{
// Read contents of virtual /proc/{pid}/cmdline file
string cmdPath = string("/proc/") + dirp->d_name + "/cmdline";
ifstream cmdFile(cmdPath.c_str());
string cmdLine;
getline(cmdFile, cmdLine);
if (!cmdLine.empty())
{
// Keep first cmdline item which contains the program path
size_t pos = cmdLine.find('\0');
if (pos != string::npos)
cmdLine = cmdLine.substr(0, pos);
// Keep program name only, removing the path
pos = cmdLine.rfind('/');
if (pos != string::npos)
cmdLine = cmdLine.substr(pos + 1);
// Compare against requested process name
if (procName == cmdLine)
pid = id;
}
}
}
}
closedir(dp);
return pid;
}
int main(int argc, char* argv[])
{
int pid = getProcIdByName("example.exe");
cout << "pid: " << pid << endl;
return 0;
}
I also tried with this method
int findProcessID(wchar_t processName[]);
int main()
{
// Declare a wchar_t array to put process name.
wchar_t processName[100];
// Input the process name, such as "notepad.exe".
printf("Enter process name: ");
scanf_s("%ls", processName);
// Get the PID.
int pid = findProcessID(processName);
if (pid > 0) {
printf("The process \"%ls\" is found.\n\tAnd PID is %d\n", processName, pid);
}
else {
printf("Not found the process \"%ls\".\n", processName);
}
system("PAUSE");
return 0;
}
int findProcessID(wchar_t processName[]) {
// Enumerate all processes.
PROCESSENTRY32 entry;
// dwSize: The size of the structure, in bytes.
// Before calling the Process32First function,
// set this member to sizeof(PROCESSENTRY32).
// If you do not initialize dwSize, Process32First fails.
entry.dwSize = sizeof(PROCESSENTRY32);
// Includes all processes in the system in the snapshot.
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE) {
while (Process32Next(snapshot, &entry) == TRUE) {
if (wcscmp(entry.szExeFile, processName) == 0) {
// Match the process name.
return entry.th32ProcessID;
}
}
}
return -1;
}
User contributions licensed under CC BY-SA 3.0