【发布时间】:2017-07-30 14:24:30
【问题描述】:
我在一个 c 程序中有两个功能,create_open_log_file() 和 write_to_log_file() 以及一个全局文件指针。
当调用这些函数时,会按预期创建日志文件(我可以在目录中看到它)。然后调用write_to_log_file() 并创建一个子进程。在这一点上,我希望字符串test test test 会循环写入该文件。字符串child process 打印在终端上o 我知道代码正在被执行。但是,日志文件没有内容?
如果有人能告诉我我是否做错了什么,我会很感激。
FILE *log_file;
static void create_open_log_file(void) {
char filename[40];
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
strftime(s, sizeof(s), "%a%b%d%T", tm);
sprintf(filename, "dut1_serial_log_%s", s);
log_file = fopen(filename,"w");
if (log_file == NULL) {
perror("Error creating log file");
}
}
static write_to_log_file() {
// Prevent killed child-processes remaining as "defunct"
struct sigaction sigchld_action = {
.sa_handler = SIG_DFL,
.sa_flags = SA_NOCLDWAIT
};
sigaction( SIGCHLD, &sigchld_action, NULL ) ;
// Duplicate ("fork") the process. Will return zero in the child
// process, and the child's PID in the parent (or negative on error).
int pid = fork();
global_pid = pid;
if( pid < 0 ) {
printf( "Fork failed\n" ) ;
return 1 ;
}
// ------------ Child process
if( pid == 0 ) {
// ------------ Child process
// Open log file and write to it from /dev/USB1
create_open_log_file();
while( 1 ) {
printf( "child process\n" ) ;
char str[] = "test test test";
fwrite(str , 1 , sizeof(str) , log_file);
sleep(1) ;
}
return 0 ; //never reached
}
}
【问题讨论】:
-
请清理代码的缩进。预览不适用于您吗?
-
尝试flushing文件的缓冲区。
-
@alk 抱歉 - 现已修复。
-
@Someprogrammerdude - 谢谢它正在刷新缓冲区。
-
@articsol:“现在修复”不是真的...
标签: c file fork parent-child