rewrite open-process in C, for robustness
[bpt/guile.git] / libguile / posix.c
1 /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
17 */
18
19
20 \f
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #include <uniconv.h>
29
30 #ifdef HAVE_SCHED_H
31 # include <sched.h>
32 #endif
33
34 #include "libguile/_scm.h"
35 #include "libguile/dynwind.h"
36 #include "libguile/fports.h"
37 #include "libguile/scmsigs.h"
38 #include "libguile/feature.h"
39 #include "libguile/strings.h"
40 #include "libguile/srfi-13.h"
41 #include "libguile/srfi-14.h"
42 #include "libguile/vectors.h"
43 #include "libguile/values.h"
44
45 #include "libguile/validate.h"
46 #include "libguile/posix.h"
47 #include "libguile/gettext.h"
48 #include "libguile/threads.h"
49 \f
50
51 #ifdef HAVE_STRING_H
52 #include <string.h>
53 #endif
54 #ifdef TIME_WITH_SYS_TIME
55 # include <sys/time.h>
56 # include <time.h>
57 #else
58 # if HAVE_SYS_TIME_H
59 # include <sys/time.h>
60 # else
61 # include <time.h>
62 # endif
63 #endif
64
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #else
68 #ifndef ttyname
69 extern char *ttyname();
70 #endif
71 #endif
72
73 #ifdef LIBC_H_WITH_UNISTD_H
74 #include <libc.h>
75 #endif
76
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <fcntl.h>
80
81 #ifdef HAVE_PWD_H
82 #include <pwd.h>
83 #endif
84 #ifdef HAVE_IO_H
85 #include <io.h>
86 #endif
87 #ifdef HAVE_WINSOCK2_H
88 #include <winsock2.h>
89 #endif
90
91 #ifdef __MINGW32__
92 /* Some defines for Windows here. */
93 # include <process.h>
94 # define pipe(fd) _pipe (fd, 256, O_BINARY)
95 #endif /* __MINGW32__ */
96
97 #if HAVE_SYS_WAIT_H
98 # include <sys/wait.h>
99 #endif
100 #ifndef WEXITSTATUS
101 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
102 #endif
103 #ifndef WIFEXITED
104 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
105 #endif
106
107 #include <signal.h>
108
109 #ifdef HAVE_GRP_H
110 #include <grp.h>
111 #endif
112 #ifdef HAVE_SYS_UTSNAME_H
113 #include <sys/utsname.h>
114 #endif
115
116 #ifdef HAVE_SETLOCALE
117 #include <locale.h>
118 #endif
119
120 #if (defined HAVE_NEWLOCALE) && (defined HAVE_STRCOLL_L)
121 # define USE_GNU_LOCALE_API
122 #endif
123
124 #if (defined USE_GNU_LOCALE_API) && (defined HAVE_XLOCALE_H)
125 # include <xlocale.h>
126 #endif
127
128 #ifdef HAVE_CRYPT_H
129 # include <crypt.h>
130 #endif
131
132 #ifdef HAVE_NETDB_H
133 #include <netdb.h> /* for MAXHOSTNAMELEN on Solaris */
134 #endif
135
136 #ifdef HAVE_SYS_PARAM_H
137 #include <sys/param.h> /* for MAXHOSTNAMELEN */
138 #endif
139
140 #if HAVE_SYS_RESOURCE_H
141 # include <sys/resource.h>
142 #endif
143
144 #include <sys/file.h> /* from Gnulib */
145
146 /* Some Unix systems don't define these. CPP hair is dangerous, but
147 this seems safe enough... */
148 #ifndef R_OK
149 #define R_OK 4
150 #endif
151
152 #ifndef W_OK
153 #define W_OK 2
154 #endif
155
156 #ifndef X_OK
157 #define X_OK 1
158 #endif
159
160 #ifndef F_OK
161 #define F_OK 0
162 #endif
163
164 /* No prototype for this on Solaris 10. The man page says it's in
165 <unistd.h> ... but it lies. */
166 #if ! HAVE_DECL_SETHOSTNAME
167 int sethostname (char *name, size_t namelen);
168 #endif
169
170 /* On NextStep, <utime.h> doesn't define struct utime, unless we
171 #define _POSIX_SOURCE before #including it. I think this is less
172 of a kludge than defining struct utimbuf ourselves. */
173 #ifdef UTIMBUF_NEEDS_POSIX
174 #define _POSIX_SOURCE
175 #endif
176
177 #ifdef HAVE_SYS_UTIME_H
178 #include <sys/utime.h>
179 #endif
180
181 #ifdef HAVE_UTIME_H
182 #include <utime.h>
183 #endif
184
185 /* Please don't add any more #includes or #defines here. The hack
186 above means that _POSIX_SOURCE may be #defined, which will
187 encourage header files to do strange things.
188
189 FIXME: Maybe should undef _POSIX_SOURCE after it's done its job.
190
191 FIXME: Probably should do all the includes first, then all the fallback
192 declarations and defines, in case things are not in the header we
193 imagine. */
194
195
196
197
198 \f
199
200 /* Two often used patterns
201 */
202
203 #define WITH_STRING(str,cstr,code) \
204 do { \
205 char *cstr = scm_to_locale_string (str); \
206 code; \
207 free (cstr); \
208 } while (0)
209
210 #define STRING_SYSCALL(str,cstr,code) \
211 do { \
212 int eno; \
213 char *cstr = scm_to_locale_string (str); \
214 SCM_SYSCALL (code); \
215 eno = errno; free (cstr); errno = eno; \
216 } while (0)
217
218
219 \f
220 SCM_SYMBOL (sym_read_pipe, "read pipe");
221 SCM_SYMBOL (sym_write_pipe, "write pipe");
222
223 SCM_DEFINE (scm_pipe, "pipe", 0, 0, 0,
224 (),
225 "Return a newly created pipe: a pair of ports which are linked\n"
226 "together on the local machine. The @emph{car} is the input\n"
227 "port and the @emph{cdr} is the output port. Data written (and\n"
228 "flushed) to the output port can be read from the input port.\n"
229 "Pipes are commonly used for communication with a newly forked\n"
230 "child process. The need to flush the output port can be\n"
231 "avoided by making it unbuffered using @code{setvbuf}.\n"
232 "\n"
233 "Writes occur atomically provided the size of the data in bytes\n"
234 "is not greater than the value of @code{PIPE_BUF}. Note that\n"
235 "the output port is likely to block if too much data (typically\n"
236 "equal to @code{PIPE_BUF}) has been written but not yet read\n"
237 "from the input port.")
238 #define FUNC_NAME s_scm_pipe
239 {
240 int fd[2], rv;
241 SCM p_rd, p_wt;
242
243 rv = pipe (fd);
244 if (rv)
245 SCM_SYSERROR;
246
247 p_rd = scm_fdes_to_port (fd[0], "r", sym_read_pipe);
248 p_wt = scm_fdes_to_port (fd[1], "w", sym_write_pipe);
249 return scm_cons (p_rd, p_wt);
250 }
251 #undef FUNC_NAME
252
253
254 #ifdef HAVE_GETGROUPS
255 SCM_DEFINE (scm_getgroups, "getgroups", 0, 0, 0,
256 (),
257 "Return a vector of integers representing the current\n"
258 "supplementary group IDs.")
259 #define FUNC_NAME s_scm_getgroups
260 {
261 SCM result;
262 int ngroups;
263 size_t size;
264 GETGROUPS_T *groups;
265
266 ngroups = getgroups (0, NULL);
267 if (ngroups <= 0)
268 SCM_SYSERROR;
269
270 size = ngroups * sizeof (GETGROUPS_T);
271 groups = scm_malloc (size);
272 ngroups = getgroups (ngroups, groups);
273
274 result = scm_c_make_vector (ngroups, SCM_BOOL_F);
275 while (--ngroups >= 0)
276 SCM_SIMPLE_VECTOR_SET (result, ngroups, scm_from_ulong (groups[ngroups]));
277
278 free (groups);
279 return result;
280 }
281 #undef FUNC_NAME
282 #endif
283
284 #ifdef HAVE_SETGROUPS
285 SCM_DEFINE (scm_setgroups, "setgroups", 1, 0, 0,
286 (SCM group_vec),
287 "Set the current set of supplementary group IDs to the integers\n"
288 "in the given vector @var{group_vec}. The return value is\n"
289 "unspecified.\n"
290 "\n"
291 "Generally only the superuser can set the process group IDs.")
292 #define FUNC_NAME s_scm_setgroups
293 {
294 size_t ngroups;
295 size_t size;
296 size_t i;
297 int result;
298 int save_errno;
299 GETGROUPS_T *groups;
300
301 SCM_VALIDATE_VECTOR (SCM_ARG1, group_vec);
302
303 ngroups = SCM_SIMPLE_VECTOR_LENGTH (group_vec);
304
305 /* validate before allocating, so we don't have to worry about leaks */
306 for (i = 0; i < ngroups; i++)
307 {
308 unsigned long ulong_gid;
309 GETGROUPS_T gid;
310 SCM_VALIDATE_ULONG_COPY (1, SCM_SIMPLE_VECTOR_REF (group_vec, i),
311 ulong_gid);
312 gid = ulong_gid;
313 if (gid != ulong_gid)
314 SCM_OUT_OF_RANGE (1, SCM_SIMPLE_VECTOR_REF (group_vec, i));
315 }
316
317 size = ngroups * sizeof (GETGROUPS_T);
318 if (size / sizeof (GETGROUPS_T) != ngroups)
319 SCM_OUT_OF_RANGE (SCM_ARG1, scm_from_int (ngroups));
320 groups = scm_malloc (size);
321 for(i = 0; i < ngroups; i++)
322 groups [i] = SCM_NUM2ULONG (1, SCM_SIMPLE_VECTOR_REF (group_vec, i));
323
324 result = setgroups (ngroups, groups);
325 save_errno = errno; /* don't let free() touch errno */
326 free (groups);
327 errno = save_errno;
328 if (result < 0)
329 SCM_SYSERROR;
330 return SCM_UNSPECIFIED;
331 }
332 #undef FUNC_NAME
333 #endif
334
335 #ifdef HAVE_GETPWENT
336 SCM_DEFINE (scm_getpwuid, "getpw", 0, 1, 0,
337 (SCM user),
338 "Look up an entry in the user database. @var{user} can be an\n"
339 "integer, a string, or omitted, giving the behaviour of\n"
340 "@code{getpwuid}, @code{getpwnam} or @code{getpwent}\n"
341 "respectively.")
342 #define FUNC_NAME s_scm_getpwuid
343 {
344 struct passwd *entry;
345
346 SCM result = scm_c_make_vector (7, SCM_UNSPECIFIED);
347 if (SCM_UNBNDP (user) || scm_is_false (user))
348 {
349 SCM_SYSCALL (entry = getpwent ());
350 if (! entry)
351 {
352 return SCM_BOOL_F;
353 }
354 }
355 else if (scm_is_integer (user))
356 {
357 entry = getpwuid (scm_to_int (user));
358 }
359 else
360 {
361 WITH_STRING (user, c_user,
362 entry = getpwnam (c_user));
363 }
364 if (!entry)
365 SCM_MISC_ERROR ("entry not found", SCM_EOL);
366
367 SCM_SIMPLE_VECTOR_SET(result, 0, scm_from_locale_string (entry->pw_name));
368 SCM_SIMPLE_VECTOR_SET(result, 1, scm_from_locale_string (entry->pw_passwd));
369 SCM_SIMPLE_VECTOR_SET(result, 2, scm_from_ulong (entry->pw_uid));
370 SCM_SIMPLE_VECTOR_SET(result, 3, scm_from_ulong (entry->pw_gid));
371 SCM_SIMPLE_VECTOR_SET(result, 4, scm_from_locale_string (entry->pw_gecos));
372 if (!entry->pw_dir)
373 SCM_SIMPLE_VECTOR_SET(result, 5, scm_from_locale_string (""));
374 else
375 SCM_SIMPLE_VECTOR_SET(result, 5, scm_from_locale_string (entry->pw_dir));
376 if (!entry->pw_shell)
377 SCM_SIMPLE_VECTOR_SET(result, 6, scm_from_locale_string (""));
378 else
379 SCM_SIMPLE_VECTOR_SET(result, 6, scm_from_locale_string (entry->pw_shell));
380 return result;
381 }
382 #undef FUNC_NAME
383 #endif /* HAVE_GETPWENT */
384
385
386 #ifdef HAVE_SETPWENT
387 SCM_DEFINE (scm_setpwent, "setpw", 0, 1, 0,
388 (SCM arg),
389 "If called with a true argument, initialize or reset the password data\n"
390 "stream. Otherwise, close the stream. The @code{setpwent} and\n"
391 "@code{endpwent} procedures are implemented on top of this.")
392 #define FUNC_NAME s_scm_setpwent
393 {
394 if (SCM_UNBNDP (arg) || scm_is_false (arg))
395 endpwent ();
396 else
397 setpwent ();
398 return SCM_UNSPECIFIED;
399 }
400 #undef FUNC_NAME
401 #endif
402
403
404 #ifdef HAVE_GETGRENT
405 /* Combines getgrgid and getgrnam. */
406 SCM_DEFINE (scm_getgrgid, "getgr", 0, 1, 0,
407 (SCM name),
408 "Look up an entry in the group database. @var{name} can be an\n"
409 "integer, a string, or omitted, giving the behaviour of\n"
410 "@code{getgrgid}, @code{getgrnam} or @code{getgrent}\n"
411 "respectively.")
412 #define FUNC_NAME s_scm_getgrgid
413 {
414 struct group *entry;
415 SCM result = scm_c_make_vector (4, SCM_UNSPECIFIED);
416
417 if (SCM_UNBNDP (name) || scm_is_false (name))
418 {
419 SCM_SYSCALL (entry = getgrent ());
420 if (! entry)
421 {
422 return SCM_BOOL_F;
423 }
424 }
425 else if (scm_is_integer (name))
426 SCM_SYSCALL (entry = getgrgid (scm_to_int (name)));
427 else
428 STRING_SYSCALL (name, c_name,
429 entry = getgrnam (c_name));
430 if (!entry)
431 SCM_SYSERROR;
432
433 SCM_SIMPLE_VECTOR_SET(result, 0, scm_from_locale_string (entry->gr_name));
434 SCM_SIMPLE_VECTOR_SET(result, 1, scm_from_locale_string (entry->gr_passwd));
435 SCM_SIMPLE_VECTOR_SET(result, 2, scm_from_ulong (entry->gr_gid));
436 SCM_SIMPLE_VECTOR_SET(result, 3, scm_makfromstrs (-1, entry->gr_mem));
437 return result;
438 }
439 #undef FUNC_NAME
440
441
442
443 SCM_DEFINE (scm_setgrent, "setgr", 0, 1, 0,
444 (SCM arg),
445 "If called with a true argument, initialize or reset the group data\n"
446 "stream. Otherwise, close the stream. The @code{setgrent} and\n"
447 "@code{endgrent} procedures are implemented on top of this.")
448 #define FUNC_NAME s_scm_setgrent
449 {
450 if (SCM_UNBNDP (arg) || scm_is_false (arg))
451 endgrent ();
452 else
453 setgrent ();
454 return SCM_UNSPECIFIED;
455 }
456 #undef FUNC_NAME
457 #endif /* HAVE_GETGRENT */
458
459
460 #ifdef HAVE_GETRLIMIT
461 #ifdef RLIMIT_AS
462 SCM_SYMBOL (sym_as, "as");
463 #endif
464 #ifdef RLIMIT_CORE
465 SCM_SYMBOL (sym_core, "core");
466 #endif
467 #ifdef RLIMIT_CPU
468 SCM_SYMBOL (sym_cpu, "cpu");
469 #endif
470 #ifdef RLIMIT_DATA
471 SCM_SYMBOL (sym_data, "data");
472 #endif
473 #ifdef RLIMIT_FSIZE
474 SCM_SYMBOL (sym_fsize, "fsize");
475 #endif
476 #ifdef RLIMIT_MEMLOCK
477 SCM_SYMBOL (sym_memlock, "memlock");
478 #endif
479 #ifdef RLIMIT_MSGQUEUE
480 SCM_SYMBOL (sym_msgqueue, "msgqueue");
481 #endif
482 #ifdef RLIMIT_NICE
483 SCM_SYMBOL (sym_nice, "nice");
484 #endif
485 #ifdef RLIMIT_NOFILE
486 SCM_SYMBOL (sym_nofile, "nofile");
487 #endif
488 #ifdef RLIMIT_NPROC
489 SCM_SYMBOL (sym_nproc, "nproc");
490 #endif
491 #ifdef RLIMIT_RSS
492 SCM_SYMBOL (sym_rss, "rss");
493 #endif
494 #ifdef RLIMIT_RTPRIO
495 SCM_SYMBOL (sym_rtprio, "rtprio");
496 #endif
497 #ifdef RLIMIT_RTPRIO
498 SCM_SYMBOL (sym_rttime, "rttime");
499 #endif
500 #ifdef RLIMIT_SIGPENDING
501 SCM_SYMBOL (sym_sigpending, "sigpending");
502 #endif
503 #ifdef RLIMIT_STACK
504 SCM_SYMBOL (sym_stack, "stack");
505 #endif
506
507 static int
508 scm_to_resource (SCM s, const char *func, int pos)
509 {
510 if (scm_is_number (s))
511 return scm_to_int (s);
512
513 SCM_ASSERT_TYPE (scm_is_symbol (s), s, pos, func, "symbol");
514
515 #ifdef RLIMIT_AS
516 if (scm_is_eq (s, sym_as))
517 return RLIMIT_AS;
518 #endif
519 #ifdef RLIMIT_CORE
520 if (scm_is_eq (s, sym_core))
521 return RLIMIT_CORE;
522 #endif
523 #ifdef RLIMIT_CPU
524 if (scm_is_eq (s, sym_cpu))
525 return RLIMIT_CPU;
526 #endif
527 #ifdef RLIMIT_DATA
528 if (scm_is_eq (s, sym_data))
529 return RLIMIT_DATA;
530 #endif
531 #ifdef RLIMIT_FSIZE
532 if (scm_is_eq (s, sym_fsize))
533 return RLIMIT_FSIZE;
534 #endif
535 #ifdef RLIMIT_MEMLOCK
536 if (scm_is_eq (s, sym_memlock))
537 return RLIMIT_MEMLOCK;
538 #endif
539 #ifdef RLIMIT_MSGQUEUE
540 if (scm_is_eq (s, sym_msgqueue))
541 return RLIMIT_MSGQUEUE;
542 #endif
543 #ifdef RLIMIT_NICE
544 if (scm_is_eq (s, sym_nice))
545 return RLIMIT_NICE;
546 #endif
547 #ifdef RLIMIT_NOFILE
548 if (scm_is_eq (s, sym_nofile))
549 return RLIMIT_NOFILE;
550 #endif
551 #ifdef RLIMIT_NPROC
552 if (scm_is_eq (s, sym_nproc))
553 return RLIMIT_NPROC;
554 #endif
555 #ifdef RLIMIT_RSS
556 if (scm_is_eq (s, sym_rss))
557 return RLIMIT_RSS;
558 #endif
559 #ifdef RLIMIT_RTPRIO
560 if (scm_is_eq (s, sym_rtprio))
561 return RLIMIT_RTPRIO;
562 #endif
563 #ifdef RLIMIT_RTPRIO
564 if (scm_is_eq (s, sym_rttime))
565 return RLIMIT_RTPRIO;
566 #endif
567 #ifdef RLIMIT_SIGPENDING
568 if (scm_is_eq (s, sym_sigpending))
569 return RLIMIT_SIGPENDING;
570 #endif
571 #ifdef RLIMIT_STACK
572 if (scm_is_eq (s, sym_stack))
573 return RLIMIT_STACK;
574 #endif
575
576 scm_misc_error (func, "invalid rlimit resource ~A", scm_list_1 (s));
577 return 0;
578 }
579
580 SCM_DEFINE (scm_getrlimit, "getrlimit", 1, 0, 0,
581 (SCM resource),
582 "Get a resource limit for this process. @var{resource} identifies the resource,\n"
583 "either as an integer or as a symbol. For example, @code{(getrlimit 'stack)}\n"
584 "gets the limits associated with @code{RLIMIT_STACK}.\n\n"
585 "@code{getrlimit} returns two values, the soft and the hard limit. If no\n"
586 "limit is set for the resource in question, the returned limit will be @code{#f}.")
587 #define FUNC_NAME s_scm_getrlimit
588 {
589 int iresource;
590 struct rlimit lim = { 0, 0 };
591
592 iresource = scm_to_resource (resource, FUNC_NAME, 1);
593
594 if (getrlimit (iresource, &lim) != 0)
595 scm_syserror (FUNC_NAME);
596
597 return scm_values (scm_list_2 ((lim.rlim_cur == RLIM_INFINITY) ? SCM_BOOL_F
598 : scm_from_long (lim.rlim_cur),
599 (lim.rlim_max == RLIM_INFINITY) ? SCM_BOOL_F
600 : scm_from_long (lim.rlim_max)));
601 }
602 #undef FUNC_NAME
603
604
605 #ifdef HAVE_SETRLIMIT
606 SCM_DEFINE (scm_setrlimit, "setrlimit", 3, 0, 0,
607 (SCM resource, SCM soft, SCM hard),
608 "Set a resource limit for this process. @var{resource} identifies the resource,\n"
609 "either as an integer or as a symbol. @var{soft} and @var{hard} should be integers,\n"
610 "or @code{#f} to indicate no limit (i.e., @code{RLIM_INFINITY}).\n\n"
611 "For example, @code{(setrlimit 'stack 150000 300000)} sets the @code{RLIMIT_STACK}\n"
612 "limit to 150 kilobytes, with a hard limit of 300 kB.")
613 #define FUNC_NAME s_scm_setrlimit
614 {
615 int iresource;
616 struct rlimit lim = { 0, 0 };
617
618 iresource = scm_to_resource (resource, FUNC_NAME, 1);
619
620 lim.rlim_cur = scm_is_false (soft) ? RLIM_INFINITY : scm_to_long (soft);
621 lim.rlim_max = scm_is_false (hard) ? RLIM_INFINITY : scm_to_long (hard);
622
623 if (setrlimit (iresource, &lim) != 0)
624 scm_syserror (FUNC_NAME);
625
626 return SCM_UNSPECIFIED;
627 }
628 #undef FUNC_NAME
629 #endif /* HAVE_SETRLIMIT */
630 #endif /* HAVE_GETRLIMIT */
631
632
633 SCM_DEFINE (scm_kill, "kill", 2, 0, 0,
634 (SCM pid, SCM sig),
635 "Sends a signal to the specified process or group of processes.\n\n"
636 "@var{pid} specifies the processes to which the signal is sent:\n\n"
637 "@table @r\n"
638 "@item @var{pid} greater than 0\n"
639 "The process whose identifier is @var{pid}.\n"
640 "@item @var{pid} equal to 0\n"
641 "All processes in the current process group.\n"
642 "@item @var{pid} less than -1\n"
643 "The process group whose identifier is -@var{pid}\n"
644 "@item @var{pid} equal to -1\n"
645 "If the process is privileged, all processes except for some special\n"
646 "system processes. Otherwise, all processes with the current effective\n"
647 "user ID.\n"
648 "@end table\n\n"
649 "@var{sig} should be specified using a variable corresponding to\n"
650 "the Unix symbolic name, e.g.,\n\n"
651 "@defvar SIGHUP\n"
652 "Hang-up signal.\n"
653 "@end defvar\n\n"
654 "@defvar SIGINT\n"
655 "Interrupt signal.\n"
656 "@end defvar")
657 #define FUNC_NAME s_scm_kill
658 {
659 /* Signal values are interned in scm_init_posix(). */
660 #ifdef HAVE_KILL
661 if (kill (scm_to_int (pid), scm_to_int (sig)) != 0)
662 SCM_SYSERROR;
663 #else
664 /* Mingw has raise(), but not kill(). (Other raw DOS environments might
665 be similar.) Use raise() when the requested pid is our own process,
666 otherwise bomb. */
667 if (scm_to_int (pid) == getpid ())
668 {
669 if (raise (scm_to_int (sig)) != 0)
670 {
671 err:
672 SCM_SYSERROR;
673 }
674 else
675 {
676 errno = ENOSYS;
677 goto err;
678 }
679 }
680 #endif
681 return SCM_UNSPECIFIED;
682 }
683 #undef FUNC_NAME
684
685 #ifdef HAVE_WAITPID
686 SCM_DEFINE (scm_waitpid, "waitpid", 1, 1, 0,
687 (SCM pid, SCM options),
688 "This procedure collects status information from a child process which\n"
689 "has terminated or (optionally) stopped. Normally it will\n"
690 "suspend the calling process until this can be done. If more than one\n"
691 "child process is eligible then one will be chosen by the operating system.\n\n"
692 "The value of @var{pid} determines the behaviour:\n\n"
693 "@table @r\n"
694 "@item @var{pid} greater than 0\n"
695 "Request status information from the specified child process.\n"
696 "@item @var{pid} equal to -1 or WAIT_ANY\n"
697 "Request status information for any child process.\n"
698 "@item @var{pid} equal to 0 or WAIT_MYPGRP\n"
699 "Request status information for any child process in the current process\n"
700 "group.\n"
701 "@item @var{pid} less than -1\n"
702 "Request status information for any child process whose process group ID\n"
703 "is -@var{pid}.\n"
704 "@end table\n\n"
705 "The @var{options} argument, if supplied, should be the bitwise OR of the\n"
706 "values of zero or more of the following variables:\n\n"
707 "@defvar WNOHANG\n"
708 "Return immediately even if there are no child processes to be collected.\n"
709 "@end defvar\n\n"
710 "@defvar WUNTRACED\n"
711 "Report status information for stopped processes as well as terminated\n"
712 "processes.\n"
713 "@end defvar\n\n"
714 "The return value is a pair containing:\n\n"
715 "@enumerate\n"
716 "@item\n"
717 "The process ID of the child process, or 0 if @code{WNOHANG} was\n"
718 "specified and no process was collected.\n"
719 "@item\n"
720 "The integer status value.\n"
721 "@end enumerate")
722 #define FUNC_NAME s_scm_waitpid
723 {
724 int i;
725 int status;
726 int ioptions;
727 if (SCM_UNBNDP (options))
728 ioptions = 0;
729 else
730 {
731 /* Flags are interned in scm_init_posix. */
732 ioptions = scm_to_int (options);
733 }
734 SCM_SYSCALL (i = waitpid (scm_to_int (pid), &status, ioptions));
735 if (i == -1)
736 SCM_SYSERROR;
737 return scm_cons (scm_from_int (i), scm_from_int (status));
738 }
739 #undef FUNC_NAME
740 #endif /* HAVE_WAITPID */
741
742 #ifndef __MINGW32__
743 SCM_DEFINE (scm_status_exit_val, "status:exit-val", 1, 0, 0,
744 (SCM status),
745 "Return the exit status value, as would be set if a process\n"
746 "ended normally through a call to @code{exit} or @code{_exit},\n"
747 "if any, otherwise @code{#f}.")
748 #define FUNC_NAME s_scm_status_exit_val
749 {
750 int lstatus;
751
752 /* On Ultrix, the WIF... macros assume their argument is an lvalue;
753 go figure. */
754 lstatus = scm_to_int (status);
755 if (WIFEXITED (lstatus))
756 return (scm_from_int (WEXITSTATUS (lstatus)));
757 else
758 return SCM_BOOL_F;
759 }
760 #undef FUNC_NAME
761
762 SCM_DEFINE (scm_status_term_sig, "status:term-sig", 1, 0, 0,
763 (SCM status),
764 "Return the signal number which terminated the process, if any,\n"
765 "otherwise @code{#f}.")
766 #define FUNC_NAME s_scm_status_term_sig
767 {
768 int lstatus;
769
770 lstatus = scm_to_int (status);
771 if (WIFSIGNALED (lstatus))
772 return scm_from_int (WTERMSIG (lstatus));
773 else
774 return SCM_BOOL_F;
775 }
776 #undef FUNC_NAME
777
778 SCM_DEFINE (scm_status_stop_sig, "status:stop-sig", 1, 0, 0,
779 (SCM status),
780 "Return the signal number which stopped the process, if any,\n"
781 "otherwise @code{#f}.")
782 #define FUNC_NAME s_scm_status_stop_sig
783 {
784 int lstatus;
785
786 lstatus = scm_to_int (status);
787 if (WIFSTOPPED (lstatus))
788 return scm_from_int (WSTOPSIG (lstatus));
789 else
790 return SCM_BOOL_F;
791 }
792 #undef FUNC_NAME
793 #endif /* __MINGW32__ */
794
795 #ifdef HAVE_GETPPID
796 SCM_DEFINE (scm_getppid, "getppid", 0, 0, 0,
797 (),
798 "Return an integer representing the process ID of the parent\n"
799 "process.")
800 #define FUNC_NAME s_scm_getppid
801 {
802 return scm_from_int (getppid ());
803 }
804 #undef FUNC_NAME
805 #endif /* HAVE_GETPPID */
806
807
808 #ifndef __MINGW32__
809 SCM_DEFINE (scm_getuid, "getuid", 0, 0, 0,
810 (),
811 "Return an integer representing the current real user ID.")
812 #define FUNC_NAME s_scm_getuid
813 {
814 return scm_from_int (getuid ());
815 }
816 #undef FUNC_NAME
817
818
819
820 SCM_DEFINE (scm_getgid, "getgid", 0, 0, 0,
821 (),
822 "Return an integer representing the current real group ID.")
823 #define FUNC_NAME s_scm_getgid
824 {
825 return scm_from_int (getgid ());
826 }
827 #undef FUNC_NAME
828
829
830
831 SCM_DEFINE (scm_geteuid, "geteuid", 0, 0, 0,
832 (),
833 "Return an integer representing the current effective user ID.\n"
834 "If the system does not support effective IDs, then the real ID\n"
835 "is returned. @code{(provided? 'EIDs)} reports whether the\n"
836 "system supports effective IDs.")
837 #define FUNC_NAME s_scm_geteuid
838 {
839 #ifdef HAVE_GETEUID
840 return scm_from_int (geteuid ());
841 #else
842 return scm_from_int (getuid ());
843 #endif
844 }
845 #undef FUNC_NAME
846
847
848 SCM_DEFINE (scm_getegid, "getegid", 0, 0, 0,
849 (),
850 "Return an integer representing the current effective group ID.\n"
851 "If the system does not support effective IDs, then the real ID\n"
852 "is returned. @code{(provided? 'EIDs)} reports whether the\n"
853 "system supports effective IDs.")
854 #define FUNC_NAME s_scm_getegid
855 {
856 #ifdef HAVE_GETEUID
857 return scm_from_int (getegid ());
858 #else
859 return scm_from_int (getgid ());
860 #endif
861 }
862 #undef FUNC_NAME
863
864
865 SCM_DEFINE (scm_setuid, "setuid", 1, 0, 0,
866 (SCM id),
867 "Sets both the real and effective user IDs to the integer @var{id}, provided\n"
868 "the process has appropriate privileges.\n"
869 "The return value is unspecified.")
870 #define FUNC_NAME s_scm_setuid
871 {
872 if (setuid (scm_to_int (id)) != 0)
873 SCM_SYSERROR;
874 return SCM_UNSPECIFIED;
875 }
876 #undef FUNC_NAME
877
878 SCM_DEFINE (scm_setgid, "setgid", 1, 0, 0,
879 (SCM id),
880 "Sets both the real and effective group IDs to the integer @var{id}, provided\n"
881 "the process has appropriate privileges.\n"
882 "The return value is unspecified.")
883 #define FUNC_NAME s_scm_setgid
884 {
885 if (setgid (scm_to_int (id)) != 0)
886 SCM_SYSERROR;
887 return SCM_UNSPECIFIED;
888 }
889 #undef FUNC_NAME
890
891 SCM_DEFINE (scm_seteuid, "seteuid", 1, 0, 0,
892 (SCM id),
893 "Sets the effective user ID to the integer @var{id}, provided the process\n"
894 "has appropriate privileges. If effective IDs are not supported, the\n"
895 "real ID is set instead -- @code{(provided? 'EIDs)} reports whether the\n"
896 "system supports effective IDs.\n"
897 "The return value is unspecified.")
898 #define FUNC_NAME s_scm_seteuid
899 {
900 int rv;
901
902 #ifdef HAVE_SETEUID
903 rv = seteuid (scm_to_int (id));
904 #else
905 rv = setuid (scm_to_int (id));
906 #endif
907 if (rv != 0)
908 SCM_SYSERROR;
909 return SCM_UNSPECIFIED;
910 }
911 #undef FUNC_NAME
912 #endif /* __MINGW32__ */
913
914
915 #ifdef HAVE_SETEGID
916 SCM_DEFINE (scm_setegid, "setegid", 1, 0, 0,
917 (SCM id),
918 "Sets the effective group ID to the integer @var{id}, provided the process\n"
919 "has appropriate privileges. If effective IDs are not supported, the\n"
920 "real ID is set instead -- @code{(provided? 'EIDs)} reports whether the\n"
921 "system supports effective IDs.\n"
922 "The return value is unspecified.")
923 #define FUNC_NAME s_scm_setegid
924 {
925 int rv;
926
927 #ifdef HAVE_SETEUID
928 rv = setegid (scm_to_int (id));
929 #else
930 rv = setgid (scm_to_int (id));
931 #endif
932 if (rv != 0)
933 SCM_SYSERROR;
934 return SCM_UNSPECIFIED;
935
936 }
937 #undef FUNC_NAME
938 #endif
939
940
941 #ifdef HAVE_GETPGRP
942 SCM_DEFINE (scm_getpgrp, "getpgrp", 0, 0, 0,
943 (),
944 "Return an integer representing the current process group ID.\n"
945 "This is the POSIX definition, not BSD.")
946 #define FUNC_NAME s_scm_getpgrp
947 {
948 int (*fn)();
949 fn = (int (*) ()) getpgrp;
950 return scm_from_int (fn (0));
951 }
952 #undef FUNC_NAME
953 #endif /* HAVE_GETPGRP */
954
955
956 #ifdef HAVE_SETPGID
957 SCM_DEFINE (scm_setpgid, "setpgid", 2, 0, 0,
958 (SCM pid, SCM pgid),
959 "Move the process @var{pid} into the process group @var{pgid}. @var{pid} or\n"
960 "@var{pgid} must be integers: they can be zero to indicate the ID of the\n"
961 "current process.\n"
962 "Fails on systems that do not support job control.\n"
963 "The return value is unspecified.")
964 #define FUNC_NAME s_scm_setpgid
965 {
966 /* FIXME(?): may be known as setpgrp. */
967 if (setpgid (scm_to_int (pid), scm_to_int (pgid)) != 0)
968 SCM_SYSERROR;
969 return SCM_UNSPECIFIED;
970 }
971 #undef FUNC_NAME
972 #endif /* HAVE_SETPGID */
973
974 #ifdef HAVE_SETSID
975 SCM_DEFINE (scm_setsid, "setsid", 0, 0, 0,
976 (),
977 "Creates a new session. The current process becomes the session leader\n"
978 "and is put in a new process group. The process will be detached\n"
979 "from its controlling terminal if it has one.\n"
980 "The return value is an integer representing the new process group ID.")
981 #define FUNC_NAME s_scm_setsid
982 {
983 pid_t sid = setsid ();
984 if (sid == -1)
985 SCM_SYSERROR;
986 return SCM_UNSPECIFIED;
987 }
988 #undef FUNC_NAME
989 #endif /* HAVE_SETSID */
990
991 #ifdef HAVE_GETSID
992 SCM_DEFINE (scm_getsid, "getsid", 1, 0, 0,
993 (SCM pid),
994 "Returns the session ID of process @var{pid}. (The session\n"
995 "ID of a process is the process group ID of its session leader.)")
996 #define FUNC_NAME s_scm_getsid
997 {
998 return scm_from_int (getsid (scm_to_int (pid)));
999 }
1000 #undef FUNC_NAME
1001 #endif /* HAVE_GETSID */
1002
1003
1004 /* ttyname returns its result in a single static buffer, hence
1005 scm_i_misc_mutex for thread safety. In glibc 2.3.2 two threads
1006 continuously calling ttyname will otherwise get an overwrite quite
1007 easily.
1008
1009 ttyname_r (when available) could be used instead of scm_i_misc_mutex, but
1010 there's probably little to be gained in either speed or parallelism. */
1011
1012 #ifdef HAVE_TTYNAME
1013 SCM_DEFINE (scm_ttyname, "ttyname", 1, 0, 0,
1014 (SCM port),
1015 "Return a string with the name of the serial terminal device\n"
1016 "underlying @var{port}.")
1017 #define FUNC_NAME s_scm_ttyname
1018 {
1019 char *result;
1020 int fd, err;
1021 SCM ret = SCM_BOOL_F;
1022
1023 port = SCM_COERCE_OUTPORT (port);
1024 SCM_VALIDATE_OPPORT (1, port);
1025 if (!SCM_FPORTP (port))
1026 return SCM_BOOL_F;
1027 fd = SCM_FPORT_FDES (port);
1028
1029 scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
1030
1031 SCM_SYSCALL (result = ttyname (fd));
1032 err = errno;
1033 if (result != NULL)
1034 result = strdup (result);
1035
1036 scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
1037
1038 if (!result)
1039 {
1040 errno = err;
1041 SCM_SYSERROR;
1042 }
1043 else
1044 ret = scm_take_locale_string (result);
1045
1046 return ret;
1047 }
1048 #undef FUNC_NAME
1049 #endif /* HAVE_TTYNAME */
1050
1051
1052 /* For thread safety "buf" is used instead of NULL for the ctermid static
1053 buffer. Actually it's unlikely the controlling terminal will change
1054 during program execution, and indeed on glibc (2.3.2) it's always just
1055 "/dev/tty", but L_ctermid on the stack is easy and fast and guarantees
1056 safety everywhere. */
1057 #ifdef HAVE_CTERMID
1058 SCM_DEFINE (scm_ctermid, "ctermid", 0, 0, 0,
1059 (),
1060 "Return a string containing the file name of the controlling\n"
1061 "terminal for the current process.")
1062 #define FUNC_NAME s_scm_ctermid
1063 {
1064 char buf[L_ctermid];
1065 char *result = ctermid (buf);
1066 if (*result == '\0')
1067 SCM_SYSERROR;
1068 return scm_from_locale_string (result);
1069 }
1070 #undef FUNC_NAME
1071 #endif /* HAVE_CTERMID */
1072
1073 #ifdef HAVE_TCGETPGRP
1074 SCM_DEFINE (scm_tcgetpgrp, "tcgetpgrp", 1, 0, 0,
1075 (SCM port),
1076 "Return the process group ID of the foreground process group\n"
1077 "associated with the terminal open on the file descriptor\n"
1078 "underlying @var{port}.\n"
1079 "\n"
1080 "If there is no foreground process group, the return value is a\n"
1081 "number greater than 1 that does not match the process group ID\n"
1082 "of any existing process group. This can happen if all of the\n"
1083 "processes in the job that was formerly the foreground job have\n"
1084 "terminated, and no other job has yet been moved into the\n"
1085 "foreground.")
1086 #define FUNC_NAME s_scm_tcgetpgrp
1087 {
1088 int fd;
1089 pid_t pgid;
1090
1091 port = SCM_COERCE_OUTPORT (port);
1092
1093 SCM_VALIDATE_OPFPORT (1, port);
1094 fd = SCM_FPORT_FDES (port);
1095 if ((pgid = tcgetpgrp (fd)) == -1)
1096 SCM_SYSERROR;
1097 return scm_from_int (pgid);
1098 }
1099 #undef FUNC_NAME
1100 #endif /* HAVE_TCGETPGRP */
1101
1102 #ifdef HAVE_TCSETPGRP
1103 SCM_DEFINE (scm_tcsetpgrp, "tcsetpgrp", 2, 0, 0,
1104 (SCM port, SCM pgid),
1105 "Set the foreground process group ID for the terminal used by the file\n"
1106 "descriptor underlying @var{port} to the integer @var{pgid}.\n"
1107 "The calling process\n"
1108 "must be a member of the same session as @var{pgid} and must have the same\n"
1109 "controlling terminal. The return value is unspecified.")
1110 #define FUNC_NAME s_scm_tcsetpgrp
1111 {
1112 int fd;
1113
1114 port = SCM_COERCE_OUTPORT (port);
1115
1116 SCM_VALIDATE_OPFPORT (1, port);
1117 fd = SCM_FPORT_FDES (port);
1118 if (tcsetpgrp (fd, scm_to_int (pgid)) == -1)
1119 SCM_SYSERROR;
1120 return SCM_UNSPECIFIED;
1121 }
1122 #undef FUNC_NAME
1123 #endif /* HAVE_TCSETPGRP */
1124
1125 SCM_DEFINE (scm_execl, "execl", 1, 0, 1,
1126 (SCM filename, SCM args),
1127 "Executes the file named by @var{filename} as a new process image.\n"
1128 "The remaining arguments are supplied to the process; from a C program\n"
1129 "they are accessible as the @code{argv} argument to @code{main}.\n"
1130 "Conventionally the first @var{arg} is the same as @var{filename}.\n"
1131 "All arguments must be strings.\n\n"
1132 "If @var{arg} is missing, @var{path} is executed with a null\n"
1133 "argument list, which may have system-dependent side-effects.\n\n"
1134 "This procedure is currently implemented using the @code{execv} system\n"
1135 "call, but we call it @code{execl} because of its Scheme calling interface.")
1136 #define FUNC_NAME s_scm_execl
1137 {
1138 char *exec_file;
1139 char **exec_argv;
1140
1141 scm_dynwind_begin (0);
1142
1143 exec_file = scm_to_locale_string (filename);
1144 scm_dynwind_free (exec_file);
1145
1146 exec_argv = scm_i_allocate_string_pointers (args);
1147
1148 execv (exec_file,
1149 #ifdef __MINGW32__
1150 /* extra "const" in mingw formals, provokes warning from gcc */
1151 (const char * const *)
1152 #endif
1153 exec_argv);
1154 SCM_SYSERROR;
1155
1156 /* not reached. */
1157 scm_dynwind_end ();
1158 return SCM_BOOL_F;
1159 }
1160 #undef FUNC_NAME
1161
1162 SCM_DEFINE (scm_execlp, "execlp", 1, 0, 1,
1163 (SCM filename, SCM args),
1164 "Similar to @code{execl}, however if\n"
1165 "@var{filename} does not contain a slash\n"
1166 "then the file to execute will be located by searching the\n"
1167 "directories listed in the @code{PATH} environment variable.\n\n"
1168 "This procedure is currently implemented using the @code{execvp} system\n"
1169 "call, but we call it @code{execlp} because of its Scheme calling interface.")
1170 #define FUNC_NAME s_scm_execlp
1171 {
1172 char *exec_file;
1173 char **exec_argv;
1174
1175 scm_dynwind_begin (0);
1176
1177 exec_file = scm_to_locale_string (filename);
1178 scm_dynwind_free (exec_file);
1179
1180 exec_argv = scm_i_allocate_string_pointers (args);
1181
1182 execvp (exec_file,
1183 #ifdef __MINGW32__
1184 /* extra "const" in mingw formals, provokes warning from gcc */
1185 (const char * const *)
1186 #endif
1187 exec_argv);
1188 SCM_SYSERROR;
1189
1190 /* not reached. */
1191 scm_dynwind_end ();
1192 return SCM_BOOL_F;
1193 }
1194 #undef FUNC_NAME
1195
1196
1197 /* OPTIMIZE-ME: scm_execle doesn't need malloced copies of the environment
1198 list strings the way environ_list_to_c gives. */
1199
1200 SCM_DEFINE (scm_execle, "execle", 2, 0, 1,
1201 (SCM filename, SCM env, SCM args),
1202 "Similar to @code{execl}, but the environment of the new process is\n"
1203 "specified by @var{env}, which must be a list of strings as returned by the\n"
1204 "@code{environ} procedure.\n\n"
1205 "This procedure is currently implemented using the @code{execve} system\n"
1206 "call, but we call it @code{execle} because of its Scheme calling interface.")
1207 #define FUNC_NAME s_scm_execle
1208 {
1209 char **exec_argv;
1210 char **exec_env;
1211 char *exec_file;
1212
1213 scm_dynwind_begin (0);
1214
1215 exec_file = scm_to_locale_string (filename);
1216 scm_dynwind_free (exec_file);
1217
1218 exec_argv = scm_i_allocate_string_pointers (args);
1219 exec_env = scm_i_allocate_string_pointers (env);
1220
1221 execve (exec_file,
1222 #ifdef __MINGW32__
1223 /* extra "const" in mingw formals, provokes warning from gcc */
1224 (const char * const *)
1225 #endif
1226 exec_argv,
1227 #ifdef __MINGW32__
1228 /* extra "const" in mingw formals, provokes warning from gcc */
1229 (const char * const *)
1230 #endif
1231 exec_env);
1232 SCM_SYSERROR;
1233
1234 /* not reached. */
1235 scm_dynwind_end ();
1236 return SCM_BOOL_F;
1237 }
1238 #undef FUNC_NAME
1239
1240 #ifdef HAVE_FORK
1241 SCM_DEFINE (scm_fork, "primitive-fork", 0, 0, 0,
1242 (),
1243 "Creates a new \"child\" process by duplicating the current \"parent\" process.\n"
1244 "In the child the return value is 0. In the parent the return value is\n"
1245 "the integer process ID of the child.\n\n"
1246 "This procedure has been renamed from @code{fork} to avoid a naming conflict\n"
1247 "with the scsh fork.")
1248 #define FUNC_NAME s_scm_fork
1249 {
1250 int pid;
1251 pid = fork ();
1252 if (pid == -1)
1253 SCM_SYSERROR;
1254 return scm_from_int (pid);
1255 }
1256 #undef FUNC_NAME
1257
1258 /* Since Guile uses threads, we have to be very careful to avoid calling
1259 functions that are not async-signal-safe in the child. That's why
1260 this function is implemented in C. */
1261 static SCM
1262 scm_open_process (SCM mode, SCM prog, SCM args)
1263 #define FUNC_NAME "open-process"
1264 {
1265 long mode_bits;
1266 int reading, writing;
1267 int c2p[2]; /* Child to parent. */
1268 int p2c[2]; /* Parent to child. */
1269 int in = -1, out = -1, err = -1;
1270 int pid;
1271 char *exec_file;
1272 char **exec_argv;
1273 int max_fd = 1024;
1274
1275 exec_file = scm_to_locale_string (prog);
1276 exec_argv = scm_i_allocate_string_pointers (scm_cons (prog, args));
1277
1278 mode_bits = scm_i_mode_bits (mode);
1279 reading = mode_bits & SCM_RDNG;
1280 writing = mode_bits & SCM_WRTNG;
1281
1282 if (reading)
1283 {
1284 if (pipe (c2p))
1285 {
1286 int errno_save = errno;
1287 free (exec_file);
1288 errno = errno_save;
1289 SCM_SYSERROR;
1290 }
1291 out = c2p[1];
1292 }
1293
1294 if (writing)
1295 {
1296 if (pipe (p2c))
1297 {
1298 int errno_save = errno;
1299 free (exec_file);
1300 if (reading)
1301 {
1302 close (c2p[0]);
1303 close (c2p[1]);
1304 }
1305 errno = errno_save;
1306 SCM_SYSERROR;
1307 }
1308 in = p2c[0];
1309 }
1310
1311 {
1312 SCM port;
1313
1314 if (SCM_OPOUTFPORTP ((port = scm_current_error_port ())))
1315 err = SCM_FPORT_FDES (port);
1316 if (out == -1 && SCM_OPOUTFPORTP ((port = scm_current_output_port ())))
1317 out = SCM_FPORT_FDES (port);
1318 if (in == -1 && SCM_OPINFPORTP ((port = scm_current_input_port ())))
1319 in = SCM_FPORT_FDES (port);
1320 }
1321
1322 #if defined (HAVE_GETRLIMIT) && defined (RLIMIT_NOFILE)
1323 {
1324 struct rlimit lim = { 0, 0 };
1325 if (getrlimit (RLIMIT_NOFILE, &lim) == 0)
1326 max_fd = lim.rlim_cur;
1327 }
1328 #endif
1329
1330 pid = fork ();
1331
1332 if (pid == -1)
1333 {
1334 int errno_save = errno;
1335 free (exec_file);
1336 if (reading)
1337 {
1338 close (c2p[0]);
1339 close (c2p[1]);
1340 }
1341 if (writing)
1342 {
1343 close (p2c[0]);
1344 close (p2c[1]);
1345 }
1346 errno = errno_save;
1347 SCM_SYSERROR;
1348 }
1349
1350 if (pid)
1351 /* Parent. */
1352 {
1353 SCM read_port = SCM_BOOL_F, write_port = SCM_BOOL_F, port;
1354
1355 /* There is no sense in catching errors on close(). */
1356 if (reading)
1357 {
1358 close (c2p[1]);
1359 read_port = scm_fdes_to_port (c2p[0], "r", sym_read_pipe);
1360 scm_setvbuf (read_port, scm_from_int (_IONBF), SCM_UNDEFINED);
1361 }
1362 if (writing)
1363 {
1364 close (p2c[0]);
1365 write_port = scm_fdes_to_port (p2c[1], "w", sym_write_pipe);
1366 scm_setvbuf (write_port, scm_from_int (_IONBF), SCM_UNDEFINED);
1367 }
1368
1369 if (reading && writing)
1370 {
1371 static SCM make_rw_port = SCM_BOOL_F;
1372
1373 if (scm_is_false (make_rw_port))
1374 make_rw_port = scm_c_private_variable ("ice-9 popen",
1375 "make-rw-port");
1376
1377 port = scm_call_2 (scm_variable_ref (make_rw_port),
1378 read_port, write_port);
1379 }
1380 else if (reading)
1381 port = read_port;
1382 else if (writing)
1383 port = write_port;
1384 else
1385 port = scm_sys_make_void_port (mode);
1386
1387 return scm_cons (port, scm_from_int (pid));
1388 }
1389
1390 /* The child. */
1391 if (reading)
1392 close (c2p[0]);
1393 if (writing)
1394 close (p2c[1]);
1395
1396 /* Close all file descriptors in ports inherited from the parent
1397 except for in, out, and err. Heavy-handed, but robust. */
1398 while (max_fd--)
1399 if (max_fd != in && max_fd != out && max_fd != err)
1400 close (max_fd);
1401
1402 /* Ignore errors on these open() calls. */
1403 if (in == -1)
1404 in = open ("/dev/null", O_RDONLY);
1405 if (out == -1)
1406 out = open ("/dev/null", O_WRONLY);
1407 if (err == -1)
1408 err = open ("/dev/null", O_WRONLY);
1409
1410 if (in > 0)
1411 {
1412 if (out == 0)
1413 do out = dup (out); while (errno == EINTR);
1414 if (err == 0)
1415 do err = dup (err); while (errno == EINTR);
1416 do dup2 (in, 0); while (errno == EINTR);
1417 close (in);
1418 }
1419 if (out > 1)
1420 {
1421 if (err == 1)
1422 do err = dup (err); while (errno == EINTR);
1423 do dup2 (out, 1); while (errno == EINTR);
1424 close (out);
1425 }
1426 if (err > 2)
1427 {
1428 do dup2 (err, 2); while (errno == EINTR);
1429 close (err);
1430 }
1431
1432 execvp (exec_file,
1433 #ifdef __MINGW32__
1434 /* extra "const" in mingw formals, provokes warning from gcc */
1435 (const char * const *)
1436 #endif
1437 exec_argv);
1438
1439 /* The exec failed! There is nothing sensible to do. */
1440 if (err > 0)
1441 {
1442 char *msg = strerror (errno);
1443 fprintf (fdopen (err, "a"), "In execlp of %s: %s\n",
1444 exec_file, msg);
1445 }
1446
1447 _exit (EXIT_FAILURE);
1448 /* Not reached. */
1449 return SCM_BOOL_F;
1450 }
1451 #undef FUNC_NAME
1452 #endif /* HAVE_FORK */
1453
1454 #ifdef __MINGW32__
1455 # include "win32-uname.h"
1456 #endif
1457
1458 #if defined (HAVE_UNAME) || defined (__MINGW32__)
1459 SCM_DEFINE (scm_uname, "uname", 0, 0, 0,
1460 (),
1461 "Return an object with some information about the computer\n"
1462 "system the program is running on.")
1463 #define FUNC_NAME s_scm_uname
1464 {
1465 struct utsname buf;
1466 SCM result = scm_c_make_vector (5, SCM_UNSPECIFIED);
1467 if (uname (&buf) < 0)
1468 SCM_SYSERROR;
1469 SCM_SIMPLE_VECTOR_SET(result, 0, scm_from_locale_string (buf.sysname));
1470 SCM_SIMPLE_VECTOR_SET(result, 1, scm_from_locale_string (buf.nodename));
1471 SCM_SIMPLE_VECTOR_SET(result, 2, scm_from_locale_string (buf.release));
1472 SCM_SIMPLE_VECTOR_SET(result, 3, scm_from_locale_string (buf.version));
1473 SCM_SIMPLE_VECTOR_SET(result, 4, scm_from_locale_string (buf.machine));
1474 /*
1475 a linux special?
1476 SCM_SIMPLE_VECTOR_SET(result, 5, scm_from_locale_string (buf.domainname));
1477 */
1478 return result;
1479 }
1480 #undef FUNC_NAME
1481 #endif /* HAVE_UNAME */
1482
1483 SCM_DEFINE (scm_environ, "environ", 0, 1, 0,
1484 (SCM env),
1485 "If @var{env} is omitted, return the current environment (in the\n"
1486 "Unix sense) as a list of strings. Otherwise set the current\n"
1487 "environment, which is also the default environment for child\n"
1488 "processes, to the supplied list of strings. Each member of\n"
1489 "@var{env} should be of the form @code{NAME=VALUE} and values of\n"
1490 "@code{NAME} should not be duplicated. If @var{env} is supplied\n"
1491 "then the return value is unspecified.")
1492 #define FUNC_NAME s_scm_environ
1493 {
1494 if (SCM_UNBNDP (env))
1495 return scm_makfromstrs (-1, environ);
1496 else
1497 {
1498 environ = scm_i_allocate_string_pointers (env);
1499 return SCM_UNSPECIFIED;
1500 }
1501 }
1502 #undef FUNC_NAME
1503
1504 #ifdef L_tmpnam
1505
1506 SCM_DEFINE (scm_tmpnam, "tmpnam", 0, 0, 0,
1507 (),
1508 "Return a name in the file system that does not match any\n"
1509 "existing file. However there is no guarantee that another\n"
1510 "process will not create the file after @code{tmpnam} is called.\n"
1511 "Care should be taken if opening the file, e.g., use the\n"
1512 "@code{O_EXCL} open flag or use @code{mkstemp!} instead.")
1513 #define FUNC_NAME s_scm_tmpnam
1514 {
1515 char name[L_tmpnam];
1516 char *rv;
1517
1518 SCM_SYSCALL (rv = tmpnam (name));
1519 if (rv == NULL)
1520 /* not SCM_SYSERROR since errno probably not set. */
1521 SCM_MISC_ERROR ("tmpnam failed", SCM_EOL);
1522 return scm_from_locale_string (name);
1523 }
1524 #undef FUNC_NAME
1525
1526 #endif
1527
1528 SCM_DEFINE (scm_tmpfile, "tmpfile", 0, 0, 0,
1529 (void),
1530 "Return an input/output port to a unique temporary file\n"
1531 "named using the path prefix @code{P_tmpdir} defined in\n"
1532 "@file{stdio.h}.\n"
1533 "The file is automatically deleted when the port is closed\n"
1534 "or the program terminates.")
1535 #define FUNC_NAME s_scm_tmpfile
1536 {
1537 FILE *rv;
1538 int fd;
1539
1540 if (! (rv = tmpfile ()))
1541 SCM_SYSERROR;
1542
1543 #ifndef __MINGW32__
1544 fd = dup (fileno (rv));
1545 fclose (rv);
1546 #else
1547 fd = fileno (rv);
1548 /* FIXME: leaking the file, it will never be closed! */
1549 #endif
1550
1551 return scm_fdes_to_port (fd, "w+", SCM_BOOL_F);
1552 }
1553 #undef FUNC_NAME
1554
1555 SCM_DEFINE (scm_utime, "utime", 1, 5, 0,
1556 (SCM pathname, SCM actime, SCM modtime, SCM actimens, SCM modtimens,
1557 SCM flags),
1558 "@code{utime} sets the access and modification times for the\n"
1559 "file named by @var{pathname}. If @var{actime} or @var{modtime} is\n"
1560 "not supplied, then the current time is used. @var{actime} and\n"
1561 "@var{modtime} must be integer time values as returned by the\n"
1562 "@code{current-time} procedure.\n\n"
1563 "The optional @var{actimens} and @var{modtimens} are nanoseconds\n"
1564 "to add @var{actime} and @var{modtime}. Nanosecond precision is\n"
1565 "only supported on some combinations of file systems and operating\n"
1566 "systems.\n"
1567 "@lisp\n"
1568 "(utime \"foo\" (- (current-time) 3600))\n"
1569 "@end lisp\n"
1570 "will set the access time to one hour in the past and the\n"
1571 "modification time to the current time.")
1572 #define FUNC_NAME s_scm_utime
1573 {
1574 int rv;
1575 time_t atim_sec, mtim_sec;
1576 long atim_nsec, mtim_nsec;
1577 int f;
1578
1579 if (SCM_UNBNDP (actime))
1580 {
1581 #ifdef HAVE_UTIMENSAT
1582 atim_sec = 0;
1583 atim_nsec = UTIME_NOW;
1584 #else
1585 SCM_SYSCALL (time (&atim_sec));
1586 atim_nsec = 0;
1587 #endif
1588 }
1589 else
1590 {
1591 atim_sec = SCM_NUM2ULONG (2, actime);
1592 if (SCM_UNBNDP (actimens))
1593 atim_nsec = 0;
1594 else
1595 atim_nsec = SCM_NUM2LONG (4, actimens);
1596 }
1597
1598 if (SCM_UNBNDP (modtime))
1599 {
1600 #ifdef HAVE_UTIMENSAT
1601 mtim_sec = 0;
1602 mtim_nsec = UTIME_NOW;
1603 #else
1604 SCM_SYSCALL (time (&mtim_sec));
1605 mtim_nsec = 0;
1606 #endif
1607 }
1608 else
1609 {
1610 mtim_sec = SCM_NUM2ULONG (3, modtime);
1611 if (SCM_UNBNDP (modtimens))
1612 mtim_nsec = 0;
1613 else
1614 mtim_nsec = SCM_NUM2LONG (5, modtimens);
1615 }
1616
1617 if (SCM_UNBNDP (flags))
1618 f = 0;
1619 else
1620 f = SCM_NUM2INT (6, flags);
1621
1622 #ifdef HAVE_UTIMENSAT
1623 {
1624 struct timespec times[2];
1625 times[0].tv_sec = atim_sec;
1626 times[0].tv_nsec = atim_nsec;
1627 times[1].tv_sec = mtim_sec;
1628 times[1].tv_nsec = mtim_nsec;
1629
1630 STRING_SYSCALL (pathname, c_pathname,
1631 rv = utimensat (AT_FDCWD, c_pathname, times, f));
1632 }
1633 #else
1634 {
1635 struct utimbuf utm;
1636 utm.actime = atim_sec;
1637 utm.modtime = mtim_sec;
1638
1639 STRING_SYSCALL (pathname, c_pathname,
1640 rv = utime (c_pathname, &utm));
1641 }
1642 #endif
1643
1644 if (rv != 0)
1645 SCM_SYSERROR;
1646 return SCM_UNSPECIFIED;
1647 }
1648 #undef FUNC_NAME
1649
1650 SCM_DEFINE (scm_getpid, "getpid", 0, 0, 0,
1651 (),
1652 "Return an integer representing the current process ID.")
1653 #define FUNC_NAME s_scm_getpid
1654 {
1655 return scm_from_ulong (getpid ());
1656 }
1657 #undef FUNC_NAME
1658
1659 SCM_DEFINE (scm_putenv, "putenv", 1, 0, 0,
1660 (SCM str),
1661 "Modifies the environment of the current process, which is also\n"
1662 "the default environment inherited by child processes. If\n"
1663 "@var{str} is of the form @code{NAME=VALUE} then it will be\n"
1664 "written directly into the environment, replacing any existing\n"
1665 "environment string with name matching @code{NAME}. If\n"
1666 "@var{str} does not contain an equal sign, then any existing\n"
1667 "string with name matching @var{str} will be removed.\n"
1668 "\n"
1669 "The return value is unspecified.")
1670 #define FUNC_NAME s_scm_putenv
1671 {
1672 int rv;
1673 char *c_str = scm_to_locale_string (str);
1674
1675 /* Leave C_STR in the environment. */
1676
1677 /* Gnulib's `putenv' module honors the semantics described above. */
1678 rv = putenv (c_str);
1679 if (rv < 0)
1680 SCM_SYSERROR;
1681
1682 return SCM_UNSPECIFIED;
1683 }
1684 #undef FUNC_NAME
1685
1686 /* This mutex is used to serialize invocations of `setlocale ()' on non-GNU
1687 systems (i.e., systems where a reentrant locale API is not available). It
1688 is also acquired before calls to `nl_langinfo ()'. See `i18n.c' for
1689 details. */
1690 scm_i_pthread_mutex_t scm_i_locale_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
1691
1692 #ifdef HAVE_SETLOCALE
1693
1694 SCM_DEFINE (scm_setlocale, "setlocale", 1, 1, 0,
1695 (SCM category, SCM locale),
1696 "If @var{locale} is omitted, return the current value of the\n"
1697 "specified locale category as a system-dependent string.\n"
1698 "@var{category} should be specified using the values\n"
1699 "@code{LC_COLLATE}, @code{LC_ALL} etc.\n"
1700 "\n"
1701 "Otherwise the specified locale category is set to the string\n"
1702 "@var{locale} and the new value is returned as a\n"
1703 "system-dependent string. If @var{locale} is an empty string,\n"
1704 "the locale will be set using environment variables.\n"
1705 "\n"
1706 "When the locale is changed, the character encoding of the new\n"
1707 "locale (UTF-8, ISO-8859-1, etc.) is used for the current\n"
1708 "input, output, and error ports\n")
1709 #define FUNC_NAME s_scm_setlocale
1710 {
1711 int c_category;
1712 char *clocale;
1713 char *rv;
1714 const char *enc;
1715
1716 scm_dynwind_begin (0);
1717
1718 if (SCM_UNBNDP (locale))
1719 {
1720 clocale = NULL;
1721 }
1722 else
1723 {
1724 clocale = scm_to_locale_string (locale);
1725 scm_dynwind_free (clocale);
1726 }
1727
1728 c_category = scm_i_to_lc_category (category, 1);
1729
1730 scm_i_pthread_mutex_lock (&scm_i_locale_mutex);
1731 rv = setlocale (c_category, clocale);
1732 scm_i_pthread_mutex_unlock (&scm_i_locale_mutex);
1733
1734 if (rv == NULL)
1735 {
1736 /* POSIX and C99 don't say anything about setlocale setting errno, so
1737 force a sensible value here. glibc leaves ENOENT, which would be
1738 fine, but it's not a documented feature. */
1739 errno = EINVAL;
1740 SCM_SYSERROR;
1741 }
1742
1743 enc = locale_charset ();
1744
1745 /* Set the default encoding for new ports. */
1746 scm_i_set_default_port_encoding (enc);
1747
1748 /* Set the encoding for the stdio ports. */
1749 scm_i_set_port_encoding_x (scm_current_input_port (), enc);
1750 scm_i_set_port_encoding_x (scm_current_output_port (), enc);
1751 scm_i_set_port_encoding_x (scm_current_error_port (), enc);
1752
1753 scm_dynwind_end ();
1754 return scm_from_locale_string (rv);
1755 }
1756 #undef FUNC_NAME
1757 #endif /* HAVE_SETLOCALE */
1758
1759 #ifdef HAVE_MKNOD
1760 SCM_DEFINE (scm_mknod, "mknod", 4, 0, 0,
1761 (SCM path, SCM type, SCM perms, SCM dev),
1762 "Creates a new special file, such as a file corresponding to a device.\n"
1763 "@var{path} specifies the name of the file. @var{type} should\n"
1764 "be one of the following symbols:\n"
1765 "regular, directory, symlink, block-special, char-special,\n"
1766 "fifo, or socket. @var{perms} (an integer) specifies the file permissions.\n"
1767 "@var{dev} (an integer) specifies which device the special file refers\n"
1768 "to. Its exact interpretation depends on the kind of special file\n"
1769 "being created.\n\n"
1770 "E.g.,\n"
1771 "@lisp\n"
1772 "(mknod \"/dev/fd0\" 'block-special #o660 (+ (* 2 256) 2))\n"
1773 "@end lisp\n\n"
1774 "The return value is unspecified.")
1775 #define FUNC_NAME s_scm_mknod
1776 {
1777 int val;
1778 const char *p;
1779 int ctype = 0;
1780
1781 SCM_VALIDATE_STRING (1, path);
1782 SCM_VALIDATE_SYMBOL (2, type);
1783
1784 p = scm_i_symbol_chars (type);
1785 if (strcmp (p, "regular") == 0)
1786 ctype = S_IFREG;
1787 else if (strcmp (p, "directory") == 0)
1788 ctype = S_IFDIR;
1789 #ifdef S_IFLNK
1790 /* systems without symlinks probably don't have S_IFLNK defined */
1791 else if (strcmp (p, "symlink") == 0)
1792 ctype = S_IFLNK;
1793 #endif
1794 else if (strcmp (p, "block-special") == 0)
1795 ctype = S_IFBLK;
1796 else if (strcmp (p, "char-special") == 0)
1797 ctype = S_IFCHR;
1798 else if (strcmp (p, "fifo") == 0)
1799 ctype = S_IFIFO;
1800 #ifdef S_IFSOCK
1801 else if (strcmp (p, "socket") == 0)
1802 ctype = S_IFSOCK;
1803 #endif
1804 else
1805 SCM_OUT_OF_RANGE (2, type);
1806
1807 STRING_SYSCALL (path, c_path,
1808 val = mknod (c_path,
1809 ctype | scm_to_int (perms),
1810 scm_to_int (dev)));
1811 if (val != 0)
1812 SCM_SYSERROR;
1813 return SCM_UNSPECIFIED;
1814 }
1815 #undef FUNC_NAME
1816 #endif /* HAVE_MKNOD */
1817
1818 #ifdef HAVE_NICE
1819 SCM_DEFINE (scm_nice, "nice", 1, 0, 0,
1820 (SCM incr),
1821 "Increment the priority of the current process by @var{incr}. A higher\n"
1822 "priority value means that the process runs less often.\n"
1823 "The return value is unspecified.")
1824 #define FUNC_NAME s_scm_nice
1825 {
1826 /* nice() returns "prio-NZERO" on success or -1 on error, but -1 can arise
1827 from "prio-NZERO", so an error must be detected from errno changed */
1828 errno = 0;
1829 nice (scm_to_int (incr));
1830 if (errno != 0)
1831 SCM_SYSERROR;
1832
1833 return SCM_UNSPECIFIED;
1834 }
1835 #undef FUNC_NAME
1836 #endif /* HAVE_NICE */
1837
1838 #ifdef HAVE_SYNC
1839 SCM_DEFINE (scm_sync, "sync", 0, 0, 0,
1840 (),
1841 "Flush the operating system disk buffers.\n"
1842 "The return value is unspecified.")
1843 #define FUNC_NAME s_scm_sync
1844 {
1845 sync();
1846 return SCM_UNSPECIFIED;
1847 }
1848 #undef FUNC_NAME
1849 #endif /* HAVE_SYNC */
1850
1851
1852 /* crypt() returns a pointer to a static buffer, so we use scm_i_misc_mutex
1853 to avoid another thread overwriting it. A test program running crypt
1854 continuously in two threads can be quickly seen tripping this problem.
1855 crypt() is pretty slow normally, so a mutex shouldn't add much overhead.
1856
1857 glibc has a thread-safe crypt_r, but (in version 2.3.2) it runs a lot
1858 slower (about 5x) than plain crypt if you pass an uninitialized data
1859 block each time. Presumably there's some one-time setups. The best way
1860 to use crypt_r for parallel execution in multiple threads would probably
1861 be to maintain a little pool of initialized crypt_data structures, take
1862 one and use it, then return it to the pool. That pool could be garbage
1863 collected so it didn't add permanently to memory use if only a few crypt
1864 calls are made. But we expect crypt will be used rarely, and even more
1865 rarely will there be any desire for lots of parallel execution on
1866 multiple cpus. So for now we don't bother with anything fancy, just
1867 ensure it works. */
1868
1869 #ifdef HAVE_CRYPT
1870 SCM_DEFINE (scm_crypt, "crypt", 2, 0, 0,
1871 (SCM key, SCM salt),
1872 "Encrypt @var{key} using @var{salt} as the salt value to the\n"
1873 "crypt(3) library call.")
1874 #define FUNC_NAME s_scm_crypt
1875 {
1876 SCM ret;
1877 char *c_key, *c_salt, *c_ret;
1878
1879 scm_dynwind_begin (0);
1880 scm_i_dynwind_pthread_mutex_lock (&scm_i_misc_mutex);
1881
1882 c_key = scm_to_locale_string (key);
1883 scm_dynwind_free (c_key);
1884 c_salt = scm_to_locale_string (salt);
1885 scm_dynwind_free (c_salt);
1886
1887 /* The Linux crypt(3) man page says crypt will return NULL and set errno
1888 on error. (Eg. ENOSYS if legal restrictions mean it cannot be
1889 implemented). */
1890 c_ret = crypt (c_key, c_salt);
1891 if (c_ret == NULL)
1892 SCM_SYSERROR;
1893
1894 ret = scm_from_locale_string (c_ret);
1895 scm_dynwind_end ();
1896 return ret;
1897 }
1898 #undef FUNC_NAME
1899 #endif /* HAVE_CRYPT */
1900
1901 #if HAVE_CHROOT
1902 SCM_DEFINE (scm_chroot, "chroot", 1, 0, 0,
1903 (SCM path),
1904 "Change the root directory to that specified in @var{path}.\n"
1905 "This directory will be used for path names beginning with\n"
1906 "@file{/}. The root directory is inherited by all children\n"
1907 "of the current process. Only the superuser may change the\n"
1908 "root directory.")
1909 #define FUNC_NAME s_scm_chroot
1910 {
1911 int rv;
1912
1913 WITH_STRING (path, c_path,
1914 rv = chroot (c_path));
1915 if (rv == -1)
1916 SCM_SYSERROR;
1917 return SCM_UNSPECIFIED;
1918 }
1919 #undef FUNC_NAME
1920 #endif /* HAVE_CHROOT */
1921
1922
1923 #ifdef __MINGW32__
1924 /* Wrapper function to supplying `getlogin()' under Windows. */
1925 static char * getlogin (void)
1926 {
1927 static char user[256];
1928 static unsigned long len = 256;
1929
1930 if (!GetUserName (user, &len))
1931 return NULL;
1932 return user;
1933 }
1934 #endif /* __MINGW32__ */
1935
1936
1937 #if defined (HAVE_GETLOGIN) || defined (__MINGW32__)
1938 SCM_DEFINE (scm_getlogin, "getlogin", 0, 0, 0,
1939 (void),
1940 "Return a string containing the name of the user logged in on\n"
1941 "the controlling terminal of the process, or @code{#f} if this\n"
1942 "information cannot be obtained.")
1943 #define FUNC_NAME s_scm_getlogin
1944 {
1945 char * p;
1946
1947 p = getlogin ();
1948 if (!p || !*p)
1949 return SCM_BOOL_F;
1950 return scm_from_locale_string (p);
1951 }
1952 #undef FUNC_NAME
1953 #endif /* HAVE_GETLOGIN */
1954
1955 #if HAVE_GETPRIORITY
1956 SCM_DEFINE (scm_getpriority, "getpriority", 2, 0, 0,
1957 (SCM which, SCM who),
1958 "Return the scheduling priority of the process, process group\n"
1959 "or user, as indicated by @var{which} and @var{who}. @var{which}\n"
1960 "is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}\n"
1961 "or @code{PRIO_USER}, and @var{who} is interpreted relative to\n"
1962 "@var{which} (a process identifier for @code{PRIO_PROCESS},\n"
1963 "process group identifier for @code{PRIO_PGRP}, and a user\n"
1964 "identifier for @code{PRIO_USER}. A zero value of @var{who}\n"
1965 "denotes the current process, process group, or user. Return\n"
1966 "the highest priority (lowest numerical value) of any of the\n"
1967 "specified processes.")
1968 #define FUNC_NAME s_scm_getpriority
1969 {
1970 int cwhich, cwho, ret;
1971
1972 cwhich = scm_to_int (which);
1973 cwho = scm_to_int (who);
1974
1975 /* We have to clear errno and examine it later, because -1 is a
1976 legal return value for getpriority(). */
1977 errno = 0;
1978 ret = getpriority (cwhich, cwho);
1979 if (errno != 0)
1980 SCM_SYSERROR;
1981 return scm_from_int (ret);
1982 }
1983 #undef FUNC_NAME
1984 #endif /* HAVE_GETPRIORITY */
1985
1986 #if HAVE_SETPRIORITY
1987 SCM_DEFINE (scm_setpriority, "setpriority", 3, 0, 0,
1988 (SCM which, SCM who, SCM prio),
1989 "Set the scheduling priority of the process, process group\n"
1990 "or user, as indicated by @var{which} and @var{who}. @var{which}\n"
1991 "is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}\n"
1992 "or @code{PRIO_USER}, and @var{who} is interpreted relative to\n"
1993 "@var{which} (a process identifier for @code{PRIO_PROCESS},\n"
1994 "process group identifier for @code{PRIO_PGRP}, and a user\n"
1995 "identifier for @code{PRIO_USER}. A zero value of @var{who}\n"
1996 "denotes the current process, process group, or user.\n"
1997 "@var{prio} is a value in the range -20 and 20, the default\n"
1998 "priority is 0; lower priorities cause more favorable\n"
1999 "scheduling. Sets the priority of all of the specified\n"
2000 "processes. Only the super-user may lower priorities.\n"
2001 "The return value is not specified.")
2002 #define FUNC_NAME s_scm_setpriority
2003 {
2004 int cwhich, cwho, cprio;
2005
2006 cwhich = scm_to_int (which);
2007 cwho = scm_to_int (who);
2008 cprio = scm_to_int (prio);
2009
2010 if (setpriority (cwhich, cwho, cprio) == -1)
2011 SCM_SYSERROR;
2012 return SCM_UNSPECIFIED;
2013 }
2014 #undef FUNC_NAME
2015 #endif /* HAVE_SETPRIORITY */
2016
2017 #ifdef HAVE_SCHED_GETAFFINITY
2018
2019 static SCM
2020 cpu_set_to_bitvector (const cpu_set_t *cs)
2021 {
2022 SCM bv;
2023 size_t cpu;
2024
2025 bv = scm_c_make_bitvector (sizeof (*cs), SCM_BOOL_F);
2026
2027 for (cpu = 0; cpu < sizeof (*cs); cpu++)
2028 {
2029 if (CPU_ISSET (cpu, cs))
2030 /* XXX: This is inefficient but avoids code duplication. */
2031 scm_c_bitvector_set_x (bv, cpu, SCM_BOOL_T);
2032 }
2033
2034 return bv;
2035 }
2036
2037 SCM_DEFINE (scm_getaffinity, "getaffinity", 1, 0, 0,
2038 (SCM pid),
2039 "Return a bitvector representing the CPU affinity mask for\n"
2040 "process @var{pid}. Each CPU the process has affinity with\n"
2041 "has its corresponding bit set in the returned bitvector.\n"
2042 "The number of bits set is a good estimate of how many CPUs\n"
2043 "Guile can use without stepping on other processes' toes.\n\n"
2044 "Currently this procedure is only defined on GNU variants\n"
2045 "(@pxref{CPU Affinity, @code{sched_getaffinity},, libc, The\n"
2046 "GNU C Library Reference Manual}).\n")
2047 #define FUNC_NAME s_scm_getaffinity
2048 {
2049 int err;
2050 cpu_set_t cs;
2051
2052 CPU_ZERO (&cs);
2053 err = sched_getaffinity (scm_to_int (pid), sizeof (cs), &cs);
2054 if (err)
2055 SCM_SYSERROR;
2056
2057 return cpu_set_to_bitvector (&cs);
2058 }
2059 #undef FUNC_NAME
2060
2061 #endif /* HAVE_SCHED_GETAFFINITY */
2062
2063 #ifdef HAVE_SCHED_SETAFFINITY
2064
2065 SCM_DEFINE (scm_setaffinity, "setaffinity", 2, 0, 0,
2066 (SCM pid, SCM mask),
2067 "Install the CPU affinity mask @var{mask}, a bitvector, for\n"
2068 "the process or thread with ID @var{pid}. The return value\n"
2069 "is unspecified.\n\n"
2070 "Currently this procedure is only defined on GNU variants\n"
2071 "(@pxref{CPU Affinity, @code{sched_setaffinity},, libc, The\n"
2072 "GNU C Library Reference Manual}).\n")
2073 #define FUNC_NAME s_scm_setaffinity
2074 {
2075 cpu_set_t cs;
2076 scm_t_array_handle handle;
2077 const scm_t_uint32 *c_mask;
2078 size_t len, off, cpu;
2079 ssize_t inc;
2080 int err;
2081
2082 c_mask = scm_bitvector_elements (mask, &handle, &off, &len, &inc);
2083
2084 CPU_ZERO (&cs);
2085 for (cpu = 0; cpu < len; cpu++)
2086 {
2087 size_t idx;
2088
2089 idx = cpu * inc + off;
2090 if (c_mask[idx / 32] & (1UL << (idx % 32)))
2091 CPU_SET (cpu, &cs);
2092 }
2093
2094 err = sched_setaffinity (scm_to_int (pid), sizeof (cs), &cs);
2095 if (err)
2096 SCM_SYSERROR;
2097
2098 return SCM_UNSPECIFIED;
2099 }
2100 #undef FUNC_NAME
2101
2102 #endif /* HAVE_SCHED_SETAFFINITY */
2103
2104 \f
2105 #if HAVE_GETPASS
2106 SCM_DEFINE (scm_getpass, "getpass", 1, 0, 0,
2107 (SCM prompt),
2108 "Display @var{prompt} to the standard error output and read\n"
2109 "a password from @file{/dev/tty}. If this file is not\n"
2110 "accessible, it reads from standard input. The password may be\n"
2111 "up to 127 characters in length. Additional characters and the\n"
2112 "terminating newline character are discarded. While reading\n"
2113 "the password, echoing and the generation of signals by special\n"
2114 "characters is disabled.")
2115 #define FUNC_NAME s_scm_getpass
2116 {
2117 char * p;
2118 SCM passwd;
2119
2120 SCM_VALIDATE_STRING (1, prompt);
2121
2122 WITH_STRING (prompt, c_prompt,
2123 p = getpass(c_prompt));
2124 passwd = scm_from_locale_string (p);
2125
2126 /* Clear out the password in the static buffer. */
2127 memset (p, 0, strlen (p));
2128
2129 return passwd;
2130 }
2131 #undef FUNC_NAME
2132 #endif /* HAVE_GETPASS */
2133
2134 SCM_DEFINE (scm_flock, "flock", 2, 0, 0,
2135 (SCM file, SCM operation),
2136 "Apply or remove an advisory lock on an open file.\n"
2137 "@var{operation} specifies the action to be done:\n"
2138 "\n"
2139 "@defvar LOCK_SH\n"
2140 "Shared lock. More than one process may hold a shared lock\n"
2141 "for a given file at a given time.\n"
2142 "@end defvar\n"
2143 "@defvar LOCK_EX\n"
2144 "Exclusive lock. Only one process may hold an exclusive lock\n"
2145 "for a given file at a given time.\n"
2146 "@end defvar\n"
2147 "@defvar LOCK_UN\n"
2148 "Unlock the file.\n"
2149 "@end defvar\n"
2150 "@defvar LOCK_NB\n"
2151 "Don't block when locking. This is combined with one of the\n"
2152 "other operations using @code{logior}. If @code{flock} would\n"
2153 "block an @code{EWOULDBLOCK} error is thrown.\n"
2154 "@end defvar\n"
2155 "\n"
2156 "The return value is not specified. @var{file} may be an open\n"
2157 "file descriptor or an open file descriptor port.\n"
2158 "\n"
2159 "Note that @code{flock} does not lock files across NFS.")
2160 #define FUNC_NAME s_scm_flock
2161 {
2162 int fdes;
2163
2164 if (scm_is_integer (file))
2165 fdes = scm_to_int (file);
2166 else
2167 {
2168 SCM_VALIDATE_OPFPORT (2, file);
2169
2170 fdes = SCM_FPORT_FDES (file);
2171 }
2172 if (flock (fdes, scm_to_int (operation)) == -1)
2173 SCM_SYSERROR;
2174 return SCM_UNSPECIFIED;
2175 }
2176 #undef FUNC_NAME
2177
2178 #if HAVE_SETHOSTNAME
2179 SCM_DEFINE (scm_sethostname, "sethostname", 1, 0, 0,
2180 (SCM name),
2181 "Set the host name of the current processor to @var{name}. May\n"
2182 "only be used by the superuser. The return value is not\n"
2183 "specified.")
2184 #define FUNC_NAME s_scm_sethostname
2185 {
2186 int rv;
2187
2188 WITH_STRING (name, c_name,
2189 rv = sethostname (c_name, strlen(c_name)));
2190 if (rv == -1)
2191 SCM_SYSERROR;
2192 return SCM_UNSPECIFIED;
2193 }
2194 #undef FUNC_NAME
2195 #endif /* HAVE_SETHOSTNAME */
2196
2197
2198 #if HAVE_GETHOSTNAME
2199 SCM_DEFINE (scm_gethostname, "gethostname", 0, 0, 0,
2200 (void),
2201 "Return the host name of the current processor.")
2202 #define FUNC_NAME s_scm_gethostname
2203 {
2204 #ifdef MAXHOSTNAMELEN
2205
2206 /* Various systems define MAXHOSTNAMELEN (including Solaris in fact).
2207 * On GNU/Linux this doesn't include the terminating '\0', hence "+ 1". */
2208 const int len = MAXHOSTNAMELEN + 1;
2209 char *const p = scm_malloc (len);
2210 const int res = gethostname (p, len);
2211
2212 scm_dynwind_begin (0);
2213 scm_dynwind_unwind_handler (free, p, 0);
2214
2215 #else
2216
2217 /* Default 256 is for Solaris, under Linux ENAMETOOLONG is returned if not
2218 * large enough. SUSv2 specifies 255 maximum too, apparently. */
2219 int len = 256;
2220 int res;
2221 char *p;
2222
2223 # if HAVE_SYSCONF && defined (_SC_HOST_NAME_MAX)
2224
2225 /* POSIX specifies the HOST_NAME_MAX system parameter for the max size,
2226 * which may reflect a particular kernel configuration.
2227 * Must watch out for this existing but giving -1, as happens for instance
2228 * in gnu/linux glibc 2.3.2. */
2229 {
2230 const long int n = sysconf (_SC_HOST_NAME_MAX);
2231 if (n != -1L)
2232 len = n;
2233 }
2234
2235 # endif
2236
2237 p = scm_malloc (len);
2238
2239 scm_dynwind_begin (0);
2240 scm_dynwind_unwind_handler (free, p, 0);
2241
2242 res = gethostname (p, len);
2243 while (res == -1 && errno == ENAMETOOLONG)
2244 {
2245 len *= 2;
2246
2247 /* scm_realloc may throw an exception. */
2248 p = scm_realloc (p, len);
2249 res = gethostname (p, len);
2250 }
2251
2252 #endif
2253
2254 if (res == -1)
2255 {
2256 const int save_errno = errno;
2257
2258 /* No guile exceptions can occur before we have freed p's memory. */
2259 scm_dynwind_end ();
2260 free (p);
2261
2262 errno = save_errno;
2263 SCM_SYSERROR;
2264 }
2265 else
2266 {
2267 /* scm_from_locale_string may throw an exception. */
2268 const SCM name = scm_from_locale_string (p);
2269
2270 /* No guile exceptions can occur before we have freed p's memory. */
2271 scm_dynwind_end ();
2272 free (p);
2273
2274 return name;
2275 }
2276 }
2277 #undef FUNC_NAME
2278 #endif /* HAVE_GETHOSTNAME */
2279
2280 \f
2281 #ifdef HAVE_FORK
2282 static void
2283 scm_init_popen (void)
2284 {
2285 scm_c_define_gsubr ("open-process", 2, 0, 1, scm_open_process);
2286 }
2287 #endif
2288
2289 void
2290 scm_init_posix ()
2291 {
2292 scm_add_feature ("posix");
2293 #ifdef HAVE_GETEUID
2294 scm_add_feature ("EIDs");
2295 #endif
2296 #ifdef WAIT_ANY
2297 scm_c_define ("WAIT_ANY", scm_from_int (WAIT_ANY));
2298 #endif
2299 #ifdef WAIT_MYPGRP
2300 scm_c_define ("WAIT_MYPGRP", scm_from_int (WAIT_MYPGRP));
2301 #endif
2302 #ifdef WNOHANG
2303 scm_c_define ("WNOHANG", scm_from_int (WNOHANG));
2304 #endif
2305 #ifdef WUNTRACED
2306 scm_c_define ("WUNTRACED", scm_from_int (WUNTRACED));
2307 #endif
2308
2309 #ifdef LC_COLLATE
2310 scm_c_define ("LC_COLLATE", scm_from_int (LC_COLLATE));
2311 #endif
2312 #ifdef LC_CTYPE
2313 scm_c_define ("LC_CTYPE", scm_from_int (LC_CTYPE));
2314 #endif
2315 #ifdef LC_MONETARY
2316 scm_c_define ("LC_MONETARY", scm_from_int (LC_MONETARY));
2317 #endif
2318 #ifdef LC_NUMERIC
2319 scm_c_define ("LC_NUMERIC", scm_from_int (LC_NUMERIC));
2320 #endif
2321 #ifdef LC_TIME
2322 scm_c_define ("LC_TIME", scm_from_int (LC_TIME));
2323 #endif
2324 #ifdef LC_MESSAGES
2325 scm_c_define ("LC_MESSAGES", scm_from_int (LC_MESSAGES));
2326 #endif
2327 #ifdef LC_ALL
2328 scm_c_define ("LC_ALL", scm_from_int (LC_ALL));
2329 #endif
2330 #ifdef LC_PAPER
2331 scm_c_define ("LC_PAPER", scm_from_int (LC_PAPER));
2332 #endif
2333 #ifdef LC_NAME
2334 scm_c_define ("LC_NAME", scm_from_int (LC_NAME));
2335 #endif
2336 #ifdef LC_ADDRESS
2337 scm_c_define ("LC_ADDRESS", scm_from_int (LC_ADDRESS));
2338 #endif
2339 #ifdef LC_TELEPHONE
2340 scm_c_define ("LC_TELEPHONE", scm_from_int (LC_TELEPHONE));
2341 #endif
2342 #ifdef LC_MEASUREMENT
2343 scm_c_define ("LC_MEASUREMENT", scm_from_int (LC_MEASUREMENT));
2344 #endif
2345 #ifdef LC_IDENTIFICATION
2346 scm_c_define ("LC_IDENTIFICATION", scm_from_int (LC_IDENTIFICATION));
2347 #endif
2348 #ifdef PIPE_BUF
2349 scm_c_define ("PIPE_BUF", scm_from_long (PIPE_BUF));
2350 #endif
2351
2352 #ifdef PRIO_PROCESS
2353 scm_c_define ("PRIO_PROCESS", scm_from_int (PRIO_PROCESS));
2354 #endif
2355 #ifdef PRIO_PGRP
2356 scm_c_define ("PRIO_PGRP", scm_from_int (PRIO_PGRP));
2357 #endif
2358 #ifdef PRIO_USER
2359 scm_c_define ("PRIO_USER", scm_from_int (PRIO_USER));
2360 #endif
2361
2362 #ifdef LOCK_SH
2363 scm_c_define ("LOCK_SH", scm_from_int (LOCK_SH));
2364 #endif
2365 #ifdef LOCK_EX
2366 scm_c_define ("LOCK_EX", scm_from_int (LOCK_EX));
2367 #endif
2368 #ifdef LOCK_UN
2369 scm_c_define ("LOCK_UN", scm_from_int (LOCK_UN));
2370 #endif
2371 #ifdef LOCK_NB
2372 scm_c_define ("LOCK_NB", scm_from_int (LOCK_NB));
2373 #endif
2374
2375 #include "libguile/cpp-SIG.c"
2376 #include "libguile/posix.x"
2377
2378 scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
2379 "scm_init_popen",
2380 (scm_t_extension_init_func) scm_init_popen,
2381 NULL);
2382 }
2383
2384 /*
2385 Local Variables:
2386 c-file-style: "gnu"
2387 End:
2388 */