Categories
Linux Programming

Linux kill process code fragment

Small C++ source code fragment to kill a certain number of instances of a process running under Linux. For example the following sends a terminate signal to the first 999 processes with the process name Tomahawk.

killproc(“Tomahawk”, “-TERM”, 999);

int killproc(const string procname, const string killcmd, const int killcnt)
{
	int proccnt = 0;
	const string procdir("/proc");

	DIR* dir = opendir(procdir.c_str());
	if (!dir)
		return 0;
	string searchstr = "(" + procname + ")";
	struct dirent *d;
	while ((d = readdir(dir)) && proccnt < killcnt)
	{
		string dirname(d->d_name);
		if( d->d_type == DT_DIR && dirname != "." && dirname != ".." && isdigit(dirname[0]))
		{
			string fn = procdir + "/" + dirname + "/stat";
			ifstream f(fn.c_str());
			if (f.is_open())
			{
				string line;
			    if (getline (f, line) && line.find(searchstr) != string::npos)
			    {
			    	proccnt++;
			    	string procid = line.substr(0, line.find(" "));
					string cmd = "kill " + killcmd + " " + procid;
					system(cmd.c_str());
			    }
			}
			f.close();
		}
	}
	closedir(dir);
	return proccnt;
}