代码之家  ›  专栏  ›  技术社区  ›  Lawrence Wong

进程使用fork运行xterm实例时出错

  •  -1
  • Lawrence Wong  · 技术社区  · 10 年前

    我的任务是分叉n个进程。

    对于每个进程,它必须启动/bin/xterm的实例

    我已经完成了生成n个进程和打开xterm实例的部分。

    我在运行程序时得到了这个输出。(粗体错误)

    要打开的进程数为1。

    儿童(1):3457

    /bin/xterm:Xt错误:无法打开显示:

    /bin/xterm:未设置DISPLAY

    我的代码在下面。

    我试着在谷歌上查找错误,但到目前为止我运气不佳。

    有什么解决方案吗?

    #include<stdio.h>
    #include<stdlib.h>
    
    int main(int argc, char *argv[])
    {
        int num = atoi(argv[1]);
        printf("Number of process to open is %d.\n", num);
        int pid;
        int i;
    
        for(i = 0; i < num; i++)
        {
            pid = fork();
            if(pid < 0) {
                printf("Error");
                exit(1);
            } else if (pid == 0) {
                printf("Child (%d): %d\n", i + 1, getpid());
                char * const argv[] = {"/bin/xterm", NULL};
                char * const envp[] = {NULL};
                int rc = execve ("/bin/xterm", argv, envp);
                exit(0); 
            } else  {
                wait(NULL);
            }
        }
        return 0;
    }
    
    3 回复  |  直到 10 年前
        1
  •  0
  •   Nullpointer    10 年前

    这个小改动的代码在我的系统上运行得很好:

        #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    int main(int argc, char *argv[])
    {
        int num = atoi(argv[1]);
        printf("Number of process to open is %d.\n", num);
        int pid;
        int i;
    
        for(i = 0; i < num; i++)
        {
            pid = fork();
            if(pid < 0) {
                printf("Error");
                exit(1);
            } else if (pid == 0) {
          //printf("Child (%d): %d\n", i + 1, getpid());
                //char * const argv[] = {"/bin/xterm", NULL};
                //char * const envp[] = {NULL};
                execl("/usr/bin/xterm", "/usr/bin/xterm", NULL);
                //exit(0); 
            }else  {
                wait(NULL);
            }
        }
        return 0;
    }
    
        2
  •  0
  •   David Schwartz    10 年前

    粘贴的输出中解释了错误:

     /bin/xterm: DISPLAY is not set
    

    你需要设置 DISPLAY 适当地。否则,它将无法知道将其显示器放置在何处。

    还有,你真的想 wait 为每个孩子创建后?

        3
  •  0
  •   Silver18020    2 年前

    使用

    char *envp[] = {"TERM=vt100", "PATH=/bin:/usr/bin", "DISPLAY=:0.0",(char *) 0 };
    

    这样做可以设置机器上的显示。

    对不起,我迟到了。