所以我在Linux系统上运行了一个守护进程,我希望记录它的活动:日志.问题是,实现这一目标的"最佳"方法是什么?
我的第一个想法是简单地打开一个文件并写入它.
FILE* log = fopen("logfile.log", "w");
/* daemon works...needs to write to log */
fprintf(log, "foo%s\n", (char*)bar);
/* ...all done, close the file */
fclose(log);
Run Code Online (Sandbox Code Playgroud)
以这种方式记录是否有任何内在错误?有没有更好的方法,比如Linux内置的一些框架?
所以我有一些C代码:
#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
Run Code Online (Sandbox Code Playgroud)
这样编译,运行和行为就像它看起来一样.但是,如果将一个或两个字符指针声明为全局变量,则strcpy会导致分段错误.为什么会这样?显然我对范围的理解有误.
通常当我需要在C中分叉时,我会这样做:
pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
Run Code Online (Sandbox Code Playgroud)
它发生在我身上,我可以抛弃额外的变量并使用:
if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
Run Code Online (Sandbox Code Playgroud)
抛开不正确的错误处理,(为什么)这个工作/不工作?