(Documentation): Add xref to Documentation Tips.
[emacs.git] / src / process.c
blobecc810cc621772eb4ceafa376a760e219439c170
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 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 2, 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>
60 #ifdef NEED_NET_ERRNO_H
61 #include <net/errno.h>
62 #endif /* NEED_NET_ERRNO_H */
64 /* Are local (unix) sockets supported? */
65 #if defined (HAVE_SYS_UN_H) && !defined (NO_SOCKETS_IN_FILE_SYSTEM)
66 #if !defined (AF_LOCAL) && defined (AF_UNIX)
67 #define AF_LOCAL AF_UNIX
68 #endif
69 #ifdef AF_LOCAL
70 #define HAVE_LOCAL_SOCKETS
71 #include <sys/un.h>
72 #endif
73 #endif
74 #endif /* HAVE_SOCKETS */
76 /* TERM is a poor-man's SLIP, used on GNU/Linux. */
77 #ifdef TERM
78 #include <client.h>
79 #endif
81 /* On some systems, e.g. DGUX, inet_addr returns a 'struct in_addr'. */
82 #ifdef HAVE_BROKEN_INET_ADDR
83 #define IN_ADDR struct in_addr
84 #define NUMERIC_ADDR_ERROR (numeric_addr.s_addr == -1)
85 #else
86 #define IN_ADDR unsigned long
87 #define NUMERIC_ADDR_ERROR (numeric_addr == -1)
88 #endif
90 #if defined(BSD_SYSTEM) || defined(STRIDE)
91 #include <sys/ioctl.h>
92 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
93 #include <fcntl.h>
94 #endif /* HAVE_PTYS and no O_NDELAY */
95 #endif /* BSD_SYSTEM || STRIDE */
97 #ifdef BROKEN_O_NONBLOCK
98 #undef O_NONBLOCK
99 #endif /* BROKEN_O_NONBLOCK */
101 #ifdef NEED_BSDTTY
102 #include <bsdtty.h>
103 #endif
105 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
106 #ifdef HAVE_SOCKETS
107 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
108 /* sys/ioctl.h may have been included already */
109 #ifndef SIOCGIFADDR
110 #include <sys/ioctl.h>
111 #endif
112 #include <net/if.h>
113 #endif
114 #endif
116 #ifdef IRIS
117 #include <sys/sysmacros.h> /* for "minor" */
118 #endif /* not IRIS */
120 #ifdef HAVE_SYS_WAIT
121 #include <sys/wait.h>
122 #endif
124 /* Disable IPv6 support for w32 until someone figures out how to do it
125 properly. */
126 #ifdef WINDOWSNT
127 # ifdef AF_INET6
128 # undef AF_INET6
129 # endif
130 #endif
132 #include "lisp.h"
133 #include "systime.h"
134 #include "systty.h"
136 #include "window.h"
137 #include "buffer.h"
138 #include "charset.h"
139 #include "coding.h"
140 #include "process.h"
141 #include "termhooks.h"
142 #include "termopts.h"
143 #include "commands.h"
144 #include "keyboard.h"
145 #include "frame.h"
146 #include "blockinput.h"
147 #include "dispextern.h"
148 #include "composite.h"
149 #include "atimer.h"
151 Lisp_Object Qprocessp;
152 Lisp_Object Qrun, Qstop, Qsignal;
153 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
154 Lisp_Object Qlocal, Qipv4, Qdatagram;
155 #ifdef AF_INET6
156 Lisp_Object Qipv6;
157 #endif
158 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
159 Lisp_Object QClocal, QCremote, QCcoding;
160 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
161 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
162 Lisp_Object QCfilter_multibyte;
163 Lisp_Object Qlast_nonmenu_event;
164 /* QCfamily is declared and initialized in xfaces.c,
165 QCfilter in keyboard.c. */
166 extern Lisp_Object QCfamily, QCfilter;
168 /* Qexit is declared and initialized in eval.c. */
170 /* QCfamily is defined in xfaces.c. */
171 extern Lisp_Object QCfamily;
172 /* QCfilter is defined in keyboard.c. */
173 extern Lisp_Object QCfilter;
175 /* a process object is a network connection when its childp field is neither
176 Qt nor Qnil but is instead a property list (KEY VAL ...). */
178 #ifdef HAVE_SOCKETS
179 #define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
180 #define NETCONN1_P(p) (GC_CONSP ((p)->childp))
181 #else
182 #define NETCONN_P(p) 0
183 #define NETCONN1_P(p) 0
184 #endif /* HAVE_SOCKETS */
186 /* Define first descriptor number available for subprocesses. */
187 #ifdef VMS
188 #define FIRST_PROC_DESC 1
189 #else /* Not VMS */
190 #define FIRST_PROC_DESC 3
191 #endif
193 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
194 testing SIGCHLD. */
196 #if !defined (SIGCHLD) && defined (SIGCLD)
197 #define SIGCHLD SIGCLD
198 #endif /* SIGCLD */
200 #include "syssignal.h"
202 #include "syswait.h"
204 extern char *get_operating_system_release ();
206 #ifndef USE_CRT_DLL
207 extern int errno;
208 #endif
209 #ifdef VMS
210 extern char *sys_errlist[];
211 #endif
213 #ifndef HAVE_H_ERRNO
214 extern int h_errno;
215 #endif
217 /* t means use pty, nil means use a pipe,
218 maybe other values to come. */
219 static Lisp_Object Vprocess_connection_type;
221 #ifdef SKTPAIR
222 #ifndef HAVE_SOCKETS
223 #include <sys/socket.h>
224 #endif
225 #endif /* SKTPAIR */
227 /* These next two vars are non-static since sysdep.c uses them in the
228 emulation of `select'. */
229 /* Number of events of change of status of a process. */
230 int process_tick;
231 /* Number of events for which the user or sentinel has been notified. */
232 int update_tick;
234 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
236 #ifdef BROKEN_NON_BLOCKING_CONNECT
237 #undef NON_BLOCKING_CONNECT
238 #else
239 #ifndef NON_BLOCKING_CONNECT
240 #ifdef HAVE_SOCKETS
241 #ifdef HAVE_SELECT
242 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
243 #if defined (O_NONBLOCK) || defined (O_NDELAY)
244 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
245 #define NON_BLOCKING_CONNECT
246 #endif /* EWOULDBLOCK || EINPROGRESS */
247 #endif /* O_NONBLOCK || O_NDELAY */
248 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
249 #endif /* HAVE_SELECT */
250 #endif /* HAVE_SOCKETS */
251 #endif /* NON_BLOCKING_CONNECT */
252 #endif /* BROKEN_NON_BLOCKING_CONNECT */
254 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
255 this system. We need to read full packets, so we need a
256 "non-destructive" select. So we require either native select,
257 or emulation of select using FIONREAD. */
259 #ifdef BROKEN_DATAGRAM_SOCKETS
260 #undef DATAGRAM_SOCKETS
261 #else
262 #ifndef DATAGRAM_SOCKETS
263 #ifdef HAVE_SOCKETS
264 #if defined (HAVE_SELECT) || defined (FIONREAD)
265 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
266 #define DATAGRAM_SOCKETS
267 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
268 #endif /* HAVE_SELECT || FIONREAD */
269 #endif /* HAVE_SOCKETS */
270 #endif /* DATAGRAM_SOCKETS */
271 #endif /* BROKEN_DATAGRAM_SOCKETS */
273 #ifdef TERM
274 #undef NON_BLOCKING_CONNECT
275 #undef DATAGRAM_SOCKETS
276 #endif
278 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
279 #ifdef EMACS_HAS_USECS
280 #define ADAPTIVE_READ_BUFFERING
281 #endif
282 #endif
284 #ifdef ADAPTIVE_READ_BUFFERING
285 #define READ_OUTPUT_DELAY_INCREMENT 10000
286 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
287 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
289 /* Number of processes which have a non-zero read_output_delay,
290 and therefore might be delayed for adaptive read buffering. */
292 static int process_output_delay_count;
294 /* Non-zero if any process has non-nil read_output_skip. */
296 static int process_output_skip;
298 /* Non-nil means to delay reading process output to improve buffering.
299 A value of t means that delay is reset after each send, any other
300 non-nil value does not reset the delay. A value of nil disables
301 adaptive read buffering completely. */
302 static Lisp_Object Vprocess_adaptive_read_buffering;
303 #else
304 #define process_output_delay_count 0
305 #endif
308 #include "sysselect.h"
310 static int keyboard_bit_set P_ ((SELECT_TYPE *));
311 static void deactivate_process P_ ((Lisp_Object));
312 static void status_notify P_ ((struct Lisp_Process *));
313 static int read_process_output P_ ((Lisp_Object, int));
315 /* If we support a window system, turn on the code to poll periodically
316 to detect C-g. It isn't actually used when doing interrupt input. */
317 #ifdef HAVE_WINDOW_SYSTEM
318 #define POLL_FOR_INPUT
319 #endif
321 static Lisp_Object get_process ();
322 static void exec_sentinel ();
324 extern EMACS_TIME timer_check ();
325 extern int timers_run;
327 /* Mask of bits indicating the descriptors that we wait for input on. */
329 static SELECT_TYPE input_wait_mask;
331 /* Mask that excludes keyboard input descriptor (s). */
333 static SELECT_TYPE non_keyboard_wait_mask;
335 /* Mask that excludes process input descriptor (s). */
337 static SELECT_TYPE non_process_wait_mask;
339 #ifdef NON_BLOCKING_CONNECT
340 /* Mask of bits indicating the descriptors that we wait for connect to
341 complete on. Once they complete, they are removed from this mask
342 and added to the input_wait_mask and non_keyboard_wait_mask. */
344 static SELECT_TYPE connect_wait_mask;
346 /* Number of bits set in connect_wait_mask. */
347 static int num_pending_connects;
349 #define IF_NON_BLOCKING_CONNECT(s) s
350 #else
351 #define IF_NON_BLOCKING_CONNECT(s)
352 #endif
354 /* The largest descriptor currently in use for a process object. */
355 static int max_process_desc;
357 /* The largest descriptor currently in use for keyboard input. */
358 static int max_keyboard_desc;
360 /* Nonzero means delete a process right away if it exits. */
361 static int delete_exited_processes;
363 /* Indexed by descriptor, gives the process (if any) for that descriptor */
364 Lisp_Object chan_process[MAXDESC];
366 /* Alist of elements (NAME . PROCESS) */
367 Lisp_Object Vprocess_alist;
369 /* Buffered-ahead input char from process, indexed by channel.
370 -1 means empty (no char is buffered).
371 Used on sys V where the only way to tell if there is any
372 output from the process is to read at least one char.
373 Always -1 on systems that support FIONREAD. */
375 /* Don't make static; need to access externally. */
376 int proc_buffered_char[MAXDESC];
378 /* Table of `struct coding-system' for each process. */
379 static struct coding_system *proc_decode_coding_system[MAXDESC];
380 static struct coding_system *proc_encode_coding_system[MAXDESC];
382 #ifdef DATAGRAM_SOCKETS
383 /* Table of `partner address' for datagram sockets. */
384 struct sockaddr_and_len {
385 struct sockaddr *sa;
386 int len;
387 } datagram_address[MAXDESC];
388 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
389 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XINT (XPROCESS (proc)->infd)].sa != 0)
390 #else
391 #define DATAGRAM_CHAN_P(chan) (0)
392 #define DATAGRAM_CONN_P(proc) (0)
393 #endif
395 /* Maximum number of bytes to send to a pty without an eof. */
396 static int pty_max_bytes;
398 /* Nonzero means don't run process sentinels. This is used
399 when exiting. */
400 int inhibit_sentinels;
402 #ifdef HAVE_PTYS
403 #ifdef HAVE_PTY_H
404 #include <pty.h>
405 #endif
406 /* The file name of the pty opened by allocate_pty. */
408 static char pty_name[24];
409 #endif
411 /* Compute the Lisp form of the process status, p->status, from
412 the numeric status that was returned by `wait'. */
414 static Lisp_Object status_convert ();
416 static void
417 update_status (p)
418 struct Lisp_Process *p;
420 union { int i; WAITTYPE wt; } u;
421 eassert (p->raw_status_new);
422 u.i = p->raw_status;
423 p->status = status_convert (u.wt);
424 p->raw_status_new = 0;
427 /* Convert a process status word in Unix format to
428 the list that we use internally. */
430 static Lisp_Object
431 status_convert (w)
432 WAITTYPE w;
434 if (WIFSTOPPED (w))
435 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
436 else if (WIFEXITED (w))
437 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
438 WCOREDUMP (w) ? Qt : Qnil));
439 else if (WIFSIGNALED (w))
440 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
441 WCOREDUMP (w) ? Qt : Qnil));
442 else
443 return Qrun;
446 /* Given a status-list, extract the three pieces of information
447 and store them individually through the three pointers. */
449 static void
450 decode_status (l, symbol, code, coredump)
451 Lisp_Object l;
452 Lisp_Object *symbol;
453 int *code;
454 int *coredump;
456 Lisp_Object tem;
458 if (SYMBOLP (l))
460 *symbol = l;
461 *code = 0;
462 *coredump = 0;
464 else
466 *symbol = XCAR (l);
467 tem = XCDR (l);
468 *code = XFASTINT (XCAR (tem));
469 tem = XCDR (tem);
470 *coredump = !NILP (tem);
474 /* Return a string describing a process status list. */
476 static Lisp_Object
477 status_message (p)
478 struct Lisp_Process *p;
480 Lisp_Object status = p->status;
481 Lisp_Object symbol;
482 int code, coredump;
483 Lisp_Object string, string2;
485 decode_status (status, &symbol, &code, &coredump);
487 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
489 char *signame;
490 synchronize_system_messages_locale ();
491 signame = strsignal (code);
492 if (signame == 0)
493 signame = "unknown";
494 string = build_string (signame);
495 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
496 SSET (string, 0, DOWNCASE (SREF (string, 0)));
497 return concat2 (string, string2);
499 else if (EQ (symbol, Qexit))
501 if (NETCONN1_P (p))
502 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
503 if (code == 0)
504 return build_string ("finished\n");
505 string = Fnumber_to_string (make_number (code));
506 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
507 return concat3 (build_string ("exited abnormally with code "),
508 string, string2);
510 else if (EQ (symbol, Qfailed))
512 string = Fnumber_to_string (make_number (code));
513 string2 = build_string ("\n");
514 return concat3 (build_string ("failed with code "),
515 string, string2);
517 else
518 return Fcopy_sequence (Fsymbol_name (symbol));
521 #ifdef HAVE_PTYS
523 /* Open an available pty, returning a file descriptor.
524 Return -1 on failure.
525 The file name of the terminal corresponding to the pty
526 is left in the variable pty_name. */
528 static int
529 allocate_pty ()
531 register int c, i;
532 int fd;
534 #ifdef PTY_ITERATION
535 PTY_ITERATION
536 #else
537 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
538 for (i = 0; i < 16; i++)
539 #endif
541 struct stat stb; /* Used in some PTY_OPEN. */
542 #ifdef PTY_NAME_SPRINTF
543 PTY_NAME_SPRINTF
544 #else
545 sprintf (pty_name, "/dev/pty%c%x", c, i);
546 #endif /* no PTY_NAME_SPRINTF */
548 #ifdef PTY_OPEN
549 PTY_OPEN;
550 #else /* no PTY_OPEN */
552 # ifdef IRIS
553 /* Unusual IRIS code */
554 *ptyv = emacs_open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
555 if (fd < 0)
556 return -1;
557 if (fstat (fd, &stb) < 0)
558 return -1;
559 # else /* not IRIS */
560 { /* Some systems name their pseudoterminals so that there are gaps in
561 the usual sequence - for example, on HP9000/S700 systems, there
562 are no pseudoterminals with names ending in 'f'. So we wait for
563 three failures in a row before deciding that we've reached the
564 end of the ptys. */
565 int failed_count = 0;
567 if (stat (pty_name, &stb) < 0)
569 failed_count++;
570 if (failed_count >= 3)
571 return -1;
573 else
574 failed_count = 0;
576 # ifdef O_NONBLOCK
577 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
578 # else
579 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
580 # endif
581 # endif /* not IRIS */
583 #endif /* no PTY_OPEN */
585 if (fd >= 0)
587 /* check to make certain that both sides are available
588 this avoids a nasty yet stupid bug in rlogins */
589 #ifdef PTY_TTY_NAME_SPRINTF
590 PTY_TTY_NAME_SPRINTF
591 #else
592 sprintf (pty_name, "/dev/tty%c%x", c, i);
593 #endif /* no PTY_TTY_NAME_SPRINTF */
594 #ifndef UNIPLUS
595 if (access (pty_name, 6) != 0)
597 emacs_close (fd);
598 # if !defined(IRIS) && !defined(__sgi)
599 continue;
600 # else
601 return -1;
602 # endif /* IRIS */
604 #endif /* not UNIPLUS */
605 setup_pty (fd);
606 return fd;
609 return -1;
611 #endif /* HAVE_PTYS */
613 static Lisp_Object
614 make_process (name)
615 Lisp_Object name;
617 register Lisp_Object val, tem, name1;
618 register struct Lisp_Process *p;
619 char suffix[10];
620 register int i;
622 p = allocate_process ();
624 XSETINT (p->infd, -1);
625 XSETINT (p->outfd, -1);
626 XSETFASTINT (p->tick, 0);
627 XSETFASTINT (p->update_tick, 0);
628 p->pid = 0;
629 p->raw_status_new = 0;
630 p->status = Qrun;
631 p->mark = Fmake_marker ();
633 #ifdef ADAPTIVE_READ_BUFFERING
634 p->adaptive_read_buffering = Qnil;
635 XSETFASTINT (p->read_output_delay, 0);
636 p->read_output_skip = Qnil;
637 #endif
639 /* If name is already in use, modify it until it is unused. */
641 name1 = name;
642 for (i = 1; ; i++)
644 tem = Fget_process (name1);
645 if (NILP (tem)) break;
646 sprintf (suffix, "<%d>", i);
647 name1 = concat2 (name, build_string (suffix));
649 name = name1;
650 p->name = name;
651 XSETPROCESS (val, p);
652 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
653 return val;
656 static void
657 remove_process (proc)
658 register Lisp_Object proc;
660 register Lisp_Object pair;
662 pair = Frassq (proc, Vprocess_alist);
663 Vprocess_alist = Fdelq (pair, Vprocess_alist);
665 deactivate_process (proc);
668 /* Setup coding systems of PROCESS. */
670 void
671 setup_process_coding_systems (process)
672 Lisp_Object process;
674 struct Lisp_Process *p = XPROCESS (process);
675 int inch = XINT (p->infd);
676 int outch = XINT (p->outfd);
678 if (inch < 0 || outch < 0)
679 return;
681 if (!proc_decode_coding_system[inch])
682 proc_decode_coding_system[inch]
683 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
684 setup_coding_system (p->decode_coding_system,
685 proc_decode_coding_system[inch]);
686 if (! NILP (p->filter))
688 if (NILP (p->filter_multibyte))
689 setup_raw_text_coding_system (proc_decode_coding_system[inch]);
691 else if (BUFFERP (p->buffer))
693 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
694 setup_raw_text_coding_system (proc_decode_coding_system[inch]);
697 if (!proc_encode_coding_system[outch])
698 proc_encode_coding_system[outch]
699 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
700 setup_coding_system (p->encode_coding_system,
701 proc_encode_coding_system[outch]);
702 if (proc_encode_coding_system[outch]->eol_type == CODING_EOL_UNDECIDED)
703 proc_encode_coding_system[outch]->eol_type = system_eol_type;
706 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
707 doc: /* Return t if OBJECT is a process. */)
708 (object)
709 Lisp_Object object;
711 return PROCESSP (object) ? Qt : Qnil;
714 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
715 doc: /* Return the process named NAME, or nil if there is none. */)
716 (name)
717 register Lisp_Object name;
719 if (PROCESSP (name))
720 return name;
721 CHECK_STRING (name);
722 return Fcdr (Fassoc (name, Vprocess_alist));
725 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
726 doc: /* Return the (or a) process associated with BUFFER.
727 BUFFER may be a buffer or the name of one. */)
728 (buffer)
729 register Lisp_Object buffer;
731 register Lisp_Object buf, tail, proc;
733 if (NILP (buffer)) return Qnil;
734 buf = Fget_buffer (buffer);
735 if (NILP (buf)) return Qnil;
737 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
739 proc = Fcdr (Fcar (tail));
740 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
741 return proc;
743 return Qnil;
746 /* This is how commands for the user decode process arguments. It
747 accepts a process, a process name, a buffer, a buffer name, or nil.
748 Buffers denote the first process in the buffer, and nil denotes the
749 current buffer. */
751 static Lisp_Object
752 get_process (name)
753 register Lisp_Object name;
755 register Lisp_Object proc, obj;
756 if (STRINGP (name))
758 obj = Fget_process (name);
759 if (NILP (obj))
760 obj = Fget_buffer (name);
761 if (NILP (obj))
762 error ("Process %s does not exist", SDATA (name));
764 else if (NILP (name))
765 obj = Fcurrent_buffer ();
766 else
767 obj = name;
769 /* Now obj should be either a buffer object or a process object.
771 if (BUFFERP (obj))
773 proc = Fget_buffer_process (obj);
774 if (NILP (proc))
775 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
777 else
779 CHECK_PROCESS (obj);
780 proc = obj;
782 return proc;
786 #ifdef SIGCHLD
787 /* Fdelete_process promises to immediately forget about the process, but in
788 reality, Emacs needs to remember those processes until they have been
789 treated by sigchld_handler; otherwise this handler would consider the
790 process as being synchronous and say that the synchronous process is
791 dead. */
792 static Lisp_Object deleted_pid_list;
793 #endif
795 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
796 doc: /* Delete PROCESS: kill it and forget about it immediately.
797 PROCESS may be a process, a buffer, the name of a process or buffer, or
798 nil, indicating the current buffer's process. */)
799 (process)
800 register Lisp_Object process;
802 register struct Lisp_Process *p;
804 process = get_process (process);
805 p = XPROCESS (process);
807 p->raw_status_new = 0;
808 if (NETCONN1_P (p))
810 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
811 XSETINT (p->tick, ++process_tick);
812 status_notify (p);
814 else if (XINT (p->infd) >= 0)
816 #ifdef SIGCHLD
817 Lisp_Object symbol;
818 /* Assignment to EMACS_INT stops GCC whining about limited range
819 of data type. */
820 EMACS_INT pid = p->pid;;
822 /* No problem storing the pid here, as it is still in Vprocess_alist. */
823 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
824 /* GC treated elements set to nil. */
825 Fdelq (Qnil, deleted_pid_list));
826 /* If the process has already signaled, remove it from the list. */
827 if (p->raw_status_new)
828 update_status (p);
829 symbol = p->status;
830 if (CONSP (p->status))
831 symbol = XCAR (p->status);
832 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
833 Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
834 else
835 #endif
837 Fkill_process (process, Qnil);
838 /* Do this now, since remove_process will make sigchld_handler do nothing. */
839 p->status
840 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
841 XSETINT (p->tick, ++process_tick);
842 status_notify (p);
845 remove_process (process);
846 return Qnil;
849 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
850 doc: /* Return the status of PROCESS.
851 The returned value is one of the following symbols:
852 run -- for a process that is running.
853 stop -- for a process stopped but continuable.
854 exit -- for a process that has exited.
855 signal -- for a process that has got a fatal signal.
856 open -- for a network stream connection that is open.
857 listen -- for a network stream server that is listening.
858 closed -- for a network stream connection that is closed.
859 connect -- when waiting for a non-blocking connection to complete.
860 failed -- when a non-blocking connection has failed.
861 nil -- if arg is a process name and no such process exists.
862 PROCESS may be a process, a buffer, the name of a process, or
863 nil, indicating the current buffer's process. */)
864 (process)
865 register Lisp_Object process;
867 register struct Lisp_Process *p;
868 register Lisp_Object status;
870 if (STRINGP (process))
871 process = Fget_process (process);
872 else
873 process = get_process (process);
875 if (NILP (process))
876 return process;
878 p = XPROCESS (process);
879 if (p->raw_status_new)
880 update_status (p);
881 status = p->status;
882 if (CONSP (status))
883 status = XCAR (status);
884 if (NETCONN1_P (p))
886 if (EQ (status, Qexit))
887 status = Qclosed;
888 else if (EQ (p->command, Qt))
889 status = Qstop;
890 else if (EQ (status, Qrun))
891 status = Qopen;
893 return status;
896 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
897 1, 1, 0,
898 doc: /* Return the exit status of PROCESS or the signal number that killed it.
899 If PROCESS has not yet exited or died, return 0. */)
900 (process)
901 register Lisp_Object process;
903 CHECK_PROCESS (process);
904 if (XPROCESS (process)->raw_status_new)
905 update_status (XPROCESS (process));
906 if (CONSP (XPROCESS (process)->status))
907 return XCAR (XCDR (XPROCESS (process)->status));
908 return make_number (0);
911 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
912 doc: /* Return the process id of PROCESS.
913 This is the pid of the external process which PROCESS uses or talks to.
914 For a network connection, this value is nil. */)
915 (process)
916 register Lisp_Object process;
918 /* Assignment to EMACS_INT stops GCC whining about limited range of
919 data type. */
920 EMACS_INT pid;
922 CHECK_PROCESS (process);
923 pid = XPROCESS (process)->pid;
924 return (pid ? make_fixnum_or_float (pid) : Qnil);
927 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
928 doc: /* Return the name of PROCESS, as a string.
929 This is the name of the program invoked in PROCESS,
930 possibly modified to make it unique among process names. */)
931 (process)
932 register Lisp_Object process;
934 CHECK_PROCESS (process);
935 return XPROCESS (process)->name;
938 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
939 doc: /* Return the command that was executed to start PROCESS.
940 This is a list of strings, the first string being the program executed
941 and the rest of the strings being the arguments given to it.
942 For a non-child channel, this is nil. */)
943 (process)
944 register Lisp_Object process;
946 CHECK_PROCESS (process);
947 return XPROCESS (process)->command;
950 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
951 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
952 This is the terminal that the process itself reads and writes on,
953 not the name of the pty that Emacs uses to talk with that terminal. */)
954 (process)
955 register Lisp_Object process;
957 CHECK_PROCESS (process);
958 return XPROCESS (process)->tty_name;
961 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
962 2, 2, 0,
963 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
964 (process, buffer)
965 register Lisp_Object process, buffer;
967 struct Lisp_Process *p;
969 CHECK_PROCESS (process);
970 if (!NILP (buffer))
971 CHECK_BUFFER (buffer);
972 p = XPROCESS (process);
973 p->buffer = buffer;
974 if (NETCONN1_P (p))
975 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
976 setup_process_coding_systems (process);
977 return buffer;
980 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
981 1, 1, 0,
982 doc: /* Return the buffer PROCESS is associated with.
983 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
984 (process)
985 register Lisp_Object process;
987 CHECK_PROCESS (process);
988 return XPROCESS (process)->buffer;
991 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
992 1, 1, 0,
993 doc: /* Return the marker for the end of the last output from PROCESS. */)
994 (process)
995 register Lisp_Object process;
997 CHECK_PROCESS (process);
998 return XPROCESS (process)->mark;
1001 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1002 2, 2, 0,
1003 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
1004 t means stop accepting output from the process.
1006 When a process has a filter, its buffer is not used for output.
1007 Instead, each time it does output, the entire string of output is
1008 passed to the filter.
1010 The filter gets two arguments: the process and the string of output.
1011 The string argument is normally a multibyte string, except:
1012 - if the process' input coding system is no-conversion or raw-text,
1013 it is a unibyte string (the non-converted input), or else
1014 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1015 string (the result of converting the decoded input multibyte
1016 string to unibyte with `string-make-unibyte'). */)
1017 (process, filter)
1018 register Lisp_Object process, filter;
1020 struct Lisp_Process *p;
1022 CHECK_PROCESS (process);
1023 p = XPROCESS (process);
1025 /* Don't signal an error if the process' input file descriptor
1026 is closed. This could make debugging Lisp more difficult,
1027 for example when doing something like
1029 (setq process (start-process ...))
1030 (debug)
1031 (set-process-filter process ...) */
1033 if (XINT (p->infd) >= 0)
1035 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1037 FD_CLR (XINT (p->infd), &input_wait_mask);
1038 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
1040 else if (EQ (p->filter, Qt)
1041 && !EQ (p->command, Qt)) /* Network process not stopped. */
1043 FD_SET (XINT (p->infd), &input_wait_mask);
1044 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
1048 p->filter = filter;
1049 if (NETCONN1_P (p))
1050 p->childp = Fplist_put (p->childp, QCfilter, filter);
1051 setup_process_coding_systems (process);
1052 return filter;
1055 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1056 1, 1, 0,
1057 doc: /* Returns the filter function of PROCESS; nil if none.
1058 See `set-process-filter' for more info on filter functions. */)
1059 (process)
1060 register Lisp_Object process;
1062 CHECK_PROCESS (process);
1063 return XPROCESS (process)->filter;
1066 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1067 2, 2, 0,
1068 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1069 The sentinel is called as a function when the process changes state.
1070 It gets two arguments: the process, and a string describing the change. */)
1071 (process, sentinel)
1072 register Lisp_Object process, sentinel;
1074 struct Lisp_Process *p;
1076 CHECK_PROCESS (process);
1077 p = XPROCESS (process);
1079 p->sentinel = sentinel;
1080 if (NETCONN1_P (p))
1081 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1082 return sentinel;
1085 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1086 1, 1, 0,
1087 doc: /* Return the sentinel of PROCESS; nil if none.
1088 See `set-process-sentinel' for more info on sentinels. */)
1089 (process)
1090 register Lisp_Object process;
1092 CHECK_PROCESS (process);
1093 return XPROCESS (process)->sentinel;
1096 DEFUN ("set-process-window-size", Fset_process_window_size,
1097 Sset_process_window_size, 3, 3, 0,
1098 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1099 (process, height, width)
1100 register Lisp_Object process, height, width;
1102 CHECK_PROCESS (process);
1103 CHECK_NATNUM (height);
1104 CHECK_NATNUM (width);
1106 if (XINT (XPROCESS (process)->infd) < 0
1107 || set_window_size (XINT (XPROCESS (process)->infd),
1108 XINT (height), XINT (width)) <= 0)
1109 return Qnil;
1110 else
1111 return Qt;
1114 DEFUN ("set-process-inherit-coding-system-flag",
1115 Fset_process_inherit_coding_system_flag,
1116 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1117 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1118 If the second argument FLAG is non-nil, then the variable
1119 `buffer-file-coding-system' of the buffer associated with PROCESS
1120 will be bound to the value of the coding system used to decode
1121 the process output.
1123 This is useful when the coding system specified for the process buffer
1124 leaves either the character code conversion or the end-of-line conversion
1125 unspecified, or if the coding system used to decode the process output
1126 is more appropriate for saving the process buffer.
1128 Binding the variable `inherit-process-coding-system' to non-nil before
1129 starting the process is an alternative way of setting the inherit flag
1130 for the process which will run. */)
1131 (process, flag)
1132 register Lisp_Object process, flag;
1134 CHECK_PROCESS (process);
1135 XPROCESS (process)->inherit_coding_system_flag = flag;
1136 return flag;
1139 DEFUN ("process-inherit-coding-system-flag",
1140 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1141 1, 1, 0,
1142 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1143 If this flag is t, `buffer-file-coding-system' of the buffer
1144 associated with PROCESS will inherit the coding system used to decode
1145 the process output. */)
1146 (process)
1147 register Lisp_Object process;
1149 CHECK_PROCESS (process);
1150 return XPROCESS (process)->inherit_coding_system_flag;
1153 DEFUN ("set-process-query-on-exit-flag",
1154 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1155 2, 2, 0,
1156 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1157 If the second argument FLAG is non-nil, Emacs will query the user before
1158 exiting if PROCESS is running. */)
1159 (process, flag)
1160 register Lisp_Object process, flag;
1162 CHECK_PROCESS (process);
1163 XPROCESS (process)->kill_without_query = Fnull (flag);
1164 return flag;
1167 DEFUN ("process-query-on-exit-flag",
1168 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1169 1, 1, 0,
1170 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1171 (process)
1172 register Lisp_Object process;
1174 CHECK_PROCESS (process);
1175 return Fnull (XPROCESS (process)->kill_without_query);
1178 #ifdef DATAGRAM_SOCKETS
1179 Lisp_Object Fprocess_datagram_address ();
1180 #endif
1182 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1183 1, 2, 0,
1184 doc: /* Return the contact info of PROCESS; t for a real child.
1185 For a net connection, the value depends on the optional KEY arg.
1186 If KEY is nil, value is a cons cell of the form (HOST SERVICE),
1187 if KEY is t, the complete contact information for the connection is
1188 returned, else the specific value for the keyword KEY is returned.
1189 See `make-network-process' for a list of keywords. */)
1190 (process, key)
1191 register Lisp_Object process, key;
1193 Lisp_Object contact;
1195 CHECK_PROCESS (process);
1196 contact = XPROCESS (process)->childp;
1198 #ifdef DATAGRAM_SOCKETS
1199 if (DATAGRAM_CONN_P (process)
1200 && (EQ (key, Qt) || EQ (key, QCremote)))
1201 contact = Fplist_put (contact, QCremote,
1202 Fprocess_datagram_address (process));
1203 #endif
1205 if (!NETCONN_P (process) || EQ (key, Qt))
1206 return contact;
1207 if (NILP (key))
1208 return Fcons (Fplist_get (contact, QChost),
1209 Fcons (Fplist_get (contact, QCservice), Qnil));
1210 return Fplist_get (contact, key);
1213 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1214 1, 1, 0,
1215 doc: /* Return the plist of PROCESS. */)
1216 (process)
1217 register Lisp_Object process;
1219 CHECK_PROCESS (process);
1220 return XPROCESS (process)->plist;
1223 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1224 2, 2, 0,
1225 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1226 (process, plist)
1227 register Lisp_Object process, plist;
1229 CHECK_PROCESS (process);
1230 CHECK_LIST (plist);
1232 XPROCESS (process)->plist = plist;
1233 return plist;
1236 #if 0 /* Turned off because we don't currently record this info
1237 in the process. Perhaps add it. */
1238 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1239 doc: /* Return the connection type of PROCESS.
1240 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1241 a socket connection. */)
1242 (process)
1243 Lisp_Object process;
1245 return XPROCESS (process)->type;
1247 #endif
1249 #ifdef HAVE_SOCKETS
1250 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1251 1, 2, 0,
1252 doc: /* Convert network ADDRESS from internal format to a string.
1253 A 4 or 5 element vector represents an IPv4 address (with port number).
1254 An 8 or 9 element vector represents an IPv6 address (with port number).
1255 If optional second argument OMIT-PORT is non-nil, don't include a port
1256 number in the string, even when present in ADDRESS.
1257 Returns nil if format of ADDRESS is invalid. */)
1258 (address, omit_port)
1259 Lisp_Object address, omit_port;
1261 if (NILP (address))
1262 return Qnil;
1264 if (STRINGP (address)) /* AF_LOCAL */
1265 return address;
1267 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1269 register struct Lisp_Vector *p = XVECTOR (address);
1270 Lisp_Object args[6];
1271 int nargs, i;
1273 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1275 args[0] = build_string ("%d.%d.%d.%d");
1276 nargs = 4;
1278 else if (p->size == 5)
1280 args[0] = build_string ("%d.%d.%d.%d:%d");
1281 nargs = 5;
1283 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1285 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1286 nargs = 8;
1288 else if (p->size == 9)
1290 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1291 nargs = 9;
1293 else
1294 return Qnil;
1296 for (i = 0; i < nargs; i++)
1297 args[i+1] = p->contents[i];
1298 return Fformat (nargs+1, args);
1301 if (CONSP (address))
1303 Lisp_Object args[2];
1304 args[0] = build_string ("<Family %d>");
1305 args[1] = Fcar (address);
1306 return Fformat (2, args);
1310 return Qnil;
1312 #endif
1314 static Lisp_Object
1315 list_processes_1 (query_only)
1316 Lisp_Object query_only;
1318 register Lisp_Object tail, tem;
1319 Lisp_Object proc, minspace, tem1;
1320 register struct Lisp_Process *p;
1321 char tembuf[300];
1322 int w_proc, w_buffer, w_tty;
1323 int exited = 0;
1324 Lisp_Object i_status, i_buffer, i_tty, i_command;
1326 w_proc = 4; /* Proc */
1327 w_buffer = 6; /* Buffer */
1328 w_tty = 0; /* Omit if no ttys */
1330 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1332 int i;
1334 proc = Fcdr (Fcar (tail));
1335 p = XPROCESS (proc);
1336 if (NILP (p->childp))
1337 continue;
1338 if (!NILP (query_only) && !NILP (p->kill_without_query))
1339 continue;
1340 if (STRINGP (p->name)
1341 && ( i = SCHARS (p->name), (i > w_proc)))
1342 w_proc = i;
1343 if (!NILP (p->buffer))
1345 if (NILP (XBUFFER (p->buffer)->name) && w_buffer < 8)
1346 w_buffer = 8; /* (Killed) */
1347 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1348 w_buffer = i;
1350 if (STRINGP (p->tty_name)
1351 && (i = SCHARS (p->tty_name), (i > w_tty)))
1352 w_tty = i;
1355 XSETFASTINT (i_status, w_proc + 1);
1356 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1357 if (w_tty)
1359 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1360 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_tty + 1);
1361 } else {
1362 i_tty = Qnil;
1363 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1366 XSETFASTINT (minspace, 1);
1368 set_buffer_internal (XBUFFER (Vstandard_output));
1369 current_buffer->undo_list = Qt;
1371 current_buffer->truncate_lines = Qt;
1373 write_string ("Proc", -1);
1374 Findent_to (i_status, minspace); write_string ("Status", -1);
1375 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1376 if (!NILP (i_tty))
1378 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1380 Findent_to (i_command, minspace); write_string ("Command", -1);
1381 write_string ("\n", -1);
1383 write_string ("----", -1);
1384 Findent_to (i_status, minspace); write_string ("------", -1);
1385 Findent_to (i_buffer, minspace); write_string ("------", -1);
1386 if (!NILP (i_tty))
1388 Findent_to (i_tty, minspace); write_string ("---", -1);
1390 Findent_to (i_command, minspace); write_string ("-------", -1);
1391 write_string ("\n", -1);
1393 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1395 Lisp_Object symbol;
1397 proc = Fcdr (Fcar (tail));
1398 p = XPROCESS (proc);
1399 if (NILP (p->childp))
1400 continue;
1401 if (!NILP (query_only) && !NILP (p->kill_without_query))
1402 continue;
1404 Finsert (1, &p->name);
1405 Findent_to (i_status, minspace);
1407 if (p->raw_status_new)
1408 update_status (p);
1409 symbol = p->status;
1410 if (CONSP (p->status))
1411 symbol = XCAR (p->status);
1414 if (EQ (symbol, Qsignal))
1416 Lisp_Object tem;
1417 tem = Fcar (Fcdr (p->status));
1418 #ifdef VMS
1419 if (XINT (tem) < NSIG)
1420 write_string (sys_errlist [XINT (tem)], -1);
1421 else
1422 #endif
1423 Fprinc (symbol, Qnil);
1425 else if (NETCONN1_P (p))
1427 if (EQ (symbol, Qexit))
1428 write_string ("closed", -1);
1429 else if (EQ (p->command, Qt))
1430 write_string ("stopped", -1);
1431 else if (EQ (symbol, Qrun))
1432 write_string ("open", -1);
1433 else
1434 Fprinc (symbol, Qnil);
1436 else
1437 Fprinc (symbol, Qnil);
1439 if (EQ (symbol, Qexit))
1441 Lisp_Object tem;
1442 tem = Fcar (Fcdr (p->status));
1443 if (XFASTINT (tem))
1445 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1446 write_string (tembuf, -1);
1450 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1451 exited++;
1453 Findent_to (i_buffer, minspace);
1454 if (NILP (p->buffer))
1455 insert_string ("(none)");
1456 else if (NILP (XBUFFER (p->buffer)->name))
1457 insert_string ("(Killed)");
1458 else
1459 Finsert (1, &XBUFFER (p->buffer)->name);
1461 if (!NILP (i_tty))
1463 Findent_to (i_tty, minspace);
1464 if (STRINGP (p->tty_name))
1465 Finsert (1, &p->tty_name);
1468 Findent_to (i_command, minspace);
1470 if (EQ (p->status, Qlisten))
1472 Lisp_Object port = Fplist_get (p->childp, QCservice);
1473 if (INTEGERP (port))
1474 port = Fnumber_to_string (port);
1475 if (NILP (port))
1476 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1477 sprintf (tembuf, "(network %s server on %s)\n",
1478 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1479 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1480 insert_string (tembuf);
1482 else if (NETCONN1_P (p))
1484 /* For a local socket, there is no host name,
1485 so display service instead. */
1486 Lisp_Object host = Fplist_get (p->childp, QChost);
1487 if (!STRINGP (host))
1489 host = Fplist_get (p->childp, QCservice);
1490 if (INTEGERP (host))
1491 host = Fnumber_to_string (host);
1493 if (NILP (host))
1494 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1495 sprintf (tembuf, "(network %s connection to %s)\n",
1496 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1497 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1498 insert_string (tembuf);
1500 else
1502 tem = p->command;
1503 while (1)
1505 tem1 = Fcar (tem);
1506 Finsert (1, &tem1);
1507 tem = Fcdr (tem);
1508 if (NILP (tem))
1509 break;
1510 insert_string (" ");
1512 insert_string ("\n");
1515 if (exited)
1516 status_notify (NULL);
1517 return Qnil;
1520 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1521 doc: /* Display a list of all processes.
1522 If optional argument QUERY-ONLY is non-nil, only processes with
1523 the query-on-exit flag set will be listed.
1524 Any process listed as exited or signaled is actually eliminated
1525 after the listing is made. */)
1526 (query_only)
1527 Lisp_Object query_only;
1529 internal_with_output_to_temp_buffer ("*Process List*",
1530 list_processes_1, query_only);
1531 return Qnil;
1534 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1535 doc: /* Return a list of all processes. */)
1538 return Fmapcar (Qcdr, Vprocess_alist);
1541 /* Starting asynchronous inferior processes. */
1543 static Lisp_Object start_process_unwind ();
1545 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1546 doc: /* Start a program in a subprocess. Return the process object for it.
1547 NAME is name for process. It is modified if necessary to make it unique.
1548 BUFFER is the buffer (or buffer name) to associate with the process.
1549 Process output goes at end of that buffer, unless you specify
1550 an output stream or filter function to handle the output.
1551 BUFFER may be also nil, meaning that this process is not associated
1552 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 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1557 (nargs, args)
1558 int nargs;
1559 register Lisp_Object *args;
1561 Lisp_Object buffer, name, program, proc, current_dir, tem;
1562 #ifdef VMS
1563 register unsigned char *new_argv;
1564 int len;
1565 #else
1566 register unsigned char **new_argv;
1567 #endif
1568 register int i;
1569 int count = SPECPDL_INDEX ();
1571 buffer = args[1];
1572 if (!NILP (buffer))
1573 buffer = Fget_buffer_create (buffer);
1575 /* Make sure that the child will be able to chdir to the current
1576 buffer's current directory, or its unhandled equivalent. We
1577 can't just have the child check for an error when it does the
1578 chdir, since it's in a vfork.
1580 We have to GCPRO around this because Fexpand_file_name and
1581 Funhandled_file_name_directory might call a file name handling
1582 function. The argument list is protected by the caller, so all
1583 we really have to worry about is buffer. */
1585 struct gcpro gcpro1, gcpro2;
1587 current_dir = current_buffer->directory;
1589 GCPRO2 (buffer, current_dir);
1591 current_dir
1592 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1593 Qnil);
1594 if (NILP (Ffile_accessible_directory_p (current_dir)))
1595 report_file_error ("Setting current directory",
1596 Fcons (current_buffer->directory, Qnil));
1598 UNGCPRO;
1601 name = args[0];
1602 CHECK_STRING (name);
1604 program = args[2];
1606 CHECK_STRING (program);
1608 proc = make_process (name);
1609 /* If an error occurs and we can't start the process, we want to
1610 remove it from the process list. This means that each error
1611 check in create_process doesn't need to call remove_process
1612 itself; it's all taken care of here. */
1613 record_unwind_protect (start_process_unwind, proc);
1615 XPROCESS (proc)->childp = Qt;
1616 XPROCESS (proc)->plist = Qnil;
1617 XPROCESS (proc)->buffer = buffer;
1618 XPROCESS (proc)->sentinel = Qnil;
1619 XPROCESS (proc)->filter = Qnil;
1620 XPROCESS (proc)->filter_multibyte
1621 = buffer_defaults.enable_multibyte_characters;
1622 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1624 #ifdef ADAPTIVE_READ_BUFFERING
1625 XPROCESS (proc)->adaptive_read_buffering = Vprocess_adaptive_read_buffering;
1626 #endif
1628 /* Make the process marker point into the process buffer (if any). */
1629 if (BUFFERP (buffer))
1630 set_marker_both (XPROCESS (proc)->mark, buffer,
1631 BUF_ZV (XBUFFER (buffer)),
1632 BUF_ZV_BYTE (XBUFFER (buffer)));
1635 /* Decide coding systems for communicating with the process. Here
1636 we don't setup the structure coding_system nor pay attention to
1637 unibyte mode. They are done in create_process. */
1639 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1640 Lisp_Object coding_systems = Qt;
1641 Lisp_Object val, *args2;
1642 struct gcpro gcpro1, gcpro2;
1644 val = Vcoding_system_for_read;
1645 if (NILP (val))
1647 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1648 args2[0] = Qstart_process;
1649 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1650 GCPRO2 (proc, current_dir);
1651 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1652 UNGCPRO;
1653 if (CONSP (coding_systems))
1654 val = XCAR (coding_systems);
1655 else if (CONSP (Vdefault_process_coding_system))
1656 val = XCAR (Vdefault_process_coding_system);
1658 XPROCESS (proc)->decode_coding_system = val;
1660 val = Vcoding_system_for_write;
1661 if (NILP (val))
1663 if (EQ (coding_systems, Qt))
1665 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1666 args2[0] = Qstart_process;
1667 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1668 GCPRO2 (proc, current_dir);
1669 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1670 UNGCPRO;
1672 if (CONSP (coding_systems))
1673 val = XCDR (coding_systems);
1674 else if (CONSP (Vdefault_process_coding_system))
1675 val = XCDR (Vdefault_process_coding_system);
1677 XPROCESS (proc)->encode_coding_system = val;
1680 #ifdef VMS
1681 /* Make a one member argv with all args concatenated
1682 together separated by a blank. */
1683 len = SBYTES (program) + 2;
1684 for (i = 3; i < nargs; i++)
1686 tem = args[i];
1687 CHECK_STRING (tem);
1688 len += SBYTES (tem) + 1; /* count the blank */
1690 new_argv = (unsigned char *) alloca (len);
1691 strcpy (new_argv, SDATA (program));
1692 for (i = 3; i < nargs; i++)
1694 tem = args[i];
1695 CHECK_STRING (tem);
1696 strcat (new_argv, " ");
1697 strcat (new_argv, SDATA (tem));
1699 /* Need to add code here to check for program existence on VMS */
1701 #else /* not VMS */
1702 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1704 /* If program file name is not absolute, search our path for it.
1705 Put the name we will really use in TEM. */
1706 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1707 && !(SCHARS (program) > 1
1708 && IS_DEVICE_SEP (SREF (program, 1))))
1710 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1712 tem = Qnil;
1713 GCPRO4 (name, program, buffer, current_dir);
1714 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1715 UNGCPRO;
1716 if (NILP (tem))
1717 report_file_error ("Searching for program", Fcons (program, Qnil));
1718 tem = Fexpand_file_name (tem, Qnil);
1720 else
1722 if (!NILP (Ffile_directory_p (program)))
1723 error ("Specified program for new process is a directory");
1724 tem = program;
1727 /* If program file name starts with /: for quoting a magic name,
1728 discard that. */
1729 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1730 && SREF (tem, 1) == ':')
1731 tem = Fsubstring (tem, make_number (2), Qnil);
1733 /* Encode the file name and put it in NEW_ARGV.
1734 That's where the child will use it to execute the program. */
1735 tem = ENCODE_FILE (tem);
1736 new_argv[0] = SDATA (tem);
1738 /* Here we encode arguments by the coding system used for sending
1739 data to the process. We don't support using different coding
1740 systems for encoding arguments and for encoding data sent to the
1741 process. */
1743 for (i = 3; i < nargs; i++)
1745 tem = args[i];
1746 CHECK_STRING (tem);
1747 if (STRING_MULTIBYTE (tem))
1748 tem = (code_convert_string_norecord
1749 (tem, XPROCESS (proc)->encode_coding_system, 1));
1750 new_argv[i - 2] = SDATA (tem);
1752 new_argv[i - 2] = 0;
1753 #endif /* not VMS */
1755 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1756 XPROCESS (proc)->decoding_carryover = make_number (0);
1757 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1758 XPROCESS (proc)->encoding_carryover = make_number (0);
1760 XPROCESS (proc)->inherit_coding_system_flag
1761 = (NILP (buffer) || !inherit_process_coding_system
1762 ? Qnil : Qt);
1764 create_process (proc, (char **) new_argv, current_dir);
1766 return unbind_to (count, proc);
1769 /* This function is the unwind_protect form for Fstart_process. If
1770 PROC doesn't have its pid set, then we know someone has signaled
1771 an error and the process wasn't started successfully, so we should
1772 remove it from the process list. */
1773 static Lisp_Object
1774 start_process_unwind (proc)
1775 Lisp_Object proc;
1777 if (!PROCESSP (proc))
1778 abort ();
1780 /* Was PROC started successfully? */
1781 if (XPROCESS (proc)->pid <= 0)
1782 remove_process (proc);
1784 return Qnil;
1787 static void
1788 create_process_1 (timer)
1789 struct atimer *timer;
1791 /* Nothing to do. */
1795 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1796 #ifdef USG
1797 #ifdef SIGCHLD
1798 /* Mimic blocking of signals on system V, which doesn't really have it. */
1800 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1801 int sigchld_deferred;
1803 SIGTYPE
1804 create_process_sigchld ()
1806 signal (SIGCHLD, create_process_sigchld);
1808 sigchld_deferred = 1;
1810 #endif
1811 #endif
1812 #endif
1814 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1815 void
1816 create_process (process, new_argv, current_dir)
1817 Lisp_Object process;
1818 char **new_argv;
1819 Lisp_Object current_dir;
1821 int pid, inchannel, outchannel;
1822 int sv[2];
1823 #ifdef POSIX_SIGNALS
1824 sigset_t procmask;
1825 sigset_t blocked;
1826 struct sigaction sigint_action;
1827 struct sigaction sigquit_action;
1828 #ifdef AIX
1829 struct sigaction sighup_action;
1830 #endif
1831 #else /* !POSIX_SIGNALS */
1832 #if 0
1833 #ifdef SIGCHLD
1834 SIGTYPE (*sigchld)();
1835 #endif
1836 #endif /* 0 */
1837 #endif /* !POSIX_SIGNALS */
1838 /* Use volatile to protect variables from being clobbered by longjmp. */
1839 volatile int forkin, forkout;
1840 volatile int pty_flag = 0;
1841 #ifndef USE_CRT_DLL
1842 extern char **environ;
1843 #endif
1845 inchannel = outchannel = -1;
1847 #ifdef HAVE_PTYS
1848 if (!NILP (Vprocess_connection_type))
1849 outchannel = inchannel = allocate_pty ();
1851 if (inchannel >= 0)
1853 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1854 /* On most USG systems it does not work to open the pty's tty here,
1855 then close it and reopen it in the child. */
1856 #ifdef O_NOCTTY
1857 /* Don't let this terminal become our controlling terminal
1858 (in case we don't have one). */
1859 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1860 #else
1861 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1862 #endif
1863 if (forkin < 0)
1864 report_file_error ("Opening pty", Qnil);
1865 #if defined (RTU) || defined (UNIPLUS) || defined (DONT_REOPEN_PTY)
1866 /* In the case that vfork is defined as fork, the parent process
1867 (Emacs) may send some data before the child process completes
1868 tty options setup. So we setup tty before forking. */
1869 child_setup_tty (forkout);
1870 #endif /* RTU or UNIPLUS or DONT_REOPEN_PTY */
1871 #else
1872 forkin = forkout = -1;
1873 #endif /* not USG, or USG_SUBTTY_WORKS */
1874 pty_flag = 1;
1876 else
1877 #endif /* HAVE_PTYS */
1878 #ifdef SKTPAIR
1880 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1881 report_file_error ("Opening socketpair", Qnil);
1882 outchannel = inchannel = sv[0];
1883 forkout = forkin = sv[1];
1885 #else /* not SKTPAIR */
1887 int tem;
1888 tem = pipe (sv);
1889 if (tem < 0)
1890 report_file_error ("Creating pipe", Qnil);
1891 inchannel = sv[0];
1892 forkout = sv[1];
1893 tem = pipe (sv);
1894 if (tem < 0)
1896 emacs_close (inchannel);
1897 emacs_close (forkout);
1898 report_file_error ("Creating pipe", Qnil);
1900 outchannel = sv[1];
1901 forkin = sv[0];
1903 #endif /* not SKTPAIR */
1905 #if 0
1906 /* Replaced by close_process_descs */
1907 set_exclusive_use (inchannel);
1908 set_exclusive_use (outchannel);
1909 #endif
1911 /* Stride people say it's a mystery why this is needed
1912 as well as the O_NDELAY, but that it fails without this. */
1913 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1915 int one = 1;
1916 ioctl (inchannel, FIONBIO, &one);
1918 #endif
1920 #ifdef O_NONBLOCK
1921 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1922 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1923 #else
1924 #ifdef O_NDELAY
1925 fcntl (inchannel, F_SETFL, O_NDELAY);
1926 fcntl (outchannel, F_SETFL, O_NDELAY);
1927 #endif
1928 #endif
1930 /* Record this as an active process, with its channels.
1931 As a result, child_setup will close Emacs's side of the pipes. */
1932 chan_process[inchannel] = process;
1933 XSETINT (XPROCESS (process)->infd, inchannel);
1934 XSETINT (XPROCESS (process)->outfd, outchannel);
1936 /* Previously we recorded the tty descriptor used in the subprocess.
1937 It was only used for getting the foreground tty process, so now
1938 we just reopen the device (see emacs_get_tty_pgrp) as this is
1939 more portable (see USG_SUBTTY_WORKS above). */
1941 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1942 XPROCESS (process)->status = Qrun;
1943 setup_process_coding_systems (process);
1945 /* Delay interrupts until we have a chance to store
1946 the new fork's pid in its process structure */
1947 #ifdef POSIX_SIGNALS
1948 sigemptyset (&blocked);
1949 #ifdef SIGCHLD
1950 sigaddset (&blocked, SIGCHLD);
1951 #endif
1952 #ifdef HAVE_WORKING_VFORK
1953 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1954 this sets the parent's signal handlers as well as the child's.
1955 So delay all interrupts whose handlers the child might munge,
1956 and record the current handlers so they can be restored later. */
1957 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1958 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1959 #ifdef AIX
1960 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1961 #endif
1962 #endif /* HAVE_WORKING_VFORK */
1963 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1964 #else /* !POSIX_SIGNALS */
1965 #ifdef SIGCHLD
1966 #ifdef BSD4_1
1967 sighold (SIGCHLD);
1968 #else /* not BSD4_1 */
1969 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1970 sigsetmask (sigmask (SIGCHLD));
1971 #else /* ordinary USG */
1972 #if 0
1973 sigchld_deferred = 0;
1974 sigchld = signal (SIGCHLD, create_process_sigchld);
1975 #endif
1976 #endif /* ordinary USG */
1977 #endif /* not BSD4_1 */
1978 #endif /* SIGCHLD */
1979 #endif /* !POSIX_SIGNALS */
1981 FD_SET (inchannel, &input_wait_mask);
1982 FD_SET (inchannel, &non_keyboard_wait_mask);
1983 if (inchannel > max_process_desc)
1984 max_process_desc = inchannel;
1986 /* Until we store the proper pid, enable sigchld_handler
1987 to recognize an unknown pid as standing for this process.
1988 It is very important not to let this `marker' value stay
1989 in the table after this function has returned; if it does
1990 it might cause call-process to hang and subsequent asynchronous
1991 processes to get their return values scrambled. */
1992 XPROCESS (process)->pid = -1;
1994 BLOCK_INPUT;
1997 /* child_setup must clobber environ on systems with true vfork.
1998 Protect it from permanent change. */
1999 char **save_environ = environ;
2001 current_dir = ENCODE_FILE (current_dir);
2003 #ifndef WINDOWSNT
2004 pid = vfork ();
2005 if (pid == 0)
2006 #endif /* not WINDOWSNT */
2008 int xforkin = forkin;
2009 int xforkout = forkout;
2011 #if 0 /* This was probably a mistake--it duplicates code later on,
2012 but fails to handle all the cases. */
2013 /* Make sure SIGCHLD is not blocked in the child. */
2014 sigsetmask (SIGEMPTYMASK);
2015 #endif
2017 /* Make the pty be the controlling terminal of the process. */
2018 #ifdef HAVE_PTYS
2019 /* First, disconnect its current controlling terminal. */
2020 #ifdef HAVE_SETSID
2021 /* We tried doing setsid only if pty_flag, but it caused
2022 process_set_signal to fail on SGI when using a pipe. */
2023 setsid ();
2024 /* Make the pty's terminal the controlling terminal. */
2025 if (pty_flag)
2027 #ifdef TIOCSCTTY
2028 /* We ignore the return value
2029 because faith@cs.unc.edu says that is necessary on Linux. */
2030 ioctl (xforkin, TIOCSCTTY, 0);
2031 #endif
2033 #else /* not HAVE_SETSID */
2034 #ifdef USG
2035 /* It's very important to call setpgrp here and no time
2036 afterwards. Otherwise, we lose our controlling tty which
2037 is set when we open the pty. */
2038 setpgrp ();
2039 #endif /* USG */
2040 #endif /* not HAVE_SETSID */
2041 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2042 if (pty_flag && xforkin >= 0)
2044 struct termios t;
2045 tcgetattr (xforkin, &t);
2046 t.c_lflag = LDISC1;
2047 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2048 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2050 #else
2051 #if defined (NTTYDISC) && defined (TIOCSETD)
2052 if (pty_flag && xforkin >= 0)
2054 /* Use new line discipline. */
2055 int ldisc = NTTYDISC;
2056 ioctl (xforkin, TIOCSETD, &ldisc);
2058 #endif
2059 #endif
2060 #ifdef TIOCNOTTY
2061 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2062 can do TIOCSPGRP only to the process's controlling tty. */
2063 if (pty_flag)
2065 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2066 I can't test it since I don't have 4.3. */
2067 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2068 ioctl (j, TIOCNOTTY, 0);
2069 emacs_close (j);
2070 #ifndef USG
2071 /* In order to get a controlling terminal on some versions
2072 of BSD, it is necessary to put the process in pgrp 0
2073 before it opens the terminal. */
2074 #ifdef HAVE_SETPGID
2075 setpgid (0, 0);
2076 #else
2077 setpgrp (0, 0);
2078 #endif
2079 #endif
2081 #endif /* TIOCNOTTY */
2083 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
2084 /*** There is a suggestion that this ought to be a
2085 conditional on TIOCSPGRP,
2086 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2087 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2088 that system does seem to need this code, even though
2089 both HAVE_SETSID and TIOCSCTTY are defined. */
2090 /* Now close the pty (if we had it open) and reopen it.
2091 This makes the pty the controlling terminal of the subprocess. */
2092 if (pty_flag)
2094 #ifdef SET_CHILD_PTY_PGRP
2095 int pgrp = getpid ();
2096 #endif
2098 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2099 would work? */
2100 if (xforkin >= 0)
2101 emacs_close (xforkin);
2102 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2104 if (xforkin < 0)
2106 emacs_write (1, "Couldn't open the pty terminal ", 31);
2107 emacs_write (1, pty_name, strlen (pty_name));
2108 emacs_write (1, "\n", 1);
2109 _exit (1);
2112 #ifdef SET_CHILD_PTY_PGRP
2113 ioctl (xforkin, TIOCSPGRP, &pgrp);
2114 ioctl (xforkout, TIOCSPGRP, &pgrp);
2115 #endif
2117 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
2119 #ifdef SETUP_SLAVE_PTY
2120 if (pty_flag)
2122 SETUP_SLAVE_PTY;
2124 #endif /* SETUP_SLAVE_PTY */
2125 #ifdef AIX
2126 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2127 Now reenable it in the child, so it will die when we want it to. */
2128 if (pty_flag)
2129 signal (SIGHUP, SIG_DFL);
2130 #endif
2131 #endif /* HAVE_PTYS */
2133 signal (SIGINT, SIG_DFL);
2134 signal (SIGQUIT, SIG_DFL);
2136 /* Stop blocking signals in the child. */
2137 #ifdef POSIX_SIGNALS
2138 sigprocmask (SIG_SETMASK, &procmask, 0);
2139 #else /* !POSIX_SIGNALS */
2140 #ifdef SIGCHLD
2141 #ifdef BSD4_1
2142 sigrelse (SIGCHLD);
2143 #else /* not BSD4_1 */
2144 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2145 sigsetmask (SIGEMPTYMASK);
2146 #else /* ordinary USG */
2147 #if 0
2148 signal (SIGCHLD, sigchld);
2149 #endif
2150 #endif /* ordinary USG */
2151 #endif /* not BSD4_1 */
2152 #endif /* SIGCHLD */
2153 #endif /* !POSIX_SIGNALS */
2155 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
2156 if (pty_flag)
2157 child_setup_tty (xforkout);
2158 #endif /* not RTU and not UNIPLUS and not DONT_REOPEN_PTY */
2159 #ifdef WINDOWSNT
2160 pid = child_setup (xforkin, xforkout, xforkout,
2161 new_argv, 1, current_dir);
2162 #else /* not WINDOWSNT */
2163 child_setup (xforkin, xforkout, xforkout,
2164 new_argv, 1, current_dir);
2165 #endif /* not WINDOWSNT */
2167 environ = save_environ;
2170 UNBLOCK_INPUT;
2172 /* This runs in the Emacs process. */
2173 if (pid < 0)
2175 if (forkin >= 0)
2176 emacs_close (forkin);
2177 if (forkin != forkout && forkout >= 0)
2178 emacs_close (forkout);
2180 else
2182 /* vfork succeeded. */
2183 XPROCESS (process)->pid = pid;
2185 #ifdef WINDOWSNT
2186 register_child (pid, inchannel);
2187 #endif /* WINDOWSNT */
2189 /* If the subfork execv fails, and it exits,
2190 this close hangs. I don't know why.
2191 So have an interrupt jar it loose. */
2193 struct atimer *timer;
2194 EMACS_TIME offset;
2196 stop_polling ();
2197 EMACS_SET_SECS_USECS (offset, 1, 0);
2198 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2200 if (forkin >= 0)
2201 emacs_close (forkin);
2203 cancel_atimer (timer);
2204 start_polling ();
2207 if (forkin != forkout && forkout >= 0)
2208 emacs_close (forkout);
2210 #ifdef HAVE_PTYS
2211 if (pty_flag)
2212 XPROCESS (process)->tty_name = build_string (pty_name);
2213 else
2214 #endif
2215 XPROCESS (process)->tty_name = Qnil;
2218 /* Restore the signal state whether vfork succeeded or not.
2219 (We will signal an error, below, if it failed.) */
2220 #ifdef POSIX_SIGNALS
2221 #ifdef HAVE_WORKING_VFORK
2222 /* Restore the parent's signal handlers. */
2223 sigaction (SIGINT, &sigint_action, 0);
2224 sigaction (SIGQUIT, &sigquit_action, 0);
2225 #ifdef AIX
2226 sigaction (SIGHUP, &sighup_action, 0);
2227 #endif
2228 #endif /* HAVE_WORKING_VFORK */
2229 /* Stop blocking signals in the parent. */
2230 sigprocmask (SIG_SETMASK, &procmask, 0);
2231 #else /* !POSIX_SIGNALS */
2232 #ifdef SIGCHLD
2233 #ifdef BSD4_1
2234 sigrelse (SIGCHLD);
2235 #else /* not BSD4_1 */
2236 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2237 sigsetmask (SIGEMPTYMASK);
2238 #else /* ordinary USG */
2239 #if 0
2240 signal (SIGCHLD, sigchld);
2241 /* Now really handle any of these signals
2242 that came in during this function. */
2243 if (sigchld_deferred)
2244 kill (getpid (), SIGCHLD);
2245 #endif
2246 #endif /* ordinary USG */
2247 #endif /* not BSD4_1 */
2248 #endif /* SIGCHLD */
2249 #endif /* !POSIX_SIGNALS */
2251 /* Now generate the error if vfork failed. */
2252 if (pid < 0)
2253 report_file_error ("Doing vfork", Qnil);
2255 #endif /* not VMS */
2258 #ifdef HAVE_SOCKETS
2260 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2261 The address family of sa is not included in the result. */
2263 static Lisp_Object
2264 conv_sockaddr_to_lisp (sa, len)
2265 struct sockaddr *sa;
2266 int len;
2268 Lisp_Object address;
2269 int i;
2270 unsigned char *cp;
2271 register struct Lisp_Vector *p;
2273 switch (sa->sa_family)
2275 case AF_INET:
2277 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2278 len = sizeof (sin->sin_addr) + 1;
2279 address = Fmake_vector (make_number (len), Qnil);
2280 p = XVECTOR (address);
2281 p->contents[--len] = make_number (ntohs (sin->sin_port));
2282 cp = (unsigned char *)&sin->sin_addr;
2283 break;
2285 #ifdef AF_INET6
2286 case AF_INET6:
2288 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2289 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2290 len = sizeof (sin6->sin6_addr)/2 + 1;
2291 address = Fmake_vector (make_number (len), Qnil);
2292 p = XVECTOR (address);
2293 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2294 for (i = 0; i < len; i++)
2295 p->contents[i] = make_number (ntohs (ip6[i]));
2296 return address;
2298 #endif
2299 #ifdef HAVE_LOCAL_SOCKETS
2300 case AF_LOCAL:
2302 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2303 for (i = 0; i < sizeof (sockun->sun_path); i++)
2304 if (sockun->sun_path[i] == 0)
2305 break;
2306 return make_unibyte_string (sockun->sun_path, i);
2308 #endif
2309 default:
2310 len -= sizeof (sa->sa_family);
2311 address = Fcons (make_number (sa->sa_family),
2312 Fmake_vector (make_number (len), Qnil));
2313 p = XVECTOR (XCDR (address));
2314 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2315 break;
2318 i = 0;
2319 while (i < len)
2320 p->contents[i++] = make_number (*cp++);
2322 return address;
2326 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2328 static int
2329 get_lisp_to_sockaddr_size (address, familyp)
2330 Lisp_Object address;
2331 int *familyp;
2333 register struct Lisp_Vector *p;
2335 if (VECTORP (address))
2337 p = XVECTOR (address);
2338 if (p->size == 5)
2340 *familyp = AF_INET;
2341 return sizeof (struct sockaddr_in);
2343 #ifdef AF_INET6
2344 else if (p->size == 9)
2346 *familyp = AF_INET6;
2347 return sizeof (struct sockaddr_in6);
2349 #endif
2351 #ifdef HAVE_LOCAL_SOCKETS
2352 else if (STRINGP (address))
2354 *familyp = AF_LOCAL;
2355 return sizeof (struct sockaddr_un);
2357 #endif
2358 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2360 struct sockaddr *sa;
2361 *familyp = XINT (XCAR (address));
2362 p = XVECTOR (XCDR (address));
2363 return p->size + sizeof (sa->sa_family);
2365 return 0;
2368 /* Convert an address object (vector or string) to an internal sockaddr.
2370 The address format has been basically validated by
2371 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2372 it could have come from user data. So if FAMILY is not valid,
2373 we return after zeroing *SA. */
2375 static void
2376 conv_lisp_to_sockaddr (family, address, sa, len)
2377 int family;
2378 Lisp_Object address;
2379 struct sockaddr *sa;
2380 int len;
2382 register struct Lisp_Vector *p;
2383 register unsigned char *cp = NULL;
2384 register int i;
2386 bzero (sa, len);
2388 if (VECTORP (address))
2390 p = XVECTOR (address);
2391 if (family == AF_INET)
2393 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2394 len = sizeof (sin->sin_addr) + 1;
2395 i = XINT (p->contents[--len]);
2396 sin->sin_port = htons (i);
2397 cp = (unsigned char *)&sin->sin_addr;
2398 sa->sa_family = family;
2400 #ifdef AF_INET6
2401 else if (family == AF_INET6)
2403 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2404 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2405 len = sizeof (sin6->sin6_addr) + 1;
2406 i = XINT (p->contents[--len]);
2407 sin6->sin6_port = htons (i);
2408 for (i = 0; i < len; i++)
2409 if (INTEGERP (p->contents[i]))
2411 int j = XFASTINT (p->contents[i]) & 0xffff;
2412 ip6[i] = ntohs (j);
2414 sa->sa_family = family;
2416 #endif
2417 return;
2419 else if (STRINGP (address))
2421 #ifdef HAVE_LOCAL_SOCKETS
2422 if (family == AF_LOCAL)
2424 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2425 cp = SDATA (address);
2426 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2427 sockun->sun_path[i] = *cp++;
2428 sa->sa_family = family;
2430 #endif
2431 return;
2433 else
2435 p = XVECTOR (XCDR (address));
2436 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2439 for (i = 0; i < len; i++)
2440 if (INTEGERP (p->contents[i]))
2441 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2444 #ifdef DATAGRAM_SOCKETS
2445 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2446 1, 1, 0,
2447 doc: /* Get the current datagram address associated with PROCESS. */)
2448 (process)
2449 Lisp_Object process;
2451 int channel;
2453 CHECK_PROCESS (process);
2455 if (!DATAGRAM_CONN_P (process))
2456 return Qnil;
2458 channel = XINT (XPROCESS (process)->infd);
2459 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2460 datagram_address[channel].len);
2463 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2464 2, 2, 0,
2465 doc: /* Set the datagram address for PROCESS to ADDRESS.
2466 Returns nil upon error setting address, ADDRESS otherwise. */)
2467 (process, address)
2468 Lisp_Object process, address;
2470 int channel;
2471 int family, len;
2473 CHECK_PROCESS (process);
2475 if (!DATAGRAM_CONN_P (process))
2476 return Qnil;
2478 channel = XINT (XPROCESS (process)->infd);
2480 len = get_lisp_to_sockaddr_size (address, &family);
2481 if (datagram_address[channel].len != len)
2482 return Qnil;
2483 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2484 return address;
2486 #endif
2489 static struct socket_options {
2490 /* The name of this option. Should be lowercase version of option
2491 name without SO_ prefix. */
2492 char *name;
2493 /* Option level SOL_... */
2494 int optlevel;
2495 /* Option number SO_... */
2496 int optnum;
2497 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2498 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2499 } socket_options[] =
2501 #ifdef SO_BINDTODEVICE
2502 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2503 #endif
2504 #ifdef SO_BROADCAST
2505 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2506 #endif
2507 #ifdef SO_DONTROUTE
2508 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2509 #endif
2510 #ifdef SO_KEEPALIVE
2511 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2512 #endif
2513 #ifdef SO_LINGER
2514 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2515 #endif
2516 #ifdef SO_OOBINLINE
2517 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2518 #endif
2519 #ifdef SO_PRIORITY
2520 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2521 #endif
2522 #ifdef SO_REUSEADDR
2523 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2524 #endif
2525 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2528 /* Set option OPT to value VAL on socket S.
2530 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2531 Signals an error if setting a known option fails.
2534 static int
2535 set_socket_option (s, opt, val)
2536 int s;
2537 Lisp_Object opt, val;
2539 char *name;
2540 struct socket_options *sopt;
2541 int ret = 0;
2543 CHECK_SYMBOL (opt);
2545 name = (char *) SDATA (SYMBOL_NAME (opt));
2546 for (sopt = socket_options; sopt->name; sopt++)
2547 if (strcmp (name, sopt->name) == 0)
2548 break;
2550 switch (sopt->opttype)
2552 case SOPT_BOOL:
2554 int optval;
2555 optval = NILP (val) ? 0 : 1;
2556 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2557 &optval, sizeof (optval));
2558 break;
2561 case SOPT_INT:
2563 int optval;
2564 if (INTEGERP (val))
2565 optval = XINT (val);
2566 else
2567 error ("Bad option value for %s", name);
2568 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2569 &optval, sizeof (optval));
2570 break;
2573 #ifdef SO_BINDTODEVICE
2574 case SOPT_IFNAME:
2576 char devname[IFNAMSIZ+1];
2578 /* This is broken, at least in the Linux 2.4 kernel.
2579 To unbind, the arg must be a zero integer, not the empty string.
2580 This should work on all systems. KFS. 2003-09-23. */
2581 bzero (devname, sizeof devname);
2582 if (STRINGP (val))
2584 char *arg = (char *) SDATA (val);
2585 int len = min (strlen (arg), IFNAMSIZ);
2586 bcopy (arg, devname, len);
2588 else if (!NILP (val))
2589 error ("Bad option value for %s", name);
2590 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2591 devname, IFNAMSIZ);
2592 break;
2594 #endif
2596 #ifdef SO_LINGER
2597 case SOPT_LINGER:
2599 struct linger linger;
2601 linger.l_onoff = 1;
2602 linger.l_linger = 0;
2603 if (INTEGERP (val))
2604 linger.l_linger = XINT (val);
2605 else
2606 linger.l_onoff = NILP (val) ? 0 : 1;
2607 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2608 &linger, sizeof (linger));
2609 break;
2611 #endif
2613 default:
2614 return 0;
2617 if (ret < 0)
2618 report_file_error ("Cannot set network option",
2619 Fcons (opt, Fcons (val, Qnil)));
2620 return (1 << sopt->optbit);
2624 DEFUN ("set-network-process-option",
2625 Fset_network_process_option, Sset_network_process_option,
2626 3, 4, 0,
2627 doc: /* For network process PROCESS set option OPTION to value VALUE.
2628 See `make-network-process' for a list of options and values.
2629 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2630 OPTION is not a supported option, return nil instead; otherwise return t. */)
2631 (process, option, value, no_error)
2632 Lisp_Object process, option, value;
2633 Lisp_Object no_error;
2635 int s;
2636 struct Lisp_Process *p;
2638 CHECK_PROCESS (process);
2639 p = XPROCESS (process);
2640 if (!NETCONN1_P (p))
2641 error ("Process is not a network process");
2643 s = XINT (p->infd);
2644 if (s < 0)
2645 error ("Process is not running");
2647 if (set_socket_option (s, option, value))
2649 p->childp = Fplist_put (p->childp, option, value);
2650 return Qt;
2653 if (NILP (no_error))
2654 error ("Unknown or unsupported option");
2656 return Qnil;
2660 /* A version of request_sigio suitable for a record_unwind_protect. */
2662 static Lisp_Object
2663 unwind_request_sigio (dummy)
2664 Lisp_Object dummy;
2666 if (interrupt_input)
2667 request_sigio ();
2668 return Qnil;
2671 /* Create a network stream/datagram client/server process. Treated
2672 exactly like a normal process when reading and writing. Primary
2673 differences are in status display and process deletion. A network
2674 connection has no PID; you cannot signal it. All you can do is
2675 stop/continue it and deactivate/close it via delete-process */
2677 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2678 0, MANY, 0,
2679 doc: /* Create and return a network server or client process.
2681 In Emacs, network connections are represented by process objects, so
2682 input and output work as for subprocesses and `delete-process' closes
2683 a network connection. However, a network process has no process id,
2684 it cannot be signaled, and the status codes are different from normal
2685 processes.
2687 Arguments are specified as keyword/argument pairs. The following
2688 arguments are defined:
2690 :name NAME -- NAME is name for process. It is modified if necessary
2691 to make it unique.
2693 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2694 with the process. Process output goes at end of that buffer, unless
2695 you specify an output stream or filter function to handle the output.
2696 BUFFER may be also nil, meaning that this process is not associated
2697 with any buffer.
2699 :host HOST -- HOST is name of the host to connect to, or its IP
2700 address. The symbol `local' specifies the local host. If specified
2701 for a server process, it must be a valid name or address for the local
2702 host, and only clients connecting to that address will be accepted.
2704 :service SERVICE -- SERVICE is name of the service desired, or an
2705 integer specifying a port number to connect to. If SERVICE is t,
2706 a random port number is selected for the server.
2708 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2709 stream type connection, `datagram' creates a datagram type connection.
2711 :family FAMILY -- FAMILY is the address (and protocol) family for the
2712 service specified by HOST and SERVICE. The default (nil) is to use
2713 whatever address family (IPv4 or IPv6) that is defined for the host
2714 and port number specified by HOST and SERVICE. Other address families
2715 supported are:
2716 local -- for a local (i.e. UNIX) address specified by SERVICE.
2717 ipv4 -- use IPv4 address family only.
2718 ipv6 -- use IPv6 address family only.
2720 :local ADDRESS -- ADDRESS is the local address used for the connection.
2721 This parameter is ignored when opening a client process. When specified
2722 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2724 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2725 connection. This parameter is ignored when opening a stream server
2726 process. For a datagram server process, it specifies the initial
2727 setting of the remote datagram address. When specified for a client
2728 process, the FAMILY, HOST, and SERVICE args are ignored.
2730 The format of ADDRESS depends on the address family:
2731 - An IPv4 address is represented as an vector of integers [A B C D P]
2732 corresponding to numeric IP address A.B.C.D and port number P.
2733 - A local address is represented as a string with the address in the
2734 local address space.
2735 - An "unsupported family" address is represented by a cons (F . AV)
2736 where F is the family number and AV is a vector containing the socket
2737 address data with one element per address data byte. Do not rely on
2738 this format in portable code, as it may depend on implementation
2739 defined constants, data sizes, and data structure alignment.
2741 :coding CODING -- If CODING is a symbol, it specifies the coding
2742 system used for both reading and writing for this process. If CODING
2743 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2744 ENCODING is used for writing.
2746 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2747 return without waiting for the connection to complete; instead, the
2748 sentinel function will be called with second arg matching "open" (if
2749 successful) or "failed" when the connect completes. Default is to use
2750 a blocking connect (i.e. wait) for stream type connections.
2752 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2753 running when Emacs is exited.
2755 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2756 In the stopped state, a server process does not accept new
2757 connections, and a client process does not handle incoming traffic.
2758 The stopped state is cleared by `continue-process' and set by
2759 `stop-process'.
2761 :filter FILTER -- Install FILTER as the process filter.
2763 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2764 process filter are multibyte, otherwise they are unibyte.
2765 If this keyword is not specified, the strings are multibyte iff
2766 `default-enable-multibyte-characters' is non-nil.
2768 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2770 :log LOG -- Install LOG as the server process log function. This
2771 function is called when the server accepts a network connection from a
2772 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2773 is the server process, CLIENT is the new process for the connection,
2774 and MESSAGE is a string.
2776 :plist PLIST -- Install PLIST as the new process' initial plist.
2778 :server QLEN -- if QLEN is non-nil, create a server process for the
2779 specified FAMILY, SERVICE, and connection type (stream or datagram).
2780 If QLEN is an integer, it is used as the max. length of the server's
2781 pending connection queue (also known as the backlog); the default
2782 queue length is 5. Default is to create a client process.
2784 The following network options can be specified for this connection:
2786 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2787 :dontroute BOOL -- Only send to directly connected hosts.
2788 :keepalive BOOL -- Send keep-alive messages on network stream.
2789 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2790 :oobinline BOOL -- Place out-of-band data in receive data stream.
2791 :priority INT -- Set protocol defined priority for sent packets.
2792 :reuseaddr BOOL -- Allow reusing a recently used local address
2793 (this is allowed by default for a server process).
2794 :bindtodevice NAME -- bind to interface NAME. Using this may require
2795 special privileges on some systems.
2797 Consult the relevant system programmer's manual pages for more
2798 information on using these options.
2801 A server process will listen for and accept connections from clients.
2802 When a client connection is accepted, a new network process is created
2803 for the connection with the following parameters:
2805 - The client's process name is constructed by concatenating the server
2806 process' NAME and a client identification string.
2807 - If the FILTER argument is non-nil, the client process will not get a
2808 separate process buffer; otherwise, the client's process buffer is a newly
2809 created buffer named after the server process' BUFFER name or process
2810 NAME concatenated with the client identification string.
2811 - The connection type and the process filter and sentinel parameters are
2812 inherited from the server process' TYPE, FILTER and SENTINEL.
2813 - The client process' contact info is set according to the client's
2814 addressing information (typically an IP address and a port number).
2815 - The client process' plist is initialized from the server's plist.
2817 Notice that the FILTER and SENTINEL args are never used directly by
2818 the server process. Also, the BUFFER argument is not used directly by
2819 the server process, but via the optional :log function, accepted (and
2820 failed) connections may be logged in the server process' buffer.
2822 The original argument list, modified with the actual connection
2823 information, is available via the `process-contact' function.
2825 usage: (make-network-process &rest ARGS) */)
2826 (nargs, args)
2827 int nargs;
2828 Lisp_Object *args;
2830 Lisp_Object proc;
2831 Lisp_Object contact;
2832 struct Lisp_Process *p;
2833 #ifdef HAVE_GETADDRINFO
2834 struct addrinfo ai, *res, *lres;
2835 struct addrinfo hints;
2836 char *portstring, portbuf[128];
2837 #else /* HAVE_GETADDRINFO */
2838 struct _emacs_addrinfo
2840 int ai_family;
2841 int ai_socktype;
2842 int ai_protocol;
2843 int ai_addrlen;
2844 struct sockaddr *ai_addr;
2845 struct _emacs_addrinfo *ai_next;
2846 } ai, *res, *lres;
2847 #endif /* HAVE_GETADDRINFO */
2848 struct sockaddr_in address_in;
2849 #ifdef HAVE_LOCAL_SOCKETS
2850 struct sockaddr_un address_un;
2851 #endif
2852 int port;
2853 int ret = 0;
2854 int xerrno = 0;
2855 int s = -1, outch, inch;
2856 struct gcpro gcpro1;
2857 int count = SPECPDL_INDEX ();
2858 int count1;
2859 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2860 Lisp_Object tem;
2861 Lisp_Object name, buffer, host, service, address;
2862 Lisp_Object filter, sentinel;
2863 int is_non_blocking_client = 0;
2864 int is_server = 0, backlog = 5;
2865 int socktype;
2866 int family = -1;
2868 if (nargs == 0)
2869 return Qnil;
2871 /* Save arguments for process-contact and clone-process. */
2872 contact = Flist (nargs, args);
2873 GCPRO1 (contact);
2875 #ifdef WINDOWSNT
2876 /* Ensure socket support is loaded if available. */
2877 init_winsock (TRUE);
2878 #endif
2880 /* :type TYPE (nil: stream, datagram */
2881 tem = Fplist_get (contact, QCtype);
2882 if (NILP (tem))
2883 socktype = SOCK_STREAM;
2884 #ifdef DATAGRAM_SOCKETS
2885 else if (EQ (tem, Qdatagram))
2886 socktype = SOCK_DGRAM;
2887 #endif
2888 else
2889 error ("Unsupported connection type");
2891 /* :server BOOL */
2892 tem = Fplist_get (contact, QCserver);
2893 if (!NILP (tem))
2895 /* Don't support network sockets when non-blocking mode is
2896 not available, since a blocked Emacs is not useful. */
2897 #if defined(TERM) || (!defined(O_NONBLOCK) && !defined(O_NDELAY))
2898 error ("Network servers not supported");
2899 #else
2900 is_server = 1;
2901 if (INTEGERP (tem))
2902 backlog = XINT (tem);
2903 #endif
2906 /* Make QCaddress an alias for :local (server) or :remote (client). */
2907 QCaddress = is_server ? QClocal : QCremote;
2909 /* :nowait BOOL */
2910 if (!is_server && socktype == SOCK_STREAM
2911 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2913 #ifndef NON_BLOCKING_CONNECT
2914 error ("Non-blocking connect not supported");
2915 #else
2916 is_non_blocking_client = 1;
2917 #endif
2920 name = Fplist_get (contact, QCname);
2921 buffer = Fplist_get (contact, QCbuffer);
2922 filter = Fplist_get (contact, QCfilter);
2923 sentinel = Fplist_get (contact, QCsentinel);
2925 CHECK_STRING (name);
2927 #ifdef TERM
2928 /* Let's handle TERM before things get complicated ... */
2929 host = Fplist_get (contact, QChost);
2930 CHECK_STRING (host);
2932 service = Fplist_get (contact, QCservice);
2933 if (INTEGERP (service))
2934 port = htons ((unsigned short) XINT (service));
2935 else
2937 struct servent *svc_info;
2938 CHECK_STRING (service);
2939 svc_info = getservbyname (SDATA (service), "tcp");
2940 if (svc_info == 0)
2941 error ("Unknown service: %s", SDATA (service));
2942 port = svc_info->s_port;
2945 s = connect_server (0);
2946 if (s < 0)
2947 report_file_error ("error creating socket", Fcons (name, Qnil));
2948 send_command (s, C_PORT, 0, "%s:%d", SDATA (host), ntohs (port));
2949 send_command (s, C_DUMB, 1, 0);
2951 #else /* not TERM */
2953 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2954 ai.ai_socktype = socktype;
2955 ai.ai_protocol = 0;
2956 ai.ai_next = NULL;
2957 res = &ai;
2959 /* :local ADDRESS or :remote ADDRESS */
2960 address = Fplist_get (contact, QCaddress);
2961 if (!NILP (address))
2963 host = service = Qnil;
2965 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2966 error ("Malformed :address");
2967 ai.ai_family = family;
2968 ai.ai_addr = alloca (ai.ai_addrlen);
2969 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2970 goto open_socket;
2973 /* :family FAMILY -- nil (for Inet), local, or integer. */
2974 tem = Fplist_get (contact, QCfamily);
2975 if (NILP (tem))
2977 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
2978 family = AF_UNSPEC;
2979 #else
2980 family = AF_INET;
2981 #endif
2983 #ifdef HAVE_LOCAL_SOCKETS
2984 else if (EQ (tem, Qlocal))
2985 family = AF_LOCAL;
2986 #endif
2987 #ifdef AF_INET6
2988 else if (EQ (tem, Qipv6))
2989 family = AF_INET6;
2990 #endif
2991 else if (EQ (tem, Qipv4))
2992 family = AF_INET;
2993 else if (INTEGERP (tem))
2994 family = XINT (tem);
2995 else
2996 error ("Unknown address family");
2998 ai.ai_family = family;
3000 /* :service SERVICE -- string, integer (port number), or t (random port). */
3001 service = Fplist_get (contact, QCservice);
3003 #ifdef HAVE_LOCAL_SOCKETS
3004 if (family == AF_LOCAL)
3006 /* Host is not used. */
3007 host = Qnil;
3008 CHECK_STRING (service);
3009 bzero (&address_un, sizeof address_un);
3010 address_un.sun_family = AF_LOCAL;
3011 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3012 ai.ai_addr = (struct sockaddr *) &address_un;
3013 ai.ai_addrlen = sizeof address_un;
3014 goto open_socket;
3016 #endif
3018 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3019 host = Fplist_get (contact, QChost);
3020 if (!NILP (host))
3022 if (EQ (host, Qlocal))
3023 host = build_string ("localhost");
3024 CHECK_STRING (host);
3027 /* Slow down polling to every ten seconds.
3028 Some kernels have a bug which causes retrying connect to fail
3029 after a connect. Polling can interfere with gethostbyname too. */
3030 #ifdef POLL_FOR_INPUT
3031 if (socktype == SOCK_STREAM)
3033 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3034 bind_polling_period (10);
3036 #endif
3038 #ifdef HAVE_GETADDRINFO
3039 /* If we have a host, use getaddrinfo to resolve both host and service.
3040 Otherwise, use getservbyname to lookup the service. */
3041 if (!NILP (host))
3044 /* SERVICE can either be a string or int.
3045 Convert to a C string for later use by getaddrinfo. */
3046 if (EQ (service, Qt))
3047 portstring = "0";
3048 else if (INTEGERP (service))
3050 sprintf (portbuf, "%ld", (long) XINT (service));
3051 portstring = portbuf;
3053 else
3055 CHECK_STRING (service);
3056 portstring = SDATA (service);
3059 immediate_quit = 1;
3060 QUIT;
3061 memset (&hints, 0, sizeof (hints));
3062 hints.ai_flags = 0;
3063 hints.ai_family = family;
3064 hints.ai_socktype = socktype;
3065 hints.ai_protocol = 0;
3066 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3067 if (ret)
3068 #ifdef HAVE_GAI_STRERROR
3069 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3070 #else
3071 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3072 #endif
3073 immediate_quit = 0;
3075 goto open_socket;
3077 #endif /* HAVE_GETADDRINFO */
3079 /* We end up here if getaddrinfo is not defined, or in case no hostname
3080 has been specified (e.g. for a local server process). */
3082 if (EQ (service, Qt))
3083 port = 0;
3084 else if (INTEGERP (service))
3085 port = htons ((unsigned short) XINT (service));
3086 else
3088 struct servent *svc_info;
3089 CHECK_STRING (service);
3090 svc_info = getservbyname (SDATA (service),
3091 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3092 if (svc_info == 0)
3093 error ("Unknown service: %s", SDATA (service));
3094 port = svc_info->s_port;
3097 bzero (&address_in, sizeof address_in);
3098 address_in.sin_family = family;
3099 address_in.sin_addr.s_addr = INADDR_ANY;
3100 address_in.sin_port = port;
3102 #ifndef HAVE_GETADDRINFO
3103 if (!NILP (host))
3105 struct hostent *host_info_ptr;
3107 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3108 as it may `hang' Emacs for a very long time. */
3109 immediate_quit = 1;
3110 QUIT;
3111 host_info_ptr = gethostbyname (SDATA (host));
3112 immediate_quit = 0;
3114 if (host_info_ptr)
3116 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3117 host_info_ptr->h_length);
3118 family = host_info_ptr->h_addrtype;
3119 address_in.sin_family = family;
3121 else
3122 /* Attempt to interpret host as numeric inet address */
3124 IN_ADDR numeric_addr;
3125 numeric_addr = inet_addr ((char *) SDATA (host));
3126 if (NUMERIC_ADDR_ERROR)
3127 error ("Unknown host \"%s\"", SDATA (host));
3129 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3130 sizeof (address_in.sin_addr));
3134 #endif /* not HAVE_GETADDRINFO */
3136 ai.ai_family = family;
3137 ai.ai_addr = (struct sockaddr *) &address_in;
3138 ai.ai_addrlen = sizeof address_in;
3140 open_socket:
3142 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
3143 when connect is interrupted. So let's not let it get interrupted.
3144 Note we do not turn off polling, because polling is only used
3145 when not interrupt_input, and thus not normally used on the systems
3146 which have this bug. On systems which use polling, there's no way
3147 to quit if polling is turned off. */
3148 if (interrupt_input
3149 && !is_server && socktype == SOCK_STREAM)
3151 /* Comment from KFS: The original open-network-stream code
3152 didn't unwind protect this, but it seems like the proper
3153 thing to do. In any case, I don't see how it could harm to
3154 do this -- and it makes cleanup (using unbind_to) easier. */
3155 record_unwind_protect (unwind_request_sigio, Qnil);
3156 unrequest_sigio ();
3159 /* Do this in case we never enter the for-loop below. */
3160 count1 = SPECPDL_INDEX ();
3161 s = -1;
3163 for (lres = res; lres; lres = lres->ai_next)
3165 int optn, optbits;
3167 retry_connect:
3169 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3170 if (s < 0)
3172 xerrno = errno;
3173 continue;
3176 #ifdef DATAGRAM_SOCKETS
3177 if (!is_server && socktype == SOCK_DGRAM)
3178 break;
3179 #endif /* DATAGRAM_SOCKETS */
3181 #ifdef NON_BLOCKING_CONNECT
3182 if (is_non_blocking_client)
3184 #ifdef O_NONBLOCK
3185 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3186 #else
3187 ret = fcntl (s, F_SETFL, O_NDELAY);
3188 #endif
3189 if (ret < 0)
3191 xerrno = errno;
3192 emacs_close (s);
3193 s = -1;
3194 continue;
3197 #endif
3199 /* Make us close S if quit. */
3200 record_unwind_protect (close_file_unwind, make_number (s));
3202 /* Parse network options in the arg list.
3203 We simply ignore anything which isn't a known option (including other keywords).
3204 An error is signalled if setting a known option fails. */
3205 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3206 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3208 if (is_server)
3210 /* Configure as a server socket. */
3212 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3213 explicit :reuseaddr key to override this. */
3214 #ifdef HAVE_LOCAL_SOCKETS
3215 if (family != AF_LOCAL)
3216 #endif
3217 if (!(optbits & (1 << OPIX_REUSEADDR)))
3219 int optval = 1;
3220 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3221 report_file_error ("Cannot set reuse option on server socket", Qnil);
3224 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3225 report_file_error ("Cannot bind server socket", Qnil);
3227 #ifdef HAVE_GETSOCKNAME
3228 if (EQ (service, Qt))
3230 struct sockaddr_in sa1;
3231 int len1 = sizeof (sa1);
3232 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3234 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3235 service = make_number (ntohs (sa1.sin_port));
3236 contact = Fplist_put (contact, QCservice, service);
3239 #endif
3241 if (socktype == SOCK_STREAM && listen (s, backlog))
3242 report_file_error ("Cannot listen on server socket", Qnil);
3244 break;
3247 immediate_quit = 1;
3248 QUIT;
3250 /* This turns off all alarm-based interrupts; the
3251 bind_polling_period call above doesn't always turn all the
3252 short-interval ones off, especially if interrupt_input is
3253 set.
3255 It'd be nice to be able to control the connect timeout
3256 though. Would non-blocking connect calls be portable?
3258 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3260 turn_on_atimers (0);
3262 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3263 xerrno = errno;
3265 turn_on_atimers (1);
3267 if (ret == 0 || xerrno == EISCONN)
3269 /* The unwind-protect will be discarded afterwards.
3270 Likewise for immediate_quit. */
3271 break;
3274 #ifdef NON_BLOCKING_CONNECT
3275 #ifdef EINPROGRESS
3276 if (is_non_blocking_client && xerrno == EINPROGRESS)
3277 break;
3278 #else
3279 #ifdef EWOULDBLOCK
3280 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3281 break;
3282 #endif
3283 #endif
3284 #endif
3286 immediate_quit = 0;
3288 /* Discard the unwind protect closing S. */
3289 specpdl_ptr = specpdl + count1;
3290 emacs_close (s);
3291 s = -1;
3293 if (xerrno == EINTR)
3294 goto retry_connect;
3297 if (s >= 0)
3299 #ifdef DATAGRAM_SOCKETS
3300 if (socktype == SOCK_DGRAM)
3302 if (datagram_address[s].sa)
3303 abort ();
3304 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3305 datagram_address[s].len = lres->ai_addrlen;
3306 if (is_server)
3308 Lisp_Object remote;
3309 bzero (datagram_address[s].sa, lres->ai_addrlen);
3310 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3312 int rfamily, rlen;
3313 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3314 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3315 conv_lisp_to_sockaddr (rfamily, remote,
3316 datagram_address[s].sa, rlen);
3319 else
3320 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3322 #endif
3323 contact = Fplist_put (contact, QCaddress,
3324 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3325 #ifdef HAVE_GETSOCKNAME
3326 if (!is_server)
3328 struct sockaddr_in sa1;
3329 int len1 = sizeof (sa1);
3330 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3331 contact = Fplist_put (contact, QClocal,
3332 conv_sockaddr_to_lisp (&sa1, len1));
3334 #endif
3337 #ifdef HAVE_GETADDRINFO
3338 if (res != &ai)
3339 freeaddrinfo (res);
3340 #endif
3342 immediate_quit = 0;
3344 /* Discard the unwind protect for closing S, if any. */
3345 specpdl_ptr = specpdl + count1;
3347 /* Unwind bind_polling_period and request_sigio. */
3348 unbind_to (count, Qnil);
3350 if (s < 0)
3352 /* If non-blocking got this far - and failed - assume non-blocking is
3353 not supported after all. This is probably a wrong assumption, but
3354 the normal blocking calls to open-network-stream handles this error
3355 better. */
3356 if (is_non_blocking_client)
3357 return Qnil;
3359 errno = xerrno;
3360 if (is_server)
3361 report_file_error ("make server process failed", contact);
3362 else
3363 report_file_error ("make client process failed", contact);
3366 #endif /* not TERM */
3368 inch = s;
3369 outch = s;
3371 if (!NILP (buffer))
3372 buffer = Fget_buffer_create (buffer);
3373 proc = make_process (name);
3375 chan_process[inch] = proc;
3377 #ifdef O_NONBLOCK
3378 fcntl (inch, F_SETFL, O_NONBLOCK);
3379 #else
3380 #ifdef O_NDELAY
3381 fcntl (inch, F_SETFL, O_NDELAY);
3382 #endif
3383 #endif
3385 p = XPROCESS (proc);
3387 p->childp = contact;
3388 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3390 p->buffer = buffer;
3391 p->sentinel = sentinel;
3392 p->filter = filter;
3393 p->filter_multibyte = buffer_defaults.enable_multibyte_characters;
3394 /* Override the above only if :filter-multibyte is specified. */
3395 if (! NILP (Fplist_member (contact, QCfilter_multibyte)))
3396 p->filter_multibyte = Fplist_get (contact, QCfilter_multibyte);
3397 p->log = Fplist_get (contact, QClog);
3398 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3399 p->kill_without_query = Qt;
3400 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3401 p->command = Qt;
3402 p->pid = 0;
3403 XSETINT (p->infd, inch);
3404 XSETINT (p->outfd, outch);
3405 if (is_server && socktype == SOCK_STREAM)
3406 p->status = Qlisten;
3408 /* Make the process marker point into the process buffer (if any). */
3409 if (BUFFERP (buffer))
3410 set_marker_both (p->mark, buffer,
3411 BUF_ZV (XBUFFER (buffer)),
3412 BUF_ZV_BYTE (XBUFFER (buffer)));
3414 #ifdef NON_BLOCKING_CONNECT
3415 if (is_non_blocking_client)
3417 /* We may get here if connect did succeed immediately. However,
3418 in that case, we still need to signal this like a non-blocking
3419 connection. */
3420 p->status = Qconnect;
3421 if (!FD_ISSET (inch, &connect_wait_mask))
3423 FD_SET (inch, &connect_wait_mask);
3424 num_pending_connects++;
3427 else
3428 #endif
3429 /* A server may have a client filter setting of Qt, but it must
3430 still listen for incoming connects unless it is stopped. */
3431 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3432 || (EQ (p->status, Qlisten) && NILP (p->command)))
3434 FD_SET (inch, &input_wait_mask);
3435 FD_SET (inch, &non_keyboard_wait_mask);
3438 if (inch > max_process_desc)
3439 max_process_desc = inch;
3441 tem = Fplist_member (contact, QCcoding);
3442 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3443 tem = Qnil; /* No error message (too late!). */
3446 /* Setup coding systems for communicating with the network stream. */
3447 struct gcpro gcpro1;
3448 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3449 Lisp_Object coding_systems = Qt;
3450 Lisp_Object args[5], val;
3452 if (!NILP (tem))
3454 val = XCAR (XCDR (tem));
3455 if (CONSP (val))
3456 val = XCAR (val);
3458 else if (!NILP (Vcoding_system_for_read))
3459 val = Vcoding_system_for_read;
3460 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3461 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3462 /* We dare not decode end-of-line format by setting VAL to
3463 Qraw_text, because the existing Emacs Lisp libraries
3464 assume that they receive bare code including a sequene of
3465 CR LF. */
3466 val = Qnil;
3467 else
3469 if (NILP (host) || NILP (service))
3470 coding_systems = Qnil;
3471 else
3473 args[0] = Qopen_network_stream, args[1] = name,
3474 args[2] = buffer, args[3] = host, args[4] = service;
3475 GCPRO1 (proc);
3476 coding_systems = Ffind_operation_coding_system (5, args);
3477 UNGCPRO;
3479 if (CONSP (coding_systems))
3480 val = XCAR (coding_systems);
3481 else if (CONSP (Vdefault_process_coding_system))
3482 val = XCAR (Vdefault_process_coding_system);
3483 else
3484 val = Qnil;
3486 p->decode_coding_system = val;
3488 if (!NILP (tem))
3490 val = XCAR (XCDR (tem));
3491 if (CONSP (val))
3492 val = XCDR (val);
3494 else if (!NILP (Vcoding_system_for_write))
3495 val = Vcoding_system_for_write;
3496 else if (NILP (current_buffer->enable_multibyte_characters))
3497 val = Qnil;
3498 else
3500 if (EQ (coding_systems, Qt))
3502 if (NILP (host) || NILP (service))
3503 coding_systems = Qnil;
3504 else
3506 args[0] = Qopen_network_stream, args[1] = name,
3507 args[2] = buffer, args[3] = host, args[4] = service;
3508 GCPRO1 (proc);
3509 coding_systems = Ffind_operation_coding_system (5, args);
3510 UNGCPRO;
3513 if (CONSP (coding_systems))
3514 val = XCDR (coding_systems);
3515 else if (CONSP (Vdefault_process_coding_system))
3516 val = XCDR (Vdefault_process_coding_system);
3517 else
3518 val = Qnil;
3520 p->encode_coding_system = val;
3522 setup_process_coding_systems (proc);
3524 p->decoding_buf = make_uninit_string (0);
3525 p->decoding_carryover = make_number (0);
3526 p->encoding_buf = make_uninit_string (0);
3527 p->encoding_carryover = make_number (0);
3529 p->inherit_coding_system_flag
3530 = (!NILP (tem) || NILP (buffer) || !inherit_process_coding_system
3531 ? Qnil : Qt);
3533 UNGCPRO;
3534 return proc;
3536 #endif /* HAVE_SOCKETS */
3539 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3541 #ifdef SIOCGIFCONF
3542 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3543 doc: /* Return an alist of all network interfaces and their network address.
3544 Each element is a cons, the car of which is a string containing the
3545 interface name, and the cdr is the network address in internal
3546 format; see the description of ADDRESS in `make-network-process'. */)
3549 struct ifconf ifconf;
3550 struct ifreq *ifreqs = NULL;
3551 int ifaces = 0;
3552 int buf_size, s;
3553 Lisp_Object res;
3555 s = socket (AF_INET, SOCK_STREAM, 0);
3556 if (s < 0)
3557 return Qnil;
3559 again:
3560 ifaces += 25;
3561 buf_size = ifaces * sizeof(ifreqs[0]);
3562 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3563 if (!ifreqs)
3565 close (s);
3566 return Qnil;
3569 ifconf.ifc_len = buf_size;
3570 ifconf.ifc_req = ifreqs;
3571 if (ioctl (s, SIOCGIFCONF, &ifconf))
3573 close (s);
3574 return Qnil;
3577 if (ifconf.ifc_len == buf_size)
3578 goto again;
3580 close (s);
3581 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3583 res = Qnil;
3584 while (--ifaces >= 0)
3586 struct ifreq *ifq = &ifreqs[ifaces];
3587 char namebuf[sizeof (ifq->ifr_name) + 1];
3588 if (ifq->ifr_addr.sa_family != AF_INET)
3589 continue;
3590 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3591 namebuf[sizeof (ifq->ifr_name)] = 0;
3592 res = Fcons (Fcons (build_string (namebuf),
3593 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3594 sizeof (struct sockaddr))),
3595 res);
3598 return res;
3600 #endif /* SIOCGIFCONF */
3602 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3604 struct ifflag_def {
3605 int flag_bit;
3606 char *flag_sym;
3609 static struct ifflag_def ifflag_table[] = {
3610 #ifdef IFF_UP
3611 { IFF_UP, "up" },
3612 #endif
3613 #ifdef IFF_BROADCAST
3614 { IFF_BROADCAST, "broadcast" },
3615 #endif
3616 #ifdef IFF_DEBUG
3617 { IFF_DEBUG, "debug" },
3618 #endif
3619 #ifdef IFF_LOOPBACK
3620 { IFF_LOOPBACK, "loopback" },
3621 #endif
3622 #ifdef IFF_POINTOPOINT
3623 { IFF_POINTOPOINT, "pointopoint" },
3624 #endif
3625 #ifdef IFF_RUNNING
3626 { IFF_RUNNING, "running" },
3627 #endif
3628 #ifdef IFF_NOARP
3629 { IFF_NOARP, "noarp" },
3630 #endif
3631 #ifdef IFF_PROMISC
3632 { IFF_PROMISC, "promisc" },
3633 #endif
3634 #ifdef IFF_NOTRAILERS
3635 { IFF_NOTRAILERS, "notrailers" },
3636 #endif
3637 #ifdef IFF_ALLMULTI
3638 { IFF_ALLMULTI, "allmulti" },
3639 #endif
3640 #ifdef IFF_MASTER
3641 { IFF_MASTER, "master" },
3642 #endif
3643 #ifdef IFF_SLAVE
3644 { IFF_SLAVE, "slave" },
3645 #endif
3646 #ifdef IFF_MULTICAST
3647 { IFF_MULTICAST, "multicast" },
3648 #endif
3649 #ifdef IFF_PORTSEL
3650 { IFF_PORTSEL, "portsel" },
3651 #endif
3652 #ifdef IFF_AUTOMEDIA
3653 { IFF_AUTOMEDIA, "automedia" },
3654 #endif
3655 #ifdef IFF_DYNAMIC
3656 { IFF_DYNAMIC, "dynamic" },
3657 #endif
3658 #ifdef IFF_OACTIVE
3659 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3660 #endif
3661 #ifdef IFF_SIMPLEX
3662 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3663 #endif
3664 #ifdef IFF_LINK0
3665 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3666 #endif
3667 #ifdef IFF_LINK1
3668 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3669 #endif
3670 #ifdef IFF_LINK2
3671 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3672 #endif
3673 { 0, 0 }
3676 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3677 doc: /* Return information about network interface named IFNAME.
3678 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3679 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3680 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3681 FLAGS is the current flags of the interface. */)
3682 (ifname)
3683 Lisp_Object ifname;
3685 struct ifreq rq;
3686 Lisp_Object res = Qnil;
3687 Lisp_Object elt;
3688 int s;
3689 int any = 0;
3691 CHECK_STRING (ifname);
3693 bzero (rq.ifr_name, sizeof rq.ifr_name);
3694 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3696 s = socket (AF_INET, SOCK_STREAM, 0);
3697 if (s < 0)
3698 return Qnil;
3700 elt = Qnil;
3701 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3702 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3704 int flags = rq.ifr_flags;
3705 struct ifflag_def *fp;
3706 int fnum;
3708 any++;
3709 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3711 if (flags & fp->flag_bit)
3713 elt = Fcons (intern (fp->flag_sym), elt);
3714 flags -= fp->flag_bit;
3717 for (fnum = 0; flags && fnum < 32; fnum++)
3719 if (flags & (1 << fnum))
3721 elt = Fcons (make_number (fnum), elt);
3725 #endif
3726 res = Fcons (elt, res);
3728 elt = Qnil;
3729 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3730 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3732 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3733 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3734 int n;
3736 any++;
3737 for (n = 0; n < 6; n++)
3738 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3739 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3741 #endif
3742 res = Fcons (elt, res);
3744 elt = Qnil;
3745 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3746 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3748 any++;
3749 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3750 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3751 #else
3752 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3753 #endif
3755 #endif
3756 res = Fcons (elt, res);
3758 elt = Qnil;
3759 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3760 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3762 any++;
3763 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3765 #endif
3766 res = Fcons (elt, res);
3768 elt = Qnil;
3769 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3770 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3772 any++;
3773 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3775 #endif
3776 res = Fcons (elt, res);
3778 close (s);
3780 return any ? res : Qnil;
3782 #endif
3783 #endif /* HAVE_SOCKETS */
3785 /* Turn off input and output for process PROC. */
3787 void
3788 deactivate_process (proc)
3789 Lisp_Object proc;
3791 register int inchannel, outchannel;
3792 register struct Lisp_Process *p = XPROCESS (proc);
3794 inchannel = XINT (p->infd);
3795 outchannel = XINT (p->outfd);
3797 #ifdef ADAPTIVE_READ_BUFFERING
3798 if (XINT (p->read_output_delay) > 0)
3800 if (--process_output_delay_count < 0)
3801 process_output_delay_count = 0;
3802 XSETINT (p->read_output_delay, 0);
3803 p->read_output_skip = Qnil;
3805 #endif
3807 if (inchannel >= 0)
3809 /* Beware SIGCHLD hereabouts. */
3810 flush_pending_output (inchannel);
3811 #ifdef VMS
3813 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
3814 sys$dassgn (outchannel);
3815 vs = get_vms_process_pointer (p->pid);
3816 if (vs)
3817 give_back_vms_process_stuff (vs);
3819 #else
3820 emacs_close (inchannel);
3821 if (outchannel >= 0 && outchannel != inchannel)
3822 emacs_close (outchannel);
3823 #endif
3825 XSETINT (p->infd, -1);
3826 XSETINT (p->outfd, -1);
3827 #ifdef DATAGRAM_SOCKETS
3828 if (DATAGRAM_CHAN_P (inchannel))
3830 xfree (datagram_address[inchannel].sa);
3831 datagram_address[inchannel].sa = 0;
3832 datagram_address[inchannel].len = 0;
3834 #endif
3835 chan_process[inchannel] = Qnil;
3836 FD_CLR (inchannel, &input_wait_mask);
3837 FD_CLR (inchannel, &non_keyboard_wait_mask);
3838 #ifdef NON_BLOCKING_CONNECT
3839 if (FD_ISSET (inchannel, &connect_wait_mask))
3841 FD_CLR (inchannel, &connect_wait_mask);
3842 if (--num_pending_connects < 0)
3843 abort ();
3845 #endif
3846 if (inchannel == max_process_desc)
3848 int i;
3849 /* We just closed the highest-numbered process input descriptor,
3850 so recompute the highest-numbered one now. */
3851 max_process_desc = 0;
3852 for (i = 0; i < MAXDESC; i++)
3853 if (!NILP (chan_process[i]))
3854 max_process_desc = i;
3859 /* Close all descriptors currently in use for communication
3860 with subprocess. This is used in a newly-forked subprocess
3861 to get rid of irrelevant descriptors. */
3863 void
3864 close_process_descs ()
3866 #ifndef WINDOWSNT
3867 int i;
3868 for (i = 0; i < MAXDESC; i++)
3870 Lisp_Object process;
3871 process = chan_process[i];
3872 if (!NILP (process))
3874 int in = XINT (XPROCESS (process)->infd);
3875 int out = XINT (XPROCESS (process)->outfd);
3876 if (in >= 0)
3877 emacs_close (in);
3878 if (out >= 0 && in != out)
3879 emacs_close (out);
3882 #endif
3885 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3886 0, 4, 0,
3887 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3888 It is read into the process' buffers or given to their filter functions.
3889 Non-nil arg PROCESS means do not return until some output has been received
3890 from PROCESS.
3892 Non-nil second arg SECONDS and third arg MILLISEC are number of
3893 seconds and milliseconds to wait; return after that much time whether
3894 or not there is input. If SECONDS is a floating point number,
3895 it specifies a fractional number of seconds to wait.
3897 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3898 from PROCESS, suspending reading output from other processes.
3899 If JUST-THIS-ONE is an integer, don't run any timers either.
3900 Return non-nil iff we received any output before the timeout expired. */)
3901 (process, seconds, millisec, just_this_one)
3902 register Lisp_Object process, seconds, millisec, just_this_one;
3904 int secs, usecs = 0;
3906 if (! NILP (process))
3907 CHECK_PROCESS (process);
3908 else
3909 just_this_one = Qnil;
3911 if (!NILP (seconds))
3913 if (INTEGERP (seconds))
3914 secs = XINT (seconds);
3915 else if (FLOATP (seconds))
3917 double timeout = XFLOAT_DATA (seconds);
3918 secs = (int) timeout;
3919 usecs = (int) ((timeout - (double) secs) * 1000000);
3921 else
3922 wrong_type_argument (Qnumberp, seconds);
3924 if (INTEGERP (millisec))
3926 int carry;
3927 usecs += XINT (millisec) * 1000;
3928 carry = usecs / 1000000;
3929 secs += carry;
3930 if ((usecs -= carry * 1000000) < 0)
3932 secs--;
3933 usecs += 1000000;
3937 if (secs < 0 || (secs == 0 && usecs == 0))
3938 secs = -1, usecs = 0;
3940 else
3941 secs = NILP (process) ? -1 : 0;
3943 return
3944 (wait_reading_process_output (secs, usecs, 0, 0,
3945 Qnil,
3946 !NILP (process) ? XPROCESS (process) : NULL,
3947 NILP (just_this_one) ? 0 :
3948 !INTEGERP (just_this_one) ? 1 : -1)
3949 ? Qt : Qnil);
3952 /* Accept a connection for server process SERVER on CHANNEL. */
3954 static int connect_counter = 0;
3956 static void
3957 server_accept_connection (server, channel)
3958 Lisp_Object server;
3959 int channel;
3961 Lisp_Object proc, caller, name, buffer;
3962 Lisp_Object contact, host, service;
3963 struct Lisp_Process *ps= XPROCESS (server);
3964 struct Lisp_Process *p;
3965 int s;
3966 union u_sockaddr {
3967 struct sockaddr sa;
3968 struct sockaddr_in in;
3969 #ifdef AF_INET6
3970 struct sockaddr_in6 in6;
3971 #endif
3972 #ifdef HAVE_LOCAL_SOCKETS
3973 struct sockaddr_un un;
3974 #endif
3975 } saddr;
3976 int len = sizeof saddr;
3978 s = accept (channel, &saddr.sa, &len);
3980 if (s < 0)
3982 int code = errno;
3984 if (code == EAGAIN)
3985 return;
3986 #ifdef EWOULDBLOCK
3987 if (code == EWOULDBLOCK)
3988 return;
3989 #endif
3991 if (!NILP (ps->log))
3992 call3 (ps->log, server, Qnil,
3993 concat3 (build_string ("accept failed with code"),
3994 Fnumber_to_string (make_number (code)),
3995 build_string ("\n")));
3996 return;
3999 connect_counter++;
4001 /* Setup a new process to handle the connection. */
4003 /* Generate a unique identification of the caller, and build contact
4004 information for this process. */
4005 host = Qt;
4006 service = Qnil;
4007 switch (saddr.sa.sa_family)
4009 case AF_INET:
4011 Lisp_Object args[5];
4012 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4013 args[0] = build_string ("%d.%d.%d.%d");
4014 args[1] = make_number (*ip++);
4015 args[2] = make_number (*ip++);
4016 args[3] = make_number (*ip++);
4017 args[4] = make_number (*ip++);
4018 host = Fformat (5, args);
4019 service = make_number (ntohs (saddr.in.sin_port));
4021 args[0] = build_string (" <%s:%d>");
4022 args[1] = host;
4023 args[2] = service;
4024 caller = Fformat (3, args);
4026 break;
4028 #ifdef AF_INET6
4029 case AF_INET6:
4031 Lisp_Object args[9];
4032 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4033 int i;
4034 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4035 for (i = 0; i < 8; i++)
4036 args[i+1] = make_number (ntohs(ip6[i]));
4037 host = Fformat (9, args);
4038 service = make_number (ntohs (saddr.in.sin_port));
4040 args[0] = build_string (" <[%s]:%d>");
4041 args[1] = host;
4042 args[2] = service;
4043 caller = Fformat (3, args);
4045 break;
4046 #endif
4048 #ifdef HAVE_LOCAL_SOCKETS
4049 case AF_LOCAL:
4050 #endif
4051 default:
4052 caller = Fnumber_to_string (make_number (connect_counter));
4053 caller = concat3 (build_string (" <*"), caller, build_string ("*>"));
4054 break;
4057 /* Create a new buffer name for this process if it doesn't have a
4058 filter. The new buffer name is based on the buffer name or
4059 process name of the server process concatenated with the caller
4060 identification. */
4062 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4063 buffer = Qnil;
4064 else
4066 buffer = ps->buffer;
4067 if (!NILP (buffer))
4068 buffer = Fbuffer_name (buffer);
4069 else
4070 buffer = ps->name;
4071 if (!NILP (buffer))
4073 buffer = concat2 (buffer, caller);
4074 buffer = Fget_buffer_create (buffer);
4078 /* Generate a unique name for the new server process. Combine the
4079 server process name with the caller identification. */
4081 name = concat2 (ps->name, caller);
4082 proc = make_process (name);
4084 chan_process[s] = proc;
4086 #ifdef O_NONBLOCK
4087 fcntl (s, F_SETFL, O_NONBLOCK);
4088 #else
4089 #ifdef O_NDELAY
4090 fcntl (s, F_SETFL, O_NDELAY);
4091 #endif
4092 #endif
4094 p = XPROCESS (proc);
4096 /* Build new contact information for this setup. */
4097 contact = Fcopy_sequence (ps->childp);
4098 contact = Fplist_put (contact, QCserver, Qnil);
4099 contact = Fplist_put (contact, QChost, host);
4100 if (!NILP (service))
4101 contact = Fplist_put (contact, QCservice, service);
4102 contact = Fplist_put (contact, QCremote,
4103 conv_sockaddr_to_lisp (&saddr.sa, len));
4104 #ifdef HAVE_GETSOCKNAME
4105 len = sizeof saddr;
4106 if (getsockname (s, &saddr.sa, &len) == 0)
4107 contact = Fplist_put (contact, QClocal,
4108 conv_sockaddr_to_lisp (&saddr.sa, len));
4109 #endif
4111 p->childp = contact;
4112 p->plist = Fcopy_sequence (ps->plist);
4114 p->buffer = buffer;
4115 p->sentinel = ps->sentinel;
4116 p->filter = ps->filter;
4117 p->command = Qnil;
4118 p->pid = 0;
4119 XSETINT (p->infd, s);
4120 XSETINT (p->outfd, s);
4121 p->status = Qrun;
4123 /* Client processes for accepted connections are not stopped initially. */
4124 if (!EQ (p->filter, Qt))
4126 FD_SET (s, &input_wait_mask);
4127 FD_SET (s, &non_keyboard_wait_mask);
4130 if (s > max_process_desc)
4131 max_process_desc = s;
4133 /* Setup coding system for new process based on server process.
4134 This seems to be the proper thing to do, as the coding system
4135 of the new process should reflect the settings at the time the
4136 server socket was opened; not the current settings. */
4138 p->decode_coding_system = ps->decode_coding_system;
4139 p->encode_coding_system = ps->encode_coding_system;
4140 setup_process_coding_systems (proc);
4142 p->decoding_buf = make_uninit_string (0);
4143 p->decoding_carryover = make_number (0);
4144 p->encoding_buf = make_uninit_string (0);
4145 p->encoding_carryover = make_number (0);
4147 p->inherit_coding_system_flag
4148 = (NILP (buffer) ? Qnil : ps->inherit_coding_system_flag);
4150 if (!NILP (ps->log))
4151 call3 (ps->log, server, proc,
4152 concat3 (build_string ("accept from "),
4153 (STRINGP (host) ? host : build_string ("-")),
4154 build_string ("\n")));
4156 if (!NILP (p->sentinel))
4157 exec_sentinel (proc,
4158 concat3 (build_string ("open from "),
4159 (STRINGP (host) ? host : build_string ("-")),
4160 build_string ("\n")));
4163 /* This variable is different from waiting_for_input in keyboard.c.
4164 It is used to communicate to a lisp process-filter/sentinel (via the
4165 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4166 for user-input when that process-filter was called.
4167 waiting_for_input cannot be used as that is by definition 0 when
4168 lisp code is being evalled.
4169 This is also used in record_asynch_buffer_change.
4170 For that purpose, this must be 0
4171 when not inside wait_reading_process_output. */
4172 static int waiting_for_user_input_p;
4174 static Lisp_Object
4175 wait_reading_process_output_unwind (data)
4176 Lisp_Object data;
4178 waiting_for_user_input_p = XINT (data);
4179 return Qnil;
4182 /* This is here so breakpoints can be put on it. */
4183 static void
4184 wait_reading_process_output_1 ()
4188 /* Use a wrapper around select to work around a bug in gdb 5.3.
4189 Normally, the wrapper is optimzed away by inlining.
4191 If emacs is stopped inside select, the gdb backtrace doesn't
4192 show the function which called select, so it is practically
4193 impossible to step through wait_reading_process_output. */
4195 #ifndef select
4196 static INLINE int
4197 select_wrapper (n, rfd, wfd, xfd, tmo)
4198 int n;
4199 SELECT_TYPE *rfd, *wfd, *xfd;
4200 EMACS_TIME *tmo;
4202 return select (n, rfd, wfd, xfd, tmo);
4204 #define select select_wrapper
4205 #endif
4207 /* Read and dispose of subprocess output while waiting for timeout to
4208 elapse and/or keyboard input to be available.
4210 TIME_LIMIT is:
4211 timeout in seconds, or
4212 zero for no limit, or
4213 -1 means gobble data immediately available but don't wait for any.
4215 MICROSECS is:
4216 an additional duration to wait, measured in microseconds.
4217 If this is nonzero and time_limit is 0, then the timeout
4218 consists of MICROSECS only.
4220 READ_KBD is a lisp value:
4221 0 to ignore keyboard input, or
4222 1 to return when input is available, or
4223 -1 meaning caller will actually read the input, so don't throw to
4224 the quit handler, or
4226 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4227 output that arrives.
4229 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4230 (and gobble terminal input into the buffer if any arrives).
4232 If WAIT_PROC is specified, wait until something arrives from that
4233 process. The return value is true iff we read some input from
4234 that process.
4236 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4237 (suspending output from other processes). A negative value
4238 means don't run any timers either.
4240 If WAIT_PROC is specified, then the function returns true iff we
4241 received input from that process before the timeout elapsed.
4242 Otherwise, return true iff we received input from any process. */
4245 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4246 wait_for_cell, wait_proc, just_wait_proc)
4247 int time_limit, microsecs, read_kbd, do_display;
4248 Lisp_Object wait_for_cell;
4249 struct Lisp_Process *wait_proc;
4250 int just_wait_proc;
4252 register int channel, nfds;
4253 SELECT_TYPE Available;
4254 #ifdef NON_BLOCKING_CONNECT
4255 SELECT_TYPE Connecting;
4256 int check_connect;
4257 #endif
4258 int check_delay, no_avail;
4259 int xerrno;
4260 Lisp_Object proc;
4261 EMACS_TIME timeout, end_time;
4262 int wait_channel = -1;
4263 int got_some_input = 0;
4264 int count = SPECPDL_INDEX ();
4266 FD_ZERO (&Available);
4267 #ifdef NON_BLOCKING_CONNECT
4268 FD_ZERO (&Connecting);
4269 #endif
4271 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4272 if (wait_proc != NULL)
4273 wait_channel = XINT (wait_proc->infd);
4275 record_unwind_protect (wait_reading_process_output_unwind,
4276 make_number (waiting_for_user_input_p));
4277 waiting_for_user_input_p = read_kbd;
4279 /* Since we may need to wait several times,
4280 compute the absolute time to return at. */
4281 if (time_limit || microsecs)
4283 EMACS_GET_TIME (end_time);
4284 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4285 EMACS_ADD_TIME (end_time, end_time, timeout);
4287 #ifdef POLL_INTERRUPTED_SYS_CALL
4288 /* AlainF 5-Jul-1996
4289 HP-UX 10.10 seem to have problems with signals coming in
4290 Causes "poll: interrupted system call" messages when Emacs is run
4291 in an X window
4292 Turn off periodic alarms (in case they are in use),
4293 and then turn off any other atimers. */
4294 stop_polling ();
4295 turn_on_atimers (0);
4296 #endif /* POLL_INTERRUPTED_SYS_CALL */
4298 while (1)
4300 int timeout_reduced_for_timers = 0;
4302 /* If calling from keyboard input, do not quit
4303 since we want to return C-g as an input character.
4304 Otherwise, do pending quit if requested. */
4305 if (read_kbd >= 0)
4306 QUIT;
4307 #ifdef SYNC_INPUT
4308 else if (interrupt_input_pending)
4309 handle_async_input ();
4310 #endif
4312 /* Exit now if the cell we're waiting for became non-nil. */
4313 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4314 break;
4316 /* Compute time from now till when time limit is up */
4317 /* Exit if already run out */
4318 if (time_limit == -1)
4320 /* -1 specified for timeout means
4321 gobble output available now
4322 but don't wait at all. */
4324 EMACS_SET_SECS_USECS (timeout, 0, 0);
4326 else if (time_limit || microsecs)
4328 EMACS_GET_TIME (timeout);
4329 EMACS_SUB_TIME (timeout, end_time, timeout);
4330 if (EMACS_TIME_NEG_P (timeout))
4331 break;
4333 else
4335 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4338 /* Normally we run timers here.
4339 But not if wait_for_cell; in those cases,
4340 the wait is supposed to be short,
4341 and those callers cannot handle running arbitrary Lisp code here. */
4342 if (NILP (wait_for_cell)
4343 && just_wait_proc >= 0)
4345 EMACS_TIME timer_delay;
4349 int old_timers_run = timers_run;
4350 struct buffer *old_buffer = current_buffer;
4352 timer_delay = timer_check (1);
4354 /* If a timer has run, this might have changed buffers
4355 an alike. Make read_key_sequence aware of that. */
4356 if (timers_run != old_timers_run
4357 && old_buffer != current_buffer
4358 && waiting_for_user_input_p == -1)
4359 record_asynch_buffer_change ();
4361 if (timers_run != old_timers_run && do_display)
4362 /* We must retry, since a timer may have requeued itself
4363 and that could alter the time_delay. */
4364 redisplay_preserve_echo_area (9);
4365 else
4366 break;
4368 while (!detect_input_pending ());
4370 /* If there is unread keyboard input, also return. */
4371 if (read_kbd != 0
4372 && requeued_events_pending_p ())
4373 break;
4375 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4377 EMACS_TIME difference;
4378 EMACS_SUB_TIME (difference, timer_delay, timeout);
4379 if (EMACS_TIME_NEG_P (difference))
4381 timeout = timer_delay;
4382 timeout_reduced_for_timers = 1;
4385 /* If time_limit is -1, we are not going to wait at all. */
4386 else if (time_limit != -1)
4388 /* This is so a breakpoint can be put here. */
4389 wait_reading_process_output_1 ();
4393 /* Cause C-g and alarm signals to take immediate action,
4394 and cause input available signals to zero out timeout.
4396 It is important that we do this before checking for process
4397 activity. If we get a SIGCHLD after the explicit checks for
4398 process activity, timeout is the only way we will know. */
4399 if (read_kbd < 0)
4400 set_waiting_for_input (&timeout);
4402 /* If status of something has changed, and no input is
4403 available, notify the user of the change right away. After
4404 this explicit check, we'll let the SIGCHLD handler zap
4405 timeout to get our attention. */
4406 if (update_tick != process_tick && do_display)
4408 SELECT_TYPE Atemp;
4409 #ifdef NON_BLOCKING_CONNECT
4410 SELECT_TYPE Ctemp;
4411 #endif
4413 Atemp = input_wait_mask;
4414 #if 0
4415 /* On Mac OS X 10.0, the SELECT system call always says input is
4416 present (for reading) at stdin, even when none is. This
4417 causes the call to SELECT below to return 1 and
4418 status_notify not to be called. As a result output of
4419 subprocesses are incorrectly discarded.
4421 FD_CLR (0, &Atemp);
4422 #endif
4423 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4425 EMACS_SET_SECS_USECS (timeout, 0, 0);
4426 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
4427 &Atemp,
4428 #ifdef NON_BLOCKING_CONNECT
4429 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4430 #else
4431 (SELECT_TYPE *)0,
4432 #endif
4433 (SELECT_TYPE *)0, &timeout)
4434 <= 0))
4436 /* It's okay for us to do this and then continue with
4437 the loop, since timeout has already been zeroed out. */
4438 clear_waiting_for_input ();
4439 status_notify (NULL);
4443 /* Don't wait for output from a non-running process. Just
4444 read whatever data has already been received. */
4445 if (wait_proc && wait_proc->raw_status_new)
4446 update_status (wait_proc);
4447 if (wait_proc
4448 && ! EQ (wait_proc->status, Qrun)
4449 && ! EQ (wait_proc->status, Qconnect))
4451 int nread, total_nread = 0;
4453 clear_waiting_for_input ();
4454 XSETPROCESS (proc, wait_proc);
4456 /* Read data from the process, until we exhaust it. */
4457 while (XINT (wait_proc->infd) >= 0)
4459 nread = read_process_output (proc, XINT (wait_proc->infd));
4461 if (nread == 0)
4462 break;
4464 if (0 < nread)
4465 total_nread += nread;
4466 #ifdef EIO
4467 else if (nread == -1 && EIO == errno)
4468 break;
4469 #endif
4470 #ifdef EAGAIN
4471 else if (nread == -1 && EAGAIN == errno)
4472 break;
4473 #endif
4474 #ifdef EWOULDBLOCK
4475 else if (nread == -1 && EWOULDBLOCK == errno)
4476 break;
4477 #endif
4479 if (total_nread > 0 && do_display)
4480 redisplay_preserve_echo_area (10);
4482 break;
4485 /* Wait till there is something to do */
4487 if (wait_proc && just_wait_proc)
4489 if (XINT (wait_proc->infd) < 0) /* Terminated */
4490 break;
4491 FD_SET (XINT (wait_proc->infd), &Available);
4492 check_delay = 0;
4493 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4495 else if (!NILP (wait_for_cell))
4497 Available = non_process_wait_mask;
4498 check_delay = 0;
4499 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4501 else
4503 if (! read_kbd)
4504 Available = non_keyboard_wait_mask;
4505 else
4506 Available = input_wait_mask;
4507 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4508 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4511 /* If frame size has changed or the window is newly mapped,
4512 redisplay now, before we start to wait. There is a race
4513 condition here; if a SIGIO arrives between now and the select
4514 and indicates that a frame is trashed, the select may block
4515 displaying a trashed screen. */
4516 if (frame_garbaged && do_display)
4518 clear_waiting_for_input ();
4519 redisplay_preserve_echo_area (11);
4520 if (read_kbd < 0)
4521 set_waiting_for_input (&timeout);
4524 no_avail = 0;
4525 if (read_kbd && detect_input_pending ())
4527 nfds = 0;
4528 no_avail = 1;
4530 else
4532 #ifdef NON_BLOCKING_CONNECT
4533 if (check_connect)
4534 Connecting = connect_wait_mask;
4535 #endif
4537 #ifdef ADAPTIVE_READ_BUFFERING
4538 /* Set the timeout for adaptive read buffering if any
4539 process has non-nil read_output_skip and non-zero
4540 read_output_delay, and we are not reading output for a
4541 specific wait_channel. It is not executed if
4542 Vprocess_adaptive_read_buffering is nil. */
4543 if (process_output_skip && check_delay > 0)
4545 int usecs = EMACS_USECS (timeout);
4546 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4547 usecs = READ_OUTPUT_DELAY_MAX;
4548 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4550 proc = chan_process[channel];
4551 if (NILP (proc))
4552 continue;
4553 /* Find minimum non-zero read_output_delay among the
4554 processes with non-nil read_output_skip. */
4555 if (XINT (XPROCESS (proc)->read_output_delay) > 0)
4557 check_delay--;
4558 if (NILP (XPROCESS (proc)->read_output_skip))
4559 continue;
4560 FD_CLR (channel, &Available);
4561 XPROCESS (proc)->read_output_skip = Qnil;
4562 if (XINT (XPROCESS (proc)->read_output_delay) < usecs)
4563 usecs = XINT (XPROCESS (proc)->read_output_delay);
4566 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4567 process_output_skip = 0;
4569 #endif
4571 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
4572 &Available,
4573 #ifdef NON_BLOCKING_CONNECT
4574 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4575 #else
4576 (SELECT_TYPE *)0,
4577 #endif
4578 (SELECT_TYPE *)0, &timeout);
4581 xerrno = errno;
4583 /* Make C-g and alarm signals set flags again */
4584 clear_waiting_for_input ();
4586 /* If we woke up due to SIGWINCH, actually change size now. */
4587 do_pending_window_change (0);
4589 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4590 /* We wanted the full specified time, so return now. */
4591 break;
4592 if (nfds < 0)
4594 if (xerrno == EINTR)
4595 no_avail = 1;
4596 #ifdef ultrix
4597 /* Ultrix select seems to return ENOMEM when it is
4598 interrupted. Treat it just like EINTR. Bleah. Note
4599 that we want to test for the "ultrix" CPP symbol, not
4600 "__ultrix__"; the latter is only defined under GCC, but
4601 not by DEC's bundled CC. -JimB */
4602 else if (xerrno == ENOMEM)
4603 no_avail = 1;
4604 #endif
4605 #ifdef ALLIANT
4606 /* This happens for no known reason on ALLIANT.
4607 I am guessing that this is the right response. -- RMS. */
4608 else if (xerrno == EFAULT)
4609 no_avail = 1;
4610 #endif
4611 else if (xerrno == EBADF)
4613 #ifdef AIX
4614 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4615 the child's closure of the pts gives the parent a SIGHUP, and
4616 the ptc file descriptor is automatically closed,
4617 yielding EBADF here or at select() call above.
4618 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4619 in m/ibmrt-aix.h), and here we just ignore the select error.
4620 Cleanup occurs c/o status_notify after SIGCLD. */
4621 no_avail = 1; /* Cannot depend on values returned */
4622 #else
4623 abort ();
4624 #endif
4626 else
4627 error ("select error: %s", emacs_strerror (xerrno));
4630 if (no_avail)
4632 FD_ZERO (&Available);
4633 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4636 #if defined(sun) && !defined(USG5_4)
4637 if (nfds > 0 && keyboard_bit_set (&Available)
4638 && interrupt_input)
4639 /* System sometimes fails to deliver SIGIO.
4641 David J. Mackenzie says that Emacs doesn't compile under
4642 Solaris if this code is enabled, thus the USG5_4 in the CPP
4643 conditional. "I haven't noticed any ill effects so far.
4644 If you find a Solaris expert somewhere, they might know
4645 better." */
4646 kill (getpid (), SIGIO);
4647 #endif
4649 #if 0 /* When polling is used, interrupt_input is 0,
4650 so get_input_pending should read the input.
4651 So this should not be needed. */
4652 /* If we are using polling for input,
4653 and we see input available, make it get read now.
4654 Otherwise it might not actually get read for a second.
4655 And on hpux, since we turn off polling in wait_reading_process_output,
4656 it might never get read at all if we don't spend much time
4657 outside of wait_reading_process_output. */
4658 if (read_kbd && interrupt_input
4659 && keyboard_bit_set (&Available)
4660 && input_polling_used ())
4661 kill (getpid (), SIGALRM);
4662 #endif
4664 /* Check for keyboard input */
4665 /* If there is any, return immediately
4666 to give it higher priority than subprocesses */
4668 if (read_kbd != 0)
4670 int old_timers_run = timers_run;
4671 struct buffer *old_buffer = current_buffer;
4672 int leave = 0;
4674 if (detect_input_pending_run_timers (do_display))
4676 swallow_events (do_display);
4677 if (detect_input_pending_run_timers (do_display))
4678 leave = 1;
4681 /* If a timer has run, this might have changed buffers
4682 an alike. Make read_key_sequence aware of that. */
4683 if (timers_run != old_timers_run
4684 && waiting_for_user_input_p == -1
4685 && old_buffer != current_buffer)
4686 record_asynch_buffer_change ();
4688 if (leave)
4689 break;
4692 /* If there is unread keyboard input, also return. */
4693 if (read_kbd != 0
4694 && requeued_events_pending_p ())
4695 break;
4697 /* If we are not checking for keyboard input now,
4698 do process events (but don't run any timers).
4699 This is so that X events will be processed.
4700 Otherwise they may have to wait until polling takes place.
4701 That would causes delays in pasting selections, for example.
4703 (We used to do this only if wait_for_cell.) */
4704 if (read_kbd == 0 && detect_input_pending ())
4706 swallow_events (do_display);
4707 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4708 if (detect_input_pending ())
4709 break;
4710 #endif
4713 /* Exit now if the cell we're waiting for became non-nil. */
4714 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4715 break;
4717 #ifdef SIGIO
4718 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4719 go read it. This can happen with X on BSD after logging out.
4720 In that case, there really is no input and no SIGIO,
4721 but select says there is input. */
4723 if (read_kbd && interrupt_input
4724 && keyboard_bit_set (&Available) && ! noninteractive)
4725 kill (getpid (), SIGIO);
4726 #endif
4728 if (! wait_proc)
4729 got_some_input |= nfds > 0;
4731 /* If checking input just got us a size-change event from X,
4732 obey it now if we should. */
4733 if (read_kbd || ! NILP (wait_for_cell))
4734 do_pending_window_change (0);
4736 /* Check for data from a process. */
4737 if (no_avail || nfds == 0)
4738 continue;
4740 /* Really FIRST_PROC_DESC should be 0 on Unix,
4741 but this is safer in the short run. */
4742 for (channel = 0; channel <= max_process_desc; channel++)
4744 if (FD_ISSET (channel, &Available)
4745 && FD_ISSET (channel, &non_keyboard_wait_mask))
4747 int nread;
4749 /* If waiting for this channel, arrange to return as
4750 soon as no more input to be processed. No more
4751 waiting. */
4752 if (wait_channel == channel)
4754 wait_channel = -1;
4755 time_limit = -1;
4756 got_some_input = 1;
4758 proc = chan_process[channel];
4759 if (NILP (proc))
4760 continue;
4762 /* If this is a server stream socket, accept connection. */
4763 if (EQ (XPROCESS (proc)->status, Qlisten))
4765 server_accept_connection (proc, channel);
4766 continue;
4769 /* Read data from the process, starting with our
4770 buffered-ahead character if we have one. */
4772 nread = read_process_output (proc, channel);
4773 if (nread > 0)
4775 /* Since read_process_output can run a filter,
4776 which can call accept-process-output,
4777 don't try to read from any other processes
4778 before doing the select again. */
4779 FD_ZERO (&Available);
4781 if (do_display)
4782 redisplay_preserve_echo_area (12);
4784 #ifdef EWOULDBLOCK
4785 else if (nread == -1 && errno == EWOULDBLOCK)
4787 #endif
4788 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4789 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4790 #ifdef O_NONBLOCK
4791 else if (nread == -1 && errno == EAGAIN)
4793 #else
4794 #ifdef O_NDELAY
4795 else if (nread == -1 && errno == EAGAIN)
4797 /* Note that we cannot distinguish between no input
4798 available now and a closed pipe.
4799 With luck, a closed pipe will be accompanied by
4800 subprocess termination and SIGCHLD. */
4801 else if (nread == 0 && !NETCONN_P (proc))
4803 #endif /* O_NDELAY */
4804 #endif /* O_NONBLOCK */
4805 #ifdef HAVE_PTYS
4806 /* On some OSs with ptys, when the process on one end of
4807 a pty exits, the other end gets an error reading with
4808 errno = EIO instead of getting an EOF (0 bytes read).
4809 Therefore, if we get an error reading and errno =
4810 EIO, just continue, because the child process has
4811 exited and should clean itself up soon (e.g. when we
4812 get a SIGCHLD).
4814 However, it has been known to happen that the SIGCHLD
4815 got lost. So raise the signl again just in case.
4816 It can't hurt. */
4817 else if (nread == -1 && errno == EIO)
4818 kill (getpid (), SIGCHLD);
4819 #endif /* HAVE_PTYS */
4820 /* If we can detect process termination, don't consider the process
4821 gone just because its pipe is closed. */
4822 #ifdef SIGCHLD
4823 else if (nread == 0 && !NETCONN_P (proc))
4825 #endif
4826 else
4828 /* Preserve status of processes already terminated. */
4829 XSETINT (XPROCESS (proc)->tick, ++process_tick);
4830 deactivate_process (proc);
4831 if (XPROCESS (proc)->raw_status_new)
4832 update_status (XPROCESS (proc));
4833 if (EQ (XPROCESS (proc)->status, Qrun))
4834 XPROCESS (proc)->status
4835 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4838 #ifdef NON_BLOCKING_CONNECT
4839 if (check_connect && FD_ISSET (channel, &Connecting)
4840 && FD_ISSET (channel, &connect_wait_mask))
4842 struct Lisp_Process *p;
4844 FD_CLR (channel, &connect_wait_mask);
4845 if (--num_pending_connects < 0)
4846 abort ();
4848 proc = chan_process[channel];
4849 if (NILP (proc))
4850 continue;
4852 p = XPROCESS (proc);
4854 #ifdef GNU_LINUX
4855 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4856 So only use it on systems where it is known to work. */
4858 int xlen = sizeof(xerrno);
4859 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4860 xerrno = errno;
4862 #else
4864 struct sockaddr pname;
4865 int pnamelen = sizeof(pname);
4867 /* If connection failed, getpeername will fail. */
4868 xerrno = 0;
4869 if (getpeername(channel, &pname, &pnamelen) < 0)
4871 /* Obtain connect failure code through error slippage. */
4872 char dummy;
4873 xerrno = errno;
4874 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4875 xerrno = errno;
4878 #endif
4879 if (xerrno)
4881 XSETINT (p->tick, ++process_tick);
4882 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4883 deactivate_process (proc);
4885 else
4887 p->status = Qrun;
4888 /* Execute the sentinel here. If we had relied on
4889 status_notify to do it later, it will read input
4890 from the process before calling the sentinel. */
4891 exec_sentinel (proc, build_string ("open\n"));
4892 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4894 FD_SET (XINT (p->infd), &input_wait_mask);
4895 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
4899 #endif /* NON_BLOCKING_CONNECT */
4900 } /* end for each file descriptor */
4901 } /* end while exit conditions not met */
4903 unbind_to (count, Qnil);
4905 /* If calling from keyboard input, do not quit
4906 since we want to return C-g as an input character.
4907 Otherwise, do pending quit if requested. */
4908 if (read_kbd >= 0)
4910 /* Prevent input_pending from remaining set if we quit. */
4911 clear_input_pending ();
4912 QUIT;
4914 #ifdef POLL_INTERRUPTED_SYS_CALL
4915 /* AlainF 5-Jul-1996
4916 HP-UX 10.10 seems to have problems with signals coming in
4917 Causes "poll: interrupted system call" messages when Emacs is run
4918 in an X window
4919 Turn periodic alarms back on */
4920 start_polling ();
4921 #endif /* POLL_INTERRUPTED_SYS_CALL */
4923 return got_some_input;
4926 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4928 static Lisp_Object
4929 read_process_output_call (fun_and_args)
4930 Lisp_Object fun_and_args;
4932 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4935 static Lisp_Object
4936 read_process_output_error_handler (error)
4937 Lisp_Object error;
4939 cmd_error_internal (error, "error in process filter: ");
4940 Vinhibit_quit = Qt;
4941 update_echo_area ();
4942 Fsleep_for (make_number (2), Qnil);
4943 return Qt;
4946 /* Read pending output from the process channel,
4947 starting with our buffered-ahead character if we have one.
4948 Yield number of decoded characters read.
4950 This function reads at most 4096 characters.
4951 If you want to read all available subprocess output,
4952 you must call it repeatedly until it returns zero.
4954 The characters read are decoded according to PROC's coding-system
4955 for decoding. */
4957 static int
4958 read_process_output (proc, channel)
4959 Lisp_Object proc;
4960 register int channel;
4962 register int nbytes;
4963 char *chars;
4964 register Lisp_Object outstream;
4965 register struct buffer *old = current_buffer;
4966 register struct Lisp_Process *p = XPROCESS (proc);
4967 register int opoint;
4968 struct coding_system *coding = proc_decode_coding_system[channel];
4969 int carryover = XINT (p->decoding_carryover);
4970 int readmax = 4096;
4972 #ifdef VMS
4973 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4975 vs = get_vms_process_pointer (p->pid);
4976 if (vs)
4978 if (!vs->iosb[0])
4979 return (0); /* Really weird if it does this */
4980 if (!(vs->iosb[0] & 1))
4981 return -1; /* I/O error */
4983 else
4984 error ("Could not get VMS process pointer");
4985 chars = vs->inputBuffer;
4986 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
4987 if (nbytes <= 0)
4989 start_vms_process_read (vs); /* Crank up the next read on the process */
4990 return 1; /* Nothing worth printing, say we got 1 */
4992 if (carryover > 0)
4994 /* The data carried over in the previous decoding (which are at
4995 the tail of decoding buffer) should be prepended to the new
4996 data read to decode all together. */
4997 chars = (char *) alloca (nbytes + carryover);
4998 bcopy (SDATA (p->decoding_buf), buf, carryover);
4999 bcopy (vs->inputBuffer, chars + carryover, nbytes);
5001 #else /* not VMS */
5003 chars = (char *) alloca (carryover + readmax);
5004 if (carryover)
5005 /* See the comment above. */
5006 bcopy (SDATA (p->decoding_buf), chars, carryover);
5008 #ifdef DATAGRAM_SOCKETS
5009 /* We have a working select, so proc_buffered_char is always -1. */
5010 if (DATAGRAM_CHAN_P (channel))
5012 int len = datagram_address[channel].len;
5013 nbytes = recvfrom (channel, chars + carryover, readmax,
5014 0, datagram_address[channel].sa, &len);
5016 else
5017 #endif
5018 if (proc_buffered_char[channel] < 0)
5020 nbytes = emacs_read (channel, chars + carryover, readmax);
5021 #ifdef ADAPTIVE_READ_BUFFERING
5022 if (nbytes > 0 && !NILP (p->adaptive_read_buffering))
5024 int delay = XINT (p->read_output_delay);
5025 if (nbytes < 256)
5027 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5029 if (delay == 0)
5030 process_output_delay_count++;
5031 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5034 else if (delay > 0 && (nbytes == readmax))
5036 delay -= READ_OUTPUT_DELAY_INCREMENT;
5037 if (delay == 0)
5038 process_output_delay_count--;
5040 XSETINT (p->read_output_delay, delay);
5041 if (delay)
5043 p->read_output_skip = Qt;
5044 process_output_skip = 1;
5047 #endif
5049 else
5051 chars[carryover] = proc_buffered_char[channel];
5052 proc_buffered_char[channel] = -1;
5053 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5054 if (nbytes < 0)
5055 nbytes = 1;
5056 else
5057 nbytes = nbytes + 1;
5059 #endif /* not VMS */
5061 XSETINT (p->decoding_carryover, 0);
5063 /* At this point, NBYTES holds number of bytes just received
5064 (including the one in proc_buffered_char[channel]). */
5065 if (nbytes <= 0)
5067 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5068 return nbytes;
5069 coding->mode |= CODING_MODE_LAST_BLOCK;
5072 /* Now set NBYTES how many bytes we must decode. */
5073 nbytes += carryover;
5075 /* Read and dispose of the process output. */
5076 outstream = p->filter;
5077 if (!NILP (outstream))
5079 /* We inhibit quit here instead of just catching it so that
5080 hitting ^G when a filter happens to be running won't screw
5081 it up. */
5082 int count = SPECPDL_INDEX ();
5083 Lisp_Object odeactivate;
5084 Lisp_Object obuffer, okeymap;
5085 Lisp_Object text;
5086 int outer_running_asynch_code = running_asynch_code;
5087 int waiting = waiting_for_user_input_p;
5089 /* No need to gcpro these, because all we do with them later
5090 is test them for EQness, and none of them should be a string. */
5091 odeactivate = Vdeactivate_mark;
5092 XSETBUFFER (obuffer, current_buffer);
5093 okeymap = current_buffer->keymap;
5095 specbind (Qinhibit_quit, Qt);
5096 specbind (Qlast_nonmenu_event, Qt);
5098 /* In case we get recursively called,
5099 and we already saved the match data nonrecursively,
5100 save the same match data in safely recursive fashion. */
5101 if (outer_running_asynch_code)
5103 Lisp_Object tem;
5104 /* Don't clobber the CURRENT match data, either! */
5105 tem = Fmatch_data (Qnil, Qnil, Qnil);
5106 restore_search_regs ();
5107 record_unwind_save_match_data ();
5108 Fset_match_data (tem, Qt);
5111 /* For speed, if a search happens within this code,
5112 save the match data in a special nonrecursive fashion. */
5113 running_asynch_code = 1;
5115 text = decode_coding_string (make_unibyte_string (chars, nbytes),
5116 coding, 0);
5117 Vlast_coding_system_used = coding->symbol;
5118 /* A new coding system might be found. */
5119 if (!EQ (p->decode_coding_system, coding->symbol))
5121 p->decode_coding_system = coding->symbol;
5123 /* Don't call setup_coding_system for
5124 proc_decode_coding_system[channel] here. It is done in
5125 detect_coding called via decode_coding above. */
5127 /* If a coding system for encoding is not yet decided, we set
5128 it as the same as coding-system for decoding.
5130 But, before doing that we must check if
5131 proc_encode_coding_system[p->outfd] surely points to a
5132 valid memory because p->outfd will be changed once EOF is
5133 sent to the process. */
5134 if (NILP (p->encode_coding_system)
5135 && proc_encode_coding_system[XINT (p->outfd)])
5137 p->encode_coding_system = coding->symbol;
5138 setup_coding_system (coding->symbol,
5139 proc_encode_coding_system[XINT (p->outfd)]);
5140 if (proc_encode_coding_system[XINT (p->outfd)]->eol_type
5141 == CODING_EOL_UNDECIDED)
5142 proc_encode_coding_system[XINT (p->outfd)]->eol_type
5143 = system_eol_type;
5147 carryover = nbytes - coding->consumed;
5148 if (carryover < 0)
5149 abort ();
5151 if (SCHARS (p->decoding_buf) < carryover)
5152 p->decoding_buf = make_uninit_string (carryover);
5153 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
5154 carryover);
5155 XSETINT (p->decoding_carryover, carryover);
5156 /* Adjust the multibyteness of TEXT to that of the filter. */
5157 if (NILP (p->filter_multibyte) != ! STRING_MULTIBYTE (text))
5158 text = (STRING_MULTIBYTE (text)
5159 ? Fstring_as_unibyte (text)
5160 : Fstring_to_multibyte (text));
5161 if (SBYTES (text) > 0)
5162 internal_condition_case_1 (read_process_output_call,
5163 Fcons (outstream,
5164 Fcons (proc, Fcons (text, Qnil))),
5165 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5166 read_process_output_error_handler);
5168 /* If we saved the match data nonrecursively, restore it now. */
5169 restore_search_regs ();
5170 running_asynch_code = outer_running_asynch_code;
5172 /* Handling the process output should not deactivate the mark. */
5173 Vdeactivate_mark = odeactivate;
5175 /* Restore waiting_for_user_input_p as it was
5176 when we were called, in case the filter clobbered it. */
5177 waiting_for_user_input_p = waiting;
5179 #if 0 /* Call record_asynch_buffer_change unconditionally,
5180 because we might have changed minor modes or other things
5181 that affect key bindings. */
5182 if (! EQ (Fcurrent_buffer (), obuffer)
5183 || ! EQ (current_buffer->keymap, okeymap))
5184 #endif
5185 /* But do it only if the caller is actually going to read events.
5186 Otherwise there's no need to make him wake up, and it could
5187 cause trouble (for example it would make sit_for return). */
5188 if (waiting_for_user_input_p == -1)
5189 record_asynch_buffer_change ();
5191 #ifdef VMS
5192 start_vms_process_read (vs);
5193 #endif
5194 unbind_to (count, Qnil);
5195 return nbytes;
5198 /* If no filter, write into buffer if it isn't dead. */
5199 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5201 Lisp_Object old_read_only;
5202 int old_begv, old_zv;
5203 int old_begv_byte, old_zv_byte;
5204 Lisp_Object odeactivate;
5205 int before, before_byte;
5206 int opoint_byte;
5207 Lisp_Object text;
5208 struct buffer *b;
5210 odeactivate = Vdeactivate_mark;
5212 Fset_buffer (p->buffer);
5213 opoint = PT;
5214 opoint_byte = PT_BYTE;
5215 old_read_only = current_buffer->read_only;
5216 old_begv = BEGV;
5217 old_zv = ZV;
5218 old_begv_byte = BEGV_BYTE;
5219 old_zv_byte = ZV_BYTE;
5221 current_buffer->read_only = Qnil;
5223 /* Insert new output into buffer
5224 at the current end-of-output marker,
5225 thus preserving logical ordering of input and output. */
5226 if (XMARKER (p->mark)->buffer)
5227 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5228 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5229 ZV_BYTE));
5230 else
5231 SET_PT_BOTH (ZV, ZV_BYTE);
5232 before = PT;
5233 before_byte = PT_BYTE;
5235 /* If the output marker is outside of the visible region, save
5236 the restriction and widen. */
5237 if (! (BEGV <= PT && PT <= ZV))
5238 Fwiden ();
5240 text = decode_coding_string (make_unibyte_string (chars, nbytes),
5241 coding, 0);
5242 Vlast_coding_system_used = coding->symbol;
5243 /* A new coding system might be found. See the comment in the
5244 similar code in the previous `if' block. */
5245 if (!EQ (p->decode_coding_system, coding->symbol))
5247 p->decode_coding_system = coding->symbol;
5248 if (NILP (p->encode_coding_system)
5249 && proc_encode_coding_system[XINT (p->outfd)])
5251 p->encode_coding_system = coding->symbol;
5252 setup_coding_system (coding->symbol,
5253 proc_encode_coding_system[XINT (p->outfd)]);
5254 if (proc_encode_coding_system[XINT (p->outfd)]->eol_type
5255 == CODING_EOL_UNDECIDED)
5256 proc_encode_coding_system[XINT (p->outfd)]->eol_type
5257 = system_eol_type;
5260 carryover = nbytes - coding->consumed;
5261 if (carryover < 0)
5262 abort ();
5264 if (SCHARS (p->decoding_buf) < carryover)
5265 p->decoding_buf = make_uninit_string (carryover);
5266 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
5267 carryover);
5268 XSETINT (p->decoding_carryover, carryover);
5270 /* Adjust the multibyteness of TEXT to that of the buffer. */
5271 if (NILP (current_buffer->enable_multibyte_characters)
5272 != ! STRING_MULTIBYTE (text))
5273 text = (STRING_MULTIBYTE (text)
5274 ? Fstring_as_unibyte (text)
5275 : Fstring_to_multibyte (text));
5276 /* Insert before markers in case we are inserting where
5277 the buffer's mark is, and the user's next command is Meta-y. */
5278 insert_from_string_before_markers (text, 0, 0,
5279 SCHARS (text), SBYTES (text), 0);
5281 /* Make sure the process marker's position is valid when the
5282 process buffer is changed in the signal_after_change above.
5283 W3 is known to do that. */
5284 if (BUFFERP (p->buffer)
5285 && (b = XBUFFER (p->buffer), b != current_buffer))
5286 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5287 else
5288 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5290 update_mode_lines++;
5292 /* Make sure opoint and the old restrictions
5293 float ahead of any new text just as point would. */
5294 if (opoint >= before)
5296 opoint += PT - before;
5297 opoint_byte += PT_BYTE - before_byte;
5299 if (old_begv > before)
5301 old_begv += PT - before;
5302 old_begv_byte += PT_BYTE - before_byte;
5304 if (old_zv >= before)
5306 old_zv += PT - before;
5307 old_zv_byte += PT_BYTE - before_byte;
5310 /* If the restriction isn't what it should be, set it. */
5311 if (old_begv != BEGV || old_zv != ZV)
5312 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5314 /* Handling the process output should not deactivate the mark. */
5315 Vdeactivate_mark = odeactivate;
5317 current_buffer->read_only = old_read_only;
5318 SET_PT_BOTH (opoint, opoint_byte);
5319 set_buffer_internal (old);
5321 #ifdef VMS
5322 start_vms_process_read (vs);
5323 #endif
5324 return nbytes;
5327 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5328 0, 0, 0,
5329 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5330 This is intended for use by asynchronous process output filters and sentinels. */)
5333 return (waiting_for_user_input_p ? Qt : Qnil);
5336 /* Sending data to subprocess */
5338 jmp_buf send_process_frame;
5339 Lisp_Object process_sent_to;
5341 SIGTYPE
5342 send_process_trap ()
5344 SIGNAL_THREAD_CHECK (SIGPIPE);
5345 #ifdef BSD4_1
5346 sigrelse (SIGPIPE);
5347 sigrelse (SIGALRM);
5348 #endif /* BSD4_1 */
5349 sigunblock (sigmask (SIGPIPE));
5350 longjmp (send_process_frame, 1);
5353 /* Send some data to process PROC.
5354 BUF is the beginning of the data; LEN is the number of characters.
5355 OBJECT is the Lisp object that the data comes from. If OBJECT is
5356 nil or t, it means that the data comes from C string.
5358 If OBJECT is not nil, the data is encoded by PROC's coding-system
5359 for encoding before it is sent.
5361 This function can evaluate Lisp code and can garbage collect. */
5363 static void
5364 send_process (proc, buf, len, object)
5365 volatile Lisp_Object proc;
5366 unsigned char *volatile buf;
5367 volatile int len;
5368 volatile Lisp_Object object;
5370 /* Use volatile to protect variables from being clobbered by longjmp. */
5371 struct Lisp_Process *p = XPROCESS (proc);
5372 int rv;
5373 struct coding_system *coding;
5374 struct gcpro gcpro1;
5375 SIGTYPE (*volatile old_sigpipe) ();
5377 GCPRO1 (object);
5379 #ifdef VMS
5380 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5381 #endif /* VMS */
5383 if (p->raw_status_new)
5384 update_status (p);
5385 if (! EQ (p->status, Qrun))
5386 error ("Process %s not running", SDATA (p->name));
5387 if (XINT (p->outfd) < 0)
5388 error ("Output file descriptor of %s is closed", SDATA (p->name));
5390 coding = proc_encode_coding_system[XINT (p->outfd)];
5391 Vlast_coding_system_used = coding->symbol;
5393 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5394 || (BUFFERP (object)
5395 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5396 || EQ (object, Qt))
5398 if (!EQ (coding->symbol, p->encode_coding_system))
5399 /* The coding system for encoding was changed to raw-text
5400 because we sent a unibyte text previously. Now we are
5401 sending a multibyte text, thus we must encode it by the
5402 original coding system specified for the current process. */
5403 setup_coding_system (p->encode_coding_system, coding);
5404 if (coding->eol_type == CODING_EOL_UNDECIDED)
5405 coding->eol_type = system_eol_type;
5406 /* src_multibyte should be set to 1 _after_ a call to
5407 setup_coding_system, since it resets src_multibyte to
5408 zero. */
5409 coding->src_multibyte = 1;
5411 else
5413 /* For sending a unibyte text, character code conversion should
5414 not take place but EOL conversion should. So, setup raw-text
5415 or one of the subsidiary if we have not yet done it. */
5416 if (coding->type != coding_type_raw_text)
5418 if (CODING_REQUIRE_FLUSHING (coding))
5420 /* But, before changing the coding, we must flush out data. */
5421 coding->mode |= CODING_MODE_LAST_BLOCK;
5422 send_process (proc, "", 0, Qt);
5424 coding->src_multibyte = 0;
5425 setup_raw_text_coding_system (coding);
5428 coding->dst_multibyte = 0;
5430 if (CODING_REQUIRE_ENCODING (coding))
5432 int require = encoding_buffer_size (coding, len);
5433 int from_byte = -1, from = -1, to = -1;
5435 if (BUFFERP (object))
5437 from_byte = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5438 from = buf_bytepos_to_charpos (XBUFFER (object), from_byte);
5439 to = buf_bytepos_to_charpos (XBUFFER (object), from_byte + len);
5441 else if (STRINGP (object))
5443 from_byte = buf - SDATA (object);
5444 from = string_byte_to_char (object, from_byte);
5445 to = string_byte_to_char (object, from_byte + len);
5448 if (coding->composing != COMPOSITION_DISABLED)
5450 if (from_byte >= 0)
5451 coding_save_composition (coding, from, to, object);
5452 else
5453 coding->composing = COMPOSITION_DISABLED;
5456 if (SBYTES (p->encoding_buf) < require)
5457 p->encoding_buf = make_uninit_string (require);
5459 if (from_byte >= 0)
5460 buf = (BUFFERP (object)
5461 ? BUF_BYTE_ADDRESS (XBUFFER (object), from_byte)
5462 : SDATA (object) + from_byte);
5464 object = p->encoding_buf;
5465 encode_coding (coding, (char *) buf, SDATA (object),
5466 len, SBYTES (object));
5467 coding_free_composition_data (coding);
5468 len = coding->produced;
5469 buf = SDATA (object);
5472 #ifdef VMS
5473 vs = get_vms_process_pointer (p->pid);
5474 if (vs == 0)
5475 error ("Could not find this process: %x", p->pid);
5476 else if (write_to_vms_process (vs, buf, len))
5478 #else /* not VMS */
5480 if (pty_max_bytes == 0)
5482 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5483 pty_max_bytes = fpathconf (XFASTINT (p->outfd), _PC_MAX_CANON);
5484 if (pty_max_bytes < 0)
5485 pty_max_bytes = 250;
5486 #else
5487 pty_max_bytes = 250;
5488 #endif
5489 /* Deduct one, to leave space for the eof. */
5490 pty_max_bytes--;
5493 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5494 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5495 when returning with longjmp despite being declared volatile. */
5496 if (!setjmp (send_process_frame))
5498 process_sent_to = proc;
5499 while (len > 0)
5501 int this = len;
5503 /* Decide how much data we can send in one batch.
5504 Long lines need to be split into multiple batches. */
5505 if (!NILP (p->pty_flag))
5507 /* Starting this at zero is always correct when not the first
5508 iteration because the previous iteration ended by sending C-d.
5509 It may not be correct for the first iteration
5510 if a partial line was sent in a separate send_process call.
5511 If that proves worth handling, we need to save linepos
5512 in the process object. */
5513 int linepos = 0;
5514 unsigned char *ptr = (unsigned char *) buf;
5515 unsigned char *end = (unsigned char *) buf + len;
5517 /* Scan through this text for a line that is too long. */
5518 while (ptr != end && linepos < pty_max_bytes)
5520 if (*ptr == '\n')
5521 linepos = 0;
5522 else
5523 linepos++;
5524 ptr++;
5526 /* If we found one, break the line there
5527 and put in a C-d to force the buffer through. */
5528 this = ptr - buf;
5531 /* Send this batch, using one or more write calls. */
5532 while (this > 0)
5534 int outfd = XINT (p->outfd);
5535 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5536 #ifdef DATAGRAM_SOCKETS
5537 if (DATAGRAM_CHAN_P (outfd))
5539 rv = sendto (outfd, (char *) buf, this,
5540 0, datagram_address[outfd].sa,
5541 datagram_address[outfd].len);
5542 if (rv < 0 && errno == EMSGSIZE)
5544 signal (SIGPIPE, old_sigpipe);
5545 report_file_error ("sending datagram",
5546 Fcons (proc, Qnil));
5549 else
5550 #endif
5552 rv = emacs_write (outfd, (char *) buf, this);
5553 #ifdef ADAPTIVE_READ_BUFFERING
5554 if (XINT (p->read_output_delay) > 0
5555 && EQ (p->adaptive_read_buffering, Qt))
5557 XSETFASTINT (p->read_output_delay, 0);
5558 process_output_delay_count--;
5559 p->read_output_skip = Qnil;
5561 #endif
5563 signal (SIGPIPE, old_sigpipe);
5565 if (rv < 0)
5567 if (0
5568 #ifdef EWOULDBLOCK
5569 || errno == EWOULDBLOCK
5570 #endif
5571 #ifdef EAGAIN
5572 || errno == EAGAIN
5573 #endif
5575 /* Buffer is full. Wait, accepting input;
5576 that may allow the program
5577 to finish doing output and read more. */
5579 int offset = 0;
5581 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5582 /* A gross hack to work around a bug in FreeBSD.
5583 In the following sequence, read(2) returns
5584 bogus data:
5586 write(2) 1022 bytes
5587 write(2) 954 bytes, get EAGAIN
5588 read(2) 1024 bytes in process_read_output
5589 read(2) 11 bytes in process_read_output
5591 That is, read(2) returns more bytes than have
5592 ever been written successfully. The 1033 bytes
5593 read are the 1022 bytes written successfully
5594 after processing (for example with CRs added if
5595 the terminal is set up that way which it is
5596 here). The same bytes will be seen again in a
5597 later read(2), without the CRs. */
5599 if (errno == EAGAIN)
5601 int flags = FWRITE;
5602 ioctl (XINT (p->outfd), TIOCFLUSH, &flags);
5604 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5606 /* Running filters might relocate buffers or strings.
5607 Arrange to relocate BUF. */
5608 if (BUFFERP (object))
5609 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5610 else if (STRINGP (object))
5611 offset = buf - SDATA (object);
5613 #ifdef EMACS_HAS_USECS
5614 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5615 #else
5616 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5617 #endif
5619 if (BUFFERP (object))
5620 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5621 else if (STRINGP (object))
5622 buf = offset + SDATA (object);
5624 rv = 0;
5626 else
5627 /* This is a real error. */
5628 report_file_error ("writing to process", Fcons (proc, Qnil));
5630 buf += rv;
5631 len -= rv;
5632 this -= rv;
5635 /* If we sent just part of the string, put in an EOF
5636 to force it through, before we send the rest. */
5637 if (len > 0)
5638 Fprocess_send_eof (proc);
5641 #endif /* not VMS */
5642 else
5644 signal (SIGPIPE, old_sigpipe);
5645 #ifndef VMS
5646 proc = process_sent_to;
5647 p = XPROCESS (proc);
5648 #endif
5649 p->raw_status_new = 0;
5650 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5651 XSETINT (p->tick, ++process_tick);
5652 deactivate_process (proc);
5653 #ifdef VMS
5654 error ("Error writing to process %s; closed it", SDATA (p->name));
5655 #else
5656 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5657 #endif
5660 UNGCPRO;
5663 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5664 3, 3, 0,
5665 doc: /* Send current contents of region as input to PROCESS.
5666 PROCESS may be a process, a buffer, the name of a process or buffer, or
5667 nil, indicating the current buffer's process.
5668 Called from program, takes three arguments, PROCESS, START and END.
5669 If the region is more than 500 characters long,
5670 it is sent in several bunches. This may happen even for shorter regions.
5671 Output from processes can arrive in between bunches. */)
5672 (process, start, end)
5673 Lisp_Object process, start, end;
5675 Lisp_Object proc;
5676 int start1, end1;
5678 proc = get_process (process);
5679 validate_region (&start, &end);
5681 if (XINT (start) < GPT && XINT (end) > GPT)
5682 move_gap (XINT (start));
5684 start1 = CHAR_TO_BYTE (XINT (start));
5685 end1 = CHAR_TO_BYTE (XINT (end));
5686 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5687 Fcurrent_buffer ());
5689 return Qnil;
5692 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5693 2, 2, 0,
5694 doc: /* Send PROCESS the contents of STRING as input.
5695 PROCESS may be a process, a buffer, the name of a process or buffer, or
5696 nil, indicating the current buffer's process.
5697 If STRING is more than 500 characters long,
5698 it is sent in several bunches. This may happen even for shorter strings.
5699 Output from processes can arrive in between bunches. */)
5700 (process, string)
5701 Lisp_Object process, string;
5703 Lisp_Object proc;
5704 CHECK_STRING (string);
5705 proc = get_process (process);
5706 send_process (proc, SDATA (string),
5707 SBYTES (string), string);
5708 return Qnil;
5711 /* Return the foreground process group for the tty/pty that
5712 the process P uses. */
5713 static int
5714 emacs_get_tty_pgrp (p)
5715 struct Lisp_Process *p;
5717 int gid = -1;
5719 #ifdef TIOCGPGRP
5720 if (ioctl (XINT (p->infd), TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5722 int fd;
5723 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5724 master side. Try the slave side. */
5725 fd = emacs_open (XSTRING (p->tty_name)->data, O_RDONLY, 0);
5727 if (fd != -1)
5729 ioctl (fd, TIOCGPGRP, &gid);
5730 emacs_close (fd);
5733 #endif /* defined (TIOCGPGRP ) */
5735 return gid;
5738 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5739 Sprocess_running_child_p, 0, 1, 0,
5740 doc: /* Return t if PROCESS has given the terminal to a child.
5741 If the operating system does not make it possible to find out,
5742 return t unconditionally. */)
5743 (process)
5744 Lisp_Object process;
5746 /* Initialize in case ioctl doesn't exist or gives an error,
5747 in a way that will cause returning t. */
5748 int gid;
5749 Lisp_Object proc;
5750 struct Lisp_Process *p;
5752 proc = get_process (process);
5753 p = XPROCESS (proc);
5755 if (!EQ (p->childp, Qt))
5756 error ("Process %s is not a subprocess",
5757 SDATA (p->name));
5758 if (XINT (p->infd) < 0)
5759 error ("Process %s is not active",
5760 SDATA (p->name));
5762 gid = emacs_get_tty_pgrp (p);
5764 if (gid == p->pid)
5765 return Qnil;
5766 return Qt;
5769 /* send a signal number SIGNO to PROCESS.
5770 If CURRENT_GROUP is t, that means send to the process group
5771 that currently owns the terminal being used to communicate with PROCESS.
5772 This is used for various commands in shell mode.
5773 If CURRENT_GROUP is lambda, that means send to the process group
5774 that currently owns the terminal, but only if it is NOT the shell itself.
5776 If NOMSG is zero, insert signal-announcements into process's buffers
5777 right away.
5779 If we can, we try to signal PROCESS by sending control characters
5780 down the pty. This allows us to signal inferiors who have changed
5781 their uid, for which killpg would return an EPERM error. */
5783 static void
5784 process_send_signal (process, signo, current_group, nomsg)
5785 Lisp_Object process;
5786 int signo;
5787 Lisp_Object current_group;
5788 int nomsg;
5790 Lisp_Object proc;
5791 register struct Lisp_Process *p;
5792 int gid;
5793 int no_pgrp = 0;
5795 proc = get_process (process);
5796 p = XPROCESS (proc);
5798 if (!EQ (p->childp, Qt))
5799 error ("Process %s is not a subprocess",
5800 SDATA (p->name));
5801 if (XINT (p->infd) < 0)
5802 error ("Process %s is not active",
5803 SDATA (p->name));
5805 if (NILP (p->pty_flag))
5806 current_group = Qnil;
5808 /* If we are using pgrps, get a pgrp number and make it negative. */
5809 if (NILP (current_group))
5810 /* Send the signal to the shell's process group. */
5811 gid = p->pid;
5812 else
5814 #ifdef SIGNALS_VIA_CHARACTERS
5815 /* If possible, send signals to the entire pgrp
5816 by sending an input character to it. */
5818 /* TERMIOS is the latest and bestest, and seems most likely to
5819 work. If the system has it, use it. */
5820 #ifdef HAVE_TERMIOS
5821 struct termios t;
5822 cc_t *sig_char = NULL;
5824 tcgetattr (XINT (p->infd), &t);
5826 switch (signo)
5828 case SIGINT:
5829 sig_char = &t.c_cc[VINTR];
5830 break;
5832 case SIGQUIT:
5833 sig_char = &t.c_cc[VQUIT];
5834 break;
5836 case SIGTSTP:
5837 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5838 sig_char = &t.c_cc[VSWTCH];
5839 #else
5840 sig_char = &t.c_cc[VSUSP];
5841 #endif
5842 break;
5845 if (sig_char && *sig_char != CDISABLE)
5847 send_process (proc, sig_char, 1, Qnil);
5848 return;
5850 /* If we can't send the signal with a character,
5851 fall through and send it another way. */
5852 #else /* ! HAVE_TERMIOS */
5854 /* On Berkeley descendants, the following IOCTL's retrieve the
5855 current control characters. */
5856 #if defined (TIOCGLTC) && defined (TIOCGETC)
5858 struct tchars c;
5859 struct ltchars lc;
5861 switch (signo)
5863 case SIGINT:
5864 ioctl (XINT (p->infd), TIOCGETC, &c);
5865 send_process (proc, &c.t_intrc, 1, Qnil);
5866 return;
5867 case SIGQUIT:
5868 ioctl (XINT (p->infd), TIOCGETC, &c);
5869 send_process (proc, &c.t_quitc, 1, Qnil);
5870 return;
5871 #ifdef SIGTSTP
5872 case SIGTSTP:
5873 ioctl (XINT (p->infd), TIOCGLTC, &lc);
5874 send_process (proc, &lc.t_suspc, 1, Qnil);
5875 return;
5876 #endif /* ! defined (SIGTSTP) */
5879 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5881 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5882 characters. */
5883 #ifdef TCGETA
5884 struct termio t;
5885 switch (signo)
5887 case SIGINT:
5888 ioctl (XINT (p->infd), TCGETA, &t);
5889 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5890 return;
5891 case SIGQUIT:
5892 ioctl (XINT (p->infd), TCGETA, &t);
5893 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5894 return;
5895 #ifdef SIGTSTP
5896 case SIGTSTP:
5897 ioctl (XINT (p->infd), TCGETA, &t);
5898 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5899 return;
5900 #endif /* ! defined (SIGTSTP) */
5902 #else /* ! defined (TCGETA) */
5903 Your configuration files are messed up.
5904 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5905 you'd better be using one of the alternatives above! */
5906 #endif /* ! defined (TCGETA) */
5907 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5908 /* In this case, the code above should alway returns. */
5909 abort ();
5910 #endif /* ! defined HAVE_TERMIOS */
5912 /* The code above may fall through if it can't
5913 handle the signal. */
5914 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5916 #ifdef TIOCGPGRP
5917 /* Get the current pgrp using the tty itself, if we have that.
5918 Otherwise, use the pty to get the pgrp.
5919 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5920 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5921 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5922 His patch indicates that if TIOCGPGRP returns an error, then
5923 we should just assume that p->pid is also the process group id. */
5925 gid = emacs_get_tty_pgrp (p);
5927 if (gid == -1)
5928 /* If we can't get the information, assume
5929 the shell owns the tty. */
5930 gid = p->pid;
5932 /* It is not clear whether anything really can set GID to -1.
5933 Perhaps on some system one of those ioctls can or could do so.
5934 Or perhaps this is vestigial. */
5935 if (gid == -1)
5936 no_pgrp = 1;
5937 #else /* ! defined (TIOCGPGRP ) */
5938 /* Can't select pgrps on this system, so we know that
5939 the child itself heads the pgrp. */
5940 gid = p->pid;
5941 #endif /* ! defined (TIOCGPGRP ) */
5943 /* If current_group is lambda, and the shell owns the terminal,
5944 don't send any signal. */
5945 if (EQ (current_group, Qlambda) && gid == p->pid)
5946 return;
5949 switch (signo)
5951 #ifdef SIGCONT
5952 case SIGCONT:
5953 p->raw_status_new = 0;
5954 p->status = Qrun;
5955 XSETINT (p->tick, ++process_tick);
5956 if (!nomsg)
5957 status_notify (NULL);
5958 break;
5959 #endif /* ! defined (SIGCONT) */
5960 case SIGINT:
5961 #ifdef VMS
5962 send_process (proc, "\003", 1, Qnil); /* ^C */
5963 goto whoosh;
5964 #endif
5965 case SIGQUIT:
5966 #ifdef VMS
5967 send_process (proc, "\031", 1, Qnil); /* ^Y */
5968 goto whoosh;
5969 #endif
5970 case SIGKILL:
5971 #ifdef VMS
5972 sys$forcex (&(p->pid), 0, 1);
5973 whoosh:
5974 #endif
5975 flush_pending_output (XINT (p->infd));
5976 break;
5979 /* If we don't have process groups, send the signal to the immediate
5980 subprocess. That isn't really right, but it's better than any
5981 obvious alternative. */
5982 if (no_pgrp)
5984 kill (p->pid, signo);
5985 return;
5988 /* gid may be a pid, or minus a pgrp's number */
5989 #ifdef TIOCSIGSEND
5990 if (!NILP (current_group))
5992 if (ioctl (XINT (p->infd), TIOCSIGSEND, signo) == -1)
5993 EMACS_KILLPG (gid, signo);
5995 else
5997 gid = - p->pid;
5998 kill (gid, signo);
6000 #else /* ! defined (TIOCSIGSEND) */
6001 EMACS_KILLPG (gid, signo);
6002 #endif /* ! defined (TIOCSIGSEND) */
6005 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6006 doc: /* Interrupt process PROCESS.
6007 PROCESS may be a process, a buffer, or the name of a process or buffer.
6008 No arg or nil means current buffer's process.
6009 Second arg CURRENT-GROUP non-nil means send signal to
6010 the current process-group of the process's controlling terminal
6011 rather than to the process's own process group.
6012 If the process is a shell, this means interrupt current subjob
6013 rather than the shell.
6015 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6016 don't send the signal. */)
6017 (process, current_group)
6018 Lisp_Object process, current_group;
6020 process_send_signal (process, SIGINT, current_group, 0);
6021 return process;
6024 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6025 doc: /* Kill process PROCESS. May be process or name of one.
6026 See function `interrupt-process' for more details on usage. */)
6027 (process, current_group)
6028 Lisp_Object process, current_group;
6030 process_send_signal (process, SIGKILL, current_group, 0);
6031 return process;
6034 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6035 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6036 See function `interrupt-process' for more details on usage. */)
6037 (process, current_group)
6038 Lisp_Object process, current_group;
6040 process_send_signal (process, SIGQUIT, current_group, 0);
6041 return process;
6044 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6045 doc: /* Stop process PROCESS. May be process or name of one.
6046 See function `interrupt-process' for more details on usage.
6047 If PROCESS is a network process, inhibit handling of incoming traffic. */)
6048 (process, current_group)
6049 Lisp_Object process, current_group;
6051 #ifdef HAVE_SOCKETS
6052 if (PROCESSP (process) && NETCONN_P (process))
6054 struct Lisp_Process *p;
6056 p = XPROCESS (process);
6057 if (NILP (p->command)
6058 && XINT (p->infd) >= 0)
6060 FD_CLR (XINT (p->infd), &input_wait_mask);
6061 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
6063 p->command = Qt;
6064 return process;
6066 #endif
6067 #ifndef SIGTSTP
6068 error ("No SIGTSTP support");
6069 #else
6070 process_send_signal (process, SIGTSTP, current_group, 0);
6071 #endif
6072 return process;
6075 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6076 doc: /* Continue process PROCESS. May be process or name of one.
6077 See function `interrupt-process' for more details on usage.
6078 If PROCESS is a network process, resume handling of incoming traffic. */)
6079 (process, current_group)
6080 Lisp_Object process, current_group;
6082 #ifdef HAVE_SOCKETS
6083 if (PROCESSP (process) && NETCONN_P (process))
6085 struct Lisp_Process *p;
6087 p = XPROCESS (process);
6088 if (EQ (p->command, Qt)
6089 && XINT (p->infd) >= 0
6090 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6092 FD_SET (XINT (p->infd), &input_wait_mask);
6093 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
6095 p->command = Qnil;
6096 return process;
6098 #endif
6099 #ifdef SIGCONT
6100 process_send_signal (process, SIGCONT, current_group, 0);
6101 #else
6102 error ("No SIGCONT support");
6103 #endif
6104 return process;
6107 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6108 2, 2, "sProcess (name or number): \nnSignal code: ",
6109 doc: /* Send PROCESS the signal with code SIGCODE.
6110 PROCESS may also be a number specifying the process id of the
6111 process to signal; in this case, the process need not be a child of
6112 this Emacs.
6113 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6114 (process, sigcode)
6115 Lisp_Object process, sigcode;
6117 pid_t pid;
6119 if (INTEGERP (process))
6121 pid = XINT (process);
6122 goto got_it;
6125 if (FLOATP (process))
6127 pid = (pid_t) XFLOAT_DATA (process);
6128 goto got_it;
6131 if (STRINGP (process))
6133 Lisp_Object tem;
6134 if (tem = Fget_process (process), NILP (tem))
6136 pid = XINT (Fstring_to_number (process, make_number (10)));
6137 if (pid > 0)
6138 goto got_it;
6140 process = tem;
6142 else
6143 process = get_process (process);
6145 if (NILP (process))
6146 return process;
6148 CHECK_PROCESS (process);
6149 pid = XPROCESS (process)->pid;
6150 if (pid <= 0)
6151 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6153 got_it:
6155 #define parse_signal(NAME, VALUE) \
6156 else if (!xstricmp (name, NAME)) \
6157 XSETINT (sigcode, VALUE)
6159 if (INTEGERP (sigcode))
6161 else
6163 unsigned char *name;
6165 CHECK_SYMBOL (sigcode);
6166 name = SDATA (SYMBOL_NAME (sigcode));
6168 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6169 name += 3;
6171 if (0)
6173 #ifdef SIGUSR1
6174 parse_signal ("usr1", SIGUSR1);
6175 #endif
6176 #ifdef SIGUSR2
6177 parse_signal ("usr2", SIGUSR2);
6178 #endif
6179 #ifdef SIGTERM
6180 parse_signal ("term", SIGTERM);
6181 #endif
6182 #ifdef SIGHUP
6183 parse_signal ("hup", SIGHUP);
6184 #endif
6185 #ifdef SIGINT
6186 parse_signal ("int", SIGINT);
6187 #endif
6188 #ifdef SIGQUIT
6189 parse_signal ("quit", SIGQUIT);
6190 #endif
6191 #ifdef SIGILL
6192 parse_signal ("ill", SIGILL);
6193 #endif
6194 #ifdef SIGABRT
6195 parse_signal ("abrt", SIGABRT);
6196 #endif
6197 #ifdef SIGEMT
6198 parse_signal ("emt", SIGEMT);
6199 #endif
6200 #ifdef SIGKILL
6201 parse_signal ("kill", SIGKILL);
6202 #endif
6203 #ifdef SIGFPE
6204 parse_signal ("fpe", SIGFPE);
6205 #endif
6206 #ifdef SIGBUS
6207 parse_signal ("bus", SIGBUS);
6208 #endif
6209 #ifdef SIGSEGV
6210 parse_signal ("segv", SIGSEGV);
6211 #endif
6212 #ifdef SIGSYS
6213 parse_signal ("sys", SIGSYS);
6214 #endif
6215 #ifdef SIGPIPE
6216 parse_signal ("pipe", SIGPIPE);
6217 #endif
6218 #ifdef SIGALRM
6219 parse_signal ("alrm", SIGALRM);
6220 #endif
6221 #ifdef SIGURG
6222 parse_signal ("urg", SIGURG);
6223 #endif
6224 #ifdef SIGSTOP
6225 parse_signal ("stop", SIGSTOP);
6226 #endif
6227 #ifdef SIGTSTP
6228 parse_signal ("tstp", SIGTSTP);
6229 #endif
6230 #ifdef SIGCONT
6231 parse_signal ("cont", SIGCONT);
6232 #endif
6233 #ifdef SIGCHLD
6234 parse_signal ("chld", SIGCHLD);
6235 #endif
6236 #ifdef SIGTTIN
6237 parse_signal ("ttin", SIGTTIN);
6238 #endif
6239 #ifdef SIGTTOU
6240 parse_signal ("ttou", SIGTTOU);
6241 #endif
6242 #ifdef SIGIO
6243 parse_signal ("io", SIGIO);
6244 #endif
6245 #ifdef SIGXCPU
6246 parse_signal ("xcpu", SIGXCPU);
6247 #endif
6248 #ifdef SIGXFSZ
6249 parse_signal ("xfsz", SIGXFSZ);
6250 #endif
6251 #ifdef SIGVTALRM
6252 parse_signal ("vtalrm", SIGVTALRM);
6253 #endif
6254 #ifdef SIGPROF
6255 parse_signal ("prof", SIGPROF);
6256 #endif
6257 #ifdef SIGWINCH
6258 parse_signal ("winch", SIGWINCH);
6259 #endif
6260 #ifdef SIGINFO
6261 parse_signal ("info", SIGINFO);
6262 #endif
6263 else
6264 error ("Undefined signal name %s", name);
6267 #undef parse_signal
6269 return make_number (kill (pid, XINT (sigcode)));
6272 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6273 doc: /* Make PROCESS see end-of-file in its input.
6274 EOF comes after any text already sent to it.
6275 PROCESS may be a process, a buffer, the name of a process or buffer, or
6276 nil, indicating the current buffer's process.
6277 If PROCESS is a network connection, or is a process communicating
6278 through a pipe (as opposed to a pty), then you cannot send any more
6279 text to PROCESS after you call this function. */)
6280 (process)
6281 Lisp_Object process;
6283 Lisp_Object proc;
6284 struct coding_system *coding;
6286 if (DATAGRAM_CONN_P (process))
6287 return process;
6289 proc = get_process (process);
6290 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
6292 /* Make sure the process is really alive. */
6293 if (XPROCESS (proc)->raw_status_new)
6294 update_status (XPROCESS (proc));
6295 if (! EQ (XPROCESS (proc)->status, Qrun))
6296 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6298 if (CODING_REQUIRE_FLUSHING (coding))
6300 coding->mode |= CODING_MODE_LAST_BLOCK;
6301 send_process (proc, "", 0, Qnil);
6304 #ifdef VMS
6305 send_process (proc, "\032", 1, Qnil); /* ^z */
6306 #else
6307 if (!NILP (XPROCESS (proc)->pty_flag))
6308 send_process (proc, "\004", 1, Qnil);
6309 else
6311 int old_outfd, new_outfd;
6313 #ifdef HAVE_SHUTDOWN
6314 /* If this is a network connection, or socketpair is used
6315 for communication with the subprocess, call shutdown to cause EOF.
6316 (In some old system, shutdown to socketpair doesn't work.
6317 Then we just can't win.) */
6318 if (XPROCESS (proc)->pid == 0
6319 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
6320 shutdown (XINT (XPROCESS (proc)->outfd), 1);
6321 /* In case of socketpair, outfd == infd, so don't close it. */
6322 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
6323 emacs_close (XINT (XPROCESS (proc)->outfd));
6324 #else /* not HAVE_SHUTDOWN */
6325 emacs_close (XINT (XPROCESS (proc)->outfd));
6326 #endif /* not HAVE_SHUTDOWN */
6327 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6328 if (new_outfd < 0)
6329 abort ();
6330 old_outfd = XINT (XPROCESS (proc)->outfd);
6332 if (!proc_encode_coding_system[new_outfd])
6333 proc_encode_coding_system[new_outfd]
6334 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6335 bcopy (proc_encode_coding_system[old_outfd],
6336 proc_encode_coding_system[new_outfd],
6337 sizeof (struct coding_system));
6338 bzero (proc_encode_coding_system[old_outfd],
6339 sizeof (struct coding_system));
6341 XSETINT (XPROCESS (proc)->outfd, new_outfd);
6343 #endif /* VMS */
6344 return process;
6347 /* Kill all processes associated with `buffer'.
6348 If `buffer' is nil, kill all processes */
6350 void
6351 kill_buffer_processes (buffer)
6352 Lisp_Object buffer;
6354 Lisp_Object tail, proc;
6356 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6358 proc = XCDR (XCAR (tail));
6359 if (GC_PROCESSP (proc)
6360 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6362 if (NETCONN_P (proc))
6363 Fdelete_process (proc);
6364 else if (XINT (XPROCESS (proc)->infd) >= 0)
6365 process_send_signal (proc, SIGHUP, Qnil, 1);
6370 /* On receipt of a signal that a child status has changed, loop asking
6371 about children with changed statuses until the system says there
6372 are no more.
6374 All we do is change the status; we do not run sentinels or print
6375 notifications. That is saved for the next time keyboard input is
6376 done, in order to avoid timing errors.
6378 ** WARNING: this can be called during garbage collection.
6379 Therefore, it must not be fooled by the presence of mark bits in
6380 Lisp objects.
6382 ** USG WARNING: Although it is not obvious from the documentation
6383 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6384 signal() before executing at least one wait(), otherwise the
6385 handler will be called again, resulting in an infinite loop. The
6386 relevant portion of the documentation reads "SIGCLD signals will be
6387 queued and the signal-catching function will be continually
6388 reentered until the queue is empty". Invoking signal() causes the
6389 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6390 Inc.
6392 ** Malloc WARNING: This should never call malloc either directly or
6393 indirectly; if it does, that is a bug */
6395 #ifdef SIGCHLD
6396 SIGTYPE
6397 sigchld_handler (signo)
6398 int signo;
6400 int old_errno = errno;
6401 Lisp_Object proc;
6402 register struct Lisp_Process *p;
6403 extern EMACS_TIME *input_available_clear_time;
6405 SIGNAL_THREAD_CHECK (signo);
6407 #ifdef BSD4_1
6408 extern int sigheld;
6409 sigheld |= sigbit (SIGCHLD);
6410 #endif
6412 while (1)
6414 register EMACS_INT pid;
6415 WAITTYPE w;
6416 Lisp_Object tail;
6418 #ifdef WNOHANG
6419 #ifndef WUNTRACED
6420 #define WUNTRACED 0
6421 #endif /* no WUNTRACED */
6422 /* Keep trying to get a status until we get a definitive result. */
6425 errno = 0;
6426 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6428 while (pid < 0 && errno == EINTR);
6430 if (pid <= 0)
6432 /* PID == 0 means no processes found, PID == -1 means a real
6433 failure. We have done all our job, so return. */
6435 /* USG systems forget handlers when they are used;
6436 must reestablish each time */
6437 #if defined (USG) && !defined (POSIX_SIGNALS)
6438 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6439 #endif
6440 #ifdef BSD4_1
6441 sigheld &= ~sigbit (SIGCHLD);
6442 sigrelse (SIGCHLD);
6443 #endif
6444 errno = old_errno;
6445 return;
6447 #else
6448 pid = wait (&w);
6449 #endif /* no WNOHANG */
6451 /* Find the process that signaled us, and record its status. */
6453 /* The process can have been deleted by Fdelete_process. */
6454 tail = Fmember (make_fixnum_or_float (pid), deleted_pid_list);
6455 if (!NILP (tail))
6457 Fsetcar (tail, Qnil);
6458 goto sigchld_end_of_loop;
6461 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6462 p = 0;
6463 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6465 proc = XCDR (XCAR (tail));
6466 p = XPROCESS (proc);
6467 if (GC_EQ (p->childp, Qt) && p->pid == pid)
6468 break;
6469 p = 0;
6472 /* Look for an asynchronous process whose pid hasn't been filled
6473 in yet. */
6474 if (p == 0)
6475 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6477 proc = XCDR (XCAR (tail));
6478 p = XPROCESS (proc);
6479 if (p->pid == -1)
6480 break;
6481 p = 0;
6484 /* Change the status of the process that was found. */
6485 if (p != 0)
6487 union { int i; WAITTYPE wt; } u;
6488 int clear_desc_flag = 0;
6490 XSETINT (p->tick, ++process_tick);
6491 u.wt = w;
6492 p->raw_status = u.i;
6493 p->raw_status_new = 1;
6495 /* If process has terminated, stop waiting for its output. */
6496 if ((WIFSIGNALED (w) || WIFEXITED (w))
6497 && XINT (p->infd) >= 0)
6498 clear_desc_flag = 1;
6500 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6501 if (clear_desc_flag)
6503 FD_CLR (XINT (p->infd), &input_wait_mask);
6504 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
6507 /* Tell wait_reading_process_output that it needs to wake up and
6508 look around. */
6509 if (input_available_clear_time)
6510 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6513 /* There was no asynchronous process found for that pid: we have
6514 a synchronous process. */
6515 else
6517 synch_process_alive = 0;
6519 /* Report the status of the synchronous process. */
6520 if (WIFEXITED (w))
6521 synch_process_retcode = WRETCODE (w);
6522 else if (WIFSIGNALED (w))
6523 synch_process_termsig = WTERMSIG (w);
6525 /* Tell wait_reading_process_output that it needs to wake up and
6526 look around. */
6527 if (input_available_clear_time)
6528 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6531 sigchld_end_of_loop:
6534 /* On some systems, we must return right away.
6535 If any more processes want to signal us, we will
6536 get another signal.
6537 Otherwise (on systems that have WNOHANG), loop around
6538 to use up all the processes that have something to tell us. */
6539 #if (defined WINDOWSNT \
6540 || (defined USG && !defined GNU_LINUX \
6541 && !(defined HPUX && defined WNOHANG)))
6542 #if defined (USG) && ! defined (POSIX_SIGNALS)
6543 signal (signo, sigchld_handler);
6544 #endif
6545 errno = old_errno;
6546 return;
6547 #endif /* USG, but not HPUX with WNOHANG */
6550 #endif /* SIGCHLD */
6553 static Lisp_Object
6554 exec_sentinel_unwind (data)
6555 Lisp_Object data;
6557 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6558 return Qnil;
6561 static Lisp_Object
6562 exec_sentinel_error_handler (error)
6563 Lisp_Object error;
6565 cmd_error_internal (error, "error in process sentinel: ");
6566 Vinhibit_quit = Qt;
6567 update_echo_area ();
6568 Fsleep_for (make_number (2), Qnil);
6569 return Qt;
6572 static void
6573 exec_sentinel (proc, reason)
6574 Lisp_Object proc, reason;
6576 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6577 register struct Lisp_Process *p = XPROCESS (proc);
6578 int count = SPECPDL_INDEX ();
6579 int outer_running_asynch_code = running_asynch_code;
6580 int waiting = waiting_for_user_input_p;
6582 if (inhibit_sentinels)
6583 return;
6585 /* No need to gcpro these, because all we do with them later
6586 is test them for EQness, and none of them should be a string. */
6587 odeactivate = Vdeactivate_mark;
6588 XSETBUFFER (obuffer, current_buffer);
6589 okeymap = current_buffer->keymap;
6591 sentinel = p->sentinel;
6592 if (NILP (sentinel))
6593 return;
6595 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6596 assure that it gets restored no matter how the sentinel exits. */
6597 p->sentinel = Qnil;
6598 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6599 /* Inhibit quit so that random quits don't screw up a running filter. */
6600 specbind (Qinhibit_quit, Qt);
6601 specbind (Qlast_nonmenu_event, Qt);
6603 /* In case we get recursively called,
6604 and we already saved the match data nonrecursively,
6605 save the same match data in safely recursive fashion. */
6606 if (outer_running_asynch_code)
6608 Lisp_Object tem;
6609 tem = Fmatch_data (Qnil, Qnil, Qnil);
6610 restore_search_regs ();
6611 record_unwind_save_match_data ();
6612 Fset_match_data (tem, Qt);
6615 /* For speed, if a search happens within this code,
6616 save the match data in a special nonrecursive fashion. */
6617 running_asynch_code = 1;
6619 internal_condition_case_1 (read_process_output_call,
6620 Fcons (sentinel,
6621 Fcons (proc, Fcons (reason, Qnil))),
6622 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6623 exec_sentinel_error_handler);
6625 /* If we saved the match data nonrecursively, restore it now. */
6626 restore_search_regs ();
6627 running_asynch_code = outer_running_asynch_code;
6629 Vdeactivate_mark = odeactivate;
6631 /* Restore waiting_for_user_input_p as it was
6632 when we were called, in case the filter clobbered it. */
6633 waiting_for_user_input_p = waiting;
6635 #if 0
6636 if (! EQ (Fcurrent_buffer (), obuffer)
6637 || ! EQ (current_buffer->keymap, okeymap))
6638 #endif
6639 /* But do it only if the caller is actually going to read events.
6640 Otherwise there's no need to make him wake up, and it could
6641 cause trouble (for example it would make sit_for return). */
6642 if (waiting_for_user_input_p == -1)
6643 record_asynch_buffer_change ();
6645 unbind_to (count, Qnil);
6648 /* Report all recent events of a change in process status
6649 (either run the sentinel or output a message).
6650 This is usually done while Emacs is waiting for keyboard input
6651 but can be done at other times. */
6653 static void
6654 status_notify (deleting_process)
6655 struct Lisp_Process *deleting_process;
6657 register Lisp_Object proc, buffer;
6658 Lisp_Object tail, msg;
6659 struct gcpro gcpro1, gcpro2;
6661 tail = Qnil;
6662 msg = Qnil;
6663 /* We need to gcpro tail; if read_process_output calls a filter
6664 which deletes a process and removes the cons to which tail points
6665 from Vprocess_alist, and then causes a GC, tail is an unprotected
6666 reference. */
6667 GCPRO2 (tail, msg);
6669 /* Set this now, so that if new processes are created by sentinels
6670 that we run, we get called again to handle their status changes. */
6671 update_tick = process_tick;
6673 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
6675 Lisp_Object symbol;
6676 register struct Lisp_Process *p;
6678 proc = Fcdr (Fcar (tail));
6679 p = XPROCESS (proc);
6681 if (XINT (p->tick) != XINT (p->update_tick))
6683 XSETINT (p->update_tick, XINT (p->tick));
6685 /* If process is still active, read any output that remains. */
6686 while (! EQ (p->filter, Qt)
6687 && ! EQ (p->status, Qconnect)
6688 && ! EQ (p->status, Qlisten)
6689 && ! EQ (p->command, Qt) /* Network process not stopped. */
6690 && XINT (p->infd) >= 0
6691 && p != deleting_process
6692 && read_process_output (proc, XINT (p->infd)) > 0);
6694 buffer = p->buffer;
6696 /* Get the text to use for the message. */
6697 if (p->raw_status_new)
6698 update_status (p);
6699 msg = status_message (p);
6701 /* If process is terminated, deactivate it or delete it. */
6702 symbol = p->status;
6703 if (CONSP (p->status))
6704 symbol = XCAR (p->status);
6706 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6707 || EQ (symbol, Qclosed))
6709 if (delete_exited_processes)
6710 remove_process (proc);
6711 else
6712 deactivate_process (proc);
6715 /* The actions above may have further incremented p->tick.
6716 So set p->update_tick again
6717 so that an error in the sentinel will not cause
6718 this code to be run again. */
6719 XSETINT (p->update_tick, XINT (p->tick));
6720 /* Now output the message suitably. */
6721 if (!NILP (p->sentinel))
6722 exec_sentinel (proc, msg);
6723 /* Don't bother with a message in the buffer
6724 when a process becomes runnable. */
6725 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6727 Lisp_Object ro, tem;
6728 struct buffer *old = current_buffer;
6729 int opoint, opoint_byte;
6730 int before, before_byte;
6732 ro = XBUFFER (buffer)->read_only;
6734 /* Avoid error if buffer is deleted
6735 (probably that's why the process is dead, too) */
6736 if (NILP (XBUFFER (buffer)->name))
6737 continue;
6738 Fset_buffer (buffer);
6740 opoint = PT;
6741 opoint_byte = PT_BYTE;
6742 /* Insert new output into buffer
6743 at the current end-of-output marker,
6744 thus preserving logical ordering of input and output. */
6745 if (XMARKER (p->mark)->buffer)
6746 Fgoto_char (p->mark);
6747 else
6748 SET_PT_BOTH (ZV, ZV_BYTE);
6750 before = PT;
6751 before_byte = PT_BYTE;
6753 tem = current_buffer->read_only;
6754 current_buffer->read_only = Qnil;
6755 insert_string ("\nProcess ");
6756 Finsert (1, &p->name);
6757 insert_string (" ");
6758 Finsert (1, &msg);
6759 current_buffer->read_only = tem;
6760 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6762 if (opoint >= before)
6763 SET_PT_BOTH (opoint + (PT - before),
6764 opoint_byte + (PT_BYTE - before_byte));
6765 else
6766 SET_PT_BOTH (opoint, opoint_byte);
6768 set_buffer_internal (old);
6771 } /* end for */
6773 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6774 redisplay_preserve_echo_area (13);
6776 UNGCPRO;
6780 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6781 Sset_process_coding_system, 1, 3, 0,
6782 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6783 DECODING will be used to decode subprocess output and ENCODING to
6784 encode subprocess input. */)
6785 (process, decoding, encoding)
6786 register Lisp_Object process, decoding, encoding;
6788 register struct Lisp_Process *p;
6790 CHECK_PROCESS (process);
6791 p = XPROCESS (process);
6792 if (XINT (p->infd) < 0)
6793 error ("Input file descriptor of %s closed", SDATA (p->name));
6794 if (XINT (p->outfd) < 0)
6795 error ("Output file descriptor of %s closed", SDATA (p->name));
6796 Fcheck_coding_system (decoding);
6797 Fcheck_coding_system (encoding);
6799 p->decode_coding_system = decoding;
6800 p->encode_coding_system = encoding;
6801 setup_process_coding_systems (process);
6803 return Qnil;
6806 DEFUN ("process-coding-system",
6807 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6808 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6809 (process)
6810 register Lisp_Object process;
6812 CHECK_PROCESS (process);
6813 return Fcons (XPROCESS (process)->decode_coding_system,
6814 XPROCESS (process)->encode_coding_system);
6817 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6818 Sset_process_filter_multibyte, 2, 2, 0,
6819 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6820 If FLAG is non-nil, the filter is given multibyte strings.
6821 If FLAG is nil, the filter is given unibyte strings. In this case,
6822 all character code conversion except for end-of-line conversion is
6823 suppressed. */)
6824 (process, flag)
6825 Lisp_Object process, flag;
6827 register struct Lisp_Process *p;
6829 CHECK_PROCESS (process);
6830 p = XPROCESS (process);
6831 p->filter_multibyte = flag;
6832 setup_process_coding_systems (process);
6834 return Qnil;
6837 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6838 Sprocess_filter_multibyte_p, 1, 1, 0,
6839 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6840 (process)
6841 Lisp_Object process;
6843 register struct Lisp_Process *p;
6845 CHECK_PROCESS (process);
6846 p = XPROCESS (process);
6848 return (NILP (p->filter_multibyte) ? Qnil : Qt);
6853 /* The first time this is called, assume keyboard input comes from DESC
6854 instead of from where we used to expect it.
6855 Subsequent calls mean assume input keyboard can come from DESC
6856 in addition to other places. */
6858 static int add_keyboard_wait_descriptor_called_flag;
6860 void
6861 add_keyboard_wait_descriptor (desc)
6862 int desc;
6864 if (! add_keyboard_wait_descriptor_called_flag)
6865 FD_CLR (0, &input_wait_mask);
6866 add_keyboard_wait_descriptor_called_flag = 1;
6867 FD_SET (desc, &input_wait_mask);
6868 FD_SET (desc, &non_process_wait_mask);
6869 if (desc > max_keyboard_desc)
6870 max_keyboard_desc = desc;
6873 /* From now on, do not expect DESC to give keyboard input. */
6875 void
6876 delete_keyboard_wait_descriptor (desc)
6877 int desc;
6879 int fd;
6880 int lim = max_keyboard_desc;
6882 FD_CLR (desc, &input_wait_mask);
6883 FD_CLR (desc, &non_process_wait_mask);
6885 if (desc == max_keyboard_desc)
6886 for (fd = 0; fd < lim; fd++)
6887 if (FD_ISSET (fd, &input_wait_mask)
6888 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6889 max_keyboard_desc = fd;
6892 /* Return nonzero if *MASK has a bit set
6893 that corresponds to one of the keyboard input descriptors. */
6895 static int
6896 keyboard_bit_set (mask)
6897 SELECT_TYPE *mask;
6899 int fd;
6901 for (fd = 0; fd <= max_keyboard_desc; fd++)
6902 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6903 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6904 return 1;
6906 return 0;
6909 void
6910 init_process ()
6912 register int i;
6914 inhibit_sentinels = 0;
6916 #ifdef SIGCHLD
6917 #ifndef CANNOT_DUMP
6918 if (! noninteractive || initialized)
6919 #endif
6920 signal (SIGCHLD, sigchld_handler);
6921 #endif
6923 FD_ZERO (&input_wait_mask);
6924 FD_ZERO (&non_keyboard_wait_mask);
6925 FD_ZERO (&non_process_wait_mask);
6926 max_process_desc = 0;
6928 #ifdef NON_BLOCKING_CONNECT
6929 FD_ZERO (&connect_wait_mask);
6930 num_pending_connects = 0;
6931 #endif
6933 #ifdef ADAPTIVE_READ_BUFFERING
6934 process_output_delay_count = 0;
6935 process_output_skip = 0;
6936 #endif
6938 FD_SET (0, &input_wait_mask);
6940 Vprocess_alist = Qnil;
6941 #ifdef SIGCHLD
6942 deleted_pid_list = Qnil;
6943 #endif
6944 for (i = 0; i < MAXDESC; i++)
6946 chan_process[i] = Qnil;
6947 proc_buffered_char[i] = -1;
6949 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
6950 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
6951 #ifdef DATAGRAM_SOCKETS
6952 bzero (datagram_address, sizeof datagram_address);
6953 #endif
6955 #ifdef HAVE_SOCKETS
6957 Lisp_Object subfeatures = Qnil;
6958 struct socket_options *sopt;
6960 #define ADD_SUBFEATURE(key, val) \
6961 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
6963 #ifdef NON_BLOCKING_CONNECT
6964 ADD_SUBFEATURE (QCnowait, Qt);
6965 #endif
6966 #ifdef DATAGRAM_SOCKETS
6967 ADD_SUBFEATURE (QCtype, Qdatagram);
6968 #endif
6969 #ifdef HAVE_LOCAL_SOCKETS
6970 ADD_SUBFEATURE (QCfamily, Qlocal);
6971 #endif
6972 ADD_SUBFEATURE (QCfamily, Qipv4);
6973 #ifdef AF_INET6
6974 ADD_SUBFEATURE (QCfamily, Qipv6);
6975 #endif
6976 #ifdef HAVE_GETSOCKNAME
6977 ADD_SUBFEATURE (QCservice, Qt);
6978 #endif
6979 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
6980 ADD_SUBFEATURE (QCserver, Qt);
6981 #endif
6983 for (sopt = socket_options; sopt->name; sopt++)
6984 subfeatures = Fcons (intern (sopt->name), subfeatures);
6986 Fprovide (intern ("make-network-process"), subfeatures);
6988 #endif /* HAVE_SOCKETS */
6990 #if defined (DARWIN) || defined (MAC_OSX)
6991 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
6992 processes. As such, we only change the default value. */
6993 if (initialized)
6995 char *release = get_operating_system_release();
6996 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
6997 && release[1] == '.')) {
6998 Vprocess_connection_type = Qnil;
7001 #endif
7004 void
7005 syms_of_process ()
7007 Qprocessp = intern ("processp");
7008 staticpro (&Qprocessp);
7009 Qrun = intern ("run");
7010 staticpro (&Qrun);
7011 Qstop = intern ("stop");
7012 staticpro (&Qstop);
7013 Qsignal = intern ("signal");
7014 staticpro (&Qsignal);
7016 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7017 here again.
7019 Qexit = intern ("exit");
7020 staticpro (&Qexit); */
7022 Qopen = intern ("open");
7023 staticpro (&Qopen);
7024 Qclosed = intern ("closed");
7025 staticpro (&Qclosed);
7026 Qconnect = intern ("connect");
7027 staticpro (&Qconnect);
7028 Qfailed = intern ("failed");
7029 staticpro (&Qfailed);
7030 Qlisten = intern ("listen");
7031 staticpro (&Qlisten);
7032 Qlocal = intern ("local");
7033 staticpro (&Qlocal);
7034 Qipv4 = intern ("ipv4");
7035 staticpro (&Qipv4);
7036 #ifdef AF_INET6
7037 Qipv6 = intern ("ipv6");
7038 staticpro (&Qipv6);
7039 #endif
7040 Qdatagram = intern ("datagram");
7041 staticpro (&Qdatagram);
7043 QCname = intern (":name");
7044 staticpro (&QCname);
7045 QCbuffer = intern (":buffer");
7046 staticpro (&QCbuffer);
7047 QChost = intern (":host");
7048 staticpro (&QChost);
7049 QCservice = intern (":service");
7050 staticpro (&QCservice);
7051 QCtype = intern (":type");
7052 staticpro (&QCtype);
7053 QClocal = intern (":local");
7054 staticpro (&QClocal);
7055 QCremote = intern (":remote");
7056 staticpro (&QCremote);
7057 QCcoding = intern (":coding");
7058 staticpro (&QCcoding);
7059 QCserver = intern (":server");
7060 staticpro (&QCserver);
7061 QCnowait = intern (":nowait");
7062 staticpro (&QCnowait);
7063 QCsentinel = intern (":sentinel");
7064 staticpro (&QCsentinel);
7065 QClog = intern (":log");
7066 staticpro (&QClog);
7067 QCnoquery = intern (":noquery");
7068 staticpro (&QCnoquery);
7069 QCstop = intern (":stop");
7070 staticpro (&QCstop);
7071 QCoptions = intern (":options");
7072 staticpro (&QCoptions);
7073 QCplist = intern (":plist");
7074 staticpro (&QCplist);
7075 QCfilter_multibyte = intern (":filter-multibyte");
7076 staticpro (&QCfilter_multibyte);
7078 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7079 staticpro (&Qlast_nonmenu_event);
7081 staticpro (&Vprocess_alist);
7082 #ifdef SIGCHLD
7083 staticpro (&deleted_pid_list);
7084 #endif
7086 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7087 doc: /* *Non-nil means delete processes immediately when they exit.
7088 A value of nil means don't delete them until `list-processes' is run. */);
7090 delete_exited_processes = 1;
7092 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7093 doc: /* Control type of device used to communicate with subprocesses.
7094 Values are nil to use a pipe, or t or `pty' to use a pty.
7095 The value has no effect if the system has no ptys or if all ptys are busy:
7096 then a pipe is used in any case.
7097 The value takes effect when `start-process' is called. */);
7098 Vprocess_connection_type = Qt;
7100 #ifdef ADAPTIVE_READ_BUFFERING
7101 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7102 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7103 On some systems, when Emacs reads the output from a subprocess, the output data
7104 is read in very small blocks, potentially resulting in very poor performance.
7105 This behavior can be remedied to some extent by setting this variable to a
7106 non-nil value, as it will automatically delay reading from such processes, to
7107 allow them to produce more output before Emacs tries to read it.
7108 If the value is t, the delay is reset after each write to the process; any other
7109 non-nil value means that the delay is not reset on write.
7110 The variable takes effect when `start-process' is called. */);
7111 Vprocess_adaptive_read_buffering = Qt;
7112 #endif
7114 defsubr (&Sprocessp);
7115 defsubr (&Sget_process);
7116 defsubr (&Sget_buffer_process);
7117 defsubr (&Sdelete_process);
7118 defsubr (&Sprocess_status);
7119 defsubr (&Sprocess_exit_status);
7120 defsubr (&Sprocess_id);
7121 defsubr (&Sprocess_name);
7122 defsubr (&Sprocess_tty_name);
7123 defsubr (&Sprocess_command);
7124 defsubr (&Sset_process_buffer);
7125 defsubr (&Sprocess_buffer);
7126 defsubr (&Sprocess_mark);
7127 defsubr (&Sset_process_filter);
7128 defsubr (&Sprocess_filter);
7129 defsubr (&Sset_process_sentinel);
7130 defsubr (&Sprocess_sentinel);
7131 defsubr (&Sset_process_window_size);
7132 defsubr (&Sset_process_inherit_coding_system_flag);
7133 defsubr (&Sprocess_inherit_coding_system_flag);
7134 defsubr (&Sset_process_query_on_exit_flag);
7135 defsubr (&Sprocess_query_on_exit_flag);
7136 defsubr (&Sprocess_contact);
7137 defsubr (&Sprocess_plist);
7138 defsubr (&Sset_process_plist);
7139 defsubr (&Slist_processes);
7140 defsubr (&Sprocess_list);
7141 defsubr (&Sstart_process);
7142 #ifdef HAVE_SOCKETS
7143 defsubr (&Sset_network_process_option);
7144 defsubr (&Smake_network_process);
7145 defsubr (&Sformat_network_address);
7146 #endif /* HAVE_SOCKETS */
7147 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7148 #ifdef SIOCGIFCONF
7149 defsubr (&Snetwork_interface_list);
7150 #endif
7151 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7152 defsubr (&Snetwork_interface_info);
7153 #endif
7154 #endif /* HAVE_SOCKETS ... */
7155 #ifdef DATAGRAM_SOCKETS
7156 defsubr (&Sprocess_datagram_address);
7157 defsubr (&Sset_process_datagram_address);
7158 #endif
7159 defsubr (&Saccept_process_output);
7160 defsubr (&Sprocess_send_region);
7161 defsubr (&Sprocess_send_string);
7162 defsubr (&Sinterrupt_process);
7163 defsubr (&Skill_process);
7164 defsubr (&Squit_process);
7165 defsubr (&Sstop_process);
7166 defsubr (&Scontinue_process);
7167 defsubr (&Sprocess_running_child_p);
7168 defsubr (&Sprocess_send_eof);
7169 defsubr (&Ssignal_process);
7170 defsubr (&Swaiting_for_user_input_p);
7171 /* defsubr (&Sprocess_connection); */
7172 defsubr (&Sset_process_coding_system);
7173 defsubr (&Sprocess_coding_system);
7174 defsubr (&Sset_process_filter_multibyte);
7175 defsubr (&Sprocess_filter_multibyte_p);
7179 #else /* not subprocesses */
7181 #include <sys/types.h>
7182 #include <errno.h>
7184 #include "lisp.h"
7185 #include "systime.h"
7186 #include "charset.h"
7187 #include "coding.h"
7188 #include "termopts.h"
7189 #include "sysselect.h"
7191 extern int frame_garbaged;
7193 extern EMACS_TIME timer_check ();
7194 extern int timers_run;
7196 Lisp_Object QCtype;
7198 /* As described above, except assuming that there are no subprocesses:
7200 Wait for timeout to elapse and/or keyboard input to be available.
7202 time_limit is:
7203 timeout in seconds, or
7204 zero for no limit, or
7205 -1 means gobble data immediately available but don't wait for any.
7207 read_kbd is a Lisp_Object:
7208 0 to ignore keyboard input, or
7209 1 to return when input is available, or
7210 -1 means caller will actually read the input, so don't throw to
7211 the quit handler.
7213 see full version for other parameters. We know that wait_proc will
7214 always be NULL, since `subprocesses' isn't defined.
7216 do_display != 0 means redisplay should be done to show subprocess
7217 output that arrives.
7219 Return true iff we received input from any process. */
7222 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7223 wait_for_cell, wait_proc, just_wait_proc)
7224 int time_limit, microsecs, read_kbd, do_display;
7225 Lisp_Object wait_for_cell;
7226 struct Lisp_Process *wait_proc;
7227 int just_wait_proc;
7229 register int nfds;
7230 EMACS_TIME end_time, timeout;
7231 SELECT_TYPE waitchannels;
7232 int xerrno;
7234 /* What does time_limit really mean? */
7235 if (time_limit || microsecs)
7237 EMACS_GET_TIME (end_time);
7238 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7239 EMACS_ADD_TIME (end_time, end_time, timeout);
7242 /* Turn off periodic alarms (in case they are in use)
7243 and then turn off any other atimers,
7244 because the select emulator uses alarms. */
7245 stop_polling ();
7246 turn_on_atimers (0);
7248 while (1)
7250 int timeout_reduced_for_timers = 0;
7252 /* If calling from keyboard input, do not quit
7253 since we want to return C-g as an input character.
7254 Otherwise, do pending quit if requested. */
7255 if (read_kbd >= 0)
7256 QUIT;
7258 /* Exit now if the cell we're waiting for became non-nil. */
7259 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7260 break;
7262 /* Compute time from now till when time limit is up */
7263 /* Exit if already run out */
7264 if (time_limit == -1)
7266 /* -1 specified for timeout means
7267 gobble output available now
7268 but don't wait at all. */
7270 EMACS_SET_SECS_USECS (timeout, 0, 0);
7272 else if (time_limit || microsecs)
7274 EMACS_GET_TIME (timeout);
7275 EMACS_SUB_TIME (timeout, end_time, timeout);
7276 if (EMACS_TIME_NEG_P (timeout))
7277 break;
7279 else
7281 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7284 /* If our caller will not immediately handle keyboard events,
7285 run timer events directly.
7286 (Callers that will immediately read keyboard events
7287 call timer_delay on their own.) */
7288 if (NILP (wait_for_cell))
7290 EMACS_TIME timer_delay;
7294 int old_timers_run = timers_run;
7295 timer_delay = timer_check (1);
7296 if (timers_run != old_timers_run && do_display)
7297 /* We must retry, since a timer may have requeued itself
7298 and that could alter the time delay. */
7299 redisplay_preserve_echo_area (14);
7300 else
7301 break;
7303 while (!detect_input_pending ());
7305 /* If there is unread keyboard input, also return. */
7306 if (read_kbd != 0
7307 && requeued_events_pending_p ())
7308 break;
7310 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7312 EMACS_TIME difference;
7313 EMACS_SUB_TIME (difference, timer_delay, timeout);
7314 if (EMACS_TIME_NEG_P (difference))
7316 timeout = timer_delay;
7317 timeout_reduced_for_timers = 1;
7322 /* Cause C-g and alarm signals to take immediate action,
7323 and cause input available signals to zero out timeout. */
7324 if (read_kbd < 0)
7325 set_waiting_for_input (&timeout);
7327 /* Wait till there is something to do. */
7329 if (! read_kbd && NILP (wait_for_cell))
7330 FD_ZERO (&waitchannels);
7331 else
7332 FD_SET (0, &waitchannels);
7334 /* If a frame has been newly mapped and needs updating,
7335 reprocess its display stuff. */
7336 if (frame_garbaged && do_display)
7338 clear_waiting_for_input ();
7339 redisplay_preserve_echo_area (15);
7340 if (read_kbd < 0)
7341 set_waiting_for_input (&timeout);
7344 if (read_kbd && detect_input_pending ())
7346 nfds = 0;
7347 FD_ZERO (&waitchannels);
7349 else
7350 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7351 &timeout);
7353 xerrno = errno;
7355 /* Make C-g and alarm signals set flags again */
7356 clear_waiting_for_input ();
7358 /* If we woke up due to SIGWINCH, actually change size now. */
7359 do_pending_window_change (0);
7361 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7362 /* We waited the full specified time, so return now. */
7363 break;
7365 if (nfds == -1)
7367 /* If the system call was interrupted, then go around the
7368 loop again. */
7369 if (xerrno == EINTR)
7370 FD_ZERO (&waitchannels);
7371 else
7372 error ("select error: %s", emacs_strerror (xerrno));
7374 #ifdef sun
7375 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7376 /* System sometimes fails to deliver SIGIO. */
7377 kill (getpid (), SIGIO);
7378 #endif
7379 #ifdef SIGIO
7380 if (read_kbd && interrupt_input && (waitchannels & 1))
7381 kill (getpid (), SIGIO);
7382 #endif
7384 /* Check for keyboard input */
7386 if (read_kbd
7387 && detect_input_pending_run_timers (do_display))
7389 swallow_events (do_display);
7390 if (detect_input_pending_run_timers (do_display))
7391 break;
7394 /* If there is unread keyboard input, also return. */
7395 if (read_kbd
7396 && requeued_events_pending_p ())
7397 break;
7399 /* If wait_for_cell. check for keyboard input
7400 but don't run any timers.
7401 ??? (It seems wrong to me to check for keyboard
7402 input at all when wait_for_cell, but the code
7403 has been this way since July 1994.
7404 Try changing this after version 19.31.) */
7405 if (! NILP (wait_for_cell)
7406 && detect_input_pending ())
7408 swallow_events (do_display);
7409 if (detect_input_pending ())
7410 break;
7413 /* Exit now if the cell we're waiting for became non-nil. */
7414 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7415 break;
7418 start_polling ();
7420 return 0;
7424 /* Don't confuse make-docfile by having two doc strings for this function.
7425 make-docfile does not pay attention to #if, for good reason! */
7426 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7428 (name)
7429 register Lisp_Object name;
7431 return Qnil;
7434 /* Don't confuse make-docfile by having two doc strings for this function.
7435 make-docfile does not pay attention to #if, for good reason! */
7436 DEFUN ("process-inherit-coding-system-flag",
7437 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7438 1, 1, 0,
7440 (process)
7441 register Lisp_Object process;
7443 /* Ignore the argument and return the value of
7444 inherit-process-coding-system. */
7445 return inherit_process_coding_system ? Qt : Qnil;
7448 /* Kill all processes associated with `buffer'.
7449 If `buffer' is nil, kill all processes.
7450 Since we have no subprocesses, this does nothing. */
7452 void
7453 kill_buffer_processes (buffer)
7454 Lisp_Object buffer;
7458 void
7459 init_process ()
7463 void
7464 syms_of_process ()
7466 QCtype = intern (":type");
7467 staticpro (&QCtype);
7469 defsubr (&Sget_buffer_process);
7470 defsubr (&Sprocess_inherit_coding_system_flag);
7474 #endif /* not subprocesses */
7476 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7477 (do not change this comment) */