1. 程式人生 > >C語言判斷當前某一個程序是否存在

C語言判斷當前某一個程序是否存在

#include <stdio.h>   
#include <stdlib.h>   
#include <unistd.h>   
#include <fcntl.h>   
#include <limits.h>   
#include <sys/types.h>   
#include <sys/wait.h>   

#define BUFSZ 150   

void err_quit(char *msg);


int main(int argc, char *argv[]) {   
	
	FILE* fp;
	int count;
	char buf[BUFSZ];   
	char command[150];   
	
	sprintf(command, "ps -ef | grep ***** | grep -v grep | wc -l" );		//*****代表要監控的程序

	if((fp = popen(command,"r")) == NULL)   

		err_quit("popen");   

	if( (fgets(buf,BUFSZ,fp))!= NULL ) { 

		count = atoi(buf);   
		
		if(count  == 0)   

			printf("程序不存在!\n");   
		
		else  

			printf("程序已找到,有%d個!\n",count);   
	} 

	pclose(fp);   
	return EXIT_SUCCESS;
}


void err_quit(char *msg) {

	perror(msg);   
	exit(EXIT_FAILURE);   
}