linux c 查看其它程序是否启动。没有则启动他

#include <sys/types.h>
#include <dirent.h>
#include<unistd.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "proc.h"

/*
* 读proc目录文件,查看所指定进程产生的文件是否存在
*/
pid_t proc_find(const char* name) {
DIR* dir;
struct dirent* ent;
char buf[512];

long pid;
char pname[100] = { 0, };
char state;
FILE *fp = NULL;

if (!(dir = opendir("/proc"))) { //Open proc directory
perror("can't open /proc");
return -1;
}

while ((ent = readdir(dir)) != NULL) { //读proc目录文件
long lpid = atol(ent->d_name);
if (lpid < 0)
continue;
snprintf(buf, sizeof(buf), "/proc/%ld/stat", lpid);
fp = fopen(buf, "r"); //打开指定目录文件

if (fp) { // 如果能打开
if ((fscanf(fp, "%ld (%[^)]) %c", &pid, pname, &state)) != 3) {
printf("fscanf failed \n");
fclose(fp);
closedir(dir);
return -1;
}
if (!strcmp(pname, name)) {
fclose(fp);
closedir(dir);
return (pid_t) lpid;
}
fclose(fp);
}
}

closedir(dir);
return -1;
}
/*
* proc 处理主函数, 做两件事
* 1. 检查mysqld, vidireports 是否启动
* 2.若没有启动,则启动他们
*/
int proc(void) {

/* if (argc == 1) {
printf("usage: %s name1 name2 ...\n", argv[0]);
return 1;
}
*/
int ret=0;
#define apps_0 0x01
#define apps_1 0x02

#define MAX_CHECK_COUNTER 3

char* apps[] = { "vidireports", "mysqld" };
char* apps_start_cmds[] = { "bin/VidiReports/start.sh",
"/etc/init.d/mysqd start" };
int apps_has_started[] = { apps_0, apps_1 };

int needCheck = apps_0 | apps_1;

int n = sizeof(apps) / sizeof(apps[0]);
int checkCounter = 0;
while (needCheck && checkCounter++ < MAX_CHECK_COUNTER) { //进行核对,最多进行3次
int i = 0;
for (; i < n; i++) {
if (!(needCheck & apps_has_started[i]))
continue;
pid_t pid = proc_find(apps[i]); //找出app[i]所指进程的ID
if (pid == -1) { // 如果找不到所指定进程
int status;
printf("%s: not found\n", apps[i]);
status = system(apps_start_cmds[i]);
status = 0;
printf("Example: %s: \n", apps_start_cmds[i]);
if (-1 == status) {
printf("system error!");
ret = status;
} else {
printf("exit status value = [0x%x]\n", status);
ret = status;
if (WIFEXITED(status)) {
if (0 == WEXITSTATUS(status)) {
printf("run shell script successfully.\n");
} else {
printf(
"run shell script fail, script exit code: %d\n",
WEXITSTATUS(status));
}
} else {
printf("exit status = [%d]\n", WEXITSTATUS(status));
}
}

} else {
needCheck ^= apps_has_started[i];
printf("%s: %d\n", apps[i], pid);
}
} //for
sleep(2);
} //when need check
return ret;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值