我必须运行一个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 daemonn");
/* Try to create our own process group */
sid = setsid();
if (sid < 0) {
syslog(LOG_ERR, "Could not create process groupn");
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 timen");
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.
update
我更新了我的代码,如下所示。它似乎运行良好,但是我会错过任何东西还是应该添加其他东西?
/* 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 terminatedn");
closelog();
return EXIT_SUCCESS;
如果您想在本机Perl中进行,这对我有用:
use IO::Handle;
open(SYSLOG, "| /usr/bin/logger -t hello") or die( "syslog problem $!" );
*STDERR = *SYSLOG;
autoflush STDERR 1;
如果Perl用die()
崩溃或类似,您将看到日志消息。