Add bug-reference.el, goto-address.el.
[emacs.git] / src / process.c
blob3acf7d35e8033ccdb27055a80f192db71c43d92b
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
24 #include <config.h>
25 #include <signal.h>
27 /* This file is split into two parts by the following preprocessor
28 conditional. The 'then' clause contains all of the support for
29 asynchronous subprocesses. The 'else' clause contains stub
30 versions of some of the asynchronous subprocess routines that are
31 often called elsewhere in Emacs, so we don't have to #ifdef the
32 sections that call them. */
35 #ifdef subprocesses
37 #include <stdio.h>
38 #include <errno.h>
39 #include <setjmp.h>
40 #include <sys/types.h> /* some typedefs are used in sys/file.h */
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_INTTYPES_H
44 #include <inttypes.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
50 #if defined(WINDOWSNT) || defined(UNIX98_PTYS)
51 #include <stdlib.h>
52 #include <fcntl.h>
53 #endif /* not WINDOWSNT */
55 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
56 #include <sys/socket.h>
57 #include <netdb.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
61 /* Are local (unix) sockets supported? */
62 #if defined (HAVE_SYS_UN_H)
63 #if !defined (AF_LOCAL) && defined (AF_UNIX)
64 #define AF_LOCAL AF_UNIX
65 #endif
66 #ifdef AF_LOCAL
67 #define HAVE_LOCAL_SOCKETS
68 #include <sys/un.h>
69 #endif
70 #endif
71 #endif /* HAVE_SOCKETS */
73 /* TERM is a poor-man's SLIP, used on GNU/Linux. */
74 #ifdef TERM
75 #include <client.h>
76 #endif
78 #if defined(BSD_SYSTEM)
79 #include <sys/ioctl.h>
80 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
81 #include <fcntl.h>
82 #endif /* HAVE_PTYS and no O_NDELAY */
83 #endif /* BSD_SYSTEM */
85 #ifdef BROKEN_O_NONBLOCK
86 #undef O_NONBLOCK
87 #endif /* BROKEN_O_NONBLOCK */
89 #ifdef NEED_BSDTTY
90 #include <bsdtty.h>
91 #endif
93 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
94 #ifdef HAVE_SOCKETS
95 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
96 /* sys/ioctl.h may have been included already */
97 #ifndef SIOCGIFADDR
98 #include <sys/ioctl.h>
99 #endif
100 #include <net/if.h>
101 #endif
102 #endif
104 #ifdef IRIS
105 #include <sys/sysmacros.h> /* for "minor" */
106 #endif /* not IRIS */
108 #ifdef HAVE_SYS_WAIT
109 #include <sys/wait.h>
110 #endif
112 #ifdef HAVE_RES_INIT
113 #include <netinet/in.h>
114 #include <arpa/nameser.h>
115 #include <resolv.h>
116 #endif
118 #include "lisp.h"
119 #include "systime.h"
120 #include "systty.h"
122 #include "window.h"
123 #include "buffer.h"
124 #include "character.h"
125 #include "coding.h"
126 #include "process.h"
127 #include "frame.h"
128 #include "termhooks.h"
129 #include "termopts.h"
130 #include "commands.h"
131 #include "keyboard.h"
132 #include "blockinput.h"
133 #include "dispextern.h"
134 #include "composite.h"
135 #include "atimer.h"
137 Lisp_Object Qprocessp;
138 Lisp_Object Qrun, Qstop, Qsignal;
139 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
140 Lisp_Object Qlocal, Qipv4, Qdatagram;
141 #ifdef AF_INET6
142 Lisp_Object Qipv6;
143 #endif
144 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
145 Lisp_Object QClocal, QCremote, QCcoding;
146 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
147 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
148 Lisp_Object Qlast_nonmenu_event;
149 /* QCfamily is declared and initialized in xfaces.c,
150 QCfilter in keyboard.c. */
151 extern Lisp_Object QCfamily, QCfilter;
153 /* Qexit is declared and initialized in eval.c. */
155 /* QCfamily is defined in xfaces.c. */
156 extern Lisp_Object QCfamily;
157 /* QCfilter is defined in keyboard.c. */
158 extern Lisp_Object QCfilter;
160 /* a process object is a network connection when its childp field is neither
161 Qt nor Qnil but is instead a property list (KEY VAL ...). */
163 #ifdef HAVE_SOCKETS
164 #define NETCONN_P(p) (CONSP (XPROCESS (p)->childp))
165 #define NETCONN1_P(p) (CONSP ((p)->childp))
166 #else
167 #define NETCONN_P(p) 0
168 #define NETCONN1_P(p) 0
169 #endif /* HAVE_SOCKETS */
171 /* Define first descriptor number available for subprocesses. */
172 #ifdef VMS
173 #define FIRST_PROC_DESC 1
174 #else /* Not VMS */
175 #define FIRST_PROC_DESC 3
176 #endif
178 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
179 testing SIGCHLD. */
181 #if !defined (SIGCHLD) && defined (SIGCLD)
182 #define SIGCHLD SIGCLD
183 #endif /* SIGCLD */
185 #include "syssignal.h"
187 #include "syswait.h"
189 extern char *get_operating_system_release ();
191 #ifndef USE_CRT_DLL
192 extern int errno;
193 #endif
194 #ifdef VMS
195 extern char *sys_errlist[];
196 #endif
198 #ifndef HAVE_H_ERRNO
199 extern int h_errno;
200 #endif
202 /* t means use pty, nil means use a pipe,
203 maybe other values to come. */
204 static Lisp_Object Vprocess_connection_type;
206 /* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
208 /* Number of events of change of status of a process. */
209 int process_tick;
210 /* Number of events for which the user or sentinel has been notified. */
211 int update_tick;
213 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
215 #ifdef BROKEN_NON_BLOCKING_CONNECT
216 #undef NON_BLOCKING_CONNECT
217 #else
218 #ifndef NON_BLOCKING_CONNECT
219 #ifdef HAVE_SOCKETS
220 #ifdef HAVE_SELECT
221 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
222 #if defined (O_NONBLOCK) || defined (O_NDELAY)
223 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
224 #define NON_BLOCKING_CONNECT
225 #endif /* EWOULDBLOCK || EINPROGRESS */
226 #endif /* O_NONBLOCK || O_NDELAY */
227 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
228 #endif /* HAVE_SELECT */
229 #endif /* HAVE_SOCKETS */
230 #endif /* NON_BLOCKING_CONNECT */
231 #endif /* BROKEN_NON_BLOCKING_CONNECT */
233 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
234 this system. We need to read full packets, so we need a
235 "non-destructive" select. So we require either native select,
236 or emulation of select using FIONREAD. */
238 #ifdef BROKEN_DATAGRAM_SOCKETS
239 #undef DATAGRAM_SOCKETS
240 #else
241 #ifndef DATAGRAM_SOCKETS
242 #ifdef HAVE_SOCKETS
243 #if defined (HAVE_SELECT) || defined (FIONREAD)
244 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
245 #define DATAGRAM_SOCKETS
246 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
247 #endif /* HAVE_SELECT || FIONREAD */
248 #endif /* HAVE_SOCKETS */
249 #endif /* DATAGRAM_SOCKETS */
250 #endif /* BROKEN_DATAGRAM_SOCKETS */
252 #ifdef TERM
253 #undef NON_BLOCKING_CONNECT
254 #undef DATAGRAM_SOCKETS
255 #endif
257 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
258 #ifdef EMACS_HAS_USECS
259 #define ADAPTIVE_READ_BUFFERING
260 #endif
261 #endif
263 #ifdef ADAPTIVE_READ_BUFFERING
264 #define READ_OUTPUT_DELAY_INCREMENT 10000
265 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
266 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
268 /* Number of processes which have a non-zero read_output_delay,
269 and therefore might be delayed for adaptive read buffering. */
271 static int process_output_delay_count;
273 /* Non-zero if any process has non-nil read_output_skip. */
275 static int process_output_skip;
277 /* Non-nil means to delay reading process output to improve buffering.
278 A value of t means that delay is reset after each send, any other
279 non-nil value does not reset the delay. A value of nil disables
280 adaptive read buffering completely. */
281 static Lisp_Object Vprocess_adaptive_read_buffering;
282 #else
283 #define process_output_delay_count 0
284 #endif
287 #include "sysselect.h"
289 static int keyboard_bit_set P_ ((SELECT_TYPE *));
290 static void deactivate_process P_ ((Lisp_Object));
291 static void status_notify P_ ((struct Lisp_Process *));
292 static int read_process_output P_ ((Lisp_Object, int));
294 /* If we support a window system, turn on the code to poll periodically
295 to detect C-g. It isn't actually used when doing interrupt input. */
296 #ifdef HAVE_WINDOW_SYSTEM
297 #define POLL_FOR_INPUT
298 #endif
300 static Lisp_Object get_process ();
301 static void exec_sentinel ();
303 extern EMACS_TIME timer_check ();
304 extern int timers_run;
306 /* Mask of bits indicating the descriptors that we wait for input on. */
308 static SELECT_TYPE input_wait_mask;
310 /* Mask that excludes keyboard input descriptor(s). */
312 static SELECT_TYPE non_keyboard_wait_mask;
314 /* Mask that excludes process input descriptor(s). */
316 static SELECT_TYPE non_process_wait_mask;
318 /* Mask for the gpm mouse input descriptor. */
320 static SELECT_TYPE gpm_wait_mask;
322 #ifdef NON_BLOCKING_CONNECT
323 /* Mask of bits indicating the descriptors that we wait for connect to
324 complete on. Once they complete, they are removed from this mask
325 and added to the input_wait_mask and non_keyboard_wait_mask. */
327 static SELECT_TYPE connect_wait_mask;
329 /* Number of bits set in connect_wait_mask. */
330 static int num_pending_connects;
332 #define IF_NON_BLOCKING_CONNECT(s) s
333 #else
334 #define IF_NON_BLOCKING_CONNECT(s)
335 #endif
337 /* The largest descriptor currently in use for a process object. */
338 static int max_process_desc;
340 /* The largest descriptor currently in use for keyboard input. */
341 static int max_keyboard_desc;
343 /* The largest descriptor currently in use for gpm mouse input. */
344 static int max_gpm_desc;
346 /* Nonzero means delete a process right away if it exits. */
347 static int delete_exited_processes;
349 /* Indexed by descriptor, gives the process (if any) for that descriptor */
350 Lisp_Object chan_process[MAXDESC];
352 /* Alist of elements (NAME . PROCESS) */
353 Lisp_Object Vprocess_alist;
355 /* Buffered-ahead input char from process, indexed by channel.
356 -1 means empty (no char is buffered).
357 Used on sys V where the only way to tell if there is any
358 output from the process is to read at least one char.
359 Always -1 on systems that support FIONREAD. */
361 /* Don't make static; need to access externally. */
362 int proc_buffered_char[MAXDESC];
364 /* Table of `struct coding-system' for each process. */
365 static struct coding_system *proc_decode_coding_system[MAXDESC];
366 static struct coding_system *proc_encode_coding_system[MAXDESC];
368 #ifdef DATAGRAM_SOCKETS
369 /* Table of `partner address' for datagram sockets. */
370 struct sockaddr_and_len {
371 struct sockaddr *sa;
372 int len;
373 } datagram_address[MAXDESC];
374 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
375 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
376 #else
377 #define DATAGRAM_CHAN_P(chan) (0)
378 #define DATAGRAM_CONN_P(proc) (0)
379 #endif
381 /* Maximum number of bytes to send to a pty without an eof. */
382 static int pty_max_bytes;
384 /* Nonzero means don't run process sentinels. This is used
385 when exiting. */
386 int inhibit_sentinels;
388 #ifdef HAVE_PTYS
389 #ifdef HAVE_PTY_H
390 #include <pty.h>
391 #endif
392 /* The file name of the pty opened by allocate_pty. */
394 static char pty_name[24];
395 #endif
397 /* Compute the Lisp form of the process status, p->status, from
398 the numeric status that was returned by `wait'. */
400 static Lisp_Object status_convert ();
402 static void
403 update_status (p)
404 struct Lisp_Process *p;
406 union { int i; WAITTYPE wt; } u;
407 eassert (p->raw_status_new);
408 u.i = p->raw_status;
409 p->status = status_convert (u.wt);
410 p->raw_status_new = 0;
413 /* Convert a process status word in Unix format to
414 the list that we use internally. */
416 static Lisp_Object
417 status_convert (w)
418 WAITTYPE w;
420 if (WIFSTOPPED (w))
421 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
422 else if (WIFEXITED (w))
423 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
424 WCOREDUMP (w) ? Qt : Qnil));
425 else if (WIFSIGNALED (w))
426 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
427 WCOREDUMP (w) ? Qt : Qnil));
428 else
429 return Qrun;
432 /* Given a status-list, extract the three pieces of information
433 and store them individually through the three pointers. */
435 static void
436 decode_status (l, symbol, code, coredump)
437 Lisp_Object l;
438 Lisp_Object *symbol;
439 int *code;
440 int *coredump;
442 Lisp_Object tem;
444 if (SYMBOLP (l))
446 *symbol = l;
447 *code = 0;
448 *coredump = 0;
450 else
452 *symbol = XCAR (l);
453 tem = XCDR (l);
454 *code = XFASTINT (XCAR (tem));
455 tem = XCDR (tem);
456 *coredump = !NILP (tem);
460 /* Return a string describing a process status list. */
462 static Lisp_Object
463 status_message (p)
464 struct Lisp_Process *p;
466 Lisp_Object status = p->status;
467 Lisp_Object symbol;
468 int code, coredump;
469 Lisp_Object string, string2;
471 decode_status (status, &symbol, &code, &coredump);
473 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
475 char *signame;
476 synchronize_system_messages_locale ();
477 signame = strsignal (code);
478 if (signame == 0)
479 signame = "unknown";
480 string = build_string (signame);
481 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
482 SSET (string, 0, DOWNCASE (SREF (string, 0)));
483 return concat2 (string, string2);
485 else if (EQ (symbol, Qexit))
487 if (NETCONN1_P (p))
488 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
489 if (code == 0)
490 return build_string ("finished\n");
491 string = Fnumber_to_string (make_number (code));
492 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
493 return concat3 (build_string ("exited abnormally with code "),
494 string, string2);
496 else if (EQ (symbol, Qfailed))
498 string = Fnumber_to_string (make_number (code));
499 string2 = build_string ("\n");
500 return concat3 (build_string ("failed with code "),
501 string, string2);
503 else
504 return Fcopy_sequence (Fsymbol_name (symbol));
507 #ifdef HAVE_PTYS
509 /* Open an available pty, returning a file descriptor.
510 Return -1 on failure.
511 The file name of the terminal corresponding to the pty
512 is left in the variable pty_name. */
514 static int
515 allocate_pty ()
517 register int c, i;
518 int fd;
520 #ifdef PTY_ITERATION
521 PTY_ITERATION
522 #else
523 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
524 for (i = 0; i < 16; i++)
525 #endif
527 struct stat stb; /* Used in some PTY_OPEN. */
528 #ifdef PTY_NAME_SPRINTF
529 PTY_NAME_SPRINTF
530 #else
531 sprintf (pty_name, "/dev/pty%c%x", c, i);
532 #endif /* no PTY_NAME_SPRINTF */
534 #ifdef PTY_OPEN
535 PTY_OPEN;
536 #else /* no PTY_OPEN */
538 # ifdef IRIS
539 /* Unusual IRIS code */
540 *ptyv = emacs_open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
541 if (fd < 0)
542 return -1;
543 if (fstat (fd, &stb) < 0)
544 return -1;
545 # else /* not IRIS */
546 { /* Some systems name their pseudoterminals so that there are gaps in
547 the usual sequence - for example, on HP9000/S700 systems, there
548 are no pseudoterminals with names ending in 'f'. So we wait for
549 three failures in a row before deciding that we've reached the
550 end of the ptys. */
551 int failed_count = 0;
553 if (stat (pty_name, &stb) < 0)
555 failed_count++;
556 if (failed_count >= 3)
557 return -1;
559 else
560 failed_count = 0;
562 # ifdef O_NONBLOCK
563 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
564 # else
565 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
566 # endif
567 # endif /* not IRIS */
569 #endif /* no PTY_OPEN */
571 if (fd >= 0)
573 /* check to make certain that both sides are available
574 this avoids a nasty yet stupid bug in rlogins */
575 #ifdef PTY_TTY_NAME_SPRINTF
576 PTY_TTY_NAME_SPRINTF
577 #else
578 sprintf (pty_name, "/dev/tty%c%x", c, i);
579 #endif /* no PTY_TTY_NAME_SPRINTF */
580 if (access (pty_name, 6) != 0)
582 emacs_close (fd);
583 # if !defined(IRIS) && !defined(__sgi)
584 continue;
585 # else
586 return -1;
587 # endif /* IRIS */
589 setup_pty (fd);
590 return fd;
593 return -1;
595 #endif /* HAVE_PTYS */
597 static Lisp_Object
598 make_process (name)
599 Lisp_Object name;
601 register Lisp_Object val, tem, name1;
602 register struct Lisp_Process *p;
603 char suffix[10];
604 register int i;
606 p = allocate_process ();
608 p->infd = -1;
609 p->outfd = -1;
610 p->tick = 0;
611 p->update_tick = 0;
612 p->pid = 0;
613 p->pty_flag = 0;
614 p->raw_status_new = 0;
615 p->status = Qrun;
616 p->mark = Fmake_marker ();
618 #ifdef ADAPTIVE_READ_BUFFERING
619 p->adaptive_read_buffering = 0;
620 p->read_output_delay = 0;
621 p->read_output_skip = 0;
622 #endif
624 /* If name is already in use, modify it until it is unused. */
626 name1 = name;
627 for (i = 1; ; i++)
629 tem = Fget_process (name1);
630 if (NILP (tem)) break;
631 sprintf (suffix, "<%d>", i);
632 name1 = concat2 (name, build_string (suffix));
634 name = name1;
635 p->name = name;
636 XSETPROCESS (val, p);
637 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
638 return val;
641 static void
642 remove_process (proc)
643 register Lisp_Object proc;
645 register Lisp_Object pair;
647 pair = Frassq (proc, Vprocess_alist);
648 Vprocess_alist = Fdelq (pair, Vprocess_alist);
650 deactivate_process (proc);
653 /* Setup coding systems of PROCESS. */
655 void
656 setup_process_coding_systems (process)
657 Lisp_Object process;
659 struct Lisp_Process *p = XPROCESS (process);
660 int inch = p->infd;
661 int outch = p->outfd;
662 Lisp_Object coding_system;
664 if (inch < 0 || outch < 0)
665 return;
667 if (!proc_decode_coding_system[inch])
668 proc_decode_coding_system[inch]
669 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
670 coding_system = p->decode_coding_system;
671 if (! NILP (p->filter))
673 else if (BUFFERP (p->buffer))
675 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
676 coding_system = raw_text_coding_system (coding_system);
678 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
680 if (!proc_encode_coding_system[outch])
681 proc_encode_coding_system[outch]
682 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
683 setup_coding_system (p->encode_coding_system,
684 proc_encode_coding_system[outch]);
687 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
688 doc: /* Return t if OBJECT is a process. */)
689 (object)
690 Lisp_Object object;
692 return PROCESSP (object) ? Qt : Qnil;
695 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
696 doc: /* Return the process named NAME, or nil if there is none. */)
697 (name)
698 register Lisp_Object name;
700 if (PROCESSP (name))
701 return name;
702 CHECK_STRING (name);
703 return Fcdr (Fassoc (name, Vprocess_alist));
706 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
707 doc: /* Return the (or a) process associated with BUFFER.
708 BUFFER may be a buffer or the name of one. */)
709 (buffer)
710 register Lisp_Object buffer;
712 register Lisp_Object buf, tail, proc;
714 if (NILP (buffer)) return Qnil;
715 buf = Fget_buffer (buffer);
716 if (NILP (buf)) return Qnil;
718 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
720 proc = Fcdr (XCAR (tail));
721 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
722 return proc;
724 return Qnil;
727 /* This is how commands for the user decode process arguments. It
728 accepts a process, a process name, a buffer, a buffer name, or nil.
729 Buffers denote the first process in the buffer, and nil denotes the
730 current buffer. */
732 static Lisp_Object
733 get_process (name)
734 register Lisp_Object name;
736 register Lisp_Object proc, obj;
737 if (STRINGP (name))
739 obj = Fget_process (name);
740 if (NILP (obj))
741 obj = Fget_buffer (name);
742 if (NILP (obj))
743 error ("Process %s does not exist", SDATA (name));
745 else if (NILP (name))
746 obj = Fcurrent_buffer ();
747 else
748 obj = name;
750 /* Now obj should be either a buffer object or a process object.
752 if (BUFFERP (obj))
754 proc = Fget_buffer_process (obj);
755 if (NILP (proc))
756 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
758 else
760 CHECK_PROCESS (obj);
761 proc = obj;
763 return proc;
767 #ifdef SIGCHLD
768 /* Fdelete_process promises to immediately forget about the process, but in
769 reality, Emacs needs to remember those processes until they have been
770 treated by sigchld_handler; otherwise this handler would consider the
771 process as being synchronous and say that the synchronous process is
772 dead. */
773 static Lisp_Object deleted_pid_list;
774 #endif
776 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
777 doc: /* Delete PROCESS: kill it and forget about it immediately.
778 PROCESS may be a process, a buffer, the name of a process or buffer, or
779 nil, indicating the current buffer's process. */)
780 (process)
781 register Lisp_Object process;
783 register struct Lisp_Process *p;
785 process = get_process (process);
786 p = XPROCESS (process);
788 p->raw_status_new = 0;
789 if (NETCONN1_P (p))
791 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
792 p->tick = ++process_tick;
793 status_notify (p);
795 else if (p->infd >= 0)
797 #ifdef SIGCHLD
798 Lisp_Object symbol;
799 /* Assignment to EMACS_INT stops GCC whining about limited range
800 of data type. */
801 EMACS_INT pid = p->pid;
803 /* No problem storing the pid here, as it is still in Vprocess_alist. */
804 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
805 /* GC treated elements set to nil. */
806 Fdelq (Qnil, deleted_pid_list));
807 /* If the process has already signaled, remove it from the list. */
808 if (p->raw_status_new)
809 update_status (p);
810 symbol = p->status;
811 if (CONSP (p->status))
812 symbol = XCAR (p->status);
813 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
814 deleted_pid_list
815 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
816 else
817 #endif
819 Fkill_process (process, Qnil);
820 /* Do this now, since remove_process will make sigchld_handler do nothing. */
821 p->status
822 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
823 p->tick = ++process_tick;
824 status_notify (p);
827 remove_process (process);
828 return Qnil;
831 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
832 doc: /* Return the status of PROCESS.
833 The returned value is one of the following symbols:
834 run -- for a process that is running.
835 stop -- for a process stopped but continuable.
836 exit -- for a process that has exited.
837 signal -- for a process that has got a fatal signal.
838 open -- for a network stream connection that is open.
839 listen -- for a network stream server that is listening.
840 closed -- for a network stream connection that is closed.
841 connect -- when waiting for a non-blocking connection to complete.
842 failed -- when a non-blocking connection has failed.
843 nil -- if arg is a process name and no such process exists.
844 PROCESS may be a process, a buffer, the name of a process, or
845 nil, indicating the current buffer's process. */)
846 (process)
847 register Lisp_Object process;
849 register struct Lisp_Process *p;
850 register Lisp_Object status;
852 if (STRINGP (process))
853 process = Fget_process (process);
854 else
855 process = get_process (process);
857 if (NILP (process))
858 return process;
860 p = XPROCESS (process);
861 if (p->raw_status_new)
862 update_status (p);
863 status = p->status;
864 if (CONSP (status))
865 status = XCAR (status);
866 if (NETCONN1_P (p))
868 if (EQ (status, Qexit))
869 status = Qclosed;
870 else if (EQ (p->command, Qt))
871 status = Qstop;
872 else if (EQ (status, Qrun))
873 status = Qopen;
875 return status;
878 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
879 1, 1, 0,
880 doc: /* Return the exit status of PROCESS or the signal number that killed it.
881 If PROCESS has not yet exited or died, return 0. */)
882 (process)
883 register Lisp_Object process;
885 CHECK_PROCESS (process);
886 if (XPROCESS (process)->raw_status_new)
887 update_status (XPROCESS (process));
888 if (CONSP (XPROCESS (process)->status))
889 return XCAR (XCDR (XPROCESS (process)->status));
890 return make_number (0);
893 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
894 doc: /* Return the process id of PROCESS.
895 This is the pid of the external process which PROCESS uses or talks to.
896 For a network connection, this value is nil. */)
897 (process)
898 register Lisp_Object process;
900 /* Assignment to EMACS_INT stops GCC whining about limited range of
901 data type. */
902 EMACS_INT pid;
904 CHECK_PROCESS (process);
905 pid = XPROCESS (process)->pid;
906 return (pid ? make_fixnum_or_float (pid) : Qnil);
909 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
910 doc: /* Return the name of PROCESS, as a string.
911 This is the name of the program invoked in PROCESS,
912 possibly modified to make it unique among process names. */)
913 (process)
914 register Lisp_Object process;
916 CHECK_PROCESS (process);
917 return XPROCESS (process)->name;
920 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
921 doc: /* Return the command that was executed to start PROCESS.
922 This is a list of strings, the first string being the program executed
923 and the rest of the strings being the arguments given to it.
924 For a non-child channel, this is nil. */)
925 (process)
926 register Lisp_Object process;
928 CHECK_PROCESS (process);
929 return XPROCESS (process)->command;
932 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
933 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
934 This is the terminal that the process itself reads and writes on,
935 not the name of the pty that Emacs uses to talk with that terminal. */)
936 (process)
937 register Lisp_Object process;
939 CHECK_PROCESS (process);
940 return XPROCESS (process)->tty_name;
943 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
944 2, 2, 0,
945 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
946 (process, buffer)
947 register Lisp_Object process, buffer;
949 struct Lisp_Process *p;
951 CHECK_PROCESS (process);
952 if (!NILP (buffer))
953 CHECK_BUFFER (buffer);
954 p = XPROCESS (process);
955 p->buffer = buffer;
956 if (NETCONN1_P (p))
957 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
958 setup_process_coding_systems (process);
959 return buffer;
962 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
963 1, 1, 0,
964 doc: /* Return the buffer PROCESS is associated with.
965 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
966 (process)
967 register Lisp_Object process;
969 CHECK_PROCESS (process);
970 return XPROCESS (process)->buffer;
973 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
974 1, 1, 0,
975 doc: /* Return the marker for the end of the last output from PROCESS. */)
976 (process)
977 register Lisp_Object process;
979 CHECK_PROCESS (process);
980 return XPROCESS (process)->mark;
983 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
984 2, 2, 0,
985 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
986 A value of t means stop accepting output from the process.
988 When a process has a filter, its buffer is not used for output.
989 Instead, each time it does output, the entire string of output is
990 passed to the filter.
992 The filter gets two arguments: the process and the string of output.
993 The string argument is normally a multibyte string, except:
994 - if the process' input coding system is no-conversion or raw-text,
995 it is a unibyte string (the non-converted input), or else
996 - if `default-enable-multibyte-characters' is nil, it is a unibyte
997 string (the result of converting the decoded input multibyte
998 string to unibyte with `string-make-unibyte'). */)
999 (process, filter)
1000 register Lisp_Object process, filter;
1002 struct Lisp_Process *p;
1004 CHECK_PROCESS (process);
1005 p = XPROCESS (process);
1007 /* Don't signal an error if the process' input file descriptor
1008 is closed. This could make debugging Lisp more difficult,
1009 for example when doing something like
1011 (setq process (start-process ...))
1012 (debug)
1013 (set-process-filter process ...) */
1015 if (p->infd >= 0)
1017 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1019 FD_CLR (p->infd, &input_wait_mask);
1020 FD_CLR (p->infd, &non_keyboard_wait_mask);
1022 else if (EQ (p->filter, Qt)
1023 && !EQ (p->command, Qt)) /* Network process not stopped. */
1025 FD_SET (p->infd, &input_wait_mask);
1026 FD_SET (p->infd, &non_keyboard_wait_mask);
1030 p->filter = filter;
1031 if (NETCONN1_P (p))
1032 p->childp = Fplist_put (p->childp, QCfilter, filter);
1033 setup_process_coding_systems (process);
1034 return filter;
1037 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1038 1, 1, 0,
1039 doc: /* Returns the filter function of PROCESS; nil if none.
1040 See `set-process-filter' for more info on filter functions. */)
1041 (process)
1042 register Lisp_Object process;
1044 CHECK_PROCESS (process);
1045 return XPROCESS (process)->filter;
1048 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1049 2, 2, 0,
1050 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1051 The sentinel is called as a function when the process changes state.
1052 It gets two arguments: the process, and a string describing the change. */)
1053 (process, sentinel)
1054 register Lisp_Object process, sentinel;
1056 struct Lisp_Process *p;
1058 CHECK_PROCESS (process);
1059 p = XPROCESS (process);
1061 p->sentinel = sentinel;
1062 if (NETCONN1_P (p))
1063 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1064 return sentinel;
1067 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1068 1, 1, 0,
1069 doc: /* Return the sentinel of PROCESS; nil if none.
1070 See `set-process-sentinel' for more info on sentinels. */)
1071 (process)
1072 register Lisp_Object process;
1074 CHECK_PROCESS (process);
1075 return XPROCESS (process)->sentinel;
1078 DEFUN ("set-process-window-size", Fset_process_window_size,
1079 Sset_process_window_size, 3, 3, 0,
1080 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1081 (process, height, width)
1082 register Lisp_Object process, height, width;
1084 CHECK_PROCESS (process);
1085 CHECK_NATNUM (height);
1086 CHECK_NATNUM (width);
1088 if (XPROCESS (process)->infd < 0
1089 || set_window_size (XPROCESS (process)->infd,
1090 XINT (height), XINT (width)) <= 0)
1091 return Qnil;
1092 else
1093 return Qt;
1096 DEFUN ("set-process-inherit-coding-system-flag",
1097 Fset_process_inherit_coding_system_flag,
1098 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1099 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1100 If the second argument FLAG is non-nil, then the variable
1101 `buffer-file-coding-system' of the buffer associated with PROCESS
1102 will be bound to the value of the coding system used to decode
1103 the process output.
1105 This is useful when the coding system specified for the process buffer
1106 leaves either the character code conversion or the end-of-line conversion
1107 unspecified, or if the coding system used to decode the process output
1108 is more appropriate for saving the process buffer.
1110 Binding the variable `inherit-process-coding-system' to non-nil before
1111 starting the process is an alternative way of setting the inherit flag
1112 for the process which will run. */)
1113 (process, flag)
1114 register Lisp_Object process, flag;
1116 CHECK_PROCESS (process);
1117 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1118 return flag;
1121 DEFUN ("process-inherit-coding-system-flag",
1122 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1123 1, 1, 0,
1124 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1125 If this flag is t, `buffer-file-coding-system' of the buffer
1126 associated with PROCESS will inherit the coding system used to decode
1127 the process output. */)
1128 (process)
1129 register Lisp_Object process;
1131 CHECK_PROCESS (process);
1132 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1135 DEFUN ("set-process-query-on-exit-flag",
1136 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1137 2, 2, 0,
1138 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1139 If the second argument FLAG is non-nil, Emacs will query the user before
1140 exiting if PROCESS is running. */)
1141 (process, flag)
1142 register Lisp_Object process, flag;
1144 CHECK_PROCESS (process);
1145 XPROCESS (process)->kill_without_query = NILP (flag);
1146 return flag;
1149 DEFUN ("process-query-on-exit-flag",
1150 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1151 1, 1, 0,
1152 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1153 (process)
1154 register Lisp_Object process;
1156 CHECK_PROCESS (process);
1157 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1160 #ifdef DATAGRAM_SOCKETS
1161 Lisp_Object Fprocess_datagram_address ();
1162 #endif
1164 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1165 1, 2, 0,
1166 doc: /* Return the contact info of PROCESS; t for a real child.
1167 For a net connection, the value depends on the optional KEY arg.
1168 If KEY is nil, value is a cons cell of the form (HOST SERVICE),
1169 if KEY is t, the complete contact information for the connection is
1170 returned, else the specific value for the keyword KEY is returned.
1171 See `make-network-process' for a list of keywords. */)
1172 (process, key)
1173 register Lisp_Object process, key;
1175 Lisp_Object contact;
1177 CHECK_PROCESS (process);
1178 contact = XPROCESS (process)->childp;
1180 #ifdef DATAGRAM_SOCKETS
1181 if (DATAGRAM_CONN_P (process)
1182 && (EQ (key, Qt) || EQ (key, QCremote)))
1183 contact = Fplist_put (contact, QCremote,
1184 Fprocess_datagram_address (process));
1185 #endif
1187 if (!NETCONN_P (process) || EQ (key, Qt))
1188 return contact;
1189 if (NILP (key))
1190 return Fcons (Fplist_get (contact, QChost),
1191 Fcons (Fplist_get (contact, QCservice), Qnil));
1192 return Fplist_get (contact, key);
1195 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1196 1, 1, 0,
1197 doc: /* Return the plist of PROCESS. */)
1198 (process)
1199 register Lisp_Object process;
1201 CHECK_PROCESS (process);
1202 return XPROCESS (process)->plist;
1205 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1206 2, 2, 0,
1207 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1208 (process, plist)
1209 register Lisp_Object process, plist;
1211 CHECK_PROCESS (process);
1212 CHECK_LIST (plist);
1214 XPROCESS (process)->plist = plist;
1215 return plist;
1218 #if 0 /* Turned off because we don't currently record this info
1219 in the process. Perhaps add it. */
1220 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1221 doc: /* Return the connection type of PROCESS.
1222 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1223 a socket connection. */)
1224 (process)
1225 Lisp_Object process;
1227 return XPROCESS (process)->type;
1229 #endif
1231 #ifdef HAVE_SOCKETS
1232 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1233 1, 2, 0,
1234 doc: /* Convert network ADDRESS from internal format to a string.
1235 A 4 or 5 element vector represents an IPv4 address (with port number).
1236 An 8 or 9 element vector represents an IPv6 address (with port number).
1237 If optional second argument OMIT-PORT is non-nil, don't include a port
1238 number in the string, even when present in ADDRESS.
1239 Returns nil if format of ADDRESS is invalid. */)
1240 (address, omit_port)
1241 Lisp_Object address, omit_port;
1243 if (NILP (address))
1244 return Qnil;
1246 if (STRINGP (address)) /* AF_LOCAL */
1247 return address;
1249 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1251 register struct Lisp_Vector *p = XVECTOR (address);
1252 Lisp_Object args[10];
1253 int nargs, i;
1255 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1257 args[0] = build_string ("%d.%d.%d.%d");
1258 nargs = 4;
1260 else if (p->size == 5)
1262 args[0] = build_string ("%d.%d.%d.%d:%d");
1263 nargs = 5;
1265 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1267 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1268 nargs = 8;
1270 else if (p->size == 9)
1272 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1273 nargs = 9;
1275 else
1276 return Qnil;
1278 for (i = 0; i < nargs; i++)
1280 EMACS_INT element = XINT (p->contents[i]);
1282 if (element < 0 || element > 65535)
1283 return Qnil;
1285 if (nargs <= 5 /* IPv4 */
1286 && i < 4 /* host, not port */
1287 && element > 255)
1288 return Qnil;
1290 args[i+1] = p->contents[i];
1293 return Fformat (nargs+1, args);
1296 if (CONSP (address))
1298 Lisp_Object args[2];
1299 args[0] = build_string ("<Family %d>");
1300 args[1] = Fcar (address);
1301 return Fformat (2, args);
1304 return Qnil;
1306 #endif
1308 static Lisp_Object
1309 list_processes_1 (query_only)
1310 Lisp_Object query_only;
1312 register Lisp_Object tail, tem;
1313 Lisp_Object proc, minspace, tem1;
1314 register struct Lisp_Process *p;
1315 char tembuf[300];
1316 int w_proc, w_buffer, w_tty;
1317 int exited = 0;
1318 Lisp_Object i_status, i_buffer, i_tty, i_command;
1320 w_proc = 4; /* Proc */
1321 w_buffer = 6; /* Buffer */
1322 w_tty = 0; /* Omit if no ttys */
1324 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1326 int i;
1328 proc = Fcdr (XCAR (tail));
1329 p = XPROCESS (proc);
1330 if (NILP (p->childp))
1331 continue;
1332 if (!NILP (query_only) && p->kill_without_query)
1333 continue;
1334 if (STRINGP (p->name)
1335 && ( i = SCHARS (p->name), (i > w_proc)))
1336 w_proc = i;
1337 if (!NILP (p->buffer))
1339 if (NILP (XBUFFER (p->buffer)->name))
1341 if (w_buffer < 8)
1342 w_buffer = 8; /* (Killed) */
1344 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1345 w_buffer = i;
1347 if (STRINGP (p->tty_name)
1348 && (i = SCHARS (p->tty_name), (i > w_tty)))
1349 w_tty = i;
1352 XSETFASTINT (i_status, w_proc + 1);
1353 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1354 if (w_tty)
1356 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1357 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1359 else
1361 i_tty = Qnil;
1362 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1365 XSETFASTINT (minspace, 1);
1367 set_buffer_internal (XBUFFER (Vstandard_output));
1368 current_buffer->undo_list = Qt;
1370 current_buffer->truncate_lines = Qt;
1372 write_string ("Proc", -1);
1373 Findent_to (i_status, minspace); write_string ("Status", -1);
1374 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1375 if (!NILP (i_tty))
1377 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1379 Findent_to (i_command, minspace); write_string ("Command", -1);
1380 write_string ("\n", -1);
1382 write_string ("----", -1);
1383 Findent_to (i_status, minspace); write_string ("------", -1);
1384 Findent_to (i_buffer, minspace); write_string ("------", -1);
1385 if (!NILP (i_tty))
1387 Findent_to (i_tty, minspace); write_string ("---", -1);
1389 Findent_to (i_command, minspace); write_string ("-------", -1);
1390 write_string ("\n", -1);
1392 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1394 Lisp_Object symbol;
1396 proc = Fcdr (XCAR (tail));
1397 p = XPROCESS (proc);
1398 if (NILP (p->childp))
1399 continue;
1400 if (!NILP (query_only) && p->kill_without_query)
1401 continue;
1403 Finsert (1, &p->name);
1404 Findent_to (i_status, minspace);
1406 if (p->raw_status_new)
1407 update_status (p);
1408 symbol = p->status;
1409 if (CONSP (p->status))
1410 symbol = XCAR (p->status);
1412 if (EQ (symbol, Qsignal))
1414 Lisp_Object tem;
1415 tem = Fcar (Fcdr (p->status));
1416 #ifdef VMS
1417 if (XINT (tem) < NSIG)
1418 write_string (sys_errlist [XINT (tem)], -1);
1419 else
1420 #endif
1421 Fprinc (symbol, Qnil);
1423 else if (NETCONN1_P (p))
1425 if (EQ (symbol, Qexit))
1426 write_string ("closed", -1);
1427 else if (EQ (p->command, Qt))
1428 write_string ("stopped", -1);
1429 else if (EQ (symbol, Qrun))
1430 write_string ("open", -1);
1431 else
1432 Fprinc (symbol, Qnil);
1434 else
1435 Fprinc (symbol, Qnil);
1437 if (EQ (symbol, Qexit))
1439 Lisp_Object tem;
1440 tem = Fcar (Fcdr (p->status));
1441 if (XFASTINT (tem))
1443 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1444 write_string (tembuf, -1);
1448 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1449 exited++;
1451 Findent_to (i_buffer, minspace);
1452 if (NILP (p->buffer))
1453 insert_string ("(none)");
1454 else if (NILP (XBUFFER (p->buffer)->name))
1455 insert_string ("(Killed)");
1456 else
1457 Finsert (1, &XBUFFER (p->buffer)->name);
1459 if (!NILP (i_tty))
1461 Findent_to (i_tty, minspace);
1462 if (STRINGP (p->tty_name))
1463 Finsert (1, &p->tty_name);
1466 Findent_to (i_command, minspace);
1468 if (EQ (p->status, Qlisten))
1470 Lisp_Object port = Fplist_get (p->childp, QCservice);
1471 if (INTEGERP (port))
1472 port = Fnumber_to_string (port);
1473 if (NILP (port))
1474 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1475 sprintf (tembuf, "(network %s server on %s)\n",
1476 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1477 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1478 insert_string (tembuf);
1480 else if (NETCONN1_P (p))
1482 /* For a local socket, there is no host name,
1483 so display service instead. */
1484 Lisp_Object host = Fplist_get (p->childp, QChost);
1485 if (!STRINGP (host))
1487 host = Fplist_get (p->childp, QCservice);
1488 if (INTEGERP (host))
1489 host = Fnumber_to_string (host);
1491 if (NILP (host))
1492 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1493 sprintf (tembuf, "(network %s connection to %s)\n",
1494 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1495 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1496 insert_string (tembuf);
1498 else
1500 tem = p->command;
1501 while (1)
1503 tem1 = Fcar (tem);
1504 Finsert (1, &tem1);
1505 tem = Fcdr (tem);
1506 if (NILP (tem))
1507 break;
1508 insert_string (" ");
1510 insert_string ("\n");
1513 if (exited)
1514 status_notify (NULL);
1515 return Qnil;
1518 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1519 doc: /* Display a list of all processes.
1520 If optional argument QUERY-ONLY is non-nil, only processes with
1521 the query-on-exit flag set will be listed.
1522 Any process listed as exited or signaled is actually eliminated
1523 after the listing is made. */)
1524 (query_only)
1525 Lisp_Object query_only;
1527 internal_with_output_to_temp_buffer ("*Process List*",
1528 list_processes_1, query_only);
1529 return Qnil;
1532 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1533 doc: /* Return a list of all processes. */)
1536 return Fmapcar (Qcdr, Vprocess_alist);
1539 /* Starting asynchronous inferior processes. */
1541 static Lisp_Object start_process_unwind ();
1543 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1544 doc: /* Start a program in a subprocess. Return the process object for it.
1545 NAME is name for process. It is modified if necessary to make it unique.
1546 BUFFER is the buffer (or buffer name) to associate with the process.
1548 Process output (both standard output and standard error streams) goes
1549 at end of BUFFER, unless you specify an output stream or filter
1550 function to handle the output. BUFFER may also be nil, meaning that
1551 this process is not associated with any buffer.
1553 PROGRAM is the program file name. It is searched for in PATH.
1554 Remaining arguments are strings to give program as arguments.
1556 If you want to separate standard output from standard error, invoke
1557 the command through a shell and redirect one of them using the shell
1558 syntax.
1560 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1561 (nargs, args)
1562 int nargs;
1563 register Lisp_Object *args;
1565 Lisp_Object buffer, name, program, proc, current_dir, tem;
1566 #ifdef VMS
1567 register unsigned char *new_argv;
1568 int len;
1569 #else
1570 register unsigned char **new_argv;
1571 #endif
1572 register int i;
1573 int count = SPECPDL_INDEX ();
1575 buffer = args[1];
1576 if (!NILP (buffer))
1577 buffer = Fget_buffer_create (buffer);
1579 /* Make sure that the child will be able to chdir to the current
1580 buffer's current directory, or its unhandled equivalent. We
1581 can't just have the child check for an error when it does the
1582 chdir, since it's in a vfork.
1584 We have to GCPRO around this because Fexpand_file_name and
1585 Funhandled_file_name_directory might call a file name handling
1586 function. The argument list is protected by the caller, so all
1587 we really have to worry about is buffer. */
1589 struct gcpro gcpro1, gcpro2;
1591 current_dir = current_buffer->directory;
1593 GCPRO2 (buffer, current_dir);
1595 current_dir = Funhandled_file_name_directory (current_dir);
1596 if (NILP (current_dir))
1597 /* If the file name handler says that current_dir is unreachable, use
1598 a sensible default. */
1599 current_dir = build_string ("~/");
1600 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1601 if (NILP (Ffile_accessible_directory_p (current_dir)))
1602 report_file_error ("Setting current directory",
1603 Fcons (current_buffer->directory, Qnil));
1605 UNGCPRO;
1608 name = args[0];
1609 CHECK_STRING (name);
1611 program = args[2];
1613 CHECK_STRING (program);
1615 proc = make_process (name);
1616 /* If an error occurs and we can't start the process, we want to
1617 remove it from the process list. This means that each error
1618 check in create_process doesn't need to call remove_process
1619 itself; it's all taken care of here. */
1620 record_unwind_protect (start_process_unwind, proc);
1622 XPROCESS (proc)->childp = Qt;
1623 XPROCESS (proc)->plist = Qnil;
1624 XPROCESS (proc)->buffer = buffer;
1625 XPROCESS (proc)->sentinel = Qnil;
1626 XPROCESS (proc)->filter = Qnil;
1627 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1629 #ifdef ADAPTIVE_READ_BUFFERING
1630 XPROCESS (proc)->adaptive_read_buffering
1631 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1632 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1633 #endif
1635 /* Make the process marker point into the process buffer (if any). */
1636 if (BUFFERP (buffer))
1637 set_marker_both (XPROCESS (proc)->mark, buffer,
1638 BUF_ZV (XBUFFER (buffer)),
1639 BUF_ZV_BYTE (XBUFFER (buffer)));
1642 /* Decide coding systems for communicating with the process. Here
1643 we don't setup the structure coding_system nor pay attention to
1644 unibyte mode. They are done in create_process. */
1646 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1647 Lisp_Object coding_systems = Qt;
1648 Lisp_Object val, *args2;
1649 struct gcpro gcpro1, gcpro2;
1651 val = Vcoding_system_for_read;
1652 if (NILP (val))
1654 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1655 args2[0] = Qstart_process;
1656 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1657 GCPRO2 (proc, current_dir);
1658 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1659 UNGCPRO;
1660 if (CONSP (coding_systems))
1661 val = XCAR (coding_systems);
1662 else if (CONSP (Vdefault_process_coding_system))
1663 val = XCAR (Vdefault_process_coding_system);
1665 XPROCESS (proc)->decode_coding_system = val;
1667 val = Vcoding_system_for_write;
1668 if (NILP (val))
1670 if (EQ (coding_systems, Qt))
1672 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1673 args2[0] = Qstart_process;
1674 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1675 GCPRO2 (proc, current_dir);
1676 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1677 UNGCPRO;
1679 if (CONSP (coding_systems))
1680 val = XCDR (coding_systems);
1681 else if (CONSP (Vdefault_process_coding_system))
1682 val = XCDR (Vdefault_process_coding_system);
1684 XPROCESS (proc)->encode_coding_system = val;
1687 #ifdef VMS
1688 /* Make a one member argv with all args concatenated
1689 together separated by a blank. */
1690 len = SBYTES (program) + 2;
1691 for (i = 3; i < nargs; i++)
1693 tem = args[i];
1694 CHECK_STRING (tem);
1695 len += SBYTES (tem) + 1; /* count the blank */
1697 new_argv = (unsigned char *) alloca (len);
1698 strcpy (new_argv, SDATA (program));
1699 for (i = 3; i < nargs; i++)
1701 tem = args[i];
1702 CHECK_STRING (tem);
1703 strcat (new_argv, " ");
1704 strcat (new_argv, SDATA (tem));
1706 /* Need to add code here to check for program existence on VMS */
1708 #else /* not VMS */
1709 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1711 /* If program file name is not absolute, search our path for it.
1712 Put the name we will really use in TEM. */
1713 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1714 && !(SCHARS (program) > 1
1715 && IS_DEVICE_SEP (SREF (program, 1))))
1717 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1719 tem = Qnil;
1720 GCPRO4 (name, program, buffer, current_dir);
1721 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1722 UNGCPRO;
1723 if (NILP (tem))
1724 report_file_error ("Searching for program", Fcons (program, Qnil));
1725 tem = Fexpand_file_name (tem, Qnil);
1727 else
1729 if (!NILP (Ffile_directory_p (program)))
1730 error ("Specified program for new process is a directory");
1731 tem = program;
1734 /* If program file name starts with /: for quoting a magic name,
1735 discard that. */
1736 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1737 && SREF (tem, 1) == ':')
1738 tem = Fsubstring (tem, make_number (2), Qnil);
1740 /* Encode the file name and put it in NEW_ARGV.
1741 That's where the child will use it to execute the program. */
1742 tem = ENCODE_FILE (tem);
1743 new_argv[0] = SDATA (tem);
1745 /* Here we encode arguments by the coding system used for sending
1746 data to the process. We don't support using different coding
1747 systems for encoding arguments and for encoding data sent to the
1748 process. */
1750 for (i = 3; i < nargs; i++)
1752 tem = args[i];
1753 CHECK_STRING (tem);
1754 if (STRING_MULTIBYTE (tem))
1755 tem = (code_convert_string_norecord
1756 (tem, XPROCESS (proc)->encode_coding_system, 1));
1757 new_argv[i - 2] = SDATA (tem);
1759 new_argv[i - 2] = 0;
1760 #endif /* not VMS */
1762 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1763 XPROCESS (proc)->decoding_carryover = 0;
1764 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1766 XPROCESS (proc)->inherit_coding_system_flag
1767 = !(NILP (buffer) || !inherit_process_coding_system);
1769 create_process (proc, (char **) new_argv, current_dir);
1771 return unbind_to (count, proc);
1774 /* This function is the unwind_protect form for Fstart_process. If
1775 PROC doesn't have its pid set, then we know someone has signaled
1776 an error and the process wasn't started successfully, so we should
1777 remove it from the process list. */
1778 static Lisp_Object
1779 start_process_unwind (proc)
1780 Lisp_Object proc;
1782 if (!PROCESSP (proc))
1783 abort ();
1785 /* Was PROC started successfully? */
1786 if (XPROCESS (proc)->pid <= 0)
1787 remove_process (proc);
1789 return Qnil;
1792 static void
1793 create_process_1 (timer)
1794 struct atimer *timer;
1796 /* Nothing to do. */
1800 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1801 #ifdef USG
1802 #ifdef SIGCHLD
1803 /* Mimic blocking of signals on system V, which doesn't really have it. */
1805 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1806 int sigchld_deferred;
1808 SIGTYPE
1809 create_process_sigchld ()
1811 signal (SIGCHLD, create_process_sigchld);
1813 sigchld_deferred = 1;
1815 #endif
1816 #endif
1817 #endif
1819 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1820 void
1821 create_process (process, new_argv, current_dir)
1822 Lisp_Object process;
1823 char **new_argv;
1824 Lisp_Object current_dir;
1826 int inchannel, outchannel;
1827 pid_t pid;
1828 int sv[2];
1829 #ifdef POSIX_SIGNALS
1830 sigset_t procmask;
1831 sigset_t blocked;
1832 struct sigaction sigint_action;
1833 struct sigaction sigquit_action;
1834 #ifdef AIX
1835 struct sigaction sighup_action;
1836 #endif
1837 #else /* !POSIX_SIGNALS */
1838 #if 0
1839 #ifdef SIGCHLD
1840 SIGTYPE (*sigchld)();
1841 #endif
1842 #endif /* 0 */
1843 #endif /* !POSIX_SIGNALS */
1844 /* Use volatile to protect variables from being clobbered by longjmp. */
1845 volatile int forkin, forkout;
1846 volatile int pty_flag = 0;
1847 #ifndef USE_CRT_DLL
1848 extern char **environ;
1849 #endif
1851 inchannel = outchannel = -1;
1853 #ifdef HAVE_PTYS
1854 if (!NILP (Vprocess_connection_type))
1855 outchannel = inchannel = allocate_pty ();
1857 if (inchannel >= 0)
1859 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1860 /* On most USG systems it does not work to open the pty's tty here,
1861 then close it and reopen it in the child. */
1862 #ifdef O_NOCTTY
1863 /* Don't let this terminal become our controlling terminal
1864 (in case we don't have one). */
1865 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1866 #else
1867 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1868 #endif
1869 if (forkin < 0)
1870 report_file_error ("Opening pty", Qnil);
1871 #if defined (DONT_REOPEN_PTY)
1872 /* In the case that vfork is defined as fork, the parent process
1873 (Emacs) may send some data before the child process completes
1874 tty options setup. So we setup tty before forking. */
1875 child_setup_tty (forkout);
1876 #endif /* DONT_REOPEN_PTY */
1877 #else
1878 forkin = forkout = -1;
1879 #endif /* not USG, or USG_SUBTTY_WORKS */
1880 pty_flag = 1;
1882 else
1883 #endif /* HAVE_PTYS */
1885 int tem;
1886 tem = pipe (sv);
1887 if (tem < 0)
1888 report_file_error ("Creating pipe", Qnil);
1889 inchannel = sv[0];
1890 forkout = sv[1];
1891 tem = pipe (sv);
1892 if (tem < 0)
1894 emacs_close (inchannel);
1895 emacs_close (forkout);
1896 report_file_error ("Creating pipe", Qnil);
1898 outchannel = sv[1];
1899 forkin = sv[0];
1902 #if 0
1903 /* Replaced by close_process_descs */
1904 set_exclusive_use (inchannel);
1905 set_exclusive_use (outchannel);
1906 #endif
1908 #ifdef O_NONBLOCK
1909 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1910 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1911 #else
1912 #ifdef O_NDELAY
1913 fcntl (inchannel, F_SETFL, O_NDELAY);
1914 fcntl (outchannel, F_SETFL, O_NDELAY);
1915 #endif
1916 #endif
1918 /* Record this as an active process, with its channels.
1919 As a result, child_setup will close Emacs's side of the pipes. */
1920 chan_process[inchannel] = process;
1921 XPROCESS (process)->infd = inchannel;
1922 XPROCESS (process)->outfd = outchannel;
1924 /* Previously we recorded the tty descriptor used in the subprocess.
1925 It was only used for getting the foreground tty process, so now
1926 we just reopen the device (see emacs_get_tty_pgrp) as this is
1927 more portable (see USG_SUBTTY_WORKS above). */
1929 XPROCESS (process)->pty_flag = pty_flag;
1930 XPROCESS (process)->status = Qrun;
1931 setup_process_coding_systems (process);
1933 /* Delay interrupts until we have a chance to store
1934 the new fork's pid in its process structure */
1935 #ifdef POSIX_SIGNALS
1936 sigemptyset (&blocked);
1937 #ifdef SIGCHLD
1938 sigaddset (&blocked, SIGCHLD);
1939 #endif
1940 #ifdef HAVE_WORKING_VFORK
1941 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1942 this sets the parent's signal handlers as well as the child's.
1943 So delay all interrupts whose handlers the child might munge,
1944 and record the current handlers so they can be restored later. */
1945 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1946 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1947 #ifdef AIX
1948 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1949 #endif
1950 #endif /* HAVE_WORKING_VFORK */
1951 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1952 #else /* !POSIX_SIGNALS */
1953 #ifdef SIGCHLD
1954 #ifdef BSD4_1
1955 sighold (SIGCHLD);
1956 #else /* not BSD4_1 */
1957 #if defined (BSD_SYSTEM) || defined (HPUX)
1958 sigsetmask (sigmask (SIGCHLD));
1959 #else /* ordinary USG */
1960 #if 0
1961 sigchld_deferred = 0;
1962 sigchld = signal (SIGCHLD, create_process_sigchld);
1963 #endif
1964 #endif /* ordinary USG */
1965 #endif /* not BSD4_1 */
1966 #endif /* SIGCHLD */
1967 #endif /* !POSIX_SIGNALS */
1969 FD_SET (inchannel, &input_wait_mask);
1970 FD_SET (inchannel, &non_keyboard_wait_mask);
1971 if (inchannel > max_process_desc)
1972 max_process_desc = inchannel;
1974 /* Until we store the proper pid, enable sigchld_handler
1975 to recognize an unknown pid as standing for this process.
1976 It is very important not to let this `marker' value stay
1977 in the table after this function has returned; if it does
1978 it might cause call-process to hang and subsequent asynchronous
1979 processes to get their return values scrambled. */
1980 XPROCESS (process)->pid = -1;
1982 BLOCK_INPUT;
1985 /* child_setup must clobber environ on systems with true vfork.
1986 Protect it from permanent change. */
1987 char **save_environ = environ;
1989 current_dir = ENCODE_FILE (current_dir);
1991 #ifndef WINDOWSNT
1992 pid = vfork ();
1993 if (pid == 0)
1994 #endif /* not WINDOWSNT */
1996 int xforkin = forkin;
1997 int xforkout = forkout;
1999 #if 0 /* This was probably a mistake--it duplicates code later on,
2000 but fails to handle all the cases. */
2001 /* Make sure SIGCHLD is not blocked in the child. */
2002 sigsetmask (SIGEMPTYMASK);
2003 #endif
2005 /* Make the pty be the controlling terminal of the process. */
2006 #ifdef HAVE_PTYS
2007 /* First, disconnect its current controlling terminal. */
2008 #ifdef HAVE_SETSID
2009 /* We tried doing setsid only if pty_flag, but it caused
2010 process_set_signal to fail on SGI when using a pipe. */
2011 setsid ();
2012 /* Make the pty's terminal the controlling terminal. */
2013 if (pty_flag)
2015 #ifdef TIOCSCTTY
2016 /* We ignore the return value
2017 because faith@cs.unc.edu says that is necessary on Linux. */
2018 ioctl (xforkin, TIOCSCTTY, 0);
2019 #endif
2021 #else /* not HAVE_SETSID */
2022 #ifdef USG
2023 /* It's very important to call setpgrp here and no time
2024 afterwards. Otherwise, we lose our controlling tty which
2025 is set when we open the pty. */
2026 setpgrp ();
2027 #endif /* USG */
2028 #endif /* not HAVE_SETSID */
2029 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2030 if (pty_flag && xforkin >= 0)
2032 struct termios t;
2033 tcgetattr (xforkin, &t);
2034 t.c_lflag = LDISC1;
2035 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2036 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2038 #else
2039 #if defined (NTTYDISC) && defined (TIOCSETD)
2040 if (pty_flag && xforkin >= 0)
2042 /* Use new line discipline. */
2043 int ldisc = NTTYDISC;
2044 ioctl (xforkin, TIOCSETD, &ldisc);
2046 #endif
2047 #endif
2048 #ifdef TIOCNOTTY
2049 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2050 can do TIOCSPGRP only to the process's controlling tty. */
2051 if (pty_flag)
2053 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2054 I can't test it since I don't have 4.3. */
2055 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2056 ioctl (j, TIOCNOTTY, 0);
2057 emacs_close (j);
2058 #ifndef USG
2059 /* In order to get a controlling terminal on some versions
2060 of BSD, it is necessary to put the process in pgrp 0
2061 before it opens the terminal. */
2062 #ifdef HAVE_SETPGID
2063 setpgid (0, 0);
2064 #else
2065 setpgrp (0, 0);
2066 #endif
2067 #endif
2069 #endif /* TIOCNOTTY */
2071 #if !defined (DONT_REOPEN_PTY)
2072 /*** There is a suggestion that this ought to be a
2073 conditional on TIOCSPGRP,
2074 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2075 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2076 that system does seem to need this code, even though
2077 both HAVE_SETSID and TIOCSCTTY are defined. */
2078 /* Now close the pty (if we had it open) and reopen it.
2079 This makes the pty the controlling terminal of the subprocess. */
2080 if (pty_flag)
2082 #ifdef SET_CHILD_PTY_PGRP
2083 int pgrp = getpid ();
2084 #endif
2086 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2087 would work? */
2088 if (xforkin >= 0)
2089 emacs_close (xforkin);
2090 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2092 if (xforkin < 0)
2094 emacs_write (1, "Couldn't open the pty terminal ", 31);
2095 emacs_write (1, pty_name, strlen (pty_name));
2096 emacs_write (1, "\n", 1);
2097 _exit (1);
2100 #ifdef SET_CHILD_PTY_PGRP
2101 ioctl (xforkin, TIOCSPGRP, &pgrp);
2102 ioctl (xforkout, TIOCSPGRP, &pgrp);
2103 #endif
2105 #endif /* not DONT_REOPEN_PTY */
2107 #ifdef SETUP_SLAVE_PTY
2108 if (pty_flag)
2110 SETUP_SLAVE_PTY;
2112 #endif /* SETUP_SLAVE_PTY */
2113 #ifdef AIX
2114 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2115 Now reenable it in the child, so it will die when we want it to. */
2116 if (pty_flag)
2117 signal (SIGHUP, SIG_DFL);
2118 #endif
2119 #endif /* HAVE_PTYS */
2121 signal (SIGINT, SIG_DFL);
2122 signal (SIGQUIT, SIG_DFL);
2124 /* Stop blocking signals in the child. */
2125 #ifdef POSIX_SIGNALS
2126 sigprocmask (SIG_SETMASK, &procmask, 0);
2127 #else /* !POSIX_SIGNALS */
2128 #ifdef SIGCHLD
2129 #ifdef BSD4_1
2130 sigrelse (SIGCHLD);
2131 #else /* not BSD4_1 */
2132 #if defined (BSD_SYSTEM) || defined (HPUX)
2133 sigsetmask (SIGEMPTYMASK);
2134 #else /* ordinary USG */
2135 #if 0
2136 signal (SIGCHLD, sigchld);
2137 #endif
2138 #endif /* ordinary USG */
2139 #endif /* not BSD4_1 */
2140 #endif /* SIGCHLD */
2141 #endif /* !POSIX_SIGNALS */
2143 #if !defined (DONT_REOPEN_PTY)
2144 if (pty_flag)
2145 child_setup_tty (xforkout);
2146 #endif /* not DONT_REOPEN_PTY */
2147 #ifdef WINDOWSNT
2148 pid = child_setup (xforkin, xforkout, xforkout,
2149 new_argv, 1, current_dir);
2150 #else /* not WINDOWSNT */
2151 child_setup (xforkin, xforkout, xforkout,
2152 new_argv, 1, current_dir);
2153 #endif /* not WINDOWSNT */
2155 environ = save_environ;
2158 UNBLOCK_INPUT;
2160 /* This runs in the Emacs process. */
2161 if (pid < 0)
2163 if (forkin >= 0)
2164 emacs_close (forkin);
2165 if (forkin != forkout && forkout >= 0)
2166 emacs_close (forkout);
2168 else
2170 /* vfork succeeded. */
2171 XPROCESS (process)->pid = pid;
2173 #ifdef WINDOWSNT
2174 register_child (pid, inchannel);
2175 #endif /* WINDOWSNT */
2177 /* If the subfork execv fails, and it exits,
2178 this close hangs. I don't know why.
2179 So have an interrupt jar it loose. */
2181 struct atimer *timer;
2182 EMACS_TIME offset;
2184 stop_polling ();
2185 EMACS_SET_SECS_USECS (offset, 1, 0);
2186 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2188 if (forkin >= 0)
2189 emacs_close (forkin);
2191 cancel_atimer (timer);
2192 start_polling ();
2195 if (forkin != forkout && forkout >= 0)
2196 emacs_close (forkout);
2198 #ifdef HAVE_PTYS
2199 if (pty_flag)
2200 XPROCESS (process)->tty_name = build_string (pty_name);
2201 else
2202 #endif
2203 XPROCESS (process)->tty_name = Qnil;
2206 /* Restore the signal state whether vfork succeeded or not.
2207 (We will signal an error, below, if it failed.) */
2208 #ifdef POSIX_SIGNALS
2209 #ifdef HAVE_WORKING_VFORK
2210 /* Restore the parent's signal handlers. */
2211 sigaction (SIGINT, &sigint_action, 0);
2212 sigaction (SIGQUIT, &sigquit_action, 0);
2213 #ifdef AIX
2214 sigaction (SIGHUP, &sighup_action, 0);
2215 #endif
2216 #endif /* HAVE_WORKING_VFORK */
2217 /* Stop blocking signals in the parent. */
2218 sigprocmask (SIG_SETMASK, &procmask, 0);
2219 #else /* !POSIX_SIGNALS */
2220 #ifdef SIGCHLD
2221 #ifdef BSD4_1
2222 sigrelse (SIGCHLD);
2223 #else /* not BSD4_1 */
2224 #if defined (BSD_SYSTEM) || defined (HPUX)
2225 sigsetmask (SIGEMPTYMASK);
2226 #else /* ordinary USG */
2227 #if 0
2228 signal (SIGCHLD, sigchld);
2229 /* Now really handle any of these signals
2230 that came in during this function. */
2231 if (sigchld_deferred)
2232 kill (getpid (), SIGCHLD);
2233 #endif
2234 #endif /* ordinary USG */
2235 #endif /* not BSD4_1 */
2236 #endif /* SIGCHLD */
2237 #endif /* !POSIX_SIGNALS */
2239 /* Now generate the error if vfork failed. */
2240 if (pid < 0)
2241 report_file_error ("Doing vfork", Qnil);
2243 #endif /* not VMS */
2246 #ifdef HAVE_SOCKETS
2248 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2249 The address family of sa is not included in the result. */
2251 static Lisp_Object
2252 conv_sockaddr_to_lisp (sa, len)
2253 struct sockaddr *sa;
2254 int len;
2256 Lisp_Object address;
2257 int i;
2258 unsigned char *cp;
2259 register struct Lisp_Vector *p;
2261 switch (sa->sa_family)
2263 case AF_INET:
2265 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2266 len = sizeof (sin->sin_addr) + 1;
2267 address = Fmake_vector (make_number (len), Qnil);
2268 p = XVECTOR (address);
2269 p->contents[--len] = make_number (ntohs (sin->sin_port));
2270 cp = (unsigned char *)&sin->sin_addr;
2271 break;
2273 #ifdef AF_INET6
2274 case AF_INET6:
2276 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2277 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2278 len = sizeof (sin6->sin6_addr)/2 + 1;
2279 address = Fmake_vector (make_number (len), Qnil);
2280 p = XVECTOR (address);
2281 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2282 for (i = 0; i < len; i++)
2283 p->contents[i] = make_number (ntohs (ip6[i]));
2284 return address;
2286 #endif
2287 #ifdef HAVE_LOCAL_SOCKETS
2288 case AF_LOCAL:
2290 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2291 for (i = 0; i < sizeof (sockun->sun_path); i++)
2292 if (sockun->sun_path[i] == 0)
2293 break;
2294 return make_unibyte_string (sockun->sun_path, i);
2296 #endif
2297 default:
2298 len -= sizeof (sa->sa_family);
2299 address = Fcons (make_number (sa->sa_family),
2300 Fmake_vector (make_number (len), Qnil));
2301 p = XVECTOR (XCDR (address));
2302 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2303 break;
2306 i = 0;
2307 while (i < len)
2308 p->contents[i++] = make_number (*cp++);
2310 return address;
2314 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2316 static int
2317 get_lisp_to_sockaddr_size (address, familyp)
2318 Lisp_Object address;
2319 int *familyp;
2321 register struct Lisp_Vector *p;
2323 if (VECTORP (address))
2325 p = XVECTOR (address);
2326 if (p->size == 5)
2328 *familyp = AF_INET;
2329 return sizeof (struct sockaddr_in);
2331 #ifdef AF_INET6
2332 else if (p->size == 9)
2334 *familyp = AF_INET6;
2335 return sizeof (struct sockaddr_in6);
2337 #endif
2339 #ifdef HAVE_LOCAL_SOCKETS
2340 else if (STRINGP (address))
2342 *familyp = AF_LOCAL;
2343 return sizeof (struct sockaddr_un);
2345 #endif
2346 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2348 struct sockaddr *sa;
2349 *familyp = XINT (XCAR (address));
2350 p = XVECTOR (XCDR (address));
2351 return p->size + sizeof (sa->sa_family);
2353 return 0;
2356 /* Convert an address object (vector or string) to an internal sockaddr.
2358 The address format has been basically validated by
2359 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2360 it could have come from user data. So if FAMILY is not valid,
2361 we return after zeroing *SA. */
2363 static void
2364 conv_lisp_to_sockaddr (family, address, sa, len)
2365 int family;
2366 Lisp_Object address;
2367 struct sockaddr *sa;
2368 int len;
2370 register struct Lisp_Vector *p;
2371 register unsigned char *cp = NULL;
2372 register int i;
2374 bzero (sa, len);
2376 if (VECTORP (address))
2378 p = XVECTOR (address);
2379 if (family == AF_INET)
2381 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2382 len = sizeof (sin->sin_addr) + 1;
2383 i = XINT (p->contents[--len]);
2384 sin->sin_port = htons (i);
2385 cp = (unsigned char *)&sin->sin_addr;
2386 sa->sa_family = family;
2388 #ifdef AF_INET6
2389 else if (family == AF_INET6)
2391 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2392 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2393 len = sizeof (sin6->sin6_addr) + 1;
2394 i = XINT (p->contents[--len]);
2395 sin6->sin6_port = htons (i);
2396 for (i = 0; i < len; i++)
2397 if (INTEGERP (p->contents[i]))
2399 int j = XFASTINT (p->contents[i]) & 0xffff;
2400 ip6[i] = ntohs (j);
2402 sa->sa_family = family;
2404 #endif
2405 return;
2407 else if (STRINGP (address))
2409 #ifdef HAVE_LOCAL_SOCKETS
2410 if (family == AF_LOCAL)
2412 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2413 cp = SDATA (address);
2414 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2415 sockun->sun_path[i] = *cp++;
2416 sa->sa_family = family;
2418 #endif
2419 return;
2421 else
2423 p = XVECTOR (XCDR (address));
2424 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2427 for (i = 0; i < len; i++)
2428 if (INTEGERP (p->contents[i]))
2429 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2432 #ifdef DATAGRAM_SOCKETS
2433 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2434 1, 1, 0,
2435 doc: /* Get the current datagram address associated with PROCESS. */)
2436 (process)
2437 Lisp_Object process;
2439 int channel;
2441 CHECK_PROCESS (process);
2443 if (!DATAGRAM_CONN_P (process))
2444 return Qnil;
2446 channel = XPROCESS (process)->infd;
2447 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2448 datagram_address[channel].len);
2451 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2452 2, 2, 0,
2453 doc: /* Set the datagram address for PROCESS to ADDRESS.
2454 Returns nil upon error setting address, ADDRESS otherwise. */)
2455 (process, address)
2456 Lisp_Object process, address;
2458 int channel;
2459 int family, len;
2461 CHECK_PROCESS (process);
2463 if (!DATAGRAM_CONN_P (process))
2464 return Qnil;
2466 channel = XPROCESS (process)->infd;
2468 len = get_lisp_to_sockaddr_size (address, &family);
2469 if (datagram_address[channel].len != len)
2470 return Qnil;
2471 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2472 return address;
2474 #endif
2477 static struct socket_options {
2478 /* The name of this option. Should be lowercase version of option
2479 name without SO_ prefix. */
2480 char *name;
2481 /* Option level SOL_... */
2482 int optlevel;
2483 /* Option number SO_... */
2484 int optnum;
2485 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2486 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2487 } socket_options[] =
2489 #ifdef SO_BINDTODEVICE
2490 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2491 #endif
2492 #ifdef SO_BROADCAST
2493 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2494 #endif
2495 #ifdef SO_DONTROUTE
2496 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2497 #endif
2498 #ifdef SO_KEEPALIVE
2499 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2500 #endif
2501 #ifdef SO_LINGER
2502 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2503 #endif
2504 #ifdef SO_OOBINLINE
2505 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2506 #endif
2507 #ifdef SO_PRIORITY
2508 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2509 #endif
2510 #ifdef SO_REUSEADDR
2511 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2512 #endif
2513 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2516 /* Set option OPT to value VAL on socket S.
2518 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2519 Signals an error if setting a known option fails.
2522 static int
2523 set_socket_option (s, opt, val)
2524 int s;
2525 Lisp_Object opt, val;
2527 char *name;
2528 struct socket_options *sopt;
2529 int ret = 0;
2531 CHECK_SYMBOL (opt);
2533 name = (char *) SDATA (SYMBOL_NAME (opt));
2534 for (sopt = socket_options; sopt->name; sopt++)
2535 if (strcmp (name, sopt->name) == 0)
2536 break;
2538 switch (sopt->opttype)
2540 case SOPT_BOOL:
2542 int optval;
2543 optval = NILP (val) ? 0 : 1;
2544 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2545 &optval, sizeof (optval));
2546 break;
2549 case SOPT_INT:
2551 int optval;
2552 if (INTEGERP (val))
2553 optval = XINT (val);
2554 else
2555 error ("Bad option value for %s", name);
2556 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2557 &optval, sizeof (optval));
2558 break;
2561 #ifdef SO_BINDTODEVICE
2562 case SOPT_IFNAME:
2564 char devname[IFNAMSIZ+1];
2566 /* This is broken, at least in the Linux 2.4 kernel.
2567 To unbind, the arg must be a zero integer, not the empty string.
2568 This should work on all systems. KFS. 2003-09-23. */
2569 bzero (devname, sizeof devname);
2570 if (STRINGP (val))
2572 char *arg = (char *) SDATA (val);
2573 int len = min (strlen (arg), IFNAMSIZ);
2574 bcopy (arg, devname, len);
2576 else if (!NILP (val))
2577 error ("Bad option value for %s", name);
2578 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2579 devname, IFNAMSIZ);
2580 break;
2582 #endif
2584 #ifdef SO_LINGER
2585 case SOPT_LINGER:
2587 struct linger linger;
2589 linger.l_onoff = 1;
2590 linger.l_linger = 0;
2591 if (INTEGERP (val))
2592 linger.l_linger = XINT (val);
2593 else
2594 linger.l_onoff = NILP (val) ? 0 : 1;
2595 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2596 &linger, sizeof (linger));
2597 break;
2599 #endif
2601 default:
2602 return 0;
2605 if (ret < 0)
2606 report_file_error ("Cannot set network option",
2607 Fcons (opt, Fcons (val, Qnil)));
2608 return (1 << sopt->optbit);
2612 DEFUN ("set-network-process-option",
2613 Fset_network_process_option, Sset_network_process_option,
2614 3, 4, 0,
2615 doc: /* For network process PROCESS set option OPTION to value VALUE.
2616 See `make-network-process' for a list of options and values.
2617 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2618 OPTION is not a supported option, return nil instead; otherwise return t. */)
2619 (process, option, value, no_error)
2620 Lisp_Object process, option, value;
2621 Lisp_Object no_error;
2623 int s;
2624 struct Lisp_Process *p;
2626 CHECK_PROCESS (process);
2627 p = XPROCESS (process);
2628 if (!NETCONN1_P (p))
2629 error ("Process is not a network process");
2631 s = p->infd;
2632 if (s < 0)
2633 error ("Process is not running");
2635 if (set_socket_option (s, option, value))
2637 p->childp = Fplist_put (p->childp, option, value);
2638 return Qt;
2641 if (NILP (no_error))
2642 error ("Unknown or unsupported option");
2644 return Qnil;
2648 /* A version of request_sigio suitable for a record_unwind_protect. */
2650 #ifdef __ultrix__
2651 static Lisp_Object
2652 unwind_request_sigio (dummy)
2653 Lisp_Object dummy;
2655 if (interrupt_input)
2656 request_sigio ();
2657 return Qnil;
2659 #endif
2661 /* Create a network stream/datagram client/server process. Treated
2662 exactly like a normal process when reading and writing. Primary
2663 differences are in status display and process deletion. A network
2664 connection has no PID; you cannot signal it. All you can do is
2665 stop/continue it and deactivate/close it via delete-process */
2667 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2668 0, MANY, 0,
2669 doc: /* Create and return a network server or client process.
2671 In Emacs, network connections are represented by process objects, so
2672 input and output work as for subprocesses and `delete-process' closes
2673 a network connection. However, a network process has no process id,
2674 it cannot be signaled, and the status codes are different from normal
2675 processes.
2677 Arguments are specified as keyword/argument pairs. The following
2678 arguments are defined:
2680 :name NAME -- NAME is name for process. It is modified if necessary
2681 to make it unique.
2683 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2684 with the process. Process output goes at end of that buffer, unless
2685 you specify an output stream or filter function to handle the output.
2686 BUFFER may be also nil, meaning that this process is not associated
2687 with any buffer.
2689 :host HOST -- HOST is name of the host to connect to, or its IP
2690 address. The symbol `local' specifies the local host. If specified
2691 for a server process, it must be a valid name or address for the local
2692 host, and only clients connecting to that address will be accepted.
2694 :service SERVICE -- SERVICE is name of the service desired, or an
2695 integer specifying a port number to connect to. If SERVICE is t,
2696 a random port number is selected for the server. (If Emacs was
2697 compiled with getaddrinfo, a port number can also be specified as a
2698 string, e.g. "80", as well as an integer. This is not portable.)
2700 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2701 stream type connection, `datagram' creates a datagram type connection.
2703 :family FAMILY -- FAMILY is the address (and protocol) family for the
2704 service specified by HOST and SERVICE. The default (nil) is to use
2705 whatever address family (IPv4 or IPv6) that is defined for the host
2706 and port number specified by HOST and SERVICE. Other address families
2707 supported are:
2708 local -- for a local (i.e. UNIX) address specified by SERVICE.
2709 ipv4 -- use IPv4 address family only.
2710 ipv6 -- use IPv6 address family only.
2712 :local ADDRESS -- ADDRESS is the local address used for the connection.
2713 This parameter is ignored when opening a client process. When specified
2714 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2716 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2717 connection. This parameter is ignored when opening a stream server
2718 process. For a datagram server process, it specifies the initial
2719 setting of the remote datagram address. When specified for a client
2720 process, the FAMILY, HOST, and SERVICE args are ignored.
2722 The format of ADDRESS depends on the address family:
2723 - An IPv4 address is represented as an vector of integers [A B C D P]
2724 corresponding to numeric IP address A.B.C.D and port number P.
2725 - A local address is represented as a string with the address in the
2726 local address space.
2727 - An "unsupported family" address is represented by a cons (F . AV)
2728 where F is the family number and AV is a vector containing the socket
2729 address data with one element per address data byte. Do not rely on
2730 this format in portable code, as it may depend on implementation
2731 defined constants, data sizes, and data structure alignment.
2733 :coding CODING -- If CODING is a symbol, it specifies the coding
2734 system used for both reading and writing for this process. If CODING
2735 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2736 ENCODING is used for writing.
2738 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2739 return without waiting for the connection to complete; instead, the
2740 sentinel function will be called with second arg matching "open" (if
2741 successful) or "failed" when the connect completes. Default is to use
2742 a blocking connect (i.e. wait) for stream type connections.
2744 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2745 running when Emacs is exited.
2747 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2748 In the stopped state, a server process does not accept new
2749 connections, and a client process does not handle incoming traffic.
2750 The stopped state is cleared by `continue-process' and set by
2751 `stop-process'.
2753 :filter FILTER -- Install FILTER as the process filter.
2755 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2756 process filter are multibyte, otherwise they are unibyte.
2757 If this keyword is not specified, the strings are multibyte if
2758 `default-enable-multibyte-characters' is non-nil.
2760 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2762 :log LOG -- Install LOG as the server process log function. This
2763 function is called when the server accepts a network connection from a
2764 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2765 is the server process, CLIENT is the new process for the connection,
2766 and MESSAGE is a string.
2768 :plist PLIST -- Install PLIST as the new process' initial plist.
2770 :server QLEN -- if QLEN is non-nil, create a server process for the
2771 specified FAMILY, SERVICE, and connection type (stream or datagram).
2772 If QLEN is an integer, it is used as the max. length of the server's
2773 pending connection queue (also known as the backlog); the default
2774 queue length is 5. Default is to create a client process.
2776 The following network options can be specified for this connection:
2778 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2779 :dontroute BOOL -- Only send to directly connected hosts.
2780 :keepalive BOOL -- Send keep-alive messages on network stream.
2781 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2782 :oobinline BOOL -- Place out-of-band data in receive data stream.
2783 :priority INT -- Set protocol defined priority for sent packets.
2784 :reuseaddr BOOL -- Allow reusing a recently used local address
2785 (this is allowed by default for a server process).
2786 :bindtodevice NAME -- bind to interface NAME. Using this may require
2787 special privileges on some systems.
2789 Consult the relevant system programmer's manual pages for more
2790 information on using these options.
2793 A server process will listen for and accept connections from clients.
2794 When a client connection is accepted, a new network process is created
2795 for the connection with the following parameters:
2797 - The client's process name is constructed by concatenating the server
2798 process' NAME and a client identification string.
2799 - If the FILTER argument is non-nil, the client process will not get a
2800 separate process buffer; otherwise, the client's process buffer is a newly
2801 created buffer named after the server process' BUFFER name or process
2802 NAME concatenated with the client identification string.
2803 - The connection type and the process filter and sentinel parameters are
2804 inherited from the server process' TYPE, FILTER and SENTINEL.
2805 - The client process' contact info is set according to the client's
2806 addressing information (typically an IP address and a port number).
2807 - The client process' plist is initialized from the server's plist.
2809 Notice that the FILTER and SENTINEL args are never used directly by
2810 the server process. Also, the BUFFER argument is not used directly by
2811 the server process, but via the optional :log function, accepted (and
2812 failed) connections may be logged in the server process' buffer.
2814 The original argument list, modified with the actual connection
2815 information, is available via the `process-contact' function.
2817 usage: (make-network-process &rest ARGS) */)
2818 (nargs, args)
2819 int nargs;
2820 Lisp_Object *args;
2822 Lisp_Object proc;
2823 Lisp_Object contact;
2824 struct Lisp_Process *p;
2825 #ifdef HAVE_GETADDRINFO
2826 struct addrinfo ai, *res, *lres;
2827 struct addrinfo hints;
2828 char *portstring, portbuf[128];
2829 #else /* HAVE_GETADDRINFO */
2830 struct _emacs_addrinfo
2832 int ai_family;
2833 int ai_socktype;
2834 int ai_protocol;
2835 int ai_addrlen;
2836 struct sockaddr *ai_addr;
2837 struct _emacs_addrinfo *ai_next;
2838 } ai, *res, *lres;
2839 #endif /* HAVE_GETADDRINFO */
2840 struct sockaddr_in address_in;
2841 #ifdef HAVE_LOCAL_SOCKETS
2842 struct sockaddr_un address_un;
2843 #endif
2844 int port;
2845 int ret = 0;
2846 int xerrno = 0;
2847 int s = -1, outch, inch;
2848 struct gcpro gcpro1;
2849 int count = SPECPDL_INDEX ();
2850 int count1;
2851 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2852 Lisp_Object tem;
2853 Lisp_Object name, buffer, host, service, address;
2854 Lisp_Object filter, sentinel;
2855 int is_non_blocking_client = 0;
2856 int is_server = 0, backlog = 5;
2857 int socktype;
2858 int family = -1;
2860 if (nargs == 0)
2861 return Qnil;
2863 /* Save arguments for process-contact and clone-process. */
2864 contact = Flist (nargs, args);
2865 GCPRO1 (contact);
2867 #ifdef WINDOWSNT
2868 /* Ensure socket support is loaded if available. */
2869 init_winsock (TRUE);
2870 #endif
2872 /* :type TYPE (nil: stream, datagram */
2873 tem = Fplist_get (contact, QCtype);
2874 if (NILP (tem))
2875 socktype = SOCK_STREAM;
2876 #ifdef DATAGRAM_SOCKETS
2877 else if (EQ (tem, Qdatagram))
2878 socktype = SOCK_DGRAM;
2879 #endif
2880 else
2881 error ("Unsupported connection type");
2883 /* :server BOOL */
2884 tem = Fplist_get (contact, QCserver);
2885 if (!NILP (tem))
2887 /* Don't support network sockets when non-blocking mode is
2888 not available, since a blocked Emacs is not useful. */
2889 #if defined(TERM) || (!defined(O_NONBLOCK) && !defined(O_NDELAY))
2890 error ("Network servers not supported");
2891 #else
2892 is_server = 1;
2893 if (INTEGERP (tem))
2894 backlog = XINT (tem);
2895 #endif
2898 /* Make QCaddress an alias for :local (server) or :remote (client). */
2899 QCaddress = is_server ? QClocal : QCremote;
2901 /* :nowait BOOL */
2902 if (!is_server && socktype == SOCK_STREAM
2903 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2905 #ifndef NON_BLOCKING_CONNECT
2906 error ("Non-blocking connect not supported");
2907 #else
2908 is_non_blocking_client = 1;
2909 #endif
2912 name = Fplist_get (contact, QCname);
2913 buffer = Fplist_get (contact, QCbuffer);
2914 filter = Fplist_get (contact, QCfilter);
2915 sentinel = Fplist_get (contact, QCsentinel);
2917 CHECK_STRING (name);
2919 #ifdef TERM
2920 /* Let's handle TERM before things get complicated ... */
2921 host = Fplist_get (contact, QChost);
2922 CHECK_STRING (host);
2924 service = Fplist_get (contact, QCservice);
2925 if (INTEGERP (service))
2926 port = htons ((unsigned short) XINT (service));
2927 else
2929 struct servent *svc_info;
2930 CHECK_STRING (service);
2931 svc_info = getservbyname (SDATA (service), "tcp");
2932 if (svc_info == 0)
2933 error ("Unknown service: %s", SDATA (service));
2934 port = svc_info->s_port;
2937 s = connect_server (0);
2938 if (s < 0)
2939 report_file_error ("error creating socket", Fcons (name, Qnil));
2940 send_command (s, C_PORT, 0, "%s:%d", SDATA (host), ntohs (port));
2941 send_command (s, C_DUMB, 1, 0);
2943 #else /* not TERM */
2945 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2946 ai.ai_socktype = socktype;
2947 ai.ai_protocol = 0;
2948 ai.ai_next = NULL;
2949 res = &ai;
2951 /* :local ADDRESS or :remote ADDRESS */
2952 address = Fplist_get (contact, QCaddress);
2953 if (!NILP (address))
2955 host = service = Qnil;
2957 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2958 error ("Malformed :address");
2959 ai.ai_family = family;
2960 ai.ai_addr = alloca (ai.ai_addrlen);
2961 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2962 goto open_socket;
2965 /* :family FAMILY -- nil (for Inet), local, or integer. */
2966 tem = Fplist_get (contact, QCfamily);
2967 if (NILP (tem))
2969 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
2970 family = AF_UNSPEC;
2971 #else
2972 family = AF_INET;
2973 #endif
2975 #ifdef HAVE_LOCAL_SOCKETS
2976 else if (EQ (tem, Qlocal))
2977 family = AF_LOCAL;
2978 #endif
2979 #ifdef AF_INET6
2980 else if (EQ (tem, Qipv6))
2981 family = AF_INET6;
2982 #endif
2983 else if (EQ (tem, Qipv4))
2984 family = AF_INET;
2985 else if (INTEGERP (tem))
2986 family = XINT (tem);
2987 else
2988 error ("Unknown address family");
2990 ai.ai_family = family;
2992 /* :service SERVICE -- string, integer (port number), or t (random port). */
2993 service = Fplist_get (contact, QCservice);
2995 #ifdef HAVE_LOCAL_SOCKETS
2996 if (family == AF_LOCAL)
2998 /* Host is not used. */
2999 host = Qnil;
3000 CHECK_STRING (service);
3001 bzero (&address_un, sizeof address_un);
3002 address_un.sun_family = AF_LOCAL;
3003 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3004 ai.ai_addr = (struct sockaddr *) &address_un;
3005 ai.ai_addrlen = sizeof address_un;
3006 goto open_socket;
3008 #endif
3010 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3011 host = Fplist_get (contact, QChost);
3012 if (!NILP (host))
3014 if (EQ (host, Qlocal))
3015 host = build_string ("localhost");
3016 CHECK_STRING (host);
3019 /* Slow down polling to every ten seconds.
3020 Some kernels have a bug which causes retrying connect to fail
3021 after a connect. Polling can interfere with gethostbyname too. */
3022 #ifdef POLL_FOR_INPUT
3023 if (socktype == SOCK_STREAM)
3025 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3026 bind_polling_period (10);
3028 #endif
3030 #ifdef HAVE_GETADDRINFO
3031 /* If we have a host, use getaddrinfo to resolve both host and service.
3032 Otherwise, use getservbyname to lookup the service. */
3033 if (!NILP (host))
3036 /* SERVICE can either be a string or int.
3037 Convert to a C string for later use by getaddrinfo. */
3038 if (EQ (service, Qt))
3039 portstring = "0";
3040 else if (INTEGERP (service))
3042 sprintf (portbuf, "%ld", (long) XINT (service));
3043 portstring = portbuf;
3045 else
3047 CHECK_STRING (service);
3048 portstring = SDATA (service);
3051 immediate_quit = 1;
3052 QUIT;
3053 memset (&hints, 0, sizeof (hints));
3054 hints.ai_flags = 0;
3055 hints.ai_family = family;
3056 hints.ai_socktype = socktype;
3057 hints.ai_protocol = 0;
3059 #ifdef HAVE_RES_INIT
3060 res_init ();
3061 #endif
3063 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3064 if (ret)
3065 #ifdef HAVE_GAI_STRERROR
3066 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3067 #else
3068 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3069 #endif
3070 immediate_quit = 0;
3072 goto open_socket;
3074 #endif /* HAVE_GETADDRINFO */
3076 /* We end up here if getaddrinfo is not defined, or in case no hostname
3077 has been specified (e.g. for a local server process). */
3079 if (EQ (service, Qt))
3080 port = 0;
3081 else if (INTEGERP (service))
3082 port = htons ((unsigned short) XINT (service));
3083 else
3085 struct servent *svc_info;
3086 CHECK_STRING (service);
3087 svc_info = getservbyname (SDATA (service),
3088 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3089 if (svc_info == 0)
3090 error ("Unknown service: %s", SDATA (service));
3091 port = svc_info->s_port;
3094 bzero (&address_in, sizeof address_in);
3095 address_in.sin_family = family;
3096 address_in.sin_addr.s_addr = INADDR_ANY;
3097 address_in.sin_port = port;
3099 #ifndef HAVE_GETADDRINFO
3100 if (!NILP (host))
3102 struct hostent *host_info_ptr;
3104 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3105 as it may `hang' Emacs for a very long time. */
3106 immediate_quit = 1;
3107 QUIT;
3109 #ifdef HAVE_RES_INIT
3110 res_init ();
3111 #endif
3113 host_info_ptr = gethostbyname (SDATA (host));
3114 immediate_quit = 0;
3116 if (host_info_ptr)
3118 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3119 host_info_ptr->h_length);
3120 family = host_info_ptr->h_addrtype;
3121 address_in.sin_family = family;
3123 else
3124 /* Attempt to interpret host as numeric inet address */
3126 unsigned long numeric_addr;
3127 numeric_addr = inet_addr ((char *) SDATA (host));
3128 if (numeric_addr == -1)
3129 error ("Unknown host \"%s\"", SDATA (host));
3131 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3132 sizeof (address_in.sin_addr));
3136 #endif /* not HAVE_GETADDRINFO */
3138 ai.ai_family = family;
3139 ai.ai_addr = (struct sockaddr *) &address_in;
3140 ai.ai_addrlen = sizeof address_in;
3142 open_socket:
3144 #ifdef __ultrix__
3145 /* Previously this was compiled unconditionally, but that seems
3146 unnecessary on modern systems, and `unrequest_sigio' was a noop
3147 under X anyway. --lorentey */
3148 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
3149 when connect is interrupted. So let's not let it get interrupted.
3150 Note we do not turn off polling, because polling is only used
3151 when not interrupt_input, and thus not normally used on the systems
3152 which have this bug. On systems which use polling, there's no way
3153 to quit if polling is turned off. */
3154 if (interrupt_input
3155 && !is_server && socktype == SOCK_STREAM)
3157 /* Comment from KFS: The original open-network-stream code
3158 didn't unwind protect this, but it seems like the proper
3159 thing to do. In any case, I don't see how it could harm to
3160 do this -- and it makes cleanup (using unbind_to) easier. */
3161 record_unwind_protect (unwind_request_sigio, Qnil);
3162 unrequest_sigio ();
3164 #endif
3166 /* Do this in case we never enter the for-loop below. */
3167 count1 = SPECPDL_INDEX ();
3168 s = -1;
3170 for (lres = res; lres; lres = lres->ai_next)
3172 int optn, optbits;
3174 retry_connect:
3176 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3177 if (s < 0)
3179 xerrno = errno;
3180 continue;
3183 #ifdef DATAGRAM_SOCKETS
3184 if (!is_server && socktype == SOCK_DGRAM)
3185 break;
3186 #endif /* DATAGRAM_SOCKETS */
3188 #ifdef NON_BLOCKING_CONNECT
3189 if (is_non_blocking_client)
3191 #ifdef O_NONBLOCK
3192 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3193 #else
3194 ret = fcntl (s, F_SETFL, O_NDELAY);
3195 #endif
3196 if (ret < 0)
3198 xerrno = errno;
3199 emacs_close (s);
3200 s = -1;
3201 continue;
3204 #endif
3206 /* Make us close S if quit. */
3207 record_unwind_protect (close_file_unwind, make_number (s));
3209 /* Parse network options in the arg list.
3210 We simply ignore anything which isn't a known option (including other keywords).
3211 An error is signalled if setting a known option fails. */
3212 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3213 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3215 if (is_server)
3217 /* Configure as a server socket. */
3219 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3220 explicit :reuseaddr key to override this. */
3221 #ifdef HAVE_LOCAL_SOCKETS
3222 if (family != AF_LOCAL)
3223 #endif
3224 if (!(optbits & (1 << OPIX_REUSEADDR)))
3226 int optval = 1;
3227 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3228 report_file_error ("Cannot set reuse option on server socket", Qnil);
3231 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3232 report_file_error ("Cannot bind server socket", Qnil);
3234 #ifdef HAVE_GETSOCKNAME
3235 if (EQ (service, Qt))
3237 struct sockaddr_in sa1;
3238 int len1 = sizeof (sa1);
3239 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3241 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3242 service = make_number (ntohs (sa1.sin_port));
3243 contact = Fplist_put (contact, QCservice, service);
3246 #endif
3248 if (socktype == SOCK_STREAM && listen (s, backlog))
3249 report_file_error ("Cannot listen on server socket", Qnil);
3251 break;
3254 immediate_quit = 1;
3255 QUIT;
3257 /* This turns off all alarm-based interrupts; the
3258 bind_polling_period call above doesn't always turn all the
3259 short-interval ones off, especially if interrupt_input is
3260 set.
3262 It'd be nice to be able to control the connect timeout
3263 though. Would non-blocking connect calls be portable?
3265 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3267 turn_on_atimers (0);
3269 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3270 xerrno = errno;
3272 turn_on_atimers (1);
3274 if (ret == 0 || xerrno == EISCONN)
3276 /* The unwind-protect will be discarded afterwards.
3277 Likewise for immediate_quit. */
3278 break;
3281 #ifdef NON_BLOCKING_CONNECT
3282 #ifdef EINPROGRESS
3283 if (is_non_blocking_client && xerrno == EINPROGRESS)
3284 break;
3285 #else
3286 #ifdef EWOULDBLOCK
3287 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3288 break;
3289 #endif
3290 #endif
3291 #endif
3293 immediate_quit = 0;
3295 /* Discard the unwind protect closing S. */
3296 specpdl_ptr = specpdl + count1;
3297 emacs_close (s);
3298 s = -1;
3300 if (xerrno == EINTR)
3301 goto retry_connect;
3304 if (s >= 0)
3306 #ifdef DATAGRAM_SOCKETS
3307 if (socktype == SOCK_DGRAM)
3309 if (datagram_address[s].sa)
3310 abort ();
3311 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3312 datagram_address[s].len = lres->ai_addrlen;
3313 if (is_server)
3315 Lisp_Object remote;
3316 bzero (datagram_address[s].sa, lres->ai_addrlen);
3317 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3319 int rfamily, rlen;
3320 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3321 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3322 conv_lisp_to_sockaddr (rfamily, remote,
3323 datagram_address[s].sa, rlen);
3326 else
3327 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3329 #endif
3330 contact = Fplist_put (contact, QCaddress,
3331 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3332 #ifdef HAVE_GETSOCKNAME
3333 if (!is_server)
3335 struct sockaddr_in sa1;
3336 int len1 = sizeof (sa1);
3337 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3338 contact = Fplist_put (contact, QClocal,
3339 conv_sockaddr_to_lisp (&sa1, len1));
3341 #endif
3344 immediate_quit = 0;
3346 #ifdef HAVE_GETADDRINFO
3347 if (res != &ai)
3349 BLOCK_INPUT;
3350 freeaddrinfo (res);
3351 UNBLOCK_INPUT;
3353 #endif
3355 /* Discard the unwind protect for closing S, if any. */
3356 specpdl_ptr = specpdl + count1;
3358 /* Unwind bind_polling_period and request_sigio. */
3359 unbind_to (count, Qnil);
3361 if (s < 0)
3363 /* If non-blocking got this far - and failed - assume non-blocking is
3364 not supported after all. This is probably a wrong assumption, but
3365 the normal blocking calls to open-network-stream handles this error
3366 better. */
3367 if (is_non_blocking_client)
3368 return Qnil;
3370 errno = xerrno;
3371 if (is_server)
3372 report_file_error ("make server process failed", contact);
3373 else
3374 report_file_error ("make client process failed", contact);
3377 #endif /* not TERM */
3379 inch = s;
3380 outch = s;
3382 if (!NILP (buffer))
3383 buffer = Fget_buffer_create (buffer);
3384 proc = make_process (name);
3386 chan_process[inch] = proc;
3388 #ifdef O_NONBLOCK
3389 fcntl (inch, F_SETFL, O_NONBLOCK);
3390 #else
3391 #ifdef O_NDELAY
3392 fcntl (inch, F_SETFL, O_NDELAY);
3393 #endif
3394 #endif
3396 p = XPROCESS (proc);
3398 p->childp = contact;
3399 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3401 p->buffer = buffer;
3402 p->sentinel = sentinel;
3403 p->filter = filter;
3404 p->log = Fplist_get (contact, QClog);
3405 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3406 p->kill_without_query = 1;
3407 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3408 p->command = Qt;
3409 p->pid = 0;
3410 p->infd = inch;
3411 p->outfd = outch;
3412 if (is_server && socktype == SOCK_STREAM)
3413 p->status = Qlisten;
3415 /* Make the process marker point into the process buffer (if any). */
3416 if (BUFFERP (buffer))
3417 set_marker_both (p->mark, buffer,
3418 BUF_ZV (XBUFFER (buffer)),
3419 BUF_ZV_BYTE (XBUFFER (buffer)));
3421 #ifdef NON_BLOCKING_CONNECT
3422 if (is_non_blocking_client)
3424 /* We may get here if connect did succeed immediately. However,
3425 in that case, we still need to signal this like a non-blocking
3426 connection. */
3427 p->status = Qconnect;
3428 if (!FD_ISSET (inch, &connect_wait_mask))
3430 FD_SET (inch, &connect_wait_mask);
3431 num_pending_connects++;
3434 else
3435 #endif
3436 /* A server may have a client filter setting of Qt, but it must
3437 still listen for incoming connects unless it is stopped. */
3438 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3439 || (EQ (p->status, Qlisten) && NILP (p->command)))
3441 FD_SET (inch, &input_wait_mask);
3442 FD_SET (inch, &non_keyboard_wait_mask);
3445 if (inch > max_process_desc)
3446 max_process_desc = inch;
3448 tem = Fplist_member (contact, QCcoding);
3449 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3450 tem = Qnil; /* No error message (too late!). */
3453 /* Setup coding systems for communicating with the network stream. */
3454 struct gcpro gcpro1;
3455 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3456 Lisp_Object coding_systems = Qt;
3457 Lisp_Object args[5], val;
3459 if (!NILP (tem))
3461 val = XCAR (XCDR (tem));
3462 if (CONSP (val))
3463 val = XCAR (val);
3465 else if (!NILP (Vcoding_system_for_read))
3466 val = Vcoding_system_for_read;
3467 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3468 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3469 /* We dare not decode end-of-line format by setting VAL to
3470 Qraw_text, because the existing Emacs Lisp libraries
3471 assume that they receive bare code including a sequene of
3472 CR LF. */
3473 val = Qnil;
3474 else
3476 if (NILP (host) || NILP (service))
3477 coding_systems = Qnil;
3478 else
3480 args[0] = Qopen_network_stream, args[1] = name,
3481 args[2] = buffer, args[3] = host, args[4] = service;
3482 GCPRO1 (proc);
3483 coding_systems = Ffind_operation_coding_system (5, args);
3484 UNGCPRO;
3486 if (CONSP (coding_systems))
3487 val = XCAR (coding_systems);
3488 else if (CONSP (Vdefault_process_coding_system))
3489 val = XCAR (Vdefault_process_coding_system);
3490 else
3491 val = Qnil;
3493 p->decode_coding_system = val;
3495 if (!NILP (tem))
3497 val = XCAR (XCDR (tem));
3498 if (CONSP (val))
3499 val = XCDR (val);
3501 else if (!NILP (Vcoding_system_for_write))
3502 val = Vcoding_system_for_write;
3503 else if (NILP (current_buffer->enable_multibyte_characters))
3504 val = Qnil;
3505 else
3507 if (EQ (coding_systems, Qt))
3509 if (NILP (host) || NILP (service))
3510 coding_systems = Qnil;
3511 else
3513 args[0] = Qopen_network_stream, args[1] = name,
3514 args[2] = buffer, args[3] = host, args[4] = service;
3515 GCPRO1 (proc);
3516 coding_systems = Ffind_operation_coding_system (5, args);
3517 UNGCPRO;
3520 if (CONSP (coding_systems))
3521 val = XCDR (coding_systems);
3522 else if (CONSP (Vdefault_process_coding_system))
3523 val = XCDR (Vdefault_process_coding_system);
3524 else
3525 val = Qnil;
3527 p->encode_coding_system = val;
3529 setup_process_coding_systems (proc);
3531 p->decoding_buf = make_uninit_string (0);
3532 p->decoding_carryover = 0;
3533 p->encoding_buf = make_uninit_string (0);
3535 p->inherit_coding_system_flag
3536 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3538 UNGCPRO;
3539 return proc;
3541 #endif /* HAVE_SOCKETS */
3544 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3546 #ifdef SIOCGIFCONF
3547 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3548 doc: /* Return an alist of all network interfaces and their network address.
3549 Each element is a cons, the car of which is a string containing the
3550 interface name, and the cdr is the network address in internal
3551 format; see the description of ADDRESS in `make-network-process'. */)
3554 struct ifconf ifconf;
3555 struct ifreq *ifreqs = NULL;
3556 int ifaces = 0;
3557 int buf_size, s;
3558 Lisp_Object res;
3560 s = socket (AF_INET, SOCK_STREAM, 0);
3561 if (s < 0)
3562 return Qnil;
3564 again:
3565 ifaces += 25;
3566 buf_size = ifaces * sizeof(ifreqs[0]);
3567 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3568 if (!ifreqs)
3570 close (s);
3571 return Qnil;
3574 ifconf.ifc_len = buf_size;
3575 ifconf.ifc_req = ifreqs;
3576 if (ioctl (s, SIOCGIFCONF, &ifconf))
3578 close (s);
3579 return Qnil;
3582 if (ifconf.ifc_len == buf_size)
3583 goto again;
3585 close (s);
3586 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3588 res = Qnil;
3589 while (--ifaces >= 0)
3591 struct ifreq *ifq = &ifreqs[ifaces];
3592 char namebuf[sizeof (ifq->ifr_name) + 1];
3593 if (ifq->ifr_addr.sa_family != AF_INET)
3594 continue;
3595 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3596 namebuf[sizeof (ifq->ifr_name)] = 0;
3597 res = Fcons (Fcons (build_string (namebuf),
3598 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3599 sizeof (struct sockaddr))),
3600 res);
3603 return res;
3605 #endif /* SIOCGIFCONF */
3607 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3609 struct ifflag_def {
3610 int flag_bit;
3611 char *flag_sym;
3614 static struct ifflag_def ifflag_table[] = {
3615 #ifdef IFF_UP
3616 { IFF_UP, "up" },
3617 #endif
3618 #ifdef IFF_BROADCAST
3619 { IFF_BROADCAST, "broadcast" },
3620 #endif
3621 #ifdef IFF_DEBUG
3622 { IFF_DEBUG, "debug" },
3623 #endif
3624 #ifdef IFF_LOOPBACK
3625 { IFF_LOOPBACK, "loopback" },
3626 #endif
3627 #ifdef IFF_POINTOPOINT
3628 { IFF_POINTOPOINT, "pointopoint" },
3629 #endif
3630 #ifdef IFF_RUNNING
3631 { IFF_RUNNING, "running" },
3632 #endif
3633 #ifdef IFF_NOARP
3634 { IFF_NOARP, "noarp" },
3635 #endif
3636 #ifdef IFF_PROMISC
3637 { IFF_PROMISC, "promisc" },
3638 #endif
3639 #ifdef IFF_NOTRAILERS
3640 { IFF_NOTRAILERS, "notrailers" },
3641 #endif
3642 #ifdef IFF_ALLMULTI
3643 { IFF_ALLMULTI, "allmulti" },
3644 #endif
3645 #ifdef IFF_MASTER
3646 { IFF_MASTER, "master" },
3647 #endif
3648 #ifdef IFF_SLAVE
3649 { IFF_SLAVE, "slave" },
3650 #endif
3651 #ifdef IFF_MULTICAST
3652 { IFF_MULTICAST, "multicast" },
3653 #endif
3654 #ifdef IFF_PORTSEL
3655 { IFF_PORTSEL, "portsel" },
3656 #endif
3657 #ifdef IFF_AUTOMEDIA
3658 { IFF_AUTOMEDIA, "automedia" },
3659 #endif
3660 #ifdef IFF_DYNAMIC
3661 { IFF_DYNAMIC, "dynamic" },
3662 #endif
3663 #ifdef IFF_OACTIVE
3664 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3665 #endif
3666 #ifdef IFF_SIMPLEX
3667 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3668 #endif
3669 #ifdef IFF_LINK0
3670 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3671 #endif
3672 #ifdef IFF_LINK1
3673 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3674 #endif
3675 #ifdef IFF_LINK2
3676 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3677 #endif
3678 { 0, 0 }
3681 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3682 doc: /* Return information about network interface named IFNAME.
3683 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3684 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3685 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3686 FLAGS is the current flags of the interface. */)
3687 (ifname)
3688 Lisp_Object ifname;
3690 struct ifreq rq;
3691 Lisp_Object res = Qnil;
3692 Lisp_Object elt;
3693 int s;
3694 int any = 0;
3696 CHECK_STRING (ifname);
3698 bzero (rq.ifr_name, sizeof rq.ifr_name);
3699 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3701 s = socket (AF_INET, SOCK_STREAM, 0);
3702 if (s < 0)
3703 return Qnil;
3705 elt = Qnil;
3706 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3707 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3709 int flags = rq.ifr_flags;
3710 struct ifflag_def *fp;
3711 int fnum;
3713 any++;
3714 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3716 if (flags & fp->flag_bit)
3718 elt = Fcons (intern (fp->flag_sym), elt);
3719 flags -= fp->flag_bit;
3722 for (fnum = 0; flags && fnum < 32; fnum++)
3724 if (flags & (1 << fnum))
3726 elt = Fcons (make_number (fnum), elt);
3730 #endif
3731 res = Fcons (elt, res);
3733 elt = Qnil;
3734 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3735 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3737 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3738 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3739 int n;
3741 any++;
3742 for (n = 0; n < 6; n++)
3743 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3744 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3746 #endif
3747 res = Fcons (elt, res);
3749 elt = Qnil;
3750 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3751 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3753 any++;
3754 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3755 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3756 #else
3757 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3758 #endif
3760 #endif
3761 res = Fcons (elt, res);
3763 elt = Qnil;
3764 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3765 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3767 any++;
3768 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3770 #endif
3771 res = Fcons (elt, res);
3773 elt = Qnil;
3774 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3775 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3777 any++;
3778 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3780 #endif
3781 res = Fcons (elt, res);
3783 close (s);
3785 return any ? res : Qnil;
3787 #endif
3788 #endif /* HAVE_SOCKETS */
3790 /* Turn off input and output for process PROC. */
3792 void
3793 deactivate_process (proc)
3794 Lisp_Object proc;
3796 register int inchannel, outchannel;
3797 register struct Lisp_Process *p = XPROCESS (proc);
3799 inchannel = p->infd;
3800 outchannel = p->outfd;
3802 #ifdef ADAPTIVE_READ_BUFFERING
3803 if (p->read_output_delay > 0)
3805 if (--process_output_delay_count < 0)
3806 process_output_delay_count = 0;
3807 p->read_output_delay = 0;
3808 p->read_output_skip = 0;
3810 #endif
3812 if (inchannel >= 0)
3814 /* Beware SIGCHLD hereabouts. */
3815 flush_pending_output (inchannel);
3816 #ifdef VMS
3818 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
3819 sys$dassgn (outchannel);
3820 vs = get_vms_process_pointer (p->pid);
3821 if (vs)
3822 give_back_vms_process_stuff (vs);
3824 #else
3825 emacs_close (inchannel);
3826 if (outchannel >= 0 && outchannel != inchannel)
3827 emacs_close (outchannel);
3828 #endif
3830 p->infd = -1;
3831 p->outfd = -1;
3832 #ifdef DATAGRAM_SOCKETS
3833 if (DATAGRAM_CHAN_P (inchannel))
3835 xfree (datagram_address[inchannel].sa);
3836 datagram_address[inchannel].sa = 0;
3837 datagram_address[inchannel].len = 0;
3839 #endif
3840 chan_process[inchannel] = Qnil;
3841 FD_CLR (inchannel, &input_wait_mask);
3842 FD_CLR (inchannel, &non_keyboard_wait_mask);
3843 #ifdef NON_BLOCKING_CONNECT
3844 if (FD_ISSET (inchannel, &connect_wait_mask))
3846 FD_CLR (inchannel, &connect_wait_mask);
3847 if (--num_pending_connects < 0)
3848 abort ();
3850 #endif
3851 if (inchannel == max_process_desc)
3853 int i;
3854 /* We just closed the highest-numbered process input descriptor,
3855 so recompute the highest-numbered one now. */
3856 max_process_desc = 0;
3857 for (i = 0; i < MAXDESC; i++)
3858 if (!NILP (chan_process[i]))
3859 max_process_desc = i;
3864 /* Close all descriptors currently in use for communication
3865 with subprocess. This is used in a newly-forked subprocess
3866 to get rid of irrelevant descriptors. */
3868 void
3869 close_process_descs ()
3871 #ifndef WINDOWSNT
3872 int i;
3873 for (i = 0; i < MAXDESC; i++)
3875 Lisp_Object process;
3876 process = chan_process[i];
3877 if (!NILP (process))
3879 int in = XPROCESS (process)->infd;
3880 int out = XPROCESS (process)->outfd;
3881 if (in >= 0)
3882 emacs_close (in);
3883 if (out >= 0 && in != out)
3884 emacs_close (out);
3887 #endif
3890 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3891 0, 4, 0,
3892 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3893 It is read into the process' buffers or given to their filter functions.
3894 Non-nil arg PROCESS means do not return until some output has been received
3895 from PROCESS.
3897 Non-nil second arg SECONDS and third arg MILLISEC are number of
3898 seconds and milliseconds to wait; return after that much time whether
3899 or not there is input. If SECONDS is a floating point number,
3900 it specifies a fractional number of seconds to wait.
3902 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3903 from PROCESS, suspending reading output from other processes.
3904 If JUST-THIS-ONE is an integer, don't run any timers either.
3905 Return non-nil if we received any output before the timeout expired. */)
3906 (process, seconds, millisec, just_this_one)
3907 register Lisp_Object process, seconds, millisec, just_this_one;
3909 int secs, usecs = 0;
3911 if (! NILP (process))
3912 CHECK_PROCESS (process);
3913 else
3914 just_this_one = Qnil;
3916 if (!NILP (seconds))
3918 if (INTEGERP (seconds))
3919 secs = XINT (seconds);
3920 else if (FLOATP (seconds))
3922 double timeout = XFLOAT_DATA (seconds);
3923 secs = (int) timeout;
3924 usecs = (int) ((timeout - (double) secs) * 1000000);
3926 else
3927 wrong_type_argument (Qnumberp, seconds);
3929 if (INTEGERP (millisec))
3931 int carry;
3932 usecs += XINT (millisec) * 1000;
3933 carry = usecs / 1000000;
3934 secs += carry;
3935 if ((usecs -= carry * 1000000) < 0)
3937 secs--;
3938 usecs += 1000000;
3942 if (secs < 0 || (secs == 0 && usecs == 0))
3943 secs = -1, usecs = 0;
3945 else
3946 secs = NILP (process) ? -1 : 0;
3948 return
3949 (wait_reading_process_output (secs, usecs, 0, 0,
3950 Qnil,
3951 !NILP (process) ? XPROCESS (process) : NULL,
3952 NILP (just_this_one) ? 0 :
3953 !INTEGERP (just_this_one) ? 1 : -1)
3954 ? Qt : Qnil);
3957 /* Accept a connection for server process SERVER on CHANNEL. */
3959 static int connect_counter = 0;
3961 static void
3962 server_accept_connection (server, channel)
3963 Lisp_Object server;
3964 int channel;
3966 Lisp_Object proc, caller, name, buffer;
3967 Lisp_Object contact, host, service;
3968 struct Lisp_Process *ps= XPROCESS (server);
3969 struct Lisp_Process *p;
3970 int s;
3971 union u_sockaddr {
3972 struct sockaddr sa;
3973 struct sockaddr_in in;
3974 #ifdef AF_INET6
3975 struct sockaddr_in6 in6;
3976 #endif
3977 #ifdef HAVE_LOCAL_SOCKETS
3978 struct sockaddr_un un;
3979 #endif
3980 } saddr;
3981 int len = sizeof saddr;
3983 s = accept (channel, &saddr.sa, &len);
3985 if (s < 0)
3987 int code = errno;
3989 if (code == EAGAIN)
3990 return;
3991 #ifdef EWOULDBLOCK
3992 if (code == EWOULDBLOCK)
3993 return;
3994 #endif
3996 if (!NILP (ps->log))
3997 call3 (ps->log, server, Qnil,
3998 concat3 (build_string ("accept failed with code"),
3999 Fnumber_to_string (make_number (code)),
4000 build_string ("\n")));
4001 return;
4004 connect_counter++;
4006 /* Setup a new process to handle the connection. */
4008 /* Generate a unique identification of the caller, and build contact
4009 information for this process. */
4010 host = Qt;
4011 service = Qnil;
4012 switch (saddr.sa.sa_family)
4014 case AF_INET:
4016 Lisp_Object args[5];
4017 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4018 args[0] = build_string ("%d.%d.%d.%d");
4019 args[1] = make_number (*ip++);
4020 args[2] = make_number (*ip++);
4021 args[3] = make_number (*ip++);
4022 args[4] = make_number (*ip++);
4023 host = Fformat (5, args);
4024 service = make_number (ntohs (saddr.in.sin_port));
4026 args[0] = build_string (" <%s:%d>");
4027 args[1] = host;
4028 args[2] = service;
4029 caller = Fformat (3, args);
4031 break;
4033 #ifdef AF_INET6
4034 case AF_INET6:
4036 Lisp_Object args[9];
4037 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4038 int i;
4039 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4040 for (i = 0; i < 8; i++)
4041 args[i+1] = make_number (ntohs(ip6[i]));
4042 host = Fformat (9, args);
4043 service = make_number (ntohs (saddr.in.sin_port));
4045 args[0] = build_string (" <[%s]:%d>");
4046 args[1] = host;
4047 args[2] = service;
4048 caller = Fformat (3, args);
4050 break;
4051 #endif
4053 #ifdef HAVE_LOCAL_SOCKETS
4054 case AF_LOCAL:
4055 #endif
4056 default:
4057 caller = Fnumber_to_string (make_number (connect_counter));
4058 caller = concat3 (build_string (" <"), caller, build_string (">"));
4059 break;
4062 /* Create a new buffer name for this process if it doesn't have a
4063 filter. The new buffer name is based on the buffer name or
4064 process name of the server process concatenated with the caller
4065 identification. */
4067 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4068 buffer = Qnil;
4069 else
4071 buffer = ps->buffer;
4072 if (!NILP (buffer))
4073 buffer = Fbuffer_name (buffer);
4074 else
4075 buffer = ps->name;
4076 if (!NILP (buffer))
4078 buffer = concat2 (buffer, caller);
4079 buffer = Fget_buffer_create (buffer);
4083 /* Generate a unique name for the new server process. Combine the
4084 server process name with the caller identification. */
4086 name = concat2 (ps->name, caller);
4087 proc = make_process (name);
4089 chan_process[s] = proc;
4091 #ifdef O_NONBLOCK
4092 fcntl (s, F_SETFL, O_NONBLOCK);
4093 #else
4094 #ifdef O_NDELAY
4095 fcntl (s, F_SETFL, O_NDELAY);
4096 #endif
4097 #endif
4099 p = XPROCESS (proc);
4101 /* Build new contact information for this setup. */
4102 contact = Fcopy_sequence (ps->childp);
4103 contact = Fplist_put (contact, QCserver, Qnil);
4104 contact = Fplist_put (contact, QChost, host);
4105 if (!NILP (service))
4106 contact = Fplist_put (contact, QCservice, service);
4107 contact = Fplist_put (contact, QCremote,
4108 conv_sockaddr_to_lisp (&saddr.sa, len));
4109 #ifdef HAVE_GETSOCKNAME
4110 len = sizeof saddr;
4111 if (getsockname (s, &saddr.sa, &len) == 0)
4112 contact = Fplist_put (contact, QClocal,
4113 conv_sockaddr_to_lisp (&saddr.sa, len));
4114 #endif
4116 p->childp = contact;
4117 p->plist = Fcopy_sequence (ps->plist);
4119 p->buffer = buffer;
4120 p->sentinel = ps->sentinel;
4121 p->filter = ps->filter;
4122 p->command = Qnil;
4123 p->pid = 0;
4124 p->infd = s;
4125 p->outfd = s;
4126 p->status = Qrun;
4128 /* Client processes for accepted connections are not stopped initially. */
4129 if (!EQ (p->filter, Qt))
4131 FD_SET (s, &input_wait_mask);
4132 FD_SET (s, &non_keyboard_wait_mask);
4135 if (s > max_process_desc)
4136 max_process_desc = s;
4138 /* Setup coding system for new process based on server process.
4139 This seems to be the proper thing to do, as the coding system
4140 of the new process should reflect the settings at the time the
4141 server socket was opened; not the current settings. */
4143 p->decode_coding_system = ps->decode_coding_system;
4144 p->encode_coding_system = ps->encode_coding_system;
4145 setup_process_coding_systems (proc);
4147 p->decoding_buf = make_uninit_string (0);
4148 p->decoding_carryover = 0;
4149 p->encoding_buf = make_uninit_string (0);
4151 p->inherit_coding_system_flag
4152 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4154 if (!NILP (ps->log))
4155 call3 (ps->log, server, proc,
4156 concat3 (build_string ("accept from "),
4157 (STRINGP (host) ? host : build_string ("-")),
4158 build_string ("\n")));
4160 if (!NILP (p->sentinel))
4161 exec_sentinel (proc,
4162 concat3 (build_string ("open from "),
4163 (STRINGP (host) ? host : build_string ("-")),
4164 build_string ("\n")));
4167 /* This variable is different from waiting_for_input in keyboard.c.
4168 It is used to communicate to a lisp process-filter/sentinel (via the
4169 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4170 for user-input when that process-filter was called.
4171 waiting_for_input cannot be used as that is by definition 0 when
4172 lisp code is being evalled.
4173 This is also used in record_asynch_buffer_change.
4174 For that purpose, this must be 0
4175 when not inside wait_reading_process_output. */
4176 static int waiting_for_user_input_p;
4178 static Lisp_Object
4179 wait_reading_process_output_unwind (data)
4180 Lisp_Object data;
4182 waiting_for_user_input_p = XINT (data);
4183 return Qnil;
4186 /* This is here so breakpoints can be put on it. */
4187 static void
4188 wait_reading_process_output_1 ()
4192 /* Use a wrapper around select to work around a bug in gdb 5.3.
4193 Normally, the wrapper is optimzed away by inlining.
4195 If emacs is stopped inside select, the gdb backtrace doesn't
4196 show the function which called select, so it is practically
4197 impossible to step through wait_reading_process_output. */
4199 #ifndef select
4200 static INLINE int
4201 select_wrapper (n, rfd, wfd, xfd, tmo)
4202 int n;
4203 SELECT_TYPE *rfd, *wfd, *xfd;
4204 EMACS_TIME *tmo;
4206 return select (n, rfd, wfd, xfd, tmo);
4208 #define select select_wrapper
4209 #endif
4211 /* Read and dispose of subprocess output while waiting for timeout to
4212 elapse and/or keyboard input to be available.
4214 TIME_LIMIT is:
4215 timeout in seconds, or
4216 zero for no limit, or
4217 -1 means gobble data immediately available but don't wait for any.
4219 MICROSECS is:
4220 an additional duration to wait, measured in microseconds.
4221 If this is nonzero and time_limit is 0, then the timeout
4222 consists of MICROSECS only.
4224 READ_KBD is a lisp value:
4225 0 to ignore keyboard input, or
4226 1 to return when input is available, or
4227 -1 meaning caller will actually read the input, so don't throw to
4228 the quit handler, or
4230 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4231 output that arrives.
4233 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4234 (and gobble terminal input into the buffer if any arrives).
4236 If WAIT_PROC is specified, wait until something arrives from that
4237 process. The return value is true if we read some input from
4238 that process.
4240 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4241 (suspending output from other processes). A negative value
4242 means don't run any timers either.
4244 If WAIT_PROC is specified, then the function returns true if we
4245 received input from that process before the timeout elapsed.
4246 Otherwise, return true if we received input from any process. */
4249 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4250 wait_for_cell, wait_proc, just_wait_proc)
4251 int time_limit, microsecs, read_kbd, do_display;
4252 Lisp_Object wait_for_cell;
4253 struct Lisp_Process *wait_proc;
4254 int just_wait_proc;
4256 register int channel, nfds;
4257 SELECT_TYPE Available;
4258 #ifdef NON_BLOCKING_CONNECT
4259 SELECT_TYPE Connecting;
4260 int check_connect;
4261 #endif
4262 int check_delay, no_avail;
4263 int xerrno;
4264 Lisp_Object proc;
4265 EMACS_TIME timeout, end_time;
4266 int wait_channel = -1;
4267 int got_some_input = 0;
4268 int count = SPECPDL_INDEX ();
4270 FD_ZERO (&Available);
4271 #ifdef NON_BLOCKING_CONNECT
4272 FD_ZERO (&Connecting);
4273 #endif
4275 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4276 if (wait_proc != NULL)
4277 wait_channel = wait_proc->infd;
4279 record_unwind_protect (wait_reading_process_output_unwind,
4280 make_number (waiting_for_user_input_p));
4281 waiting_for_user_input_p = read_kbd;
4283 /* Since we may need to wait several times,
4284 compute the absolute time to return at. */
4285 if (time_limit || microsecs)
4287 EMACS_GET_TIME (end_time);
4288 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4289 EMACS_ADD_TIME (end_time, end_time, timeout);
4291 #ifdef POLL_INTERRUPTED_SYS_CALL
4292 /* AlainF 5-Jul-1996
4293 HP-UX 10.10 seem to have problems with signals coming in
4294 Causes "poll: interrupted system call" messages when Emacs is run
4295 in an X window
4296 Turn off periodic alarms (in case they are in use),
4297 and then turn off any other atimers. */
4298 stop_polling ();
4299 turn_on_atimers (0);
4300 #endif /* POLL_INTERRUPTED_SYS_CALL */
4302 while (1)
4304 int timeout_reduced_for_timers = 0;
4306 /* If calling from keyboard input, do not quit
4307 since we want to return C-g as an input character.
4308 Otherwise, do pending quit if requested. */
4309 if (read_kbd >= 0)
4310 QUIT;
4311 #ifdef SYNC_INPUT
4312 else
4314 if (interrupt_input_pending)
4315 handle_async_input ();
4316 if (pending_atimers)
4317 do_pending_atimers ();
4319 #endif
4321 /* Exit now if the cell we're waiting for became non-nil. */
4322 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4323 break;
4325 /* Compute time from now till when time limit is up */
4326 /* Exit if already run out */
4327 if (time_limit == -1)
4329 /* -1 specified for timeout means
4330 gobble output available now
4331 but don't wait at all. */
4333 EMACS_SET_SECS_USECS (timeout, 0, 0);
4335 else if (time_limit || microsecs)
4337 EMACS_GET_TIME (timeout);
4338 EMACS_SUB_TIME (timeout, end_time, timeout);
4339 if (EMACS_TIME_NEG_P (timeout))
4340 break;
4342 else
4344 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4347 /* Normally we run timers here.
4348 But not if wait_for_cell; in those cases,
4349 the wait is supposed to be short,
4350 and those callers cannot handle running arbitrary Lisp code here. */
4351 if (NILP (wait_for_cell)
4352 && just_wait_proc >= 0)
4354 EMACS_TIME timer_delay;
4358 int old_timers_run = timers_run;
4359 struct buffer *old_buffer = current_buffer;
4360 Lisp_Object old_window = selected_window;
4362 timer_delay = timer_check (1);
4364 /* If a timer has run, this might have changed buffers
4365 an alike. Make read_key_sequence aware of that. */
4366 if (timers_run != old_timers_run
4367 && (old_buffer != current_buffer
4368 || !EQ (old_window, selected_window))
4369 && waiting_for_user_input_p == -1)
4370 record_asynch_buffer_change ();
4372 if (timers_run != old_timers_run && do_display)
4373 /* We must retry, since a timer may have requeued itself
4374 and that could alter the time_delay. */
4375 redisplay_preserve_echo_area (9);
4376 else
4377 break;
4379 while (!detect_input_pending ());
4381 /* If there is unread keyboard input, also return. */
4382 if (read_kbd != 0
4383 && requeued_events_pending_p ())
4384 break;
4386 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4388 EMACS_TIME difference;
4389 EMACS_SUB_TIME (difference, timer_delay, timeout);
4390 if (EMACS_TIME_NEG_P (difference))
4392 timeout = timer_delay;
4393 timeout_reduced_for_timers = 1;
4396 /* If time_limit is -1, we are not going to wait at all. */
4397 else if (time_limit != -1)
4399 /* This is so a breakpoint can be put here. */
4400 wait_reading_process_output_1 ();
4404 /* Cause C-g and alarm signals to take immediate action,
4405 and cause input available signals to zero out timeout.
4407 It is important that we do this before checking for process
4408 activity. If we get a SIGCHLD after the explicit checks for
4409 process activity, timeout is the only way we will know. */
4410 if (read_kbd < 0)
4411 set_waiting_for_input (&timeout);
4413 /* If status of something has changed, and no input is
4414 available, notify the user of the change right away. After
4415 this explicit check, we'll let the SIGCHLD handler zap
4416 timeout to get our attention. */
4417 if (update_tick != process_tick && do_display)
4419 SELECT_TYPE Atemp;
4420 #ifdef NON_BLOCKING_CONNECT
4421 SELECT_TYPE Ctemp;
4422 #endif
4424 Atemp = input_wait_mask;
4425 #if 0
4426 /* On Mac OS X 10.0, the SELECT system call always says input is
4427 present (for reading) at stdin, even when none is. This
4428 causes the call to SELECT below to return 1 and
4429 status_notify not to be called. As a result output of
4430 subprocesses are incorrectly discarded.
4432 FD_CLR (0, &Atemp);
4433 #endif
4434 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4436 EMACS_SET_SECS_USECS (timeout, 0, 0);
4437 if ((select (max (max (max_process_desc, max_keyboard_desc),
4438 max_gpm_desc) + 1,
4439 &Atemp,
4440 #ifdef NON_BLOCKING_CONNECT
4441 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4442 #else
4443 (SELECT_TYPE *)0,
4444 #endif
4445 (SELECT_TYPE *)0, &timeout)
4446 <= 0))
4448 /* It's okay for us to do this and then continue with
4449 the loop, since timeout has already been zeroed out. */
4450 clear_waiting_for_input ();
4451 status_notify (NULL);
4455 /* Don't wait for output from a non-running process. Just
4456 read whatever data has already been received. */
4457 if (wait_proc && wait_proc->raw_status_new)
4458 update_status (wait_proc);
4459 if (wait_proc
4460 && ! EQ (wait_proc->status, Qrun)
4461 && ! EQ (wait_proc->status, Qconnect))
4463 int nread, total_nread = 0;
4465 clear_waiting_for_input ();
4466 XSETPROCESS (proc, wait_proc);
4468 /* Read data from the process, until we exhaust it. */
4469 while (wait_proc->infd >= 0)
4471 nread = read_process_output (proc, wait_proc->infd);
4473 if (nread == 0)
4474 break;
4476 if (0 < nread)
4477 total_nread += nread;
4478 #ifdef EIO
4479 else if (nread == -1 && EIO == errno)
4480 break;
4481 #endif
4482 #ifdef EAGAIN
4483 else if (nread == -1 && EAGAIN == errno)
4484 break;
4485 #endif
4486 #ifdef EWOULDBLOCK
4487 else if (nread == -1 && EWOULDBLOCK == errno)
4488 break;
4489 #endif
4491 if (total_nread > 0 && do_display)
4492 redisplay_preserve_echo_area (10);
4494 break;
4497 /* Wait till there is something to do */
4499 if (wait_proc && just_wait_proc)
4501 if (wait_proc->infd < 0) /* Terminated */
4502 break;
4503 FD_SET (wait_proc->infd, &Available);
4504 check_delay = 0;
4505 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4507 else if (!NILP (wait_for_cell))
4509 Available = non_process_wait_mask;
4510 check_delay = 0;
4511 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4513 else
4515 if (! read_kbd)
4516 Available = non_keyboard_wait_mask;
4517 else
4518 Available = input_wait_mask;
4519 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4520 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4523 /* If frame size has changed or the window is newly mapped,
4524 redisplay now, before we start to wait. There is a race
4525 condition here; if a SIGIO arrives between now and the select
4526 and indicates that a frame is trashed, the select may block
4527 displaying a trashed screen. */
4528 if (frame_garbaged && do_display)
4530 clear_waiting_for_input ();
4531 redisplay_preserve_echo_area (11);
4532 if (read_kbd < 0)
4533 set_waiting_for_input (&timeout);
4536 no_avail = 0;
4537 if (read_kbd && detect_input_pending ())
4539 nfds = 0;
4540 no_avail = 1;
4542 else
4544 #ifdef NON_BLOCKING_CONNECT
4545 if (check_connect)
4546 Connecting = connect_wait_mask;
4547 #endif
4549 #ifdef ADAPTIVE_READ_BUFFERING
4550 /* Set the timeout for adaptive read buffering if any
4551 process has non-zero read_output_skip and non-zero
4552 read_output_delay, and we are not reading output for a
4553 specific wait_channel. It is not executed if
4554 Vprocess_adaptive_read_buffering is nil. */
4555 if (process_output_skip && check_delay > 0)
4557 int usecs = EMACS_USECS (timeout);
4558 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4559 usecs = READ_OUTPUT_DELAY_MAX;
4560 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4562 proc = chan_process[channel];
4563 if (NILP (proc))
4564 continue;
4565 /* Find minimum non-zero read_output_delay among the
4566 processes with non-zero read_output_skip. */
4567 if (XPROCESS (proc)->read_output_delay > 0)
4569 check_delay--;
4570 if (!XPROCESS (proc)->read_output_skip)
4571 continue;
4572 FD_CLR (channel, &Available);
4573 XPROCESS (proc)->read_output_skip = 0;
4574 if (XPROCESS (proc)->read_output_delay < usecs)
4575 usecs = XPROCESS (proc)->read_output_delay;
4578 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4579 process_output_skip = 0;
4581 #endif
4583 nfds = select (max (max (max_process_desc, max_keyboard_desc),
4584 max_gpm_desc) + 1,
4585 &Available,
4586 #ifdef NON_BLOCKING_CONNECT
4587 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4588 #else
4589 (SELECT_TYPE *)0,
4590 #endif
4591 (SELECT_TYPE *)0, &timeout);
4594 xerrno = errno;
4596 /* Make C-g and alarm signals set flags again */
4597 clear_waiting_for_input ();
4599 /* If we woke up due to SIGWINCH, actually change size now. */
4600 do_pending_window_change (0);
4602 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4603 /* We wanted the full specified time, so return now. */
4604 break;
4605 if (nfds < 0)
4607 if (xerrno == EINTR)
4608 no_avail = 1;
4609 #ifdef ultrix
4610 /* Ultrix select seems to return ENOMEM when it is
4611 interrupted. Treat it just like EINTR. Bleah. Note
4612 that we want to test for the "ultrix" CPP symbol, not
4613 "__ultrix__"; the latter is only defined under GCC, but
4614 not by DEC's bundled CC. -JimB */
4615 else if (xerrno == ENOMEM)
4616 no_avail = 1;
4617 #endif
4618 else if (xerrno == EBADF)
4620 #ifdef AIX
4621 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4622 the child's closure of the pts gives the parent a SIGHUP, and
4623 the ptc file descriptor is automatically closed,
4624 yielding EBADF here or at select() call above.
4625 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4626 in m/ibmrt-aix.h), and here we just ignore the select error.
4627 Cleanup occurs c/o status_notify after SIGCLD. */
4628 no_avail = 1; /* Cannot depend on values returned */
4629 #else
4630 abort ();
4631 #endif
4633 else
4634 error ("select error: %s", emacs_strerror (xerrno));
4637 if (no_avail)
4639 FD_ZERO (&Available);
4640 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4643 #if defined(sun) && !defined(USG5_4)
4644 if (nfds > 0 && keyboard_bit_set (&Available)
4645 && interrupt_input)
4646 /* System sometimes fails to deliver SIGIO.
4648 David J. Mackenzie says that Emacs doesn't compile under
4649 Solaris if this code is enabled, thus the USG5_4 in the CPP
4650 conditional. "I haven't noticed any ill effects so far.
4651 If you find a Solaris expert somewhere, they might know
4652 better." */
4653 kill (getpid (), SIGIO);
4654 #endif
4656 #if 0 /* When polling is used, interrupt_input is 0,
4657 so get_input_pending should read the input.
4658 So this should not be needed. */
4659 /* If we are using polling for input,
4660 and we see input available, make it get read now.
4661 Otherwise it might not actually get read for a second.
4662 And on hpux, since we turn off polling in wait_reading_process_output,
4663 it might never get read at all if we don't spend much time
4664 outside of wait_reading_process_output. */
4665 if (read_kbd && interrupt_input
4666 && keyboard_bit_set (&Available)
4667 && input_polling_used ())
4668 kill (getpid (), SIGALRM);
4669 #endif
4671 /* Check for keyboard input */
4672 /* If there is any, return immediately
4673 to give it higher priority than subprocesses */
4675 if (read_kbd != 0)
4677 int old_timers_run = timers_run;
4678 struct buffer *old_buffer = current_buffer;
4679 Lisp_Object old_window = selected_window;
4680 int leave = 0;
4682 if (detect_input_pending_run_timers (do_display))
4684 swallow_events (do_display);
4685 if (detect_input_pending_run_timers (do_display))
4686 leave = 1;
4689 /* If a timer has run, this might have changed buffers
4690 an alike. Make read_key_sequence aware of that. */
4691 if (timers_run != old_timers_run
4692 && waiting_for_user_input_p == -1
4693 && (old_buffer != current_buffer
4694 || !EQ (old_window, selected_window)))
4695 record_asynch_buffer_change ();
4697 if (leave)
4698 break;
4701 /* If there is unread keyboard input, also return. */
4702 if (read_kbd != 0
4703 && requeued_events_pending_p ())
4704 break;
4706 /* If we are not checking for keyboard input now,
4707 do process events (but don't run any timers).
4708 This is so that X events will be processed.
4709 Otherwise they may have to wait until polling takes place.
4710 That would causes delays in pasting selections, for example.
4712 (We used to do this only if wait_for_cell.) */
4713 if (read_kbd == 0 && detect_input_pending ())
4715 swallow_events (do_display);
4716 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4717 if (detect_input_pending ())
4718 break;
4719 #endif
4722 /* Exit now if the cell we're waiting for became non-nil. */
4723 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4724 break;
4726 #ifdef SIGIO
4727 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4728 go read it. This can happen with X on BSD after logging out.
4729 In that case, there really is no input and no SIGIO,
4730 but select says there is input. */
4732 if (read_kbd && interrupt_input
4733 && keyboard_bit_set (&Available) && ! noninteractive)
4734 kill (getpid (), SIGIO);
4735 #endif
4737 if (! wait_proc)
4738 got_some_input |= nfds > 0;
4740 /* If checking input just got us a size-change event from X,
4741 obey it now if we should. */
4742 if (read_kbd || ! NILP (wait_for_cell))
4743 do_pending_window_change (0);
4745 /* Check for data from a process. */
4746 if (no_avail || nfds == 0)
4747 continue;
4749 /* Really FIRST_PROC_DESC should be 0 on Unix,
4750 but this is safer in the short run. */
4751 for (channel = 0; channel <= max_process_desc; channel++)
4753 if (FD_ISSET (channel, &Available)
4754 && FD_ISSET (channel, &non_keyboard_wait_mask))
4756 int nread;
4758 /* If waiting for this channel, arrange to return as
4759 soon as no more input to be processed. No more
4760 waiting. */
4761 if (wait_channel == channel)
4763 wait_channel = -1;
4764 time_limit = -1;
4765 got_some_input = 1;
4767 proc = chan_process[channel];
4768 if (NILP (proc))
4769 continue;
4771 /* If this is a server stream socket, accept connection. */
4772 if (EQ (XPROCESS (proc)->status, Qlisten))
4774 server_accept_connection (proc, channel);
4775 continue;
4778 /* Read data from the process, starting with our
4779 buffered-ahead character if we have one. */
4781 nread = read_process_output (proc, channel);
4782 if (nread > 0)
4784 /* Since read_process_output can run a filter,
4785 which can call accept-process-output,
4786 don't try to read from any other processes
4787 before doing the select again. */
4788 FD_ZERO (&Available);
4790 if (do_display)
4791 redisplay_preserve_echo_area (12);
4793 #ifdef EWOULDBLOCK
4794 else if (nread == -1 && errno == EWOULDBLOCK)
4796 #endif
4797 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4798 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4799 #ifdef O_NONBLOCK
4800 else if (nread == -1 && errno == EAGAIN)
4802 #else
4803 #ifdef O_NDELAY
4804 else if (nread == -1 && errno == EAGAIN)
4806 /* Note that we cannot distinguish between no input
4807 available now and a closed pipe.
4808 With luck, a closed pipe will be accompanied by
4809 subprocess termination and SIGCHLD. */
4810 else if (nread == 0 && !NETCONN_P (proc))
4812 #endif /* O_NDELAY */
4813 #endif /* O_NONBLOCK */
4814 #ifdef HAVE_PTYS
4815 /* On some OSs with ptys, when the process on one end of
4816 a pty exits, the other end gets an error reading with
4817 errno = EIO instead of getting an EOF (0 bytes read).
4818 Therefore, if we get an error reading and errno =
4819 EIO, just continue, because the child process has
4820 exited and should clean itself up soon (e.g. when we
4821 get a SIGCHLD).
4823 However, it has been known to happen that the SIGCHLD
4824 got lost. So raise the signal again just in case.
4825 It can't hurt. */
4826 else if (nread == -1 && errno == EIO)
4828 /* Clear the descriptor now, so we only raise the signal once. */
4829 FD_CLR (channel, &input_wait_mask);
4830 FD_CLR (channel, &non_keyboard_wait_mask);
4832 kill (getpid (), SIGCHLD);
4834 #endif /* HAVE_PTYS */
4835 /* If we can detect process termination, don't consider the process
4836 gone just because its pipe is closed. */
4837 #ifdef SIGCHLD
4838 else if (nread == 0 && !NETCONN_P (proc))
4840 #endif
4841 else
4843 /* Preserve status of processes already terminated. */
4844 XPROCESS (proc)->tick = ++process_tick;
4845 deactivate_process (proc);
4846 if (XPROCESS (proc)->raw_status_new)
4847 update_status (XPROCESS (proc));
4848 if (EQ (XPROCESS (proc)->status, Qrun))
4849 XPROCESS (proc)->status
4850 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4853 #ifdef NON_BLOCKING_CONNECT
4854 if (check_connect && FD_ISSET (channel, &Connecting)
4855 && FD_ISSET (channel, &connect_wait_mask))
4857 struct Lisp_Process *p;
4859 FD_CLR (channel, &connect_wait_mask);
4860 if (--num_pending_connects < 0)
4861 abort ();
4863 proc = chan_process[channel];
4864 if (NILP (proc))
4865 continue;
4867 p = XPROCESS (proc);
4869 #ifdef GNU_LINUX
4870 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4871 So only use it on systems where it is known to work. */
4873 int xlen = sizeof(xerrno);
4874 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4875 xerrno = errno;
4877 #else
4879 struct sockaddr pname;
4880 int pnamelen = sizeof(pname);
4882 /* If connection failed, getpeername will fail. */
4883 xerrno = 0;
4884 if (getpeername(channel, &pname, &pnamelen) < 0)
4886 /* Obtain connect failure code through error slippage. */
4887 char dummy;
4888 xerrno = errno;
4889 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4890 xerrno = errno;
4893 #endif
4894 if (xerrno)
4896 p->tick = ++process_tick;
4897 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4898 deactivate_process (proc);
4900 else
4902 p->status = Qrun;
4903 /* Execute the sentinel here. If we had relied on
4904 status_notify to do it later, it will read input
4905 from the process before calling the sentinel. */
4906 exec_sentinel (proc, build_string ("open\n"));
4907 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4909 FD_SET (p->infd, &input_wait_mask);
4910 FD_SET (p->infd, &non_keyboard_wait_mask);
4914 #endif /* NON_BLOCKING_CONNECT */
4915 } /* end for each file descriptor */
4916 } /* end while exit conditions not met */
4918 unbind_to (count, Qnil);
4920 /* If calling from keyboard input, do not quit
4921 since we want to return C-g as an input character.
4922 Otherwise, do pending quit if requested. */
4923 if (read_kbd >= 0)
4925 /* Prevent input_pending from remaining set if we quit. */
4926 clear_input_pending ();
4927 QUIT;
4929 #ifdef POLL_INTERRUPTED_SYS_CALL
4930 /* AlainF 5-Jul-1996
4931 HP-UX 10.10 seems to have problems with signals coming in
4932 Causes "poll: interrupted system call" messages when Emacs is run
4933 in an X window
4934 Turn periodic alarms back on */
4935 start_polling ();
4936 #endif /* POLL_INTERRUPTED_SYS_CALL */
4938 return got_some_input;
4941 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4943 static Lisp_Object
4944 read_process_output_call (fun_and_args)
4945 Lisp_Object fun_and_args;
4947 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4950 static Lisp_Object
4951 read_process_output_error_handler (error)
4952 Lisp_Object error;
4954 cmd_error_internal (error, "error in process filter: ");
4955 Vinhibit_quit = Qt;
4956 update_echo_area ();
4957 Fsleep_for (make_number (2), Qnil);
4958 return Qt;
4961 /* Read pending output from the process channel,
4962 starting with our buffered-ahead character if we have one.
4963 Yield number of decoded characters read.
4965 This function reads at most 4096 characters.
4966 If you want to read all available subprocess output,
4967 you must call it repeatedly until it returns zero.
4969 The characters read are decoded according to PROC's coding-system
4970 for decoding. */
4972 static int
4973 read_process_output (proc, channel)
4974 Lisp_Object proc;
4975 register int channel;
4977 register int nbytes;
4978 char *chars;
4979 register Lisp_Object outstream;
4980 register struct buffer *old = current_buffer;
4981 register struct Lisp_Process *p = XPROCESS (proc);
4982 register int opoint;
4983 struct coding_system *coding = proc_decode_coding_system[channel];
4984 int carryover = p->decoding_carryover;
4985 int readmax = 4096;
4987 #ifdef VMS
4988 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4990 vs = get_vms_process_pointer (p->pid);
4991 if (vs)
4993 if (!vs->iosb[0])
4994 return (0); /* Really weird if it does this */
4995 if (!(vs->iosb[0] & 1))
4996 return -1; /* I/O error */
4998 else
4999 error ("Could not get VMS process pointer");
5000 chars = vs->inputBuffer;
5001 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
5002 if (nbytes <= 0)
5004 start_vms_process_read (vs); /* Crank up the next read on the process */
5005 return 1; /* Nothing worth printing, say we got 1 */
5007 if (carryover > 0)
5009 /* The data carried over in the previous decoding (which are at
5010 the tail of decoding buffer) should be prepended to the new
5011 data read to decode all together. */
5012 chars = (char *) alloca (nbytes + carryover);
5013 bcopy (SDATA (p->decoding_buf), buf, carryover);
5014 bcopy (vs->inputBuffer, chars + carryover, nbytes);
5016 #else /* not VMS */
5018 chars = (char *) alloca (carryover + readmax);
5019 if (carryover)
5020 /* See the comment above. */
5021 bcopy (SDATA (p->decoding_buf), chars, carryover);
5023 #ifdef DATAGRAM_SOCKETS
5024 /* We have a working select, so proc_buffered_char is always -1. */
5025 if (DATAGRAM_CHAN_P (channel))
5027 int len = datagram_address[channel].len;
5028 nbytes = recvfrom (channel, chars + carryover, readmax,
5029 0, datagram_address[channel].sa, &len);
5031 else
5032 #endif
5033 if (proc_buffered_char[channel] < 0)
5035 nbytes = emacs_read (channel, chars + carryover, readmax);
5036 #ifdef ADAPTIVE_READ_BUFFERING
5037 if (nbytes > 0 && p->adaptive_read_buffering)
5039 int delay = p->read_output_delay;
5040 if (nbytes < 256)
5042 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5044 if (delay == 0)
5045 process_output_delay_count++;
5046 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5049 else if (delay > 0 && (nbytes == readmax))
5051 delay -= READ_OUTPUT_DELAY_INCREMENT;
5052 if (delay == 0)
5053 process_output_delay_count--;
5055 p->read_output_delay = delay;
5056 if (delay)
5058 p->read_output_skip = 1;
5059 process_output_skip = 1;
5062 #endif
5064 else
5066 chars[carryover] = proc_buffered_char[channel];
5067 proc_buffered_char[channel] = -1;
5068 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5069 if (nbytes < 0)
5070 nbytes = 1;
5071 else
5072 nbytes = nbytes + 1;
5074 #endif /* not VMS */
5076 p->decoding_carryover = 0;
5078 /* At this point, NBYTES holds number of bytes just received
5079 (including the one in proc_buffered_char[channel]). */
5080 if (nbytes <= 0)
5082 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5083 return nbytes;
5084 coding->mode |= CODING_MODE_LAST_BLOCK;
5087 /* Now set NBYTES how many bytes we must decode. */
5088 nbytes += carryover;
5090 /* Read and dispose of the process output. */
5091 outstream = p->filter;
5092 if (!NILP (outstream))
5094 /* We inhibit quit here instead of just catching it so that
5095 hitting ^G when a filter happens to be running won't screw
5096 it up. */
5097 int count = SPECPDL_INDEX ();
5098 Lisp_Object odeactivate;
5099 Lisp_Object obuffer, okeymap;
5100 Lisp_Object text;
5101 int outer_running_asynch_code = running_asynch_code;
5102 int waiting = waiting_for_user_input_p;
5104 /* No need to gcpro these, because all we do with them later
5105 is test them for EQness, and none of them should be a string. */
5106 odeactivate = Vdeactivate_mark;
5107 XSETBUFFER (obuffer, current_buffer);
5108 okeymap = current_buffer->keymap;
5110 specbind (Qinhibit_quit, Qt);
5111 specbind (Qlast_nonmenu_event, Qt);
5113 /* In case we get recursively called,
5114 and we already saved the match data nonrecursively,
5115 save the same match data in safely recursive fashion. */
5116 if (outer_running_asynch_code)
5118 Lisp_Object tem;
5119 /* Don't clobber the CURRENT match data, either! */
5120 tem = Fmatch_data (Qnil, Qnil, Qnil);
5121 restore_search_regs ();
5122 record_unwind_save_match_data ();
5123 Fset_match_data (tem, Qt);
5126 /* For speed, if a search happens within this code,
5127 save the match data in a special nonrecursive fashion. */
5128 running_asynch_code = 1;
5130 decode_coding_c_string (coding, chars, nbytes, Qt);
5131 text = coding->dst_object;
5132 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5133 /* A new coding system might be found. */
5134 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5136 p->decode_coding_system = Vlast_coding_system_used;
5138 /* Don't call setup_coding_system for
5139 proc_decode_coding_system[channel] here. It is done in
5140 detect_coding called via decode_coding above. */
5142 /* If a coding system for encoding is not yet decided, we set
5143 it as the same as coding-system for decoding.
5145 But, before doing that we must check if
5146 proc_encode_coding_system[p->outfd] surely points to a
5147 valid memory because p->outfd will be changed once EOF is
5148 sent to the process. */
5149 if (NILP (p->encode_coding_system)
5150 && proc_encode_coding_system[p->outfd])
5152 p->encode_coding_system
5153 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5154 setup_coding_system (p->encode_coding_system,
5155 proc_encode_coding_system[p->outfd]);
5159 if (coding->carryover_bytes > 0)
5161 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5162 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5163 bcopy (coding->carryover, SDATA (p->decoding_buf),
5164 coding->carryover_bytes);
5165 p->decoding_carryover = coding->carryover_bytes;
5167 if (SBYTES (text) > 0)
5168 internal_condition_case_1 (read_process_output_call,
5169 Fcons (outstream,
5170 Fcons (proc, Fcons (text, Qnil))),
5171 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5172 read_process_output_error_handler);
5174 /* If we saved the match data nonrecursively, restore it now. */
5175 restore_search_regs ();
5176 running_asynch_code = outer_running_asynch_code;
5178 /* Handling the process output should not deactivate the mark. */
5179 Vdeactivate_mark = odeactivate;
5181 /* Restore waiting_for_user_input_p as it was
5182 when we were called, in case the filter clobbered it. */
5183 waiting_for_user_input_p = waiting;
5185 #if 0 /* Call record_asynch_buffer_change unconditionally,
5186 because we might have changed minor modes or other things
5187 that affect key bindings. */
5188 if (! EQ (Fcurrent_buffer (), obuffer)
5189 || ! EQ (current_buffer->keymap, okeymap))
5190 #endif
5191 /* But do it only if the caller is actually going to read events.
5192 Otherwise there's no need to make him wake up, and it could
5193 cause trouble (for example it would make sit_for return). */
5194 if (waiting_for_user_input_p == -1)
5195 record_asynch_buffer_change ();
5197 #ifdef VMS
5198 start_vms_process_read (vs);
5199 #endif
5200 unbind_to (count, Qnil);
5201 return nbytes;
5204 /* If no filter, write into buffer if it isn't dead. */
5205 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5207 Lisp_Object old_read_only;
5208 int old_begv, old_zv;
5209 int old_begv_byte, old_zv_byte;
5210 Lisp_Object odeactivate;
5211 int before, before_byte;
5212 int opoint_byte;
5213 Lisp_Object text;
5214 struct buffer *b;
5216 odeactivate = Vdeactivate_mark;
5218 Fset_buffer (p->buffer);
5219 opoint = PT;
5220 opoint_byte = PT_BYTE;
5221 old_read_only = current_buffer->read_only;
5222 old_begv = BEGV;
5223 old_zv = ZV;
5224 old_begv_byte = BEGV_BYTE;
5225 old_zv_byte = ZV_BYTE;
5227 current_buffer->read_only = Qnil;
5229 /* Insert new output into buffer
5230 at the current end-of-output marker,
5231 thus preserving logical ordering of input and output. */
5232 if (XMARKER (p->mark)->buffer)
5233 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5234 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5235 ZV_BYTE));
5236 else
5237 SET_PT_BOTH (ZV, ZV_BYTE);
5238 before = PT;
5239 before_byte = PT_BYTE;
5241 /* If the output marker is outside of the visible region, save
5242 the restriction and widen. */
5243 if (! (BEGV <= PT && PT <= ZV))
5244 Fwiden ();
5246 decode_coding_c_string (coding, chars, nbytes, Qt);
5247 text = coding->dst_object;
5248 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5249 /* A new coding system might be found. See the comment in the
5250 similar code in the previous `if' block. */
5251 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5253 p->decode_coding_system = Vlast_coding_system_used;
5254 if (NILP (p->encode_coding_system)
5255 && proc_encode_coding_system[p->outfd])
5257 p->encode_coding_system
5258 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5259 setup_coding_system (p->encode_coding_system,
5260 proc_encode_coding_system[p->outfd]);
5263 if (coding->carryover_bytes > 0)
5265 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5266 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5267 bcopy (coding->carryover, SDATA (p->decoding_buf),
5268 coding->carryover_bytes);
5269 p->decoding_carryover = coding->carryover_bytes;
5271 /* Adjust the multibyteness of TEXT to that of the buffer. */
5272 if (NILP (current_buffer->enable_multibyte_characters)
5273 != ! STRING_MULTIBYTE (text))
5274 text = (STRING_MULTIBYTE (text)
5275 ? Fstring_as_unibyte (text)
5276 : Fstring_to_multibyte (text));
5277 /* Insert before markers in case we are inserting where
5278 the buffer's mark is, and the user's next command is Meta-y. */
5279 insert_from_string_before_markers (text, 0, 0,
5280 SCHARS (text), SBYTES (text), 0);
5282 /* Make sure the process marker's position is valid when the
5283 process buffer is changed in the signal_after_change above.
5284 W3 is known to do that. */
5285 if (BUFFERP (p->buffer)
5286 && (b = XBUFFER (p->buffer), b != current_buffer))
5287 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5288 else
5289 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5291 update_mode_lines++;
5293 /* Make sure opoint and the old restrictions
5294 float ahead of any new text just as point would. */
5295 if (opoint >= before)
5297 opoint += PT - before;
5298 opoint_byte += PT_BYTE - before_byte;
5300 if (old_begv > before)
5302 old_begv += PT - before;
5303 old_begv_byte += PT_BYTE - before_byte;
5305 if (old_zv >= before)
5307 old_zv += PT - before;
5308 old_zv_byte += PT_BYTE - before_byte;
5311 /* If the restriction isn't what it should be, set it. */
5312 if (old_begv != BEGV || old_zv != ZV)
5313 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5315 /* Handling the process output should not deactivate the mark. */
5316 Vdeactivate_mark = odeactivate;
5318 current_buffer->read_only = old_read_only;
5319 SET_PT_BOTH (opoint, opoint_byte);
5320 set_buffer_internal (old);
5322 #ifdef VMS
5323 start_vms_process_read (vs);
5324 #endif
5325 return nbytes;
5328 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5329 0, 0, 0,
5330 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5331 This is intended for use by asynchronous process output filters and sentinels. */)
5334 return (waiting_for_user_input_p ? Qt : Qnil);
5337 /* Sending data to subprocess */
5339 jmp_buf send_process_frame;
5340 Lisp_Object process_sent_to;
5342 SIGTYPE
5343 send_process_trap ()
5345 SIGNAL_THREAD_CHECK (SIGPIPE);
5346 #ifdef BSD4_1
5347 sigrelse (SIGPIPE);
5348 sigrelse (SIGALRM);
5349 #endif /* BSD4_1 */
5350 sigunblock (sigmask (SIGPIPE));
5351 longjmp (send_process_frame, 1);
5354 /* Send some data to process PROC.
5355 BUF is the beginning of the data; LEN is the number of characters.
5356 OBJECT is the Lisp object that the data comes from. If OBJECT is
5357 nil or t, it means that the data comes from C string.
5359 If OBJECT is not nil, the data is encoded by PROC's coding-system
5360 for encoding before it is sent.
5362 This function can evaluate Lisp code and can garbage collect. */
5364 static void
5365 send_process (proc, buf, len, object)
5366 volatile Lisp_Object proc;
5367 unsigned char *volatile buf;
5368 volatile int len;
5369 volatile Lisp_Object object;
5371 /* Use volatile to protect variables from being clobbered by longjmp. */
5372 struct Lisp_Process *p = XPROCESS (proc);
5373 int rv;
5374 struct coding_system *coding;
5375 struct gcpro gcpro1;
5376 SIGTYPE (*volatile old_sigpipe) ();
5378 GCPRO1 (object);
5380 #ifdef VMS
5381 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5382 #endif /* VMS */
5384 if (p->raw_status_new)
5385 update_status (p);
5386 if (! EQ (p->status, Qrun))
5387 error ("Process %s not running", SDATA (p->name));
5388 if (p->outfd < 0)
5389 error ("Output file descriptor of %s is closed", SDATA (p->name));
5391 coding = proc_encode_coding_system[p->outfd];
5392 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5394 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5395 || (BUFFERP (object)
5396 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5397 || EQ (object, Qt))
5399 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5400 /* The coding system for encoding was changed to raw-text
5401 because we sent a unibyte text previously. Now we are
5402 sending a multibyte text, thus we must encode it by the
5403 original coding system specified for the current process. */
5404 setup_coding_system (p->encode_coding_system, coding);
5405 coding->src_multibyte = 1;
5407 else
5409 /* For sending a unibyte text, character code conversion should
5410 not take place but EOL conversion should. So, setup raw-text
5411 or one of the subsidiary if we have not yet done it. */
5412 if (CODING_REQUIRE_ENCODING (coding))
5414 if (CODING_REQUIRE_FLUSHING (coding))
5416 /* But, before changing the coding, we must flush out data. */
5417 coding->mode |= CODING_MODE_LAST_BLOCK;
5418 send_process (proc, "", 0, Qt);
5419 coding->mode &= CODING_MODE_LAST_BLOCK;
5421 setup_coding_system (raw_text_coding_system
5422 (Vlast_coding_system_used),
5423 coding);
5424 coding->src_multibyte = 0;
5427 coding->dst_multibyte = 0;
5429 if (CODING_REQUIRE_ENCODING (coding))
5431 coding->dst_object = Qt;
5432 if (BUFFERP (object))
5434 int from_byte, from, to;
5435 int save_pt, save_pt_byte;
5436 struct buffer *cur = current_buffer;
5438 set_buffer_internal (XBUFFER (object));
5439 save_pt = PT, save_pt_byte = PT_BYTE;
5441 from_byte = PTR_BYTE_POS (buf);
5442 from = BYTE_TO_CHAR (from_byte);
5443 to = BYTE_TO_CHAR (from_byte + len);
5444 TEMP_SET_PT_BOTH (from, from_byte);
5445 encode_coding_object (coding, object, from, from_byte,
5446 to, from_byte + len, Qt);
5447 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5448 set_buffer_internal (cur);
5450 else if (STRINGP (object))
5452 encode_coding_string (coding, object, 1);
5454 else
5456 coding->dst_object = make_unibyte_string (buf, len);
5457 coding->produced = len;
5460 len = coding->produced;
5461 buf = SDATA (coding->dst_object);
5464 #ifdef VMS
5465 vs = get_vms_process_pointer (p->pid);
5466 if (vs == 0)
5467 error ("Could not find this process: %x", p->pid);
5468 else if (write_to_vms_process (vs, buf, len))
5470 #else /* not VMS */
5472 if (pty_max_bytes == 0)
5474 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5475 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5476 if (pty_max_bytes < 0)
5477 pty_max_bytes = 250;
5478 #else
5479 pty_max_bytes = 250;
5480 #endif
5481 /* Deduct one, to leave space for the eof. */
5482 pty_max_bytes--;
5485 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5486 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5487 when returning with longjmp despite being declared volatile. */
5488 if (!setjmp (send_process_frame))
5490 process_sent_to = proc;
5491 while (len > 0)
5493 int this = len;
5495 /* Decide how much data we can send in one batch.
5496 Long lines need to be split into multiple batches. */
5497 if (p->pty_flag)
5499 /* Starting this at zero is always correct when not the first
5500 iteration because the previous iteration ended by sending C-d.
5501 It may not be correct for the first iteration
5502 if a partial line was sent in a separate send_process call.
5503 If that proves worth handling, we need to save linepos
5504 in the process object. */
5505 int linepos = 0;
5506 unsigned char *ptr = (unsigned char *) buf;
5507 unsigned char *end = (unsigned char *) buf + len;
5509 /* Scan through this text for a line that is too long. */
5510 while (ptr != end && linepos < pty_max_bytes)
5512 if (*ptr == '\n')
5513 linepos = 0;
5514 else
5515 linepos++;
5516 ptr++;
5518 /* If we found one, break the line there
5519 and put in a C-d to force the buffer through. */
5520 this = ptr - buf;
5523 /* Send this batch, using one or more write calls. */
5524 while (this > 0)
5526 int outfd = p->outfd;
5527 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5528 #ifdef DATAGRAM_SOCKETS
5529 if (DATAGRAM_CHAN_P (outfd))
5531 rv = sendto (outfd, (char *) buf, this,
5532 0, datagram_address[outfd].sa,
5533 datagram_address[outfd].len);
5534 if (rv < 0 && errno == EMSGSIZE)
5536 signal (SIGPIPE, old_sigpipe);
5537 report_file_error ("sending datagram",
5538 Fcons (proc, Qnil));
5541 else
5542 #endif
5544 rv = emacs_write (outfd, (char *) buf, this);
5545 #ifdef ADAPTIVE_READ_BUFFERING
5546 if (p->read_output_delay > 0
5547 && p->adaptive_read_buffering == 1)
5549 p->read_output_delay = 0;
5550 process_output_delay_count--;
5551 p->read_output_skip = 0;
5553 #endif
5555 signal (SIGPIPE, old_sigpipe);
5557 if (rv < 0)
5559 if (0
5560 #ifdef EWOULDBLOCK
5561 || errno == EWOULDBLOCK
5562 #endif
5563 #ifdef EAGAIN
5564 || errno == EAGAIN
5565 #endif
5567 /* Buffer is full. Wait, accepting input;
5568 that may allow the program
5569 to finish doing output and read more. */
5571 int offset = 0;
5573 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5574 /* A gross hack to work around a bug in FreeBSD.
5575 In the following sequence, read(2) returns
5576 bogus data:
5578 write(2) 1022 bytes
5579 write(2) 954 bytes, get EAGAIN
5580 read(2) 1024 bytes in process_read_output
5581 read(2) 11 bytes in process_read_output
5583 That is, read(2) returns more bytes than have
5584 ever been written successfully. The 1033 bytes
5585 read are the 1022 bytes written successfully
5586 after processing (for example with CRs added if
5587 the terminal is set up that way which it is
5588 here). The same bytes will be seen again in a
5589 later read(2), without the CRs. */
5591 if (errno == EAGAIN)
5593 int flags = FWRITE;
5594 ioctl (p->outfd, TIOCFLUSH, &flags);
5596 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5598 /* Running filters might relocate buffers or strings.
5599 Arrange to relocate BUF. */
5600 if (BUFFERP (object))
5601 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5602 else if (STRINGP (object))
5603 offset = buf - SDATA (object);
5605 #ifdef EMACS_HAS_USECS
5606 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5607 #else
5608 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5609 #endif
5611 if (BUFFERP (object))
5612 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5613 else if (STRINGP (object))
5614 buf = offset + SDATA (object);
5616 rv = 0;
5618 else
5619 /* This is a real error. */
5620 report_file_error ("writing to process", Fcons (proc, Qnil));
5622 buf += rv;
5623 len -= rv;
5624 this -= rv;
5627 /* If we sent just part of the string, put in an EOF
5628 to force it through, before we send the rest. */
5629 if (len > 0)
5630 Fprocess_send_eof (proc);
5633 #endif /* not VMS */
5634 else
5636 signal (SIGPIPE, old_sigpipe);
5637 #ifndef VMS
5638 proc = process_sent_to;
5639 p = XPROCESS (proc);
5640 #endif
5641 p->raw_status_new = 0;
5642 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5643 p->tick = ++process_tick;
5644 deactivate_process (proc);
5645 #ifdef VMS
5646 error ("Error writing to process %s; closed it", SDATA (p->name));
5647 #else
5648 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5649 #endif
5652 UNGCPRO;
5655 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5656 3, 3, 0,
5657 doc: /* Send current contents of region as input to PROCESS.
5658 PROCESS may be a process, a buffer, the name of a process or buffer, or
5659 nil, indicating the current buffer's process.
5660 Called from program, takes three arguments, PROCESS, START and END.
5661 If the region is more than 500 characters long,
5662 it is sent in several bunches. This may happen even for shorter regions.
5663 Output from processes can arrive in between bunches. */)
5664 (process, start, end)
5665 Lisp_Object process, start, end;
5667 Lisp_Object proc;
5668 int start1, end1;
5670 proc = get_process (process);
5671 validate_region (&start, &end);
5673 if (XINT (start) < GPT && XINT (end) > GPT)
5674 move_gap (XINT (start));
5676 start1 = CHAR_TO_BYTE (XINT (start));
5677 end1 = CHAR_TO_BYTE (XINT (end));
5678 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5679 Fcurrent_buffer ());
5681 return Qnil;
5684 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5685 2, 2, 0,
5686 doc: /* Send PROCESS the contents of STRING as input.
5687 PROCESS may be a process, a buffer, the name of a process or buffer, or
5688 nil, indicating the current buffer's process.
5689 If STRING is more than 500 characters long,
5690 it is sent in several bunches. This may happen even for shorter strings.
5691 Output from processes can arrive in between bunches. */)
5692 (process, string)
5693 Lisp_Object process, string;
5695 Lisp_Object proc;
5696 CHECK_STRING (string);
5697 proc = get_process (process);
5698 send_process (proc, SDATA (string),
5699 SBYTES (string), string);
5700 return Qnil;
5703 /* Return the foreground process group for the tty/pty that
5704 the process P uses. */
5705 static int
5706 emacs_get_tty_pgrp (p)
5707 struct Lisp_Process *p;
5709 int gid = -1;
5711 #ifdef TIOCGPGRP
5712 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5714 int fd;
5715 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5716 master side. Try the slave side. */
5717 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5719 if (fd != -1)
5721 ioctl (fd, TIOCGPGRP, &gid);
5722 emacs_close (fd);
5725 #endif /* defined (TIOCGPGRP ) */
5727 return gid;
5730 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5731 Sprocess_running_child_p, 0, 1, 0,
5732 doc: /* Return t if PROCESS has given the terminal to a child.
5733 If the operating system does not make it possible to find out,
5734 return t unconditionally. */)
5735 (process)
5736 Lisp_Object process;
5738 /* Initialize in case ioctl doesn't exist or gives an error,
5739 in a way that will cause returning t. */
5740 int gid;
5741 Lisp_Object proc;
5742 struct Lisp_Process *p;
5744 proc = get_process (process);
5745 p = XPROCESS (proc);
5747 if (!EQ (p->childp, Qt))
5748 error ("Process %s is not a subprocess",
5749 SDATA (p->name));
5750 if (p->infd < 0)
5751 error ("Process %s is not active",
5752 SDATA (p->name));
5754 gid = emacs_get_tty_pgrp (p);
5756 if (gid == p->pid)
5757 return Qnil;
5758 return Qt;
5761 /* send a signal number SIGNO to PROCESS.
5762 If CURRENT_GROUP is t, that means send to the process group
5763 that currently owns the terminal being used to communicate with PROCESS.
5764 This is used for various commands in shell mode.
5765 If CURRENT_GROUP is lambda, that means send to the process group
5766 that currently owns the terminal, but only if it is NOT the shell itself.
5768 If NOMSG is zero, insert signal-announcements into process's buffers
5769 right away.
5771 If we can, we try to signal PROCESS by sending control characters
5772 down the pty. This allows us to signal inferiors who have changed
5773 their uid, for which killpg would return an EPERM error. */
5775 static void
5776 process_send_signal (process, signo, current_group, nomsg)
5777 Lisp_Object process;
5778 int signo;
5779 Lisp_Object current_group;
5780 int nomsg;
5782 Lisp_Object proc;
5783 register struct Lisp_Process *p;
5784 int gid;
5785 int no_pgrp = 0;
5787 proc = get_process (process);
5788 p = XPROCESS (proc);
5790 if (!EQ (p->childp, Qt))
5791 error ("Process %s is not a subprocess",
5792 SDATA (p->name));
5793 if (p->infd < 0)
5794 error ("Process %s is not active",
5795 SDATA (p->name));
5797 if (!p->pty_flag)
5798 current_group = Qnil;
5800 /* If we are using pgrps, get a pgrp number and make it negative. */
5801 if (NILP (current_group))
5802 /* Send the signal to the shell's process group. */
5803 gid = p->pid;
5804 else
5806 #ifdef SIGNALS_VIA_CHARACTERS
5807 /* If possible, send signals to the entire pgrp
5808 by sending an input character to it. */
5810 /* TERMIOS is the latest and bestest, and seems most likely to
5811 work. If the system has it, use it. */
5812 #ifdef HAVE_TERMIOS
5813 struct termios t;
5814 cc_t *sig_char = NULL;
5816 tcgetattr (p->infd, &t);
5818 switch (signo)
5820 case SIGINT:
5821 sig_char = &t.c_cc[VINTR];
5822 break;
5824 case SIGQUIT:
5825 sig_char = &t.c_cc[VQUIT];
5826 break;
5828 case SIGTSTP:
5829 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5830 sig_char = &t.c_cc[VSWTCH];
5831 #else
5832 sig_char = &t.c_cc[VSUSP];
5833 #endif
5834 break;
5837 if (sig_char && *sig_char != CDISABLE)
5839 send_process (proc, sig_char, 1, Qnil);
5840 return;
5842 /* If we can't send the signal with a character,
5843 fall through and send it another way. */
5844 #else /* ! HAVE_TERMIOS */
5846 /* On Berkeley descendants, the following IOCTL's retrieve the
5847 current control characters. */
5848 #if defined (TIOCGLTC) && defined (TIOCGETC)
5850 struct tchars c;
5851 struct ltchars lc;
5853 switch (signo)
5855 case SIGINT:
5856 ioctl (p->infd, TIOCGETC, &c);
5857 send_process (proc, &c.t_intrc, 1, Qnil);
5858 return;
5859 case SIGQUIT:
5860 ioctl (p->infd, TIOCGETC, &c);
5861 send_process (proc, &c.t_quitc, 1, Qnil);
5862 return;
5863 #ifdef SIGTSTP
5864 case SIGTSTP:
5865 ioctl (p->infd, TIOCGLTC, &lc);
5866 send_process (proc, &lc.t_suspc, 1, Qnil);
5867 return;
5868 #endif /* ! defined (SIGTSTP) */
5871 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5873 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5874 characters. */
5875 #ifdef TCGETA
5876 struct termio t;
5877 switch (signo)
5879 case SIGINT:
5880 ioctl (p->infd, TCGETA, &t);
5881 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5882 return;
5883 case SIGQUIT:
5884 ioctl (p->infd, TCGETA, &t);
5885 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5886 return;
5887 #ifdef SIGTSTP
5888 case SIGTSTP:
5889 ioctl (p->infd, TCGETA, &t);
5890 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5891 return;
5892 #endif /* ! defined (SIGTSTP) */
5894 #else /* ! defined (TCGETA) */
5895 Your configuration files are messed up.
5896 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5897 you'd better be using one of the alternatives above! */
5898 #endif /* ! defined (TCGETA) */
5899 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5900 /* In this case, the code above should alway return. */
5901 abort ();
5902 #endif /* ! defined HAVE_TERMIOS */
5904 /* The code above may fall through if it can't
5905 handle the signal. */
5906 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5908 #ifdef TIOCGPGRP
5909 /* Get the current pgrp using the tty itself, if we have that.
5910 Otherwise, use the pty to get the pgrp.
5911 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5912 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5913 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5914 His patch indicates that if TIOCGPGRP returns an error, then
5915 we should just assume that p->pid is also the process group id. */
5917 gid = emacs_get_tty_pgrp (p);
5919 if (gid == -1)
5920 /* If we can't get the information, assume
5921 the shell owns the tty. */
5922 gid = p->pid;
5924 /* It is not clear whether anything really can set GID to -1.
5925 Perhaps on some system one of those ioctls can or could do so.
5926 Or perhaps this is vestigial. */
5927 if (gid == -1)
5928 no_pgrp = 1;
5929 #else /* ! defined (TIOCGPGRP ) */
5930 /* Can't select pgrps on this system, so we know that
5931 the child itself heads the pgrp. */
5932 gid = p->pid;
5933 #endif /* ! defined (TIOCGPGRP ) */
5935 /* If current_group is lambda, and the shell owns the terminal,
5936 don't send any signal. */
5937 if (EQ (current_group, Qlambda) && gid == p->pid)
5938 return;
5941 switch (signo)
5943 #ifdef SIGCONT
5944 case SIGCONT:
5945 p->raw_status_new = 0;
5946 p->status = Qrun;
5947 p->tick = ++process_tick;
5948 if (!nomsg)
5949 status_notify (NULL);
5950 break;
5951 #endif /* ! defined (SIGCONT) */
5952 case SIGINT:
5953 #ifdef VMS
5954 send_process (proc, "\003", 1, Qnil); /* ^C */
5955 goto whoosh;
5956 #endif
5957 case SIGQUIT:
5958 #ifdef VMS
5959 send_process (proc, "\031", 1, Qnil); /* ^Y */
5960 goto whoosh;
5961 #endif
5962 case SIGKILL:
5963 #ifdef VMS
5964 sys$forcex (&(p->pid), 0, 1);
5965 whoosh:
5966 #endif
5967 flush_pending_output (p->infd);
5968 break;
5971 /* If we don't have process groups, send the signal to the immediate
5972 subprocess. That isn't really right, but it's better than any
5973 obvious alternative. */
5974 if (no_pgrp)
5976 kill (p->pid, signo);
5977 return;
5980 /* gid may be a pid, or minus a pgrp's number */
5981 #ifdef TIOCSIGSEND
5982 if (!NILP (current_group))
5984 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5985 EMACS_KILLPG (gid, signo);
5987 else
5989 gid = - p->pid;
5990 kill (gid, signo);
5992 #else /* ! defined (TIOCSIGSEND) */
5993 EMACS_KILLPG (gid, signo);
5994 #endif /* ! defined (TIOCSIGSEND) */
5997 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5998 doc: /* Interrupt process PROCESS.
5999 PROCESS may be a process, a buffer, or the name of a process or buffer.
6000 No arg or nil means current buffer's process.
6001 Second arg CURRENT-GROUP non-nil means send signal to
6002 the current process-group of the process's controlling terminal
6003 rather than to the process's own process group.
6004 If the process is a shell, this means interrupt current subjob
6005 rather than the shell.
6007 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6008 don't send the signal. */)
6009 (process, current_group)
6010 Lisp_Object process, current_group;
6012 process_send_signal (process, SIGINT, current_group, 0);
6013 return process;
6016 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6017 doc: /* Kill process PROCESS. May be process or name of one.
6018 See function `interrupt-process' for more details on usage. */)
6019 (process, current_group)
6020 Lisp_Object process, current_group;
6022 process_send_signal (process, SIGKILL, current_group, 0);
6023 return process;
6026 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6027 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6028 See function `interrupt-process' for more details on usage. */)
6029 (process, current_group)
6030 Lisp_Object process, current_group;
6032 process_send_signal (process, SIGQUIT, current_group, 0);
6033 return process;
6036 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6037 doc: /* Stop process PROCESS. May be process or name of one.
6038 See function `interrupt-process' for more details on usage.
6039 If PROCESS is a network process, inhibit handling of incoming traffic. */)
6040 (process, current_group)
6041 Lisp_Object process, current_group;
6043 #ifdef HAVE_SOCKETS
6044 if (PROCESSP (process) && NETCONN_P (process))
6046 struct Lisp_Process *p;
6048 p = XPROCESS (process);
6049 if (NILP (p->command)
6050 && p->infd >= 0)
6052 FD_CLR (p->infd, &input_wait_mask);
6053 FD_CLR (p->infd, &non_keyboard_wait_mask);
6055 p->command = Qt;
6056 return process;
6058 #endif
6059 #ifndef SIGTSTP
6060 error ("No SIGTSTP support");
6061 #else
6062 process_send_signal (process, SIGTSTP, current_group, 0);
6063 #endif
6064 return process;
6067 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6068 doc: /* Continue process PROCESS. May be process or name of one.
6069 See function `interrupt-process' for more details on usage.
6070 If PROCESS is a network process, resume handling of incoming traffic. */)
6071 (process, current_group)
6072 Lisp_Object process, current_group;
6074 #ifdef HAVE_SOCKETS
6075 if (PROCESSP (process) && NETCONN_P (process))
6077 struct Lisp_Process *p;
6079 p = XPROCESS (process);
6080 if (EQ (p->command, Qt)
6081 && p->infd >= 0
6082 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6084 FD_SET (p->infd, &input_wait_mask);
6085 FD_SET (p->infd, &non_keyboard_wait_mask);
6087 p->command = Qnil;
6088 return process;
6090 #endif
6091 #ifdef SIGCONT
6092 process_send_signal (process, SIGCONT, current_group, 0);
6093 #else
6094 error ("No SIGCONT support");
6095 #endif
6096 return process;
6099 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6100 2, 2, "sProcess (name or number): \nnSignal code: ",
6101 doc: /* Send PROCESS the signal with code SIGCODE.
6102 PROCESS may also be a number specifying the process id of the
6103 process to signal; in this case, the process need not be a child of
6104 this Emacs.
6105 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6106 (process, sigcode)
6107 Lisp_Object process, sigcode;
6109 pid_t pid;
6111 if (INTEGERP (process))
6113 pid = XINT (process);
6114 goto got_it;
6117 if (FLOATP (process))
6119 pid = (pid_t) XFLOAT_DATA (process);
6120 goto got_it;
6123 if (STRINGP (process))
6125 Lisp_Object tem;
6126 if (tem = Fget_process (process), NILP (tem))
6128 pid = XINT (Fstring_to_number (process, make_number (10)));
6129 if (pid > 0)
6130 goto got_it;
6132 process = tem;
6134 else
6135 process = get_process (process);
6137 if (NILP (process))
6138 return process;
6140 CHECK_PROCESS (process);
6141 pid = XPROCESS (process)->pid;
6142 if (pid <= 0)
6143 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6145 got_it:
6147 #define parse_signal(NAME, VALUE) \
6148 else if (!xstricmp (name, NAME)) \
6149 XSETINT (sigcode, VALUE)
6151 if (INTEGERP (sigcode))
6153 else
6155 unsigned char *name;
6157 CHECK_SYMBOL (sigcode);
6158 name = SDATA (SYMBOL_NAME (sigcode));
6160 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6161 name += 3;
6163 if (0)
6165 #ifdef SIGUSR1
6166 parse_signal ("usr1", SIGUSR1);
6167 #endif
6168 #ifdef SIGUSR2
6169 parse_signal ("usr2", SIGUSR2);
6170 #endif
6171 #ifdef SIGTERM
6172 parse_signal ("term", SIGTERM);
6173 #endif
6174 #ifdef SIGHUP
6175 parse_signal ("hup", SIGHUP);
6176 #endif
6177 #ifdef SIGINT
6178 parse_signal ("int", SIGINT);
6179 #endif
6180 #ifdef SIGQUIT
6181 parse_signal ("quit", SIGQUIT);
6182 #endif
6183 #ifdef SIGILL
6184 parse_signal ("ill", SIGILL);
6185 #endif
6186 #ifdef SIGABRT
6187 parse_signal ("abrt", SIGABRT);
6188 #endif
6189 #ifdef SIGEMT
6190 parse_signal ("emt", SIGEMT);
6191 #endif
6192 #ifdef SIGKILL
6193 parse_signal ("kill", SIGKILL);
6194 #endif
6195 #ifdef SIGFPE
6196 parse_signal ("fpe", SIGFPE);
6197 #endif
6198 #ifdef SIGBUS
6199 parse_signal ("bus", SIGBUS);
6200 #endif
6201 #ifdef SIGSEGV
6202 parse_signal ("segv", SIGSEGV);
6203 #endif
6204 #ifdef SIGSYS
6205 parse_signal ("sys", SIGSYS);
6206 #endif
6207 #ifdef SIGPIPE
6208 parse_signal ("pipe", SIGPIPE);
6209 #endif
6210 #ifdef SIGALRM
6211 parse_signal ("alrm", SIGALRM);
6212 #endif
6213 #ifdef SIGURG
6214 parse_signal ("urg", SIGURG);
6215 #endif
6216 #ifdef SIGSTOP
6217 parse_signal ("stop", SIGSTOP);
6218 #endif
6219 #ifdef SIGTSTP
6220 parse_signal ("tstp", SIGTSTP);
6221 #endif
6222 #ifdef SIGCONT
6223 parse_signal ("cont", SIGCONT);
6224 #endif
6225 #ifdef SIGCHLD
6226 parse_signal ("chld", SIGCHLD);
6227 #endif
6228 #ifdef SIGTTIN
6229 parse_signal ("ttin", SIGTTIN);
6230 #endif
6231 #ifdef SIGTTOU
6232 parse_signal ("ttou", SIGTTOU);
6233 #endif
6234 #ifdef SIGIO
6235 parse_signal ("io", SIGIO);
6236 #endif
6237 #ifdef SIGXCPU
6238 parse_signal ("xcpu", SIGXCPU);
6239 #endif
6240 #ifdef SIGXFSZ
6241 parse_signal ("xfsz", SIGXFSZ);
6242 #endif
6243 #ifdef SIGVTALRM
6244 parse_signal ("vtalrm", SIGVTALRM);
6245 #endif
6246 #ifdef SIGPROF
6247 parse_signal ("prof", SIGPROF);
6248 #endif
6249 #ifdef SIGWINCH
6250 parse_signal ("winch", SIGWINCH);
6251 #endif
6252 #ifdef SIGINFO
6253 parse_signal ("info", SIGINFO);
6254 #endif
6255 else
6256 error ("Undefined signal name %s", name);
6259 #undef parse_signal
6261 return make_number (kill (pid, XINT (sigcode)));
6264 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6265 doc: /* Make PROCESS see end-of-file in its input.
6266 EOF comes after any text already sent to it.
6267 PROCESS may be a process, a buffer, the name of a process or buffer, or
6268 nil, indicating the current buffer's process.
6269 If PROCESS is a network connection, or is a process communicating
6270 through a pipe (as opposed to a pty), then you cannot send any more
6271 text to PROCESS after you call this function. */)
6272 (process)
6273 Lisp_Object process;
6275 Lisp_Object proc;
6276 struct coding_system *coding;
6278 if (DATAGRAM_CONN_P (process))
6279 return process;
6281 proc = get_process (process);
6282 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6284 /* Make sure the process is really alive. */
6285 if (XPROCESS (proc)->raw_status_new)
6286 update_status (XPROCESS (proc));
6287 if (! EQ (XPROCESS (proc)->status, Qrun))
6288 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6290 if (CODING_REQUIRE_FLUSHING (coding))
6292 coding->mode |= CODING_MODE_LAST_BLOCK;
6293 send_process (proc, "", 0, Qnil);
6296 #ifdef VMS
6297 send_process (proc, "\032", 1, Qnil); /* ^z */
6298 #else
6299 if (XPROCESS (proc)->pty_flag)
6300 send_process (proc, "\004", 1, Qnil);
6301 else
6303 int old_outfd, new_outfd;
6305 #ifdef HAVE_SHUTDOWN
6306 /* If this is a network connection, or socketpair is used
6307 for communication with the subprocess, call shutdown to cause EOF.
6308 (In some old system, shutdown to socketpair doesn't work.
6309 Then we just can't win.) */
6310 if (XPROCESS (proc)->pid == 0
6311 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6312 shutdown (XPROCESS (proc)->outfd, 1);
6313 /* In case of socketpair, outfd == infd, so don't close it. */
6314 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6315 emacs_close (XPROCESS (proc)->outfd);
6316 #else /* not HAVE_SHUTDOWN */
6317 emacs_close (XPROCESS (proc)->outfd);
6318 #endif /* not HAVE_SHUTDOWN */
6319 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6320 if (new_outfd < 0)
6321 abort ();
6322 old_outfd = XPROCESS (proc)->outfd;
6324 if (!proc_encode_coding_system[new_outfd])
6325 proc_encode_coding_system[new_outfd]
6326 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6327 bcopy (proc_encode_coding_system[old_outfd],
6328 proc_encode_coding_system[new_outfd],
6329 sizeof (struct coding_system));
6330 bzero (proc_encode_coding_system[old_outfd],
6331 sizeof (struct coding_system));
6333 XPROCESS (proc)->outfd = new_outfd;
6335 #endif /* VMS */
6336 return process;
6339 /* Kill all processes associated with `buffer'.
6340 If `buffer' is nil, kill all processes */
6342 void
6343 kill_buffer_processes (buffer)
6344 Lisp_Object buffer;
6346 Lisp_Object tail, proc;
6348 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6350 proc = XCDR (XCAR (tail));
6351 if (PROCESSP (proc)
6352 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6354 if (NETCONN_P (proc))
6355 Fdelete_process (proc);
6356 else if (XPROCESS (proc)->infd >= 0)
6357 process_send_signal (proc, SIGHUP, Qnil, 1);
6362 /* On receipt of a signal that a child status has changed, loop asking
6363 about children with changed statuses until the system says there
6364 are no more.
6366 All we do is change the status; we do not run sentinels or print
6367 notifications. That is saved for the next time keyboard input is
6368 done, in order to avoid timing errors.
6370 ** WARNING: this can be called during garbage collection.
6371 Therefore, it must not be fooled by the presence of mark bits in
6372 Lisp objects.
6374 ** USG WARNING: Although it is not obvious from the documentation
6375 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6376 signal() before executing at least one wait(), otherwise the
6377 handler will be called again, resulting in an infinite loop. The
6378 relevant portion of the documentation reads "SIGCLD signals will be
6379 queued and the signal-catching function will be continually
6380 reentered until the queue is empty". Invoking signal() causes the
6381 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6382 Inc.
6384 ** Malloc WARNING: This should never call malloc either directly or
6385 indirectly; if it does, that is a bug */
6387 #ifdef SIGCHLD
6388 SIGTYPE
6389 sigchld_handler (signo)
6390 int signo;
6392 int old_errno = errno;
6393 Lisp_Object proc;
6394 register struct Lisp_Process *p;
6395 extern EMACS_TIME *input_available_clear_time;
6397 SIGNAL_THREAD_CHECK (signo);
6399 #ifdef BSD4_1
6400 extern int sigheld;
6401 sigheld |= sigbit (SIGCHLD);
6402 #endif
6404 while (1)
6406 pid_t pid;
6407 WAITTYPE w;
6408 Lisp_Object tail;
6410 #ifdef WNOHANG
6411 #ifndef WUNTRACED
6412 #define WUNTRACED 0
6413 #endif /* no WUNTRACED */
6414 /* Keep trying to get a status until we get a definitive result. */
6417 errno = 0;
6418 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6420 while (pid < 0 && errno == EINTR);
6422 if (pid <= 0)
6424 /* PID == 0 means no processes found, PID == -1 means a real
6425 failure. We have done all our job, so return. */
6427 /* USG systems forget handlers when they are used;
6428 must reestablish each time */
6429 #if defined (USG) && !defined (POSIX_SIGNALS)
6430 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6431 #endif
6432 #ifdef BSD4_1
6433 sigheld &= ~sigbit (SIGCHLD);
6434 sigrelse (SIGCHLD);
6435 #endif
6436 errno = old_errno;
6437 return;
6439 #else
6440 pid = wait (&w);
6441 #endif /* no WNOHANG */
6443 /* Find the process that signaled us, and record its status. */
6445 /* The process can have been deleted by Fdelete_process. */
6446 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6448 Lisp_Object xpid = XCAR (tail);
6449 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6450 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6452 XSETCAR (tail, Qnil);
6453 goto sigchld_end_of_loop;
6457 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6458 p = 0;
6459 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6461 proc = XCDR (XCAR (tail));
6462 p = XPROCESS (proc);
6463 if (EQ (p->childp, Qt) && p->pid == pid)
6464 break;
6465 p = 0;
6468 /* Look for an asynchronous process whose pid hasn't been filled
6469 in yet. */
6470 if (p == 0)
6471 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6473 proc = XCDR (XCAR (tail));
6474 p = XPROCESS (proc);
6475 if (p->pid == -1)
6476 break;
6477 p = 0;
6480 /* Change the status of the process that was found. */
6481 if (p != 0)
6483 union { int i; WAITTYPE wt; } u;
6484 int clear_desc_flag = 0;
6486 p->tick = ++process_tick;
6487 u.wt = w;
6488 p->raw_status = u.i;
6489 p->raw_status_new = 1;
6491 /* If process has terminated, stop waiting for its output. */
6492 if ((WIFSIGNALED (w) || WIFEXITED (w))
6493 && p->infd >= 0)
6494 clear_desc_flag = 1;
6496 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6497 if (clear_desc_flag)
6499 FD_CLR (p->infd, &input_wait_mask);
6500 FD_CLR (p->infd, &non_keyboard_wait_mask);
6503 /* Tell wait_reading_process_output that it needs to wake up and
6504 look around. */
6505 if (input_available_clear_time)
6506 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6509 /* There was no asynchronous process found for that pid: we have
6510 a synchronous process. */
6511 else
6513 synch_process_alive = 0;
6515 /* Report the status of the synchronous process. */
6516 if (WIFEXITED (w))
6517 synch_process_retcode = WRETCODE (w);
6518 else if (WIFSIGNALED (w))
6519 synch_process_termsig = WTERMSIG (w);
6521 /* Tell wait_reading_process_output that it needs to wake up and
6522 look around. */
6523 if (input_available_clear_time)
6524 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6527 sigchld_end_of_loop:
6530 /* On some systems, we must return right away.
6531 If any more processes want to signal us, we will
6532 get another signal.
6533 Otherwise (on systems that have WNOHANG), loop around
6534 to use up all the processes that have something to tell us. */
6535 #if (defined WINDOWSNT \
6536 || (defined USG && !defined GNU_LINUX \
6537 && !(defined HPUX && defined WNOHANG)))
6538 #if defined (USG) && ! defined (POSIX_SIGNALS)
6539 signal (signo, sigchld_handler);
6540 #endif
6541 errno = old_errno;
6542 return;
6543 #endif /* USG, but not HPUX with WNOHANG */
6546 #endif /* SIGCHLD */
6549 static Lisp_Object
6550 exec_sentinel_unwind (data)
6551 Lisp_Object data;
6553 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6554 return Qnil;
6557 static Lisp_Object
6558 exec_sentinel_error_handler (error)
6559 Lisp_Object error;
6561 cmd_error_internal (error, "error in process sentinel: ");
6562 Vinhibit_quit = Qt;
6563 update_echo_area ();
6564 Fsleep_for (make_number (2), Qnil);
6565 return Qt;
6568 static void
6569 exec_sentinel (proc, reason)
6570 Lisp_Object proc, reason;
6572 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6573 register struct Lisp_Process *p = XPROCESS (proc);
6574 int count = SPECPDL_INDEX ();
6575 int outer_running_asynch_code = running_asynch_code;
6576 int waiting = waiting_for_user_input_p;
6578 if (inhibit_sentinels)
6579 return;
6581 /* No need to gcpro these, because all we do with them later
6582 is test them for EQness, and none of them should be a string. */
6583 odeactivate = Vdeactivate_mark;
6584 XSETBUFFER (obuffer, current_buffer);
6585 okeymap = current_buffer->keymap;
6587 sentinel = p->sentinel;
6588 if (NILP (sentinel))
6589 return;
6591 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6592 assure that it gets restored no matter how the sentinel exits. */
6593 p->sentinel = Qnil;
6594 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6595 /* Inhibit quit so that random quits don't screw up a running filter. */
6596 specbind (Qinhibit_quit, Qt);
6597 specbind (Qlast_nonmenu_event, Qt);
6599 /* In case we get recursively called,
6600 and we already saved the match data nonrecursively,
6601 save the same match data in safely recursive fashion. */
6602 if (outer_running_asynch_code)
6604 Lisp_Object tem;
6605 tem = Fmatch_data (Qnil, Qnil, Qnil);
6606 restore_search_regs ();
6607 record_unwind_save_match_data ();
6608 Fset_match_data (tem, Qt);
6611 /* For speed, if a search happens within this code,
6612 save the match data in a special nonrecursive fashion. */
6613 running_asynch_code = 1;
6615 internal_condition_case_1 (read_process_output_call,
6616 Fcons (sentinel,
6617 Fcons (proc, Fcons (reason, Qnil))),
6618 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6619 exec_sentinel_error_handler);
6621 /* If we saved the match data nonrecursively, restore it now. */
6622 restore_search_regs ();
6623 running_asynch_code = outer_running_asynch_code;
6625 Vdeactivate_mark = odeactivate;
6627 /* Restore waiting_for_user_input_p as it was
6628 when we were called, in case the filter clobbered it. */
6629 waiting_for_user_input_p = waiting;
6631 #if 0
6632 if (! EQ (Fcurrent_buffer (), obuffer)
6633 || ! EQ (current_buffer->keymap, okeymap))
6634 #endif
6635 /* But do it only if the caller is actually going to read events.
6636 Otherwise there's no need to make him wake up, and it could
6637 cause trouble (for example it would make sit_for return). */
6638 if (waiting_for_user_input_p == -1)
6639 record_asynch_buffer_change ();
6641 unbind_to (count, Qnil);
6644 /* Report all recent events of a change in process status
6645 (either run the sentinel or output a message).
6646 This is usually done while Emacs is waiting for keyboard input
6647 but can be done at other times. */
6649 static void
6650 status_notify (deleting_process)
6651 struct Lisp_Process *deleting_process;
6653 register Lisp_Object proc, buffer;
6654 Lisp_Object tail, msg;
6655 struct gcpro gcpro1, gcpro2;
6657 tail = Qnil;
6658 msg = Qnil;
6659 /* We need to gcpro tail; if read_process_output calls a filter
6660 which deletes a process and removes the cons to which tail points
6661 from Vprocess_alist, and then causes a GC, tail is an unprotected
6662 reference. */
6663 GCPRO2 (tail, msg);
6665 /* Set this now, so that if new processes are created by sentinels
6666 that we run, we get called again to handle their status changes. */
6667 update_tick = process_tick;
6669 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6671 Lisp_Object symbol;
6672 register struct Lisp_Process *p;
6674 proc = Fcdr (XCAR (tail));
6675 p = XPROCESS (proc);
6677 if (p->tick != p->update_tick)
6679 p->update_tick = p->tick;
6681 /* If process is still active, read any output that remains. */
6682 while (! EQ (p->filter, Qt)
6683 && ! EQ (p->status, Qconnect)
6684 && ! EQ (p->status, Qlisten)
6685 && ! EQ (p->command, Qt) /* Network process not stopped. */
6686 && p->infd >= 0
6687 && p != deleting_process
6688 && read_process_output (proc, p->infd) > 0);
6690 buffer = p->buffer;
6692 /* Get the text to use for the message. */
6693 if (p->raw_status_new)
6694 update_status (p);
6695 msg = status_message (p);
6697 /* If process is terminated, deactivate it or delete it. */
6698 symbol = p->status;
6699 if (CONSP (p->status))
6700 symbol = XCAR (p->status);
6702 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6703 || EQ (symbol, Qclosed))
6705 if (delete_exited_processes)
6706 remove_process (proc);
6707 else
6708 deactivate_process (proc);
6711 /* The actions above may have further incremented p->tick.
6712 So set p->update_tick again
6713 so that an error in the sentinel will not cause
6714 this code to be run again. */
6715 p->update_tick = p->tick;
6716 /* Now output the message suitably. */
6717 if (!NILP (p->sentinel))
6718 exec_sentinel (proc, msg);
6719 /* Don't bother with a message in the buffer
6720 when a process becomes runnable. */
6721 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6723 Lisp_Object ro, tem;
6724 struct buffer *old = current_buffer;
6725 int opoint, opoint_byte;
6726 int before, before_byte;
6728 ro = XBUFFER (buffer)->read_only;
6730 /* Avoid error if buffer is deleted
6731 (probably that's why the process is dead, too) */
6732 if (NILP (XBUFFER (buffer)->name))
6733 continue;
6734 Fset_buffer (buffer);
6736 opoint = PT;
6737 opoint_byte = PT_BYTE;
6738 /* Insert new output into buffer
6739 at the current end-of-output marker,
6740 thus preserving logical ordering of input and output. */
6741 if (XMARKER (p->mark)->buffer)
6742 Fgoto_char (p->mark);
6743 else
6744 SET_PT_BOTH (ZV, ZV_BYTE);
6746 before = PT;
6747 before_byte = PT_BYTE;
6749 tem = current_buffer->read_only;
6750 current_buffer->read_only = Qnil;
6751 insert_string ("\nProcess ");
6752 Finsert (1, &p->name);
6753 insert_string (" ");
6754 Finsert (1, &msg);
6755 current_buffer->read_only = tem;
6756 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6758 if (opoint >= before)
6759 SET_PT_BOTH (opoint + (PT - before),
6760 opoint_byte + (PT_BYTE - before_byte));
6761 else
6762 SET_PT_BOTH (opoint, opoint_byte);
6764 set_buffer_internal (old);
6767 } /* end for */
6769 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6770 redisplay_preserve_echo_area (13);
6772 UNGCPRO;
6776 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6777 Sset_process_coding_system, 1, 3, 0,
6778 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6779 DECODING will be used to decode subprocess output and ENCODING to
6780 encode subprocess input. */)
6781 (process, decoding, encoding)
6782 register Lisp_Object process, decoding, encoding;
6784 register struct Lisp_Process *p;
6786 CHECK_PROCESS (process);
6787 p = XPROCESS (process);
6788 if (p->infd < 0)
6789 error ("Input file descriptor of %s closed", SDATA (p->name));
6790 if (p->outfd < 0)
6791 error ("Output file descriptor of %s closed", SDATA (p->name));
6792 Fcheck_coding_system (decoding);
6793 Fcheck_coding_system (encoding);
6794 encoding = coding_inherit_eol_type (encoding, Qnil);
6795 p->decode_coding_system = decoding;
6796 p->encode_coding_system = encoding;
6797 setup_process_coding_systems (process);
6799 return Qnil;
6802 DEFUN ("process-coding-system",
6803 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6804 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6805 (process)
6806 register Lisp_Object process;
6808 CHECK_PROCESS (process);
6809 return Fcons (XPROCESS (process)->decode_coding_system,
6810 XPROCESS (process)->encode_coding_system);
6813 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6814 Sset_process_filter_multibyte, 2, 2, 0,
6815 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6816 If FLAG is non-nil, the filter is given multibyte strings.
6817 If FLAG is nil, the filter is given unibyte strings. In this case,
6818 all character code conversion except for end-of-line conversion is
6819 suppressed. */)
6820 (process, flag)
6821 Lisp_Object process, flag;
6823 register struct Lisp_Process *p;
6825 CHECK_PROCESS (process);
6826 p = XPROCESS (process);
6827 if (NILP (flag))
6828 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6829 setup_process_coding_systems (process);
6831 return Qnil;
6834 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6835 Sprocess_filter_multibyte_p, 1, 1, 0,
6836 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6837 (process)
6838 Lisp_Object process;
6840 register struct Lisp_Process *p;
6841 struct coding_system *coding;
6843 CHECK_PROCESS (process);
6844 p = XPROCESS (process);
6845 coding = proc_decode_coding_system[p->infd];
6846 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6851 /* Add DESC to the set of keyboard input descriptors. */
6853 void
6854 add_keyboard_wait_descriptor (desc)
6855 int desc;
6857 FD_SET (desc, &input_wait_mask);
6858 FD_SET (desc, &non_process_wait_mask);
6859 if (desc > max_keyboard_desc)
6860 max_keyboard_desc = desc;
6863 static int add_gpm_wait_descriptor_called_flag;
6865 void
6866 add_gpm_wait_descriptor (desc)
6867 int desc;
6869 if (! add_gpm_wait_descriptor_called_flag)
6870 FD_CLR (0, &input_wait_mask);
6871 add_gpm_wait_descriptor_called_flag = 1;
6872 FD_SET (desc, &input_wait_mask);
6873 FD_SET (desc, &gpm_wait_mask);
6874 if (desc > max_gpm_desc)
6875 max_gpm_desc = desc;
6878 /* From now on, do not expect DESC to give keyboard input. */
6880 void
6881 delete_keyboard_wait_descriptor (desc)
6882 int desc;
6884 int fd;
6885 int lim = max_keyboard_desc;
6887 FD_CLR (desc, &input_wait_mask);
6888 FD_CLR (desc, &non_process_wait_mask);
6890 if (desc == max_keyboard_desc)
6891 for (fd = 0; fd < lim; fd++)
6892 if (FD_ISSET (fd, &input_wait_mask)
6893 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6894 && !FD_ISSET (fd, &gpm_wait_mask))
6895 max_keyboard_desc = fd;
6898 void
6899 delete_gpm_wait_descriptor (desc)
6900 int desc;
6902 int fd;
6903 int lim = max_gpm_desc;
6905 FD_CLR (desc, &input_wait_mask);
6906 FD_CLR (desc, &non_process_wait_mask);
6908 if (desc == max_gpm_desc)
6909 for (fd = 0; fd < lim; fd++)
6910 if (FD_ISSET (fd, &input_wait_mask)
6911 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6912 && !FD_ISSET (fd, &non_process_wait_mask))
6913 max_gpm_desc = fd;
6916 /* Return nonzero if *MASK has a bit set
6917 that corresponds to one of the keyboard input descriptors. */
6919 static int
6920 keyboard_bit_set (mask)
6921 SELECT_TYPE *mask;
6923 int fd;
6925 for (fd = 0; fd <= max_keyboard_desc; fd++)
6926 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6927 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6928 return 1;
6930 return 0;
6933 void
6934 init_process ()
6936 register int i;
6938 inhibit_sentinels = 0;
6940 #ifdef SIGCHLD
6941 #ifndef CANNOT_DUMP
6942 if (! noninteractive || initialized)
6943 #endif
6944 signal (SIGCHLD, sigchld_handler);
6945 #endif
6947 FD_ZERO (&input_wait_mask);
6948 FD_ZERO (&non_keyboard_wait_mask);
6949 FD_ZERO (&non_process_wait_mask);
6950 max_process_desc = 0;
6952 #ifdef NON_BLOCKING_CONNECT
6953 FD_ZERO (&connect_wait_mask);
6954 num_pending_connects = 0;
6955 #endif
6957 #ifdef ADAPTIVE_READ_BUFFERING
6958 process_output_delay_count = 0;
6959 process_output_skip = 0;
6960 #endif
6962 /* Don't do this, it caused infinite select loops. The display
6963 method should call add_keyboard_wait_descriptor on stdin if it
6964 needs that. */
6965 #if 0
6966 FD_SET (0, &input_wait_mask);
6967 #endif
6969 Vprocess_alist = Qnil;
6970 #ifdef SIGCHLD
6971 deleted_pid_list = Qnil;
6972 #endif
6973 for (i = 0; i < MAXDESC; i++)
6975 chan_process[i] = Qnil;
6976 proc_buffered_char[i] = -1;
6978 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
6979 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
6980 #ifdef DATAGRAM_SOCKETS
6981 bzero (datagram_address, sizeof datagram_address);
6982 #endif
6984 #ifdef HAVE_SOCKETS
6986 Lisp_Object subfeatures = Qnil;
6987 struct socket_options *sopt;
6989 #define ADD_SUBFEATURE(key, val) \
6990 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
6992 #ifdef NON_BLOCKING_CONNECT
6993 ADD_SUBFEATURE (QCnowait, Qt);
6994 #endif
6995 #ifdef DATAGRAM_SOCKETS
6996 ADD_SUBFEATURE (QCtype, Qdatagram);
6997 #endif
6998 #ifdef HAVE_LOCAL_SOCKETS
6999 ADD_SUBFEATURE (QCfamily, Qlocal);
7000 #endif
7001 ADD_SUBFEATURE (QCfamily, Qipv4);
7002 #ifdef AF_INET6
7003 ADD_SUBFEATURE (QCfamily, Qipv6);
7004 #endif
7005 #ifdef HAVE_GETSOCKNAME
7006 ADD_SUBFEATURE (QCservice, Qt);
7007 #endif
7008 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
7009 ADD_SUBFEATURE (QCserver, Qt);
7010 #endif
7012 for (sopt = socket_options; sopt->name; sopt++)
7013 subfeatures = Fcons (intern (sopt->name), subfeatures);
7015 Fprovide (intern ("make-network-process"), subfeatures);
7017 #endif /* HAVE_SOCKETS */
7019 #if defined (DARWIN) || defined (MAC_OSX)
7020 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7021 processes. As such, we only change the default value. */
7022 if (initialized)
7024 char *release = get_operating_system_release();
7025 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7026 && release[1] == '.')) {
7027 Vprocess_connection_type = Qnil;
7030 #endif
7033 void
7034 syms_of_process ()
7036 Qprocessp = intern ("processp");
7037 staticpro (&Qprocessp);
7038 Qrun = intern ("run");
7039 staticpro (&Qrun);
7040 Qstop = intern ("stop");
7041 staticpro (&Qstop);
7042 Qsignal = intern ("signal");
7043 staticpro (&Qsignal);
7045 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7046 here again.
7048 Qexit = intern ("exit");
7049 staticpro (&Qexit); */
7051 Qopen = intern ("open");
7052 staticpro (&Qopen);
7053 Qclosed = intern ("closed");
7054 staticpro (&Qclosed);
7055 Qconnect = intern ("connect");
7056 staticpro (&Qconnect);
7057 Qfailed = intern ("failed");
7058 staticpro (&Qfailed);
7059 Qlisten = intern ("listen");
7060 staticpro (&Qlisten);
7061 Qlocal = intern ("local");
7062 staticpro (&Qlocal);
7063 Qipv4 = intern ("ipv4");
7064 staticpro (&Qipv4);
7065 #ifdef AF_INET6
7066 Qipv6 = intern ("ipv6");
7067 staticpro (&Qipv6);
7068 #endif
7069 Qdatagram = intern ("datagram");
7070 staticpro (&Qdatagram);
7072 QCname = intern (":name");
7073 staticpro (&QCname);
7074 QCbuffer = intern (":buffer");
7075 staticpro (&QCbuffer);
7076 QChost = intern (":host");
7077 staticpro (&QChost);
7078 QCservice = intern (":service");
7079 staticpro (&QCservice);
7080 QCtype = intern (":type");
7081 staticpro (&QCtype);
7082 QClocal = intern (":local");
7083 staticpro (&QClocal);
7084 QCremote = intern (":remote");
7085 staticpro (&QCremote);
7086 QCcoding = intern (":coding");
7087 staticpro (&QCcoding);
7088 QCserver = intern (":server");
7089 staticpro (&QCserver);
7090 QCnowait = intern (":nowait");
7091 staticpro (&QCnowait);
7092 QCsentinel = intern (":sentinel");
7093 staticpro (&QCsentinel);
7094 QClog = intern (":log");
7095 staticpro (&QClog);
7096 QCnoquery = intern (":noquery");
7097 staticpro (&QCnoquery);
7098 QCstop = intern (":stop");
7099 staticpro (&QCstop);
7100 QCoptions = intern (":options");
7101 staticpro (&QCoptions);
7102 QCplist = intern (":plist");
7103 staticpro (&QCplist);
7105 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7106 staticpro (&Qlast_nonmenu_event);
7108 staticpro (&Vprocess_alist);
7109 #ifdef SIGCHLD
7110 staticpro (&deleted_pid_list);
7111 #endif
7113 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7114 doc: /* *Non-nil means delete processes immediately when they exit.
7115 A value of nil means don't delete them until `list-processes' is run. */);
7117 delete_exited_processes = 1;
7119 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7120 doc: /* Control type of device used to communicate with subprocesses.
7121 Values are nil to use a pipe, or t or `pty' to use a pty.
7122 The value has no effect if the system has no ptys or if all ptys are busy:
7123 then a pipe is used in any case.
7124 The value takes effect when `start-process' is called. */);
7125 Vprocess_connection_type = Qt;
7127 #ifdef ADAPTIVE_READ_BUFFERING
7128 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7129 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7130 On some systems, when Emacs reads the output from a subprocess, the output data
7131 is read in very small blocks, potentially resulting in very poor performance.
7132 This behavior can be remedied to some extent by setting this variable to a
7133 non-nil value, as it will automatically delay reading from such processes, to
7134 allow them to produce more output before Emacs tries to read it.
7135 If the value is t, the delay is reset after each write to the process; any other
7136 non-nil value means that the delay is not reset on write.
7137 The variable takes effect when `start-process' is called. */);
7138 Vprocess_adaptive_read_buffering = Qt;
7139 #endif
7141 defsubr (&Sprocessp);
7142 defsubr (&Sget_process);
7143 defsubr (&Sget_buffer_process);
7144 defsubr (&Sdelete_process);
7145 defsubr (&Sprocess_status);
7146 defsubr (&Sprocess_exit_status);
7147 defsubr (&Sprocess_id);
7148 defsubr (&Sprocess_name);
7149 defsubr (&Sprocess_tty_name);
7150 defsubr (&Sprocess_command);
7151 defsubr (&Sset_process_buffer);
7152 defsubr (&Sprocess_buffer);
7153 defsubr (&Sprocess_mark);
7154 defsubr (&Sset_process_filter);
7155 defsubr (&Sprocess_filter);
7156 defsubr (&Sset_process_sentinel);
7157 defsubr (&Sprocess_sentinel);
7158 defsubr (&Sset_process_window_size);
7159 defsubr (&Sset_process_inherit_coding_system_flag);
7160 defsubr (&Sprocess_inherit_coding_system_flag);
7161 defsubr (&Sset_process_query_on_exit_flag);
7162 defsubr (&Sprocess_query_on_exit_flag);
7163 defsubr (&Sprocess_contact);
7164 defsubr (&Sprocess_plist);
7165 defsubr (&Sset_process_plist);
7166 defsubr (&Slist_processes);
7167 defsubr (&Sprocess_list);
7168 defsubr (&Sstart_process);
7169 #ifdef HAVE_SOCKETS
7170 defsubr (&Sset_network_process_option);
7171 defsubr (&Smake_network_process);
7172 defsubr (&Sformat_network_address);
7173 #endif /* HAVE_SOCKETS */
7174 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7175 #ifdef SIOCGIFCONF
7176 defsubr (&Snetwork_interface_list);
7177 #endif
7178 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7179 defsubr (&Snetwork_interface_info);
7180 #endif
7181 #endif /* HAVE_SOCKETS ... */
7182 #ifdef DATAGRAM_SOCKETS
7183 defsubr (&Sprocess_datagram_address);
7184 defsubr (&Sset_process_datagram_address);
7185 #endif
7186 defsubr (&Saccept_process_output);
7187 defsubr (&Sprocess_send_region);
7188 defsubr (&Sprocess_send_string);
7189 defsubr (&Sinterrupt_process);
7190 defsubr (&Skill_process);
7191 defsubr (&Squit_process);
7192 defsubr (&Sstop_process);
7193 defsubr (&Scontinue_process);
7194 defsubr (&Sprocess_running_child_p);
7195 defsubr (&Sprocess_send_eof);
7196 defsubr (&Ssignal_process);
7197 defsubr (&Swaiting_for_user_input_p);
7198 /* defsubr (&Sprocess_connection); */
7199 defsubr (&Sset_process_coding_system);
7200 defsubr (&Sprocess_coding_system);
7201 defsubr (&Sset_process_filter_multibyte);
7202 defsubr (&Sprocess_filter_multibyte_p);
7206 #else /* not subprocesses */
7208 #include <sys/types.h>
7209 #include <errno.h>
7211 #include "lisp.h"
7212 #include "systime.h"
7213 #include "character.h"
7214 #include "coding.h"
7215 #include "termopts.h"
7216 #include "sysselect.h"
7218 extern int frame_garbaged;
7220 extern EMACS_TIME timer_check ();
7221 extern int timers_run;
7223 Lisp_Object QCtype;
7225 /* As described above, except assuming that there are no subprocesses:
7227 Wait for timeout to elapse and/or keyboard input to be available.
7229 time_limit is:
7230 timeout in seconds, or
7231 zero for no limit, or
7232 -1 means gobble data immediately available but don't wait for any.
7234 read_kbd is a Lisp_Object:
7235 0 to ignore keyboard input, or
7236 1 to return when input is available, or
7237 -1 means caller will actually read the input, so don't throw to
7238 the quit handler.
7240 see full version for other parameters. We know that wait_proc will
7241 always be NULL, since `subprocesses' isn't defined.
7243 do_display != 0 means redisplay should be done to show subprocess
7244 output that arrives.
7246 Return true if we received input from any process. */
7249 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7250 wait_for_cell, wait_proc, just_wait_proc)
7251 int time_limit, microsecs, read_kbd, do_display;
7252 Lisp_Object wait_for_cell;
7253 struct Lisp_Process *wait_proc;
7254 int just_wait_proc;
7256 register int nfds;
7257 EMACS_TIME end_time, timeout;
7258 SELECT_TYPE waitchannels;
7259 int xerrno;
7261 /* What does time_limit really mean? */
7262 if (time_limit || microsecs)
7264 EMACS_GET_TIME (end_time);
7265 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7266 EMACS_ADD_TIME (end_time, end_time, timeout);
7269 /* Turn off periodic alarms (in case they are in use)
7270 and then turn off any other atimers,
7271 because the select emulator uses alarms. */
7272 stop_polling ();
7273 turn_on_atimers (0);
7275 while (1)
7277 int timeout_reduced_for_timers = 0;
7279 /* If calling from keyboard input, do not quit
7280 since we want to return C-g as an input character.
7281 Otherwise, do pending quit if requested. */
7282 if (read_kbd >= 0)
7283 QUIT;
7285 /* Exit now if the cell we're waiting for became non-nil. */
7286 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7287 break;
7289 /* Compute time from now till when time limit is up */
7290 /* Exit if already run out */
7291 if (time_limit == -1)
7293 /* -1 specified for timeout means
7294 gobble output available now
7295 but don't wait at all. */
7297 EMACS_SET_SECS_USECS (timeout, 0, 0);
7299 else if (time_limit || microsecs)
7301 EMACS_GET_TIME (timeout);
7302 EMACS_SUB_TIME (timeout, end_time, timeout);
7303 if (EMACS_TIME_NEG_P (timeout))
7304 break;
7306 else
7308 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7311 /* If our caller will not immediately handle keyboard events,
7312 run timer events directly.
7313 (Callers that will immediately read keyboard events
7314 call timer_delay on their own.) */
7315 if (NILP (wait_for_cell))
7317 EMACS_TIME timer_delay;
7321 int old_timers_run = timers_run;
7322 timer_delay = timer_check (1);
7323 if (timers_run != old_timers_run && do_display)
7324 /* We must retry, since a timer may have requeued itself
7325 and that could alter the time delay. */
7326 redisplay_preserve_echo_area (14);
7327 else
7328 break;
7330 while (!detect_input_pending ());
7332 /* If there is unread keyboard input, also return. */
7333 if (read_kbd != 0
7334 && requeued_events_pending_p ())
7335 break;
7337 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7339 EMACS_TIME difference;
7340 EMACS_SUB_TIME (difference, timer_delay, timeout);
7341 if (EMACS_TIME_NEG_P (difference))
7343 timeout = timer_delay;
7344 timeout_reduced_for_timers = 1;
7349 /* Cause C-g and alarm signals to take immediate action,
7350 and cause input available signals to zero out timeout. */
7351 if (read_kbd < 0)
7352 set_waiting_for_input (&timeout);
7354 /* Wait till there is something to do. */
7356 if (! read_kbd && NILP (wait_for_cell))
7357 FD_ZERO (&waitchannels);
7358 else
7359 FD_SET (0, &waitchannels);
7361 /* If a frame has been newly mapped and needs updating,
7362 reprocess its display stuff. */
7363 if (frame_garbaged && do_display)
7365 clear_waiting_for_input ();
7366 redisplay_preserve_echo_area (15);
7367 if (read_kbd < 0)
7368 set_waiting_for_input (&timeout);
7371 if (read_kbd && detect_input_pending ())
7373 nfds = 0;
7374 FD_ZERO (&waitchannels);
7376 else
7377 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7378 &timeout);
7380 xerrno = errno;
7382 /* Make C-g and alarm signals set flags again */
7383 clear_waiting_for_input ();
7385 /* If we woke up due to SIGWINCH, actually change size now. */
7386 do_pending_window_change (0);
7388 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7389 /* We waited the full specified time, so return now. */
7390 break;
7392 if (nfds == -1)
7394 /* If the system call was interrupted, then go around the
7395 loop again. */
7396 if (xerrno == EINTR)
7397 FD_ZERO (&waitchannels);
7398 else
7399 error ("select error: %s", emacs_strerror (xerrno));
7401 #ifdef sun
7402 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7403 /* System sometimes fails to deliver SIGIO. */
7404 kill (getpid (), SIGIO);
7405 #endif
7406 #ifdef SIGIO
7407 if (read_kbd && interrupt_input && (waitchannels & 1))
7408 kill (getpid (), SIGIO);
7409 #endif
7411 /* Check for keyboard input */
7413 if (read_kbd
7414 && detect_input_pending_run_timers (do_display))
7416 swallow_events (do_display);
7417 if (detect_input_pending_run_timers (do_display))
7418 break;
7421 /* If there is unread keyboard input, also return. */
7422 if (read_kbd
7423 && requeued_events_pending_p ())
7424 break;
7426 /* If wait_for_cell. check for keyboard input
7427 but don't run any timers.
7428 ??? (It seems wrong to me to check for keyboard
7429 input at all when wait_for_cell, but the code
7430 has been this way since July 1994.
7431 Try changing this after version 19.31.) */
7432 if (! NILP (wait_for_cell)
7433 && detect_input_pending ())
7435 swallow_events (do_display);
7436 if (detect_input_pending ())
7437 break;
7440 /* Exit now if the cell we're waiting for became non-nil. */
7441 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7442 break;
7445 start_polling ();
7447 return 0;
7451 /* Don't confuse make-docfile by having two doc strings for this function.
7452 make-docfile does not pay attention to #if, for good reason! */
7453 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7455 (name)
7456 register Lisp_Object name;
7458 return Qnil;
7461 /* Don't confuse make-docfile by having two doc strings for this function.
7462 make-docfile does not pay attention to #if, for good reason! */
7463 DEFUN ("process-inherit-coding-system-flag",
7464 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7465 1, 1, 0,
7467 (process)
7468 register Lisp_Object process;
7470 /* Ignore the argument and return the value of
7471 inherit-process-coding-system. */
7472 return inherit_process_coding_system ? Qt : Qnil;
7475 /* Kill all processes associated with `buffer'.
7476 If `buffer' is nil, kill all processes.
7477 Since we have no subprocesses, this does nothing. */
7479 void
7480 kill_buffer_processes (buffer)
7481 Lisp_Object buffer;
7485 void
7486 init_process ()
7490 void
7491 syms_of_process ()
7493 QCtype = intern (":type");
7494 staticpro (&QCtype);
7496 defsubr (&Sget_buffer_process);
7497 defsubr (&Sprocess_inherit_coding_system_flag);
7501 #endif /* not subprocesses */
7503 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7504 (do not change this comment) */