2017-07-30 40 views
-2

我在c程序中有两个炉台,create_open_log_file()write_to_log_file()以及一个全局文件指针。c - 无法将数据写入子进程内的文件

当这些函数被调用时,日志文件按预期创建(我可以在目录中看到它)。然后调用write_to_log_file()并创建子进程。在这一点上,我会预期字符串test test test将被写入该文件中的一个循环。字符串child process打印在终端o我知道代码正在执行。但是,日志文件没有内容?

我会appreicate是否有人可以告诉我,如果我做一些明显的错误。

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 
} 
} 
+1

请清理代码的缩进。预览不适合你吗? – alk

+1

尝试[*清空*](http://en.cppreference.com/w/c/io/fflush)文件的缓冲区。 –

+0

@alk抱歉 - 现在修复。 –

回答

2

从快速代码审查,它看起来像子进程从不关闭文件,因此数据可能会或可能不会到达该文件。

啊。既然它是一个无限循环,你真的不打算结束。是。刷新缓冲区通常会将数据全部获取到磁盘,这是我猜测的是你真正想要的。

2

冲洗a FILE是必要的;否则你的输出只是在内存中(文件的缓冲块),直到块被填满,或者你的文件指针为止。这是缓冲stdio和裸文件句柄之间差异的一部分。