/************************************************************************
 * AUTHOR: NiuJiuRu
 * FILENAME: swprogress.c
 * CONTENT: 进程
 * NOTE:
 * HISTORY:
 * 1, [2010-12-21] created by NiuJiuRu
 ***********************************************************************/
#include "swapi.h"
#include "swstring.h"
#include "swdir.h"
#include "swprogress.h"

/* 得到当前进程的PID */
int xGetCurrentProcessId()
{
	return getpid();
}

/* 得到当前进程所对应的命令文件名 */
char *sw_progress_getCMD(char *cmd)
{
	if(!cmd) return NULL;
	xGetSelfRunningInfo(NULL, cmd);
	return cmd;
}

/* 根据进程ID杀死进程 */
void sw_progress_killByPID(int pid)
{
	kill(pid, SIGKILL);
}

/* 根据命令文件名杀死进程 */
void sw_progress_killByCMD(const char *cmd, int ignorePID)
{
	FILE *fp = NULL;
	char buf[MAX_LINE_CHARS] = { 0 };
	int pid = 0;

	// 创建进程快照
	fp = popen("ps -e", "r");
	if(!fp) return;
	
	// 遍历所有进程
	while(fgets(buf, sizeof(buf), fp) != NULL)
	{
		sscanf(buf, "%d", &pid); // 得到进程PID
		if(xstrcasestr(buf, "right", cmd) != NULL && pid != ignorePID)
			sw_progress_killByPID(pid);
		memset(buf, 0, sizeof(buf));
	}
	
	// 关闭快照句柄
	pclose(fp);
}
