How to see if a program is already running

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



The question in the subject line was raised earlier on this list. A simple technique is available for GTK running on Linux/Unix. It doesn't work on Windows, and I don't know if it would work on BeOS. An example program is attached.

1. Compile the program with:

   % gcc -g -o gtk gtk.c `pkg-config gtk+-2.0 --cflags --libs`

2. Start the first instance of the program.

   % ./gtk &

3. Start the second instance of the program. This should produce the message "gtk: already running.".

   % ./gtk
--
---------------------------------------------------------------------------
Mark Leisher
Computing Research Lab            A sneer is the weapon of the weak.
New Mexico State University         -- James Russell Lowell (1819-1891)
Box 30001, MSC 3CRL
Las Cruces, NM  88003
#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>

#ifdef G_OS_UNIX

/*
 * This will only work on an X Window system.
 */

#include <gdk/gdkx.h>

static GdkAtom running = 0;

static gboolean
property_owned(GdkAtom atom)
{
    GdkDisplay *d = gdk_display_get_default();

    return (XGetSelectionOwner(gdk_x11_display_get_xdisplay(d),
                               gdk_x11_atom_to_xatom_for_display(d,atom))
            != None) ? TRUE : FALSE;
}
#endif /* G_OS_UNIX */

static void
done(GtkWidget *widget, gpointer data)
{
    gdk_selection_owner_set(0, running, GDK_CURRENT_TIME, FALSE);
    gtk_main_quit();
    exit(0);
}

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

    gtk_init(&argc, &argv);

#ifdef G_OS_UNIX
    running = gdk_atom_intern("PROG_RUNNING", TRUE);

    if (property_owned(running) != 0) {
        printf("%s: already running.\n", g_get_prgname());
        return 1;
    }
#endif

    w = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    gtk_window_set_title(GTK_WINDOW(w), "Am I Already Running?");
    g_signal_connect(G_OBJECT(w), "destroy", G_CALLBACK(gtk_main_quit), 0);
    g_signal_connect(G_OBJECT(w), "delete_event", G_CALLBACK(gtk_main_quit),0);

    b = gtk_button_new_with_label("Exit");
    gtk_widget_set_size_request(b, 100, 100);
    g_signal_connect(G_OBJECT(b), "clicked", G_CALLBACK(done), 0);
    gtk_container_add(GTK_CONTAINER(w), b);

    gtk_widget_show_all(w);

#ifdef G_OS_UNIX
    /*
     * Own the selection.
     */
    gdk_selection_owner_set(w->window, running, GDK_CURRENT_TIME, TRUE);
#endif

    gtk_main();

    return 0;
}
_______________________________________________

gtk-list@xxxxxxxxx
http://mail.gnome.org/mailman/listinfo/gtk-list

[Index of Archives]     [Touch Screen Library]     [GIMP Users]     [Gnome]     [KDE]     [Yosemite News]     [Steve's Art]

  Powered by Linux