1 /* portability.c - code to workaround the deficiencies of various platforms.
2  *
3  * Copyright 2012 Rob Landley <rob@landley.net>
4  * Copyright 2012 Georgi Chorbadzhiyski <gf@unixsol.org>
5  */
6 
7 #include "toys.h"
8 
9 #if !defined(__uClinux__)
xfork(void)10 pid_t xfork(void)
11 {
12   pid_t pid = fork();
13 
14   if (pid < 0) perror_exit("fork");
15 
16   return pid;
17 }
18 #endif
19 
20 #if defined(__APPLE__)
getdelim(char ** linep,size_t * np,int delim,FILE * stream)21 ssize_t getdelim(char **linep, size_t *np, int delim, FILE *stream)
22 {
23   int ch;
24   size_t new_len;
25   ssize_t i = 0;
26   char *line, *new_line;
27 
28   // Invalid input
29   if (!linep || !np) {
30     errno = EINVAL;
31     return -1;
32   }
33 
34   if (*linep == NULL || *np == 0) {
35     *np = 1024;
36     *linep = calloc(1, *np);
37     if (*linep == NULL) return -1;
38   }
39   line = *linep;
40 
41   while ((ch = getc(stream)) != EOF) {
42     if (i > *np) {
43       // Need more space
44       new_len = *np + 1024;
45       new_line = realloc(*linep, new_len);
46       if (!new_line) return -1;
47       *np = new_len;
48       line = *linep = new_line;
49     }
50 
51     line[i] = ch;
52     if (ch == delim) break;
53     i += 1;
54   }
55 
56   if (i > *np) {
57     // Need more space
58     new_len  = i + 2;
59     new_line = realloc(*linep, new_len);
60     if (!new_line) return -1;
61     *np = new_len;
62     line = *linep = new_line;
63   }
64   line[i + 1] = '\0';
65 
66   return i > 0 ? i : -1;
67 }
68 
getline(char ** linep,size_t * np,FILE * stream)69 ssize_t getline(char **linep, size_t *np, FILE *stream)
70 {
71   return getdelim(linep, np, '\n', stream);
72 }
73 
74 extern char **environ;
75 
clearenv(void)76 int clearenv(void)
77 {
78   *environ = NULL;
79   return 0;
80 }
81 #endif
82