Yes you have used fork()/exec() calls incorrectly.
What fork() does is create another copy of your process, so that you will have two copies of your current process. What is called the parent and the child, note that there are certain things that are not copied to the child process and the child will have its own process id. You have then called execlp(), this is supposed to replace the process with another application, but keeping many details including the process id. execlp() should not return if everything is OK, but if it does you have an error.
What I think has happened is that you have used fork() and that has succeeded in creating two processes. You have then called execlp() but in both cases (yes twice as it is being run in two processes) it has failed probably due to the arguments being passed to it being incorrect. You are now left with two processes trying to run the same GUI and confusing the X11 back end and it now does not know what order to apply the commands.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
void example_run(void)
{
pid_t pid;
pid = fork();
if (pid == 0) {
/* Here we are running as the child */
/* This should replace the child process */
execlp("echo", "echo", "Hello world", (char *) NULL);
printf("Exec failed\n");
_exit(EXIT_FAILURE);
} else if (pid > 0) {
/* Here we are running as the parent */
printf("Fork success\n");
/* Do what you want from here in the original process
* you could pass on the process id, wait on the process id etc
*/
} else {
printf("Fork failed\n");
}
}
As you can see this does make using g_spawn_async() seam simple in comparison. Here is your example corrected (but untested) using g_spawn_async(), and including setting up the arguments correctly. As you can see most of the arguments to the function call is ignored by simply passing a NULL to it. At some point you may want to use these for certain features.
Code:
int run_motor(int posn)
{
printf("Starting motor\n");
printf("Entered position =%i=\n",posn);
if (posn==0)
{
puts("Let's read commands from file");
system("./stepper<data.txt");
}
else
{
gchar *motor_args[6];
puts("Let's move to posn...");
motor_args[0] = "stepper";
motor_args[1] = g_strdup_printf("%i", posn);
motor_args[2] = "1";
motor_args[3] = "0";
motor_args[4] = NULL;
g_spawn_async(NULL, motor_args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL, NULL);
g_free(motor_args[1]);
}
return 0;
}