第一个 while 循环需要一直运行,直到用户输入 1。(假设在子进程中运行)。
第二个 while 循环将是后台运行的守护进程,每 1 秒记录一次计数器。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char* argv[])
{
FILE *fp= NULL;
pid_t process_id = 0;
pid_t sid = 0;
// Create child process
process_id = fork();
int clos =0;
int count=0;
这是应该一直运行到用户输入 1 的循环
while(clos !=1){
printf("Type: ");
scanf("%d",&clos);
if (clos !=1){
count = clos;
}
}
// Indication of fork() failure
if (process_id < 0)
{
printf("fork failed!\n");
// Return failure in exit status
exit(1);
}
// PARENT PROCESS. Need to kill it.
if (process_id > 0)
{
printf("process_id of child process %d \n", process_id);
// return success in exit status
exit(0);
}
//unmask the file mode
umask(0);
//set new session
sid = setsid();
if(sid < 0)
{
// Return failure
exit(1);
}
// Change the current working directory to root.
chdir(".");
// Close stdin. stdout and stderr
// Open a log file in write mode.
fp = fopen ("votes.log", "w+");
这是应该在后台运行并从第一次登录计数的守护进程。
while (1)
{
//Dont block context switches, let the process sleep for some time
sleep(1);
fprintf(fp, "Logging info...\n");
fprintf(fp, "%d",count);
fprintf(fp, "\n");
fflush(fp);
// Implement and call some function that does core work for this daemon.
}
fclose(fp);
return (0);
}