* process.h (PSET): Remove.
[emacs.git] / src / process.c
blob66cc6a103bd112a84fa3dbf9c00b90aa2ca3555e
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2012
4 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 of the License, or
11 (at your option) 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. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #define PROCESS_INLINE EXTERN_INLINE
26 #include <signal.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <setjmp.h>
30 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
31 #include <sys/file.h>
32 #include <sys/stat.h>
33 #include <setjmp.h>
35 #include <unistd.h>
36 #include <fcntl.h>
38 #include "lisp.h"
40 /* Only MS-DOS does not define `subprocesses'. */
41 #ifdef subprocesses
43 #include <sys/socket.h>
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
48 /* Are local (unix) sockets supported? */
49 #if defined (HAVE_SYS_UN_H)
50 #if !defined (AF_LOCAL) && defined (AF_UNIX)
51 #define AF_LOCAL AF_UNIX
52 #endif
53 #ifdef AF_LOCAL
54 #define HAVE_LOCAL_SOCKETS
55 #include <sys/un.h>
56 #endif
57 #endif
59 #include <sys/ioctl.h>
60 #if defined (HAVE_NET_IF_H)
61 #include <net/if.h>
62 #endif /* HAVE_NET_IF_H */
64 #if defined (HAVE_IFADDRS_H)
65 /* Must be after net/if.h */
66 #include <ifaddrs.h>
68 /* We only use structs from this header when we use getifaddrs. */
69 #if defined (HAVE_NET_IF_DL_H)
70 #include <net/if_dl.h>
71 #endif
73 #endif
75 #ifdef NEED_BSDTTY
76 #include <bsdtty.h>
77 #endif
79 #ifdef HAVE_RES_INIT
80 #include <netinet/in.h>
81 #include <arpa/nameser.h>
82 #include <resolv.h>
83 #endif
85 #ifdef HAVE_UTIL_H
86 #include <util.h>
87 #endif
89 #ifdef HAVE_PTY_H
90 #include <pty.h>
91 #endif
93 #endif /* subprocesses */
95 #include "systime.h"
96 #include "systty.h"
98 #include "window.h"
99 #include "character.h"
100 #include "buffer.h"
101 #include "coding.h"
102 #include "process.h"
103 #include "frame.h"
104 #include "termhooks.h"
105 #include "termopts.h"
106 #include "commands.h"
107 #include "keyboard.h"
108 #include "blockinput.h"
109 #include "dispextern.h"
110 #include "composite.h"
111 #include "atimer.h"
112 #include "sysselect.h"
113 #include "syssignal.h"
114 #include "syswait.h"
115 #ifdef HAVE_GNUTLS
116 #include "gnutls.h"
117 #endif
119 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
120 #include "xgselect.h"
121 #endif
122 #ifdef HAVE_NS
123 #include "nsterm.h"
124 #endif
126 /* Work around GCC 4.7.0 bug with strict overflow checking; see
127 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
128 These lines can be removed once the GCC bug is fixed. */
129 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
130 # pragma GCC diagnostic ignored "-Wstrict-overflow"
131 #endif
133 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
134 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
135 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
136 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
137 Lisp_Object QCname, QCtype;
139 /* Non-zero if keyboard input is on hold, zero otherwise. */
141 static int kbd_is_on_hold;
143 /* Nonzero means don't run process sentinels. This is used
144 when exiting. */
145 int inhibit_sentinels;
147 #ifdef subprocesses
149 Lisp_Object Qprocessp;
150 static Lisp_Object Qrun, Qstop, Qsignal;
151 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
152 Lisp_Object Qlocal;
153 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
154 static Lisp_Object Qreal, Qnetwork, Qserial;
155 #ifdef AF_INET6
156 static Lisp_Object Qipv6;
157 #endif
158 static Lisp_Object QCport, QCprocess;
159 Lisp_Object QCspeed;
160 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
161 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
162 static Lisp_Object QCbuffer, QChost, QCservice;
163 static Lisp_Object QClocal, QCremote, QCcoding;
164 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
165 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
166 static Lisp_Object Qlast_nonmenu_event;
167 /* QCfamily is declared and initialized in xfaces.c,
168 QCfilter in keyboard.c. */
169 extern Lisp_Object QCfamily, QCfilter;
171 /* Qexit is declared and initialized in eval.c. */
173 /* QCfamily is defined in xfaces.c. */
174 extern Lisp_Object QCfamily;
175 /* QCfilter is defined in keyboard.c. */
176 extern Lisp_Object QCfilter;
178 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
179 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
180 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
181 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
183 #ifndef HAVE_H_ERRNO
184 extern int h_errno;
185 #endif
187 /* Number of events of change of status of a process. */
188 static EMACS_INT process_tick;
189 /* Number of events for which the user or sentinel has been notified. */
190 static EMACS_INT update_tick;
192 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
194 /* Only W32 has this, it really means that select can't take write mask. */
195 #ifdef BROKEN_NON_BLOCKING_CONNECT
196 #undef NON_BLOCKING_CONNECT
197 #define SELECT_CANT_DO_WRITE_MASK
198 #else
199 #ifndef NON_BLOCKING_CONNECT
200 #ifdef HAVE_SELECT
201 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
202 #if defined (O_NONBLOCK) || defined (O_NDELAY)
203 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
204 #define NON_BLOCKING_CONNECT
205 #endif /* EWOULDBLOCK || EINPROGRESS */
206 #endif /* O_NONBLOCK || O_NDELAY */
207 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
208 #endif /* HAVE_SELECT */
209 #endif /* NON_BLOCKING_CONNECT */
210 #endif /* BROKEN_NON_BLOCKING_CONNECT */
212 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
213 this system. We need to read full packets, so we need a
214 "non-destructive" select. So we require either native select,
215 or emulation of select using FIONREAD. */
217 #ifdef BROKEN_DATAGRAM_SOCKETS
218 #undef DATAGRAM_SOCKETS
219 #else
220 #ifndef DATAGRAM_SOCKETS
221 #if defined (HAVE_SELECT) || defined (FIONREAD)
222 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
223 #define DATAGRAM_SOCKETS
224 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
225 #endif /* HAVE_SELECT || FIONREAD */
226 #endif /* DATAGRAM_SOCKETS */
227 #endif /* BROKEN_DATAGRAM_SOCKETS */
229 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
230 # define HAVE_SEQPACKET
231 #endif
233 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
234 #define ADAPTIVE_READ_BUFFERING
235 #endif
237 #ifdef ADAPTIVE_READ_BUFFERING
238 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
239 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
240 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
242 /* Number of processes which have a non-zero read_output_delay,
243 and therefore might be delayed for adaptive read buffering. */
245 static int process_output_delay_count;
247 /* Non-zero if any process has non-nil read_output_skip. */
249 static int process_output_skip;
251 #else
252 #define process_output_delay_count 0
253 #endif
255 static void create_process (Lisp_Object, char **, Lisp_Object);
256 #ifdef SIGIO
257 static int keyboard_bit_set (SELECT_TYPE *);
258 #endif
259 static void deactivate_process (Lisp_Object);
260 static void status_notify (struct Lisp_Process *);
261 static int read_process_output (Lisp_Object, int);
262 static void create_pty (Lisp_Object);
264 /* If we support a window system, turn on the code to poll periodically
265 to detect C-g. It isn't actually used when doing interrupt input. */
266 #if defined (HAVE_WINDOW_SYSTEM) && !defined (USE_ASYNC_EVENTS)
267 #define POLL_FOR_INPUT
268 #endif
270 static Lisp_Object get_process (register Lisp_Object name);
271 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
273 /* Mask of bits indicating the descriptors that we wait for input on. */
275 static SELECT_TYPE input_wait_mask;
277 /* Mask that excludes keyboard input descriptor(s). */
279 static SELECT_TYPE non_keyboard_wait_mask;
281 /* Mask that excludes process input descriptor(s). */
283 static SELECT_TYPE non_process_wait_mask;
285 /* Mask for selecting for write. */
287 static SELECT_TYPE write_mask;
289 #ifdef NON_BLOCKING_CONNECT
290 /* Mask of bits indicating the descriptors that we wait for connect to
291 complete on. Once they complete, they are removed from this mask
292 and added to the input_wait_mask and non_keyboard_wait_mask. */
294 static SELECT_TYPE connect_wait_mask;
296 /* Number of bits set in connect_wait_mask. */
297 static int num_pending_connects;
298 #endif /* NON_BLOCKING_CONNECT */
300 /* The largest descriptor currently in use for a process object. */
301 static int max_process_desc;
303 /* The largest descriptor currently in use for input. */
304 static int max_input_desc;
306 /* Indexed by descriptor, gives the process (if any) for that descriptor */
307 static Lisp_Object chan_process[MAXDESC];
309 /* Alist of elements (NAME . PROCESS) */
310 static Lisp_Object Vprocess_alist;
312 /* Buffered-ahead input char from process, indexed by channel.
313 -1 means empty (no char is buffered).
314 Used on sys V where the only way to tell if there is any
315 output from the process is to read at least one char.
316 Always -1 on systems that support FIONREAD. */
318 static int proc_buffered_char[MAXDESC];
320 /* Table of `struct coding-system' for each process. */
321 static struct coding_system *proc_decode_coding_system[MAXDESC];
322 static struct coding_system *proc_encode_coding_system[MAXDESC];
324 #ifdef DATAGRAM_SOCKETS
325 /* Table of `partner address' for datagram sockets. */
326 static struct sockaddr_and_len {
327 struct sockaddr *sa;
328 int len;
329 } datagram_address[MAXDESC];
330 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
331 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
332 #else
333 #define DATAGRAM_CHAN_P(chan) (0)
334 #define DATAGRAM_CONN_P(proc) (0)
335 #endif
337 /* Maximum number of bytes to send to a pty without an eof. */
338 static int pty_max_bytes;
340 /* These setters are used only in this file, so they can be private. */
341 static inline void
342 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
344 p->buffer = val;
346 static inline void
347 pset_command (struct Lisp_Process *p, Lisp_Object val)
349 p->command = val;
351 static inline void
352 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
354 p->decode_coding_system = val;
356 static inline void
357 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
359 p->decoding_buf = val;
361 static inline void
362 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
364 p->encode_coding_system = val;
366 static inline void
367 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
369 p->encoding_buf = val;
371 static inline void
372 pset_filter (struct Lisp_Process *p, Lisp_Object val)
374 p->filter = val;
376 static inline void
377 pset_log (struct Lisp_Process *p, Lisp_Object val)
379 p->log = val;
381 static inline void
382 pset_mark (struct Lisp_Process *p, Lisp_Object val)
384 p->mark = val;
386 static inline void
387 pset_name (struct Lisp_Process *p, Lisp_Object val)
389 p->name = val;
391 static inline void
392 pset_plist (struct Lisp_Process *p, Lisp_Object val)
394 p->plist = val;
396 static inline void
397 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
399 p->sentinel = val;
401 static inline void
402 pset_status (struct Lisp_Process *p, Lisp_Object val)
404 p->status = val;
406 static inline void
407 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
409 p->tty_name = val;
411 static inline void
412 pset_type (struct Lisp_Process *p, Lisp_Object val)
414 p->type = val;
416 static inline void
417 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
419 p->write_queue = val;
424 static struct fd_callback_data
426 fd_callback func;
427 void *data;
428 #define FOR_READ 1
429 #define FOR_WRITE 2
430 int condition; /* mask of the defines above. */
431 } fd_callback_info[MAXDESC];
434 /* Add a file descriptor FD to be monitored for when read is possible.
435 When read is possible, call FUNC with argument DATA. */
437 void
438 add_read_fd (int fd, fd_callback func, void *data)
440 eassert (fd < MAXDESC);
441 add_keyboard_wait_descriptor (fd);
443 fd_callback_info[fd].func = func;
444 fd_callback_info[fd].data = data;
445 fd_callback_info[fd].condition |= FOR_READ;
448 /* Stop monitoring file descriptor FD for when read is possible. */
450 void
451 delete_read_fd (int fd)
453 eassert (fd < MAXDESC);
454 delete_keyboard_wait_descriptor (fd);
456 fd_callback_info[fd].condition &= ~FOR_READ;
457 if (fd_callback_info[fd].condition == 0)
459 fd_callback_info[fd].func = 0;
460 fd_callback_info[fd].data = 0;
464 /* Add a file descriptor FD to be monitored for when write is possible.
465 When write is possible, call FUNC with argument DATA. */
467 void
468 add_write_fd (int fd, fd_callback func, void *data)
470 eassert (fd < MAXDESC);
471 FD_SET (fd, &write_mask);
472 if (fd > max_input_desc)
473 max_input_desc = fd;
475 fd_callback_info[fd].func = func;
476 fd_callback_info[fd].data = data;
477 fd_callback_info[fd].condition |= FOR_WRITE;
480 /* Stop monitoring file descriptor FD for when write is possible. */
482 void
483 delete_write_fd (int fd)
485 int lim = max_input_desc;
487 eassert (fd < MAXDESC);
488 FD_CLR (fd, &write_mask);
489 fd_callback_info[fd].condition &= ~FOR_WRITE;
490 if (fd_callback_info[fd].condition == 0)
492 fd_callback_info[fd].func = 0;
493 fd_callback_info[fd].data = 0;
495 if (fd == max_input_desc)
496 for (fd = lim; fd >= 0; fd--)
497 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
499 max_input_desc = fd;
500 break;
507 /* Compute the Lisp form of the process status, p->status, from
508 the numeric status that was returned by `wait'. */
510 static Lisp_Object status_convert (int);
512 static void
513 update_status (struct Lisp_Process *p)
515 eassert (p->raw_status_new);
516 pset_status (p, status_convert (p->raw_status));
517 p->raw_status_new = 0;
520 /* Convert a process status word in Unix format to
521 the list that we use internally. */
523 static Lisp_Object
524 status_convert (int w)
526 if (WIFSTOPPED (w))
527 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
528 else if (WIFEXITED (w))
529 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
530 WCOREDUMP (w) ? Qt : Qnil));
531 else if (WIFSIGNALED (w))
532 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
533 WCOREDUMP (w) ? Qt : Qnil));
534 else
535 return Qrun;
538 /* Given a status-list, extract the three pieces of information
539 and store them individually through the three pointers. */
541 static void
542 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
544 Lisp_Object tem;
546 if (SYMBOLP (l))
548 *symbol = l;
549 *code = 0;
550 *coredump = 0;
552 else
554 *symbol = XCAR (l);
555 tem = XCDR (l);
556 *code = XFASTINT (XCAR (tem));
557 tem = XCDR (tem);
558 *coredump = !NILP (tem);
562 /* Return a string describing a process status list. */
564 static Lisp_Object
565 status_message (struct Lisp_Process *p)
567 Lisp_Object status = p->status;
568 Lisp_Object symbol;
569 int code, coredump;
570 Lisp_Object string, string2;
572 decode_status (status, &symbol, &code, &coredump);
574 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
576 char *signame;
577 synchronize_system_messages_locale ();
578 signame = strsignal (code);
579 if (signame == 0)
580 string = build_string ("unknown");
581 else
583 int c1, c2;
585 string = build_unibyte_string (signame);
586 if (! NILP (Vlocale_coding_system))
587 string = (code_convert_string_norecord
588 (string, Vlocale_coding_system, 0));
589 c1 = STRING_CHAR (SDATA (string));
590 c2 = downcase (c1);
591 if (c1 != c2)
592 Faset (string, make_number (0), make_number (c2));
594 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
595 return concat2 (string, string2);
597 else if (EQ (symbol, Qexit))
599 if (NETCONN1_P (p))
600 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
601 if (code == 0)
602 return build_string ("finished\n");
603 string = Fnumber_to_string (make_number (code));
604 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
605 return concat3 (build_string ("exited abnormally with code "),
606 string, string2);
608 else if (EQ (symbol, Qfailed))
610 string = Fnumber_to_string (make_number (code));
611 string2 = build_string ("\n");
612 return concat3 (build_string ("failed with code "),
613 string, string2);
615 else
616 return Fcopy_sequence (Fsymbol_name (symbol));
619 #ifdef HAVE_PTYS
621 /* The file name of the pty opened by allocate_pty. */
622 static char pty_name[24];
624 /* Open an available pty, returning a file descriptor.
625 Return -1 on failure.
626 The file name of the terminal corresponding to the pty
627 is left in the variable pty_name. */
629 static int
630 allocate_pty (void)
632 int fd;
634 #ifdef PTY_ITERATION
635 PTY_ITERATION
636 #else
637 register int c, i;
638 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
639 for (i = 0; i < 16; i++)
640 #endif
642 #ifdef PTY_NAME_SPRINTF
643 PTY_NAME_SPRINTF
644 #else
645 sprintf (pty_name, "/dev/pty%c%x", c, i);
646 #endif /* no PTY_NAME_SPRINTF */
648 #ifdef PTY_OPEN
649 PTY_OPEN;
650 #else /* no PTY_OPEN */
652 { /* Some systems name their pseudoterminals so that there are gaps in
653 the usual sequence - for example, on HP9000/S700 systems, there
654 are no pseudoterminals with names ending in 'f'. So we wait for
655 three failures in a row before deciding that we've reached the
656 end of the ptys. */
657 int failed_count = 0;
658 struct stat stb;
660 if (stat (pty_name, &stb) < 0)
662 failed_count++;
663 if (failed_count >= 3)
664 return -1;
666 else
667 failed_count = 0;
669 # ifdef O_NONBLOCK
670 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
671 # else
672 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
673 # endif
675 #endif /* no PTY_OPEN */
677 if (fd >= 0)
679 /* check to make certain that both sides are available
680 this avoids a nasty yet stupid bug in rlogins */
681 #ifdef PTY_TTY_NAME_SPRINTF
682 PTY_TTY_NAME_SPRINTF
683 #else
684 sprintf (pty_name, "/dev/tty%c%x", c, i);
685 #endif /* no PTY_TTY_NAME_SPRINTF */
686 if (access (pty_name, 6) != 0)
688 emacs_close (fd);
689 # ifndef __sgi
690 continue;
691 # else
692 return -1;
693 # endif /* __sgi */
695 setup_pty (fd);
696 return fd;
699 return -1;
701 #endif /* HAVE_PTYS */
703 static Lisp_Object
704 make_process (Lisp_Object name)
706 register Lisp_Object val, tem, name1;
707 register struct Lisp_Process *p;
708 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
709 printmax_t i;
711 p = allocate_process ();
712 /* Initialize Lisp data. Note that allocate_process initializes all
713 Lisp data to nil, so do it only for slots which should not be nil. */
714 pset_status (p, Qrun);
715 pset_mark (p, Fmake_marker ());
717 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
718 non-Lisp data, so do it only for slots which should not be zero. */
719 p->infd = -1;
720 p->outfd = -1;
722 #ifdef HAVE_GNUTLS
723 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
724 #endif
726 /* If name is already in use, modify it until it is unused. */
728 name1 = name;
729 for (i = 1; ; i++)
731 tem = Fget_process (name1);
732 if (NILP (tem)) break;
733 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
735 name = name1;
736 pset_name (p, name);
737 XSETPROCESS (val, p);
738 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
739 return val;
742 static void
743 remove_process (register Lisp_Object proc)
745 register Lisp_Object pair;
747 pair = Frassq (proc, Vprocess_alist);
748 Vprocess_alist = Fdelq (pair, Vprocess_alist);
750 deactivate_process (proc);
754 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
755 doc: /* Return t if OBJECT is a process. */)
756 (Lisp_Object object)
758 return PROCESSP (object) ? Qt : Qnil;
761 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
762 doc: /* Return the process named NAME, or nil if there is none. */)
763 (register Lisp_Object name)
765 if (PROCESSP (name))
766 return name;
767 CHECK_STRING (name);
768 return Fcdr (Fassoc (name, Vprocess_alist));
771 /* This is how commands for the user decode process arguments. It
772 accepts a process, a process name, a buffer, a buffer name, or nil.
773 Buffers denote the first process in the buffer, and nil denotes the
774 current buffer. */
776 static Lisp_Object
777 get_process (register Lisp_Object name)
779 register Lisp_Object proc, obj;
780 if (STRINGP (name))
782 obj = Fget_process (name);
783 if (NILP (obj))
784 obj = Fget_buffer (name);
785 if (NILP (obj))
786 error ("Process %s does not exist", SDATA (name));
788 else if (NILP (name))
789 obj = Fcurrent_buffer ();
790 else
791 obj = name;
793 /* Now obj should be either a buffer object or a process object.
795 if (BUFFERP (obj))
797 proc = Fget_buffer_process (obj);
798 if (NILP (proc))
799 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
801 else
803 CHECK_PROCESS (obj);
804 proc = obj;
806 return proc;
810 #ifdef SIGCHLD
811 /* Fdelete_process promises to immediately forget about the process, but in
812 reality, Emacs needs to remember those processes until they have been
813 treated by sigchld_handler; otherwise this handler would consider the
814 process as being synchronous and say that the synchronous process is
815 dead. */
816 static Lisp_Object deleted_pid_list;
817 #endif
819 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
820 doc: /* Delete PROCESS: kill it and forget about it immediately.
821 PROCESS may be a process, a buffer, the name of a process or buffer, or
822 nil, indicating the current buffer's process. */)
823 (register Lisp_Object process)
825 register struct Lisp_Process *p;
827 process = get_process (process);
828 p = XPROCESS (process);
830 p->raw_status_new = 0;
831 if (NETCONN1_P (p) || SERIALCONN1_P (p))
833 pset_status (p, Fcons (Qexit, Fcons (make_number (0), Qnil)));
834 p->tick = ++process_tick;
835 status_notify (p);
836 redisplay_preserve_echo_area (13);
838 else if (p->infd >= 0)
840 #ifdef SIGCHLD
841 Lisp_Object symbol;
842 pid_t pid = p->pid;
844 /* No problem storing the pid here, as it is still in Vprocess_alist. */
845 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
846 /* GC treated elements set to nil. */
847 Fdelq (Qnil, deleted_pid_list));
848 /* If the process has already signaled, remove it from the list. */
849 if (p->raw_status_new)
850 update_status (p);
851 symbol = p->status;
852 if (CONSP (p->status))
853 symbol = XCAR (p->status);
854 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
855 deleted_pid_list
856 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
857 else
858 #endif
860 Fkill_process (process, Qnil);
861 /* Do this now, since remove_process will make sigchld_handler do nothing. */
862 pset_status (p, Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil)));
863 p->tick = ++process_tick;
864 status_notify (p);
865 redisplay_preserve_echo_area (13);
868 remove_process (process);
869 return Qnil;
872 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
873 doc: /* Return the status of PROCESS.
874 The returned value is one of the following symbols:
875 run -- for a process that is running.
876 stop -- for a process stopped but continuable.
877 exit -- for a process that has exited.
878 signal -- for a process that has got a fatal signal.
879 open -- for a network stream connection that is open.
880 listen -- for a network stream server that is listening.
881 closed -- for a network stream connection that is closed.
882 connect -- when waiting for a non-blocking connection to complete.
883 failed -- when a non-blocking connection has failed.
884 nil -- if arg is a process name and no such process exists.
885 PROCESS may be a process, a buffer, the name of a process, or
886 nil, indicating the current buffer's process. */)
887 (register Lisp_Object process)
889 register struct Lisp_Process *p;
890 register Lisp_Object status;
892 if (STRINGP (process))
893 process = Fget_process (process);
894 else
895 process = get_process (process);
897 if (NILP (process))
898 return process;
900 p = XPROCESS (process);
901 if (p->raw_status_new)
902 update_status (p);
903 status = p->status;
904 if (CONSP (status))
905 status = XCAR (status);
906 if (NETCONN1_P (p) || SERIALCONN1_P (p))
908 if (EQ (status, Qexit))
909 status = Qclosed;
910 else if (EQ (p->command, Qt))
911 status = Qstop;
912 else if (EQ (status, Qrun))
913 status = Qopen;
915 return status;
918 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
919 1, 1, 0,
920 doc: /* Return the exit status of PROCESS or the signal number that killed it.
921 If PROCESS has not yet exited or died, return 0. */)
922 (register Lisp_Object process)
924 CHECK_PROCESS (process);
925 if (XPROCESS (process)->raw_status_new)
926 update_status (XPROCESS (process));
927 if (CONSP (XPROCESS (process)->status))
928 return XCAR (XCDR (XPROCESS (process)->status));
929 return make_number (0);
932 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
933 doc: /* Return the process id of PROCESS.
934 This is the pid of the external process which PROCESS uses or talks to.
935 For a network connection, this value is nil. */)
936 (register Lisp_Object process)
938 pid_t pid;
940 CHECK_PROCESS (process);
941 pid = XPROCESS (process)->pid;
942 return (pid ? make_fixnum_or_float (pid) : Qnil);
945 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
946 doc: /* Return the name of PROCESS, as a string.
947 This is the name of the program invoked in PROCESS,
948 possibly modified to make it unique among process names. */)
949 (register Lisp_Object process)
951 CHECK_PROCESS (process);
952 return XPROCESS (process)->name;
955 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
956 doc: /* Return the command that was executed to start PROCESS.
957 This is a list of strings, the first string being the program executed
958 and the rest of the strings being the arguments given to it.
959 For a network or serial process, this is nil (process is running) or t
960 \(process is stopped). */)
961 (register Lisp_Object process)
963 CHECK_PROCESS (process);
964 return XPROCESS (process)->command;
967 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
968 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
969 This is the terminal that the process itself reads and writes on,
970 not the name of the pty that Emacs uses to talk with that terminal. */)
971 (register Lisp_Object process)
973 CHECK_PROCESS (process);
974 return XPROCESS (process)->tty_name;
977 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
978 2, 2, 0,
979 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
980 Return BUFFER. */)
981 (register Lisp_Object process, Lisp_Object buffer)
983 struct Lisp_Process *p;
985 CHECK_PROCESS (process);
986 if (!NILP (buffer))
987 CHECK_BUFFER (buffer);
988 p = XPROCESS (process);
989 pset_buffer (p, buffer);
990 if (NETCONN1_P (p) || SERIALCONN1_P (p))
991 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
992 setup_process_coding_systems (process);
993 return buffer;
996 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
997 1, 1, 0,
998 doc: /* Return the buffer PROCESS is associated with.
999 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1000 (register Lisp_Object process)
1002 CHECK_PROCESS (process);
1003 return XPROCESS (process)->buffer;
1006 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1007 1, 1, 0,
1008 doc: /* Return the marker for the end of the last output from PROCESS. */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->mark;
1015 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1016 2, 2, 0,
1017 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
1018 A value of t means stop accepting output from the process.
1020 When a process has a filter, its buffer is not used for output.
1021 Instead, each time it does output, the entire string of output is
1022 passed to the filter.
1024 The filter gets two arguments: the process and the string of output.
1025 The string argument is normally a multibyte string, except:
1026 - if the process' input coding system is no-conversion or raw-text,
1027 it is a unibyte string (the non-converted input), or else
1028 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1029 string (the result of converting the decoded input multibyte
1030 string to unibyte with `string-make-unibyte'). */)
1031 (register Lisp_Object process, Lisp_Object filter)
1033 struct Lisp_Process *p;
1035 CHECK_PROCESS (process);
1036 p = XPROCESS (process);
1038 /* Don't signal an error if the process' input file descriptor
1039 is closed. This could make debugging Lisp more difficult,
1040 for example when doing something like
1042 (setq process (start-process ...))
1043 (debug)
1044 (set-process-filter process ...) */
1046 if (p->infd >= 0)
1048 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1050 FD_CLR (p->infd, &input_wait_mask);
1051 FD_CLR (p->infd, &non_keyboard_wait_mask);
1053 else if (EQ (p->filter, Qt)
1054 /* Network or serial process not stopped: */
1055 && !EQ (p->command, Qt))
1057 FD_SET (p->infd, &input_wait_mask);
1058 FD_SET (p->infd, &non_keyboard_wait_mask);
1062 pset_filter (p, filter);
1063 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1064 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1065 setup_process_coding_systems (process);
1066 return filter;
1069 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1070 1, 1, 0,
1071 doc: /* Returns the filter function of PROCESS; nil if none.
1072 See `set-process-filter' for more info on filter functions. */)
1073 (register Lisp_Object process)
1075 CHECK_PROCESS (process);
1076 return XPROCESS (process)->filter;
1079 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1080 2, 2, 0,
1081 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1082 The sentinel is called as a function when the process changes state.
1083 It gets two arguments: the process, and a string describing the change. */)
1084 (register Lisp_Object process, Lisp_Object sentinel)
1086 struct Lisp_Process *p;
1088 CHECK_PROCESS (process);
1089 p = XPROCESS (process);
1091 pset_sentinel (p, sentinel);
1092 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1093 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1094 return sentinel;
1097 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1098 1, 1, 0,
1099 doc: /* Return the sentinel of PROCESS; nil if none.
1100 See `set-process-sentinel' for more info on sentinels. */)
1101 (register Lisp_Object process)
1103 CHECK_PROCESS (process);
1104 return XPROCESS (process)->sentinel;
1107 DEFUN ("set-process-window-size", Fset_process_window_size,
1108 Sset_process_window_size, 3, 3, 0,
1109 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1110 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1112 CHECK_PROCESS (process);
1113 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1114 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1116 if (XPROCESS (process)->infd < 0
1117 || set_window_size (XPROCESS (process)->infd,
1118 XINT (height), XINT (width)) <= 0)
1119 return Qnil;
1120 else
1121 return Qt;
1124 DEFUN ("set-process-inherit-coding-system-flag",
1125 Fset_process_inherit_coding_system_flag,
1126 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1127 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1128 If the second argument FLAG is non-nil, then the variable
1129 `buffer-file-coding-system' of the buffer associated with PROCESS
1130 will be bound to the value of the coding system used to decode
1131 the process output.
1133 This is useful when the coding system specified for the process buffer
1134 leaves either the character code conversion or the end-of-line conversion
1135 unspecified, or if the coding system used to decode the process output
1136 is more appropriate for saving the process buffer.
1138 Binding the variable `inherit-process-coding-system' to non-nil before
1139 starting the process is an alternative way of setting the inherit flag
1140 for the process which will run.
1142 This function returns FLAG. */)
1143 (register Lisp_Object process, Lisp_Object flag)
1145 CHECK_PROCESS (process);
1146 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1147 return flag;
1150 DEFUN ("set-process-query-on-exit-flag",
1151 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1152 2, 2, 0,
1153 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1154 If the second argument FLAG is non-nil, Emacs will query the user before
1155 exiting or killing a buffer if PROCESS is running. This function
1156 returns FLAG. */)
1157 (register Lisp_Object process, Lisp_Object flag)
1159 CHECK_PROCESS (process);
1160 XPROCESS (process)->kill_without_query = NILP (flag);
1161 return flag;
1164 DEFUN ("process-query-on-exit-flag",
1165 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1166 1, 1, 0,
1167 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1168 (register Lisp_Object process)
1170 CHECK_PROCESS (process);
1171 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1174 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1175 1, 2, 0,
1176 doc: /* Return the contact info of PROCESS; t for a real child.
1177 For a network or serial connection, the value depends on the optional
1178 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1179 SERVICE) for a network connection or (PORT SPEED) for a serial
1180 connection. If KEY is t, the complete contact information for the
1181 connection is returned, else the specific value for the keyword KEY is
1182 returned. See `make-network-process' or `make-serial-process' for a
1183 list of keywords. */)
1184 (register Lisp_Object process, Lisp_Object key)
1186 Lisp_Object contact;
1188 CHECK_PROCESS (process);
1189 contact = XPROCESS (process)->childp;
1191 #ifdef DATAGRAM_SOCKETS
1192 if (DATAGRAM_CONN_P (process)
1193 && (EQ (key, Qt) || EQ (key, QCremote)))
1194 contact = Fplist_put (contact, QCremote,
1195 Fprocess_datagram_address (process));
1196 #endif
1198 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1199 return contact;
1200 if (NILP (key) && NETCONN_P (process))
1201 return Fcons (Fplist_get (contact, QChost),
1202 Fcons (Fplist_get (contact, QCservice), Qnil));
1203 if (NILP (key) && SERIALCONN_P (process))
1204 return Fcons (Fplist_get (contact, QCport),
1205 Fcons (Fplist_get (contact, QCspeed), Qnil));
1206 return Fplist_get (contact, key);
1209 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1210 1, 1, 0,
1211 doc: /* Return the plist of PROCESS. */)
1212 (register Lisp_Object process)
1214 CHECK_PROCESS (process);
1215 return XPROCESS (process)->plist;
1218 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1219 2, 2, 0,
1220 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1221 (register Lisp_Object process, Lisp_Object plist)
1223 CHECK_PROCESS (process);
1224 CHECK_LIST (plist);
1226 pset_plist (XPROCESS (process), plist);
1227 return plist;
1230 #if 0 /* Turned off because we don't currently record this info
1231 in the process. Perhaps add it. */
1232 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1233 doc: /* Return the connection type of PROCESS.
1234 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1235 a socket connection. */)
1236 (Lisp_Object process)
1238 return XPROCESS (process)->type;
1240 #endif
1242 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1243 doc: /* Return the connection type of PROCESS.
1244 The value is either the symbol `real', `network', or `serial'.
1245 PROCESS may be a process, a buffer, the name of a process or buffer, or
1246 nil, indicating the current buffer's process. */)
1247 (Lisp_Object process)
1249 Lisp_Object proc;
1250 proc = get_process (process);
1251 return XPROCESS (proc)->type;
1254 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1255 1, 2, 0,
1256 doc: /* Convert network ADDRESS from internal format to a string.
1257 A 4 or 5 element vector represents an IPv4 address (with port number).
1258 An 8 or 9 element vector represents an IPv6 address (with port number).
1259 If optional second argument OMIT-PORT is non-nil, don't include a port
1260 number in the string, even when present in ADDRESS.
1261 Returns nil if format of ADDRESS is invalid. */)
1262 (Lisp_Object address, Lisp_Object omit_port)
1264 if (NILP (address))
1265 return Qnil;
1267 if (STRINGP (address)) /* AF_LOCAL */
1268 return address;
1270 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1272 register struct Lisp_Vector *p = XVECTOR (address);
1273 ptrdiff_t size = p->header.size;
1274 Lisp_Object args[10];
1275 int nargs, i;
1277 if (size == 4 || (size == 5 && !NILP (omit_port)))
1279 args[0] = build_string ("%d.%d.%d.%d");
1280 nargs = 4;
1282 else if (size == 5)
1284 args[0] = build_string ("%d.%d.%d.%d:%d");
1285 nargs = 5;
1287 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1289 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1290 nargs = 8;
1292 else if (size == 9)
1294 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1295 nargs = 9;
1297 else
1298 return Qnil;
1300 for (i = 0; i < nargs; i++)
1302 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1303 return Qnil;
1305 if (nargs <= 5 /* IPv4 */
1306 && i < 4 /* host, not port */
1307 && XINT (p->contents[i]) > 255)
1308 return Qnil;
1310 args[i+1] = p->contents[i];
1313 return Fformat (nargs+1, args);
1316 if (CONSP (address))
1318 Lisp_Object args[2];
1319 args[0] = build_string ("<Family %d>");
1320 args[1] = Fcar (address);
1321 return Fformat (2, args);
1324 return Qnil;
1327 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1328 doc: /* Return a list of all processes. */)
1329 (void)
1331 return Fmapcar (Qcdr, Vprocess_alist);
1334 /* Starting asynchronous inferior processes. */
1336 static Lisp_Object start_process_unwind (Lisp_Object proc);
1338 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1339 doc: /* Start a program in a subprocess. Return the process object for it.
1340 NAME is name for process. It is modified if necessary to make it unique.
1341 BUFFER is the buffer (or buffer name) to associate with the process.
1343 Process output (both standard output and standard error streams) goes
1344 at end of BUFFER, unless you specify an output stream or filter
1345 function to handle the output. BUFFER may also be nil, meaning that
1346 this process is not associated with any buffer.
1348 PROGRAM is the program file name. It is searched for in `exec-path'
1349 (which see). If nil, just associate a pty with the buffer. Remaining
1350 arguments are strings to give program as arguments.
1352 If you want to separate standard output from standard error, invoke
1353 the command through a shell and redirect one of them using the shell
1354 syntax.
1356 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1357 (ptrdiff_t nargs, Lisp_Object *args)
1359 Lisp_Object buffer, name, program, proc, current_dir, tem;
1360 register unsigned char **new_argv;
1361 ptrdiff_t i;
1362 ptrdiff_t count = SPECPDL_INDEX ();
1364 buffer = args[1];
1365 if (!NILP (buffer))
1366 buffer = Fget_buffer_create (buffer);
1368 /* Make sure that the child will be able to chdir to the current
1369 buffer's current directory, or its unhandled equivalent. We
1370 can't just have the child check for an error when it does the
1371 chdir, since it's in a vfork.
1373 We have to GCPRO around this because Fexpand_file_name and
1374 Funhandled_file_name_directory might call a file name handling
1375 function. The argument list is protected by the caller, so all
1376 we really have to worry about is buffer. */
1378 struct gcpro gcpro1, gcpro2;
1380 current_dir = BVAR (current_buffer, directory);
1382 GCPRO2 (buffer, current_dir);
1384 current_dir = Funhandled_file_name_directory (current_dir);
1385 if (NILP (current_dir))
1386 /* If the file name handler says that current_dir is unreachable, use
1387 a sensible default. */
1388 current_dir = build_string ("~/");
1389 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1390 if (NILP (Ffile_accessible_directory_p (current_dir)))
1391 report_file_error ("Setting current directory",
1392 Fcons (BVAR (current_buffer, directory), Qnil));
1394 UNGCPRO;
1397 name = args[0];
1398 CHECK_STRING (name);
1400 program = args[2];
1402 if (!NILP (program))
1403 CHECK_STRING (program);
1405 proc = make_process (name);
1406 /* If an error occurs and we can't start the process, we want to
1407 remove it from the process list. This means that each error
1408 check in create_process doesn't need to call remove_process
1409 itself; it's all taken care of here. */
1410 record_unwind_protect (start_process_unwind, proc);
1412 pset_childp (XPROCESS (proc), Qt);
1413 pset_plist (XPROCESS (proc), Qnil);
1414 pset_type (XPROCESS (proc), Qreal);
1415 pset_buffer (XPROCESS (proc), buffer);
1416 pset_sentinel (XPROCESS (proc), Qnil);
1417 pset_filter (XPROCESS (proc), Qnil);
1418 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1420 #ifdef HAVE_GNUTLS
1421 /* AKA GNUTLS_INITSTAGE(proc). */
1422 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1423 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1424 #endif
1426 #ifdef ADAPTIVE_READ_BUFFERING
1427 XPROCESS (proc)->adaptive_read_buffering
1428 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1429 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1430 #endif
1432 /* Make the process marker point into the process buffer (if any). */
1433 if (BUFFERP (buffer))
1434 set_marker_both (XPROCESS (proc)->mark, buffer,
1435 BUF_ZV (XBUFFER (buffer)),
1436 BUF_ZV_BYTE (XBUFFER (buffer)));
1439 /* Decide coding systems for communicating with the process. Here
1440 we don't setup the structure coding_system nor pay attention to
1441 unibyte mode. They are done in create_process. */
1443 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1444 Lisp_Object coding_systems = Qt;
1445 Lisp_Object val, *args2;
1446 struct gcpro gcpro1, gcpro2;
1448 val = Vcoding_system_for_read;
1449 if (NILP (val))
1451 args2 = alloca ((nargs + 1) * sizeof *args2);
1452 args2[0] = Qstart_process;
1453 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1454 GCPRO2 (proc, current_dir);
1455 if (!NILP (program))
1456 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1457 UNGCPRO;
1458 if (CONSP (coding_systems))
1459 val = XCAR (coding_systems);
1460 else if (CONSP (Vdefault_process_coding_system))
1461 val = XCAR (Vdefault_process_coding_system);
1463 pset_decode_coding_system (XPROCESS (proc), val);
1465 val = Vcoding_system_for_write;
1466 if (NILP (val))
1468 if (EQ (coding_systems, Qt))
1470 args2 = alloca ((nargs + 1) * sizeof *args2);
1471 args2[0] = Qstart_process;
1472 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1473 GCPRO2 (proc, current_dir);
1474 if (!NILP (program))
1475 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1476 UNGCPRO;
1478 if (CONSP (coding_systems))
1479 val = XCDR (coding_systems);
1480 else if (CONSP (Vdefault_process_coding_system))
1481 val = XCDR (Vdefault_process_coding_system);
1483 pset_encode_coding_system (XPROCESS (proc), val);
1484 /* Note: At this moment, the above coding system may leave
1485 text-conversion or eol-conversion unspecified. They will be
1486 decided after we read output from the process and decode it by
1487 some coding system, or just before we actually send a text to
1488 the process. */
1492 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1493 XPROCESS (proc)->decoding_carryover = 0;
1494 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1496 XPROCESS (proc)->inherit_coding_system_flag
1497 = !(NILP (buffer) || !inherit_process_coding_system);
1499 if (!NILP (program))
1501 /* If program file name is not absolute, search our path for it.
1502 Put the name we will really use in TEM. */
1503 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1504 && !(SCHARS (program) > 1
1505 && IS_DEVICE_SEP (SREF (program, 1))))
1507 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1509 tem = Qnil;
1510 GCPRO4 (name, program, buffer, current_dir);
1511 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1512 UNGCPRO;
1513 if (NILP (tem))
1514 report_file_error ("Searching for program", Fcons (program, Qnil));
1515 tem = Fexpand_file_name (tem, Qnil);
1517 else
1519 if (!NILP (Ffile_directory_p (program)))
1520 error ("Specified program for new process is a directory");
1521 tem = program;
1524 /* If program file name starts with /: for quoting a magic name,
1525 discard that. */
1526 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1527 && SREF (tem, 1) == ':')
1528 tem = Fsubstring (tem, make_number (2), Qnil);
1531 Lisp_Object arg_encoding = Qnil;
1532 struct gcpro gcpro1;
1533 GCPRO1 (tem);
1535 /* Encode the file name and put it in NEW_ARGV.
1536 That's where the child will use it to execute the program. */
1537 tem = Fcons (ENCODE_FILE (tem), Qnil);
1539 /* Here we encode arguments by the coding system used for sending
1540 data to the process. We don't support using different coding
1541 systems for encoding arguments and for encoding data sent to the
1542 process. */
1544 for (i = 3; i < nargs; i++)
1546 tem = Fcons (args[i], tem);
1547 CHECK_STRING (XCAR (tem));
1548 if (STRING_MULTIBYTE (XCAR (tem)))
1550 if (NILP (arg_encoding))
1551 arg_encoding = (complement_process_encoding_system
1552 (XPROCESS (proc)->encode_coding_system));
1553 XSETCAR (tem,
1554 code_convert_string_norecord
1555 (XCAR (tem), arg_encoding, 1));
1559 UNGCPRO;
1562 /* Now that everything is encoded we can collect the strings into
1563 NEW_ARGV. */
1564 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1565 new_argv[nargs - 2] = 0;
1567 for (i = nargs - 2; i-- != 0; )
1569 new_argv[i] = SDATA (XCAR (tem));
1570 tem = XCDR (tem);
1573 create_process (proc, (char **) new_argv, current_dir);
1575 else
1576 create_pty (proc);
1578 return unbind_to (count, proc);
1581 /* This function is the unwind_protect form for Fstart_process. If
1582 PROC doesn't have its pid set, then we know someone has signaled
1583 an error and the process wasn't started successfully, so we should
1584 remove it from the process list. */
1585 static Lisp_Object
1586 start_process_unwind (Lisp_Object proc)
1588 if (!PROCESSP (proc))
1589 abort ();
1591 /* Was PROC started successfully?
1592 -2 is used for a pty with no process, eg for gdb. */
1593 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1594 remove_process (proc);
1596 return Qnil;
1599 static void
1600 create_process_1 (struct atimer *timer)
1602 /* Nothing to do. */
1606 static void
1607 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1609 int inchannel, outchannel;
1610 pid_t pid;
1611 int sv[2];
1612 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1613 int wait_child_setup[2];
1614 #endif
1615 sigset_t procmask;
1616 sigset_t blocked;
1617 struct sigaction sigint_action;
1618 struct sigaction sigquit_action;
1619 struct sigaction sigpipe_action;
1620 #ifdef AIX
1621 struct sigaction sighup_action;
1622 #endif
1623 /* Use volatile to protect variables from being clobbered by longjmp. */
1624 volatile int forkin, forkout;
1625 volatile int pty_flag = 0;
1626 #ifndef USE_CRT_DLL
1627 extern char **environ;
1628 #endif
1630 inchannel = outchannel = -1;
1632 #ifdef HAVE_PTYS
1633 if (!NILP (Vprocess_connection_type))
1634 outchannel = inchannel = allocate_pty ();
1636 if (inchannel >= 0)
1638 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1639 /* On most USG systems it does not work to open the pty's tty here,
1640 then close it and reopen it in the child. */
1641 #ifdef O_NOCTTY
1642 /* Don't let this terminal become our controlling terminal
1643 (in case we don't have one). */
1644 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1645 #else
1646 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1647 #endif
1648 if (forkin < 0)
1649 report_file_error ("Opening pty", Qnil);
1650 #else
1651 forkin = forkout = -1;
1652 #endif /* not USG, or USG_SUBTTY_WORKS */
1653 pty_flag = 1;
1655 else
1656 #endif /* HAVE_PTYS */
1658 int tem;
1659 tem = pipe (sv);
1660 if (tem < 0)
1661 report_file_error ("Creating pipe", Qnil);
1662 inchannel = sv[0];
1663 forkout = sv[1];
1664 tem = pipe (sv);
1665 if (tem < 0)
1667 emacs_close (inchannel);
1668 emacs_close (forkout);
1669 report_file_error ("Creating pipe", Qnil);
1671 outchannel = sv[1];
1672 forkin = sv[0];
1675 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1677 int tem;
1679 tem = pipe (wait_child_setup);
1680 if (tem < 0)
1681 report_file_error ("Creating pipe", Qnil);
1682 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1683 if (tem >= 0)
1684 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1685 if (tem < 0)
1687 emacs_close (wait_child_setup[0]);
1688 emacs_close (wait_child_setup[1]);
1689 report_file_error ("Setting file descriptor flags", Qnil);
1692 #endif
1694 #ifdef O_NONBLOCK
1695 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1696 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1697 #else
1698 #ifdef O_NDELAY
1699 fcntl (inchannel, F_SETFL, O_NDELAY);
1700 fcntl (outchannel, F_SETFL, O_NDELAY);
1701 #endif
1702 #endif
1704 /* Record this as an active process, with its channels.
1705 As a result, child_setup will close Emacs's side of the pipes. */
1706 chan_process[inchannel] = process;
1707 XPROCESS (process)->infd = inchannel;
1708 XPROCESS (process)->outfd = outchannel;
1710 /* Previously we recorded the tty descriptor used in the subprocess.
1711 It was only used for getting the foreground tty process, so now
1712 we just reopen the device (see emacs_get_tty_pgrp) as this is
1713 more portable (see USG_SUBTTY_WORKS above). */
1715 XPROCESS (process)->pty_flag = pty_flag;
1716 pset_status (XPROCESS (process), Qrun);
1718 /* Delay interrupts until we have a chance to store
1719 the new fork's pid in its process structure */
1720 sigemptyset (&blocked);
1721 #ifdef SIGCHLD
1722 sigaddset (&blocked, SIGCHLD);
1723 #endif
1724 #ifdef HAVE_WORKING_VFORK
1725 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1726 this sets the parent's signal handlers as well as the child's.
1727 So delay all interrupts whose handlers the child might munge,
1728 and record the current handlers so they can be restored later. */
1729 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1730 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1731 sigaddset (&blocked, SIGPIPE); sigaction (SIGPIPE, 0, &sigpipe_action);
1732 #ifdef AIX
1733 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1734 #endif
1735 #endif /* HAVE_WORKING_VFORK */
1736 pthread_sigmask (SIG_BLOCK, &blocked, &procmask);
1738 FD_SET (inchannel, &input_wait_mask);
1739 FD_SET (inchannel, &non_keyboard_wait_mask);
1740 if (inchannel > max_process_desc)
1741 max_process_desc = inchannel;
1743 /* Until we store the proper pid, enable sigchld_handler
1744 to recognize an unknown pid as standing for this process.
1745 It is very important not to let this `marker' value stay
1746 in the table after this function has returned; if it does
1747 it might cause call-process to hang and subsequent asynchronous
1748 processes to get their return values scrambled. */
1749 XPROCESS (process)->pid = -1;
1751 /* This must be called after the above line because it may signal an
1752 error. */
1753 setup_process_coding_systems (process);
1755 BLOCK_INPUT;
1758 /* child_setup must clobber environ on systems with true vfork.
1759 Protect it from permanent change. */
1760 char **save_environ = environ;
1761 volatile Lisp_Object encoded_current_dir = ENCODE_FILE (current_dir);
1763 #ifndef WINDOWSNT
1764 pid = vfork ();
1765 if (pid == 0)
1766 #endif /* not WINDOWSNT */
1768 int xforkin = forkin;
1769 int xforkout = forkout;
1771 #if 0 /* This was probably a mistake--it duplicates code later on,
1772 but fails to handle all the cases. */
1773 /* Make sure SIGCHLD is not blocked in the child. */
1774 sigsetmask (SIGEMPTYMASK);
1775 #endif
1777 /* Make the pty be the controlling terminal of the process. */
1778 #ifdef HAVE_PTYS
1779 /* First, disconnect its current controlling terminal. */
1780 #ifdef HAVE_SETSID
1781 /* We tried doing setsid only if pty_flag, but it caused
1782 process_set_signal to fail on SGI when using a pipe. */
1783 setsid ();
1784 /* Make the pty's terminal the controlling terminal. */
1785 if (pty_flag && xforkin >= 0)
1787 #ifdef TIOCSCTTY
1788 /* We ignore the return value
1789 because faith@cs.unc.edu says that is necessary on Linux. */
1790 ioctl (xforkin, TIOCSCTTY, 0);
1791 #endif
1793 #else /* not HAVE_SETSID */
1794 #ifdef USG
1795 /* It's very important to call setpgrp here and no time
1796 afterwards. Otherwise, we lose our controlling tty which
1797 is set when we open the pty. */
1798 setpgrp ();
1799 #endif /* USG */
1800 #endif /* not HAVE_SETSID */
1801 #if defined (LDISC1)
1802 if (pty_flag && xforkin >= 0)
1804 struct termios t;
1805 tcgetattr (xforkin, &t);
1806 t.c_lflag = LDISC1;
1807 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1808 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1810 #else
1811 #if defined (NTTYDISC) && defined (TIOCSETD)
1812 if (pty_flag && xforkin >= 0)
1814 /* Use new line discipline. */
1815 int ldisc = NTTYDISC;
1816 ioctl (xforkin, TIOCSETD, &ldisc);
1818 #endif
1819 #endif
1820 #ifdef TIOCNOTTY
1821 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1822 can do TIOCSPGRP only to the process's controlling tty. */
1823 if (pty_flag)
1825 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1826 I can't test it since I don't have 4.3. */
1827 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1828 if (j >= 0)
1830 ioctl (j, TIOCNOTTY, 0);
1831 emacs_close (j);
1833 #ifndef USG
1834 /* In order to get a controlling terminal on some versions
1835 of BSD, it is necessary to put the process in pgrp 0
1836 before it opens the terminal. */
1837 #ifdef HAVE_SETPGID
1838 setpgid (0, 0);
1839 #else
1840 setpgrp (0, 0);
1841 #endif
1842 #endif
1844 #endif /* TIOCNOTTY */
1846 #if !defined (DONT_REOPEN_PTY)
1847 /*** There is a suggestion that this ought to be a
1848 conditional on TIOCSPGRP,
1849 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1850 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1851 that system does seem to need this code, even though
1852 both HAVE_SETSID and TIOCSCTTY are defined. */
1853 /* Now close the pty (if we had it open) and reopen it.
1854 This makes the pty the controlling terminal of the subprocess. */
1855 if (pty_flag)
1858 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1859 would work? */
1860 if (xforkin >= 0)
1861 emacs_close (xforkin);
1862 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1864 if (xforkin < 0)
1866 emacs_write (1, "Couldn't open the pty terminal ", 31);
1867 emacs_write (1, pty_name, strlen (pty_name));
1868 emacs_write (1, "\n", 1);
1869 _exit (1);
1873 #endif /* not DONT_REOPEN_PTY */
1875 #ifdef SETUP_SLAVE_PTY
1876 if (pty_flag)
1878 SETUP_SLAVE_PTY;
1880 #endif /* SETUP_SLAVE_PTY */
1881 #ifdef AIX
1882 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1883 Now reenable it in the child, so it will die when we want it to. */
1884 if (pty_flag)
1885 signal (SIGHUP, SIG_DFL);
1886 #endif
1887 #endif /* HAVE_PTYS */
1889 signal (SIGINT, SIG_DFL);
1890 signal (SIGQUIT, SIG_DFL);
1891 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1892 in the child. */
1893 signal (SIGPIPE, SIG_DFL);
1895 /* Stop blocking signals in the child. */
1896 pthread_sigmask (SIG_SETMASK, &procmask, 0);
1898 if (pty_flag)
1899 child_setup_tty (xforkout);
1900 #ifdef WINDOWSNT
1901 pid = child_setup (xforkin, xforkout, xforkout,
1902 new_argv, 1, encoded_current_dir);
1903 #else /* not WINDOWSNT */
1904 #ifdef FD_CLOEXEC
1905 emacs_close (wait_child_setup[0]);
1906 #endif
1907 child_setup (xforkin, xforkout, xforkout,
1908 new_argv, 1, encoded_current_dir);
1909 #endif /* not WINDOWSNT */
1911 environ = save_environ;
1914 UNBLOCK_INPUT;
1916 /* This runs in the Emacs process. */
1917 if (pid < 0)
1919 if (forkin >= 0)
1920 emacs_close (forkin);
1921 if (forkin != forkout && forkout >= 0)
1922 emacs_close (forkout);
1924 else
1926 /* vfork succeeded. */
1927 XPROCESS (process)->pid = pid;
1929 #ifdef WINDOWSNT
1930 register_child (pid, inchannel);
1931 #endif /* WINDOWSNT */
1933 /* If the subfork execv fails, and it exits,
1934 this close hangs. I don't know why.
1935 So have an interrupt jar it loose. */
1937 struct atimer *timer;
1938 EMACS_TIME offset = make_emacs_time (1, 0);
1940 stop_polling ();
1941 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1943 if (forkin >= 0)
1944 emacs_close (forkin);
1946 cancel_atimer (timer);
1947 start_polling ();
1950 if (forkin != forkout && forkout >= 0)
1951 emacs_close (forkout);
1953 #ifdef HAVE_PTYS
1954 if (pty_flag)
1955 pset_tty_name (XPROCESS (process), build_string (pty_name));
1956 else
1957 #endif
1958 pset_tty_name (XPROCESS (process), Qnil);
1960 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1961 /* Wait for child_setup to complete in case that vfork is
1962 actually defined as fork. The descriptor wait_child_setup[1]
1963 of a pipe is closed at the child side either by close-on-exec
1964 on successful execvp or the _exit call in child_setup. */
1966 char dummy;
1968 emacs_close (wait_child_setup[1]);
1969 emacs_read (wait_child_setup[0], &dummy, 1);
1970 emacs_close (wait_child_setup[0]);
1972 #endif
1975 /* Restore the signal state whether vfork succeeded or not.
1976 (We will signal an error, below, if it failed.) */
1977 #ifdef HAVE_WORKING_VFORK
1978 /* Restore the parent's signal handlers. */
1979 sigaction (SIGINT, &sigint_action, 0);
1980 sigaction (SIGQUIT, &sigquit_action, 0);
1981 sigaction (SIGPIPE, &sigpipe_action, 0);
1982 #ifdef AIX
1983 sigaction (SIGHUP, &sighup_action, 0);
1984 #endif
1985 #endif /* HAVE_WORKING_VFORK */
1986 /* Stop blocking signals in the parent. */
1987 pthread_sigmask (SIG_SETMASK, &procmask, 0);
1989 /* Now generate the error if vfork failed. */
1990 if (pid < 0)
1991 report_file_error ("Doing vfork", Qnil);
1994 void
1995 create_pty (Lisp_Object process)
1997 int inchannel, outchannel;
1998 int pty_flag = 0;
2000 inchannel = outchannel = -1;
2002 #ifdef HAVE_PTYS
2003 if (!NILP (Vprocess_connection_type))
2004 outchannel = inchannel = allocate_pty ();
2006 if (inchannel >= 0)
2008 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2009 /* On most USG systems it does not work to open the pty's tty here,
2010 then close it and reopen it in the child. */
2011 #ifdef O_NOCTTY
2012 /* Don't let this terminal become our controlling terminal
2013 (in case we don't have one). */
2014 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2015 #else
2016 int forkout = emacs_open (pty_name, O_RDWR, 0);
2017 #endif
2018 if (forkout < 0)
2019 report_file_error ("Opening pty", Qnil);
2020 #if defined (DONT_REOPEN_PTY)
2021 /* In the case that vfork is defined as fork, the parent process
2022 (Emacs) may send some data before the child process completes
2023 tty options setup. So we setup tty before forking. */
2024 child_setup_tty (forkout);
2025 #endif /* DONT_REOPEN_PTY */
2026 #endif /* not USG, or USG_SUBTTY_WORKS */
2027 pty_flag = 1;
2029 #endif /* HAVE_PTYS */
2031 #ifdef O_NONBLOCK
2032 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2033 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2034 #else
2035 #ifdef O_NDELAY
2036 fcntl (inchannel, F_SETFL, O_NDELAY);
2037 fcntl (outchannel, F_SETFL, O_NDELAY);
2038 #endif
2039 #endif
2041 /* Record this as an active process, with its channels.
2042 As a result, child_setup will close Emacs's side of the pipes. */
2043 chan_process[inchannel] = process;
2044 XPROCESS (process)->infd = inchannel;
2045 XPROCESS (process)->outfd = outchannel;
2047 /* Previously we recorded the tty descriptor used in the subprocess.
2048 It was only used for getting the foreground tty process, so now
2049 we just reopen the device (see emacs_get_tty_pgrp) as this is
2050 more portable (see USG_SUBTTY_WORKS above). */
2052 XPROCESS (process)->pty_flag = pty_flag;
2053 pset_status (XPROCESS (process), Qrun);
2054 setup_process_coding_systems (process);
2056 FD_SET (inchannel, &input_wait_mask);
2057 FD_SET (inchannel, &non_keyboard_wait_mask);
2058 if (inchannel > max_process_desc)
2059 max_process_desc = inchannel;
2061 XPROCESS (process)->pid = -2;
2062 #ifdef HAVE_PTYS
2063 if (pty_flag)
2064 pset_tty_name (XPROCESS (process), build_string (pty_name));
2065 else
2066 #endif
2067 pset_tty_name (XPROCESS (process), Qnil);
2071 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2072 The address family of sa is not included in the result. */
2074 static Lisp_Object
2075 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2077 Lisp_Object address;
2078 int i;
2079 unsigned char *cp;
2080 register struct Lisp_Vector *p;
2082 /* Workaround for a bug in getsockname on BSD: Names bound to
2083 sockets in the UNIX domain are inaccessible; getsockname returns
2084 a zero length name. */
2085 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2086 return empty_unibyte_string;
2088 switch (sa->sa_family)
2090 case AF_INET:
2092 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2093 len = sizeof (sin->sin_addr) + 1;
2094 address = Fmake_vector (make_number (len), Qnil);
2095 p = XVECTOR (address);
2096 p->contents[--len] = make_number (ntohs (sin->sin_port));
2097 cp = (unsigned char *) &sin->sin_addr;
2098 break;
2100 #ifdef AF_INET6
2101 case AF_INET6:
2103 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2104 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2105 len = sizeof (sin6->sin6_addr)/2 + 1;
2106 address = Fmake_vector (make_number (len), Qnil);
2107 p = XVECTOR (address);
2108 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2109 for (i = 0; i < len; i++)
2110 p->contents[i] = make_number (ntohs (ip6[i]));
2111 return address;
2113 #endif
2114 #ifdef HAVE_LOCAL_SOCKETS
2115 case AF_LOCAL:
2117 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2118 for (i = 0; i < sizeof (sockun->sun_path); i++)
2119 if (sockun->sun_path[i] == 0)
2120 break;
2121 return make_unibyte_string (sockun->sun_path, i);
2123 #endif
2124 default:
2125 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2126 address = Fcons (make_number (sa->sa_family),
2127 Fmake_vector (make_number (len), Qnil));
2128 p = XVECTOR (XCDR (address));
2129 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2130 break;
2133 i = 0;
2134 while (i < len)
2135 p->contents[i++] = make_number (*cp++);
2137 return address;
2141 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2143 static int
2144 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2146 register struct Lisp_Vector *p;
2148 if (VECTORP (address))
2150 p = XVECTOR (address);
2151 if (p->header.size == 5)
2153 *familyp = AF_INET;
2154 return sizeof (struct sockaddr_in);
2156 #ifdef AF_INET6
2157 else if (p->header.size == 9)
2159 *familyp = AF_INET6;
2160 return sizeof (struct sockaddr_in6);
2162 #endif
2164 #ifdef HAVE_LOCAL_SOCKETS
2165 else if (STRINGP (address))
2167 *familyp = AF_LOCAL;
2168 return sizeof (struct sockaddr_un);
2170 #endif
2171 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2172 && VECTORP (XCDR (address)))
2174 struct sockaddr *sa;
2175 *familyp = XINT (XCAR (address));
2176 p = XVECTOR (XCDR (address));
2177 return p->header.size + sizeof (sa->sa_family);
2179 return 0;
2182 /* Convert an address object (vector or string) to an internal sockaddr.
2184 The address format has been basically validated by
2185 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2186 it could have come from user data. So if FAMILY is not valid,
2187 we return after zeroing *SA. */
2189 static void
2190 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2192 register struct Lisp_Vector *p;
2193 register unsigned char *cp = NULL;
2194 register int i;
2195 EMACS_INT hostport;
2197 memset (sa, 0, len);
2199 if (VECTORP (address))
2201 p = XVECTOR (address);
2202 if (family == AF_INET)
2204 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2205 len = sizeof (sin->sin_addr) + 1;
2206 hostport = XINT (p->contents[--len]);
2207 sin->sin_port = htons (hostport);
2208 cp = (unsigned char *)&sin->sin_addr;
2209 sa->sa_family = family;
2211 #ifdef AF_INET6
2212 else if (family == AF_INET6)
2214 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2215 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2216 len = sizeof (sin6->sin6_addr) + 1;
2217 hostport = XINT (p->contents[--len]);
2218 sin6->sin6_port = htons (hostport);
2219 for (i = 0; i < len; i++)
2220 if (INTEGERP (p->contents[i]))
2222 int j = XFASTINT (p->contents[i]) & 0xffff;
2223 ip6[i] = ntohs (j);
2225 sa->sa_family = family;
2226 return;
2228 #endif
2229 else
2230 return;
2232 else if (STRINGP (address))
2234 #ifdef HAVE_LOCAL_SOCKETS
2235 if (family == AF_LOCAL)
2237 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2238 cp = SDATA (address);
2239 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2240 sockun->sun_path[i] = *cp++;
2241 sa->sa_family = family;
2243 #endif
2244 return;
2246 else
2248 p = XVECTOR (XCDR (address));
2249 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2252 for (i = 0; i < len; i++)
2253 if (INTEGERP (p->contents[i]))
2254 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2257 #ifdef DATAGRAM_SOCKETS
2258 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2259 1, 1, 0,
2260 doc: /* Get the current datagram address associated with PROCESS. */)
2261 (Lisp_Object process)
2263 int channel;
2265 CHECK_PROCESS (process);
2267 if (!DATAGRAM_CONN_P (process))
2268 return Qnil;
2270 channel = XPROCESS (process)->infd;
2271 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2272 datagram_address[channel].len);
2275 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2276 2, 2, 0,
2277 doc: /* Set the datagram address for PROCESS to ADDRESS.
2278 Returns nil upon error setting address, ADDRESS otherwise. */)
2279 (Lisp_Object process, Lisp_Object address)
2281 int channel;
2282 int family, len;
2284 CHECK_PROCESS (process);
2286 if (!DATAGRAM_CONN_P (process))
2287 return Qnil;
2289 channel = XPROCESS (process)->infd;
2291 len = get_lisp_to_sockaddr_size (address, &family);
2292 if (datagram_address[channel].len != len)
2293 return Qnil;
2294 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2295 return address;
2297 #endif
2300 static const struct socket_options {
2301 /* The name of this option. Should be lowercase version of option
2302 name without SO_ prefix. */
2303 const char *name;
2304 /* Option level SOL_... */
2305 int optlevel;
2306 /* Option number SO_... */
2307 int optnum;
2308 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2309 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2310 } socket_options[] =
2312 #ifdef SO_BINDTODEVICE
2313 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2314 #endif
2315 #ifdef SO_BROADCAST
2316 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2317 #endif
2318 #ifdef SO_DONTROUTE
2319 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2320 #endif
2321 #ifdef SO_KEEPALIVE
2322 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2323 #endif
2324 #ifdef SO_LINGER
2325 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2326 #endif
2327 #ifdef SO_OOBINLINE
2328 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2329 #endif
2330 #ifdef SO_PRIORITY
2331 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2332 #endif
2333 #ifdef SO_REUSEADDR
2334 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2335 #endif
2336 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2339 /* Set option OPT to value VAL on socket S.
2341 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2342 Signals an error if setting a known option fails.
2345 static int
2346 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2348 char *name;
2349 const struct socket_options *sopt;
2350 int ret = 0;
2352 CHECK_SYMBOL (opt);
2354 name = SSDATA (SYMBOL_NAME (opt));
2355 for (sopt = socket_options; sopt->name; sopt++)
2356 if (strcmp (name, sopt->name) == 0)
2357 break;
2359 switch (sopt->opttype)
2361 case SOPT_BOOL:
2363 int optval;
2364 optval = NILP (val) ? 0 : 1;
2365 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2366 &optval, sizeof (optval));
2367 break;
2370 case SOPT_INT:
2372 int optval;
2373 if (TYPE_RANGED_INTEGERP (int, val))
2374 optval = XINT (val);
2375 else
2376 error ("Bad option value for %s", name);
2377 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2378 &optval, sizeof (optval));
2379 break;
2382 #ifdef SO_BINDTODEVICE
2383 case SOPT_IFNAME:
2385 char devname[IFNAMSIZ+1];
2387 /* This is broken, at least in the Linux 2.4 kernel.
2388 To unbind, the arg must be a zero integer, not the empty string.
2389 This should work on all systems. KFS. 2003-09-23. */
2390 memset (devname, 0, sizeof devname);
2391 if (STRINGP (val))
2393 char *arg = SSDATA (val);
2394 int len = min (strlen (arg), IFNAMSIZ);
2395 memcpy (devname, arg, len);
2397 else if (!NILP (val))
2398 error ("Bad option value for %s", name);
2399 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2400 devname, IFNAMSIZ);
2401 break;
2403 #endif
2405 #ifdef SO_LINGER
2406 case SOPT_LINGER:
2408 struct linger linger;
2410 linger.l_onoff = 1;
2411 linger.l_linger = 0;
2412 if (TYPE_RANGED_INTEGERP (int, val))
2413 linger.l_linger = XINT (val);
2414 else
2415 linger.l_onoff = NILP (val) ? 0 : 1;
2416 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2417 &linger, sizeof (linger));
2418 break;
2420 #endif
2422 default:
2423 return 0;
2426 if (ret < 0)
2427 report_file_error ("Cannot set network option",
2428 Fcons (opt, Fcons (val, Qnil)));
2429 return (1 << sopt->optbit);
2433 DEFUN ("set-network-process-option",
2434 Fset_network_process_option, Sset_network_process_option,
2435 3, 4, 0,
2436 doc: /* For network process PROCESS set option OPTION to value VALUE.
2437 See `make-network-process' for a list of options and values.
2438 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2439 OPTION is not a supported option, return nil instead; otherwise return t. */)
2440 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2442 int s;
2443 struct Lisp_Process *p;
2445 CHECK_PROCESS (process);
2446 p = XPROCESS (process);
2447 if (!NETCONN1_P (p))
2448 error ("Process is not a network process");
2450 s = p->infd;
2451 if (s < 0)
2452 error ("Process is not running");
2454 if (set_socket_option (s, option, value))
2456 pset_childp (p, Fplist_put (p->childp, option, value));
2457 return Qt;
2460 if (NILP (no_error))
2461 error ("Unknown or unsupported option");
2463 return Qnil;
2467 DEFUN ("serial-process-configure",
2468 Fserial_process_configure,
2469 Sserial_process_configure,
2470 0, MANY, 0,
2471 doc: /* Configure speed, bytesize, etc. of a serial process.
2473 Arguments are specified as keyword/argument pairs. Attributes that
2474 are not given are re-initialized from the process's current
2475 configuration (available via the function `process-contact') or set to
2476 reasonable default values. The following arguments are defined:
2478 :process PROCESS
2479 :name NAME
2480 :buffer BUFFER
2481 :port PORT
2482 -- Any of these arguments can be given to identify the process that is
2483 to be configured. If none of these arguments is given, the current
2484 buffer's process is used.
2486 :speed SPEED -- SPEED is the speed of the serial port in bits per
2487 second, also called baud rate. Any value can be given for SPEED, but
2488 most serial ports work only at a few defined values between 1200 and
2489 115200, with 9600 being the most common value. If SPEED is nil, the
2490 serial port is not configured any further, i.e., all other arguments
2491 are ignored. This may be useful for special serial ports such as
2492 Bluetooth-to-serial converters which can only be configured through AT
2493 commands. A value of nil for SPEED can be used only when passed
2494 through `make-serial-process' or `serial-term'.
2496 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2497 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2499 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2500 `odd' (use odd parity), or the symbol `even' (use even parity). If
2501 PARITY is not given, no parity is used.
2503 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2504 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2505 is not given or nil, 1 stopbit is used.
2507 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2508 flowcontrol to be used, which is either nil (don't use flowcontrol),
2509 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2510 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2511 flowcontrol is used.
2513 `serial-process-configure' is called by `make-serial-process' for the
2514 initial configuration of the serial port.
2516 Examples:
2518 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2520 \(serial-process-configure
2521 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2523 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2525 usage: (serial-process-configure &rest ARGS) */)
2526 (ptrdiff_t nargs, Lisp_Object *args)
2528 struct Lisp_Process *p;
2529 Lisp_Object contact = Qnil;
2530 Lisp_Object proc = Qnil;
2531 struct gcpro gcpro1;
2533 contact = Flist (nargs, args);
2534 GCPRO1 (contact);
2536 proc = Fplist_get (contact, QCprocess);
2537 if (NILP (proc))
2538 proc = Fplist_get (contact, QCname);
2539 if (NILP (proc))
2540 proc = Fplist_get (contact, QCbuffer);
2541 if (NILP (proc))
2542 proc = Fplist_get (contact, QCport);
2543 proc = get_process (proc);
2544 p = XPROCESS (proc);
2545 if (!EQ (p->type, Qserial))
2546 error ("Not a serial process");
2548 if (NILP (Fplist_get (p->childp, QCspeed)))
2550 UNGCPRO;
2551 return Qnil;
2554 serial_configure (p, contact);
2556 UNGCPRO;
2557 return Qnil;
2560 /* Used by make-serial-process to recover from errors. */
2561 static Lisp_Object
2562 make_serial_process_unwind (Lisp_Object proc)
2564 if (!PROCESSP (proc))
2565 abort ();
2566 remove_process (proc);
2567 return Qnil;
2570 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2571 0, MANY, 0,
2572 doc: /* Create and return a serial port process.
2574 In Emacs, serial port connections are represented by process objects,
2575 so input and output work as for subprocesses, and `delete-process'
2576 closes a serial port connection. However, a serial process has no
2577 process id, it cannot be signaled, and the status codes are different
2578 from normal processes.
2580 `make-serial-process' creates a process and a buffer, on which you
2581 probably want to use `process-send-string'. Try \\[serial-term] for
2582 an interactive terminal. See below for examples.
2584 Arguments are specified as keyword/argument pairs. The following
2585 arguments are defined:
2587 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2588 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2589 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2590 the backslashes in strings).
2592 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2593 which this function calls.
2595 :name NAME -- NAME is the name of the process. If NAME is not given,
2596 the value of PORT is used.
2598 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2599 with the process. Process output goes at the end of that buffer,
2600 unless you specify an output stream or filter function to handle the
2601 output. If BUFFER is not given, the value of NAME is used.
2603 :coding CODING -- If CODING is a symbol, it specifies the coding
2604 system used for both reading and writing for this process. If CODING
2605 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2606 ENCODING is used for writing.
2608 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2609 the process is running. If BOOL is not given, query before exiting.
2611 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2612 In the stopped state, a serial process does not accept incoming data,
2613 but you can send outgoing data. The stopped state is cleared by
2614 `continue-process' and set by `stop-process'.
2616 :filter FILTER -- Install FILTER as the process filter.
2618 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2620 :plist PLIST -- Install PLIST as the initial plist of the process.
2622 :bytesize
2623 :parity
2624 :stopbits
2625 :flowcontrol
2626 -- This function calls `serial-process-configure' to handle these
2627 arguments.
2629 The original argument list, possibly modified by later configuration,
2630 is available via the function `process-contact'.
2632 Examples:
2634 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2636 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2638 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2640 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2642 usage: (make-serial-process &rest ARGS) */)
2643 (ptrdiff_t nargs, Lisp_Object *args)
2645 int fd = -1;
2646 Lisp_Object proc, contact, port;
2647 struct Lisp_Process *p;
2648 struct gcpro gcpro1;
2649 Lisp_Object name, buffer;
2650 Lisp_Object tem, val;
2651 ptrdiff_t specpdl_count = -1;
2653 if (nargs == 0)
2654 return Qnil;
2656 contact = Flist (nargs, args);
2657 GCPRO1 (contact);
2659 port = Fplist_get (contact, QCport);
2660 if (NILP (port))
2661 error ("No port specified");
2662 CHECK_STRING (port);
2664 if (NILP (Fplist_member (contact, QCspeed)))
2665 error (":speed not specified");
2666 if (!NILP (Fplist_get (contact, QCspeed)))
2667 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2669 name = Fplist_get (contact, QCname);
2670 if (NILP (name))
2671 name = port;
2672 CHECK_STRING (name);
2673 proc = make_process (name);
2674 specpdl_count = SPECPDL_INDEX ();
2675 record_unwind_protect (make_serial_process_unwind, proc);
2676 p = XPROCESS (proc);
2678 fd = serial_open (SSDATA (port));
2679 p->infd = fd;
2680 p->outfd = fd;
2681 if (fd > max_process_desc)
2682 max_process_desc = fd;
2683 chan_process[fd] = proc;
2685 buffer = Fplist_get (contact, QCbuffer);
2686 if (NILP (buffer))
2687 buffer = name;
2688 buffer = Fget_buffer_create (buffer);
2689 pset_buffer (p, buffer);
2691 pset_childp (p, contact);
2692 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2693 pset_type (p, Qserial);
2694 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2695 pset_filter (p, Fplist_get (contact, QCfilter));
2696 pset_log (p, Qnil);
2697 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2698 p->kill_without_query = 1;
2699 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2700 pset_command (p, Qt);
2701 p->pty_flag = 0;
2703 if (!EQ (p->command, Qt))
2705 FD_SET (fd, &input_wait_mask);
2706 FD_SET (fd, &non_keyboard_wait_mask);
2709 if (BUFFERP (buffer))
2711 set_marker_both (p->mark, buffer,
2712 BUF_ZV (XBUFFER (buffer)),
2713 BUF_ZV_BYTE (XBUFFER (buffer)));
2716 tem = Fplist_member (contact, QCcoding);
2717 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2718 tem = Qnil;
2720 val = Qnil;
2721 if (!NILP (tem))
2723 val = XCAR (XCDR (tem));
2724 if (CONSP (val))
2725 val = XCAR (val);
2727 else if (!NILP (Vcoding_system_for_read))
2728 val = Vcoding_system_for_read;
2729 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2730 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2731 val = Qnil;
2732 pset_decode_coding_system (p, val);
2734 val = Qnil;
2735 if (!NILP (tem))
2737 val = XCAR (XCDR (tem));
2738 if (CONSP (val))
2739 val = XCDR (val);
2741 else if (!NILP (Vcoding_system_for_write))
2742 val = Vcoding_system_for_write;
2743 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2744 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2745 val = Qnil;
2746 pset_encode_coding_system (p, val);
2748 setup_process_coding_systems (proc);
2749 pset_decoding_buf (p, empty_unibyte_string);
2750 p->decoding_carryover = 0;
2751 pset_encoding_buf (p, empty_unibyte_string);
2752 p->inherit_coding_system_flag
2753 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2755 Fserial_process_configure (nargs, args);
2757 specpdl_ptr = specpdl + specpdl_count;
2759 UNGCPRO;
2760 return proc;
2763 /* Create a network stream/datagram client/server process. Treated
2764 exactly like a normal process when reading and writing. Primary
2765 differences are in status display and process deletion. A network
2766 connection has no PID; you cannot signal it. All you can do is
2767 stop/continue it and deactivate/close it via delete-process */
2769 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2770 0, MANY, 0,
2771 doc: /* Create and return a network server or client process.
2773 In Emacs, network connections are represented by process objects, so
2774 input and output work as for subprocesses and `delete-process' closes
2775 a network connection. However, a network process has no process id,
2776 it cannot be signaled, and the status codes are different from normal
2777 processes.
2779 Arguments are specified as keyword/argument pairs. The following
2780 arguments are defined:
2782 :name NAME -- NAME is name for process. It is modified if necessary
2783 to make it unique.
2785 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2786 with the process. Process output goes at end of that buffer, unless
2787 you specify an output stream or filter function to handle the output.
2788 BUFFER may be also nil, meaning that this process is not associated
2789 with any buffer.
2791 :host HOST -- HOST is name of the host to connect to, or its IP
2792 address. The symbol `local' specifies the local host. If specified
2793 for a server process, it must be a valid name or address for the local
2794 host, and only clients connecting to that address will be accepted.
2796 :service SERVICE -- SERVICE is name of the service desired, or an
2797 integer specifying a port number to connect to. If SERVICE is t,
2798 a random port number is selected for the server. (If Emacs was
2799 compiled with getaddrinfo, a port number can also be specified as a
2800 string, e.g. "80", as well as an integer. This is not portable.)
2802 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2803 stream type connection, `datagram' creates a datagram type connection,
2804 `seqpacket' creates a reliable datagram connection.
2806 :family FAMILY -- FAMILY is the address (and protocol) family for the
2807 service specified by HOST and SERVICE. The default (nil) is to use
2808 whatever address family (IPv4 or IPv6) that is defined for the host
2809 and port number specified by HOST and SERVICE. Other address families
2810 supported are:
2811 local -- for a local (i.e. UNIX) address specified by SERVICE.
2812 ipv4 -- use IPv4 address family only.
2813 ipv6 -- use IPv6 address family only.
2815 :local ADDRESS -- ADDRESS is the local address used for the connection.
2816 This parameter is ignored when opening a client process. When specified
2817 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2819 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2820 connection. This parameter is ignored when opening a stream server
2821 process. For a datagram server process, it specifies the initial
2822 setting of the remote datagram address. When specified for a client
2823 process, the FAMILY, HOST, and SERVICE args are ignored.
2825 The format of ADDRESS depends on the address family:
2826 - An IPv4 address is represented as an vector of integers [A B C D P]
2827 corresponding to numeric IP address A.B.C.D and port number P.
2828 - A local address is represented as a string with the address in the
2829 local address space.
2830 - An "unsupported family" address is represented by a cons (F . AV)
2831 where F is the family number and AV is a vector containing the socket
2832 address data with one element per address data byte. Do not rely on
2833 this format in portable code, as it may depend on implementation
2834 defined constants, data sizes, and data structure alignment.
2836 :coding CODING -- If CODING is a symbol, it specifies the coding
2837 system used for both reading and writing for this process. If CODING
2838 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2839 ENCODING is used for writing.
2841 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2842 return without waiting for the connection to complete; instead, the
2843 sentinel function will be called with second arg matching "open" (if
2844 successful) or "failed" when the connect completes. Default is to use
2845 a blocking connect (i.e. wait) for stream type connections.
2847 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2848 running when Emacs is exited.
2850 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2851 In the stopped state, a server process does not accept new
2852 connections, and a client process does not handle incoming traffic.
2853 The stopped state is cleared by `continue-process' and set by
2854 `stop-process'.
2856 :filter FILTER -- Install FILTER as the process filter.
2858 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2859 process filter are multibyte, otherwise they are unibyte.
2860 If this keyword is not specified, the strings are multibyte if
2861 the default value of `enable-multibyte-characters' is non-nil.
2863 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2865 :log LOG -- Install LOG as the server process log function. This
2866 function is called when the server accepts a network connection from a
2867 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2868 is the server process, CLIENT is the new process for the connection,
2869 and MESSAGE is a string.
2871 :plist PLIST -- Install PLIST as the new process' initial plist.
2873 :server QLEN -- if QLEN is non-nil, create a server process for the
2874 specified FAMILY, SERVICE, and connection type (stream or datagram).
2875 If QLEN is an integer, it is used as the max. length of the server's
2876 pending connection queue (also known as the backlog); the default
2877 queue length is 5. Default is to create a client process.
2879 The following network options can be specified for this connection:
2881 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2882 :dontroute BOOL -- Only send to directly connected hosts.
2883 :keepalive BOOL -- Send keep-alive messages on network stream.
2884 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2885 :oobinline BOOL -- Place out-of-band data in receive data stream.
2886 :priority INT -- Set protocol defined priority for sent packets.
2887 :reuseaddr BOOL -- Allow reusing a recently used local address
2888 (this is allowed by default for a server process).
2889 :bindtodevice NAME -- bind to interface NAME. Using this may require
2890 special privileges on some systems.
2892 Consult the relevant system programmer's manual pages for more
2893 information on using these options.
2896 A server process will listen for and accept connections from clients.
2897 When a client connection is accepted, a new network process is created
2898 for the connection with the following parameters:
2900 - The client's process name is constructed by concatenating the server
2901 process' NAME and a client identification string.
2902 - If the FILTER argument is non-nil, the client process will not get a
2903 separate process buffer; otherwise, the client's process buffer is a newly
2904 created buffer named after the server process' BUFFER name or process
2905 NAME concatenated with the client identification string.
2906 - The connection type and the process filter and sentinel parameters are
2907 inherited from the server process' TYPE, FILTER and SENTINEL.
2908 - The client process' contact info is set according to the client's
2909 addressing information (typically an IP address and a port number).
2910 - The client process' plist is initialized from the server's plist.
2912 Notice that the FILTER and SENTINEL args are never used directly by
2913 the server process. Also, the BUFFER argument is not used directly by
2914 the server process, but via the optional :log function, accepted (and
2915 failed) connections may be logged in the server process' buffer.
2917 The original argument list, modified with the actual connection
2918 information, is available via the `process-contact' function.
2920 usage: (make-network-process &rest ARGS) */)
2921 (ptrdiff_t nargs, Lisp_Object *args)
2923 Lisp_Object proc;
2924 Lisp_Object contact;
2925 struct Lisp_Process *p;
2926 #ifdef HAVE_GETADDRINFO
2927 struct addrinfo ai, *res, *lres;
2928 struct addrinfo hints;
2929 const char *portstring;
2930 char portbuf[128];
2931 #else /* HAVE_GETADDRINFO */
2932 struct _emacs_addrinfo
2934 int ai_family;
2935 int ai_socktype;
2936 int ai_protocol;
2937 int ai_addrlen;
2938 struct sockaddr *ai_addr;
2939 struct _emacs_addrinfo *ai_next;
2940 } ai, *res, *lres;
2941 #endif /* HAVE_GETADDRINFO */
2942 struct sockaddr_in address_in;
2943 #ifdef HAVE_LOCAL_SOCKETS
2944 struct sockaddr_un address_un;
2945 #endif
2946 int port;
2947 int ret = 0;
2948 int xerrno = 0;
2949 int s = -1, outch, inch;
2950 struct gcpro gcpro1;
2951 ptrdiff_t count = SPECPDL_INDEX ();
2952 ptrdiff_t count1;
2953 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2954 Lisp_Object tem;
2955 Lisp_Object name, buffer, host, service, address;
2956 Lisp_Object filter, sentinel;
2957 int is_non_blocking_client = 0;
2958 int is_server = 0, backlog = 5;
2959 int socktype;
2960 int family = -1;
2962 if (nargs == 0)
2963 return Qnil;
2965 /* Save arguments for process-contact and clone-process. */
2966 contact = Flist (nargs, args);
2967 GCPRO1 (contact);
2969 #ifdef WINDOWSNT
2970 /* Ensure socket support is loaded if available. */
2971 init_winsock (TRUE);
2972 #endif
2974 /* :type TYPE (nil: stream, datagram */
2975 tem = Fplist_get (contact, QCtype);
2976 if (NILP (tem))
2977 socktype = SOCK_STREAM;
2978 #ifdef DATAGRAM_SOCKETS
2979 else if (EQ (tem, Qdatagram))
2980 socktype = SOCK_DGRAM;
2981 #endif
2982 #ifdef HAVE_SEQPACKET
2983 else if (EQ (tem, Qseqpacket))
2984 socktype = SOCK_SEQPACKET;
2985 #endif
2986 else
2987 error ("Unsupported connection type");
2989 /* :server BOOL */
2990 tem = Fplist_get (contact, QCserver);
2991 if (!NILP (tem))
2993 /* Don't support network sockets when non-blocking mode is
2994 not available, since a blocked Emacs is not useful. */
2995 #if !defined (O_NONBLOCK) && !defined (O_NDELAY)
2996 error ("Network servers not supported");
2997 #else
2998 is_server = 1;
2999 if (TYPE_RANGED_INTEGERP (int, tem))
3000 backlog = XINT (tem);
3001 #endif
3004 /* Make QCaddress an alias for :local (server) or :remote (client). */
3005 QCaddress = is_server ? QClocal : QCremote;
3007 /* :nowait BOOL */
3008 if (!is_server && socktype != SOCK_DGRAM
3009 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3011 #ifndef NON_BLOCKING_CONNECT
3012 error ("Non-blocking connect not supported");
3013 #else
3014 is_non_blocking_client = 1;
3015 #endif
3018 name = Fplist_get (contact, QCname);
3019 buffer = Fplist_get (contact, QCbuffer);
3020 filter = Fplist_get (contact, QCfilter);
3021 sentinel = Fplist_get (contact, QCsentinel);
3023 CHECK_STRING (name);
3025 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3026 ai.ai_socktype = socktype;
3027 ai.ai_protocol = 0;
3028 ai.ai_next = NULL;
3029 res = &ai;
3031 /* :local ADDRESS or :remote ADDRESS */
3032 address = Fplist_get (contact, QCaddress);
3033 if (!NILP (address))
3035 host = service = Qnil;
3037 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3038 error ("Malformed :address");
3039 ai.ai_family = family;
3040 ai.ai_addr = alloca (ai.ai_addrlen);
3041 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3042 goto open_socket;
3045 /* :family FAMILY -- nil (for Inet), local, or integer. */
3046 tem = Fplist_get (contact, QCfamily);
3047 if (NILP (tem))
3049 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3050 family = AF_UNSPEC;
3051 #else
3052 family = AF_INET;
3053 #endif
3055 #ifdef HAVE_LOCAL_SOCKETS
3056 else if (EQ (tem, Qlocal))
3057 family = AF_LOCAL;
3058 #endif
3059 #ifdef AF_INET6
3060 else if (EQ (tem, Qipv6))
3061 family = AF_INET6;
3062 #endif
3063 else if (EQ (tem, Qipv4))
3064 family = AF_INET;
3065 else if (TYPE_RANGED_INTEGERP (int, tem))
3066 family = XINT (tem);
3067 else
3068 error ("Unknown address family");
3070 ai.ai_family = family;
3072 /* :service SERVICE -- string, integer (port number), or t (random port). */
3073 service = Fplist_get (contact, QCservice);
3075 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3076 host = Fplist_get (contact, QChost);
3077 if (!NILP (host))
3079 if (EQ (host, Qlocal))
3080 /* Depending on setup, "localhost" may map to different IPv4 and/or
3081 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3082 host = build_string ("127.0.0.1");
3083 CHECK_STRING (host);
3086 #ifdef HAVE_LOCAL_SOCKETS
3087 if (family == AF_LOCAL)
3089 if (!NILP (host))
3091 message (":family local ignores the :host \"%s\" property",
3092 SDATA (host));
3093 contact = Fplist_put (contact, QChost, Qnil);
3094 host = Qnil;
3096 CHECK_STRING (service);
3097 memset (&address_un, 0, sizeof address_un);
3098 address_un.sun_family = AF_LOCAL;
3099 if (sizeof address_un.sun_path <= SBYTES (service))
3100 error ("Service name too long");
3101 strcpy (address_un.sun_path, SSDATA (service));
3102 ai.ai_addr = (struct sockaddr *) &address_un;
3103 ai.ai_addrlen = sizeof address_un;
3104 goto open_socket;
3106 #endif
3108 /* Slow down polling to every ten seconds.
3109 Some kernels have a bug which causes retrying connect to fail
3110 after a connect. Polling can interfere with gethostbyname too. */
3111 #ifdef POLL_FOR_INPUT
3112 if (socktype != SOCK_DGRAM)
3114 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3115 bind_polling_period (10);
3117 #endif
3119 #ifdef HAVE_GETADDRINFO
3120 /* If we have a host, use getaddrinfo to resolve both host and service.
3121 Otherwise, use getservbyname to lookup the service. */
3122 if (!NILP (host))
3125 /* SERVICE can either be a string or int.
3126 Convert to a C string for later use by getaddrinfo. */
3127 if (EQ (service, Qt))
3128 portstring = "0";
3129 else if (INTEGERP (service))
3131 sprintf (portbuf, "%"pI"d", XINT (service));
3132 portstring = portbuf;
3134 else
3136 CHECK_STRING (service);
3137 portstring = SSDATA (service);
3140 immediate_quit = 1;
3141 QUIT;
3142 memset (&hints, 0, sizeof (hints));
3143 hints.ai_flags = 0;
3144 hints.ai_family = family;
3145 hints.ai_socktype = socktype;
3146 hints.ai_protocol = 0;
3148 #ifdef HAVE_RES_INIT
3149 res_init ();
3150 #endif
3152 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3153 if (ret)
3154 #ifdef HAVE_GAI_STRERROR
3155 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3156 #else
3157 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3158 #endif
3159 immediate_quit = 0;
3161 goto open_socket;
3163 #endif /* HAVE_GETADDRINFO */
3165 /* We end up here if getaddrinfo is not defined, or in case no hostname
3166 has been specified (e.g. for a local server process). */
3168 if (EQ (service, Qt))
3169 port = 0;
3170 else if (INTEGERP (service))
3171 port = htons ((unsigned short) XINT (service));
3172 else
3174 struct servent *svc_info;
3175 CHECK_STRING (service);
3176 svc_info = getservbyname (SSDATA (service),
3177 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3178 if (svc_info == 0)
3179 error ("Unknown service: %s", SDATA (service));
3180 port = svc_info->s_port;
3183 memset (&address_in, 0, sizeof address_in);
3184 address_in.sin_family = family;
3185 address_in.sin_addr.s_addr = INADDR_ANY;
3186 address_in.sin_port = port;
3188 #ifndef HAVE_GETADDRINFO
3189 if (!NILP (host))
3191 struct hostent *host_info_ptr;
3193 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3194 as it may `hang' Emacs for a very long time. */
3195 immediate_quit = 1;
3196 QUIT;
3198 #ifdef HAVE_RES_INIT
3199 res_init ();
3200 #endif
3202 host_info_ptr = gethostbyname (SDATA (host));
3203 immediate_quit = 0;
3205 if (host_info_ptr)
3207 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3208 host_info_ptr->h_length);
3209 family = host_info_ptr->h_addrtype;
3210 address_in.sin_family = family;
3212 else
3213 /* Attempt to interpret host as numeric inet address */
3215 unsigned long numeric_addr;
3216 numeric_addr = inet_addr (SSDATA (host));
3217 if (numeric_addr == -1)
3218 error ("Unknown host \"%s\"", SDATA (host));
3220 memcpy (&address_in.sin_addr, &numeric_addr,
3221 sizeof (address_in.sin_addr));
3225 #endif /* not HAVE_GETADDRINFO */
3227 ai.ai_family = family;
3228 ai.ai_addr = (struct sockaddr *) &address_in;
3229 ai.ai_addrlen = sizeof address_in;
3231 open_socket:
3233 /* Do this in case we never enter the for-loop below. */
3234 count1 = SPECPDL_INDEX ();
3235 s = -1;
3237 for (lres = res; lres; lres = lres->ai_next)
3239 ptrdiff_t optn;
3240 int optbits;
3242 #ifdef WINDOWSNT
3243 retry_connect:
3244 #endif
3246 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3247 if (s < 0)
3249 xerrno = errno;
3250 continue;
3253 #ifdef DATAGRAM_SOCKETS
3254 if (!is_server && socktype == SOCK_DGRAM)
3255 break;
3256 #endif /* DATAGRAM_SOCKETS */
3258 #ifdef NON_BLOCKING_CONNECT
3259 if (is_non_blocking_client)
3261 #ifdef O_NONBLOCK
3262 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3263 #else
3264 ret = fcntl (s, F_SETFL, O_NDELAY);
3265 #endif
3266 if (ret < 0)
3268 xerrno = errno;
3269 emacs_close (s);
3270 s = -1;
3271 continue;
3274 #endif
3276 /* Make us close S if quit. */
3277 record_unwind_protect (close_file_unwind, make_number (s));
3279 /* Parse network options in the arg list.
3280 We simply ignore anything which isn't a known option (including other keywords).
3281 An error is signaled if setting a known option fails. */
3282 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3283 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3285 if (is_server)
3287 /* Configure as a server socket. */
3289 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3290 explicit :reuseaddr key to override this. */
3291 #ifdef HAVE_LOCAL_SOCKETS
3292 if (family != AF_LOCAL)
3293 #endif
3294 if (!(optbits & (1 << OPIX_REUSEADDR)))
3296 int optval = 1;
3297 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3298 report_file_error ("Cannot set reuse option on server socket", Qnil);
3301 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3302 report_file_error ("Cannot bind server socket", Qnil);
3304 #ifdef HAVE_GETSOCKNAME
3305 if (EQ (service, Qt))
3307 struct sockaddr_in sa1;
3308 socklen_t len1 = sizeof (sa1);
3309 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3311 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3312 service = make_number (ntohs (sa1.sin_port));
3313 contact = Fplist_put (contact, QCservice, service);
3316 #endif
3318 if (socktype != SOCK_DGRAM && listen (s, backlog))
3319 report_file_error ("Cannot listen on server socket", Qnil);
3321 break;
3324 immediate_quit = 1;
3325 QUIT;
3327 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3328 xerrno = errno;
3330 if (ret == 0 || xerrno == EISCONN)
3332 /* The unwind-protect will be discarded afterwards.
3333 Likewise for immediate_quit. */
3334 break;
3337 #ifdef NON_BLOCKING_CONNECT
3338 #ifdef EINPROGRESS
3339 if (is_non_blocking_client && xerrno == EINPROGRESS)
3340 break;
3341 #else
3342 #ifdef EWOULDBLOCK
3343 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3344 break;
3345 #endif
3346 #endif
3347 #endif
3349 #ifndef WINDOWSNT
3350 if (xerrno == EINTR)
3352 /* Unlike most other syscalls connect() cannot be called
3353 again. (That would return EALREADY.) The proper way to
3354 wait for completion is pselect(). */
3355 int sc;
3356 socklen_t len;
3357 SELECT_TYPE fdset;
3358 retry_select:
3359 FD_ZERO (&fdset);
3360 FD_SET (s, &fdset);
3361 QUIT;
3362 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3363 if (sc == -1)
3365 if (errno == EINTR)
3366 goto retry_select;
3367 else
3368 report_file_error ("select failed", Qnil);
3370 eassert (sc > 0);
3372 len = sizeof xerrno;
3373 eassert (FD_ISSET (s, &fdset));
3374 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3375 report_file_error ("getsockopt failed", Qnil);
3376 if (xerrno)
3377 errno = xerrno, report_file_error ("error during connect", Qnil);
3378 else
3379 break;
3381 #endif /* !WINDOWSNT */
3383 immediate_quit = 0;
3385 /* Discard the unwind protect closing S. */
3386 specpdl_ptr = specpdl + count1;
3387 emacs_close (s);
3388 s = -1;
3390 #ifdef WINDOWSNT
3391 if (xerrno == EINTR)
3392 goto retry_connect;
3393 #endif
3396 if (s >= 0)
3398 #ifdef DATAGRAM_SOCKETS
3399 if (socktype == SOCK_DGRAM)
3401 if (datagram_address[s].sa)
3402 abort ();
3403 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3404 datagram_address[s].len = lres->ai_addrlen;
3405 if (is_server)
3407 Lisp_Object remote;
3408 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3409 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3411 int rfamily, rlen;
3412 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3413 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3414 conv_lisp_to_sockaddr (rfamily, remote,
3415 datagram_address[s].sa, rlen);
3418 else
3419 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3421 #endif
3422 contact = Fplist_put (contact, QCaddress,
3423 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3424 #ifdef HAVE_GETSOCKNAME
3425 if (!is_server)
3427 struct sockaddr_in sa1;
3428 socklen_t len1 = sizeof (sa1);
3429 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3430 contact = Fplist_put (contact, QClocal,
3431 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3433 #endif
3436 immediate_quit = 0;
3438 #ifdef HAVE_GETADDRINFO
3439 if (res != &ai)
3441 BLOCK_INPUT;
3442 freeaddrinfo (res);
3443 UNBLOCK_INPUT;
3445 #endif
3447 /* Discard the unwind protect for closing S, if any. */
3448 specpdl_ptr = specpdl + count1;
3450 /* Unwind bind_polling_period and request_sigio. */
3451 unbind_to (count, Qnil);
3453 if (s < 0)
3455 /* If non-blocking got this far - and failed - assume non-blocking is
3456 not supported after all. This is probably a wrong assumption, but
3457 the normal blocking calls to open-network-stream handles this error
3458 better. */
3459 if (is_non_blocking_client)
3460 return Qnil;
3462 errno = xerrno;
3463 if (is_server)
3464 report_file_error ("make server process failed", contact);
3465 else
3466 report_file_error ("make client process failed", contact);
3469 inch = s;
3470 outch = s;
3472 if (!NILP (buffer))
3473 buffer = Fget_buffer_create (buffer);
3474 proc = make_process (name);
3476 chan_process[inch] = proc;
3478 #ifdef O_NONBLOCK
3479 fcntl (inch, F_SETFL, O_NONBLOCK);
3480 #else
3481 #ifdef O_NDELAY
3482 fcntl (inch, F_SETFL, O_NDELAY);
3483 #endif
3484 #endif
3486 p = XPROCESS (proc);
3488 pset_childp (p, contact);
3489 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3490 pset_type (p, Qnetwork);
3492 pset_buffer (p, buffer);
3493 pset_sentinel (p, sentinel);
3494 pset_filter (p, filter);
3495 pset_log (p, Fplist_get (contact, QClog));
3496 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3497 p->kill_without_query = 1;
3498 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3499 pset_command (p, Qt);
3500 p->pid = 0;
3501 p->infd = inch;
3502 p->outfd = outch;
3503 if (is_server && socktype != SOCK_DGRAM)
3504 pset_status (p, Qlisten);
3506 /* Make the process marker point into the process buffer (if any). */
3507 if (BUFFERP (buffer))
3508 set_marker_both (p->mark, buffer,
3509 BUF_ZV (XBUFFER (buffer)),
3510 BUF_ZV_BYTE (XBUFFER (buffer)));
3512 #ifdef NON_BLOCKING_CONNECT
3513 if (is_non_blocking_client)
3515 /* We may get here if connect did succeed immediately. However,
3516 in that case, we still need to signal this like a non-blocking
3517 connection. */
3518 pset_status (p, Qconnect);
3519 if (!FD_ISSET (inch, &connect_wait_mask))
3521 FD_SET (inch, &connect_wait_mask);
3522 FD_SET (inch, &write_mask);
3523 num_pending_connects++;
3526 else
3527 #endif
3528 /* A server may have a client filter setting of Qt, but it must
3529 still listen for incoming connects unless it is stopped. */
3530 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3531 || (EQ (p->status, Qlisten) && NILP (p->command)))
3533 FD_SET (inch, &input_wait_mask);
3534 FD_SET (inch, &non_keyboard_wait_mask);
3537 if (inch > max_process_desc)
3538 max_process_desc = inch;
3540 tem = Fplist_member (contact, QCcoding);
3541 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3542 tem = Qnil; /* No error message (too late!). */
3545 /* Setup coding systems for communicating with the network stream. */
3546 struct gcpro gcpro1;
3547 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3548 Lisp_Object coding_systems = Qt;
3549 Lisp_Object fargs[5], val;
3551 if (!NILP (tem))
3553 val = XCAR (XCDR (tem));
3554 if (CONSP (val))
3555 val = XCAR (val);
3557 else if (!NILP (Vcoding_system_for_read))
3558 val = Vcoding_system_for_read;
3559 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3560 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3561 /* We dare not decode end-of-line format by setting VAL to
3562 Qraw_text, because the existing Emacs Lisp libraries
3563 assume that they receive bare code including a sequence of
3564 CR LF. */
3565 val = Qnil;
3566 else
3568 if (NILP (host) || NILP (service))
3569 coding_systems = Qnil;
3570 else
3572 fargs[0] = Qopen_network_stream, fargs[1] = name,
3573 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3574 GCPRO1 (proc);
3575 coding_systems = Ffind_operation_coding_system (5, fargs);
3576 UNGCPRO;
3578 if (CONSP (coding_systems))
3579 val = XCAR (coding_systems);
3580 else if (CONSP (Vdefault_process_coding_system))
3581 val = XCAR (Vdefault_process_coding_system);
3582 else
3583 val = Qnil;
3585 pset_decode_coding_system (p, val);
3587 if (!NILP (tem))
3589 val = XCAR (XCDR (tem));
3590 if (CONSP (val))
3591 val = XCDR (val);
3593 else if (!NILP (Vcoding_system_for_write))
3594 val = Vcoding_system_for_write;
3595 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3596 val = Qnil;
3597 else
3599 if (EQ (coding_systems, Qt))
3601 if (NILP (host) || NILP (service))
3602 coding_systems = Qnil;
3603 else
3605 fargs[0] = Qopen_network_stream, fargs[1] = name,
3606 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3607 GCPRO1 (proc);
3608 coding_systems = Ffind_operation_coding_system (5, fargs);
3609 UNGCPRO;
3612 if (CONSP (coding_systems))
3613 val = XCDR (coding_systems);
3614 else if (CONSP (Vdefault_process_coding_system))
3615 val = XCDR (Vdefault_process_coding_system);
3616 else
3617 val = Qnil;
3619 pset_encode_coding_system (p, val);
3621 setup_process_coding_systems (proc);
3623 pset_decoding_buf (p, empty_unibyte_string);
3624 p->decoding_carryover = 0;
3625 pset_encoding_buf (p, empty_unibyte_string);
3627 p->inherit_coding_system_flag
3628 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3630 UNGCPRO;
3631 return proc;
3635 #if defined (HAVE_NET_IF_H)
3637 #ifdef SIOCGIFCONF
3638 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3639 doc: /* Return an alist of all network interfaces and their network address.
3640 Each element is a cons, the car of which is a string containing the
3641 interface name, and the cdr is the network address in internal
3642 format; see the description of ADDRESS in `make-network-process'. */)
3643 (void)
3645 struct ifconf ifconf;
3646 struct ifreq *ifreq;
3647 void *buf = NULL;
3648 ptrdiff_t buf_size = 512;
3649 int s, i;
3650 Lisp_Object res;
3652 s = socket (AF_INET, SOCK_STREAM, 0);
3653 if (s < 0)
3654 return Qnil;
3658 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3659 ifconf.ifc_buf = buf;
3660 ifconf.ifc_len = buf_size;
3661 if (ioctl (s, SIOCGIFCONF, &ifconf))
3663 close (s);
3664 xfree (buf);
3665 return Qnil;
3668 while (ifconf.ifc_len == buf_size);
3670 close (s);
3672 res = Qnil;
3673 ifreq = ifconf.ifc_req;
3674 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3676 struct ifreq *ifq = ifreq;
3677 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3678 #define SIZEOF_IFREQ(sif) \
3679 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3680 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3682 int len = SIZEOF_IFREQ (ifq);
3683 #else
3684 int len = sizeof (*ifreq);
3685 #endif
3686 char namebuf[sizeof (ifq->ifr_name) + 1];
3687 i += len;
3688 ifreq = (struct ifreq *) ((char *) ifreq + len);
3690 if (ifq->ifr_addr.sa_family != AF_INET)
3691 continue;
3693 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3694 namebuf[sizeof (ifq->ifr_name)] = 0;
3695 res = Fcons (Fcons (build_string (namebuf),
3696 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3697 sizeof (struct sockaddr))),
3698 res);
3701 xfree (buf);
3702 return res;
3704 #endif /* SIOCGIFCONF */
3706 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3708 struct ifflag_def {
3709 int flag_bit;
3710 const char *flag_sym;
3713 static const struct ifflag_def ifflag_table[] = {
3714 #ifdef IFF_UP
3715 { IFF_UP, "up" },
3716 #endif
3717 #ifdef IFF_BROADCAST
3718 { IFF_BROADCAST, "broadcast" },
3719 #endif
3720 #ifdef IFF_DEBUG
3721 { IFF_DEBUG, "debug" },
3722 #endif
3723 #ifdef IFF_LOOPBACK
3724 { IFF_LOOPBACK, "loopback" },
3725 #endif
3726 #ifdef IFF_POINTOPOINT
3727 { IFF_POINTOPOINT, "pointopoint" },
3728 #endif
3729 #ifdef IFF_RUNNING
3730 { IFF_RUNNING, "running" },
3731 #endif
3732 #ifdef IFF_NOARP
3733 { IFF_NOARP, "noarp" },
3734 #endif
3735 #ifdef IFF_PROMISC
3736 { IFF_PROMISC, "promisc" },
3737 #endif
3738 #ifdef IFF_NOTRAILERS
3739 #ifdef NS_IMPL_COCOA
3740 /* Really means smart, notrailers is obsolete */
3741 { IFF_NOTRAILERS, "smart" },
3742 #else
3743 { IFF_NOTRAILERS, "notrailers" },
3744 #endif
3745 #endif
3746 #ifdef IFF_ALLMULTI
3747 { IFF_ALLMULTI, "allmulti" },
3748 #endif
3749 #ifdef IFF_MASTER
3750 { IFF_MASTER, "master" },
3751 #endif
3752 #ifdef IFF_SLAVE
3753 { IFF_SLAVE, "slave" },
3754 #endif
3755 #ifdef IFF_MULTICAST
3756 { IFF_MULTICAST, "multicast" },
3757 #endif
3758 #ifdef IFF_PORTSEL
3759 { IFF_PORTSEL, "portsel" },
3760 #endif
3761 #ifdef IFF_AUTOMEDIA
3762 { IFF_AUTOMEDIA, "automedia" },
3763 #endif
3764 #ifdef IFF_DYNAMIC
3765 { IFF_DYNAMIC, "dynamic" },
3766 #endif
3767 #ifdef IFF_OACTIVE
3768 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3769 #endif
3770 #ifdef IFF_SIMPLEX
3771 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3772 #endif
3773 #ifdef IFF_LINK0
3774 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3775 #endif
3776 #ifdef IFF_LINK1
3777 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3778 #endif
3779 #ifdef IFF_LINK2
3780 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3781 #endif
3782 { 0, 0 }
3785 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3786 doc: /* Return information about network interface named IFNAME.
3787 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3788 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3789 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3790 FLAGS is the current flags of the interface. */)
3791 (Lisp_Object ifname)
3793 struct ifreq rq;
3794 Lisp_Object res = Qnil;
3795 Lisp_Object elt;
3796 int s;
3797 int any = 0;
3798 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3799 && defined HAVE_GETIFADDRS && defined LLADDR)
3800 struct ifaddrs *ifap;
3801 #endif
3803 CHECK_STRING (ifname);
3805 if (sizeof rq.ifr_name <= SBYTES (ifname))
3806 error ("interface name too long");
3807 strcpy (rq.ifr_name, SSDATA (ifname));
3809 s = socket (AF_INET, SOCK_STREAM, 0);
3810 if (s < 0)
3811 return Qnil;
3813 elt = Qnil;
3814 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3815 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3817 int flags = rq.ifr_flags;
3818 const struct ifflag_def *fp;
3819 int fnum;
3821 /* If flags is smaller than int (i.e. short) it may have the high bit set
3822 due to IFF_MULTICAST. In that case, sign extending it into
3823 an int is wrong. */
3824 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3825 flags = (unsigned short) rq.ifr_flags;
3827 any = 1;
3828 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3830 if (flags & fp->flag_bit)
3832 elt = Fcons (intern (fp->flag_sym), elt);
3833 flags -= fp->flag_bit;
3836 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3838 if (flags & 1)
3840 elt = Fcons (make_number (fnum), elt);
3844 #endif
3845 res = Fcons (elt, res);
3847 elt = Qnil;
3848 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3849 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3851 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3852 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3853 int n;
3855 any = 1;
3856 for (n = 0; n < 6; n++)
3857 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3858 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3860 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3861 if (getifaddrs (&ifap) != -1)
3863 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3864 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3865 struct ifaddrs *it;
3867 for (it = ifap; it != NULL; it = it->ifa_next)
3869 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3870 unsigned char linkaddr[6];
3871 int n;
3873 if (it->ifa_addr->sa_family != AF_LINK
3874 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3875 || sdl->sdl_alen != 6)
3876 continue;
3878 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3879 for (n = 0; n < 6; n++)
3880 p->contents[n] = make_number (linkaddr[n]);
3882 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3883 break;
3886 #ifdef HAVE_FREEIFADDRS
3887 freeifaddrs (ifap);
3888 #endif
3890 #endif /* HAVE_GETIFADDRS && LLADDR */
3892 res = Fcons (elt, res);
3894 elt = Qnil;
3895 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3896 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3898 any = 1;
3899 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3900 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3901 #else
3902 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3903 #endif
3905 #endif
3906 res = Fcons (elt, res);
3908 elt = Qnil;
3909 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3910 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3912 any = 1;
3913 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3915 #endif
3916 res = Fcons (elt, res);
3918 elt = Qnil;
3919 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3920 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3922 any = 1;
3923 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3925 #endif
3926 res = Fcons (elt, res);
3928 close (s);
3930 return any ? res : Qnil;
3932 #endif
3933 #endif /* defined (HAVE_NET_IF_H) */
3935 /* Turn off input and output for process PROC. */
3937 static void
3938 deactivate_process (Lisp_Object proc)
3940 register int inchannel, outchannel;
3941 register struct Lisp_Process *p = XPROCESS (proc);
3943 #ifdef HAVE_GNUTLS
3944 /* Delete GnuTLS structures in PROC, if any. */
3945 emacs_gnutls_deinit (proc);
3946 #endif /* HAVE_GNUTLS */
3948 inchannel = p->infd;
3949 outchannel = p->outfd;
3951 #ifdef ADAPTIVE_READ_BUFFERING
3952 if (p->read_output_delay > 0)
3954 if (--process_output_delay_count < 0)
3955 process_output_delay_count = 0;
3956 p->read_output_delay = 0;
3957 p->read_output_skip = 0;
3959 #endif
3961 if (inchannel >= 0)
3963 /* Beware SIGCHLD hereabouts. */
3964 flush_pending_output (inchannel);
3965 emacs_close (inchannel);
3966 if (outchannel >= 0 && outchannel != inchannel)
3967 emacs_close (outchannel);
3969 p->infd = -1;
3970 p->outfd = -1;
3971 #ifdef DATAGRAM_SOCKETS
3972 if (DATAGRAM_CHAN_P (inchannel))
3974 xfree (datagram_address[inchannel].sa);
3975 datagram_address[inchannel].sa = 0;
3976 datagram_address[inchannel].len = 0;
3978 #endif
3979 chan_process[inchannel] = Qnil;
3980 FD_CLR (inchannel, &input_wait_mask);
3981 FD_CLR (inchannel, &non_keyboard_wait_mask);
3982 #ifdef NON_BLOCKING_CONNECT
3983 if (FD_ISSET (inchannel, &connect_wait_mask))
3985 FD_CLR (inchannel, &connect_wait_mask);
3986 FD_CLR (inchannel, &write_mask);
3987 if (--num_pending_connects < 0)
3988 abort ();
3990 #endif
3991 if (inchannel == max_process_desc)
3993 int i;
3994 /* We just closed the highest-numbered process input descriptor,
3995 so recompute the highest-numbered one now. */
3996 max_process_desc = 0;
3997 for (i = 0; i < MAXDESC; i++)
3998 if (!NILP (chan_process[i]))
3999 max_process_desc = i;
4005 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4006 0, 4, 0,
4007 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4008 It is read into the process' buffers or given to their filter functions.
4009 Non-nil arg PROCESS means do not return until some output has been received
4010 from PROCESS.
4012 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4013 and milliseconds to wait; return after that much time whether or not
4014 there is any subprocess output. If SECONDS is a floating point number,
4015 it specifies a fractional number of seconds to wait.
4016 The MILLISEC argument is obsolete and should be avoided.
4018 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4019 from PROCESS, suspending reading output from other processes.
4020 If JUST-THIS-ONE is an integer, don't run any timers either.
4021 Return non-nil if we received any output before the timeout expired. */)
4022 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4024 intmax_t secs;
4025 int nsecs;
4027 if (! NILP (process))
4028 CHECK_PROCESS (process);
4029 else
4030 just_this_one = Qnil;
4032 if (!NILP (millisec))
4033 { /* Obsolete calling convention using integers rather than floats. */
4034 CHECK_NUMBER (millisec);
4035 if (NILP (seconds))
4036 seconds = make_float (XINT (millisec) / 1000.0);
4037 else
4039 CHECK_NUMBER (seconds);
4040 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4044 secs = 0;
4045 nsecs = -1;
4047 if (!NILP (seconds))
4049 if (INTEGERP (seconds))
4051 if (0 < XINT (seconds))
4053 secs = XINT (seconds);
4054 nsecs = 0;
4057 else if (FLOATP (seconds))
4059 if (0 < XFLOAT_DATA (seconds))
4061 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
4062 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
4063 nsecs = EMACS_NSECS (t);
4066 else
4067 wrong_type_argument (Qnumberp, seconds);
4069 else if (! NILP (process))
4070 nsecs = 0;
4072 return
4073 (wait_reading_process_output (secs, nsecs, 0, 0,
4074 Qnil,
4075 !NILP (process) ? XPROCESS (process) : NULL,
4076 NILP (just_this_one) ? 0 :
4077 !INTEGERP (just_this_one) ? 1 : -1)
4078 ? Qt : Qnil);
4081 /* Accept a connection for server process SERVER on CHANNEL. */
4083 static int connect_counter = 0;
4085 static void
4086 server_accept_connection (Lisp_Object server, int channel)
4088 Lisp_Object proc, caller, name, buffer;
4089 Lisp_Object contact, host, service;
4090 struct Lisp_Process *ps= XPROCESS (server);
4091 struct Lisp_Process *p;
4092 int s;
4093 union u_sockaddr {
4094 struct sockaddr sa;
4095 struct sockaddr_in in;
4096 #ifdef AF_INET6
4097 struct sockaddr_in6 in6;
4098 #endif
4099 #ifdef HAVE_LOCAL_SOCKETS
4100 struct sockaddr_un un;
4101 #endif
4102 } saddr;
4103 socklen_t len = sizeof saddr;
4105 s = accept (channel, &saddr.sa, &len);
4107 if (s < 0)
4109 int code = errno;
4111 if (code == EAGAIN)
4112 return;
4113 #ifdef EWOULDBLOCK
4114 if (code == EWOULDBLOCK)
4115 return;
4116 #endif
4118 if (!NILP (ps->log))
4119 call3 (ps->log, server, Qnil,
4120 concat3 (build_string ("accept failed with code"),
4121 Fnumber_to_string (make_number (code)),
4122 build_string ("\n")));
4123 return;
4126 connect_counter++;
4128 /* Setup a new process to handle the connection. */
4130 /* Generate a unique identification of the caller, and build contact
4131 information for this process. */
4132 host = Qt;
4133 service = Qnil;
4134 switch (saddr.sa.sa_family)
4136 case AF_INET:
4138 Lisp_Object args[5];
4139 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4140 args[0] = build_string ("%d.%d.%d.%d");
4141 args[1] = make_number (*ip++);
4142 args[2] = make_number (*ip++);
4143 args[3] = make_number (*ip++);
4144 args[4] = make_number (*ip++);
4145 host = Fformat (5, args);
4146 service = make_number (ntohs (saddr.in.sin_port));
4148 args[0] = build_string (" <%s:%d>");
4149 args[1] = host;
4150 args[2] = service;
4151 caller = Fformat (3, args);
4153 break;
4155 #ifdef AF_INET6
4156 case AF_INET6:
4158 Lisp_Object args[9];
4159 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4160 int i;
4161 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4162 for (i = 0; i < 8; i++)
4163 args[i+1] = make_number (ntohs (ip6[i]));
4164 host = Fformat (9, args);
4165 service = make_number (ntohs (saddr.in.sin_port));
4167 args[0] = build_string (" <[%s]:%d>");
4168 args[1] = host;
4169 args[2] = service;
4170 caller = Fformat (3, args);
4172 break;
4173 #endif
4175 #ifdef HAVE_LOCAL_SOCKETS
4176 case AF_LOCAL:
4177 #endif
4178 default:
4179 caller = Fnumber_to_string (make_number (connect_counter));
4180 caller = concat3 (build_string (" <"), caller, build_string (">"));
4181 break;
4184 /* Create a new buffer name for this process if it doesn't have a
4185 filter. The new buffer name is based on the buffer name or
4186 process name of the server process concatenated with the caller
4187 identification. */
4189 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4190 buffer = Qnil;
4191 else
4193 buffer = ps->buffer;
4194 if (!NILP (buffer))
4195 buffer = Fbuffer_name (buffer);
4196 else
4197 buffer = ps->name;
4198 if (!NILP (buffer))
4200 buffer = concat2 (buffer, caller);
4201 buffer = Fget_buffer_create (buffer);
4205 /* Generate a unique name for the new server process. Combine the
4206 server process name with the caller identification. */
4208 name = concat2 (ps->name, caller);
4209 proc = make_process (name);
4211 chan_process[s] = proc;
4213 #ifdef O_NONBLOCK
4214 fcntl (s, F_SETFL, O_NONBLOCK);
4215 #else
4216 #ifdef O_NDELAY
4217 fcntl (s, F_SETFL, O_NDELAY);
4218 #endif
4219 #endif
4221 p = XPROCESS (proc);
4223 /* Build new contact information for this setup. */
4224 contact = Fcopy_sequence (ps->childp);
4225 contact = Fplist_put (contact, QCserver, Qnil);
4226 contact = Fplist_put (contact, QChost, host);
4227 if (!NILP (service))
4228 contact = Fplist_put (contact, QCservice, service);
4229 contact = Fplist_put (contact, QCremote,
4230 conv_sockaddr_to_lisp (&saddr.sa, len));
4231 #ifdef HAVE_GETSOCKNAME
4232 len = sizeof saddr;
4233 if (getsockname (s, &saddr.sa, &len) == 0)
4234 contact = Fplist_put (contact, QClocal,
4235 conv_sockaddr_to_lisp (&saddr.sa, len));
4236 #endif
4238 pset_childp (p, contact);
4239 pset_plist (p, Fcopy_sequence (ps->plist));
4240 pset_type (p, Qnetwork);
4242 pset_buffer (p, buffer);
4243 pset_sentinel (p, ps->sentinel);
4244 pset_filter (p, ps->filter);
4245 pset_command (p, Qnil);
4246 p->pid = 0;
4247 p->infd = s;
4248 p->outfd = s;
4249 pset_status (p, Qrun);
4251 /* Client processes for accepted connections are not stopped initially. */
4252 if (!EQ (p->filter, Qt))
4254 FD_SET (s, &input_wait_mask);
4255 FD_SET (s, &non_keyboard_wait_mask);
4258 if (s > max_process_desc)
4259 max_process_desc = s;
4261 /* Setup coding system for new process based on server process.
4262 This seems to be the proper thing to do, as the coding system
4263 of the new process should reflect the settings at the time the
4264 server socket was opened; not the current settings. */
4266 pset_decode_coding_system (p, ps->decode_coding_system);
4267 pset_encode_coding_system (p, ps->encode_coding_system);
4268 setup_process_coding_systems (proc);
4270 pset_decoding_buf (p, empty_unibyte_string);
4271 p->decoding_carryover = 0;
4272 pset_encoding_buf (p, empty_unibyte_string);
4274 p->inherit_coding_system_flag
4275 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4277 if (!NILP (ps->log))
4278 call3 (ps->log, server, proc,
4279 concat3 (build_string ("accept from "),
4280 (STRINGP (host) ? host : build_string ("-")),
4281 build_string ("\n")));
4283 if (!NILP (p->sentinel))
4284 exec_sentinel (proc,
4285 concat3 (build_string ("open from "),
4286 (STRINGP (host) ? host : build_string ("-")),
4287 build_string ("\n")));
4290 /* This variable is different from waiting_for_input in keyboard.c.
4291 It is used to communicate to a lisp process-filter/sentinel (via the
4292 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4293 for user-input when that process-filter was called.
4294 waiting_for_input cannot be used as that is by definition 0 when
4295 lisp code is being evalled.
4296 This is also used in record_asynch_buffer_change.
4297 For that purpose, this must be 0
4298 when not inside wait_reading_process_output. */
4299 static int waiting_for_user_input_p;
4301 static Lisp_Object
4302 wait_reading_process_output_unwind (Lisp_Object data)
4304 waiting_for_user_input_p = XINT (data);
4305 return Qnil;
4308 /* This is here so breakpoints can be put on it. */
4309 static void
4310 wait_reading_process_output_1 (void)
4314 /* Read and dispose of subprocess output while waiting for timeout to
4315 elapse and/or keyboard input to be available.
4317 TIME_LIMIT is:
4318 timeout in seconds
4319 If negative, gobble data immediately available but don't wait for any.
4321 NSECS is:
4322 an additional duration to wait, measured in nanoseconds
4323 If TIME_LIMIT is zero, then:
4324 If NSECS == 0, there is no limit.
4325 If NSECS > 0, the timeout consists of NSECS only.
4326 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4328 READ_KBD is:
4329 0 to ignore keyboard input, or
4330 1 to return when input is available, or
4331 -1 meaning caller will actually read the input, so don't throw to
4332 the quit handler, or
4334 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4335 output that arrives.
4337 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4338 (and gobble terminal input into the buffer if any arrives).
4340 If WAIT_PROC is specified, wait until something arrives from that
4341 process. The return value is true if we read some input from
4342 that process.
4344 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4345 (suspending output from other processes). A negative value
4346 means don't run any timers either.
4348 If WAIT_PROC is specified, then the function returns true if we
4349 received input from that process before the timeout elapsed.
4350 Otherwise, return true if we received input from any process. */
4353 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4354 int do_display,
4355 Lisp_Object wait_for_cell,
4356 struct Lisp_Process *wait_proc, int just_wait_proc)
4358 register int channel, nfds;
4359 SELECT_TYPE Available;
4360 SELECT_TYPE Writeok;
4361 int check_write;
4362 int check_delay, no_avail;
4363 int xerrno;
4364 Lisp_Object proc;
4365 EMACS_TIME timeout, end_time;
4366 int wait_channel = -1;
4367 int got_some_input = 0;
4368 ptrdiff_t count = SPECPDL_INDEX ();
4370 FD_ZERO (&Available);
4371 FD_ZERO (&Writeok);
4373 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4374 && !(CONSP (wait_proc->status)
4375 && EQ (XCAR (wait_proc->status), Qexit)))
4376 message ("Blocking call to accept-process-output with quit inhibited!!");
4378 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4379 if (wait_proc != NULL)
4380 wait_channel = wait_proc->infd;
4382 record_unwind_protect (wait_reading_process_output_unwind,
4383 make_number (waiting_for_user_input_p));
4384 waiting_for_user_input_p = read_kbd;
4386 if (time_limit < 0)
4388 time_limit = 0;
4389 nsecs = -1;
4391 else if (TYPE_MAXIMUM (time_t) < time_limit)
4392 time_limit = TYPE_MAXIMUM (time_t);
4394 /* Since we may need to wait several times,
4395 compute the absolute time to return at. */
4396 if (time_limit || 0 < nsecs)
4398 timeout = make_emacs_time (time_limit, nsecs);
4399 end_time = add_emacs_time (current_emacs_time (), timeout);
4402 while (1)
4404 int timeout_reduced_for_timers = 0;
4406 /* If calling from keyboard input, do not quit
4407 since we want to return C-g as an input character.
4408 Otherwise, do pending quit if requested. */
4409 if (read_kbd >= 0)
4410 QUIT;
4411 #ifdef SYNC_INPUT
4412 else
4413 process_pending_signals ();
4414 #endif
4416 /* Exit now if the cell we're waiting for became non-nil. */
4417 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4418 break;
4420 /* Compute time from now till when time limit is up */
4421 /* Exit if already run out */
4422 if (nsecs < 0)
4424 /* A negative timeout means
4425 gobble output available now
4426 but don't wait at all. */
4428 timeout = make_emacs_time (0, 0);
4430 else if (time_limit || 0 < nsecs)
4432 EMACS_TIME now = current_emacs_time ();
4433 if (EMACS_TIME_LE (end_time, now))
4434 break;
4435 timeout = sub_emacs_time (end_time, now);
4437 else
4439 timeout = make_emacs_time (100000, 0);
4442 /* Normally we run timers here.
4443 But not if wait_for_cell; in those cases,
4444 the wait is supposed to be short,
4445 and those callers cannot handle running arbitrary Lisp code here. */
4446 if (NILP (wait_for_cell)
4447 && just_wait_proc >= 0)
4449 EMACS_TIME timer_delay;
4453 int old_timers_run = timers_run;
4454 struct buffer *old_buffer = current_buffer;
4455 Lisp_Object old_window = selected_window;
4457 timer_delay = timer_check ();
4459 /* If a timer has run, this might have changed buffers
4460 an alike. Make read_key_sequence aware of that. */
4461 if (timers_run != old_timers_run
4462 && (old_buffer != current_buffer
4463 || !EQ (old_window, selected_window))
4464 && waiting_for_user_input_p == -1)
4465 record_asynch_buffer_change ();
4467 if (timers_run != old_timers_run && do_display)
4468 /* We must retry, since a timer may have requeued itself
4469 and that could alter the time_delay. */
4470 redisplay_preserve_echo_area (9);
4471 else
4472 break;
4474 while (!detect_input_pending ());
4476 /* If there is unread keyboard input, also return. */
4477 if (read_kbd != 0
4478 && requeued_events_pending_p ())
4479 break;
4481 /* A negative timeout means do not wait at all. */
4482 if (0 <= nsecs)
4484 if (EMACS_TIME_VALID_P (timer_delay))
4486 if (EMACS_TIME_LT (timer_delay, timeout))
4488 timeout = timer_delay;
4489 timeout_reduced_for_timers = 1;
4492 else
4494 /* This is so a breakpoint can be put here. */
4495 wait_reading_process_output_1 ();
4500 /* Cause C-g and alarm signals to take immediate action,
4501 and cause input available signals to zero out timeout.
4503 It is important that we do this before checking for process
4504 activity. If we get a SIGCHLD after the explicit checks for
4505 process activity, timeout is the only way we will know. */
4506 if (read_kbd < 0)
4507 set_waiting_for_input (&timeout);
4509 /* If status of something has changed, and no input is
4510 available, notify the user of the change right away. After
4511 this explicit check, we'll let the SIGCHLD handler zap
4512 timeout to get our attention. */
4513 if (update_tick != process_tick)
4515 SELECT_TYPE Atemp;
4516 SELECT_TYPE Ctemp;
4518 if (kbd_on_hold_p ())
4519 FD_ZERO (&Atemp);
4520 else
4521 Atemp = input_wait_mask;
4522 Ctemp = write_mask;
4524 timeout = make_emacs_time (0, 0);
4525 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4526 &Atemp,
4527 #ifdef NON_BLOCKING_CONNECT
4528 (num_pending_connects > 0 ? &Ctemp : NULL),
4529 #else
4530 NULL,
4531 #endif
4532 NULL, &timeout, NULL)
4533 <= 0))
4535 /* It's okay for us to do this and then continue with
4536 the loop, since timeout has already been zeroed out. */
4537 clear_waiting_for_input ();
4538 status_notify (NULL);
4539 if (do_display) redisplay_preserve_echo_area (13);
4543 /* Don't wait for output from a non-running process. Just
4544 read whatever data has already been received. */
4545 if (wait_proc && wait_proc->raw_status_new)
4546 update_status (wait_proc);
4547 if (wait_proc
4548 && ! EQ (wait_proc->status, Qrun)
4549 && ! EQ (wait_proc->status, Qconnect))
4551 int nread, total_nread = 0;
4553 clear_waiting_for_input ();
4554 XSETPROCESS (proc, wait_proc);
4556 /* Read data from the process, until we exhaust it. */
4557 while (wait_proc->infd >= 0)
4559 nread = read_process_output (proc, wait_proc->infd);
4561 if (nread == 0)
4562 break;
4564 if (0 < nread)
4566 total_nread += nread;
4567 got_some_input = 1;
4569 #ifdef EIO
4570 else if (nread == -1 && EIO == errno)
4571 break;
4572 #endif
4573 #ifdef EAGAIN
4574 else if (nread == -1 && EAGAIN == errno)
4575 break;
4576 #endif
4577 #ifdef EWOULDBLOCK
4578 else if (nread == -1 && EWOULDBLOCK == errno)
4579 break;
4580 #endif
4582 if (total_nread > 0 && do_display)
4583 redisplay_preserve_echo_area (10);
4585 break;
4588 /* Wait till there is something to do */
4590 if (wait_proc && just_wait_proc)
4592 if (wait_proc->infd < 0) /* Terminated */
4593 break;
4594 FD_SET (wait_proc->infd, &Available);
4595 check_delay = 0;
4596 check_write = 0;
4598 else if (!NILP (wait_for_cell))
4600 Available = non_process_wait_mask;
4601 check_delay = 0;
4602 check_write = 0;
4604 else
4606 if (! read_kbd)
4607 Available = non_keyboard_wait_mask;
4608 else
4609 Available = input_wait_mask;
4610 Writeok = write_mask;
4611 #ifdef SELECT_CANT_DO_WRITE_MASK
4612 check_write = 0;
4613 #else
4614 check_write = 1;
4615 #endif
4616 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4619 /* If frame size has changed or the window is newly mapped,
4620 redisplay now, before we start to wait. There is a race
4621 condition here; if a SIGIO arrives between now and the select
4622 and indicates that a frame is trashed, the select may block
4623 displaying a trashed screen. */
4624 if (frame_garbaged && do_display)
4626 clear_waiting_for_input ();
4627 redisplay_preserve_echo_area (11);
4628 if (read_kbd < 0)
4629 set_waiting_for_input (&timeout);
4632 /* Skip the `select' call if input is available and we're
4633 waiting for keyboard input or a cell change (which can be
4634 triggered by processing X events). In the latter case, set
4635 nfds to 1 to avoid breaking the loop. */
4636 no_avail = 0;
4637 if ((read_kbd || !NILP (wait_for_cell))
4638 && detect_input_pending ())
4640 nfds = read_kbd ? 0 : 1;
4641 no_avail = 1;
4644 if (!no_avail)
4647 #ifdef ADAPTIVE_READ_BUFFERING
4648 /* Set the timeout for adaptive read buffering if any
4649 process has non-zero read_output_skip and non-zero
4650 read_output_delay, and we are not reading output for a
4651 specific wait_channel. It is not executed if
4652 Vprocess_adaptive_read_buffering is nil. */
4653 if (process_output_skip && check_delay > 0)
4655 int nsecs = EMACS_NSECS (timeout);
4656 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4657 nsecs = READ_OUTPUT_DELAY_MAX;
4658 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4660 proc = chan_process[channel];
4661 if (NILP (proc))
4662 continue;
4663 /* Find minimum non-zero read_output_delay among the
4664 processes with non-zero read_output_skip. */
4665 if (XPROCESS (proc)->read_output_delay > 0)
4667 check_delay--;
4668 if (!XPROCESS (proc)->read_output_skip)
4669 continue;
4670 FD_CLR (channel, &Available);
4671 XPROCESS (proc)->read_output_skip = 0;
4672 if (XPROCESS (proc)->read_output_delay < nsecs)
4673 nsecs = XPROCESS (proc)->read_output_delay;
4676 timeout = make_emacs_time (0, nsecs);
4677 process_output_skip = 0;
4679 #endif
4680 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4681 nfds = xg_select
4682 #elif defined (HAVE_NS)
4683 nfds = ns_select
4684 #else
4685 nfds = pselect
4686 #endif
4687 (max (max_process_desc, max_input_desc) + 1,
4688 &Available,
4689 (check_write ? &Writeok : (SELECT_TYPE *)0),
4690 NULL, &timeout, NULL);
4692 #ifdef HAVE_GNUTLS
4693 /* GnuTLS buffers data internally. In lowat mode it leaves
4694 some data in the TCP buffers so that select works, but
4695 with custom pull/push functions we need to check if some
4696 data is available in the buffers manually. */
4697 if (nfds == 0)
4699 if (! wait_proc)
4701 /* We're not waiting on a specific process, so loop
4702 through all the channels and check for data.
4703 This is a workaround needed for some versions of
4704 the gnutls library -- 2.12.14 has been confirmed
4705 to need it. See
4706 http://comments.gmane.org/gmane.emacs.devel/145074 */
4707 for (channel = 0; channel < MAXDESC; ++channel)
4708 if (! NILP (chan_process[channel]))
4710 struct Lisp_Process *p =
4711 XPROCESS (chan_process[channel]);
4712 if (p && p->gnutls_p && p->infd
4713 && ((emacs_gnutls_record_check_pending
4714 (p->gnutls_state))
4715 > 0))
4717 nfds++;
4718 FD_SET (p->infd, &Available);
4722 else
4724 /* Check this specific channel. */
4725 if (wait_proc->gnutls_p /* Check for valid process. */
4726 /* Do we have pending data? */
4727 && ((emacs_gnutls_record_check_pending
4728 (wait_proc->gnutls_state))
4729 > 0))
4731 nfds = 1;
4732 /* Set to Available. */
4733 FD_SET (wait_proc->infd, &Available);
4737 #endif
4740 xerrno = errno;
4742 /* Make C-g and alarm signals set flags again */
4743 clear_waiting_for_input ();
4745 /* If we woke up due to SIGWINCH, actually change size now. */
4746 do_pending_window_change (0);
4748 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4749 /* We waited the full specified time, so return now. */
4750 break;
4751 if (nfds < 0)
4753 if (xerrno == EINTR)
4754 no_avail = 1;
4755 else if (xerrno == EBADF)
4757 #ifdef AIX
4758 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4759 the child's closure of the pts gives the parent a SIGHUP, and
4760 the ptc file descriptor is automatically closed,
4761 yielding EBADF here or at select() call above.
4762 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4763 in m/ibmrt-aix.h), and here we just ignore the select error.
4764 Cleanup occurs c/o status_notify after SIGCLD. */
4765 no_avail = 1; /* Cannot depend on values returned */
4766 #else
4767 abort ();
4768 #endif
4770 else
4771 error ("select error: %s", emacs_strerror (xerrno));
4774 if (no_avail)
4776 FD_ZERO (&Available);
4777 check_write = 0;
4780 #if 0 /* When polling is used, interrupt_input is 0,
4781 so get_input_pending should read the input.
4782 So this should not be needed. */
4783 /* If we are using polling for input,
4784 and we see input available, make it get read now.
4785 Otherwise it might not actually get read for a second.
4786 And on hpux, since we turn off polling in wait_reading_process_output,
4787 it might never get read at all if we don't spend much time
4788 outside of wait_reading_process_output. */
4789 if (read_kbd && interrupt_input
4790 && keyboard_bit_set (&Available)
4791 && input_polling_used ())
4792 kill (getpid (), SIGALRM);
4793 #endif
4795 /* Check for keyboard input */
4796 /* If there is any, return immediately
4797 to give it higher priority than subprocesses */
4799 if (read_kbd != 0)
4801 int old_timers_run = timers_run;
4802 struct buffer *old_buffer = current_buffer;
4803 Lisp_Object old_window = selected_window;
4804 int leave = 0;
4806 if (detect_input_pending_run_timers (do_display))
4808 swallow_events (do_display);
4809 if (detect_input_pending_run_timers (do_display))
4810 leave = 1;
4813 /* If a timer has run, this might have changed buffers
4814 an alike. Make read_key_sequence aware of that. */
4815 if (timers_run != old_timers_run
4816 && waiting_for_user_input_p == -1
4817 && (old_buffer != current_buffer
4818 || !EQ (old_window, selected_window)))
4819 record_asynch_buffer_change ();
4821 if (leave)
4822 break;
4825 /* If there is unread keyboard input, also return. */
4826 if (read_kbd != 0
4827 && requeued_events_pending_p ())
4828 break;
4830 /* If we are not checking for keyboard input now,
4831 do process events (but don't run any timers).
4832 This is so that X events will be processed.
4833 Otherwise they may have to wait until polling takes place.
4834 That would causes delays in pasting selections, for example.
4836 (We used to do this only if wait_for_cell.) */
4837 if (read_kbd == 0 && detect_input_pending ())
4839 swallow_events (do_display);
4840 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4841 if (detect_input_pending ())
4842 break;
4843 #endif
4846 /* Exit now if the cell we're waiting for became non-nil. */
4847 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4848 break;
4850 #ifdef SIGIO
4851 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4852 go read it. This can happen with X on BSD after logging out.
4853 In that case, there really is no input and no SIGIO,
4854 but select says there is input. */
4856 if (read_kbd && interrupt_input
4857 && keyboard_bit_set (&Available) && ! noninteractive)
4858 kill (getpid (), SIGIO);
4859 #endif
4861 if (! wait_proc)
4862 got_some_input |= nfds > 0;
4864 /* If checking input just got us a size-change event from X,
4865 obey it now if we should. */
4866 if (read_kbd || ! NILP (wait_for_cell))
4867 do_pending_window_change (0);
4869 /* Check for data from a process. */
4870 if (no_avail || nfds == 0)
4871 continue;
4873 for (channel = 0; channel <= max_input_desc; ++channel)
4875 struct fd_callback_data *d = &fd_callback_info[channel];
4876 if (FD_ISSET (channel, &Available)
4877 && d->func != 0
4878 && (d->condition & FOR_READ) != 0)
4879 d->func (channel, d->data, 1);
4880 if (FD_ISSET (channel, &write_mask)
4881 && d->func != 0
4882 && (d->condition & FOR_WRITE) != 0)
4883 d->func (channel, d->data, 0);
4886 for (channel = 0; channel <= max_process_desc; channel++)
4888 if (FD_ISSET (channel, &Available)
4889 && FD_ISSET (channel, &non_keyboard_wait_mask)
4890 && !FD_ISSET (channel, &non_process_wait_mask))
4892 int nread;
4894 /* If waiting for this channel, arrange to return as
4895 soon as no more input to be processed. No more
4896 waiting. */
4897 if (wait_channel == channel)
4899 wait_channel = -1;
4900 nsecs = -1;
4901 got_some_input = 1;
4903 proc = chan_process[channel];
4904 if (NILP (proc))
4905 continue;
4907 /* If this is a server stream socket, accept connection. */
4908 if (EQ (XPROCESS (proc)->status, Qlisten))
4910 server_accept_connection (proc, channel);
4911 continue;
4914 /* Read data from the process, starting with our
4915 buffered-ahead character if we have one. */
4917 nread = read_process_output (proc, channel);
4918 if (nread > 0)
4920 /* Since read_process_output can run a filter,
4921 which can call accept-process-output,
4922 don't try to read from any other processes
4923 before doing the select again. */
4924 FD_ZERO (&Available);
4926 if (do_display)
4927 redisplay_preserve_echo_area (12);
4929 #ifdef EWOULDBLOCK
4930 else if (nread == -1 && errno == EWOULDBLOCK)
4932 #endif
4933 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4934 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4935 #ifdef O_NONBLOCK
4936 else if (nread == -1 && errno == EAGAIN)
4938 #else
4939 #ifdef O_NDELAY
4940 else if (nread == -1 && errno == EAGAIN)
4942 /* Note that we cannot distinguish between no input
4943 available now and a closed pipe.
4944 With luck, a closed pipe will be accompanied by
4945 subprocess termination and SIGCHLD. */
4946 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4948 #endif /* O_NDELAY */
4949 #endif /* O_NONBLOCK */
4950 #ifdef HAVE_PTYS
4951 /* On some OSs with ptys, when the process on one end of
4952 a pty exits, the other end gets an error reading with
4953 errno = EIO instead of getting an EOF (0 bytes read).
4954 Therefore, if we get an error reading and errno =
4955 EIO, just continue, because the child process has
4956 exited and should clean itself up soon (e.g. when we
4957 get a SIGCHLD).
4959 However, it has been known to happen that the SIGCHLD
4960 got lost. So raise the signal again just in case.
4961 It can't hurt. */
4962 else if (nread == -1 && errno == EIO)
4964 struct Lisp_Process *p = XPROCESS (proc);
4966 /* Clear the descriptor now, so we only raise the
4967 signal once. */
4968 FD_CLR (channel, &input_wait_mask);
4969 FD_CLR (channel, &non_keyboard_wait_mask);
4971 if (p->pid == -2)
4973 /* If the EIO occurs on a pty, sigchld_handler's
4974 waitpid() will not find the process object to
4975 delete. Do it here. */
4976 p->tick = ++process_tick;
4977 pset_status (p, Qfailed);
4979 else
4980 kill (getpid (), SIGCHLD);
4982 #endif /* HAVE_PTYS */
4983 /* If we can detect process termination, don't consider the
4984 process gone just because its pipe is closed. */
4985 #ifdef SIGCHLD
4986 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4988 #endif
4989 else
4991 /* Preserve status of processes already terminated. */
4992 XPROCESS (proc)->tick = ++process_tick;
4993 deactivate_process (proc);
4994 if (XPROCESS (proc)->raw_status_new)
4995 update_status (XPROCESS (proc));
4996 if (EQ (XPROCESS (proc)->status, Qrun))
4997 pset_status (XPROCESS (proc),
4998 list2 (Qexit, make_number (256)));
5001 #ifdef NON_BLOCKING_CONNECT
5002 if (FD_ISSET (channel, &Writeok)
5003 && FD_ISSET (channel, &connect_wait_mask))
5005 struct Lisp_Process *p;
5007 FD_CLR (channel, &connect_wait_mask);
5008 FD_CLR (channel, &write_mask);
5009 if (--num_pending_connects < 0)
5010 abort ();
5012 proc = chan_process[channel];
5013 if (NILP (proc))
5014 continue;
5016 p = XPROCESS (proc);
5018 #ifdef GNU_LINUX
5019 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5020 So only use it on systems where it is known to work. */
5022 socklen_t xlen = sizeof (xerrno);
5023 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5024 xerrno = errno;
5026 #else
5028 struct sockaddr pname;
5029 int pnamelen = sizeof (pname);
5031 /* If connection failed, getpeername will fail. */
5032 xerrno = 0;
5033 if (getpeername (channel, &pname, &pnamelen) < 0)
5035 /* Obtain connect failure code through error slippage. */
5036 char dummy;
5037 xerrno = errno;
5038 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5039 xerrno = errno;
5042 #endif
5043 if (xerrno)
5045 p->tick = ++process_tick;
5046 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5047 deactivate_process (proc);
5049 else
5051 pset_status (p, Qrun);
5052 /* Execute the sentinel here. If we had relied on
5053 status_notify to do it later, it will read input
5054 from the process before calling the sentinel. */
5055 exec_sentinel (proc, build_string ("open\n"));
5056 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5058 FD_SET (p->infd, &input_wait_mask);
5059 FD_SET (p->infd, &non_keyboard_wait_mask);
5063 #endif /* NON_BLOCKING_CONNECT */
5064 } /* end for each file descriptor */
5065 } /* end while exit conditions not met */
5067 unbind_to (count, Qnil);
5069 /* If calling from keyboard input, do not quit
5070 since we want to return C-g as an input character.
5071 Otherwise, do pending quit if requested. */
5072 if (read_kbd >= 0)
5074 /* Prevent input_pending from remaining set if we quit. */
5075 clear_input_pending ();
5076 QUIT;
5079 return got_some_input;
5082 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5084 static Lisp_Object
5085 read_process_output_call (Lisp_Object fun_and_args)
5087 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5090 static Lisp_Object
5091 read_process_output_error_handler (Lisp_Object error_val)
5093 cmd_error_internal (error_val, "error in process filter: ");
5094 Vinhibit_quit = Qt;
5095 update_echo_area ();
5096 Fsleep_for (make_number (2), Qnil);
5097 return Qt;
5100 /* Read pending output from the process channel,
5101 starting with our buffered-ahead character if we have one.
5102 Yield number of decoded characters read.
5104 This function reads at most 4096 characters.
5105 If you want to read all available subprocess output,
5106 you must call it repeatedly until it returns zero.
5108 The characters read are decoded according to PROC's coding-system
5109 for decoding. */
5111 static int
5112 read_process_output (Lisp_Object proc, register int channel)
5114 register ssize_t nbytes;
5115 char *chars;
5116 register Lisp_Object outstream;
5117 register struct Lisp_Process *p = XPROCESS (proc);
5118 register ptrdiff_t opoint;
5119 struct coding_system *coding = proc_decode_coding_system[channel];
5120 int carryover = p->decoding_carryover;
5121 int readmax = 4096;
5122 ptrdiff_t count = SPECPDL_INDEX ();
5123 Lisp_Object odeactivate;
5125 chars = alloca (carryover + readmax);
5126 if (carryover)
5127 /* See the comment above. */
5128 memcpy (chars, SDATA (p->decoding_buf), carryover);
5130 #ifdef DATAGRAM_SOCKETS
5131 /* We have a working select, so proc_buffered_char is always -1. */
5132 if (DATAGRAM_CHAN_P (channel))
5134 socklen_t len = datagram_address[channel].len;
5135 nbytes = recvfrom (channel, chars + carryover, readmax,
5136 0, datagram_address[channel].sa, &len);
5138 else
5139 #endif
5141 int buffered = 0 <= proc_buffered_char[channel];
5142 if (buffered)
5144 chars[carryover] = proc_buffered_char[channel];
5145 proc_buffered_char[channel] = -1;
5147 #ifdef HAVE_GNUTLS
5148 if (p->gnutls_p)
5149 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5150 readmax - buffered);
5151 else
5152 #endif
5153 nbytes = emacs_read (channel, chars + carryover + buffered,
5154 readmax - buffered);
5155 #ifdef ADAPTIVE_READ_BUFFERING
5156 if (nbytes > 0 && p->adaptive_read_buffering)
5158 int delay = p->read_output_delay;
5159 if (nbytes < 256)
5161 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5163 if (delay == 0)
5164 process_output_delay_count++;
5165 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5168 else if (delay > 0 && nbytes == readmax - buffered)
5170 delay -= READ_OUTPUT_DELAY_INCREMENT;
5171 if (delay == 0)
5172 process_output_delay_count--;
5174 p->read_output_delay = delay;
5175 if (delay)
5177 p->read_output_skip = 1;
5178 process_output_skip = 1;
5181 #endif
5182 nbytes += buffered;
5183 nbytes += buffered && nbytes <= 0;
5186 p->decoding_carryover = 0;
5188 /* At this point, NBYTES holds number of bytes just received
5189 (including the one in proc_buffered_char[channel]). */
5190 if (nbytes <= 0)
5192 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5193 return nbytes;
5194 coding->mode |= CODING_MODE_LAST_BLOCK;
5197 /* Now set NBYTES how many bytes we must decode. */
5198 nbytes += carryover;
5200 odeactivate = Vdeactivate_mark;
5201 /* There's no good reason to let process filters change the current
5202 buffer, and many callers of accept-process-output, sit-for, and
5203 friends don't expect current-buffer to be changed from under them. */
5204 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5206 /* Read and dispose of the process output. */
5207 outstream = p->filter;
5208 if (!NILP (outstream))
5210 Lisp_Object text;
5211 int outer_running_asynch_code = running_asynch_code;
5212 int waiting = waiting_for_user_input_p;
5214 /* No need to gcpro these, because all we do with them later
5215 is test them for EQness, and none of them should be a string. */
5216 #if 0
5217 Lisp_Object obuffer, okeymap;
5218 XSETBUFFER (obuffer, current_buffer);
5219 okeymap = BVAR (current_buffer, keymap);
5220 #endif
5222 /* We inhibit quit here instead of just catching it so that
5223 hitting ^G when a filter happens to be running won't screw
5224 it up. */
5225 specbind (Qinhibit_quit, Qt);
5226 specbind (Qlast_nonmenu_event, Qt);
5228 /* In case we get recursively called,
5229 and we already saved the match data nonrecursively,
5230 save the same match data in safely recursive fashion. */
5231 if (outer_running_asynch_code)
5233 Lisp_Object tem;
5234 /* Don't clobber the CURRENT match data, either! */
5235 tem = Fmatch_data (Qnil, Qnil, Qnil);
5236 restore_search_regs ();
5237 record_unwind_save_match_data ();
5238 Fset_match_data (tem, Qt);
5241 /* For speed, if a search happens within this code,
5242 save the match data in a special nonrecursive fashion. */
5243 running_asynch_code = 1;
5245 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5246 text = coding->dst_object;
5247 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5248 /* A new coding system might be found. */
5249 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5251 pset_decode_coding_system (p, Vlast_coding_system_used);
5253 /* Don't call setup_coding_system for
5254 proc_decode_coding_system[channel] here. It is done in
5255 detect_coding called via decode_coding above. */
5257 /* If a coding system for encoding is not yet decided, we set
5258 it as the same as coding-system for decoding.
5260 But, before doing that we must check if
5261 proc_encode_coding_system[p->outfd] surely points to a
5262 valid memory because p->outfd will be changed once EOF is
5263 sent to the process. */
5264 if (NILP (p->encode_coding_system)
5265 && proc_encode_coding_system[p->outfd])
5267 pset_encode_coding_system
5268 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5269 setup_coding_system (p->encode_coding_system,
5270 proc_encode_coding_system[p->outfd]);
5274 if (coding->carryover_bytes > 0)
5276 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5277 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5278 memcpy (SDATA (p->decoding_buf), coding->carryover,
5279 coding->carryover_bytes);
5280 p->decoding_carryover = coding->carryover_bytes;
5282 if (SBYTES (text) > 0)
5283 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5284 sometimes it's simply wrong to wrap (e.g. when called from
5285 accept-process-output). */
5286 internal_condition_case_1 (read_process_output_call,
5287 Fcons (outstream,
5288 Fcons (proc, Fcons (text, Qnil))),
5289 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5290 read_process_output_error_handler);
5292 /* If we saved the match data nonrecursively, restore it now. */
5293 restore_search_regs ();
5294 running_asynch_code = outer_running_asynch_code;
5296 /* Restore waiting_for_user_input_p as it was
5297 when we were called, in case the filter clobbered it. */
5298 waiting_for_user_input_p = waiting;
5300 #if 0 /* Call record_asynch_buffer_change unconditionally,
5301 because we might have changed minor modes or other things
5302 that affect key bindings. */
5303 if (! EQ (Fcurrent_buffer (), obuffer)
5304 || ! EQ (current_buffer->keymap, okeymap))
5305 #endif
5306 /* But do it only if the caller is actually going to read events.
5307 Otherwise there's no need to make him wake up, and it could
5308 cause trouble (for example it would make sit_for return). */
5309 if (waiting_for_user_input_p == -1)
5310 record_asynch_buffer_change ();
5313 /* If no filter, write into buffer if it isn't dead. */
5314 else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
5316 Lisp_Object old_read_only;
5317 ptrdiff_t old_begv, old_zv;
5318 ptrdiff_t old_begv_byte, old_zv_byte;
5319 ptrdiff_t before, before_byte;
5320 ptrdiff_t opoint_byte;
5321 Lisp_Object text;
5322 struct buffer *b;
5324 Fset_buffer (p->buffer);
5325 opoint = PT;
5326 opoint_byte = PT_BYTE;
5327 old_read_only = BVAR (current_buffer, read_only);
5328 old_begv = BEGV;
5329 old_zv = ZV;
5330 old_begv_byte = BEGV_BYTE;
5331 old_zv_byte = ZV_BYTE;
5333 BSET (current_buffer, read_only, Qnil);
5335 /* Insert new output into buffer
5336 at the current end-of-output marker,
5337 thus preserving logical ordering of input and output. */
5338 if (XMARKER (p->mark)->buffer)
5339 SET_PT_BOTH (clip_to_bounds (BEGV,
5340 marker_position (p->mark), ZV),
5341 clip_to_bounds (BEGV_BYTE,
5342 marker_byte_position (p->mark),
5343 ZV_BYTE));
5344 else
5345 SET_PT_BOTH (ZV, ZV_BYTE);
5346 before = PT;
5347 before_byte = PT_BYTE;
5349 /* If the output marker is outside of the visible region, save
5350 the restriction and widen. */
5351 if (! (BEGV <= PT && PT <= ZV))
5352 Fwiden ();
5354 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5355 text = coding->dst_object;
5356 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5357 /* A new coding system might be found. See the comment in the
5358 similar code in the previous `if' block. */
5359 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5361 pset_decode_coding_system (p, Vlast_coding_system_used);
5362 if (NILP (p->encode_coding_system)
5363 && proc_encode_coding_system[p->outfd])
5365 pset_encode_coding_system
5366 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5367 setup_coding_system (p->encode_coding_system,
5368 proc_encode_coding_system[p->outfd]);
5371 if (coding->carryover_bytes > 0)
5373 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5374 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5375 memcpy (SDATA (p->decoding_buf), coding->carryover,
5376 coding->carryover_bytes);
5377 p->decoding_carryover = coding->carryover_bytes;
5379 /* Adjust the multibyteness of TEXT to that of the buffer. */
5380 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5381 != ! STRING_MULTIBYTE (text))
5382 text = (STRING_MULTIBYTE (text)
5383 ? Fstring_as_unibyte (text)
5384 : Fstring_to_multibyte (text));
5385 /* Insert before markers in case we are inserting where
5386 the buffer's mark is, and the user's next command is Meta-y. */
5387 insert_from_string_before_markers (text, 0, 0,
5388 SCHARS (text), SBYTES (text), 0);
5390 /* Make sure the process marker's position is valid when the
5391 process buffer is changed in the signal_after_change above.
5392 W3 is known to do that. */
5393 if (BUFFERP (p->buffer)
5394 && (b = XBUFFER (p->buffer), b != current_buffer))
5395 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5396 else
5397 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5399 update_mode_lines++;
5401 /* Make sure opoint and the old restrictions
5402 float ahead of any new text just as point would. */
5403 if (opoint >= before)
5405 opoint += PT - before;
5406 opoint_byte += PT_BYTE - before_byte;
5408 if (old_begv > before)
5410 old_begv += PT - before;
5411 old_begv_byte += PT_BYTE - before_byte;
5413 if (old_zv >= before)
5415 old_zv += PT - before;
5416 old_zv_byte += PT_BYTE - before_byte;
5419 /* If the restriction isn't what it should be, set it. */
5420 if (old_begv != BEGV || old_zv != ZV)
5421 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5424 BSET (current_buffer, read_only, old_read_only);
5425 SET_PT_BOTH (opoint, opoint_byte);
5427 /* Handling the process output should not deactivate the mark. */
5428 Vdeactivate_mark = odeactivate;
5430 unbind_to (count, Qnil);
5431 return nbytes;
5434 /* Sending data to subprocess */
5436 static jmp_buf send_process_frame;
5437 static Lisp_Object process_sent_to;
5439 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5440 static _Noreturn void send_process_trap (int);
5441 #endif
5443 static void
5444 send_process_trap (int ignore)
5446 SIGNAL_THREAD_CHECK (SIGPIPE);
5447 sigunblock (sigmask (SIGPIPE));
5448 longjmp (send_process_frame, 1);
5451 /* In send_process, when a write fails temporarily,
5452 wait_reading_process_output is called. It may execute user code,
5453 e.g. timers, that attempts to write new data to the same process.
5454 We must ensure that data is sent in the right order, and not
5455 interspersed half-completed with other writes (Bug#10815). This is
5456 handled by the write_queue element of struct process. It is a list
5457 with each entry having the form
5459 (string . (offset . length))
5461 where STRING is a lisp string, OFFSET is the offset into the
5462 string's byte sequence from which we should begin to send, and
5463 LENGTH is the number of bytes left to send. */
5465 /* Create a new entry in write_queue.
5466 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5467 BUF is a pointer to the string sequence of the input_obj or a C
5468 string in case of Qt or Qnil. */
5470 static void
5471 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5472 const char *buf, ptrdiff_t len, int front)
5474 ptrdiff_t offset;
5475 Lisp_Object entry, obj;
5477 if (STRINGP (input_obj))
5479 offset = buf - SSDATA (input_obj);
5480 obj = input_obj;
5482 else
5484 offset = 0;
5485 obj = make_unibyte_string (buf, len);
5488 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5490 if (front)
5491 pset_write_queue (p, Fcons (entry, p->write_queue));
5492 else
5493 pset_write_queue (p, nconc2 (p->write_queue, Fcons (entry, Qnil)));
5496 /* Remove the first element in the write_queue of process P, put its
5497 contents in OBJ, BUF and LEN, and return non-zero. If the
5498 write_queue is empty, return zero. */
5500 static int
5501 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5502 const char **buf, ptrdiff_t *len)
5504 Lisp_Object entry, offset_length;
5505 ptrdiff_t offset;
5507 if (NILP (p->write_queue))
5508 return 0;
5510 entry = XCAR (p->write_queue);
5511 pset_write_queue (p, XCDR (p->write_queue));
5513 *obj = XCAR (entry);
5514 offset_length = XCDR (entry);
5516 *len = XINT (XCDR (offset_length));
5517 offset = XINT (XCAR (offset_length));
5518 *buf = SSDATA (*obj) + offset;
5520 return 1;
5523 /* Send some data to process PROC.
5524 BUF is the beginning of the data; LEN is the number of characters.
5525 OBJECT is the Lisp object that the data comes from. If OBJECT is
5526 nil or t, it means that the data comes from C string.
5528 If OBJECT is not nil, the data is encoded by PROC's coding-system
5529 for encoding before it is sent.
5531 This function can evaluate Lisp code and can garbage collect. */
5533 static void
5534 send_process (volatile Lisp_Object proc, const char *volatile buf,
5535 volatile ptrdiff_t len, volatile Lisp_Object object)
5537 /* Use volatile to protect variables from being clobbered by longjmp. */
5538 struct Lisp_Process *p = XPROCESS (proc);
5539 ssize_t rv;
5540 struct coding_system *coding;
5541 void (*volatile old_sigpipe) (int);
5543 if (p->raw_status_new)
5544 update_status (p);
5545 if (! EQ (p->status, Qrun))
5546 error ("Process %s not running", SDATA (p->name));
5547 if (p->outfd < 0)
5548 error ("Output file descriptor of %s is closed", SDATA (p->name));
5550 coding = proc_encode_coding_system[p->outfd];
5551 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5553 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5554 || (BUFFERP (object)
5555 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5556 || EQ (object, Qt))
5558 pset_encode_coding_system
5559 (p, complement_process_encoding_system (p->encode_coding_system));
5560 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5562 /* The coding system for encoding was changed to raw-text
5563 because we sent a unibyte text previously. Now we are
5564 sending a multibyte text, thus we must encode it by the
5565 original coding system specified for the current process.
5567 Another reason we come here is that the coding system
5568 was just complemented and a new one was returned by
5569 complement_process_encoding_system. */
5570 setup_coding_system (p->encode_coding_system, coding);
5571 Vlast_coding_system_used = p->encode_coding_system;
5573 coding->src_multibyte = 1;
5575 else
5577 coding->src_multibyte = 0;
5578 /* For sending a unibyte text, character code conversion should
5579 not take place but EOL conversion should. So, setup raw-text
5580 or one of the subsidiary if we have not yet done it. */
5581 if (CODING_REQUIRE_ENCODING (coding))
5583 if (CODING_REQUIRE_FLUSHING (coding))
5585 /* But, before changing the coding, we must flush out data. */
5586 coding->mode |= CODING_MODE_LAST_BLOCK;
5587 send_process (proc, "", 0, Qt);
5588 coding->mode &= CODING_MODE_LAST_BLOCK;
5590 setup_coding_system (raw_text_coding_system
5591 (Vlast_coding_system_used),
5592 coding);
5593 coding->src_multibyte = 0;
5596 coding->dst_multibyte = 0;
5598 if (CODING_REQUIRE_ENCODING (coding))
5600 coding->dst_object = Qt;
5601 if (BUFFERP (object))
5603 ptrdiff_t from_byte, from, to;
5604 ptrdiff_t save_pt, save_pt_byte;
5605 struct buffer *cur = current_buffer;
5607 set_buffer_internal (XBUFFER (object));
5608 save_pt = PT, save_pt_byte = PT_BYTE;
5610 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5611 from = BYTE_TO_CHAR (from_byte);
5612 to = BYTE_TO_CHAR (from_byte + len);
5613 TEMP_SET_PT_BOTH (from, from_byte);
5614 encode_coding_object (coding, object, from, from_byte,
5615 to, from_byte + len, Qt);
5616 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5617 set_buffer_internal (cur);
5619 else if (STRINGP (object))
5621 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5622 SBYTES (object), Qt);
5624 else
5626 coding->dst_object = make_unibyte_string (buf, len);
5627 coding->produced = len;
5630 len = coding->produced;
5631 object = coding->dst_object;
5632 buf = SSDATA (object);
5635 if (pty_max_bytes == 0)
5637 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5638 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5639 if (pty_max_bytes < 0)
5640 pty_max_bytes = 250;
5641 #else
5642 pty_max_bytes = 250;
5643 #endif
5644 /* Deduct one, to leave space for the eof. */
5645 pty_max_bytes--;
5648 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5649 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5650 when returning with longjmp despite being declared volatile. */
5651 if (!setjmp (send_process_frame))
5653 p = XPROCESS (proc); /* Repair any setjmp clobbering. */
5654 process_sent_to = proc;
5656 /* If there is already data in the write_queue, put the new data
5657 in the back of queue. Otherwise, ignore it. */
5658 if (!NILP (p->write_queue))
5659 write_queue_push (p, object, buf, len, 0);
5661 do /* while !NILP (p->write_queue) */
5663 ptrdiff_t cur_len = -1;
5664 const char *cur_buf;
5665 Lisp_Object cur_object;
5667 /* If write_queue is empty, ignore it. */
5668 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5670 cur_len = len;
5671 cur_buf = buf;
5672 cur_object = object;
5675 while (cur_len > 0)
5677 /* Send this batch, using one or more write calls. */
5678 ptrdiff_t written = 0;
5679 int outfd = p->outfd;
5680 old_sigpipe = (void (*) (int)) signal (SIGPIPE, send_process_trap);
5681 #ifdef DATAGRAM_SOCKETS
5682 if (DATAGRAM_CHAN_P (outfd))
5684 rv = sendto (outfd, cur_buf, cur_len,
5685 0, datagram_address[outfd].sa,
5686 datagram_address[outfd].len);
5687 if (0 <= rv)
5688 written = rv;
5689 else if (errno == EMSGSIZE)
5691 signal (SIGPIPE, old_sigpipe);
5692 report_file_error ("sending datagram",
5693 Fcons (proc, Qnil));
5696 else
5697 #endif
5699 #ifdef HAVE_GNUTLS
5700 if (p->gnutls_p)
5701 written = emacs_gnutls_write (p, cur_buf, cur_len);
5702 else
5703 #endif
5704 written = emacs_write (outfd, cur_buf, cur_len);
5705 rv = (written ? 0 : -1);
5706 #ifdef ADAPTIVE_READ_BUFFERING
5707 if (p->read_output_delay > 0
5708 && p->adaptive_read_buffering == 1)
5710 p->read_output_delay = 0;
5711 process_output_delay_count--;
5712 p->read_output_skip = 0;
5714 #endif
5716 signal (SIGPIPE, old_sigpipe);
5718 if (rv < 0)
5720 if (0
5721 #ifdef EWOULDBLOCK
5722 || errno == EWOULDBLOCK
5723 #endif
5724 #ifdef EAGAIN
5725 || errno == EAGAIN
5726 #endif
5728 /* Buffer is full. Wait, accepting input;
5729 that may allow the program
5730 to finish doing output and read more. */
5732 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5733 /* A gross hack to work around a bug in FreeBSD.
5734 In the following sequence, read(2) returns
5735 bogus data:
5737 write(2) 1022 bytes
5738 write(2) 954 bytes, get EAGAIN
5739 read(2) 1024 bytes in process_read_output
5740 read(2) 11 bytes in process_read_output
5742 That is, read(2) returns more bytes than have
5743 ever been written successfully. The 1033 bytes
5744 read are the 1022 bytes written successfully
5745 after processing (for example with CRs added if
5746 the terminal is set up that way which it is
5747 here). The same bytes will be seen again in a
5748 later read(2), without the CRs. */
5750 if (errno == EAGAIN)
5752 int flags = FWRITE;
5753 ioctl (p->outfd, TIOCFLUSH, &flags);
5755 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5757 /* Put what we should have written in wait_queue. */
5758 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5759 wait_reading_process_output (0, 20 * 1000 * 1000,
5760 0, 0, Qnil, NULL, 0);
5761 /* Reread queue, to see what is left. */
5762 break;
5764 else
5765 /* This is a real error. */
5766 report_file_error ("writing to process", Fcons (proc, Qnil));
5768 cur_buf += written;
5769 cur_len -= written;
5772 while (!NILP (p->write_queue));
5774 else
5776 signal (SIGPIPE, old_sigpipe);
5777 proc = process_sent_to;
5778 p = XPROCESS (proc);
5779 p->raw_status_new = 0;
5780 pset_status (p, Fcons (Qexit, Fcons (make_number (256), Qnil)));
5781 p->tick = ++process_tick;
5782 deactivate_process (proc);
5783 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5787 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5788 3, 3, 0,
5789 doc: /* Send current contents of region as input to PROCESS.
5790 PROCESS may be a process, a buffer, the name of a process or buffer, or
5791 nil, indicating the current buffer's process.
5792 Called from program, takes three arguments, PROCESS, START and END.
5793 If the region is more than 500 characters long,
5794 it is sent in several bunches. This may happen even for shorter regions.
5795 Output from processes can arrive in between bunches. */)
5796 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5798 Lisp_Object proc;
5799 ptrdiff_t start1, end1;
5801 proc = get_process (process);
5802 validate_region (&start, &end);
5804 if (XINT (start) < GPT && XINT (end) > GPT)
5805 move_gap (XINT (start));
5807 start1 = CHAR_TO_BYTE (XINT (start));
5808 end1 = CHAR_TO_BYTE (XINT (end));
5809 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5810 Fcurrent_buffer ());
5812 return Qnil;
5815 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5816 2, 2, 0,
5817 doc: /* Send PROCESS the contents of STRING as input.
5818 PROCESS may be a process, a buffer, the name of a process or buffer, or
5819 nil, indicating the current buffer's process.
5820 If STRING is more than 500 characters long,
5821 it is sent in several bunches. This may happen even for shorter strings.
5822 Output from processes can arrive in between bunches. */)
5823 (Lisp_Object process, Lisp_Object string)
5825 Lisp_Object proc;
5826 CHECK_STRING (string);
5827 proc = get_process (process);
5828 send_process (proc, SSDATA (string),
5829 SBYTES (string), string);
5830 return Qnil;
5833 /* Return the foreground process group for the tty/pty that
5834 the process P uses. */
5835 static pid_t
5836 emacs_get_tty_pgrp (struct Lisp_Process *p)
5838 pid_t gid = -1;
5840 #ifdef TIOCGPGRP
5841 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5843 int fd;
5844 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5845 master side. Try the slave side. */
5846 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5848 if (fd != -1)
5850 ioctl (fd, TIOCGPGRP, &gid);
5851 emacs_close (fd);
5854 #endif /* defined (TIOCGPGRP ) */
5856 return gid;
5859 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5860 Sprocess_running_child_p, 0, 1, 0,
5861 doc: /* Return t if PROCESS has given the terminal to a child.
5862 If the operating system does not make it possible to find out,
5863 return t unconditionally. */)
5864 (Lisp_Object process)
5866 /* Initialize in case ioctl doesn't exist or gives an error,
5867 in a way that will cause returning t. */
5868 pid_t gid;
5869 Lisp_Object proc;
5870 struct Lisp_Process *p;
5872 proc = get_process (process);
5873 p = XPROCESS (proc);
5875 if (!EQ (p->type, Qreal))
5876 error ("Process %s is not a subprocess",
5877 SDATA (p->name));
5878 if (p->infd < 0)
5879 error ("Process %s is not active",
5880 SDATA (p->name));
5882 gid = emacs_get_tty_pgrp (p);
5884 if (gid == p->pid)
5885 return Qnil;
5886 return Qt;
5889 /* send a signal number SIGNO to PROCESS.
5890 If CURRENT_GROUP is t, that means send to the process group
5891 that currently owns the terminal being used to communicate with PROCESS.
5892 This is used for various commands in shell mode.
5893 If CURRENT_GROUP is lambda, that means send to the process group
5894 that currently owns the terminal, but only if it is NOT the shell itself.
5896 If NOMSG is zero, insert signal-announcements into process's buffers
5897 right away.
5899 If we can, we try to signal PROCESS by sending control characters
5900 down the pty. This allows us to signal inferiors who have changed
5901 their uid, for which killpg would return an EPERM error. */
5903 static void
5904 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5905 int nomsg)
5907 Lisp_Object proc;
5908 register struct Lisp_Process *p;
5909 pid_t gid;
5910 int no_pgrp = 0;
5912 proc = get_process (process);
5913 p = XPROCESS (proc);
5915 if (!EQ (p->type, Qreal))
5916 error ("Process %s is not a subprocess",
5917 SDATA (p->name));
5918 if (p->infd < 0)
5919 error ("Process %s is not active",
5920 SDATA (p->name));
5922 if (!p->pty_flag)
5923 current_group = Qnil;
5925 /* If we are using pgrps, get a pgrp number and make it negative. */
5926 if (NILP (current_group))
5927 /* Send the signal to the shell's process group. */
5928 gid = p->pid;
5929 else
5931 #ifdef SIGNALS_VIA_CHARACTERS
5932 /* If possible, send signals to the entire pgrp
5933 by sending an input character to it. */
5935 struct termios t;
5936 cc_t *sig_char = NULL;
5938 tcgetattr (p->infd, &t);
5940 switch (signo)
5942 case SIGINT:
5943 sig_char = &t.c_cc[VINTR];
5944 break;
5946 case SIGQUIT:
5947 sig_char = &t.c_cc[VQUIT];
5948 break;
5950 case SIGTSTP:
5951 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5952 sig_char = &t.c_cc[VSWTCH];
5953 #else
5954 sig_char = &t.c_cc[VSUSP];
5955 #endif
5956 break;
5959 if (sig_char && *sig_char != CDISABLE)
5961 send_process (proc, (char *) sig_char, 1, Qnil);
5962 return;
5964 /* If we can't send the signal with a character,
5965 fall through and send it another way. */
5967 /* The code above may fall through if it can't
5968 handle the signal. */
5969 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5971 #ifdef TIOCGPGRP
5972 /* Get the current pgrp using the tty itself, if we have that.
5973 Otherwise, use the pty to get the pgrp.
5974 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5975 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5976 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5977 His patch indicates that if TIOCGPGRP returns an error, then
5978 we should just assume that p->pid is also the process group id. */
5980 gid = emacs_get_tty_pgrp (p);
5982 if (gid == -1)
5983 /* If we can't get the information, assume
5984 the shell owns the tty. */
5985 gid = p->pid;
5987 /* It is not clear whether anything really can set GID to -1.
5988 Perhaps on some system one of those ioctls can or could do so.
5989 Or perhaps this is vestigial. */
5990 if (gid == -1)
5991 no_pgrp = 1;
5992 #else /* ! defined (TIOCGPGRP ) */
5993 /* Can't select pgrps on this system, so we know that
5994 the child itself heads the pgrp. */
5995 gid = p->pid;
5996 #endif /* ! defined (TIOCGPGRP ) */
5998 /* If current_group is lambda, and the shell owns the terminal,
5999 don't send any signal. */
6000 if (EQ (current_group, Qlambda) && gid == p->pid)
6001 return;
6004 switch (signo)
6006 #ifdef SIGCONT
6007 case SIGCONT:
6008 p->raw_status_new = 0;
6009 pset_status (p, Qrun);
6010 p->tick = ++process_tick;
6011 if (!nomsg)
6013 status_notify (NULL);
6014 redisplay_preserve_echo_area (13);
6016 break;
6017 #endif /* ! defined (SIGCONT) */
6018 case SIGINT:
6019 case SIGQUIT:
6020 case SIGKILL:
6021 flush_pending_output (p->infd);
6022 break;
6025 /* If we don't have process groups, send the signal to the immediate
6026 subprocess. That isn't really right, but it's better than any
6027 obvious alternative. */
6028 if (no_pgrp)
6030 kill (p->pid, signo);
6031 return;
6034 /* gid may be a pid, or minus a pgrp's number */
6035 #ifdef TIOCSIGSEND
6036 if (!NILP (current_group))
6038 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6039 EMACS_KILLPG (gid, signo);
6041 else
6043 gid = - p->pid;
6044 kill (gid, signo);
6046 #else /* ! defined (TIOCSIGSEND) */
6047 EMACS_KILLPG (gid, signo);
6048 #endif /* ! defined (TIOCSIGSEND) */
6051 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6052 doc: /* Interrupt process PROCESS.
6053 PROCESS may be a process, a buffer, or the name of a process or buffer.
6054 No arg or nil means current buffer's process.
6055 Second arg CURRENT-GROUP non-nil means send signal to
6056 the current process-group of the process's controlling terminal
6057 rather than to the process's own process group.
6058 If the process is a shell, this means interrupt current subjob
6059 rather than the shell.
6061 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6062 don't send the signal. */)
6063 (Lisp_Object process, Lisp_Object current_group)
6065 process_send_signal (process, SIGINT, current_group, 0);
6066 return process;
6069 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6070 doc: /* Kill process PROCESS. May be process or name of one.
6071 See function `interrupt-process' for more details on usage. */)
6072 (Lisp_Object process, Lisp_Object current_group)
6074 process_send_signal (process, SIGKILL, current_group, 0);
6075 return process;
6078 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6079 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6080 See function `interrupt-process' for more details on usage. */)
6081 (Lisp_Object process, Lisp_Object current_group)
6083 process_send_signal (process, SIGQUIT, current_group, 0);
6084 return process;
6087 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6088 doc: /* Stop process PROCESS. May be process or name of one.
6089 See function `interrupt-process' for more details on usage.
6090 If PROCESS is a network or serial process, inhibit handling of incoming
6091 traffic. */)
6092 (Lisp_Object process, Lisp_Object current_group)
6094 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6096 struct Lisp_Process *p;
6098 p = XPROCESS (process);
6099 if (NILP (p->command)
6100 && p->infd >= 0)
6102 FD_CLR (p->infd, &input_wait_mask);
6103 FD_CLR (p->infd, &non_keyboard_wait_mask);
6105 pset_command (p, Qt);
6106 return process;
6108 #ifndef SIGTSTP
6109 error ("No SIGTSTP support");
6110 #else
6111 process_send_signal (process, SIGTSTP, current_group, 0);
6112 #endif
6113 return process;
6116 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6117 doc: /* Continue process PROCESS. May be process or name of one.
6118 See function `interrupt-process' for more details on usage.
6119 If PROCESS is a network or serial process, resume handling of incoming
6120 traffic. */)
6121 (Lisp_Object process, Lisp_Object current_group)
6123 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6125 struct Lisp_Process *p;
6127 p = XPROCESS (process);
6128 if (EQ (p->command, Qt)
6129 && p->infd >= 0
6130 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6132 FD_SET (p->infd, &input_wait_mask);
6133 FD_SET (p->infd, &non_keyboard_wait_mask);
6134 #ifdef WINDOWSNT
6135 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6136 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6137 #else /* not WINDOWSNT */
6138 tcflush (p->infd, TCIFLUSH);
6139 #endif /* not WINDOWSNT */
6141 pset_command (p, Qnil);
6142 return process;
6144 #ifdef SIGCONT
6145 process_send_signal (process, SIGCONT, current_group, 0);
6146 #else
6147 error ("No SIGCONT support");
6148 #endif
6149 return process;
6152 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6153 2, 2, "sProcess (name or number): \nnSignal code: ",
6154 doc: /* Send PROCESS the signal with code SIGCODE.
6155 PROCESS may also be a number specifying the process id of the
6156 process to signal; in this case, the process need not be a child of
6157 this Emacs.
6158 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6159 (Lisp_Object process, Lisp_Object sigcode)
6161 pid_t pid;
6163 if (STRINGP (process))
6165 Lisp_Object tem = Fget_process (process);
6166 if (NILP (tem))
6168 Lisp_Object process_number =
6169 string_to_number (SSDATA (process), 10, 1);
6170 if (INTEGERP (process_number) || FLOATP (process_number))
6171 tem = process_number;
6173 process = tem;
6175 else if (!NUMBERP (process))
6176 process = get_process (process);
6178 if (NILP (process))
6179 return process;
6181 if (NUMBERP (process))
6182 CONS_TO_INTEGER (process, pid_t, pid);
6183 else
6185 CHECK_PROCESS (process);
6186 pid = XPROCESS (process)->pid;
6187 if (pid <= 0)
6188 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6191 #define parse_signal(NAME, VALUE) \
6192 else if (!xstrcasecmp (name, NAME)) \
6193 XSETINT (sigcode, VALUE)
6195 if (INTEGERP (sigcode))
6196 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6197 else
6199 char *name;
6201 CHECK_SYMBOL (sigcode);
6202 name = SSDATA (SYMBOL_NAME (sigcode));
6204 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6205 name += 3;
6207 if (0)
6209 #ifdef SIGUSR1
6210 parse_signal ("usr1", SIGUSR1);
6211 #endif
6212 #ifdef SIGUSR2
6213 parse_signal ("usr2", SIGUSR2);
6214 #endif
6215 #ifdef SIGTERM
6216 parse_signal ("term", SIGTERM);
6217 #endif
6218 #ifdef SIGHUP
6219 parse_signal ("hup", SIGHUP);
6220 #endif
6221 #ifdef SIGINT
6222 parse_signal ("int", SIGINT);
6223 #endif
6224 #ifdef SIGQUIT
6225 parse_signal ("quit", SIGQUIT);
6226 #endif
6227 #ifdef SIGILL
6228 parse_signal ("ill", SIGILL);
6229 #endif
6230 #ifdef SIGABRT
6231 parse_signal ("abrt", SIGABRT);
6232 #endif
6233 #ifdef SIGEMT
6234 parse_signal ("emt", SIGEMT);
6235 #endif
6236 #ifdef SIGKILL
6237 parse_signal ("kill", SIGKILL);
6238 #endif
6239 #ifdef SIGFPE
6240 parse_signal ("fpe", SIGFPE);
6241 #endif
6242 #ifdef SIGBUS
6243 parse_signal ("bus", SIGBUS);
6244 #endif
6245 #ifdef SIGSEGV
6246 parse_signal ("segv", SIGSEGV);
6247 #endif
6248 #ifdef SIGSYS
6249 parse_signal ("sys", SIGSYS);
6250 #endif
6251 #ifdef SIGPIPE
6252 parse_signal ("pipe", SIGPIPE);
6253 #endif
6254 #ifdef SIGALRM
6255 parse_signal ("alrm", SIGALRM);
6256 #endif
6257 #ifdef SIGURG
6258 parse_signal ("urg", SIGURG);
6259 #endif
6260 #ifdef SIGSTOP
6261 parse_signal ("stop", SIGSTOP);
6262 #endif
6263 #ifdef SIGTSTP
6264 parse_signal ("tstp", SIGTSTP);
6265 #endif
6266 #ifdef SIGCONT
6267 parse_signal ("cont", SIGCONT);
6268 #endif
6269 #ifdef SIGCHLD
6270 parse_signal ("chld", SIGCHLD);
6271 #endif
6272 #ifdef SIGTTIN
6273 parse_signal ("ttin", SIGTTIN);
6274 #endif
6275 #ifdef SIGTTOU
6276 parse_signal ("ttou", SIGTTOU);
6277 #endif
6278 #ifdef SIGIO
6279 parse_signal ("io", SIGIO);
6280 #endif
6281 #ifdef SIGXCPU
6282 parse_signal ("xcpu", SIGXCPU);
6283 #endif
6284 #ifdef SIGXFSZ
6285 parse_signal ("xfsz", SIGXFSZ);
6286 #endif
6287 #ifdef SIGVTALRM
6288 parse_signal ("vtalrm", SIGVTALRM);
6289 #endif
6290 #ifdef SIGPROF
6291 parse_signal ("prof", SIGPROF);
6292 #endif
6293 #ifdef SIGWINCH
6294 parse_signal ("winch", SIGWINCH);
6295 #endif
6296 #ifdef SIGINFO
6297 parse_signal ("info", SIGINFO);
6298 #endif
6299 else
6300 error ("Undefined signal name %s", name);
6303 #undef parse_signal
6305 return make_number (kill (pid, XINT (sigcode)));
6308 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6309 doc: /* Make PROCESS see end-of-file in its input.
6310 EOF comes after any text already sent to it.
6311 PROCESS may be a process, a buffer, the name of a process or buffer, or
6312 nil, indicating the current buffer's process.
6313 If PROCESS is a network connection, or is a process communicating
6314 through a pipe (as opposed to a pty), then you cannot send any more
6315 text to PROCESS after you call this function.
6316 If PROCESS is a serial process, wait until all output written to the
6317 process has been transmitted to the serial port. */)
6318 (Lisp_Object process)
6320 Lisp_Object proc;
6321 struct coding_system *coding;
6323 if (DATAGRAM_CONN_P (process))
6324 return process;
6326 proc = get_process (process);
6327 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6329 /* Make sure the process is really alive. */
6330 if (XPROCESS (proc)->raw_status_new)
6331 update_status (XPROCESS (proc));
6332 if (! EQ (XPROCESS (proc)->status, Qrun))
6333 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6335 if (CODING_REQUIRE_FLUSHING (coding))
6337 coding->mode |= CODING_MODE_LAST_BLOCK;
6338 send_process (proc, "", 0, Qnil);
6341 if (XPROCESS (proc)->pty_flag)
6342 send_process (proc, "\004", 1, Qnil);
6343 else if (EQ (XPROCESS (proc)->type, Qserial))
6345 #ifndef WINDOWSNT
6346 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6347 error ("tcdrain() failed: %s", emacs_strerror (errno));
6348 #endif /* not WINDOWSNT */
6349 /* Do nothing on Windows because writes are blocking. */
6351 else
6353 int old_outfd, new_outfd;
6355 #ifdef HAVE_SHUTDOWN
6356 /* If this is a network connection, or socketpair is used
6357 for communication with the subprocess, call shutdown to cause EOF.
6358 (In some old system, shutdown to socketpair doesn't work.
6359 Then we just can't win.) */
6360 if (EQ (XPROCESS (proc)->type, Qnetwork)
6361 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6362 shutdown (XPROCESS (proc)->outfd, 1);
6363 /* In case of socketpair, outfd == infd, so don't close it. */
6364 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6365 emacs_close (XPROCESS (proc)->outfd);
6366 #else /* not HAVE_SHUTDOWN */
6367 emacs_close (XPROCESS (proc)->outfd);
6368 #endif /* not HAVE_SHUTDOWN */
6369 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6370 if (new_outfd < 0)
6371 abort ();
6372 old_outfd = XPROCESS (proc)->outfd;
6374 if (!proc_encode_coding_system[new_outfd])
6375 proc_encode_coding_system[new_outfd]
6376 = xmalloc (sizeof (struct coding_system));
6377 memcpy (proc_encode_coding_system[new_outfd],
6378 proc_encode_coding_system[old_outfd],
6379 sizeof (struct coding_system));
6380 memset (proc_encode_coding_system[old_outfd], 0,
6381 sizeof (struct coding_system));
6383 XPROCESS (proc)->outfd = new_outfd;
6385 return process;
6388 /* On receipt of a signal that a child status has changed, loop asking
6389 about children with changed statuses until the system says there
6390 are no more.
6392 All we do is change the status; we do not run sentinels or print
6393 notifications. That is saved for the next time keyboard input is
6394 done, in order to avoid timing errors.
6396 ** WARNING: this can be called during garbage collection.
6397 Therefore, it must not be fooled by the presence of mark bits in
6398 Lisp objects.
6400 ** USG WARNING: Although it is not obvious from the documentation
6401 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6402 signal() before executing at least one wait(), otherwise the
6403 handler will be called again, resulting in an infinite loop. The
6404 relevant portion of the documentation reads "SIGCLD signals will be
6405 queued and the signal-catching function will be continually
6406 reentered until the queue is empty". Invoking signal() causes the
6407 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6408 Inc.
6410 ** Malloc WARNING: This should never call malloc either directly or
6411 indirectly; if it does, that is a bug */
6413 #ifdef SIGCHLD
6414 static void
6415 sigchld_handler (int signo)
6417 int old_errno = errno;
6418 Lisp_Object proc;
6419 struct Lisp_Process *p;
6421 SIGNAL_THREAD_CHECK (signo);
6423 while (1)
6425 pid_t pid;
6426 int w;
6427 Lisp_Object tail;
6429 #ifdef WNOHANG
6430 #ifndef WUNTRACED
6431 #define WUNTRACED 0
6432 #endif /* no WUNTRACED */
6433 /* Keep trying to get a status until we get a definitive result. */
6436 errno = 0;
6437 pid = waitpid (-1, &w, WNOHANG | WUNTRACED);
6439 while (pid < 0 && errno == EINTR);
6441 if (pid <= 0)
6443 /* PID == 0 means no processes found, PID == -1 means a real
6444 failure. We have done all our job, so return. */
6446 errno = old_errno;
6447 return;
6449 #else
6450 pid = wait (&w);
6451 #endif /* no WNOHANG */
6453 /* Find the process that signaled us, and record its status. */
6455 /* The process can have been deleted by Fdelete_process. */
6456 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6458 Lisp_Object xpid = XCAR (tail);
6459 if ((INTEGERP (xpid) && pid == XINT (xpid))
6460 || (FLOATP (xpid) && pid == XFLOAT_DATA (xpid)))
6462 XSETCAR (tail, Qnil);
6463 goto sigchld_end_of_loop;
6467 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6468 p = 0;
6469 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6471 proc = XCDR (XCAR (tail));
6472 p = XPROCESS (proc);
6473 if (EQ (p->type, Qreal) && p->pid == pid)
6474 break;
6475 p = 0;
6478 /* Look for an asynchronous process whose pid hasn't been filled
6479 in yet. */
6480 if (p == 0)
6481 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6483 proc = XCDR (XCAR (tail));
6484 p = XPROCESS (proc);
6485 if (p->pid == -1)
6486 break;
6487 p = 0;
6490 /* Change the status of the process that was found. */
6491 if (p != 0)
6493 int clear_desc_flag = 0;
6495 p->tick = ++process_tick;
6496 p->raw_status = w;
6497 p->raw_status_new = 1;
6499 /* If process has terminated, stop waiting for its output. */
6500 if ((WIFSIGNALED (w) || WIFEXITED (w))
6501 && p->infd >= 0)
6502 clear_desc_flag = 1;
6504 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6505 if (clear_desc_flag)
6507 FD_CLR (p->infd, &input_wait_mask);
6508 FD_CLR (p->infd, &non_keyboard_wait_mask);
6511 /* Tell wait_reading_process_output that it needs to wake up and
6512 look around. */
6513 if (input_available_clear_time)
6514 *input_available_clear_time = make_emacs_time (0, 0);
6517 /* There was no asynchronous process found for that pid: we have
6518 a synchronous process. */
6519 else
6521 synch_process_alive = 0;
6523 /* Report the status of the synchronous process. */
6524 if (WIFEXITED (w))
6525 synch_process_retcode = WEXITSTATUS (w);
6526 else if (WIFSIGNALED (w))
6527 synch_process_termsig = WTERMSIG (w);
6529 /* Tell wait_reading_process_output that it needs to wake up and
6530 look around. */
6531 if (input_available_clear_time)
6532 *input_available_clear_time = make_emacs_time (0, 0);
6535 sigchld_end_of_loop:
6538 /* On some systems, we must return right away.
6539 If any more processes want to signal us, we will
6540 get another signal.
6541 Otherwise (on systems that have WNOHANG), loop around
6542 to use up all the processes that have something to tell us. */
6543 #if (defined WINDOWSNT \
6544 || (defined USG && !defined GNU_LINUX \
6545 && !(defined HPUX && defined WNOHANG)))
6546 errno = old_errno;
6547 return;
6548 #endif /* USG, but not HPUX with WNOHANG */
6551 #endif /* SIGCHLD */
6554 static Lisp_Object
6555 exec_sentinel_unwind (Lisp_Object data)
6557 pset_sentinel (XPROCESS (XCAR (data)), XCDR (data));
6558 return Qnil;
6561 static Lisp_Object
6562 exec_sentinel_error_handler (Lisp_Object error_val)
6564 cmd_error_internal (error_val, "error in process sentinel: ");
6565 Vinhibit_quit = Qt;
6566 update_echo_area ();
6567 Fsleep_for (make_number (2), Qnil);
6568 return Qt;
6571 static void
6572 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6574 Lisp_Object sentinel, odeactivate;
6575 register struct Lisp_Process *p = XPROCESS (proc);
6576 ptrdiff_t count = SPECPDL_INDEX ();
6577 int outer_running_asynch_code = running_asynch_code;
6578 int waiting = waiting_for_user_input_p;
6580 if (inhibit_sentinels)
6581 return;
6583 /* No need to gcpro these, because all we do with them later
6584 is test them for EQness, and none of them should be a string. */
6585 odeactivate = Vdeactivate_mark;
6586 #if 0
6587 Lisp_Object obuffer, okeymap;
6588 XSETBUFFER (obuffer, current_buffer);
6589 okeymap = BVAR (current_buffer, keymap);
6590 #endif
6592 /* There's no good reason to let sentinels change the current
6593 buffer, and many callers of accept-process-output, sit-for, and
6594 friends don't expect current-buffer to be changed from under them. */
6595 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6597 sentinel = p->sentinel;
6598 if (NILP (sentinel))
6599 return;
6601 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6602 assure that it gets restored no matter how the sentinel exits. */
6603 pset_sentinel (p, Qnil);
6604 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6605 /* Inhibit quit so that random quits don't screw up a running filter. */
6606 specbind (Qinhibit_quit, Qt);
6607 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6609 /* In case we get recursively called,
6610 and we already saved the match data nonrecursively,
6611 save the same match data in safely recursive fashion. */
6612 if (outer_running_asynch_code)
6614 Lisp_Object tem;
6615 tem = Fmatch_data (Qnil, Qnil, Qnil);
6616 restore_search_regs ();
6617 record_unwind_save_match_data ();
6618 Fset_match_data (tem, Qt);
6621 /* For speed, if a search happens within this code,
6622 save the match data in a special nonrecursive fashion. */
6623 running_asynch_code = 1;
6625 internal_condition_case_1 (read_process_output_call,
6626 Fcons (sentinel,
6627 Fcons (proc, Fcons (reason, Qnil))),
6628 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6629 exec_sentinel_error_handler);
6631 /* If we saved the match data nonrecursively, restore it now. */
6632 restore_search_regs ();
6633 running_asynch_code = outer_running_asynch_code;
6635 Vdeactivate_mark = odeactivate;
6637 /* Restore waiting_for_user_input_p as it was
6638 when we were called, in case the filter clobbered it. */
6639 waiting_for_user_input_p = waiting;
6641 #if 0
6642 if (! EQ (Fcurrent_buffer (), obuffer)
6643 || ! EQ (current_buffer->keymap, okeymap))
6644 #endif
6645 /* But do it only if the caller is actually going to read events.
6646 Otherwise there's no need to make him wake up, and it could
6647 cause trouble (for example it would make sit_for return). */
6648 if (waiting_for_user_input_p == -1)
6649 record_asynch_buffer_change ();
6651 unbind_to (count, Qnil);
6654 /* Report all recent events of a change in process status
6655 (either run the sentinel or output a message).
6656 This is usually done while Emacs is waiting for keyboard input
6657 but can be done at other times. */
6659 static void
6660 status_notify (struct Lisp_Process *deleting_process)
6662 register Lisp_Object proc, buffer;
6663 Lisp_Object tail, msg;
6664 struct gcpro gcpro1, gcpro2;
6666 tail = Qnil;
6667 msg = Qnil;
6668 /* We need to gcpro tail; if read_process_output calls a filter
6669 which deletes a process and removes the cons to which tail points
6670 from Vprocess_alist, and then causes a GC, tail is an unprotected
6671 reference. */
6672 GCPRO2 (tail, msg);
6674 /* Set this now, so that if new processes are created by sentinels
6675 that we run, we get called again to handle their status changes. */
6676 update_tick = process_tick;
6678 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6680 Lisp_Object symbol;
6681 register struct Lisp_Process *p;
6683 proc = Fcdr (XCAR (tail));
6684 p = XPROCESS (proc);
6686 if (p->tick != p->update_tick)
6688 p->update_tick = p->tick;
6690 /* If process is still active, read any output that remains. */
6691 while (! EQ (p->filter, Qt)
6692 && ! EQ (p->status, Qconnect)
6693 && ! EQ (p->status, Qlisten)
6694 /* Network or serial process not stopped: */
6695 && ! EQ (p->command, Qt)
6696 && p->infd >= 0
6697 && p != deleting_process
6698 && read_process_output (proc, p->infd) > 0);
6700 buffer = p->buffer;
6702 /* Get the text to use for the message. */
6703 if (p->raw_status_new)
6704 update_status (p);
6705 msg = status_message (p);
6707 /* If process is terminated, deactivate it or delete it. */
6708 symbol = p->status;
6709 if (CONSP (p->status))
6710 symbol = XCAR (p->status);
6712 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6713 || EQ (symbol, Qclosed))
6715 if (delete_exited_processes)
6716 remove_process (proc);
6717 else
6718 deactivate_process (proc);
6721 /* The actions above may have further incremented p->tick.
6722 So set p->update_tick again
6723 so that an error in the sentinel will not cause
6724 this code to be run again. */
6725 p->update_tick = p->tick;
6726 /* Now output the message suitably. */
6727 if (!NILP (p->sentinel))
6728 exec_sentinel (proc, msg);
6729 /* Don't bother with a message in the buffer
6730 when a process becomes runnable. */
6731 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6733 Lisp_Object tem;
6734 struct buffer *old = current_buffer;
6735 ptrdiff_t opoint, opoint_byte;
6736 ptrdiff_t before, before_byte;
6738 /* Avoid error if buffer is deleted
6739 (probably that's why the process is dead, too) */
6740 if (NILP (BVAR (XBUFFER (buffer), name)))
6741 continue;
6742 Fset_buffer (buffer);
6744 opoint = PT;
6745 opoint_byte = PT_BYTE;
6746 /* Insert new output into buffer
6747 at the current end-of-output marker,
6748 thus preserving logical ordering of input and output. */
6749 if (XMARKER (p->mark)->buffer)
6750 Fgoto_char (p->mark);
6751 else
6752 SET_PT_BOTH (ZV, ZV_BYTE);
6754 before = PT;
6755 before_byte = PT_BYTE;
6757 tem = BVAR (current_buffer, read_only);
6758 BSET (current_buffer, read_only, Qnil);
6759 insert_string ("\nProcess ");
6760 { /* FIXME: temporary kludge */
6761 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6762 insert_string (" ");
6763 Finsert (1, &msg);
6764 BSET (current_buffer, read_only, tem);
6765 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6767 if (opoint >= before)
6768 SET_PT_BOTH (opoint + (PT - before),
6769 opoint_byte + (PT_BYTE - before_byte));
6770 else
6771 SET_PT_BOTH (opoint, opoint_byte);
6773 set_buffer_internal (old);
6776 } /* end for */
6778 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6779 UNGCPRO;
6783 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6784 Sset_process_coding_system, 1, 3, 0,
6785 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6786 DECODING will be used to decode subprocess output and ENCODING to
6787 encode subprocess input. */)
6788 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6790 register struct Lisp_Process *p;
6792 CHECK_PROCESS (process);
6793 p = XPROCESS (process);
6794 if (p->infd < 0)
6795 error ("Input file descriptor of %s closed", SDATA (p->name));
6796 if (p->outfd < 0)
6797 error ("Output file descriptor of %s closed", SDATA (p->name));
6798 Fcheck_coding_system (decoding);
6799 Fcheck_coding_system (encoding);
6800 encoding = coding_inherit_eol_type (encoding, Qnil);
6801 pset_decode_coding_system (p, decoding);
6802 pset_encode_coding_system (p, encoding);
6803 setup_process_coding_systems (process);
6805 return Qnil;
6808 DEFUN ("process-coding-system",
6809 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6810 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6811 (register Lisp_Object process)
6813 CHECK_PROCESS (process);
6814 return Fcons (XPROCESS (process)->decode_coding_system,
6815 XPROCESS (process)->encode_coding_system);
6818 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6819 Sset_process_filter_multibyte, 2, 2, 0,
6820 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6821 If FLAG is non-nil, the filter is given multibyte strings.
6822 If FLAG is nil, the filter is given unibyte strings. In this case,
6823 all character code conversion except for end-of-line conversion is
6824 suppressed. */)
6825 (Lisp_Object process, Lisp_Object flag)
6827 register struct Lisp_Process *p;
6829 CHECK_PROCESS (process);
6830 p = XPROCESS (process);
6831 if (NILP (flag))
6832 pset_decode_coding_system
6833 (p, raw_text_coding_system (p->decode_coding_system));
6834 setup_process_coding_systems (process);
6836 return Qnil;
6839 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6840 Sprocess_filter_multibyte_p, 1, 1, 0,
6841 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6842 (Lisp_Object process)
6844 register struct Lisp_Process *p;
6845 struct coding_system *coding;
6847 CHECK_PROCESS (process);
6848 p = XPROCESS (process);
6849 coding = proc_decode_coding_system[p->infd];
6850 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6856 # ifdef HAVE_GPM
6858 void
6859 add_gpm_wait_descriptor (int desc)
6861 add_keyboard_wait_descriptor (desc);
6864 void
6865 delete_gpm_wait_descriptor (int desc)
6867 delete_keyboard_wait_descriptor (desc);
6870 # endif
6872 # ifdef SIGIO
6874 /* Return nonzero if *MASK has a bit set
6875 that corresponds to one of the keyboard input descriptors. */
6877 static int
6878 keyboard_bit_set (fd_set *mask)
6880 int fd;
6882 for (fd = 0; fd <= max_input_desc; fd++)
6883 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6884 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6885 return 1;
6887 return 0;
6889 # endif
6891 #else /* not subprocesses */
6893 /* Defined on msdos.c. */
6894 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6895 EMACS_TIME *, void *);
6897 /* Implementation of wait_reading_process_output, assuming that there
6898 are no subprocesses. Used only by the MS-DOS build.
6900 Wait for timeout to elapse and/or keyboard input to be available.
6902 TIME_LIMIT is:
6903 timeout in seconds
6904 If negative, gobble data immediately available but don't wait for any.
6906 NSECS is:
6907 an additional duration to wait, measured in nanoseconds
6908 If TIME_LIMIT is zero, then:
6909 If NSECS == 0, there is no limit.
6910 If NSECS > 0, the timeout consists of NSECS only.
6911 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6913 READ_KBD is:
6914 0 to ignore keyboard input, or
6915 1 to return when input is available, or
6916 -1 means caller will actually read the input, so don't throw to
6917 the quit handler.
6919 see full version for other parameters. We know that wait_proc will
6920 always be NULL, since `subprocesses' isn't defined.
6922 DO_DISPLAY != 0 means redisplay should be done to show subprocess
6923 output that arrives.
6925 Return true if we received input from any process. */
6928 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6929 int do_display,
6930 Lisp_Object wait_for_cell,
6931 struct Lisp_Process *wait_proc, int just_wait_proc)
6933 register int nfds;
6934 EMACS_TIME end_time, timeout;
6936 if (time_limit < 0)
6938 time_limit = 0;
6939 nsecs = -1;
6941 else if (TYPE_MAXIMUM (time_t) < time_limit)
6942 time_limit = TYPE_MAXIMUM (time_t);
6944 /* What does time_limit really mean? */
6945 if (time_limit || 0 < nsecs)
6947 timeout = make_emacs_time (time_limit, nsecs);
6948 end_time = add_emacs_time (current_emacs_time (), timeout);
6951 /* Turn off periodic alarms (in case they are in use)
6952 and then turn off any other atimers,
6953 because the select emulator uses alarms. */
6954 stop_polling ();
6955 turn_on_atimers (0);
6957 while (1)
6959 int timeout_reduced_for_timers = 0;
6960 SELECT_TYPE waitchannels;
6961 int xerrno;
6963 /* If calling from keyboard input, do not quit
6964 since we want to return C-g as an input character.
6965 Otherwise, do pending quit if requested. */
6966 if (read_kbd >= 0)
6967 QUIT;
6969 /* Exit now if the cell we're waiting for became non-nil. */
6970 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6971 break;
6973 /* Compute time from now till when time limit is up */
6974 /* Exit if already run out */
6975 if (nsecs < 0)
6977 /* A negative timeout means
6978 gobble output available now
6979 but don't wait at all. */
6981 timeout = make_emacs_time (0, 0);
6983 else if (time_limit || 0 < nsecs)
6985 EMACS_TIME now = current_emacs_time ();
6986 if (EMACS_TIME_LE (end_time, now))
6987 break;
6988 timeout = sub_emacs_time (end_time, now);
6990 else
6992 timeout = make_emacs_time (100000, 0);
6995 /* If our caller will not immediately handle keyboard events,
6996 run timer events directly.
6997 (Callers that will immediately read keyboard events
6998 call timer_delay on their own.) */
6999 if (NILP (wait_for_cell))
7001 EMACS_TIME timer_delay;
7005 int old_timers_run = timers_run;
7006 timer_delay = timer_check ();
7007 if (timers_run != old_timers_run && do_display)
7008 /* We must retry, since a timer may have requeued itself
7009 and that could alter the time delay. */
7010 redisplay_preserve_echo_area (14);
7011 else
7012 break;
7014 while (!detect_input_pending ());
7016 /* If there is unread keyboard input, also return. */
7017 if (read_kbd != 0
7018 && requeued_events_pending_p ())
7019 break;
7021 if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
7023 if (EMACS_TIME_LT (timer_delay, timeout))
7025 timeout = timer_delay;
7026 timeout_reduced_for_timers = 1;
7031 /* Cause C-g and alarm signals to take immediate action,
7032 and cause input available signals to zero out timeout. */
7033 if (read_kbd < 0)
7034 set_waiting_for_input (&timeout);
7036 /* If a frame has been newly mapped and needs updating,
7037 reprocess its display stuff. */
7038 if (frame_garbaged && do_display)
7040 clear_waiting_for_input ();
7041 redisplay_preserve_echo_area (15);
7042 if (read_kbd < 0)
7043 set_waiting_for_input (&timeout);
7046 /* Wait till there is something to do. */
7047 FD_ZERO (&waitchannels);
7048 if (read_kbd && detect_input_pending ())
7049 nfds = 0;
7050 else
7052 if (read_kbd || !NILP (wait_for_cell))
7053 FD_SET (0, &waitchannels);
7054 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7057 xerrno = errno;
7059 /* Make C-g and alarm signals set flags again */
7060 clear_waiting_for_input ();
7062 /* If we woke up due to SIGWINCH, actually change size now. */
7063 do_pending_window_change (0);
7065 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7066 /* We waited the full specified time, so return now. */
7067 break;
7069 if (nfds == -1)
7071 /* If the system call was interrupted, then go around the
7072 loop again. */
7073 if (xerrno == EINTR)
7074 FD_ZERO (&waitchannels);
7075 else
7076 error ("select error: %s", emacs_strerror (xerrno));
7079 /* Check for keyboard input */
7081 if (read_kbd
7082 && detect_input_pending_run_timers (do_display))
7084 swallow_events (do_display);
7085 if (detect_input_pending_run_timers (do_display))
7086 break;
7089 /* If there is unread keyboard input, also return. */
7090 if (read_kbd
7091 && requeued_events_pending_p ())
7092 break;
7094 /* If wait_for_cell. check for keyboard input
7095 but don't run any timers.
7096 ??? (It seems wrong to me to check for keyboard
7097 input at all when wait_for_cell, but the code
7098 has been this way since July 1994.
7099 Try changing this after version 19.31.) */
7100 if (! NILP (wait_for_cell)
7101 && detect_input_pending ())
7103 swallow_events (do_display);
7104 if (detect_input_pending ())
7105 break;
7108 /* Exit now if the cell we're waiting for became non-nil. */
7109 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7110 break;
7113 start_polling ();
7115 return 0;
7118 #endif /* not subprocesses */
7120 /* The following functions are needed even if async subprocesses are
7121 not supported. Some of them are no-op stubs in that case. */
7123 /* Add DESC to the set of keyboard input descriptors. */
7125 void
7126 add_keyboard_wait_descriptor (int desc)
7128 #ifdef subprocesses /* actually means "not MSDOS" */
7129 FD_SET (desc, &input_wait_mask);
7130 FD_SET (desc, &non_process_wait_mask);
7131 if (desc > max_input_desc)
7132 max_input_desc = desc;
7133 #endif
7136 /* From now on, do not expect DESC to give keyboard input. */
7138 void
7139 delete_keyboard_wait_descriptor (int desc)
7141 #ifdef subprocesses
7142 int fd;
7143 int lim = max_input_desc;
7145 FD_CLR (desc, &input_wait_mask);
7146 FD_CLR (desc, &non_process_wait_mask);
7148 if (desc == max_input_desc)
7149 for (fd = 0; fd < lim; fd++)
7150 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7151 max_input_desc = fd;
7152 #endif
7155 /* Setup coding systems of PROCESS. */
7157 void
7158 setup_process_coding_systems (Lisp_Object process)
7160 #ifdef subprocesses
7161 struct Lisp_Process *p = XPROCESS (process);
7162 int inch = p->infd;
7163 int outch = p->outfd;
7164 Lisp_Object coding_system;
7166 if (inch < 0 || outch < 0)
7167 return;
7169 if (!proc_decode_coding_system[inch])
7170 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7171 coding_system = p->decode_coding_system;
7172 if (! NILP (p->filter))
7174 else if (BUFFERP (p->buffer))
7176 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7177 coding_system = raw_text_coding_system (coding_system);
7179 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7181 if (!proc_encode_coding_system[outch])
7182 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7183 setup_coding_system (p->encode_coding_system,
7184 proc_encode_coding_system[outch]);
7185 #endif
7188 /* Close all descriptors currently in use for communication
7189 with subprocess. This is used in a newly-forked subprocess
7190 to get rid of irrelevant descriptors. */
7192 void
7193 close_process_descs (void)
7195 #ifndef DOS_NT
7196 int i;
7197 for (i = 0; i < MAXDESC; i++)
7199 Lisp_Object process;
7200 process = chan_process[i];
7201 if (!NILP (process))
7203 int in = XPROCESS (process)->infd;
7204 int out = XPROCESS (process)->outfd;
7205 if (in >= 0)
7206 emacs_close (in);
7207 if (out >= 0 && in != out)
7208 emacs_close (out);
7211 #endif
7214 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7215 doc: /* Return the (or a) process associated with BUFFER.
7216 BUFFER may be a buffer or the name of one. */)
7217 (register Lisp_Object buffer)
7219 #ifdef subprocesses
7220 register Lisp_Object buf, tail, proc;
7222 if (NILP (buffer)) return Qnil;
7223 buf = Fget_buffer (buffer);
7224 if (NILP (buf)) return Qnil;
7226 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7228 proc = Fcdr (XCAR (tail));
7229 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7230 return proc;
7232 #endif /* subprocesses */
7233 return Qnil;
7236 DEFUN ("process-inherit-coding-system-flag",
7237 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7238 1, 1, 0,
7239 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7240 If this flag is t, `buffer-file-coding-system' of the buffer
7241 associated with PROCESS will inherit the coding system used to decode
7242 the process output. */)
7243 (register Lisp_Object process)
7245 #ifdef subprocesses
7246 CHECK_PROCESS (process);
7247 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7248 #else
7249 /* Ignore the argument and return the value of
7250 inherit-process-coding-system. */
7251 return inherit_process_coding_system ? Qt : Qnil;
7252 #endif
7255 /* Kill all processes associated with `buffer'.
7256 If `buffer' is nil, kill all processes */
7258 void
7259 kill_buffer_processes (Lisp_Object buffer)
7261 #ifdef subprocesses
7262 Lisp_Object tail, proc;
7264 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7266 proc = XCDR (XCAR (tail));
7267 if (PROCESSP (proc)
7268 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7270 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7271 Fdelete_process (proc);
7272 else if (XPROCESS (proc)->infd >= 0)
7273 process_send_signal (proc, SIGHUP, Qnil, 1);
7276 #else /* subprocesses */
7277 /* Since we have no subprocesses, this does nothing. */
7278 #endif /* subprocesses */
7281 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7282 Swaiting_for_user_input_p, 0, 0, 0,
7283 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7284 This is intended for use by asynchronous process output filters and sentinels. */)
7285 (void)
7287 #ifdef subprocesses
7288 return (waiting_for_user_input_p ? Qt : Qnil);
7289 #else
7290 return Qnil;
7291 #endif
7294 /* Stop reading input from keyboard sources. */
7296 void
7297 hold_keyboard_input (void)
7299 kbd_is_on_hold = 1;
7302 /* Resume reading input from keyboard sources. */
7304 void
7305 unhold_keyboard_input (void)
7307 kbd_is_on_hold = 0;
7310 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7313 kbd_on_hold_p (void)
7315 return kbd_is_on_hold;
7319 /* Enumeration of and access to system processes a-la ps(1). */
7321 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7322 0, 0, 0,
7323 doc: /* Return a list of numerical process IDs of all running processes.
7324 If this functionality is unsupported, return nil.
7326 See `process-attributes' for getting attributes of a process given its ID. */)
7327 (void)
7329 return list_system_processes ();
7332 DEFUN ("process-attributes", Fprocess_attributes,
7333 Sprocess_attributes, 1, 1, 0,
7334 doc: /* Return attributes of the process given by its PID, a number.
7336 Value is an alist where each element is a cons cell of the form
7338 \(KEY . VALUE)
7340 If this functionality is unsupported, the value is nil.
7342 See `list-system-processes' for getting a list of all process IDs.
7344 The KEYs of the attributes that this function may return are listed
7345 below, together with the type of the associated VALUE (in parentheses).
7346 Not all platforms support all of these attributes; unsupported
7347 attributes will not appear in the returned alist.
7348 Unless explicitly indicated otherwise, numbers can have either
7349 integer or floating point values.
7351 euid -- Effective user User ID of the process (number)
7352 user -- User name corresponding to euid (string)
7353 egid -- Effective user Group ID of the process (number)
7354 group -- Group name corresponding to egid (string)
7355 comm -- Command name (executable name only) (string)
7356 state -- Process state code, such as "S", "R", or "T" (string)
7357 ppid -- Parent process ID (number)
7358 pgrp -- Process group ID (number)
7359 sess -- Session ID, i.e. process ID of session leader (number)
7360 ttname -- Controlling tty name (string)
7361 tpgid -- ID of foreground process group on the process's tty (number)
7362 minflt -- number of minor page faults (number)
7363 majflt -- number of major page faults (number)
7364 cminflt -- cumulative number of minor page faults (number)
7365 cmajflt -- cumulative number of major page faults (number)
7366 utime -- user time used by the process, in (current-time) format,
7367 which is a list of integers (HIGH LOW USEC PSEC)
7368 stime -- system time used by the process (current-time)
7369 time -- sum of utime and stime (current-time)
7370 cutime -- user time used by the process and its children (current-time)
7371 cstime -- system time used by the process and its children (current-time)
7372 ctime -- sum of cutime and cstime (current-time)
7373 pri -- priority of the process (number)
7374 nice -- nice value of the process (number)
7375 thcount -- process thread count (number)
7376 start -- time the process started (current-time)
7377 vsize -- virtual memory size of the process in KB's (number)
7378 rss -- resident set size of the process in KB's (number)
7379 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7380 pcpu -- percents of CPU time used by the process (floating-point number)
7381 pmem -- percents of total physical memory used by process's resident set
7382 (floating-point number)
7383 args -- command line which invoked the process (string). */)
7384 ( Lisp_Object pid)
7386 return system_process_attributes (pid);
7390 /* This is not called "init_process" because that is the name of a
7391 Mach system call, so it would cause problems on Darwin systems. */
7392 void
7393 init_process_emacs (void)
7395 #ifdef subprocesses
7396 register int i;
7398 inhibit_sentinels = 0;
7400 #ifdef SIGCHLD
7401 #ifndef CANNOT_DUMP
7402 if (! noninteractive || initialized)
7403 #endif
7404 signal (SIGCHLD, sigchld_handler);
7405 #endif
7407 FD_ZERO (&input_wait_mask);
7408 FD_ZERO (&non_keyboard_wait_mask);
7409 FD_ZERO (&non_process_wait_mask);
7410 FD_ZERO (&write_mask);
7411 max_process_desc = 0;
7412 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7414 #ifdef NON_BLOCKING_CONNECT
7415 FD_ZERO (&connect_wait_mask);
7416 num_pending_connects = 0;
7417 #endif
7419 #ifdef ADAPTIVE_READ_BUFFERING
7420 process_output_delay_count = 0;
7421 process_output_skip = 0;
7422 #endif
7424 /* Don't do this, it caused infinite select loops. The display
7425 method should call add_keyboard_wait_descriptor on stdin if it
7426 needs that. */
7427 #if 0
7428 FD_SET (0, &input_wait_mask);
7429 #endif
7431 Vprocess_alist = Qnil;
7432 #ifdef SIGCHLD
7433 deleted_pid_list = Qnil;
7434 #endif
7435 for (i = 0; i < MAXDESC; i++)
7437 chan_process[i] = Qnil;
7438 proc_buffered_char[i] = -1;
7440 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7441 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7442 #ifdef DATAGRAM_SOCKETS
7443 memset (datagram_address, 0, sizeof datagram_address);
7444 #endif
7447 Lisp_Object subfeatures = Qnil;
7448 const struct socket_options *sopt;
7450 #define ADD_SUBFEATURE(key, val) \
7451 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7453 #ifdef NON_BLOCKING_CONNECT
7454 ADD_SUBFEATURE (QCnowait, Qt);
7455 #endif
7456 #ifdef DATAGRAM_SOCKETS
7457 ADD_SUBFEATURE (QCtype, Qdatagram);
7458 #endif
7459 #ifdef HAVE_SEQPACKET
7460 ADD_SUBFEATURE (QCtype, Qseqpacket);
7461 #endif
7462 #ifdef HAVE_LOCAL_SOCKETS
7463 ADD_SUBFEATURE (QCfamily, Qlocal);
7464 #endif
7465 ADD_SUBFEATURE (QCfamily, Qipv4);
7466 #ifdef AF_INET6
7467 ADD_SUBFEATURE (QCfamily, Qipv6);
7468 #endif
7469 #ifdef HAVE_GETSOCKNAME
7470 ADD_SUBFEATURE (QCservice, Qt);
7471 #endif
7472 #if defined (O_NONBLOCK) || defined (O_NDELAY)
7473 ADD_SUBFEATURE (QCserver, Qt);
7474 #endif
7476 for (sopt = socket_options; sopt->name; sopt++)
7477 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7479 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7482 #if defined (DARWIN_OS)
7483 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7484 processes. As such, we only change the default value. */
7485 if (initialized)
7487 char const *release = (STRINGP (Voperating_system_release)
7488 ? SSDATA (Voperating_system_release)
7489 : 0);
7490 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7491 Vprocess_connection_type = Qnil;
7494 #endif
7495 #endif /* subprocesses */
7496 kbd_is_on_hold = 0;
7499 void
7500 syms_of_process (void)
7502 #ifdef subprocesses
7504 DEFSYM (Qprocessp, "processp");
7505 DEFSYM (Qrun, "run");
7506 DEFSYM (Qstop, "stop");
7507 DEFSYM (Qsignal, "signal");
7509 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7510 here again.
7512 Qexit = intern_c_string ("exit");
7513 staticpro (&Qexit); */
7515 DEFSYM (Qopen, "open");
7516 DEFSYM (Qclosed, "closed");
7517 DEFSYM (Qconnect, "connect");
7518 DEFSYM (Qfailed, "failed");
7519 DEFSYM (Qlisten, "listen");
7520 DEFSYM (Qlocal, "local");
7521 DEFSYM (Qipv4, "ipv4");
7522 #ifdef AF_INET6
7523 DEFSYM (Qipv6, "ipv6");
7524 #endif
7525 DEFSYM (Qdatagram, "datagram");
7526 DEFSYM (Qseqpacket, "seqpacket");
7528 DEFSYM (QCport, ":port");
7529 DEFSYM (QCspeed, ":speed");
7530 DEFSYM (QCprocess, ":process");
7532 DEFSYM (QCbytesize, ":bytesize");
7533 DEFSYM (QCstopbits, ":stopbits");
7534 DEFSYM (QCparity, ":parity");
7535 DEFSYM (Qodd, "odd");
7536 DEFSYM (Qeven, "even");
7537 DEFSYM (QCflowcontrol, ":flowcontrol");
7538 DEFSYM (Qhw, "hw");
7539 DEFSYM (Qsw, "sw");
7540 DEFSYM (QCsummary, ":summary");
7542 DEFSYM (Qreal, "real");
7543 DEFSYM (Qnetwork, "network");
7544 DEFSYM (Qserial, "serial");
7545 DEFSYM (QCbuffer, ":buffer");
7546 DEFSYM (QChost, ":host");
7547 DEFSYM (QCservice, ":service");
7548 DEFSYM (QClocal, ":local");
7549 DEFSYM (QCremote, ":remote");
7550 DEFSYM (QCcoding, ":coding");
7551 DEFSYM (QCserver, ":server");
7552 DEFSYM (QCnowait, ":nowait");
7553 DEFSYM (QCsentinel, ":sentinel");
7554 DEFSYM (QClog, ":log");
7555 DEFSYM (QCnoquery, ":noquery");
7556 DEFSYM (QCstop, ":stop");
7557 DEFSYM (QCoptions, ":options");
7558 DEFSYM (QCplist, ":plist");
7560 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7562 staticpro (&Vprocess_alist);
7563 #ifdef SIGCHLD
7564 staticpro (&deleted_pid_list);
7565 #endif
7567 #endif /* subprocesses */
7569 DEFSYM (QCname, ":name");
7570 DEFSYM (QCtype, ":type");
7572 DEFSYM (Qeuid, "euid");
7573 DEFSYM (Qegid, "egid");
7574 DEFSYM (Quser, "user");
7575 DEFSYM (Qgroup, "group");
7576 DEFSYM (Qcomm, "comm");
7577 DEFSYM (Qstate, "state");
7578 DEFSYM (Qppid, "ppid");
7579 DEFSYM (Qpgrp, "pgrp");
7580 DEFSYM (Qsess, "sess");
7581 DEFSYM (Qttname, "ttname");
7582 DEFSYM (Qtpgid, "tpgid");
7583 DEFSYM (Qminflt, "minflt");
7584 DEFSYM (Qmajflt, "majflt");
7585 DEFSYM (Qcminflt, "cminflt");
7586 DEFSYM (Qcmajflt, "cmajflt");
7587 DEFSYM (Qutime, "utime");
7588 DEFSYM (Qstime, "stime");
7589 DEFSYM (Qtime, "time");
7590 DEFSYM (Qcutime, "cutime");
7591 DEFSYM (Qcstime, "cstime");
7592 DEFSYM (Qctime, "ctime");
7593 DEFSYM (Qpri, "pri");
7594 DEFSYM (Qnice, "nice");
7595 DEFSYM (Qthcount, "thcount");
7596 DEFSYM (Qstart, "start");
7597 DEFSYM (Qvsize, "vsize");
7598 DEFSYM (Qrss, "rss");
7599 DEFSYM (Qetime, "etime");
7600 DEFSYM (Qpcpu, "pcpu");
7601 DEFSYM (Qpmem, "pmem");
7602 DEFSYM (Qargs, "args");
7604 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7605 doc: /* Non-nil means delete processes immediately when they exit.
7606 A value of nil means don't delete them until `list-processes' is run. */);
7608 delete_exited_processes = 1;
7610 #ifdef subprocesses
7611 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7612 doc: /* Control type of device used to communicate with subprocesses.
7613 Values are nil to use a pipe, or t or `pty' to use a pty.
7614 The value has no effect if the system has no ptys or if all ptys are busy:
7615 then a pipe is used in any case.
7616 The value takes effect when `start-process' is called. */);
7617 Vprocess_connection_type = Qt;
7619 #ifdef ADAPTIVE_READ_BUFFERING
7620 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7621 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7622 On some systems, when Emacs reads the output from a subprocess, the output data
7623 is read in very small blocks, potentially resulting in very poor performance.
7624 This behavior can be remedied to some extent by setting this variable to a
7625 non-nil value, as it will automatically delay reading from such processes, to
7626 allow them to produce more output before Emacs tries to read it.
7627 If the value is t, the delay is reset after each write to the process; any other
7628 non-nil value means that the delay is not reset on write.
7629 The variable takes effect when `start-process' is called. */);
7630 Vprocess_adaptive_read_buffering = Qt;
7631 #endif
7633 defsubr (&Sprocessp);
7634 defsubr (&Sget_process);
7635 defsubr (&Sdelete_process);
7636 defsubr (&Sprocess_status);
7637 defsubr (&Sprocess_exit_status);
7638 defsubr (&Sprocess_id);
7639 defsubr (&Sprocess_name);
7640 defsubr (&Sprocess_tty_name);
7641 defsubr (&Sprocess_command);
7642 defsubr (&Sset_process_buffer);
7643 defsubr (&Sprocess_buffer);
7644 defsubr (&Sprocess_mark);
7645 defsubr (&Sset_process_filter);
7646 defsubr (&Sprocess_filter);
7647 defsubr (&Sset_process_sentinel);
7648 defsubr (&Sprocess_sentinel);
7649 defsubr (&Sset_process_window_size);
7650 defsubr (&Sset_process_inherit_coding_system_flag);
7651 defsubr (&Sset_process_query_on_exit_flag);
7652 defsubr (&Sprocess_query_on_exit_flag);
7653 defsubr (&Sprocess_contact);
7654 defsubr (&Sprocess_plist);
7655 defsubr (&Sset_process_plist);
7656 defsubr (&Sprocess_list);
7657 defsubr (&Sstart_process);
7658 defsubr (&Sserial_process_configure);
7659 defsubr (&Smake_serial_process);
7660 defsubr (&Sset_network_process_option);
7661 defsubr (&Smake_network_process);
7662 defsubr (&Sformat_network_address);
7663 #if defined (HAVE_NET_IF_H)
7664 #ifdef SIOCGIFCONF
7665 defsubr (&Snetwork_interface_list);
7666 #endif
7667 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7668 defsubr (&Snetwork_interface_info);
7669 #endif
7670 #endif /* defined (HAVE_NET_IF_H) */
7671 #ifdef DATAGRAM_SOCKETS
7672 defsubr (&Sprocess_datagram_address);
7673 defsubr (&Sset_process_datagram_address);
7674 #endif
7675 defsubr (&Saccept_process_output);
7676 defsubr (&Sprocess_send_region);
7677 defsubr (&Sprocess_send_string);
7678 defsubr (&Sinterrupt_process);
7679 defsubr (&Skill_process);
7680 defsubr (&Squit_process);
7681 defsubr (&Sstop_process);
7682 defsubr (&Scontinue_process);
7683 defsubr (&Sprocess_running_child_p);
7684 defsubr (&Sprocess_send_eof);
7685 defsubr (&Ssignal_process);
7686 defsubr (&Swaiting_for_user_input_p);
7687 defsubr (&Sprocess_type);
7688 defsubr (&Sset_process_coding_system);
7689 defsubr (&Sprocess_coding_system);
7690 defsubr (&Sset_process_filter_multibyte);
7691 defsubr (&Sprocess_filter_multibyte_p);
7693 #endif /* subprocesses */
7695 defsubr (&Sget_buffer_process);
7696 defsubr (&Sprocess_inherit_coding_system_flag);
7697 defsubr (&Slist_system_processes);
7698 defsubr (&Sprocess_attributes);