守护进程(学习笔记六)

写三个程序,分别执行如下功能:
程序一:打印“I am process 1”,然后睡眠3秒,退出
程序二:打印“I am process 2”,然后睡眠3秒,退出
程序三:程序执行起来后创建两个子进程,此两个子进程分别使用exec运行程序一和程序二,当主进程检测到任何一个子进程退出时,打印出退出的子进程,并重新启动相应的子进程。

daemon.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
pid_t RunProcess(const char *proc)
{
	pid_t pid;

	pid = fork();
	if(pid == 0) {
		execl(proc, proc, NULL);
		exit(0);
	}
	return pid;
}

int main(int argc, char *argv[])
{
	int status;
	pid_t pid1 = 0;
	pid_t pid2 = 0;
	pid_t pid;

	while(1) {
		if(pid1 <= 0) {
			pid1 = RunProcess("./p1");
		}
		if(pid2 <= 0) {
			pid2 = RunProcess("./p2");
		}
		pid = wait(&status);
		if(pid == pid1) {
			pid1 = 0;
		}
		if(pid == pid2) {
			pid2 = 0;
		}
	}
}

 

p1.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
	int i = 0;
	printf("%s started\n", argv[0]);
	while(1) {
		printf("Process %d, i=%d\n", getpid(), i++);
		sleep(3);
	}
	return 0;
}


p2.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
	int i = 0;
	printf("%s started\n", argv[0]);
	while(1) {
		printf("Process %d, i=%d\n", getpid(), i++);
		sleep(5);
	}
	return 0;
}


 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值