守护进程daemon.c

它的特点是:
不占用控制终端(后台运行)
独立于控制终端
周期性运行

 

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>


int main()
{
pid_t pid;
int fd;
int i,fd,flag=1;
char *buf="i am a daemon\n";
//1创建子进程

pid=fork();


if(pid<0)
{
printf("creat failed\n");

}
if(pid>0)
exit(0);


//2脱离控制终端 //执行到此的只能是子进程,pid》0的父进程已经退出
setsid();

//3.1改变工作目录
chdir("/");

//3.2清楚掩码
umask(0);

//3.3关闭打开的文件
for(i;i<65535;i++)
{
close(i);
}
//4守护进程的实际工作
while(1)
{
if((flag==1)&&(fd=open("/temp/daemon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
{ printf("open file failed\n");
flag=0;
exit(0);
}

write(fd,buf,strlen(buf));
close(fd);
sleep(1);
}


}

转载于:https://www.cnblogs.com/1932238825qq/p/7389872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的打印机守护进程模拟代码,使用C语言实现,它可以监控打印队列并按顺序打印文件: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #define MAX_QUEUE_SIZE 100 typedef struct { char *filename; } PrintJob; typedef struct { PrintJob queue[MAX_QUEUE_SIZE]; int front, rear; } PrintQueue; void init_queue(PrintQueue *q) { q->front = q->rear = 0; } bool is_queue_empty(PrintQueue *q) { return q->front == q->rear; } bool is_queue_full(PrintQueue *q) { return (q->rear + 1) % MAX_QUEUE_SIZE == q->front; } void enqueue(PrintQueue *q, char *filename) { if (is_queue_full(q)) { printf("Queue is full!\n"); return; } q->queue[q->rear].filename = filename; q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; } PrintJob dequeue(PrintQueue *q) { if (is_queue_empty(q)) { printf("Queue is empty!\n"); exit(1); } PrintJob job = q->queue[q->front]; q->front = (q->front + 1) % MAX_QUEUE_SIZE; return job; } void print_file(char *filename) { printf("Printing file: %s\n", filename); sleep(2); // 模拟打印时间 printf("File printed.\n"); } int main() { PrintQueue queue; init_queue(&queue); // 添加打印文件到队列 enqueue(&queue, "file1.txt"); enqueue(&queue, "file2.txt"); enqueue(&queue, "file3.txt"); // 开始打印 while (!is_queue_empty(&queue)) { PrintJob job = dequeue(&queue); print_file(job.filename); } return 0; } ``` 这段代码使用了一个打印队列 `PrintQueue` 结构体,其中包含一个循环队列 `queue` 和 `front`、`rear` 两个指针。通过 `enqueue` 方法将打印文件添加到队列中,`dequeue` 方法从队列中取出打印文件。在 `print_file` 方法中,使用 `sleep` 模拟打印时间。 使用方法: 编译并运行该程序: ``` gcc -o printer_daemon printer_daemon.c ./printer_daemon ``` 输出: ``` Printing file: file1.txt File printed. Printing file: file2.txt File printed. Printing file: file3.txt File printed. ``` 这段代码比较简单,只是一个打印队列的模拟,实际的守护进程还需要考虑更多的因素,比如打印机状态、错误处理等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值