我在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
}
}
请清理代码的缩进。预览不适合你吗? – alk
尝试[*清空*](http://en.cppreference.com/w/c/io/fflush)文件的缓冲区。 –
@alk抱歉 - 现在修复。 –