开发者

"Gtk-WARNING **: cannot open display: " when using execve to launch a Gtk program on ubuntu

I have the following c program which launches a Gtk Program on ubuntu:

#include <unistd.h>

int main( int argc, const char* argv[] )
{
    char *args[2] = { "testarg", 0 };
    char *envp[1] = { 0 };
    execve("/home/michael/MyGtkApp",args,envp);
}

I get "Gtk-WARNING **: cannot open display: " and my program is not launched.

I have tried setting char *envp[1] = {"DISPLAY:0.0"}; and execute 'xhost +' , I don't 开发者_高级运维see the 'cannot open display' warning, but my program is still not launched.

Does anyone know how to fix my problem?

Thank you.


char *envp[1] = {"DISPLAY:0.0"};

Very wrong. Separate name and value by =, and terminate the list by NULL like args.

char *envp[2] = {"DISPLAY=:0.0", 0};

or better yet, don't hard-code the display, and use Xauthority too.

char *display = 0, *xauthority = 0;
char *envp[3] = {0};
asprintf(&display, "DISPLAY=%s", getenv("DISPLAY"));
asprintf(&xauthority, "XAUTHORITY=%s", getenv("XAUTHORITY"));
envp[0] = display;
envp[1] = xauthority;

I'm left wondering why you give the program such a sparse environment, though – depending on how you're configured and what you're using, Gtk+ may not be entirely happy with DBUS_SESSION_BUS_ADDRESS,GTK2_RC_FILES,GTK_IM_MODULE,HOME,LANG*,LC_*,PATH,XDG_* etc. environment variables gone. Why don't you just use execv or execvp, and just allow the parent's environment to be inherited?


I tried setting the envp to this, and it tries to launch my application.

char *envp[2] = { (char*)"DISPLAY=:0.0", 0 };

But I end up with a Segmentation Fault (my program runs fine when I launch it via command prompt:

(gdb) bt
#0  0x007e5f4e in g_main_context_prepare () from /lib/libglib-2.0.so.0
#1  0x007e6351 in ?? () from /lib/libglib-2.0.so.0
#2  0x007e6b9f in g_main_loop_run () from /lib/libglib-2.0.so.0
#3  0x0041b419 in gtk_main () from /usr/lib/libgtk-x11-2.0.so.0
#4  0x08049191 in main (argc=1, argv=0xbffffed4)
    at main.c:471


If you ended up with a segmentation fault in MyGtkApp, your app is buggy and this has nothing to do with the program you posted.

Some suggestions:

  1. I would never use 0 instead of NULL, it is a pain generator on 64 bit platforms: use at least (void *) 0;
  2. no need to specify the array size if you're initializing it;
  3. the first argument is (by convention) always the program name, so:

    char *args[] = { "/home/michael/MyGtkApp", "testarg", (void *) 0 };
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜