首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GTK+系统(3)使用线程调用

GTK+系统(3)使用线程调用
EN

Stack Overflow用户
提问于 2012-09-13 16:35:19
回答 2查看 654关注 0票数 1

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

这是我的代码片段,我尽量简化。问候

代码语言:javascript
复制
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 );
}    
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-13 16:44:13

不要直接调用fork()

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

票数 7
EN

Stack Overflow用户

发布于 2012-09-13 16:40:00

尝试派生您的流程,并在派生的流程中启动bash脚本。

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12402400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档