gpt4 book ai didi

c - 生成守护函数和信号处理程序

转载 作者:行者123 更新时间:2023-11-30 17:38:43 25 4
gpt4 key购买 nike

我想生成一个守护进程并应用信号处理程序并将它们记录在文件中。我无法在文件中记录信号处理程序。另外我不确定这些信号处理程序是否正常工作......如何检查它们。请帮忙

/* A signal handler */

void signal_handler(int signal)
{
printf("Caught signal %d\t", signal);
if (signal == SIGINT)
printf("Interrupt (Ctrl-C)");
else if (signal == SIGQUIT)
{
printf("QUIT");
exit(0);
}
else if (signal == SIGABRT)
{
printf("Process Aborted");
exit(0);
}
else if (signal == SIGTRAP)
printf("Trace/breakpoint trap");
else if (signal == SIGKILL)
{
printf("Kill");
exit(0);
}
else if (signal == SIGTERM)
printf("Termination");
else if (signal == SIGCONT)
printf("Continue if stopped");
else if (signal == SIGTSTP)
printf("Pause the execution");
printf("\n");
}

Here is the main function

FILE *fp= NULL;
fp = fopen ("Log.txt", "w+");
do
{
daemon(1, 1);// fork to a background daemon process
//printf("daemon is not working");
printf("daemon-ed \n ");
/* Registering signal handlers */
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler); // Set signal_handler() as the
signal(SIGABRT, signal_handler); // signal handler for these
signal(SIGTRAP, signal_handler); // signals.
signal(SIGKILL, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGCONT, signal_handler);
signal(SIGTSTP, signal_handler);

fprintf(fp, "%s", signal);
fflush(fp);
// Implement and call some function that does core work for this daemon.

fclose(fp);
}while(-1);


return 0;

最佳答案

fprintf() 到文件确实非常简单下面的示例来自http://www.cplusplus.com/reference/cstdio/fprintf/

您需要文件指针,您可以在 main FILE * pFile 中声明它,例如

然后使用fopen给pFile值

之后您可以使用 fprintf 写入文件

/* fprintf example */
#include <stdio.h>

int main ()
{
FILE * pFile;
int n;
char name [100];

pFile = fopen ("myfile.txt","w");
for (n=0 ; n<3 ; n++)
{
puts ("please, enter a name: ");
gets (name);
fprintf (pFile, "Name %d [%-10.10s]\n",n,name);
}
fclose (pFile);

return 0;
}

关于c - 生成守护函数和信号处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com