2011-02-26 23:02 4422 People read comments (2) Collection report
Recently learning to communicate between processes, but I have not found a Linux from the process name can be used to get the process ID of the function, so I wrote one. Can get the correct result, but it is not efficient to get it through the system function and then read the file. If high man see, have any good suggestions please remind me, thank you.
getprocessattr.h///////////////////////////////////// //////////////
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
Class Getprocessattr
{
Public
Getprocessattr ();
~getprocessattr ();
Gets the process ID based on the process name
int GetProcessID (char *process_name);
Gets the process name based on the process ID
char* getprocessname (int process_id);
};
getprocessattr.cpp////////////////////////////////////// //////////
#include "GetProcessAttr.h"
Getprocessattr::getprocessattr ()
{
}
Getprocessattr::~getprocessattr ()
{
}
int Getprocessattr::getprocessid (char *process_name)
{
Get process ID by Shell
Char cmd[100]={0};
sprintf (cmd, "pidof%s > Pid.txt", process_name);
System (CMD);
Open File
int Fd=open ("Pid.txt", O_RDWR);
if (fd<0)
{
Perror ("Open File failed/n");
System ("rm pid.txt");
return-1;
}
Read file
Char read_buf[50]={0};
if (read (fd,read_buf,50) <0)
{
Perror ("Read ():");
Close (FD)
System ("rm pid.txt");
return-1;
}
Close File
if (Close (FD) <0)
{
Perror ("Close ():");
System ("rm pid.txt");
return-1;
}
Remove file
System ("rm pid.txt");
return atoi (READ_BUF);
}
char* getprocessattr::getprocessname (int process_id)
{
Get Process name by Shell
Char cmd[100]={0};
sprintf (cmd, "Readlink/proc/%d/exe >pname.txt", process_id);
System (CMD);
Open File
int Fd=open ("Pname.txt", O_RDWR);
if (fd<0)
{
Perror ("Open ():/n");
return NULL;
}
Read file
Char *pname = new char[200];
if (read (fd,pname,200) <0)
{
Perror ("Read ():");
return NULL;
}
Close File
if (Close (FD) <0)
{
Perror ("Close ():");
return NULL;
}
Remove file
System ("rm pname.txt");
return pname;
}