Use AUTO_CONS instead of SCOPED_CONS, etc.
[emacs.git] / src / process.c
blobf767ae05e9649bb3b0d90ebdebae7418525e2c82
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2014
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
145 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
146 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
147 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
148 Lisp_Object QCname, QCtype;
150 /* True if keyboard input is on hold, zero otherwise. */
152 static bool kbd_is_on_hold;
154 /* Nonzero means don't run process sentinels. This is used
155 when exiting. */
156 bool inhibit_sentinels;
158 #ifdef subprocesses
160 #ifndef SOCK_CLOEXEC
161 # define SOCK_CLOEXEC 0
162 #endif
164 #ifndef HAVE_ACCEPT4
166 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
168 static int
169 close_on_exec (int fd)
171 if (0 <= fd)
172 fcntl (fd, F_SETFD, FD_CLOEXEC);
173 return fd;
176 static int
177 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
179 return close_on_exec (accept (sockfd, addr, addrlen));
182 static int
183 process_socket (int domain, int type, int protocol)
185 return close_on_exec (socket (domain, type, protocol));
187 # undef socket
188 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
189 #endif
191 Lisp_Object Qprocessp;
192 static Lisp_Object Qrun, Qstop, Qsignal;
193 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
194 Lisp_Object Qlocal;
195 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
196 static Lisp_Object Qreal, Qnetwork, Qserial;
197 #ifdef AF_INET6
198 static Lisp_Object Qipv6;
199 #endif
200 static Lisp_Object QCport, QCprocess;
201 Lisp_Object QCspeed;
202 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
203 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
204 static Lisp_Object QCbuffer, QChost, QCservice;
205 static Lisp_Object QClocal, QCremote, QCcoding;
206 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
207 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
208 static Lisp_Object Qlast_nonmenu_event;
209 static Lisp_Object Qinternal_default_process_sentinel;
210 static Lisp_Object Qinternal_default_process_filter;
212 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
213 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
214 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
215 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 /* Only W32 has this, it really means that select can't take write mask. */
225 #ifdef BROKEN_NON_BLOCKING_CONNECT
226 #undef NON_BLOCKING_CONNECT
227 enum { SELECT_CAN_DO_WRITE_MASK = false };
228 #else
229 enum { SELECT_CAN_DO_WRITE_MASK = true };
230 #ifndef NON_BLOCKING_CONNECT
231 #ifdef HAVE_SELECT
232 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
233 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
234 #define NON_BLOCKING_CONNECT
235 #endif /* EWOULDBLOCK || EINPROGRESS */
236 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
237 #endif /* HAVE_SELECT */
238 #endif /* NON_BLOCKING_CONNECT */
239 #endif /* BROKEN_NON_BLOCKING_CONNECT */
241 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
242 this system. We need to read full packets, so we need a
243 "non-destructive" select. So we require either native select,
244 or emulation of select using FIONREAD. */
246 #ifndef BROKEN_DATAGRAM_SOCKETS
247 # if defined HAVE_SELECT || defined USABLE_FIONREAD
248 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
249 # define DATAGRAM_SOCKETS
250 # endif
251 # endif
252 #endif
254 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
255 # define HAVE_SEQPACKET
256 #endif
258 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
259 #define ADAPTIVE_READ_BUFFERING
260 #endif
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count;
272 /* True if any process has non-nil read_output_skip. */
274 static bool process_output_skip;
276 #else
277 #define process_output_delay_count 0
278 #endif
280 static void create_process (Lisp_Object, char **, Lisp_Object);
281 #ifdef USABLE_SIGIO
282 static bool keyboard_bit_set (fd_set *);
283 #endif
284 static void deactivate_process (Lisp_Object);
285 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
286 static int read_process_output (Lisp_Object, int);
287 static void handle_child_signal (int);
288 static void create_pty (Lisp_Object);
290 static Lisp_Object get_process (register Lisp_Object name);
291 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
293 /* Mask of bits indicating the descriptors that we wait for input on. */
295 static fd_set input_wait_mask;
297 /* Mask that excludes keyboard input descriptor(s). */
299 static fd_set non_keyboard_wait_mask;
301 /* Mask that excludes process input descriptor(s). */
303 static fd_set non_process_wait_mask;
305 /* Mask for selecting for write. */
307 static fd_set write_mask;
309 #ifdef NON_BLOCKING_CONNECT
310 /* Mask of bits indicating the descriptors that we wait for connect to
311 complete on. Once they complete, they are removed from this mask
312 and added to the input_wait_mask and non_keyboard_wait_mask. */
314 static fd_set connect_wait_mask;
316 /* Number of bits set in connect_wait_mask. */
317 static int num_pending_connects;
318 #endif /* NON_BLOCKING_CONNECT */
320 /* The largest descriptor currently in use for a process object; -1 if none. */
321 static int max_process_desc;
323 /* The largest descriptor currently in use for input; -1 if none. */
324 static int max_input_desc;
326 /* Indexed by descriptor, gives the process (if any) for that descriptor */
327 static Lisp_Object chan_process[FD_SETSIZE];
329 /* Alist of elements (NAME . PROCESS) */
330 static Lisp_Object Vprocess_alist;
332 /* Buffered-ahead input char from process, indexed by channel.
333 -1 means empty (no char is buffered).
334 Used on sys V where the only way to tell if there is any
335 output from the process is to read at least one char.
336 Always -1 on systems that support FIONREAD. */
338 static int proc_buffered_char[FD_SETSIZE];
340 /* Table of `struct coding-system' for each process. */
341 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
342 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
344 #ifdef DATAGRAM_SOCKETS
345 /* Table of `partner address' for datagram sockets. */
346 static struct sockaddr_and_len {
347 struct sockaddr *sa;
348 int len;
349 } datagram_address[FD_SETSIZE];
350 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
351 #define DATAGRAM_CONN_P(proc) \
352 (PROCESSP (proc) && \
353 XPROCESS (proc)->infd >= 0 && \
354 datagram_address[XPROCESS (proc)->infd].sa != 0)
355 #else
356 #define DATAGRAM_CHAN_P(chan) (0)
357 #define DATAGRAM_CONN_P(proc) (0)
358 #endif
360 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
361 a `for' loop which iterates over processes from Vprocess_alist. */
363 #define FOR_EACH_PROCESS(list_var, proc_var) \
364 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
366 /* These setters are used only in this file, so they can be private. */
367 static void
368 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
370 p->buffer = val;
372 static void
373 pset_command (struct Lisp_Process *p, Lisp_Object val)
375 p->command = val;
377 static void
378 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
380 p->decode_coding_system = val;
382 static void
383 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
385 p->decoding_buf = val;
387 static void
388 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
390 p->encode_coding_system = val;
392 static void
393 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
395 p->encoding_buf = val;
397 static void
398 pset_filter (struct Lisp_Process *p, Lisp_Object val)
400 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
402 static void
403 pset_log (struct Lisp_Process *p, Lisp_Object val)
405 p->log = val;
407 static void
408 pset_mark (struct Lisp_Process *p, Lisp_Object val)
410 p->mark = val;
412 static void
413 pset_name (struct Lisp_Process *p, Lisp_Object val)
415 p->name = val;
417 static void
418 pset_plist (struct Lisp_Process *p, Lisp_Object val)
420 p->plist = val;
422 static void
423 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
425 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
427 static void
428 pset_status (struct Lisp_Process *p, Lisp_Object val)
430 p->status = val;
432 static void
433 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
435 p->tty_name = val;
437 static void
438 pset_type (struct Lisp_Process *p, Lisp_Object val)
440 p->type = val;
442 static void
443 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
445 p->write_queue = val;
450 static struct fd_callback_data
452 fd_callback func;
453 void *data;
454 #define FOR_READ 1
455 #define FOR_WRITE 2
456 int condition; /* mask of the defines above. */
457 } fd_callback_info[FD_SETSIZE];
460 /* Add a file descriptor FD to be monitored for when read is possible.
461 When read is possible, call FUNC with argument DATA. */
463 void
464 add_read_fd (int fd, fd_callback func, void *data)
466 add_keyboard_wait_descriptor (fd);
468 fd_callback_info[fd].func = func;
469 fd_callback_info[fd].data = data;
470 fd_callback_info[fd].condition |= FOR_READ;
473 /* Stop monitoring file descriptor FD for when read is possible. */
475 void
476 delete_read_fd (int fd)
478 delete_keyboard_wait_descriptor (fd);
480 fd_callback_info[fd].condition &= ~FOR_READ;
481 if (fd_callback_info[fd].condition == 0)
483 fd_callback_info[fd].func = 0;
484 fd_callback_info[fd].data = 0;
488 /* Add a file descriptor FD to be monitored for when write is possible.
489 When write is possible, call FUNC with argument DATA. */
491 void
492 add_write_fd (int fd, fd_callback func, void *data)
494 FD_SET (fd, &write_mask);
495 if (fd > max_input_desc)
496 max_input_desc = fd;
498 fd_callback_info[fd].func = func;
499 fd_callback_info[fd].data = data;
500 fd_callback_info[fd].condition |= FOR_WRITE;
503 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
505 static void
506 delete_input_desc (int fd)
508 if (fd == max_input_desc)
511 fd--;
512 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
513 || FD_ISSET (fd, &write_mask)));
515 max_input_desc = fd;
519 /* Stop monitoring file descriptor FD for when write is possible. */
521 void
522 delete_write_fd (int fd)
524 FD_CLR (fd, &write_mask);
525 fd_callback_info[fd].condition &= ~FOR_WRITE;
526 if (fd_callback_info[fd].condition == 0)
528 fd_callback_info[fd].func = 0;
529 fd_callback_info[fd].data = 0;
530 delete_input_desc (fd);
535 /* Compute the Lisp form of the process status, p->status, from
536 the numeric status that was returned by `wait'. */
538 static Lisp_Object status_convert (int);
540 static void
541 update_status (struct Lisp_Process *p)
543 eassert (p->raw_status_new);
544 pset_status (p, status_convert (p->raw_status));
545 p->raw_status_new = 0;
548 /* Convert a process status word in Unix format to
549 the list that we use internally. */
551 static Lisp_Object
552 status_convert (int w)
554 if (WIFSTOPPED (w))
555 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
556 else if (WIFEXITED (w))
557 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
558 WCOREDUMP (w) ? Qt : Qnil));
559 else if (WIFSIGNALED (w))
560 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
561 WCOREDUMP (w) ? Qt : Qnil));
562 else
563 return Qrun;
566 /* Given a status-list, extract the three pieces of information
567 and store them individually through the three pointers. */
569 static void
570 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
572 Lisp_Object tem;
574 if (SYMBOLP (l))
576 *symbol = l;
577 *code = 0;
578 *coredump = 0;
580 else
582 *symbol = XCAR (l);
583 tem = XCDR (l);
584 *code = XFASTINT (XCAR (tem));
585 tem = XCDR (tem);
586 *coredump = !NILP (tem);
590 /* Return a string describing a process status list. */
592 static Lisp_Object
593 status_message (struct Lisp_Process *p)
595 Lisp_Object status = p->status;
596 Lisp_Object symbol;
597 int code;
598 bool coredump;
599 Lisp_Object string;
601 decode_status (status, &symbol, &code, &coredump);
603 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
605 char const *signame;
606 synchronize_system_messages_locale ();
607 signame = strsignal (code);
608 if (signame == 0)
609 string = build_string ("unknown");
610 else
612 int c1, c2;
614 string = build_unibyte_string (signame);
615 if (! NILP (Vlocale_coding_system))
616 string = (code_convert_string_norecord
617 (string, Vlocale_coding_system, 0));
618 c1 = STRING_CHAR (SDATA (string));
619 c2 = downcase (c1);
620 if (c1 != c2)
621 Faset (string, make_number (0), make_number (c2));
623 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
624 return concat2 (string, suffix);
626 else if (EQ (symbol, Qexit))
628 if (NETCONN1_P (p))
629 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
630 if (code == 0)
631 return build_string ("finished\n");
632 AUTO_STRING (prefix, "exited abnormally with code ");
633 string = Fnumber_to_string (make_number (code));
634 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
635 return concat3 (prefix, string, suffix);
637 else if (EQ (symbol, Qfailed))
639 AUTO_STRING (prefix, "failed with code ");
640 string = Fnumber_to_string (make_number (code));
641 AUTO_STRING (suffix, "\n");
642 return concat3 (prefix, string, suffix);
644 else
645 return Fcopy_sequence (Fsymbol_name (symbol));
648 enum { PTY_NAME_SIZE = 24 };
650 /* Open an available pty, returning a file descriptor.
651 Store into PTY_NAME the file name of the terminal corresponding to the pty.
652 Return -1 on failure. */
654 static int
655 allocate_pty (char pty_name[PTY_NAME_SIZE])
657 #ifdef HAVE_PTYS
658 int fd;
660 #ifdef PTY_ITERATION
661 PTY_ITERATION
662 #else
663 register int c, i;
664 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
665 for (i = 0; i < 16; i++)
666 #endif
668 #ifdef PTY_NAME_SPRINTF
669 PTY_NAME_SPRINTF
670 #else
671 sprintf (pty_name, "/dev/pty%c%x", c, i);
672 #endif /* no PTY_NAME_SPRINTF */
674 #ifdef PTY_OPEN
675 PTY_OPEN;
676 #else /* no PTY_OPEN */
677 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
678 #endif /* no PTY_OPEN */
680 if (fd >= 0)
682 #ifdef PTY_OPEN
683 /* Set FD's close-on-exec flag. This is needed even if
684 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
685 doesn't require support for that combination.
686 Multithreaded platforms where posix_openpt ignores
687 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
688 have a race condition between the PTY_OPEN and here. */
689 fcntl (fd, F_SETFD, FD_CLOEXEC);
690 #endif
691 /* check to make certain that both sides are available
692 this avoids a nasty yet stupid bug in rlogins */
693 #ifdef PTY_TTY_NAME_SPRINTF
694 PTY_TTY_NAME_SPRINTF
695 #else
696 sprintf (pty_name, "/dev/tty%c%x", c, i);
697 #endif /* no PTY_TTY_NAME_SPRINTF */
698 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
700 emacs_close (fd);
701 # ifndef __sgi
702 continue;
703 # else
704 return -1;
705 # endif /* __sgi */
707 setup_pty (fd);
708 return fd;
711 #endif /* HAVE_PTYS */
712 return -1;
715 static Lisp_Object
716 make_process (Lisp_Object name)
718 register Lisp_Object val, tem, name1;
719 register struct Lisp_Process *p;
720 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
721 printmax_t i;
723 p = allocate_process ();
724 /* Initialize Lisp data. Note that allocate_process initializes all
725 Lisp data to nil, so do it only for slots which should not be nil. */
726 pset_status (p, Qrun);
727 pset_mark (p, Fmake_marker ());
729 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
730 non-Lisp data, so do it only for slots which should not be zero. */
731 p->infd = -1;
732 p->outfd = -1;
733 for (i = 0; i < PROCESS_OPEN_FDS; i++)
734 p->open_fd[i] = -1;
736 #ifdef HAVE_GNUTLS
737 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
738 #endif
740 /* If name is already in use, modify it until it is unused. */
742 name1 = name;
743 for (i = 1; ; i++)
745 tem = Fget_process (name1);
746 if (NILP (tem)) break;
747 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
749 name = name1;
750 pset_name (p, name);
751 pset_sentinel (p, Qinternal_default_process_sentinel);
752 pset_filter (p, Qinternal_default_process_filter);
753 XSETPROCESS (val, p);
754 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
755 return val;
758 static void
759 remove_process (register Lisp_Object proc)
761 register Lisp_Object pair;
763 pair = Frassq (proc, Vprocess_alist);
764 Vprocess_alist = Fdelq (pair, Vprocess_alist);
766 deactivate_process (proc);
770 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
771 doc: /* Return t if OBJECT is a process. */)
772 (Lisp_Object object)
774 return PROCESSP (object) ? Qt : Qnil;
777 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
778 doc: /* Return the process named NAME, or nil if there is none. */)
779 (register Lisp_Object name)
781 if (PROCESSP (name))
782 return name;
783 CHECK_STRING (name);
784 return Fcdr (Fassoc (name, Vprocess_alist));
787 /* This is how commands for the user decode process arguments. It
788 accepts a process, a process name, a buffer, a buffer name, or nil.
789 Buffers denote the first process in the buffer, and nil denotes the
790 current buffer. */
792 static Lisp_Object
793 get_process (register Lisp_Object name)
795 register Lisp_Object proc, obj;
796 if (STRINGP (name))
798 obj = Fget_process (name);
799 if (NILP (obj))
800 obj = Fget_buffer (name);
801 if (NILP (obj))
802 error ("Process %s does not exist", SDATA (name));
804 else if (NILP (name))
805 obj = Fcurrent_buffer ();
806 else
807 obj = name;
809 /* Now obj should be either a buffer object or a process object. */
810 if (BUFFERP (obj))
812 if (NILP (BVAR (XBUFFER (obj), name)))
813 error ("Attempt to get process for a dead buffer");
814 proc = Fget_buffer_process (obj);
815 if (NILP (proc))
816 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
818 else
820 CHECK_PROCESS (obj);
821 proc = obj;
823 return proc;
827 /* Fdelete_process promises to immediately forget about the process, but in
828 reality, Emacs needs to remember those processes until they have been
829 treated by the SIGCHLD handler and waitpid has been invoked on them;
830 otherwise they might fill up the kernel's process table.
832 Some processes created by call-process are also put onto this list.
834 Members of this list are (process-ID . filename) pairs. The
835 process-ID is a number; the filename, if a string, is a file that
836 needs to be removed after the process exits. */
837 static Lisp_Object deleted_pid_list;
839 void
840 record_deleted_pid (pid_t pid, Lisp_Object filename)
842 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
843 /* GC treated elements set to nil. */
844 Fdelq (Qnil, deleted_pid_list));
848 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
849 doc: /* Delete PROCESS: kill it and forget about it immediately.
850 PROCESS may be a process, a buffer, the name of a process or buffer, or
851 nil, indicating the current buffer's process. */)
852 (register Lisp_Object process)
854 register struct Lisp_Process *p;
856 process = get_process (process);
857 p = XPROCESS (process);
859 p->raw_status_new = 0;
860 if (NETCONN1_P (p) || SERIALCONN1_P (p))
862 pset_status (p, list2 (Qexit, make_number (0)));
863 p->tick = ++process_tick;
864 status_notify (p, NULL);
865 redisplay_preserve_echo_area (13);
867 else
869 if (p->alive)
870 record_kill_process (p, Qnil);
872 if (p->infd >= 0)
874 /* Update P's status, since record_kill_process will make the
875 SIGCHLD handler update deleted_pid_list, not *P. */
876 Lisp_Object symbol;
877 if (p->raw_status_new)
878 update_status (p);
879 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
880 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
881 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
883 p->tick = ++process_tick;
884 status_notify (p, NULL);
885 redisplay_preserve_echo_area (13);
888 remove_process (process);
889 return Qnil;
892 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
893 doc: /* Return the status of PROCESS.
894 The returned value is one of the following symbols:
895 run -- for a process that is running.
896 stop -- for a process stopped but continuable.
897 exit -- for a process that has exited.
898 signal -- for a process that has got a fatal signal.
899 open -- for a network stream connection that is open.
900 listen -- for a network stream server that is listening.
901 closed -- for a network stream connection that is closed.
902 connect -- when waiting for a non-blocking connection to complete.
903 failed -- when a non-blocking connection has failed.
904 nil -- if arg is a process name and no such process exists.
905 PROCESS may be a process, a buffer, the name of a process, or
906 nil, indicating the current buffer's process. */)
907 (register Lisp_Object process)
909 register struct Lisp_Process *p;
910 register Lisp_Object status;
912 if (STRINGP (process))
913 process = Fget_process (process);
914 else
915 process = get_process (process);
917 if (NILP (process))
918 return process;
920 p = XPROCESS (process);
921 if (p->raw_status_new)
922 update_status (p);
923 status = p->status;
924 if (CONSP (status))
925 status = XCAR (status);
926 if (NETCONN1_P (p) || SERIALCONN1_P (p))
928 if (EQ (status, Qexit))
929 status = Qclosed;
930 else if (EQ (p->command, Qt))
931 status = Qstop;
932 else if (EQ (status, Qrun))
933 status = Qopen;
935 return status;
938 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
939 1, 1, 0,
940 doc: /* Return the exit status of PROCESS or the signal number that killed it.
941 If PROCESS has not yet exited or died, return 0. */)
942 (register Lisp_Object process)
944 CHECK_PROCESS (process);
945 if (XPROCESS (process)->raw_status_new)
946 update_status (XPROCESS (process));
947 if (CONSP (XPROCESS (process)->status))
948 return XCAR (XCDR (XPROCESS (process)->status));
949 return make_number (0);
952 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
953 doc: /* Return the process id of PROCESS.
954 This is the pid of the external process which PROCESS uses or talks to.
955 For a network connection, this value is nil. */)
956 (register Lisp_Object process)
958 pid_t pid;
960 CHECK_PROCESS (process);
961 pid = XPROCESS (process)->pid;
962 return (pid ? make_fixnum_or_float (pid) : Qnil);
965 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
966 doc: /* Return the name of PROCESS, as a string.
967 This is the name of the program invoked in PROCESS,
968 possibly modified to make it unique among process names. */)
969 (register Lisp_Object process)
971 CHECK_PROCESS (process);
972 return XPROCESS (process)->name;
975 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
976 doc: /* Return the command that was executed to start PROCESS.
977 This is a list of strings, the first string being the program executed
978 and the rest of the strings being the arguments given to it.
979 For a network or serial process, this is nil (process is running) or t
980 \(process is stopped). */)
981 (register Lisp_Object process)
983 CHECK_PROCESS (process);
984 return XPROCESS (process)->command;
987 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
988 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
989 This is the terminal that the process itself reads and writes on,
990 not the name of the pty that Emacs uses to talk with that terminal. */)
991 (register Lisp_Object process)
993 CHECK_PROCESS (process);
994 return XPROCESS (process)->tty_name;
997 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
998 2, 2, 0,
999 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1000 Return BUFFER. */)
1001 (register Lisp_Object process, Lisp_Object buffer)
1003 struct Lisp_Process *p;
1005 CHECK_PROCESS (process);
1006 if (!NILP (buffer))
1007 CHECK_BUFFER (buffer);
1008 p = XPROCESS (process);
1009 pset_buffer (p, buffer);
1010 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1011 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1012 setup_process_coding_systems (process);
1013 return buffer;
1016 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1017 1, 1, 0,
1018 doc: /* Return the buffer PROCESS is associated with.
1019 The default process filter inserts output from PROCESS into this buffer. */)
1020 (register Lisp_Object process)
1022 CHECK_PROCESS (process);
1023 return XPROCESS (process)->buffer;
1026 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1027 1, 1, 0,
1028 doc: /* Return the marker for the end of the last output from PROCESS. */)
1029 (register Lisp_Object process)
1031 CHECK_PROCESS (process);
1032 return XPROCESS (process)->mark;
1035 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1036 2, 2, 0,
1037 doc: /* Give PROCESS the filter function FILTER; nil means default.
1038 A value of t means stop accepting output from the process.
1040 When a process has a non-default filter, its buffer is not used for output.
1041 Instead, each time it does output, the entire string of output is
1042 passed to the filter.
1044 The filter gets two arguments: the process and the string of output.
1045 The string argument is normally a multibyte string, except:
1046 - if the process's input coding system is no-conversion or raw-text,
1047 it is a unibyte string (the non-converted input), or else
1048 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1049 string (the result of converting the decoded input multibyte
1050 string to unibyte with `string-make-unibyte'). */)
1051 (register Lisp_Object process, Lisp_Object filter)
1053 struct Lisp_Process *p;
1055 CHECK_PROCESS (process);
1056 p = XPROCESS (process);
1058 /* Don't signal an error if the process's input file descriptor
1059 is closed. This could make debugging Lisp more difficult,
1060 for example when doing something like
1062 (setq process (start-process ...))
1063 (debug)
1064 (set-process-filter process ...) */
1066 if (NILP (filter))
1067 filter = Qinternal_default_process_filter;
1069 if (p->infd >= 0)
1071 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1073 FD_CLR (p->infd, &input_wait_mask);
1074 FD_CLR (p->infd, &non_keyboard_wait_mask);
1076 else if (EQ (p->filter, Qt)
1077 /* Network or serial process not stopped: */
1078 && !EQ (p->command, Qt))
1080 FD_SET (p->infd, &input_wait_mask);
1081 FD_SET (p->infd, &non_keyboard_wait_mask);
1085 pset_filter (p, filter);
1086 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1087 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1088 setup_process_coding_systems (process);
1089 return filter;
1092 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1093 1, 1, 0,
1094 doc: /* Return the filter function of PROCESS.
1095 See `set-process-filter' for more info on filter functions. */)
1096 (register Lisp_Object process)
1098 CHECK_PROCESS (process);
1099 return XPROCESS (process)->filter;
1102 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1103 2, 2, 0,
1104 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1105 The sentinel is called as a function when the process changes state.
1106 It gets two arguments: the process, and a string describing the change. */)
1107 (register Lisp_Object process, Lisp_Object sentinel)
1109 struct Lisp_Process *p;
1111 CHECK_PROCESS (process);
1112 p = XPROCESS (process);
1114 if (NILP (sentinel))
1115 sentinel = Qinternal_default_process_sentinel;
1117 pset_sentinel (p, sentinel);
1118 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1119 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1120 return sentinel;
1123 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1124 1, 1, 0,
1125 doc: /* Return the sentinel of PROCESS.
1126 See `set-process-sentinel' for more info on sentinels. */)
1127 (register Lisp_Object process)
1129 CHECK_PROCESS (process);
1130 return XPROCESS (process)->sentinel;
1133 DEFUN ("set-process-window-size", Fset_process_window_size,
1134 Sset_process_window_size, 3, 3, 0,
1135 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1136 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1138 CHECK_PROCESS (process);
1140 /* All known platforms store window sizes as 'unsigned short'. */
1141 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1142 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1144 if (XPROCESS (process)->infd < 0
1145 || (set_window_size (XPROCESS (process)->infd,
1146 XINT (height), XINT (width))
1147 < 0))
1148 return Qnil;
1149 else
1150 return Qt;
1153 DEFUN ("set-process-inherit-coding-system-flag",
1154 Fset_process_inherit_coding_system_flag,
1155 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1156 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1157 If the second argument FLAG is non-nil, then the variable
1158 `buffer-file-coding-system' of the buffer associated with PROCESS
1159 will be bound to the value of the coding system used to decode
1160 the process output.
1162 This is useful when the coding system specified for the process buffer
1163 leaves either the character code conversion or the end-of-line conversion
1164 unspecified, or if the coding system used to decode the process output
1165 is more appropriate for saving the process buffer.
1167 Binding the variable `inherit-process-coding-system' to non-nil before
1168 starting the process is an alternative way of setting the inherit flag
1169 for the process which will run.
1171 This function returns FLAG. */)
1172 (register Lisp_Object process, Lisp_Object flag)
1174 CHECK_PROCESS (process);
1175 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1176 return flag;
1179 DEFUN ("set-process-query-on-exit-flag",
1180 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1181 2, 2, 0,
1182 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1183 If the second argument FLAG is non-nil, Emacs will query the user before
1184 exiting or killing a buffer if PROCESS is running. This function
1185 returns FLAG. */)
1186 (register Lisp_Object process, Lisp_Object flag)
1188 CHECK_PROCESS (process);
1189 XPROCESS (process)->kill_without_query = NILP (flag);
1190 return flag;
1193 DEFUN ("process-query-on-exit-flag",
1194 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1195 1, 1, 0,
1196 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1197 (register Lisp_Object process)
1199 CHECK_PROCESS (process);
1200 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1203 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1204 1, 2, 0,
1205 doc: /* Return the contact info of PROCESS; t for a real child.
1206 For a network or serial connection, the value depends on the optional
1207 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1208 SERVICE) for a network connection or (PORT SPEED) for a serial
1209 connection. If KEY is t, the complete contact information for the
1210 connection is returned, else the specific value for the keyword KEY is
1211 returned. See `make-network-process' or `make-serial-process' for a
1212 list of keywords. */)
1213 (register Lisp_Object process, Lisp_Object key)
1215 Lisp_Object contact;
1217 CHECK_PROCESS (process);
1218 contact = XPROCESS (process)->childp;
1220 #ifdef DATAGRAM_SOCKETS
1221 if (DATAGRAM_CONN_P (process)
1222 && (EQ (key, Qt) || EQ (key, QCremote)))
1223 contact = Fplist_put (contact, QCremote,
1224 Fprocess_datagram_address (process));
1225 #endif
1227 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1228 return contact;
1229 if (NILP (key) && NETCONN_P (process))
1230 return list2 (Fplist_get (contact, QChost),
1231 Fplist_get (contact, QCservice));
1232 if (NILP (key) && SERIALCONN_P (process))
1233 return list2 (Fplist_get (contact, QCport),
1234 Fplist_get (contact, QCspeed));
1235 return Fplist_get (contact, key);
1238 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1239 1, 1, 0,
1240 doc: /* Return the plist of PROCESS. */)
1241 (register Lisp_Object process)
1243 CHECK_PROCESS (process);
1244 return XPROCESS (process)->plist;
1247 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1248 2, 2, 0,
1249 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1250 (register Lisp_Object process, Lisp_Object plist)
1252 CHECK_PROCESS (process);
1253 CHECK_LIST (plist);
1255 pset_plist (XPROCESS (process), plist);
1256 return plist;
1259 #if 0 /* Turned off because we don't currently record this info
1260 in the process. Perhaps add it. */
1261 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1262 doc: /* Return the connection type of PROCESS.
1263 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1264 a socket connection. */)
1265 (Lisp_Object process)
1267 return XPROCESS (process)->type;
1269 #endif
1271 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1272 doc: /* Return the connection type of PROCESS.
1273 The value is either the symbol `real', `network', or `serial'.
1274 PROCESS may be a process, a buffer, the name of a process or buffer, or
1275 nil, indicating the current buffer's process. */)
1276 (Lisp_Object process)
1278 Lisp_Object proc;
1279 proc = get_process (process);
1280 return XPROCESS (proc)->type;
1283 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1284 1, 2, 0,
1285 doc: /* Convert network ADDRESS from internal format to a string.
1286 A 4 or 5 element vector represents an IPv4 address (with port number).
1287 An 8 or 9 element vector represents an IPv6 address (with port number).
1288 If optional second argument OMIT-PORT is non-nil, don't include a port
1289 number in the string, even when present in ADDRESS.
1290 Returns nil if format of ADDRESS is invalid. */)
1291 (Lisp_Object address, Lisp_Object omit_port)
1293 if (NILP (address))
1294 return Qnil;
1296 if (STRINGP (address)) /* AF_LOCAL */
1297 return address;
1299 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1301 register struct Lisp_Vector *p = XVECTOR (address);
1302 ptrdiff_t size = p->header.size;
1303 Lisp_Object args[10];
1304 int nargs, i;
1305 char const *format;
1307 if (size == 4 || (size == 5 && !NILP (omit_port)))
1309 format = "%d.%d.%d.%d";
1310 nargs = 4;
1312 else if (size == 5)
1314 format = "%d.%d.%d.%d:%d";
1315 nargs = 5;
1317 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1319 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1320 nargs = 8;
1322 else if (size == 9)
1324 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1325 nargs = 9;
1327 else
1328 return Qnil;
1330 AUTO_STRING (format_obj, format);
1331 args[0] = format_obj;
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 AUTO_STRING (format, "<Family %d>");
1352 return Fformat (2, (Lisp_Object []) {format, Fcar (address)});
1355 return Qnil;
1358 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1359 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1360 (void)
1362 return Fmapcar (Qcdr, Vprocess_alist);
1365 /* Starting asynchronous inferior processes. */
1367 static void start_process_unwind (Lisp_Object proc);
1369 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1370 doc: /* Start a program in a subprocess. Return the process object for it.
1371 NAME is name for process. It is modified if necessary to make it unique.
1372 BUFFER is the buffer (or buffer name) to associate with the process.
1374 Process output (both standard output and standard error streams) goes
1375 at end of BUFFER, unless you specify an output stream or filter
1376 function to handle the output. BUFFER may also be nil, meaning that
1377 this process is not associated with any buffer.
1379 PROGRAM is the program file name. It is searched for in `exec-path'
1380 (which see). If nil, just associate a pty with the buffer. Remaining
1381 arguments are strings to give program as arguments.
1383 If you want to separate standard output from standard error, invoke
1384 the command through a shell and redirect one of them using the shell
1385 syntax.
1387 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1388 (ptrdiff_t nargs, Lisp_Object *args)
1390 Lisp_Object buffer, name, program, proc, current_dir, tem;
1391 unsigned char **new_argv;
1392 ptrdiff_t i;
1393 ptrdiff_t count = SPECPDL_INDEX ();
1394 USE_SAFE_ALLOCA;
1396 buffer = args[1];
1397 if (!NILP (buffer))
1398 buffer = Fget_buffer_create (buffer);
1400 /* Make sure that the child will be able to chdir to the current
1401 buffer's current directory, or its unhandled equivalent. We
1402 can't just have the child check for an error when it does the
1403 chdir, since it's in a vfork.
1405 We have to GCPRO around this because Fexpand_file_name and
1406 Funhandled_file_name_directory might call a file name handling
1407 function. The argument list is protected by the caller, so all
1408 we really have to worry about is buffer. */
1410 struct gcpro gcpro1;
1411 GCPRO1 (buffer);
1412 current_dir = encode_current_directory ();
1413 UNGCPRO;
1416 name = args[0];
1417 CHECK_STRING (name);
1419 program = args[2];
1421 if (!NILP (program))
1422 CHECK_STRING (program);
1424 proc = make_process (name);
1425 /* If an error occurs and we can't start the process, we want to
1426 remove it from the process list. This means that each error
1427 check in create_process doesn't need to call remove_process
1428 itself; it's all taken care of here. */
1429 record_unwind_protect (start_process_unwind, proc);
1431 pset_childp (XPROCESS (proc), Qt);
1432 pset_plist (XPROCESS (proc), Qnil);
1433 pset_type (XPROCESS (proc), Qreal);
1434 pset_buffer (XPROCESS (proc), buffer);
1435 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1436 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1437 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1439 #ifdef HAVE_GNUTLS
1440 /* AKA GNUTLS_INITSTAGE(proc). */
1441 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1442 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1443 #endif
1445 #ifdef ADAPTIVE_READ_BUFFERING
1446 XPROCESS (proc)->adaptive_read_buffering
1447 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1448 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1449 #endif
1451 /* Make the process marker point into the process buffer (if any). */
1452 if (BUFFERP (buffer))
1453 set_marker_both (XPROCESS (proc)->mark, buffer,
1454 BUF_ZV (XBUFFER (buffer)),
1455 BUF_ZV_BYTE (XBUFFER (buffer)));
1458 /* Decide coding systems for communicating with the process. Here
1459 we don't setup the structure coding_system nor pay attention to
1460 unibyte mode. They are done in create_process. */
1462 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1463 Lisp_Object coding_systems = Qt;
1464 Lisp_Object val, *args2;
1465 struct gcpro gcpro1, gcpro2;
1467 val = Vcoding_system_for_read;
1468 if (NILP (val))
1470 SAFE_ALLOCA_LISP (args2, nargs + 1);
1471 args2[0] = Qstart_process;
1472 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1473 GCPRO2 (proc, current_dir);
1474 if (!NILP (program))
1475 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1476 UNGCPRO;
1477 if (CONSP (coding_systems))
1478 val = XCAR (coding_systems);
1479 else if (CONSP (Vdefault_process_coding_system))
1480 val = XCAR (Vdefault_process_coding_system);
1482 pset_decode_coding_system (XPROCESS (proc), val);
1484 val = Vcoding_system_for_write;
1485 if (NILP (val))
1487 if (EQ (coding_systems, Qt))
1489 SAFE_ALLOCA_LISP (args2, nargs + 1);
1490 args2[0] = Qstart_process;
1491 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1492 GCPRO2 (proc, current_dir);
1493 if (!NILP (program))
1494 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1495 UNGCPRO;
1497 if (CONSP (coding_systems))
1498 val = XCDR (coding_systems);
1499 else if (CONSP (Vdefault_process_coding_system))
1500 val = XCDR (Vdefault_process_coding_system);
1502 pset_encode_coding_system (XPROCESS (proc), val);
1503 /* Note: At this moment, the above coding system may leave
1504 text-conversion or eol-conversion unspecified. They will be
1505 decided after we read output from the process and decode it by
1506 some coding system, or just before we actually send a text to
1507 the process. */
1511 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1512 XPROCESS (proc)->decoding_carryover = 0;
1513 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1515 XPROCESS (proc)->inherit_coding_system_flag
1516 = !(NILP (buffer) || !inherit_process_coding_system);
1518 if (!NILP (program))
1520 /* If program file name is not absolute, search our path for it.
1521 Put the name we will really use in TEM. */
1522 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1523 && !(SCHARS (program) > 1
1524 && IS_DEVICE_SEP (SREF (program, 1))))
1526 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1528 tem = Qnil;
1529 GCPRO4 (name, program, buffer, current_dir);
1530 openp (Vexec_path, program, Vexec_suffixes, &tem,
1531 make_number (X_OK), false);
1532 UNGCPRO;
1533 if (NILP (tem))
1534 report_file_error ("Searching for program", program);
1535 tem = Fexpand_file_name (tem, Qnil);
1537 else
1539 if (!NILP (Ffile_directory_p (program)))
1540 error ("Specified program for new process is a directory");
1541 tem = program;
1544 /* If program file name starts with /: for quoting a magic name,
1545 discard that. */
1546 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1547 && SREF (tem, 1) == ':')
1548 tem = Fsubstring (tem, make_number (2), Qnil);
1551 Lisp_Object arg_encoding = Qnil;
1552 struct gcpro gcpro1;
1553 GCPRO1 (tem);
1555 /* Encode the file name and put it in NEW_ARGV.
1556 That's where the child will use it to execute the program. */
1557 tem = list1 (ENCODE_FILE (tem));
1559 /* Here we encode arguments by the coding system used for sending
1560 data to the process. We don't support using different coding
1561 systems for encoding arguments and for encoding data sent to the
1562 process. */
1564 for (i = 3; i < nargs; i++)
1566 tem = Fcons (args[i], tem);
1567 CHECK_STRING (XCAR (tem));
1568 if (STRING_MULTIBYTE (XCAR (tem)))
1570 if (NILP (arg_encoding))
1571 arg_encoding = (complement_process_encoding_system
1572 (XPROCESS (proc)->encode_coding_system));
1573 XSETCAR (tem,
1574 code_convert_string_norecord
1575 (XCAR (tem), arg_encoding, 1));
1579 UNGCPRO;
1582 /* Now that everything is encoded we can collect the strings into
1583 NEW_ARGV. */
1584 SAFE_NALLOCA (new_argv, 1, nargs - 1);
1585 new_argv[nargs - 2] = 0;
1587 for (i = nargs - 2; i-- != 0; )
1589 new_argv[i] = SDATA (XCAR (tem));
1590 tem = XCDR (tem);
1593 create_process (proc, (char **) new_argv, current_dir);
1595 else
1596 create_pty (proc);
1598 SAFE_FREE ();
1599 return unbind_to (count, proc);
1602 /* This function is the unwind_protect form for Fstart_process. If
1603 PROC doesn't have its pid set, then we know someone has signaled
1604 an error and the process wasn't started successfully, so we should
1605 remove it from the process list. */
1606 static void
1607 start_process_unwind (Lisp_Object proc)
1609 if (!PROCESSP (proc))
1610 emacs_abort ();
1612 /* Was PROC started successfully?
1613 -2 is used for a pty with no process, eg for gdb. */
1614 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1615 remove_process (proc);
1618 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1620 static void
1621 close_process_fd (int *fd_addr)
1623 int fd = *fd_addr;
1624 if (0 <= fd)
1626 *fd_addr = -1;
1627 emacs_close (fd);
1631 /* Indexes of file descriptors in open_fds. */
1632 enum
1634 /* The pipe from Emacs to its subprocess. */
1635 SUBPROCESS_STDIN,
1636 WRITE_TO_SUBPROCESS,
1638 /* The main pipe from the subprocess to Emacs. */
1639 READ_FROM_SUBPROCESS,
1640 SUBPROCESS_STDOUT,
1642 /* The pipe from the subprocess to Emacs that is closed when the
1643 subprocess execs. */
1644 READ_FROM_EXEC_MONITOR,
1645 EXEC_MONITOR_OUTPUT
1648 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1650 static void
1651 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1653 struct Lisp_Process *p = XPROCESS (process);
1654 int inchannel, outchannel;
1655 pid_t pid;
1656 int vfork_errno;
1657 int forkin, forkout;
1658 bool pty_flag = 0;
1659 char pty_name[PTY_NAME_SIZE];
1660 Lisp_Object lisp_pty_name = Qnil;
1661 sigset_t oldset;
1663 inchannel = outchannel = -1;
1665 if (!NILP (Vprocess_connection_type))
1666 outchannel = inchannel = allocate_pty (pty_name);
1668 if (inchannel >= 0)
1670 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1671 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1672 /* On most USG systems it does not work to open the pty's tty here,
1673 then close it and reopen it in the child. */
1674 /* Don't let this terminal become our controlling terminal
1675 (in case we don't have one). */
1676 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1677 if (forkin < 0)
1678 report_file_error ("Opening pty", Qnil);
1679 p->open_fd[SUBPROCESS_STDIN] = forkin;
1680 #else
1681 forkin = forkout = -1;
1682 #endif /* not USG, or USG_SUBTTY_WORKS */
1683 pty_flag = 1;
1684 lisp_pty_name = build_string (pty_name);
1686 else
1688 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1689 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1690 report_file_error ("Creating pipe", Qnil);
1691 forkin = p->open_fd[SUBPROCESS_STDIN];
1692 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1693 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1694 forkout = p->open_fd[SUBPROCESS_STDOUT];
1697 #ifndef WINDOWSNT
1698 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1699 report_file_error ("Creating pipe", Qnil);
1700 #endif
1702 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1703 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1705 /* Record this as an active process, with its channels. */
1706 chan_process[inchannel] = process;
1707 p->infd = inchannel;
1708 p->outfd = outchannel;
1710 /* Previously we recorded the tty descriptor used in the subprocess.
1711 It was only used for getting the foreground tty process, so now
1712 we just reopen the device (see emacs_get_tty_pgrp) as this is
1713 more portable (see USG_SUBTTY_WORKS above). */
1715 p->pty_flag = pty_flag;
1716 pset_status (p, Qrun);
1718 FD_SET (inchannel, &input_wait_mask);
1719 FD_SET (inchannel, &non_keyboard_wait_mask);
1720 if (inchannel > max_process_desc)
1721 max_process_desc = inchannel;
1723 /* This may signal an error. */
1724 setup_process_coding_systems (process);
1726 block_input ();
1727 block_child_signal (&oldset);
1729 #ifndef WINDOWSNT
1730 /* vfork, and prevent local vars from being clobbered by the vfork. */
1732 Lisp_Object volatile current_dir_volatile = current_dir;
1733 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1734 char **volatile new_argv_volatile = new_argv;
1735 int volatile forkin_volatile = forkin;
1736 int volatile forkout_volatile = forkout;
1737 struct Lisp_Process *p_volatile = p;
1739 pid = vfork ();
1741 current_dir = current_dir_volatile;
1742 lisp_pty_name = lisp_pty_name_volatile;
1743 new_argv = new_argv_volatile;
1744 forkin = forkin_volatile;
1745 forkout = forkout_volatile;
1746 p = p_volatile;
1748 pty_flag = p->pty_flag;
1751 if (pid == 0)
1752 #endif /* not WINDOWSNT */
1754 int xforkin = forkin;
1755 int xforkout = forkout;
1757 /* Make the pty be the controlling terminal of the process. */
1758 #ifdef HAVE_PTYS
1759 /* First, disconnect its current controlling terminal. */
1760 /* We tried doing setsid only if pty_flag, but it caused
1761 process_set_signal to fail on SGI when using a pipe. */
1762 setsid ();
1763 /* Make the pty's terminal the controlling terminal. */
1764 if (pty_flag && xforkin >= 0)
1766 #ifdef TIOCSCTTY
1767 /* We ignore the return value
1768 because faith@cs.unc.edu says that is necessary on Linux. */
1769 ioctl (xforkin, TIOCSCTTY, 0);
1770 #endif
1772 #if defined (LDISC1)
1773 if (pty_flag && xforkin >= 0)
1775 struct termios t;
1776 tcgetattr (xforkin, &t);
1777 t.c_lflag = LDISC1;
1778 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1779 emacs_perror ("create_process/tcsetattr LDISC1");
1781 #else
1782 #if defined (NTTYDISC) && defined (TIOCSETD)
1783 if (pty_flag && xforkin >= 0)
1785 /* Use new line discipline. */
1786 int ldisc = NTTYDISC;
1787 ioctl (xforkin, TIOCSETD, &ldisc);
1789 #endif
1790 #endif
1791 #ifdef TIOCNOTTY
1792 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1793 can do TIOCSPGRP only to the process's controlling tty. */
1794 if (pty_flag)
1796 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1797 I can't test it since I don't have 4.3. */
1798 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1799 if (j >= 0)
1801 ioctl (j, TIOCNOTTY, 0);
1802 emacs_close (j);
1805 #endif /* TIOCNOTTY */
1807 #if !defined (DONT_REOPEN_PTY)
1808 /*** There is a suggestion that this ought to be a
1809 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1810 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1811 that system does seem to need this code, even though
1812 both TIOCSCTTY is defined. */
1813 /* Now close the pty (if we had it open) and reopen it.
1814 This makes the pty the controlling terminal of the subprocess. */
1815 if (pty_flag)
1818 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1819 would work? */
1820 if (xforkin >= 0)
1821 emacs_close (xforkin);
1822 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1824 if (xforkin < 0)
1826 emacs_perror (SSDATA (lisp_pty_name));
1827 _exit (EXIT_CANCELED);
1831 #endif /* not DONT_REOPEN_PTY */
1833 #ifdef SETUP_SLAVE_PTY
1834 if (pty_flag)
1836 SETUP_SLAVE_PTY;
1838 #endif /* SETUP_SLAVE_PTY */
1839 #endif /* HAVE_PTYS */
1841 signal (SIGINT, SIG_DFL);
1842 signal (SIGQUIT, SIG_DFL);
1843 #ifdef SIGPROF
1844 signal (SIGPROF, SIG_DFL);
1845 #endif
1847 /* Emacs ignores SIGPIPE, but the child should not. */
1848 signal (SIGPIPE, SIG_DFL);
1850 /* Stop blocking SIGCHLD in the child. */
1851 unblock_child_signal (&oldset);
1853 if (pty_flag)
1854 child_setup_tty (xforkout);
1855 #ifdef WINDOWSNT
1856 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1857 #else /* not WINDOWSNT */
1858 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1859 #endif /* not WINDOWSNT */
1862 /* Back in the parent process. */
1864 vfork_errno = errno;
1865 p->pid = pid;
1866 if (pid >= 0)
1867 p->alive = 1;
1869 /* Stop blocking in the parent. */
1870 unblock_child_signal (&oldset);
1871 unblock_input ();
1873 if (pid < 0)
1874 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1875 else
1877 /* vfork succeeded. */
1879 /* Close the pipe ends that the child uses, or the child's pty. */
1880 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1881 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1883 #ifdef WINDOWSNT
1884 register_child (pid, inchannel);
1885 #endif /* WINDOWSNT */
1887 pset_tty_name (p, lisp_pty_name);
1889 #ifndef WINDOWSNT
1890 /* Wait for child_setup to complete in case that vfork is
1891 actually defined as fork. The descriptor
1892 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1893 of a pipe is closed at the child side either by close-on-exec
1894 on successful execve or the _exit call in child_setup. */
1896 char dummy;
1898 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1899 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1900 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1902 #endif
1906 static void
1907 create_pty (Lisp_Object process)
1909 struct Lisp_Process *p = XPROCESS (process);
1910 char pty_name[PTY_NAME_SIZE];
1911 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1913 if (pty_fd >= 0)
1915 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1916 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1917 /* On most USG systems it does not work to open the pty's tty here,
1918 then close it and reopen it in the child. */
1919 /* Don't let this terminal become our controlling terminal
1920 (in case we don't have one). */
1921 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1922 if (forkout < 0)
1923 report_file_error ("Opening pty", Qnil);
1924 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1925 #if defined (DONT_REOPEN_PTY)
1926 /* In the case that vfork is defined as fork, the parent process
1927 (Emacs) may send some data before the child process completes
1928 tty options setup. So we setup tty before forking. */
1929 child_setup_tty (forkout);
1930 #endif /* DONT_REOPEN_PTY */
1931 #endif /* not USG, or USG_SUBTTY_WORKS */
1933 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1935 /* Record this as an active process, with its channels.
1936 As a result, child_setup will close Emacs's side of the pipes. */
1937 chan_process[pty_fd] = process;
1938 p->infd = pty_fd;
1939 p->outfd = pty_fd;
1941 /* Previously we recorded the tty descriptor used in the subprocess.
1942 It was only used for getting the foreground tty process, so now
1943 we just reopen the device (see emacs_get_tty_pgrp) as this is
1944 more portable (see USG_SUBTTY_WORKS above). */
1946 p->pty_flag = 1;
1947 pset_status (p, Qrun);
1948 setup_process_coding_systems (process);
1950 FD_SET (pty_fd, &input_wait_mask);
1951 FD_SET (pty_fd, &non_keyboard_wait_mask);
1952 if (pty_fd > max_process_desc)
1953 max_process_desc = pty_fd;
1955 pset_tty_name (p, build_string (pty_name));
1958 p->pid = -2;
1962 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1963 The address family of sa is not included in the result. */
1965 Lisp_Object
1966 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1968 Lisp_Object address;
1969 int i;
1970 unsigned char *cp;
1971 register struct Lisp_Vector *p;
1973 /* Workaround for a bug in getsockname on BSD: Names bound to
1974 sockets in the UNIX domain are inaccessible; getsockname returns
1975 a zero length name. */
1976 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1977 return empty_unibyte_string;
1979 switch (sa->sa_family)
1981 case AF_INET:
1983 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1984 len = sizeof (sin->sin_addr) + 1;
1985 address = Fmake_vector (make_number (len), Qnil);
1986 p = XVECTOR (address);
1987 p->contents[--len] = make_number (ntohs (sin->sin_port));
1988 cp = (unsigned char *) &sin->sin_addr;
1989 break;
1991 #ifdef AF_INET6
1992 case AF_INET6:
1994 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1995 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1996 len = sizeof (sin6->sin6_addr)/2 + 1;
1997 address = Fmake_vector (make_number (len), Qnil);
1998 p = XVECTOR (address);
1999 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2000 for (i = 0; i < len; i++)
2001 p->contents[i] = make_number (ntohs (ip6[i]));
2002 return address;
2004 #endif
2005 #ifdef HAVE_LOCAL_SOCKETS
2006 case AF_LOCAL:
2008 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2009 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2010 /* If the first byte is NUL, the name is a Linux abstract
2011 socket name, and the name can contain embedded NULs. If
2012 it's not, we have a NUL-terminated string. Be careful not
2013 to walk past the end of the object looking for the name
2014 terminator, however. */
2015 if (name_length > 0 && sockun->sun_path[0] != '\0')
2017 const char *terminator
2018 = memchr (sockun->sun_path, '\0', name_length);
2020 if (terminator)
2021 name_length = terminator - (const char *) sockun->sun_path;
2024 return make_unibyte_string (sockun->sun_path, name_length);
2026 #endif
2027 default:
2028 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2029 address = Fcons (make_number (sa->sa_family),
2030 Fmake_vector (make_number (len), Qnil));
2031 p = XVECTOR (XCDR (address));
2032 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2033 break;
2036 i = 0;
2037 while (i < len)
2038 p->contents[i++] = make_number (*cp++);
2040 return address;
2044 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2046 static int
2047 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2049 register struct Lisp_Vector *p;
2051 if (VECTORP (address))
2053 p = XVECTOR (address);
2054 if (p->header.size == 5)
2056 *familyp = AF_INET;
2057 return sizeof (struct sockaddr_in);
2059 #ifdef AF_INET6
2060 else if (p->header.size == 9)
2062 *familyp = AF_INET6;
2063 return sizeof (struct sockaddr_in6);
2065 #endif
2067 #ifdef HAVE_LOCAL_SOCKETS
2068 else if (STRINGP (address))
2070 *familyp = AF_LOCAL;
2071 return sizeof (struct sockaddr_un);
2073 #endif
2074 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2075 && VECTORP (XCDR (address)))
2077 struct sockaddr *sa;
2078 p = XVECTOR (XCDR (address));
2079 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2080 return 0;
2081 *familyp = XINT (XCAR (address));
2082 return p->header.size + sizeof (sa->sa_family);
2084 return 0;
2087 /* Convert an address object (vector or string) to an internal sockaddr.
2089 The address format has been basically validated by
2090 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2091 it could have come from user data. So if FAMILY is not valid,
2092 we return after zeroing *SA. */
2094 static void
2095 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2097 register struct Lisp_Vector *p;
2098 register unsigned char *cp = NULL;
2099 register int i;
2100 EMACS_INT hostport;
2102 memset (sa, 0, len);
2104 if (VECTORP (address))
2106 p = XVECTOR (address);
2107 if (family == AF_INET)
2109 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2110 len = sizeof (sin->sin_addr) + 1;
2111 hostport = XINT (p->contents[--len]);
2112 sin->sin_port = htons (hostport);
2113 cp = (unsigned char *)&sin->sin_addr;
2114 sa->sa_family = family;
2116 #ifdef AF_INET6
2117 else if (family == AF_INET6)
2119 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2120 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2121 len = sizeof (sin6->sin6_addr) + 1;
2122 hostport = XINT (p->contents[--len]);
2123 sin6->sin6_port = htons (hostport);
2124 for (i = 0; i < len; i++)
2125 if (INTEGERP (p->contents[i]))
2127 int j = XFASTINT (p->contents[i]) & 0xffff;
2128 ip6[i] = ntohs (j);
2130 sa->sa_family = family;
2131 return;
2133 #endif
2134 else
2135 return;
2137 else if (STRINGP (address))
2139 #ifdef HAVE_LOCAL_SOCKETS
2140 if (family == AF_LOCAL)
2142 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2143 cp = SDATA (address);
2144 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2145 sockun->sun_path[i] = *cp++;
2146 sa->sa_family = family;
2148 #endif
2149 return;
2151 else
2153 p = XVECTOR (XCDR (address));
2154 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2157 for (i = 0; i < len; i++)
2158 if (INTEGERP (p->contents[i]))
2159 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2162 #ifdef DATAGRAM_SOCKETS
2163 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2164 1, 1, 0,
2165 doc: /* Get the current datagram address associated with PROCESS. */)
2166 (Lisp_Object process)
2168 int channel;
2170 CHECK_PROCESS (process);
2172 if (!DATAGRAM_CONN_P (process))
2173 return Qnil;
2175 channel = XPROCESS (process)->infd;
2176 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2177 datagram_address[channel].len);
2180 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2181 2, 2, 0,
2182 doc: /* Set the datagram address for PROCESS to ADDRESS.
2183 Returns nil upon error setting address, ADDRESS otherwise. */)
2184 (Lisp_Object process, Lisp_Object address)
2186 int channel;
2187 int family, len;
2189 CHECK_PROCESS (process);
2191 if (!DATAGRAM_CONN_P (process))
2192 return Qnil;
2194 channel = XPROCESS (process)->infd;
2196 len = get_lisp_to_sockaddr_size (address, &family);
2197 if (len == 0 || datagram_address[channel].len != len)
2198 return Qnil;
2199 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2200 return address;
2202 #endif
2205 static const struct socket_options {
2206 /* The name of this option. Should be lowercase version of option
2207 name without SO_ prefix. */
2208 const char *name;
2209 /* Option level SOL_... */
2210 int optlevel;
2211 /* Option number SO_... */
2212 int optnum;
2213 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2214 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2215 } socket_options[] =
2217 #ifdef SO_BINDTODEVICE
2218 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2219 #endif
2220 #ifdef SO_BROADCAST
2221 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2222 #endif
2223 #ifdef SO_DONTROUTE
2224 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2225 #endif
2226 #ifdef SO_KEEPALIVE
2227 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2228 #endif
2229 #ifdef SO_LINGER
2230 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2231 #endif
2232 #ifdef SO_OOBINLINE
2233 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2234 #endif
2235 #ifdef SO_PRIORITY
2236 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2237 #endif
2238 #ifdef SO_REUSEADDR
2239 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2240 #endif
2241 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2244 /* Set option OPT to value VAL on socket S.
2246 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2247 Signals an error if setting a known option fails.
2250 static int
2251 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2253 char *name;
2254 const struct socket_options *sopt;
2255 int ret = 0;
2257 CHECK_SYMBOL (opt);
2259 name = SSDATA (SYMBOL_NAME (opt));
2260 for (sopt = socket_options; sopt->name; sopt++)
2261 if (strcmp (name, sopt->name) == 0)
2262 break;
2264 switch (sopt->opttype)
2266 case SOPT_BOOL:
2268 int optval;
2269 optval = NILP (val) ? 0 : 1;
2270 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2271 &optval, sizeof (optval));
2272 break;
2275 case SOPT_INT:
2277 int optval;
2278 if (TYPE_RANGED_INTEGERP (int, val))
2279 optval = XINT (val);
2280 else
2281 error ("Bad option value for %s", name);
2282 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2283 &optval, sizeof (optval));
2284 break;
2287 #ifdef SO_BINDTODEVICE
2288 case SOPT_IFNAME:
2290 char devname[IFNAMSIZ+1];
2292 /* This is broken, at least in the Linux 2.4 kernel.
2293 To unbind, the arg must be a zero integer, not the empty string.
2294 This should work on all systems. KFS. 2003-09-23. */
2295 memset (devname, 0, sizeof devname);
2296 if (STRINGP (val))
2298 char *arg = SSDATA (val);
2299 int len = min (strlen (arg), IFNAMSIZ);
2300 memcpy (devname, arg, len);
2302 else if (!NILP (val))
2303 error ("Bad option value for %s", name);
2304 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2305 devname, IFNAMSIZ);
2306 break;
2308 #endif
2310 #ifdef SO_LINGER
2311 case SOPT_LINGER:
2313 struct linger linger;
2315 linger.l_onoff = 1;
2316 linger.l_linger = 0;
2317 if (TYPE_RANGED_INTEGERP (int, val))
2318 linger.l_linger = XINT (val);
2319 else
2320 linger.l_onoff = NILP (val) ? 0 : 1;
2321 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2322 &linger, sizeof (linger));
2323 break;
2325 #endif
2327 default:
2328 return 0;
2331 if (ret < 0)
2333 int setsockopt_errno = errno;
2334 report_file_errno ("Cannot set network option", list2 (opt, val),
2335 setsockopt_errno);
2338 return (1 << sopt->optbit);
2342 DEFUN ("set-network-process-option",
2343 Fset_network_process_option, Sset_network_process_option,
2344 3, 4, 0,
2345 doc: /* For network process PROCESS set option OPTION to value VALUE.
2346 See `make-network-process' for a list of options and values.
2347 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2348 OPTION is not a supported option, return nil instead; otherwise return t. */)
2349 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2351 int s;
2352 struct Lisp_Process *p;
2354 CHECK_PROCESS (process);
2355 p = XPROCESS (process);
2356 if (!NETCONN1_P (p))
2357 error ("Process is not a network process");
2359 s = p->infd;
2360 if (s < 0)
2361 error ("Process is not running");
2363 if (set_socket_option (s, option, value))
2365 pset_childp (p, Fplist_put (p->childp, option, value));
2366 return Qt;
2369 if (NILP (no_error))
2370 error ("Unknown or unsupported option");
2372 return Qnil;
2376 DEFUN ("serial-process-configure",
2377 Fserial_process_configure,
2378 Sserial_process_configure,
2379 0, MANY, 0,
2380 doc: /* Configure speed, bytesize, etc. of a serial process.
2382 Arguments are specified as keyword/argument pairs. Attributes that
2383 are not given are re-initialized from the process's current
2384 configuration (available via the function `process-contact') or set to
2385 reasonable default values. The following arguments are defined:
2387 :process PROCESS
2388 :name NAME
2389 :buffer BUFFER
2390 :port PORT
2391 -- Any of these arguments can be given to identify the process that is
2392 to be configured. If none of these arguments is given, the current
2393 buffer's process is used.
2395 :speed SPEED -- SPEED is the speed of the serial port in bits per
2396 second, also called baud rate. Any value can be given for SPEED, but
2397 most serial ports work only at a few defined values between 1200 and
2398 115200, with 9600 being the most common value. If SPEED is nil, the
2399 serial port is not configured any further, i.e., all other arguments
2400 are ignored. This may be useful for special serial ports such as
2401 Bluetooth-to-serial converters which can only be configured through AT
2402 commands. A value of nil for SPEED can be used only when passed
2403 through `make-serial-process' or `serial-term'.
2405 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2406 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2408 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2409 `odd' (use odd parity), or the symbol `even' (use even parity). If
2410 PARITY is not given, no parity is used.
2412 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2413 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2414 is not given or nil, 1 stopbit is used.
2416 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2417 flowcontrol to be used, which is either nil (don't use flowcontrol),
2418 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2419 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2420 flowcontrol is used.
2422 `serial-process-configure' is called by `make-serial-process' for the
2423 initial configuration of the serial port.
2425 Examples:
2427 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2429 \(serial-process-configure
2430 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2432 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2434 usage: (serial-process-configure &rest ARGS) */)
2435 (ptrdiff_t nargs, Lisp_Object *args)
2437 struct Lisp_Process *p;
2438 Lisp_Object contact = Qnil;
2439 Lisp_Object proc = Qnil;
2440 struct gcpro gcpro1;
2442 contact = Flist (nargs, args);
2443 GCPRO1 (contact);
2445 proc = Fplist_get (contact, QCprocess);
2446 if (NILP (proc))
2447 proc = Fplist_get (contact, QCname);
2448 if (NILP (proc))
2449 proc = Fplist_get (contact, QCbuffer);
2450 if (NILP (proc))
2451 proc = Fplist_get (contact, QCport);
2452 proc = get_process (proc);
2453 p = XPROCESS (proc);
2454 if (!EQ (p->type, Qserial))
2455 error ("Not a serial process");
2457 if (NILP (Fplist_get (p->childp, QCspeed)))
2459 UNGCPRO;
2460 return Qnil;
2463 serial_configure (p, contact);
2465 UNGCPRO;
2466 return Qnil;
2469 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2470 0, MANY, 0,
2471 doc: /* Create and return a serial port process.
2473 In Emacs, serial port connections are represented by process objects,
2474 so input and output work as for subprocesses, and `delete-process'
2475 closes a serial port connection. However, a serial process has no
2476 process id, it cannot be signaled, and the status codes are different
2477 from normal processes.
2479 `make-serial-process' creates a process and a buffer, on which you
2480 probably want to use `process-send-string'. Try \\[serial-term] for
2481 an interactive terminal. See below for examples.
2483 Arguments are specified as keyword/argument pairs. The following
2484 arguments are defined:
2486 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2487 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2488 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2489 the backslashes in strings).
2491 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2492 which this function calls.
2494 :name NAME -- NAME is the name of the process. If NAME is not given,
2495 the value of PORT is used.
2497 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2498 with the process. Process output goes at the end of that buffer,
2499 unless you specify an output stream or filter function to handle the
2500 output. If BUFFER is not given, the value of NAME is used.
2502 :coding CODING -- If CODING is a symbol, it specifies the coding
2503 system used for both reading and writing for this process. If CODING
2504 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2505 ENCODING is used for writing.
2507 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2508 the process is running. If BOOL is not given, query before exiting.
2510 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2511 In the stopped state, a serial process does not accept incoming data,
2512 but you can send outgoing data. The stopped state is cleared by
2513 `continue-process' and set by `stop-process'.
2515 :filter FILTER -- Install FILTER as the process filter.
2517 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2519 :plist PLIST -- Install PLIST as the initial plist of the process.
2521 :bytesize
2522 :parity
2523 :stopbits
2524 :flowcontrol
2525 -- This function calls `serial-process-configure' to handle these
2526 arguments.
2528 The original argument list, possibly modified by later configuration,
2529 is available via the function `process-contact'.
2531 Examples:
2533 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2535 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2537 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2539 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2541 usage: (make-serial-process &rest ARGS) */)
2542 (ptrdiff_t nargs, Lisp_Object *args)
2544 int fd = -1;
2545 Lisp_Object proc, contact, port;
2546 struct Lisp_Process *p;
2547 struct gcpro gcpro1;
2548 Lisp_Object name, buffer;
2549 Lisp_Object tem, val;
2550 ptrdiff_t specpdl_count;
2552 if (nargs == 0)
2553 return Qnil;
2555 contact = Flist (nargs, args);
2556 GCPRO1 (contact);
2558 port = Fplist_get (contact, QCport);
2559 if (NILP (port))
2560 error ("No port specified");
2561 CHECK_STRING (port);
2563 if (NILP (Fplist_member (contact, QCspeed)))
2564 error (":speed not specified");
2565 if (!NILP (Fplist_get (contact, QCspeed)))
2566 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2568 name = Fplist_get (contact, QCname);
2569 if (NILP (name))
2570 name = port;
2571 CHECK_STRING (name);
2572 proc = make_process (name);
2573 specpdl_count = SPECPDL_INDEX ();
2574 record_unwind_protect (remove_process, proc);
2575 p = XPROCESS (proc);
2577 fd = serial_open (port);
2578 p->open_fd[SUBPROCESS_STDIN] = fd;
2579 p->infd = fd;
2580 p->outfd = fd;
2581 if (fd > max_process_desc)
2582 max_process_desc = fd;
2583 chan_process[fd] = proc;
2585 buffer = Fplist_get (contact, QCbuffer);
2586 if (NILP (buffer))
2587 buffer = name;
2588 buffer = Fget_buffer_create (buffer);
2589 pset_buffer (p, buffer);
2591 pset_childp (p, contact);
2592 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2593 pset_type (p, Qserial);
2594 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2595 pset_filter (p, Fplist_get (contact, QCfilter));
2596 pset_log (p, Qnil);
2597 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2598 p->kill_without_query = 1;
2599 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2600 pset_command (p, Qt);
2601 eassert (! p->pty_flag);
2603 if (!EQ (p->command, Qt))
2605 FD_SET (fd, &input_wait_mask);
2606 FD_SET (fd, &non_keyboard_wait_mask);
2609 if (BUFFERP (buffer))
2611 set_marker_both (p->mark, buffer,
2612 BUF_ZV (XBUFFER (buffer)),
2613 BUF_ZV_BYTE (XBUFFER (buffer)));
2616 tem = Fplist_member (contact, QCcoding);
2617 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2618 tem = Qnil;
2620 val = Qnil;
2621 if (!NILP (tem))
2623 val = XCAR (XCDR (tem));
2624 if (CONSP (val))
2625 val = XCAR (val);
2627 else if (!NILP (Vcoding_system_for_read))
2628 val = Vcoding_system_for_read;
2629 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2630 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2631 val = Qnil;
2632 pset_decode_coding_system (p, val);
2634 val = Qnil;
2635 if (!NILP (tem))
2637 val = XCAR (XCDR (tem));
2638 if (CONSP (val))
2639 val = XCDR (val);
2641 else if (!NILP (Vcoding_system_for_write))
2642 val = Vcoding_system_for_write;
2643 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2644 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2645 val = Qnil;
2646 pset_encode_coding_system (p, val);
2648 setup_process_coding_systems (proc);
2649 pset_decoding_buf (p, empty_unibyte_string);
2650 p->decoding_carryover = 0;
2651 pset_encoding_buf (p, empty_unibyte_string);
2652 p->inherit_coding_system_flag
2653 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2655 Fserial_process_configure (nargs, args);
2657 specpdl_ptr = specpdl + specpdl_count;
2659 UNGCPRO;
2660 return proc;
2663 /* Create a network stream/datagram client/server process. Treated
2664 exactly like a normal process when reading and writing. Primary
2665 differences are in status display and process deletion. A network
2666 connection has no PID; you cannot signal it. All you can do is
2667 stop/continue it and deactivate/close it via delete-process */
2669 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2670 0, MANY, 0,
2671 doc: /* Create and return a network server or client process.
2673 In Emacs, network connections are represented by process objects, so
2674 input and output work as for subprocesses and `delete-process' closes
2675 a network connection. However, a network process has no process id,
2676 it cannot be signaled, and the status codes are different from normal
2677 processes.
2679 Arguments are specified as keyword/argument pairs. The following
2680 arguments are defined:
2682 :name NAME -- NAME is name for process. It is modified if necessary
2683 to make it unique.
2685 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2686 with the process. Process output goes at end of that buffer, unless
2687 you specify an output stream or filter function to handle the output.
2688 BUFFER may be also nil, meaning that this process is not associated
2689 with any buffer.
2691 :host HOST -- HOST is name of the host to connect to, or its IP
2692 address. The symbol `local' specifies the local host. If specified
2693 for a server process, it must be a valid name or address for the local
2694 host, and only clients connecting to that address will be accepted.
2696 :service SERVICE -- SERVICE is name of the service desired, or an
2697 integer specifying a port number to connect to. If SERVICE is t,
2698 a random port number is selected for the server. (If Emacs was
2699 compiled with getaddrinfo, a port number can also be specified as a
2700 string, e.g. "80", as well as an integer. This is not portable.)
2702 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2703 stream type connection, `datagram' creates a datagram type connection,
2704 `seqpacket' creates a reliable datagram connection.
2706 :family FAMILY -- FAMILY is the address (and protocol) family for the
2707 service specified by HOST and SERVICE. The default (nil) is to use
2708 whatever address family (IPv4 or IPv6) that is defined for the host
2709 and port number specified by HOST and SERVICE. Other address families
2710 supported are:
2711 local -- for a local (i.e. UNIX) address specified by SERVICE.
2712 ipv4 -- use IPv4 address family only.
2713 ipv6 -- use IPv6 address family only.
2715 :local ADDRESS -- ADDRESS is the local address used for the connection.
2716 This parameter is ignored when opening a client process. When specified
2717 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2719 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2720 connection. This parameter is ignored when opening a stream server
2721 process. For a datagram server process, it specifies the initial
2722 setting of the remote datagram address. When specified for a client
2723 process, the FAMILY, HOST, and SERVICE args are ignored.
2725 The format of ADDRESS depends on the address family:
2726 - An IPv4 address is represented as an vector of integers [A B C D P]
2727 corresponding to numeric IP address A.B.C.D and port number P.
2728 - A local address is represented as a string with the address in the
2729 local address space.
2730 - An "unsupported family" address is represented by a cons (F . AV)
2731 where F is the family number and AV is a vector containing the socket
2732 address data with one element per address data byte. Do not rely on
2733 this format in portable code, as it may depend on implementation
2734 defined constants, data sizes, and data structure alignment.
2736 :coding CODING -- If CODING is a symbol, it specifies the coding
2737 system used for both reading and writing for this process. If CODING
2738 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2739 ENCODING is used for writing.
2741 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2742 return without waiting for the connection to complete; instead, the
2743 sentinel function will be called with second arg matching "open" (if
2744 successful) or "failed" when the connect completes. Default is to use
2745 a blocking connect (i.e. wait) for stream type connections.
2747 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2748 running when Emacs is exited.
2750 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2751 In the stopped state, a server process does not accept new
2752 connections, and a client process does not handle incoming traffic.
2753 The stopped state is cleared by `continue-process' and set by
2754 `stop-process'.
2756 :filter FILTER -- Install FILTER as the process filter.
2758 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2759 process filter are multibyte, otherwise they are unibyte.
2760 If this keyword is not specified, the strings are multibyte if
2761 the default value of `enable-multibyte-characters' is non-nil.
2763 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2765 :log LOG -- Install LOG as the server process log function. This
2766 function is called when the server accepts a network connection from a
2767 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2768 is the server process, CLIENT is the new process for the connection,
2769 and MESSAGE is a string.
2771 :plist PLIST -- Install PLIST as the new process's initial plist.
2773 :server QLEN -- if QLEN is non-nil, create a server process for the
2774 specified FAMILY, SERVICE, and connection type (stream or datagram).
2775 If QLEN is an integer, it is used as the max. length of the server's
2776 pending connection queue (also known as the backlog); the default
2777 queue length is 5. Default is to create a client process.
2779 The following network options can be specified for this connection:
2781 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2782 :dontroute BOOL -- Only send to directly connected hosts.
2783 :keepalive BOOL -- Send keep-alive messages on network stream.
2784 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2785 :oobinline BOOL -- Place out-of-band data in receive data stream.
2786 :priority INT -- Set protocol defined priority for sent packets.
2787 :reuseaddr BOOL -- Allow reusing a recently used local address
2788 (this is allowed by default for a server process).
2789 :bindtodevice NAME -- bind to interface NAME. Using this may require
2790 special privileges on some systems.
2792 Consult the relevant system programmer's manual pages for more
2793 information on using these options.
2796 A server process will listen for and accept connections from clients.
2797 When a client connection is accepted, a new network process is created
2798 for the connection with the following parameters:
2800 - The client's process name is constructed by concatenating the server
2801 process's NAME and a client identification string.
2802 - If the FILTER argument is non-nil, the client process will not get a
2803 separate process buffer; otherwise, the client's process buffer is a newly
2804 created buffer named after the server process's BUFFER name or process
2805 NAME concatenated with the client identification string.
2806 - The connection type and the process filter and sentinel parameters are
2807 inherited from the server process's TYPE, FILTER and SENTINEL.
2808 - The client process's contact info is set according to the client's
2809 addressing information (typically an IP address and a port number).
2810 - The client process's plist is initialized from the server's plist.
2812 Notice that the FILTER and SENTINEL args are never used directly by
2813 the server process. Also, the BUFFER argument is not used directly by
2814 the server process, but via the optional :log function, accepted (and
2815 failed) connections may be logged in the server process's buffer.
2817 The original argument list, modified with the actual connection
2818 information, is available via the `process-contact' function.
2820 usage: (make-network-process &rest ARGS) */)
2821 (ptrdiff_t nargs, Lisp_Object *args)
2823 Lisp_Object proc;
2824 Lisp_Object contact;
2825 struct Lisp_Process *p;
2826 #ifdef HAVE_GETADDRINFO
2827 struct addrinfo ai, *res, *lres;
2828 struct addrinfo hints;
2829 const char *portstring;
2830 char portbuf[128];
2831 #else /* HAVE_GETADDRINFO */
2832 struct _emacs_addrinfo
2834 int ai_family;
2835 int ai_socktype;
2836 int ai_protocol;
2837 int ai_addrlen;
2838 struct sockaddr *ai_addr;
2839 struct _emacs_addrinfo *ai_next;
2840 } ai, *res, *lres;
2841 #endif /* HAVE_GETADDRINFO */
2842 struct sockaddr_in address_in;
2843 #ifdef HAVE_LOCAL_SOCKETS
2844 struct sockaddr_un address_un;
2845 #endif
2846 int port;
2847 int ret = 0;
2848 int xerrno = 0;
2849 int s = -1, outch, inch;
2850 struct gcpro gcpro1;
2851 ptrdiff_t count = SPECPDL_INDEX ();
2852 ptrdiff_t count1;
2853 Lisp_Object colon_address; /* Either QClocal or QCremote. */
2854 Lisp_Object tem;
2855 Lisp_Object name, buffer, host, service, address;
2856 Lisp_Object filter, sentinel;
2857 bool is_non_blocking_client = 0;
2858 bool is_server = 0;
2859 int backlog = 5;
2860 int socktype;
2861 int family = -1;
2863 if (nargs == 0)
2864 return Qnil;
2866 /* Save arguments for process-contact and clone-process. */
2867 contact = Flist (nargs, args);
2868 GCPRO1 (contact);
2870 #ifdef WINDOWSNT
2871 /* Ensure socket support is loaded if available. */
2872 init_winsock (TRUE);
2873 #endif
2875 /* :type TYPE (nil: stream, datagram */
2876 tem = Fplist_get (contact, QCtype);
2877 if (NILP (tem))
2878 socktype = SOCK_STREAM;
2879 #ifdef DATAGRAM_SOCKETS
2880 else if (EQ (tem, Qdatagram))
2881 socktype = SOCK_DGRAM;
2882 #endif
2883 #ifdef HAVE_SEQPACKET
2884 else if (EQ (tem, Qseqpacket))
2885 socktype = SOCK_SEQPACKET;
2886 #endif
2887 else
2888 error ("Unsupported connection type");
2890 /* :server BOOL */
2891 tem = Fplist_get (contact, QCserver);
2892 if (!NILP (tem))
2894 /* Don't support network sockets when non-blocking mode is
2895 not available, since a blocked Emacs is not useful. */
2896 is_server = 1;
2897 if (TYPE_RANGED_INTEGERP (int, tem))
2898 backlog = XINT (tem);
2901 /* Make colon_address an alias for :local (server) or :remote (client). */
2902 colon_address = is_server ? QClocal : QCremote;
2904 /* :nowait BOOL */
2905 if (!is_server && socktype != SOCK_DGRAM
2906 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2908 #ifndef NON_BLOCKING_CONNECT
2909 error ("Non-blocking connect not supported");
2910 #else
2911 is_non_blocking_client = 1;
2912 #endif
2915 name = Fplist_get (contact, QCname);
2916 buffer = Fplist_get (contact, QCbuffer);
2917 filter = Fplist_get (contact, QCfilter);
2918 sentinel = Fplist_get (contact, QCsentinel);
2920 CHECK_STRING (name);
2922 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2923 ai.ai_socktype = socktype;
2924 ai.ai_protocol = 0;
2925 ai.ai_next = NULL;
2926 res = &ai;
2928 /* :local ADDRESS or :remote ADDRESS */
2929 address = Fplist_get (contact, colon_address);
2930 if (!NILP (address))
2932 host = service = Qnil;
2934 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2935 error ("Malformed :address");
2936 ai.ai_family = family;
2937 ai.ai_addr = alloca (ai.ai_addrlen);
2938 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2939 goto open_socket;
2942 /* :family FAMILY -- nil (for Inet), local, or integer. */
2943 tem = Fplist_get (contact, QCfamily);
2944 if (NILP (tem))
2946 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2947 family = AF_UNSPEC;
2948 #else
2949 family = AF_INET;
2950 #endif
2952 #ifdef HAVE_LOCAL_SOCKETS
2953 else if (EQ (tem, Qlocal))
2954 family = AF_LOCAL;
2955 #endif
2956 #ifdef AF_INET6
2957 else if (EQ (tem, Qipv6))
2958 family = AF_INET6;
2959 #endif
2960 else if (EQ (tem, Qipv4))
2961 family = AF_INET;
2962 else if (TYPE_RANGED_INTEGERP (int, tem))
2963 family = XINT (tem);
2964 else
2965 error ("Unknown address family");
2967 ai.ai_family = family;
2969 /* :service SERVICE -- string, integer (port number), or t (random port). */
2970 service = Fplist_get (contact, QCservice);
2972 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2973 host = Fplist_get (contact, QChost);
2974 if (!NILP (host))
2976 if (EQ (host, Qlocal))
2977 /* Depending on setup, "localhost" may map to different IPv4 and/or
2978 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2979 host = build_string ("127.0.0.1");
2980 CHECK_STRING (host);
2983 #ifdef HAVE_LOCAL_SOCKETS
2984 if (family == AF_LOCAL)
2986 if (!NILP (host))
2988 message (":family local ignores the :host \"%s\" property",
2989 SDATA (host));
2990 contact = Fplist_put (contact, QChost, Qnil);
2991 host = Qnil;
2993 CHECK_STRING (service);
2994 memset (&address_un, 0, sizeof address_un);
2995 address_un.sun_family = AF_LOCAL;
2996 if (sizeof address_un.sun_path <= SBYTES (service))
2997 error ("Service name too long");
2998 lispstpcpy (address_un.sun_path, service);
2999 ai.ai_addr = (struct sockaddr *) &address_un;
3000 ai.ai_addrlen = sizeof address_un;
3001 goto open_socket;
3003 #endif
3005 /* Slow down polling to every ten seconds.
3006 Some kernels have a bug which causes retrying connect to fail
3007 after a connect. Polling can interfere with gethostbyname too. */
3008 #ifdef POLL_FOR_INPUT
3009 if (socktype != SOCK_DGRAM)
3011 record_unwind_protect_void (run_all_atimers);
3012 bind_polling_period (10);
3014 #endif
3016 #ifdef HAVE_GETADDRINFO
3017 /* If we have a host, use getaddrinfo to resolve both host and service.
3018 Otherwise, use getservbyname to lookup the service. */
3019 if (!NILP (host))
3022 /* SERVICE can either be a string or int.
3023 Convert to a C string for later use by getaddrinfo. */
3024 if (EQ (service, Qt))
3025 portstring = "0";
3026 else if (INTEGERP (service))
3028 sprintf (portbuf, "%"pI"d", XINT (service));
3029 portstring = portbuf;
3031 else
3033 CHECK_STRING (service);
3034 portstring = SSDATA (service);
3037 immediate_quit = 1;
3038 QUIT;
3039 memset (&hints, 0, sizeof (hints));
3040 hints.ai_flags = 0;
3041 hints.ai_family = family;
3042 hints.ai_socktype = socktype;
3043 hints.ai_protocol = 0;
3045 #ifdef HAVE_RES_INIT
3046 res_init ();
3047 #endif
3049 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3050 if (ret)
3051 #ifdef HAVE_GAI_STRERROR
3052 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3053 #else
3054 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3055 #endif
3056 immediate_quit = 0;
3058 goto open_socket;
3060 #endif /* HAVE_GETADDRINFO */
3062 /* We end up here if getaddrinfo is not defined, or in case no hostname
3063 has been specified (e.g. for a local server process). */
3065 if (EQ (service, Qt))
3066 port = 0;
3067 else if (INTEGERP (service))
3068 port = htons ((unsigned short) XINT (service));
3069 else
3071 struct servent *svc_info;
3072 CHECK_STRING (service);
3073 svc_info = getservbyname (SSDATA (service),
3074 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3075 if (svc_info == 0)
3076 error ("Unknown service: %s", SDATA (service));
3077 port = svc_info->s_port;
3080 memset (&address_in, 0, sizeof address_in);
3081 address_in.sin_family = family;
3082 address_in.sin_addr.s_addr = INADDR_ANY;
3083 address_in.sin_port = port;
3085 #ifndef HAVE_GETADDRINFO
3086 if (!NILP (host))
3088 struct hostent *host_info_ptr;
3090 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3091 as it may `hang' Emacs for a very long time. */
3092 immediate_quit = 1;
3093 QUIT;
3095 #ifdef HAVE_RES_INIT
3096 res_init ();
3097 #endif
3099 host_info_ptr = gethostbyname (SDATA (host));
3100 immediate_quit = 0;
3102 if (host_info_ptr)
3104 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3105 host_info_ptr->h_length);
3106 family = host_info_ptr->h_addrtype;
3107 address_in.sin_family = family;
3109 else
3110 /* Attempt to interpret host as numeric inet address */
3112 unsigned long numeric_addr;
3113 numeric_addr = inet_addr (SSDATA (host));
3114 if (numeric_addr == -1)
3115 error ("Unknown host \"%s\"", SDATA (host));
3117 memcpy (&address_in.sin_addr, &numeric_addr,
3118 sizeof (address_in.sin_addr));
3122 #endif /* not HAVE_GETADDRINFO */
3124 ai.ai_family = family;
3125 ai.ai_addr = (struct sockaddr *) &address_in;
3126 ai.ai_addrlen = sizeof address_in;
3128 open_socket:
3130 /* Do this in case we never enter the for-loop below. */
3131 count1 = SPECPDL_INDEX ();
3132 s = -1;
3134 for (lres = res; lres; lres = lres->ai_next)
3136 ptrdiff_t optn;
3137 int optbits;
3139 #ifdef WINDOWSNT
3140 retry_connect:
3141 #endif
3143 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3144 lres->ai_protocol);
3145 if (s < 0)
3147 xerrno = errno;
3148 continue;
3151 #ifdef DATAGRAM_SOCKETS
3152 if (!is_server && socktype == SOCK_DGRAM)
3153 break;
3154 #endif /* DATAGRAM_SOCKETS */
3156 #ifdef NON_BLOCKING_CONNECT
3157 if (is_non_blocking_client)
3159 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3160 if (ret < 0)
3162 xerrno = errno;
3163 emacs_close (s);
3164 s = -1;
3165 continue;
3168 #endif
3170 /* Make us close S if quit. */
3171 record_unwind_protect_int (close_file_unwind, s);
3173 /* Parse network options in the arg list.
3174 We simply ignore anything which isn't a known option (including other keywords).
3175 An error is signaled if setting a known option fails. */
3176 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3177 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3179 if (is_server)
3181 /* Configure as a server socket. */
3183 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3184 explicit :reuseaddr key to override this. */
3185 #ifdef HAVE_LOCAL_SOCKETS
3186 if (family != AF_LOCAL)
3187 #endif
3188 if (!(optbits & (1 << OPIX_REUSEADDR)))
3190 int optval = 1;
3191 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3192 report_file_error ("Cannot set reuse option on server socket", Qnil);
3195 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3196 report_file_error ("Cannot bind server socket", Qnil);
3198 #ifdef HAVE_GETSOCKNAME
3199 if (EQ (service, Qt))
3201 struct sockaddr_in sa1;
3202 socklen_t len1 = sizeof (sa1);
3203 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3205 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3206 service = make_number (ntohs (sa1.sin_port));
3207 contact = Fplist_put (contact, QCservice, service);
3210 #endif
3212 if (socktype != SOCK_DGRAM && listen (s, backlog))
3213 report_file_error ("Cannot listen on server socket", Qnil);
3215 break;
3218 immediate_quit = 1;
3219 QUIT;
3221 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3222 xerrno = errno;
3224 if (ret == 0 || xerrno == EISCONN)
3226 /* The unwind-protect will be discarded afterwards.
3227 Likewise for immediate_quit. */
3228 break;
3231 #ifdef NON_BLOCKING_CONNECT
3232 #ifdef EINPROGRESS
3233 if (is_non_blocking_client && xerrno == EINPROGRESS)
3234 break;
3235 #else
3236 #ifdef EWOULDBLOCK
3237 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3238 break;
3239 #endif
3240 #endif
3241 #endif
3243 #ifndef WINDOWSNT
3244 if (xerrno == EINTR)
3246 /* Unlike most other syscalls connect() cannot be called
3247 again. (That would return EALREADY.) The proper way to
3248 wait for completion is pselect(). */
3249 int sc;
3250 socklen_t len;
3251 fd_set fdset;
3252 retry_select:
3253 FD_ZERO (&fdset);
3254 FD_SET (s, &fdset);
3255 QUIT;
3256 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3257 if (sc == -1)
3259 if (errno == EINTR)
3260 goto retry_select;
3261 else
3262 report_file_error ("Failed select", Qnil);
3264 eassert (sc > 0);
3266 len = sizeof xerrno;
3267 eassert (FD_ISSET (s, &fdset));
3268 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3269 report_file_error ("Failed getsockopt", Qnil);
3270 if (xerrno)
3271 report_file_errno ("Failed connect", Qnil, xerrno);
3272 break;
3274 #endif /* !WINDOWSNT */
3276 immediate_quit = 0;
3278 /* Discard the unwind protect closing S. */
3279 specpdl_ptr = specpdl + count1;
3280 emacs_close (s);
3281 s = -1;
3283 #ifdef WINDOWSNT
3284 if (xerrno == EINTR)
3285 goto retry_connect;
3286 #endif
3289 if (s >= 0)
3291 #ifdef DATAGRAM_SOCKETS
3292 if (socktype == SOCK_DGRAM)
3294 if (datagram_address[s].sa)
3295 emacs_abort ();
3296 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3297 datagram_address[s].len = lres->ai_addrlen;
3298 if (is_server)
3300 Lisp_Object remote;
3301 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3302 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3304 int rfamily, rlen;
3305 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3306 if (rlen != 0 && rfamily == lres->ai_family
3307 && rlen == lres->ai_addrlen)
3308 conv_lisp_to_sockaddr (rfamily, remote,
3309 datagram_address[s].sa, rlen);
3312 else
3313 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3315 #endif
3316 contact = Fplist_put (contact, colon_address,
3317 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3318 #ifdef HAVE_GETSOCKNAME
3319 if (!is_server)
3321 struct sockaddr_in sa1;
3322 socklen_t len1 = sizeof (sa1);
3323 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3324 contact = Fplist_put (contact, QClocal,
3325 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3327 #endif
3330 immediate_quit = 0;
3332 #ifdef HAVE_GETADDRINFO
3333 if (res != &ai)
3335 block_input ();
3336 freeaddrinfo (res);
3337 unblock_input ();
3339 #endif
3341 if (s < 0)
3343 /* If non-blocking got this far - and failed - assume non-blocking is
3344 not supported after all. This is probably a wrong assumption, but
3345 the normal blocking calls to open-network-stream handles this error
3346 better. */
3347 if (is_non_blocking_client)
3348 return Qnil;
3350 report_file_errno ((is_server
3351 ? "make server process failed"
3352 : "make client process failed"),
3353 contact, xerrno);
3356 inch = s;
3357 outch = s;
3359 if (!NILP (buffer))
3360 buffer = Fget_buffer_create (buffer);
3361 proc = make_process (name);
3363 chan_process[inch] = proc;
3365 fcntl (inch, F_SETFL, O_NONBLOCK);
3367 p = XPROCESS (proc);
3369 pset_childp (p, contact);
3370 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3371 pset_type (p, Qnetwork);
3373 pset_buffer (p, buffer);
3374 pset_sentinel (p, sentinel);
3375 pset_filter (p, filter);
3376 pset_log (p, Fplist_get (contact, QClog));
3377 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3378 p->kill_without_query = 1;
3379 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3380 pset_command (p, Qt);
3381 p->pid = 0;
3383 p->open_fd[SUBPROCESS_STDIN] = inch;
3384 p->infd = inch;
3385 p->outfd = outch;
3387 /* Discard the unwind protect for closing S, if any. */
3388 specpdl_ptr = specpdl + count1;
3390 /* Unwind bind_polling_period and request_sigio. */
3391 unbind_to (count, Qnil);
3393 if (is_server && socktype != SOCK_DGRAM)
3394 pset_status (p, Qlisten);
3396 /* Make the process marker point into the process buffer (if any). */
3397 if (BUFFERP (buffer))
3398 set_marker_both (p->mark, buffer,
3399 BUF_ZV (XBUFFER (buffer)),
3400 BUF_ZV_BYTE (XBUFFER (buffer)));
3402 #ifdef NON_BLOCKING_CONNECT
3403 if (is_non_blocking_client)
3405 /* We may get here if connect did succeed immediately. However,
3406 in that case, we still need to signal this like a non-blocking
3407 connection. */
3408 pset_status (p, Qconnect);
3409 if (!FD_ISSET (inch, &connect_wait_mask))
3411 FD_SET (inch, &connect_wait_mask);
3412 FD_SET (inch, &write_mask);
3413 num_pending_connects++;
3416 else
3417 #endif
3418 /* A server may have a client filter setting of Qt, but it must
3419 still listen for incoming connects unless it is stopped. */
3420 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3421 || (EQ (p->status, Qlisten) && NILP (p->command)))
3423 FD_SET (inch, &input_wait_mask);
3424 FD_SET (inch, &non_keyboard_wait_mask);
3427 if (inch > max_process_desc)
3428 max_process_desc = inch;
3430 tem = Fplist_member (contact, QCcoding);
3431 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3432 tem = Qnil; /* No error message (too late!). */
3435 /* Setup coding systems for communicating with the network stream. */
3436 struct gcpro gcpro1;
3437 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3438 Lisp_Object coding_systems = Qt;
3439 Lisp_Object fargs[5], val;
3441 if (!NILP (tem))
3443 val = XCAR (XCDR (tem));
3444 if (CONSP (val))
3445 val = XCAR (val);
3447 else if (!NILP (Vcoding_system_for_read))
3448 val = Vcoding_system_for_read;
3449 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3450 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3451 /* We dare not decode end-of-line format by setting VAL to
3452 Qraw_text, because the existing Emacs Lisp libraries
3453 assume that they receive bare code including a sequence of
3454 CR LF. */
3455 val = Qnil;
3456 else
3458 if (NILP (host) || NILP (service))
3459 coding_systems = Qnil;
3460 else
3462 fargs[0] = Qopen_network_stream, fargs[1] = name,
3463 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3464 GCPRO1 (proc);
3465 coding_systems = Ffind_operation_coding_system (5, fargs);
3466 UNGCPRO;
3468 if (CONSP (coding_systems))
3469 val = XCAR (coding_systems);
3470 else if (CONSP (Vdefault_process_coding_system))
3471 val = XCAR (Vdefault_process_coding_system);
3472 else
3473 val = Qnil;
3475 pset_decode_coding_system (p, val);
3477 if (!NILP (tem))
3479 val = XCAR (XCDR (tem));
3480 if (CONSP (val))
3481 val = XCDR (val);
3483 else if (!NILP (Vcoding_system_for_write))
3484 val = Vcoding_system_for_write;
3485 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3486 val = Qnil;
3487 else
3489 if (EQ (coding_systems, Qt))
3491 if (NILP (host) || NILP (service))
3492 coding_systems = Qnil;
3493 else
3495 fargs[0] = Qopen_network_stream, fargs[1] = name,
3496 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3497 GCPRO1 (proc);
3498 coding_systems = Ffind_operation_coding_system (5, fargs);
3499 UNGCPRO;
3502 if (CONSP (coding_systems))
3503 val = XCDR (coding_systems);
3504 else if (CONSP (Vdefault_process_coding_system))
3505 val = XCDR (Vdefault_process_coding_system);
3506 else
3507 val = Qnil;
3509 pset_encode_coding_system (p, val);
3511 setup_process_coding_systems (proc);
3513 pset_decoding_buf (p, empty_unibyte_string);
3514 p->decoding_carryover = 0;
3515 pset_encoding_buf (p, empty_unibyte_string);
3517 p->inherit_coding_system_flag
3518 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3520 UNGCPRO;
3521 return proc;
3525 #ifdef HAVE_NET_IF_H
3527 #ifdef SIOCGIFCONF
3528 static Lisp_Object
3529 network_interface_list (void)
3531 struct ifconf ifconf;
3532 struct ifreq *ifreq;
3533 void *buf = NULL;
3534 ptrdiff_t buf_size = 512;
3535 int s;
3536 Lisp_Object res;
3537 ptrdiff_t count;
3539 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3540 if (s < 0)
3541 return Qnil;
3542 count = SPECPDL_INDEX ();
3543 record_unwind_protect_int (close_file_unwind, s);
3547 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3548 ifconf.ifc_buf = buf;
3549 ifconf.ifc_len = buf_size;
3550 if (ioctl (s, SIOCGIFCONF, &ifconf))
3552 emacs_close (s);
3553 xfree (buf);
3554 return Qnil;
3557 while (ifconf.ifc_len == buf_size);
3559 res = unbind_to (count, Qnil);
3560 ifreq = ifconf.ifc_req;
3561 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3563 struct ifreq *ifq = ifreq;
3564 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3565 #define SIZEOF_IFREQ(sif) \
3566 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3567 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3569 int len = SIZEOF_IFREQ (ifq);
3570 #else
3571 int len = sizeof (*ifreq);
3572 #endif
3573 char namebuf[sizeof (ifq->ifr_name) + 1];
3574 ifreq = (struct ifreq *) ((char *) ifreq + len);
3576 if (ifq->ifr_addr.sa_family != AF_INET)
3577 continue;
3579 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3580 namebuf[sizeof (ifq->ifr_name)] = 0;
3581 res = Fcons (Fcons (build_string (namebuf),
3582 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3583 sizeof (struct sockaddr))),
3584 res);
3587 xfree (buf);
3588 return res;
3590 #endif /* SIOCGIFCONF */
3592 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3594 struct ifflag_def {
3595 int flag_bit;
3596 const char *flag_sym;
3599 static const struct ifflag_def ifflag_table[] = {
3600 #ifdef IFF_UP
3601 { IFF_UP, "up" },
3602 #endif
3603 #ifdef IFF_BROADCAST
3604 { IFF_BROADCAST, "broadcast" },
3605 #endif
3606 #ifdef IFF_DEBUG
3607 { IFF_DEBUG, "debug" },
3608 #endif
3609 #ifdef IFF_LOOPBACK
3610 { IFF_LOOPBACK, "loopback" },
3611 #endif
3612 #ifdef IFF_POINTOPOINT
3613 { IFF_POINTOPOINT, "pointopoint" },
3614 #endif
3615 #ifdef IFF_RUNNING
3616 { IFF_RUNNING, "running" },
3617 #endif
3618 #ifdef IFF_NOARP
3619 { IFF_NOARP, "noarp" },
3620 #endif
3621 #ifdef IFF_PROMISC
3622 { IFF_PROMISC, "promisc" },
3623 #endif
3624 #ifdef IFF_NOTRAILERS
3625 #ifdef NS_IMPL_COCOA
3626 /* Really means smart, notrailers is obsolete */
3627 { IFF_NOTRAILERS, "smart" },
3628 #else
3629 { IFF_NOTRAILERS, "notrailers" },
3630 #endif
3631 #endif
3632 #ifdef IFF_ALLMULTI
3633 { IFF_ALLMULTI, "allmulti" },
3634 #endif
3635 #ifdef IFF_MASTER
3636 { IFF_MASTER, "master" },
3637 #endif
3638 #ifdef IFF_SLAVE
3639 { IFF_SLAVE, "slave" },
3640 #endif
3641 #ifdef IFF_MULTICAST
3642 { IFF_MULTICAST, "multicast" },
3643 #endif
3644 #ifdef IFF_PORTSEL
3645 { IFF_PORTSEL, "portsel" },
3646 #endif
3647 #ifdef IFF_AUTOMEDIA
3648 { IFF_AUTOMEDIA, "automedia" },
3649 #endif
3650 #ifdef IFF_DYNAMIC
3651 { IFF_DYNAMIC, "dynamic" },
3652 #endif
3653 #ifdef IFF_OACTIVE
3654 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3655 #endif
3656 #ifdef IFF_SIMPLEX
3657 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3658 #endif
3659 #ifdef IFF_LINK0
3660 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3661 #endif
3662 #ifdef IFF_LINK1
3663 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3664 #endif
3665 #ifdef IFF_LINK2
3666 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3667 #endif
3668 { 0, 0 }
3671 static Lisp_Object
3672 network_interface_info (Lisp_Object ifname)
3674 struct ifreq rq;
3675 Lisp_Object res = Qnil;
3676 Lisp_Object elt;
3677 int s;
3678 bool any = 0;
3679 ptrdiff_t count;
3680 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3681 && defined HAVE_GETIFADDRS && defined LLADDR)
3682 struct ifaddrs *ifap;
3683 #endif
3685 CHECK_STRING (ifname);
3687 if (sizeof rq.ifr_name <= SBYTES (ifname))
3688 error ("interface name too long");
3689 lispstpcpy (rq.ifr_name, ifname);
3691 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3692 if (s < 0)
3693 return Qnil;
3694 count = SPECPDL_INDEX ();
3695 record_unwind_protect_int (close_file_unwind, s);
3697 elt = Qnil;
3698 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3699 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3701 int flags = rq.ifr_flags;
3702 const struct ifflag_def *fp;
3703 int fnum;
3705 /* If flags is smaller than int (i.e. short) it may have the high bit set
3706 due to IFF_MULTICAST. In that case, sign extending it into
3707 an int is wrong. */
3708 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3709 flags = (unsigned short) rq.ifr_flags;
3711 any = 1;
3712 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3714 if (flags & fp->flag_bit)
3716 elt = Fcons (intern (fp->flag_sym), elt);
3717 flags -= fp->flag_bit;
3720 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3722 if (flags & 1)
3724 elt = Fcons (make_number (fnum), elt);
3728 #endif
3729 res = Fcons (elt, res);
3731 elt = Qnil;
3732 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3733 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3735 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3736 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3737 int n;
3739 any = 1;
3740 for (n = 0; n < 6; n++)
3741 p->contents[n] = make_number (((unsigned char *)
3742 &rq.ifr_hwaddr.sa_data[0])
3743 [n]);
3744 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3746 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3747 if (getifaddrs (&ifap) != -1)
3749 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3750 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3751 struct ifaddrs *it;
3753 for (it = ifap; it != NULL; it = it->ifa_next)
3755 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3756 unsigned char linkaddr[6];
3757 int n;
3759 if (it->ifa_addr->sa_family != AF_LINK
3760 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3761 || sdl->sdl_alen != 6)
3762 continue;
3764 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3765 for (n = 0; n < 6; n++)
3766 p->contents[n] = make_number (linkaddr[n]);
3768 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3769 break;
3772 #ifdef HAVE_FREEIFADDRS
3773 freeifaddrs (ifap);
3774 #endif
3776 #endif /* HAVE_GETIFADDRS && LLADDR */
3778 res = Fcons (elt, res);
3780 elt = Qnil;
3781 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3782 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3784 any = 1;
3785 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3786 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3787 #else
3788 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3789 #endif
3791 #endif
3792 res = Fcons (elt, res);
3794 elt = Qnil;
3795 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3796 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3798 any = 1;
3799 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3801 #endif
3802 res = Fcons (elt, res);
3804 elt = Qnil;
3805 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3806 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3808 any = 1;
3809 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3811 #endif
3812 res = Fcons (elt, res);
3814 return unbind_to (count, any ? res : Qnil);
3816 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3817 #endif /* defined (HAVE_NET_IF_H) */
3819 DEFUN ("network-interface-list", Fnetwork_interface_list,
3820 Snetwork_interface_list, 0, 0, 0,
3821 doc: /* Return an alist of all network interfaces and their network address.
3822 Each element is a cons, the car of which is a string containing the
3823 interface name, and the cdr is the network address in internal
3824 format; see the description of ADDRESS in `make-network-process'.
3826 If the information is not available, return nil. */)
3827 (void)
3829 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3830 return network_interface_list ();
3831 #else
3832 return Qnil;
3833 #endif
3836 DEFUN ("network-interface-info", Fnetwork_interface_info,
3837 Snetwork_interface_info, 1, 1, 0,
3838 doc: /* Return information about network interface named IFNAME.
3839 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3840 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3841 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3842 FLAGS is the current flags of the interface.
3844 Data that is unavailable is returned as nil. */)
3845 (Lisp_Object ifname)
3847 #if ((defined HAVE_NET_IF_H \
3848 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3849 || defined SIOCGIFFLAGS)) \
3850 || defined WINDOWSNT)
3851 return network_interface_info (ifname);
3852 #else
3853 return Qnil;
3854 #endif
3858 /* Turn off input and output for process PROC. */
3860 static void
3861 deactivate_process (Lisp_Object proc)
3863 int inchannel;
3864 struct Lisp_Process *p = XPROCESS (proc);
3865 int i;
3867 #ifdef HAVE_GNUTLS
3868 /* Delete GnuTLS structures in PROC, if any. */
3869 emacs_gnutls_deinit (proc);
3870 #endif /* HAVE_GNUTLS */
3872 #ifdef ADAPTIVE_READ_BUFFERING
3873 if (p->read_output_delay > 0)
3875 if (--process_output_delay_count < 0)
3876 process_output_delay_count = 0;
3877 p->read_output_delay = 0;
3878 p->read_output_skip = 0;
3880 #endif
3882 /* Beware SIGCHLD hereabouts. */
3884 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3885 close_process_fd (&p->open_fd[i]);
3887 inchannel = p->infd;
3888 if (inchannel >= 0)
3890 p->infd = -1;
3891 p->outfd = -1;
3892 #ifdef DATAGRAM_SOCKETS
3893 if (DATAGRAM_CHAN_P (inchannel))
3895 xfree (datagram_address[inchannel].sa);
3896 datagram_address[inchannel].sa = 0;
3897 datagram_address[inchannel].len = 0;
3899 #endif
3900 chan_process[inchannel] = Qnil;
3901 FD_CLR (inchannel, &input_wait_mask);
3902 FD_CLR (inchannel, &non_keyboard_wait_mask);
3903 #ifdef NON_BLOCKING_CONNECT
3904 if (FD_ISSET (inchannel, &connect_wait_mask))
3906 FD_CLR (inchannel, &connect_wait_mask);
3907 FD_CLR (inchannel, &write_mask);
3908 if (--num_pending_connects < 0)
3909 emacs_abort ();
3911 #endif
3912 if (inchannel == max_process_desc)
3914 /* We just closed the highest-numbered process input descriptor,
3915 so recompute the highest-numbered one now. */
3916 int i = inchannel;
3918 i--;
3919 while (0 <= i && NILP (chan_process[i]));
3921 max_process_desc = i;
3927 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3928 0, 4, 0,
3929 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3930 It is given to their filter functions.
3931 Optional argument PROCESS means do not return until output has been
3932 received from PROCESS.
3934 Optional second argument SECONDS and third argument MILLISEC
3935 specify a timeout; return after that much time even if there is
3936 no subprocess output. If SECONDS is a floating point number,
3937 it specifies a fractional number of seconds to wait.
3938 The MILLISEC argument is obsolete and should be avoided.
3940 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
3941 from PROCESS only, suspending reading output from other processes.
3942 If JUST-THIS-ONE is an integer, don't run any timers either.
3943 Return non-nil if we received any output from PROCESS (or, if PROCESS
3944 is nil, from any process) before the timeout expired. */)
3945 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3947 intmax_t secs;
3948 int nsecs;
3950 if (! NILP (process))
3951 CHECK_PROCESS (process);
3952 else
3953 just_this_one = Qnil;
3955 if (!NILP (millisec))
3956 { /* Obsolete calling convention using integers rather than floats. */
3957 CHECK_NUMBER (millisec);
3958 if (NILP (seconds))
3959 seconds = make_float (XINT (millisec) / 1000.0);
3960 else
3962 CHECK_NUMBER (seconds);
3963 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3967 secs = 0;
3968 nsecs = -1;
3970 if (!NILP (seconds))
3972 if (INTEGERP (seconds))
3974 if (XINT (seconds) > 0)
3976 secs = XINT (seconds);
3977 nsecs = 0;
3980 else if (FLOATP (seconds))
3982 if (XFLOAT_DATA (seconds) > 0)
3984 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3985 secs = min (t.tv_sec, WAIT_READING_MAX);
3986 nsecs = t.tv_nsec;
3989 else
3990 wrong_type_argument (Qnumberp, seconds);
3992 else if (! NILP (process))
3993 nsecs = 0;
3995 return
3996 ((wait_reading_process_output (secs, nsecs, 0, 0,
3997 Qnil,
3998 !NILP (process) ? XPROCESS (process) : NULL,
3999 NILP (just_this_one) ? 0 :
4000 !INTEGERP (just_this_one) ? 1 : -1)
4001 <= 0)
4002 ? Qnil : Qt);
4005 /* Accept a connection for server process SERVER on CHANNEL. */
4007 static EMACS_INT connect_counter = 0;
4009 static void
4010 server_accept_connection (Lisp_Object server, int channel)
4012 Lisp_Object proc, caller, name, buffer;
4013 Lisp_Object contact, host, service;
4014 struct Lisp_Process *ps= XPROCESS (server);
4015 struct Lisp_Process *p;
4016 int s;
4017 union u_sockaddr {
4018 struct sockaddr sa;
4019 struct sockaddr_in in;
4020 #ifdef AF_INET6
4021 struct sockaddr_in6 in6;
4022 #endif
4023 #ifdef HAVE_LOCAL_SOCKETS
4024 struct sockaddr_un un;
4025 #endif
4026 } saddr;
4027 socklen_t len = sizeof saddr;
4028 ptrdiff_t count;
4030 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4032 if (s < 0)
4034 int code = errno;
4036 if (code == EAGAIN)
4037 return;
4038 #ifdef EWOULDBLOCK
4039 if (code == EWOULDBLOCK)
4040 return;
4041 #endif
4043 if (!NILP (ps->log))
4044 call3 (ps->log, server, Qnil,
4045 concat3 (build_string ("accept failed with code"),
4046 Fnumber_to_string (make_number (code)),
4047 build_string ("\n")));
4048 return;
4051 count = SPECPDL_INDEX ();
4052 record_unwind_protect_int (close_file_unwind, s);
4054 connect_counter++;
4056 /* Setup a new process to handle the connection. */
4058 /* Generate a unique identification of the caller, and build contact
4059 information for this process. */
4060 host = Qt;
4061 service = Qnil;
4062 switch (saddr.sa.sa_family)
4064 case AF_INET:
4066 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4068 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4069 host = Fformat (5, ((Lisp_Object [])
4070 { ipv4_format, make_number (ip[0]),
4071 make_number (ip[1]), make_number (ip[2]), make_number (ip[3]) }));
4072 service = make_number (ntohs (saddr.in.sin_port));
4073 AUTO_STRING (caller_format, " <%s:%d>");
4074 caller = Fformat (3, (Lisp_Object []) {caller_format, host, service});
4076 break;
4078 #ifdef AF_INET6
4079 case AF_INET6:
4081 Lisp_Object args[9];
4082 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4083 int i;
4085 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4086 args[0] = ipv6_format;
4087 for (i = 0; i < 8; i++)
4088 args[i + 1] = make_number (ntohs (ip6[i]));
4089 host = Fformat (9, args);
4090 service = make_number (ntohs (saddr.in.sin_port));
4091 AUTO_STRING (caller_format, " <[%s]:%d>");
4092 caller = Fformat (3, (Lisp_Object []) {caller_format, host, service});
4094 break;
4095 #endif
4097 #ifdef HAVE_LOCAL_SOCKETS
4098 case AF_LOCAL:
4099 #endif
4100 default:
4101 caller = Fnumber_to_string (make_number (connect_counter));
4102 AUTO_STRING (space_lessthan, " <");
4103 AUTO_STRING (greaterthan, ">");
4104 caller = concat3 (space_lessthan, caller, greaterthan);
4105 break;
4108 /* Create a new buffer name for this process if it doesn't have a
4109 filter. The new buffer name is based on the buffer name or
4110 process name of the server process concatenated with the caller
4111 identification. */
4113 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4114 || EQ (ps->filter, Qt)))
4115 buffer = Qnil;
4116 else
4118 buffer = ps->buffer;
4119 if (!NILP (buffer))
4120 buffer = Fbuffer_name (buffer);
4121 else
4122 buffer = ps->name;
4123 if (!NILP (buffer))
4125 buffer = concat2 (buffer, caller);
4126 buffer = Fget_buffer_create (buffer);
4130 /* Generate a unique name for the new server process. Combine the
4131 server process name with the caller identification. */
4133 name = concat2 (ps->name, caller);
4134 proc = make_process (name);
4136 chan_process[s] = proc;
4138 fcntl (s, F_SETFL, O_NONBLOCK);
4140 p = XPROCESS (proc);
4142 /* Build new contact information for this setup. */
4143 contact = Fcopy_sequence (ps->childp);
4144 contact = Fplist_put (contact, QCserver, Qnil);
4145 contact = Fplist_put (contact, QChost, host);
4146 if (!NILP (service))
4147 contact = Fplist_put (contact, QCservice, service);
4148 contact = Fplist_put (contact, QCremote,
4149 conv_sockaddr_to_lisp (&saddr.sa, len));
4150 #ifdef HAVE_GETSOCKNAME
4151 len = sizeof saddr;
4152 if (getsockname (s, &saddr.sa, &len) == 0)
4153 contact = Fplist_put (contact, QClocal,
4154 conv_sockaddr_to_lisp (&saddr.sa, len));
4155 #endif
4157 pset_childp (p, contact);
4158 pset_plist (p, Fcopy_sequence (ps->plist));
4159 pset_type (p, Qnetwork);
4161 pset_buffer (p, buffer);
4162 pset_sentinel (p, ps->sentinel);
4163 pset_filter (p, ps->filter);
4164 pset_command (p, Qnil);
4165 p->pid = 0;
4167 /* Discard the unwind protect for closing S. */
4168 specpdl_ptr = specpdl + count;
4170 p->open_fd[SUBPROCESS_STDIN] = s;
4171 p->infd = s;
4172 p->outfd = s;
4173 pset_status (p, Qrun);
4175 /* Client processes for accepted connections are not stopped initially. */
4176 if (!EQ (p->filter, Qt))
4178 FD_SET (s, &input_wait_mask);
4179 FD_SET (s, &non_keyboard_wait_mask);
4182 if (s > max_process_desc)
4183 max_process_desc = s;
4185 /* Setup coding system for new process based on server process.
4186 This seems to be the proper thing to do, as the coding system
4187 of the new process should reflect the settings at the time the
4188 server socket was opened; not the current settings. */
4190 pset_decode_coding_system (p, ps->decode_coding_system);
4191 pset_encode_coding_system (p, ps->encode_coding_system);
4192 setup_process_coding_systems (proc);
4194 pset_decoding_buf (p, empty_unibyte_string);
4195 p->decoding_carryover = 0;
4196 pset_encoding_buf (p, empty_unibyte_string);
4198 p->inherit_coding_system_flag
4199 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4201 AUTO_STRING (dash, "-");
4202 AUTO_STRING (nl, "\n");
4203 Lisp_Object host_string = STRINGP (host) ? host : dash;
4205 if (!NILP (ps->log))
4207 AUTO_STRING (accept_from, "accept from ");
4208 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4211 AUTO_STRING (open_from, "open from ");
4212 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4215 /* This variable is different from waiting_for_input in keyboard.c.
4216 It is used to communicate to a lisp process-filter/sentinel (via the
4217 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4218 for user-input when that process-filter was called.
4219 waiting_for_input cannot be used as that is by definition 0 when
4220 lisp code is being evalled.
4221 This is also used in record_asynch_buffer_change.
4222 For that purpose, this must be 0
4223 when not inside wait_reading_process_output. */
4224 static int waiting_for_user_input_p;
4226 static void
4227 wait_reading_process_output_unwind (int data)
4229 waiting_for_user_input_p = data;
4232 /* This is here so breakpoints can be put on it. */
4233 static void
4234 wait_reading_process_output_1 (void)
4238 /* Read and dispose of subprocess output while waiting for timeout to
4239 elapse and/or keyboard input to be available.
4241 TIME_LIMIT is:
4242 timeout in seconds
4243 If negative, gobble data immediately available but don't wait for any.
4245 NSECS is:
4246 an additional duration to wait, measured in nanoseconds
4247 If TIME_LIMIT is zero, then:
4248 If NSECS == 0, there is no limit.
4249 If NSECS > 0, the timeout consists of NSECS only.
4250 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4252 READ_KBD is:
4253 0 to ignore keyboard input, or
4254 1 to return when input is available, or
4255 -1 meaning caller will actually read the input, so don't throw to
4256 the quit handler, or
4258 DO_DISPLAY means redisplay should be done to show subprocess
4259 output that arrives.
4261 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4262 (and gobble terminal input into the buffer if any arrives).
4264 If WAIT_PROC is specified, wait until something arrives from that
4265 process.
4267 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4268 (suspending output from other processes). A negative value
4269 means don't run any timers either.
4271 Return positive if we received input from WAIT_PROC (or from any
4272 process if WAIT_PROC is null), zero if we attempted to receive
4273 input but got none, and negative if we didn't even try. */
4276 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4277 bool do_display,
4278 Lisp_Object wait_for_cell,
4279 struct Lisp_Process *wait_proc, int just_wait_proc)
4281 int channel, nfds;
4282 fd_set Available;
4283 fd_set Writeok;
4284 bool check_write;
4285 int check_delay;
4286 bool no_avail;
4287 int xerrno;
4288 Lisp_Object proc;
4289 struct timespec timeout, end_time;
4290 int got_some_input = -1;
4291 ptrdiff_t count = SPECPDL_INDEX ();
4293 FD_ZERO (&Available);
4294 FD_ZERO (&Writeok);
4296 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4297 && !(CONSP (wait_proc->status)
4298 && EQ (XCAR (wait_proc->status), Qexit)))
4299 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4301 record_unwind_protect_int (wait_reading_process_output_unwind,
4302 waiting_for_user_input_p);
4303 waiting_for_user_input_p = read_kbd;
4305 if (time_limit < 0)
4307 time_limit = 0;
4308 nsecs = -1;
4310 else if (TYPE_MAXIMUM (time_t) < time_limit)
4311 time_limit = TYPE_MAXIMUM (time_t);
4313 /* Since we may need to wait several times,
4314 compute the absolute time to return at. */
4315 if (time_limit || nsecs > 0)
4317 timeout = make_timespec (time_limit, nsecs);
4318 end_time = timespec_add (current_timespec (), timeout);
4321 while (1)
4323 bool timeout_reduced_for_timers = 0;
4325 /* If calling from keyboard input, do not quit
4326 since we want to return C-g as an input character.
4327 Otherwise, do pending quit if requested. */
4328 if (read_kbd >= 0)
4329 QUIT;
4330 else if (pending_signals)
4331 process_pending_signals ();
4333 /* Exit now if the cell we're waiting for became non-nil. */
4334 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4335 break;
4337 /* After reading input, vacuum up any leftovers without waiting. */
4338 if (0 <= got_some_input)
4339 nsecs = -1;
4341 /* Compute time from now till when time limit is up. */
4342 /* Exit if already run out. */
4343 if (nsecs < 0)
4345 /* A negative timeout means
4346 gobble output available now
4347 but don't wait at all. */
4349 timeout = make_timespec (0, 0);
4351 else if (time_limit || nsecs > 0)
4353 struct timespec now = current_timespec ();
4354 if (timespec_cmp (end_time, now) <= 0)
4355 break;
4356 timeout = timespec_sub (end_time, now);
4358 else
4360 timeout = make_timespec (100000, 0);
4363 /* Normally we run timers here.
4364 But not if wait_for_cell; in those cases,
4365 the wait is supposed to be short,
4366 and those callers cannot handle running arbitrary Lisp code here. */
4367 if (NILP (wait_for_cell)
4368 && just_wait_proc >= 0)
4370 struct timespec timer_delay;
4374 unsigned old_timers_run = timers_run;
4375 struct buffer *old_buffer = current_buffer;
4376 Lisp_Object old_window = selected_window;
4378 timer_delay = timer_check ();
4380 /* If a timer has run, this might have changed buffers
4381 an alike. Make read_key_sequence aware of that. */
4382 if (timers_run != old_timers_run
4383 && (old_buffer != current_buffer
4384 || !EQ (old_window, selected_window))
4385 && waiting_for_user_input_p == -1)
4386 record_asynch_buffer_change ();
4388 if (timers_run != old_timers_run && do_display)
4389 /* We must retry, since a timer may have requeued itself
4390 and that could alter the time_delay. */
4391 redisplay_preserve_echo_area (9);
4392 else
4393 break;
4395 while (!detect_input_pending ());
4397 /* If there is unread keyboard input, also return. */
4398 if (read_kbd != 0
4399 && requeued_events_pending_p ())
4400 break;
4402 /* A negative timeout means do not wait at all. */
4403 if (nsecs >= 0)
4405 if (timespec_valid_p (timer_delay))
4407 if (timespec_cmp (timer_delay, timeout) < 0)
4409 timeout = timer_delay;
4410 timeout_reduced_for_timers = 1;
4413 else
4415 /* This is so a breakpoint can be put here. */
4416 wait_reading_process_output_1 ();
4421 /* Cause C-g and alarm signals to take immediate action,
4422 and cause input available signals to zero out timeout.
4424 It is important that we do this before checking for process
4425 activity. If we get a SIGCHLD after the explicit checks for
4426 process activity, timeout is the only way we will know. */
4427 if (read_kbd < 0)
4428 set_waiting_for_input (&timeout);
4430 /* If status of something has changed, and no input is
4431 available, notify the user of the change right away. After
4432 this explicit check, we'll let the SIGCHLD handler zap
4433 timeout to get our attention. */
4434 if (update_tick != process_tick)
4436 fd_set Atemp;
4437 fd_set Ctemp;
4439 if (kbd_on_hold_p ())
4440 FD_ZERO (&Atemp);
4441 else
4442 Atemp = input_wait_mask;
4443 Ctemp = write_mask;
4445 timeout = make_timespec (0, 0);
4446 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4447 &Atemp,
4448 #ifdef NON_BLOCKING_CONNECT
4449 (num_pending_connects > 0 ? &Ctemp : NULL),
4450 #else
4451 NULL,
4452 #endif
4453 NULL, &timeout, NULL)
4454 <= 0))
4456 /* It's okay for us to do this and then continue with
4457 the loop, since timeout has already been zeroed out. */
4458 clear_waiting_for_input ();
4459 got_some_input = status_notify (NULL, wait_proc);
4460 if (do_display) redisplay_preserve_echo_area (13);
4464 /* Don't wait for output from a non-running process. Just
4465 read whatever data has already been received. */
4466 if (wait_proc && wait_proc->raw_status_new)
4467 update_status (wait_proc);
4468 if (wait_proc
4469 && wait_proc->infd >= 0
4470 && ! EQ (wait_proc->status, Qrun)
4471 && ! EQ (wait_proc->status, Qconnect))
4473 bool read_some_bytes = 0;
4475 clear_waiting_for_input ();
4476 XSETPROCESS (proc, wait_proc);
4478 /* Read data from the process, until we exhaust it. */
4479 while (true)
4481 int nread = read_process_output (proc, wait_proc->infd);
4482 if (nread < 0)
4484 if (errno == EIO || errno == EAGAIN)
4485 break;
4486 #ifdef EWOULDBLOCK
4487 if (errno == EWOULDBLOCK)
4488 break;
4489 #endif
4491 else
4493 if (got_some_input < nread)
4494 got_some_input = nread;
4495 if (nread == 0)
4496 break;
4497 read_some_bytes = true;
4500 if (read_some_bytes && do_display)
4501 redisplay_preserve_echo_area (10);
4503 break;
4506 /* Wait till there is something to do */
4508 if (wait_proc && just_wait_proc)
4510 if (wait_proc->infd < 0) /* Terminated */
4511 break;
4512 FD_SET (wait_proc->infd, &Available);
4513 check_delay = 0;
4514 check_write = 0;
4516 else if (!NILP (wait_for_cell))
4518 Available = non_process_wait_mask;
4519 check_delay = 0;
4520 check_write = 0;
4522 else
4524 if (! read_kbd)
4525 Available = non_keyboard_wait_mask;
4526 else
4527 Available = input_wait_mask;
4528 Writeok = write_mask;
4529 check_delay = wait_proc ? 0 : process_output_delay_count;
4530 check_write = SELECT_CAN_DO_WRITE_MASK;
4533 /* If frame size has changed or the window is newly mapped,
4534 redisplay now, before we start to wait. There is a race
4535 condition here; if a SIGIO arrives between now and the select
4536 and indicates that a frame is trashed, the select may block
4537 displaying a trashed screen. */
4538 if (frame_garbaged && do_display)
4540 clear_waiting_for_input ();
4541 redisplay_preserve_echo_area (11);
4542 if (read_kbd < 0)
4543 set_waiting_for_input (&timeout);
4546 /* Skip the `select' call if input is available and we're
4547 waiting for keyboard input or a cell change (which can be
4548 triggered by processing X events). In the latter case, set
4549 nfds to 1 to avoid breaking the loop. */
4550 no_avail = 0;
4551 if ((read_kbd || !NILP (wait_for_cell))
4552 && detect_input_pending ())
4554 nfds = read_kbd ? 0 : 1;
4555 no_avail = 1;
4556 FD_ZERO (&Available);
4559 if (!no_avail)
4562 #ifdef ADAPTIVE_READ_BUFFERING
4563 /* Set the timeout for adaptive read buffering if any
4564 process has non-zero read_output_skip and non-zero
4565 read_output_delay, and we are not reading output for a
4566 specific process. It is not executed if
4567 Vprocess_adaptive_read_buffering is nil. */
4568 if (process_output_skip && check_delay > 0)
4570 int nsecs = timeout.tv_nsec;
4571 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4572 nsecs = READ_OUTPUT_DELAY_MAX;
4573 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4575 proc = chan_process[channel];
4576 if (NILP (proc))
4577 continue;
4578 /* Find minimum non-zero read_output_delay among the
4579 processes with non-zero read_output_skip. */
4580 if (XPROCESS (proc)->read_output_delay > 0)
4582 check_delay--;
4583 if (!XPROCESS (proc)->read_output_skip)
4584 continue;
4585 FD_CLR (channel, &Available);
4586 XPROCESS (proc)->read_output_skip = 0;
4587 if (XPROCESS (proc)->read_output_delay < nsecs)
4588 nsecs = XPROCESS (proc)->read_output_delay;
4591 timeout = make_timespec (0, nsecs);
4592 process_output_skip = 0;
4594 #endif
4596 #if defined (HAVE_NS)
4597 nfds = ns_select
4598 #elif defined (HAVE_GLIB)
4599 nfds = xg_select
4600 #else
4601 nfds = pselect
4602 #endif
4603 (max (max_process_desc, max_input_desc) + 1,
4604 &Available,
4605 (check_write ? &Writeok : 0),
4606 NULL, &timeout, NULL);
4608 #ifdef HAVE_GNUTLS
4609 /* GnuTLS buffers data internally. In lowat mode it leaves
4610 some data in the TCP buffers so that select works, but
4611 with custom pull/push functions we need to check if some
4612 data is available in the buffers manually. */
4613 if (nfds == 0)
4615 if (! wait_proc)
4617 /* We're not waiting on a specific process, so loop
4618 through all the channels and check for data.
4619 This is a workaround needed for some versions of
4620 the gnutls library -- 2.12.14 has been confirmed
4621 to need it. See
4622 http://comments.gmane.org/gmane.emacs.devel/145074 */
4623 for (channel = 0; channel < FD_SETSIZE; ++channel)
4624 if (! NILP (chan_process[channel]))
4626 struct Lisp_Process *p =
4627 XPROCESS (chan_process[channel]);
4628 if (p && p->gnutls_p && p->gnutls_state
4629 && ((emacs_gnutls_record_check_pending
4630 (p->gnutls_state))
4631 > 0))
4633 nfds++;
4634 eassert (p->infd == channel);
4635 FD_SET (p->infd, &Available);
4639 else
4641 /* Check this specific channel. */
4642 if (wait_proc->gnutls_p /* Check for valid process. */
4643 && wait_proc->gnutls_state
4644 /* Do we have pending data? */
4645 && ((emacs_gnutls_record_check_pending
4646 (wait_proc->gnutls_state))
4647 > 0))
4649 nfds = 1;
4650 eassert (0 <= wait_proc->infd);
4651 /* Set to Available. */
4652 FD_SET (wait_proc->infd, &Available);
4656 #endif
4659 xerrno = errno;
4661 /* Make C-g and alarm signals set flags again */
4662 clear_waiting_for_input ();
4664 /* If we woke up due to SIGWINCH, actually change size now. */
4665 do_pending_window_change (0);
4667 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4668 /* We waited the full specified time, so return now. */
4669 break;
4670 if (nfds < 0)
4672 if (xerrno == EINTR)
4673 no_avail = 1;
4674 else if (xerrno == EBADF)
4675 emacs_abort ();
4676 else
4677 report_file_errno ("Failed select", Qnil, xerrno);
4680 /* Check for keyboard input */
4681 /* If there is any, return immediately
4682 to give it higher priority than subprocesses */
4684 if (read_kbd != 0)
4686 unsigned old_timers_run = timers_run;
4687 struct buffer *old_buffer = current_buffer;
4688 Lisp_Object old_window = selected_window;
4689 bool leave = 0;
4691 if (detect_input_pending_run_timers (do_display))
4693 swallow_events (do_display);
4694 if (detect_input_pending_run_timers (do_display))
4695 leave = 1;
4698 /* If a timer has run, this might have changed buffers
4699 an alike. Make read_key_sequence aware of that. */
4700 if (timers_run != old_timers_run
4701 && waiting_for_user_input_p == -1
4702 && (old_buffer != current_buffer
4703 || !EQ (old_window, selected_window)))
4704 record_asynch_buffer_change ();
4706 if (leave)
4707 break;
4710 /* If there is unread keyboard input, also return. */
4711 if (read_kbd != 0
4712 && requeued_events_pending_p ())
4713 break;
4715 /* If we are not checking for keyboard input now,
4716 do process events (but don't run any timers).
4717 This is so that X events will be processed.
4718 Otherwise they may have to wait until polling takes place.
4719 That would causes delays in pasting selections, for example.
4721 (We used to do this only if wait_for_cell.) */
4722 if (read_kbd == 0 && detect_input_pending ())
4724 swallow_events (do_display);
4725 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4726 if (detect_input_pending ())
4727 break;
4728 #endif
4731 /* Exit now if the cell we're waiting for became non-nil. */
4732 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4733 break;
4735 #ifdef USABLE_SIGIO
4736 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4737 go read it. This can happen with X on BSD after logging out.
4738 In that case, there really is no input and no SIGIO,
4739 but select says there is input. */
4741 if (read_kbd && interrupt_input
4742 && keyboard_bit_set (&Available) && ! noninteractive)
4743 handle_input_available_signal (SIGIO);
4744 #endif
4746 /* If checking input just got us a size-change event from X,
4747 obey it now if we should. */
4748 if (read_kbd || ! NILP (wait_for_cell))
4749 do_pending_window_change (0);
4751 /* Check for data from a process. */
4752 if (no_avail || nfds == 0)
4753 continue;
4755 for (channel = 0; channel <= max_input_desc; ++channel)
4757 struct fd_callback_data *d = &fd_callback_info[channel];
4758 if (d->func
4759 && ((d->condition & FOR_READ
4760 && FD_ISSET (channel, &Available))
4761 || (d->condition & FOR_WRITE
4762 && FD_ISSET (channel, &write_mask))))
4763 d->func (channel, d->data);
4766 for (channel = 0; channel <= max_process_desc; channel++)
4768 if (FD_ISSET (channel, &Available)
4769 && FD_ISSET (channel, &non_keyboard_wait_mask)
4770 && !FD_ISSET (channel, &non_process_wait_mask))
4772 int nread;
4774 /* If waiting for this channel, arrange to return as
4775 soon as no more input to be processed. No more
4776 waiting. */
4777 proc = chan_process[channel];
4778 if (NILP (proc))
4779 continue;
4781 /* If this is a server stream socket, accept connection. */
4782 if (EQ (XPROCESS (proc)->status, Qlisten))
4784 server_accept_connection (proc, channel);
4785 continue;
4788 /* Read data from the process, starting with our
4789 buffered-ahead character if we have one. */
4791 nread = read_process_output (proc, channel);
4792 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
4793 got_some_input = nread;
4794 if (nread > 0)
4796 /* Since read_process_output can run a filter,
4797 which can call accept-process-output,
4798 don't try to read from any other processes
4799 before doing the select again. */
4800 FD_ZERO (&Available);
4802 if (do_display)
4803 redisplay_preserve_echo_area (12);
4805 #ifdef EWOULDBLOCK
4806 else if (nread == -1 && errno == EWOULDBLOCK)
4808 #endif
4809 else if (nread == -1 && errno == EAGAIN)
4811 #ifdef WINDOWSNT
4812 /* FIXME: Is this special case still needed? */
4813 /* Note that we cannot distinguish between no input
4814 available now and a closed pipe.
4815 With luck, a closed pipe will be accompanied by
4816 subprocess termination and SIGCHLD. */
4817 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4819 #endif
4820 #ifdef HAVE_PTYS
4821 /* On some OSs with ptys, when the process on one end of
4822 a pty exits, the other end gets an error reading with
4823 errno = EIO instead of getting an EOF (0 bytes read).
4824 Therefore, if we get an error reading and errno =
4825 EIO, just continue, because the child process has
4826 exited and should clean itself up soon (e.g. when we
4827 get a SIGCHLD). */
4828 else if (nread == -1 && errno == EIO)
4830 struct Lisp_Process *p = XPROCESS (proc);
4832 /* Clear the descriptor now, so we only raise the
4833 signal once. */
4834 FD_CLR (channel, &input_wait_mask);
4835 FD_CLR (channel, &non_keyboard_wait_mask);
4837 if (p->pid == -2)
4839 /* If the EIO occurs on a pty, the SIGCHLD handler's
4840 waitpid call will not find the process object to
4841 delete. Do it here. */
4842 p->tick = ++process_tick;
4843 pset_status (p, Qfailed);
4846 #endif /* HAVE_PTYS */
4847 /* If we can detect process termination, don't consider the
4848 process gone just because its pipe is closed. */
4849 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4851 else
4853 /* Preserve status of processes already terminated. */
4854 XPROCESS (proc)->tick = ++process_tick;
4855 deactivate_process (proc);
4856 if (XPROCESS (proc)->raw_status_new)
4857 update_status (XPROCESS (proc));
4858 if (EQ (XPROCESS (proc)->status, Qrun))
4859 pset_status (XPROCESS (proc),
4860 list2 (Qexit, make_number (256)));
4863 #ifdef NON_BLOCKING_CONNECT
4864 if (FD_ISSET (channel, &Writeok)
4865 && FD_ISSET (channel, &connect_wait_mask))
4867 struct Lisp_Process *p;
4869 FD_CLR (channel, &connect_wait_mask);
4870 FD_CLR (channel, &write_mask);
4871 if (--num_pending_connects < 0)
4872 emacs_abort ();
4874 proc = chan_process[channel];
4875 if (NILP (proc))
4876 continue;
4878 p = XPROCESS (proc);
4880 #ifdef GNU_LINUX
4881 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4882 So only use it on systems where it is known to work. */
4884 socklen_t xlen = sizeof (xerrno);
4885 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4886 xerrno = errno;
4888 #else
4890 struct sockaddr pname;
4891 socklen_t pnamelen = sizeof (pname);
4893 /* If connection failed, getpeername will fail. */
4894 xerrno = 0;
4895 if (getpeername (channel, &pname, &pnamelen) < 0)
4897 /* Obtain connect failure code through error slippage. */
4898 char dummy;
4899 xerrno = errno;
4900 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4901 xerrno = errno;
4904 #endif
4905 if (xerrno)
4907 p->tick = ++process_tick;
4908 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4909 deactivate_process (proc);
4911 else
4913 pset_status (p, Qrun);
4914 /* Execute the sentinel here. If we had relied on
4915 status_notify to do it later, it will read input
4916 from the process before calling the sentinel. */
4917 exec_sentinel (proc, build_string ("open\n"));
4918 if (0 <= p->infd && !EQ (p->filter, Qt)
4919 && !EQ (p->command, Qt))
4921 FD_SET (p->infd, &input_wait_mask);
4922 FD_SET (p->infd, &non_keyboard_wait_mask);
4926 #endif /* NON_BLOCKING_CONNECT */
4927 } /* End for each file descriptor. */
4928 } /* End while exit conditions not met. */
4930 unbind_to (count, Qnil);
4932 /* If calling from keyboard input, do not quit
4933 since we want to return C-g as an input character.
4934 Otherwise, do pending quit if requested. */
4935 if (read_kbd >= 0)
4937 /* Prevent input_pending from remaining set if we quit. */
4938 clear_input_pending ();
4939 QUIT;
4942 return got_some_input;
4945 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4947 static Lisp_Object
4948 read_process_output_call (Lisp_Object fun_and_args)
4950 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4953 static Lisp_Object
4954 read_process_output_error_handler (Lisp_Object error_val)
4956 cmd_error_internal (error_val, "error in process filter: ");
4957 Vinhibit_quit = Qt;
4958 update_echo_area ();
4959 Fsleep_for (make_number (2), Qnil);
4960 return Qt;
4963 static void
4964 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4965 ssize_t nbytes,
4966 struct coding_system *coding);
4968 /* Read pending output from the process channel,
4969 starting with our buffered-ahead character if we have one.
4970 Yield number of decoded characters read.
4972 This function reads at most 4096 characters.
4973 If you want to read all available subprocess output,
4974 you must call it repeatedly until it returns zero.
4976 The characters read are decoded according to PROC's coding-system
4977 for decoding. */
4979 static int
4980 read_process_output (Lisp_Object proc, int channel)
4982 ssize_t nbytes;
4983 struct Lisp_Process *p = XPROCESS (proc);
4984 struct coding_system *coding = proc_decode_coding_system[channel];
4985 int carryover = p->decoding_carryover;
4986 enum { readmax = 4096 };
4987 ptrdiff_t count = SPECPDL_INDEX ();
4988 Lisp_Object odeactivate;
4989 char chars[sizeof coding->carryover + readmax];
4991 if (carryover)
4992 /* See the comment above. */
4993 memcpy (chars, SDATA (p->decoding_buf), carryover);
4995 #ifdef DATAGRAM_SOCKETS
4996 /* We have a working select, so proc_buffered_char is always -1. */
4997 if (DATAGRAM_CHAN_P (channel))
4999 socklen_t len = datagram_address[channel].len;
5000 nbytes = recvfrom (channel, chars + carryover, readmax,
5001 0, datagram_address[channel].sa, &len);
5003 else
5004 #endif
5006 bool buffered = proc_buffered_char[channel] >= 0;
5007 if (buffered)
5009 chars[carryover] = proc_buffered_char[channel];
5010 proc_buffered_char[channel] = -1;
5012 #ifdef HAVE_GNUTLS
5013 if (p->gnutls_p && p->gnutls_state)
5014 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5015 readmax - buffered);
5016 else
5017 #endif
5018 nbytes = emacs_read (channel, chars + carryover + buffered,
5019 readmax - buffered);
5020 #ifdef ADAPTIVE_READ_BUFFERING
5021 if (nbytes > 0 && p->adaptive_read_buffering)
5023 int delay = p->read_output_delay;
5024 if (nbytes < 256)
5026 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5028 if (delay == 0)
5029 process_output_delay_count++;
5030 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5033 else if (delay > 0 && nbytes == readmax - buffered)
5035 delay -= READ_OUTPUT_DELAY_INCREMENT;
5036 if (delay == 0)
5037 process_output_delay_count--;
5039 p->read_output_delay = delay;
5040 if (delay)
5042 p->read_output_skip = 1;
5043 process_output_skip = 1;
5046 #endif
5047 nbytes += buffered;
5048 nbytes += buffered && nbytes <= 0;
5051 p->decoding_carryover = 0;
5053 /* At this point, NBYTES holds number of bytes just received
5054 (including the one in proc_buffered_char[channel]). */
5055 if (nbytes <= 0)
5057 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5058 return nbytes;
5059 coding->mode |= CODING_MODE_LAST_BLOCK;
5062 /* Now set NBYTES how many bytes we must decode. */
5063 nbytes += carryover;
5065 odeactivate = Vdeactivate_mark;
5066 /* There's no good reason to let process filters change the current
5067 buffer, and many callers of accept-process-output, sit-for, and
5068 friends don't expect current-buffer to be changed from under them. */
5069 record_unwind_current_buffer ();
5071 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5073 /* Handling the process output should not deactivate the mark. */
5074 Vdeactivate_mark = odeactivate;
5076 unbind_to (count, Qnil);
5077 return nbytes;
5080 static void
5081 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5082 ssize_t nbytes,
5083 struct coding_system *coding)
5085 Lisp_Object outstream = p->filter;
5086 Lisp_Object text;
5087 bool outer_running_asynch_code = running_asynch_code;
5088 int waiting = waiting_for_user_input_p;
5090 /* No need to gcpro these, because all we do with them later
5091 is test them for EQness, and none of them should be a string. */
5092 #if 0
5093 Lisp_Object obuffer, okeymap;
5094 XSETBUFFER (obuffer, current_buffer);
5095 okeymap = BVAR (current_buffer, keymap);
5096 #endif
5098 /* We inhibit quit here instead of just catching it so that
5099 hitting ^G when a filter happens to be running won't screw
5100 it up. */
5101 specbind (Qinhibit_quit, Qt);
5102 specbind (Qlast_nonmenu_event, Qt);
5104 /* In case we get recursively called,
5105 and we already saved the match data nonrecursively,
5106 save the same match data in safely recursive fashion. */
5107 if (outer_running_asynch_code)
5109 Lisp_Object tem;
5110 /* Don't clobber the CURRENT match data, either! */
5111 tem = Fmatch_data (Qnil, Qnil, Qnil);
5112 restore_search_regs ();
5113 record_unwind_save_match_data ();
5114 Fset_match_data (tem, Qt);
5117 /* For speed, if a search happens within this code,
5118 save the match data in a special nonrecursive fashion. */
5119 running_asynch_code = 1;
5121 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5122 text = coding->dst_object;
5123 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5124 /* A new coding system might be found. */
5125 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5127 pset_decode_coding_system (p, Vlast_coding_system_used);
5129 /* Don't call setup_coding_system for
5130 proc_decode_coding_system[channel] here. It is done in
5131 detect_coding called via decode_coding above. */
5133 /* If a coding system for encoding is not yet decided, we set
5134 it as the same as coding-system for decoding.
5136 But, before doing that we must check if
5137 proc_encode_coding_system[p->outfd] surely points to a
5138 valid memory because p->outfd will be changed once EOF is
5139 sent to the process. */
5140 if (NILP (p->encode_coding_system) && p->outfd >= 0
5141 && proc_encode_coding_system[p->outfd])
5143 pset_encode_coding_system
5144 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5145 setup_coding_system (p->encode_coding_system,
5146 proc_encode_coding_system[p->outfd]);
5150 if (coding->carryover_bytes > 0)
5152 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5153 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5154 memcpy (SDATA (p->decoding_buf), coding->carryover,
5155 coding->carryover_bytes);
5156 p->decoding_carryover = coding->carryover_bytes;
5158 if (SBYTES (text) > 0)
5159 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5160 sometimes it's simply wrong to wrap (e.g. when called from
5161 accept-process-output). */
5162 internal_condition_case_1 (read_process_output_call,
5163 list3 (outstream, make_lisp_proc (p), text),
5164 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5165 read_process_output_error_handler);
5167 /* If we saved the match data nonrecursively, restore it now. */
5168 restore_search_regs ();
5169 running_asynch_code = outer_running_asynch_code;
5171 /* Restore waiting_for_user_input_p as it was
5172 when we were called, in case the filter clobbered it. */
5173 waiting_for_user_input_p = waiting;
5175 #if 0 /* Call record_asynch_buffer_change unconditionally,
5176 because we might have changed minor modes or other things
5177 that affect key bindings. */
5178 if (! EQ (Fcurrent_buffer (), obuffer)
5179 || ! EQ (current_buffer->keymap, okeymap))
5180 #endif
5181 /* But do it only if the caller is actually going to read events.
5182 Otherwise there's no need to make him wake up, and it could
5183 cause trouble (for example it would make sit_for return). */
5184 if (waiting_for_user_input_p == -1)
5185 record_asynch_buffer_change ();
5188 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5189 Sinternal_default_process_filter, 2, 2, 0,
5190 doc: /* Function used as default process filter.
5191 This inserts the process's output into its buffer, if there is one.
5192 Otherwise it discards the output. */)
5193 (Lisp_Object proc, Lisp_Object text)
5195 struct Lisp_Process *p;
5196 ptrdiff_t opoint;
5198 CHECK_PROCESS (proc);
5199 p = XPROCESS (proc);
5200 CHECK_STRING (text);
5202 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5204 Lisp_Object old_read_only;
5205 ptrdiff_t old_begv, old_zv;
5206 ptrdiff_t old_begv_byte, old_zv_byte;
5207 ptrdiff_t before, before_byte;
5208 ptrdiff_t opoint_byte;
5209 struct buffer *b;
5211 Fset_buffer (p->buffer);
5212 opoint = PT;
5213 opoint_byte = PT_BYTE;
5214 old_read_only = BVAR (current_buffer, read_only);
5215 old_begv = BEGV;
5216 old_zv = ZV;
5217 old_begv_byte = BEGV_BYTE;
5218 old_zv_byte = ZV_BYTE;
5220 bset_read_only (current_buffer, Qnil);
5222 /* Insert new output into buffer at the current end-of-output
5223 marker, thus preserving logical ordering of input and output. */
5224 if (XMARKER (p->mark)->buffer)
5225 set_point_from_marker (p->mark);
5226 else
5227 SET_PT_BOTH (ZV, ZV_BYTE);
5228 before = PT;
5229 before_byte = PT_BYTE;
5231 /* If the output marker is outside of the visible region, save
5232 the restriction and widen. */
5233 if (! (BEGV <= PT && PT <= ZV))
5234 Fwiden ();
5236 /* Adjust the multibyteness of TEXT to that of the buffer. */
5237 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5238 != ! STRING_MULTIBYTE (text))
5239 text = (STRING_MULTIBYTE (text)
5240 ? Fstring_as_unibyte (text)
5241 : Fstring_to_multibyte (text));
5242 /* Insert before markers in case we are inserting where
5243 the buffer's mark is, and the user's next command is Meta-y. */
5244 insert_from_string_before_markers (text, 0, 0,
5245 SCHARS (text), SBYTES (text), 0);
5247 /* Make sure the process marker's position is valid when the
5248 process buffer is changed in the signal_after_change above.
5249 W3 is known to do that. */
5250 if (BUFFERP (p->buffer)
5251 && (b = XBUFFER (p->buffer), b != current_buffer))
5252 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5253 else
5254 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5256 update_mode_lines = 23;
5258 /* Make sure opoint and the old restrictions
5259 float ahead of any new text just as point would. */
5260 if (opoint >= before)
5262 opoint += PT - before;
5263 opoint_byte += PT_BYTE - before_byte;
5265 if (old_begv > before)
5267 old_begv += PT - before;
5268 old_begv_byte += PT_BYTE - before_byte;
5270 if (old_zv >= before)
5272 old_zv += PT - before;
5273 old_zv_byte += PT_BYTE - before_byte;
5276 /* If the restriction isn't what it should be, set it. */
5277 if (old_begv != BEGV || old_zv != ZV)
5278 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5280 bset_read_only (current_buffer, old_read_only);
5281 SET_PT_BOTH (opoint, opoint_byte);
5283 return Qnil;
5286 /* Sending data to subprocess. */
5288 /* In send_process, when a write fails temporarily,
5289 wait_reading_process_output is called. It may execute user code,
5290 e.g. timers, that attempts to write new data to the same process.
5291 We must ensure that data is sent in the right order, and not
5292 interspersed half-completed with other writes (Bug#10815). This is
5293 handled by the write_queue element of struct process. It is a list
5294 with each entry having the form
5296 (string . (offset . length))
5298 where STRING is a lisp string, OFFSET is the offset into the
5299 string's byte sequence from which we should begin to send, and
5300 LENGTH is the number of bytes left to send. */
5302 /* Create a new entry in write_queue.
5303 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5304 BUF is a pointer to the string sequence of the input_obj or a C
5305 string in case of Qt or Qnil. */
5307 static void
5308 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5309 const char *buf, ptrdiff_t len, bool front)
5311 ptrdiff_t offset;
5312 Lisp_Object entry, obj;
5314 if (STRINGP (input_obj))
5316 offset = buf - SSDATA (input_obj);
5317 obj = input_obj;
5319 else
5321 offset = 0;
5322 obj = make_unibyte_string (buf, len);
5325 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5327 if (front)
5328 pset_write_queue (p, Fcons (entry, p->write_queue));
5329 else
5330 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5333 /* Remove the first element in the write_queue of process P, put its
5334 contents in OBJ, BUF and LEN, and return true. If the
5335 write_queue is empty, return false. */
5337 static bool
5338 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5339 const char **buf, ptrdiff_t *len)
5341 Lisp_Object entry, offset_length;
5342 ptrdiff_t offset;
5344 if (NILP (p->write_queue))
5345 return 0;
5347 entry = XCAR (p->write_queue);
5348 pset_write_queue (p, XCDR (p->write_queue));
5350 *obj = XCAR (entry);
5351 offset_length = XCDR (entry);
5353 *len = XINT (XCDR (offset_length));
5354 offset = XINT (XCAR (offset_length));
5355 *buf = SSDATA (*obj) + offset;
5357 return 1;
5360 /* Send some data to process PROC.
5361 BUF is the beginning of the data; LEN is the number of characters.
5362 OBJECT is the Lisp object that the data comes from. If OBJECT is
5363 nil or t, it means that the data comes from C string.
5365 If OBJECT is not nil, the data is encoded by PROC's coding-system
5366 for encoding before it is sent.
5368 This function can evaluate Lisp code and can garbage collect. */
5370 static void
5371 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5372 Lisp_Object object)
5374 struct Lisp_Process *p = XPROCESS (proc);
5375 ssize_t rv;
5376 struct coding_system *coding;
5378 if (p->raw_status_new)
5379 update_status (p);
5380 if (! EQ (p->status, Qrun))
5381 error ("Process %s not running", SDATA (p->name));
5382 if (p->outfd < 0)
5383 error ("Output file descriptor of %s is closed", SDATA (p->name));
5385 coding = proc_encode_coding_system[p->outfd];
5386 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5388 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5389 || (BUFFERP (object)
5390 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5391 || EQ (object, Qt))
5393 pset_encode_coding_system
5394 (p, complement_process_encoding_system (p->encode_coding_system));
5395 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5397 /* The coding system for encoding was changed to raw-text
5398 because we sent a unibyte text previously. Now we are
5399 sending a multibyte text, thus we must encode it by the
5400 original coding system specified for the current process.
5402 Another reason we come here is that the coding system
5403 was just complemented and a new one was returned by
5404 complement_process_encoding_system. */
5405 setup_coding_system (p->encode_coding_system, coding);
5406 Vlast_coding_system_used = p->encode_coding_system;
5408 coding->src_multibyte = 1;
5410 else
5412 coding->src_multibyte = 0;
5413 /* For sending a unibyte text, character code conversion should
5414 not take place but EOL conversion should. So, setup raw-text
5415 or one of the subsidiary if we have not yet done it. */
5416 if (CODING_REQUIRE_ENCODING (coding))
5418 if (CODING_REQUIRE_FLUSHING (coding))
5420 /* But, before changing the coding, we must flush out data. */
5421 coding->mode |= CODING_MODE_LAST_BLOCK;
5422 send_process (proc, "", 0, Qt);
5423 coding->mode &= CODING_MODE_LAST_BLOCK;
5425 setup_coding_system (raw_text_coding_system
5426 (Vlast_coding_system_used),
5427 coding);
5428 coding->src_multibyte = 0;
5431 coding->dst_multibyte = 0;
5433 if (CODING_REQUIRE_ENCODING (coding))
5435 coding->dst_object = Qt;
5436 if (BUFFERP (object))
5438 ptrdiff_t from_byte, from, to;
5439 ptrdiff_t save_pt, save_pt_byte;
5440 struct buffer *cur = current_buffer;
5442 set_buffer_internal (XBUFFER (object));
5443 save_pt = PT, save_pt_byte = PT_BYTE;
5445 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5446 from = BYTE_TO_CHAR (from_byte);
5447 to = BYTE_TO_CHAR (from_byte + len);
5448 TEMP_SET_PT_BOTH (from, from_byte);
5449 encode_coding_object (coding, object, from, from_byte,
5450 to, from_byte + len, Qt);
5451 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5452 set_buffer_internal (cur);
5454 else if (STRINGP (object))
5456 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5457 SBYTES (object), Qt);
5459 else
5461 coding->dst_object = make_unibyte_string (buf, len);
5462 coding->produced = len;
5465 len = coding->produced;
5466 object = coding->dst_object;
5467 buf = SSDATA (object);
5470 /* If there is already data in the write_queue, put the new data
5471 in the back of queue. Otherwise, ignore it. */
5472 if (!NILP (p->write_queue))
5473 write_queue_push (p, object, buf, len, 0);
5475 do /* while !NILP (p->write_queue) */
5477 ptrdiff_t cur_len = -1;
5478 const char *cur_buf;
5479 Lisp_Object cur_object;
5481 /* If write_queue is empty, ignore it. */
5482 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5484 cur_len = len;
5485 cur_buf = buf;
5486 cur_object = object;
5489 while (cur_len > 0)
5491 /* Send this batch, using one or more write calls. */
5492 ptrdiff_t written = 0;
5493 int outfd = p->outfd;
5494 #ifdef DATAGRAM_SOCKETS
5495 if (DATAGRAM_CHAN_P (outfd))
5497 rv = sendto (outfd, cur_buf, cur_len,
5498 0, datagram_address[outfd].sa,
5499 datagram_address[outfd].len);
5500 if (rv >= 0)
5501 written = rv;
5502 else if (errno == EMSGSIZE)
5503 report_file_error ("Sending datagram", proc);
5505 else
5506 #endif
5508 #ifdef HAVE_GNUTLS
5509 if (p->gnutls_p && p->gnutls_state)
5510 written = emacs_gnutls_write (p, cur_buf, cur_len);
5511 else
5512 #endif
5513 written = emacs_write_sig (outfd, cur_buf, cur_len);
5514 rv = (written ? 0 : -1);
5515 #ifdef ADAPTIVE_READ_BUFFERING
5516 if (p->read_output_delay > 0
5517 && p->adaptive_read_buffering == 1)
5519 p->read_output_delay = 0;
5520 process_output_delay_count--;
5521 p->read_output_skip = 0;
5523 #endif
5526 if (rv < 0)
5528 if (errno == EAGAIN
5529 #ifdef EWOULDBLOCK
5530 || errno == EWOULDBLOCK
5531 #endif
5533 /* Buffer is full. Wait, accepting input;
5534 that may allow the program
5535 to finish doing output and read more. */
5537 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5538 /* A gross hack to work around a bug in FreeBSD.
5539 In the following sequence, read(2) returns
5540 bogus data:
5542 write(2) 1022 bytes
5543 write(2) 954 bytes, get EAGAIN
5544 read(2) 1024 bytes in process_read_output
5545 read(2) 11 bytes in process_read_output
5547 That is, read(2) returns more bytes than have
5548 ever been written successfully. The 1033 bytes
5549 read are the 1022 bytes written successfully
5550 after processing (for example with CRs added if
5551 the terminal is set up that way which it is
5552 here). The same bytes will be seen again in a
5553 later read(2), without the CRs. */
5555 if (errno == EAGAIN)
5557 int flags = FWRITE;
5558 ioctl (p->outfd, TIOCFLUSH, &flags);
5560 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5562 /* Put what we should have written in wait_queue. */
5563 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5564 wait_reading_process_output (0, 20 * 1000 * 1000,
5565 0, 0, Qnil, NULL, 0);
5566 /* Reread queue, to see what is left. */
5567 break;
5569 else if (errno == EPIPE)
5571 p->raw_status_new = 0;
5572 pset_status (p, list2 (Qexit, make_number (256)));
5573 p->tick = ++process_tick;
5574 deactivate_process (proc);
5575 error ("process %s no longer connected to pipe; closed it",
5576 SDATA (p->name));
5578 else
5579 /* This is a real error. */
5580 report_file_error ("Writing to process", proc);
5582 cur_buf += written;
5583 cur_len -= written;
5586 while (!NILP (p->write_queue));
5589 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5590 3, 3, 0,
5591 doc: /* Send current contents of region as input to PROCESS.
5592 PROCESS may be a process, a buffer, the name of a process or buffer, or
5593 nil, indicating the current buffer's process.
5594 Called from program, takes three arguments, PROCESS, START and END.
5595 If the region is more than 500 characters long,
5596 it is sent in several bunches. This may happen even for shorter regions.
5597 Output from processes can arrive in between bunches. */)
5598 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5600 Lisp_Object proc = get_process (process);
5601 ptrdiff_t start_byte, end_byte;
5603 validate_region (&start, &end);
5605 start_byte = CHAR_TO_BYTE (XINT (start));
5606 end_byte = CHAR_TO_BYTE (XINT (end));
5608 if (XINT (start) < GPT && XINT (end) > GPT)
5609 move_gap_both (XINT (start), start_byte);
5611 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5612 end_byte - start_byte, Fcurrent_buffer ());
5614 return Qnil;
5617 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5618 2, 2, 0,
5619 doc: /* Send PROCESS the contents of STRING as input.
5620 PROCESS may be a process, a buffer, the name of a process or buffer, or
5621 nil, indicating the current buffer's process.
5622 If STRING is more than 500 characters long,
5623 it is sent in several bunches. This may happen even for shorter strings.
5624 Output from processes can arrive in between bunches. */)
5625 (Lisp_Object process, Lisp_Object string)
5627 Lisp_Object proc;
5628 CHECK_STRING (string);
5629 proc = get_process (process);
5630 send_process (proc, SSDATA (string),
5631 SBYTES (string), string);
5632 return Qnil;
5635 /* Return the foreground process group for the tty/pty that
5636 the process P uses. */
5637 static pid_t
5638 emacs_get_tty_pgrp (struct Lisp_Process *p)
5640 pid_t gid = -1;
5642 #ifdef TIOCGPGRP
5643 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5645 int fd;
5646 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5647 master side. Try the slave side. */
5648 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5650 if (fd != -1)
5652 ioctl (fd, TIOCGPGRP, &gid);
5653 emacs_close (fd);
5656 #endif /* defined (TIOCGPGRP ) */
5658 return gid;
5661 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5662 Sprocess_running_child_p, 0, 1, 0,
5663 doc: /* Return t if PROCESS has given the terminal to a child.
5664 If the operating system does not make it possible to find out,
5665 return t unconditionally. */)
5666 (Lisp_Object process)
5668 /* Initialize in case ioctl doesn't exist or gives an error,
5669 in a way that will cause returning t. */
5670 pid_t gid;
5671 Lisp_Object proc;
5672 struct Lisp_Process *p;
5674 proc = get_process (process);
5675 p = XPROCESS (proc);
5677 if (!EQ (p->type, Qreal))
5678 error ("Process %s is not a subprocess",
5679 SDATA (p->name));
5680 if (p->infd < 0)
5681 error ("Process %s is not active",
5682 SDATA (p->name));
5684 gid = emacs_get_tty_pgrp (p);
5686 if (gid == p->pid)
5687 return Qnil;
5688 return Qt;
5691 /* send a signal number SIGNO to PROCESS.
5692 If CURRENT_GROUP is t, that means send to the process group
5693 that currently owns the terminal being used to communicate with PROCESS.
5694 This is used for various commands in shell mode.
5695 If CURRENT_GROUP is lambda, that means send to the process group
5696 that currently owns the terminal, but only if it is NOT the shell itself.
5698 If NOMSG is false, insert signal-announcements into process's buffers
5699 right away.
5701 If we can, we try to signal PROCESS by sending control characters
5702 down the pty. This allows us to signal inferiors who have changed
5703 their uid, for which kill would return an EPERM error. */
5705 static void
5706 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5707 bool nomsg)
5709 Lisp_Object proc;
5710 struct Lisp_Process *p;
5711 pid_t gid;
5712 bool no_pgrp = 0;
5714 proc = get_process (process);
5715 p = XPROCESS (proc);
5717 if (!EQ (p->type, Qreal))
5718 error ("Process %s is not a subprocess",
5719 SDATA (p->name));
5720 if (p->infd < 0)
5721 error ("Process %s is not active",
5722 SDATA (p->name));
5724 if (!p->pty_flag)
5725 current_group = Qnil;
5727 /* If we are using pgrps, get a pgrp number and make it negative. */
5728 if (NILP (current_group))
5729 /* Send the signal to the shell's process group. */
5730 gid = p->pid;
5731 else
5733 #ifdef SIGNALS_VIA_CHARACTERS
5734 /* If possible, send signals to the entire pgrp
5735 by sending an input character to it. */
5737 struct termios t;
5738 cc_t *sig_char = NULL;
5740 tcgetattr (p->infd, &t);
5742 switch (signo)
5744 case SIGINT:
5745 sig_char = &t.c_cc[VINTR];
5746 break;
5748 case SIGQUIT:
5749 sig_char = &t.c_cc[VQUIT];
5750 break;
5752 case SIGTSTP:
5753 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5754 sig_char = &t.c_cc[VSWTCH];
5755 #else
5756 sig_char = &t.c_cc[VSUSP];
5757 #endif
5758 break;
5761 if (sig_char && *sig_char != CDISABLE)
5763 send_process (proc, (char *) sig_char, 1, Qnil);
5764 return;
5766 /* If we can't send the signal with a character,
5767 fall through and send it another way. */
5769 /* The code above may fall through if it can't
5770 handle the signal. */
5771 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5773 #ifdef TIOCGPGRP
5774 /* Get the current pgrp using the tty itself, if we have that.
5775 Otherwise, use the pty to get the pgrp.
5776 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5777 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5778 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5779 His patch indicates that if TIOCGPGRP returns an error, then
5780 we should just assume that p->pid is also the process group id. */
5782 gid = emacs_get_tty_pgrp (p);
5784 if (gid == -1)
5785 /* If we can't get the information, assume
5786 the shell owns the tty. */
5787 gid = p->pid;
5789 /* It is not clear whether anything really can set GID to -1.
5790 Perhaps on some system one of those ioctls can or could do so.
5791 Or perhaps this is vestigial. */
5792 if (gid == -1)
5793 no_pgrp = 1;
5794 #else /* ! defined (TIOCGPGRP ) */
5795 /* Can't select pgrps on this system, so we know that
5796 the child itself heads the pgrp. */
5797 gid = p->pid;
5798 #endif /* ! defined (TIOCGPGRP ) */
5800 /* If current_group is lambda, and the shell owns the terminal,
5801 don't send any signal. */
5802 if (EQ (current_group, Qlambda) && gid == p->pid)
5803 return;
5806 #ifdef SIGCONT
5807 if (signo == SIGCONT)
5809 p->raw_status_new = 0;
5810 pset_status (p, Qrun);
5811 p->tick = ++process_tick;
5812 if (!nomsg)
5814 status_notify (NULL, NULL);
5815 redisplay_preserve_echo_area (13);
5818 #endif
5820 #ifdef TIOCSIGSEND
5821 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5822 We don't know whether the bug is fixed in later HP-UX versions. */
5823 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
5824 return;
5825 #endif
5827 /* If we don't have process groups, send the signal to the immediate
5828 subprocess. That isn't really right, but it's better than any
5829 obvious alternative. */
5830 pid_t pid = no_pgrp ? gid : - gid;
5832 /* Do not kill an already-reaped process, as that could kill an
5833 innocent bystander that happens to have the same process ID. */
5834 sigset_t oldset;
5835 block_child_signal (&oldset);
5836 if (p->alive)
5837 kill (pid, signo);
5838 unblock_child_signal (&oldset);
5841 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5842 doc: /* Interrupt process PROCESS.
5843 PROCESS may be a process, a buffer, or the name of a process or buffer.
5844 No arg or nil means current buffer's process.
5845 Second arg CURRENT-GROUP non-nil means send signal to
5846 the current process-group of the process's controlling terminal
5847 rather than to the process's own process group.
5848 If the process is a shell, this means interrupt current subjob
5849 rather than the shell.
5851 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5852 don't send the signal. */)
5853 (Lisp_Object process, Lisp_Object current_group)
5855 process_send_signal (process, SIGINT, current_group, 0);
5856 return process;
5859 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5860 doc: /* Kill process PROCESS. May be process or name of one.
5861 See function `interrupt-process' for more details on usage. */)
5862 (Lisp_Object process, Lisp_Object current_group)
5864 process_send_signal (process, SIGKILL, current_group, 0);
5865 return process;
5868 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5869 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5870 See function `interrupt-process' for more details on usage. */)
5871 (Lisp_Object process, Lisp_Object current_group)
5873 process_send_signal (process, SIGQUIT, current_group, 0);
5874 return process;
5877 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5878 doc: /* Stop process PROCESS. May be process or name of one.
5879 See function `interrupt-process' for more details on usage.
5880 If PROCESS is a network or serial process, inhibit handling of incoming
5881 traffic. */)
5882 (Lisp_Object process, Lisp_Object current_group)
5884 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5886 struct Lisp_Process *p;
5888 p = XPROCESS (process);
5889 if (NILP (p->command)
5890 && p->infd >= 0)
5892 FD_CLR (p->infd, &input_wait_mask);
5893 FD_CLR (p->infd, &non_keyboard_wait_mask);
5895 pset_command (p, Qt);
5896 return process;
5898 #ifndef SIGTSTP
5899 error ("No SIGTSTP support");
5900 #else
5901 process_send_signal (process, SIGTSTP, current_group, 0);
5902 #endif
5903 return process;
5906 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5907 doc: /* Continue process PROCESS. May be process or name of one.
5908 See function `interrupt-process' for more details on usage.
5909 If PROCESS is a network or serial process, resume handling of incoming
5910 traffic. */)
5911 (Lisp_Object process, Lisp_Object current_group)
5913 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5915 struct Lisp_Process *p;
5917 p = XPROCESS (process);
5918 if (EQ (p->command, Qt)
5919 && p->infd >= 0
5920 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5922 FD_SET (p->infd, &input_wait_mask);
5923 FD_SET (p->infd, &non_keyboard_wait_mask);
5924 #ifdef WINDOWSNT
5925 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5926 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5927 #else /* not WINDOWSNT */
5928 tcflush (p->infd, TCIFLUSH);
5929 #endif /* not WINDOWSNT */
5931 pset_command (p, Qnil);
5932 return process;
5934 #ifdef SIGCONT
5935 process_send_signal (process, SIGCONT, current_group, 0);
5936 #else
5937 error ("No SIGCONT support");
5938 #endif
5939 return process;
5942 /* Return the integer value of the signal whose abbreviation is ABBR,
5943 or a negative number if there is no such signal. */
5944 static int
5945 abbr_to_signal (char const *name)
5947 int i, signo;
5948 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5950 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5951 name += 3;
5953 for (i = 0; i < sizeof sigbuf; i++)
5955 sigbuf[i] = c_toupper (name[i]);
5956 if (! sigbuf[i])
5957 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5960 return -1;
5963 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5964 2, 2, "sProcess (name or number): \nnSignal code: ",
5965 doc: /* Send PROCESS the signal with code SIGCODE.
5966 PROCESS may also be a number specifying the process id of the
5967 process to signal; in this case, the process need not be a child of
5968 this Emacs.
5969 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5970 (Lisp_Object process, Lisp_Object sigcode)
5972 pid_t pid;
5973 int signo;
5975 if (STRINGP (process))
5977 Lisp_Object tem = Fget_process (process);
5978 if (NILP (tem))
5980 Lisp_Object process_number =
5981 string_to_number (SSDATA (process), 10, 1);
5982 if (INTEGERP (process_number) || FLOATP (process_number))
5983 tem = process_number;
5985 process = tem;
5987 else if (!NUMBERP (process))
5988 process = get_process (process);
5990 if (NILP (process))
5991 return process;
5993 if (NUMBERP (process))
5994 CONS_TO_INTEGER (process, pid_t, pid);
5995 else
5997 CHECK_PROCESS (process);
5998 pid = XPROCESS (process)->pid;
5999 if (pid <= 0)
6000 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6003 if (INTEGERP (sigcode))
6005 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6006 signo = XINT (sigcode);
6008 else
6010 char *name;
6012 CHECK_SYMBOL (sigcode);
6013 name = SSDATA (SYMBOL_NAME (sigcode));
6015 signo = abbr_to_signal (name);
6016 if (signo < 0)
6017 error ("Undefined signal name %s", name);
6020 return make_number (kill (pid, signo));
6023 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6024 doc: /* Make PROCESS see end-of-file in its input.
6025 EOF comes after any text already sent to it.
6026 PROCESS may be a process, a buffer, the name of a process or buffer, or
6027 nil, indicating the current buffer's process.
6028 If PROCESS is a network connection, or is a process communicating
6029 through a pipe (as opposed to a pty), then you cannot send any more
6030 text to PROCESS after you call this function.
6031 If PROCESS is a serial process, wait until all output written to the
6032 process has been transmitted to the serial port. */)
6033 (Lisp_Object process)
6035 Lisp_Object proc;
6036 struct coding_system *coding = NULL;
6037 int outfd;
6039 if (DATAGRAM_CONN_P (process))
6040 return process;
6042 proc = get_process (process);
6043 outfd = XPROCESS (proc)->outfd;
6044 if (outfd >= 0)
6045 coding = proc_encode_coding_system[outfd];
6047 /* Make sure the process is really alive. */
6048 if (XPROCESS (proc)->raw_status_new)
6049 update_status (XPROCESS (proc));
6050 if (! EQ (XPROCESS (proc)->status, Qrun))
6051 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6053 if (coding && CODING_REQUIRE_FLUSHING (coding))
6055 coding->mode |= CODING_MODE_LAST_BLOCK;
6056 send_process (proc, "", 0, Qnil);
6059 if (XPROCESS (proc)->pty_flag)
6060 send_process (proc, "\004", 1, Qnil);
6061 else if (EQ (XPROCESS (proc)->type, Qserial))
6063 #ifndef WINDOWSNT
6064 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6065 report_file_error ("Failed tcdrain", Qnil);
6066 #endif /* not WINDOWSNT */
6067 /* Do nothing on Windows because writes are blocking. */
6069 else
6071 struct Lisp_Process *p = XPROCESS (proc);
6072 int old_outfd = p->outfd;
6073 int new_outfd;
6075 #ifdef HAVE_SHUTDOWN
6076 /* If this is a network connection, or socketpair is used
6077 for communication with the subprocess, call shutdown to cause EOF.
6078 (In some old system, shutdown to socketpair doesn't work.
6079 Then we just can't win.) */
6080 if (0 <= old_outfd
6081 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6082 shutdown (old_outfd, 1);
6083 #endif
6084 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6085 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6086 if (new_outfd < 0)
6087 report_file_error ("Opening null device", Qnil);
6088 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6089 p->outfd = new_outfd;
6091 if (!proc_encode_coding_system[new_outfd])
6092 proc_encode_coding_system[new_outfd]
6093 = xmalloc (sizeof (struct coding_system));
6094 if (old_outfd >= 0)
6096 *proc_encode_coding_system[new_outfd]
6097 = *proc_encode_coding_system[old_outfd];
6098 memset (proc_encode_coding_system[old_outfd], 0,
6099 sizeof (struct coding_system));
6101 else
6102 setup_coding_system (p->encode_coding_system,
6103 proc_encode_coding_system[new_outfd]);
6105 return process;
6108 /* The main Emacs thread records child processes in three places:
6110 - Vprocess_alist, for asynchronous subprocesses, which are child
6111 processes visible to Lisp.
6113 - deleted_pid_list, for child processes invisible to Lisp,
6114 typically because of delete-process. These are recorded so that
6115 the processes can be reaped when they exit, so that the operating
6116 system's process table is not cluttered by zombies.
6118 - the local variable PID in Fcall_process, call_process_cleanup and
6119 call_process_kill, for synchronous subprocesses.
6120 record_unwind_protect is used to make sure this process is not
6121 forgotten: if the user interrupts call-process and the child
6122 process refuses to exit immediately even with two C-g's,
6123 call_process_kill adds PID's contents to deleted_pid_list before
6124 returning.
6126 The main Emacs thread invokes waitpid only on child processes that
6127 it creates and that have not been reaped. This avoid races on
6128 platforms such as GTK, where other threads create their own
6129 subprocesses which the main thread should not reap. For example,
6130 if the main thread attempted to reap an already-reaped child, it
6131 might inadvertently reap a GTK-created process that happened to
6132 have the same process ID. */
6134 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6135 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6136 keep track of its own children. GNUstep is similar. */
6138 static void dummy_handler (int sig) {}
6139 static signal_handler_t volatile lib_child_handler;
6141 /* Handle a SIGCHLD signal by looking for known child processes of
6142 Emacs whose status have changed. For each one found, record its
6143 new status.
6145 All we do is change the status; we do not run sentinels or print
6146 notifications. That is saved for the next time keyboard input is
6147 done, in order to avoid timing errors.
6149 ** WARNING: this can be called during garbage collection.
6150 Therefore, it must not be fooled by the presence of mark bits in
6151 Lisp objects.
6153 ** USG WARNING: Although it is not obvious from the documentation
6154 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6155 signal() before executing at least one wait(), otherwise the
6156 handler will be called again, resulting in an infinite loop. The
6157 relevant portion of the documentation reads "SIGCLD signals will be
6158 queued and the signal-catching function will be continually
6159 reentered until the queue is empty". Invoking signal() causes the
6160 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6161 Inc.
6163 ** Malloc WARNING: This should never call malloc either directly or
6164 indirectly; if it does, that is a bug */
6166 static void
6167 handle_child_signal (int sig)
6169 Lisp_Object tail, proc;
6171 /* Find the process that signaled us, and record its status. */
6173 /* The process can have been deleted by Fdelete_process, or have
6174 been started asynchronously by Fcall_process. */
6175 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6177 bool all_pids_are_fixnums
6178 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6179 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6180 Lisp_Object head = XCAR (tail);
6181 Lisp_Object xpid;
6182 if (! CONSP (head))
6183 continue;
6184 xpid = XCAR (head);
6185 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6187 pid_t deleted_pid;
6188 if (INTEGERP (xpid))
6189 deleted_pid = XINT (xpid);
6190 else
6191 deleted_pid = XFLOAT_DATA (xpid);
6192 if (child_status_changed (deleted_pid, 0, 0))
6194 if (STRINGP (XCDR (head)))
6195 unlink (SSDATA (XCDR (head)));
6196 XSETCAR (tail, Qnil);
6201 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6202 FOR_EACH_PROCESS (tail, proc)
6204 struct Lisp_Process *p = XPROCESS (proc);
6205 int status;
6207 if (p->alive
6208 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6210 /* Change the status of the process that was found. */
6211 p->tick = ++process_tick;
6212 p->raw_status = status;
6213 p->raw_status_new = 1;
6215 /* If process has terminated, stop waiting for its output. */
6216 if (WIFSIGNALED (status) || WIFEXITED (status))
6218 bool clear_desc_flag = 0;
6219 p->alive = 0;
6220 if (p->infd >= 0)
6221 clear_desc_flag = 1;
6223 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6224 if (clear_desc_flag)
6226 FD_CLR (p->infd, &input_wait_mask);
6227 FD_CLR (p->infd, &non_keyboard_wait_mask);
6233 lib_child_handler (sig);
6234 #ifdef NS_IMPL_GNUSTEP
6235 /* NSTask in GNUstep sets its child handler each time it is called.
6236 So we must re-set ours. */
6237 catch_child_signal();
6238 #endif
6241 static void
6242 deliver_child_signal (int sig)
6244 deliver_process_signal (sig, handle_child_signal);
6248 static Lisp_Object
6249 exec_sentinel_error_handler (Lisp_Object error_val)
6251 cmd_error_internal (error_val, "error in process sentinel: ");
6252 Vinhibit_quit = Qt;
6253 update_echo_area ();
6254 Fsleep_for (make_number (2), Qnil);
6255 return Qt;
6258 static void
6259 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6261 Lisp_Object sentinel, odeactivate;
6262 struct Lisp_Process *p = XPROCESS (proc);
6263 ptrdiff_t count = SPECPDL_INDEX ();
6264 bool outer_running_asynch_code = running_asynch_code;
6265 int waiting = waiting_for_user_input_p;
6267 if (inhibit_sentinels)
6268 return;
6270 /* No need to gcpro these, because all we do with them later
6271 is test them for EQness, and none of them should be a string. */
6272 odeactivate = Vdeactivate_mark;
6273 #if 0
6274 Lisp_Object obuffer, okeymap;
6275 XSETBUFFER (obuffer, current_buffer);
6276 okeymap = BVAR (current_buffer, keymap);
6277 #endif
6279 /* There's no good reason to let sentinels change the current
6280 buffer, and many callers of accept-process-output, sit-for, and
6281 friends don't expect current-buffer to be changed from under them. */
6282 record_unwind_current_buffer ();
6284 sentinel = p->sentinel;
6286 /* Inhibit quit so that random quits don't screw up a running filter. */
6287 specbind (Qinhibit_quit, Qt);
6288 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6290 /* In case we get recursively called,
6291 and we already saved the match data nonrecursively,
6292 save the same match data in safely recursive fashion. */
6293 if (outer_running_asynch_code)
6295 Lisp_Object tem;
6296 tem = Fmatch_data (Qnil, Qnil, Qnil);
6297 restore_search_regs ();
6298 record_unwind_save_match_data ();
6299 Fset_match_data (tem, Qt);
6302 /* For speed, if a search happens within this code,
6303 save the match data in a special nonrecursive fashion. */
6304 running_asynch_code = 1;
6306 internal_condition_case_1 (read_process_output_call,
6307 list3 (sentinel, proc, reason),
6308 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6309 exec_sentinel_error_handler);
6311 /* If we saved the match data nonrecursively, restore it now. */
6312 restore_search_regs ();
6313 running_asynch_code = outer_running_asynch_code;
6315 Vdeactivate_mark = odeactivate;
6317 /* Restore waiting_for_user_input_p as it was
6318 when we were called, in case the filter clobbered it. */
6319 waiting_for_user_input_p = waiting;
6321 #if 0
6322 if (! EQ (Fcurrent_buffer (), obuffer)
6323 || ! EQ (current_buffer->keymap, okeymap))
6324 #endif
6325 /* But do it only if the caller is actually going to read events.
6326 Otherwise there's no need to make him wake up, and it could
6327 cause trouble (for example it would make sit_for return). */
6328 if (waiting_for_user_input_p == -1)
6329 record_asynch_buffer_change ();
6331 unbind_to (count, Qnil);
6334 /* Report all recent events of a change in process status
6335 (either run the sentinel or output a message).
6336 This is usually done while Emacs is waiting for keyboard input
6337 but can be done at other times.
6339 Return positive if any input was received from WAIT_PROC (or from
6340 any process if WAIT_PROC is null), zero if input was attempted but
6341 none received, and negative if we didn't even try. */
6343 static int
6344 status_notify (struct Lisp_Process *deleting_process,
6345 struct Lisp_Process *wait_proc)
6347 Lisp_Object proc;
6348 Lisp_Object tail, msg;
6349 struct gcpro gcpro1, gcpro2;
6350 int got_some_input = -1;
6352 tail = Qnil;
6353 msg = Qnil;
6354 /* We need to gcpro tail; if read_process_output calls a filter
6355 which deletes a process and removes the cons to which tail points
6356 from Vprocess_alist, and then causes a GC, tail is an unprotected
6357 reference. */
6358 GCPRO2 (tail, msg);
6360 /* Set this now, so that if new processes are created by sentinels
6361 that we run, we get called again to handle their status changes. */
6362 update_tick = process_tick;
6364 FOR_EACH_PROCESS (tail, proc)
6366 Lisp_Object symbol;
6367 register struct Lisp_Process *p = XPROCESS (proc);
6369 if (p->tick != p->update_tick)
6371 p->update_tick = p->tick;
6373 /* If process is still active, read any output that remains. */
6374 while (! EQ (p->filter, Qt)
6375 && ! EQ (p->status, Qconnect)
6376 && ! EQ (p->status, Qlisten)
6377 /* Network or serial process not stopped: */
6378 && ! EQ (p->command, Qt)
6379 && p->infd >= 0
6380 && p != deleting_process)
6382 int nread = read_process_output (proc, p->infd);
6383 if (got_some_input < nread)
6384 got_some_input = nread;
6385 if (nread <= 0)
6386 break;
6389 /* Get the text to use for the message. */
6390 if (p->raw_status_new)
6391 update_status (p);
6392 msg = status_message (p);
6394 /* If process is terminated, deactivate it or delete it. */
6395 symbol = p->status;
6396 if (CONSP (p->status))
6397 symbol = XCAR (p->status);
6399 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6400 || EQ (symbol, Qclosed))
6402 if (delete_exited_processes)
6403 remove_process (proc);
6404 else
6405 deactivate_process (proc);
6408 /* The actions above may have further incremented p->tick.
6409 So set p->update_tick again so that an error in the sentinel will
6410 not cause this code to be run again. */
6411 p->update_tick = p->tick;
6412 /* Now output the message suitably. */
6413 exec_sentinel (proc, msg);
6415 } /* end for */
6417 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6418 UNGCPRO;
6419 return got_some_input;
6422 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6423 Sinternal_default_process_sentinel, 2, 2, 0,
6424 doc: /* Function used as default sentinel for processes.
6425 This inserts a status message into the process's buffer, if there is one. */)
6426 (Lisp_Object proc, Lisp_Object msg)
6428 Lisp_Object buffer, symbol;
6429 struct Lisp_Process *p;
6430 CHECK_PROCESS (proc);
6431 p = XPROCESS (proc);
6432 buffer = p->buffer;
6433 symbol = p->status;
6434 if (CONSP (symbol))
6435 symbol = XCAR (symbol);
6437 if (!EQ (symbol, Qrun) && !NILP (buffer))
6439 Lisp_Object tem;
6440 struct buffer *old = current_buffer;
6441 ptrdiff_t opoint, opoint_byte;
6442 ptrdiff_t before, before_byte;
6444 /* Avoid error if buffer is deleted
6445 (probably that's why the process is dead, too). */
6446 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6447 return Qnil;
6448 Fset_buffer (buffer);
6450 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6451 msg = (code_convert_string_norecord
6452 (msg, Vlocale_coding_system, 1));
6454 opoint = PT;
6455 opoint_byte = PT_BYTE;
6456 /* Insert new output into buffer
6457 at the current end-of-output marker,
6458 thus preserving logical ordering of input and output. */
6459 if (XMARKER (p->mark)->buffer)
6460 Fgoto_char (p->mark);
6461 else
6462 SET_PT_BOTH (ZV, ZV_BYTE);
6464 before = PT;
6465 before_byte = PT_BYTE;
6467 tem = BVAR (current_buffer, read_only);
6468 bset_read_only (current_buffer, Qnil);
6469 insert_string ("\nProcess ");
6470 { /* FIXME: temporary kludge. */
6471 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6472 insert_string (" ");
6473 Finsert (1, &msg);
6474 bset_read_only (current_buffer, tem);
6475 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6477 if (opoint >= before)
6478 SET_PT_BOTH (opoint + (PT - before),
6479 opoint_byte + (PT_BYTE - before_byte));
6480 else
6481 SET_PT_BOTH (opoint, opoint_byte);
6483 set_buffer_internal (old);
6485 return Qnil;
6489 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6490 Sset_process_coding_system, 1, 3, 0,
6491 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6492 DECODING will be used to decode subprocess output and ENCODING to
6493 encode subprocess input. */)
6494 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6496 register struct Lisp_Process *p;
6498 CHECK_PROCESS (process);
6499 p = XPROCESS (process);
6500 if (p->infd < 0)
6501 error ("Input file descriptor of %s closed", SDATA (p->name));
6502 if (p->outfd < 0)
6503 error ("Output file descriptor of %s closed", SDATA (p->name));
6504 Fcheck_coding_system (decoding);
6505 Fcheck_coding_system (encoding);
6506 encoding = coding_inherit_eol_type (encoding, Qnil);
6507 pset_decode_coding_system (p, decoding);
6508 pset_encode_coding_system (p, encoding);
6509 setup_process_coding_systems (process);
6511 return Qnil;
6514 DEFUN ("process-coding-system",
6515 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6516 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6517 (register Lisp_Object process)
6519 CHECK_PROCESS (process);
6520 return Fcons (XPROCESS (process)->decode_coding_system,
6521 XPROCESS (process)->encode_coding_system);
6524 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6525 Sset_process_filter_multibyte, 2, 2, 0,
6526 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6527 If FLAG is non-nil, the filter is given multibyte strings.
6528 If FLAG is nil, the filter is given unibyte strings. In this case,
6529 all character code conversion except for end-of-line conversion is
6530 suppressed. */)
6531 (Lisp_Object process, Lisp_Object flag)
6533 register struct Lisp_Process *p;
6535 CHECK_PROCESS (process);
6536 p = XPROCESS (process);
6537 if (NILP (flag))
6538 pset_decode_coding_system
6539 (p, raw_text_coding_system (p->decode_coding_system));
6540 setup_process_coding_systems (process);
6542 return Qnil;
6545 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6546 Sprocess_filter_multibyte_p, 1, 1, 0,
6547 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6548 (Lisp_Object process)
6550 register struct Lisp_Process *p;
6551 struct coding_system *coding;
6553 CHECK_PROCESS (process);
6554 p = XPROCESS (process);
6555 if (p->infd < 0)
6556 return Qnil;
6557 coding = proc_decode_coding_system[p->infd];
6558 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6564 # ifdef HAVE_GPM
6566 void
6567 add_gpm_wait_descriptor (int desc)
6569 add_keyboard_wait_descriptor (desc);
6572 void
6573 delete_gpm_wait_descriptor (int desc)
6575 delete_keyboard_wait_descriptor (desc);
6578 # endif
6580 # ifdef USABLE_SIGIO
6582 /* Return true if *MASK has a bit set
6583 that corresponds to one of the keyboard input descriptors. */
6585 static bool
6586 keyboard_bit_set (fd_set *mask)
6588 int fd;
6590 for (fd = 0; fd <= max_input_desc; fd++)
6591 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6592 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6593 return 1;
6595 return 0;
6597 # endif
6599 #else /* not subprocesses */
6601 /* Defined in msdos.c. */
6602 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6603 struct timespec *, void *);
6605 /* Implementation of wait_reading_process_output, assuming that there
6606 are no subprocesses. Used only by the MS-DOS build.
6608 Wait for timeout to elapse and/or keyboard input to be available.
6610 TIME_LIMIT is:
6611 timeout in seconds
6612 If negative, gobble data immediately available but don't wait for any.
6614 NSECS is:
6615 an additional duration to wait, measured in nanoseconds
6616 If TIME_LIMIT is zero, then:
6617 If NSECS == 0, there is no limit.
6618 If NSECS > 0, the timeout consists of NSECS only.
6619 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6621 READ_KBD is:
6622 0 to ignore keyboard input, or
6623 1 to return when input is available, or
6624 -1 means caller will actually read the input, so don't throw to
6625 the quit handler.
6627 see full version for other parameters. We know that wait_proc will
6628 always be NULL, since `subprocesses' isn't defined.
6630 DO_DISPLAY means redisplay should be done to show subprocess
6631 output that arrives.
6633 Return positive if we received input from WAIT_PROC (or from any
6634 process if WAIT_PROC is null), zero if we attempted to receive
6635 input but got none, and negative if we didn't even try. */
6638 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6639 bool do_display,
6640 Lisp_Object wait_for_cell,
6641 struct Lisp_Process *wait_proc, int just_wait_proc)
6643 register int nfds;
6644 struct timespec end_time, timeout;
6646 if (time_limit < 0)
6648 time_limit = 0;
6649 nsecs = -1;
6651 else if (TYPE_MAXIMUM (time_t) < time_limit)
6652 time_limit = TYPE_MAXIMUM (time_t);
6654 /* What does time_limit really mean? */
6655 if (time_limit || nsecs > 0)
6657 timeout = make_timespec (time_limit, nsecs);
6658 end_time = timespec_add (current_timespec (), timeout);
6661 /* Turn off periodic alarms (in case they are in use)
6662 and then turn off any other atimers,
6663 because the select emulator uses alarms. */
6664 stop_polling ();
6665 turn_on_atimers (0);
6667 while (1)
6669 bool timeout_reduced_for_timers = 0;
6670 fd_set waitchannels;
6671 int xerrno;
6673 /* If calling from keyboard input, do not quit
6674 since we want to return C-g as an input character.
6675 Otherwise, do pending quit if requested. */
6676 if (read_kbd >= 0)
6677 QUIT;
6679 /* Exit now if the cell we're waiting for became non-nil. */
6680 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6681 break;
6683 /* Compute time from now till when time limit is up. */
6684 /* Exit if already run out. */
6685 if (nsecs < 0)
6687 /* A negative timeout means
6688 gobble output available now
6689 but don't wait at all. */
6691 timeout = make_timespec (0, 0);
6693 else if (time_limit || nsecs > 0)
6695 struct timespec now = current_timespec ();
6696 if (timespec_cmp (end_time, now) <= 0)
6697 break;
6698 timeout = timespec_sub (end_time, now);
6700 else
6702 timeout = make_timespec (100000, 0);
6705 /* If our caller will not immediately handle keyboard events,
6706 run timer events directly.
6707 (Callers that will immediately read keyboard events
6708 call timer_delay on their own.) */
6709 if (NILP (wait_for_cell))
6711 struct timespec timer_delay;
6715 unsigned old_timers_run = timers_run;
6716 timer_delay = timer_check ();
6717 if (timers_run != old_timers_run && do_display)
6718 /* We must retry, since a timer may have requeued itself
6719 and that could alter the time delay. */
6720 redisplay_preserve_echo_area (14);
6721 else
6722 break;
6724 while (!detect_input_pending ());
6726 /* If there is unread keyboard input, also return. */
6727 if (read_kbd != 0
6728 && requeued_events_pending_p ())
6729 break;
6731 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6733 if (timespec_cmp (timer_delay, timeout) < 0)
6735 timeout = timer_delay;
6736 timeout_reduced_for_timers = 1;
6741 /* Cause C-g and alarm signals to take immediate action,
6742 and cause input available signals to zero out timeout. */
6743 if (read_kbd < 0)
6744 set_waiting_for_input (&timeout);
6746 /* If a frame has been newly mapped and needs updating,
6747 reprocess its display stuff. */
6748 if (frame_garbaged && do_display)
6750 clear_waiting_for_input ();
6751 redisplay_preserve_echo_area (15);
6752 if (read_kbd < 0)
6753 set_waiting_for_input (&timeout);
6756 /* Wait till there is something to do. */
6757 FD_ZERO (&waitchannels);
6758 if (read_kbd && detect_input_pending ())
6759 nfds = 0;
6760 else
6762 if (read_kbd || !NILP (wait_for_cell))
6763 FD_SET (0, &waitchannels);
6764 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6767 xerrno = errno;
6769 /* Make C-g and alarm signals set flags again */
6770 clear_waiting_for_input ();
6772 /* If we woke up due to SIGWINCH, actually change size now. */
6773 do_pending_window_change (0);
6775 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6776 /* We waited the full specified time, so return now. */
6777 break;
6779 if (nfds == -1)
6781 /* If the system call was interrupted, then go around the
6782 loop again. */
6783 if (xerrno == EINTR)
6784 FD_ZERO (&waitchannels);
6785 else
6786 report_file_errno ("Failed select", Qnil, xerrno);
6789 /* Check for keyboard input */
6791 if (read_kbd
6792 && detect_input_pending_run_timers (do_display))
6794 swallow_events (do_display);
6795 if (detect_input_pending_run_timers (do_display))
6796 break;
6799 /* If there is unread keyboard input, also return. */
6800 if (read_kbd
6801 && requeued_events_pending_p ())
6802 break;
6804 /* If wait_for_cell. check for keyboard input
6805 but don't run any timers.
6806 ??? (It seems wrong to me to check for keyboard
6807 input at all when wait_for_cell, but the code
6808 has been this way since July 1994.
6809 Try changing this after version 19.31.) */
6810 if (! NILP (wait_for_cell)
6811 && detect_input_pending ())
6813 swallow_events (do_display);
6814 if (detect_input_pending ())
6815 break;
6818 /* Exit now if the cell we're waiting for became non-nil. */
6819 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6820 break;
6823 start_polling ();
6825 return -1;
6828 #endif /* not subprocesses */
6830 /* The following functions are needed even if async subprocesses are
6831 not supported. Some of them are no-op stubs in that case. */
6833 #ifdef HAVE_TIMERFD
6835 /* Add FD, which is a descriptor returned by timerfd_create,
6836 to the set of non-keyboard input descriptors. */
6838 void
6839 add_timer_wait_descriptor (int fd)
6841 FD_SET (fd, &input_wait_mask);
6842 FD_SET (fd, &non_keyboard_wait_mask);
6843 FD_SET (fd, &non_process_wait_mask);
6844 fd_callback_info[fd].func = timerfd_callback;
6845 fd_callback_info[fd].data = NULL;
6846 fd_callback_info[fd].condition |= FOR_READ;
6847 if (fd > max_input_desc)
6848 max_input_desc = fd;
6851 #endif /* HAVE_TIMERFD */
6853 /* Add DESC to the set of keyboard input descriptors. */
6855 void
6856 add_keyboard_wait_descriptor (int desc)
6858 #ifdef subprocesses /* actually means "not MSDOS" */
6859 FD_SET (desc, &input_wait_mask);
6860 FD_SET (desc, &non_process_wait_mask);
6861 if (desc > max_input_desc)
6862 max_input_desc = desc;
6863 #endif
6866 /* From now on, do not expect DESC to give keyboard input. */
6868 void
6869 delete_keyboard_wait_descriptor (int desc)
6871 #ifdef subprocesses
6872 FD_CLR (desc, &input_wait_mask);
6873 FD_CLR (desc, &non_process_wait_mask);
6874 delete_input_desc (desc);
6875 #endif
6878 /* Setup coding systems of PROCESS. */
6880 void
6881 setup_process_coding_systems (Lisp_Object process)
6883 #ifdef subprocesses
6884 struct Lisp_Process *p = XPROCESS (process);
6885 int inch = p->infd;
6886 int outch = p->outfd;
6887 Lisp_Object coding_system;
6889 if (inch < 0 || outch < 0)
6890 return;
6892 if (!proc_decode_coding_system[inch])
6893 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6894 coding_system = p->decode_coding_system;
6895 if (EQ (p->filter, Qinternal_default_process_filter)
6896 && BUFFERP (p->buffer))
6898 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6899 coding_system = raw_text_coding_system (coding_system);
6901 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6903 if (!proc_encode_coding_system[outch])
6904 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6905 setup_coding_system (p->encode_coding_system,
6906 proc_encode_coding_system[outch]);
6907 #endif
6910 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6911 doc: /* Return the (or a) process associated with BUFFER.
6912 BUFFER may be a buffer or the name of one. */)
6913 (register Lisp_Object buffer)
6915 #ifdef subprocesses
6916 register Lisp_Object buf, tail, proc;
6918 if (NILP (buffer)) return Qnil;
6919 buf = Fget_buffer (buffer);
6920 if (NILP (buf)) return Qnil;
6922 FOR_EACH_PROCESS (tail, proc)
6923 if (EQ (XPROCESS (proc)->buffer, buf))
6924 return proc;
6925 #endif /* subprocesses */
6926 return Qnil;
6929 DEFUN ("process-inherit-coding-system-flag",
6930 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6931 1, 1, 0,
6932 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6933 If this flag is t, `buffer-file-coding-system' of the buffer
6934 associated with PROCESS will inherit the coding system used to decode
6935 the process output. */)
6936 (register Lisp_Object process)
6938 #ifdef subprocesses
6939 CHECK_PROCESS (process);
6940 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6941 #else
6942 /* Ignore the argument and return the value of
6943 inherit-process-coding-system. */
6944 return inherit_process_coding_system ? Qt : Qnil;
6945 #endif
6948 /* Kill all processes associated with `buffer'.
6949 If `buffer' is nil, kill all processes */
6951 void
6952 kill_buffer_processes (Lisp_Object buffer)
6954 #ifdef subprocesses
6955 Lisp_Object tail, proc;
6957 FOR_EACH_PROCESS (tail, proc)
6958 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6960 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6961 Fdelete_process (proc);
6962 else if (XPROCESS (proc)->infd >= 0)
6963 process_send_signal (proc, SIGHUP, Qnil, 1);
6965 #else /* subprocesses */
6966 /* Since we have no subprocesses, this does nothing. */
6967 #endif /* subprocesses */
6970 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6971 Swaiting_for_user_input_p, 0, 0, 0,
6972 doc: /* Return non-nil if Emacs is waiting for input from the user.
6973 This is intended for use by asynchronous process output filters and sentinels. */)
6974 (void)
6976 #ifdef subprocesses
6977 return (waiting_for_user_input_p ? Qt : Qnil);
6978 #else
6979 return Qnil;
6980 #endif
6983 /* Stop reading input from keyboard sources. */
6985 void
6986 hold_keyboard_input (void)
6988 kbd_is_on_hold = 1;
6991 /* Resume reading input from keyboard sources. */
6993 void
6994 unhold_keyboard_input (void)
6996 kbd_is_on_hold = 0;
6999 /* Return true if keyboard input is on hold, zero otherwise. */
7001 bool
7002 kbd_on_hold_p (void)
7004 return kbd_is_on_hold;
7008 /* Enumeration of and access to system processes a-la ps(1). */
7010 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7011 0, 0, 0,
7012 doc: /* Return a list of numerical process IDs of all running processes.
7013 If this functionality is unsupported, return nil.
7015 See `process-attributes' for getting attributes of a process given its ID. */)
7016 (void)
7018 return list_system_processes ();
7021 DEFUN ("process-attributes", Fprocess_attributes,
7022 Sprocess_attributes, 1, 1, 0,
7023 doc: /* Return attributes of the process given by its PID, a number.
7025 Value is an alist where each element is a cons cell of the form
7027 \(KEY . VALUE)
7029 If this functionality is unsupported, the value is nil.
7031 See `list-system-processes' for getting a list of all process IDs.
7033 The KEYs of the attributes that this function may return are listed
7034 below, together with the type of the associated VALUE (in parentheses).
7035 Not all platforms support all of these attributes; unsupported
7036 attributes will not appear in the returned alist.
7037 Unless explicitly indicated otherwise, numbers can have either
7038 integer or floating point values.
7040 euid -- Effective user User ID of the process (number)
7041 user -- User name corresponding to euid (string)
7042 egid -- Effective user Group ID of the process (number)
7043 group -- Group name corresponding to egid (string)
7044 comm -- Command name (executable name only) (string)
7045 state -- Process state code, such as "S", "R", or "T" (string)
7046 ppid -- Parent process ID (number)
7047 pgrp -- Process group ID (number)
7048 sess -- Session ID, i.e. process ID of session leader (number)
7049 ttname -- Controlling tty name (string)
7050 tpgid -- ID of foreground process group on the process's tty (number)
7051 minflt -- number of minor page faults (number)
7052 majflt -- number of major page faults (number)
7053 cminflt -- cumulative number of minor page faults (number)
7054 cmajflt -- cumulative number of major page faults (number)
7055 utime -- user time used by the process, in (current-time) format,
7056 which is a list of integers (HIGH LOW USEC PSEC)
7057 stime -- system time used by the process (current-time)
7058 time -- sum of utime and stime (current-time)
7059 cutime -- user time used by the process and its children (current-time)
7060 cstime -- system time used by the process and its children (current-time)
7061 ctime -- sum of cutime and cstime (current-time)
7062 pri -- priority of the process (number)
7063 nice -- nice value of the process (number)
7064 thcount -- process thread count (number)
7065 start -- time the process started (current-time)
7066 vsize -- virtual memory size of the process in KB's (number)
7067 rss -- resident set size of the process in KB's (number)
7068 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7069 pcpu -- percents of CPU time used by the process (floating-point number)
7070 pmem -- percents of total physical memory used by process's resident set
7071 (floating-point number)
7072 args -- command line which invoked the process (string). */)
7073 ( Lisp_Object pid)
7075 return system_process_attributes (pid);
7078 #ifdef subprocesses
7079 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7080 Invoke this after init_process_emacs, and after glib and/or GNUstep
7081 futz with the SIGCHLD handler, but before Emacs forks any children.
7082 This function's caller should block SIGCHLD. */
7084 void
7085 catch_child_signal (void)
7087 struct sigaction action, old_action;
7088 sigset_t oldset;
7089 emacs_sigaction_init (&action, deliver_child_signal);
7090 block_child_signal (&oldset);
7091 sigaction (SIGCHLD, &action, &old_action);
7092 eassert (! (old_action.sa_flags & SA_SIGINFO));
7094 if (old_action.sa_handler != deliver_child_signal)
7095 lib_child_handler
7096 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7097 ? dummy_handler
7098 : old_action.sa_handler);
7099 unblock_child_signal (&oldset);
7101 #endif /* subprocesses */
7104 /* This is not called "init_process" because that is the name of a
7105 Mach system call, so it would cause problems on Darwin systems. */
7106 void
7107 init_process_emacs (void)
7109 #ifdef subprocesses
7110 register int i;
7112 inhibit_sentinels = 0;
7114 #ifndef CANNOT_DUMP
7115 if (! noninteractive || initialized)
7116 #endif
7118 #if defined HAVE_GLIB && !defined WINDOWSNT
7119 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7120 this should always fail, but is enough to initialize glib's
7121 private SIGCHLD handler, allowing catch_child_signal to copy
7122 it into lib_child_handler. */
7123 g_source_unref (g_child_watch_source_new (getpid ()));
7124 #endif
7125 catch_child_signal ();
7128 FD_ZERO (&input_wait_mask);
7129 FD_ZERO (&non_keyboard_wait_mask);
7130 FD_ZERO (&non_process_wait_mask);
7131 FD_ZERO (&write_mask);
7132 max_process_desc = max_input_desc = -1;
7133 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7135 #ifdef NON_BLOCKING_CONNECT
7136 FD_ZERO (&connect_wait_mask);
7137 num_pending_connects = 0;
7138 #endif
7140 #ifdef ADAPTIVE_READ_BUFFERING
7141 process_output_delay_count = 0;
7142 process_output_skip = 0;
7143 #endif
7145 /* Don't do this, it caused infinite select loops. The display
7146 method should call add_keyboard_wait_descriptor on stdin if it
7147 needs that. */
7148 #if 0
7149 FD_SET (0, &input_wait_mask);
7150 #endif
7152 Vprocess_alist = Qnil;
7153 deleted_pid_list = Qnil;
7154 for (i = 0; i < FD_SETSIZE; i++)
7156 chan_process[i] = Qnil;
7157 proc_buffered_char[i] = -1;
7159 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7160 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7161 #ifdef DATAGRAM_SOCKETS
7162 memset (datagram_address, 0, sizeof datagram_address);
7163 #endif
7166 Lisp_Object subfeatures = Qnil;
7167 const struct socket_options *sopt;
7169 #define ADD_SUBFEATURE(key, val) \
7170 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7172 #ifdef NON_BLOCKING_CONNECT
7173 ADD_SUBFEATURE (QCnowait, Qt);
7174 #endif
7175 #ifdef DATAGRAM_SOCKETS
7176 ADD_SUBFEATURE (QCtype, Qdatagram);
7177 #endif
7178 #ifdef HAVE_SEQPACKET
7179 ADD_SUBFEATURE (QCtype, Qseqpacket);
7180 #endif
7181 #ifdef HAVE_LOCAL_SOCKETS
7182 ADD_SUBFEATURE (QCfamily, Qlocal);
7183 #endif
7184 ADD_SUBFEATURE (QCfamily, Qipv4);
7185 #ifdef AF_INET6
7186 ADD_SUBFEATURE (QCfamily, Qipv6);
7187 #endif
7188 #ifdef HAVE_GETSOCKNAME
7189 ADD_SUBFEATURE (QCservice, Qt);
7190 #endif
7191 ADD_SUBFEATURE (QCserver, Qt);
7193 for (sopt = socket_options; sopt->name; sopt++)
7194 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7196 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7199 #if defined (DARWIN_OS)
7200 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7201 processes. As such, we only change the default value. */
7202 if (initialized)
7204 char const *release = (STRINGP (Voperating_system_release)
7205 ? SSDATA (Voperating_system_release)
7206 : 0);
7207 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7208 Vprocess_connection_type = Qnil;
7211 #endif
7212 #endif /* subprocesses */
7213 kbd_is_on_hold = 0;
7216 void
7217 syms_of_process (void)
7219 #ifdef subprocesses
7221 DEFSYM (Qprocessp, "processp");
7222 DEFSYM (Qrun, "run");
7223 DEFSYM (Qstop, "stop");
7224 DEFSYM (Qsignal, "signal");
7226 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7227 here again.
7229 Qexit = intern_c_string ("exit");
7230 staticpro (&Qexit); */
7232 DEFSYM (Qopen, "open");
7233 DEFSYM (Qclosed, "closed");
7234 DEFSYM (Qconnect, "connect");
7235 DEFSYM (Qfailed, "failed");
7236 DEFSYM (Qlisten, "listen");
7237 DEFSYM (Qlocal, "local");
7238 DEFSYM (Qipv4, "ipv4");
7239 #ifdef AF_INET6
7240 DEFSYM (Qipv6, "ipv6");
7241 #endif
7242 DEFSYM (Qdatagram, "datagram");
7243 DEFSYM (Qseqpacket, "seqpacket");
7245 DEFSYM (QCport, ":port");
7246 DEFSYM (QCspeed, ":speed");
7247 DEFSYM (QCprocess, ":process");
7249 DEFSYM (QCbytesize, ":bytesize");
7250 DEFSYM (QCstopbits, ":stopbits");
7251 DEFSYM (QCparity, ":parity");
7252 DEFSYM (Qodd, "odd");
7253 DEFSYM (Qeven, "even");
7254 DEFSYM (QCflowcontrol, ":flowcontrol");
7255 DEFSYM (Qhw, "hw");
7256 DEFSYM (Qsw, "sw");
7257 DEFSYM (QCsummary, ":summary");
7259 DEFSYM (Qreal, "real");
7260 DEFSYM (Qnetwork, "network");
7261 DEFSYM (Qserial, "serial");
7262 DEFSYM (QCbuffer, ":buffer");
7263 DEFSYM (QChost, ":host");
7264 DEFSYM (QCservice, ":service");
7265 DEFSYM (QClocal, ":local");
7266 DEFSYM (QCremote, ":remote");
7267 DEFSYM (QCcoding, ":coding");
7268 DEFSYM (QCserver, ":server");
7269 DEFSYM (QCnowait, ":nowait");
7270 DEFSYM (QCsentinel, ":sentinel");
7271 DEFSYM (QClog, ":log");
7272 DEFSYM (QCnoquery, ":noquery");
7273 DEFSYM (QCstop, ":stop");
7274 DEFSYM (QCoptions, ":options");
7275 DEFSYM (QCplist, ":plist");
7277 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7279 staticpro (&Vprocess_alist);
7280 staticpro (&deleted_pid_list);
7282 #endif /* subprocesses */
7284 DEFSYM (QCname, ":name");
7285 DEFSYM (QCtype, ":type");
7287 DEFSYM (Qeuid, "euid");
7288 DEFSYM (Qegid, "egid");
7289 DEFSYM (Quser, "user");
7290 DEFSYM (Qgroup, "group");
7291 DEFSYM (Qcomm, "comm");
7292 DEFSYM (Qstate, "state");
7293 DEFSYM (Qppid, "ppid");
7294 DEFSYM (Qpgrp, "pgrp");
7295 DEFSYM (Qsess, "sess");
7296 DEFSYM (Qttname, "ttname");
7297 DEFSYM (Qtpgid, "tpgid");
7298 DEFSYM (Qminflt, "minflt");
7299 DEFSYM (Qmajflt, "majflt");
7300 DEFSYM (Qcminflt, "cminflt");
7301 DEFSYM (Qcmajflt, "cmajflt");
7302 DEFSYM (Qutime, "utime");
7303 DEFSYM (Qstime, "stime");
7304 DEFSYM (Qtime, "time");
7305 DEFSYM (Qcutime, "cutime");
7306 DEFSYM (Qcstime, "cstime");
7307 DEFSYM (Qctime, "ctime");
7308 #ifdef subprocesses
7309 DEFSYM (Qinternal_default_process_sentinel,
7310 "internal-default-process-sentinel");
7311 DEFSYM (Qinternal_default_process_filter,
7312 "internal-default-process-filter");
7313 #endif
7314 DEFSYM (Qpri, "pri");
7315 DEFSYM (Qnice, "nice");
7316 DEFSYM (Qthcount, "thcount");
7317 DEFSYM (Qstart, "start");
7318 DEFSYM (Qvsize, "vsize");
7319 DEFSYM (Qrss, "rss");
7320 DEFSYM (Qetime, "etime");
7321 DEFSYM (Qpcpu, "pcpu");
7322 DEFSYM (Qpmem, "pmem");
7323 DEFSYM (Qargs, "args");
7325 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7326 doc: /* Non-nil means delete processes immediately when they exit.
7327 A value of nil means don't delete them until `list-processes' is run. */);
7329 delete_exited_processes = 1;
7331 #ifdef subprocesses
7332 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7333 doc: /* Control type of device used to communicate with subprocesses.
7334 Values are nil to use a pipe, or t or `pty' to use a pty.
7335 The value has no effect if the system has no ptys or if all ptys are busy:
7336 then a pipe is used in any case.
7337 The value takes effect when `start-process' is called. */);
7338 Vprocess_connection_type = Qt;
7340 #ifdef ADAPTIVE_READ_BUFFERING
7341 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7342 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7343 On some systems, when Emacs reads the output from a subprocess, the output data
7344 is read in very small blocks, potentially resulting in very poor performance.
7345 This behavior can be remedied to some extent by setting this variable to a
7346 non-nil value, as it will automatically delay reading from such processes, to
7347 allow them to produce more output before Emacs tries to read it.
7348 If the value is t, the delay is reset after each write to the process; any other
7349 non-nil value means that the delay is not reset on write.
7350 The variable takes effect when `start-process' is called. */);
7351 Vprocess_adaptive_read_buffering = Qt;
7352 #endif
7354 defsubr (&Sprocessp);
7355 defsubr (&Sget_process);
7356 defsubr (&Sdelete_process);
7357 defsubr (&Sprocess_status);
7358 defsubr (&Sprocess_exit_status);
7359 defsubr (&Sprocess_id);
7360 defsubr (&Sprocess_name);
7361 defsubr (&Sprocess_tty_name);
7362 defsubr (&Sprocess_command);
7363 defsubr (&Sset_process_buffer);
7364 defsubr (&Sprocess_buffer);
7365 defsubr (&Sprocess_mark);
7366 defsubr (&Sset_process_filter);
7367 defsubr (&Sprocess_filter);
7368 defsubr (&Sset_process_sentinel);
7369 defsubr (&Sprocess_sentinel);
7370 defsubr (&Sset_process_window_size);
7371 defsubr (&Sset_process_inherit_coding_system_flag);
7372 defsubr (&Sset_process_query_on_exit_flag);
7373 defsubr (&Sprocess_query_on_exit_flag);
7374 defsubr (&Sprocess_contact);
7375 defsubr (&Sprocess_plist);
7376 defsubr (&Sset_process_plist);
7377 defsubr (&Sprocess_list);
7378 defsubr (&Sstart_process);
7379 defsubr (&Sserial_process_configure);
7380 defsubr (&Smake_serial_process);
7381 defsubr (&Sset_network_process_option);
7382 defsubr (&Smake_network_process);
7383 defsubr (&Sformat_network_address);
7384 defsubr (&Snetwork_interface_list);
7385 defsubr (&Snetwork_interface_info);
7386 #ifdef DATAGRAM_SOCKETS
7387 defsubr (&Sprocess_datagram_address);
7388 defsubr (&Sset_process_datagram_address);
7389 #endif
7390 defsubr (&Saccept_process_output);
7391 defsubr (&Sprocess_send_region);
7392 defsubr (&Sprocess_send_string);
7393 defsubr (&Sinterrupt_process);
7394 defsubr (&Skill_process);
7395 defsubr (&Squit_process);
7396 defsubr (&Sstop_process);
7397 defsubr (&Scontinue_process);
7398 defsubr (&Sprocess_running_child_p);
7399 defsubr (&Sprocess_send_eof);
7400 defsubr (&Ssignal_process);
7401 defsubr (&Swaiting_for_user_input_p);
7402 defsubr (&Sprocess_type);
7403 defsubr (&Sinternal_default_process_sentinel);
7404 defsubr (&Sinternal_default_process_filter);
7405 defsubr (&Sset_process_coding_system);
7406 defsubr (&Sprocess_coding_system);
7407 defsubr (&Sset_process_filter_multibyte);
7408 defsubr (&Sprocess_filter_multibyte_p);
7410 #endif /* subprocesses */
7412 defsubr (&Sget_buffer_process);
7413 defsubr (&Sprocess_inherit_coding_system_flag);
7414 defsubr (&Slist_system_processes);
7415 defsubr (&Sprocess_attributes);