blob: 4da49dd698c31456f66fceda68b4b3c5b8ed670f [file] [log] [blame]
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -05001/* 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
Rob Landley50fc9ed2014-12-04 21:46:59 -06009#if !defined(__uClinux__)
10pid_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
Elliott Hughes6a29bb12014-11-21 21:49:05 -060020#if defined(__APPLE__)
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050021ssize_t getdelim(char **linep, size_t *np, int delim, FILE *stream)
22{
Rob Landley7aa651a2012-11-13 17:14:08 -060023 int ch;
24 size_t new_len;
25 ssize_t i = 0;
26 char *line, *new_line;
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050027
Rob Landley7aa651a2012-11-13 17:14:08 -060028 // Invalid input
29 if (!linep || !np) {
30 errno = EINVAL;
31 return -1;
32 }
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050033
Rob Landley7aa651a2012-11-13 17:14:08 -060034 if (*linep == NULL || *np == 0) {
35 *np = 1024;
36 *linep = calloc(1, *np);
37 if (*linep == NULL) return -1;
38 }
39 line = *linep;
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050040
Rob Landley7aa651a2012-11-13 17:14:08 -060041 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;
Rob Landleycff8e132015-03-21 15:29:21 -050048 line = *linep = new_line;
Rob Landley7aa651a2012-11-13 17:14:08 -060049 }
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050050
Rob Landley7aa651a2012-11-13 17:14:08 -060051 line[i] = ch;
52 if (ch == delim) break;
53 i += 1;
54 }
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050055
Rob Landley7aa651a2012-11-13 17:14:08 -060056 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;
Rob Landleycff8e132015-03-21 15:29:21 -050062 line = *linep = new_line;
Rob Landley7aa651a2012-11-13 17:14:08 -060063 }
64 line[i + 1] = '\0';
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050065
Rob Landley7aa651a2012-11-13 17:14:08 -060066 return i > 0 ? i : -1;
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050067}
68
Rob Landley7aa651a2012-11-13 17:14:08 -060069ssize_t getline(char **linep, size_t *np, FILE *stream)
70{
71 return getdelim(linep, np, '\n', stream);
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050072}
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050073
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050074extern char **environ;
75
Rob Landley7aa651a2012-11-13 17:14:08 -060076int clearenv(void)
77{
78 *environ = NULL;
79 return 0;
Georgi Chorbadzhiyski522d9062012-03-16 06:42:08 -050080}
81#endif