00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 #include <stdio.h>
00038 #include <stdlib.h>
00039 #include <unistd.h>
00040 #include <str.h>
00041 #include <fcntl.h>
00042 #include <str_error.h>
00043 #include <errno.h>
00044
00045 #include "config.h"
00046 #include "util.h"
00047 #include "exec.h"
00048 #include "errors.h"
00049
00050
00051 static char *found;
00052
00053 static char *find_command(char *);
00054 static int try_access(const char *);
00055
00056
00057 static int try_access(const char *f)
00058 {
00059 int fd;
00060
00061 fd = open(f, O_RDONLY);
00062 if (fd > -1) {
00063 close(fd);
00064 return 0;
00065 } else
00066 return -1;
00067 }
00068
00069
00070
00071 static char *find_command(char *cmd)
00072 {
00073 char *path_tok;
00074 char *path[PATH_MAX];
00075 int n = 0, i = 0;
00076 size_t x = str_size(cmd) + 2;
00077
00078 found = (char *)malloc(PATH_MAX);
00079
00080
00081 if (-1 != try_access(cmd)) {
00082 return (char *) cmd;
00083 }
00084
00085 path_tok = str_dup(PATH);
00086
00087
00088 path[n] = strtok(path_tok, PATH_DELIM);
00089 while (NULL != path[n]) {
00090 if ((str_size(path[n]) + x ) > PATH_MAX) {
00091 cli_error(CL_ENOTSUP,
00092 "Segment %d of path is too large, search ends at segment %d",
00093 n, n-1);
00094 break;
00095 }
00096 path[++n] = strtok(NULL, PATH_DELIM);
00097 }
00098
00099
00100 for (i=0; path[i]; i++) {
00101 memset(found, 0, sizeof(found));
00102 snprintf(found, PATH_MAX, "%s/%s", path[i], cmd);
00103 if (-1 != try_access(found)) {
00104 free(path_tok);
00105 return (char *) found;
00106 }
00107 }
00108
00109
00110 free(path_tok);
00111 return (char *) cmd;
00112 }
00113
00114 unsigned int try_exec(char *cmd, char **argv)
00115 {
00116 task_id_t tid;
00117 task_exit_t texit;
00118 char *tmp;
00119 int rc, retval;
00120
00121 tmp = str_dup(find_command(cmd));
00122 free(found);
00123
00124 rc = task_spawnv(&tid, tmp, (const char **) argv);
00125 free(tmp);
00126
00127 if (rc != 0) {
00128 cli_error(CL_EEXEC, "%s: Cannot spawn `%s' (%s)", progname, cmd,
00129 str_error(rc));
00130 return 1;
00131 }
00132
00133 rc = task_wait(tid, &texit, &retval);
00134 if (rc != EOK) {
00135 printf("%s: Failed waiting for command (%s)\n", progname,
00136 str_error(rc));
00137 } else if (texit != TASK_EXIT_NORMAL) {
00138 printf("%s: Command failed (unexpectedly terminated)\n", progname);
00139 } else if (retval != 0) {
00140 printf("%s: Command failed (exit code %d)\n",
00141 progname, retval);
00142 }
00143
00144 return 0;
00145 }