【问题标题】:c - Unable to write data to a file from inside a child processc - 无法从子进程内部将数据写入文件
【发布时间】: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


【解决方案1】:

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

啊。因为它是一个无限循环,你真的不打算关闭。是的。刷新缓冲区通常会将数据一路获取到磁盘,这就是我猜你真正想要的。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多