Oops...describe the file...
[emacs.git] / src / process.c
blob0204388e6722e307dc251221de6e0e926e17354d
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 3, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
24 #include <config.h>
25 #include <signal.h>
27 /* This file is split into two parts by the following preprocessor
28 conditional. The 'then' clause contains all of the support for
29 asynchronous subprocesses. The 'else' clause contains stub
30 versions of some of the asynchronous subprocess routines that are
31 often called elsewhere in Emacs, so we don't have to #ifdef the
32 sections that call them. */
35 #ifdef subprocesses
37 #include <stdio.h>
38 #include <errno.h>
39 #include <setjmp.h>
40 #include <sys/types.h> /* some typedefs are used in sys/file.h */
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_INTTYPES_H
44 #include <inttypes.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
50 #if defined(WINDOWSNT) || defined(UNIX98_PTYS)
51 #include <stdlib.h>
52 #include <fcntl.h>
53 #endif /* not WINDOWSNT */
55 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
56 #include <sys/socket.h>
57 #include <netdb.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
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 #ifdef HAVE_RES_INIT
125 #include <netinet/in.h>
126 #include <arpa/nameser.h>
127 #include <resolv.h>
128 #endif
130 #include "lisp.h"
131 #include "systime.h"
132 #include "systty.h"
134 #include "window.h"
135 #include "buffer.h"
136 #include "charset.h"
137 #include "coding.h"
138 #include "process.h"
139 #include "frame.h"
140 #include "termhooks.h"
141 #include "termopts.h"
142 #include "commands.h"
143 #include "keyboard.h"
144 #include "blockinput.h"
145 #include "dispextern.h"
146 #include "composite.h"
147 #include "atimer.h"
149 Lisp_Object Qprocessp;
150 Lisp_Object Qrun, Qstop, Qsignal;
151 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
152 Lisp_Object Qlocal, Qipv4, Qdatagram;
153 #ifdef AF_INET6
154 Lisp_Object Qipv6;
155 #endif
156 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
157 Lisp_Object QClocal, QCremote, QCcoding;
158 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
159 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
160 Lisp_Object QCfilter_multibyte;
161 Lisp_Object Qlast_nonmenu_event;
162 /* QCfamily is declared and initialized in xfaces.c,
163 QCfilter in keyboard.c. */
164 extern Lisp_Object QCfamily, QCfilter;
166 /* Qexit is declared and initialized in eval.c. */
168 /* QCfamily is defined in xfaces.c. */
169 extern Lisp_Object QCfamily;
170 /* QCfilter is defined in keyboard.c. */
171 extern Lisp_Object QCfilter;
173 /* a process object is a network connection when its childp field is neither
174 Qt nor Qnil but is instead a property list (KEY VAL ...). */
176 #ifdef HAVE_SOCKETS
177 #define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
178 #define NETCONN1_P(p) (GC_CONSP ((p)->childp))
179 #else
180 #define NETCONN_P(p) 0
181 #define NETCONN1_P(p) 0
182 #endif /* HAVE_SOCKETS */
184 /* Define first descriptor number available for subprocesses. */
185 #ifdef VMS
186 #define FIRST_PROC_DESC 1
187 #else /* Not VMS */
188 #define FIRST_PROC_DESC 3
189 #endif
191 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
192 testing SIGCHLD. */
194 #if !defined (SIGCHLD) && defined (SIGCLD)
195 #define SIGCHLD SIGCLD
196 #endif /* SIGCLD */
198 #include "syssignal.h"
200 #include "syswait.h"
202 extern char *get_operating_system_release ();
204 #ifndef USE_CRT_DLL
205 extern int errno;
206 #endif
207 #ifdef VMS
208 extern char *sys_errlist[];
209 #endif
211 #ifndef HAVE_H_ERRNO
212 extern int h_errno;
213 #endif
215 /* t means use pty, nil means use a pipe,
216 maybe other values to come. */
217 static Lisp_Object Vprocess_connection_type;
219 #ifdef SKTPAIR
220 #ifndef HAVE_SOCKETS
221 #include <sys/socket.h>
222 #endif
223 #endif /* SKTPAIR */
225 /* These next two vars are non-static since sysdep.c uses them in the
226 emulation of `select'. */
227 /* Number of events of change of status of a process. */
228 int process_tick;
229 /* Number of events for which the user or sentinel has been notified. */
230 int update_tick;
232 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
234 #ifdef BROKEN_NON_BLOCKING_CONNECT
235 #undef NON_BLOCKING_CONNECT
236 #else
237 #ifndef NON_BLOCKING_CONNECT
238 #ifdef HAVE_SOCKETS
239 #ifdef HAVE_SELECT
240 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
241 #if defined (O_NONBLOCK) || defined (O_NDELAY)
242 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
243 #define NON_BLOCKING_CONNECT
244 #endif /* EWOULDBLOCK || EINPROGRESS */
245 #endif /* O_NONBLOCK || O_NDELAY */
246 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
247 #endif /* HAVE_SELECT */
248 #endif /* HAVE_SOCKETS */
249 #endif /* NON_BLOCKING_CONNECT */
250 #endif /* BROKEN_NON_BLOCKING_CONNECT */
252 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
253 this system. We need to read full packets, so we need a
254 "non-destructive" select. So we require either native select,
255 or emulation of select using FIONREAD. */
257 #ifdef BROKEN_DATAGRAM_SOCKETS
258 #undef DATAGRAM_SOCKETS
259 #else
260 #ifndef DATAGRAM_SOCKETS
261 #ifdef HAVE_SOCKETS
262 #if defined (HAVE_SELECT) || defined (FIONREAD)
263 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
264 #define DATAGRAM_SOCKETS
265 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
266 #endif /* HAVE_SELECT || FIONREAD */
267 #endif /* HAVE_SOCKETS */
268 #endif /* DATAGRAM_SOCKETS */
269 #endif /* BROKEN_DATAGRAM_SOCKETS */
271 #ifdef TERM
272 #undef NON_BLOCKING_CONNECT
273 #undef DATAGRAM_SOCKETS
274 #endif
276 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
277 #ifdef EMACS_HAS_USECS
278 #define ADAPTIVE_READ_BUFFERING
279 #endif
280 #endif
282 #ifdef ADAPTIVE_READ_BUFFERING
283 #define READ_OUTPUT_DELAY_INCREMENT 10000
284 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
285 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
287 /* Number of processes which have a non-zero read_output_delay,
288 and therefore might be delayed for adaptive read buffering. */
290 static int process_output_delay_count;
292 /* Non-zero if any process has non-nil read_output_skip. */
294 static int process_output_skip;
296 /* Non-nil means to delay reading process output to improve buffering.
297 A value of t means that delay is reset after each send, any other
298 non-nil value does not reset the delay. A value of nil disables
299 adaptive read buffering completely. */
300 static Lisp_Object Vprocess_adaptive_read_buffering;
301 #else
302 #define process_output_delay_count 0
303 #endif
306 #include "sysselect.h"
308 static int keyboard_bit_set P_ ((SELECT_TYPE *));
309 static void deactivate_process P_ ((Lisp_Object));
310 static void status_notify P_ ((struct Lisp_Process *));
311 static int read_process_output P_ ((Lisp_Object, int));
313 /* If we support a window system, turn on the code to poll periodically
314 to detect C-g. It isn't actually used when doing interrupt input. */
315 #ifdef HAVE_WINDOW_SYSTEM
316 #define POLL_FOR_INPUT
317 #endif
319 static Lisp_Object get_process ();
320 static void exec_sentinel ();
322 extern EMACS_TIME timer_check ();
323 extern int timers_run;
325 /* Mask of bits indicating the descriptors that we wait for input on. */
327 static SELECT_TYPE input_wait_mask;
329 /* Mask that excludes keyboard input descriptor(s). */
331 static SELECT_TYPE non_keyboard_wait_mask;
333 /* Mask that excludes process input descriptor(s). */
335 static SELECT_TYPE non_process_wait_mask;
337 /* Mask for the gpm mouse input descriptor. */
339 static SELECT_TYPE gpm_wait_mask;
341 #ifdef NON_BLOCKING_CONNECT
342 /* Mask of bits indicating the descriptors that we wait for connect to
343 complete on. Once they complete, they are removed from this mask
344 and added to the input_wait_mask and non_keyboard_wait_mask. */
346 static SELECT_TYPE connect_wait_mask;
348 /* Number of bits set in connect_wait_mask. */
349 static int num_pending_connects;
351 #define IF_NON_BLOCKING_CONNECT(s) s
352 #else
353 #define IF_NON_BLOCKING_CONNECT(s)
354 #endif
356 /* The largest descriptor currently in use for a process object. */
357 static int max_process_desc;
359 /* The largest descriptor currently in use for keyboard input. */
360 static int max_keyboard_desc;
362 /* The largest descriptor currently in use for gpm mouse input. */
363 static int max_gpm_desc;
365 /* Nonzero means delete a process right away if it exits. */
366 static int delete_exited_processes;
368 /* Indexed by descriptor, gives the process (if any) for that descriptor */
369 Lisp_Object chan_process[MAXDESC];
371 /* Alist of elements (NAME . PROCESS) */
372 Lisp_Object Vprocess_alist;
374 /* Buffered-ahead input char from process, indexed by channel.
375 -1 means empty (no char is buffered).
376 Used on sys V where the only way to tell if there is any
377 output from the process is to read at least one char.
378 Always -1 on systems that support FIONREAD. */
380 /* Don't make static; need to access externally. */
381 int proc_buffered_char[MAXDESC];
383 /* Table of `struct coding-system' for each process. */
384 static struct coding_system *proc_decode_coding_system[MAXDESC];
385 static struct coding_system *proc_encode_coding_system[MAXDESC];
387 #ifdef DATAGRAM_SOCKETS
388 /* Table of `partner address' for datagram sockets. */
389 struct sockaddr_and_len {
390 struct sockaddr *sa;
391 int len;
392 } datagram_address[MAXDESC];
393 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
394 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
395 #else
396 #define DATAGRAM_CHAN_P(chan) (0)
397 #define DATAGRAM_CONN_P(proc) (0)
398 #endif
400 /* Maximum number of bytes to send to a pty without an eof. */
401 static int pty_max_bytes;
403 /* Nonzero means don't run process sentinels. This is used
404 when exiting. */
405 int inhibit_sentinels;
407 #ifdef HAVE_PTYS
408 #ifdef HAVE_PTY_H
409 #include <pty.h>
410 #endif
411 /* The file name of the pty opened by allocate_pty. */
413 static char pty_name[24];
414 #endif
416 /* Compute the Lisp form of the process status, p->status, from
417 the numeric status that was returned by `wait'. */
419 static Lisp_Object status_convert ();
421 static void
422 update_status (p)
423 struct Lisp_Process *p;
425 union { int i; WAITTYPE wt; } u;
426 eassert (p->raw_status_new);
427 u.i = p->raw_status;
428 p->status = status_convert (u.wt);
429 p->raw_status_new = 0;
432 /* Convert a process status word in Unix format to
433 the list that we use internally. */
435 static Lisp_Object
436 status_convert (w)
437 WAITTYPE w;
439 if (WIFSTOPPED (w))
440 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
441 else if (WIFEXITED (w))
442 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
443 WCOREDUMP (w) ? Qt : Qnil));
444 else if (WIFSIGNALED (w))
445 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
446 WCOREDUMP (w) ? Qt : Qnil));
447 else
448 return Qrun;
451 /* Given a status-list, extract the three pieces of information
452 and store them individually through the three pointers. */
454 static void
455 decode_status (l, symbol, code, coredump)
456 Lisp_Object l;
457 Lisp_Object *symbol;
458 int *code;
459 int *coredump;
461 Lisp_Object tem;
463 if (SYMBOLP (l))
465 *symbol = l;
466 *code = 0;
467 *coredump = 0;
469 else
471 *symbol = XCAR (l);
472 tem = XCDR (l);
473 *code = XFASTINT (XCAR (tem));
474 tem = XCDR (tem);
475 *coredump = !NILP (tem);
479 /* Return a string describing a process status list. */
481 static Lisp_Object
482 status_message (p)
483 struct Lisp_Process *p;
485 Lisp_Object status = p->status;
486 Lisp_Object symbol;
487 int code, coredump;
488 Lisp_Object string, string2;
490 decode_status (status, &symbol, &code, &coredump);
492 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
494 char *signame;
495 synchronize_system_messages_locale ();
496 signame = strsignal (code);
497 if (signame == 0)
498 signame = "unknown";
499 string = build_string (signame);
500 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
501 SSET (string, 0, DOWNCASE (SREF (string, 0)));
502 return concat2 (string, string2);
504 else if (EQ (symbol, Qexit))
506 if (NETCONN1_P (p))
507 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
508 if (code == 0)
509 return build_string ("finished\n");
510 string = Fnumber_to_string (make_number (code));
511 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
512 return concat3 (build_string ("exited abnormally with code "),
513 string, string2);
515 else if (EQ (symbol, Qfailed))
517 string = Fnumber_to_string (make_number (code));
518 string2 = build_string ("\n");
519 return concat3 (build_string ("failed with code "),
520 string, string2);
522 else
523 return Fcopy_sequence (Fsymbol_name (symbol));
526 #ifdef HAVE_PTYS
528 /* Open an available pty, returning a file descriptor.
529 Return -1 on failure.
530 The file name of the terminal corresponding to the pty
531 is left in the variable pty_name. */
533 static int
534 allocate_pty ()
536 register int c, i;
537 int fd;
539 #ifdef PTY_ITERATION
540 PTY_ITERATION
541 #else
542 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
543 for (i = 0; i < 16; i++)
544 #endif
546 struct stat stb; /* Used in some PTY_OPEN. */
547 #ifdef PTY_NAME_SPRINTF
548 PTY_NAME_SPRINTF
549 #else
550 sprintf (pty_name, "/dev/pty%c%x", c, i);
551 #endif /* no PTY_NAME_SPRINTF */
553 #ifdef PTY_OPEN
554 PTY_OPEN;
555 #else /* no PTY_OPEN */
557 # ifdef IRIS
558 /* Unusual IRIS code */
559 *ptyv = emacs_open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
560 if (fd < 0)
561 return -1;
562 if (fstat (fd, &stb) < 0)
563 return -1;
564 # else /* not IRIS */
565 { /* Some systems name their pseudoterminals so that there are gaps in
566 the usual sequence - for example, on HP9000/S700 systems, there
567 are no pseudoterminals with names ending in 'f'. So we wait for
568 three failures in a row before deciding that we've reached the
569 end of the ptys. */
570 int failed_count = 0;
572 if (stat (pty_name, &stb) < 0)
574 failed_count++;
575 if (failed_count >= 3)
576 return -1;
578 else
579 failed_count = 0;
581 # ifdef O_NONBLOCK
582 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
583 # else
584 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
585 # endif
586 # endif /* not IRIS */
588 #endif /* no PTY_OPEN */
590 if (fd >= 0)
592 /* check to make certain that both sides are available
593 this avoids a nasty yet stupid bug in rlogins */
594 #ifdef PTY_TTY_NAME_SPRINTF
595 PTY_TTY_NAME_SPRINTF
596 #else
597 sprintf (pty_name, "/dev/tty%c%x", c, i);
598 #endif /* no PTY_TTY_NAME_SPRINTF */
599 #ifndef UNIPLUS
600 if (access (pty_name, 6) != 0)
602 emacs_close (fd);
603 # if !defined(IRIS) && !defined(__sgi)
604 continue;
605 # else
606 return -1;
607 # endif /* IRIS */
609 #endif /* not UNIPLUS */
610 setup_pty (fd);
611 return fd;
614 return -1;
616 #endif /* HAVE_PTYS */
618 static Lisp_Object
619 make_process (name)
620 Lisp_Object name;
622 register Lisp_Object val, tem, name1;
623 register struct Lisp_Process *p;
624 char suffix[10];
625 register int i;
627 p = allocate_process ();
629 p->infd = -1;
630 p->outfd = -1;
631 p->tick = 0;
632 p->update_tick = 0;
633 p->pid = 0;
634 p->pty_flag = 0;
635 p->raw_status_new = 0;
636 p->status = Qrun;
637 p->mark = Fmake_marker ();
639 #ifdef ADAPTIVE_READ_BUFFERING
640 p->adaptive_read_buffering = 0;
641 p->read_output_delay = 0;
642 p->read_output_skip = 0;
643 #endif
645 /* If name is already in use, modify it until it is unused. */
647 name1 = name;
648 for (i = 1; ; i++)
650 tem = Fget_process (name1);
651 if (NILP (tem)) break;
652 sprintf (suffix, "<%d>", i);
653 name1 = concat2 (name, build_string (suffix));
655 name = name1;
656 p->name = name;
657 XSETPROCESS (val, p);
658 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
659 return val;
662 static void
663 remove_process (proc)
664 register Lisp_Object proc;
666 register Lisp_Object pair;
668 pair = Frassq (proc, Vprocess_alist);
669 Vprocess_alist = Fdelq (pair, Vprocess_alist);
671 deactivate_process (proc);
674 /* Setup coding systems of PROCESS. */
676 void
677 setup_process_coding_systems (process)
678 Lisp_Object process;
680 struct Lisp_Process *p = XPROCESS (process);
681 int inch = p->infd;
682 int outch = p->outfd;
684 if (inch < 0 || outch < 0)
685 return;
687 if (!proc_decode_coding_system[inch])
688 proc_decode_coding_system[inch]
689 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
690 setup_coding_system (p->decode_coding_system,
691 proc_decode_coding_system[inch]);
692 if (! NILP (p->filter))
694 if (!p->filter_multibyte)
695 setup_raw_text_coding_system (proc_decode_coding_system[inch]);
697 else if (BUFFERP (p->buffer))
699 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
700 setup_raw_text_coding_system (proc_decode_coding_system[inch]);
703 if (!proc_encode_coding_system[outch])
704 proc_encode_coding_system[outch]
705 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
706 setup_coding_system (p->encode_coding_system,
707 proc_encode_coding_system[outch]);
708 if (proc_encode_coding_system[outch]->eol_type == CODING_EOL_UNDECIDED)
709 proc_encode_coding_system[outch]->eol_type = system_eol_type;
712 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
713 doc: /* Return t if OBJECT is a process. */)
714 (object)
715 Lisp_Object object;
717 return PROCESSP (object) ? Qt : Qnil;
720 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
721 doc: /* Return the process named NAME, or nil if there is none. */)
722 (name)
723 register Lisp_Object name;
725 if (PROCESSP (name))
726 return name;
727 CHECK_STRING (name);
728 return Fcdr (Fassoc (name, Vprocess_alist));
731 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
732 doc: /* Return the (or a) process associated with BUFFER.
733 BUFFER may be a buffer or the name of one. */)
734 (buffer)
735 register Lisp_Object buffer;
737 register Lisp_Object buf, tail, proc;
739 if (NILP (buffer)) return Qnil;
740 buf = Fget_buffer (buffer);
741 if (NILP (buf)) return Qnil;
743 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
745 proc = Fcdr (XCAR (tail));
746 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
747 return proc;
749 return Qnil;
752 /* This is how commands for the user decode process arguments. It
753 accepts a process, a process name, a buffer, a buffer name, or nil.
754 Buffers denote the first process in the buffer, and nil denotes the
755 current buffer. */
757 static Lisp_Object
758 get_process (name)
759 register Lisp_Object name;
761 register Lisp_Object proc, obj;
762 if (STRINGP (name))
764 obj = Fget_process (name);
765 if (NILP (obj))
766 obj = Fget_buffer (name);
767 if (NILP (obj))
768 error ("Process %s does not exist", SDATA (name));
770 else if (NILP (name))
771 obj = Fcurrent_buffer ();
772 else
773 obj = name;
775 /* Now obj should be either a buffer object or a process object.
777 if (BUFFERP (obj))
779 proc = Fget_buffer_process (obj);
780 if (NILP (proc))
781 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
783 else
785 CHECK_PROCESS (obj);
786 proc = obj;
788 return proc;
792 #ifdef SIGCHLD
793 /* Fdelete_process promises to immediately forget about the process, but in
794 reality, Emacs needs to remember those processes until they have been
795 treated by sigchld_handler; otherwise this handler would consider the
796 process as being synchronous and say that the synchronous process is
797 dead. */
798 static Lisp_Object deleted_pid_list;
799 #endif
801 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
802 doc: /* Delete PROCESS: kill it and forget about it immediately.
803 PROCESS may be a process, a buffer, the name of a process or buffer, or
804 nil, indicating the current buffer's process. */)
805 (process)
806 register Lisp_Object process;
808 register struct Lisp_Process *p;
810 process = get_process (process);
811 p = XPROCESS (process);
813 p->raw_status_new = 0;
814 if (NETCONN1_P (p))
816 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
817 p->tick = ++process_tick;
818 status_notify (p);
820 else if (p->infd >= 0)
822 #ifdef SIGCHLD
823 Lisp_Object symbol;
824 /* Assignment to EMACS_INT stops GCC whining about limited range
825 of data type. */
826 EMACS_INT pid = p->pid;
828 /* No problem storing the pid here, as it is still in Vprocess_alist. */
829 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
830 /* GC treated elements set to nil. */
831 Fdelq (Qnil, deleted_pid_list));
832 /* If the process has already signaled, remove it from the list. */
833 if (p->raw_status_new)
834 update_status (p);
835 symbol = p->status;
836 if (CONSP (p->status))
837 symbol = XCAR (p->status);
838 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
839 deleted_pid_list
840 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
841 else
842 #endif
844 Fkill_process (process, Qnil);
845 /* Do this now, since remove_process will make sigchld_handler do nothing. */
846 p->status
847 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
848 p->tick = ++process_tick;
849 status_notify (p);
852 remove_process (process);
853 return Qnil;
856 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
857 doc: /* Return the status of PROCESS.
858 The returned value is one of the following symbols:
859 run -- for a process that is running.
860 stop -- for a process stopped but continuable.
861 exit -- for a process that has exited.
862 signal -- for a process that has got a fatal signal.
863 open -- for a network stream connection that is open.
864 listen -- for a network stream server that is listening.
865 closed -- for a network stream connection that is closed.
866 connect -- when waiting for a non-blocking connection to complete.
867 failed -- when a non-blocking connection has failed.
868 nil -- if arg is a process name and no such process exists.
869 PROCESS may be a process, a buffer, the name of a process, or
870 nil, indicating the current buffer's process. */)
871 (process)
872 register Lisp_Object process;
874 register struct Lisp_Process *p;
875 register Lisp_Object status;
877 if (STRINGP (process))
878 process = Fget_process (process);
879 else
880 process = get_process (process);
882 if (NILP (process))
883 return process;
885 p = XPROCESS (process);
886 if (p->raw_status_new)
887 update_status (p);
888 status = p->status;
889 if (CONSP (status))
890 status = XCAR (status);
891 if (NETCONN1_P (p))
893 if (EQ (status, Qexit))
894 status = Qclosed;
895 else if (EQ (p->command, Qt))
896 status = Qstop;
897 else if (EQ (status, Qrun))
898 status = Qopen;
900 return status;
903 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
904 1, 1, 0,
905 doc: /* Return the exit status of PROCESS or the signal number that killed it.
906 If PROCESS has not yet exited or died, return 0. */)
907 (process)
908 register Lisp_Object process;
910 CHECK_PROCESS (process);
911 if (XPROCESS (process)->raw_status_new)
912 update_status (XPROCESS (process));
913 if (CONSP (XPROCESS (process)->status))
914 return XCAR (XCDR (XPROCESS (process)->status));
915 return make_number (0);
918 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
919 doc: /* Return the process id of PROCESS.
920 This is the pid of the external process which PROCESS uses or talks to.
921 For a network connection, this value is nil. */)
922 (process)
923 register Lisp_Object process;
925 /* Assignment to EMACS_INT stops GCC whining about limited range of
926 data type. */
927 EMACS_INT pid;
929 CHECK_PROCESS (process);
930 pid = XPROCESS (process)->pid;
931 return (pid ? make_fixnum_or_float (pid) : Qnil);
934 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
935 doc: /* Return the name of PROCESS, as a string.
936 This is the name of the program invoked in PROCESS,
937 possibly modified to make it unique among process names. */)
938 (process)
939 register Lisp_Object process;
941 CHECK_PROCESS (process);
942 return XPROCESS (process)->name;
945 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
946 doc: /* Return the command that was executed to start PROCESS.
947 This is a list of strings, the first string being the program executed
948 and the rest of the strings being the arguments given to it.
949 For a non-child channel, this is nil. */)
950 (process)
951 register Lisp_Object process;
953 CHECK_PROCESS (process);
954 return XPROCESS (process)->command;
957 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
958 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
959 This is the terminal that the process itself reads and writes on,
960 not the name of the pty that Emacs uses to talk with that terminal. */)
961 (process)
962 register Lisp_Object process;
964 CHECK_PROCESS (process);
965 return XPROCESS (process)->tty_name;
968 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
969 2, 2, 0,
970 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
971 (process, buffer)
972 register Lisp_Object process, buffer;
974 struct Lisp_Process *p;
976 CHECK_PROCESS (process);
977 if (!NILP (buffer))
978 CHECK_BUFFER (buffer);
979 p = XPROCESS (process);
980 p->buffer = buffer;
981 if (NETCONN1_P (p))
982 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
983 setup_process_coding_systems (process);
984 return buffer;
987 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
988 1, 1, 0,
989 doc: /* Return the buffer PROCESS is associated with.
990 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
991 (process)
992 register Lisp_Object process;
994 CHECK_PROCESS (process);
995 return XPROCESS (process)->buffer;
998 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
999 1, 1, 0,
1000 doc: /* Return the marker for the end of the last output from PROCESS. */)
1001 (process)
1002 register Lisp_Object process;
1004 CHECK_PROCESS (process);
1005 return XPROCESS (process)->mark;
1008 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1009 2, 2, 0,
1010 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
1011 A value of t means stop accepting output from the process.
1013 When a process has a filter, its buffer is not used for output.
1014 Instead, each time it does output, the entire string of output is
1015 passed to the filter.
1017 The filter gets two arguments: the process and the string of output.
1018 The string argument is normally a multibyte string, except:
1019 - if the process' input coding system is no-conversion or raw-text,
1020 it is a unibyte string (the non-converted input), or else
1021 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1022 string (the result of converting the decoded input multibyte
1023 string to unibyte with `string-make-unibyte'). */)
1024 (process, filter)
1025 register Lisp_Object process, filter;
1027 struct Lisp_Process *p;
1029 CHECK_PROCESS (process);
1030 p = XPROCESS (process);
1032 /* Don't signal an error if the process' input file descriptor
1033 is closed. This could make debugging Lisp more difficult,
1034 for example when doing something like
1036 (setq process (start-process ...))
1037 (debug)
1038 (set-process-filter process ...) */
1040 if (p->infd >= 0)
1042 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1044 FD_CLR (p->infd, &input_wait_mask);
1045 FD_CLR (p->infd, &non_keyboard_wait_mask);
1047 else if (EQ (p->filter, Qt)
1048 && !EQ (p->command, Qt)) /* Network process not stopped. */
1050 FD_SET (p->infd, &input_wait_mask);
1051 FD_SET (p->infd, &non_keyboard_wait_mask);
1055 p->filter = filter;
1056 if (NETCONN1_P (p))
1057 p->childp = Fplist_put (p->childp, QCfilter, filter);
1058 setup_process_coding_systems (process);
1059 return filter;
1062 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1063 1, 1, 0,
1064 doc: /* Returns the filter function of PROCESS; nil if none.
1065 See `set-process-filter' for more info on filter functions. */)
1066 (process)
1067 register Lisp_Object process;
1069 CHECK_PROCESS (process);
1070 return XPROCESS (process)->filter;
1073 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1074 2, 2, 0,
1075 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1076 The sentinel is called as a function when the process changes state.
1077 It gets two arguments: the process, and a string describing the change. */)
1078 (process, sentinel)
1079 register Lisp_Object process, sentinel;
1081 struct Lisp_Process *p;
1083 CHECK_PROCESS (process);
1084 p = XPROCESS (process);
1086 p->sentinel = sentinel;
1087 if (NETCONN1_P (p))
1088 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1089 return sentinel;
1092 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1093 1, 1, 0,
1094 doc: /* Return the sentinel of PROCESS; nil if none.
1095 See `set-process-sentinel' for more info on sentinels. */)
1096 (process)
1097 register Lisp_Object process;
1099 CHECK_PROCESS (process);
1100 return XPROCESS (process)->sentinel;
1103 DEFUN ("set-process-window-size", Fset_process_window_size,
1104 Sset_process_window_size, 3, 3, 0,
1105 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1106 (process, height, width)
1107 register Lisp_Object process, height, width;
1109 CHECK_PROCESS (process);
1110 CHECK_NATNUM (height);
1111 CHECK_NATNUM (width);
1113 if (XPROCESS (process)->infd < 0
1114 || set_window_size (XPROCESS (process)->infd,
1115 XINT (height), XINT (width)) <= 0)
1116 return Qnil;
1117 else
1118 return Qt;
1121 DEFUN ("set-process-inherit-coding-system-flag",
1122 Fset_process_inherit_coding_system_flag,
1123 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1124 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1125 If the second argument FLAG is non-nil, then the variable
1126 `buffer-file-coding-system' of the buffer associated with PROCESS
1127 will be bound to the value of the coding system used to decode
1128 the process output.
1130 This is useful when the coding system specified for the process buffer
1131 leaves either the character code conversion or the end-of-line conversion
1132 unspecified, or if the coding system used to decode the process output
1133 is more appropriate for saving the process buffer.
1135 Binding the variable `inherit-process-coding-system' to non-nil before
1136 starting the process is an alternative way of setting the inherit flag
1137 for the process which will run. */)
1138 (process, flag)
1139 register Lisp_Object process, flag;
1141 CHECK_PROCESS (process);
1142 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1143 return flag;
1146 DEFUN ("process-inherit-coding-system-flag",
1147 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1148 1, 1, 0,
1149 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1150 If this flag is t, `buffer-file-coding-system' of the buffer
1151 associated with PROCESS will inherit the coding system used to decode
1152 the process output. */)
1153 (process)
1154 register Lisp_Object process;
1156 CHECK_PROCESS (process);
1157 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1160 DEFUN ("set-process-query-on-exit-flag",
1161 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1162 2, 2, 0,
1163 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1164 If the second argument FLAG is non-nil, Emacs will query the user before
1165 exiting if PROCESS is running. */)
1166 (process, flag)
1167 register Lisp_Object process, flag;
1169 CHECK_PROCESS (process);
1170 XPROCESS (process)->kill_without_query = NILP (flag);
1171 return flag;
1174 DEFUN ("process-query-on-exit-flag",
1175 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1176 1, 1, 0,
1177 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1178 (process)
1179 register Lisp_Object process;
1181 CHECK_PROCESS (process);
1182 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1185 #ifdef DATAGRAM_SOCKETS
1186 Lisp_Object Fprocess_datagram_address ();
1187 #endif
1189 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1190 1, 2, 0,
1191 doc: /* Return the contact info of PROCESS; t for a real child.
1192 For a net connection, the value depends on the optional KEY arg.
1193 If KEY is nil, value is a cons cell of the form (HOST SERVICE),
1194 if KEY is t, the complete contact information for the connection is
1195 returned, else the specific value for the keyword KEY is returned.
1196 See `make-network-process' for a list of keywords. */)
1197 (process, key)
1198 register Lisp_Object process, key;
1200 Lisp_Object contact;
1202 CHECK_PROCESS (process);
1203 contact = XPROCESS (process)->childp;
1205 #ifdef DATAGRAM_SOCKETS
1206 if (DATAGRAM_CONN_P (process)
1207 && (EQ (key, Qt) || EQ (key, QCremote)))
1208 contact = Fplist_put (contact, QCremote,
1209 Fprocess_datagram_address (process));
1210 #endif
1212 if (!NETCONN_P (process) || EQ (key, Qt))
1213 return contact;
1214 if (NILP (key))
1215 return Fcons (Fplist_get (contact, QChost),
1216 Fcons (Fplist_get (contact, QCservice), Qnil));
1217 return Fplist_get (contact, key);
1220 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1221 1, 1, 0,
1222 doc: /* Return the plist of PROCESS. */)
1223 (process)
1224 register Lisp_Object process;
1226 CHECK_PROCESS (process);
1227 return XPROCESS (process)->plist;
1230 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1231 2, 2, 0,
1232 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1233 (process, plist)
1234 register Lisp_Object process, plist;
1236 CHECK_PROCESS (process);
1237 CHECK_LIST (plist);
1239 XPROCESS (process)->plist = plist;
1240 return plist;
1243 #if 0 /* Turned off because we don't currently record this info
1244 in the process. Perhaps add it. */
1245 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1246 doc: /* Return the connection type of PROCESS.
1247 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1248 a socket connection. */)
1249 (process)
1250 Lisp_Object process;
1252 return XPROCESS (process)->type;
1254 #endif
1256 #ifdef HAVE_SOCKETS
1257 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1258 1, 2, 0,
1259 doc: /* Convert network ADDRESS from internal format to a string.
1260 A 4 or 5 element vector represents an IPv4 address (with port number).
1261 An 8 or 9 element vector represents an IPv6 address (with port number).
1262 If optional second argument OMIT-PORT is non-nil, don't include a port
1263 number in the string, even when present in ADDRESS.
1264 Returns nil if format of ADDRESS is invalid. */)
1265 (address, omit_port)
1266 Lisp_Object address, omit_port;
1268 if (NILP (address))
1269 return Qnil;
1271 if (STRINGP (address)) /* AF_LOCAL */
1272 return address;
1274 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1276 register struct Lisp_Vector *p = XVECTOR (address);
1277 Lisp_Object args[10];
1278 int nargs, i;
1280 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1282 args[0] = build_string ("%d.%d.%d.%d");
1283 nargs = 4;
1285 else if (p->size == 5)
1287 args[0] = build_string ("%d.%d.%d.%d:%d");
1288 nargs = 5;
1290 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1292 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1293 nargs = 8;
1295 else if (p->size == 9)
1297 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1298 nargs = 9;
1300 else
1301 return Qnil;
1303 for (i = 0; i < nargs; i++)
1305 EMACS_INT element = XINT (p->contents[i]);
1307 if (element < 0 || element > 65535)
1308 return Qnil;
1310 if (nargs <= 5 /* IPv4 */
1311 && i < 4 /* host, not port */
1312 && element > 255)
1313 return Qnil;
1315 args[i+1] = p->contents[i];
1318 return Fformat (nargs+1, args);
1321 if (CONSP (address))
1323 Lisp_Object args[2];
1324 args[0] = build_string ("<Family %d>");
1325 args[1] = Fcar (address);
1326 return Fformat (2, args);
1329 return Qnil;
1331 #endif
1333 static Lisp_Object
1334 list_processes_1 (query_only)
1335 Lisp_Object query_only;
1337 register Lisp_Object tail, tem;
1338 Lisp_Object proc, minspace, tem1;
1339 register struct Lisp_Process *p;
1340 char tembuf[300];
1341 int w_proc, w_buffer, w_tty;
1342 int exited = 0;
1343 Lisp_Object i_status, i_buffer, i_tty, i_command;
1345 w_proc = 4; /* Proc */
1346 w_buffer = 6; /* Buffer */
1347 w_tty = 0; /* Omit if no ttys */
1349 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1351 int i;
1353 proc = Fcdr (XCAR (tail));
1354 p = XPROCESS (proc);
1355 if (NILP (p->childp))
1356 continue;
1357 if (!NILP (query_only) && p->kill_without_query)
1358 continue;
1359 if (STRINGP (p->name)
1360 && ( i = SCHARS (p->name), (i > w_proc)))
1361 w_proc = i;
1362 if (!NILP (p->buffer))
1364 if (NILP (XBUFFER (p->buffer)->name) && w_buffer < 8)
1365 w_buffer = 8; /* (Killed) */
1366 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1367 w_buffer = i;
1369 if (STRINGP (p->tty_name)
1370 && (i = SCHARS (p->tty_name), (i > w_tty)))
1371 w_tty = i;
1374 XSETFASTINT (i_status, w_proc + 1);
1375 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1376 if (w_tty)
1378 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1379 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1381 else
1383 i_tty = Qnil;
1384 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1387 XSETFASTINT (minspace, 1);
1389 set_buffer_internal (XBUFFER (Vstandard_output));
1390 current_buffer->undo_list = Qt;
1392 current_buffer->truncate_lines = Qt;
1394 write_string ("Proc", -1);
1395 Findent_to (i_status, minspace); write_string ("Status", -1);
1396 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1397 if (!NILP (i_tty))
1399 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1401 Findent_to (i_command, minspace); write_string ("Command", -1);
1402 write_string ("\n", -1);
1404 write_string ("----", -1);
1405 Findent_to (i_status, minspace); write_string ("------", -1);
1406 Findent_to (i_buffer, minspace); write_string ("------", -1);
1407 if (!NILP (i_tty))
1409 Findent_to (i_tty, minspace); write_string ("---", -1);
1411 Findent_to (i_command, minspace); write_string ("-------", -1);
1412 write_string ("\n", -1);
1414 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1416 Lisp_Object symbol;
1418 proc = Fcdr (XCAR (tail));
1419 p = XPROCESS (proc);
1420 if (NILP (p->childp))
1421 continue;
1422 if (!NILP (query_only) && p->kill_without_query)
1423 continue;
1425 Finsert (1, &p->name);
1426 Findent_to (i_status, minspace);
1428 if (p->raw_status_new)
1429 update_status (p);
1430 symbol = p->status;
1431 if (CONSP (p->status))
1432 symbol = XCAR (p->status);
1434 if (EQ (symbol, Qsignal))
1436 Lisp_Object tem;
1437 tem = Fcar (Fcdr (p->status));
1438 #ifdef VMS
1439 if (XINT (tem) < NSIG)
1440 write_string (sys_errlist [XINT (tem)], -1);
1441 else
1442 #endif
1443 Fprinc (symbol, Qnil);
1445 else if (NETCONN1_P (p))
1447 if (EQ (symbol, Qexit))
1448 write_string ("closed", -1);
1449 else if (EQ (p->command, Qt))
1450 write_string ("stopped", -1);
1451 else if (EQ (symbol, Qrun))
1452 write_string ("open", -1);
1453 else
1454 Fprinc (symbol, Qnil);
1456 else
1457 Fprinc (symbol, Qnil);
1459 if (EQ (symbol, Qexit))
1461 Lisp_Object tem;
1462 tem = Fcar (Fcdr (p->status));
1463 if (XFASTINT (tem))
1465 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1466 write_string (tembuf, -1);
1470 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1471 exited++;
1473 Findent_to (i_buffer, minspace);
1474 if (NILP (p->buffer))
1475 insert_string ("(none)");
1476 else if (NILP (XBUFFER (p->buffer)->name))
1477 insert_string ("(Killed)");
1478 else
1479 Finsert (1, &XBUFFER (p->buffer)->name);
1481 if (!NILP (i_tty))
1483 Findent_to (i_tty, minspace);
1484 if (STRINGP (p->tty_name))
1485 Finsert (1, &p->tty_name);
1488 Findent_to (i_command, minspace);
1490 if (EQ (p->status, Qlisten))
1492 Lisp_Object port = Fplist_get (p->childp, QCservice);
1493 if (INTEGERP (port))
1494 port = Fnumber_to_string (port);
1495 if (NILP (port))
1496 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1497 sprintf (tembuf, "(network %s server on %s)\n",
1498 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1499 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1500 insert_string (tembuf);
1502 else if (NETCONN1_P (p))
1504 /* For a local socket, there is no host name,
1505 so display service instead. */
1506 Lisp_Object host = Fplist_get (p->childp, QChost);
1507 if (!STRINGP (host))
1509 host = Fplist_get (p->childp, QCservice);
1510 if (INTEGERP (host))
1511 host = Fnumber_to_string (host);
1513 if (NILP (host))
1514 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1515 sprintf (tembuf, "(network %s connection to %s)\n",
1516 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1517 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1518 insert_string (tembuf);
1520 else
1522 tem = p->command;
1523 while (1)
1525 tem1 = Fcar (tem);
1526 Finsert (1, &tem1);
1527 tem = Fcdr (tem);
1528 if (NILP (tem))
1529 break;
1530 insert_string (" ");
1532 insert_string ("\n");
1535 if (exited)
1536 status_notify (NULL);
1537 return Qnil;
1540 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1541 doc: /* Display a list of all processes.
1542 If optional argument QUERY-ONLY is non-nil, only processes with
1543 the query-on-exit flag set will be listed.
1544 Any process listed as exited or signaled is actually eliminated
1545 after the listing is made. */)
1546 (query_only)
1547 Lisp_Object query_only;
1549 internal_with_output_to_temp_buffer ("*Process List*",
1550 list_processes_1, query_only);
1551 return Qnil;
1554 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1555 doc: /* Return a list of all processes. */)
1558 return Fmapcar (Qcdr, Vprocess_alist);
1561 /* Starting asynchronous inferior processes. */
1563 static Lisp_Object start_process_unwind ();
1565 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1566 doc: /* Start a program in a subprocess. Return the process object for it.
1567 NAME is name for process. It is modified if necessary to make it unique.
1568 BUFFER is the buffer (or buffer name) to associate with the process.
1570 Process output (both standard output and standard error streams) goes
1571 at end of BUFFER, unless you specify an output stream or filter
1572 function to handle the output. BUFFER may also be nil, meaning that
1573 this process is not associated with any buffer.
1575 PROGRAM is the program file name. It is searched for in PATH.
1576 Remaining arguments are strings to give program as arguments.
1578 If you want to separate standard output from standard error, invoke
1579 the command through a shell and redirect one of them using the shell
1580 syntax.
1582 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1583 (nargs, args)
1584 int nargs;
1585 register Lisp_Object *args;
1587 Lisp_Object buffer, name, program, proc, current_dir, tem;
1588 #ifdef VMS
1589 register unsigned char *new_argv;
1590 int len;
1591 #else
1592 register unsigned char **new_argv;
1593 #endif
1594 register int i;
1595 int count = SPECPDL_INDEX ();
1597 buffer = args[1];
1598 if (!NILP (buffer))
1599 buffer = Fget_buffer_create (buffer);
1601 /* Make sure that the child will be able to chdir to the current
1602 buffer's current directory, or its unhandled equivalent. We
1603 can't just have the child check for an error when it does the
1604 chdir, since it's in a vfork.
1606 We have to GCPRO around this because Fexpand_file_name and
1607 Funhandled_file_name_directory might call a file name handling
1608 function. The argument list is protected by the caller, so all
1609 we really have to worry about is buffer. */
1611 struct gcpro gcpro1, gcpro2;
1613 current_dir = current_buffer->directory;
1615 GCPRO2 (buffer, current_dir);
1617 current_dir
1618 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1619 Qnil);
1620 if (NILP (Ffile_accessible_directory_p (current_dir)))
1621 report_file_error ("Setting current directory",
1622 Fcons (current_buffer->directory, Qnil));
1624 UNGCPRO;
1627 name = args[0];
1628 CHECK_STRING (name);
1630 program = args[2];
1632 CHECK_STRING (program);
1634 proc = make_process (name);
1635 /* If an error occurs and we can't start the process, we want to
1636 remove it from the process list. This means that each error
1637 check in create_process doesn't need to call remove_process
1638 itself; it's all taken care of here. */
1639 record_unwind_protect (start_process_unwind, proc);
1641 XPROCESS (proc)->childp = Qt;
1642 XPROCESS (proc)->plist = Qnil;
1643 XPROCESS (proc)->buffer = buffer;
1644 XPROCESS (proc)->sentinel = Qnil;
1645 XPROCESS (proc)->filter = Qnil;
1646 XPROCESS (proc)->filter_multibyte
1647 = !NILP (buffer_defaults.enable_multibyte_characters);
1648 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1650 #ifdef ADAPTIVE_READ_BUFFERING
1651 XPROCESS (proc)->adaptive_read_buffering
1652 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1653 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1654 #endif
1656 /* Make the process marker point into the process buffer (if any). */
1657 if (BUFFERP (buffer))
1658 set_marker_both (XPROCESS (proc)->mark, buffer,
1659 BUF_ZV (XBUFFER (buffer)),
1660 BUF_ZV_BYTE (XBUFFER (buffer)));
1663 /* Decide coding systems for communicating with the process. Here
1664 we don't setup the structure coding_system nor pay attention to
1665 unibyte mode. They are done in create_process. */
1667 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1668 Lisp_Object coding_systems = Qt;
1669 Lisp_Object val, *args2;
1670 struct gcpro gcpro1, gcpro2;
1672 val = Vcoding_system_for_read;
1673 if (NILP (val))
1675 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1676 args2[0] = Qstart_process;
1677 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1678 GCPRO2 (proc, current_dir);
1679 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1680 UNGCPRO;
1681 if (CONSP (coding_systems))
1682 val = XCAR (coding_systems);
1683 else if (CONSP (Vdefault_process_coding_system))
1684 val = XCAR (Vdefault_process_coding_system);
1686 XPROCESS (proc)->decode_coding_system = val;
1688 val = Vcoding_system_for_write;
1689 if (NILP (val))
1691 if (EQ (coding_systems, Qt))
1693 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1694 args2[0] = Qstart_process;
1695 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1696 GCPRO2 (proc, current_dir);
1697 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1698 UNGCPRO;
1700 if (CONSP (coding_systems))
1701 val = XCDR (coding_systems);
1702 else if (CONSP (Vdefault_process_coding_system))
1703 val = XCDR (Vdefault_process_coding_system);
1705 XPROCESS (proc)->encode_coding_system = val;
1708 #ifdef VMS
1709 /* Make a one member argv with all args concatenated
1710 together separated by a blank. */
1711 len = SBYTES (program) + 2;
1712 for (i = 3; i < nargs; i++)
1714 tem = args[i];
1715 CHECK_STRING (tem);
1716 len += SBYTES (tem) + 1; /* count the blank */
1718 new_argv = (unsigned char *) alloca (len);
1719 strcpy (new_argv, SDATA (program));
1720 for (i = 3; i < nargs; i++)
1722 tem = args[i];
1723 CHECK_STRING (tem);
1724 strcat (new_argv, " ");
1725 strcat (new_argv, SDATA (tem));
1727 /* Need to add code here to check for program existence on VMS */
1729 #else /* not VMS */
1730 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1732 /* If program file name is not absolute, search our path for it.
1733 Put the name we will really use in TEM. */
1734 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1735 && !(SCHARS (program) > 1
1736 && IS_DEVICE_SEP (SREF (program, 1))))
1738 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1740 tem = Qnil;
1741 GCPRO4 (name, program, buffer, current_dir);
1742 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1743 UNGCPRO;
1744 if (NILP (tem))
1745 report_file_error ("Searching for program", Fcons (program, Qnil));
1746 tem = Fexpand_file_name (tem, Qnil);
1748 else
1750 if (!NILP (Ffile_directory_p (program)))
1751 error ("Specified program for new process is a directory");
1752 tem = program;
1755 /* If program file name starts with /: for quoting a magic name,
1756 discard that. */
1757 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1758 && SREF (tem, 1) == ':')
1759 tem = Fsubstring (tem, make_number (2), Qnil);
1761 /* Encode the file name and put it in NEW_ARGV.
1762 That's where the child will use it to execute the program. */
1763 tem = ENCODE_FILE (tem);
1764 new_argv[0] = SDATA (tem);
1766 /* Here we encode arguments by the coding system used for sending
1767 data to the process. We don't support using different coding
1768 systems for encoding arguments and for encoding data sent to the
1769 process. */
1771 for (i = 3; i < nargs; i++)
1773 tem = args[i];
1774 CHECK_STRING (tem);
1775 if (STRING_MULTIBYTE (tem))
1776 tem = (code_convert_string_norecord
1777 (tem, XPROCESS (proc)->encode_coding_system, 1));
1778 new_argv[i - 2] = SDATA (tem);
1780 new_argv[i - 2] = 0;
1781 #endif /* not VMS */
1783 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1784 XPROCESS (proc)->decoding_carryover = 0;
1785 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1787 XPROCESS (proc)->inherit_coding_system_flag
1788 = !(NILP (buffer) || !inherit_process_coding_system);
1790 create_process (proc, (char **) new_argv, current_dir);
1792 return unbind_to (count, proc);
1795 /* This function is the unwind_protect form for Fstart_process. If
1796 PROC doesn't have its pid set, then we know someone has signaled
1797 an error and the process wasn't started successfully, so we should
1798 remove it from the process list. */
1799 static Lisp_Object
1800 start_process_unwind (proc)
1801 Lisp_Object proc;
1803 if (!PROCESSP (proc))
1804 abort ();
1806 /* Was PROC started successfully? */
1807 if (XPROCESS (proc)->pid <= 0)
1808 remove_process (proc);
1810 return Qnil;
1813 static void
1814 create_process_1 (timer)
1815 struct atimer *timer;
1817 /* Nothing to do. */
1821 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1822 #ifdef USG
1823 #ifdef SIGCHLD
1824 /* Mimic blocking of signals on system V, which doesn't really have it. */
1826 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1827 int sigchld_deferred;
1829 SIGTYPE
1830 create_process_sigchld ()
1832 signal (SIGCHLD, create_process_sigchld);
1834 sigchld_deferred = 1;
1836 #endif
1837 #endif
1838 #endif
1840 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1841 void
1842 create_process (process, new_argv, current_dir)
1843 Lisp_Object process;
1844 char **new_argv;
1845 Lisp_Object current_dir;
1847 int inchannel, outchannel;
1848 pid_t pid;
1849 int sv[2];
1850 #ifdef POSIX_SIGNALS
1851 sigset_t procmask;
1852 sigset_t blocked;
1853 struct sigaction sigint_action;
1854 struct sigaction sigquit_action;
1855 #ifdef AIX
1856 struct sigaction sighup_action;
1857 #endif
1858 #else /* !POSIX_SIGNALS */
1859 #if 0
1860 #ifdef SIGCHLD
1861 SIGTYPE (*sigchld)();
1862 #endif
1863 #endif /* 0 */
1864 #endif /* !POSIX_SIGNALS */
1865 /* Use volatile to protect variables from being clobbered by longjmp. */
1866 volatile int forkin, forkout;
1867 volatile int pty_flag = 0;
1868 #ifndef USE_CRT_DLL
1869 extern char **environ;
1870 #endif
1872 inchannel = outchannel = -1;
1874 #ifdef HAVE_PTYS
1875 if (!NILP (Vprocess_connection_type))
1876 outchannel = inchannel = allocate_pty ();
1878 if (inchannel >= 0)
1880 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1881 /* On most USG systems it does not work to open the pty's tty here,
1882 then close it and reopen it in the child. */
1883 #ifdef O_NOCTTY
1884 /* Don't let this terminal become our controlling terminal
1885 (in case we don't have one). */
1886 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1887 #else
1888 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1889 #endif
1890 if (forkin < 0)
1891 report_file_error ("Opening pty", Qnil);
1892 #if defined (RTU) || defined (UNIPLUS) || defined (DONT_REOPEN_PTY)
1893 /* In the case that vfork is defined as fork, the parent process
1894 (Emacs) may send some data before the child process completes
1895 tty options setup. So we setup tty before forking. */
1896 child_setup_tty (forkout);
1897 #endif /* RTU or UNIPLUS or DONT_REOPEN_PTY */
1898 #else
1899 forkin = forkout = -1;
1900 #endif /* not USG, or USG_SUBTTY_WORKS */
1901 pty_flag = 1;
1903 else
1904 #endif /* HAVE_PTYS */
1905 #ifdef SKTPAIR
1907 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1908 report_file_error ("Opening socketpair", Qnil);
1909 outchannel = inchannel = sv[0];
1910 forkout = forkin = sv[1];
1912 #else /* not SKTPAIR */
1914 int tem;
1915 tem = pipe (sv);
1916 if (tem < 0)
1917 report_file_error ("Creating pipe", Qnil);
1918 inchannel = sv[0];
1919 forkout = sv[1];
1920 tem = pipe (sv);
1921 if (tem < 0)
1923 emacs_close (inchannel);
1924 emacs_close (forkout);
1925 report_file_error ("Creating pipe", Qnil);
1927 outchannel = sv[1];
1928 forkin = sv[0];
1930 #endif /* not SKTPAIR */
1932 #if 0
1933 /* Replaced by close_process_descs */
1934 set_exclusive_use (inchannel);
1935 set_exclusive_use (outchannel);
1936 #endif
1938 /* Stride people say it's a mystery why this is needed
1939 as well as the O_NDELAY, but that it fails without this. */
1940 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1942 int one = 1;
1943 ioctl (inchannel, FIONBIO, &one);
1945 #endif
1947 #ifdef O_NONBLOCK
1948 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1949 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1950 #else
1951 #ifdef O_NDELAY
1952 fcntl (inchannel, F_SETFL, O_NDELAY);
1953 fcntl (outchannel, F_SETFL, O_NDELAY);
1954 #endif
1955 #endif
1957 /* Record this as an active process, with its channels.
1958 As a result, child_setup will close Emacs's side of the pipes. */
1959 chan_process[inchannel] = process;
1960 XPROCESS (process)->infd = inchannel;
1961 XPROCESS (process)->outfd = outchannel;
1963 /* Previously we recorded the tty descriptor used in the subprocess.
1964 It was only used for getting the foreground tty process, so now
1965 we just reopen the device (see emacs_get_tty_pgrp) as this is
1966 more portable (see USG_SUBTTY_WORKS above). */
1968 XPROCESS (process)->pty_flag = pty_flag;
1969 XPROCESS (process)->status = Qrun;
1970 setup_process_coding_systems (process);
1972 /* Delay interrupts until we have a chance to store
1973 the new fork's pid in its process structure */
1974 #ifdef POSIX_SIGNALS
1975 sigemptyset (&blocked);
1976 #ifdef SIGCHLD
1977 sigaddset (&blocked, SIGCHLD);
1978 #endif
1979 #ifdef HAVE_WORKING_VFORK
1980 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1981 this sets the parent's signal handlers as well as the child's.
1982 So delay all interrupts whose handlers the child might munge,
1983 and record the current handlers so they can be restored later. */
1984 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1985 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1986 #ifdef AIX
1987 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1988 #endif
1989 #endif /* HAVE_WORKING_VFORK */
1990 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1991 #else /* !POSIX_SIGNALS */
1992 #ifdef SIGCHLD
1993 #ifdef BSD4_1
1994 sighold (SIGCHLD);
1995 #else /* not BSD4_1 */
1996 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1997 sigsetmask (sigmask (SIGCHLD));
1998 #else /* ordinary USG */
1999 #if 0
2000 sigchld_deferred = 0;
2001 sigchld = signal (SIGCHLD, create_process_sigchld);
2002 #endif
2003 #endif /* ordinary USG */
2004 #endif /* not BSD4_1 */
2005 #endif /* SIGCHLD */
2006 #endif /* !POSIX_SIGNALS */
2008 FD_SET (inchannel, &input_wait_mask);
2009 FD_SET (inchannel, &non_keyboard_wait_mask);
2010 if (inchannel > max_process_desc)
2011 max_process_desc = inchannel;
2013 /* Until we store the proper pid, enable sigchld_handler
2014 to recognize an unknown pid as standing for this process.
2015 It is very important not to let this `marker' value stay
2016 in the table after this function has returned; if it does
2017 it might cause call-process to hang and subsequent asynchronous
2018 processes to get their return values scrambled. */
2019 XPROCESS (process)->pid = -1;
2021 BLOCK_INPUT;
2024 /* child_setup must clobber environ on systems with true vfork.
2025 Protect it from permanent change. */
2026 char **save_environ = environ;
2028 current_dir = ENCODE_FILE (current_dir);
2030 #ifndef WINDOWSNT
2031 pid = vfork ();
2032 if (pid == 0)
2033 #endif /* not WINDOWSNT */
2035 int xforkin = forkin;
2036 int xforkout = forkout;
2038 #if 0 /* This was probably a mistake--it duplicates code later on,
2039 but fails to handle all the cases. */
2040 /* Make sure SIGCHLD is not blocked in the child. */
2041 sigsetmask (SIGEMPTYMASK);
2042 #endif
2044 /* Make the pty be the controlling terminal of the process. */
2045 #ifdef HAVE_PTYS
2046 /* First, disconnect its current controlling terminal. */
2047 #ifdef HAVE_SETSID
2048 /* We tried doing setsid only if pty_flag, but it caused
2049 process_set_signal to fail on SGI when using a pipe. */
2050 setsid ();
2051 /* Make the pty's terminal the controlling terminal. */
2052 if (pty_flag)
2054 #ifdef TIOCSCTTY
2055 /* We ignore the return value
2056 because faith@cs.unc.edu says that is necessary on Linux. */
2057 ioctl (xforkin, TIOCSCTTY, 0);
2058 #endif
2060 #else /* not HAVE_SETSID */
2061 #ifdef USG
2062 /* It's very important to call setpgrp here and no time
2063 afterwards. Otherwise, we lose our controlling tty which
2064 is set when we open the pty. */
2065 setpgrp ();
2066 #endif /* USG */
2067 #endif /* not HAVE_SETSID */
2068 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2069 if (pty_flag && xforkin >= 0)
2071 struct termios t;
2072 tcgetattr (xforkin, &t);
2073 t.c_lflag = LDISC1;
2074 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2075 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2077 #else
2078 #if defined (NTTYDISC) && defined (TIOCSETD)
2079 if (pty_flag && xforkin >= 0)
2081 /* Use new line discipline. */
2082 int ldisc = NTTYDISC;
2083 ioctl (xforkin, TIOCSETD, &ldisc);
2085 #endif
2086 #endif
2087 #ifdef TIOCNOTTY
2088 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2089 can do TIOCSPGRP only to the process's controlling tty. */
2090 if (pty_flag)
2092 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2093 I can't test it since I don't have 4.3. */
2094 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2095 ioctl (j, TIOCNOTTY, 0);
2096 emacs_close (j);
2097 #ifndef USG
2098 /* In order to get a controlling terminal on some versions
2099 of BSD, it is necessary to put the process in pgrp 0
2100 before it opens the terminal. */
2101 #ifdef HAVE_SETPGID
2102 setpgid (0, 0);
2103 #else
2104 setpgrp (0, 0);
2105 #endif
2106 #endif
2108 #endif /* TIOCNOTTY */
2110 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
2111 /*** There is a suggestion that this ought to be a
2112 conditional on TIOCSPGRP,
2113 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2114 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2115 that system does seem to need this code, even though
2116 both HAVE_SETSID and TIOCSCTTY are defined. */
2117 /* Now close the pty (if we had it open) and reopen it.
2118 This makes the pty the controlling terminal of the subprocess. */
2119 if (pty_flag)
2121 #ifdef SET_CHILD_PTY_PGRP
2122 int pgrp = getpid ();
2123 #endif
2125 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2126 would work? */
2127 if (xforkin >= 0)
2128 emacs_close (xforkin);
2129 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2131 if (xforkin < 0)
2133 emacs_write (1, "Couldn't open the pty terminal ", 31);
2134 emacs_write (1, pty_name, strlen (pty_name));
2135 emacs_write (1, "\n", 1);
2136 _exit (1);
2139 #ifdef SET_CHILD_PTY_PGRP
2140 ioctl (xforkin, TIOCSPGRP, &pgrp);
2141 ioctl (xforkout, TIOCSPGRP, &pgrp);
2142 #endif
2144 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
2146 #ifdef SETUP_SLAVE_PTY
2147 if (pty_flag)
2149 SETUP_SLAVE_PTY;
2151 #endif /* SETUP_SLAVE_PTY */
2152 #ifdef AIX
2153 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2154 Now reenable it in the child, so it will die when we want it to. */
2155 if (pty_flag)
2156 signal (SIGHUP, SIG_DFL);
2157 #endif
2158 #endif /* HAVE_PTYS */
2160 signal (SIGINT, SIG_DFL);
2161 signal (SIGQUIT, SIG_DFL);
2163 /* Stop blocking signals in the child. */
2164 #ifdef POSIX_SIGNALS
2165 sigprocmask (SIG_SETMASK, &procmask, 0);
2166 #else /* !POSIX_SIGNALS */
2167 #ifdef SIGCHLD
2168 #ifdef BSD4_1
2169 sigrelse (SIGCHLD);
2170 #else /* not BSD4_1 */
2171 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2172 sigsetmask (SIGEMPTYMASK);
2173 #else /* ordinary USG */
2174 #if 0
2175 signal (SIGCHLD, sigchld);
2176 #endif
2177 #endif /* ordinary USG */
2178 #endif /* not BSD4_1 */
2179 #endif /* SIGCHLD */
2180 #endif /* !POSIX_SIGNALS */
2182 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
2183 if (pty_flag)
2184 child_setup_tty (xforkout);
2185 #endif /* not RTU and not UNIPLUS and not DONT_REOPEN_PTY */
2186 #ifdef WINDOWSNT
2187 pid = child_setup (xforkin, xforkout, xforkout,
2188 new_argv, 1, current_dir);
2189 #else /* not WINDOWSNT */
2190 child_setup (xforkin, xforkout, xforkout,
2191 new_argv, 1, current_dir);
2192 #endif /* not WINDOWSNT */
2194 environ = save_environ;
2197 UNBLOCK_INPUT;
2199 /* This runs in the Emacs process. */
2200 if (pid < 0)
2202 if (forkin >= 0)
2203 emacs_close (forkin);
2204 if (forkin != forkout && forkout >= 0)
2205 emacs_close (forkout);
2207 else
2209 /* vfork succeeded. */
2210 XPROCESS (process)->pid = pid;
2212 #ifdef WINDOWSNT
2213 register_child (pid, inchannel);
2214 #endif /* WINDOWSNT */
2216 /* If the subfork execv fails, and it exits,
2217 this close hangs. I don't know why.
2218 So have an interrupt jar it loose. */
2220 struct atimer *timer;
2221 EMACS_TIME offset;
2223 stop_polling ();
2224 EMACS_SET_SECS_USECS (offset, 1, 0);
2225 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2227 if (forkin >= 0)
2228 emacs_close (forkin);
2230 cancel_atimer (timer);
2231 start_polling ();
2234 if (forkin != forkout && forkout >= 0)
2235 emacs_close (forkout);
2237 #ifdef HAVE_PTYS
2238 if (pty_flag)
2239 XPROCESS (process)->tty_name = build_string (pty_name);
2240 else
2241 #endif
2242 XPROCESS (process)->tty_name = Qnil;
2245 /* Restore the signal state whether vfork succeeded or not.
2246 (We will signal an error, below, if it failed.) */
2247 #ifdef POSIX_SIGNALS
2248 #ifdef HAVE_WORKING_VFORK
2249 /* Restore the parent's signal handlers. */
2250 sigaction (SIGINT, &sigint_action, 0);
2251 sigaction (SIGQUIT, &sigquit_action, 0);
2252 #ifdef AIX
2253 sigaction (SIGHUP, &sighup_action, 0);
2254 #endif
2255 #endif /* HAVE_WORKING_VFORK */
2256 /* Stop blocking signals in the parent. */
2257 sigprocmask (SIG_SETMASK, &procmask, 0);
2258 #else /* !POSIX_SIGNALS */
2259 #ifdef SIGCHLD
2260 #ifdef BSD4_1
2261 sigrelse (SIGCHLD);
2262 #else /* not BSD4_1 */
2263 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2264 sigsetmask (SIGEMPTYMASK);
2265 #else /* ordinary USG */
2266 #if 0
2267 signal (SIGCHLD, sigchld);
2268 /* Now really handle any of these signals
2269 that came in during this function. */
2270 if (sigchld_deferred)
2271 kill (getpid (), SIGCHLD);
2272 #endif
2273 #endif /* ordinary USG */
2274 #endif /* not BSD4_1 */
2275 #endif /* SIGCHLD */
2276 #endif /* !POSIX_SIGNALS */
2278 /* Now generate the error if vfork failed. */
2279 if (pid < 0)
2280 report_file_error ("Doing vfork", Qnil);
2282 #endif /* not VMS */
2285 #ifdef HAVE_SOCKETS
2287 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2288 The address family of sa is not included in the result. */
2290 static Lisp_Object
2291 conv_sockaddr_to_lisp (sa, len)
2292 struct sockaddr *sa;
2293 int len;
2295 Lisp_Object address;
2296 int i;
2297 unsigned char *cp;
2298 register struct Lisp_Vector *p;
2300 switch (sa->sa_family)
2302 case AF_INET:
2304 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2305 len = sizeof (sin->sin_addr) + 1;
2306 address = Fmake_vector (make_number (len), Qnil);
2307 p = XVECTOR (address);
2308 p->contents[--len] = make_number (ntohs (sin->sin_port));
2309 cp = (unsigned char *)&sin->sin_addr;
2310 break;
2312 #ifdef AF_INET6
2313 case AF_INET6:
2315 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2316 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2317 len = sizeof (sin6->sin6_addr)/2 + 1;
2318 address = Fmake_vector (make_number (len), Qnil);
2319 p = XVECTOR (address);
2320 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2321 for (i = 0; i < len; i++)
2322 p->contents[i] = make_number (ntohs (ip6[i]));
2323 return address;
2325 #endif
2326 #ifdef HAVE_LOCAL_SOCKETS
2327 case AF_LOCAL:
2329 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2330 for (i = 0; i < sizeof (sockun->sun_path); i++)
2331 if (sockun->sun_path[i] == 0)
2332 break;
2333 return make_unibyte_string (sockun->sun_path, i);
2335 #endif
2336 default:
2337 len -= sizeof (sa->sa_family);
2338 address = Fcons (make_number (sa->sa_family),
2339 Fmake_vector (make_number (len), Qnil));
2340 p = XVECTOR (XCDR (address));
2341 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2342 break;
2345 i = 0;
2346 while (i < len)
2347 p->contents[i++] = make_number (*cp++);
2349 return address;
2353 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2355 static int
2356 get_lisp_to_sockaddr_size (address, familyp)
2357 Lisp_Object address;
2358 int *familyp;
2360 register struct Lisp_Vector *p;
2362 if (VECTORP (address))
2364 p = XVECTOR (address);
2365 if (p->size == 5)
2367 *familyp = AF_INET;
2368 return sizeof (struct sockaddr_in);
2370 #ifdef AF_INET6
2371 else if (p->size == 9)
2373 *familyp = AF_INET6;
2374 return sizeof (struct sockaddr_in6);
2376 #endif
2378 #ifdef HAVE_LOCAL_SOCKETS
2379 else if (STRINGP (address))
2381 *familyp = AF_LOCAL;
2382 return sizeof (struct sockaddr_un);
2384 #endif
2385 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2387 struct sockaddr *sa;
2388 *familyp = XINT (XCAR (address));
2389 p = XVECTOR (XCDR (address));
2390 return p->size + sizeof (sa->sa_family);
2392 return 0;
2395 /* Convert an address object (vector or string) to an internal sockaddr.
2397 The address format has been basically validated by
2398 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2399 it could have come from user data. So if FAMILY is not valid,
2400 we return after zeroing *SA. */
2402 static void
2403 conv_lisp_to_sockaddr (family, address, sa, len)
2404 int family;
2405 Lisp_Object address;
2406 struct sockaddr *sa;
2407 int len;
2409 register struct Lisp_Vector *p;
2410 register unsigned char *cp = NULL;
2411 register int i;
2413 bzero (sa, len);
2415 if (VECTORP (address))
2417 p = XVECTOR (address);
2418 if (family == AF_INET)
2420 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2421 len = sizeof (sin->sin_addr) + 1;
2422 i = XINT (p->contents[--len]);
2423 sin->sin_port = htons (i);
2424 cp = (unsigned char *)&sin->sin_addr;
2425 sa->sa_family = family;
2427 #ifdef AF_INET6
2428 else if (family == AF_INET6)
2430 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2431 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2432 len = sizeof (sin6->sin6_addr) + 1;
2433 i = XINT (p->contents[--len]);
2434 sin6->sin6_port = htons (i);
2435 for (i = 0; i < len; i++)
2436 if (INTEGERP (p->contents[i]))
2438 int j = XFASTINT (p->contents[i]) & 0xffff;
2439 ip6[i] = ntohs (j);
2441 sa->sa_family = family;
2443 #endif
2444 return;
2446 else if (STRINGP (address))
2448 #ifdef HAVE_LOCAL_SOCKETS
2449 if (family == AF_LOCAL)
2451 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2452 cp = SDATA (address);
2453 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2454 sockun->sun_path[i] = *cp++;
2455 sa->sa_family = family;
2457 #endif
2458 return;
2460 else
2462 p = XVECTOR (XCDR (address));
2463 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2466 for (i = 0; i < len; i++)
2467 if (INTEGERP (p->contents[i]))
2468 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2471 #ifdef DATAGRAM_SOCKETS
2472 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2473 1, 1, 0,
2474 doc: /* Get the current datagram address associated with PROCESS. */)
2475 (process)
2476 Lisp_Object process;
2478 int channel;
2480 CHECK_PROCESS (process);
2482 if (!DATAGRAM_CONN_P (process))
2483 return Qnil;
2485 channel = XPROCESS (process)->infd;
2486 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2487 datagram_address[channel].len);
2490 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2491 2, 2, 0,
2492 doc: /* Set the datagram address for PROCESS to ADDRESS.
2493 Returns nil upon error setting address, ADDRESS otherwise. */)
2494 (process, address)
2495 Lisp_Object process, address;
2497 int channel;
2498 int family, len;
2500 CHECK_PROCESS (process);
2502 if (!DATAGRAM_CONN_P (process))
2503 return Qnil;
2505 channel = XPROCESS (process)->infd;
2507 len = get_lisp_to_sockaddr_size (address, &family);
2508 if (datagram_address[channel].len != len)
2509 return Qnil;
2510 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2511 return address;
2513 #endif
2516 static struct socket_options {
2517 /* The name of this option. Should be lowercase version of option
2518 name without SO_ prefix. */
2519 char *name;
2520 /* Option level SOL_... */
2521 int optlevel;
2522 /* Option number SO_... */
2523 int optnum;
2524 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2525 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2526 } socket_options[] =
2528 #ifdef SO_BINDTODEVICE
2529 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2530 #endif
2531 #ifdef SO_BROADCAST
2532 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2533 #endif
2534 #ifdef SO_DONTROUTE
2535 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2536 #endif
2537 #ifdef SO_KEEPALIVE
2538 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2539 #endif
2540 #ifdef SO_LINGER
2541 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2542 #endif
2543 #ifdef SO_OOBINLINE
2544 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2545 #endif
2546 #ifdef SO_PRIORITY
2547 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2548 #endif
2549 #ifdef SO_REUSEADDR
2550 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2551 #endif
2552 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2555 /* Set option OPT to value VAL on socket S.
2557 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2558 Signals an error if setting a known option fails.
2561 static int
2562 set_socket_option (s, opt, val)
2563 int s;
2564 Lisp_Object opt, val;
2566 char *name;
2567 struct socket_options *sopt;
2568 int ret = 0;
2570 CHECK_SYMBOL (opt);
2572 name = (char *) SDATA (SYMBOL_NAME (opt));
2573 for (sopt = socket_options; sopt->name; sopt++)
2574 if (strcmp (name, sopt->name) == 0)
2575 break;
2577 switch (sopt->opttype)
2579 case SOPT_BOOL:
2581 int optval;
2582 optval = NILP (val) ? 0 : 1;
2583 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2584 &optval, sizeof (optval));
2585 break;
2588 case SOPT_INT:
2590 int optval;
2591 if (INTEGERP (val))
2592 optval = XINT (val);
2593 else
2594 error ("Bad option value for %s", name);
2595 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2596 &optval, sizeof (optval));
2597 break;
2600 #ifdef SO_BINDTODEVICE
2601 case SOPT_IFNAME:
2603 char devname[IFNAMSIZ+1];
2605 /* This is broken, at least in the Linux 2.4 kernel.
2606 To unbind, the arg must be a zero integer, not the empty string.
2607 This should work on all systems. KFS. 2003-09-23. */
2608 bzero (devname, sizeof devname);
2609 if (STRINGP (val))
2611 char *arg = (char *) SDATA (val);
2612 int len = min (strlen (arg), IFNAMSIZ);
2613 bcopy (arg, devname, len);
2615 else if (!NILP (val))
2616 error ("Bad option value for %s", name);
2617 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2618 devname, IFNAMSIZ);
2619 break;
2621 #endif
2623 #ifdef SO_LINGER
2624 case SOPT_LINGER:
2626 struct linger linger;
2628 linger.l_onoff = 1;
2629 linger.l_linger = 0;
2630 if (INTEGERP (val))
2631 linger.l_linger = XINT (val);
2632 else
2633 linger.l_onoff = NILP (val) ? 0 : 1;
2634 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2635 &linger, sizeof (linger));
2636 break;
2638 #endif
2640 default:
2641 return 0;
2644 if (ret < 0)
2645 report_file_error ("Cannot set network option",
2646 Fcons (opt, Fcons (val, Qnil)));
2647 return (1 << sopt->optbit);
2651 DEFUN ("set-network-process-option",
2652 Fset_network_process_option, Sset_network_process_option,
2653 3, 4, 0,
2654 doc: /* For network process PROCESS set option OPTION to value VALUE.
2655 See `make-network-process' for a list of options and values.
2656 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2657 OPTION is not a supported option, return nil instead; otherwise return t. */)
2658 (process, option, value, no_error)
2659 Lisp_Object process, option, value;
2660 Lisp_Object no_error;
2662 int s;
2663 struct Lisp_Process *p;
2665 CHECK_PROCESS (process);
2666 p = XPROCESS (process);
2667 if (!NETCONN1_P (p))
2668 error ("Process is not a network process");
2670 s = p->infd;
2671 if (s < 0)
2672 error ("Process is not running");
2674 if (set_socket_option (s, option, value))
2676 p->childp = Fplist_put (p->childp, option, value);
2677 return Qt;
2680 if (NILP (no_error))
2681 error ("Unknown or unsupported option");
2683 return Qnil;
2687 /* A version of request_sigio suitable for a record_unwind_protect. */
2689 #ifdef __ultrix__
2690 static Lisp_Object
2691 unwind_request_sigio (dummy)
2692 Lisp_Object dummy;
2694 if (interrupt_input)
2695 request_sigio ();
2696 return Qnil;
2698 #endif
2700 /* Create a network stream/datagram client/server process. Treated
2701 exactly like a normal process when reading and writing. Primary
2702 differences are in status display and process deletion. A network
2703 connection has no PID; you cannot signal it. All you can do is
2704 stop/continue it and deactivate/close it via delete-process */
2706 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2707 0, MANY, 0,
2708 doc: /* Create and return a network server or client process.
2710 In Emacs, network connections are represented by process objects, so
2711 input and output work as for subprocesses and `delete-process' closes
2712 a network connection. However, a network process has no process id,
2713 it cannot be signaled, and the status codes are different from normal
2714 processes.
2716 Arguments are specified as keyword/argument pairs. The following
2717 arguments are defined:
2719 :name NAME -- NAME is name for process. It is modified if necessary
2720 to make it unique.
2722 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2723 with the process. Process output goes at end of that buffer, unless
2724 you specify an output stream or filter function to handle the output.
2725 BUFFER may be also nil, meaning that this process is not associated
2726 with any buffer.
2728 :host HOST -- HOST is name of the host to connect to, or its IP
2729 address. The symbol `local' specifies the local host. If specified
2730 for a server process, it must be a valid name or address for the local
2731 host, and only clients connecting to that address will be accepted.
2733 :service SERVICE -- SERVICE is name of the service desired, or an
2734 integer specifying a port number to connect to. If SERVICE is t,
2735 a random port number is selected for the server. (If Emacs was
2736 compiled with getaddrinfo, a port number can also be specified as a
2737 string, e.g. "80", as well as an integer. This is not portable.)
2739 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2740 stream type connection, `datagram' creates a datagram type connection.
2742 :family FAMILY -- FAMILY is the address (and protocol) family for the
2743 service specified by HOST and SERVICE. The default (nil) is to use
2744 whatever address family (IPv4 or IPv6) that is defined for the host
2745 and port number specified by HOST and SERVICE. Other address families
2746 supported are:
2747 local -- for a local (i.e. UNIX) address specified by SERVICE.
2748 ipv4 -- use IPv4 address family only.
2749 ipv6 -- use IPv6 address family only.
2751 :local ADDRESS -- ADDRESS is the local address used for the connection.
2752 This parameter is ignored when opening a client process. When specified
2753 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2755 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2756 connection. This parameter is ignored when opening a stream server
2757 process. For a datagram server process, it specifies the initial
2758 setting of the remote datagram address. When specified for a client
2759 process, the FAMILY, HOST, and SERVICE args are ignored.
2761 The format of ADDRESS depends on the address family:
2762 - An IPv4 address is represented as an vector of integers [A B C D P]
2763 corresponding to numeric IP address A.B.C.D and port number P.
2764 - A local address is represented as a string with the address in the
2765 local address space.
2766 - An "unsupported family" address is represented by a cons (F . AV)
2767 where F is the family number and AV is a vector containing the socket
2768 address data with one element per address data byte. Do not rely on
2769 this format in portable code, as it may depend on implementation
2770 defined constants, data sizes, and data structure alignment.
2772 :coding CODING -- If CODING is a symbol, it specifies the coding
2773 system used for both reading and writing for this process. If CODING
2774 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2775 ENCODING is used for writing.
2777 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2778 return without waiting for the connection to complete; instead, the
2779 sentinel function will be called with second arg matching "open" (if
2780 successful) or "failed" when the connect completes. Default is to use
2781 a blocking connect (i.e. wait) for stream type connections.
2783 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2784 running when Emacs is exited.
2786 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2787 In the stopped state, a server process does not accept new
2788 connections, and a client process does not handle incoming traffic.
2789 The stopped state is cleared by `continue-process' and set by
2790 `stop-process'.
2792 :filter FILTER -- Install FILTER as the process filter.
2794 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2795 process filter are multibyte, otherwise they are unibyte.
2796 If this keyword is not specified, the strings are multibyte if
2797 `default-enable-multibyte-characters' is non-nil.
2799 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2801 :log LOG -- Install LOG as the server process log function. This
2802 function is called when the server accepts a network connection from a
2803 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2804 is the server process, CLIENT is the new process for the connection,
2805 and MESSAGE is a string.
2807 :plist PLIST -- Install PLIST as the new process' initial plist.
2809 :server QLEN -- if QLEN is non-nil, create a server process for the
2810 specified FAMILY, SERVICE, and connection type (stream or datagram).
2811 If QLEN is an integer, it is used as the max. length of the server's
2812 pending connection queue (also known as the backlog); the default
2813 queue length is 5. Default is to create a client process.
2815 The following network options can be specified for this connection:
2817 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2818 :dontroute BOOL -- Only send to directly connected hosts.
2819 :keepalive BOOL -- Send keep-alive messages on network stream.
2820 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2821 :oobinline BOOL -- Place out-of-band data in receive data stream.
2822 :priority INT -- Set protocol defined priority for sent packets.
2823 :reuseaddr BOOL -- Allow reusing a recently used local address
2824 (this is allowed by default for a server process).
2825 :bindtodevice NAME -- bind to interface NAME. Using this may require
2826 special privileges on some systems.
2828 Consult the relevant system programmer's manual pages for more
2829 information on using these options.
2832 A server process will listen for and accept connections from clients.
2833 When a client connection is accepted, a new network process is created
2834 for the connection with the following parameters:
2836 - The client's process name is constructed by concatenating the server
2837 process' NAME and a client identification string.
2838 - If the FILTER argument is non-nil, the client process will not get a
2839 separate process buffer; otherwise, the client's process buffer is a newly
2840 created buffer named after the server process' BUFFER name or process
2841 NAME concatenated with the client identification string.
2842 - The connection type and the process filter and sentinel parameters are
2843 inherited from the server process' TYPE, FILTER and SENTINEL.
2844 - The client process' contact info is set according to the client's
2845 addressing information (typically an IP address and a port number).
2846 - The client process' plist is initialized from the server's plist.
2848 Notice that the FILTER and SENTINEL args are never used directly by
2849 the server process. Also, the BUFFER argument is not used directly by
2850 the server process, but via the optional :log function, accepted (and
2851 failed) connections may be logged in the server process' buffer.
2853 The original argument list, modified with the actual connection
2854 information, is available via the `process-contact' function.
2856 usage: (make-network-process &rest ARGS) */)
2857 (nargs, args)
2858 int nargs;
2859 Lisp_Object *args;
2861 Lisp_Object proc;
2862 Lisp_Object contact;
2863 struct Lisp_Process *p;
2864 #ifdef HAVE_GETADDRINFO
2865 struct addrinfo ai, *res, *lres;
2866 struct addrinfo hints;
2867 char *portstring, portbuf[128];
2868 #else /* HAVE_GETADDRINFO */
2869 struct _emacs_addrinfo
2871 int ai_family;
2872 int ai_socktype;
2873 int ai_protocol;
2874 int ai_addrlen;
2875 struct sockaddr *ai_addr;
2876 struct _emacs_addrinfo *ai_next;
2877 } ai, *res, *lres;
2878 #endif /* HAVE_GETADDRINFO */
2879 struct sockaddr_in address_in;
2880 #ifdef HAVE_LOCAL_SOCKETS
2881 struct sockaddr_un address_un;
2882 #endif
2883 int port;
2884 int ret = 0;
2885 int xerrno = 0;
2886 int s = -1, outch, inch;
2887 struct gcpro gcpro1;
2888 int count = SPECPDL_INDEX ();
2889 int count1;
2890 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2891 Lisp_Object tem;
2892 Lisp_Object name, buffer, host, service, address;
2893 Lisp_Object filter, sentinel;
2894 int is_non_blocking_client = 0;
2895 int is_server = 0, backlog = 5;
2896 int socktype;
2897 int family = -1;
2899 if (nargs == 0)
2900 return Qnil;
2902 /* Save arguments for process-contact and clone-process. */
2903 contact = Flist (nargs, args);
2904 GCPRO1 (contact);
2906 #ifdef WINDOWSNT
2907 /* Ensure socket support is loaded if available. */
2908 init_winsock (TRUE);
2909 #endif
2911 /* :type TYPE (nil: stream, datagram */
2912 tem = Fplist_get (contact, QCtype);
2913 if (NILP (tem))
2914 socktype = SOCK_STREAM;
2915 #ifdef DATAGRAM_SOCKETS
2916 else if (EQ (tem, Qdatagram))
2917 socktype = SOCK_DGRAM;
2918 #endif
2919 else
2920 error ("Unsupported connection type");
2922 /* :server BOOL */
2923 tem = Fplist_get (contact, QCserver);
2924 if (!NILP (tem))
2926 /* Don't support network sockets when non-blocking mode is
2927 not available, since a blocked Emacs is not useful. */
2928 #if defined(TERM) || (!defined(O_NONBLOCK) && !defined(O_NDELAY))
2929 error ("Network servers not supported");
2930 #else
2931 is_server = 1;
2932 if (INTEGERP (tem))
2933 backlog = XINT (tem);
2934 #endif
2937 /* Make QCaddress an alias for :local (server) or :remote (client). */
2938 QCaddress = is_server ? QClocal : QCremote;
2940 /* :nowait BOOL */
2941 if (!is_server && socktype == SOCK_STREAM
2942 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2944 #ifndef NON_BLOCKING_CONNECT
2945 error ("Non-blocking connect not supported");
2946 #else
2947 is_non_blocking_client = 1;
2948 #endif
2951 name = Fplist_get (contact, QCname);
2952 buffer = Fplist_get (contact, QCbuffer);
2953 filter = Fplist_get (contact, QCfilter);
2954 sentinel = Fplist_get (contact, QCsentinel);
2956 CHECK_STRING (name);
2958 #ifdef TERM
2959 /* Let's handle TERM before things get complicated ... */
2960 host = Fplist_get (contact, QChost);
2961 CHECK_STRING (host);
2963 service = Fplist_get (contact, QCservice);
2964 if (INTEGERP (service))
2965 port = htons ((unsigned short) XINT (service));
2966 else
2968 struct servent *svc_info;
2969 CHECK_STRING (service);
2970 svc_info = getservbyname (SDATA (service), "tcp");
2971 if (svc_info == 0)
2972 error ("Unknown service: %s", SDATA (service));
2973 port = svc_info->s_port;
2976 s = connect_server (0);
2977 if (s < 0)
2978 report_file_error ("error creating socket", Fcons (name, Qnil));
2979 send_command (s, C_PORT, 0, "%s:%d", SDATA (host), ntohs (port));
2980 send_command (s, C_DUMB, 1, 0);
2982 #else /* not TERM */
2984 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2985 ai.ai_socktype = socktype;
2986 ai.ai_protocol = 0;
2987 ai.ai_next = NULL;
2988 res = &ai;
2990 /* :local ADDRESS or :remote ADDRESS */
2991 address = Fplist_get (contact, QCaddress);
2992 if (!NILP (address))
2994 host = service = Qnil;
2996 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2997 error ("Malformed :address");
2998 ai.ai_family = family;
2999 ai.ai_addr = alloca (ai.ai_addrlen);
3000 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3001 goto open_socket;
3004 /* :family FAMILY -- nil (for Inet), local, or integer. */
3005 tem = Fplist_get (contact, QCfamily);
3006 if (NILP (tem))
3008 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3009 family = AF_UNSPEC;
3010 #else
3011 family = AF_INET;
3012 #endif
3014 #ifdef HAVE_LOCAL_SOCKETS
3015 else if (EQ (tem, Qlocal))
3016 family = AF_LOCAL;
3017 #endif
3018 #ifdef AF_INET6
3019 else if (EQ (tem, Qipv6))
3020 family = AF_INET6;
3021 #endif
3022 else if (EQ (tem, Qipv4))
3023 family = AF_INET;
3024 else if (INTEGERP (tem))
3025 family = XINT (tem);
3026 else
3027 error ("Unknown address family");
3029 ai.ai_family = family;
3031 /* :service SERVICE -- string, integer (port number), or t (random port). */
3032 service = Fplist_get (contact, QCservice);
3034 #ifdef HAVE_LOCAL_SOCKETS
3035 if (family == AF_LOCAL)
3037 /* Host is not used. */
3038 host = Qnil;
3039 CHECK_STRING (service);
3040 bzero (&address_un, sizeof address_un);
3041 address_un.sun_family = AF_LOCAL;
3042 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3043 ai.ai_addr = (struct sockaddr *) &address_un;
3044 ai.ai_addrlen = sizeof address_un;
3045 goto open_socket;
3047 #endif
3049 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3050 host = Fplist_get (contact, QChost);
3051 if (!NILP (host))
3053 if (EQ (host, Qlocal))
3054 host = build_string ("localhost");
3055 CHECK_STRING (host);
3058 /* Slow down polling to every ten seconds.
3059 Some kernels have a bug which causes retrying connect to fail
3060 after a connect. Polling can interfere with gethostbyname too. */
3061 #ifdef POLL_FOR_INPUT
3062 if (socktype == SOCK_STREAM)
3064 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3065 bind_polling_period (10);
3067 #endif
3069 #ifdef HAVE_GETADDRINFO
3070 /* If we have a host, use getaddrinfo to resolve both host and service.
3071 Otherwise, use getservbyname to lookup the service. */
3072 if (!NILP (host))
3075 /* SERVICE can either be a string or int.
3076 Convert to a C string for later use by getaddrinfo. */
3077 if (EQ (service, Qt))
3078 portstring = "0";
3079 else if (INTEGERP (service))
3081 sprintf (portbuf, "%ld", (long) XINT (service));
3082 portstring = portbuf;
3084 else
3086 CHECK_STRING (service);
3087 portstring = SDATA (service);
3090 immediate_quit = 1;
3091 QUIT;
3092 memset (&hints, 0, sizeof (hints));
3093 hints.ai_flags = 0;
3094 hints.ai_family = family;
3095 hints.ai_socktype = socktype;
3096 hints.ai_protocol = 0;
3098 #ifdef HAVE_RES_INIT
3099 res_init ();
3100 #endif
3102 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3103 if (ret)
3104 #ifdef HAVE_GAI_STRERROR
3105 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3106 #else
3107 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3108 #endif
3109 immediate_quit = 0;
3111 goto open_socket;
3113 #endif /* HAVE_GETADDRINFO */
3115 /* We end up here if getaddrinfo is not defined, or in case no hostname
3116 has been specified (e.g. for a local server process). */
3118 if (EQ (service, Qt))
3119 port = 0;
3120 else if (INTEGERP (service))
3121 port = htons ((unsigned short) XINT (service));
3122 else
3124 struct servent *svc_info;
3125 CHECK_STRING (service);
3126 svc_info = getservbyname (SDATA (service),
3127 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3128 if (svc_info == 0)
3129 error ("Unknown service: %s", SDATA (service));
3130 port = svc_info->s_port;
3133 bzero (&address_in, sizeof address_in);
3134 address_in.sin_family = family;
3135 address_in.sin_addr.s_addr = INADDR_ANY;
3136 address_in.sin_port = port;
3138 #ifndef HAVE_GETADDRINFO
3139 if (!NILP (host))
3141 struct hostent *host_info_ptr;
3143 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3144 as it may `hang' Emacs for a very long time. */
3145 immediate_quit = 1;
3146 QUIT;
3148 #ifdef HAVE_RES_INIT
3149 res_init ();
3150 #endif
3152 host_info_ptr = gethostbyname (SDATA (host));
3153 immediate_quit = 0;
3155 if (host_info_ptr)
3157 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3158 host_info_ptr->h_length);
3159 family = host_info_ptr->h_addrtype;
3160 address_in.sin_family = family;
3162 else
3163 /* Attempt to interpret host as numeric inet address */
3165 IN_ADDR numeric_addr;
3166 numeric_addr = inet_addr ((char *) SDATA (host));
3167 if (NUMERIC_ADDR_ERROR)
3168 error ("Unknown host \"%s\"", SDATA (host));
3170 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3171 sizeof (address_in.sin_addr));
3175 #endif /* not HAVE_GETADDRINFO */
3177 ai.ai_family = family;
3178 ai.ai_addr = (struct sockaddr *) &address_in;
3179 ai.ai_addrlen = sizeof address_in;
3181 open_socket:
3183 #ifdef __ultrix__
3184 /* Previously this was compiled unconditionally, but that seems
3185 unnecessary on modern systems, and `unrequest_sigio' was a noop
3186 under X anyway. --lorentey */
3187 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
3188 when connect is interrupted. So let's not let it get interrupted.
3189 Note we do not turn off polling, because polling is only used
3190 when not interrupt_input, and thus not normally used on the systems
3191 which have this bug. On systems which use polling, there's no way
3192 to quit if polling is turned off. */
3193 if (interrupt_input
3194 && !is_server && socktype == SOCK_STREAM)
3196 /* Comment from KFS: The original open-network-stream code
3197 didn't unwind protect this, but it seems like the proper
3198 thing to do. In any case, I don't see how it could harm to
3199 do this -- and it makes cleanup (using unbind_to) easier. */
3200 record_unwind_protect (unwind_request_sigio, Qnil);
3201 unrequest_sigio ();
3203 #endif
3205 /* Do this in case we never enter the for-loop below. */
3206 count1 = SPECPDL_INDEX ();
3207 s = -1;
3209 for (lres = res; lres; lres = lres->ai_next)
3211 int optn, optbits;
3213 retry_connect:
3215 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3216 if (s < 0)
3218 xerrno = errno;
3219 continue;
3222 #ifdef DATAGRAM_SOCKETS
3223 if (!is_server && socktype == SOCK_DGRAM)
3224 break;
3225 #endif /* DATAGRAM_SOCKETS */
3227 #ifdef NON_BLOCKING_CONNECT
3228 if (is_non_blocking_client)
3230 #ifdef O_NONBLOCK
3231 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3232 #else
3233 ret = fcntl (s, F_SETFL, O_NDELAY);
3234 #endif
3235 if (ret < 0)
3237 xerrno = errno;
3238 emacs_close (s);
3239 s = -1;
3240 continue;
3243 #endif
3245 /* Make us close S if quit. */
3246 record_unwind_protect (close_file_unwind, make_number (s));
3248 /* Parse network options in the arg list.
3249 We simply ignore anything which isn't a known option (including other keywords).
3250 An error is signalled if setting a known option fails. */
3251 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3252 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3254 if (is_server)
3256 /* Configure as a server socket. */
3258 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3259 explicit :reuseaddr key to override this. */
3260 #ifdef HAVE_LOCAL_SOCKETS
3261 if (family != AF_LOCAL)
3262 #endif
3263 if (!(optbits & (1 << OPIX_REUSEADDR)))
3265 int optval = 1;
3266 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3267 report_file_error ("Cannot set reuse option on server socket", Qnil);
3270 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3271 report_file_error ("Cannot bind server socket", Qnil);
3273 #ifdef HAVE_GETSOCKNAME
3274 if (EQ (service, Qt))
3276 struct sockaddr_in sa1;
3277 int len1 = sizeof (sa1);
3278 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3280 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3281 service = make_number (ntohs (sa1.sin_port));
3282 contact = Fplist_put (contact, QCservice, service);
3285 #endif
3287 if (socktype == SOCK_STREAM && listen (s, backlog))
3288 report_file_error ("Cannot listen on server socket", Qnil);
3290 break;
3293 immediate_quit = 1;
3294 QUIT;
3296 /* This turns off all alarm-based interrupts; the
3297 bind_polling_period call above doesn't always turn all the
3298 short-interval ones off, especially if interrupt_input is
3299 set.
3301 It'd be nice to be able to control the connect timeout
3302 though. Would non-blocking connect calls be portable?
3304 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3306 turn_on_atimers (0);
3308 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3309 xerrno = errno;
3311 turn_on_atimers (1);
3313 if (ret == 0 || xerrno == EISCONN)
3315 /* The unwind-protect will be discarded afterwards.
3316 Likewise for immediate_quit. */
3317 break;
3320 #ifdef NON_BLOCKING_CONNECT
3321 #ifdef EINPROGRESS
3322 if (is_non_blocking_client && xerrno == EINPROGRESS)
3323 break;
3324 #else
3325 #ifdef EWOULDBLOCK
3326 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3327 break;
3328 #endif
3329 #endif
3330 #endif
3332 immediate_quit = 0;
3334 /* Discard the unwind protect closing S. */
3335 specpdl_ptr = specpdl + count1;
3336 emacs_close (s);
3337 s = -1;
3339 if (xerrno == EINTR)
3340 goto retry_connect;
3343 if (s >= 0)
3345 #ifdef DATAGRAM_SOCKETS
3346 if (socktype == SOCK_DGRAM)
3348 if (datagram_address[s].sa)
3349 abort ();
3350 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3351 datagram_address[s].len = lres->ai_addrlen;
3352 if (is_server)
3354 Lisp_Object remote;
3355 bzero (datagram_address[s].sa, lres->ai_addrlen);
3356 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3358 int rfamily, rlen;
3359 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3360 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3361 conv_lisp_to_sockaddr (rfamily, remote,
3362 datagram_address[s].sa, rlen);
3365 else
3366 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3368 #endif
3369 contact = Fplist_put (contact, QCaddress,
3370 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3371 #ifdef HAVE_GETSOCKNAME
3372 if (!is_server)
3374 struct sockaddr_in sa1;
3375 int len1 = sizeof (sa1);
3376 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3377 contact = Fplist_put (contact, QClocal,
3378 conv_sockaddr_to_lisp (&sa1, len1));
3380 #endif
3383 immediate_quit = 0;
3385 #ifdef HAVE_GETADDRINFO
3386 if (res != &ai)
3388 BLOCK_INPUT;
3389 freeaddrinfo (res);
3390 UNBLOCK_INPUT;
3392 #endif
3394 /* Discard the unwind protect for closing S, if any. */
3395 specpdl_ptr = specpdl + count1;
3397 /* Unwind bind_polling_period and request_sigio. */
3398 unbind_to (count, Qnil);
3400 if (s < 0)
3402 /* If non-blocking got this far - and failed - assume non-blocking is
3403 not supported after all. This is probably a wrong assumption, but
3404 the normal blocking calls to open-network-stream handles this error
3405 better. */
3406 if (is_non_blocking_client)
3407 return Qnil;
3409 errno = xerrno;
3410 if (is_server)
3411 report_file_error ("make server process failed", contact);
3412 else
3413 report_file_error ("make client process failed", contact);
3416 #endif /* not TERM */
3418 inch = s;
3419 outch = s;
3421 if (!NILP (buffer))
3422 buffer = Fget_buffer_create (buffer);
3423 proc = make_process (name);
3425 chan_process[inch] = proc;
3427 #ifdef O_NONBLOCK
3428 fcntl (inch, F_SETFL, O_NONBLOCK);
3429 #else
3430 #ifdef O_NDELAY
3431 fcntl (inch, F_SETFL, O_NDELAY);
3432 #endif
3433 #endif
3435 p = XPROCESS (proc);
3437 p->childp = contact;
3438 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3440 p->buffer = buffer;
3441 p->sentinel = sentinel;
3442 p->filter = filter;
3443 p->filter_multibyte = !NILP (buffer_defaults.enable_multibyte_characters);
3444 /* Override the above only if :filter-multibyte is specified. */
3445 if (! NILP (Fplist_member (contact, QCfilter_multibyte)))
3446 p->filter_multibyte = !NILP (Fplist_get (contact, QCfilter_multibyte));
3447 p->log = Fplist_get (contact, QClog);
3448 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3449 p->kill_without_query = 1;
3450 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3451 p->command = Qt;
3452 p->pid = 0;
3453 p->infd = inch;
3454 p->outfd = outch;
3455 if (is_server && socktype == SOCK_STREAM)
3456 p->status = Qlisten;
3458 /* Make the process marker point into the process buffer (if any). */
3459 if (BUFFERP (buffer))
3460 set_marker_both (p->mark, buffer,
3461 BUF_ZV (XBUFFER (buffer)),
3462 BUF_ZV_BYTE (XBUFFER (buffer)));
3464 #ifdef NON_BLOCKING_CONNECT
3465 if (is_non_blocking_client)
3467 /* We may get here if connect did succeed immediately. However,
3468 in that case, we still need to signal this like a non-blocking
3469 connection. */
3470 p->status = Qconnect;
3471 if (!FD_ISSET (inch, &connect_wait_mask))
3473 FD_SET (inch, &connect_wait_mask);
3474 num_pending_connects++;
3477 else
3478 #endif
3479 /* A server may have a client filter setting of Qt, but it must
3480 still listen for incoming connects unless it is stopped. */
3481 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3482 || (EQ (p->status, Qlisten) && NILP (p->command)))
3484 FD_SET (inch, &input_wait_mask);
3485 FD_SET (inch, &non_keyboard_wait_mask);
3488 if (inch > max_process_desc)
3489 max_process_desc = inch;
3491 tem = Fplist_member (contact, QCcoding);
3492 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3493 tem = Qnil; /* No error message (too late!). */
3496 /* Setup coding systems for communicating with the network stream. */
3497 struct gcpro gcpro1;
3498 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3499 Lisp_Object coding_systems = Qt;
3500 Lisp_Object args[5], val;
3502 if (!NILP (tem))
3504 val = XCAR (XCDR (tem));
3505 if (CONSP (val))
3506 val = XCAR (val);
3508 else if (!NILP (Vcoding_system_for_read))
3509 val = Vcoding_system_for_read;
3510 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3511 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3512 /* We dare not decode end-of-line format by setting VAL to
3513 Qraw_text, because the existing Emacs Lisp libraries
3514 assume that they receive bare code including a sequene of
3515 CR LF. */
3516 val = Qnil;
3517 else
3519 if (NILP (host) || NILP (service))
3520 coding_systems = Qnil;
3521 else
3523 args[0] = Qopen_network_stream, args[1] = name,
3524 args[2] = buffer, args[3] = host, args[4] = service;
3525 GCPRO1 (proc);
3526 coding_systems = Ffind_operation_coding_system (5, args);
3527 UNGCPRO;
3529 if (CONSP (coding_systems))
3530 val = XCAR (coding_systems);
3531 else if (CONSP (Vdefault_process_coding_system))
3532 val = XCAR (Vdefault_process_coding_system);
3533 else
3534 val = Qnil;
3536 p->decode_coding_system = val;
3538 if (!NILP (tem))
3540 val = XCAR (XCDR (tem));
3541 if (CONSP (val))
3542 val = XCDR (val);
3544 else if (!NILP (Vcoding_system_for_write))
3545 val = Vcoding_system_for_write;
3546 else if (NILP (current_buffer->enable_multibyte_characters))
3547 val = Qnil;
3548 else
3550 if (EQ (coding_systems, Qt))
3552 if (NILP (host) || NILP (service))
3553 coding_systems = Qnil;
3554 else
3556 args[0] = Qopen_network_stream, args[1] = name,
3557 args[2] = buffer, args[3] = host, args[4] = service;
3558 GCPRO1 (proc);
3559 coding_systems = Ffind_operation_coding_system (5, args);
3560 UNGCPRO;
3563 if (CONSP (coding_systems))
3564 val = XCDR (coding_systems);
3565 else if (CONSP (Vdefault_process_coding_system))
3566 val = XCDR (Vdefault_process_coding_system);
3567 else
3568 val = Qnil;
3570 p->encode_coding_system = val;
3572 setup_process_coding_systems (proc);
3574 p->decoding_buf = make_uninit_string (0);
3575 p->decoding_carryover = 0;
3576 p->encoding_buf = make_uninit_string (0);
3578 p->inherit_coding_system_flag
3579 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3581 UNGCPRO;
3582 return proc;
3584 #endif /* HAVE_SOCKETS */
3587 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3589 #ifdef SIOCGIFCONF
3590 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3591 doc: /* Return an alist of all network interfaces and their network address.
3592 Each element is a cons, the car of which is a string containing the
3593 interface name, and the cdr is the network address in internal
3594 format; see the description of ADDRESS in `make-network-process'. */)
3597 struct ifconf ifconf;
3598 struct ifreq *ifreqs = NULL;
3599 int ifaces = 0;
3600 int buf_size, s;
3601 Lisp_Object res;
3603 s = socket (AF_INET, SOCK_STREAM, 0);
3604 if (s < 0)
3605 return Qnil;
3607 again:
3608 ifaces += 25;
3609 buf_size = ifaces * sizeof(ifreqs[0]);
3610 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3611 if (!ifreqs)
3613 close (s);
3614 return Qnil;
3617 ifconf.ifc_len = buf_size;
3618 ifconf.ifc_req = ifreqs;
3619 if (ioctl (s, SIOCGIFCONF, &ifconf))
3621 close (s);
3622 return Qnil;
3625 if (ifconf.ifc_len == buf_size)
3626 goto again;
3628 close (s);
3629 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3631 res = Qnil;
3632 while (--ifaces >= 0)
3634 struct ifreq *ifq = &ifreqs[ifaces];
3635 char namebuf[sizeof (ifq->ifr_name) + 1];
3636 if (ifq->ifr_addr.sa_family != AF_INET)
3637 continue;
3638 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3639 namebuf[sizeof (ifq->ifr_name)] = 0;
3640 res = Fcons (Fcons (build_string (namebuf),
3641 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3642 sizeof (struct sockaddr))),
3643 res);
3646 return res;
3648 #endif /* SIOCGIFCONF */
3650 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3652 struct ifflag_def {
3653 int flag_bit;
3654 char *flag_sym;
3657 static struct ifflag_def ifflag_table[] = {
3658 #ifdef IFF_UP
3659 { IFF_UP, "up" },
3660 #endif
3661 #ifdef IFF_BROADCAST
3662 { IFF_BROADCAST, "broadcast" },
3663 #endif
3664 #ifdef IFF_DEBUG
3665 { IFF_DEBUG, "debug" },
3666 #endif
3667 #ifdef IFF_LOOPBACK
3668 { IFF_LOOPBACK, "loopback" },
3669 #endif
3670 #ifdef IFF_POINTOPOINT
3671 { IFF_POINTOPOINT, "pointopoint" },
3672 #endif
3673 #ifdef IFF_RUNNING
3674 { IFF_RUNNING, "running" },
3675 #endif
3676 #ifdef IFF_NOARP
3677 { IFF_NOARP, "noarp" },
3678 #endif
3679 #ifdef IFF_PROMISC
3680 { IFF_PROMISC, "promisc" },
3681 #endif
3682 #ifdef IFF_NOTRAILERS
3683 { IFF_NOTRAILERS, "notrailers" },
3684 #endif
3685 #ifdef IFF_ALLMULTI
3686 { IFF_ALLMULTI, "allmulti" },
3687 #endif
3688 #ifdef IFF_MASTER
3689 { IFF_MASTER, "master" },
3690 #endif
3691 #ifdef IFF_SLAVE
3692 { IFF_SLAVE, "slave" },
3693 #endif
3694 #ifdef IFF_MULTICAST
3695 { IFF_MULTICAST, "multicast" },
3696 #endif
3697 #ifdef IFF_PORTSEL
3698 { IFF_PORTSEL, "portsel" },
3699 #endif
3700 #ifdef IFF_AUTOMEDIA
3701 { IFF_AUTOMEDIA, "automedia" },
3702 #endif
3703 #ifdef IFF_DYNAMIC
3704 { IFF_DYNAMIC, "dynamic" },
3705 #endif
3706 #ifdef IFF_OACTIVE
3707 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3708 #endif
3709 #ifdef IFF_SIMPLEX
3710 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3711 #endif
3712 #ifdef IFF_LINK0
3713 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3714 #endif
3715 #ifdef IFF_LINK1
3716 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3717 #endif
3718 #ifdef IFF_LINK2
3719 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3720 #endif
3721 { 0, 0 }
3724 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3725 doc: /* Return information about network interface named IFNAME.
3726 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3727 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3728 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3729 FLAGS is the current flags of the interface. */)
3730 (ifname)
3731 Lisp_Object ifname;
3733 struct ifreq rq;
3734 Lisp_Object res = Qnil;
3735 Lisp_Object elt;
3736 int s;
3737 int any = 0;
3739 CHECK_STRING (ifname);
3741 bzero (rq.ifr_name, sizeof rq.ifr_name);
3742 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3744 s = socket (AF_INET, SOCK_STREAM, 0);
3745 if (s < 0)
3746 return Qnil;
3748 elt = Qnil;
3749 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3750 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3752 int flags = rq.ifr_flags;
3753 struct ifflag_def *fp;
3754 int fnum;
3756 any++;
3757 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3759 if (flags & fp->flag_bit)
3761 elt = Fcons (intern (fp->flag_sym), elt);
3762 flags -= fp->flag_bit;
3765 for (fnum = 0; flags && fnum < 32; fnum++)
3767 if (flags & (1 << fnum))
3769 elt = Fcons (make_number (fnum), elt);
3773 #endif
3774 res = Fcons (elt, res);
3776 elt = Qnil;
3777 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3778 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3780 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3781 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3782 int n;
3784 any++;
3785 for (n = 0; n < 6; n++)
3786 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3787 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3789 #endif
3790 res = Fcons (elt, res);
3792 elt = Qnil;
3793 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3794 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3796 any++;
3797 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3798 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3799 #else
3800 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3801 #endif
3803 #endif
3804 res = Fcons (elt, res);
3806 elt = Qnil;
3807 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3808 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3810 any++;
3811 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3813 #endif
3814 res = Fcons (elt, res);
3816 elt = Qnil;
3817 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3818 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3820 any++;
3821 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3823 #endif
3824 res = Fcons (elt, res);
3826 close (s);
3828 return any ? res : Qnil;
3830 #endif
3831 #endif /* HAVE_SOCKETS */
3833 /* Turn off input and output for process PROC. */
3835 void
3836 deactivate_process (proc)
3837 Lisp_Object proc;
3839 register int inchannel, outchannel;
3840 register struct Lisp_Process *p = XPROCESS (proc);
3842 inchannel = p->infd;
3843 outchannel = p->outfd;
3845 #ifdef ADAPTIVE_READ_BUFFERING
3846 if (p->read_output_delay > 0)
3848 if (--process_output_delay_count < 0)
3849 process_output_delay_count = 0;
3850 p->read_output_delay = 0;
3851 p->read_output_skip = 0;
3853 #endif
3855 if (inchannel >= 0)
3857 /* Beware SIGCHLD hereabouts. */
3858 flush_pending_output (inchannel);
3859 #ifdef VMS
3861 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
3862 sys$dassgn (outchannel);
3863 vs = get_vms_process_pointer (p->pid);
3864 if (vs)
3865 give_back_vms_process_stuff (vs);
3867 #else
3868 emacs_close (inchannel);
3869 if (outchannel >= 0 && outchannel != inchannel)
3870 emacs_close (outchannel);
3871 #endif
3873 p->infd = -1;
3874 p->outfd = -1;
3875 #ifdef DATAGRAM_SOCKETS
3876 if (DATAGRAM_CHAN_P (inchannel))
3878 xfree (datagram_address[inchannel].sa);
3879 datagram_address[inchannel].sa = 0;
3880 datagram_address[inchannel].len = 0;
3882 #endif
3883 chan_process[inchannel] = Qnil;
3884 FD_CLR (inchannel, &input_wait_mask);
3885 FD_CLR (inchannel, &non_keyboard_wait_mask);
3886 #ifdef NON_BLOCKING_CONNECT
3887 if (FD_ISSET (inchannel, &connect_wait_mask))
3889 FD_CLR (inchannel, &connect_wait_mask);
3890 if (--num_pending_connects < 0)
3891 abort ();
3893 #endif
3894 if (inchannel == max_process_desc)
3896 int i;
3897 /* We just closed the highest-numbered process input descriptor,
3898 so recompute the highest-numbered one now. */
3899 max_process_desc = 0;
3900 for (i = 0; i < MAXDESC; i++)
3901 if (!NILP (chan_process[i]))
3902 max_process_desc = i;
3907 /* Close all descriptors currently in use for communication
3908 with subprocess. This is used in a newly-forked subprocess
3909 to get rid of irrelevant descriptors. */
3911 void
3912 close_process_descs ()
3914 #ifndef WINDOWSNT
3915 int i;
3916 for (i = 0; i < MAXDESC; i++)
3918 Lisp_Object process;
3919 process = chan_process[i];
3920 if (!NILP (process))
3922 int in = XPROCESS (process)->infd;
3923 int out = XPROCESS (process)->outfd;
3924 if (in >= 0)
3925 emacs_close (in);
3926 if (out >= 0 && in != out)
3927 emacs_close (out);
3930 #endif
3933 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3934 0, 4, 0,
3935 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3936 It is read into the process' buffers or given to their filter functions.
3937 Non-nil arg PROCESS means do not return until some output has been received
3938 from PROCESS.
3940 Non-nil second arg SECONDS and third arg MILLISEC are number of
3941 seconds and milliseconds to wait; return after that much time whether
3942 or not there is input. If SECONDS is a floating point number,
3943 it specifies a fractional number of seconds to wait.
3945 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3946 from PROCESS, suspending reading output from other processes.
3947 If JUST-THIS-ONE is an integer, don't run any timers either.
3948 Return non-nil if we received any output before the timeout expired. */)
3949 (process, seconds, millisec, just_this_one)
3950 register Lisp_Object process, seconds, millisec, just_this_one;
3952 int secs, usecs = 0;
3954 if (! NILP (process))
3955 CHECK_PROCESS (process);
3956 else
3957 just_this_one = Qnil;
3959 if (!NILP (seconds))
3961 if (INTEGERP (seconds))
3962 secs = XINT (seconds);
3963 else if (FLOATP (seconds))
3965 double timeout = XFLOAT_DATA (seconds);
3966 secs = (int) timeout;
3967 usecs = (int) ((timeout - (double) secs) * 1000000);
3969 else
3970 wrong_type_argument (Qnumberp, seconds);
3972 if (INTEGERP (millisec))
3974 int carry;
3975 usecs += XINT (millisec) * 1000;
3976 carry = usecs / 1000000;
3977 secs += carry;
3978 if ((usecs -= carry * 1000000) < 0)
3980 secs--;
3981 usecs += 1000000;
3985 if (secs < 0 || (secs == 0 && usecs == 0))
3986 secs = -1, usecs = 0;
3988 else
3989 secs = NILP (process) ? -1 : 0;
3991 return
3992 (wait_reading_process_output (secs, usecs, 0, 0,
3993 Qnil,
3994 !NILP (process) ? XPROCESS (process) : NULL,
3995 NILP (just_this_one) ? 0 :
3996 !INTEGERP (just_this_one) ? 1 : -1)
3997 ? Qt : Qnil);
4000 /* Accept a connection for server process SERVER on CHANNEL. */
4002 static int connect_counter = 0;
4004 static void
4005 server_accept_connection (server, channel)
4006 Lisp_Object server;
4007 int channel;
4009 Lisp_Object proc, caller, name, buffer;
4010 Lisp_Object contact, host, service;
4011 struct Lisp_Process *ps= XPROCESS (server);
4012 struct Lisp_Process *p;
4013 int s;
4014 union u_sockaddr {
4015 struct sockaddr sa;
4016 struct sockaddr_in in;
4017 #ifdef AF_INET6
4018 struct sockaddr_in6 in6;
4019 #endif
4020 #ifdef HAVE_LOCAL_SOCKETS
4021 struct sockaddr_un un;
4022 #endif
4023 } saddr;
4024 int len = sizeof saddr;
4026 s = accept (channel, &saddr.sa, &len);
4028 if (s < 0)
4030 int code = errno;
4032 if (code == EAGAIN)
4033 return;
4034 #ifdef EWOULDBLOCK
4035 if (code == EWOULDBLOCK)
4036 return;
4037 #endif
4039 if (!NILP (ps->log))
4040 call3 (ps->log, server, Qnil,
4041 concat3 (build_string ("accept failed with code"),
4042 Fnumber_to_string (make_number (code)),
4043 build_string ("\n")));
4044 return;
4047 connect_counter++;
4049 /* Setup a new process to handle the connection. */
4051 /* Generate a unique identification of the caller, and build contact
4052 information for this process. */
4053 host = Qt;
4054 service = Qnil;
4055 switch (saddr.sa.sa_family)
4057 case AF_INET:
4059 Lisp_Object args[5];
4060 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4061 args[0] = build_string ("%d.%d.%d.%d");
4062 args[1] = make_number (*ip++);
4063 args[2] = make_number (*ip++);
4064 args[3] = make_number (*ip++);
4065 args[4] = make_number (*ip++);
4066 host = Fformat (5, args);
4067 service = make_number (ntohs (saddr.in.sin_port));
4069 args[0] = build_string (" <%s:%d>");
4070 args[1] = host;
4071 args[2] = service;
4072 caller = Fformat (3, args);
4074 break;
4076 #ifdef AF_INET6
4077 case AF_INET6:
4079 Lisp_Object args[9];
4080 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4081 int i;
4082 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4083 for (i = 0; i < 8; i++)
4084 args[i+1] = make_number (ntohs(ip6[i]));
4085 host = Fformat (9, args);
4086 service = make_number (ntohs (saddr.in.sin_port));
4088 args[0] = build_string (" <[%s]:%d>");
4089 args[1] = host;
4090 args[2] = service;
4091 caller = Fformat (3, args);
4093 break;
4094 #endif
4096 #ifdef HAVE_LOCAL_SOCKETS
4097 case AF_LOCAL:
4098 #endif
4099 default:
4100 caller = Fnumber_to_string (make_number (connect_counter));
4101 caller = concat3 (build_string (" <*"), caller, build_string ("*>"));
4102 break;
4105 /* Create a new buffer name for this process if it doesn't have a
4106 filter. The new buffer name is based on the buffer name or
4107 process name of the server process concatenated with the caller
4108 identification. */
4110 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4111 buffer = Qnil;
4112 else
4114 buffer = ps->buffer;
4115 if (!NILP (buffer))
4116 buffer = Fbuffer_name (buffer);
4117 else
4118 buffer = ps->name;
4119 if (!NILP (buffer))
4121 buffer = concat2 (buffer, caller);
4122 buffer = Fget_buffer_create (buffer);
4126 /* Generate a unique name for the new server process. Combine the
4127 server process name with the caller identification. */
4129 name = concat2 (ps->name, caller);
4130 proc = make_process (name);
4132 chan_process[s] = proc;
4134 #ifdef O_NONBLOCK
4135 fcntl (s, F_SETFL, O_NONBLOCK);
4136 #else
4137 #ifdef O_NDELAY
4138 fcntl (s, F_SETFL, O_NDELAY);
4139 #endif
4140 #endif
4142 p = XPROCESS (proc);
4144 /* Build new contact information for this setup. */
4145 contact = Fcopy_sequence (ps->childp);
4146 contact = Fplist_put (contact, QCserver, Qnil);
4147 contact = Fplist_put (contact, QChost, host);
4148 if (!NILP (service))
4149 contact = Fplist_put (contact, QCservice, service);
4150 contact = Fplist_put (contact, QCremote,
4151 conv_sockaddr_to_lisp (&saddr.sa, len));
4152 #ifdef HAVE_GETSOCKNAME
4153 len = sizeof saddr;
4154 if (getsockname (s, &saddr.sa, &len) == 0)
4155 contact = Fplist_put (contact, QClocal,
4156 conv_sockaddr_to_lisp (&saddr.sa, len));
4157 #endif
4159 p->childp = contact;
4160 p->plist = Fcopy_sequence (ps->plist);
4162 p->buffer = buffer;
4163 p->sentinel = ps->sentinel;
4164 p->filter = ps->filter;
4165 p->command = Qnil;
4166 p->pid = 0;
4167 p->infd = s;
4168 p->outfd = s;
4169 p->status = Qrun;
4171 /* Client processes for accepted connections are not stopped initially. */
4172 if (!EQ (p->filter, Qt))
4174 FD_SET (s, &input_wait_mask);
4175 FD_SET (s, &non_keyboard_wait_mask);
4178 if (s > max_process_desc)
4179 max_process_desc = s;
4181 /* Setup coding system for new process based on server process.
4182 This seems to be the proper thing to do, as the coding system
4183 of the new process should reflect the settings at the time the
4184 server socket was opened; not the current settings. */
4186 p->decode_coding_system = ps->decode_coding_system;
4187 p->encode_coding_system = ps->encode_coding_system;
4188 setup_process_coding_systems (proc);
4190 p->decoding_buf = make_uninit_string (0);
4191 p->decoding_carryover = 0;
4192 p->encoding_buf = make_uninit_string (0);
4194 p->inherit_coding_system_flag
4195 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4197 if (!NILP (ps->log))
4198 call3 (ps->log, server, proc,
4199 concat3 (build_string ("accept from "),
4200 (STRINGP (host) ? host : build_string ("-")),
4201 build_string ("\n")));
4203 if (!NILP (p->sentinel))
4204 exec_sentinel (proc,
4205 concat3 (build_string ("open from "),
4206 (STRINGP (host) ? host : build_string ("-")),
4207 build_string ("\n")));
4210 /* This variable is different from waiting_for_input in keyboard.c.
4211 It is used to communicate to a lisp process-filter/sentinel (via the
4212 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4213 for user-input when that process-filter was called.
4214 waiting_for_input cannot be used as that is by definition 0 when
4215 lisp code is being evalled.
4216 This is also used in record_asynch_buffer_change.
4217 For that purpose, this must be 0
4218 when not inside wait_reading_process_output. */
4219 static int waiting_for_user_input_p;
4221 static Lisp_Object
4222 wait_reading_process_output_unwind (data)
4223 Lisp_Object data;
4225 waiting_for_user_input_p = XINT (data);
4226 return Qnil;
4229 /* This is here so breakpoints can be put on it. */
4230 static void
4231 wait_reading_process_output_1 ()
4235 /* Use a wrapper around select to work around a bug in gdb 5.3.
4236 Normally, the wrapper is optimzed away by inlining.
4238 If emacs is stopped inside select, the gdb backtrace doesn't
4239 show the function which called select, so it is practically
4240 impossible to step through wait_reading_process_output. */
4242 #ifndef select
4243 static INLINE int
4244 select_wrapper (n, rfd, wfd, xfd, tmo)
4245 int n;
4246 SELECT_TYPE *rfd, *wfd, *xfd;
4247 EMACS_TIME *tmo;
4249 return select (n, rfd, wfd, xfd, tmo);
4251 #define select select_wrapper
4252 #endif
4254 /* Read and dispose of subprocess output while waiting for timeout to
4255 elapse and/or keyboard input to be available.
4257 TIME_LIMIT is:
4258 timeout in seconds, or
4259 zero for no limit, or
4260 -1 means gobble data immediately available but don't wait for any.
4262 MICROSECS is:
4263 an additional duration to wait, measured in microseconds.
4264 If this is nonzero and time_limit is 0, then the timeout
4265 consists of MICROSECS only.
4267 READ_KBD is a lisp value:
4268 0 to ignore keyboard input, or
4269 1 to return when input is available, or
4270 -1 meaning caller will actually read the input, so don't throw to
4271 the quit handler, or
4273 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4274 output that arrives.
4276 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4277 (and gobble terminal input into the buffer if any arrives).
4279 If WAIT_PROC is specified, wait until something arrives from that
4280 process. The return value is true if we read some input from
4281 that process.
4283 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4284 (suspending output from other processes). A negative value
4285 means don't run any timers either.
4287 If WAIT_PROC is specified, then the function returns true if we
4288 received input from that process before the timeout elapsed.
4289 Otherwise, return true if we received input from any process. */
4292 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4293 wait_for_cell, wait_proc, just_wait_proc)
4294 int time_limit, microsecs, read_kbd, do_display;
4295 Lisp_Object wait_for_cell;
4296 struct Lisp_Process *wait_proc;
4297 int just_wait_proc;
4299 register int channel, nfds;
4300 SELECT_TYPE Available;
4301 #ifdef NON_BLOCKING_CONNECT
4302 SELECT_TYPE Connecting;
4303 int check_connect;
4304 #endif
4305 int check_delay, no_avail;
4306 int xerrno;
4307 Lisp_Object proc;
4308 EMACS_TIME timeout, end_time;
4309 int wait_channel = -1;
4310 int got_some_input = 0;
4311 int count = SPECPDL_INDEX ();
4313 FD_ZERO (&Available);
4314 #ifdef NON_BLOCKING_CONNECT
4315 FD_ZERO (&Connecting);
4316 #endif
4318 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4319 if (wait_proc != NULL)
4320 wait_channel = wait_proc->infd;
4322 record_unwind_protect (wait_reading_process_output_unwind,
4323 make_number (waiting_for_user_input_p));
4324 waiting_for_user_input_p = read_kbd;
4326 /* Since we may need to wait several times,
4327 compute the absolute time to return at. */
4328 if (time_limit || microsecs)
4330 EMACS_GET_TIME (end_time);
4331 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4332 EMACS_ADD_TIME (end_time, end_time, timeout);
4334 #ifdef POLL_INTERRUPTED_SYS_CALL
4335 /* AlainF 5-Jul-1996
4336 HP-UX 10.10 seem to have problems with signals coming in
4337 Causes "poll: interrupted system call" messages when Emacs is run
4338 in an X window
4339 Turn off periodic alarms (in case they are in use),
4340 and then turn off any other atimers. */
4341 stop_polling ();
4342 turn_on_atimers (0);
4343 #endif /* POLL_INTERRUPTED_SYS_CALL */
4345 while (1)
4347 int timeout_reduced_for_timers = 0;
4349 /* If calling from keyboard input, do not quit
4350 since we want to return C-g as an input character.
4351 Otherwise, do pending quit if requested. */
4352 if (read_kbd >= 0)
4353 QUIT;
4354 #ifdef SYNC_INPUT
4355 else if (interrupt_input_pending)
4356 handle_async_input ();
4357 #endif
4359 /* Exit now if the cell we're waiting for became non-nil. */
4360 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4361 break;
4363 /* Compute time from now till when time limit is up */
4364 /* Exit if already run out */
4365 if (time_limit == -1)
4367 /* -1 specified for timeout means
4368 gobble output available now
4369 but don't wait at all. */
4371 EMACS_SET_SECS_USECS (timeout, 0, 0);
4373 else if (time_limit || microsecs)
4375 EMACS_GET_TIME (timeout);
4376 EMACS_SUB_TIME (timeout, end_time, timeout);
4377 if (EMACS_TIME_NEG_P (timeout))
4378 break;
4380 else
4382 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4385 /* Normally we run timers here.
4386 But not if wait_for_cell; in those cases,
4387 the wait is supposed to be short,
4388 and those callers cannot handle running arbitrary Lisp code here. */
4389 if (NILP (wait_for_cell)
4390 && just_wait_proc >= 0)
4392 EMACS_TIME timer_delay;
4396 int old_timers_run = timers_run;
4397 struct buffer *old_buffer = current_buffer;
4399 timer_delay = timer_check (1);
4401 /* If a timer has run, this might have changed buffers
4402 an alike. Make read_key_sequence aware of that. */
4403 if (timers_run != old_timers_run
4404 && old_buffer != current_buffer
4405 && waiting_for_user_input_p == -1)
4406 record_asynch_buffer_change ();
4408 if (timers_run != old_timers_run && do_display)
4409 /* We must retry, since a timer may have requeued itself
4410 and that could alter the time_delay. */
4411 redisplay_preserve_echo_area (9);
4412 else
4413 break;
4415 while (!detect_input_pending ());
4417 /* If there is unread keyboard input, also return. */
4418 if (read_kbd != 0
4419 && requeued_events_pending_p ())
4420 break;
4422 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4424 EMACS_TIME difference;
4425 EMACS_SUB_TIME (difference, timer_delay, timeout);
4426 if (EMACS_TIME_NEG_P (difference))
4428 timeout = timer_delay;
4429 timeout_reduced_for_timers = 1;
4432 /* If time_limit is -1, we are not going to wait at all. */
4433 else if (time_limit != -1)
4435 /* This is so a breakpoint can be put here. */
4436 wait_reading_process_output_1 ();
4440 /* Cause C-g and alarm signals to take immediate action,
4441 and cause input available signals to zero out timeout.
4443 It is important that we do this before checking for process
4444 activity. If we get a SIGCHLD after the explicit checks for
4445 process activity, timeout is the only way we will know. */
4446 if (read_kbd < 0)
4447 set_waiting_for_input (&timeout);
4449 /* If status of something has changed, and no input is
4450 available, notify the user of the change right away. After
4451 this explicit check, we'll let the SIGCHLD handler zap
4452 timeout to get our attention. */
4453 if (update_tick != process_tick && do_display)
4455 SELECT_TYPE Atemp;
4456 #ifdef NON_BLOCKING_CONNECT
4457 SELECT_TYPE Ctemp;
4458 #endif
4460 Atemp = input_wait_mask;
4461 #if 0
4462 /* On Mac OS X 10.0, the SELECT system call always says input is
4463 present (for reading) at stdin, even when none is. This
4464 causes the call to SELECT below to return 1 and
4465 status_notify not to be called. As a result output of
4466 subprocesses are incorrectly discarded.
4468 FD_CLR (0, &Atemp);
4469 #endif
4470 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4472 EMACS_SET_SECS_USECS (timeout, 0, 0);
4473 if ((select (max (max (max_process_desc, max_keyboard_desc),
4474 max_gpm_desc) + 1,
4475 &Atemp,
4476 #ifdef NON_BLOCKING_CONNECT
4477 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4478 #else
4479 (SELECT_TYPE *)0,
4480 #endif
4481 (SELECT_TYPE *)0, &timeout)
4482 <= 0))
4484 /* It's okay for us to do this and then continue with
4485 the loop, since timeout has already been zeroed out. */
4486 clear_waiting_for_input ();
4487 status_notify (NULL);
4491 /* Don't wait for output from a non-running process. Just
4492 read whatever data has already been received. */
4493 if (wait_proc && wait_proc->raw_status_new)
4494 update_status (wait_proc);
4495 if (wait_proc
4496 && ! EQ (wait_proc->status, Qrun)
4497 && ! EQ (wait_proc->status, Qconnect))
4499 int nread, total_nread = 0;
4501 clear_waiting_for_input ();
4502 XSETPROCESS (proc, wait_proc);
4504 /* Read data from the process, until we exhaust it. */
4505 while (wait_proc->infd >= 0)
4507 nread = read_process_output (proc, wait_proc->infd);
4509 if (nread == 0)
4510 break;
4512 if (0 < nread)
4513 total_nread += nread;
4514 #ifdef EIO
4515 else if (nread == -1 && EIO == errno)
4516 break;
4517 #endif
4518 #ifdef EAGAIN
4519 else if (nread == -1 && EAGAIN == errno)
4520 break;
4521 #endif
4522 #ifdef EWOULDBLOCK
4523 else if (nread == -1 && EWOULDBLOCK == errno)
4524 break;
4525 #endif
4527 if (total_nread > 0 && do_display)
4528 redisplay_preserve_echo_area (10);
4530 break;
4533 /* Wait till there is something to do */
4535 if (wait_proc && just_wait_proc)
4537 if (wait_proc->infd < 0) /* Terminated */
4538 break;
4539 FD_SET (wait_proc->infd, &Available);
4540 check_delay = 0;
4541 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4543 else if (!NILP (wait_for_cell))
4545 Available = non_process_wait_mask;
4546 check_delay = 0;
4547 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4549 else
4551 if (! read_kbd)
4552 Available = non_keyboard_wait_mask;
4553 else
4554 Available = input_wait_mask;
4555 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4556 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4559 /* If frame size has changed or the window is newly mapped,
4560 redisplay now, before we start to wait. There is a race
4561 condition here; if a SIGIO arrives between now and the select
4562 and indicates that a frame is trashed, the select may block
4563 displaying a trashed screen. */
4564 if (frame_garbaged && do_display)
4566 clear_waiting_for_input ();
4567 redisplay_preserve_echo_area (11);
4568 if (read_kbd < 0)
4569 set_waiting_for_input (&timeout);
4572 no_avail = 0;
4573 if (read_kbd && detect_input_pending ())
4575 nfds = 0;
4576 no_avail = 1;
4578 else
4580 #ifdef NON_BLOCKING_CONNECT
4581 if (check_connect)
4582 Connecting = connect_wait_mask;
4583 #endif
4585 #ifdef ADAPTIVE_READ_BUFFERING
4586 /* Set the timeout for adaptive read buffering if any
4587 process has non-zero read_output_skip and non-zero
4588 read_output_delay, and we are not reading output for a
4589 specific wait_channel. It is not executed if
4590 Vprocess_adaptive_read_buffering is nil. */
4591 if (process_output_skip && check_delay > 0)
4593 int usecs = EMACS_USECS (timeout);
4594 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4595 usecs = READ_OUTPUT_DELAY_MAX;
4596 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4598 proc = chan_process[channel];
4599 if (NILP (proc))
4600 continue;
4601 /* Find minimum non-zero read_output_delay among the
4602 processes with non-zero read_output_skip. */
4603 if (XPROCESS (proc)->read_output_delay > 0)
4605 check_delay--;
4606 if (!XPROCESS (proc)->read_output_skip)
4607 continue;
4608 FD_CLR (channel, &Available);
4609 XPROCESS (proc)->read_output_skip = 0;
4610 if (XPROCESS (proc)->read_output_delay < usecs)
4611 usecs = XPROCESS (proc)->read_output_delay;
4614 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4615 process_output_skip = 0;
4617 #endif
4619 nfds = select (max (max (max_process_desc, max_keyboard_desc),
4620 max_gpm_desc) + 1,
4621 &Available,
4622 #ifdef NON_BLOCKING_CONNECT
4623 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4624 #else
4625 (SELECT_TYPE *)0,
4626 #endif
4627 (SELECT_TYPE *)0, &timeout);
4630 xerrno = errno;
4632 /* Make C-g and alarm signals set flags again */
4633 clear_waiting_for_input ();
4635 /* If we woke up due to SIGWINCH, actually change size now. */
4636 do_pending_window_change (0);
4638 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4639 /* We wanted the full specified time, so return now. */
4640 break;
4641 if (nfds < 0)
4643 if (xerrno == EINTR)
4644 no_avail = 1;
4645 #ifdef ultrix
4646 /* Ultrix select seems to return ENOMEM when it is
4647 interrupted. Treat it just like EINTR. Bleah. Note
4648 that we want to test for the "ultrix" CPP symbol, not
4649 "__ultrix__"; the latter is only defined under GCC, but
4650 not by DEC's bundled CC. -JimB */
4651 else if (xerrno == ENOMEM)
4652 no_avail = 1;
4653 #endif
4654 #ifdef ALLIANT
4655 /* This happens for no known reason on ALLIANT.
4656 I am guessing that this is the right response. -- RMS. */
4657 else if (xerrno == EFAULT)
4658 no_avail = 1;
4659 #endif
4660 else if (xerrno == EBADF)
4662 #ifdef AIX
4663 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4664 the child's closure of the pts gives the parent a SIGHUP, and
4665 the ptc file descriptor is automatically closed,
4666 yielding EBADF here or at select() call above.
4667 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4668 in m/ibmrt-aix.h), and here we just ignore the select error.
4669 Cleanup occurs c/o status_notify after SIGCLD. */
4670 no_avail = 1; /* Cannot depend on values returned */
4671 #else
4672 abort ();
4673 #endif
4675 else
4676 error ("select error: %s", emacs_strerror (xerrno));
4679 if (no_avail)
4681 FD_ZERO (&Available);
4682 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4685 #if defined(sun) && !defined(USG5_4)
4686 if (nfds > 0 && keyboard_bit_set (&Available)
4687 && interrupt_input)
4688 /* System sometimes fails to deliver SIGIO.
4690 David J. Mackenzie says that Emacs doesn't compile under
4691 Solaris if this code is enabled, thus the USG5_4 in the CPP
4692 conditional. "I haven't noticed any ill effects so far.
4693 If you find a Solaris expert somewhere, they might know
4694 better." */
4695 kill (getpid (), SIGIO);
4696 #endif
4698 #if 0 /* When polling is used, interrupt_input is 0,
4699 so get_input_pending should read the input.
4700 So this should not be needed. */
4701 /* If we are using polling for input,
4702 and we see input available, make it get read now.
4703 Otherwise it might not actually get read for a second.
4704 And on hpux, since we turn off polling in wait_reading_process_output,
4705 it might never get read at all if we don't spend much time
4706 outside of wait_reading_process_output. */
4707 if (read_kbd && interrupt_input
4708 && keyboard_bit_set (&Available)
4709 && input_polling_used ())
4710 kill (getpid (), SIGALRM);
4711 #endif
4713 /* Check for keyboard input */
4714 /* If there is any, return immediately
4715 to give it higher priority than subprocesses */
4717 if (read_kbd != 0)
4719 int old_timers_run = timers_run;
4720 struct buffer *old_buffer = current_buffer;
4721 int leave = 0;
4723 if (detect_input_pending_run_timers (do_display))
4725 swallow_events (do_display);
4726 if (detect_input_pending_run_timers (do_display))
4727 leave = 1;
4730 /* If a timer has run, this might have changed buffers
4731 an alike. Make read_key_sequence aware of that. */
4732 if (timers_run != old_timers_run
4733 && waiting_for_user_input_p == -1
4734 && old_buffer != current_buffer)
4735 record_asynch_buffer_change ();
4737 if (leave)
4738 break;
4741 /* If there is unread keyboard input, also return. */
4742 if (read_kbd != 0
4743 && requeued_events_pending_p ())
4744 break;
4746 /* If we are not checking for keyboard input now,
4747 do process events (but don't run any timers).
4748 This is so that X events will be processed.
4749 Otherwise they may have to wait until polling takes place.
4750 That would causes delays in pasting selections, for example.
4752 (We used to do this only if wait_for_cell.) */
4753 if (read_kbd == 0 && detect_input_pending ())
4755 swallow_events (do_display);
4756 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4757 if (detect_input_pending ())
4758 break;
4759 #endif
4762 /* Exit now if the cell we're waiting for became non-nil. */
4763 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4764 break;
4766 #ifdef SIGIO
4767 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4768 go read it. This can happen with X on BSD after logging out.
4769 In that case, there really is no input and no SIGIO,
4770 but select says there is input. */
4772 if (read_kbd && interrupt_input
4773 && keyboard_bit_set (&Available) && ! noninteractive)
4774 kill (getpid (), SIGIO);
4775 #endif
4777 if (! wait_proc)
4778 got_some_input |= nfds > 0;
4780 /* If checking input just got us a size-change event from X,
4781 obey it now if we should. */
4782 if (read_kbd || ! NILP (wait_for_cell))
4783 do_pending_window_change (0);
4785 /* Check for data from a process. */
4786 if (no_avail || nfds == 0)
4787 continue;
4789 /* Really FIRST_PROC_DESC should be 0 on Unix,
4790 but this is safer in the short run. */
4791 for (channel = 0; channel <= max_process_desc; channel++)
4793 if (FD_ISSET (channel, &Available)
4794 && FD_ISSET (channel, &non_keyboard_wait_mask))
4796 int nread;
4798 /* If waiting for this channel, arrange to return as
4799 soon as no more input to be processed. No more
4800 waiting. */
4801 if (wait_channel == channel)
4803 wait_channel = -1;
4804 time_limit = -1;
4805 got_some_input = 1;
4807 proc = chan_process[channel];
4808 if (NILP (proc))
4809 continue;
4811 /* If this is a server stream socket, accept connection. */
4812 if (EQ (XPROCESS (proc)->status, Qlisten))
4814 server_accept_connection (proc, channel);
4815 continue;
4818 /* Read data from the process, starting with our
4819 buffered-ahead character if we have one. */
4821 nread = read_process_output (proc, channel);
4822 if (nread > 0)
4824 /* Since read_process_output can run a filter,
4825 which can call accept-process-output,
4826 don't try to read from any other processes
4827 before doing the select again. */
4828 FD_ZERO (&Available);
4830 if (do_display)
4831 redisplay_preserve_echo_area (12);
4833 #ifdef EWOULDBLOCK
4834 else if (nread == -1 && errno == EWOULDBLOCK)
4836 #endif
4837 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4838 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4839 #ifdef O_NONBLOCK
4840 else if (nread == -1 && errno == EAGAIN)
4842 #else
4843 #ifdef O_NDELAY
4844 else if (nread == -1 && errno == EAGAIN)
4846 /* Note that we cannot distinguish between no input
4847 available now and a closed pipe.
4848 With luck, a closed pipe will be accompanied by
4849 subprocess termination and SIGCHLD. */
4850 else if (nread == 0 && !NETCONN_P (proc))
4852 #endif /* O_NDELAY */
4853 #endif /* O_NONBLOCK */
4854 #ifdef HAVE_PTYS
4855 /* On some OSs with ptys, when the process on one end of
4856 a pty exits, the other end gets an error reading with
4857 errno = EIO instead of getting an EOF (0 bytes read).
4858 Therefore, if we get an error reading and errno =
4859 EIO, just continue, because the child process has
4860 exited and should clean itself up soon (e.g. when we
4861 get a SIGCHLD).
4863 However, it has been known to happen that the SIGCHLD
4864 got lost. So raise the signal again just in case.
4865 It can't hurt. */
4866 else if (nread == -1 && errno == EIO)
4868 /* Clear the descriptor now, so we only raise the signal once. */
4869 FD_CLR (channel, &input_wait_mask);
4870 FD_CLR (channel, &non_keyboard_wait_mask);
4872 kill (getpid (), SIGCHLD);
4874 #endif /* HAVE_PTYS */
4875 /* If we can detect process termination, don't consider the process
4876 gone just because its pipe is closed. */
4877 #ifdef SIGCHLD
4878 else if (nread == 0 && !NETCONN_P (proc))
4880 #endif
4881 else
4883 /* Preserve status of processes already terminated. */
4884 XPROCESS (proc)->tick = ++process_tick;
4885 deactivate_process (proc);
4886 if (XPROCESS (proc)->raw_status_new)
4887 update_status (XPROCESS (proc));
4888 if (EQ (XPROCESS (proc)->status, Qrun))
4889 XPROCESS (proc)->status
4890 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4893 #ifdef NON_BLOCKING_CONNECT
4894 if (check_connect && FD_ISSET (channel, &Connecting)
4895 && FD_ISSET (channel, &connect_wait_mask))
4897 struct Lisp_Process *p;
4899 FD_CLR (channel, &connect_wait_mask);
4900 if (--num_pending_connects < 0)
4901 abort ();
4903 proc = chan_process[channel];
4904 if (NILP (proc))
4905 continue;
4907 p = XPROCESS (proc);
4909 #ifdef GNU_LINUX
4910 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4911 So only use it on systems where it is known to work. */
4913 int xlen = sizeof(xerrno);
4914 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4915 xerrno = errno;
4917 #else
4919 struct sockaddr pname;
4920 int pnamelen = sizeof(pname);
4922 /* If connection failed, getpeername will fail. */
4923 xerrno = 0;
4924 if (getpeername(channel, &pname, &pnamelen) < 0)
4926 /* Obtain connect failure code through error slippage. */
4927 char dummy;
4928 xerrno = errno;
4929 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4930 xerrno = errno;
4933 #endif
4934 if (xerrno)
4936 p->tick = ++process_tick;
4937 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4938 deactivate_process (proc);
4940 else
4942 p->status = Qrun;
4943 /* Execute the sentinel here. If we had relied on
4944 status_notify to do it later, it will read input
4945 from the process before calling the sentinel. */
4946 exec_sentinel (proc, build_string ("open\n"));
4947 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4949 FD_SET (p->infd, &input_wait_mask);
4950 FD_SET (p->infd, &non_keyboard_wait_mask);
4954 #endif /* NON_BLOCKING_CONNECT */
4955 } /* end for each file descriptor */
4956 } /* end while exit conditions not met */
4958 unbind_to (count, Qnil);
4960 /* If calling from keyboard input, do not quit
4961 since we want to return C-g as an input character.
4962 Otherwise, do pending quit if requested. */
4963 if (read_kbd >= 0)
4965 /* Prevent input_pending from remaining set if we quit. */
4966 clear_input_pending ();
4967 QUIT;
4969 #ifdef POLL_INTERRUPTED_SYS_CALL
4970 /* AlainF 5-Jul-1996
4971 HP-UX 10.10 seems to have problems with signals coming in
4972 Causes "poll: interrupted system call" messages when Emacs is run
4973 in an X window
4974 Turn periodic alarms back on */
4975 start_polling ();
4976 #endif /* POLL_INTERRUPTED_SYS_CALL */
4978 return got_some_input;
4981 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4983 static Lisp_Object
4984 read_process_output_call (fun_and_args)
4985 Lisp_Object fun_and_args;
4987 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4990 static Lisp_Object
4991 read_process_output_error_handler (error)
4992 Lisp_Object error;
4994 cmd_error_internal (error, "error in process filter: ");
4995 Vinhibit_quit = Qt;
4996 update_echo_area ();
4997 Fsleep_for (make_number (2), Qnil);
4998 return Qt;
5001 /* Read pending output from the process channel,
5002 starting with our buffered-ahead character if we have one.
5003 Yield number of decoded characters read.
5005 This function reads at most 4096 characters.
5006 If you want to read all available subprocess output,
5007 you must call it repeatedly until it returns zero.
5009 The characters read are decoded according to PROC's coding-system
5010 for decoding. */
5012 static int
5013 read_process_output (proc, channel)
5014 Lisp_Object proc;
5015 register int channel;
5017 register int nbytes;
5018 char *chars;
5019 register Lisp_Object outstream;
5020 register struct buffer *old = current_buffer;
5021 register struct Lisp_Process *p = XPROCESS (proc);
5022 register int opoint;
5023 struct coding_system *coding = proc_decode_coding_system[channel];
5024 int carryover = p->decoding_carryover;
5025 int readmax = 4096;
5027 #ifdef VMS
5028 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5030 vs = get_vms_process_pointer (p->pid);
5031 if (vs)
5033 if (!vs->iosb[0])
5034 return (0); /* Really weird if it does this */
5035 if (!(vs->iosb[0] & 1))
5036 return -1; /* I/O error */
5038 else
5039 error ("Could not get VMS process pointer");
5040 chars = vs->inputBuffer;
5041 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
5042 if (nbytes <= 0)
5044 start_vms_process_read (vs); /* Crank up the next read on the process */
5045 return 1; /* Nothing worth printing, say we got 1 */
5047 if (carryover > 0)
5049 /* The data carried over in the previous decoding (which are at
5050 the tail of decoding buffer) should be prepended to the new
5051 data read to decode all together. */
5052 chars = (char *) alloca (nbytes + carryover);
5053 bcopy (SDATA (p->decoding_buf), buf, carryover);
5054 bcopy (vs->inputBuffer, chars + carryover, nbytes);
5056 #else /* not VMS */
5058 chars = (char *) alloca (carryover + readmax);
5059 if (carryover)
5060 /* See the comment above. */
5061 bcopy (SDATA (p->decoding_buf), chars, carryover);
5063 #ifdef DATAGRAM_SOCKETS
5064 /* We have a working select, so proc_buffered_char is always -1. */
5065 if (DATAGRAM_CHAN_P (channel))
5067 int len = datagram_address[channel].len;
5068 nbytes = recvfrom (channel, chars + carryover, readmax,
5069 0, datagram_address[channel].sa, &len);
5071 else
5072 #endif
5073 if (proc_buffered_char[channel] < 0)
5075 nbytes = emacs_read (channel, chars + carryover, readmax);
5076 #ifdef ADAPTIVE_READ_BUFFERING
5077 if (nbytes > 0 && p->adaptive_read_buffering)
5079 int delay = p->read_output_delay;
5080 if (nbytes < 256)
5082 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5084 if (delay == 0)
5085 process_output_delay_count++;
5086 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5089 else if (delay > 0 && (nbytes == readmax))
5091 delay -= READ_OUTPUT_DELAY_INCREMENT;
5092 if (delay == 0)
5093 process_output_delay_count--;
5095 p->read_output_delay = delay;
5096 if (delay)
5098 p->read_output_skip = 1;
5099 process_output_skip = 1;
5102 #endif
5104 else
5106 chars[carryover] = proc_buffered_char[channel];
5107 proc_buffered_char[channel] = -1;
5108 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5109 if (nbytes < 0)
5110 nbytes = 1;
5111 else
5112 nbytes = nbytes + 1;
5114 #endif /* not VMS */
5116 p->decoding_carryover = 0;
5118 /* At this point, NBYTES holds number of bytes just received
5119 (including the one in proc_buffered_char[channel]). */
5120 if (nbytes <= 0)
5122 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5123 return nbytes;
5124 coding->mode |= CODING_MODE_LAST_BLOCK;
5127 /* Now set NBYTES how many bytes we must decode. */
5128 nbytes += carryover;
5130 /* Read and dispose of the process output. */
5131 outstream = p->filter;
5132 if (!NILP (outstream))
5134 /* We inhibit quit here instead of just catching it so that
5135 hitting ^G when a filter happens to be running won't screw
5136 it up. */
5137 int count = SPECPDL_INDEX ();
5138 Lisp_Object odeactivate;
5139 Lisp_Object obuffer, okeymap;
5140 Lisp_Object text;
5141 int outer_running_asynch_code = running_asynch_code;
5142 int waiting = waiting_for_user_input_p;
5144 /* No need to gcpro these, because all we do with them later
5145 is test them for EQness, and none of them should be a string. */
5146 odeactivate = Vdeactivate_mark;
5147 XSETBUFFER (obuffer, current_buffer);
5148 okeymap = current_buffer->keymap;
5150 specbind (Qinhibit_quit, Qt);
5151 specbind (Qlast_nonmenu_event, Qt);
5153 /* In case we get recursively called,
5154 and we already saved the match data nonrecursively,
5155 save the same match data in safely recursive fashion. */
5156 if (outer_running_asynch_code)
5158 Lisp_Object tem;
5159 /* Don't clobber the CURRENT match data, either! */
5160 tem = Fmatch_data (Qnil, Qnil, Qnil);
5161 restore_search_regs ();
5162 record_unwind_save_match_data ();
5163 Fset_match_data (tem, Qt);
5166 /* For speed, if a search happens within this code,
5167 save the match data in a special nonrecursive fashion. */
5168 running_asynch_code = 1;
5170 text = decode_coding_string (make_unibyte_string (chars, nbytes),
5171 coding, 0);
5172 Vlast_coding_system_used = coding->symbol;
5173 /* A new coding system might be found. */
5174 if (!EQ (p->decode_coding_system, coding->symbol))
5176 p->decode_coding_system = coding->symbol;
5178 /* Don't call setup_coding_system for
5179 proc_decode_coding_system[channel] here. It is done in
5180 detect_coding called via decode_coding above. */
5182 /* If a coding system for encoding is not yet decided, we set
5183 it as the same as coding-system for decoding.
5185 But, before doing that we must check if
5186 proc_encode_coding_system[p->outfd] surely points to a
5187 valid memory because p->outfd will be changed once EOF is
5188 sent to the process. */
5189 if (NILP (p->encode_coding_system)
5190 && proc_encode_coding_system[p->outfd])
5192 p->encode_coding_system = coding->symbol;
5193 setup_coding_system (coding->symbol,
5194 proc_encode_coding_system[p->outfd]);
5195 if (proc_encode_coding_system[p->outfd]->eol_type
5196 == CODING_EOL_UNDECIDED)
5197 proc_encode_coding_system[p->outfd]->eol_type
5198 = system_eol_type;
5202 carryover = nbytes - coding->consumed;
5203 if (carryover < 0)
5204 abort ();
5206 if (SCHARS (p->decoding_buf) < carryover)
5207 p->decoding_buf = make_uninit_string (carryover);
5208 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
5209 carryover);
5210 p->decoding_carryover = carryover;
5211 /* Adjust the multibyteness of TEXT to that of the filter. */
5212 if (!p->filter_multibyte != !STRING_MULTIBYTE (text))
5213 text = (STRING_MULTIBYTE (text)
5214 ? Fstring_as_unibyte (text)
5215 : Fstring_to_multibyte (text));
5216 if (SBYTES (text) > 0)
5217 internal_condition_case_1 (read_process_output_call,
5218 Fcons (outstream,
5219 Fcons (proc, Fcons (text, Qnil))),
5220 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5221 read_process_output_error_handler);
5223 /* If we saved the match data nonrecursively, restore it now. */
5224 restore_search_regs ();
5225 running_asynch_code = outer_running_asynch_code;
5227 /* Handling the process output should not deactivate the mark. */
5228 Vdeactivate_mark = odeactivate;
5230 /* Restore waiting_for_user_input_p as it was
5231 when we were called, in case the filter clobbered it. */
5232 waiting_for_user_input_p = waiting;
5234 #if 0 /* Call record_asynch_buffer_change unconditionally,
5235 because we might have changed minor modes or other things
5236 that affect key bindings. */
5237 if (! EQ (Fcurrent_buffer (), obuffer)
5238 || ! EQ (current_buffer->keymap, okeymap))
5239 #endif
5240 /* But do it only if the caller is actually going to read events.
5241 Otherwise there's no need to make him wake up, and it could
5242 cause trouble (for example it would make sit_for return). */
5243 if (waiting_for_user_input_p == -1)
5244 record_asynch_buffer_change ();
5246 #ifdef VMS
5247 start_vms_process_read (vs);
5248 #endif
5249 unbind_to (count, Qnil);
5250 return nbytes;
5253 /* If no filter, write into buffer if it isn't dead. */
5254 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5256 Lisp_Object old_read_only;
5257 int old_begv, old_zv;
5258 int old_begv_byte, old_zv_byte;
5259 Lisp_Object odeactivate;
5260 int before, before_byte;
5261 int opoint_byte;
5262 Lisp_Object text;
5263 struct buffer *b;
5265 odeactivate = Vdeactivate_mark;
5267 Fset_buffer (p->buffer);
5268 opoint = PT;
5269 opoint_byte = PT_BYTE;
5270 old_read_only = current_buffer->read_only;
5271 old_begv = BEGV;
5272 old_zv = ZV;
5273 old_begv_byte = BEGV_BYTE;
5274 old_zv_byte = ZV_BYTE;
5276 current_buffer->read_only = Qnil;
5278 /* Insert new output into buffer
5279 at the current end-of-output marker,
5280 thus preserving logical ordering of input and output. */
5281 if (XMARKER (p->mark)->buffer)
5282 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5283 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5284 ZV_BYTE));
5285 else
5286 SET_PT_BOTH (ZV, ZV_BYTE);
5287 before = PT;
5288 before_byte = PT_BYTE;
5290 /* If the output marker is outside of the visible region, save
5291 the restriction and widen. */
5292 if (! (BEGV <= PT && PT <= ZV))
5293 Fwiden ();
5295 text = decode_coding_string (make_unibyte_string (chars, nbytes),
5296 coding, 0);
5297 Vlast_coding_system_used = coding->symbol;
5298 /* A new coding system might be found. See the comment in the
5299 similar code in the previous `if' block. */
5300 if (!EQ (p->decode_coding_system, coding->symbol))
5302 p->decode_coding_system = coding->symbol;
5303 if (NILP (p->encode_coding_system)
5304 && proc_encode_coding_system[p->outfd])
5306 p->encode_coding_system = coding->symbol;
5307 setup_coding_system (coding->symbol,
5308 proc_encode_coding_system[p->outfd]);
5309 if (proc_encode_coding_system[p->outfd]->eol_type
5310 == CODING_EOL_UNDECIDED)
5311 proc_encode_coding_system[p->outfd]->eol_type
5312 = system_eol_type;
5315 carryover = nbytes - coding->consumed;
5316 if (carryover < 0)
5317 abort ();
5319 if (SCHARS (p->decoding_buf) < carryover)
5320 p->decoding_buf = make_uninit_string (carryover);
5321 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
5322 carryover);
5323 p->decoding_carryover = carryover;
5325 /* Adjust the multibyteness of TEXT to that of the buffer. */
5326 if (NILP (current_buffer->enable_multibyte_characters)
5327 != ! STRING_MULTIBYTE (text))
5328 text = (STRING_MULTIBYTE (text)
5329 ? Fstring_as_unibyte (text)
5330 : Fstring_to_multibyte (text));
5331 /* Insert before markers in case we are inserting where
5332 the buffer's mark is, and the user's next command is Meta-y. */
5333 insert_from_string_before_markers (text, 0, 0,
5334 SCHARS (text), SBYTES (text), 0);
5336 /* Make sure the process marker's position is valid when the
5337 process buffer is changed in the signal_after_change above.
5338 W3 is known to do that. */
5339 if (BUFFERP (p->buffer)
5340 && (b = XBUFFER (p->buffer), b != current_buffer))
5341 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5342 else
5343 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5345 update_mode_lines++;
5347 /* Make sure opoint and the old restrictions
5348 float ahead of any new text just as point would. */
5349 if (opoint >= before)
5351 opoint += PT - before;
5352 opoint_byte += PT_BYTE - before_byte;
5354 if (old_begv > before)
5356 old_begv += PT - before;
5357 old_begv_byte += PT_BYTE - before_byte;
5359 if (old_zv >= before)
5361 old_zv += PT - before;
5362 old_zv_byte += PT_BYTE - before_byte;
5365 /* If the restriction isn't what it should be, set it. */
5366 if (old_begv != BEGV || old_zv != ZV)
5367 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5369 /* Handling the process output should not deactivate the mark. */
5370 Vdeactivate_mark = odeactivate;
5372 current_buffer->read_only = old_read_only;
5373 SET_PT_BOTH (opoint, opoint_byte);
5374 set_buffer_internal (old);
5376 #ifdef VMS
5377 start_vms_process_read (vs);
5378 #endif
5379 return nbytes;
5382 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5383 0, 0, 0,
5384 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5385 This is intended for use by asynchronous process output filters and sentinels. */)
5388 return (waiting_for_user_input_p ? Qt : Qnil);
5391 /* Sending data to subprocess */
5393 jmp_buf send_process_frame;
5394 Lisp_Object process_sent_to;
5396 SIGTYPE
5397 send_process_trap ()
5399 SIGNAL_THREAD_CHECK (SIGPIPE);
5400 #ifdef BSD4_1
5401 sigrelse (SIGPIPE);
5402 sigrelse (SIGALRM);
5403 #endif /* BSD4_1 */
5404 sigunblock (sigmask (SIGPIPE));
5405 longjmp (send_process_frame, 1);
5408 /* Send some data to process PROC.
5409 BUF is the beginning of the data; LEN is the number of characters.
5410 OBJECT is the Lisp object that the data comes from. If OBJECT is
5411 nil or t, it means that the data comes from C string.
5413 If OBJECT is not nil, the data is encoded by PROC's coding-system
5414 for encoding before it is sent.
5416 This function can evaluate Lisp code and can garbage collect. */
5418 static void
5419 send_process (proc, buf, len, object)
5420 volatile Lisp_Object proc;
5421 unsigned char *volatile buf;
5422 volatile int len;
5423 volatile Lisp_Object object;
5425 /* Use volatile to protect variables from being clobbered by longjmp. */
5426 struct Lisp_Process *p = XPROCESS (proc);
5427 int rv;
5428 struct coding_system *coding;
5429 struct gcpro gcpro1;
5430 SIGTYPE (*volatile old_sigpipe) ();
5432 GCPRO1 (object);
5434 #ifdef VMS
5435 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5436 #endif /* VMS */
5438 if (p->raw_status_new)
5439 update_status (p);
5440 if (! EQ (p->status, Qrun))
5441 error ("Process %s not running", SDATA (p->name));
5442 if (p->outfd < 0)
5443 error ("Output file descriptor of %s is closed", SDATA (p->name));
5445 coding = proc_encode_coding_system[p->outfd];
5446 Vlast_coding_system_used = coding->symbol;
5448 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5449 || (BUFFERP (object)
5450 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5451 || EQ (object, Qt))
5453 if (!EQ (coding->symbol, p->encode_coding_system))
5454 /* The coding system for encoding was changed to raw-text
5455 because we sent a unibyte text previously. Now we are
5456 sending a multibyte text, thus we must encode it by the
5457 original coding system specified for the current process. */
5458 setup_coding_system (p->encode_coding_system, coding);
5459 if (coding->eol_type == CODING_EOL_UNDECIDED)
5460 coding->eol_type = system_eol_type;
5461 /* src_multibyte should be set to 1 _after_ a call to
5462 setup_coding_system, since it resets src_multibyte to
5463 zero. */
5464 coding->src_multibyte = 1;
5466 else
5468 /* For sending a unibyte text, character code conversion should
5469 not take place but EOL conversion should. So, setup raw-text
5470 or one of the subsidiary if we have not yet done it. */
5471 if (coding->type != coding_type_raw_text)
5473 if (CODING_REQUIRE_FLUSHING (coding))
5475 /* But, before changing the coding, we must flush out data. */
5476 coding->mode |= CODING_MODE_LAST_BLOCK;
5477 send_process (proc, "", 0, Qt);
5479 coding->src_multibyte = 0;
5480 setup_raw_text_coding_system (coding);
5483 coding->dst_multibyte = 0;
5485 if (CODING_REQUIRE_ENCODING (coding))
5487 int require = encoding_buffer_size (coding, len);
5488 int from_byte = -1, from = -1, to = -1;
5490 if (BUFFERP (object))
5492 from_byte = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5493 from = buf_bytepos_to_charpos (XBUFFER (object), from_byte);
5494 to = buf_bytepos_to_charpos (XBUFFER (object), from_byte + len);
5496 else if (STRINGP (object))
5498 from_byte = buf - SDATA (object);
5499 from = string_byte_to_char (object, from_byte);
5500 to = string_byte_to_char (object, from_byte + len);
5503 if (coding->composing != COMPOSITION_DISABLED)
5505 if (from_byte >= 0)
5506 coding_save_composition (coding, from, to, object);
5507 else
5508 coding->composing = COMPOSITION_DISABLED;
5511 if (SBYTES (p->encoding_buf) < require)
5512 p->encoding_buf = make_uninit_string (require);
5514 if (from_byte >= 0)
5515 buf = (BUFFERP (object)
5516 ? BUF_BYTE_ADDRESS (XBUFFER (object), from_byte)
5517 : SDATA (object) + from_byte);
5519 object = p->encoding_buf;
5520 encode_coding (coding, (char *) buf, SDATA (object),
5521 len, SBYTES (object));
5522 coding_free_composition_data (coding);
5523 len = coding->produced;
5524 buf = SDATA (object);
5527 #ifdef VMS
5528 vs = get_vms_process_pointer (p->pid);
5529 if (vs == 0)
5530 error ("Could not find this process: %x", p->pid);
5531 else if (write_to_vms_process (vs, buf, len))
5533 #else /* not VMS */
5535 if (pty_max_bytes == 0)
5537 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5538 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5539 if (pty_max_bytes < 0)
5540 pty_max_bytes = 250;
5541 #else
5542 pty_max_bytes = 250;
5543 #endif
5544 /* Deduct one, to leave space for the eof. */
5545 pty_max_bytes--;
5548 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5549 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5550 when returning with longjmp despite being declared volatile. */
5551 if (!setjmp (send_process_frame))
5553 process_sent_to = proc;
5554 while (len > 0)
5556 int this = len;
5558 /* Decide how much data we can send in one batch.
5559 Long lines need to be split into multiple batches. */
5560 if (p->pty_flag)
5562 /* Starting this at zero is always correct when not the first
5563 iteration because the previous iteration ended by sending C-d.
5564 It may not be correct for the first iteration
5565 if a partial line was sent in a separate send_process call.
5566 If that proves worth handling, we need to save linepos
5567 in the process object. */
5568 int linepos = 0;
5569 unsigned char *ptr = (unsigned char *) buf;
5570 unsigned char *end = (unsigned char *) buf + len;
5572 /* Scan through this text for a line that is too long. */
5573 while (ptr != end && linepos < pty_max_bytes)
5575 if (*ptr == '\n')
5576 linepos = 0;
5577 else
5578 linepos++;
5579 ptr++;
5581 /* If we found one, break the line there
5582 and put in a C-d to force the buffer through. */
5583 this = ptr - buf;
5586 /* Send this batch, using one or more write calls. */
5587 while (this > 0)
5589 int outfd = p->outfd;
5590 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5591 #ifdef DATAGRAM_SOCKETS
5592 if (DATAGRAM_CHAN_P (outfd))
5594 rv = sendto (outfd, (char *) buf, this,
5595 0, datagram_address[outfd].sa,
5596 datagram_address[outfd].len);
5597 if (rv < 0 && errno == EMSGSIZE)
5599 signal (SIGPIPE, old_sigpipe);
5600 report_file_error ("sending datagram",
5601 Fcons (proc, Qnil));
5604 else
5605 #endif
5607 rv = emacs_write (outfd, (char *) buf, this);
5608 #ifdef ADAPTIVE_READ_BUFFERING
5609 if (p->read_output_delay > 0
5610 && p->adaptive_read_buffering == 1)
5612 p->read_output_delay = 0;
5613 process_output_delay_count--;
5614 p->read_output_skip = 0;
5616 #endif
5618 signal (SIGPIPE, old_sigpipe);
5620 if (rv < 0)
5622 if (0
5623 #ifdef EWOULDBLOCK
5624 || errno == EWOULDBLOCK
5625 #endif
5626 #ifdef EAGAIN
5627 || errno == EAGAIN
5628 #endif
5630 /* Buffer is full. Wait, accepting input;
5631 that may allow the program
5632 to finish doing output and read more. */
5634 int offset = 0;
5636 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5637 /* A gross hack to work around a bug in FreeBSD.
5638 In the following sequence, read(2) returns
5639 bogus data:
5641 write(2) 1022 bytes
5642 write(2) 954 bytes, get EAGAIN
5643 read(2) 1024 bytes in process_read_output
5644 read(2) 11 bytes in process_read_output
5646 That is, read(2) returns more bytes than have
5647 ever been written successfully. The 1033 bytes
5648 read are the 1022 bytes written successfully
5649 after processing (for example with CRs added if
5650 the terminal is set up that way which it is
5651 here). The same bytes will be seen again in a
5652 later read(2), without the CRs. */
5654 if (errno == EAGAIN)
5656 int flags = FWRITE;
5657 ioctl (p->outfd, TIOCFLUSH, &flags);
5659 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5661 /* Running filters might relocate buffers or strings.
5662 Arrange to relocate BUF. */
5663 if (BUFFERP (object))
5664 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5665 else if (STRINGP (object))
5666 offset = buf - SDATA (object);
5668 #ifdef EMACS_HAS_USECS
5669 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5670 #else
5671 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5672 #endif
5674 if (BUFFERP (object))
5675 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5676 else if (STRINGP (object))
5677 buf = offset + SDATA (object);
5679 rv = 0;
5681 else
5682 /* This is a real error. */
5683 report_file_error ("writing to process", Fcons (proc, Qnil));
5685 buf += rv;
5686 len -= rv;
5687 this -= rv;
5690 /* If we sent just part of the string, put in an EOF
5691 to force it through, before we send the rest. */
5692 if (len > 0)
5693 Fprocess_send_eof (proc);
5696 #endif /* not VMS */
5697 else
5699 signal (SIGPIPE, old_sigpipe);
5700 #ifndef VMS
5701 proc = process_sent_to;
5702 p = XPROCESS (proc);
5703 #endif
5704 p->raw_status_new = 0;
5705 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5706 p->tick = ++process_tick;
5707 deactivate_process (proc);
5708 #ifdef VMS
5709 error ("Error writing to process %s; closed it", SDATA (p->name));
5710 #else
5711 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5712 #endif
5715 UNGCPRO;
5718 static Lisp_Object
5719 send_process_object_unwind (buf)
5720 Lisp_Object buf;
5722 Lisp_Object tembuf;
5724 if (XBUFFER (buf) == current_buffer)
5725 return Qnil;
5726 tembuf = Fcurrent_buffer ();
5727 Fset_buffer (buf);
5728 Fkill_buffer (tembuf);
5729 return Qnil;
5732 /* Send current contents of region between START and END to PROC.
5733 If START is a string, send it instead.
5734 This function can evaluate Lisp code and can garbage collect. */
5736 static void
5737 send_process_object (proc, start, end)
5738 Lisp_Object proc, start, end;
5740 int count = SPECPDL_INDEX ();
5741 Lisp_Object object = STRINGP (start) ? start : Fcurrent_buffer ();
5742 struct buffer *given_buffer = current_buffer;
5743 unsigned char *buf;
5744 int len;
5746 record_unwind_protect (send_process_object_unwind, Fcurrent_buffer ());
5748 if (STRINGP (object) ? STRING_MULTIBYTE (object)
5749 : ! NILP (XBUFFER (object)->enable_multibyte_characters))
5751 struct Lisp_Process *p = XPROCESS (proc);
5752 struct coding_system *coding;
5754 if (p->raw_status_new)
5755 update_status (p);
5756 if (! EQ (p->status, Qrun))
5757 error ("Process %s not running", SDATA (p->name));
5758 if (p->outfd < 0)
5759 error ("Output file descriptor of %s is closed", SDATA (p->name));
5761 coding = proc_encode_coding_system[p->outfd];
5762 if (! EQ (coding->symbol, p->encode_coding_system))
5763 /* The coding system for encoding was changed to raw-text
5764 because we sent a unibyte text previously. Now we are
5765 sending a multibyte text, thus we must encode it by the
5766 original coding system specified for the current process. */
5767 setup_coding_system (p->encode_coding_system, coding);
5768 if (! NILP (coding->pre_write_conversion))
5770 struct gcpro gcpro1, gcpro2;
5772 GCPRO2 (proc, object);
5773 call2 (coding->pre_write_conversion, start, end);
5774 UNGCPRO;
5775 if (given_buffer != current_buffer)
5777 start = make_number (BEGV), end = make_number (ZV);
5778 object = Fcurrent_buffer ();
5783 if (BUFFERP (object))
5785 EMACS_INT start_byte;
5787 if (XINT (start) < GPT && XINT (end) > GPT)
5788 move_gap (XINT (end));
5789 start_byte = CHAR_TO_BYTE (XINT (start));
5790 buf = BYTE_POS_ADDR (start_byte);
5791 len = CHAR_TO_BYTE (XINT (end)) - start_byte;
5793 else
5795 buf = SDATA (object);
5796 len = SBYTES (object);
5798 send_process (proc, buf, len, object);
5800 unbind_to (count, Qnil);
5803 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5804 3, 3, 0,
5805 doc: /* Send current contents of region as input to PROCESS.
5806 PROCESS may be a process, a buffer, the name of a process or buffer, or
5807 nil, indicating the current buffer's process.
5808 Called from program, takes three arguments, PROCESS, START and END.
5809 If the region is more than 500 characters long,
5810 it is sent in several bunches. This may happen even for shorter regions.
5811 Output from processes can arrive in between bunches. */)
5812 (process, start, end)
5813 Lisp_Object process, start, end;
5815 Lisp_Object proc;
5817 proc = get_process (process);
5818 validate_region (&start, &end);
5819 send_process_object (proc, start, end);
5820 return Qnil;
5823 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5824 2, 2, 0,
5825 doc: /* Send PROCESS the contents of STRING as input.
5826 PROCESS may be a process, a buffer, the name of a process or buffer, or
5827 nil, indicating the current buffer's process.
5828 If STRING is more than 500 characters long,
5829 it is sent in several bunches. This may happen even for shorter strings.
5830 Output from processes can arrive in between bunches. */)
5831 (process, string)
5832 Lisp_Object process, string;
5834 Lisp_Object proc;
5835 CHECK_STRING (string);
5836 proc = get_process (process);
5837 send_process_object (proc, string, Qnil);
5838 return Qnil;
5841 /* Return the foreground process group for the tty/pty that
5842 the process P uses. */
5843 static int
5844 emacs_get_tty_pgrp (p)
5845 struct Lisp_Process *p;
5847 int gid = -1;
5849 #ifdef TIOCGPGRP
5850 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5852 int fd;
5853 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5854 master side. Try the slave side. */
5855 fd = emacs_open (XSTRING (p->tty_name)->data, O_RDONLY, 0);
5857 if (fd != -1)
5859 ioctl (fd, TIOCGPGRP, &gid);
5860 emacs_close (fd);
5863 #endif /* defined (TIOCGPGRP ) */
5865 return gid;
5868 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5869 Sprocess_running_child_p, 0, 1, 0,
5870 doc: /* Return t if PROCESS has given the terminal to a child.
5871 If the operating system does not make it possible to find out,
5872 return t unconditionally. */)
5873 (process)
5874 Lisp_Object process;
5876 /* Initialize in case ioctl doesn't exist or gives an error,
5877 in a way that will cause returning t. */
5878 int gid;
5879 Lisp_Object proc;
5880 struct Lisp_Process *p;
5882 proc = get_process (process);
5883 p = XPROCESS (proc);
5885 if (!EQ (p->childp, Qt))
5886 error ("Process %s is not a subprocess",
5887 SDATA (p->name));
5888 if (p->infd < 0)
5889 error ("Process %s is not active",
5890 SDATA (p->name));
5892 gid = emacs_get_tty_pgrp (p);
5894 if (gid == p->pid)
5895 return Qnil;
5896 return Qt;
5899 /* send a signal number SIGNO to PROCESS.
5900 If CURRENT_GROUP is t, that means send to the process group
5901 that currently owns the terminal being used to communicate with PROCESS.
5902 This is used for various commands in shell mode.
5903 If CURRENT_GROUP is lambda, that means send to the process group
5904 that currently owns the terminal, but only if it is NOT the shell itself.
5906 If NOMSG is zero, insert signal-announcements into process's buffers
5907 right away.
5909 If we can, we try to signal PROCESS by sending control characters
5910 down the pty. This allows us to signal inferiors who have changed
5911 their uid, for which killpg would return an EPERM error. */
5913 static void
5914 process_send_signal (process, signo, current_group, nomsg)
5915 Lisp_Object process;
5916 int signo;
5917 Lisp_Object current_group;
5918 int nomsg;
5920 Lisp_Object proc;
5921 register struct Lisp_Process *p;
5922 int gid;
5923 int no_pgrp = 0;
5925 proc = get_process (process);
5926 p = XPROCESS (proc);
5928 if (!EQ (p->childp, Qt))
5929 error ("Process %s is not a subprocess",
5930 SDATA (p->name));
5931 if (p->infd < 0)
5932 error ("Process %s is not active",
5933 SDATA (p->name));
5935 if (!p->pty_flag)
5936 current_group = Qnil;
5938 /* If we are using pgrps, get a pgrp number and make it negative. */
5939 if (NILP (current_group))
5940 /* Send the signal to the shell's process group. */
5941 gid = p->pid;
5942 else
5944 #ifdef SIGNALS_VIA_CHARACTERS
5945 /* If possible, send signals to the entire pgrp
5946 by sending an input character to it. */
5948 /* TERMIOS is the latest and bestest, and seems most likely to
5949 work. If the system has it, use it. */
5950 #ifdef HAVE_TERMIOS
5951 struct termios t;
5952 cc_t *sig_char = NULL;
5954 tcgetattr (p->infd, &t);
5956 switch (signo)
5958 case SIGINT:
5959 sig_char = &t.c_cc[VINTR];
5960 break;
5962 case SIGQUIT:
5963 sig_char = &t.c_cc[VQUIT];
5964 break;
5966 case SIGTSTP:
5967 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5968 sig_char = &t.c_cc[VSWTCH];
5969 #else
5970 sig_char = &t.c_cc[VSUSP];
5971 #endif
5972 break;
5975 if (sig_char && *sig_char != CDISABLE)
5977 send_process (proc, sig_char, 1, Qnil);
5978 return;
5980 /* If we can't send the signal with a character,
5981 fall through and send it another way. */
5982 #else /* ! HAVE_TERMIOS */
5984 /* On Berkeley descendants, the following IOCTL's retrieve the
5985 current control characters. */
5986 #if defined (TIOCGLTC) && defined (TIOCGETC)
5988 struct tchars c;
5989 struct ltchars lc;
5991 switch (signo)
5993 case SIGINT:
5994 ioctl (p->infd, TIOCGETC, &c);
5995 send_process (proc, &c.t_intrc, 1, Qnil);
5996 return;
5997 case SIGQUIT:
5998 ioctl (p->infd, TIOCGETC, &c);
5999 send_process (proc, &c.t_quitc, 1, Qnil);
6000 return;
6001 #ifdef SIGTSTP
6002 case SIGTSTP:
6003 ioctl (p->infd, TIOCGLTC, &lc);
6004 send_process (proc, &lc.t_suspc, 1, Qnil);
6005 return;
6006 #endif /* ! defined (SIGTSTP) */
6009 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6011 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6012 characters. */
6013 #ifdef TCGETA
6014 struct termio t;
6015 switch (signo)
6017 case SIGINT:
6018 ioctl (p->infd, TCGETA, &t);
6019 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6020 return;
6021 case SIGQUIT:
6022 ioctl (p->infd, TCGETA, &t);
6023 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6024 return;
6025 #ifdef SIGTSTP
6026 case SIGTSTP:
6027 ioctl (p->infd, TCGETA, &t);
6028 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6029 return;
6030 #endif /* ! defined (SIGTSTP) */
6032 #else /* ! defined (TCGETA) */
6033 Your configuration files are messed up.
6034 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6035 you'd better be using one of the alternatives above! */
6036 #endif /* ! defined (TCGETA) */
6037 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6038 /* In this case, the code above should alway returns. */
6039 abort ();
6040 #endif /* ! defined HAVE_TERMIOS */
6042 /* The code above may fall through if it can't
6043 handle the signal. */
6044 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6046 #ifdef TIOCGPGRP
6047 /* Get the current pgrp using the tty itself, if we have that.
6048 Otherwise, use the pty to get the pgrp.
6049 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6050 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6051 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6052 His patch indicates that if TIOCGPGRP returns an error, then
6053 we should just assume that p->pid is also the process group id. */
6055 gid = emacs_get_tty_pgrp (p);
6057 if (gid == -1)
6058 /* If we can't get the information, assume
6059 the shell owns the tty. */
6060 gid = p->pid;
6062 /* It is not clear whether anything really can set GID to -1.
6063 Perhaps on some system one of those ioctls can or could do so.
6064 Or perhaps this is vestigial. */
6065 if (gid == -1)
6066 no_pgrp = 1;
6067 #else /* ! defined (TIOCGPGRP ) */
6068 /* Can't select pgrps on this system, so we know that
6069 the child itself heads the pgrp. */
6070 gid = p->pid;
6071 #endif /* ! defined (TIOCGPGRP ) */
6073 /* If current_group is lambda, and the shell owns the terminal,
6074 don't send any signal. */
6075 if (EQ (current_group, Qlambda) && gid == p->pid)
6076 return;
6079 switch (signo)
6081 #ifdef SIGCONT
6082 case SIGCONT:
6083 p->raw_status_new = 0;
6084 p->status = Qrun;
6085 p->tick = ++process_tick;
6086 if (!nomsg)
6087 status_notify (NULL);
6088 break;
6089 #endif /* ! defined (SIGCONT) */
6090 case SIGINT:
6091 #ifdef VMS
6092 send_process (proc, "\003", 1, Qnil); /* ^C */
6093 goto whoosh;
6094 #endif
6095 case SIGQUIT:
6096 #ifdef VMS
6097 send_process (proc, "\031", 1, Qnil); /* ^Y */
6098 goto whoosh;
6099 #endif
6100 case SIGKILL:
6101 #ifdef VMS
6102 sys$forcex (&(p->pid), 0, 1);
6103 whoosh:
6104 #endif
6105 flush_pending_output (p->infd);
6106 break;
6109 /* If we don't have process groups, send the signal to the immediate
6110 subprocess. That isn't really right, but it's better than any
6111 obvious alternative. */
6112 if (no_pgrp)
6114 kill (p->pid, signo);
6115 return;
6118 /* gid may be a pid, or minus a pgrp's number */
6119 #ifdef TIOCSIGSEND
6120 if (!NILP (current_group))
6122 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6123 EMACS_KILLPG (gid, signo);
6125 else
6127 gid = - p->pid;
6128 kill (gid, signo);
6130 #else /* ! defined (TIOCSIGSEND) */
6131 EMACS_KILLPG (gid, signo);
6132 #endif /* ! defined (TIOCSIGSEND) */
6135 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6136 doc: /* Interrupt process PROCESS.
6137 PROCESS may be a process, a buffer, or the name of a process or buffer.
6138 No arg or nil means current buffer's process.
6139 Second arg CURRENT-GROUP non-nil means send signal to
6140 the current process-group of the process's controlling terminal
6141 rather than to the process's own process group.
6142 If the process is a shell, this means interrupt current subjob
6143 rather than the shell.
6145 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6146 don't send the signal. */)
6147 (process, current_group)
6148 Lisp_Object process, current_group;
6150 process_send_signal (process, SIGINT, current_group, 0);
6151 return process;
6154 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6155 doc: /* Kill process PROCESS. May be process or name of one.
6156 See function `interrupt-process' for more details on usage. */)
6157 (process, current_group)
6158 Lisp_Object process, current_group;
6160 process_send_signal (process, SIGKILL, current_group, 0);
6161 return process;
6164 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6165 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6166 See function `interrupt-process' for more details on usage. */)
6167 (process, current_group)
6168 Lisp_Object process, current_group;
6170 process_send_signal (process, SIGQUIT, current_group, 0);
6171 return process;
6174 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6175 doc: /* Stop process PROCESS. May be process or name of one.
6176 See function `interrupt-process' for more details on usage.
6177 If PROCESS is a network process, inhibit handling of incoming traffic. */)
6178 (process, current_group)
6179 Lisp_Object process, current_group;
6181 #ifdef HAVE_SOCKETS
6182 if (PROCESSP (process) && NETCONN_P (process))
6184 struct Lisp_Process *p;
6186 p = XPROCESS (process);
6187 if (NILP (p->command)
6188 && p->infd >= 0)
6190 FD_CLR (p->infd, &input_wait_mask);
6191 FD_CLR (p->infd, &non_keyboard_wait_mask);
6193 p->command = Qt;
6194 return process;
6196 #endif
6197 #ifndef SIGTSTP
6198 error ("No SIGTSTP support");
6199 #else
6200 process_send_signal (process, SIGTSTP, current_group, 0);
6201 #endif
6202 return process;
6205 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6206 doc: /* Continue process PROCESS. May be process or name of one.
6207 See function `interrupt-process' for more details on usage.
6208 If PROCESS is a network process, resume handling of incoming traffic. */)
6209 (process, current_group)
6210 Lisp_Object process, current_group;
6212 #ifdef HAVE_SOCKETS
6213 if (PROCESSP (process) && NETCONN_P (process))
6215 struct Lisp_Process *p;
6217 p = XPROCESS (process);
6218 if (EQ (p->command, Qt)
6219 && p->infd >= 0
6220 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6222 FD_SET (p->infd, &input_wait_mask);
6223 FD_SET (p->infd, &non_keyboard_wait_mask);
6225 p->command = Qnil;
6226 return process;
6228 #endif
6229 #ifdef SIGCONT
6230 process_send_signal (process, SIGCONT, current_group, 0);
6231 #else
6232 error ("No SIGCONT support");
6233 #endif
6234 return process;
6237 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6238 2, 2, "sProcess (name or number): \nnSignal code: ",
6239 doc: /* Send PROCESS the signal with code SIGCODE.
6240 PROCESS may also be a number specifying the process id of the
6241 process to signal; in this case, the process need not be a child of
6242 this Emacs.
6243 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6244 (process, sigcode)
6245 Lisp_Object process, sigcode;
6247 pid_t pid;
6249 if (INTEGERP (process))
6251 pid = XINT (process);
6252 goto got_it;
6255 if (FLOATP (process))
6257 pid = (pid_t) XFLOAT_DATA (process);
6258 goto got_it;
6261 if (STRINGP (process))
6263 Lisp_Object tem;
6264 if (tem = Fget_process (process), NILP (tem))
6266 pid = XINT (Fstring_to_number (process, make_number (10)));
6267 if (pid > 0)
6268 goto got_it;
6270 process = tem;
6272 else
6273 process = get_process (process);
6275 if (NILP (process))
6276 return process;
6278 CHECK_PROCESS (process);
6279 pid = XPROCESS (process)->pid;
6280 if (pid <= 0)
6281 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6283 got_it:
6285 #define parse_signal(NAME, VALUE) \
6286 else if (!xstricmp (name, NAME)) \
6287 XSETINT (sigcode, VALUE)
6289 if (INTEGERP (sigcode))
6291 else
6293 unsigned char *name;
6295 CHECK_SYMBOL (sigcode);
6296 name = SDATA (SYMBOL_NAME (sigcode));
6298 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6299 name += 3;
6301 if (0)
6303 #ifdef SIGUSR1
6304 parse_signal ("usr1", SIGUSR1);
6305 #endif
6306 #ifdef SIGUSR2
6307 parse_signal ("usr2", SIGUSR2);
6308 #endif
6309 #ifdef SIGTERM
6310 parse_signal ("term", SIGTERM);
6311 #endif
6312 #ifdef SIGHUP
6313 parse_signal ("hup", SIGHUP);
6314 #endif
6315 #ifdef SIGINT
6316 parse_signal ("int", SIGINT);
6317 #endif
6318 #ifdef SIGQUIT
6319 parse_signal ("quit", SIGQUIT);
6320 #endif
6321 #ifdef SIGILL
6322 parse_signal ("ill", SIGILL);
6323 #endif
6324 #ifdef SIGABRT
6325 parse_signal ("abrt", SIGABRT);
6326 #endif
6327 #ifdef SIGEMT
6328 parse_signal ("emt", SIGEMT);
6329 #endif
6330 #ifdef SIGKILL
6331 parse_signal ("kill", SIGKILL);
6332 #endif
6333 #ifdef SIGFPE
6334 parse_signal ("fpe", SIGFPE);
6335 #endif
6336 #ifdef SIGBUS
6337 parse_signal ("bus", SIGBUS);
6338 #endif
6339 #ifdef SIGSEGV
6340 parse_signal ("segv", SIGSEGV);
6341 #endif
6342 #ifdef SIGSYS
6343 parse_signal ("sys", SIGSYS);
6344 #endif
6345 #ifdef SIGPIPE
6346 parse_signal ("pipe", SIGPIPE);
6347 #endif
6348 #ifdef SIGALRM
6349 parse_signal ("alrm", SIGALRM);
6350 #endif
6351 #ifdef SIGURG
6352 parse_signal ("urg", SIGURG);
6353 #endif
6354 #ifdef SIGSTOP
6355 parse_signal ("stop", SIGSTOP);
6356 #endif
6357 #ifdef SIGTSTP
6358 parse_signal ("tstp", SIGTSTP);
6359 #endif
6360 #ifdef SIGCONT
6361 parse_signal ("cont", SIGCONT);
6362 #endif
6363 #ifdef SIGCHLD
6364 parse_signal ("chld", SIGCHLD);
6365 #endif
6366 #ifdef SIGTTIN
6367 parse_signal ("ttin", SIGTTIN);
6368 #endif
6369 #ifdef SIGTTOU
6370 parse_signal ("ttou", SIGTTOU);
6371 #endif
6372 #ifdef SIGIO
6373 parse_signal ("io", SIGIO);
6374 #endif
6375 #ifdef SIGXCPU
6376 parse_signal ("xcpu", SIGXCPU);
6377 #endif
6378 #ifdef SIGXFSZ
6379 parse_signal ("xfsz", SIGXFSZ);
6380 #endif
6381 #ifdef SIGVTALRM
6382 parse_signal ("vtalrm", SIGVTALRM);
6383 #endif
6384 #ifdef SIGPROF
6385 parse_signal ("prof", SIGPROF);
6386 #endif
6387 #ifdef SIGWINCH
6388 parse_signal ("winch", SIGWINCH);
6389 #endif
6390 #ifdef SIGINFO
6391 parse_signal ("info", SIGINFO);
6392 #endif
6393 else
6394 error ("Undefined signal name %s", name);
6397 #undef parse_signal
6399 return make_number (kill (pid, XINT (sigcode)));
6402 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6403 doc: /* Make PROCESS see end-of-file in its input.
6404 EOF comes after any text already sent to it.
6405 PROCESS may be a process, a buffer, the name of a process or buffer, or
6406 nil, indicating the current buffer's process.
6407 If PROCESS is a network connection, or is a process communicating
6408 through a pipe (as opposed to a pty), then you cannot send any more
6409 text to PROCESS after you call this function. */)
6410 (process)
6411 Lisp_Object process;
6413 Lisp_Object proc;
6414 struct coding_system *coding;
6416 if (DATAGRAM_CONN_P (process))
6417 return process;
6419 proc = get_process (process);
6420 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6422 /* Make sure the process is really alive. */
6423 if (XPROCESS (proc)->raw_status_new)
6424 update_status (XPROCESS (proc));
6425 if (! EQ (XPROCESS (proc)->status, Qrun))
6426 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6428 if (CODING_REQUIRE_FLUSHING (coding))
6430 coding->mode |= CODING_MODE_LAST_BLOCK;
6431 send_process (proc, "", 0, Qnil);
6434 #ifdef VMS
6435 send_process (proc, "\032", 1, Qnil); /* ^z */
6436 #else
6437 if (XPROCESS (proc)->pty_flag)
6438 send_process (proc, "\004", 1, Qnil);
6439 else
6441 int old_outfd, new_outfd;
6443 #ifdef HAVE_SHUTDOWN
6444 /* If this is a network connection, or socketpair is used
6445 for communication with the subprocess, call shutdown to cause EOF.
6446 (In some old system, shutdown to socketpair doesn't work.
6447 Then we just can't win.) */
6448 if (XPROCESS (proc)->pid == 0
6449 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6450 shutdown (XPROCESS (proc)->outfd, 1);
6451 /* In case of socketpair, outfd == infd, so don't close it. */
6452 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6453 emacs_close (XPROCESS (proc)->outfd);
6454 #else /* not HAVE_SHUTDOWN */
6455 emacs_close (XPROCESS (proc)->outfd);
6456 #endif /* not HAVE_SHUTDOWN */
6457 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6458 if (new_outfd < 0)
6459 abort ();
6460 old_outfd = XPROCESS (proc)->outfd;
6462 if (!proc_encode_coding_system[new_outfd])
6463 proc_encode_coding_system[new_outfd]
6464 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6465 bcopy (proc_encode_coding_system[old_outfd],
6466 proc_encode_coding_system[new_outfd],
6467 sizeof (struct coding_system));
6468 bzero (proc_encode_coding_system[old_outfd],
6469 sizeof (struct coding_system));
6471 XPROCESS (proc)->outfd = new_outfd;
6473 #endif /* VMS */
6474 return process;
6477 /* Kill all processes associated with `buffer'.
6478 If `buffer' is nil, kill all processes */
6480 void
6481 kill_buffer_processes (buffer)
6482 Lisp_Object buffer;
6484 Lisp_Object tail, proc;
6486 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6488 proc = XCDR (XCAR (tail));
6489 if (GC_PROCESSP (proc)
6490 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6492 if (NETCONN_P (proc))
6493 Fdelete_process (proc);
6494 else if (XPROCESS (proc)->infd >= 0)
6495 process_send_signal (proc, SIGHUP, Qnil, 1);
6500 /* On receipt of a signal that a child status has changed, loop asking
6501 about children with changed statuses until the system says there
6502 are no more.
6504 All we do is change the status; we do not run sentinels or print
6505 notifications. That is saved for the next time keyboard input is
6506 done, in order to avoid timing errors.
6508 ** WARNING: this can be called during garbage collection.
6509 Therefore, it must not be fooled by the presence of mark bits in
6510 Lisp objects.
6512 ** USG WARNING: Although it is not obvious from the documentation
6513 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6514 signal() before executing at least one wait(), otherwise the
6515 handler will be called again, resulting in an infinite loop. The
6516 relevant portion of the documentation reads "SIGCLD signals will be
6517 queued and the signal-catching function will be continually
6518 reentered until the queue is empty". Invoking signal() causes the
6519 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6520 Inc.
6522 ** Malloc WARNING: This should never call malloc either directly or
6523 indirectly; if it does, that is a bug */
6525 #ifdef SIGCHLD
6526 SIGTYPE
6527 sigchld_handler (signo)
6528 int signo;
6530 int old_errno = errno;
6531 Lisp_Object proc;
6532 register struct Lisp_Process *p;
6533 extern EMACS_TIME *input_available_clear_time;
6535 SIGNAL_THREAD_CHECK (signo);
6537 #ifdef BSD4_1
6538 extern int sigheld;
6539 sigheld |= sigbit (SIGCHLD);
6540 #endif
6542 while (1)
6544 pid_t pid;
6545 WAITTYPE w;
6546 Lisp_Object tail;
6548 #ifdef WNOHANG
6549 #ifndef WUNTRACED
6550 #define WUNTRACED 0
6551 #endif /* no WUNTRACED */
6552 /* Keep trying to get a status until we get a definitive result. */
6555 errno = 0;
6556 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6558 while (pid < 0 && errno == EINTR);
6560 if (pid <= 0)
6562 /* PID == 0 means no processes found, PID == -1 means a real
6563 failure. We have done all our job, so return. */
6565 /* USG systems forget handlers when they are used;
6566 must reestablish each time */
6567 #if defined (USG) && !defined (POSIX_SIGNALS)
6568 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6569 #endif
6570 #ifdef BSD4_1
6571 sigheld &= ~sigbit (SIGCHLD);
6572 sigrelse (SIGCHLD);
6573 #endif
6574 errno = old_errno;
6575 return;
6577 #else
6578 pid = wait (&w);
6579 #endif /* no WNOHANG */
6581 /* Find the process that signaled us, and record its status. */
6583 /* The process can have been deleted by Fdelete_process. */
6584 for (tail = deleted_pid_list; GC_CONSP (tail); tail = XCDR (tail))
6586 Lisp_Object xpid = XCAR (tail);
6587 if ((GC_INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6588 || (GC_FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6590 XSETCAR (tail, Qnil);
6591 goto sigchld_end_of_loop;
6595 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6596 p = 0;
6597 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6599 proc = XCDR (XCAR (tail));
6600 p = XPROCESS (proc);
6601 if (GC_EQ (p->childp, Qt) && p->pid == pid)
6602 break;
6603 p = 0;
6606 /* Look for an asynchronous process whose pid hasn't been filled
6607 in yet. */
6608 if (p == 0)
6609 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
6611 proc = XCDR (XCAR (tail));
6612 p = XPROCESS (proc);
6613 if (p->pid == -1)
6614 break;
6615 p = 0;
6618 /* Change the status of the process that was found. */
6619 if (p != 0)
6621 union { int i; WAITTYPE wt; } u;
6622 int clear_desc_flag = 0;
6624 p->tick = ++process_tick;
6625 u.wt = w;
6626 p->raw_status = u.i;
6627 p->raw_status_new = 1;
6629 /* If process has terminated, stop waiting for its output. */
6630 if ((WIFSIGNALED (w) || WIFEXITED (w))
6631 && p->infd >= 0)
6632 clear_desc_flag = 1;
6634 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6635 if (clear_desc_flag)
6637 FD_CLR (p->infd, &input_wait_mask);
6638 FD_CLR (p->infd, &non_keyboard_wait_mask);
6641 /* Tell wait_reading_process_output that it needs to wake up and
6642 look around. */
6643 if (input_available_clear_time)
6644 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6647 /* There was no asynchronous process found for that pid: we have
6648 a synchronous process. */
6649 else
6651 synch_process_alive = 0;
6653 /* Report the status of the synchronous process. */
6654 if (WIFEXITED (w))
6655 synch_process_retcode = WRETCODE (w);
6656 else if (WIFSIGNALED (w))
6657 synch_process_termsig = WTERMSIG (w);
6659 /* Tell wait_reading_process_output that it needs to wake up and
6660 look around. */
6661 if (input_available_clear_time)
6662 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6665 sigchld_end_of_loop:
6668 /* On some systems, we must return right away.
6669 If any more processes want to signal us, we will
6670 get another signal.
6671 Otherwise (on systems that have WNOHANG), loop around
6672 to use up all the processes that have something to tell us. */
6673 #if (defined WINDOWSNT \
6674 || (defined USG && !defined GNU_LINUX \
6675 && !(defined HPUX && defined WNOHANG)))
6676 #if defined (USG) && ! defined (POSIX_SIGNALS)
6677 signal (signo, sigchld_handler);
6678 #endif
6679 errno = old_errno;
6680 return;
6681 #endif /* USG, but not HPUX with WNOHANG */
6684 #endif /* SIGCHLD */
6687 static Lisp_Object
6688 exec_sentinel_unwind (data)
6689 Lisp_Object data;
6691 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6692 return Qnil;
6695 static Lisp_Object
6696 exec_sentinel_error_handler (error)
6697 Lisp_Object error;
6699 cmd_error_internal (error, "error in process sentinel: ");
6700 Vinhibit_quit = Qt;
6701 update_echo_area ();
6702 Fsleep_for (make_number (2), Qnil);
6703 return Qt;
6706 static void
6707 exec_sentinel (proc, reason)
6708 Lisp_Object proc, reason;
6710 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6711 register struct Lisp_Process *p = XPROCESS (proc);
6712 int count = SPECPDL_INDEX ();
6713 int outer_running_asynch_code = running_asynch_code;
6714 int waiting = waiting_for_user_input_p;
6716 if (inhibit_sentinels)
6717 return;
6719 /* No need to gcpro these, because all we do with them later
6720 is test them for EQness, and none of them should be a string. */
6721 odeactivate = Vdeactivate_mark;
6722 XSETBUFFER (obuffer, current_buffer);
6723 okeymap = current_buffer->keymap;
6725 sentinel = p->sentinel;
6726 if (NILP (sentinel))
6727 return;
6729 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6730 assure that it gets restored no matter how the sentinel exits. */
6731 p->sentinel = Qnil;
6732 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6733 /* Inhibit quit so that random quits don't screw up a running filter. */
6734 specbind (Qinhibit_quit, Qt);
6735 specbind (Qlast_nonmenu_event, Qt);
6737 /* In case we get recursively called,
6738 and we already saved the match data nonrecursively,
6739 save the same match data in safely recursive fashion. */
6740 if (outer_running_asynch_code)
6742 Lisp_Object tem;
6743 tem = Fmatch_data (Qnil, Qnil, Qnil);
6744 restore_search_regs ();
6745 record_unwind_save_match_data ();
6746 Fset_match_data (tem, Qt);
6749 /* For speed, if a search happens within this code,
6750 save the match data in a special nonrecursive fashion. */
6751 running_asynch_code = 1;
6753 internal_condition_case_1 (read_process_output_call,
6754 Fcons (sentinel,
6755 Fcons (proc, Fcons (reason, Qnil))),
6756 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6757 exec_sentinel_error_handler);
6759 /* If we saved the match data nonrecursively, restore it now. */
6760 restore_search_regs ();
6761 running_asynch_code = outer_running_asynch_code;
6763 Vdeactivate_mark = odeactivate;
6765 /* Restore waiting_for_user_input_p as it was
6766 when we were called, in case the filter clobbered it. */
6767 waiting_for_user_input_p = waiting;
6769 #if 0
6770 if (! EQ (Fcurrent_buffer (), obuffer)
6771 || ! EQ (current_buffer->keymap, okeymap))
6772 #endif
6773 /* But do it only if the caller is actually going to read events.
6774 Otherwise there's no need to make him wake up, and it could
6775 cause trouble (for example it would make sit_for return). */
6776 if (waiting_for_user_input_p == -1)
6777 record_asynch_buffer_change ();
6779 unbind_to (count, Qnil);
6782 /* Report all recent events of a change in process status
6783 (either run the sentinel or output a message).
6784 This is usually done while Emacs is waiting for keyboard input
6785 but can be done at other times. */
6787 static void
6788 status_notify (deleting_process)
6789 struct Lisp_Process *deleting_process;
6791 register Lisp_Object proc, buffer;
6792 Lisp_Object tail, msg;
6793 struct gcpro gcpro1, gcpro2;
6795 tail = Qnil;
6796 msg = Qnil;
6797 /* We need to gcpro tail; if read_process_output calls a filter
6798 which deletes a process and removes the cons to which tail points
6799 from Vprocess_alist, and then causes a GC, tail is an unprotected
6800 reference. */
6801 GCPRO2 (tail, msg);
6803 /* Set this now, so that if new processes are created by sentinels
6804 that we run, we get called again to handle their status changes. */
6805 update_tick = process_tick;
6807 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6809 Lisp_Object symbol;
6810 register struct Lisp_Process *p;
6812 proc = Fcdr (XCAR (tail));
6813 p = XPROCESS (proc);
6815 if (p->tick != p->update_tick)
6817 p->update_tick = p->tick;
6819 /* If process is still active, read any output that remains. */
6820 while (! EQ (p->filter, Qt)
6821 && ! EQ (p->status, Qconnect)
6822 && ! EQ (p->status, Qlisten)
6823 && ! EQ (p->command, Qt) /* Network process not stopped. */
6824 && p->infd >= 0
6825 && p != deleting_process
6826 && read_process_output (proc, p->infd) > 0);
6828 buffer = p->buffer;
6830 /* Get the text to use for the message. */
6831 if (p->raw_status_new)
6832 update_status (p);
6833 msg = status_message (p);
6835 /* If process is terminated, deactivate it or delete it. */
6836 symbol = p->status;
6837 if (CONSP (p->status))
6838 symbol = XCAR (p->status);
6840 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6841 || EQ (symbol, Qclosed))
6843 if (delete_exited_processes)
6844 remove_process (proc);
6845 else
6846 deactivate_process (proc);
6849 /* The actions above may have further incremented p->tick.
6850 So set p->update_tick again
6851 so that an error in the sentinel will not cause
6852 this code to be run again. */
6853 p->update_tick = p->tick;
6854 /* Now output the message suitably. */
6855 if (!NILP (p->sentinel))
6856 exec_sentinel (proc, msg);
6857 /* Don't bother with a message in the buffer
6858 when a process becomes runnable. */
6859 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6861 Lisp_Object ro, tem;
6862 struct buffer *old = current_buffer;
6863 int opoint, opoint_byte;
6864 int before, before_byte;
6866 ro = XBUFFER (buffer)->read_only;
6868 /* Avoid error if buffer is deleted
6869 (probably that's why the process is dead, too) */
6870 if (NILP (XBUFFER (buffer)->name))
6871 continue;
6872 Fset_buffer (buffer);
6874 opoint = PT;
6875 opoint_byte = PT_BYTE;
6876 /* Insert new output into buffer
6877 at the current end-of-output marker,
6878 thus preserving logical ordering of input and output. */
6879 if (XMARKER (p->mark)->buffer)
6880 Fgoto_char (p->mark);
6881 else
6882 SET_PT_BOTH (ZV, ZV_BYTE);
6884 before = PT;
6885 before_byte = PT_BYTE;
6887 tem = current_buffer->read_only;
6888 current_buffer->read_only = Qnil;
6889 insert_string ("\nProcess ");
6890 Finsert (1, &p->name);
6891 insert_string (" ");
6892 Finsert (1, &msg);
6893 current_buffer->read_only = tem;
6894 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6896 if (opoint >= before)
6897 SET_PT_BOTH (opoint + (PT - before),
6898 opoint_byte + (PT_BYTE - before_byte));
6899 else
6900 SET_PT_BOTH (opoint, opoint_byte);
6902 set_buffer_internal (old);
6905 } /* end for */
6907 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6908 redisplay_preserve_echo_area (13);
6910 UNGCPRO;
6914 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6915 Sset_process_coding_system, 1, 3, 0,
6916 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6917 DECODING will be used to decode subprocess output and ENCODING to
6918 encode subprocess input. */)
6919 (process, decoding, encoding)
6920 register Lisp_Object process, decoding, encoding;
6922 register struct Lisp_Process *p;
6924 CHECK_PROCESS (process);
6925 p = XPROCESS (process);
6926 if (p->infd < 0)
6927 error ("Input file descriptor of %s closed", SDATA (p->name));
6928 if (p->outfd < 0)
6929 error ("Output file descriptor of %s closed", SDATA (p->name));
6930 Fcheck_coding_system (decoding);
6931 Fcheck_coding_system (encoding);
6933 p->decode_coding_system = decoding;
6934 p->encode_coding_system = encoding;
6935 setup_process_coding_systems (process);
6937 return Qnil;
6940 DEFUN ("process-coding-system",
6941 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6942 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6943 (process)
6944 register Lisp_Object process;
6946 CHECK_PROCESS (process);
6947 return Fcons (XPROCESS (process)->decode_coding_system,
6948 XPROCESS (process)->encode_coding_system);
6951 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6952 Sset_process_filter_multibyte, 2, 2, 0,
6953 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6954 If FLAG is non-nil, the filter is given multibyte strings.
6955 If FLAG is nil, the filter is given unibyte strings. In this case,
6956 all character code conversion except for end-of-line conversion is
6957 suppressed. */)
6958 (process, flag)
6959 Lisp_Object process, flag;
6961 register struct Lisp_Process *p;
6963 CHECK_PROCESS (process);
6964 p = XPROCESS (process);
6965 p->filter_multibyte = !NILP (flag);
6966 setup_process_coding_systems (process);
6968 return Qnil;
6971 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6972 Sprocess_filter_multibyte_p, 1, 1, 0,
6973 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6974 (process)
6975 Lisp_Object process;
6977 register struct Lisp_Process *p;
6979 CHECK_PROCESS (process);
6980 p = XPROCESS (process);
6982 return (p->filter_multibyte ? Qt : Qnil);
6987 /* Add DESC to the set of keyboard input descriptors. */
6989 void
6990 add_keyboard_wait_descriptor (desc)
6991 int desc;
6993 FD_SET (desc, &input_wait_mask);
6994 FD_SET (desc, &non_process_wait_mask);
6995 if (desc > max_keyboard_desc)
6996 max_keyboard_desc = desc;
6999 static int add_gpm_wait_descriptor_called_flag;
7001 void
7002 add_gpm_wait_descriptor (desc)
7003 int desc;
7005 if (! add_gpm_wait_descriptor_called_flag)
7006 FD_CLR (0, &input_wait_mask);
7007 add_gpm_wait_descriptor_called_flag = 1;
7008 FD_SET (desc, &input_wait_mask);
7009 FD_SET (desc, &gpm_wait_mask);
7010 if (desc > max_gpm_desc)
7011 max_gpm_desc = desc;
7014 /* From now on, do not expect DESC to give keyboard input. */
7016 void
7017 delete_keyboard_wait_descriptor (desc)
7018 int desc;
7020 int fd;
7021 int lim = max_keyboard_desc;
7023 FD_CLR (desc, &input_wait_mask);
7024 FD_CLR (desc, &non_process_wait_mask);
7026 if (desc == max_keyboard_desc)
7027 for (fd = 0; fd < lim; fd++)
7028 if (FD_ISSET (fd, &input_wait_mask)
7029 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7030 && !FD_ISSET (fd, &gpm_wait_mask))
7031 max_keyboard_desc = fd;
7034 void
7035 delete_gpm_wait_descriptor (desc)
7036 int desc;
7038 int fd;
7039 int lim = max_gpm_desc;
7041 FD_CLR (desc, &input_wait_mask);
7042 FD_CLR (desc, &non_process_wait_mask);
7044 if (desc == max_gpm_desc)
7045 for (fd = 0; fd < lim; fd++)
7046 if (FD_ISSET (fd, &input_wait_mask)
7047 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7048 && !FD_ISSET (fd, &non_process_wait_mask))
7049 max_gpm_desc = fd;
7052 /* Return nonzero if *MASK has a bit set
7053 that corresponds to one of the keyboard input descriptors. */
7055 static int
7056 keyboard_bit_set (mask)
7057 SELECT_TYPE *mask;
7059 int fd;
7061 for (fd = 0; fd <= max_keyboard_desc; fd++)
7062 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7063 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7064 return 1;
7066 return 0;
7069 void
7070 init_process ()
7072 register int i;
7074 inhibit_sentinels = 0;
7076 #ifdef SIGCHLD
7077 #ifndef CANNOT_DUMP
7078 if (! noninteractive || initialized)
7079 #endif
7080 signal (SIGCHLD, sigchld_handler);
7081 #endif
7083 FD_ZERO (&input_wait_mask);
7084 FD_ZERO (&non_keyboard_wait_mask);
7085 FD_ZERO (&non_process_wait_mask);
7086 max_process_desc = 0;
7088 #ifdef NON_BLOCKING_CONNECT
7089 FD_ZERO (&connect_wait_mask);
7090 num_pending_connects = 0;
7091 #endif
7093 #ifdef ADAPTIVE_READ_BUFFERING
7094 process_output_delay_count = 0;
7095 process_output_skip = 0;
7096 #endif
7098 /* Don't do this, it caused infinite select loops. The display
7099 method should call add_keyboard_wait_descriptor on stdin if it
7100 needs that. */
7101 #if 0
7102 FD_SET (0, &input_wait_mask);
7103 #endif
7105 Vprocess_alist = Qnil;
7106 #ifdef SIGCHLD
7107 deleted_pid_list = Qnil;
7108 #endif
7109 for (i = 0; i < MAXDESC; i++)
7111 chan_process[i] = Qnil;
7112 proc_buffered_char[i] = -1;
7114 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7115 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7116 #ifdef DATAGRAM_SOCKETS
7117 bzero (datagram_address, sizeof datagram_address);
7118 #endif
7120 #ifdef HAVE_SOCKETS
7122 Lisp_Object subfeatures = Qnil;
7123 struct socket_options *sopt;
7125 #define ADD_SUBFEATURE(key, val) \
7126 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7128 #ifdef NON_BLOCKING_CONNECT
7129 ADD_SUBFEATURE (QCnowait, Qt);
7130 #endif
7131 #ifdef DATAGRAM_SOCKETS
7132 ADD_SUBFEATURE (QCtype, Qdatagram);
7133 #endif
7134 #ifdef HAVE_LOCAL_SOCKETS
7135 ADD_SUBFEATURE (QCfamily, Qlocal);
7136 #endif
7137 ADD_SUBFEATURE (QCfamily, Qipv4);
7138 #ifdef AF_INET6
7139 ADD_SUBFEATURE (QCfamily, Qipv6);
7140 #endif
7141 #ifdef HAVE_GETSOCKNAME
7142 ADD_SUBFEATURE (QCservice, Qt);
7143 #endif
7144 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
7145 ADD_SUBFEATURE (QCserver, Qt);
7146 #endif
7148 for (sopt = socket_options; sopt->name; sopt++)
7149 subfeatures = Fcons (intern (sopt->name), subfeatures);
7151 Fprovide (intern ("make-network-process"), subfeatures);
7153 #endif /* HAVE_SOCKETS */
7155 #if defined (DARWIN) || defined (MAC_OSX)
7156 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7157 processes. As such, we only change the default value. */
7158 if (initialized)
7160 char *release = get_operating_system_release();
7161 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7162 && release[1] == '.')) {
7163 Vprocess_connection_type = Qnil;
7166 #endif
7169 void
7170 syms_of_process ()
7172 Qprocessp = intern ("processp");
7173 staticpro (&Qprocessp);
7174 Qrun = intern ("run");
7175 staticpro (&Qrun);
7176 Qstop = intern ("stop");
7177 staticpro (&Qstop);
7178 Qsignal = intern ("signal");
7179 staticpro (&Qsignal);
7181 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7182 here again.
7184 Qexit = intern ("exit");
7185 staticpro (&Qexit); */
7187 Qopen = intern ("open");
7188 staticpro (&Qopen);
7189 Qclosed = intern ("closed");
7190 staticpro (&Qclosed);
7191 Qconnect = intern ("connect");
7192 staticpro (&Qconnect);
7193 Qfailed = intern ("failed");
7194 staticpro (&Qfailed);
7195 Qlisten = intern ("listen");
7196 staticpro (&Qlisten);
7197 Qlocal = intern ("local");
7198 staticpro (&Qlocal);
7199 Qipv4 = intern ("ipv4");
7200 staticpro (&Qipv4);
7201 #ifdef AF_INET6
7202 Qipv6 = intern ("ipv6");
7203 staticpro (&Qipv6);
7204 #endif
7205 Qdatagram = intern ("datagram");
7206 staticpro (&Qdatagram);
7208 QCname = intern (":name");
7209 staticpro (&QCname);
7210 QCbuffer = intern (":buffer");
7211 staticpro (&QCbuffer);
7212 QChost = intern (":host");
7213 staticpro (&QChost);
7214 QCservice = intern (":service");
7215 staticpro (&QCservice);
7216 QCtype = intern (":type");
7217 staticpro (&QCtype);
7218 QClocal = intern (":local");
7219 staticpro (&QClocal);
7220 QCremote = intern (":remote");
7221 staticpro (&QCremote);
7222 QCcoding = intern (":coding");
7223 staticpro (&QCcoding);
7224 QCserver = intern (":server");
7225 staticpro (&QCserver);
7226 QCnowait = intern (":nowait");
7227 staticpro (&QCnowait);
7228 QCsentinel = intern (":sentinel");
7229 staticpro (&QCsentinel);
7230 QClog = intern (":log");
7231 staticpro (&QClog);
7232 QCnoquery = intern (":noquery");
7233 staticpro (&QCnoquery);
7234 QCstop = intern (":stop");
7235 staticpro (&QCstop);
7236 QCoptions = intern (":options");
7237 staticpro (&QCoptions);
7238 QCplist = intern (":plist");
7239 staticpro (&QCplist);
7240 QCfilter_multibyte = intern (":filter-multibyte");
7241 staticpro (&QCfilter_multibyte);
7243 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7244 staticpro (&Qlast_nonmenu_event);
7246 staticpro (&Vprocess_alist);
7247 #ifdef SIGCHLD
7248 staticpro (&deleted_pid_list);
7249 #endif
7251 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7252 doc: /* *Non-nil means delete processes immediately when they exit.
7253 A value of nil means don't delete them until `list-processes' is run. */);
7255 delete_exited_processes = 1;
7257 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7258 doc: /* Control type of device used to communicate with subprocesses.
7259 Values are nil to use a pipe, or t or `pty' to use a pty.
7260 The value has no effect if the system has no ptys or if all ptys are busy:
7261 then a pipe is used in any case.
7262 The value takes effect when `start-process' is called. */);
7263 Vprocess_connection_type = Qt;
7265 #ifdef ADAPTIVE_READ_BUFFERING
7266 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7267 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7268 On some systems, when Emacs reads the output from a subprocess, the output data
7269 is read in very small blocks, potentially resulting in very poor performance.
7270 This behavior can be remedied to some extent by setting this variable to a
7271 non-nil value, as it will automatically delay reading from such processes, to
7272 allow them to produce more output before Emacs tries to read it.
7273 If the value is t, the delay is reset after each write to the process; any other
7274 non-nil value means that the delay is not reset on write.
7275 The variable takes effect when `start-process' is called. */);
7276 Vprocess_adaptive_read_buffering = Qt;
7277 #endif
7279 defsubr (&Sprocessp);
7280 defsubr (&Sget_process);
7281 defsubr (&Sget_buffer_process);
7282 defsubr (&Sdelete_process);
7283 defsubr (&Sprocess_status);
7284 defsubr (&Sprocess_exit_status);
7285 defsubr (&Sprocess_id);
7286 defsubr (&Sprocess_name);
7287 defsubr (&Sprocess_tty_name);
7288 defsubr (&Sprocess_command);
7289 defsubr (&Sset_process_buffer);
7290 defsubr (&Sprocess_buffer);
7291 defsubr (&Sprocess_mark);
7292 defsubr (&Sset_process_filter);
7293 defsubr (&Sprocess_filter);
7294 defsubr (&Sset_process_sentinel);
7295 defsubr (&Sprocess_sentinel);
7296 defsubr (&Sset_process_window_size);
7297 defsubr (&Sset_process_inherit_coding_system_flag);
7298 defsubr (&Sprocess_inherit_coding_system_flag);
7299 defsubr (&Sset_process_query_on_exit_flag);
7300 defsubr (&Sprocess_query_on_exit_flag);
7301 defsubr (&Sprocess_contact);
7302 defsubr (&Sprocess_plist);
7303 defsubr (&Sset_process_plist);
7304 defsubr (&Slist_processes);
7305 defsubr (&Sprocess_list);
7306 defsubr (&Sstart_process);
7307 #ifdef HAVE_SOCKETS
7308 defsubr (&Sset_network_process_option);
7309 defsubr (&Smake_network_process);
7310 defsubr (&Sformat_network_address);
7311 #endif /* HAVE_SOCKETS */
7312 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7313 #ifdef SIOCGIFCONF
7314 defsubr (&Snetwork_interface_list);
7315 #endif
7316 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7317 defsubr (&Snetwork_interface_info);
7318 #endif
7319 #endif /* HAVE_SOCKETS ... */
7320 #ifdef DATAGRAM_SOCKETS
7321 defsubr (&Sprocess_datagram_address);
7322 defsubr (&Sset_process_datagram_address);
7323 #endif
7324 defsubr (&Saccept_process_output);
7325 defsubr (&Sprocess_send_region);
7326 defsubr (&Sprocess_send_string);
7327 defsubr (&Sinterrupt_process);
7328 defsubr (&Skill_process);
7329 defsubr (&Squit_process);
7330 defsubr (&Sstop_process);
7331 defsubr (&Scontinue_process);
7332 defsubr (&Sprocess_running_child_p);
7333 defsubr (&Sprocess_send_eof);
7334 defsubr (&Ssignal_process);
7335 defsubr (&Swaiting_for_user_input_p);
7336 /* defsubr (&Sprocess_connection); */
7337 defsubr (&Sset_process_coding_system);
7338 defsubr (&Sprocess_coding_system);
7339 defsubr (&Sset_process_filter_multibyte);
7340 defsubr (&Sprocess_filter_multibyte_p);
7344 #else /* not subprocesses */
7346 #include <sys/types.h>
7347 #include <errno.h>
7349 #include "lisp.h"
7350 #include "systime.h"
7351 #include "charset.h"
7352 #include "coding.h"
7353 #include "termopts.h"
7354 #include "sysselect.h"
7356 extern int frame_garbaged;
7358 extern EMACS_TIME timer_check ();
7359 extern int timers_run;
7361 Lisp_Object QCtype;
7363 /* As described above, except assuming that there are no subprocesses:
7365 Wait for timeout to elapse and/or keyboard input to be available.
7367 time_limit is:
7368 timeout in seconds, or
7369 zero for no limit, or
7370 -1 means gobble data immediately available but don't wait for any.
7372 read_kbd is a Lisp_Object:
7373 0 to ignore keyboard input, or
7374 1 to return when input is available, or
7375 -1 means caller will actually read the input, so don't throw to
7376 the quit handler.
7378 see full version for other parameters. We know that wait_proc will
7379 always be NULL, since `subprocesses' isn't defined.
7381 do_display != 0 means redisplay should be done to show subprocess
7382 output that arrives.
7384 Return true if we received input from any process. */
7387 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7388 wait_for_cell, wait_proc, just_wait_proc)
7389 int time_limit, microsecs, read_kbd, do_display;
7390 Lisp_Object wait_for_cell;
7391 struct Lisp_Process *wait_proc;
7392 int just_wait_proc;
7394 register int nfds;
7395 EMACS_TIME end_time, timeout;
7396 SELECT_TYPE waitchannels;
7397 int xerrno;
7399 /* What does time_limit really mean? */
7400 if (time_limit || microsecs)
7402 EMACS_GET_TIME (end_time);
7403 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7404 EMACS_ADD_TIME (end_time, end_time, timeout);
7407 /* Turn off periodic alarms (in case they are in use)
7408 and then turn off any other atimers,
7409 because the select emulator uses alarms. */
7410 stop_polling ();
7411 turn_on_atimers (0);
7413 while (1)
7415 int timeout_reduced_for_timers = 0;
7417 /* If calling from keyboard input, do not quit
7418 since we want to return C-g as an input character.
7419 Otherwise, do pending quit if requested. */
7420 if (read_kbd >= 0)
7421 QUIT;
7423 /* Exit now if the cell we're waiting for became non-nil. */
7424 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7425 break;
7427 /* Compute time from now till when time limit is up */
7428 /* Exit if already run out */
7429 if (time_limit == -1)
7431 /* -1 specified for timeout means
7432 gobble output available now
7433 but don't wait at all. */
7435 EMACS_SET_SECS_USECS (timeout, 0, 0);
7437 else if (time_limit || microsecs)
7439 EMACS_GET_TIME (timeout);
7440 EMACS_SUB_TIME (timeout, end_time, timeout);
7441 if (EMACS_TIME_NEG_P (timeout))
7442 break;
7444 else
7446 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7449 /* If our caller will not immediately handle keyboard events,
7450 run timer events directly.
7451 (Callers that will immediately read keyboard events
7452 call timer_delay on their own.) */
7453 if (NILP (wait_for_cell))
7455 EMACS_TIME timer_delay;
7459 int old_timers_run = timers_run;
7460 timer_delay = timer_check (1);
7461 if (timers_run != old_timers_run && do_display)
7462 /* We must retry, since a timer may have requeued itself
7463 and that could alter the time delay. */
7464 redisplay_preserve_echo_area (14);
7465 else
7466 break;
7468 while (!detect_input_pending ());
7470 /* If there is unread keyboard input, also return. */
7471 if (read_kbd != 0
7472 && requeued_events_pending_p ())
7473 break;
7475 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7477 EMACS_TIME difference;
7478 EMACS_SUB_TIME (difference, timer_delay, timeout);
7479 if (EMACS_TIME_NEG_P (difference))
7481 timeout = timer_delay;
7482 timeout_reduced_for_timers = 1;
7487 /* Cause C-g and alarm signals to take immediate action,
7488 and cause input available signals to zero out timeout. */
7489 if (read_kbd < 0)
7490 set_waiting_for_input (&timeout);
7492 /* Wait till there is something to do. */
7494 if (! read_kbd && NILP (wait_for_cell))
7495 FD_ZERO (&waitchannels);
7496 else
7497 FD_SET (0, &waitchannels);
7499 /* If a frame has been newly mapped and needs updating,
7500 reprocess its display stuff. */
7501 if (frame_garbaged && do_display)
7503 clear_waiting_for_input ();
7504 redisplay_preserve_echo_area (15);
7505 if (read_kbd < 0)
7506 set_waiting_for_input (&timeout);
7509 if (read_kbd && detect_input_pending ())
7511 nfds = 0;
7512 FD_ZERO (&waitchannels);
7514 else
7515 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7516 &timeout);
7518 xerrno = errno;
7520 /* Make C-g and alarm signals set flags again */
7521 clear_waiting_for_input ();
7523 /* If we woke up due to SIGWINCH, actually change size now. */
7524 do_pending_window_change (0);
7526 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7527 /* We waited the full specified time, so return now. */
7528 break;
7530 if (nfds == -1)
7532 /* If the system call was interrupted, then go around the
7533 loop again. */
7534 if (xerrno == EINTR)
7535 FD_ZERO (&waitchannels);
7536 else
7537 error ("select error: %s", emacs_strerror (xerrno));
7539 #ifdef sun
7540 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7541 /* System sometimes fails to deliver SIGIO. */
7542 kill (getpid (), SIGIO);
7543 #endif
7544 #ifdef SIGIO
7545 if (read_kbd && interrupt_input && (waitchannels & 1))
7546 kill (getpid (), SIGIO);
7547 #endif
7549 /* Check for keyboard input */
7551 if (read_kbd
7552 && detect_input_pending_run_timers (do_display))
7554 swallow_events (do_display);
7555 if (detect_input_pending_run_timers (do_display))
7556 break;
7559 /* If there is unread keyboard input, also return. */
7560 if (read_kbd
7561 && requeued_events_pending_p ())
7562 break;
7564 /* If wait_for_cell. check for keyboard input
7565 but don't run any timers.
7566 ??? (It seems wrong to me to check for keyboard
7567 input at all when wait_for_cell, but the code
7568 has been this way since July 1994.
7569 Try changing this after version 19.31.) */
7570 if (! NILP (wait_for_cell)
7571 && detect_input_pending ())
7573 swallow_events (do_display);
7574 if (detect_input_pending ())
7575 break;
7578 /* Exit now if the cell we're waiting for became non-nil. */
7579 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7580 break;
7583 start_polling ();
7585 return 0;
7589 /* Don't confuse make-docfile by having two doc strings for this function.
7590 make-docfile does not pay attention to #if, for good reason! */
7591 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7593 (name)
7594 register Lisp_Object name;
7596 return Qnil;
7599 /* Don't confuse make-docfile by having two doc strings for this function.
7600 make-docfile does not pay attention to #if, for good reason! */
7601 DEFUN ("process-inherit-coding-system-flag",
7602 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7603 1, 1, 0,
7605 (process)
7606 register Lisp_Object process;
7608 /* Ignore the argument and return the value of
7609 inherit-process-coding-system. */
7610 return inherit_process_coding_system ? Qt : Qnil;
7613 /* Kill all processes associated with `buffer'.
7614 If `buffer' is nil, kill all processes.
7615 Since we have no subprocesses, this does nothing. */
7617 void
7618 kill_buffer_processes (buffer)
7619 Lisp_Object buffer;
7623 void
7624 init_process ()
7628 void
7629 syms_of_process ()
7631 QCtype = intern (":type");
7632 staticpro (&QCtype);
7634 defsubr (&Sget_buffer_process);
7635 defsubr (&Sprocess_inherit_coding_system_flag);
7639 #endif /* not subprocesses */
7641 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7642 (do not change this comment) */