我必须将Perl脚本作为服务运行(即守护进程)。我在下面找到了C程序,一般来说它工作正常。但是,如果perl脚本因异常而死,我不会收到任何错误消息。如何从perl中获取错误?
终端(即STDERR)不可用,我认为最好的办法是在syslog
中收到错误消息。
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>
int main( int argc, char *argv[] ) {
pid_t pid, sid;
if( argc < 1 ) {
printf("At least one argument expected.\n");
return EXIT_FAILURE;
}
char arg[1000];
strcpy(arg, argv[1]);
int i = 2;
for(i = 2; i < argc; i++) {
strcat(arg, " ");
strcat(arg, argv[i]);
}
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Open a connection to the syslog server */
openlog ("mediationd", LOG_PID, LOG_DAEMON);
syslog(LOG_NOTICE, "Successfully started daemon\n");
/* Try to create our own process group */
sid = setsid();
if (sid < 0) {
syslog(LOG_ERR, "Could not create process group\n");
closelog();
exit(EXIT_FAILURE);
}
/* Catch, ignore and handle signals */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0) {
syslog(LOG_ERR, "Could not fork second time\n");
closelog();
exit(EXIT_FAILURE);
}
/* Success: Let the parent terminate */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Change the current working directory */
if ((chdir("/")) < 0) {
syslog(LOG_ERR, "Could not change working directory to /\n");
exit(EXIT_FAILURE);
}
/* Close the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Starting the perl script which does the job.
* Note, this perl scripts runs forever till it is terminated by 'kill' command */
system(arg);
/* Terminate the daemon */
syslog (LOG_NOTICE, "Daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
我通过简单的复制/粘贴编写了这个小程序,因为我对C没有任何线索。如果有人可以提供一些&#34;准备使用&#34;那就太好了。代码。
更新
我更新了我的代码,如下所示。它似乎运作良好,但我是否会错过任何东西或者我应该添加其他东西?
/* Close the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
/* Redirect STDERR to syslog, i.e. logger */
FILE *fl;
fl = popen("logger --id --priority user.error", "w");
if (fl == NULL) {
syslog(LOG_ERR, "Could not open 'looger'\n");
exit(EXIT_FAILURE);
}
int nf = fileno(fl);
dup2(nf, STDERR_FILENO);
/* Starting the perl script which does the job.
* Note, this perl scripts runs forever till it is terminated by 'kill' command */
system(arg);
close(STDERR_FILENO);
/* Terminate the daemon */
syslog (LOG_NOTICE, "Daemon terminated\n");
closelog();
return EXIT_SUCCESS;
答案 0 :(得分:1)
如果你想在原生Perl中这样做,这对我有用:
use IO::Handle;
open(SYSLOG, "| /usr/bin/logger -t hello") or die( "syslog problem $!" );
*STDERR = *SYSLOG;
autoflush STDERR 1;
如果Perl与die()
或类似的崩溃,您将看到日志消息。