exec/exec_fork.c

Go to the documentation of this file.
00001 // Copyright (C) 2006-2007 Benedikt Böhm <hollow@gentoo.org>
00002 //
00003 // This program is free software; you can redistribute it and/or
00004 // modify it under the terms of the GNU General Public License
00005 // as published by the Free Software Foundation; either version 2
00006 // of the License, or (at your option) any later version.
00007 //
00008 // This program is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011 // GNU General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU General Public License
00014 // along with this program; if not, write to the Free Software
00015 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
00016 
00017 #include <unistd.h>
00018 #include <stdlib.h>
00019 #include <stdarg.h>
00020 #include <sys/wait.h>
00021 
00022 #include "exec.h"
00023 #include "mem.h"
00024 #include "printf.h"
00025 #include "strtok.h"
00026 
00027 int exec_fork(const char *fmt, ...)
00028 {
00029         va_list ap;
00030         va_start(ap, fmt);
00031 
00032         char *cmd;
00033 
00034         if (_lucid_vasprintf(&cmd, fmt, ap) == -1) {
00035                 va_end(ap);
00036                 return -1;
00037         }
00038 
00039         va_end(ap);
00040 
00041         strtok_t _st, *st = &_st;
00042 
00043         if (!strtok_init_str(st, cmd, " ", 0)) {
00044                 mem_free(cmd);
00045                 return -1;
00046         }
00047 
00048         mem_free(cmd);
00049 
00050         int argc    = strtok_count(st);
00051         char **argv = mem_alloc((argc + 1) * sizeof(char *));
00052 
00053         if (!argv) {
00054                 strtok_free(st);
00055                 return -1;
00056         }
00057 
00058         if (strtok_toargv(st, argv) < 1) {
00059                 mem_free(argv);
00060                 strtok_free(st);
00061                 return -1;
00062         }
00063 
00064         pid_t pid;
00065         int status;
00066 
00067         switch ((pid = fork())) {
00068         case -1:
00069                 return -1;
00070 
00071         case 0:
00072                 usleep(200);
00073                 execvp(argv[0], argv);
00074 
00075                 /* never get here */
00076                 exit(1);
00077 
00078         default:
00079                 mem_free(argv);
00080                 strtok_free(st);
00081 
00082                 if (waitpid(pid, &status, 0) == -1)
00083                         return -1;
00084         }
00085 
00086         return status;
00087 }

Generated on Tue Jun 19 20:38:26 2007 for lucid by  doxygen 1.5.2