Linux下查看进程是否运行,结束进程!
#include <stdio.h>
#include <string.h>
/*get the pid array*/
static int *get_pid(char *key)
{
char buff[80];
int *pid = NULL;
int i = 0;
char *ret;
pid = (int *)malloc(8*sizeof(int));
if (NULL == pid)
{
printf("pid malloc error!\n");
}
memset(pid,0,8*sizeof(int));
sprintf(buff,"pidof %s",key);
FILE *pidreader = popen(buff,"r");
memset(buff,0,80);
ret = fgets(buff,79,pidred);
pclose(pidreader);
ret = strtok(buff," ");
while (ret != NULL)
{
pid[i++]=atoi(ret);
ret =strtok(NULL," ");
}
return pid;
}
/*this function is usesd to signal the process with "kill -10" */
void stop_process()
{
int *pid=get_pid("your_process_name");
int i = 0;
while (pid[i] )
{
//printf("signal to pid=%d\n",pid[i]);
kill(pid[i++],10);
}
free(pid);
}