Pregunta

I am given the task of forking n processes.

For each process, it must start an instance of /bin/xterm

I am done with the part of generating n processes and opening the xterm instance.

I got this output when I tried running the program. (Error in bold)

Number of process to open is 1.

Child (1): 3457

/bin/xterm: Xt error: Can't open display:

/bin/xterm: DISPLAY is not set

My code is below.

I tried googleing for the error but I have no luck so far.

Any solutions?

#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;
}
¿Fue útil?

Solución

This little changed code works perfectly fine on my system:

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

Otros consejos

The error was explained in the output you pasted:

 /bin/xterm: DISPLAY is not set

You need to set DISPLAY appropriately. Otherwise, it will have no way to know where to put its display.

Also, did you really want to wait for each child after creating it?

Use

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

Doing so you set the display on your machine.

Sorry I'm late.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top