关闭

守护进程日志探寻

108人阅读 评论(0) 收藏 举报
分类:

1.首先要更改配置文件,Ubuntu下不存在/etc/syslog.conf,经过一番折腾,找到了rsyslog.conf,进而发现了真正的配置文件/etc/syslog.d/50-default.conf

  修改配置文件如下,含义为openlog时,参数为LOG_MAIL的直接发送到UDP的514端口,参数为LOG_USER的即存到本地,也发送到UDP,修改好后重启

 服务,service rsyslog restart。

2. 测试代码

客户端发送日志

#include <stdio.h>
#include <syslog.h>
#include <sys/param.h>
#include <stdlib.h>
void init_daemon(void)
{
    int pid;
    int i;
    if(pid=fork())
        exit(0);        
    else if(pid< 0)
        exit(1);        
    setsid();               
    if(pid=fork())
        exit(0);        
    else if(pid< 0)
        exit(1);           
    for(i=0;i< NOFILE;++i)  
        close(i);
    chdir("/home");      
    umask(0);           
}
int main(int argc,char* argv[])
{
	init_daemon();
openlog(argv[0],LOG_CONS | LOG_PID, LOG_USER);
int count=0;
while(count<5){
syslog(LOG_DEBUG,"%d, log info test...",count);
printf("haha\n");
count++;
}
closelog();
return 0;
}

服务端接受日志

#include <sys/types.h>
#include <sys/socket.h>
#include<pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: %s port\n", argv[0]);
        exit(1);
    }
    printf("Welcome! This is a UDP server, I can only received message from client and reply with same message\n");
   
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int sock;
    if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket");
        exit(1);
    }
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(1);
    }
    char buff[512];
    struct sockaddr_in clientAddr;
    int n;
    int len = sizeof(clientAddr);
    while (1)
    {
        n = recvfrom(sock, buff, 511, 0, (struct sockaddr*)&clientAddr, &len);
        if (n>0)
        {
            buff[n] = 0;
            printf("%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff);
            n = sendto(sock, buff, n, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
            if (n < 0)
            {
                perror("sendto");
                break;
            }
        }
        else
        {
            perror("recv");
            break;
        }
    }
    return 0;
}

3.测试



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20545次
    • 积分:469
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:6篇
    • 译文:0篇
    • 评论:0条
    文章分类