C語言有什么函數可以判斷某進程是否存在
3 回答
至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
C語言沒有庫函數可以做到這一點。但是在Linux下,有一些替代方案。
見下:
基本思路是先定義一個FILE指針,用該指針接收popen()執行ps指令的返回值,再從指針中讀取數據到緩存,根據得到的數據判斷進程是否存在,怎么操作要看ps的參數了。
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 | #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<limits.h> #define BUFSZ PIPE_BUF void err_quit(char *msg) { perror(msg); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { FILE* fp; int count; char buf[BUFSZ]; char command[150]; if(argc != 2) {printf("USAGE: example <process name>\n"); exit(EXIT_SUCCESS); } elsesprintf(command, "ps -C %s|wc -l", argv[1] ); if((fp = popen(command,"r")) == NULL) err_quit("popen"); if( (fgets(buf,BUFSZ,fp))!= NULL ) {count = atoi(buf); if((count - 1) == 0) printf("%s not found\n",argv[1]); elseprintf("process : %s total is %d\n",argv[1],(count - 1)); } pclose(fp); exit(EXIT_SUCCESS); } |
繁花如伊
TA貢獻2012條經驗 獲得超12個贊
可以遍歷進程查找進程的PID跟進程名進行判斷,這個需要操作系統提供支持,如果不用第三方庫的話windows下是
#include<TlHelp32.h>
CreateToolhelp32Snapshot/*創建進程快照*/
Process32First/*獲得第一個進程*/
Process32Next/*獲得下一個進程*/
或者使用
#include<psapi.h>
EnumProcesses/*返回所有進程數組,可用于OpenProcess*/
來枚舉進程,具體的可以查看MSDN獲取幫助
- 3 回答
- 0 關注
- 2153 瀏覽
添加回答
舉報
0/150
提交
取消
