File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2020int safe_cmd (const char *cmd) {
2121 std::vector<char *> argv;
2222
23+ pid_t pid = fork ();
24+ if (pid < 0 ) {
25+ return -1 ;
26+ }
27+
2328 // Copy string to local variable
2429 size_t cmd_len = strlen (cmd) + 1 ;
2530 char *local = static_cast <char *>(malloc (cmd_len));
@@ -28,26 +33,32 @@ int safe_cmd(const char *cmd) {
2833 }
2934 strncpy (local, cmd, cmd_len);
3035
31- char *token = strtok (local, " " );
36+ char *save = nullptr ;
37+ char *token = strtok_r (local, " " , &save);
3238 while (token) {
3339 argv.push_back (token);
34- token = strtok (NULL , " " );
40+ token = strtok_r (NULL , " " , &save );
3541 }
3642 argv.push_back (nullptr );
3743
38- free (local);
39-
40- pid_t pid = fork ();
41- if (pid < 0 ) {
44+ if (argv.size () == 1 ) {
45+ free (local);
4246 return -1 ;
4347 }
48+
4449 if (pid == 0 ) {
4550 execvp (argv[0 ], argv.data ());
46- _exit (127 );
51+ _exit (errno == ENOENT ? 127 : 126 );
4752 }
53+
4854 int status = 0 ;
49- if (waitpid (pid, &status, 0 ) < 0 ) {
55+ pid_t r;
56+ while ((r = waitpid (pid, &status, 0 )) < 0 && errno == EINTR ) {
57+ }
58+ free (local);
59+ if (r < 0 ) {
5060 return -1 ;
5161 }
62+
5263 return WIFEXITED (status) ? WEXITSTATUS (status) : -1 ;
5364}
You can’t perform that action at this time.
0 commit comments