/* * Forks a program in a thread. */ #include #include #include #include #include void *start(void *arg) { int pid, status; char **av = (char **)arg; printf("Forking in a thread to start %s\n", av[0]); pid = fork(); if (pid == -1) { perror("fork"); exit(1); } if (pid == 0) { execvp(av[0], av); perror("execvp"); exit(1); } printf("Waiting in thread for %s to finish\n", av[0]); if (wait(&status) == -1) { perror("wait"); exit(1); } if (WIFEXITED(status) && WEXITSTATUS(status)) fprintf(stderr, "%s returned nonzero status %d", av[0], WEXITSTATUS(status)); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t thread; int i, rc; char **av; if (argc < 2) { printf("Usage: %s [ ...]\n", argv[0]); exit(0); } /* Build the argument vector for the child */ av = malloc(argc * sizeof(char *)); if (!av) { fprintf(stderr, "%s: no memory\n", argv[0]); exit(1); } for (i = 0; i < argc - 1; ++i) { av[i] = strdup(argv[i + 1]); if (!av[i]) { fprintf(stderr, "%s: no memory\n", argv[0]); exit(1); } } av[argc - 1] = NULL; printf("Main: creating thread for starting %s\n", argv[1]); rc = pthread_create(&thread, NULL, start, (void *)av); if (rc) { fprintf(stderr, "Error: return code from pthread_create() is %d\n", rc); exit(1); } return 0; }