c - 无法从子进程内部将数据写入文件

时间:2017-07-30 14:24:30

标签: c file fork parent-child

我在c程序中有两个装置,create_open_log_file()write_to_log_file()以及一个全局文件指针。

调用这些函数时,会按预期创建日志文件(我可以在dir中看到它)。然后调用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
}
}

2 个答案:

答案 0 :(得分:2)

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

阿。因为它是一个无限循环你真的不打算接近。是。刷新缓冲区通常会将数据一直传送到磁盘,这正是我猜你正在追求的。

答案 1 :(得分:2)

需要刷新FILE;否则你的输出只是在内存(文件的缓冲区块)中,直到块被填满,或者你fclose文件指针。这是缓冲的stdio和裸文件句柄之间的区别的一部分。