LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   X Error with system()/fork() (https://www.linuxquestions.org/questions/programming-9/x-error-with-system-fork-219365/)

aaa 08-18-2004 02:51 PM

X Error with system()/fork()
 
While running my 'execute' ( execute("echo hi") ) function, I get this error:
Quote:

hi
Xlib: unexpected async reply (sequence 0x2d8)!
system() by itself works without the error, but I want the 'execute' function to run a command and not hang the gui waiting for it to finish.

The execute function:
Code:

void execute(const char *cmd)
{
  switch(fork())
  {
    case -1:
      perror("execute: fork");
      return;
    case 0:
      if (system(cmd) == -1)
        printf("execute: fork failed");
    default:
  }
  return;
}


itsme86 08-18-2004 03:21 PM

Instead of using system() after fork(), try using one of the exec() functions after fork().

kev82 08-18-2004 03:57 PM

or call exit() after youve run the command, although exec would be better. the problem is 2 processes are returning from your function both trying to access the Display* returned by XOpenDisplay which is confusing X.

aaa 08-18-2004 05:05 PM

exec appears more straightforward, but 'execlp("sh", "-c", "du -sh /", NULL)' says 'du -sh /: command not found'. I don't want to seperate the arguments myself as I don't know how many will be entered in.

Anyways, system() by itself with an '&' appears to work, but I keep getting random "Segmentation Fault"s. I think it is because I did not add the '&' properly.

Also, while using fork(), do I have to worry about zombie processes or anything like that?

Here is the function using 'execlp':
Code:

void execute(const char *cmd)
{
  switch(fork()) 
  {
    case -1:
      perror("execute: fork");
      return;
    case 0: 
      if (execlp("sh", "-c ",  cmd, NULL) == -1)
        perror("execute: exec() failed");
      default: 
  }
  return;
}

Here is the function using system() with '&':
Code:

void execute(const char *cmd)
{
  char * copy = malloc(sizeof(cmd) + sizeof(char));
  strcpy(copy, cmd);
  strcat(copy, '&');
  system(copy);
  free(copy);
  return;
}



All times are GMT -5. The time now is 06:11 PM.