linuxc语言进程是否存在
发布时间: 2023-06-12 07:09:17
1、打开kali linux的终端。创建一个文件并命名为test.c。在终端输入:touch test.c。
‘贰’ 如何在Linux下用c语言创建守护进程并监控系统运行期间的所有进程
可以分三步来做:
- 做两个简单的守护进程,并能正常运行
- 监控进程是否在运行
- 启动进程
综合起来就可以了,代码如下:
被监控进程thisisatest.c(来自):
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid<0)
exit(1); //创建错误,退出
else if(pid>0) //父进程退出
exit(0);
setsid(); //使子进程成为组长
pid=fork();
if(pid>0)
exit(0); //再次退出,使进程不是组长,这样进程就不会打开控制终端
else if(pid<0)
exit(1);
//关闭进程打开的文件句柄
for(i=0;i<NOFILE;i++)
close(i);
chdir("/root/test"); //改变目录
umask(0);//重设文件创建的掩码
return;
}
void main()
{
FILE *fp;
time_t t;
init_daemon();
while(1)
{
sleep(60); //等待一分钟再写入
fp=fopen("testfork2.log","a");
if(fp>=0)
{
time(&t);
fprintf(fp,"current time is:%s ",asctime(localtime(&t))); //转换为本地时间输出
fclose(fp);
}
}
return;
}
监控进程monitor.c:
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<limits.h>
#define BUFSZ 150
void init_daemon()
{
int pid;
int i;
pid=fork();
if(pid<0)
exit(1); //创建错误,退出
else if(pid>0) //父进程退出
exit(0);
setsid(); //使子进程成为组长
pid=fork();
if(pid>0)
exit(0); //再次退出,使进程不是组长,这样进程就不会打开控制终端
else if(pid<0)
exit(1);
//关闭进程打开的文件句柄
for(i=0;i<NOFILE;i++)
close(i);
chdir("/root/test"); //改变目录
umask(0);//重设文件创建的掩码
return;
}
void err_quit(char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
// 判断程序是否在运行
int does_service_work()
{
FILE* fp;
int count;
char buf[BUFSZ];
char command[150];
sprintf(command, "ps -ef | grep thisisatest | grep -v grep | wc -l" );
if((fp = popen(command,"r")) == NULL)
err_quit("popen");
if( (fgets(buf,BUFSZ,fp))!= NULL )
{
count = atoi(buf);
}
pclose(fp);
return count;
// exit(EXIT_SUCCESS);
}
void main()
{
FILE *fp;
time_t t;
int count;
init_daemon();
while(1)
{
sleep(10); //等待一分钟再写入
fp=fopen("testfork3.log","a");
if(fp>=0)
{
count = does_service_work();
time(&t);
if(count>0)
fprintf(fp,"current time is:%s and the process exists, the count is %d ",asctime(localtime(&t)), count); //转换为本地时间输出
else
{
fprintf(fp,"current time is:%s and the process does not exist, restart it! ",asctime(localtime(&t))); //转换为本地时间输出
system("/home/user/daemon/thisisatest"); //启动服务
}
fclose(fp);
}
}
return;
}
具体CMD命令:
cc thisisatest.c -o thisisatest
./thisisatest
cc monitor.c -o monitor
./monitor
tail -f testfork3.log -- 查看日志
‘叁’ linux C语言实现意外退出后自动重启程序
在脚本里 可以用
jobs | grep 进程号 || a.out的绝对路径
‘肆’ linux简单的C语言程序,多进程,为什么存在死循环的时候不打印字符死循环明明在打印语句的后面呀
流来不及刷新,不是你打印就立刻出现再终端的,它需要一个刷新过程,而你的死循环让它没有时间刷新
热点内容