Last active
August 29, 2015 14:21
-
-
Save dan82840/f96adbddad4e213de413 to your computer and use it in GitHub Desktop.
Execute command in the pthread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <errno.h> | |
static int | |
execute_command(char *cmd) | |
{ | |
pid_t pid; | |
int ret = 0; | |
char * argv[] = {"sh", "-c", cmd, 0}; | |
if ((pid = fork()) < 0) { | |
printf("fork error\n"); | |
ret = -1; | |
} else if (pid == 0) { /* child */ | |
execvp(argv[0], argv); | |
perror(argv[0]); | |
exit(errno); | |
} else { | |
int status; | |
wait(&status); | |
ret = WEXITSTATUS(status); | |
//printf("ret: %d\n", ret); | |
} | |
return ret; | |
} | |
void pexecute_func(void *ptr) | |
{ | |
char *cmd = (char *)ptr; | |
execute_command(cmd); | |
pthread_exit(NULL); | |
} | |
int pexecute(char *cmd) | |
{ | |
pthread_t p_id; | |
int ret = 0; | |
ret = pthread_create(&p_id, NULL, (void *)&pexecute_func, (void *)cmd); | |
if (ret != 0) { | |
printf("create pthread error\n"); | |
ret = 1; | |
} | |
//printf("ret=%d\n", ret); | |
//pthread_join(p_id, NULL); | |
return ret; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int ret = 0; | |
if (argc != 2) { | |
printf("Usage: %s [command]\n", argv[0]); | |
return 1; | |
} | |
ret = pexecute(argv[1]); | |
printf("ret=%d\n", ret); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment