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語言程序,多進程,為什麼存在死循環的時候不列印字元死循環明明在列印語句的後面呀
流來不及刷新,不是你列印就立刻出現再終端的,它需要一個刷新過程,而你的死循環讓它沒有時間刷新
熱點內容