我正在尝试记录我的进程收到的信号。每当我写入 signal.log
文件时,它都会被覆盖。我是否缺少偶然附加的文件标志?
代码:
#include <stdio.h>
#include <unistd.h>
#include "signalinfo.h"
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <fcntl.h>
void
setsig(struct sigaction sa)
{
int i;
for(i=0; i<SIGNAL_LIST_LENGTH; i++) {
if(sigaction(siglist[i].code, &sa, NULL) == -1) {
printf("Sigaction Error When: %s \n", siglist[i].name);
}
}
}
void
handler(int sig)
{
char path[PATH_MAX];
int fd, flags, i;
flags = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH | S_IROTH;
getcwd(path, PATH_MAX);
strcat(path,"/signal.log");
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, flags);
for(i=0; i<SIGNAL_LIST_LENGTH; i++) {
if(sig == siglist[i].code) {
write(fd, siglist[i].name, strlen(siglist[i].name));
}
}
close(fd);
}
int
main(void)
{
struct sigaction sa;
sa.sa_handler = handler;
setsig(sa);
while(1) {
printf("In loop with PID: %d\n", getpid());
sleep(1);
}
}
这是否是偶然发生的,因为我缺少一面旗帜?运行后没有追加文件,只写了一行
SIGINT
我正在使用 write,因为它是一个异步信号安全函数
最佳答案
你需要附加标志
O_APPEND
并移除
O_TRUNC
关于c - 使用 write() 写入文件时文件被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386139/