我正在尝试实现一个简单的syslog应用程序。它应该创建一个/ dev / log套接字,同时它将在无限循环中接收logger
终端命令提供的日志消息。
我的代码的当前状态如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define SOCKET_NAME "/dev/log"
#define BUFFER_SIZE 50
int main()
{
struct sockaddr_un name;
int ret;
int connection_socket;
int data_socket;
char buffer[BUFFER_SIZE];
/*
* In case the program exited inadvertently on the last run,
* remove the socket.
*/
unlink(SOCKET_NAME);
/* Create local socket. */
connection_socket = socket(AF_UNIX, SOCK_DGRAM, 0);
if (connection_socket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
/*
* For portability clear the whole structure, since some
* implementations have additional (nonstandard) fields in
* the structure.
*/
memset(&name, 0, sizeof(struct sockaddr_un));
/* Bind socket to socket name. */
name.sun_family = AF_UNIX;
strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path));
name.sun_path[sizeof(name.sun_path)-1] = '\0';
ret = bind(connection_socket, (const struct sockaddr *) &name, SUN_LEN(&name));
if (ret == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
/*
* Prepare for accepting connections. The backlog size is set
* to 20. So while one request is being processed other requests
* can be waiting.
*/
ret = listen(connection_socket, 20);
if (ret == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
/* This is the main loop for handling connections. */
for (;;) {
/* Wait for incoming connection. */
data_socket = accept(connection_socket, NULL, NULL);
if (data_socket == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
for (;;) {
/* Wait for next data packet. */
ret = read(data_socket, buffer, BUFFER_SIZE);
if (ret == -1) {
perror("read");
exit(EXIT_FAILURE);
}
/* Ensure buffer is 0-terminated. */
buffer[BUFFER_SIZE - 1] = 0;
/* Printf buffer*/
printf("Log message: \n", buffer);
}
close(data_socket);
}
close(connection_socket);
/* Unlink the socket. */
unlink(SOCKET_NAME);
exit(EXIT_SUCCESS);
}
错误消息如下:绑定:地址已在使用中
我的问题是:
我认为此行为是由原始syslog引起的,因此我用systemctl stop rsyslog
停止了syslog。但是,这对结果没有影响。
最终程序应如下所示:How to read /dev/log?