写三个程序,分别执行如下功能:
程序一:打印“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;
}