#include <gio/gio.h>
#include <glib-object.h>
#include <glib/gthread.h>

GCancellable *cancellable;

gboolean thread_func(gpointer stream) {
  char buf[1000000];
  gsize len = 0;
  gboolean succ = g_input_stream_read_all(G_INPUT_STREAM(stream), buf, 1000000,&len, cancellable, NULL);
  if(g_cancellable_is_cancelled(cancellable))
    g_print("interrupted\n",len); 
  g_print("closing...\n");
  g_input_stream_close(G_INPUT_STREAM(stream),NULL,NULL);
  g_print("closed\n");
  return FALSE;
}

int main(int argc,char **argv) {
  if(!g_thread_supported())
    g_thread_init(NULL);
  g_type_init();

  if(argc<2) {
    g_printf("usage: %s uri\n",argv[0]);
    return 1;
  }

  cancellable=g_cancellable_new();
  GFile *file = g_file_new_for_uri(argv[1]);
  GFileInputStream *stream = g_file_read(file,NULL,NULL);
  if(!stream) {
    g_print("can't read\n");
    return 1;
  }
  
  GThread *thread=g_thread_create((GThreadFunc)thread_func,stream,TRUE,NULL);

  usleep(10000);

  g_cancellable_cancel(cancellable);

  g_thread_join(thread);

//  g_main_loop_run(g_main_loop_new(g_main_context_default(),TRUE));
}
