2012-09-13 101 views
1

我使用GTK + -2.0開發了一個簡單的應用程序。 我的問題是如何在沒有凍結程序的情況下運行bash腳本(例如使用system(3))? 我試圖實現一個線程系統,但它沒有奏效。GTK +系統(3)使用線程調用

這是我的代碼片段,我試圖儘可能簡化。 Regards

int main(int argc, 
    char * argv[]) 
{ 
    GtkWidget *button; 


    /* init threads */ 
    g_thread_init(NULL); 
    gdk_threads_init(); 
    gtk_init(&argc,&argv); 

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL); 
    ... 

    button = gtk_button_new_with_label("Format"); 
    g_signal_connect(button,"clicked",G_CALLBACK(callback),(gpointer)"button 1"); 
    gtk_table_attach_defaults (GTK_TABLE (table), button, 0, 1, 0, 1); 
    gtk_widget_show(button); 


     gdk_threads_enter(); 
    gtk_main(); 
    gdk_threads_leave(); 

    return 0; 

} 

/* Our callback. 
* The data passed to this function is printed to stdout */ 
static void callback(GtkWidget *widget, 
        gpointer data) 
{ 
    int sTemp=0; 
    GThread *thread; 
     GError *error = NULL; 
     g_print ("Hello again - %s was pressed\n", (char *) data); 
     sTemp=ChecckIfFileExits("/dev/mmcblk0"); 
     if(sTemp) 
     { 
     gtk_label_set_text(GTK_LABEL(label),"Formatting"); 
     thread = g_thread_create(PFormatThrad, (gpointer)widget, 
          FALSE, &error); 
     if(! thread) 
     { 
      g_print("Error: %s\n", error->message); 

     } 

    } 
    else 
    { 
     g_print ("SD/MMC not found\n"); 
    } 
} 


static gpointer 
PFormatThrad(gpointer data) 
{ 

     sleep(3); 

     gdk_threads_enter(); 

     system("./mkcard.txt /dev/mmcblk0"); 
    gtk_widget_set_sensitive(selectImageButton,TRUE); 
    gtk_label_set_text(GTK_LABEL(label),"Format tamamlandı\nİmajı Seçin"); 
     gdk_threads_leave(); 

    return(NULL); 
}  

回答

1

嘗試分叉您的進程並在分叉進程中啓動bash腳本。

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 

int main() 
{ 
    int pid; 

    pid = fork(); 

    if (pid == 0) { 
     // Call bash script 
    } else if (pid > 0) { 
    // Your parent process 
    } 
    return 0; 
} 
+0

謝謝,這似乎是工作。我在if block中寫了腳本調用,但是如果block被引用爲父進程,我應該怎麼寫呢? – user1336117