【问题标题】:GTK+ system(3) call with threadGTK+ system(3) 线程调用
【发布时间】:2012-09-13 08:35:18
【问题描述】:

我用 GTK+-2.0 开发了一个简单的应用程序。 我的问题是如何在不冻结程序的情况下运行 bash 脚本(例如使用 system(3))? 我尝试实现一个线程系统,但没有成功。

这是我的代码 sn-p,我尽量简化。 问候

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 );
}    

【问题讨论】:

    标签: c linux multithreading gtk system


    【解决方案1】:

    不要直接拨打fork()

    在 GTK+ 应用程序中,最好使用 glib 的 process spawning API:s。例如,如果您想读取子进程的输出,@987654322@ 函数非常方便。

    【讨论】:

      【解决方案2】:

      尝试分叉您的进程并在分叉的进程中启动 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;
      }
      

      【讨论】:

      • 谢谢,它似乎工作正常。我在 if 块内编写了脚本调用,但是如果块被称为父进程,我应该在 else 中写入什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多