* process.c (allocate_pty) [PTY_OPEN]: Set fd's FD_CLOEXEC flag.
[emacs.git] / src / process.c
blob349ec26534b7938fb9bfa4c992b0f7ace27d551a
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 Free Software
4 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 <stdio.h>
27 #include <errno.h>
28 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
29 #include <sys/file.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <fcntl.h>
34 #include "lisp.h"
36 /* Only MS-DOS does not define `subprocesses'. */
37 #ifdef subprocesses
39 #include <sys/socket.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
44 /* Are local (unix) sockets supported? */
45 #if defined (HAVE_SYS_UN_H)
46 #if !defined (AF_LOCAL) && defined (AF_UNIX)
47 #define AF_LOCAL AF_UNIX
48 #endif
49 #ifdef AF_LOCAL
50 #define HAVE_LOCAL_SOCKETS
51 #include <sys/un.h>
52 #endif
53 #endif
55 #include <sys/ioctl.h>
56 #if defined (HAVE_NET_IF_H)
57 #include <net/if.h>
58 #endif /* HAVE_NET_IF_H */
60 #if defined (HAVE_IFADDRS_H)
61 /* Must be after net/if.h */
62 #include <ifaddrs.h>
64 /* We only use structs from this header when we use getifaddrs. */
65 #if defined (HAVE_NET_IF_DL_H)
66 #include <net/if_dl.h>
67 #endif
69 #endif
71 #ifdef NEED_BSDTTY
72 #include <bsdtty.h>
73 #endif
75 #ifdef USG5_4
76 # include <sys/stream.h>
77 # include <sys/stropts.h>
78 #endif
80 #ifdef HAVE_RES_INIT
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 #include <c-ctype.h>
94 #include <sig2str.h>
95 #include <verify.h>
97 #endif /* subprocesses */
99 #include "systime.h"
100 #include "systty.h"
102 #include "window.h"
103 #include "character.h"
104 #include "buffer.h"
105 #include "coding.h"
106 #include "process.h"
107 #include "frame.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
127 #ifdef HAVE_GLIB
128 #include "xgselect.h"
129 #ifndef WINDOWSNT
130 #include <glib.h>
131 #endif
132 #endif
134 #ifdef WINDOWSNT
135 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
136 EMACS_TIME *, void *);
137 #endif
139 #ifndef SOCK_CLOEXEC
140 # define SOCK_CLOEXEC 0
141 #endif
143 #ifndef HAVE_ACCEPT4
145 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
147 static int
148 close_on_exec (int fd)
150 if (0 <= fd)
151 fcntl (fd, F_SETFD, FD_CLOEXEC);
152 return fd;
155 static int
156 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
158 return close_on_exec (accept (sockfd, addr, addrlen));
161 static int
162 process_socket (int domain, int type, int protocol)
164 return close_on_exec (socket (domain, type, protocol));
166 # undef socket
167 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
168 #endif
170 /* Work around GCC 4.7.0 bug with strict overflow checking; see
171 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
172 These lines can be removed once the GCC bug is fixed. */
173 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
174 # pragma GCC diagnostic ignored "-Wstrict-overflow"
175 #endif
177 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
178 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
179 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
180 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
181 Lisp_Object QCname, QCtype;
183 /* True if keyboard input is on hold, zero otherwise. */
185 static bool kbd_is_on_hold;
187 /* Nonzero means don't run process sentinels. This is used
188 when exiting. */
189 bool inhibit_sentinels;
191 #ifdef subprocesses
193 Lisp_Object Qprocessp;
194 static Lisp_Object Qrun, Qstop, Qsignal;
195 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
196 Lisp_Object Qlocal;
197 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
198 static Lisp_Object Qreal, Qnetwork, Qserial;
199 #ifdef AF_INET6
200 static Lisp_Object Qipv6;
201 #endif
202 static Lisp_Object QCport, QCprocess;
203 Lisp_Object QCspeed;
204 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
205 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
206 static Lisp_Object QCbuffer, QChost, QCservice;
207 static Lisp_Object QClocal, QCremote, QCcoding;
208 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
209 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
210 static Lisp_Object Qlast_nonmenu_event;
211 static Lisp_Object Qinternal_default_process_sentinel;
212 static Lisp_Object Qinternal_default_process_filter;
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
219 /* Number of events of change of status of a process. */
220 static EMACS_INT process_tick;
221 /* Number of events for which the user or sentinel has been notified. */
222 static EMACS_INT update_tick;
224 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
226 /* Only W32 has this, it really means that select can't take write mask. */
227 #ifdef BROKEN_NON_BLOCKING_CONNECT
228 #undef NON_BLOCKING_CONNECT
229 #define SELECT_CANT_DO_WRITE_MASK
230 #else
231 #ifndef NON_BLOCKING_CONNECT
232 #ifdef HAVE_SELECT
233 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
234 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
235 #define NON_BLOCKING_CONNECT
236 #endif /* EWOULDBLOCK || EINPROGRESS */
237 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
238 #endif /* HAVE_SELECT */
239 #endif /* NON_BLOCKING_CONNECT */
240 #endif /* BROKEN_NON_BLOCKING_CONNECT */
242 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
243 this system. We need to read full packets, so we need a
244 "non-destructive" select. So we require either native select,
245 or emulation of select using FIONREAD. */
247 #ifndef BROKEN_DATAGRAM_SOCKETS
248 # if defined HAVE_SELECT || defined USABLE_FIONREAD
249 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
250 # define DATAGRAM_SOCKETS
251 # endif
252 # endif
253 #endif
255 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
256 # define HAVE_SEQPACKET
257 #endif
259 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
260 #define ADAPTIVE_READ_BUFFERING
261 #endif
263 #ifdef ADAPTIVE_READ_BUFFERING
264 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
265 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
266 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
268 /* Number of processes which have a non-zero read_output_delay,
269 and therefore might be delayed for adaptive read buffering. */
271 static int process_output_delay_count;
273 /* True if any process has non-nil read_output_skip. */
275 static bool process_output_skip;
277 #else
278 #define process_output_delay_count 0
279 #endif
281 static void create_process (Lisp_Object, char **, Lisp_Object);
282 #ifdef USABLE_SIGIO
283 static bool keyboard_bit_set (SELECT_TYPE *);
284 #endif
285 static void deactivate_process (Lisp_Object);
286 static void status_notify (struct Lisp_Process *);
287 static int read_process_output (Lisp_Object, int);
288 static void handle_child_signal (int);
289 static void create_pty (Lisp_Object);
291 /* If we support a window system, turn on the code to poll periodically
292 to detect C-g. It isn't actually used when doing interrupt input. */
293 #ifdef HAVE_WINDOW_SYSTEM
294 #define POLL_FOR_INPUT
295 #endif
297 static Lisp_Object get_process (register Lisp_Object name);
298 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
300 /* Mask of bits indicating the descriptors that we wait for input on. */
302 static SELECT_TYPE input_wait_mask;
304 /* Mask that excludes keyboard input descriptor(s). */
306 static SELECT_TYPE non_keyboard_wait_mask;
308 /* Mask that excludes process input descriptor(s). */
310 static SELECT_TYPE non_process_wait_mask;
312 /* Mask for selecting for write. */
314 static SELECT_TYPE write_mask;
316 #ifdef NON_BLOCKING_CONNECT
317 /* Mask of bits indicating the descriptors that we wait for connect to
318 complete on. Once they complete, they are removed from this mask
319 and added to the input_wait_mask and non_keyboard_wait_mask. */
321 static SELECT_TYPE connect_wait_mask;
323 /* Number of bits set in connect_wait_mask. */
324 static int num_pending_connects;
325 #endif /* NON_BLOCKING_CONNECT */
327 /* The largest descriptor currently in use for a process object; -1 if none. */
328 static int max_process_desc;
330 /* The largest descriptor currently in use for input; -1 if none. */
331 static int max_input_desc;
333 /* Indexed by descriptor, gives the process (if any) for that descriptor */
334 static Lisp_Object chan_process[MAXDESC];
336 /* Alist of elements (NAME . PROCESS) */
337 static Lisp_Object Vprocess_alist;
339 /* Buffered-ahead input char from process, indexed by channel.
340 -1 means empty (no char is buffered).
341 Used on sys V where the only way to tell if there is any
342 output from the process is to read at least one char.
343 Always -1 on systems that support FIONREAD. */
345 static int proc_buffered_char[MAXDESC];
347 /* Table of `struct coding-system' for each process. */
348 static struct coding_system *proc_decode_coding_system[MAXDESC];
349 static struct coding_system *proc_encode_coding_system[MAXDESC];
351 #ifdef DATAGRAM_SOCKETS
352 /* Table of `partner address' for datagram sockets. */
353 static struct sockaddr_and_len {
354 struct sockaddr *sa;
355 int len;
356 } datagram_address[MAXDESC];
357 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
358 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
359 #else
360 #define DATAGRAM_CHAN_P(chan) (0)
361 #define DATAGRAM_CONN_P(proc) (0)
362 #endif
364 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
365 a `for' loop which iterates over processes from Vprocess_alist. */
367 #define FOR_EACH_PROCESS(list_var, proc_var) \
368 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
370 /* These setters are used only in this file, so they can be private. */
371 static void
372 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
374 p->buffer = val;
376 static void
377 pset_command (struct Lisp_Process *p, Lisp_Object val)
379 p->command = val;
381 static void
382 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
384 p->decode_coding_system = val;
386 static void
387 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
389 p->decoding_buf = val;
391 static void
392 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
394 p->encode_coding_system = val;
396 static void
397 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
399 p->encoding_buf = val;
401 static void
402 pset_filter (struct Lisp_Process *p, Lisp_Object val)
404 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
406 static void
407 pset_log (struct Lisp_Process *p, Lisp_Object val)
409 p->log = val;
411 static void
412 pset_mark (struct Lisp_Process *p, Lisp_Object val)
414 p->mark = val;
416 static void
417 pset_name (struct Lisp_Process *p, Lisp_Object val)
419 p->name = val;
421 static void
422 pset_plist (struct Lisp_Process *p, Lisp_Object val)
424 p->plist = val;
426 static void
427 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
429 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
431 static void
432 pset_status (struct Lisp_Process *p, Lisp_Object val)
434 p->status = val;
436 static void
437 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
439 p->tty_name = val;
441 static void
442 pset_type (struct Lisp_Process *p, Lisp_Object val)
444 p->type = val;
446 static void
447 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
449 p->write_queue = val;
454 static struct fd_callback_data
456 fd_callback func;
457 void *data;
458 #define FOR_READ 1
459 #define FOR_WRITE 2
460 int condition; /* mask of the defines above. */
461 } fd_callback_info[MAXDESC];
464 /* Add a file descriptor FD to be monitored for when read is possible.
465 When read is possible, call FUNC with argument DATA. */
467 void
468 add_read_fd (int fd, fd_callback func, void *data)
470 eassert (fd < MAXDESC);
471 add_keyboard_wait_descriptor (fd);
473 fd_callback_info[fd].func = func;
474 fd_callback_info[fd].data = data;
475 fd_callback_info[fd].condition |= FOR_READ;
478 /* Stop monitoring file descriptor FD for when read is possible. */
480 void
481 delete_read_fd (int fd)
483 eassert (fd < MAXDESC);
484 delete_keyboard_wait_descriptor (fd);
486 fd_callback_info[fd].condition &= ~FOR_READ;
487 if (fd_callback_info[fd].condition == 0)
489 fd_callback_info[fd].func = 0;
490 fd_callback_info[fd].data = 0;
494 /* Add a file descriptor FD to be monitored for when write is possible.
495 When write is possible, call FUNC with argument DATA. */
497 void
498 add_write_fd (int fd, fd_callback func, void *data)
500 eassert (fd < MAXDESC);
501 FD_SET (fd, &write_mask);
502 if (fd > max_input_desc)
503 max_input_desc = fd;
505 fd_callback_info[fd].func = func;
506 fd_callback_info[fd].data = data;
507 fd_callback_info[fd].condition |= FOR_WRITE;
510 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
512 static void
513 delete_input_desc (int fd)
515 if (fd == max_input_desc)
518 fd--;
519 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
520 || FD_ISSET (fd, &write_mask)));
522 max_input_desc = fd;
526 /* Stop monitoring file descriptor FD for when write is possible. */
528 void
529 delete_write_fd (int fd)
531 eassert (fd < MAXDESC);
532 FD_CLR (fd, &write_mask);
533 fd_callback_info[fd].condition &= ~FOR_WRITE;
534 if (fd_callback_info[fd].condition == 0)
536 fd_callback_info[fd].func = 0;
537 fd_callback_info[fd].data = 0;
538 delete_input_desc (fd);
543 /* Compute the Lisp form of the process status, p->status, from
544 the numeric status that was returned by `wait'. */
546 static Lisp_Object status_convert (int);
548 static void
549 update_status (struct Lisp_Process *p)
551 eassert (p->raw_status_new);
552 pset_status (p, status_convert (p->raw_status));
553 p->raw_status_new = 0;
556 /* Convert a process status word in Unix format to
557 the list that we use internally. */
559 static Lisp_Object
560 status_convert (int w)
562 if (WIFSTOPPED (w))
563 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
564 else if (WIFEXITED (w))
565 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
566 WCOREDUMP (w) ? Qt : Qnil));
567 else if (WIFSIGNALED (w))
568 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
569 WCOREDUMP (w) ? Qt : Qnil));
570 else
571 return Qrun;
574 /* Given a status-list, extract the three pieces of information
575 and store them individually through the three pointers. */
577 static void
578 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
580 Lisp_Object tem;
582 if (SYMBOLP (l))
584 *symbol = l;
585 *code = 0;
586 *coredump = 0;
588 else
590 *symbol = XCAR (l);
591 tem = XCDR (l);
592 *code = XFASTINT (XCAR (tem));
593 tem = XCDR (tem);
594 *coredump = !NILP (tem);
598 /* Return a string describing a process status list. */
600 static Lisp_Object
601 status_message (struct Lisp_Process *p)
603 Lisp_Object status = p->status;
604 Lisp_Object symbol;
605 int code;
606 bool coredump;
607 Lisp_Object string, string2;
609 decode_status (status, &symbol, &code, &coredump);
611 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
613 char const *signame;
614 synchronize_system_messages_locale ();
615 signame = strsignal (code);
616 if (signame == 0)
617 string = build_string ("unknown");
618 else
620 int c1, c2;
622 string = build_unibyte_string (signame);
623 if (! NILP (Vlocale_coding_system))
624 string = (code_convert_string_norecord
625 (string, Vlocale_coding_system, 0));
626 c1 = STRING_CHAR (SDATA (string));
627 c2 = downcase (c1);
628 if (c1 != c2)
629 Faset (string, make_number (0), make_number (c2));
631 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
632 return concat2 (string, string2);
634 else if (EQ (symbol, Qexit))
636 if (NETCONN1_P (p))
637 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
638 if (code == 0)
639 return build_string ("finished\n");
640 string = Fnumber_to_string (make_number (code));
641 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
642 return concat3 (build_string ("exited abnormally with code "),
643 string, string2);
645 else if (EQ (symbol, Qfailed))
647 string = Fnumber_to_string (make_number (code));
648 string2 = build_string ("\n");
649 return concat3 (build_string ("failed with code "),
650 string, string2);
652 else
653 return Fcopy_sequence (Fsymbol_name (symbol));
656 enum { PTY_NAME_SIZE = 24 };
658 /* Open an available pty, returning a file descriptor.
659 Store into PTY_NAME the file name of the terminal corresponding to the pty.
660 Return -1 on failure. */
662 static int
663 allocate_pty (char pty_name[PTY_NAME_SIZE])
665 #ifdef HAVE_PTYS
666 int fd;
668 #ifdef PTY_ITERATION
669 PTY_ITERATION
670 #else
671 register int c, i;
672 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
673 for (i = 0; i < 16; i++)
674 #endif
676 #ifdef PTY_NAME_SPRINTF
677 PTY_NAME_SPRINTF
678 #else
679 sprintf (pty_name, "/dev/pty%c%x", c, i);
680 #endif /* no PTY_NAME_SPRINTF */
682 #ifdef PTY_OPEN
683 PTY_OPEN;
684 #else /* no PTY_OPEN */
685 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
686 #endif /* no PTY_OPEN */
688 if (fd >= 0)
690 #ifdef PTY_OPEN
691 /* Set FD's close-on-exec flag. This is needed even if
692 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
693 doesn't require support for that combination.
694 Multithreaded platforms where posix_openpt ignores
695 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
696 have a race condition between the PTY_OPEN and here. */
697 fcntl (fd, F_SETFD, FD_CLOEXEC);
698 #endif
699 /* check to make certain that both sides are available
700 this avoids a nasty yet stupid bug in rlogins */
701 #ifdef PTY_TTY_NAME_SPRINTF
702 PTY_TTY_NAME_SPRINTF
703 #else
704 sprintf (pty_name, "/dev/tty%c%x", c, i);
705 #endif /* no PTY_TTY_NAME_SPRINTF */
706 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
708 emacs_close (fd);
709 # ifndef __sgi
710 continue;
711 # else
712 return -1;
713 # endif /* __sgi */
715 setup_pty (fd);
716 return fd;
719 #endif /* HAVE_PTYS */
720 return -1;
723 static Lisp_Object
724 make_process (Lisp_Object name)
726 register Lisp_Object val, tem, name1;
727 register struct Lisp_Process *p;
728 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
729 printmax_t i;
731 p = allocate_process ();
732 /* Initialize Lisp data. Note that allocate_process initializes all
733 Lisp data to nil, so do it only for slots which should not be nil. */
734 pset_status (p, Qrun);
735 pset_mark (p, Fmake_marker ());
737 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
738 non-Lisp data, so do it only for slots which should not be zero. */
739 p->infd = -1;
740 p->outfd = -1;
741 for (i = 0; i < PROCESS_OPEN_FDS; i++)
742 p->open_fd[i] = -1;
744 #ifdef HAVE_GNUTLS
745 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
746 #endif
748 /* If name is already in use, modify it until it is unused. */
750 name1 = name;
751 for (i = 1; ; i++)
753 tem = Fget_process (name1);
754 if (NILP (tem)) break;
755 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
757 name = name1;
758 pset_name (p, name);
759 pset_sentinel (p, Qinternal_default_process_sentinel);
760 pset_filter (p, Qinternal_default_process_filter);
761 XSETPROCESS (val, p);
762 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
763 return val;
766 static void
767 remove_process (register Lisp_Object proc)
769 register Lisp_Object pair;
771 pair = Frassq (proc, Vprocess_alist);
772 Vprocess_alist = Fdelq (pair, Vprocess_alist);
774 deactivate_process (proc);
778 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
779 doc: /* Return t if OBJECT is a process. */)
780 (Lisp_Object object)
782 return PROCESSP (object) ? Qt : Qnil;
785 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
786 doc: /* Return the process named NAME, or nil if there is none. */)
787 (register Lisp_Object name)
789 if (PROCESSP (name))
790 return name;
791 CHECK_STRING (name);
792 return Fcdr (Fassoc (name, Vprocess_alist));
795 /* This is how commands for the user decode process arguments. It
796 accepts a process, a process name, a buffer, a buffer name, or nil.
797 Buffers denote the first process in the buffer, and nil denotes the
798 current buffer. */
800 static Lisp_Object
801 get_process (register Lisp_Object name)
803 register Lisp_Object proc, obj;
804 if (STRINGP (name))
806 obj = Fget_process (name);
807 if (NILP (obj))
808 obj = Fget_buffer (name);
809 if (NILP (obj))
810 error ("Process %s does not exist", SDATA (name));
812 else if (NILP (name))
813 obj = Fcurrent_buffer ();
814 else
815 obj = name;
817 /* Now obj should be either a buffer object or a process object.
819 if (BUFFERP (obj))
821 proc = Fget_buffer_process (obj);
822 if (NILP (proc))
823 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
825 else
827 CHECK_PROCESS (obj);
828 proc = obj;
830 return proc;
834 /* Fdelete_process promises to immediately forget about the process, but in
835 reality, Emacs needs to remember those processes until they have been
836 treated by the SIGCHLD handler and waitpid has been invoked on them;
837 otherwise they might fill up the kernel's process table.
839 Some processes created by call-process are also put onto this list.
841 Members of this list are (process-ID . filename) pairs. The
842 process-ID is a number; the filename, if a string, is a file that
843 needs to be removed after the process exits. */
844 static Lisp_Object deleted_pid_list;
846 void
847 record_deleted_pid (pid_t pid, Lisp_Object filename)
849 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
850 /* GC treated elements set to nil. */
851 Fdelq (Qnil, deleted_pid_list));
855 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
856 doc: /* Delete PROCESS: kill it and forget about it immediately.
857 PROCESS may be a process, a buffer, the name of a process or buffer, or
858 nil, indicating the current buffer's process. */)
859 (register Lisp_Object process)
861 register struct Lisp_Process *p;
863 process = get_process (process);
864 p = XPROCESS (process);
866 p->raw_status_new = 0;
867 if (NETCONN1_P (p) || SERIALCONN1_P (p))
869 pset_status (p, list2 (Qexit, make_number (0)));
870 p->tick = ++process_tick;
871 status_notify (p);
872 redisplay_preserve_echo_area (13);
874 else
876 if (p->alive)
877 record_kill_process (p, Qnil);
879 if (p->infd >= 0)
881 /* Update P's status, since record_kill_process will make the
882 SIGCHLD handler update deleted_pid_list, not *P. */
883 Lisp_Object symbol;
884 if (p->raw_status_new)
885 update_status (p);
886 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
887 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
888 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
890 p->tick = ++process_tick;
891 status_notify (p);
892 redisplay_preserve_echo_area (13);
895 remove_process (process);
896 return Qnil;
899 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
900 doc: /* Return the status of PROCESS.
901 The returned value is one of the following symbols:
902 run -- for a process that is running.
903 stop -- for a process stopped but continuable.
904 exit -- for a process that has exited.
905 signal -- for a process that has got a fatal signal.
906 open -- for a network stream connection that is open.
907 listen -- for a network stream server that is listening.
908 closed -- for a network stream connection that is closed.
909 connect -- when waiting for a non-blocking connection to complete.
910 failed -- when a non-blocking connection has failed.
911 nil -- if arg is a process name and no such process exists.
912 PROCESS may be a process, a buffer, the name of a process, or
913 nil, indicating the current buffer's process. */)
914 (register Lisp_Object process)
916 register struct Lisp_Process *p;
917 register Lisp_Object status;
919 if (STRINGP (process))
920 process = Fget_process (process);
921 else
922 process = get_process (process);
924 if (NILP (process))
925 return process;
927 p = XPROCESS (process);
928 if (p->raw_status_new)
929 update_status (p);
930 status = p->status;
931 if (CONSP (status))
932 status = XCAR (status);
933 if (NETCONN1_P (p) || SERIALCONN1_P (p))
935 if (EQ (status, Qexit))
936 status = Qclosed;
937 else if (EQ (p->command, Qt))
938 status = Qstop;
939 else if (EQ (status, Qrun))
940 status = Qopen;
942 return status;
945 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
946 1, 1, 0,
947 doc: /* Return the exit status of PROCESS or the signal number that killed it.
948 If PROCESS has not yet exited or died, return 0. */)
949 (register Lisp_Object process)
951 CHECK_PROCESS (process);
952 if (XPROCESS (process)->raw_status_new)
953 update_status (XPROCESS (process));
954 if (CONSP (XPROCESS (process)->status))
955 return XCAR (XCDR (XPROCESS (process)->status));
956 return make_number (0);
959 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
960 doc: /* Return the process id of PROCESS.
961 This is the pid of the external process which PROCESS uses or talks to.
962 For a network connection, this value is nil. */)
963 (register Lisp_Object process)
965 pid_t pid;
967 CHECK_PROCESS (process);
968 pid = XPROCESS (process)->pid;
969 return (pid ? make_fixnum_or_float (pid) : Qnil);
972 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
973 doc: /* Return the name of PROCESS, as a string.
974 This is the name of the program invoked in PROCESS,
975 possibly modified to make it unique among process names. */)
976 (register Lisp_Object process)
978 CHECK_PROCESS (process);
979 return XPROCESS (process)->name;
982 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
983 doc: /* Return the command that was executed to start PROCESS.
984 This is a list of strings, the first string being the program executed
985 and the rest of the strings being the arguments given to it.
986 For a network or serial process, this is nil (process is running) or t
987 \(process is stopped). */)
988 (register Lisp_Object process)
990 CHECK_PROCESS (process);
991 return XPROCESS (process)->command;
994 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
995 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
996 This is the terminal that the process itself reads and writes on,
997 not the name of the pty that Emacs uses to talk with that terminal. */)
998 (register Lisp_Object process)
1000 CHECK_PROCESS (process);
1001 return XPROCESS (process)->tty_name;
1004 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1005 2, 2, 0,
1006 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1007 Return BUFFER. */)
1008 (register Lisp_Object process, Lisp_Object buffer)
1010 struct Lisp_Process *p;
1012 CHECK_PROCESS (process);
1013 if (!NILP (buffer))
1014 CHECK_BUFFER (buffer);
1015 p = XPROCESS (process);
1016 pset_buffer (p, buffer);
1017 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1018 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1019 setup_process_coding_systems (process);
1020 return buffer;
1023 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1024 1, 1, 0,
1025 doc: /* Return the buffer PROCESS is associated with.
1026 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1027 (register Lisp_Object process)
1029 CHECK_PROCESS (process);
1030 return XPROCESS (process)->buffer;
1033 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1034 1, 1, 0,
1035 doc: /* Return the marker for the end of the last output from PROCESS. */)
1036 (register Lisp_Object process)
1038 CHECK_PROCESS (process);
1039 return XPROCESS (process)->mark;
1042 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1043 2, 2, 0,
1044 doc: /* Give PROCESS the filter function FILTER; nil means default.
1045 A value of t means stop accepting output from the process.
1047 When a process has a non-default filter, its buffer is not used for output.
1048 Instead, each time it does output, the entire string of output is
1049 passed to the filter.
1051 The filter gets two arguments: the process and the string of output.
1052 The string argument is normally a multibyte string, except:
1053 - if the process' input coding system is no-conversion or raw-text,
1054 it is a unibyte string (the non-converted input), or else
1055 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1056 string (the result of converting the decoded input multibyte
1057 string to unibyte with `string-make-unibyte'). */)
1058 (register Lisp_Object process, Lisp_Object filter)
1060 struct Lisp_Process *p;
1062 CHECK_PROCESS (process);
1063 p = XPROCESS (process);
1065 /* Don't signal an error if the process' input file descriptor
1066 is closed. This could make debugging Lisp more difficult,
1067 for example when doing something like
1069 (setq process (start-process ...))
1070 (debug)
1071 (set-process-filter process ...) */
1073 if (NILP (filter))
1074 filter = Qinternal_default_process_filter;
1076 if (p->infd >= 0)
1078 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1080 FD_CLR (p->infd, &input_wait_mask);
1081 FD_CLR (p->infd, &non_keyboard_wait_mask);
1083 else if (EQ (p->filter, Qt)
1084 /* Network or serial process not stopped: */
1085 && !EQ (p->command, Qt))
1087 FD_SET (p->infd, &input_wait_mask);
1088 FD_SET (p->infd, &non_keyboard_wait_mask);
1092 pset_filter (p, filter);
1093 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1094 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1095 setup_process_coding_systems (process);
1096 return filter;
1099 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1100 1, 1, 0,
1101 doc: /* Return the filter function of PROCESS.
1102 See `set-process-filter' for more info on filter functions. */)
1103 (register Lisp_Object process)
1105 CHECK_PROCESS (process);
1106 return XPROCESS (process)->filter;
1109 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1110 2, 2, 0,
1111 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1112 The sentinel is called as a function when the process changes state.
1113 It gets two arguments: the process, and a string describing the change. */)
1114 (register Lisp_Object process, Lisp_Object sentinel)
1116 struct Lisp_Process *p;
1118 CHECK_PROCESS (process);
1119 p = XPROCESS (process);
1121 if (NILP (sentinel))
1122 sentinel = Qinternal_default_process_sentinel;
1124 pset_sentinel (p, sentinel);
1125 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1126 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1127 return sentinel;
1130 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1131 1, 1, 0,
1132 doc: /* Return the sentinel of PROCESS.
1133 See `set-process-sentinel' for more info on sentinels. */)
1134 (register Lisp_Object process)
1136 CHECK_PROCESS (process);
1137 return XPROCESS (process)->sentinel;
1140 DEFUN ("set-process-window-size", Fset_process_window_size,
1141 Sset_process_window_size, 3, 3, 0,
1142 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1143 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1145 CHECK_PROCESS (process);
1146 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1147 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1149 if (XPROCESS (process)->infd < 0
1150 || set_window_size (XPROCESS (process)->infd,
1151 XINT (height), XINT (width)) <= 0)
1152 return Qnil;
1153 else
1154 return Qt;
1157 DEFUN ("set-process-inherit-coding-system-flag",
1158 Fset_process_inherit_coding_system_flag,
1159 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1160 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1161 If the second argument FLAG is non-nil, then the variable
1162 `buffer-file-coding-system' of the buffer associated with PROCESS
1163 will be bound to the value of the coding system used to decode
1164 the process output.
1166 This is useful when the coding system specified for the process buffer
1167 leaves either the character code conversion or the end-of-line conversion
1168 unspecified, or if the coding system used to decode the process output
1169 is more appropriate for saving the process buffer.
1171 Binding the variable `inherit-process-coding-system' to non-nil before
1172 starting the process is an alternative way of setting the inherit flag
1173 for the process which will run.
1175 This function returns FLAG. */)
1176 (register Lisp_Object process, Lisp_Object flag)
1178 CHECK_PROCESS (process);
1179 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1180 return flag;
1183 DEFUN ("set-process-query-on-exit-flag",
1184 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1185 2, 2, 0,
1186 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1187 If the second argument FLAG is non-nil, Emacs will query the user before
1188 exiting or killing a buffer if PROCESS is running. This function
1189 returns FLAG. */)
1190 (register Lisp_Object process, Lisp_Object flag)
1192 CHECK_PROCESS (process);
1193 XPROCESS (process)->kill_without_query = NILP (flag);
1194 return flag;
1197 DEFUN ("process-query-on-exit-flag",
1198 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1199 1, 1, 0,
1200 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1201 (register Lisp_Object process)
1203 CHECK_PROCESS (process);
1204 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1207 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1208 1, 2, 0,
1209 doc: /* Return the contact info of PROCESS; t for a real child.
1210 For a network or serial connection, the value depends on the optional
1211 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1212 SERVICE) for a network connection or (PORT SPEED) for a serial
1213 connection. If KEY is t, the complete contact information for the
1214 connection is returned, else the specific value for the keyword KEY is
1215 returned. See `make-network-process' or `make-serial-process' for a
1216 list of keywords. */)
1217 (register Lisp_Object process, Lisp_Object key)
1219 Lisp_Object contact;
1221 CHECK_PROCESS (process);
1222 contact = XPROCESS (process)->childp;
1224 #ifdef DATAGRAM_SOCKETS
1225 if (DATAGRAM_CONN_P (process)
1226 && (EQ (key, Qt) || EQ (key, QCremote)))
1227 contact = Fplist_put (contact, QCremote,
1228 Fprocess_datagram_address (process));
1229 #endif
1231 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1232 return contact;
1233 if (NILP (key) && NETCONN_P (process))
1234 return list2 (Fplist_get (contact, QChost),
1235 Fplist_get (contact, QCservice));
1236 if (NILP (key) && SERIALCONN_P (process))
1237 return list2 (Fplist_get (contact, QCport),
1238 Fplist_get (contact, QCspeed));
1239 return Fplist_get (contact, key);
1242 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1243 1, 1, 0,
1244 doc: /* Return the plist of PROCESS. */)
1245 (register Lisp_Object process)
1247 CHECK_PROCESS (process);
1248 return XPROCESS (process)->plist;
1251 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1252 2, 2, 0,
1253 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1254 (register Lisp_Object process, Lisp_Object plist)
1256 CHECK_PROCESS (process);
1257 CHECK_LIST (plist);
1259 pset_plist (XPROCESS (process), plist);
1260 return plist;
1263 #if 0 /* Turned off because we don't currently record this info
1264 in the process. Perhaps add it. */
1265 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1266 doc: /* Return the connection type of PROCESS.
1267 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1268 a socket connection. */)
1269 (Lisp_Object process)
1271 return XPROCESS (process)->type;
1273 #endif
1275 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1276 doc: /* Return the connection type of PROCESS.
1277 The value is either the symbol `real', `network', or `serial'.
1278 PROCESS may be a process, a buffer, the name of a process or buffer, or
1279 nil, indicating the current buffer's process. */)
1280 (Lisp_Object process)
1282 Lisp_Object proc;
1283 proc = get_process (process);
1284 return XPROCESS (proc)->type;
1287 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1288 1, 2, 0,
1289 doc: /* Convert network ADDRESS from internal format to a string.
1290 A 4 or 5 element vector represents an IPv4 address (with port number).
1291 An 8 or 9 element vector represents an IPv6 address (with port number).
1292 If optional second argument OMIT-PORT is non-nil, don't include a port
1293 number in the string, even when present in ADDRESS.
1294 Returns nil if format of ADDRESS is invalid. */)
1295 (Lisp_Object address, Lisp_Object omit_port)
1297 if (NILP (address))
1298 return Qnil;
1300 if (STRINGP (address)) /* AF_LOCAL */
1301 return address;
1303 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1305 register struct Lisp_Vector *p = XVECTOR (address);
1306 ptrdiff_t size = p->header.size;
1307 Lisp_Object args[10];
1308 int nargs, i;
1310 if (size == 4 || (size == 5 && !NILP (omit_port)))
1312 args[0] = build_string ("%d.%d.%d.%d");
1313 nargs = 4;
1315 else if (size == 5)
1317 args[0] = build_string ("%d.%d.%d.%d:%d");
1318 nargs = 5;
1320 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1322 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1323 nargs = 8;
1325 else if (size == 9)
1327 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1328 nargs = 9;
1330 else
1331 return Qnil;
1333 for (i = 0; i < nargs; i++)
1335 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1336 return Qnil;
1338 if (nargs <= 5 /* IPv4 */
1339 && i < 4 /* host, not port */
1340 && XINT (p->contents[i]) > 255)
1341 return Qnil;
1343 args[i+1] = p->contents[i];
1346 return Fformat (nargs+1, args);
1349 if (CONSP (address))
1351 Lisp_Object args[2];
1352 args[0] = build_string ("<Family %d>");
1353 args[1] = Fcar (address);
1354 return Fformat (2, args);
1357 return Qnil;
1360 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1361 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1362 (void)
1364 return Fmapcar (Qcdr, Vprocess_alist);
1367 /* Starting asynchronous inferior processes. */
1369 static void start_process_unwind (Lisp_Object proc);
1371 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1372 doc: /* Start a program in a subprocess. Return the process object for it.
1373 NAME is name for process. It is modified if necessary to make it unique.
1374 BUFFER is the buffer (or buffer name) to associate with the process.
1376 Process output (both standard output and standard error streams) goes
1377 at end of BUFFER, unless you specify an output stream or filter
1378 function to handle the output. BUFFER may also be nil, meaning that
1379 this process is not associated with any buffer.
1381 PROGRAM is the program file name. It is searched for in `exec-path'
1382 (which see). If nil, just associate a pty with the buffer. Remaining
1383 arguments are strings to give program as arguments.
1385 If you want to separate standard output from standard error, invoke
1386 the command through a shell and redirect one of them using the shell
1387 syntax.
1389 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1390 (ptrdiff_t nargs, Lisp_Object *args)
1392 Lisp_Object buffer, name, program, proc, current_dir, tem;
1393 register unsigned char **new_argv;
1394 ptrdiff_t i;
1395 ptrdiff_t count = SPECPDL_INDEX ();
1397 buffer = args[1];
1398 if (!NILP (buffer))
1399 buffer = Fget_buffer_create (buffer);
1401 /* Make sure that the child will be able to chdir to the current
1402 buffer's current directory, or its unhandled equivalent. We
1403 can't just have the child check for an error when it does the
1404 chdir, since it's in a vfork.
1406 We have to GCPRO around this because Fexpand_file_name and
1407 Funhandled_file_name_directory might call a file name handling
1408 function. The argument list is protected by the caller, so all
1409 we really have to worry about is buffer. */
1411 struct gcpro gcpro1, gcpro2;
1413 current_dir = BVAR (current_buffer, directory);
1415 GCPRO2 (buffer, current_dir);
1417 current_dir = Funhandled_file_name_directory (current_dir);
1418 if (NILP (current_dir))
1419 /* If the file name handler says that current_dir is unreachable, use
1420 a sensible default. */
1421 current_dir = build_string ("~/");
1422 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1423 if (NILP (Ffile_accessible_directory_p (current_dir)))
1424 report_file_error ("Setting current directory",
1425 BVAR (current_buffer, directory));
1427 UNGCPRO;
1430 name = args[0];
1431 CHECK_STRING (name);
1433 program = args[2];
1435 if (!NILP (program))
1436 CHECK_STRING (program);
1438 proc = make_process (name);
1439 /* If an error occurs and we can't start the process, we want to
1440 remove it from the process list. This means that each error
1441 check in create_process doesn't need to call remove_process
1442 itself; it's all taken care of here. */
1443 record_unwind_protect (start_process_unwind, proc);
1445 pset_childp (XPROCESS (proc), Qt);
1446 pset_plist (XPROCESS (proc), Qnil);
1447 pset_type (XPROCESS (proc), Qreal);
1448 pset_buffer (XPROCESS (proc), buffer);
1449 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1450 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1451 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1453 #ifdef HAVE_GNUTLS
1454 /* AKA GNUTLS_INITSTAGE(proc). */
1455 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1456 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1457 #endif
1459 #ifdef ADAPTIVE_READ_BUFFERING
1460 XPROCESS (proc)->adaptive_read_buffering
1461 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1462 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1463 #endif
1465 /* Make the process marker point into the process buffer (if any). */
1466 if (BUFFERP (buffer))
1467 set_marker_both (XPROCESS (proc)->mark, buffer,
1468 BUF_ZV (XBUFFER (buffer)),
1469 BUF_ZV_BYTE (XBUFFER (buffer)));
1472 /* Decide coding systems for communicating with the process. Here
1473 we don't setup the structure coding_system nor pay attention to
1474 unibyte mode. They are done in create_process. */
1476 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1477 Lisp_Object coding_systems = Qt;
1478 Lisp_Object val, *args2;
1479 struct gcpro gcpro1, gcpro2;
1481 val = Vcoding_system_for_read;
1482 if (NILP (val))
1484 args2 = alloca ((nargs + 1) * sizeof *args2);
1485 args2[0] = Qstart_process;
1486 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1487 GCPRO2 (proc, current_dir);
1488 if (!NILP (program))
1489 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1490 UNGCPRO;
1491 if (CONSP (coding_systems))
1492 val = XCAR (coding_systems);
1493 else if (CONSP (Vdefault_process_coding_system))
1494 val = XCAR (Vdefault_process_coding_system);
1496 pset_decode_coding_system (XPROCESS (proc), val);
1498 val = Vcoding_system_for_write;
1499 if (NILP (val))
1501 if (EQ (coding_systems, Qt))
1503 args2 = alloca ((nargs + 1) * sizeof *args2);
1504 args2[0] = Qstart_process;
1505 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1506 GCPRO2 (proc, current_dir);
1507 if (!NILP (program))
1508 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1509 UNGCPRO;
1511 if (CONSP (coding_systems))
1512 val = XCDR (coding_systems);
1513 else if (CONSP (Vdefault_process_coding_system))
1514 val = XCDR (Vdefault_process_coding_system);
1516 pset_encode_coding_system (XPROCESS (proc), val);
1517 /* Note: At this moment, the above coding system may leave
1518 text-conversion or eol-conversion unspecified. They will be
1519 decided after we read output from the process and decode it by
1520 some coding system, or just before we actually send a text to
1521 the process. */
1525 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1526 XPROCESS (proc)->decoding_carryover = 0;
1527 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1529 XPROCESS (proc)->inherit_coding_system_flag
1530 = !(NILP (buffer) || !inherit_process_coding_system);
1532 if (!NILP (program))
1534 /* If program file name is not absolute, search our path for it.
1535 Put the name we will really use in TEM. */
1536 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1537 && !(SCHARS (program) > 1
1538 && IS_DEVICE_SEP (SREF (program, 1))))
1540 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1542 tem = Qnil;
1543 GCPRO4 (name, program, buffer, current_dir);
1544 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1545 UNGCPRO;
1546 if (NILP (tem))
1547 report_file_error ("Searching for program", program);
1548 tem = Fexpand_file_name (tem, Qnil);
1550 else
1552 if (!NILP (Ffile_directory_p (program)))
1553 error ("Specified program for new process is a directory");
1554 tem = program;
1557 /* If program file name starts with /: for quoting a magic name,
1558 discard that. */
1559 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1560 && SREF (tem, 1) == ':')
1561 tem = Fsubstring (tem, make_number (2), Qnil);
1564 Lisp_Object arg_encoding = Qnil;
1565 struct gcpro gcpro1;
1566 GCPRO1 (tem);
1568 /* Encode the file name and put it in NEW_ARGV.
1569 That's where the child will use it to execute the program. */
1570 tem = list1 (ENCODE_FILE (tem));
1572 /* Here we encode arguments by the coding system used for sending
1573 data to the process. We don't support using different coding
1574 systems for encoding arguments and for encoding data sent to the
1575 process. */
1577 for (i = 3; i < nargs; i++)
1579 tem = Fcons (args[i], tem);
1580 CHECK_STRING (XCAR (tem));
1581 if (STRING_MULTIBYTE (XCAR (tem)))
1583 if (NILP (arg_encoding))
1584 arg_encoding = (complement_process_encoding_system
1585 (XPROCESS (proc)->encode_coding_system));
1586 XSETCAR (tem,
1587 code_convert_string_norecord
1588 (XCAR (tem), arg_encoding, 1));
1592 UNGCPRO;
1595 /* Now that everything is encoded we can collect the strings into
1596 NEW_ARGV. */
1597 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1598 new_argv[nargs - 2] = 0;
1600 for (i = nargs - 2; i-- != 0; )
1602 new_argv[i] = SDATA (XCAR (tem));
1603 tem = XCDR (tem);
1606 create_process (proc, (char **) new_argv, current_dir);
1608 else
1609 create_pty (proc);
1611 return unbind_to (count, proc);
1614 /* This function is the unwind_protect form for Fstart_process. If
1615 PROC doesn't have its pid set, then we know someone has signaled
1616 an error and the process wasn't started successfully, so we should
1617 remove it from the process list. */
1618 static void
1619 start_process_unwind (Lisp_Object proc)
1621 if (!PROCESSP (proc))
1622 emacs_abort ();
1624 /* Was PROC started successfully?
1625 -2 is used for a pty with no process, eg for gdb. */
1626 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1627 remove_process (proc);
1630 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1632 static void
1633 close_process_fd (int *fd_addr)
1635 int fd = *fd_addr;
1636 if (0 <= fd)
1638 *fd_addr = -1;
1639 emacs_close (fd);
1643 /* Indexes of file descriptors in open_fds. */
1644 enum
1646 /* The pipe from Emacs to its subprocess. */
1647 SUBPROCESS_STDIN,
1648 WRITE_TO_SUBPROCESS,
1650 /* The main pipe from the subprocess to Emacs. */
1651 READ_FROM_SUBPROCESS,
1652 SUBPROCESS_STDOUT,
1654 /* The pipe from the subprocess to Emacs that is closed when the
1655 subprocess execs. */
1656 READ_FROM_EXEC_MONITOR,
1657 EXEC_MONITOR_OUTPUT
1660 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1662 static void
1663 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1665 struct Lisp_Process *p = XPROCESS (process);
1666 int inchannel, outchannel;
1667 pid_t pid;
1668 int vfork_errno;
1669 int forkin, forkout;
1670 bool pty_flag = 0;
1671 char pty_name[PTY_NAME_SIZE];
1672 Lisp_Object lisp_pty_name = Qnil;
1673 Lisp_Object encoded_current_dir;
1675 inchannel = outchannel = -1;
1677 if (!NILP (Vprocess_connection_type))
1678 outchannel = inchannel = allocate_pty (pty_name);
1680 if (inchannel >= 0)
1682 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1683 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1684 /* On most USG systems it does not work to open the pty's tty here,
1685 then close it and reopen it in the child. */
1686 /* Don't let this terminal become our controlling terminal
1687 (in case we don't have one). */
1688 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1689 if (forkin < 0)
1690 report_file_error ("Opening pty", Qnil);
1691 p->open_fd[SUBPROCESS_STDIN] = forkin;
1692 #else
1693 forkin = forkout = -1;
1694 #endif /* not USG, or USG_SUBTTY_WORKS */
1695 pty_flag = 1;
1696 lisp_pty_name = build_string (pty_name);
1698 else
1700 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1701 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1702 report_file_error ("Creating pipe", Qnil);
1703 forkin = p->open_fd[SUBPROCESS_STDIN];
1704 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1705 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1706 forkout = p->open_fd[SUBPROCESS_STDOUT];
1709 #ifndef WINDOWSNT
1710 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1711 report_file_error ("Creating pipe", Qnil);
1712 #endif
1714 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1715 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1717 /* Record this as an active process, with its channels. */
1718 chan_process[inchannel] = process;
1719 p->infd = inchannel;
1720 p->outfd = outchannel;
1722 /* Previously we recorded the tty descriptor used in the subprocess.
1723 It was only used for getting the foreground tty process, so now
1724 we just reopen the device (see emacs_get_tty_pgrp) as this is
1725 more portable (see USG_SUBTTY_WORKS above). */
1727 p->pty_flag = pty_flag;
1728 pset_status (p, Qrun);
1730 FD_SET (inchannel, &input_wait_mask);
1731 FD_SET (inchannel, &non_keyboard_wait_mask);
1732 if (inchannel > max_process_desc)
1733 max_process_desc = inchannel;
1735 /* This may signal an error. */
1736 setup_process_coding_systems (process);
1738 encoded_current_dir = ENCODE_FILE (current_dir);
1740 block_input ();
1741 block_child_signal ();
1743 #ifndef WINDOWSNT
1744 /* vfork, and prevent local vars from being clobbered by the vfork. */
1746 Lisp_Object volatile encoded_current_dir_volatile = encoded_current_dir;
1747 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1748 char **volatile new_argv_volatile = new_argv;
1749 int volatile forkin_volatile = forkin;
1750 int volatile forkout_volatile = forkout;
1751 struct Lisp_Process *p_volatile = p;
1753 pid = vfork ();
1755 encoded_current_dir = encoded_current_dir_volatile;
1756 lisp_pty_name = lisp_pty_name_volatile;
1757 new_argv = new_argv_volatile;
1758 forkin = forkin_volatile;
1759 forkout = forkout_volatile;
1760 p = p_volatile;
1762 pty_flag = p->pty_flag;
1765 if (pid == 0)
1766 #endif /* not WINDOWSNT */
1768 int xforkin = forkin;
1769 int xforkout = forkout;
1771 /* Make the pty be the controlling terminal of the process. */
1772 #ifdef HAVE_PTYS
1773 /* First, disconnect its current controlling terminal. */
1774 /* We tried doing setsid only if pty_flag, but it caused
1775 process_set_signal to fail on SGI when using a pipe. */
1776 setsid ();
1777 /* Make the pty's terminal the controlling terminal. */
1778 if (pty_flag && xforkin >= 0)
1780 #ifdef TIOCSCTTY
1781 /* We ignore the return value
1782 because faith@cs.unc.edu says that is necessary on Linux. */
1783 ioctl (xforkin, TIOCSCTTY, 0);
1784 #endif
1786 #if defined (LDISC1)
1787 if (pty_flag && xforkin >= 0)
1789 struct termios t;
1790 tcgetattr (xforkin, &t);
1791 t.c_lflag = LDISC1;
1792 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1793 emacs_perror ("create_process/tcsetattr LDISC1");
1795 #else
1796 #if defined (NTTYDISC) && defined (TIOCSETD)
1797 if (pty_flag && xforkin >= 0)
1799 /* Use new line discipline. */
1800 int ldisc = NTTYDISC;
1801 ioctl (xforkin, TIOCSETD, &ldisc);
1803 #endif
1804 #endif
1805 #ifdef TIOCNOTTY
1806 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1807 can do TIOCSPGRP only to the process's controlling tty. */
1808 if (pty_flag)
1810 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1811 I can't test it since I don't have 4.3. */
1812 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1813 if (j >= 0)
1815 ioctl (j, TIOCNOTTY, 0);
1816 emacs_close (j);
1819 #endif /* TIOCNOTTY */
1821 #if !defined (DONT_REOPEN_PTY)
1822 /*** There is a suggestion that this ought to be a
1823 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1824 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1825 that system does seem to need this code, even though
1826 both TIOCSCTTY is defined. */
1827 /* Now close the pty (if we had it open) and reopen it.
1828 This makes the pty the controlling terminal of the subprocess. */
1829 if (pty_flag)
1832 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1833 would work? */
1834 if (xforkin >= 0)
1835 emacs_close (xforkin);
1836 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1838 if (xforkin < 0)
1840 emacs_perror (SSDATA (lisp_pty_name));
1841 _exit (EXIT_CANCELED);
1845 #endif /* not DONT_REOPEN_PTY */
1847 #ifdef SETUP_SLAVE_PTY
1848 if (pty_flag)
1850 SETUP_SLAVE_PTY;
1852 #endif /* SETUP_SLAVE_PTY */
1853 #endif /* HAVE_PTYS */
1855 signal (SIGINT, SIG_DFL);
1856 signal (SIGQUIT, SIG_DFL);
1858 /* Emacs ignores SIGPIPE, but the child should not. */
1859 signal (SIGPIPE, SIG_DFL);
1861 /* Stop blocking SIGCHLD in the child. */
1862 unblock_child_signal ();
1864 if (pty_flag)
1865 child_setup_tty (xforkout);
1866 #ifdef WINDOWSNT
1867 pid = child_setup (xforkin, xforkout, xforkout,
1868 new_argv, 1, encoded_current_dir);
1869 #else /* not WINDOWSNT */
1870 child_setup (xforkin, xforkout, xforkout,
1871 new_argv, 1, encoded_current_dir);
1872 #endif /* not WINDOWSNT */
1875 /* Back in the parent process. */
1877 vfork_errno = errno;
1878 p->pid = pid;
1879 if (pid >= 0)
1880 p->alive = 1;
1882 /* Stop blocking in the parent. */
1883 unblock_child_signal ();
1884 unblock_input ();
1886 if (pid < 0)
1887 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1888 else
1890 /* vfork succeeded. */
1892 /* Close the pipe ends that the child uses, or the child's pty. */
1893 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1894 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1896 #ifdef WINDOWSNT
1897 register_child (pid, inchannel);
1898 #endif /* WINDOWSNT */
1900 pset_tty_name (p, lisp_pty_name);
1902 #ifndef WINDOWSNT
1903 /* Wait for child_setup to complete in case that vfork is
1904 actually defined as fork. The descriptor
1905 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1906 of a pipe is closed at the child side either by close-on-exec
1907 on successful execve or the _exit call in child_setup. */
1909 char dummy;
1911 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1912 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1913 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1915 #endif
1919 static void
1920 create_pty (Lisp_Object process)
1922 struct Lisp_Process *p = XPROCESS (process);
1923 char pty_name[PTY_NAME_SIZE];
1924 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1926 if (pty_fd >= 0)
1928 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1929 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1930 /* On most USG systems it does not work to open the pty's tty here,
1931 then close it and reopen it in the child. */
1932 /* Don't let this terminal become our controlling terminal
1933 (in case we don't have one). */
1934 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1935 if (forkout < 0)
1936 report_file_error ("Opening pty", Qnil);
1937 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1938 #if defined (DONT_REOPEN_PTY)
1939 /* In the case that vfork is defined as fork, the parent process
1940 (Emacs) may send some data before the child process completes
1941 tty options setup. So we setup tty before forking. */
1942 child_setup_tty (forkout);
1943 #endif /* DONT_REOPEN_PTY */
1944 #endif /* not USG, or USG_SUBTTY_WORKS */
1946 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1948 /* Record this as an active process, with its channels.
1949 As a result, child_setup will close Emacs's side of the pipes. */
1950 chan_process[pty_fd] = process;
1951 p->infd = pty_fd;
1952 p->outfd = pty_fd;
1954 /* Previously we recorded the tty descriptor used in the subprocess.
1955 It was only used for getting the foreground tty process, so now
1956 we just reopen the device (see emacs_get_tty_pgrp) as this is
1957 more portable (see USG_SUBTTY_WORKS above). */
1959 p->pty_flag = 1;
1960 pset_status (p, Qrun);
1961 setup_process_coding_systems (process);
1963 FD_SET (pty_fd, &input_wait_mask);
1964 FD_SET (pty_fd, &non_keyboard_wait_mask);
1965 if (pty_fd > max_process_desc)
1966 max_process_desc = pty_fd;
1968 pset_tty_name (p, build_string (pty_name));
1971 p->pid = -2;
1975 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1976 The address family of sa is not included in the result. */
1978 static Lisp_Object
1979 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1981 Lisp_Object address;
1982 int i;
1983 unsigned char *cp;
1984 register struct Lisp_Vector *p;
1986 /* Workaround for a bug in getsockname on BSD: Names bound to
1987 sockets in the UNIX domain are inaccessible; getsockname returns
1988 a zero length name. */
1989 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1990 return empty_unibyte_string;
1992 switch (sa->sa_family)
1994 case AF_INET:
1996 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1997 len = sizeof (sin->sin_addr) + 1;
1998 address = Fmake_vector (make_number (len), Qnil);
1999 p = XVECTOR (address);
2000 p->contents[--len] = make_number (ntohs (sin->sin_port));
2001 cp = (unsigned char *) &sin->sin_addr;
2002 break;
2004 #ifdef AF_INET6
2005 case AF_INET6:
2007 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2008 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2009 len = sizeof (sin6->sin6_addr)/2 + 1;
2010 address = Fmake_vector (make_number (len), Qnil);
2011 p = XVECTOR (address);
2012 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2013 for (i = 0; i < len; i++)
2014 p->contents[i] = make_number (ntohs (ip6[i]));
2015 return address;
2017 #endif
2018 #ifdef HAVE_LOCAL_SOCKETS
2019 case AF_LOCAL:
2021 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2022 for (i = 0; i < sizeof (sockun->sun_path); i++)
2023 if (sockun->sun_path[i] == 0)
2024 break;
2025 return make_unibyte_string (sockun->sun_path, i);
2027 #endif
2028 default:
2029 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2030 address = Fcons (make_number (sa->sa_family),
2031 Fmake_vector (make_number (len), Qnil));
2032 p = XVECTOR (XCDR (address));
2033 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2034 break;
2037 i = 0;
2038 while (i < len)
2039 p->contents[i++] = make_number (*cp++);
2041 return address;
2045 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2047 static int
2048 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2050 register struct Lisp_Vector *p;
2052 if (VECTORP (address))
2054 p = XVECTOR (address);
2055 if (p->header.size == 5)
2057 *familyp = AF_INET;
2058 return sizeof (struct sockaddr_in);
2060 #ifdef AF_INET6
2061 else if (p->header.size == 9)
2063 *familyp = AF_INET6;
2064 return sizeof (struct sockaddr_in6);
2066 #endif
2068 #ifdef HAVE_LOCAL_SOCKETS
2069 else if (STRINGP (address))
2071 *familyp = AF_LOCAL;
2072 return sizeof (struct sockaddr_un);
2074 #endif
2075 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2076 && VECTORP (XCDR (address)))
2078 struct sockaddr *sa;
2079 *familyp = XINT (XCAR (address));
2080 p = XVECTOR (XCDR (address));
2081 return p->header.size + sizeof (sa->sa_family);
2083 return 0;
2086 /* Convert an address object (vector or string) to an internal sockaddr.
2088 The address format has been basically validated by
2089 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2090 it could have come from user data. So if FAMILY is not valid,
2091 we return after zeroing *SA. */
2093 static void
2094 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2096 register struct Lisp_Vector *p;
2097 register unsigned char *cp = NULL;
2098 register int i;
2099 EMACS_INT hostport;
2101 memset (sa, 0, len);
2103 if (VECTORP (address))
2105 p = XVECTOR (address);
2106 if (family == AF_INET)
2108 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2109 len = sizeof (sin->sin_addr) + 1;
2110 hostport = XINT (p->contents[--len]);
2111 sin->sin_port = htons (hostport);
2112 cp = (unsigned char *)&sin->sin_addr;
2113 sa->sa_family = family;
2115 #ifdef AF_INET6
2116 else if (family == AF_INET6)
2118 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2119 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2120 len = sizeof (sin6->sin6_addr) + 1;
2121 hostport = XINT (p->contents[--len]);
2122 sin6->sin6_port = htons (hostport);
2123 for (i = 0; i < len; i++)
2124 if (INTEGERP (p->contents[i]))
2126 int j = XFASTINT (p->contents[i]) & 0xffff;
2127 ip6[i] = ntohs (j);
2129 sa->sa_family = family;
2130 return;
2132 #endif
2133 else
2134 return;
2136 else if (STRINGP (address))
2138 #ifdef HAVE_LOCAL_SOCKETS
2139 if (family == AF_LOCAL)
2141 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2142 cp = SDATA (address);
2143 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2144 sockun->sun_path[i] = *cp++;
2145 sa->sa_family = family;
2147 #endif
2148 return;
2150 else
2152 p = XVECTOR (XCDR (address));
2153 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2156 for (i = 0; i < len; i++)
2157 if (INTEGERP (p->contents[i]))
2158 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2161 #ifdef DATAGRAM_SOCKETS
2162 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2163 1, 1, 0,
2164 doc: /* Get the current datagram address associated with PROCESS. */)
2165 (Lisp_Object process)
2167 int channel;
2169 CHECK_PROCESS (process);
2171 if (!DATAGRAM_CONN_P (process))
2172 return Qnil;
2174 channel = XPROCESS (process)->infd;
2175 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2176 datagram_address[channel].len);
2179 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2180 2, 2, 0,
2181 doc: /* Set the datagram address for PROCESS to ADDRESS.
2182 Returns nil upon error setting address, ADDRESS otherwise. */)
2183 (Lisp_Object process, Lisp_Object address)
2185 int channel;
2186 int family, len;
2188 CHECK_PROCESS (process);
2190 if (!DATAGRAM_CONN_P (process))
2191 return Qnil;
2193 channel = XPROCESS (process)->infd;
2195 len = get_lisp_to_sockaddr_size (address, &family);
2196 if (len == 0 || datagram_address[channel].len != len)
2197 return Qnil;
2198 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2199 return address;
2201 #endif
2204 static const struct socket_options {
2205 /* The name of this option. Should be lowercase version of option
2206 name without SO_ prefix. */
2207 const char *name;
2208 /* Option level SOL_... */
2209 int optlevel;
2210 /* Option number SO_... */
2211 int optnum;
2212 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2213 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2214 } socket_options[] =
2216 #ifdef SO_BINDTODEVICE
2217 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2218 #endif
2219 #ifdef SO_BROADCAST
2220 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2221 #endif
2222 #ifdef SO_DONTROUTE
2223 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2224 #endif
2225 #ifdef SO_KEEPALIVE
2226 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2227 #endif
2228 #ifdef SO_LINGER
2229 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2230 #endif
2231 #ifdef SO_OOBINLINE
2232 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2233 #endif
2234 #ifdef SO_PRIORITY
2235 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2236 #endif
2237 #ifdef SO_REUSEADDR
2238 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2239 #endif
2240 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2243 /* Set option OPT to value VAL on socket S.
2245 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2246 Signals an error if setting a known option fails.
2249 static int
2250 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2252 char *name;
2253 const struct socket_options *sopt;
2254 int ret = 0;
2256 CHECK_SYMBOL (opt);
2258 name = SSDATA (SYMBOL_NAME (opt));
2259 for (sopt = socket_options; sopt->name; sopt++)
2260 if (strcmp (name, sopt->name) == 0)
2261 break;
2263 switch (sopt->opttype)
2265 case SOPT_BOOL:
2267 int optval;
2268 optval = NILP (val) ? 0 : 1;
2269 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2270 &optval, sizeof (optval));
2271 break;
2274 case SOPT_INT:
2276 int optval;
2277 if (TYPE_RANGED_INTEGERP (int, val))
2278 optval = XINT (val);
2279 else
2280 error ("Bad option value for %s", name);
2281 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2282 &optval, sizeof (optval));
2283 break;
2286 #ifdef SO_BINDTODEVICE
2287 case SOPT_IFNAME:
2289 char devname[IFNAMSIZ+1];
2291 /* This is broken, at least in the Linux 2.4 kernel.
2292 To unbind, the arg must be a zero integer, not the empty string.
2293 This should work on all systems. KFS. 2003-09-23. */
2294 memset (devname, 0, sizeof devname);
2295 if (STRINGP (val))
2297 char *arg = SSDATA (val);
2298 int len = min (strlen (arg), IFNAMSIZ);
2299 memcpy (devname, arg, len);
2301 else if (!NILP (val))
2302 error ("Bad option value for %s", name);
2303 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2304 devname, IFNAMSIZ);
2305 break;
2307 #endif
2309 #ifdef SO_LINGER
2310 case SOPT_LINGER:
2312 struct linger linger;
2314 linger.l_onoff = 1;
2315 linger.l_linger = 0;
2316 if (TYPE_RANGED_INTEGERP (int, val))
2317 linger.l_linger = XINT (val);
2318 else
2319 linger.l_onoff = NILP (val) ? 0 : 1;
2320 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2321 &linger, sizeof (linger));
2322 break;
2324 #endif
2326 default:
2327 return 0;
2330 if (ret < 0)
2332 int setsockopt_errno = errno;
2333 report_file_errno ("Cannot set network option", list2 (opt, val),
2334 setsockopt_errno);
2337 return (1 << sopt->optbit);
2341 DEFUN ("set-network-process-option",
2342 Fset_network_process_option, Sset_network_process_option,
2343 3, 4, 0,
2344 doc: /* For network process PROCESS set option OPTION to value VALUE.
2345 See `make-network-process' for a list of options and values.
2346 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2347 OPTION is not a supported option, return nil instead; otherwise return t. */)
2348 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2350 int s;
2351 struct Lisp_Process *p;
2353 CHECK_PROCESS (process);
2354 p = XPROCESS (process);
2355 if (!NETCONN1_P (p))
2356 error ("Process is not a network process");
2358 s = p->infd;
2359 if (s < 0)
2360 error ("Process is not running");
2362 if (set_socket_option (s, option, value))
2364 pset_childp (p, Fplist_put (p->childp, option, value));
2365 return Qt;
2368 if (NILP (no_error))
2369 error ("Unknown or unsupported option");
2371 return Qnil;
2375 DEFUN ("serial-process-configure",
2376 Fserial_process_configure,
2377 Sserial_process_configure,
2378 0, MANY, 0,
2379 doc: /* Configure speed, bytesize, etc. of a serial process.
2381 Arguments are specified as keyword/argument pairs. Attributes that
2382 are not given are re-initialized from the process's current
2383 configuration (available via the function `process-contact') or set to
2384 reasonable default values. The following arguments are defined:
2386 :process PROCESS
2387 :name NAME
2388 :buffer BUFFER
2389 :port PORT
2390 -- Any of these arguments can be given to identify the process that is
2391 to be configured. If none of these arguments is given, the current
2392 buffer's process is used.
2394 :speed SPEED -- SPEED is the speed of the serial port in bits per
2395 second, also called baud rate. Any value can be given for SPEED, but
2396 most serial ports work only at a few defined values between 1200 and
2397 115200, with 9600 being the most common value. If SPEED is nil, the
2398 serial port is not configured any further, i.e., all other arguments
2399 are ignored. This may be useful for special serial ports such as
2400 Bluetooth-to-serial converters which can only be configured through AT
2401 commands. A value of nil for SPEED can be used only when passed
2402 through `make-serial-process' or `serial-term'.
2404 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2405 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2407 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2408 `odd' (use odd parity), or the symbol `even' (use even parity). If
2409 PARITY is not given, no parity is used.
2411 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2412 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2413 is not given or nil, 1 stopbit is used.
2415 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2416 flowcontrol to be used, which is either nil (don't use flowcontrol),
2417 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2418 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2419 flowcontrol is used.
2421 `serial-process-configure' is called by `make-serial-process' for the
2422 initial configuration of the serial port.
2424 Examples:
2426 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2428 \(serial-process-configure
2429 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2431 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2433 usage: (serial-process-configure &rest ARGS) */)
2434 (ptrdiff_t nargs, Lisp_Object *args)
2436 struct Lisp_Process *p;
2437 Lisp_Object contact = Qnil;
2438 Lisp_Object proc = Qnil;
2439 struct gcpro gcpro1;
2441 contact = Flist (nargs, args);
2442 GCPRO1 (contact);
2444 proc = Fplist_get (contact, QCprocess);
2445 if (NILP (proc))
2446 proc = Fplist_get (contact, QCname);
2447 if (NILP (proc))
2448 proc = Fplist_get (contact, QCbuffer);
2449 if (NILP (proc))
2450 proc = Fplist_get (contact, QCport);
2451 proc = get_process (proc);
2452 p = XPROCESS (proc);
2453 if (!EQ (p->type, Qserial))
2454 error ("Not a serial process");
2456 if (NILP (Fplist_get (p->childp, QCspeed)))
2458 UNGCPRO;
2459 return Qnil;
2462 serial_configure (p, contact);
2464 UNGCPRO;
2465 return Qnil;
2468 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2469 0, MANY, 0,
2470 doc: /* Create and return a serial port process.
2472 In Emacs, serial port connections are represented by process objects,
2473 so input and output work as for subprocesses, and `delete-process'
2474 closes a serial port connection. However, a serial process has no
2475 process id, it cannot be signaled, and the status codes are different
2476 from normal processes.
2478 `make-serial-process' creates a process and a buffer, on which you
2479 probably want to use `process-send-string'. Try \\[serial-term] for
2480 an interactive terminal. See below for examples.
2482 Arguments are specified as keyword/argument pairs. The following
2483 arguments are defined:
2485 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2486 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2487 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2488 the backslashes in strings).
2490 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2491 which this function calls.
2493 :name NAME -- NAME is the name of the process. If NAME is not given,
2494 the value of PORT is used.
2496 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2497 with the process. Process output goes at the end of that buffer,
2498 unless you specify an output stream or filter function to handle the
2499 output. If BUFFER is not given, the value of NAME is used.
2501 :coding CODING -- If CODING is a symbol, it specifies the coding
2502 system used for both reading and writing for this process. If CODING
2503 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2504 ENCODING is used for writing.
2506 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2507 the process is running. If BOOL is not given, query before exiting.
2509 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2510 In the stopped state, a serial process does not accept incoming data,
2511 but you can send outgoing data. The stopped state is cleared by
2512 `continue-process' and set by `stop-process'.
2514 :filter FILTER -- Install FILTER as the process filter.
2516 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2518 :plist PLIST -- Install PLIST as the initial plist of the process.
2520 :bytesize
2521 :parity
2522 :stopbits
2523 :flowcontrol
2524 -- This function calls `serial-process-configure' to handle these
2525 arguments.
2527 The original argument list, possibly modified by later configuration,
2528 is available via the function `process-contact'.
2530 Examples:
2532 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2534 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2536 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2538 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2540 usage: (make-serial-process &rest ARGS) */)
2541 (ptrdiff_t nargs, Lisp_Object *args)
2543 int fd = -1;
2544 Lisp_Object proc, contact, port;
2545 struct Lisp_Process *p;
2546 struct gcpro gcpro1;
2547 Lisp_Object name, buffer;
2548 Lisp_Object tem, val;
2549 ptrdiff_t specpdl_count;
2551 if (nargs == 0)
2552 return Qnil;
2554 contact = Flist (nargs, args);
2555 GCPRO1 (contact);
2557 port = Fplist_get (contact, QCport);
2558 if (NILP (port))
2559 error ("No port specified");
2560 CHECK_STRING (port);
2562 if (NILP (Fplist_member (contact, QCspeed)))
2563 error (":speed not specified");
2564 if (!NILP (Fplist_get (contact, QCspeed)))
2565 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2567 name = Fplist_get (contact, QCname);
2568 if (NILP (name))
2569 name = port;
2570 CHECK_STRING (name);
2571 proc = make_process (name);
2572 specpdl_count = SPECPDL_INDEX ();
2573 record_unwind_protect (remove_process, proc);
2574 p = XPROCESS (proc);
2576 fd = serial_open (port);
2577 p->open_fd[SUBPROCESS_STDIN] = fd;
2578 p->infd = fd;
2579 p->outfd = fd;
2580 if (fd > max_process_desc)
2581 max_process_desc = fd;
2582 chan_process[fd] = proc;
2584 buffer = Fplist_get (contact, QCbuffer);
2585 if (NILP (buffer))
2586 buffer = name;
2587 buffer = Fget_buffer_create (buffer);
2588 pset_buffer (p, buffer);
2590 pset_childp (p, contact);
2591 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2592 pset_type (p, Qserial);
2593 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2594 pset_filter (p, Fplist_get (contact, QCfilter));
2595 pset_log (p, Qnil);
2596 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2597 p->kill_without_query = 1;
2598 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2599 pset_command (p, Qt);
2600 eassert (! p->pty_flag);
2602 if (!EQ (p->command, Qt))
2604 FD_SET (fd, &input_wait_mask);
2605 FD_SET (fd, &non_keyboard_wait_mask);
2608 if (BUFFERP (buffer))
2610 set_marker_both (p->mark, buffer,
2611 BUF_ZV (XBUFFER (buffer)),
2612 BUF_ZV_BYTE (XBUFFER (buffer)));
2615 tem = Fplist_member (contact, QCcoding);
2616 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2617 tem = Qnil;
2619 val = Qnil;
2620 if (!NILP (tem))
2622 val = XCAR (XCDR (tem));
2623 if (CONSP (val))
2624 val = XCAR (val);
2626 else if (!NILP (Vcoding_system_for_read))
2627 val = Vcoding_system_for_read;
2628 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2629 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2630 val = Qnil;
2631 pset_decode_coding_system (p, val);
2633 val = Qnil;
2634 if (!NILP (tem))
2636 val = XCAR (XCDR (tem));
2637 if (CONSP (val))
2638 val = XCDR (val);
2640 else if (!NILP (Vcoding_system_for_write))
2641 val = Vcoding_system_for_write;
2642 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2643 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2644 val = Qnil;
2645 pset_encode_coding_system (p, val);
2647 setup_process_coding_systems (proc);
2648 pset_decoding_buf (p, empty_unibyte_string);
2649 p->decoding_carryover = 0;
2650 pset_encoding_buf (p, empty_unibyte_string);
2651 p->inherit_coding_system_flag
2652 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2654 Fserial_process_configure (nargs, args);
2656 specpdl_ptr = specpdl + specpdl_count;
2658 UNGCPRO;
2659 return proc;
2662 /* Create a network stream/datagram client/server process. Treated
2663 exactly like a normal process when reading and writing. Primary
2664 differences are in status display and process deletion. A network
2665 connection has no PID; you cannot signal it. All you can do is
2666 stop/continue it and deactivate/close it via delete-process */
2668 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2669 0, MANY, 0,
2670 doc: /* Create and return a network server or client process.
2672 In Emacs, network connections are represented by process objects, so
2673 input and output work as for subprocesses and `delete-process' closes
2674 a network connection. However, a network process has no process id,
2675 it cannot be signaled, and the status codes are different from normal
2676 processes.
2678 Arguments are specified as keyword/argument pairs. The following
2679 arguments are defined:
2681 :name NAME -- NAME is name for process. It is modified if necessary
2682 to make it unique.
2684 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2685 with the process. Process output goes at end of that buffer, unless
2686 you specify an output stream or filter function to handle the output.
2687 BUFFER may be also nil, meaning that this process is not associated
2688 with any buffer.
2690 :host HOST -- HOST is name of the host to connect to, or its IP
2691 address. The symbol `local' specifies the local host. If specified
2692 for a server process, it must be a valid name or address for the local
2693 host, and only clients connecting to that address will be accepted.
2695 :service SERVICE -- SERVICE is name of the service desired, or an
2696 integer specifying a port number to connect to. If SERVICE is t,
2697 a random port number is selected for the server. (If Emacs was
2698 compiled with getaddrinfo, a port number can also be specified as a
2699 string, e.g. "80", as well as an integer. This is not portable.)
2701 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2702 stream type connection, `datagram' creates a datagram type connection,
2703 `seqpacket' creates a reliable datagram connection.
2705 :family FAMILY -- FAMILY is the address (and protocol) family for the
2706 service specified by HOST and SERVICE. The default (nil) is to use
2707 whatever address family (IPv4 or IPv6) that is defined for the host
2708 and port number specified by HOST and SERVICE. Other address families
2709 supported are:
2710 local -- for a local (i.e. UNIX) address specified by SERVICE.
2711 ipv4 -- use IPv4 address family only.
2712 ipv6 -- use IPv6 address family only.
2714 :local ADDRESS -- ADDRESS is the local address used for the connection.
2715 This parameter is ignored when opening a client process. When specified
2716 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2718 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2719 connection. This parameter is ignored when opening a stream server
2720 process. For a datagram server process, it specifies the initial
2721 setting of the remote datagram address. When specified for a client
2722 process, the FAMILY, HOST, and SERVICE args are ignored.
2724 The format of ADDRESS depends on the address family:
2725 - An IPv4 address is represented as an vector of integers [A B C D P]
2726 corresponding to numeric IP address A.B.C.D and port number P.
2727 - A local address is represented as a string with the address in the
2728 local address space.
2729 - An "unsupported family" address is represented by a cons (F . AV)
2730 where F is the family number and AV is a vector containing the socket
2731 address data with one element per address data byte. Do not rely on
2732 this format in portable code, as it may depend on implementation
2733 defined constants, data sizes, and data structure alignment.
2735 :coding CODING -- If CODING is a symbol, it specifies the coding
2736 system used for both reading and writing for this process. If CODING
2737 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2738 ENCODING is used for writing.
2740 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2741 return without waiting for the connection to complete; instead, the
2742 sentinel function will be called with second arg matching "open" (if
2743 successful) or "failed" when the connect completes. Default is to use
2744 a blocking connect (i.e. wait) for stream type connections.
2746 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2747 running when Emacs is exited.
2749 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2750 In the stopped state, a server process does not accept new
2751 connections, and a client process does not handle incoming traffic.
2752 The stopped state is cleared by `continue-process' and set by
2753 `stop-process'.
2755 :filter FILTER -- Install FILTER as the process filter.
2757 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2758 process filter are multibyte, otherwise they are unibyte.
2759 If this keyword is not specified, the strings are multibyte if
2760 the default value of `enable-multibyte-characters' is non-nil.
2762 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2764 :log LOG -- Install LOG as the server process log function. This
2765 function is called when the server accepts a network connection from a
2766 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2767 is the server process, CLIENT is the new process for the connection,
2768 and MESSAGE is a string.
2770 :plist PLIST -- Install PLIST as the new process' initial plist.
2772 :server QLEN -- if QLEN is non-nil, create a server process for the
2773 specified FAMILY, SERVICE, and connection type (stream or datagram).
2774 If QLEN is an integer, it is used as the max. length of the server's
2775 pending connection queue (also known as the backlog); the default
2776 queue length is 5. Default is to create a client process.
2778 The following network options can be specified for this connection:
2780 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2781 :dontroute BOOL -- Only send to directly connected hosts.
2782 :keepalive BOOL -- Send keep-alive messages on network stream.
2783 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2784 :oobinline BOOL -- Place out-of-band data in receive data stream.
2785 :priority INT -- Set protocol defined priority for sent packets.
2786 :reuseaddr BOOL -- Allow reusing a recently used local address
2787 (this is allowed by default for a server process).
2788 :bindtodevice NAME -- bind to interface NAME. Using this may require
2789 special privileges on some systems.
2791 Consult the relevant system programmer's manual pages for more
2792 information on using these options.
2795 A server process will listen for and accept connections from clients.
2796 When a client connection is accepted, a new network process is created
2797 for the connection with the following parameters:
2799 - The client's process name is constructed by concatenating the server
2800 process' NAME and a client identification string.
2801 - If the FILTER argument is non-nil, the client process will not get a
2802 separate process buffer; otherwise, the client's process buffer is a newly
2803 created buffer named after the server process' BUFFER name or process
2804 NAME concatenated with the client identification string.
2805 - The connection type and the process filter and sentinel parameters are
2806 inherited from the server process' TYPE, FILTER and SENTINEL.
2807 - The client process' contact info is set according to the client's
2808 addressing information (typically an IP address and a port number).
2809 - The client process' plist is initialized from the server's plist.
2811 Notice that the FILTER and SENTINEL args are never used directly by
2812 the server process. Also, the BUFFER argument is not used directly by
2813 the server process, but via the optional :log function, accepted (and
2814 failed) connections may be logged in the server process' buffer.
2816 The original argument list, modified with the actual connection
2817 information, is available via the `process-contact' function.
2819 usage: (make-network-process &rest ARGS) */)
2820 (ptrdiff_t nargs, Lisp_Object *args)
2822 Lisp_Object proc;
2823 Lisp_Object contact;
2824 struct Lisp_Process *p;
2825 #ifdef HAVE_GETADDRINFO
2826 struct addrinfo ai, *res, *lres;
2827 struct addrinfo hints;
2828 const char *portstring;
2829 char portbuf[128];
2830 #else /* HAVE_GETADDRINFO */
2831 struct _emacs_addrinfo
2833 int ai_family;
2834 int ai_socktype;
2835 int ai_protocol;
2836 int ai_addrlen;
2837 struct sockaddr *ai_addr;
2838 struct _emacs_addrinfo *ai_next;
2839 } ai, *res, *lres;
2840 #endif /* HAVE_GETADDRINFO */
2841 struct sockaddr_in address_in;
2842 #ifdef HAVE_LOCAL_SOCKETS
2843 struct sockaddr_un address_un;
2844 #endif
2845 int port;
2846 int ret = 0;
2847 int xerrno = 0;
2848 int s = -1, outch, inch;
2849 struct gcpro gcpro1;
2850 ptrdiff_t count = SPECPDL_INDEX ();
2851 ptrdiff_t count1;
2852 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2853 Lisp_Object tem;
2854 Lisp_Object name, buffer, host, service, address;
2855 Lisp_Object filter, sentinel;
2856 bool is_non_blocking_client = 0;
2857 bool is_server = 0;
2858 int backlog = 5;
2859 int socktype;
2860 int family = -1;
2862 if (nargs == 0)
2863 return Qnil;
2865 /* Save arguments for process-contact and clone-process. */
2866 contact = Flist (nargs, args);
2867 GCPRO1 (contact);
2869 #ifdef WINDOWSNT
2870 /* Ensure socket support is loaded if available. */
2871 init_winsock (TRUE);
2872 #endif
2874 /* :type TYPE (nil: stream, datagram */
2875 tem = Fplist_get (contact, QCtype);
2876 if (NILP (tem))
2877 socktype = SOCK_STREAM;
2878 #ifdef DATAGRAM_SOCKETS
2879 else if (EQ (tem, Qdatagram))
2880 socktype = SOCK_DGRAM;
2881 #endif
2882 #ifdef HAVE_SEQPACKET
2883 else if (EQ (tem, Qseqpacket))
2884 socktype = SOCK_SEQPACKET;
2885 #endif
2886 else
2887 error ("Unsupported connection type");
2889 /* :server BOOL */
2890 tem = Fplist_get (contact, QCserver);
2891 if (!NILP (tem))
2893 /* Don't support network sockets when non-blocking mode is
2894 not available, since a blocked Emacs is not useful. */
2895 is_server = 1;
2896 if (TYPE_RANGED_INTEGERP (int, tem))
2897 backlog = XINT (tem);
2900 /* Make QCaddress an alias for :local (server) or :remote (client). */
2901 QCaddress = is_server ? QClocal : QCremote;
2903 /* :nowait BOOL */
2904 if (!is_server && socktype != SOCK_DGRAM
2905 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2907 #ifndef NON_BLOCKING_CONNECT
2908 error ("Non-blocking connect not supported");
2909 #else
2910 is_non_blocking_client = 1;
2911 #endif
2914 name = Fplist_get (contact, QCname);
2915 buffer = Fplist_get (contact, QCbuffer);
2916 filter = Fplist_get (contact, QCfilter);
2917 sentinel = Fplist_get (contact, QCsentinel);
2919 CHECK_STRING (name);
2921 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2922 ai.ai_socktype = socktype;
2923 ai.ai_protocol = 0;
2924 ai.ai_next = NULL;
2925 res = &ai;
2927 /* :local ADDRESS or :remote ADDRESS */
2928 address = Fplist_get (contact, QCaddress);
2929 if (!NILP (address))
2931 host = service = Qnil;
2933 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2934 error ("Malformed :address");
2935 ai.ai_family = family;
2936 ai.ai_addr = alloca (ai.ai_addrlen);
2937 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2938 goto open_socket;
2941 /* :family FAMILY -- nil (for Inet), local, or integer. */
2942 tem = Fplist_get (contact, QCfamily);
2943 if (NILP (tem))
2945 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2946 family = AF_UNSPEC;
2947 #else
2948 family = AF_INET;
2949 #endif
2951 #ifdef HAVE_LOCAL_SOCKETS
2952 else if (EQ (tem, Qlocal))
2953 family = AF_LOCAL;
2954 #endif
2955 #ifdef AF_INET6
2956 else if (EQ (tem, Qipv6))
2957 family = AF_INET6;
2958 #endif
2959 else if (EQ (tem, Qipv4))
2960 family = AF_INET;
2961 else if (TYPE_RANGED_INTEGERP (int, tem))
2962 family = XINT (tem);
2963 else
2964 error ("Unknown address family");
2966 ai.ai_family = family;
2968 /* :service SERVICE -- string, integer (port number), or t (random port). */
2969 service = Fplist_get (contact, QCservice);
2971 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2972 host = Fplist_get (contact, QChost);
2973 if (!NILP (host))
2975 if (EQ (host, Qlocal))
2976 /* Depending on setup, "localhost" may map to different IPv4 and/or
2977 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2978 host = build_string ("127.0.0.1");
2979 CHECK_STRING (host);
2982 #ifdef HAVE_LOCAL_SOCKETS
2983 if (family == AF_LOCAL)
2985 if (!NILP (host))
2987 message (":family local ignores the :host \"%s\" property",
2988 SDATA (host));
2989 contact = Fplist_put (contact, QChost, Qnil);
2990 host = Qnil;
2992 CHECK_STRING (service);
2993 memset (&address_un, 0, sizeof address_un);
2994 address_un.sun_family = AF_LOCAL;
2995 if (sizeof address_un.sun_path <= SBYTES (service))
2996 error ("Service name too long");
2997 strcpy (address_un.sun_path, SSDATA (service));
2998 ai.ai_addr = (struct sockaddr *) &address_un;
2999 ai.ai_addrlen = sizeof address_un;
3000 goto open_socket;
3002 #endif
3004 /* Slow down polling to every ten seconds.
3005 Some kernels have a bug which causes retrying connect to fail
3006 after a connect. Polling can interfere with gethostbyname too. */
3007 #ifdef POLL_FOR_INPUT
3008 if (socktype != SOCK_DGRAM)
3010 record_unwind_protect_void (run_all_atimers);
3011 bind_polling_period (10);
3013 #endif
3015 #ifdef HAVE_GETADDRINFO
3016 /* If we have a host, use getaddrinfo to resolve both host and service.
3017 Otherwise, use getservbyname to lookup the service. */
3018 if (!NILP (host))
3021 /* SERVICE can either be a string or int.
3022 Convert to a C string for later use by getaddrinfo. */
3023 if (EQ (service, Qt))
3024 portstring = "0";
3025 else if (INTEGERP (service))
3027 sprintf (portbuf, "%"pI"d", XINT (service));
3028 portstring = portbuf;
3030 else
3032 CHECK_STRING (service);
3033 portstring = SSDATA (service);
3036 immediate_quit = 1;
3037 QUIT;
3038 memset (&hints, 0, sizeof (hints));
3039 hints.ai_flags = 0;
3040 hints.ai_family = family;
3041 hints.ai_socktype = socktype;
3042 hints.ai_protocol = 0;
3044 #ifdef HAVE_RES_INIT
3045 res_init ();
3046 #endif
3048 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3049 if (ret)
3050 #ifdef HAVE_GAI_STRERROR
3051 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3052 #else
3053 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3054 #endif
3055 immediate_quit = 0;
3057 goto open_socket;
3059 #endif /* HAVE_GETADDRINFO */
3061 /* We end up here if getaddrinfo is not defined, or in case no hostname
3062 has been specified (e.g. for a local server process). */
3064 if (EQ (service, Qt))
3065 port = 0;
3066 else if (INTEGERP (service))
3067 port = htons ((unsigned short) XINT (service));
3068 else
3070 struct servent *svc_info;
3071 CHECK_STRING (service);
3072 svc_info = getservbyname (SSDATA (service),
3073 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3074 if (svc_info == 0)
3075 error ("Unknown service: %s", SDATA (service));
3076 port = svc_info->s_port;
3079 memset (&address_in, 0, sizeof address_in);
3080 address_in.sin_family = family;
3081 address_in.sin_addr.s_addr = INADDR_ANY;
3082 address_in.sin_port = port;
3084 #ifndef HAVE_GETADDRINFO
3085 if (!NILP (host))
3087 struct hostent *host_info_ptr;
3089 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3090 as it may `hang' Emacs for a very long time. */
3091 immediate_quit = 1;
3092 QUIT;
3094 #ifdef HAVE_RES_INIT
3095 res_init ();
3096 #endif
3098 host_info_ptr = gethostbyname (SDATA (host));
3099 immediate_quit = 0;
3101 if (host_info_ptr)
3103 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3104 host_info_ptr->h_length);
3105 family = host_info_ptr->h_addrtype;
3106 address_in.sin_family = family;
3108 else
3109 /* Attempt to interpret host as numeric inet address */
3111 unsigned long numeric_addr;
3112 numeric_addr = inet_addr (SSDATA (host));
3113 if (numeric_addr == -1)
3114 error ("Unknown host \"%s\"", SDATA (host));
3116 memcpy (&address_in.sin_addr, &numeric_addr,
3117 sizeof (address_in.sin_addr));
3121 #endif /* not HAVE_GETADDRINFO */
3123 ai.ai_family = family;
3124 ai.ai_addr = (struct sockaddr *) &address_in;
3125 ai.ai_addrlen = sizeof address_in;
3127 open_socket:
3129 /* Do this in case we never enter the for-loop below. */
3130 count1 = SPECPDL_INDEX ();
3131 s = -1;
3133 for (lres = res; lres; lres = lres->ai_next)
3135 ptrdiff_t optn;
3136 int optbits;
3138 #ifdef WINDOWSNT
3139 retry_connect:
3140 #endif
3142 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3143 lres->ai_protocol);
3144 if (s < 0)
3146 xerrno = errno;
3147 continue;
3150 #ifdef DATAGRAM_SOCKETS
3151 if (!is_server && socktype == SOCK_DGRAM)
3152 break;
3153 #endif /* DATAGRAM_SOCKETS */
3155 #ifdef NON_BLOCKING_CONNECT
3156 if (is_non_blocking_client)
3158 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3159 if (ret < 0)
3161 xerrno = errno;
3162 emacs_close (s);
3163 s = -1;
3164 continue;
3167 #endif
3169 /* Make us close S if quit. */
3170 record_unwind_protect_int (close_file_unwind, s);
3172 /* Parse network options in the arg list.
3173 We simply ignore anything which isn't a known option (including other keywords).
3174 An error is signaled if setting a known option fails. */
3175 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3176 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3178 if (is_server)
3180 /* Configure as a server socket. */
3182 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3183 explicit :reuseaddr key to override this. */
3184 #ifdef HAVE_LOCAL_SOCKETS
3185 if (family != AF_LOCAL)
3186 #endif
3187 if (!(optbits & (1 << OPIX_REUSEADDR)))
3189 int optval = 1;
3190 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3191 report_file_error ("Cannot set reuse option on server socket", Qnil);
3194 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3195 report_file_error ("Cannot bind server socket", Qnil);
3197 #ifdef HAVE_GETSOCKNAME
3198 if (EQ (service, Qt))
3200 struct sockaddr_in sa1;
3201 socklen_t len1 = sizeof (sa1);
3202 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3204 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3205 service = make_number (ntohs (sa1.sin_port));
3206 contact = Fplist_put (contact, QCservice, service);
3209 #endif
3211 if (socktype != SOCK_DGRAM && listen (s, backlog))
3212 report_file_error ("Cannot listen on server socket", Qnil);
3214 break;
3217 immediate_quit = 1;
3218 QUIT;
3220 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3221 xerrno = errno;
3223 if (ret == 0 || xerrno == EISCONN)
3225 /* The unwind-protect will be discarded afterwards.
3226 Likewise for immediate_quit. */
3227 break;
3230 #ifdef NON_BLOCKING_CONNECT
3231 #ifdef EINPROGRESS
3232 if (is_non_blocking_client && xerrno == EINPROGRESS)
3233 break;
3234 #else
3235 #ifdef EWOULDBLOCK
3236 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3237 break;
3238 #endif
3239 #endif
3240 #endif
3242 #ifndef WINDOWSNT
3243 if (xerrno == EINTR)
3245 /* Unlike most other syscalls connect() cannot be called
3246 again. (That would return EALREADY.) The proper way to
3247 wait for completion is pselect(). */
3248 int sc;
3249 socklen_t len;
3250 SELECT_TYPE fdset;
3251 retry_select:
3252 FD_ZERO (&fdset);
3253 FD_SET (s, &fdset);
3254 QUIT;
3255 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3256 if (sc == -1)
3258 if (errno == EINTR)
3259 goto retry_select;
3260 else
3261 report_file_error ("Failed select", Qnil);
3263 eassert (sc > 0);
3265 len = sizeof xerrno;
3266 eassert (FD_ISSET (s, &fdset));
3267 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3268 report_file_error ("Failed getsockopt", Qnil);
3269 if (xerrno)
3270 report_file_errno ("Failed connect", Qnil, xerrno);
3271 break;
3273 #endif /* !WINDOWSNT */
3275 immediate_quit = 0;
3277 /* Discard the unwind protect closing S. */
3278 specpdl_ptr = specpdl + count1;
3279 emacs_close (s);
3280 s = -1;
3282 #ifdef WINDOWSNT
3283 if (xerrno == EINTR)
3284 goto retry_connect;
3285 #endif
3288 if (s >= 0)
3290 #ifdef DATAGRAM_SOCKETS
3291 if (socktype == SOCK_DGRAM)
3293 if (datagram_address[s].sa)
3294 emacs_abort ();
3295 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3296 datagram_address[s].len = lres->ai_addrlen;
3297 if (is_server)
3299 Lisp_Object remote;
3300 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3301 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3303 int rfamily, rlen;
3304 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3305 if (rlen != 0 && rfamily == lres->ai_family
3306 && rlen == lres->ai_addrlen)
3307 conv_lisp_to_sockaddr (rfamily, remote,
3308 datagram_address[s].sa, rlen);
3311 else
3312 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3314 #endif
3315 contact = Fplist_put (contact, QCaddress,
3316 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3317 #ifdef HAVE_GETSOCKNAME
3318 if (!is_server)
3320 struct sockaddr_in sa1;
3321 socklen_t len1 = sizeof (sa1);
3322 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3323 contact = Fplist_put (contact, QClocal,
3324 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3326 #endif
3329 immediate_quit = 0;
3331 #ifdef HAVE_GETADDRINFO
3332 if (res != &ai)
3334 block_input ();
3335 freeaddrinfo (res);
3336 unblock_input ();
3338 #endif
3340 if (s < 0)
3342 /* If non-blocking got this far - and failed - assume non-blocking is
3343 not supported after all. This is probably a wrong assumption, but
3344 the normal blocking calls to open-network-stream handles this error
3345 better. */
3346 if (is_non_blocking_client)
3347 return Qnil;
3349 report_file_errno ((is_server
3350 ? "make server process failed"
3351 : "make client process failed"),
3352 contact, xerrno);
3355 inch = s;
3356 outch = s;
3358 if (!NILP (buffer))
3359 buffer = Fget_buffer_create (buffer);
3360 proc = make_process (name);
3362 chan_process[inch] = proc;
3364 fcntl (inch, F_SETFL, O_NONBLOCK);
3366 p = XPROCESS (proc);
3368 pset_childp (p, contact);
3369 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3370 pset_type (p, Qnetwork);
3372 pset_buffer (p, buffer);
3373 pset_sentinel (p, sentinel);
3374 pset_filter (p, filter);
3375 pset_log (p, Fplist_get (contact, QClog));
3376 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3377 p->kill_without_query = 1;
3378 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3379 pset_command (p, Qt);
3380 p->pid = 0;
3382 p->open_fd[SUBPROCESS_STDIN] = inch;
3383 p->infd = inch;
3384 p->outfd = outch;
3386 /* Discard the unwind protect for closing S, if any. */
3387 specpdl_ptr = specpdl + count1;
3389 /* Unwind bind_polling_period and request_sigio. */
3390 unbind_to (count, Qnil);
3392 if (is_server && socktype != SOCK_DGRAM)
3393 pset_status (p, Qlisten);
3395 /* Make the process marker point into the process buffer (if any). */
3396 if (BUFFERP (buffer))
3397 set_marker_both (p->mark, buffer,
3398 BUF_ZV (XBUFFER (buffer)),
3399 BUF_ZV_BYTE (XBUFFER (buffer)));
3401 #ifdef NON_BLOCKING_CONNECT
3402 if (is_non_blocking_client)
3404 /* We may get here if connect did succeed immediately. However,
3405 in that case, we still need to signal this like a non-blocking
3406 connection. */
3407 pset_status (p, Qconnect);
3408 if (!FD_ISSET (inch, &connect_wait_mask))
3410 FD_SET (inch, &connect_wait_mask);
3411 FD_SET (inch, &write_mask);
3412 num_pending_connects++;
3415 else
3416 #endif
3417 /* A server may have a client filter setting of Qt, but it must
3418 still listen for incoming connects unless it is stopped. */
3419 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3420 || (EQ (p->status, Qlisten) && NILP (p->command)))
3422 FD_SET (inch, &input_wait_mask);
3423 FD_SET (inch, &non_keyboard_wait_mask);
3426 if (inch > max_process_desc)
3427 max_process_desc = inch;
3429 tem = Fplist_member (contact, QCcoding);
3430 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3431 tem = Qnil; /* No error message (too late!). */
3434 /* Setup coding systems for communicating with the network stream. */
3435 struct gcpro gcpro1;
3436 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3437 Lisp_Object coding_systems = Qt;
3438 Lisp_Object fargs[5], val;
3440 if (!NILP (tem))
3442 val = XCAR (XCDR (tem));
3443 if (CONSP (val))
3444 val = XCAR (val);
3446 else if (!NILP (Vcoding_system_for_read))
3447 val = Vcoding_system_for_read;
3448 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3449 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3450 /* We dare not decode end-of-line format by setting VAL to
3451 Qraw_text, because the existing Emacs Lisp libraries
3452 assume that they receive bare code including a sequence of
3453 CR LF. */
3454 val = Qnil;
3455 else
3457 if (NILP (host) || NILP (service))
3458 coding_systems = Qnil;
3459 else
3461 fargs[0] = Qopen_network_stream, fargs[1] = name,
3462 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3463 GCPRO1 (proc);
3464 coding_systems = Ffind_operation_coding_system (5, fargs);
3465 UNGCPRO;
3467 if (CONSP (coding_systems))
3468 val = XCAR (coding_systems);
3469 else if (CONSP (Vdefault_process_coding_system))
3470 val = XCAR (Vdefault_process_coding_system);
3471 else
3472 val = Qnil;
3474 pset_decode_coding_system (p, val);
3476 if (!NILP (tem))
3478 val = XCAR (XCDR (tem));
3479 if (CONSP (val))
3480 val = XCDR (val);
3482 else if (!NILP (Vcoding_system_for_write))
3483 val = Vcoding_system_for_write;
3484 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3485 val = Qnil;
3486 else
3488 if (EQ (coding_systems, Qt))
3490 if (NILP (host) || NILP (service))
3491 coding_systems = Qnil;
3492 else
3494 fargs[0] = Qopen_network_stream, fargs[1] = name,
3495 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3496 GCPRO1 (proc);
3497 coding_systems = Ffind_operation_coding_system (5, fargs);
3498 UNGCPRO;
3501 if (CONSP (coding_systems))
3502 val = XCDR (coding_systems);
3503 else if (CONSP (Vdefault_process_coding_system))
3504 val = XCDR (Vdefault_process_coding_system);
3505 else
3506 val = Qnil;
3508 pset_encode_coding_system (p, val);
3510 setup_process_coding_systems (proc);
3512 pset_decoding_buf (p, empty_unibyte_string);
3513 p->decoding_carryover = 0;
3514 pset_encoding_buf (p, empty_unibyte_string);
3516 p->inherit_coding_system_flag
3517 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3519 UNGCPRO;
3520 return proc;
3524 #if defined (HAVE_NET_IF_H)
3526 #ifdef SIOCGIFCONF
3527 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3528 doc: /* Return an alist of all network interfaces and their network address.
3529 Each element is a cons, the car of which is a string containing the
3530 interface name, and the cdr is the network address in internal
3531 format; see the description of ADDRESS in `make-network-process'. */)
3532 (void)
3534 struct ifconf ifconf;
3535 struct ifreq *ifreq;
3536 void *buf = NULL;
3537 ptrdiff_t buf_size = 512;
3538 int s;
3539 Lisp_Object res;
3540 ptrdiff_t count;
3542 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3543 if (s < 0)
3544 return Qnil;
3545 count = SPECPDL_INDEX ();
3546 record_unwind_protect_int (close_file_unwind, s);
3550 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3551 ifconf.ifc_buf = buf;
3552 ifconf.ifc_len = buf_size;
3553 if (ioctl (s, SIOCGIFCONF, &ifconf))
3555 emacs_close (s);
3556 xfree (buf);
3557 return Qnil;
3560 while (ifconf.ifc_len == buf_size);
3562 res = unbind_to (count, Qnil);
3563 ifreq = ifconf.ifc_req;
3564 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3566 struct ifreq *ifq = ifreq;
3567 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3568 #define SIZEOF_IFREQ(sif) \
3569 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3570 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3572 int len = SIZEOF_IFREQ (ifq);
3573 #else
3574 int len = sizeof (*ifreq);
3575 #endif
3576 char namebuf[sizeof (ifq->ifr_name) + 1];
3577 ifreq = (struct ifreq *) ((char *) ifreq + len);
3579 if (ifq->ifr_addr.sa_family != AF_INET)
3580 continue;
3582 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3583 namebuf[sizeof (ifq->ifr_name)] = 0;
3584 res = Fcons (Fcons (build_string (namebuf),
3585 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3586 sizeof (struct sockaddr))),
3587 res);
3590 xfree (buf);
3591 return res;
3593 #endif /* SIOCGIFCONF */
3595 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3597 struct ifflag_def {
3598 int flag_bit;
3599 const char *flag_sym;
3602 static const struct ifflag_def ifflag_table[] = {
3603 #ifdef IFF_UP
3604 { IFF_UP, "up" },
3605 #endif
3606 #ifdef IFF_BROADCAST
3607 { IFF_BROADCAST, "broadcast" },
3608 #endif
3609 #ifdef IFF_DEBUG
3610 { IFF_DEBUG, "debug" },
3611 #endif
3612 #ifdef IFF_LOOPBACK
3613 { IFF_LOOPBACK, "loopback" },
3614 #endif
3615 #ifdef IFF_POINTOPOINT
3616 { IFF_POINTOPOINT, "pointopoint" },
3617 #endif
3618 #ifdef IFF_RUNNING
3619 { IFF_RUNNING, "running" },
3620 #endif
3621 #ifdef IFF_NOARP
3622 { IFF_NOARP, "noarp" },
3623 #endif
3624 #ifdef IFF_PROMISC
3625 { IFF_PROMISC, "promisc" },
3626 #endif
3627 #ifdef IFF_NOTRAILERS
3628 #ifdef NS_IMPL_COCOA
3629 /* Really means smart, notrailers is obsolete */
3630 { IFF_NOTRAILERS, "smart" },
3631 #else
3632 { IFF_NOTRAILERS, "notrailers" },
3633 #endif
3634 #endif
3635 #ifdef IFF_ALLMULTI
3636 { IFF_ALLMULTI, "allmulti" },
3637 #endif
3638 #ifdef IFF_MASTER
3639 { IFF_MASTER, "master" },
3640 #endif
3641 #ifdef IFF_SLAVE
3642 { IFF_SLAVE, "slave" },
3643 #endif
3644 #ifdef IFF_MULTICAST
3645 { IFF_MULTICAST, "multicast" },
3646 #endif
3647 #ifdef IFF_PORTSEL
3648 { IFF_PORTSEL, "portsel" },
3649 #endif
3650 #ifdef IFF_AUTOMEDIA
3651 { IFF_AUTOMEDIA, "automedia" },
3652 #endif
3653 #ifdef IFF_DYNAMIC
3654 { IFF_DYNAMIC, "dynamic" },
3655 #endif
3656 #ifdef IFF_OACTIVE
3657 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3658 #endif
3659 #ifdef IFF_SIMPLEX
3660 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3661 #endif
3662 #ifdef IFF_LINK0
3663 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3664 #endif
3665 #ifdef IFF_LINK1
3666 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3667 #endif
3668 #ifdef IFF_LINK2
3669 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3670 #endif
3671 { 0, 0 }
3674 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3675 doc: /* Return information about network interface named IFNAME.
3676 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3677 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3678 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3679 FLAGS is the current flags of the interface. */)
3680 (Lisp_Object ifname)
3682 struct ifreq rq;
3683 Lisp_Object res = Qnil;
3684 Lisp_Object elt;
3685 int s;
3686 bool any = 0;
3687 ptrdiff_t count;
3688 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3689 && defined HAVE_GETIFADDRS && defined LLADDR)
3690 struct ifaddrs *ifap;
3691 #endif
3693 CHECK_STRING (ifname);
3695 if (sizeof rq.ifr_name <= SBYTES (ifname))
3696 error ("interface name too long");
3697 strcpy (rq.ifr_name, SSDATA (ifname));
3699 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3700 if (s < 0)
3701 return Qnil;
3702 count = SPECPDL_INDEX ();
3703 record_unwind_protect_int (close_file_unwind, s);
3705 elt = Qnil;
3706 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3707 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3709 int flags = rq.ifr_flags;
3710 const struct ifflag_def *fp;
3711 int fnum;
3713 /* If flags is smaller than int (i.e. short) it may have the high bit set
3714 due to IFF_MULTICAST. In that case, sign extending it into
3715 an int is wrong. */
3716 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3717 flags = (unsigned short) rq.ifr_flags;
3719 any = 1;
3720 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3722 if (flags & fp->flag_bit)
3724 elt = Fcons (intern (fp->flag_sym), elt);
3725 flags -= fp->flag_bit;
3728 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3730 if (flags & 1)
3732 elt = Fcons (make_number (fnum), elt);
3736 #endif
3737 res = Fcons (elt, res);
3739 elt = Qnil;
3740 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3741 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3743 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3744 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3745 int n;
3747 any = 1;
3748 for (n = 0; n < 6; n++)
3749 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3750 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3752 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3753 if (getifaddrs (&ifap) != -1)
3755 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3756 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3757 struct ifaddrs *it;
3759 for (it = ifap; it != NULL; it = it->ifa_next)
3761 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3762 unsigned char linkaddr[6];
3763 int n;
3765 if (it->ifa_addr->sa_family != AF_LINK
3766 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3767 || sdl->sdl_alen != 6)
3768 continue;
3770 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3771 for (n = 0; n < 6; n++)
3772 p->contents[n] = make_number (linkaddr[n]);
3774 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3775 break;
3778 #ifdef HAVE_FREEIFADDRS
3779 freeifaddrs (ifap);
3780 #endif
3782 #endif /* HAVE_GETIFADDRS && LLADDR */
3784 res = Fcons (elt, res);
3786 elt = Qnil;
3787 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3788 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3790 any = 1;
3791 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3792 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3793 #else
3794 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3795 #endif
3797 #endif
3798 res = Fcons (elt, res);
3800 elt = Qnil;
3801 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3802 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3804 any = 1;
3805 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3807 #endif
3808 res = Fcons (elt, res);
3810 elt = Qnil;
3811 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3812 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3814 any = 1;
3815 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3817 #endif
3818 res = Fcons (elt, res);
3820 return unbind_to (count, any ? res : Qnil);
3822 #endif
3823 #endif /* defined (HAVE_NET_IF_H) */
3825 /* Turn off input and output for process PROC. */
3827 static void
3828 deactivate_process (Lisp_Object proc)
3830 int inchannel;
3831 struct Lisp_Process *p = XPROCESS (proc);
3832 int i;
3834 #ifdef HAVE_GNUTLS
3835 /* Delete GnuTLS structures in PROC, if any. */
3836 emacs_gnutls_deinit (proc);
3837 #endif /* HAVE_GNUTLS */
3839 #ifdef ADAPTIVE_READ_BUFFERING
3840 if (p->read_output_delay > 0)
3842 if (--process_output_delay_count < 0)
3843 process_output_delay_count = 0;
3844 p->read_output_delay = 0;
3845 p->read_output_skip = 0;
3847 #endif
3849 inchannel = p->infd;
3851 /* Beware SIGCHLD hereabouts. */
3852 if (inchannel >= 0)
3853 flush_pending_output (inchannel);
3855 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3856 close_process_fd (&p->open_fd[i]);
3858 if (inchannel >= 0)
3860 p->infd = -1;
3861 p->outfd = -1;
3862 #ifdef DATAGRAM_SOCKETS
3863 if (DATAGRAM_CHAN_P (inchannel))
3865 xfree (datagram_address[inchannel].sa);
3866 datagram_address[inchannel].sa = 0;
3867 datagram_address[inchannel].len = 0;
3869 #endif
3870 chan_process[inchannel] = Qnil;
3871 FD_CLR (inchannel, &input_wait_mask);
3872 FD_CLR (inchannel, &non_keyboard_wait_mask);
3873 #ifdef NON_BLOCKING_CONNECT
3874 if (FD_ISSET (inchannel, &connect_wait_mask))
3876 FD_CLR (inchannel, &connect_wait_mask);
3877 FD_CLR (inchannel, &write_mask);
3878 if (--num_pending_connects < 0)
3879 emacs_abort ();
3881 #endif
3882 if (inchannel == max_process_desc)
3884 /* We just closed the highest-numbered process input descriptor,
3885 so recompute the highest-numbered one now. */
3886 int i = inchannel;
3888 i--;
3889 while (0 <= i && NILP (chan_process[i]));
3891 max_process_desc = i;
3897 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3898 0, 4, 0,
3899 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3900 It is read into the process' buffers or given to their filter functions.
3901 Non-nil arg PROCESS means do not return until some output has been received
3902 from PROCESS.
3904 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3905 and milliseconds to wait; return after that much time whether or not
3906 there is any subprocess output. If SECONDS is a floating point number,
3907 it specifies a fractional number of seconds to wait.
3908 The MILLISEC argument is obsolete and should be avoided.
3910 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3911 from PROCESS, suspending reading output from other processes.
3912 If JUST-THIS-ONE is an integer, don't run any timers either.
3913 Return non-nil if we received any output before the timeout expired. */)
3914 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3916 intmax_t secs;
3917 int nsecs;
3919 if (! NILP (process))
3920 CHECK_PROCESS (process);
3921 else
3922 just_this_one = Qnil;
3924 if (!NILP (millisec))
3925 { /* Obsolete calling convention using integers rather than floats. */
3926 CHECK_NUMBER (millisec);
3927 if (NILP (seconds))
3928 seconds = make_float (XINT (millisec) / 1000.0);
3929 else
3931 CHECK_NUMBER (seconds);
3932 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3936 secs = 0;
3937 nsecs = -1;
3939 if (!NILP (seconds))
3941 if (INTEGERP (seconds))
3943 if (XINT (seconds) > 0)
3945 secs = XINT (seconds);
3946 nsecs = 0;
3949 else if (FLOATP (seconds))
3951 if (XFLOAT_DATA (seconds) > 0)
3953 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3954 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3955 nsecs = EMACS_NSECS (t);
3958 else
3959 wrong_type_argument (Qnumberp, seconds);
3961 else if (! NILP (process))
3962 nsecs = 0;
3964 return
3965 (wait_reading_process_output (secs, nsecs, 0, 0,
3966 Qnil,
3967 !NILP (process) ? XPROCESS (process) : NULL,
3968 NILP (just_this_one) ? 0 :
3969 !INTEGERP (just_this_one) ? 1 : -1)
3970 ? Qt : Qnil);
3973 /* Accept a connection for server process SERVER on CHANNEL. */
3975 static EMACS_INT connect_counter = 0;
3977 static void
3978 server_accept_connection (Lisp_Object server, int channel)
3980 Lisp_Object proc, caller, name, buffer;
3981 Lisp_Object contact, host, service;
3982 struct Lisp_Process *ps= XPROCESS (server);
3983 struct Lisp_Process *p;
3984 int s;
3985 union u_sockaddr {
3986 struct sockaddr sa;
3987 struct sockaddr_in in;
3988 #ifdef AF_INET6
3989 struct sockaddr_in6 in6;
3990 #endif
3991 #ifdef HAVE_LOCAL_SOCKETS
3992 struct sockaddr_un un;
3993 #endif
3994 } saddr;
3995 socklen_t len = sizeof saddr;
3996 ptrdiff_t count;
3998 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4000 if (s < 0)
4002 int code = errno;
4004 if (code == EAGAIN)
4005 return;
4006 #ifdef EWOULDBLOCK
4007 if (code == EWOULDBLOCK)
4008 return;
4009 #endif
4011 if (!NILP (ps->log))
4012 call3 (ps->log, server, Qnil,
4013 concat3 (build_string ("accept failed with code"),
4014 Fnumber_to_string (make_number (code)),
4015 build_string ("\n")));
4016 return;
4019 count = SPECPDL_INDEX ();
4020 record_unwind_protect_int (close_file_unwind, s);
4022 connect_counter++;
4024 /* Setup a new process to handle the connection. */
4026 /* Generate a unique identification of the caller, and build contact
4027 information for this process. */
4028 host = Qt;
4029 service = Qnil;
4030 switch (saddr.sa.sa_family)
4032 case AF_INET:
4034 Lisp_Object args[5];
4035 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4036 args[0] = build_string ("%d.%d.%d.%d");
4037 args[1] = make_number (*ip++);
4038 args[2] = make_number (*ip++);
4039 args[3] = make_number (*ip++);
4040 args[4] = make_number (*ip++);
4041 host = Fformat (5, args);
4042 service = make_number (ntohs (saddr.in.sin_port));
4044 args[0] = build_string (" <%s:%d>");
4045 args[1] = host;
4046 args[2] = service;
4047 caller = Fformat (3, args);
4049 break;
4051 #ifdef AF_INET6
4052 case AF_INET6:
4054 Lisp_Object args[9];
4055 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4056 int i;
4057 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4058 for (i = 0; i < 8; i++)
4059 args[i+1] = make_number (ntohs (ip6[i]));
4060 host = Fformat (9, args);
4061 service = make_number (ntohs (saddr.in.sin_port));
4063 args[0] = build_string (" <[%s]:%d>");
4064 args[1] = host;
4065 args[2] = service;
4066 caller = Fformat (3, args);
4068 break;
4069 #endif
4071 #ifdef HAVE_LOCAL_SOCKETS
4072 case AF_LOCAL:
4073 #endif
4074 default:
4075 caller = Fnumber_to_string (make_number (connect_counter));
4076 caller = concat3 (build_string (" <"), caller, build_string (">"));
4077 break;
4080 /* Create a new buffer name for this process if it doesn't have a
4081 filter. The new buffer name is based on the buffer name or
4082 process name of the server process concatenated with the caller
4083 identification. */
4085 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4086 || EQ (ps->filter, Qt)))
4087 buffer = Qnil;
4088 else
4090 buffer = ps->buffer;
4091 if (!NILP (buffer))
4092 buffer = Fbuffer_name (buffer);
4093 else
4094 buffer = ps->name;
4095 if (!NILP (buffer))
4097 buffer = concat2 (buffer, caller);
4098 buffer = Fget_buffer_create (buffer);
4102 /* Generate a unique name for the new server process. Combine the
4103 server process name with the caller identification. */
4105 name = concat2 (ps->name, caller);
4106 proc = make_process (name);
4108 chan_process[s] = proc;
4110 fcntl (s, F_SETFL, O_NONBLOCK);
4112 p = XPROCESS (proc);
4114 /* Build new contact information for this setup. */
4115 contact = Fcopy_sequence (ps->childp);
4116 contact = Fplist_put (contact, QCserver, Qnil);
4117 contact = Fplist_put (contact, QChost, host);
4118 if (!NILP (service))
4119 contact = Fplist_put (contact, QCservice, service);
4120 contact = Fplist_put (contact, QCremote,
4121 conv_sockaddr_to_lisp (&saddr.sa, len));
4122 #ifdef HAVE_GETSOCKNAME
4123 len = sizeof saddr;
4124 if (getsockname (s, &saddr.sa, &len) == 0)
4125 contact = Fplist_put (contact, QClocal,
4126 conv_sockaddr_to_lisp (&saddr.sa, len));
4127 #endif
4129 pset_childp (p, contact);
4130 pset_plist (p, Fcopy_sequence (ps->plist));
4131 pset_type (p, Qnetwork);
4133 pset_buffer (p, buffer);
4134 pset_sentinel (p, ps->sentinel);
4135 pset_filter (p, ps->filter);
4136 pset_command (p, Qnil);
4137 p->pid = 0;
4139 /* Discard the unwind protect for closing S. */
4140 specpdl_ptr = specpdl + count;
4142 p->open_fd[SUBPROCESS_STDIN] = s;
4143 p->infd = s;
4144 p->outfd = s;
4145 pset_status (p, Qrun);
4147 /* Client processes for accepted connections are not stopped initially. */
4148 if (!EQ (p->filter, Qt))
4150 FD_SET (s, &input_wait_mask);
4151 FD_SET (s, &non_keyboard_wait_mask);
4154 if (s > max_process_desc)
4155 max_process_desc = s;
4157 /* Setup coding system for new process based on server process.
4158 This seems to be the proper thing to do, as the coding system
4159 of the new process should reflect the settings at the time the
4160 server socket was opened; not the current settings. */
4162 pset_decode_coding_system (p, ps->decode_coding_system);
4163 pset_encode_coding_system (p, ps->encode_coding_system);
4164 setup_process_coding_systems (proc);
4166 pset_decoding_buf (p, empty_unibyte_string);
4167 p->decoding_carryover = 0;
4168 pset_encoding_buf (p, empty_unibyte_string);
4170 p->inherit_coding_system_flag
4171 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4173 if (!NILP (ps->log))
4174 call3 (ps->log, server, proc,
4175 concat3 (build_string ("accept from "),
4176 (STRINGP (host) ? host : build_string ("-")),
4177 build_string ("\n")));
4179 exec_sentinel (proc,
4180 concat3 (build_string ("open from "),
4181 (STRINGP (host) ? host : build_string ("-")),
4182 build_string ("\n")));
4185 /* This variable is different from waiting_for_input in keyboard.c.
4186 It is used to communicate to a lisp process-filter/sentinel (via the
4187 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4188 for user-input when that process-filter was called.
4189 waiting_for_input cannot be used as that is by definition 0 when
4190 lisp code is being evalled.
4191 This is also used in record_asynch_buffer_change.
4192 For that purpose, this must be 0
4193 when not inside wait_reading_process_output. */
4194 static int waiting_for_user_input_p;
4196 static void
4197 wait_reading_process_output_unwind (int data)
4199 waiting_for_user_input_p = data;
4202 /* This is here so breakpoints can be put on it. */
4203 static void
4204 wait_reading_process_output_1 (void)
4208 /* Read and dispose of subprocess output while waiting for timeout to
4209 elapse and/or keyboard input to be available.
4211 TIME_LIMIT is:
4212 timeout in seconds
4213 If negative, gobble data immediately available but don't wait for any.
4215 NSECS is:
4216 an additional duration to wait, measured in nanoseconds
4217 If TIME_LIMIT is zero, then:
4218 If NSECS == 0, there is no limit.
4219 If NSECS > 0, the timeout consists of NSECS only.
4220 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4222 READ_KBD is:
4223 0 to ignore keyboard input, or
4224 1 to return when input is available, or
4225 -1 meaning caller will actually read the input, so don't throw to
4226 the quit handler, or
4228 DO_DISPLAY means redisplay should be done to show subprocess
4229 output that arrives.
4231 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4232 (and gobble terminal input into the buffer if any arrives).
4234 If WAIT_PROC is specified, wait until something arrives from that
4235 process. The return value is true if we read some input from
4236 that process.
4238 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4239 (suspending output from other processes). A negative value
4240 means don't run any timers either.
4242 If WAIT_PROC is specified, then the function returns true if we
4243 received input from that process before the timeout elapsed.
4244 Otherwise, return true if we received input from any process. */
4246 bool
4247 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4248 bool do_display,
4249 Lisp_Object wait_for_cell,
4250 struct Lisp_Process *wait_proc, int just_wait_proc)
4252 int channel, nfds;
4253 SELECT_TYPE Available;
4254 SELECT_TYPE Writeok;
4255 bool check_write;
4256 int check_delay;
4257 bool no_avail;
4258 int xerrno;
4259 Lisp_Object proc;
4260 EMACS_TIME timeout, end_time;
4261 int wait_channel = -1;
4262 bool got_some_input = 0;
4263 ptrdiff_t count = SPECPDL_INDEX ();
4265 FD_ZERO (&Available);
4266 FD_ZERO (&Writeok);
4268 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4269 && !(CONSP (wait_proc->status)
4270 && EQ (XCAR (wait_proc->status), Qexit)))
4271 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4273 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4274 if (wait_proc != NULL)
4275 wait_channel = wait_proc->infd;
4277 record_unwind_protect_int (wait_reading_process_output_unwind,
4278 waiting_for_user_input_p);
4279 waiting_for_user_input_p = read_kbd;
4281 if (time_limit < 0)
4283 time_limit = 0;
4284 nsecs = -1;
4286 else if (TYPE_MAXIMUM (time_t) < time_limit)
4287 time_limit = TYPE_MAXIMUM (time_t);
4289 /* Since we may need to wait several times,
4290 compute the absolute time to return at. */
4291 if (time_limit || nsecs > 0)
4293 timeout = make_emacs_time (time_limit, nsecs);
4294 end_time = add_emacs_time (current_emacs_time (), timeout);
4297 while (1)
4299 bool timeout_reduced_for_timers = 0;
4301 /* If calling from keyboard input, do not quit
4302 since we want to return C-g as an input character.
4303 Otherwise, do pending quit if requested. */
4304 if (read_kbd >= 0)
4305 QUIT;
4306 else if (pending_signals)
4307 process_pending_signals ();
4309 /* Exit now if the cell we're waiting for became non-nil. */
4310 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4311 break;
4313 /* Compute time from now till when time limit is up. */
4314 /* Exit if already run out. */
4315 if (nsecs < 0)
4317 /* A negative timeout means
4318 gobble output available now
4319 but don't wait at all. */
4321 timeout = make_emacs_time (0, 0);
4323 else if (time_limit || nsecs > 0)
4325 EMACS_TIME now = current_emacs_time ();
4326 if (EMACS_TIME_LE (end_time, now))
4327 break;
4328 timeout = sub_emacs_time (end_time, now);
4330 else
4332 timeout = make_emacs_time (100000, 0);
4335 /* Normally we run timers here.
4336 But not if wait_for_cell; in those cases,
4337 the wait is supposed to be short,
4338 and those callers cannot handle running arbitrary Lisp code here. */
4339 if (NILP (wait_for_cell)
4340 && just_wait_proc >= 0)
4342 EMACS_TIME timer_delay;
4346 unsigned old_timers_run = timers_run;
4347 struct buffer *old_buffer = current_buffer;
4348 Lisp_Object old_window = selected_window;
4350 timer_delay = timer_check ();
4352 /* If a timer has run, this might have changed buffers
4353 an alike. Make read_key_sequence aware of that. */
4354 if (timers_run != old_timers_run
4355 && (old_buffer != current_buffer
4356 || !EQ (old_window, selected_window))
4357 && waiting_for_user_input_p == -1)
4358 record_asynch_buffer_change ();
4360 if (timers_run != old_timers_run && do_display)
4361 /* We must retry, since a timer may have requeued itself
4362 and that could alter the time_delay. */
4363 redisplay_preserve_echo_area (9);
4364 else
4365 break;
4367 while (!detect_input_pending ());
4369 /* If there is unread keyboard input, also return. */
4370 if (read_kbd != 0
4371 && requeued_events_pending_p ())
4372 break;
4374 /* A negative timeout means do not wait at all. */
4375 if (nsecs >= 0)
4377 if (EMACS_TIME_VALID_P (timer_delay))
4379 if (EMACS_TIME_LT (timer_delay, timeout))
4381 timeout = timer_delay;
4382 timeout_reduced_for_timers = 1;
4385 else
4387 /* This is so a breakpoint can be put here. */
4388 wait_reading_process_output_1 ();
4393 /* Cause C-g and alarm signals to take immediate action,
4394 and cause input available signals to zero out timeout.
4396 It is important that we do this before checking for process
4397 activity. If we get a SIGCHLD after the explicit checks for
4398 process activity, timeout is the only way we will know. */
4399 if (read_kbd < 0)
4400 set_waiting_for_input (&timeout);
4402 /* If status of something has changed, and no input is
4403 available, notify the user of the change right away. After
4404 this explicit check, we'll let the SIGCHLD handler zap
4405 timeout to get our attention. */
4406 if (update_tick != process_tick)
4408 SELECT_TYPE Atemp;
4409 SELECT_TYPE Ctemp;
4411 if (kbd_on_hold_p ())
4412 FD_ZERO (&Atemp);
4413 else
4414 Atemp = input_wait_mask;
4415 Ctemp = write_mask;
4417 timeout = make_emacs_time (0, 0);
4418 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4419 &Atemp,
4420 #ifdef NON_BLOCKING_CONNECT
4421 (num_pending_connects > 0 ? &Ctemp : NULL),
4422 #else
4423 NULL,
4424 #endif
4425 NULL, &timeout, NULL)
4426 <= 0))
4428 /* It's okay for us to do this and then continue with
4429 the loop, since timeout has already been zeroed out. */
4430 clear_waiting_for_input ();
4431 status_notify (NULL);
4432 if (do_display) redisplay_preserve_echo_area (13);
4436 /* Don't wait for output from a non-running process. Just
4437 read whatever data has already been received. */
4438 if (wait_proc && wait_proc->raw_status_new)
4439 update_status (wait_proc);
4440 if (wait_proc
4441 && ! EQ (wait_proc->status, Qrun)
4442 && ! EQ (wait_proc->status, Qconnect))
4444 bool read_some_bytes = 0;
4446 clear_waiting_for_input ();
4447 XSETPROCESS (proc, wait_proc);
4449 /* Read data from the process, until we exhaust it. */
4450 while (wait_proc->infd >= 0)
4452 int nread = read_process_output (proc, wait_proc->infd);
4454 if (nread == 0)
4455 break;
4457 if (nread > 0)
4458 got_some_input = read_some_bytes = 1;
4459 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4460 break;
4461 #ifdef EWOULDBLOCK
4462 else if (nread == -1 && EWOULDBLOCK == errno)
4463 break;
4464 #endif
4466 if (read_some_bytes && do_display)
4467 redisplay_preserve_echo_area (10);
4469 break;
4472 /* Wait till there is something to do */
4474 if (wait_proc && just_wait_proc)
4476 if (wait_proc->infd < 0) /* Terminated */
4477 break;
4478 FD_SET (wait_proc->infd, &Available);
4479 check_delay = 0;
4480 check_write = 0;
4482 else if (!NILP (wait_for_cell))
4484 Available = non_process_wait_mask;
4485 check_delay = 0;
4486 check_write = 0;
4488 else
4490 if (! read_kbd)
4491 Available = non_keyboard_wait_mask;
4492 else
4493 Available = input_wait_mask;
4494 Writeok = write_mask;
4495 #ifdef SELECT_CANT_DO_WRITE_MASK
4496 check_write = 0;
4497 #else
4498 check_write = 1;
4499 #endif
4500 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4503 /* If frame size has changed or the window is newly mapped,
4504 redisplay now, before we start to wait. There is a race
4505 condition here; if a SIGIO arrives between now and the select
4506 and indicates that a frame is trashed, the select may block
4507 displaying a trashed screen. */
4508 if (frame_garbaged && do_display)
4510 clear_waiting_for_input ();
4511 redisplay_preserve_echo_area (11);
4512 if (read_kbd < 0)
4513 set_waiting_for_input (&timeout);
4516 /* Skip the `select' call if input is available and we're
4517 waiting for keyboard input or a cell change (which can be
4518 triggered by processing X events). In the latter case, set
4519 nfds to 1 to avoid breaking the loop. */
4520 no_avail = 0;
4521 if ((read_kbd || !NILP (wait_for_cell))
4522 && detect_input_pending ())
4524 nfds = read_kbd ? 0 : 1;
4525 no_avail = 1;
4528 if (!no_avail)
4531 #ifdef ADAPTIVE_READ_BUFFERING
4532 /* Set the timeout for adaptive read buffering if any
4533 process has non-zero read_output_skip and non-zero
4534 read_output_delay, and we are not reading output for a
4535 specific wait_channel. It is not executed if
4536 Vprocess_adaptive_read_buffering is nil. */
4537 if (process_output_skip && check_delay > 0)
4539 int nsecs = EMACS_NSECS (timeout);
4540 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4541 nsecs = READ_OUTPUT_DELAY_MAX;
4542 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4544 proc = chan_process[channel];
4545 if (NILP (proc))
4546 continue;
4547 /* Find minimum non-zero read_output_delay among the
4548 processes with non-zero read_output_skip. */
4549 if (XPROCESS (proc)->read_output_delay > 0)
4551 check_delay--;
4552 if (!XPROCESS (proc)->read_output_skip)
4553 continue;
4554 FD_CLR (channel, &Available);
4555 XPROCESS (proc)->read_output_skip = 0;
4556 if (XPROCESS (proc)->read_output_delay < nsecs)
4557 nsecs = XPROCESS (proc)->read_output_delay;
4560 timeout = make_emacs_time (0, nsecs);
4561 process_output_skip = 0;
4563 #endif
4565 #if defined (HAVE_NS)
4566 nfds = ns_select
4567 #elif defined (HAVE_GLIB)
4568 nfds = xg_select
4569 #else
4570 nfds = pselect
4571 #endif
4572 (max (max_process_desc, max_input_desc) + 1,
4573 &Available,
4574 (check_write ? &Writeok : 0),
4575 NULL, &timeout, NULL);
4577 #ifdef HAVE_GNUTLS
4578 /* GnuTLS buffers data internally. In lowat mode it leaves
4579 some data in the TCP buffers so that select works, but
4580 with custom pull/push functions we need to check if some
4581 data is available in the buffers manually. */
4582 if (nfds == 0)
4584 if (! wait_proc)
4586 /* We're not waiting on a specific process, so loop
4587 through all the channels and check for data.
4588 This is a workaround needed for some versions of
4589 the gnutls library -- 2.12.14 has been confirmed
4590 to need it. See
4591 http://comments.gmane.org/gmane.emacs.devel/145074 */
4592 for (channel = 0; channel < MAXDESC; ++channel)
4593 if (! NILP (chan_process[channel]))
4595 struct Lisp_Process *p =
4596 XPROCESS (chan_process[channel]);
4597 if (p && p->gnutls_p && p->infd
4598 && ((emacs_gnutls_record_check_pending
4599 (p->gnutls_state))
4600 > 0))
4602 nfds++;
4603 FD_SET (p->infd, &Available);
4607 else
4609 /* Check this specific channel. */
4610 if (wait_proc->gnutls_p /* Check for valid process. */
4611 /* Do we have pending data? */
4612 && ((emacs_gnutls_record_check_pending
4613 (wait_proc->gnutls_state))
4614 > 0))
4616 nfds = 1;
4617 /* Set to Available. */
4618 FD_SET (wait_proc->infd, &Available);
4622 #endif
4625 xerrno = errno;
4627 /* Make C-g and alarm signals set flags again */
4628 clear_waiting_for_input ();
4630 /* If we woke up due to SIGWINCH, actually change size now. */
4631 do_pending_window_change (0);
4633 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4634 /* We waited the full specified time, so return now. */
4635 break;
4636 if (nfds < 0)
4638 if (xerrno == EINTR)
4639 no_avail = 1;
4640 else if (xerrno == EBADF)
4641 emacs_abort ();
4642 else
4643 report_file_errno ("Failed select", Qnil, xerrno);
4646 if (no_avail)
4648 FD_ZERO (&Available);
4649 check_write = 0;
4652 /* Check for keyboard input */
4653 /* If there is any, return immediately
4654 to give it higher priority than subprocesses */
4656 if (read_kbd != 0)
4658 unsigned old_timers_run = timers_run;
4659 struct buffer *old_buffer = current_buffer;
4660 Lisp_Object old_window = selected_window;
4661 bool leave = 0;
4663 if (detect_input_pending_run_timers (do_display))
4665 swallow_events (do_display);
4666 if (detect_input_pending_run_timers (do_display))
4667 leave = 1;
4670 /* If a timer has run, this might have changed buffers
4671 an alike. Make read_key_sequence aware of that. */
4672 if (timers_run != old_timers_run
4673 && waiting_for_user_input_p == -1
4674 && (old_buffer != current_buffer
4675 || !EQ (old_window, selected_window)))
4676 record_asynch_buffer_change ();
4678 if (leave)
4679 break;
4682 /* If there is unread keyboard input, also return. */
4683 if (read_kbd != 0
4684 && requeued_events_pending_p ())
4685 break;
4687 /* If we are not checking for keyboard input now,
4688 do process events (but don't run any timers).
4689 This is so that X events will be processed.
4690 Otherwise they may have to wait until polling takes place.
4691 That would causes delays in pasting selections, for example.
4693 (We used to do this only if wait_for_cell.) */
4694 if (read_kbd == 0 && detect_input_pending ())
4696 swallow_events (do_display);
4697 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4698 if (detect_input_pending ())
4699 break;
4700 #endif
4703 /* Exit now if the cell we're waiting for became non-nil. */
4704 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4705 break;
4707 #ifdef USABLE_SIGIO
4708 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4709 go read it. This can happen with X on BSD after logging out.
4710 In that case, there really is no input and no SIGIO,
4711 but select says there is input. */
4713 if (read_kbd && interrupt_input
4714 && keyboard_bit_set (&Available) && ! noninteractive)
4715 handle_input_available_signal (SIGIO);
4716 #endif
4718 if (! wait_proc)
4719 got_some_input |= nfds > 0;
4721 /* If checking input just got us a size-change event from X,
4722 obey it now if we should. */
4723 if (read_kbd || ! NILP (wait_for_cell))
4724 do_pending_window_change (0);
4726 /* Check for data from a process. */
4727 if (no_avail || nfds == 0)
4728 continue;
4730 for (channel = 0; channel <= max_input_desc; ++channel)
4732 struct fd_callback_data *d = &fd_callback_info[channel];
4733 if (d->func
4734 && ((d->condition & FOR_READ
4735 && FD_ISSET (channel, &Available))
4736 || (d->condition & FOR_WRITE
4737 && FD_ISSET (channel, &write_mask))))
4738 d->func (channel, d->data);
4741 for (channel = 0; channel <= max_process_desc; channel++)
4743 if (FD_ISSET (channel, &Available)
4744 && FD_ISSET (channel, &non_keyboard_wait_mask)
4745 && !FD_ISSET (channel, &non_process_wait_mask))
4747 int nread;
4749 /* If waiting for this channel, arrange to return as
4750 soon as no more input to be processed. No more
4751 waiting. */
4752 if (wait_channel == channel)
4754 wait_channel = -1;
4755 nsecs = -1;
4756 got_some_input = 1;
4758 proc = chan_process[channel];
4759 if (NILP (proc))
4760 continue;
4762 /* If this is a server stream socket, accept connection. */
4763 if (EQ (XPROCESS (proc)->status, Qlisten))
4765 server_accept_connection (proc, channel);
4766 continue;
4769 /* Read data from the process, starting with our
4770 buffered-ahead character if we have one. */
4772 nread = read_process_output (proc, channel);
4773 if (nread > 0)
4775 /* Since read_process_output can run a filter,
4776 which can call accept-process-output,
4777 don't try to read from any other processes
4778 before doing the select again. */
4779 FD_ZERO (&Available);
4781 if (do_display)
4782 redisplay_preserve_echo_area (12);
4784 #ifdef EWOULDBLOCK
4785 else if (nread == -1 && errno == EWOULDBLOCK)
4787 #endif
4788 else if (nread == -1 && errno == EAGAIN)
4790 #ifdef WINDOWSNT
4791 /* FIXME: Is this special case still needed? */
4792 /* Note that we cannot distinguish between no input
4793 available now and a closed pipe.
4794 With luck, a closed pipe will be accompanied by
4795 subprocess termination and SIGCHLD. */
4796 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4798 #endif
4799 #ifdef HAVE_PTYS
4800 /* On some OSs with ptys, when the process on one end of
4801 a pty exits, the other end gets an error reading with
4802 errno = EIO instead of getting an EOF (0 bytes read).
4803 Therefore, if we get an error reading and errno =
4804 EIO, just continue, because the child process has
4805 exited and should clean itself up soon (e.g. when we
4806 get a SIGCHLD). */
4807 else if (nread == -1 && errno == EIO)
4809 struct Lisp_Process *p = XPROCESS (proc);
4811 /* Clear the descriptor now, so we only raise the
4812 signal once. */
4813 FD_CLR (channel, &input_wait_mask);
4814 FD_CLR (channel, &non_keyboard_wait_mask);
4816 if (p->pid == -2)
4818 /* If the EIO occurs on a pty, the SIGCHLD handler's
4819 waitpid call will not find the process object to
4820 delete. Do it here. */
4821 p->tick = ++process_tick;
4822 pset_status (p, Qfailed);
4825 #endif /* HAVE_PTYS */
4826 /* If we can detect process termination, don't consider the
4827 process gone just because its pipe is closed. */
4828 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4830 else
4832 /* Preserve status of processes already terminated. */
4833 XPROCESS (proc)->tick = ++process_tick;
4834 deactivate_process (proc);
4835 if (XPROCESS (proc)->raw_status_new)
4836 update_status (XPROCESS (proc));
4837 if (EQ (XPROCESS (proc)->status, Qrun))
4838 pset_status (XPROCESS (proc),
4839 list2 (Qexit, make_number (256)));
4842 #ifdef NON_BLOCKING_CONNECT
4843 if (FD_ISSET (channel, &Writeok)
4844 && FD_ISSET (channel, &connect_wait_mask))
4846 struct Lisp_Process *p;
4848 FD_CLR (channel, &connect_wait_mask);
4849 FD_CLR (channel, &write_mask);
4850 if (--num_pending_connects < 0)
4851 emacs_abort ();
4853 proc = chan_process[channel];
4854 if (NILP (proc))
4855 continue;
4857 p = XPROCESS (proc);
4859 #ifdef GNU_LINUX
4860 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4861 So only use it on systems where it is known to work. */
4863 socklen_t xlen = sizeof (xerrno);
4864 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4865 xerrno = errno;
4867 #else
4869 struct sockaddr pname;
4870 int pnamelen = sizeof (pname);
4872 /* If connection failed, getpeername will fail. */
4873 xerrno = 0;
4874 if (getpeername (channel, &pname, &pnamelen) < 0)
4876 /* Obtain connect failure code through error slippage. */
4877 char dummy;
4878 xerrno = errno;
4879 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4880 xerrno = errno;
4883 #endif
4884 if (xerrno)
4886 p->tick = ++process_tick;
4887 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4888 deactivate_process (proc);
4890 else
4892 pset_status (p, Qrun);
4893 /* Execute the sentinel here. If we had relied on
4894 status_notify to do it later, it will read input
4895 from the process before calling the sentinel. */
4896 exec_sentinel (proc, build_string ("open\n"));
4897 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4899 FD_SET (p->infd, &input_wait_mask);
4900 FD_SET (p->infd, &non_keyboard_wait_mask);
4904 #endif /* NON_BLOCKING_CONNECT */
4905 } /* End for each file descriptor. */
4906 } /* End while exit conditions not met. */
4908 unbind_to (count, Qnil);
4910 /* If calling from keyboard input, do not quit
4911 since we want to return C-g as an input character.
4912 Otherwise, do pending quit if requested. */
4913 if (read_kbd >= 0)
4915 /* Prevent input_pending from remaining set if we quit. */
4916 clear_input_pending ();
4917 QUIT;
4920 return got_some_input;
4923 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4925 static Lisp_Object
4926 read_process_output_call (Lisp_Object fun_and_args)
4928 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4931 static Lisp_Object
4932 read_process_output_error_handler (Lisp_Object error_val)
4934 cmd_error_internal (error_val, "error in process filter: ");
4935 Vinhibit_quit = Qt;
4936 update_echo_area ();
4937 Fsleep_for (make_number (2), Qnil);
4938 return Qt;
4941 static void
4942 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4943 ssize_t nbytes,
4944 struct coding_system *coding);
4946 /* Read pending output from the process channel,
4947 starting with our buffered-ahead character if we have one.
4948 Yield number of decoded characters read.
4950 This function reads at most 4096 characters.
4951 If you want to read all available subprocess output,
4952 you must call it repeatedly until it returns zero.
4954 The characters read are decoded according to PROC's coding-system
4955 for decoding. */
4957 static int
4958 read_process_output (Lisp_Object proc, register int channel)
4960 register ssize_t nbytes;
4961 char *chars;
4962 register struct Lisp_Process *p = XPROCESS (proc);
4963 struct coding_system *coding = proc_decode_coding_system[channel];
4964 int carryover = p->decoding_carryover;
4965 int readmax = 4096;
4966 ptrdiff_t count = SPECPDL_INDEX ();
4967 Lisp_Object odeactivate;
4969 chars = alloca (carryover + readmax);
4970 if (carryover)
4971 /* See the comment above. */
4972 memcpy (chars, SDATA (p->decoding_buf), carryover);
4974 #ifdef DATAGRAM_SOCKETS
4975 /* We have a working select, so proc_buffered_char is always -1. */
4976 if (DATAGRAM_CHAN_P (channel))
4978 socklen_t len = datagram_address[channel].len;
4979 nbytes = recvfrom (channel, chars + carryover, readmax,
4980 0, datagram_address[channel].sa, &len);
4982 else
4983 #endif
4985 bool buffered = proc_buffered_char[channel] >= 0;
4986 if (buffered)
4988 chars[carryover] = proc_buffered_char[channel];
4989 proc_buffered_char[channel] = -1;
4991 #ifdef HAVE_GNUTLS
4992 if (p->gnutls_p)
4993 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
4994 readmax - buffered);
4995 else
4996 #endif
4997 nbytes = emacs_read (channel, chars + carryover + buffered,
4998 readmax - buffered);
4999 #ifdef ADAPTIVE_READ_BUFFERING
5000 if (nbytes > 0 && p->adaptive_read_buffering)
5002 int delay = p->read_output_delay;
5003 if (nbytes < 256)
5005 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5007 if (delay == 0)
5008 process_output_delay_count++;
5009 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5012 else if (delay > 0 && nbytes == readmax - buffered)
5014 delay -= READ_OUTPUT_DELAY_INCREMENT;
5015 if (delay == 0)
5016 process_output_delay_count--;
5018 p->read_output_delay = delay;
5019 if (delay)
5021 p->read_output_skip = 1;
5022 process_output_skip = 1;
5025 #endif
5026 nbytes += buffered;
5027 nbytes += buffered && nbytes <= 0;
5030 p->decoding_carryover = 0;
5032 /* At this point, NBYTES holds number of bytes just received
5033 (including the one in proc_buffered_char[channel]). */
5034 if (nbytes <= 0)
5036 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5037 return nbytes;
5038 coding->mode |= CODING_MODE_LAST_BLOCK;
5041 /* Now set NBYTES how many bytes we must decode. */
5042 nbytes += carryover;
5044 odeactivate = Vdeactivate_mark;
5045 /* There's no good reason to let process filters change the current
5046 buffer, and many callers of accept-process-output, sit-for, and
5047 friends don't expect current-buffer to be changed from under them. */
5048 record_unwind_current_buffer ();
5050 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5052 /* Handling the process output should not deactivate the mark. */
5053 Vdeactivate_mark = odeactivate;
5055 unbind_to (count, Qnil);
5056 return nbytes;
5059 static void
5060 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5061 ssize_t nbytes,
5062 struct coding_system *coding)
5064 Lisp_Object outstream = p->filter;
5065 Lisp_Object text;
5066 bool outer_running_asynch_code = running_asynch_code;
5067 int waiting = waiting_for_user_input_p;
5069 /* No need to gcpro these, because all we do with them later
5070 is test them for EQness, and none of them should be a string. */
5071 #if 0
5072 Lisp_Object obuffer, okeymap;
5073 XSETBUFFER (obuffer, current_buffer);
5074 okeymap = BVAR (current_buffer, keymap);
5075 #endif
5077 /* We inhibit quit here instead of just catching it so that
5078 hitting ^G when a filter happens to be running won't screw
5079 it up. */
5080 specbind (Qinhibit_quit, Qt);
5081 specbind (Qlast_nonmenu_event, Qt);
5083 /* In case we get recursively called,
5084 and we already saved the match data nonrecursively,
5085 save the same match data in safely recursive fashion. */
5086 if (outer_running_asynch_code)
5088 Lisp_Object tem;
5089 /* Don't clobber the CURRENT match data, either! */
5090 tem = Fmatch_data (Qnil, Qnil, Qnil);
5091 restore_search_regs ();
5092 record_unwind_save_match_data ();
5093 Fset_match_data (tem, Qt);
5096 /* For speed, if a search happens within this code,
5097 save the match data in a special nonrecursive fashion. */
5098 running_asynch_code = 1;
5100 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5101 text = coding->dst_object;
5102 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5103 /* A new coding system might be found. */
5104 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5106 pset_decode_coding_system (p, Vlast_coding_system_used);
5108 /* Don't call setup_coding_system for
5109 proc_decode_coding_system[channel] here. It is done in
5110 detect_coding called via decode_coding above. */
5112 /* If a coding system for encoding is not yet decided, we set
5113 it as the same as coding-system for decoding.
5115 But, before doing that we must check if
5116 proc_encode_coding_system[p->outfd] surely points to a
5117 valid memory because p->outfd will be changed once EOF is
5118 sent to the process. */
5119 if (NILP (p->encode_coding_system)
5120 && proc_encode_coding_system[p->outfd])
5122 pset_encode_coding_system
5123 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5124 setup_coding_system (p->encode_coding_system,
5125 proc_encode_coding_system[p->outfd]);
5129 if (coding->carryover_bytes > 0)
5131 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5132 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5133 memcpy (SDATA (p->decoding_buf), coding->carryover,
5134 coding->carryover_bytes);
5135 p->decoding_carryover = coding->carryover_bytes;
5137 if (SBYTES (text) > 0)
5138 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5139 sometimes it's simply wrong to wrap (e.g. when called from
5140 accept-process-output). */
5141 internal_condition_case_1 (read_process_output_call,
5142 list3 (outstream, make_lisp_proc (p), text),
5143 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5144 read_process_output_error_handler);
5146 /* If we saved the match data nonrecursively, restore it now. */
5147 restore_search_regs ();
5148 running_asynch_code = outer_running_asynch_code;
5150 /* Restore waiting_for_user_input_p as it was
5151 when we were called, in case the filter clobbered it. */
5152 waiting_for_user_input_p = waiting;
5154 #if 0 /* Call record_asynch_buffer_change unconditionally,
5155 because we might have changed minor modes or other things
5156 that affect key bindings. */
5157 if (! EQ (Fcurrent_buffer (), obuffer)
5158 || ! EQ (current_buffer->keymap, okeymap))
5159 #endif
5160 /* But do it only if the caller is actually going to read events.
5161 Otherwise there's no need to make him wake up, and it could
5162 cause trouble (for example it would make sit_for return). */
5163 if (waiting_for_user_input_p == -1)
5164 record_asynch_buffer_change ();
5167 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5168 Sinternal_default_process_filter, 2, 2, 0,
5169 doc: /* Function used as default process filter. */)
5170 (Lisp_Object proc, Lisp_Object text)
5172 struct Lisp_Process *p;
5173 ptrdiff_t opoint;
5175 CHECK_PROCESS (proc);
5176 p = XPROCESS (proc);
5177 CHECK_STRING (text);
5179 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5181 Lisp_Object old_read_only;
5182 ptrdiff_t old_begv, old_zv;
5183 ptrdiff_t old_begv_byte, old_zv_byte;
5184 ptrdiff_t before, before_byte;
5185 ptrdiff_t opoint_byte;
5186 struct buffer *b;
5188 Fset_buffer (p->buffer);
5189 opoint = PT;
5190 opoint_byte = PT_BYTE;
5191 old_read_only = BVAR (current_buffer, read_only);
5192 old_begv = BEGV;
5193 old_zv = ZV;
5194 old_begv_byte = BEGV_BYTE;
5195 old_zv_byte = ZV_BYTE;
5197 bset_read_only (current_buffer, Qnil);
5199 /* Insert new output into buffer
5200 at the current end-of-output marker,
5201 thus preserving logical ordering of input and output. */
5202 if (XMARKER (p->mark)->buffer)
5203 SET_PT_BOTH (clip_to_bounds (BEGV,
5204 marker_position (p->mark), ZV),
5205 clip_to_bounds (BEGV_BYTE,
5206 marker_byte_position (p->mark),
5207 ZV_BYTE));
5208 else
5209 SET_PT_BOTH (ZV, ZV_BYTE);
5210 before = PT;
5211 before_byte = PT_BYTE;
5213 /* If the output marker is outside of the visible region, save
5214 the restriction and widen. */
5215 if (! (BEGV <= PT && PT <= ZV))
5216 Fwiden ();
5218 /* Adjust the multibyteness of TEXT to that of the buffer. */
5219 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5220 != ! STRING_MULTIBYTE (text))
5221 text = (STRING_MULTIBYTE (text)
5222 ? Fstring_as_unibyte (text)
5223 : Fstring_to_multibyte (text));
5224 /* Insert before markers in case we are inserting where
5225 the buffer's mark is, and the user's next command is Meta-y. */
5226 insert_from_string_before_markers (text, 0, 0,
5227 SCHARS (text), SBYTES (text), 0);
5229 /* Make sure the process marker's position is valid when the
5230 process buffer is changed in the signal_after_change above.
5231 W3 is known to do that. */
5232 if (BUFFERP (p->buffer)
5233 && (b = XBUFFER (p->buffer), b != current_buffer))
5234 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5235 else
5236 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5238 update_mode_lines++;
5240 /* Make sure opoint and the old restrictions
5241 float ahead of any new text just as point would. */
5242 if (opoint >= before)
5244 opoint += PT - before;
5245 opoint_byte += PT_BYTE - before_byte;
5247 if (old_begv > before)
5249 old_begv += PT - before;
5250 old_begv_byte += PT_BYTE - before_byte;
5252 if (old_zv >= before)
5254 old_zv += PT - before;
5255 old_zv_byte += PT_BYTE - before_byte;
5258 /* If the restriction isn't what it should be, set it. */
5259 if (old_begv != BEGV || old_zv != ZV)
5260 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5262 bset_read_only (current_buffer, old_read_only);
5263 SET_PT_BOTH (opoint, opoint_byte);
5265 return Qnil;
5268 /* Sending data to subprocess. */
5270 /* In send_process, when a write fails temporarily,
5271 wait_reading_process_output is called. It may execute user code,
5272 e.g. timers, that attempts to write new data to the same process.
5273 We must ensure that data is sent in the right order, and not
5274 interspersed half-completed with other writes (Bug#10815). This is
5275 handled by the write_queue element of struct process. It is a list
5276 with each entry having the form
5278 (string . (offset . length))
5280 where STRING is a lisp string, OFFSET is the offset into the
5281 string's byte sequence from which we should begin to send, and
5282 LENGTH is the number of bytes left to send. */
5284 /* Create a new entry in write_queue.
5285 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5286 BUF is a pointer to the string sequence of the input_obj or a C
5287 string in case of Qt or Qnil. */
5289 static void
5290 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5291 const char *buf, ptrdiff_t len, bool front)
5293 ptrdiff_t offset;
5294 Lisp_Object entry, obj;
5296 if (STRINGP (input_obj))
5298 offset = buf - SSDATA (input_obj);
5299 obj = input_obj;
5301 else
5303 offset = 0;
5304 obj = make_unibyte_string (buf, len);
5307 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5309 if (front)
5310 pset_write_queue (p, Fcons (entry, p->write_queue));
5311 else
5312 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5315 /* Remove the first element in the write_queue of process P, put its
5316 contents in OBJ, BUF and LEN, and return true. If the
5317 write_queue is empty, return false. */
5319 static bool
5320 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5321 const char **buf, ptrdiff_t *len)
5323 Lisp_Object entry, offset_length;
5324 ptrdiff_t offset;
5326 if (NILP (p->write_queue))
5327 return 0;
5329 entry = XCAR (p->write_queue);
5330 pset_write_queue (p, XCDR (p->write_queue));
5332 *obj = XCAR (entry);
5333 offset_length = XCDR (entry);
5335 *len = XINT (XCDR (offset_length));
5336 offset = XINT (XCAR (offset_length));
5337 *buf = SSDATA (*obj) + offset;
5339 return 1;
5342 /* Send some data to process PROC.
5343 BUF is the beginning of the data; LEN is the number of characters.
5344 OBJECT is the Lisp object that the data comes from. If OBJECT is
5345 nil or t, it means that the data comes from C string.
5347 If OBJECT is not nil, the data is encoded by PROC's coding-system
5348 for encoding before it is sent.
5350 This function can evaluate Lisp code and can garbage collect. */
5352 static void
5353 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5354 Lisp_Object object)
5356 struct Lisp_Process *p = XPROCESS (proc);
5357 ssize_t rv;
5358 struct coding_system *coding;
5360 if (p->raw_status_new)
5361 update_status (p);
5362 if (! EQ (p->status, Qrun))
5363 error ("Process %s not running", SDATA (p->name));
5364 if (p->outfd < 0)
5365 error ("Output file descriptor of %s is closed", SDATA (p->name));
5367 coding = proc_encode_coding_system[p->outfd];
5368 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5370 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5371 || (BUFFERP (object)
5372 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5373 || EQ (object, Qt))
5375 pset_encode_coding_system
5376 (p, complement_process_encoding_system (p->encode_coding_system));
5377 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5379 /* The coding system for encoding was changed to raw-text
5380 because we sent a unibyte text previously. Now we are
5381 sending a multibyte text, thus we must encode it by the
5382 original coding system specified for the current process.
5384 Another reason we come here is that the coding system
5385 was just complemented and a new one was returned by
5386 complement_process_encoding_system. */
5387 setup_coding_system (p->encode_coding_system, coding);
5388 Vlast_coding_system_used = p->encode_coding_system;
5390 coding->src_multibyte = 1;
5392 else
5394 coding->src_multibyte = 0;
5395 /* For sending a unibyte text, character code conversion should
5396 not take place but EOL conversion should. So, setup raw-text
5397 or one of the subsidiary if we have not yet done it. */
5398 if (CODING_REQUIRE_ENCODING (coding))
5400 if (CODING_REQUIRE_FLUSHING (coding))
5402 /* But, before changing the coding, we must flush out data. */
5403 coding->mode |= CODING_MODE_LAST_BLOCK;
5404 send_process (proc, "", 0, Qt);
5405 coding->mode &= CODING_MODE_LAST_BLOCK;
5407 setup_coding_system (raw_text_coding_system
5408 (Vlast_coding_system_used),
5409 coding);
5410 coding->src_multibyte = 0;
5413 coding->dst_multibyte = 0;
5415 if (CODING_REQUIRE_ENCODING (coding))
5417 coding->dst_object = Qt;
5418 if (BUFFERP (object))
5420 ptrdiff_t from_byte, from, to;
5421 ptrdiff_t save_pt, save_pt_byte;
5422 struct buffer *cur = current_buffer;
5424 set_buffer_internal (XBUFFER (object));
5425 save_pt = PT, save_pt_byte = PT_BYTE;
5427 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5428 from = BYTE_TO_CHAR (from_byte);
5429 to = BYTE_TO_CHAR (from_byte + len);
5430 TEMP_SET_PT_BOTH (from, from_byte);
5431 encode_coding_object (coding, object, from, from_byte,
5432 to, from_byte + len, Qt);
5433 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5434 set_buffer_internal (cur);
5436 else if (STRINGP (object))
5438 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5439 SBYTES (object), Qt);
5441 else
5443 coding->dst_object = make_unibyte_string (buf, len);
5444 coding->produced = len;
5447 len = coding->produced;
5448 object = coding->dst_object;
5449 buf = SSDATA (object);
5452 /* If there is already data in the write_queue, put the new data
5453 in the back of queue. Otherwise, ignore it. */
5454 if (!NILP (p->write_queue))
5455 write_queue_push (p, object, buf, len, 0);
5457 do /* while !NILP (p->write_queue) */
5459 ptrdiff_t cur_len = -1;
5460 const char *cur_buf;
5461 Lisp_Object cur_object;
5463 /* If write_queue is empty, ignore it. */
5464 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5466 cur_len = len;
5467 cur_buf = buf;
5468 cur_object = object;
5471 while (cur_len > 0)
5473 /* Send this batch, using one or more write calls. */
5474 ptrdiff_t written = 0;
5475 int outfd = p->outfd;
5476 #ifdef DATAGRAM_SOCKETS
5477 if (DATAGRAM_CHAN_P (outfd))
5479 rv = sendto (outfd, cur_buf, cur_len,
5480 0, datagram_address[outfd].sa,
5481 datagram_address[outfd].len);
5482 if (rv >= 0)
5483 written = rv;
5484 else if (errno == EMSGSIZE)
5485 report_file_error ("Sending datagram", proc);
5487 else
5488 #endif
5490 #ifdef HAVE_GNUTLS
5491 if (p->gnutls_p)
5492 written = emacs_gnutls_write (p, cur_buf, cur_len);
5493 else
5494 #endif
5495 written = emacs_write_sig (outfd, cur_buf, cur_len);
5496 rv = (written ? 0 : -1);
5497 #ifdef ADAPTIVE_READ_BUFFERING
5498 if (p->read_output_delay > 0
5499 && p->adaptive_read_buffering == 1)
5501 p->read_output_delay = 0;
5502 process_output_delay_count--;
5503 p->read_output_skip = 0;
5505 #endif
5508 if (rv < 0)
5510 if (errno == EAGAIN
5511 #ifdef EWOULDBLOCK
5512 || errno == EWOULDBLOCK
5513 #endif
5515 /* Buffer is full. Wait, accepting input;
5516 that may allow the program
5517 to finish doing output and read more. */
5519 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5520 /* A gross hack to work around a bug in FreeBSD.
5521 In the following sequence, read(2) returns
5522 bogus data:
5524 write(2) 1022 bytes
5525 write(2) 954 bytes, get EAGAIN
5526 read(2) 1024 bytes in process_read_output
5527 read(2) 11 bytes in process_read_output
5529 That is, read(2) returns more bytes than have
5530 ever been written successfully. The 1033 bytes
5531 read are the 1022 bytes written successfully
5532 after processing (for example with CRs added if
5533 the terminal is set up that way which it is
5534 here). The same bytes will be seen again in a
5535 later read(2), without the CRs. */
5537 if (errno == EAGAIN)
5539 int flags = FWRITE;
5540 ioctl (p->outfd, TIOCFLUSH, &flags);
5542 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5544 /* Put what we should have written in wait_queue. */
5545 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5546 wait_reading_process_output (0, 20 * 1000 * 1000,
5547 0, 0, Qnil, NULL, 0);
5548 /* Reread queue, to see what is left. */
5549 break;
5551 else if (errno == EPIPE)
5553 p->raw_status_new = 0;
5554 pset_status (p, list2 (Qexit, make_number (256)));
5555 p->tick = ++process_tick;
5556 deactivate_process (proc);
5557 error ("process %s no longer connected to pipe; closed it",
5558 SDATA (p->name));
5560 else
5561 /* This is a real error. */
5562 report_file_error ("Writing to process", proc);
5564 cur_buf += written;
5565 cur_len -= written;
5568 while (!NILP (p->write_queue));
5571 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5572 3, 3, 0,
5573 doc: /* Send current contents of region as input to PROCESS.
5574 PROCESS may be a process, a buffer, the name of a process or buffer, or
5575 nil, indicating the current buffer's process.
5576 Called from program, takes three arguments, PROCESS, START and END.
5577 If the region is more than 500 characters long,
5578 it is sent in several bunches. This may happen even for shorter regions.
5579 Output from processes can arrive in between bunches. */)
5580 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5582 Lisp_Object proc = get_process (process);
5583 ptrdiff_t start_byte, end_byte;
5585 validate_region (&start, &end);
5587 start_byte = CHAR_TO_BYTE (XINT (start));
5588 end_byte = CHAR_TO_BYTE (XINT (end));
5590 if (XINT (start) < GPT && XINT (end) > GPT)
5591 move_gap_both (XINT (start), start_byte);
5593 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5594 end_byte - start_byte, Fcurrent_buffer ());
5596 return Qnil;
5599 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5600 2, 2, 0,
5601 doc: /* Send PROCESS the contents of STRING as input.
5602 PROCESS may be a process, a buffer, the name of a process or buffer, or
5603 nil, indicating the current buffer's process.
5604 If STRING is more than 500 characters long,
5605 it is sent in several bunches. This may happen even for shorter strings.
5606 Output from processes can arrive in between bunches. */)
5607 (Lisp_Object process, Lisp_Object string)
5609 Lisp_Object proc;
5610 CHECK_STRING (string);
5611 proc = get_process (process);
5612 send_process (proc, SSDATA (string),
5613 SBYTES (string), string);
5614 return Qnil;
5617 /* Return the foreground process group for the tty/pty that
5618 the process P uses. */
5619 static pid_t
5620 emacs_get_tty_pgrp (struct Lisp_Process *p)
5622 pid_t gid = -1;
5624 #ifdef TIOCGPGRP
5625 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5627 int fd;
5628 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5629 master side. Try the slave side. */
5630 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5632 if (fd != -1)
5634 ioctl (fd, TIOCGPGRP, &gid);
5635 emacs_close (fd);
5638 #endif /* defined (TIOCGPGRP ) */
5640 return gid;
5643 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5644 Sprocess_running_child_p, 0, 1, 0,
5645 doc: /* Return t if PROCESS has given the terminal to a child.
5646 If the operating system does not make it possible to find out,
5647 return t unconditionally. */)
5648 (Lisp_Object process)
5650 /* Initialize in case ioctl doesn't exist or gives an error,
5651 in a way that will cause returning t. */
5652 pid_t gid;
5653 Lisp_Object proc;
5654 struct Lisp_Process *p;
5656 proc = get_process (process);
5657 p = XPROCESS (proc);
5659 if (!EQ (p->type, Qreal))
5660 error ("Process %s is not a subprocess",
5661 SDATA (p->name));
5662 if (p->infd < 0)
5663 error ("Process %s is not active",
5664 SDATA (p->name));
5666 gid = emacs_get_tty_pgrp (p);
5668 if (gid == p->pid)
5669 return Qnil;
5670 return Qt;
5673 /* send a signal number SIGNO to PROCESS.
5674 If CURRENT_GROUP is t, that means send to the process group
5675 that currently owns the terminal being used to communicate with PROCESS.
5676 This is used for various commands in shell mode.
5677 If CURRENT_GROUP is lambda, that means send to the process group
5678 that currently owns the terminal, but only if it is NOT the shell itself.
5680 If NOMSG is false, insert signal-announcements into process's buffers
5681 right away.
5683 If we can, we try to signal PROCESS by sending control characters
5684 down the pty. This allows us to signal inferiors who have changed
5685 their uid, for which kill would return an EPERM error. */
5687 static void
5688 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5689 bool nomsg)
5691 Lisp_Object proc;
5692 struct Lisp_Process *p;
5693 pid_t gid;
5694 bool no_pgrp = 0;
5696 proc = get_process (process);
5697 p = XPROCESS (proc);
5699 if (!EQ (p->type, Qreal))
5700 error ("Process %s is not a subprocess",
5701 SDATA (p->name));
5702 if (p->infd < 0)
5703 error ("Process %s is not active",
5704 SDATA (p->name));
5706 if (!p->pty_flag)
5707 current_group = Qnil;
5709 /* If we are using pgrps, get a pgrp number and make it negative. */
5710 if (NILP (current_group))
5711 /* Send the signal to the shell's process group. */
5712 gid = p->pid;
5713 else
5715 #ifdef SIGNALS_VIA_CHARACTERS
5716 /* If possible, send signals to the entire pgrp
5717 by sending an input character to it. */
5719 struct termios t;
5720 cc_t *sig_char = NULL;
5722 tcgetattr (p->infd, &t);
5724 switch (signo)
5726 case SIGINT:
5727 sig_char = &t.c_cc[VINTR];
5728 break;
5730 case SIGQUIT:
5731 sig_char = &t.c_cc[VQUIT];
5732 break;
5734 case SIGTSTP:
5735 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5736 sig_char = &t.c_cc[VSWTCH];
5737 #else
5738 sig_char = &t.c_cc[VSUSP];
5739 #endif
5740 break;
5743 if (sig_char && *sig_char != CDISABLE)
5745 send_process (proc, (char *) sig_char, 1, Qnil);
5746 return;
5748 /* If we can't send the signal with a character,
5749 fall through and send it another way. */
5751 /* The code above may fall through if it can't
5752 handle the signal. */
5753 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5755 #ifdef TIOCGPGRP
5756 /* Get the current pgrp using the tty itself, if we have that.
5757 Otherwise, use the pty to get the pgrp.
5758 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5759 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5760 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5761 His patch indicates that if TIOCGPGRP returns an error, then
5762 we should just assume that p->pid is also the process group id. */
5764 gid = emacs_get_tty_pgrp (p);
5766 if (gid == -1)
5767 /* If we can't get the information, assume
5768 the shell owns the tty. */
5769 gid = p->pid;
5771 /* It is not clear whether anything really can set GID to -1.
5772 Perhaps on some system one of those ioctls can or could do so.
5773 Or perhaps this is vestigial. */
5774 if (gid == -1)
5775 no_pgrp = 1;
5776 #else /* ! defined (TIOCGPGRP ) */
5777 /* Can't select pgrps on this system, so we know that
5778 the child itself heads the pgrp. */
5779 gid = p->pid;
5780 #endif /* ! defined (TIOCGPGRP ) */
5782 /* If current_group is lambda, and the shell owns the terminal,
5783 don't send any signal. */
5784 if (EQ (current_group, Qlambda) && gid == p->pid)
5785 return;
5788 switch (signo)
5790 #ifdef SIGCONT
5791 case SIGCONT:
5792 p->raw_status_new = 0;
5793 pset_status (p, Qrun);
5794 p->tick = ++process_tick;
5795 if (!nomsg)
5797 status_notify (NULL);
5798 redisplay_preserve_echo_area (13);
5800 break;
5801 #endif /* ! defined (SIGCONT) */
5802 case SIGINT:
5803 case SIGQUIT:
5804 case SIGKILL:
5805 flush_pending_output (p->infd);
5806 break;
5809 /* If we don't have process groups, send the signal to the immediate
5810 subprocess. That isn't really right, but it's better than any
5811 obvious alternative. */
5812 if (no_pgrp)
5814 kill (p->pid, signo);
5815 return;
5818 /* gid may be a pid, or minus a pgrp's number */
5819 #ifdef TIOCSIGSEND
5820 if (!NILP (current_group))
5822 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5823 kill (-gid, signo);
5825 else
5827 gid = - p->pid;
5828 kill (gid, signo);
5830 #else /* ! defined (TIOCSIGSEND) */
5831 kill (-gid, signo);
5832 #endif /* ! defined (TIOCSIGSEND) */
5835 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5836 doc: /* Interrupt process PROCESS.
5837 PROCESS may be a process, a buffer, or the name of a process or buffer.
5838 No arg or nil means current buffer's process.
5839 Second arg CURRENT-GROUP non-nil means send signal to
5840 the current process-group of the process's controlling terminal
5841 rather than to the process's own process group.
5842 If the process is a shell, this means interrupt current subjob
5843 rather than the shell.
5845 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5846 don't send the signal. */)
5847 (Lisp_Object process, Lisp_Object current_group)
5849 process_send_signal (process, SIGINT, current_group, 0);
5850 return process;
5853 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5854 doc: /* Kill process PROCESS. May be process or name of one.
5855 See function `interrupt-process' for more details on usage. */)
5856 (Lisp_Object process, Lisp_Object current_group)
5858 process_send_signal (process, SIGKILL, current_group, 0);
5859 return process;
5862 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5863 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5864 See function `interrupt-process' for more details on usage. */)
5865 (Lisp_Object process, Lisp_Object current_group)
5867 process_send_signal (process, SIGQUIT, current_group, 0);
5868 return process;
5871 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5872 doc: /* Stop process PROCESS. May be process or name of one.
5873 See function `interrupt-process' for more details on usage.
5874 If PROCESS is a network or serial process, inhibit handling of incoming
5875 traffic. */)
5876 (Lisp_Object process, Lisp_Object current_group)
5878 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5880 struct Lisp_Process *p;
5882 p = XPROCESS (process);
5883 if (NILP (p->command)
5884 && p->infd >= 0)
5886 FD_CLR (p->infd, &input_wait_mask);
5887 FD_CLR (p->infd, &non_keyboard_wait_mask);
5889 pset_command (p, Qt);
5890 return process;
5892 #ifndef SIGTSTP
5893 error ("No SIGTSTP support");
5894 #else
5895 process_send_signal (process, SIGTSTP, current_group, 0);
5896 #endif
5897 return process;
5900 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5901 doc: /* Continue process PROCESS. May be process or name of one.
5902 See function `interrupt-process' for more details on usage.
5903 If PROCESS is a network or serial process, resume handling of incoming
5904 traffic. */)
5905 (Lisp_Object process, Lisp_Object current_group)
5907 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5909 struct Lisp_Process *p;
5911 p = XPROCESS (process);
5912 if (EQ (p->command, Qt)
5913 && p->infd >= 0
5914 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5916 FD_SET (p->infd, &input_wait_mask);
5917 FD_SET (p->infd, &non_keyboard_wait_mask);
5918 #ifdef WINDOWSNT
5919 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5920 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5921 #else /* not WINDOWSNT */
5922 tcflush (p->infd, TCIFLUSH);
5923 #endif /* not WINDOWSNT */
5925 pset_command (p, Qnil);
5926 return process;
5928 #ifdef SIGCONT
5929 process_send_signal (process, SIGCONT, current_group, 0);
5930 #else
5931 error ("No SIGCONT support");
5932 #endif
5933 return process;
5936 /* Return the integer value of the signal whose abbreviation is ABBR,
5937 or a negative number if there is no such signal. */
5938 static int
5939 abbr_to_signal (char const *name)
5941 int i, signo;
5942 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5944 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5945 name += 3;
5947 for (i = 0; i < sizeof sigbuf; i++)
5949 sigbuf[i] = c_toupper (name[i]);
5950 if (! sigbuf[i])
5951 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5954 return -1;
5957 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5958 2, 2, "sProcess (name or number): \nnSignal code: ",
5959 doc: /* Send PROCESS the signal with code SIGCODE.
5960 PROCESS may also be a number specifying the process id of the
5961 process to signal; in this case, the process need not be a child of
5962 this Emacs.
5963 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5964 (Lisp_Object process, Lisp_Object sigcode)
5966 pid_t pid;
5967 int signo;
5969 if (STRINGP (process))
5971 Lisp_Object tem = Fget_process (process);
5972 if (NILP (tem))
5974 Lisp_Object process_number =
5975 string_to_number (SSDATA (process), 10, 1);
5976 if (INTEGERP (process_number) || FLOATP (process_number))
5977 tem = process_number;
5979 process = tem;
5981 else if (!NUMBERP (process))
5982 process = get_process (process);
5984 if (NILP (process))
5985 return process;
5987 if (NUMBERP (process))
5988 CONS_TO_INTEGER (process, pid_t, pid);
5989 else
5991 CHECK_PROCESS (process);
5992 pid = XPROCESS (process)->pid;
5993 if (pid <= 0)
5994 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5997 if (INTEGERP (sigcode))
5999 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6000 signo = XINT (sigcode);
6002 else
6004 char *name;
6006 CHECK_SYMBOL (sigcode);
6007 name = SSDATA (SYMBOL_NAME (sigcode));
6009 signo = abbr_to_signal (name);
6010 if (signo < 0)
6011 error ("Undefined signal name %s", name);
6014 return make_number (kill (pid, signo));
6017 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6018 doc: /* Make PROCESS see end-of-file in its input.
6019 EOF comes after any text already sent to it.
6020 PROCESS may be a process, a buffer, the name of a process or buffer, or
6021 nil, indicating the current buffer's process.
6022 If PROCESS is a network connection, or is a process communicating
6023 through a pipe (as opposed to a pty), then you cannot send any more
6024 text to PROCESS after you call this function.
6025 If PROCESS is a serial process, wait until all output written to the
6026 process has been transmitted to the serial port. */)
6027 (Lisp_Object process)
6029 Lisp_Object proc;
6030 struct coding_system *coding;
6032 if (DATAGRAM_CONN_P (process))
6033 return process;
6035 proc = get_process (process);
6036 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6038 /* Make sure the process is really alive. */
6039 if (XPROCESS (proc)->raw_status_new)
6040 update_status (XPROCESS (proc));
6041 if (! EQ (XPROCESS (proc)->status, Qrun))
6042 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6044 if (CODING_REQUIRE_FLUSHING (coding))
6046 coding->mode |= CODING_MODE_LAST_BLOCK;
6047 send_process (proc, "", 0, Qnil);
6050 if (XPROCESS (proc)->pty_flag)
6051 send_process (proc, "\004", 1, Qnil);
6052 else if (EQ (XPROCESS (proc)->type, Qserial))
6054 #ifndef WINDOWSNT
6055 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6056 report_file_error ("Failed tcdrain", Qnil);
6057 #endif /* not WINDOWSNT */
6058 /* Do nothing on Windows because writes are blocking. */
6060 else
6062 int old_outfd = XPROCESS (proc)->outfd;
6063 int new_outfd;
6065 #ifdef HAVE_SHUTDOWN
6066 /* If this is a network connection, or socketpair is used
6067 for communication with the subprocess, call shutdown to cause EOF.
6068 (In some old system, shutdown to socketpair doesn't work.
6069 Then we just can't win.) */
6070 if (EQ (XPROCESS (proc)->type, Qnetwork)
6071 || XPROCESS (proc)->infd == old_outfd)
6072 shutdown (old_outfd, 1);
6073 #endif
6074 close_process_fd (&XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS]);
6075 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6076 if (new_outfd < 0)
6077 report_file_error ("Opening null device", Qnil);
6078 XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6079 XPROCESS (proc)->outfd = new_outfd;
6081 if (!proc_encode_coding_system[new_outfd])
6082 proc_encode_coding_system[new_outfd]
6083 = xmalloc (sizeof (struct coding_system));
6084 *proc_encode_coding_system[new_outfd]
6085 = *proc_encode_coding_system[old_outfd];
6086 memset (proc_encode_coding_system[old_outfd], 0,
6087 sizeof (struct coding_system));
6089 return process;
6092 /* The main Emacs thread records child processes in three places:
6094 - Vprocess_alist, for asynchronous subprocesses, which are child
6095 processes visible to Lisp.
6097 - deleted_pid_list, for child processes invisible to Lisp,
6098 typically because of delete-process. These are recorded so that
6099 the processes can be reaped when they exit, so that the operating
6100 system's process table is not cluttered by zombies.
6102 - the local variable PID in Fcall_process, call_process_cleanup and
6103 call_process_kill, for synchronous subprocesses.
6104 record_unwind_protect is used to make sure this process is not
6105 forgotten: if the user interrupts call-process and the child
6106 process refuses to exit immediately even with two C-g's,
6107 call_process_kill adds PID's contents to deleted_pid_list before
6108 returning.
6110 The main Emacs thread invokes waitpid only on child processes that
6111 it creates and that have not been reaped. This avoid races on
6112 platforms such as GTK, where other threads create their own
6113 subprocesses which the main thread should not reap. For example,
6114 if the main thread attempted to reap an already-reaped child, it
6115 might inadvertently reap a GTK-created process that happened to
6116 have the same process ID. */
6118 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6119 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6120 keep track of its own children. GNUstep is similar. */
6122 static void dummy_handler (int sig) {}
6123 static signal_handler_t volatile lib_child_handler;
6125 /* Handle a SIGCHLD signal by looking for known child processes of
6126 Emacs whose status have changed. For each one found, record its
6127 new status.
6129 All we do is change the status; we do not run sentinels or print
6130 notifications. That is saved for the next time keyboard input is
6131 done, in order to avoid timing errors.
6133 ** WARNING: this can be called during garbage collection.
6134 Therefore, it must not be fooled by the presence of mark bits in
6135 Lisp objects.
6137 ** USG WARNING: Although it is not obvious from the documentation
6138 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6139 signal() before executing at least one wait(), otherwise the
6140 handler will be called again, resulting in an infinite loop. The
6141 relevant portion of the documentation reads "SIGCLD signals will be
6142 queued and the signal-catching function will be continually
6143 reentered until the queue is empty". Invoking signal() causes the
6144 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6145 Inc.
6147 ** Malloc WARNING: This should never call malloc either directly or
6148 indirectly; if it does, that is a bug */
6150 static void
6151 handle_child_signal (int sig)
6153 Lisp_Object tail, proc;
6155 /* Find the process that signaled us, and record its status. */
6157 /* The process can have been deleted by Fdelete_process, or have
6158 been started asynchronously by Fcall_process. */
6159 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6161 bool all_pids_are_fixnums
6162 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6163 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6164 Lisp_Object head = XCAR (tail);
6165 Lisp_Object xpid;
6166 if (! CONSP (head))
6167 continue;
6168 xpid = XCAR (head);
6169 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6171 pid_t deleted_pid;
6172 if (INTEGERP (xpid))
6173 deleted_pid = XINT (xpid);
6174 else
6175 deleted_pid = XFLOAT_DATA (xpid);
6176 if (child_status_changed (deleted_pid, 0, 0))
6178 if (STRINGP (XCDR (head)))
6179 unlink (SSDATA (XCDR (head)));
6180 XSETCAR (tail, Qnil);
6185 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6186 FOR_EACH_PROCESS (tail, proc)
6188 struct Lisp_Process *p = XPROCESS (proc);
6189 int status;
6191 if (p->alive
6192 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6194 /* Change the status of the process that was found. */
6195 p->tick = ++process_tick;
6196 p->raw_status = status;
6197 p->raw_status_new = 1;
6199 /* If process has terminated, stop waiting for its output. */
6200 if (WIFSIGNALED (status) || WIFEXITED (status))
6202 bool clear_desc_flag = 0;
6203 p->alive = 0;
6204 if (p->infd >= 0)
6205 clear_desc_flag = 1;
6207 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6208 if (clear_desc_flag)
6210 FD_CLR (p->infd, &input_wait_mask);
6211 FD_CLR (p->infd, &non_keyboard_wait_mask);
6217 lib_child_handler (sig);
6218 #ifdef NS_IMPL_GNUSTEP
6219 /* NSTask in GNUStep sets its child handler each time it is called.
6220 So we must re-set ours. */
6221 catch_child_signal();
6222 #endif
6225 static void
6226 deliver_child_signal (int sig)
6228 deliver_process_signal (sig, handle_child_signal);
6232 static Lisp_Object
6233 exec_sentinel_error_handler (Lisp_Object error_val)
6235 cmd_error_internal (error_val, "error in process sentinel: ");
6236 Vinhibit_quit = Qt;
6237 update_echo_area ();
6238 Fsleep_for (make_number (2), Qnil);
6239 return Qt;
6242 static void
6243 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6245 Lisp_Object sentinel, odeactivate;
6246 struct Lisp_Process *p = XPROCESS (proc);
6247 ptrdiff_t count = SPECPDL_INDEX ();
6248 bool outer_running_asynch_code = running_asynch_code;
6249 int waiting = waiting_for_user_input_p;
6251 if (inhibit_sentinels)
6252 return;
6254 /* No need to gcpro these, because all we do with them later
6255 is test them for EQness, and none of them should be a string. */
6256 odeactivate = Vdeactivate_mark;
6257 #if 0
6258 Lisp_Object obuffer, okeymap;
6259 XSETBUFFER (obuffer, current_buffer);
6260 okeymap = BVAR (current_buffer, keymap);
6261 #endif
6263 /* There's no good reason to let sentinels change the current
6264 buffer, and many callers of accept-process-output, sit-for, and
6265 friends don't expect current-buffer to be changed from under them. */
6266 record_unwind_current_buffer ();
6268 sentinel = p->sentinel;
6270 /* Inhibit quit so that random quits don't screw up a running filter. */
6271 specbind (Qinhibit_quit, Qt);
6272 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6274 /* In case we get recursively called,
6275 and we already saved the match data nonrecursively,
6276 save the same match data in safely recursive fashion. */
6277 if (outer_running_asynch_code)
6279 Lisp_Object tem;
6280 tem = Fmatch_data (Qnil, Qnil, Qnil);
6281 restore_search_regs ();
6282 record_unwind_save_match_data ();
6283 Fset_match_data (tem, Qt);
6286 /* For speed, if a search happens within this code,
6287 save the match data in a special nonrecursive fashion. */
6288 running_asynch_code = 1;
6290 internal_condition_case_1 (read_process_output_call,
6291 list3 (sentinel, proc, reason),
6292 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6293 exec_sentinel_error_handler);
6295 /* If we saved the match data nonrecursively, restore it now. */
6296 restore_search_regs ();
6297 running_asynch_code = outer_running_asynch_code;
6299 Vdeactivate_mark = odeactivate;
6301 /* Restore waiting_for_user_input_p as it was
6302 when we were called, in case the filter clobbered it. */
6303 waiting_for_user_input_p = waiting;
6305 #if 0
6306 if (! EQ (Fcurrent_buffer (), obuffer)
6307 || ! EQ (current_buffer->keymap, okeymap))
6308 #endif
6309 /* But do it only if the caller is actually going to read events.
6310 Otherwise there's no need to make him wake up, and it could
6311 cause trouble (for example it would make sit_for return). */
6312 if (waiting_for_user_input_p == -1)
6313 record_asynch_buffer_change ();
6315 unbind_to (count, Qnil);
6318 /* Report all recent events of a change in process status
6319 (either run the sentinel or output a message).
6320 This is usually done while Emacs is waiting for keyboard input
6321 but can be done at other times. */
6323 static void
6324 status_notify (struct Lisp_Process *deleting_process)
6326 register Lisp_Object proc;
6327 Lisp_Object tail, msg;
6328 struct gcpro gcpro1, gcpro2;
6330 tail = Qnil;
6331 msg = Qnil;
6332 /* We need to gcpro tail; if read_process_output calls a filter
6333 which deletes a process and removes the cons to which tail points
6334 from Vprocess_alist, and then causes a GC, tail is an unprotected
6335 reference. */
6336 GCPRO2 (tail, msg);
6338 /* Set this now, so that if new processes are created by sentinels
6339 that we run, we get called again to handle their status changes. */
6340 update_tick = process_tick;
6342 FOR_EACH_PROCESS (tail, proc)
6344 Lisp_Object symbol;
6345 register struct Lisp_Process *p = XPROCESS (proc);
6347 if (p->tick != p->update_tick)
6349 p->update_tick = p->tick;
6351 /* If process is still active, read any output that remains. */
6352 while (! EQ (p->filter, Qt)
6353 && ! EQ (p->status, Qconnect)
6354 && ! EQ (p->status, Qlisten)
6355 /* Network or serial process not stopped: */
6356 && ! EQ (p->command, Qt)
6357 && p->infd >= 0
6358 && p != deleting_process
6359 && read_process_output (proc, p->infd) > 0);
6361 /* Get the text to use for the message. */
6362 if (p->raw_status_new)
6363 update_status (p);
6364 msg = status_message (p);
6366 /* If process is terminated, deactivate it or delete it. */
6367 symbol = p->status;
6368 if (CONSP (p->status))
6369 symbol = XCAR (p->status);
6371 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6372 || EQ (symbol, Qclosed))
6374 if (delete_exited_processes)
6375 remove_process (proc);
6376 else
6377 deactivate_process (proc);
6380 /* The actions above may have further incremented p->tick.
6381 So set p->update_tick again so that an error in the sentinel will
6382 not cause this code to be run again. */
6383 p->update_tick = p->tick;
6384 /* Now output the message suitably. */
6385 exec_sentinel (proc, msg);
6387 } /* end for */
6389 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6390 UNGCPRO;
6393 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6394 Sinternal_default_process_sentinel, 2, 2, 0,
6395 doc: /* Function used as default sentinel for processes. */)
6396 (Lisp_Object proc, Lisp_Object msg)
6398 Lisp_Object buffer, symbol;
6399 struct Lisp_Process *p;
6400 CHECK_PROCESS (proc);
6401 p = XPROCESS (proc);
6402 buffer = p->buffer;
6403 symbol = p->status;
6404 if (CONSP (symbol))
6405 symbol = XCAR (symbol);
6407 if (!EQ (symbol, Qrun) && !NILP (buffer))
6409 Lisp_Object tem;
6410 struct buffer *old = current_buffer;
6411 ptrdiff_t opoint, opoint_byte;
6412 ptrdiff_t before, before_byte;
6414 /* Avoid error if buffer is deleted
6415 (probably that's why the process is dead, too). */
6416 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6417 return Qnil;
6418 Fset_buffer (buffer);
6420 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6421 msg = (code_convert_string_norecord
6422 (msg, Vlocale_coding_system, 1));
6424 opoint = PT;
6425 opoint_byte = PT_BYTE;
6426 /* Insert new output into buffer
6427 at the current end-of-output marker,
6428 thus preserving logical ordering of input and output. */
6429 if (XMARKER (p->mark)->buffer)
6430 Fgoto_char (p->mark);
6431 else
6432 SET_PT_BOTH (ZV, ZV_BYTE);
6434 before = PT;
6435 before_byte = PT_BYTE;
6437 tem = BVAR (current_buffer, read_only);
6438 bset_read_only (current_buffer, Qnil);
6439 insert_string ("\nProcess ");
6440 { /* FIXME: temporary kludge. */
6441 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6442 insert_string (" ");
6443 Finsert (1, &msg);
6444 bset_read_only (current_buffer, tem);
6445 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6447 if (opoint >= before)
6448 SET_PT_BOTH (opoint + (PT - before),
6449 opoint_byte + (PT_BYTE - before_byte));
6450 else
6451 SET_PT_BOTH (opoint, opoint_byte);
6453 set_buffer_internal (old);
6455 return Qnil;
6459 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6460 Sset_process_coding_system, 1, 3, 0,
6461 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6462 DECODING will be used to decode subprocess output and ENCODING to
6463 encode subprocess input. */)
6464 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6466 register struct Lisp_Process *p;
6468 CHECK_PROCESS (process);
6469 p = XPROCESS (process);
6470 if (p->infd < 0)
6471 error ("Input file descriptor of %s closed", SDATA (p->name));
6472 if (p->outfd < 0)
6473 error ("Output file descriptor of %s closed", SDATA (p->name));
6474 Fcheck_coding_system (decoding);
6475 Fcheck_coding_system (encoding);
6476 encoding = coding_inherit_eol_type (encoding, Qnil);
6477 pset_decode_coding_system (p, decoding);
6478 pset_encode_coding_system (p, encoding);
6479 setup_process_coding_systems (process);
6481 return Qnil;
6484 DEFUN ("process-coding-system",
6485 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6486 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6487 (register Lisp_Object process)
6489 CHECK_PROCESS (process);
6490 return Fcons (XPROCESS (process)->decode_coding_system,
6491 XPROCESS (process)->encode_coding_system);
6494 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6495 Sset_process_filter_multibyte, 2, 2, 0,
6496 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6497 If FLAG is non-nil, the filter is given multibyte strings.
6498 If FLAG is nil, the filter is given unibyte strings. In this case,
6499 all character code conversion except for end-of-line conversion is
6500 suppressed. */)
6501 (Lisp_Object process, Lisp_Object flag)
6503 register struct Lisp_Process *p;
6505 CHECK_PROCESS (process);
6506 p = XPROCESS (process);
6507 if (NILP (flag))
6508 pset_decode_coding_system
6509 (p, raw_text_coding_system (p->decode_coding_system));
6510 setup_process_coding_systems (process);
6512 return Qnil;
6515 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6516 Sprocess_filter_multibyte_p, 1, 1, 0,
6517 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6518 (Lisp_Object process)
6520 register struct Lisp_Process *p;
6521 struct coding_system *coding;
6523 CHECK_PROCESS (process);
6524 p = XPROCESS (process);
6525 coding = proc_decode_coding_system[p->infd];
6526 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6532 # ifdef HAVE_GPM
6534 void
6535 add_gpm_wait_descriptor (int desc)
6537 add_keyboard_wait_descriptor (desc);
6540 void
6541 delete_gpm_wait_descriptor (int desc)
6543 delete_keyboard_wait_descriptor (desc);
6546 # endif
6548 # ifdef USABLE_SIGIO
6550 /* Return true if *MASK has a bit set
6551 that corresponds to one of the keyboard input descriptors. */
6553 static bool
6554 keyboard_bit_set (fd_set *mask)
6556 int fd;
6558 for (fd = 0; fd <= max_input_desc; fd++)
6559 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6560 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6561 return 1;
6563 return 0;
6565 # endif
6567 #else /* not subprocesses */
6569 /* Defined on msdos.c. */
6570 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6571 EMACS_TIME *, void *);
6573 /* Implementation of wait_reading_process_output, assuming that there
6574 are no subprocesses. Used only by the MS-DOS build.
6576 Wait for timeout to elapse and/or keyboard input to be available.
6578 TIME_LIMIT is:
6579 timeout in seconds
6580 If negative, gobble data immediately available but don't wait for any.
6582 NSECS is:
6583 an additional duration to wait, measured in nanoseconds
6584 If TIME_LIMIT is zero, then:
6585 If NSECS == 0, there is no limit.
6586 If NSECS > 0, the timeout consists of NSECS only.
6587 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6589 READ_KBD is:
6590 0 to ignore keyboard input, or
6591 1 to return when input is available, or
6592 -1 means caller will actually read the input, so don't throw to
6593 the quit handler.
6595 see full version for other parameters. We know that wait_proc will
6596 always be NULL, since `subprocesses' isn't defined.
6598 DO_DISPLAY means redisplay should be done to show subprocess
6599 output that arrives.
6601 Return true if we received input from any process. */
6603 bool
6604 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6605 bool do_display,
6606 Lisp_Object wait_for_cell,
6607 struct Lisp_Process *wait_proc, int just_wait_proc)
6609 register int nfds;
6610 EMACS_TIME end_time, timeout;
6612 if (time_limit < 0)
6614 time_limit = 0;
6615 nsecs = -1;
6617 else if (TYPE_MAXIMUM (time_t) < time_limit)
6618 time_limit = TYPE_MAXIMUM (time_t);
6620 /* What does time_limit really mean? */
6621 if (time_limit || nsecs > 0)
6623 timeout = make_emacs_time (time_limit, nsecs);
6624 end_time = add_emacs_time (current_emacs_time (), timeout);
6627 /* Turn off periodic alarms (in case they are in use)
6628 and then turn off any other atimers,
6629 because the select emulator uses alarms. */
6630 stop_polling ();
6631 turn_on_atimers (0);
6633 while (1)
6635 bool timeout_reduced_for_timers = 0;
6636 SELECT_TYPE waitchannels;
6637 int xerrno;
6639 /* If calling from keyboard input, do not quit
6640 since we want to return C-g as an input character.
6641 Otherwise, do pending quit if requested. */
6642 if (read_kbd >= 0)
6643 QUIT;
6645 /* Exit now if the cell we're waiting for became non-nil. */
6646 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6647 break;
6649 /* Compute time from now till when time limit is up. */
6650 /* Exit if already run out. */
6651 if (nsecs < 0)
6653 /* A negative timeout means
6654 gobble output available now
6655 but don't wait at all. */
6657 timeout = make_emacs_time (0, 0);
6659 else if (time_limit || nsecs > 0)
6661 EMACS_TIME now = current_emacs_time ();
6662 if (EMACS_TIME_LE (end_time, now))
6663 break;
6664 timeout = sub_emacs_time (end_time, now);
6666 else
6668 timeout = make_emacs_time (100000, 0);
6671 /* If our caller will not immediately handle keyboard events,
6672 run timer events directly.
6673 (Callers that will immediately read keyboard events
6674 call timer_delay on their own.) */
6675 if (NILP (wait_for_cell))
6677 EMACS_TIME timer_delay;
6681 unsigned old_timers_run = timers_run;
6682 timer_delay = timer_check ();
6683 if (timers_run != old_timers_run && do_display)
6684 /* We must retry, since a timer may have requeued itself
6685 and that could alter the time delay. */
6686 redisplay_preserve_echo_area (14);
6687 else
6688 break;
6690 while (!detect_input_pending ());
6692 /* If there is unread keyboard input, also return. */
6693 if (read_kbd != 0
6694 && requeued_events_pending_p ())
6695 break;
6697 if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
6699 if (EMACS_TIME_LT (timer_delay, timeout))
6701 timeout = timer_delay;
6702 timeout_reduced_for_timers = 1;
6707 /* Cause C-g and alarm signals to take immediate action,
6708 and cause input available signals to zero out timeout. */
6709 if (read_kbd < 0)
6710 set_waiting_for_input (&timeout);
6712 /* If a frame has been newly mapped and needs updating,
6713 reprocess its display stuff. */
6714 if (frame_garbaged && do_display)
6716 clear_waiting_for_input ();
6717 redisplay_preserve_echo_area (15);
6718 if (read_kbd < 0)
6719 set_waiting_for_input (&timeout);
6722 /* Wait till there is something to do. */
6723 FD_ZERO (&waitchannels);
6724 if (read_kbd && detect_input_pending ())
6725 nfds = 0;
6726 else
6728 if (read_kbd || !NILP (wait_for_cell))
6729 FD_SET (0, &waitchannels);
6730 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6733 xerrno = errno;
6735 /* Make C-g and alarm signals set flags again */
6736 clear_waiting_for_input ();
6738 /* If we woke up due to SIGWINCH, actually change size now. */
6739 do_pending_window_change (0);
6741 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6742 /* We waited the full specified time, so return now. */
6743 break;
6745 if (nfds == -1)
6747 /* If the system call was interrupted, then go around the
6748 loop again. */
6749 if (xerrno == EINTR)
6750 FD_ZERO (&waitchannels);
6751 else
6752 report_file_errno ("Failed select", Qnil, xerrno);
6755 /* Check for keyboard input */
6757 if (read_kbd
6758 && detect_input_pending_run_timers (do_display))
6760 swallow_events (do_display);
6761 if (detect_input_pending_run_timers (do_display))
6762 break;
6765 /* If there is unread keyboard input, also return. */
6766 if (read_kbd
6767 && requeued_events_pending_p ())
6768 break;
6770 /* If wait_for_cell. check for keyboard input
6771 but don't run any timers.
6772 ??? (It seems wrong to me to check for keyboard
6773 input at all when wait_for_cell, but the code
6774 has been this way since July 1994.
6775 Try changing this after version 19.31.) */
6776 if (! NILP (wait_for_cell)
6777 && detect_input_pending ())
6779 swallow_events (do_display);
6780 if (detect_input_pending ())
6781 break;
6784 /* Exit now if the cell we're waiting for became non-nil. */
6785 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6786 break;
6789 start_polling ();
6791 return 0;
6794 #endif /* not subprocesses */
6796 /* The following functions are needed even if async subprocesses are
6797 not supported. Some of them are no-op stubs in that case. */
6799 /* Add DESC to the set of keyboard input descriptors. */
6801 void
6802 add_keyboard_wait_descriptor (int desc)
6804 #ifdef subprocesses /* actually means "not MSDOS" */
6805 FD_SET (desc, &input_wait_mask);
6806 FD_SET (desc, &non_process_wait_mask);
6807 if (desc > max_input_desc)
6808 max_input_desc = desc;
6809 #endif
6812 /* From now on, do not expect DESC to give keyboard input. */
6814 void
6815 delete_keyboard_wait_descriptor (int desc)
6817 #ifdef subprocesses
6818 FD_CLR (desc, &input_wait_mask);
6819 FD_CLR (desc, &non_process_wait_mask);
6820 delete_input_desc (desc);
6821 #endif
6824 /* Setup coding systems of PROCESS. */
6826 void
6827 setup_process_coding_systems (Lisp_Object process)
6829 #ifdef subprocesses
6830 struct Lisp_Process *p = XPROCESS (process);
6831 int inch = p->infd;
6832 int outch = p->outfd;
6833 Lisp_Object coding_system;
6835 if (inch < 0 || outch < 0)
6836 return;
6838 if (!proc_decode_coding_system[inch])
6839 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6840 coding_system = p->decode_coding_system;
6841 if (EQ (p->filter, Qinternal_default_process_filter)
6842 && BUFFERP (p->buffer))
6844 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6845 coding_system = raw_text_coding_system (coding_system);
6847 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6849 if (!proc_encode_coding_system[outch])
6850 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6851 setup_coding_system (p->encode_coding_system,
6852 proc_encode_coding_system[outch]);
6853 #endif
6856 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6857 doc: /* Return the (or a) process associated with BUFFER.
6858 BUFFER may be a buffer or the name of one. */)
6859 (register Lisp_Object buffer)
6861 #ifdef subprocesses
6862 register Lisp_Object buf, tail, proc;
6864 if (NILP (buffer)) return Qnil;
6865 buf = Fget_buffer (buffer);
6866 if (NILP (buf)) return Qnil;
6868 FOR_EACH_PROCESS (tail, proc)
6869 if (EQ (XPROCESS (proc)->buffer, buf))
6870 return proc;
6871 #endif /* subprocesses */
6872 return Qnil;
6875 DEFUN ("process-inherit-coding-system-flag",
6876 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6877 1, 1, 0,
6878 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6879 If this flag is t, `buffer-file-coding-system' of the buffer
6880 associated with PROCESS will inherit the coding system used to decode
6881 the process output. */)
6882 (register Lisp_Object process)
6884 #ifdef subprocesses
6885 CHECK_PROCESS (process);
6886 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6887 #else
6888 /* Ignore the argument and return the value of
6889 inherit-process-coding-system. */
6890 return inherit_process_coding_system ? Qt : Qnil;
6891 #endif
6894 /* Kill all processes associated with `buffer'.
6895 If `buffer' is nil, kill all processes */
6897 void
6898 kill_buffer_processes (Lisp_Object buffer)
6900 #ifdef subprocesses
6901 Lisp_Object tail, proc;
6903 FOR_EACH_PROCESS (tail, proc)
6904 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6906 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6907 Fdelete_process (proc);
6908 else if (XPROCESS (proc)->infd >= 0)
6909 process_send_signal (proc, SIGHUP, Qnil, 1);
6911 #else /* subprocesses */
6912 /* Since we have no subprocesses, this does nothing. */
6913 #endif /* subprocesses */
6916 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6917 Swaiting_for_user_input_p, 0, 0, 0,
6918 doc: /* Return non-nil if Emacs is waiting for input from the user.
6919 This is intended for use by asynchronous process output filters and sentinels. */)
6920 (void)
6922 #ifdef subprocesses
6923 return (waiting_for_user_input_p ? Qt : Qnil);
6924 #else
6925 return Qnil;
6926 #endif
6929 /* Stop reading input from keyboard sources. */
6931 void
6932 hold_keyboard_input (void)
6934 kbd_is_on_hold = 1;
6937 /* Resume reading input from keyboard sources. */
6939 void
6940 unhold_keyboard_input (void)
6942 kbd_is_on_hold = 0;
6945 /* Return true if keyboard input is on hold, zero otherwise. */
6947 bool
6948 kbd_on_hold_p (void)
6950 return kbd_is_on_hold;
6954 /* Enumeration of and access to system processes a-la ps(1). */
6956 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6957 0, 0, 0,
6958 doc: /* Return a list of numerical process IDs of all running processes.
6959 If this functionality is unsupported, return nil.
6961 See `process-attributes' for getting attributes of a process given its ID. */)
6962 (void)
6964 return list_system_processes ();
6967 DEFUN ("process-attributes", Fprocess_attributes,
6968 Sprocess_attributes, 1, 1, 0,
6969 doc: /* Return attributes of the process given by its PID, a number.
6971 Value is an alist where each element is a cons cell of the form
6973 \(KEY . VALUE)
6975 If this functionality is unsupported, the value is nil.
6977 See `list-system-processes' for getting a list of all process IDs.
6979 The KEYs of the attributes that this function may return are listed
6980 below, together with the type of the associated VALUE (in parentheses).
6981 Not all platforms support all of these attributes; unsupported
6982 attributes will not appear in the returned alist.
6983 Unless explicitly indicated otherwise, numbers can have either
6984 integer or floating point values.
6986 euid -- Effective user User ID of the process (number)
6987 user -- User name corresponding to euid (string)
6988 egid -- Effective user Group ID of the process (number)
6989 group -- Group name corresponding to egid (string)
6990 comm -- Command name (executable name only) (string)
6991 state -- Process state code, such as "S", "R", or "T" (string)
6992 ppid -- Parent process ID (number)
6993 pgrp -- Process group ID (number)
6994 sess -- Session ID, i.e. process ID of session leader (number)
6995 ttname -- Controlling tty name (string)
6996 tpgid -- ID of foreground process group on the process's tty (number)
6997 minflt -- number of minor page faults (number)
6998 majflt -- number of major page faults (number)
6999 cminflt -- cumulative number of minor page faults (number)
7000 cmajflt -- cumulative number of major page faults (number)
7001 utime -- user time used by the process, in (current-time) format,
7002 which is a list of integers (HIGH LOW USEC PSEC)
7003 stime -- system time used by the process (current-time)
7004 time -- sum of utime and stime (current-time)
7005 cutime -- user time used by the process and its children (current-time)
7006 cstime -- system time used by the process and its children (current-time)
7007 ctime -- sum of cutime and cstime (current-time)
7008 pri -- priority of the process (number)
7009 nice -- nice value of the process (number)
7010 thcount -- process thread count (number)
7011 start -- time the process started (current-time)
7012 vsize -- virtual memory size of the process in KB's (number)
7013 rss -- resident set size of the process in KB's (number)
7014 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7015 pcpu -- percents of CPU time used by the process (floating-point number)
7016 pmem -- percents of total physical memory used by process's resident set
7017 (floating-point number)
7018 args -- command line which invoked the process (string). */)
7019 ( Lisp_Object pid)
7021 return system_process_attributes (pid);
7024 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7025 Invoke this after init_process_emacs, and after glib and/or GNUstep
7026 futz with the SIGCHLD handler, but before Emacs forks any children.
7027 This function's caller should block SIGCHLD. */
7029 #ifndef NS_IMPL_GNUSTEP
7030 static
7031 #endif
7032 void
7033 catch_child_signal (void)
7035 struct sigaction action, old_action;
7036 emacs_sigaction_init (&action, deliver_child_signal);
7037 block_child_signal ();
7038 sigaction (SIGCHLD, &action, &old_action);
7039 eassert (! (old_action.sa_flags & SA_SIGINFO));
7041 if (old_action.sa_handler != deliver_child_signal)
7042 lib_child_handler
7043 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7044 ? dummy_handler
7045 : old_action.sa_handler);
7046 unblock_child_signal ();
7050 /* This is not called "init_process" because that is the name of a
7051 Mach system call, so it would cause problems on Darwin systems. */
7052 void
7053 init_process_emacs (void)
7055 #ifdef subprocesses
7056 register int i;
7058 inhibit_sentinels = 0;
7060 #ifndef CANNOT_DUMP
7061 if (! noninteractive || initialized)
7062 #endif
7064 #if defined HAVE_GLIB && !defined WINDOWSNT
7065 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7066 this should always fail, but is enough to initialize glib's
7067 private SIGCHLD handler, allowing catch_child_signal to copy
7068 it into lib_child_handler. */
7069 g_source_unref (g_child_watch_source_new (getpid ()));
7070 #endif
7071 catch_child_signal ();
7074 FD_ZERO (&input_wait_mask);
7075 FD_ZERO (&non_keyboard_wait_mask);
7076 FD_ZERO (&non_process_wait_mask);
7077 FD_ZERO (&write_mask);
7078 max_process_desc = max_input_desc = -1;
7079 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7081 #ifdef NON_BLOCKING_CONNECT
7082 FD_ZERO (&connect_wait_mask);
7083 num_pending_connects = 0;
7084 #endif
7086 #ifdef ADAPTIVE_READ_BUFFERING
7087 process_output_delay_count = 0;
7088 process_output_skip = 0;
7089 #endif
7091 /* Don't do this, it caused infinite select loops. The display
7092 method should call add_keyboard_wait_descriptor on stdin if it
7093 needs that. */
7094 #if 0
7095 FD_SET (0, &input_wait_mask);
7096 #endif
7098 Vprocess_alist = Qnil;
7099 deleted_pid_list = Qnil;
7100 for (i = 0; i < MAXDESC; i++)
7102 chan_process[i] = Qnil;
7103 proc_buffered_char[i] = -1;
7105 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7106 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7107 #ifdef DATAGRAM_SOCKETS
7108 memset (datagram_address, 0, sizeof datagram_address);
7109 #endif
7112 Lisp_Object subfeatures = Qnil;
7113 const struct socket_options *sopt;
7115 #define ADD_SUBFEATURE(key, val) \
7116 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7118 #ifdef NON_BLOCKING_CONNECT
7119 ADD_SUBFEATURE (QCnowait, Qt);
7120 #endif
7121 #ifdef DATAGRAM_SOCKETS
7122 ADD_SUBFEATURE (QCtype, Qdatagram);
7123 #endif
7124 #ifdef HAVE_SEQPACKET
7125 ADD_SUBFEATURE (QCtype, Qseqpacket);
7126 #endif
7127 #ifdef HAVE_LOCAL_SOCKETS
7128 ADD_SUBFEATURE (QCfamily, Qlocal);
7129 #endif
7130 ADD_SUBFEATURE (QCfamily, Qipv4);
7131 #ifdef AF_INET6
7132 ADD_SUBFEATURE (QCfamily, Qipv6);
7133 #endif
7134 #ifdef HAVE_GETSOCKNAME
7135 ADD_SUBFEATURE (QCservice, Qt);
7136 #endif
7137 ADD_SUBFEATURE (QCserver, Qt);
7139 for (sopt = socket_options; sopt->name; sopt++)
7140 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7142 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7145 #if defined (DARWIN_OS)
7146 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7147 processes. As such, we only change the default value. */
7148 if (initialized)
7150 char const *release = (STRINGP (Voperating_system_release)
7151 ? SSDATA (Voperating_system_release)
7152 : 0);
7153 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7154 Vprocess_connection_type = Qnil;
7157 #endif
7158 #endif /* subprocesses */
7159 kbd_is_on_hold = 0;
7162 void
7163 syms_of_process (void)
7165 #ifdef subprocesses
7167 DEFSYM (Qprocessp, "processp");
7168 DEFSYM (Qrun, "run");
7169 DEFSYM (Qstop, "stop");
7170 DEFSYM (Qsignal, "signal");
7172 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7173 here again.
7175 Qexit = intern_c_string ("exit");
7176 staticpro (&Qexit); */
7178 DEFSYM (Qopen, "open");
7179 DEFSYM (Qclosed, "closed");
7180 DEFSYM (Qconnect, "connect");
7181 DEFSYM (Qfailed, "failed");
7182 DEFSYM (Qlisten, "listen");
7183 DEFSYM (Qlocal, "local");
7184 DEFSYM (Qipv4, "ipv4");
7185 #ifdef AF_INET6
7186 DEFSYM (Qipv6, "ipv6");
7187 #endif
7188 DEFSYM (Qdatagram, "datagram");
7189 DEFSYM (Qseqpacket, "seqpacket");
7191 DEFSYM (QCport, ":port");
7192 DEFSYM (QCspeed, ":speed");
7193 DEFSYM (QCprocess, ":process");
7195 DEFSYM (QCbytesize, ":bytesize");
7196 DEFSYM (QCstopbits, ":stopbits");
7197 DEFSYM (QCparity, ":parity");
7198 DEFSYM (Qodd, "odd");
7199 DEFSYM (Qeven, "even");
7200 DEFSYM (QCflowcontrol, ":flowcontrol");
7201 DEFSYM (Qhw, "hw");
7202 DEFSYM (Qsw, "sw");
7203 DEFSYM (QCsummary, ":summary");
7205 DEFSYM (Qreal, "real");
7206 DEFSYM (Qnetwork, "network");
7207 DEFSYM (Qserial, "serial");
7208 DEFSYM (QCbuffer, ":buffer");
7209 DEFSYM (QChost, ":host");
7210 DEFSYM (QCservice, ":service");
7211 DEFSYM (QClocal, ":local");
7212 DEFSYM (QCremote, ":remote");
7213 DEFSYM (QCcoding, ":coding");
7214 DEFSYM (QCserver, ":server");
7215 DEFSYM (QCnowait, ":nowait");
7216 DEFSYM (QCsentinel, ":sentinel");
7217 DEFSYM (QClog, ":log");
7218 DEFSYM (QCnoquery, ":noquery");
7219 DEFSYM (QCstop, ":stop");
7220 DEFSYM (QCoptions, ":options");
7221 DEFSYM (QCplist, ":plist");
7223 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7225 staticpro (&Vprocess_alist);
7226 staticpro (&deleted_pid_list);
7228 #endif /* subprocesses */
7230 DEFSYM (QCname, ":name");
7231 DEFSYM (QCtype, ":type");
7233 DEFSYM (Qeuid, "euid");
7234 DEFSYM (Qegid, "egid");
7235 DEFSYM (Quser, "user");
7236 DEFSYM (Qgroup, "group");
7237 DEFSYM (Qcomm, "comm");
7238 DEFSYM (Qstate, "state");
7239 DEFSYM (Qppid, "ppid");
7240 DEFSYM (Qpgrp, "pgrp");
7241 DEFSYM (Qsess, "sess");
7242 DEFSYM (Qttname, "ttname");
7243 DEFSYM (Qtpgid, "tpgid");
7244 DEFSYM (Qminflt, "minflt");
7245 DEFSYM (Qmajflt, "majflt");
7246 DEFSYM (Qcminflt, "cminflt");
7247 DEFSYM (Qcmajflt, "cmajflt");
7248 DEFSYM (Qutime, "utime");
7249 DEFSYM (Qstime, "stime");
7250 DEFSYM (Qtime, "time");
7251 DEFSYM (Qcutime, "cutime");
7252 DEFSYM (Qcstime, "cstime");
7253 DEFSYM (Qctime, "ctime");
7254 DEFSYM (Qinternal_default_process_sentinel,
7255 "internal-default-process-sentinel");
7256 DEFSYM (Qinternal_default_process_filter,
7257 "internal-default-process-filter");
7258 DEFSYM (Qpri, "pri");
7259 DEFSYM (Qnice, "nice");
7260 DEFSYM (Qthcount, "thcount");
7261 DEFSYM (Qstart, "start");
7262 DEFSYM (Qvsize, "vsize");
7263 DEFSYM (Qrss, "rss");
7264 DEFSYM (Qetime, "etime");
7265 DEFSYM (Qpcpu, "pcpu");
7266 DEFSYM (Qpmem, "pmem");
7267 DEFSYM (Qargs, "args");
7269 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7270 doc: /* Non-nil means delete processes immediately when they exit.
7271 A value of nil means don't delete them until `list-processes' is run. */);
7273 delete_exited_processes = 1;
7275 #ifdef subprocesses
7276 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7277 doc: /* Control type of device used to communicate with subprocesses.
7278 Values are nil to use a pipe, or t or `pty' to use a pty.
7279 The value has no effect if the system has no ptys or if all ptys are busy:
7280 then a pipe is used in any case.
7281 The value takes effect when `start-process' is called. */);
7282 Vprocess_connection_type = Qt;
7284 #ifdef ADAPTIVE_READ_BUFFERING
7285 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7286 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7287 On some systems, when Emacs reads the output from a subprocess, the output data
7288 is read in very small blocks, potentially resulting in very poor performance.
7289 This behavior can be remedied to some extent by setting this variable to a
7290 non-nil value, as it will automatically delay reading from such processes, to
7291 allow them to produce more output before Emacs tries to read it.
7292 If the value is t, the delay is reset after each write to the process; any other
7293 non-nil value means that the delay is not reset on write.
7294 The variable takes effect when `start-process' is called. */);
7295 Vprocess_adaptive_read_buffering = Qt;
7296 #endif
7298 defsubr (&Sprocessp);
7299 defsubr (&Sget_process);
7300 defsubr (&Sdelete_process);
7301 defsubr (&Sprocess_status);
7302 defsubr (&Sprocess_exit_status);
7303 defsubr (&Sprocess_id);
7304 defsubr (&Sprocess_name);
7305 defsubr (&Sprocess_tty_name);
7306 defsubr (&Sprocess_command);
7307 defsubr (&Sset_process_buffer);
7308 defsubr (&Sprocess_buffer);
7309 defsubr (&Sprocess_mark);
7310 defsubr (&Sset_process_filter);
7311 defsubr (&Sprocess_filter);
7312 defsubr (&Sset_process_sentinel);
7313 defsubr (&Sprocess_sentinel);
7314 defsubr (&Sset_process_window_size);
7315 defsubr (&Sset_process_inherit_coding_system_flag);
7316 defsubr (&Sset_process_query_on_exit_flag);
7317 defsubr (&Sprocess_query_on_exit_flag);
7318 defsubr (&Sprocess_contact);
7319 defsubr (&Sprocess_plist);
7320 defsubr (&Sset_process_plist);
7321 defsubr (&Sprocess_list);
7322 defsubr (&Sstart_process);
7323 defsubr (&Sserial_process_configure);
7324 defsubr (&Smake_serial_process);
7325 defsubr (&Sset_network_process_option);
7326 defsubr (&Smake_network_process);
7327 defsubr (&Sformat_network_address);
7328 #if defined (HAVE_NET_IF_H)
7329 #ifdef SIOCGIFCONF
7330 defsubr (&Snetwork_interface_list);
7331 #endif
7332 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7333 defsubr (&Snetwork_interface_info);
7334 #endif
7335 #endif /* defined (HAVE_NET_IF_H) */
7336 #ifdef DATAGRAM_SOCKETS
7337 defsubr (&Sprocess_datagram_address);
7338 defsubr (&Sset_process_datagram_address);
7339 #endif
7340 defsubr (&Saccept_process_output);
7341 defsubr (&Sprocess_send_region);
7342 defsubr (&Sprocess_send_string);
7343 defsubr (&Sinterrupt_process);
7344 defsubr (&Skill_process);
7345 defsubr (&Squit_process);
7346 defsubr (&Sstop_process);
7347 defsubr (&Scontinue_process);
7348 defsubr (&Sprocess_running_child_p);
7349 defsubr (&Sprocess_send_eof);
7350 defsubr (&Ssignal_process);
7351 defsubr (&Swaiting_for_user_input_p);
7352 defsubr (&Sprocess_type);
7353 defsubr (&Sinternal_default_process_sentinel);
7354 defsubr (&Sinternal_default_process_filter);
7355 defsubr (&Sset_process_coding_system);
7356 defsubr (&Sprocess_coding_system);
7357 defsubr (&Sset_process_filter_multibyte);
7358 defsubr (&Sprocess_filter_multibyte_p);
7360 #endif /* subprocesses */
7362 defsubr (&Sget_buffer_process);
7363 defsubr (&Sprocess_inherit_coding_system_flag);
7364 defsubr (&Slist_system_processes);
7365 defsubr (&Sprocess_attributes);