1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10 #include <sys/types.h>
22 void *xmalloc(size_t size)
24 void *ptr = malloc(size);
25 if (ptr == NULL && size != 0)
26 bb_error_msg_and_die(bb_msg_memory_exhausted);
32 void *xrealloc(void *ptr, size_t size)
34 ptr = realloc(ptr, size);
35 if (ptr == NULL && size != 0)
36 bb_error_msg_and_die(bb_msg_memory_exhausted);
42 void *xzalloc(size_t size)
44 void *ptr = xmalloc(size);
51 void *xcalloc(size_t nmemb, size_t size)
53 void *ptr = calloc(nmemb, size);
54 if (ptr == NULL && nmemb != 0 && size != 0)
55 bb_error_msg_and_die(bb_msg_memory_exhausted);
62 char * bb_xstrdup (const char *s)
72 bb_error_msg_and_die(bb_msg_memory_exhausted);
79 char * bb_xstrndup (const char *s, int n)
84 bb_error_msg_and_die("bb_xstrndup bug");
88 return safe_strncpy(t,s,n);
93 FILE *bb_xfopen(const char *path, const char *mode)
96 if ((fp = fopen(path, mode)) == NULL)
97 bb_perror_msg_and_die("%s", path);
103 int bb_xopen(const char *pathname, int flags)
105 return bb_xopen3(pathname, flags, 0777);
110 int bb_xopen3(const char *pathname, int flags, int mode)
114 ret = open(pathname, flags, mode);
116 bb_perror_msg_and_die("%s", pathname);
123 ssize_t bb_xread(int fd, void *buf, size_t count)
127 size = read(fd, buf, count);
129 bb_perror_msg_and_die(bb_msg_read_error);
136 void bb_xread_all(int fd, void *buf, size_t count)
141 if ((size = bb_xread(fd, buf, count)) == 0) { /* EOF */
142 bb_error_msg_and_die("Short read");
145 buf = ((char *) buf) + size;
152 unsigned char bb_xread_char(int fd)
156 bb_xread_all(fd, &tmp, 1);
163 void bb_xferror(FILE *fp, const char *fn)
166 bb_error_msg_and_die("%s", fn);
171 #ifdef L_xferror_stdout
172 void bb_xferror_stdout(void)
174 bb_xferror(stdout, bb_msg_standard_output);
178 #ifdef L_xfflush_stdout
179 void bb_xfflush_stdout(void)
181 if (fflush(stdout)) {
182 bb_perror_msg_and_die(bb_msg_standard_output);
188 // This does a fork/exec in one call, using vfork().
189 pid_t bb_spawn(char **argv)
193 void *app = find_applet_by_name(argv[0]);
195 // Be nice to nommu machines.
198 if (pid < 0) return pid;
200 execvp(app ? CONFIG_BUSYBOX_EXEC_PATH : *argv, argv);
202 // We're sharing a stack with blocked parent, let parent know we failed
203 // and then exit to unblock parent (but don't run atexit() stuff, which
204 // would screw up parent.)
209 return failed ? failed : pid;
214 pid_t bb_xspawn(char **argv)
216 pid_t pid = bb_spawn(argv);
217 if (pid < 0) bb_perror_msg_and_die("%s", *argv);
223 int wait4pid(int pid)
227 if (pid == -1 || waitpid(pid, &status, 0) == -1) return -1;
228 if (WIFEXITED(status)) return WEXITSTATUS(status);
229 if (WIFSIGNALED(status)) return WTERMSIG(status);