Update copyright year to 2015
[emacs.git] / src / process.c
blob6eb0f9e2ab47be9fa30afea067ec731610c2d0a0
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #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 # undef accept4
177 # define accept4(sockfd, addr, addrlen, flags) \
178 process_accept4 (sockfd, addr, addrlen, flags)
179 static int
180 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
182 return close_on_exec (accept (sockfd, addr, addrlen));
185 static int
186 process_socket (int domain, int type, int protocol)
188 return close_on_exec (socket (domain, type, protocol));
190 # undef socket
191 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
192 #endif
194 Lisp_Object Qprocessp;
195 static Lisp_Object Qrun, Qstop, Qsignal;
196 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
197 Lisp_Object Qlocal;
198 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
199 static Lisp_Object Qreal, Qnetwork, Qserial;
200 #ifdef AF_INET6
201 static Lisp_Object Qipv6;
202 #endif
203 static Lisp_Object QCport, QCprocess;
204 Lisp_Object QCspeed;
205 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
206 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
207 static Lisp_Object QCbuffer, QChost, QCservice;
208 static Lisp_Object QClocal, QCremote, QCcoding;
209 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
210 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
211 static Lisp_Object Qlast_nonmenu_event;
212 static Lisp_Object Qinternal_default_process_sentinel;
213 static Lisp_Object Qinternal_default_process_filter;
215 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
216 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
217 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
218 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
220 /* Number of events of change of status of a process. */
221 static EMACS_INT process_tick;
222 /* Number of events for which the user or sentinel has been notified. */
223 static EMACS_INT update_tick;
225 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
227 /* Only W32 has this, it really means that select can't take write mask. */
228 #ifdef BROKEN_NON_BLOCKING_CONNECT
229 #undef NON_BLOCKING_CONNECT
230 enum { SELECT_CAN_DO_WRITE_MASK = false };
231 #else
232 enum { SELECT_CAN_DO_WRITE_MASK = true };
233 #ifndef NON_BLOCKING_CONNECT
234 #ifdef HAVE_SELECT
235 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
236 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
237 #define NON_BLOCKING_CONNECT
238 #endif /* EWOULDBLOCK || EINPROGRESS */
239 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
240 #endif /* HAVE_SELECT */
241 #endif /* NON_BLOCKING_CONNECT */
242 #endif /* BROKEN_NON_BLOCKING_CONNECT */
244 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
245 this system. We need to read full packets, so we need a
246 "non-destructive" select. So we require either native select,
247 or emulation of select using FIONREAD. */
249 #ifndef BROKEN_DATAGRAM_SOCKETS
250 # if defined HAVE_SELECT || defined USABLE_FIONREAD
251 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
252 # define DATAGRAM_SOCKETS
253 # endif
254 # endif
255 #endif
257 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
258 # define HAVE_SEQPACKET
259 #endif
261 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
262 #define ADAPTIVE_READ_BUFFERING
263 #endif
265 #ifdef ADAPTIVE_READ_BUFFERING
266 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
267 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
268 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
270 /* Number of processes which have a non-zero read_output_delay,
271 and therefore might be delayed for adaptive read buffering. */
273 static int process_output_delay_count;
275 /* True if any process has non-nil read_output_skip. */
277 static bool process_output_skip;
279 #else
280 #define process_output_delay_count 0
281 #endif
283 static void create_process (Lisp_Object, char **, Lisp_Object);
284 #ifdef USABLE_SIGIO
285 static bool keyboard_bit_set (fd_set *);
286 #endif
287 static void deactivate_process (Lisp_Object);
288 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
289 static int read_process_output (Lisp_Object, int);
290 static void handle_child_signal (int);
291 static void create_pty (Lisp_Object);
293 static Lisp_Object get_process (register Lisp_Object name);
294 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
296 /* Mask of bits indicating the descriptors that we wait for input on. */
298 static fd_set input_wait_mask;
300 /* Mask that excludes keyboard input descriptor(s). */
302 static fd_set non_keyboard_wait_mask;
304 /* Mask that excludes process input descriptor(s). */
306 static fd_set non_process_wait_mask;
308 /* Mask for selecting for write. */
310 static fd_set write_mask;
312 #ifdef NON_BLOCKING_CONNECT
313 /* Mask of bits indicating the descriptors that we wait for connect to
314 complete on. Once they complete, they are removed from this mask
315 and added to the input_wait_mask and non_keyboard_wait_mask. */
317 static fd_set connect_wait_mask;
319 /* Number of bits set in connect_wait_mask. */
320 static int num_pending_connects;
321 #endif /* NON_BLOCKING_CONNECT */
323 /* The largest descriptor currently in use for a process object; -1 if none. */
324 static int max_process_desc;
326 /* The largest descriptor currently in use for input; -1 if none. */
327 static int max_input_desc;
329 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
330 static Lisp_Object chan_process[FD_SETSIZE];
332 /* Alist of elements (NAME . PROCESS). */
333 static Lisp_Object Vprocess_alist;
335 /* Buffered-ahead input char from process, indexed by channel.
336 -1 means empty (no char is buffered).
337 Used on sys V where the only way to tell if there is any
338 output from the process is to read at least one char.
339 Always -1 on systems that support FIONREAD. */
341 static int proc_buffered_char[FD_SETSIZE];
343 /* Table of `struct coding-system' for each process. */
344 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
345 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
347 #ifdef DATAGRAM_SOCKETS
348 /* Table of `partner address' for datagram sockets. */
349 static struct sockaddr_and_len {
350 struct sockaddr *sa;
351 int len;
352 } datagram_address[FD_SETSIZE];
353 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
354 #define DATAGRAM_CONN_P(proc) \
355 (PROCESSP (proc) && \
356 XPROCESS (proc)->infd >= 0 && \
357 datagram_address[XPROCESS (proc)->infd].sa != 0)
358 #else
359 #define DATAGRAM_CHAN_P(chan) (0)
360 #define DATAGRAM_CONN_P(proc) (0)
361 #endif
363 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
364 a `for' loop which iterates over processes from Vprocess_alist. */
366 #define FOR_EACH_PROCESS(list_var, proc_var) \
367 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
369 /* These setters are used only in this file, so they can be private. */
370 static void
371 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
373 p->buffer = val;
375 static void
376 pset_command (struct Lisp_Process *p, Lisp_Object val)
378 p->command = val;
380 static void
381 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
383 p->decode_coding_system = val;
385 static void
386 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
388 p->decoding_buf = val;
390 static void
391 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
393 p->encode_coding_system = val;
395 static void
396 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
398 p->encoding_buf = val;
400 static void
401 pset_filter (struct Lisp_Process *p, Lisp_Object val)
403 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
405 static void
406 pset_log (struct Lisp_Process *p, Lisp_Object val)
408 p->log = val;
410 static void
411 pset_mark (struct Lisp_Process *p, Lisp_Object val)
413 p->mark = val;
415 static void
416 pset_name (struct Lisp_Process *p, Lisp_Object val)
418 p->name = val;
420 static void
421 pset_plist (struct Lisp_Process *p, Lisp_Object val)
423 p->plist = val;
425 static void
426 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
428 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
430 static void
431 pset_status (struct Lisp_Process *p, Lisp_Object val)
433 p->status = val;
435 static void
436 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
438 p->tty_name = val;
440 static void
441 pset_type (struct Lisp_Process *p, Lisp_Object val)
443 p->type = val;
445 static void
446 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
448 p->write_queue = val;
453 static struct fd_callback_data
455 fd_callback func;
456 void *data;
457 #define FOR_READ 1
458 #define FOR_WRITE 2
459 int condition; /* Mask of the defines above. */
460 } fd_callback_info[FD_SETSIZE];
463 /* Add a file descriptor FD to be monitored for when read is possible.
464 When read is possible, call FUNC with argument DATA. */
466 void
467 add_read_fd (int fd, fd_callback func, void *data)
469 add_keyboard_wait_descriptor (fd);
471 fd_callback_info[fd].func = func;
472 fd_callback_info[fd].data = data;
473 fd_callback_info[fd].condition |= FOR_READ;
476 /* Stop monitoring file descriptor FD for when read is possible. */
478 void
479 delete_read_fd (int fd)
481 delete_keyboard_wait_descriptor (fd);
483 fd_callback_info[fd].condition &= ~FOR_READ;
484 if (fd_callback_info[fd].condition == 0)
486 fd_callback_info[fd].func = 0;
487 fd_callback_info[fd].data = 0;
491 /* Add a file descriptor FD to be monitored for when write is possible.
492 When write is possible, call FUNC with argument DATA. */
494 void
495 add_write_fd (int fd, fd_callback func, void *data)
497 FD_SET (fd, &write_mask);
498 if (fd > max_input_desc)
499 max_input_desc = fd;
501 fd_callback_info[fd].func = func;
502 fd_callback_info[fd].data = data;
503 fd_callback_info[fd].condition |= FOR_WRITE;
506 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
508 static void
509 delete_input_desc (int fd)
511 if (fd == max_input_desc)
514 fd--;
515 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
516 || FD_ISSET (fd, &write_mask)));
518 max_input_desc = fd;
522 /* Stop monitoring file descriptor FD for when write is possible. */
524 void
525 delete_write_fd (int fd)
527 FD_CLR (fd, &write_mask);
528 fd_callback_info[fd].condition &= ~FOR_WRITE;
529 if (fd_callback_info[fd].condition == 0)
531 fd_callback_info[fd].func = 0;
532 fd_callback_info[fd].data = 0;
533 delete_input_desc (fd);
538 /* Compute the Lisp form of the process status, p->status, from
539 the numeric status that was returned by `wait'. */
541 static Lisp_Object status_convert (int);
543 static void
544 update_status (struct Lisp_Process *p)
546 eassert (p->raw_status_new);
547 pset_status (p, status_convert (p->raw_status));
548 p->raw_status_new = 0;
551 /* Convert a process status word in Unix format to
552 the list that we use internally. */
554 static Lisp_Object
555 status_convert (int w)
557 if (WIFSTOPPED (w))
558 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
559 else if (WIFEXITED (w))
560 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
561 WCOREDUMP (w) ? Qt : Qnil));
562 else if (WIFSIGNALED (w))
563 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
564 WCOREDUMP (w) ? Qt : Qnil));
565 else
566 return Qrun;
569 /* Given a status-list, extract the three pieces of information
570 and store them individually through the three pointers. */
572 static void
573 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
575 Lisp_Object tem;
577 if (SYMBOLP (l))
579 *symbol = l;
580 *code = 0;
581 *coredump = 0;
583 else
585 *symbol = XCAR (l);
586 tem = XCDR (l);
587 *code = XFASTINT (XCAR (tem));
588 tem = XCDR (tem);
589 *coredump = !NILP (tem);
593 /* Return a string describing a process status list. */
595 static Lisp_Object
596 status_message (struct Lisp_Process *p)
598 Lisp_Object status = p->status;
599 Lisp_Object symbol;
600 int code;
601 bool coredump;
602 Lisp_Object string;
604 decode_status (status, &symbol, &code, &coredump);
606 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
608 char const *signame;
609 synchronize_system_messages_locale ();
610 signame = strsignal (code);
611 if (signame == 0)
612 string = build_string ("unknown");
613 else
615 int c1, c2;
617 string = build_unibyte_string (signame);
618 if (! NILP (Vlocale_coding_system))
619 string = (code_convert_string_norecord
620 (string, Vlocale_coding_system, 0));
621 c1 = STRING_CHAR (SDATA (string));
622 c2 = downcase (c1);
623 if (c1 != c2)
624 Faset (string, make_number (0), make_number (c2));
626 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
627 return concat2 (string, suffix);
629 else if (EQ (symbol, Qexit))
631 if (NETCONN1_P (p))
632 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
633 if (code == 0)
634 return build_string ("finished\n");
635 AUTO_STRING (prefix, "exited abnormally with code ");
636 string = Fnumber_to_string (make_number (code));
637 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
638 return concat3 (prefix, string, suffix);
640 else if (EQ (symbol, Qfailed))
642 AUTO_STRING (prefix, "failed with code ");
643 string = Fnumber_to_string (make_number (code));
644 AUTO_STRING (suffix, "\n");
645 return concat3 (prefix, string, suffix);
647 else
648 return Fcopy_sequence (Fsymbol_name (symbol));
651 enum { PTY_NAME_SIZE = 24 };
653 /* Open an available pty, returning a file descriptor.
654 Store into PTY_NAME the file name of the terminal corresponding to the pty.
655 Return -1 on failure. */
657 static int
658 allocate_pty (char pty_name[PTY_NAME_SIZE])
660 #ifdef HAVE_PTYS
661 int fd;
663 #ifdef PTY_ITERATION
664 PTY_ITERATION
665 #else
666 register int c, i;
667 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
668 for (i = 0; i < 16; i++)
669 #endif
671 #ifdef PTY_NAME_SPRINTF
672 PTY_NAME_SPRINTF
673 #else
674 sprintf (pty_name, "/dev/pty%c%x", c, i);
675 #endif /* no PTY_NAME_SPRINTF */
677 #ifdef PTY_OPEN
678 PTY_OPEN;
679 #else /* no PTY_OPEN */
680 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
681 #endif /* no PTY_OPEN */
683 if (fd >= 0)
685 #ifdef PTY_OPEN
686 /* Set FD's close-on-exec flag. This is needed even if
687 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
688 doesn't require support for that combination.
689 Multithreaded platforms where posix_openpt ignores
690 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
691 have a race condition between the PTY_OPEN and here. */
692 fcntl (fd, F_SETFD, FD_CLOEXEC);
693 #endif
694 /* Check to make certain that both sides are available
695 this avoids a nasty yet stupid bug in rlogins. */
696 #ifdef PTY_TTY_NAME_SPRINTF
697 PTY_TTY_NAME_SPRINTF
698 #else
699 sprintf (pty_name, "/dev/tty%c%x", c, i);
700 #endif /* no PTY_TTY_NAME_SPRINTF */
701 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
703 emacs_close (fd);
704 # ifndef __sgi
705 continue;
706 # else
707 return -1;
708 # endif /* __sgi */
710 setup_pty (fd);
711 return fd;
714 #endif /* HAVE_PTYS */
715 return -1;
718 static Lisp_Object
719 make_process (Lisp_Object name)
721 register Lisp_Object val, tem, name1;
722 register struct Lisp_Process *p;
723 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
724 printmax_t i;
726 p = allocate_process ();
727 /* Initialize Lisp data. Note that allocate_process initializes all
728 Lisp data to nil, so do it only for slots which should not be nil. */
729 pset_status (p, Qrun);
730 pset_mark (p, Fmake_marker ());
732 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
733 non-Lisp data, so do it only for slots which should not be zero. */
734 p->infd = -1;
735 p->outfd = -1;
736 for (i = 0; i < PROCESS_OPEN_FDS; i++)
737 p->open_fd[i] = -1;
739 #ifdef HAVE_GNUTLS
740 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
741 #endif
743 /* If name is already in use, modify it until it is unused. */
745 name1 = name;
746 for (i = 1; ; i++)
748 tem = Fget_process (name1);
749 if (NILP (tem)) break;
750 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
752 name = name1;
753 pset_name (p, name);
754 pset_sentinel (p, Qinternal_default_process_sentinel);
755 pset_filter (p, Qinternal_default_process_filter);
756 XSETPROCESS (val, p);
757 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
758 return val;
761 static void
762 remove_process (register Lisp_Object proc)
764 register Lisp_Object pair;
766 pair = Frassq (proc, Vprocess_alist);
767 Vprocess_alist = Fdelq (pair, Vprocess_alist);
769 deactivate_process (proc);
773 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
774 doc: /* Return t if OBJECT is a process. */)
775 (Lisp_Object object)
777 return PROCESSP (object) ? Qt : Qnil;
780 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
781 doc: /* Return the process named NAME, or nil if there is none. */)
782 (register Lisp_Object name)
784 if (PROCESSP (name))
785 return name;
786 CHECK_STRING (name);
787 return Fcdr (Fassoc (name, Vprocess_alist));
790 /* This is how commands for the user decode process arguments. It
791 accepts a process, a process name, a buffer, a buffer name, or nil.
792 Buffers denote the first process in the buffer, and nil denotes the
793 current buffer. */
795 static Lisp_Object
796 get_process (register Lisp_Object name)
798 register Lisp_Object proc, obj;
799 if (STRINGP (name))
801 obj = Fget_process (name);
802 if (NILP (obj))
803 obj = Fget_buffer (name);
804 if (NILP (obj))
805 error ("Process %s does not exist", SDATA (name));
807 else if (NILP (name))
808 obj = Fcurrent_buffer ();
809 else
810 obj = name;
812 /* Now obj should be either a buffer object or a process object. */
813 if (BUFFERP (obj))
815 if (NILP (BVAR (XBUFFER (obj), name)))
816 error ("Attempt to get process for a dead buffer");
817 proc = Fget_buffer_process (obj);
818 if (NILP (proc))
819 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
821 else
823 CHECK_PROCESS (obj);
824 proc = obj;
826 return proc;
830 /* Fdelete_process promises to immediately forget about the process, but in
831 reality, Emacs needs to remember those processes until they have been
832 treated by the SIGCHLD handler and waitpid has been invoked on them;
833 otherwise they might fill up the kernel's process table.
835 Some processes created by call-process are also put onto this list.
837 Members of this list are (process-ID . filename) pairs. The
838 process-ID is a number; the filename, if a string, is a file that
839 needs to be removed after the process exits. */
840 static Lisp_Object deleted_pid_list;
842 void
843 record_deleted_pid (pid_t pid, Lisp_Object filename)
845 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
846 /* GC treated elements set to nil. */
847 Fdelq (Qnil, deleted_pid_list));
851 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
852 doc: /* Delete PROCESS: kill it and forget about it immediately.
853 PROCESS may be a process, a buffer, the name of a process or buffer, or
854 nil, indicating the current buffer's process. */)
855 (register Lisp_Object process)
857 register struct Lisp_Process *p;
859 process = get_process (process);
860 p = XPROCESS (process);
862 p->raw_status_new = 0;
863 if (NETCONN1_P (p) || SERIALCONN1_P (p))
865 pset_status (p, list2 (Qexit, make_number (0)));
866 p->tick = ++process_tick;
867 status_notify (p, NULL);
868 redisplay_preserve_echo_area (13);
870 else
872 if (p->alive)
873 record_kill_process (p, Qnil);
875 if (p->infd >= 0)
877 /* Update P's status, since record_kill_process will make the
878 SIGCHLD handler update deleted_pid_list, not *P. */
879 Lisp_Object symbol;
880 if (p->raw_status_new)
881 update_status (p);
882 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
883 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
884 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
886 p->tick = ++process_tick;
887 status_notify (p, NULL);
888 redisplay_preserve_echo_area (13);
891 remove_process (process);
892 return Qnil;
895 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
896 doc: /* Return the status of PROCESS.
897 The returned value is one of the following symbols:
898 run -- for a process that is running.
899 stop -- for a process stopped but continuable.
900 exit -- for a process that has exited.
901 signal -- for a process that has got a fatal signal.
902 open -- for a network stream connection that is open.
903 listen -- for a network stream server that is listening.
904 closed -- for a network stream connection that is closed.
905 connect -- when waiting for a non-blocking connection to complete.
906 failed -- when a non-blocking connection has failed.
907 nil -- if arg is a process name and no such process exists.
908 PROCESS may be a process, a buffer, the name of a process, or
909 nil, indicating the current buffer's process. */)
910 (register Lisp_Object process)
912 register struct Lisp_Process *p;
913 register Lisp_Object status;
915 if (STRINGP (process))
916 process = Fget_process (process);
917 else
918 process = get_process (process);
920 if (NILP (process))
921 return process;
923 p = XPROCESS (process);
924 if (p->raw_status_new)
925 update_status (p);
926 status = p->status;
927 if (CONSP (status))
928 status = XCAR (status);
929 if (NETCONN1_P (p) || SERIALCONN1_P (p))
931 if (EQ (status, Qexit))
932 status = Qclosed;
933 else if (EQ (p->command, Qt))
934 status = Qstop;
935 else if (EQ (status, Qrun))
936 status = Qopen;
938 return status;
941 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
942 1, 1, 0,
943 doc: /* Return the exit status of PROCESS or the signal number that killed it.
944 If PROCESS has not yet exited or died, return 0. */)
945 (register Lisp_Object process)
947 CHECK_PROCESS (process);
948 if (XPROCESS (process)->raw_status_new)
949 update_status (XPROCESS (process));
950 if (CONSP (XPROCESS (process)->status))
951 return XCAR (XCDR (XPROCESS (process)->status));
952 return make_number (0);
955 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
956 doc: /* Return the process id of PROCESS.
957 This is the pid of the external process which PROCESS uses or talks to.
958 For a network connection, this value is nil. */)
959 (register Lisp_Object process)
961 pid_t pid;
963 CHECK_PROCESS (process);
964 pid = XPROCESS (process)->pid;
965 return (pid ? make_fixnum_or_float (pid) : Qnil);
968 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
969 doc: /* Return the name of PROCESS, as a string.
970 This is the name of the program invoked in PROCESS,
971 possibly modified to make it unique among process names. */)
972 (register Lisp_Object process)
974 CHECK_PROCESS (process);
975 return XPROCESS (process)->name;
978 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
979 doc: /* Return the command that was executed to start PROCESS.
980 This is a list of strings, the first string being the program executed
981 and the rest of the strings being the arguments given to it.
982 For a network or serial process, this is nil (process is running) or t
983 \(process is stopped). */)
984 (register Lisp_Object process)
986 CHECK_PROCESS (process);
987 return XPROCESS (process)->command;
990 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
991 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
992 This is the terminal that the process itself reads and writes on,
993 not the name of the pty that Emacs uses to talk with that terminal. */)
994 (register Lisp_Object process)
996 CHECK_PROCESS (process);
997 return XPROCESS (process)->tty_name;
1000 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1001 2, 2, 0,
1002 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1003 Return BUFFER. */)
1004 (register Lisp_Object process, Lisp_Object buffer)
1006 struct Lisp_Process *p;
1008 CHECK_PROCESS (process);
1009 if (!NILP (buffer))
1010 CHECK_BUFFER (buffer);
1011 p = XPROCESS (process);
1012 pset_buffer (p, buffer);
1013 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1014 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1015 setup_process_coding_systems (process);
1016 return buffer;
1019 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1020 1, 1, 0,
1021 doc: /* Return the buffer PROCESS is associated with.
1022 The default process filter inserts output from PROCESS into this buffer. */)
1023 (register Lisp_Object process)
1025 CHECK_PROCESS (process);
1026 return XPROCESS (process)->buffer;
1029 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1030 1, 1, 0,
1031 doc: /* Return the marker for the end of the last output from PROCESS. */)
1032 (register Lisp_Object process)
1034 CHECK_PROCESS (process);
1035 return XPROCESS (process)->mark;
1038 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1039 2, 2, 0,
1040 doc: /* Give PROCESS the filter function FILTER; nil means default.
1041 A value of t means stop accepting output from the process.
1043 When a process has a non-default filter, its buffer is not used for output.
1044 Instead, each time it does output, the entire string of output is
1045 passed to the filter.
1047 The filter gets two arguments: the process and the string of output.
1048 The string argument is normally a multibyte string, except:
1049 - if the process's input coding system is no-conversion or raw-text,
1050 it is a unibyte string (the non-converted input), or else
1051 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1052 string (the result of converting the decoded input multibyte
1053 string to unibyte with `string-make-unibyte'). */)
1054 (register Lisp_Object process, Lisp_Object filter)
1056 struct Lisp_Process *p;
1058 CHECK_PROCESS (process);
1059 p = XPROCESS (process);
1061 /* Don't signal an error if the process's input file descriptor
1062 is closed. This could make debugging Lisp more difficult,
1063 for example when doing something like
1065 (setq process (start-process ...))
1066 (debug)
1067 (set-process-filter process ...) */
1069 if (NILP (filter))
1070 filter = Qinternal_default_process_filter;
1072 if (p->infd >= 0)
1074 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1076 FD_CLR (p->infd, &input_wait_mask);
1077 FD_CLR (p->infd, &non_keyboard_wait_mask);
1079 else if (EQ (p->filter, Qt)
1080 /* Network or serial process not stopped: */
1081 && !EQ (p->command, Qt))
1083 FD_SET (p->infd, &input_wait_mask);
1084 FD_SET (p->infd, &non_keyboard_wait_mask);
1088 pset_filter (p, filter);
1089 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1090 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1091 setup_process_coding_systems (process);
1092 return filter;
1095 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1096 1, 1, 0,
1097 doc: /* Return the filter function of PROCESS.
1098 See `set-process-filter' for more info on filter functions. */)
1099 (register Lisp_Object process)
1101 CHECK_PROCESS (process);
1102 return XPROCESS (process)->filter;
1105 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1106 2, 2, 0,
1107 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1108 The sentinel is called as a function when the process changes state.
1109 It gets two arguments: the process, and a string describing the change. */)
1110 (register Lisp_Object process, Lisp_Object sentinel)
1112 struct Lisp_Process *p;
1114 CHECK_PROCESS (process);
1115 p = XPROCESS (process);
1117 if (NILP (sentinel))
1118 sentinel = Qinternal_default_process_sentinel;
1120 pset_sentinel (p, sentinel);
1121 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1122 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1123 return sentinel;
1126 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1127 1, 1, 0,
1128 doc: /* Return the sentinel of PROCESS.
1129 See `set-process-sentinel' for more info on sentinels. */)
1130 (register Lisp_Object process)
1132 CHECK_PROCESS (process);
1133 return XPROCESS (process)->sentinel;
1136 DEFUN ("set-process-window-size", Fset_process_window_size,
1137 Sset_process_window_size, 3, 3, 0,
1138 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1139 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1141 CHECK_PROCESS (process);
1143 /* All known platforms store window sizes as 'unsigned short'. */
1144 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1145 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1147 if (XPROCESS (process)->infd < 0
1148 || (set_window_size (XPROCESS (process)->infd,
1149 XINT (height), XINT (width))
1150 < 0))
1151 return Qnil;
1152 else
1153 return Qt;
1156 DEFUN ("set-process-inherit-coding-system-flag",
1157 Fset_process_inherit_coding_system_flag,
1158 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1159 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1160 If the second argument FLAG is non-nil, then the variable
1161 `buffer-file-coding-system' of the buffer associated with PROCESS
1162 will be bound to the value of the coding system used to decode
1163 the process output.
1165 This is useful when the coding system specified for the process buffer
1166 leaves either the character code conversion or the end-of-line conversion
1167 unspecified, or if the coding system used to decode the process output
1168 is more appropriate for saving the process buffer.
1170 Binding the variable `inherit-process-coding-system' to non-nil before
1171 starting the process is an alternative way of setting the inherit flag
1172 for the process which will run.
1174 This function returns FLAG. */)
1175 (register Lisp_Object process, Lisp_Object flag)
1177 CHECK_PROCESS (process);
1178 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1179 return flag;
1182 DEFUN ("set-process-query-on-exit-flag",
1183 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1184 2, 2, 0,
1185 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1186 If the second argument FLAG is non-nil, Emacs will query the user before
1187 exiting or killing a buffer if PROCESS is running. This function
1188 returns FLAG. */)
1189 (register Lisp_Object process, Lisp_Object flag)
1191 CHECK_PROCESS (process);
1192 XPROCESS (process)->kill_without_query = NILP (flag);
1193 return flag;
1196 DEFUN ("process-query-on-exit-flag",
1197 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1198 1, 1, 0,
1199 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1200 (register Lisp_Object process)
1202 CHECK_PROCESS (process);
1203 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1206 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1207 1, 2, 0,
1208 doc: /* Return the contact info of PROCESS; t for a real child.
1209 For a network or serial connection, the value depends on the optional
1210 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1211 SERVICE) for a network connection or (PORT SPEED) for a serial
1212 connection. If KEY is t, the complete contact information for the
1213 connection is returned, else the specific value for the keyword KEY is
1214 returned. See `make-network-process' or `make-serial-process' for a
1215 list of keywords. */)
1216 (register Lisp_Object process, Lisp_Object key)
1218 Lisp_Object contact;
1220 CHECK_PROCESS (process);
1221 contact = XPROCESS (process)->childp;
1223 #ifdef DATAGRAM_SOCKETS
1224 if (DATAGRAM_CONN_P (process)
1225 && (EQ (key, Qt) || EQ (key, QCremote)))
1226 contact = Fplist_put (contact, QCremote,
1227 Fprocess_datagram_address (process));
1228 #endif
1230 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1231 return contact;
1232 if (NILP (key) && NETCONN_P (process))
1233 return list2 (Fplist_get (contact, QChost),
1234 Fplist_get (contact, QCservice));
1235 if (NILP (key) && SERIALCONN_P (process))
1236 return list2 (Fplist_get (contact, QCport),
1237 Fplist_get (contact, QCspeed));
1238 return Fplist_get (contact, key);
1241 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1242 1, 1, 0,
1243 doc: /* Return the plist of PROCESS. */)
1244 (register Lisp_Object process)
1246 CHECK_PROCESS (process);
1247 return XPROCESS (process)->plist;
1250 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1251 2, 2, 0,
1252 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1253 (register Lisp_Object process, Lisp_Object plist)
1255 CHECK_PROCESS (process);
1256 CHECK_LIST (plist);
1258 pset_plist (XPROCESS (process), plist);
1259 return plist;
1262 #if 0 /* Turned off because we don't currently record this info
1263 in the process. Perhaps add it. */
1264 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1265 doc: /* Return the connection type of PROCESS.
1266 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1267 a socket connection. */)
1268 (Lisp_Object process)
1270 return XPROCESS (process)->type;
1272 #endif
1274 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1275 doc: /* Return the connection type of PROCESS.
1276 The value is either the symbol `real', `network', or `serial'.
1277 PROCESS may be a process, a buffer, the name of a process or buffer, or
1278 nil, indicating the current buffer's process. */)
1279 (Lisp_Object process)
1281 Lisp_Object proc;
1282 proc = get_process (process);
1283 return XPROCESS (proc)->type;
1286 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1287 1, 2, 0,
1288 doc: /* Convert network ADDRESS from internal format to a string.
1289 A 4 or 5 element vector represents an IPv4 address (with port number).
1290 An 8 or 9 element vector represents an IPv6 address (with port number).
1291 If optional second argument OMIT-PORT is non-nil, don't include a port
1292 number in the string, even when present in ADDRESS.
1293 Returns nil if format of ADDRESS is invalid. */)
1294 (Lisp_Object address, Lisp_Object omit_port)
1296 if (NILP (address))
1297 return Qnil;
1299 if (STRINGP (address)) /* AF_LOCAL */
1300 return address;
1302 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1304 register struct Lisp_Vector *p = XVECTOR (address);
1305 ptrdiff_t size = p->header.size;
1306 Lisp_Object args[10];
1307 int nargs, i;
1308 char const *format;
1310 if (size == 4 || (size == 5 && !NILP (omit_port)))
1312 format = "%d.%d.%d.%d";
1313 nargs = 4;
1315 else if (size == 5)
1317 format = "%d.%d.%d.%d:%d";
1318 nargs = 5;
1320 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1322 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1323 nargs = 8;
1325 else if (size == 9)
1327 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1328 nargs = 9;
1330 else
1331 return Qnil;
1333 AUTO_STRING (format_obj, format);
1334 args[0] = format_obj;
1336 for (i = 0; i < nargs; i++)
1338 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1339 return Qnil;
1341 if (nargs <= 5 /* IPv4 */
1342 && i < 4 /* host, not port */
1343 && XINT (p->contents[i]) > 255)
1344 return Qnil;
1346 args[i + 1] = p->contents[i];
1349 return Fformat (nargs + 1, args);
1352 if (CONSP (address))
1354 AUTO_STRING (format, "<Family %d>");
1355 return Fformat (2, (Lisp_Object []) {format, Fcar (address)});
1358 return Qnil;
1361 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1362 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1363 (void)
1365 return Fmapcar (Qcdr, Vprocess_alist);
1368 /* Starting asynchronous inferior processes. */
1370 static void start_process_unwind (Lisp_Object proc);
1372 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1373 doc: /* Start a program in a subprocess. Return the process object for it.
1374 NAME is name for process. It is modified if necessary to make it unique.
1375 BUFFER is the buffer (or buffer name) to associate with the process.
1377 Process output (both standard output and standard error streams) goes
1378 at end of BUFFER, unless you specify an output stream or filter
1379 function to handle the output. BUFFER may also be nil, meaning that
1380 this process is not associated with any buffer.
1382 PROGRAM is the program file name. It is searched for in `exec-path'
1383 (which see). If nil, just associate a pty with the buffer. Remaining
1384 arguments are strings to give program as arguments.
1386 If you want to separate standard output from standard error, invoke
1387 the command through a shell and redirect one of them using the shell
1388 syntax.
1390 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1391 (ptrdiff_t nargs, Lisp_Object *args)
1393 Lisp_Object buffer, name, program, proc, current_dir, tem;
1394 unsigned char **new_argv;
1395 ptrdiff_t i;
1396 ptrdiff_t count = SPECPDL_INDEX ();
1397 USE_SAFE_ALLOCA;
1399 buffer = args[1];
1400 if (!NILP (buffer))
1401 buffer = Fget_buffer_create (buffer);
1403 /* Make sure that the child will be able to chdir to the current
1404 buffer's current directory, or its unhandled equivalent. We
1405 can't just have the child check for an error when it does the
1406 chdir, since it's in a vfork.
1408 We have to GCPRO around this because Fexpand_file_name and
1409 Funhandled_file_name_directory might call a file name handling
1410 function. The argument list is protected by the caller, so all
1411 we really have to worry about is buffer. */
1413 struct gcpro gcpro1;
1414 GCPRO1 (buffer);
1415 current_dir = encode_current_directory ();
1416 UNGCPRO;
1419 name = args[0];
1420 CHECK_STRING (name);
1422 program = args[2];
1424 if (!NILP (program))
1425 CHECK_STRING (program);
1427 proc = make_process (name);
1428 /* If an error occurs and we can't start the process, we want to
1429 remove it from the process list. This means that each error
1430 check in create_process doesn't need to call remove_process
1431 itself; it's all taken care of here. */
1432 record_unwind_protect (start_process_unwind, proc);
1434 pset_childp (XPROCESS (proc), Qt);
1435 pset_plist (XPROCESS (proc), Qnil);
1436 pset_type (XPROCESS (proc), Qreal);
1437 pset_buffer (XPROCESS (proc), buffer);
1438 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1439 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1440 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1442 #ifdef HAVE_GNUTLS
1443 /* AKA GNUTLS_INITSTAGE(proc). */
1444 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1445 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1446 #endif
1448 #ifdef ADAPTIVE_READ_BUFFERING
1449 XPROCESS (proc)->adaptive_read_buffering
1450 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1451 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1452 #endif
1454 /* Make the process marker point into the process buffer (if any). */
1455 if (BUFFERP (buffer))
1456 set_marker_both (XPROCESS (proc)->mark, buffer,
1457 BUF_ZV (XBUFFER (buffer)),
1458 BUF_ZV_BYTE (XBUFFER (buffer)));
1461 /* Decide coding systems for communicating with the process. Here
1462 we don't setup the structure coding_system nor pay attention to
1463 unibyte mode. They are done in create_process. */
1465 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1466 Lisp_Object coding_systems = Qt;
1467 Lisp_Object val, *args2;
1468 struct gcpro gcpro1, gcpro2;
1470 val = Vcoding_system_for_read;
1471 if (NILP (val))
1473 SAFE_ALLOCA_LISP (args2, nargs + 1);
1474 args2[0] = Qstart_process;
1475 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1476 GCPRO2 (proc, current_dir);
1477 if (!NILP (program))
1478 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1479 UNGCPRO;
1480 if (CONSP (coding_systems))
1481 val = XCAR (coding_systems);
1482 else if (CONSP (Vdefault_process_coding_system))
1483 val = XCAR (Vdefault_process_coding_system);
1485 pset_decode_coding_system (XPROCESS (proc), val);
1487 val = Vcoding_system_for_write;
1488 if (NILP (val))
1490 if (EQ (coding_systems, Qt))
1492 SAFE_ALLOCA_LISP (args2, nargs + 1);
1493 args2[0] = Qstart_process;
1494 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1495 GCPRO2 (proc, current_dir);
1496 if (!NILP (program))
1497 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1498 UNGCPRO;
1500 if (CONSP (coding_systems))
1501 val = XCDR (coding_systems);
1502 else if (CONSP (Vdefault_process_coding_system))
1503 val = XCDR (Vdefault_process_coding_system);
1505 pset_encode_coding_system (XPROCESS (proc), val);
1506 /* Note: At this moment, the above coding system may leave
1507 text-conversion or eol-conversion unspecified. They will be
1508 decided after we read output from the process and decode it by
1509 some coding system, or just before we actually send a text to
1510 the process. */
1514 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1515 XPROCESS (proc)->decoding_carryover = 0;
1516 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1518 XPROCESS (proc)->inherit_coding_system_flag
1519 = !(NILP (buffer) || !inherit_process_coding_system);
1521 if (!NILP (program))
1523 /* If program file name is not absolute, search our path for it.
1524 Put the name we will really use in TEM. */
1525 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1526 && !(SCHARS (program) > 1
1527 && IS_DEVICE_SEP (SREF (program, 1))))
1529 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1531 tem = Qnil;
1532 GCPRO4 (name, program, buffer, current_dir);
1533 openp (Vexec_path, program, Vexec_suffixes, &tem,
1534 make_number (X_OK), false);
1535 UNGCPRO;
1536 if (NILP (tem))
1537 report_file_error ("Searching for program", program);
1538 tem = Fexpand_file_name (tem, Qnil);
1540 else
1542 if (!NILP (Ffile_directory_p (program)))
1543 error ("Specified program for new process is a directory");
1544 tem = program;
1547 /* If program file name starts with /: for quoting a magic name,
1548 discard that. */
1549 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1550 && SREF (tem, 1) == ':')
1551 tem = Fsubstring (tem, make_number (2), Qnil);
1554 Lisp_Object arg_encoding = Qnil;
1555 struct gcpro gcpro1;
1556 GCPRO1 (tem);
1558 /* Encode the file name and put it in NEW_ARGV.
1559 That's where the child will use it to execute the program. */
1560 tem = list1 (ENCODE_FILE (tem));
1562 /* Here we encode arguments by the coding system used for sending
1563 data to the process. We don't support using different coding
1564 systems for encoding arguments and for encoding data sent to the
1565 process. */
1567 for (i = 3; i < nargs; i++)
1569 tem = Fcons (args[i], tem);
1570 CHECK_STRING (XCAR (tem));
1571 if (STRING_MULTIBYTE (XCAR (tem)))
1573 if (NILP (arg_encoding))
1574 arg_encoding = (complement_process_encoding_system
1575 (XPROCESS (proc)->encode_coding_system));
1576 XSETCAR (tem,
1577 code_convert_string_norecord
1578 (XCAR (tem), arg_encoding, 1));
1582 UNGCPRO;
1585 /* Now that everything is encoded we can collect the strings into
1586 NEW_ARGV. */
1587 SAFE_NALLOCA (new_argv, 1, nargs - 1);
1588 new_argv[nargs - 2] = 0;
1590 for (i = nargs - 2; i-- != 0; )
1592 new_argv[i] = SDATA (XCAR (tem));
1593 tem = XCDR (tem);
1596 create_process (proc, (char **) new_argv, current_dir);
1598 else
1599 create_pty (proc);
1601 SAFE_FREE ();
1602 return unbind_to (count, proc);
1605 /* This function is the unwind_protect form for Fstart_process. If
1606 PROC doesn't have its pid set, then we know someone has signaled
1607 an error and the process wasn't started successfully, so we should
1608 remove it from the process list. */
1609 static void
1610 start_process_unwind (Lisp_Object proc)
1612 if (!PROCESSP (proc))
1613 emacs_abort ();
1615 /* Was PROC started successfully?
1616 -2 is used for a pty with no process, eg for gdb. */
1617 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1618 remove_process (proc);
1621 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1623 static void
1624 close_process_fd (int *fd_addr)
1626 int fd = *fd_addr;
1627 if (0 <= fd)
1629 *fd_addr = -1;
1630 emacs_close (fd);
1634 /* Indexes of file descriptors in open_fds. */
1635 enum
1637 /* The pipe from Emacs to its subprocess. */
1638 SUBPROCESS_STDIN,
1639 WRITE_TO_SUBPROCESS,
1641 /* The main pipe from the subprocess to Emacs. */
1642 READ_FROM_SUBPROCESS,
1643 SUBPROCESS_STDOUT,
1645 /* The pipe from the subprocess to Emacs that is closed when the
1646 subprocess execs. */
1647 READ_FROM_EXEC_MONITOR,
1648 EXEC_MONITOR_OUTPUT
1651 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1653 static void
1654 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1656 struct Lisp_Process *p = XPROCESS (process);
1657 int inchannel, outchannel;
1658 pid_t pid;
1659 int vfork_errno;
1660 int forkin, forkout;
1661 bool pty_flag = 0;
1662 char pty_name[PTY_NAME_SIZE];
1663 Lisp_Object lisp_pty_name = Qnil;
1664 sigset_t oldset;
1666 inchannel = outchannel = -1;
1668 if (!NILP (Vprocess_connection_type))
1669 outchannel = inchannel = allocate_pty (pty_name);
1671 if (inchannel >= 0)
1673 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1674 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1675 /* On most USG systems it does not work to open the pty's tty here,
1676 then close it and reopen it in the child. */
1677 /* Don't let this terminal become our controlling terminal
1678 (in case we don't have one). */
1679 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1680 if (forkin < 0)
1681 report_file_error ("Opening pty", Qnil);
1682 p->open_fd[SUBPROCESS_STDIN] = forkin;
1683 #else
1684 forkin = forkout = -1;
1685 #endif /* not USG, or USG_SUBTTY_WORKS */
1686 pty_flag = 1;
1687 lisp_pty_name = build_string (pty_name);
1689 else
1691 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1692 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1693 report_file_error ("Creating pipe", Qnil);
1694 forkin = p->open_fd[SUBPROCESS_STDIN];
1695 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1696 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1697 forkout = p->open_fd[SUBPROCESS_STDOUT];
1700 #ifndef WINDOWSNT
1701 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1702 report_file_error ("Creating pipe", Qnil);
1703 #endif
1705 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1706 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1708 /* Record this as an active process, with its channels. */
1709 chan_process[inchannel] = process;
1710 p->infd = inchannel;
1711 p->outfd = outchannel;
1713 /* Previously we recorded the tty descriptor used in the subprocess.
1714 It was only used for getting the foreground tty process, so now
1715 we just reopen the device (see emacs_get_tty_pgrp) as this is
1716 more portable (see USG_SUBTTY_WORKS above). */
1718 p->pty_flag = pty_flag;
1719 pset_status (p, Qrun);
1721 FD_SET (inchannel, &input_wait_mask);
1722 FD_SET (inchannel, &non_keyboard_wait_mask);
1723 if (inchannel > max_process_desc)
1724 max_process_desc = inchannel;
1726 /* This may signal an error. */
1727 setup_process_coding_systems (process);
1729 block_input ();
1730 block_child_signal (&oldset);
1732 #ifndef WINDOWSNT
1733 /* vfork, and prevent local vars from being clobbered by the vfork. */
1735 Lisp_Object volatile current_dir_volatile = current_dir;
1736 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1737 char **volatile new_argv_volatile = new_argv;
1738 int volatile forkin_volatile = forkin;
1739 int volatile forkout_volatile = forkout;
1740 struct Lisp_Process *p_volatile = p;
1742 pid = vfork ();
1744 current_dir = current_dir_volatile;
1745 lisp_pty_name = lisp_pty_name_volatile;
1746 new_argv = new_argv_volatile;
1747 forkin = forkin_volatile;
1748 forkout = forkout_volatile;
1749 p = p_volatile;
1751 pty_flag = p->pty_flag;
1754 if (pid == 0)
1755 #endif /* not WINDOWSNT */
1757 int xforkin = forkin;
1758 int xforkout = forkout;
1760 /* Make the pty be the controlling terminal of the process. */
1761 #ifdef HAVE_PTYS
1762 /* First, disconnect its current controlling terminal. */
1763 /* We tried doing setsid only if pty_flag, but it caused
1764 process_set_signal to fail on SGI when using a pipe. */
1765 setsid ();
1766 /* Make the pty's terminal the controlling terminal. */
1767 if (pty_flag && xforkin >= 0)
1769 #ifdef TIOCSCTTY
1770 /* We ignore the return value
1771 because faith@cs.unc.edu says that is necessary on Linux. */
1772 ioctl (xforkin, TIOCSCTTY, 0);
1773 #endif
1775 #if defined (LDISC1)
1776 if (pty_flag && xforkin >= 0)
1778 struct termios t;
1779 tcgetattr (xforkin, &t);
1780 t.c_lflag = LDISC1;
1781 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1782 emacs_perror ("create_process/tcsetattr LDISC1");
1784 #else
1785 #if defined (NTTYDISC) && defined (TIOCSETD)
1786 if (pty_flag && xforkin >= 0)
1788 /* Use new line discipline. */
1789 int ldisc = NTTYDISC;
1790 ioctl (xforkin, TIOCSETD, &ldisc);
1792 #endif
1793 #endif
1794 #ifdef TIOCNOTTY
1795 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1796 can do TIOCSPGRP only to the process's controlling tty. */
1797 if (pty_flag)
1799 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1800 I can't test it since I don't have 4.3. */
1801 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1802 if (j >= 0)
1804 ioctl (j, TIOCNOTTY, 0);
1805 emacs_close (j);
1808 #endif /* TIOCNOTTY */
1810 #if !defined (DONT_REOPEN_PTY)
1811 /*** There is a suggestion that this ought to be a
1812 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1813 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1814 that system does seem to need this code, even though
1815 both TIOCSCTTY is defined. */
1816 /* Now close the pty (if we had it open) and reopen it.
1817 This makes the pty the controlling terminal of the subprocess. */
1818 if (pty_flag)
1821 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1822 would work? */
1823 if (xforkin >= 0)
1824 emacs_close (xforkin);
1825 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1827 if (xforkin < 0)
1829 emacs_perror (SSDATA (lisp_pty_name));
1830 _exit (EXIT_CANCELED);
1834 #endif /* not DONT_REOPEN_PTY */
1836 #ifdef SETUP_SLAVE_PTY
1837 if (pty_flag)
1839 SETUP_SLAVE_PTY;
1841 #endif /* SETUP_SLAVE_PTY */
1842 #endif /* HAVE_PTYS */
1844 signal (SIGINT, SIG_DFL);
1845 signal (SIGQUIT, SIG_DFL);
1846 #ifdef SIGPROF
1847 signal (SIGPROF, SIG_DFL);
1848 #endif
1850 /* Emacs ignores SIGPIPE, but the child should not. */
1851 signal (SIGPIPE, SIG_DFL);
1853 /* Stop blocking SIGCHLD in the child. */
1854 unblock_child_signal (&oldset);
1856 if (pty_flag)
1857 child_setup_tty (xforkout);
1858 #ifdef WINDOWSNT
1859 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1860 #else /* not WINDOWSNT */
1861 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1862 #endif /* not WINDOWSNT */
1865 /* Back in the parent process. */
1867 vfork_errno = errno;
1868 p->pid = pid;
1869 if (pid >= 0)
1870 p->alive = 1;
1872 /* Stop blocking in the parent. */
1873 unblock_child_signal (&oldset);
1874 unblock_input ();
1876 if (pid < 0)
1877 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1878 else
1880 /* vfork succeeded. */
1882 /* Close the pipe ends that the child uses, or the child's pty. */
1883 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1884 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1886 #ifdef WINDOWSNT
1887 register_child (pid, inchannel);
1888 #endif /* WINDOWSNT */
1890 pset_tty_name (p, lisp_pty_name);
1892 #ifndef WINDOWSNT
1893 /* Wait for child_setup to complete in case that vfork is
1894 actually defined as fork. The descriptor
1895 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1896 of a pipe is closed at the child side either by close-on-exec
1897 on successful execve or the _exit call in child_setup. */
1899 char dummy;
1901 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1902 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1903 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1905 #endif
1909 static void
1910 create_pty (Lisp_Object process)
1912 struct Lisp_Process *p = XPROCESS (process);
1913 char pty_name[PTY_NAME_SIZE];
1914 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1916 if (pty_fd >= 0)
1918 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1919 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1920 /* On most USG systems it does not work to open the pty's tty here,
1921 then close it and reopen it in the child. */
1922 /* Don't let this terminal become our controlling terminal
1923 (in case we don't have one). */
1924 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1925 if (forkout < 0)
1926 report_file_error ("Opening pty", Qnil);
1927 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1928 #if defined (DONT_REOPEN_PTY)
1929 /* In the case that vfork is defined as fork, the parent process
1930 (Emacs) may send some data before the child process completes
1931 tty options setup. So we setup tty before forking. */
1932 child_setup_tty (forkout);
1933 #endif /* DONT_REOPEN_PTY */
1934 #endif /* not USG, or USG_SUBTTY_WORKS */
1936 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1938 /* Record this as an active process, with its channels.
1939 As a result, child_setup will close Emacs's side of the pipes. */
1940 chan_process[pty_fd] = process;
1941 p->infd = pty_fd;
1942 p->outfd = pty_fd;
1944 /* Previously we recorded the tty descriptor used in the subprocess.
1945 It was only used for getting the foreground tty process, so now
1946 we just reopen the device (see emacs_get_tty_pgrp) as this is
1947 more portable (see USG_SUBTTY_WORKS above). */
1949 p->pty_flag = 1;
1950 pset_status (p, Qrun);
1951 setup_process_coding_systems (process);
1953 FD_SET (pty_fd, &input_wait_mask);
1954 FD_SET (pty_fd, &non_keyboard_wait_mask);
1955 if (pty_fd > max_process_desc)
1956 max_process_desc = pty_fd;
1958 pset_tty_name (p, build_string (pty_name));
1961 p->pid = -2;
1965 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1966 The address family of sa is not included in the result. */
1968 Lisp_Object
1969 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1971 Lisp_Object address;
1972 int i;
1973 unsigned char *cp;
1974 register struct Lisp_Vector *p;
1976 /* Workaround for a bug in getsockname on BSD: Names bound to
1977 sockets in the UNIX domain are inaccessible; getsockname returns
1978 a zero length name. */
1979 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1980 return empty_unibyte_string;
1982 switch (sa->sa_family)
1984 case AF_INET:
1986 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1987 len = sizeof (sin->sin_addr) + 1;
1988 address = Fmake_vector (make_number (len), Qnil);
1989 p = XVECTOR (address);
1990 p->contents[--len] = make_number (ntohs (sin->sin_port));
1991 cp = (unsigned char *) &sin->sin_addr;
1992 break;
1994 #ifdef AF_INET6
1995 case AF_INET6:
1997 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1998 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1999 len = sizeof (sin6->sin6_addr) / 2 + 1;
2000 address = Fmake_vector (make_number (len), Qnil);
2001 p = XVECTOR (address);
2002 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2003 for (i = 0; i < len; i++)
2004 p->contents[i] = make_number (ntohs (ip6[i]));
2005 return address;
2007 #endif
2008 #ifdef HAVE_LOCAL_SOCKETS
2009 case AF_LOCAL:
2011 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2012 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2013 /* If the first byte is NUL, the name is a Linux abstract
2014 socket name, and the name can contain embedded NULs. If
2015 it's not, we have a NUL-terminated string. Be careful not
2016 to walk past the end of the object looking for the name
2017 terminator, however. */
2018 if (name_length > 0 && sockun->sun_path[0] != '\0')
2020 const char *terminator
2021 = memchr (sockun->sun_path, '\0', name_length);
2023 if (terminator)
2024 name_length = terminator - (const char *) sockun->sun_path;
2027 return make_unibyte_string (sockun->sun_path, name_length);
2029 #endif
2030 default:
2031 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2032 address = Fcons (make_number (sa->sa_family),
2033 Fmake_vector (make_number (len), Qnil));
2034 p = XVECTOR (XCDR (address));
2035 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2036 break;
2039 i = 0;
2040 while (i < len)
2041 p->contents[i++] = make_number (*cp++);
2043 return address;
2047 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2049 static int
2050 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2052 register struct Lisp_Vector *p;
2054 if (VECTORP (address))
2056 p = XVECTOR (address);
2057 if (p->header.size == 5)
2059 *familyp = AF_INET;
2060 return sizeof (struct sockaddr_in);
2062 #ifdef AF_INET6
2063 else if (p->header.size == 9)
2065 *familyp = AF_INET6;
2066 return sizeof (struct sockaddr_in6);
2068 #endif
2070 #ifdef HAVE_LOCAL_SOCKETS
2071 else if (STRINGP (address))
2073 *familyp = AF_LOCAL;
2074 return sizeof (struct sockaddr_un);
2076 #endif
2077 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2078 && VECTORP (XCDR (address)))
2080 struct sockaddr *sa;
2081 p = XVECTOR (XCDR (address));
2082 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2083 return 0;
2084 *familyp = XINT (XCAR (address));
2085 return p->header.size + sizeof (sa->sa_family);
2087 return 0;
2090 /* Convert an address object (vector or string) to an internal sockaddr.
2092 The address format has been basically validated by
2093 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2094 it could have come from user data. So if FAMILY is not valid,
2095 we return after zeroing *SA. */
2097 static void
2098 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2100 register struct Lisp_Vector *p;
2101 register unsigned char *cp = NULL;
2102 register int i;
2103 EMACS_INT hostport;
2105 memset (sa, 0, len);
2107 if (VECTORP (address))
2109 p = XVECTOR (address);
2110 if (family == AF_INET)
2112 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2113 len = sizeof (sin->sin_addr) + 1;
2114 hostport = XINT (p->contents[--len]);
2115 sin->sin_port = htons (hostport);
2116 cp = (unsigned char *)&sin->sin_addr;
2117 sa->sa_family = family;
2119 #ifdef AF_INET6
2120 else if (family == AF_INET6)
2122 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2123 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2124 len = sizeof (sin6->sin6_addr) + 1;
2125 hostport = XINT (p->contents[--len]);
2126 sin6->sin6_port = htons (hostport);
2127 for (i = 0; i < len; i++)
2128 if (INTEGERP (p->contents[i]))
2130 int j = XFASTINT (p->contents[i]) & 0xffff;
2131 ip6[i] = ntohs (j);
2133 sa->sa_family = family;
2134 return;
2136 #endif
2137 else
2138 return;
2140 else if (STRINGP (address))
2142 #ifdef HAVE_LOCAL_SOCKETS
2143 if (family == AF_LOCAL)
2145 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2146 cp = SDATA (address);
2147 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2148 sockun->sun_path[i] = *cp++;
2149 sa->sa_family = family;
2151 #endif
2152 return;
2154 else
2156 p = XVECTOR (XCDR (address));
2157 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2160 for (i = 0; i < len; i++)
2161 if (INTEGERP (p->contents[i]))
2162 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2165 #ifdef DATAGRAM_SOCKETS
2166 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2167 1, 1, 0,
2168 doc: /* Get the current datagram address associated with PROCESS. */)
2169 (Lisp_Object process)
2171 int channel;
2173 CHECK_PROCESS (process);
2175 if (!DATAGRAM_CONN_P (process))
2176 return Qnil;
2178 channel = XPROCESS (process)->infd;
2179 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2180 datagram_address[channel].len);
2183 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2184 2, 2, 0,
2185 doc: /* Set the datagram address for PROCESS to ADDRESS.
2186 Returns nil upon error setting address, ADDRESS otherwise. */)
2187 (Lisp_Object process, Lisp_Object address)
2189 int channel;
2190 int family, len;
2192 CHECK_PROCESS (process);
2194 if (!DATAGRAM_CONN_P (process))
2195 return Qnil;
2197 channel = XPROCESS (process)->infd;
2199 len = get_lisp_to_sockaddr_size (address, &family);
2200 if (len == 0 || datagram_address[channel].len != len)
2201 return Qnil;
2202 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2203 return address;
2205 #endif
2208 static const struct socket_options {
2209 /* The name of this option. Should be lowercase version of option
2210 name without SO_ prefix. */
2211 const char *name;
2212 /* Option level SOL_... */
2213 int optlevel;
2214 /* Option number SO_... */
2215 int optnum;
2216 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2217 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2218 } socket_options[] =
2220 #ifdef SO_BINDTODEVICE
2221 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2222 #endif
2223 #ifdef SO_BROADCAST
2224 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2225 #endif
2226 #ifdef SO_DONTROUTE
2227 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2228 #endif
2229 #ifdef SO_KEEPALIVE
2230 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2231 #endif
2232 #ifdef SO_LINGER
2233 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2234 #endif
2235 #ifdef SO_OOBINLINE
2236 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2237 #endif
2238 #ifdef SO_PRIORITY
2239 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2240 #endif
2241 #ifdef SO_REUSEADDR
2242 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2243 #endif
2244 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2247 /* Set option OPT to value VAL on socket S.
2249 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2250 Signals an error if setting a known option fails.
2253 static int
2254 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2256 char *name;
2257 const struct socket_options *sopt;
2258 int ret = 0;
2260 CHECK_SYMBOL (opt);
2262 name = SSDATA (SYMBOL_NAME (opt));
2263 for (sopt = socket_options; sopt->name; sopt++)
2264 if (strcmp (name, sopt->name) == 0)
2265 break;
2267 switch (sopt->opttype)
2269 case SOPT_BOOL:
2271 int optval;
2272 optval = NILP (val) ? 0 : 1;
2273 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2274 &optval, sizeof (optval));
2275 break;
2278 case SOPT_INT:
2280 int optval;
2281 if (TYPE_RANGED_INTEGERP (int, val))
2282 optval = XINT (val);
2283 else
2284 error ("Bad option value for %s", name);
2285 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2286 &optval, sizeof (optval));
2287 break;
2290 #ifdef SO_BINDTODEVICE
2291 case SOPT_IFNAME:
2293 char devname[IFNAMSIZ + 1];
2295 /* This is broken, at least in the Linux 2.4 kernel.
2296 To unbind, the arg must be a zero integer, not the empty string.
2297 This should work on all systems. KFS. 2003-09-23. */
2298 memset (devname, 0, sizeof devname);
2299 if (STRINGP (val))
2301 char *arg = SSDATA (val);
2302 int len = min (strlen (arg), IFNAMSIZ);
2303 memcpy (devname, arg, len);
2305 else if (!NILP (val))
2306 error ("Bad option value for %s", name);
2307 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2308 devname, IFNAMSIZ);
2309 break;
2311 #endif
2313 #ifdef SO_LINGER
2314 case SOPT_LINGER:
2316 struct linger linger;
2318 linger.l_onoff = 1;
2319 linger.l_linger = 0;
2320 if (TYPE_RANGED_INTEGERP (int, val))
2321 linger.l_linger = XINT (val);
2322 else
2323 linger.l_onoff = NILP (val) ? 0 : 1;
2324 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2325 &linger, sizeof (linger));
2326 break;
2328 #endif
2330 default:
2331 return 0;
2334 if (ret < 0)
2336 int setsockopt_errno = errno;
2337 report_file_errno ("Cannot set network option", list2 (opt, val),
2338 setsockopt_errno);
2341 return (1 << sopt->optbit);
2345 DEFUN ("set-network-process-option",
2346 Fset_network_process_option, Sset_network_process_option,
2347 3, 4, 0,
2348 doc: /* For network process PROCESS set option OPTION to value VALUE.
2349 See `make-network-process' for a list of options and values.
2350 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2351 OPTION is not a supported option, return nil instead; otherwise return t. */)
2352 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2354 int s;
2355 struct Lisp_Process *p;
2357 CHECK_PROCESS (process);
2358 p = XPROCESS (process);
2359 if (!NETCONN1_P (p))
2360 error ("Process is not a network process");
2362 s = p->infd;
2363 if (s < 0)
2364 error ("Process is not running");
2366 if (set_socket_option (s, option, value))
2368 pset_childp (p, Fplist_put (p->childp, option, value));
2369 return Qt;
2372 if (NILP (no_error))
2373 error ("Unknown or unsupported option");
2375 return Qnil;
2379 DEFUN ("serial-process-configure",
2380 Fserial_process_configure,
2381 Sserial_process_configure,
2382 0, MANY, 0,
2383 doc: /* Configure speed, bytesize, etc. of a serial process.
2385 Arguments are specified as keyword/argument pairs. Attributes that
2386 are not given are re-initialized from the process's current
2387 configuration (available via the function `process-contact') or set to
2388 reasonable default values. The following arguments are defined:
2390 :process PROCESS
2391 :name NAME
2392 :buffer BUFFER
2393 :port PORT
2394 -- Any of these arguments can be given to identify the process that is
2395 to be configured. If none of these arguments is given, the current
2396 buffer's process is used.
2398 :speed SPEED -- SPEED is the speed of the serial port in bits per
2399 second, also called baud rate. Any value can be given for SPEED, but
2400 most serial ports work only at a few defined values between 1200 and
2401 115200, with 9600 being the most common value. If SPEED is nil, the
2402 serial port is not configured any further, i.e., all other arguments
2403 are ignored. This may be useful for special serial ports such as
2404 Bluetooth-to-serial converters which can only be configured through AT
2405 commands. A value of nil for SPEED can be used only when passed
2406 through `make-serial-process' or `serial-term'.
2408 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2409 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2411 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2412 `odd' (use odd parity), or the symbol `even' (use even parity). If
2413 PARITY is not given, no parity is used.
2415 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2416 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2417 is not given or nil, 1 stopbit is used.
2419 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2420 flowcontrol to be used, which is either nil (don't use flowcontrol),
2421 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2422 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2423 flowcontrol is used.
2425 `serial-process-configure' is called by `make-serial-process' for the
2426 initial configuration of the serial port.
2428 Examples:
2430 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2432 \(serial-process-configure
2433 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2435 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2437 usage: (serial-process-configure &rest ARGS) */)
2438 (ptrdiff_t nargs, Lisp_Object *args)
2440 struct Lisp_Process *p;
2441 Lisp_Object contact = Qnil;
2442 Lisp_Object proc = Qnil;
2443 struct gcpro gcpro1;
2445 contact = Flist (nargs, args);
2446 GCPRO1 (contact);
2448 proc = Fplist_get (contact, QCprocess);
2449 if (NILP (proc))
2450 proc = Fplist_get (contact, QCname);
2451 if (NILP (proc))
2452 proc = Fplist_get (contact, QCbuffer);
2453 if (NILP (proc))
2454 proc = Fplist_get (contact, QCport);
2455 proc = get_process (proc);
2456 p = XPROCESS (proc);
2457 if (!EQ (p->type, Qserial))
2458 error ("Not a serial process");
2460 if (NILP (Fplist_get (p->childp, QCspeed)))
2462 UNGCPRO;
2463 return Qnil;
2466 serial_configure (p, contact);
2468 UNGCPRO;
2469 return Qnil;
2472 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2473 0, MANY, 0,
2474 doc: /* Create and return a serial port process.
2476 In Emacs, serial port connections are represented by process objects,
2477 so input and output work as for subprocesses, and `delete-process'
2478 closes a serial port connection. However, a serial process has no
2479 process id, it cannot be signaled, and the status codes are different
2480 from normal processes.
2482 `make-serial-process' creates a process and a buffer, on which you
2483 probably want to use `process-send-string'. Try \\[serial-term] for
2484 an interactive terminal. See below for examples.
2486 Arguments are specified as keyword/argument pairs. The following
2487 arguments are defined:
2489 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2490 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2491 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2492 the backslashes in strings).
2494 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2495 which this function calls.
2497 :name NAME -- NAME is the name of the process. If NAME is not given,
2498 the value of PORT is used.
2500 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2501 with the process. Process output goes at the end of that buffer,
2502 unless you specify an output stream or filter function to handle the
2503 output. If BUFFER is not given, the value of NAME is used.
2505 :coding CODING -- If CODING is a symbol, it specifies the coding
2506 system used for both reading and writing for this process. If CODING
2507 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2508 ENCODING is used for writing.
2510 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2511 the process is running. If BOOL is not given, query before exiting.
2513 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2514 In the stopped state, a serial process does not accept incoming data,
2515 but you can send outgoing data. The stopped state is cleared by
2516 `continue-process' and set by `stop-process'.
2518 :filter FILTER -- Install FILTER as the process filter.
2520 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2522 :plist PLIST -- Install PLIST as the initial plist of the process.
2524 :bytesize
2525 :parity
2526 :stopbits
2527 :flowcontrol
2528 -- This function calls `serial-process-configure' to handle these
2529 arguments.
2531 The original argument list, possibly modified by later configuration,
2532 is available via the function `process-contact'.
2534 Examples:
2536 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2538 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2540 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2542 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2544 usage: (make-serial-process &rest ARGS) */)
2545 (ptrdiff_t nargs, Lisp_Object *args)
2547 int fd = -1;
2548 Lisp_Object proc, contact, port;
2549 struct Lisp_Process *p;
2550 struct gcpro gcpro1;
2551 Lisp_Object name, buffer;
2552 Lisp_Object tem, val;
2553 ptrdiff_t specpdl_count;
2555 if (nargs == 0)
2556 return Qnil;
2558 contact = Flist (nargs, args);
2559 GCPRO1 (contact);
2561 port = Fplist_get (contact, QCport);
2562 if (NILP (port))
2563 error ("No port specified");
2564 CHECK_STRING (port);
2566 if (NILP (Fplist_member (contact, QCspeed)))
2567 error (":speed not specified");
2568 if (!NILP (Fplist_get (contact, QCspeed)))
2569 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2571 name = Fplist_get (contact, QCname);
2572 if (NILP (name))
2573 name = port;
2574 CHECK_STRING (name);
2575 proc = make_process (name);
2576 specpdl_count = SPECPDL_INDEX ();
2577 record_unwind_protect (remove_process, proc);
2578 p = XPROCESS (proc);
2580 fd = serial_open (port);
2581 p->open_fd[SUBPROCESS_STDIN] = fd;
2582 p->infd = fd;
2583 p->outfd = fd;
2584 if (fd > max_process_desc)
2585 max_process_desc = fd;
2586 chan_process[fd] = proc;
2588 buffer = Fplist_get (contact, QCbuffer);
2589 if (NILP (buffer))
2590 buffer = name;
2591 buffer = Fget_buffer_create (buffer);
2592 pset_buffer (p, buffer);
2594 pset_childp (p, contact);
2595 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2596 pset_type (p, Qserial);
2597 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2598 pset_filter (p, Fplist_get (contact, QCfilter));
2599 pset_log (p, Qnil);
2600 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2601 p->kill_without_query = 1;
2602 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2603 pset_command (p, Qt);
2604 eassert (! p->pty_flag);
2606 if (!EQ (p->command, Qt))
2608 FD_SET (fd, &input_wait_mask);
2609 FD_SET (fd, &non_keyboard_wait_mask);
2612 if (BUFFERP (buffer))
2614 set_marker_both (p->mark, buffer,
2615 BUF_ZV (XBUFFER (buffer)),
2616 BUF_ZV_BYTE (XBUFFER (buffer)));
2619 tem = Fplist_member (contact, QCcoding);
2620 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2621 tem = Qnil;
2623 val = Qnil;
2624 if (!NILP (tem))
2626 val = XCAR (XCDR (tem));
2627 if (CONSP (val))
2628 val = XCAR (val);
2630 else if (!NILP (Vcoding_system_for_read))
2631 val = Vcoding_system_for_read;
2632 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2633 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2634 val = Qnil;
2635 pset_decode_coding_system (p, val);
2637 val = Qnil;
2638 if (!NILP (tem))
2640 val = XCAR (XCDR (tem));
2641 if (CONSP (val))
2642 val = XCDR (val);
2644 else if (!NILP (Vcoding_system_for_write))
2645 val = Vcoding_system_for_write;
2646 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2647 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2648 val = Qnil;
2649 pset_encode_coding_system (p, val);
2651 setup_process_coding_systems (proc);
2652 pset_decoding_buf (p, empty_unibyte_string);
2653 p->decoding_carryover = 0;
2654 pset_encoding_buf (p, empty_unibyte_string);
2655 p->inherit_coding_system_flag
2656 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2658 Fserial_process_configure (nargs, args);
2660 specpdl_ptr = specpdl + specpdl_count;
2662 UNGCPRO;
2663 return proc;
2666 /* Create a network stream/datagram client/server process. Treated
2667 exactly like a normal process when reading and writing. Primary
2668 differences are in status display and process deletion. A network
2669 connection has no PID; you cannot signal it. All you can do is
2670 stop/continue it and deactivate/close it via delete-process. */
2672 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2673 0, MANY, 0,
2674 doc: /* Create and return a network server or client process.
2676 In Emacs, network connections are represented by process objects, so
2677 input and output work as for subprocesses and `delete-process' closes
2678 a network connection. However, a network process has no process id,
2679 it cannot be signaled, and the status codes are different from normal
2680 processes.
2682 Arguments are specified as keyword/argument pairs. The following
2683 arguments are defined:
2685 :name NAME -- NAME is name for process. It is modified if necessary
2686 to make it unique.
2688 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2689 with the process. Process output goes at end of that buffer, unless
2690 you specify an output stream or filter function to handle the output.
2691 BUFFER may be also nil, meaning that this process is not associated
2692 with any buffer.
2694 :host HOST -- HOST is name of the host to connect to, or its IP
2695 address. The symbol `local' specifies the local host. If specified
2696 for a server process, it must be a valid name or address for the local
2697 host, and only clients connecting to that address will be accepted.
2699 :service SERVICE -- SERVICE is name of the service desired, or an
2700 integer specifying a port number to connect to. If SERVICE is t,
2701 a random port number is selected for the server. (If Emacs was
2702 compiled with getaddrinfo, a port number can also be specified as a
2703 string, e.g. "80", as well as an integer. This is not portable.)
2705 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2706 stream type connection, `datagram' creates a datagram type connection,
2707 `seqpacket' creates a reliable datagram connection.
2709 :family FAMILY -- FAMILY is the address (and protocol) family for the
2710 service specified by HOST and SERVICE. The default (nil) is to use
2711 whatever address family (IPv4 or IPv6) that is defined for the host
2712 and port number specified by HOST and SERVICE. Other address families
2713 supported are:
2714 local -- for a local (i.e. UNIX) address specified by SERVICE.
2715 ipv4 -- use IPv4 address family only.
2716 ipv6 -- use IPv6 address family only.
2718 :local ADDRESS -- ADDRESS is the local address used for the connection.
2719 This parameter is ignored when opening a client process. When specified
2720 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2722 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2723 connection. This parameter is ignored when opening a stream server
2724 process. For a datagram server process, it specifies the initial
2725 setting of the remote datagram address. When specified for a client
2726 process, the FAMILY, HOST, and SERVICE args are ignored.
2728 The format of ADDRESS depends on the address family:
2729 - An IPv4 address is represented as an vector of integers [A B C D P]
2730 corresponding to numeric IP address A.B.C.D and port number P.
2731 - A local address is represented as a string with the address in the
2732 local address space.
2733 - An "unsupported family" address is represented by a cons (F . AV)
2734 where F is the family number and AV is a vector containing the socket
2735 address data with one element per address data byte. Do not rely on
2736 this format in portable code, as it may depend on implementation
2737 defined constants, data sizes, and data structure alignment.
2739 :coding CODING -- If CODING is a symbol, it specifies the coding
2740 system used for both reading and writing for this process. If CODING
2741 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2742 ENCODING is used for writing.
2744 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2745 return without waiting for the connection to complete; instead, the
2746 sentinel function will be called with second arg matching "open" (if
2747 successful) or "failed" when the connect completes. Default is to use
2748 a blocking connect (i.e. wait) for stream type connections.
2750 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2751 running when Emacs is exited.
2753 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2754 In the stopped state, a server process does not accept new
2755 connections, and a client process does not handle incoming traffic.
2756 The stopped state is cleared by `continue-process' and set by
2757 `stop-process'.
2759 :filter FILTER -- Install FILTER as the process filter.
2761 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2762 process filter are multibyte, otherwise they are unibyte.
2763 If this keyword is not specified, the strings are multibyte if
2764 the default value of `enable-multibyte-characters' is non-nil.
2766 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2768 :log LOG -- Install LOG as the server process log function. This
2769 function is called when the server accepts a network connection from a
2770 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2771 is the server process, CLIENT is the new process for the connection,
2772 and MESSAGE is a string.
2774 :plist PLIST -- Install PLIST as the new process's initial plist.
2776 :server QLEN -- if QLEN is non-nil, create a server process for the
2777 specified FAMILY, SERVICE, and connection type (stream or datagram).
2778 If QLEN is an integer, it is used as the max. length of the server's
2779 pending connection queue (also known as the backlog); the default
2780 queue length is 5. Default is to create a client process.
2782 The following network options can be specified for this connection:
2784 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2785 :dontroute BOOL -- Only send to directly connected hosts.
2786 :keepalive BOOL -- Send keep-alive messages on network stream.
2787 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2788 :oobinline BOOL -- Place out-of-band data in receive data stream.
2789 :priority INT -- Set protocol defined priority for sent packets.
2790 :reuseaddr BOOL -- Allow reusing a recently used local address
2791 (this is allowed by default for a server process).
2792 :bindtodevice NAME -- bind to interface NAME. Using this may require
2793 special privileges on some systems.
2795 Consult the relevant system programmer's manual pages for more
2796 information on using these options.
2799 A server process will listen for and accept connections from clients.
2800 When a client connection is accepted, a new network process is created
2801 for the connection with the following parameters:
2803 - The client's process name is constructed by concatenating the server
2804 process's NAME and a client identification string.
2805 - If the FILTER argument is non-nil, the client process will not get a
2806 separate process buffer; otherwise, the client's process buffer is a newly
2807 created buffer named after the server process's BUFFER name or process
2808 NAME concatenated with the client identification string.
2809 - The connection type and the process filter and sentinel parameters are
2810 inherited from the server process's TYPE, FILTER and SENTINEL.
2811 - The client process's contact info is set according to the client's
2812 addressing information (typically an IP address and a port number).
2813 - The client process's plist is initialized from the server's plist.
2815 Notice that the FILTER and SENTINEL args are never used directly by
2816 the server process. Also, the BUFFER argument is not used directly by
2817 the server process, but via the optional :log function, accepted (and
2818 failed) connections may be logged in the server process's buffer.
2820 The original argument list, modified with the actual connection
2821 information, is available via the `process-contact' function.
2823 usage: (make-network-process &rest ARGS) */)
2824 (ptrdiff_t nargs, Lisp_Object *args)
2826 Lisp_Object proc;
2827 Lisp_Object contact;
2828 struct Lisp_Process *p;
2829 #ifdef HAVE_GETADDRINFO
2830 struct addrinfo ai, *res, *lres;
2831 struct addrinfo hints;
2832 const char *portstring;
2833 char portbuf[128];
2834 #else /* HAVE_GETADDRINFO */
2835 struct _emacs_addrinfo
2837 int ai_family;
2838 int ai_socktype;
2839 int ai_protocol;
2840 int ai_addrlen;
2841 struct sockaddr *ai_addr;
2842 struct _emacs_addrinfo *ai_next;
2843 } ai, *res, *lres;
2844 #endif /* HAVE_GETADDRINFO */
2845 struct sockaddr_in address_in;
2846 #ifdef HAVE_LOCAL_SOCKETS
2847 struct sockaddr_un address_un;
2848 #endif
2849 int port;
2850 int ret = 0;
2851 int xerrno = 0;
2852 int s = -1, outch, inch;
2853 struct gcpro gcpro1;
2854 ptrdiff_t count = SPECPDL_INDEX ();
2855 ptrdiff_t count1;
2856 Lisp_Object colon_address; /* Either QClocal or QCremote. */
2857 Lisp_Object tem;
2858 Lisp_Object name, buffer, host, service, address;
2859 Lisp_Object filter, sentinel;
2860 bool is_non_blocking_client = 0;
2861 bool is_server = 0;
2862 int backlog = 5;
2863 int socktype;
2864 int family = -1;
2866 if (nargs == 0)
2867 return Qnil;
2869 /* Save arguments for process-contact and clone-process. */
2870 contact = Flist (nargs, args);
2871 GCPRO1 (contact);
2873 #ifdef WINDOWSNT
2874 /* Ensure socket support is loaded if available. */
2875 init_winsock (TRUE);
2876 #endif
2878 /* :type TYPE (nil: stream, datagram */
2879 tem = Fplist_get (contact, QCtype);
2880 if (NILP (tem))
2881 socktype = SOCK_STREAM;
2882 #ifdef DATAGRAM_SOCKETS
2883 else if (EQ (tem, Qdatagram))
2884 socktype = SOCK_DGRAM;
2885 #endif
2886 #ifdef HAVE_SEQPACKET
2887 else if (EQ (tem, Qseqpacket))
2888 socktype = SOCK_SEQPACKET;
2889 #endif
2890 else
2891 error ("Unsupported connection type");
2893 /* :server BOOL */
2894 tem = Fplist_get (contact, QCserver);
2895 if (!NILP (tem))
2897 /* Don't support network sockets when non-blocking mode is
2898 not available, since a blocked Emacs is not useful. */
2899 is_server = 1;
2900 if (TYPE_RANGED_INTEGERP (int, tem))
2901 backlog = XINT (tem);
2904 /* Make colon_address an alias for :local (server) or :remote (client). */
2905 colon_address = is_server ? QClocal : QCremote;
2907 /* :nowait BOOL */
2908 if (!is_server && socktype != SOCK_DGRAM
2909 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2911 #ifndef NON_BLOCKING_CONNECT
2912 error ("Non-blocking connect not supported");
2913 #else
2914 is_non_blocking_client = 1;
2915 #endif
2918 name = Fplist_get (contact, QCname);
2919 buffer = Fplist_get (contact, QCbuffer);
2920 filter = Fplist_get (contact, QCfilter);
2921 sentinel = Fplist_get (contact, QCsentinel);
2923 CHECK_STRING (name);
2925 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2926 ai.ai_socktype = socktype;
2927 ai.ai_protocol = 0;
2928 ai.ai_next = NULL;
2929 res = &ai;
2931 /* :local ADDRESS or :remote ADDRESS */
2932 address = Fplist_get (contact, colon_address);
2933 if (!NILP (address))
2935 host = service = Qnil;
2937 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2938 error ("Malformed :address");
2939 ai.ai_family = family;
2940 ai.ai_addr = alloca (ai.ai_addrlen);
2941 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2942 goto open_socket;
2945 /* :family FAMILY -- nil (for Inet), local, or integer. */
2946 tem = Fplist_get (contact, QCfamily);
2947 if (NILP (tem))
2949 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2950 family = AF_UNSPEC;
2951 #else
2952 family = AF_INET;
2953 #endif
2955 #ifdef HAVE_LOCAL_SOCKETS
2956 else if (EQ (tem, Qlocal))
2957 family = AF_LOCAL;
2958 #endif
2959 #ifdef AF_INET6
2960 else if (EQ (tem, Qipv6))
2961 family = AF_INET6;
2962 #endif
2963 else if (EQ (tem, Qipv4))
2964 family = AF_INET;
2965 else if (TYPE_RANGED_INTEGERP (int, tem))
2966 family = XINT (tem);
2967 else
2968 error ("Unknown address family");
2970 ai.ai_family = family;
2972 /* :service SERVICE -- string, integer (port number), or t (random port). */
2973 service = Fplist_get (contact, QCservice);
2975 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2976 host = Fplist_get (contact, QChost);
2977 if (!NILP (host))
2979 if (EQ (host, Qlocal))
2980 /* Depending on setup, "localhost" may map to different IPv4 and/or
2981 IPv6 addresses, so it's better to be explicit (Bug#6781). */
2982 host = build_string ("127.0.0.1");
2983 CHECK_STRING (host);
2986 #ifdef HAVE_LOCAL_SOCKETS
2987 if (family == AF_LOCAL)
2989 if (!NILP (host))
2991 message (":family local ignores the :host \"%s\" property",
2992 SDATA (host));
2993 contact = Fplist_put (contact, QChost, Qnil);
2994 host = Qnil;
2996 CHECK_STRING (service);
2997 memset (&address_un, 0, sizeof address_un);
2998 address_un.sun_family = AF_LOCAL;
2999 if (sizeof address_un.sun_path <= SBYTES (service))
3000 error ("Service name too long");
3001 lispstpcpy (address_un.sun_path, service);
3002 ai.ai_addr = (struct sockaddr *) &address_un;
3003 ai.ai_addrlen = sizeof address_un;
3004 goto open_socket;
3006 #endif
3008 /* Slow down polling to every ten seconds.
3009 Some kernels have a bug which causes retrying connect to fail
3010 after a connect. Polling can interfere with gethostbyname too. */
3011 #ifdef POLL_FOR_INPUT
3012 if (socktype != SOCK_DGRAM)
3014 record_unwind_protect_void (run_all_atimers);
3015 bind_polling_period (10);
3017 #endif
3019 #ifdef HAVE_GETADDRINFO
3020 /* If we have a host, use getaddrinfo to resolve both host and service.
3021 Otherwise, use getservbyname to lookup the service. */
3022 if (!NILP (host))
3025 /* SERVICE can either be a string or int.
3026 Convert to a C string for later use by getaddrinfo. */
3027 if (EQ (service, Qt))
3028 portstring = "0";
3029 else if (INTEGERP (service))
3031 sprintf (portbuf, "%"pI"d", XINT (service));
3032 portstring = portbuf;
3034 else
3036 CHECK_STRING (service);
3037 portstring = SSDATA (service);
3040 immediate_quit = 1;
3041 QUIT;
3042 memset (&hints, 0, sizeof (hints));
3043 hints.ai_flags = 0;
3044 hints.ai_family = family;
3045 hints.ai_socktype = socktype;
3046 hints.ai_protocol = 0;
3048 #ifdef HAVE_RES_INIT
3049 res_init ();
3050 #endif
3052 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3053 if (ret)
3054 #ifdef HAVE_GAI_STRERROR
3055 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3056 #else
3057 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3058 #endif
3059 immediate_quit = 0;
3061 goto open_socket;
3063 #endif /* HAVE_GETADDRINFO */
3065 /* We end up here if getaddrinfo is not defined, or in case no hostname
3066 has been specified (e.g. for a local server process). */
3068 if (EQ (service, Qt))
3069 port = 0;
3070 else if (INTEGERP (service))
3071 port = htons ((unsigned short) XINT (service));
3072 else
3074 struct servent *svc_info;
3075 CHECK_STRING (service);
3076 svc_info = getservbyname (SSDATA (service),
3077 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3078 if (svc_info == 0)
3079 error ("Unknown service: %s", SDATA (service));
3080 port = svc_info->s_port;
3083 memset (&address_in, 0, sizeof address_in);
3084 address_in.sin_family = family;
3085 address_in.sin_addr.s_addr = INADDR_ANY;
3086 address_in.sin_port = port;
3088 #ifndef HAVE_GETADDRINFO
3089 if (!NILP (host))
3091 struct hostent *host_info_ptr;
3093 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3094 as it may `hang' Emacs for a very long time. */
3095 immediate_quit = 1;
3096 QUIT;
3098 #ifdef HAVE_RES_INIT
3099 res_init ();
3100 #endif
3102 host_info_ptr = gethostbyname (SDATA (host));
3103 immediate_quit = 0;
3105 if (host_info_ptr)
3107 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3108 host_info_ptr->h_length);
3109 family = host_info_ptr->h_addrtype;
3110 address_in.sin_family = family;
3112 else
3113 /* Attempt to interpret host as numeric inet address. */
3115 unsigned long numeric_addr;
3116 numeric_addr = inet_addr (SSDATA (host));
3117 if (numeric_addr == -1)
3118 error ("Unknown host \"%s\"", SDATA (host));
3120 memcpy (&address_in.sin_addr, &numeric_addr,
3121 sizeof (address_in.sin_addr));
3125 #endif /* not HAVE_GETADDRINFO */
3127 ai.ai_family = family;
3128 ai.ai_addr = (struct sockaddr *) &address_in;
3129 ai.ai_addrlen = sizeof address_in;
3131 open_socket:
3133 /* Do this in case we never enter the for-loop below. */
3134 count1 = SPECPDL_INDEX ();
3135 s = -1;
3137 for (lres = res; lres; lres = lres->ai_next)
3139 ptrdiff_t optn;
3140 int optbits;
3142 #ifdef WINDOWSNT
3143 retry_connect:
3144 #endif
3146 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3147 lres->ai_protocol);
3148 if (s < 0)
3150 xerrno = errno;
3151 continue;
3154 #ifdef DATAGRAM_SOCKETS
3155 if (!is_server && socktype == SOCK_DGRAM)
3156 break;
3157 #endif /* DATAGRAM_SOCKETS */
3159 #ifdef NON_BLOCKING_CONNECT
3160 if (is_non_blocking_client)
3162 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3163 if (ret < 0)
3165 xerrno = errno;
3166 emacs_close (s);
3167 s = -1;
3168 continue;
3171 #endif
3173 /* Make us close S if quit. */
3174 record_unwind_protect_int (close_file_unwind, s);
3176 /* Parse network options in the arg list.
3177 We simply ignore anything which isn't a known option (including other keywords).
3178 An error is signaled if setting a known option fails. */
3179 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3180 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3182 if (is_server)
3184 /* Configure as a server socket. */
3186 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3187 explicit :reuseaddr key to override this. */
3188 #ifdef HAVE_LOCAL_SOCKETS
3189 if (family != AF_LOCAL)
3190 #endif
3191 if (!(optbits & (1 << OPIX_REUSEADDR)))
3193 int optval = 1;
3194 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3195 report_file_error ("Cannot set reuse option on server socket", Qnil);
3198 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3199 report_file_error ("Cannot bind server socket", Qnil);
3201 #ifdef HAVE_GETSOCKNAME
3202 if (EQ (service, Qt))
3204 struct sockaddr_in sa1;
3205 socklen_t len1 = sizeof (sa1);
3206 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3208 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3209 service = make_number (ntohs (sa1.sin_port));
3210 contact = Fplist_put (contact, QCservice, service);
3213 #endif
3215 if (socktype != SOCK_DGRAM && listen (s, backlog))
3216 report_file_error ("Cannot listen on server socket", Qnil);
3218 break;
3221 immediate_quit = 1;
3222 QUIT;
3224 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3225 xerrno = errno;
3227 if (ret == 0 || xerrno == EISCONN)
3229 /* The unwind-protect will be discarded afterwards.
3230 Likewise for immediate_quit. */
3231 break;
3234 #ifdef NON_BLOCKING_CONNECT
3235 #ifdef EINPROGRESS
3236 if (is_non_blocking_client && xerrno == EINPROGRESS)
3237 break;
3238 #else
3239 #ifdef EWOULDBLOCK
3240 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3241 break;
3242 #endif
3243 #endif
3244 #endif
3246 #ifndef WINDOWSNT
3247 if (xerrno == EINTR)
3249 /* Unlike most other syscalls connect() cannot be called
3250 again. (That would return EALREADY.) The proper way to
3251 wait for completion is pselect(). */
3252 int sc;
3253 socklen_t len;
3254 fd_set fdset;
3255 retry_select:
3256 FD_ZERO (&fdset);
3257 FD_SET (s, &fdset);
3258 QUIT;
3259 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3260 if (sc == -1)
3262 if (errno == EINTR)
3263 goto retry_select;
3264 else
3265 report_file_error ("Failed select", Qnil);
3267 eassert (sc > 0);
3269 len = sizeof xerrno;
3270 eassert (FD_ISSET (s, &fdset));
3271 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3272 report_file_error ("Failed getsockopt", Qnil);
3273 if (xerrno)
3274 report_file_errno ("Failed connect", Qnil, xerrno);
3275 break;
3277 #endif /* !WINDOWSNT */
3279 immediate_quit = 0;
3281 /* Discard the unwind protect closing S. */
3282 specpdl_ptr = specpdl + count1;
3283 emacs_close (s);
3284 s = -1;
3286 #ifdef WINDOWSNT
3287 if (xerrno == EINTR)
3288 goto retry_connect;
3289 #endif
3292 if (s >= 0)
3294 #ifdef DATAGRAM_SOCKETS
3295 if (socktype == SOCK_DGRAM)
3297 if (datagram_address[s].sa)
3298 emacs_abort ();
3299 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3300 datagram_address[s].len = lres->ai_addrlen;
3301 if (is_server)
3303 Lisp_Object remote;
3304 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3305 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3307 int rfamily, rlen;
3308 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3309 if (rlen != 0 && rfamily == lres->ai_family
3310 && rlen == lres->ai_addrlen)
3311 conv_lisp_to_sockaddr (rfamily, remote,
3312 datagram_address[s].sa, rlen);
3315 else
3316 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3318 #endif
3319 contact = Fplist_put (contact, colon_address,
3320 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3321 #ifdef HAVE_GETSOCKNAME
3322 if (!is_server)
3324 struct sockaddr_in sa1;
3325 socklen_t len1 = sizeof (sa1);
3326 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3327 contact = Fplist_put (contact, QClocal,
3328 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3330 #endif
3333 immediate_quit = 0;
3335 #ifdef HAVE_GETADDRINFO
3336 if (res != &ai)
3338 block_input ();
3339 freeaddrinfo (res);
3340 unblock_input ();
3342 #endif
3344 if (s < 0)
3346 /* If non-blocking got this far - and failed - assume non-blocking is
3347 not supported after all. This is probably a wrong assumption, but
3348 the normal blocking calls to open-network-stream handles this error
3349 better. */
3350 if (is_non_blocking_client)
3351 return Qnil;
3353 report_file_errno ((is_server
3354 ? "make server process failed"
3355 : "make client process failed"),
3356 contact, xerrno);
3359 inch = s;
3360 outch = s;
3362 if (!NILP (buffer))
3363 buffer = Fget_buffer_create (buffer);
3364 proc = make_process (name);
3366 chan_process[inch] = proc;
3368 fcntl (inch, F_SETFL, O_NONBLOCK);
3370 p = XPROCESS (proc);
3372 pset_childp (p, contact);
3373 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3374 pset_type (p, Qnetwork);
3376 pset_buffer (p, buffer);
3377 pset_sentinel (p, sentinel);
3378 pset_filter (p, filter);
3379 pset_log (p, Fplist_get (contact, QClog));
3380 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3381 p->kill_without_query = 1;
3382 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3383 pset_command (p, Qt);
3384 p->pid = 0;
3386 p->open_fd[SUBPROCESS_STDIN] = inch;
3387 p->infd = inch;
3388 p->outfd = outch;
3390 /* Discard the unwind protect for closing S, if any. */
3391 specpdl_ptr = specpdl + count1;
3393 /* Unwind bind_polling_period and request_sigio. */
3394 unbind_to (count, Qnil);
3396 if (is_server && socktype != SOCK_DGRAM)
3397 pset_status (p, Qlisten);
3399 /* Make the process marker point into the process buffer (if any). */
3400 if (BUFFERP (buffer))
3401 set_marker_both (p->mark, buffer,
3402 BUF_ZV (XBUFFER (buffer)),
3403 BUF_ZV_BYTE (XBUFFER (buffer)));
3405 #ifdef NON_BLOCKING_CONNECT
3406 if (is_non_blocking_client)
3408 /* We may get here if connect did succeed immediately. However,
3409 in that case, we still need to signal this like a non-blocking
3410 connection. */
3411 pset_status (p, Qconnect);
3412 if (!FD_ISSET (inch, &connect_wait_mask))
3414 FD_SET (inch, &connect_wait_mask);
3415 FD_SET (inch, &write_mask);
3416 num_pending_connects++;
3419 else
3420 #endif
3421 /* A server may have a client filter setting of Qt, but it must
3422 still listen for incoming connects unless it is stopped. */
3423 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3424 || (EQ (p->status, Qlisten) && NILP (p->command)))
3426 FD_SET (inch, &input_wait_mask);
3427 FD_SET (inch, &non_keyboard_wait_mask);
3430 if (inch > max_process_desc)
3431 max_process_desc = inch;
3433 tem = Fplist_member (contact, QCcoding);
3434 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3435 tem = Qnil; /* No error message (too late!). */
3438 /* Setup coding systems for communicating with the network stream. */
3439 struct gcpro gcpro1;
3440 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3441 Lisp_Object coding_systems = Qt;
3442 Lisp_Object fargs[5], val;
3444 if (!NILP (tem))
3446 val = XCAR (XCDR (tem));
3447 if (CONSP (val))
3448 val = XCAR (val);
3450 else if (!NILP (Vcoding_system_for_read))
3451 val = Vcoding_system_for_read;
3452 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3453 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3454 /* We dare not decode end-of-line format by setting VAL to
3455 Qraw_text, because the existing Emacs Lisp libraries
3456 assume that they receive bare code including a sequence of
3457 CR LF. */
3458 val = Qnil;
3459 else
3461 if (NILP (host) || NILP (service))
3462 coding_systems = Qnil;
3463 else
3465 fargs[0] = Qopen_network_stream, fargs[1] = name,
3466 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3467 GCPRO1 (proc);
3468 coding_systems = Ffind_operation_coding_system (5, fargs);
3469 UNGCPRO;
3471 if (CONSP (coding_systems))
3472 val = XCAR (coding_systems);
3473 else if (CONSP (Vdefault_process_coding_system))
3474 val = XCAR (Vdefault_process_coding_system);
3475 else
3476 val = Qnil;
3478 pset_decode_coding_system (p, val);
3480 if (!NILP (tem))
3482 val = XCAR (XCDR (tem));
3483 if (CONSP (val))
3484 val = XCDR (val);
3486 else if (!NILP (Vcoding_system_for_write))
3487 val = Vcoding_system_for_write;
3488 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3489 val = Qnil;
3490 else
3492 if (EQ (coding_systems, Qt))
3494 if (NILP (host) || NILP (service))
3495 coding_systems = Qnil;
3496 else
3498 fargs[0] = Qopen_network_stream, fargs[1] = name,
3499 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3500 GCPRO1 (proc);
3501 coding_systems = Ffind_operation_coding_system (5, fargs);
3502 UNGCPRO;
3505 if (CONSP (coding_systems))
3506 val = XCDR (coding_systems);
3507 else if (CONSP (Vdefault_process_coding_system))
3508 val = XCDR (Vdefault_process_coding_system);
3509 else
3510 val = Qnil;
3512 pset_encode_coding_system (p, val);
3514 setup_process_coding_systems (proc);
3516 pset_decoding_buf (p, empty_unibyte_string);
3517 p->decoding_carryover = 0;
3518 pset_encoding_buf (p, empty_unibyte_string);
3520 p->inherit_coding_system_flag
3521 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3523 UNGCPRO;
3524 return proc;
3528 #ifdef HAVE_NET_IF_H
3530 #ifdef SIOCGIFCONF
3531 static Lisp_Object
3532 network_interface_list (void)
3534 struct ifconf ifconf;
3535 struct ifreq *ifreq;
3536 void *buf = NULL;
3537 ptrdiff_t buf_size = 512;
3538 int s;
3539 Lisp_Object res;
3540 ptrdiff_t count;
3542 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3543 if (s < 0)
3544 return Qnil;
3545 count = SPECPDL_INDEX ();
3546 record_unwind_protect_int (close_file_unwind, s);
3550 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3551 ifconf.ifc_buf = buf;
3552 ifconf.ifc_len = buf_size;
3553 if (ioctl (s, SIOCGIFCONF, &ifconf))
3555 emacs_close (s);
3556 xfree (buf);
3557 return Qnil;
3560 while (ifconf.ifc_len == buf_size);
3562 res = unbind_to (count, Qnil);
3563 ifreq = ifconf.ifc_req;
3564 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3566 struct ifreq *ifq = ifreq;
3567 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3568 #define SIZEOF_IFREQ(sif) \
3569 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3570 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3572 int len = SIZEOF_IFREQ (ifq);
3573 #else
3574 int len = sizeof (*ifreq);
3575 #endif
3576 char namebuf[sizeof (ifq->ifr_name) + 1];
3577 ifreq = (struct ifreq *) ((char *) ifreq + len);
3579 if (ifq->ifr_addr.sa_family != AF_INET)
3580 continue;
3582 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3583 namebuf[sizeof (ifq->ifr_name)] = 0;
3584 res = Fcons (Fcons (build_string (namebuf),
3585 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3586 sizeof (struct sockaddr))),
3587 res);
3590 xfree (buf);
3591 return res;
3593 #endif /* SIOCGIFCONF */
3595 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3597 struct ifflag_def {
3598 int flag_bit;
3599 const char *flag_sym;
3602 static const struct ifflag_def ifflag_table[] = {
3603 #ifdef IFF_UP
3604 { IFF_UP, "up" },
3605 #endif
3606 #ifdef IFF_BROADCAST
3607 { IFF_BROADCAST, "broadcast" },
3608 #endif
3609 #ifdef IFF_DEBUG
3610 { IFF_DEBUG, "debug" },
3611 #endif
3612 #ifdef IFF_LOOPBACK
3613 { IFF_LOOPBACK, "loopback" },
3614 #endif
3615 #ifdef IFF_POINTOPOINT
3616 { IFF_POINTOPOINT, "pointopoint" },
3617 #endif
3618 #ifdef IFF_RUNNING
3619 { IFF_RUNNING, "running" },
3620 #endif
3621 #ifdef IFF_NOARP
3622 { IFF_NOARP, "noarp" },
3623 #endif
3624 #ifdef IFF_PROMISC
3625 { IFF_PROMISC, "promisc" },
3626 #endif
3627 #ifdef IFF_NOTRAILERS
3628 #ifdef NS_IMPL_COCOA
3629 /* Really means smart, notrailers is obsolete. */
3630 { IFF_NOTRAILERS, "smart" },
3631 #else
3632 { IFF_NOTRAILERS, "notrailers" },
3633 #endif
3634 #endif
3635 #ifdef IFF_ALLMULTI
3636 { IFF_ALLMULTI, "allmulti" },
3637 #endif
3638 #ifdef IFF_MASTER
3639 { IFF_MASTER, "master" },
3640 #endif
3641 #ifdef IFF_SLAVE
3642 { IFF_SLAVE, "slave" },
3643 #endif
3644 #ifdef IFF_MULTICAST
3645 { IFF_MULTICAST, "multicast" },
3646 #endif
3647 #ifdef IFF_PORTSEL
3648 { IFF_PORTSEL, "portsel" },
3649 #endif
3650 #ifdef IFF_AUTOMEDIA
3651 { IFF_AUTOMEDIA, "automedia" },
3652 #endif
3653 #ifdef IFF_DYNAMIC
3654 { IFF_DYNAMIC, "dynamic" },
3655 #endif
3656 #ifdef IFF_OACTIVE
3657 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3658 #endif
3659 #ifdef IFF_SIMPLEX
3660 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3661 #endif
3662 #ifdef IFF_LINK0
3663 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3664 #endif
3665 #ifdef IFF_LINK1
3666 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3667 #endif
3668 #ifdef IFF_LINK2
3669 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3670 #endif
3671 { 0, 0 }
3674 static Lisp_Object
3675 network_interface_info (Lisp_Object ifname)
3677 struct ifreq rq;
3678 Lisp_Object res = Qnil;
3679 Lisp_Object elt;
3680 int s;
3681 bool any = 0;
3682 ptrdiff_t count;
3683 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3684 && defined HAVE_GETIFADDRS && defined LLADDR)
3685 struct ifaddrs *ifap;
3686 #endif
3688 CHECK_STRING (ifname);
3690 if (sizeof rq.ifr_name <= SBYTES (ifname))
3691 error ("interface name too long");
3692 lispstpcpy (rq.ifr_name, ifname);
3694 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3695 if (s < 0)
3696 return Qnil;
3697 count = SPECPDL_INDEX ();
3698 record_unwind_protect_int (close_file_unwind, s);
3700 elt = Qnil;
3701 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3702 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3704 int flags = rq.ifr_flags;
3705 const struct ifflag_def *fp;
3706 int fnum;
3708 /* If flags is smaller than int (i.e. short) it may have the high bit set
3709 due to IFF_MULTICAST. In that case, sign extending it into
3710 an int is wrong. */
3711 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3712 flags = (unsigned short) rq.ifr_flags;
3714 any = 1;
3715 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3717 if (flags & fp->flag_bit)
3719 elt = Fcons (intern (fp->flag_sym), elt);
3720 flags -= fp->flag_bit;
3723 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3725 if (flags & 1)
3727 elt = Fcons (make_number (fnum), elt);
3731 #endif
3732 res = Fcons (elt, res);
3734 elt = Qnil;
3735 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3736 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3738 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3739 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3740 int n;
3742 any = 1;
3743 for (n = 0; n < 6; n++)
3744 p->contents[n] = make_number (((unsigned char *)
3745 &rq.ifr_hwaddr.sa_data[0])
3746 [n]);
3747 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3749 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3750 if (getifaddrs (&ifap) != -1)
3752 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3753 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3754 struct ifaddrs *it;
3756 for (it = ifap; it != NULL; it = it->ifa_next)
3758 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3759 unsigned char linkaddr[6];
3760 int n;
3762 if (it->ifa_addr->sa_family != AF_LINK
3763 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3764 || sdl->sdl_alen != 6)
3765 continue;
3767 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3768 for (n = 0; n < 6; n++)
3769 p->contents[n] = make_number (linkaddr[n]);
3771 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3772 break;
3775 #ifdef HAVE_FREEIFADDRS
3776 freeifaddrs (ifap);
3777 #endif
3779 #endif /* HAVE_GETIFADDRS && LLADDR */
3781 res = Fcons (elt, res);
3783 elt = Qnil;
3784 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3785 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3787 any = 1;
3788 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3789 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3790 #else
3791 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3792 #endif
3794 #endif
3795 res = Fcons (elt, res);
3797 elt = Qnil;
3798 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3799 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3801 any = 1;
3802 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3804 #endif
3805 res = Fcons (elt, res);
3807 elt = Qnil;
3808 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3809 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3811 any = 1;
3812 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3814 #endif
3815 res = Fcons (elt, res);
3817 return unbind_to (count, any ? res : Qnil);
3819 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3820 #endif /* defined (HAVE_NET_IF_H) */
3822 DEFUN ("network-interface-list", Fnetwork_interface_list,
3823 Snetwork_interface_list, 0, 0, 0,
3824 doc: /* Return an alist of all network interfaces and their network address.
3825 Each element is a cons, the car of which is a string containing the
3826 interface name, and the cdr is the network address in internal
3827 format; see the description of ADDRESS in `make-network-process'.
3829 If the information is not available, return nil. */)
3830 (void)
3832 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3833 return network_interface_list ();
3834 #else
3835 return Qnil;
3836 #endif
3839 DEFUN ("network-interface-info", Fnetwork_interface_info,
3840 Snetwork_interface_info, 1, 1, 0,
3841 doc: /* Return information about network interface named IFNAME.
3842 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3843 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3844 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3845 FLAGS is the current flags of the interface.
3847 Data that is unavailable is returned as nil. */)
3848 (Lisp_Object ifname)
3850 #if ((defined HAVE_NET_IF_H \
3851 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3852 || defined SIOCGIFFLAGS)) \
3853 || defined WINDOWSNT)
3854 return network_interface_info (ifname);
3855 #else
3856 return Qnil;
3857 #endif
3861 /* Turn off input and output for process PROC. */
3863 static void
3864 deactivate_process (Lisp_Object proc)
3866 int inchannel;
3867 struct Lisp_Process *p = XPROCESS (proc);
3868 int i;
3870 #ifdef HAVE_GNUTLS
3871 /* Delete GnuTLS structures in PROC, if any. */
3872 emacs_gnutls_deinit (proc);
3873 #endif /* HAVE_GNUTLS */
3875 #ifdef ADAPTIVE_READ_BUFFERING
3876 if (p->read_output_delay > 0)
3878 if (--process_output_delay_count < 0)
3879 process_output_delay_count = 0;
3880 p->read_output_delay = 0;
3881 p->read_output_skip = 0;
3883 #endif
3885 /* Beware SIGCHLD hereabouts. */
3887 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3888 close_process_fd (&p->open_fd[i]);
3890 inchannel = p->infd;
3891 if (inchannel >= 0)
3893 p->infd = -1;
3894 p->outfd = -1;
3895 #ifdef DATAGRAM_SOCKETS
3896 if (DATAGRAM_CHAN_P (inchannel))
3898 xfree (datagram_address[inchannel].sa);
3899 datagram_address[inchannel].sa = 0;
3900 datagram_address[inchannel].len = 0;
3902 #endif
3903 chan_process[inchannel] = Qnil;
3904 FD_CLR (inchannel, &input_wait_mask);
3905 FD_CLR (inchannel, &non_keyboard_wait_mask);
3906 #ifdef NON_BLOCKING_CONNECT
3907 if (FD_ISSET (inchannel, &connect_wait_mask))
3909 FD_CLR (inchannel, &connect_wait_mask);
3910 FD_CLR (inchannel, &write_mask);
3911 if (--num_pending_connects < 0)
3912 emacs_abort ();
3914 #endif
3915 if (inchannel == max_process_desc)
3917 /* We just closed the highest-numbered process input descriptor,
3918 so recompute the highest-numbered one now. */
3919 int i = inchannel;
3921 i--;
3922 while (0 <= i && NILP (chan_process[i]));
3924 max_process_desc = i;
3930 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3931 0, 4, 0,
3932 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3933 It is given to their filter functions.
3934 Optional argument PROCESS means do not return until output has been
3935 received from PROCESS.
3937 Optional second argument SECONDS and third argument MILLISEC
3938 specify a timeout; return after that much time even if there is
3939 no subprocess output. If SECONDS is a floating point number,
3940 it specifies a fractional number of seconds to wait.
3941 The MILLISEC argument is obsolete and should be avoided.
3943 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
3944 from PROCESS only, suspending reading output from other processes.
3945 If JUST-THIS-ONE is an integer, don't run any timers either.
3946 Return non-nil if we received any output from PROCESS (or, if PROCESS
3947 is nil, from any process) before the timeout expired. */)
3948 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3950 intmax_t secs;
3951 int nsecs;
3953 if (! NILP (process))
3954 CHECK_PROCESS (process);
3955 else
3956 just_this_one = Qnil;
3958 if (!NILP (millisec))
3959 { /* Obsolete calling convention using integers rather than floats. */
3960 CHECK_NUMBER (millisec);
3961 if (NILP (seconds))
3962 seconds = make_float (XINT (millisec) / 1000.0);
3963 else
3965 CHECK_NUMBER (seconds);
3966 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3970 secs = 0;
3971 nsecs = -1;
3973 if (!NILP (seconds))
3975 if (INTEGERP (seconds))
3977 if (XINT (seconds) > 0)
3979 secs = XINT (seconds);
3980 nsecs = 0;
3983 else if (FLOATP (seconds))
3985 if (XFLOAT_DATA (seconds) > 0)
3987 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3988 secs = min (t.tv_sec, WAIT_READING_MAX);
3989 nsecs = t.tv_nsec;
3992 else
3993 wrong_type_argument (Qnumberp, seconds);
3995 else if (! NILP (process))
3996 nsecs = 0;
3998 return
3999 ((wait_reading_process_output (secs, nsecs, 0, 0,
4000 Qnil,
4001 !NILP (process) ? XPROCESS (process) : NULL,
4002 (NILP (just_this_one) ? 0
4003 : !INTEGERP (just_this_one) ? 1 : -1))
4004 <= 0)
4005 ? Qnil : Qt);
4008 /* Accept a connection for server process SERVER on CHANNEL. */
4010 static EMACS_INT connect_counter = 0;
4012 static void
4013 server_accept_connection (Lisp_Object server, int channel)
4015 Lisp_Object proc, caller, name, buffer;
4016 Lisp_Object contact, host, service;
4017 struct Lisp_Process *ps = XPROCESS (server);
4018 struct Lisp_Process *p;
4019 int s;
4020 union u_sockaddr {
4021 struct sockaddr sa;
4022 struct sockaddr_in in;
4023 #ifdef AF_INET6
4024 struct sockaddr_in6 in6;
4025 #endif
4026 #ifdef HAVE_LOCAL_SOCKETS
4027 struct sockaddr_un un;
4028 #endif
4029 } saddr;
4030 socklen_t len = sizeof saddr;
4031 ptrdiff_t count;
4033 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4035 if (s < 0)
4037 int code = errno;
4039 if (code == EAGAIN)
4040 return;
4041 #ifdef EWOULDBLOCK
4042 if (code == EWOULDBLOCK)
4043 return;
4044 #endif
4046 if (!NILP (ps->log))
4047 call3 (ps->log, server, Qnil,
4048 concat3 (build_string ("accept failed with code"),
4049 Fnumber_to_string (make_number (code)),
4050 build_string ("\n")));
4051 return;
4054 count = SPECPDL_INDEX ();
4055 record_unwind_protect_int (close_file_unwind, s);
4057 connect_counter++;
4059 /* Setup a new process to handle the connection. */
4061 /* Generate a unique identification of the caller, and build contact
4062 information for this process. */
4063 host = Qt;
4064 service = Qnil;
4065 switch (saddr.sa.sa_family)
4067 case AF_INET:
4069 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4071 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4072 host = Fformat (5, ((Lisp_Object [])
4073 { ipv4_format, make_number (ip[0]),
4074 make_number (ip[1]), make_number (ip[2]), make_number (ip[3]) }));
4075 service = make_number (ntohs (saddr.in.sin_port));
4076 AUTO_STRING (caller_format, " <%s:%d>");
4077 caller = Fformat (3, (Lisp_Object []) {caller_format, host, service});
4079 break;
4081 #ifdef AF_INET6
4082 case AF_INET6:
4084 Lisp_Object args[9];
4085 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4086 int i;
4088 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4089 args[0] = ipv6_format;
4090 for (i = 0; i < 8; i++)
4091 args[i + 1] = make_number (ntohs (ip6[i]));
4092 host = Fformat (9, args);
4093 service = make_number (ntohs (saddr.in.sin_port));
4094 AUTO_STRING (caller_format, " <[%s]:%d>");
4095 caller = Fformat (3, (Lisp_Object []) {caller_format, host, service});
4097 break;
4098 #endif
4100 #ifdef HAVE_LOCAL_SOCKETS
4101 case AF_LOCAL:
4102 #endif
4103 default:
4104 caller = Fnumber_to_string (make_number (connect_counter));
4105 AUTO_STRING (space_less_than, " <");
4106 AUTO_STRING (greater_than, ">");
4107 caller = concat3 (space_less_than, caller, greater_than);
4108 break;
4111 /* Create a new buffer name for this process if it doesn't have a
4112 filter. The new buffer name is based on the buffer name or
4113 process name of the server process concatenated with the caller
4114 identification. */
4116 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4117 || EQ (ps->filter, Qt)))
4118 buffer = Qnil;
4119 else
4121 buffer = ps->buffer;
4122 if (!NILP (buffer))
4123 buffer = Fbuffer_name (buffer);
4124 else
4125 buffer = ps->name;
4126 if (!NILP (buffer))
4128 buffer = concat2 (buffer, caller);
4129 buffer = Fget_buffer_create (buffer);
4133 /* Generate a unique name for the new server process. Combine the
4134 server process name with the caller identification. */
4136 name = concat2 (ps->name, caller);
4137 proc = make_process (name);
4139 chan_process[s] = proc;
4141 fcntl (s, F_SETFL, O_NONBLOCK);
4143 p = XPROCESS (proc);
4145 /* Build new contact information for this setup. */
4146 contact = Fcopy_sequence (ps->childp);
4147 contact = Fplist_put (contact, QCserver, Qnil);
4148 contact = Fplist_put (contact, QChost, host);
4149 if (!NILP (service))
4150 contact = Fplist_put (contact, QCservice, service);
4151 contact = Fplist_put (contact, QCremote,
4152 conv_sockaddr_to_lisp (&saddr.sa, len));
4153 #ifdef HAVE_GETSOCKNAME
4154 len = sizeof saddr;
4155 if (getsockname (s, &saddr.sa, &len) == 0)
4156 contact = Fplist_put (contact, QClocal,
4157 conv_sockaddr_to_lisp (&saddr.sa, len));
4158 #endif
4160 pset_childp (p, contact);
4161 pset_plist (p, Fcopy_sequence (ps->plist));
4162 pset_type (p, Qnetwork);
4164 pset_buffer (p, buffer);
4165 pset_sentinel (p, ps->sentinel);
4166 pset_filter (p, ps->filter);
4167 pset_command (p, Qnil);
4168 p->pid = 0;
4170 /* Discard the unwind protect for closing S. */
4171 specpdl_ptr = specpdl + count;
4173 p->open_fd[SUBPROCESS_STDIN] = s;
4174 p->infd = s;
4175 p->outfd = s;
4176 pset_status (p, Qrun);
4178 /* Client processes for accepted connections are not stopped initially. */
4179 if (!EQ (p->filter, Qt))
4181 FD_SET (s, &input_wait_mask);
4182 FD_SET (s, &non_keyboard_wait_mask);
4185 if (s > max_process_desc)
4186 max_process_desc = s;
4188 /* Setup coding system for new process based on server process.
4189 This seems to be the proper thing to do, as the coding system
4190 of the new process should reflect the settings at the time the
4191 server socket was opened; not the current settings. */
4193 pset_decode_coding_system (p, ps->decode_coding_system);
4194 pset_encode_coding_system (p, ps->encode_coding_system);
4195 setup_process_coding_systems (proc);
4197 pset_decoding_buf (p, empty_unibyte_string);
4198 p->decoding_carryover = 0;
4199 pset_encoding_buf (p, empty_unibyte_string);
4201 p->inherit_coding_system_flag
4202 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4204 AUTO_STRING (dash, "-");
4205 AUTO_STRING (nl, "\n");
4206 Lisp_Object host_string = STRINGP (host) ? host : dash;
4208 if (!NILP (ps->log))
4210 AUTO_STRING (accept_from, "accept from ");
4211 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4214 AUTO_STRING (open_from, "open from ");
4215 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4218 /* This variable is different from waiting_for_input in keyboard.c.
4219 It is used to communicate to a lisp process-filter/sentinel (via the
4220 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4221 for user-input when that process-filter was called.
4222 waiting_for_input cannot be used as that is by definition 0 when
4223 lisp code is being evalled.
4224 This is also used in record_asynch_buffer_change.
4225 For that purpose, this must be 0
4226 when not inside wait_reading_process_output. */
4227 static int waiting_for_user_input_p;
4229 static void
4230 wait_reading_process_output_unwind (int data)
4232 waiting_for_user_input_p = data;
4235 /* This is here so breakpoints can be put on it. */
4236 static void
4237 wait_reading_process_output_1 (void)
4241 /* Read and dispose of subprocess output while waiting for timeout to
4242 elapse and/or keyboard input to be available.
4244 TIME_LIMIT is:
4245 timeout in seconds
4246 If negative, gobble data immediately available but don't wait for any.
4248 NSECS is:
4249 an additional duration to wait, measured in nanoseconds
4250 If TIME_LIMIT is zero, then:
4251 If NSECS == 0, there is no limit.
4252 If NSECS > 0, the timeout consists of NSECS only.
4253 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4255 READ_KBD is:
4256 0 to ignore keyboard input, or
4257 1 to return when input is available, or
4258 -1 meaning caller will actually read the input, so don't throw to
4259 the quit handler, or
4261 DO_DISPLAY means redisplay should be done to show subprocess
4262 output that arrives.
4264 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4265 (and gobble terminal input into the buffer if any arrives).
4267 If WAIT_PROC is specified, wait until something arrives from that
4268 process.
4270 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4271 (suspending output from other processes). A negative value
4272 means don't run any timers either.
4274 Return positive if we received input from WAIT_PROC (or from any
4275 process if WAIT_PROC is null), zero if we attempted to receive
4276 input but got none, and negative if we didn't even try. */
4279 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4280 bool do_display,
4281 Lisp_Object wait_for_cell,
4282 struct Lisp_Process *wait_proc, int just_wait_proc)
4284 int channel, nfds;
4285 fd_set Available;
4286 fd_set Writeok;
4287 bool check_write;
4288 int check_delay;
4289 bool no_avail;
4290 int xerrno;
4291 Lisp_Object proc;
4292 struct timespec timeout, end_time;
4293 int got_some_input = -1;
4294 ptrdiff_t count = SPECPDL_INDEX ();
4296 FD_ZERO (&Available);
4297 FD_ZERO (&Writeok);
4299 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4300 && !(CONSP (wait_proc->status)
4301 && EQ (XCAR (wait_proc->status), Qexit)))
4302 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4304 record_unwind_protect_int (wait_reading_process_output_unwind,
4305 waiting_for_user_input_p);
4306 waiting_for_user_input_p = read_kbd;
4308 if (time_limit < 0)
4310 time_limit = 0;
4311 nsecs = -1;
4313 else if (TYPE_MAXIMUM (time_t) < time_limit)
4314 time_limit = TYPE_MAXIMUM (time_t);
4316 /* Since we may need to wait several times,
4317 compute the absolute time to return at. */
4318 if (time_limit || nsecs > 0)
4320 timeout = make_timespec (time_limit, nsecs);
4321 end_time = timespec_add (current_timespec (), timeout);
4324 while (1)
4326 bool timeout_reduced_for_timers = false;
4328 /* If calling from keyboard input, do not quit
4329 since we want to return C-g as an input character.
4330 Otherwise, do pending quit if requested. */
4331 if (read_kbd >= 0)
4332 QUIT;
4333 else if (pending_signals)
4334 process_pending_signals ();
4336 /* Exit now if the cell we're waiting for became non-nil. */
4337 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4338 break;
4340 /* After reading input, vacuum up any leftovers without waiting. */
4341 if (0 <= got_some_input)
4342 nsecs = -1;
4344 /* Compute time from now till when time limit is up. */
4345 /* Exit if already run out. */
4346 if (nsecs < 0)
4348 /* A negative timeout means
4349 gobble output available now
4350 but don't wait at all. */
4352 timeout = make_timespec (0, 0);
4354 else if (time_limit || nsecs > 0)
4356 struct timespec now = current_timespec ();
4357 if (timespec_cmp (end_time, now) <= 0)
4358 break;
4359 timeout = timespec_sub (end_time, now);
4361 else
4363 timeout = make_timespec (100000, 0);
4366 /* Normally we run timers here.
4367 But not if wait_for_cell; in those cases,
4368 the wait is supposed to be short,
4369 and those callers cannot handle running arbitrary Lisp code here. */
4370 if (NILP (wait_for_cell)
4371 && just_wait_proc >= 0)
4373 struct timespec timer_delay;
4377 unsigned old_timers_run = timers_run;
4378 struct buffer *old_buffer = current_buffer;
4379 Lisp_Object old_window = selected_window;
4381 timer_delay = timer_check ();
4383 /* If a timer has run, this might have changed buffers
4384 an alike. Make read_key_sequence aware of that. */
4385 if (timers_run != old_timers_run
4386 && (old_buffer != current_buffer
4387 || !EQ (old_window, selected_window))
4388 && waiting_for_user_input_p == -1)
4389 record_asynch_buffer_change ();
4391 if (timers_run != old_timers_run && do_display)
4392 /* We must retry, since a timer may have requeued itself
4393 and that could alter the time_delay. */
4394 redisplay_preserve_echo_area (9);
4395 else
4396 break;
4398 while (!detect_input_pending ());
4400 /* If there is unread keyboard input, also return. */
4401 if (read_kbd != 0
4402 && requeued_events_pending_p ())
4403 break;
4405 /* A negative timeout means do not wait at all. */
4406 if (nsecs >= 0)
4408 if (timespec_valid_p (timer_delay))
4410 if (timespec_cmp (timer_delay, timeout) < 0)
4412 timeout = timer_delay;
4413 timeout_reduced_for_timers = true;
4416 else
4418 /* This is so a breakpoint can be put here. */
4419 wait_reading_process_output_1 ();
4424 /* Cause C-g and alarm signals to take immediate action,
4425 and cause input available signals to zero out timeout.
4427 It is important that we do this before checking for process
4428 activity. If we get a SIGCHLD after the explicit checks for
4429 process activity, timeout is the only way we will know. */
4430 if (read_kbd < 0)
4431 set_waiting_for_input (&timeout);
4433 /* If status of something has changed, and no input is
4434 available, notify the user of the change right away. After
4435 this explicit check, we'll let the SIGCHLD handler zap
4436 timeout to get our attention. */
4437 if (update_tick != process_tick)
4439 fd_set Atemp;
4440 fd_set Ctemp;
4442 if (kbd_on_hold_p ())
4443 FD_ZERO (&Atemp);
4444 else
4445 Atemp = input_wait_mask;
4446 Ctemp = write_mask;
4448 timeout = make_timespec (0, 0);
4449 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4450 &Atemp,
4451 #ifdef NON_BLOCKING_CONNECT
4452 (num_pending_connects > 0 ? &Ctemp : NULL),
4453 #else
4454 NULL,
4455 #endif
4456 NULL, &timeout, NULL)
4457 <= 0))
4459 /* It's okay for us to do this and then continue with
4460 the loop, since timeout has already been zeroed out. */
4461 clear_waiting_for_input ();
4462 got_some_input = status_notify (NULL, wait_proc);
4463 if (do_display) redisplay_preserve_echo_area (13);
4467 /* Don't wait for output from a non-running process. Just
4468 read whatever data has already been received. */
4469 if (wait_proc && wait_proc->raw_status_new)
4470 update_status (wait_proc);
4471 if (wait_proc
4472 && wait_proc->infd >= 0
4473 && ! EQ (wait_proc->status, Qrun)
4474 && ! EQ (wait_proc->status, Qconnect))
4476 bool read_some_bytes = false;
4478 clear_waiting_for_input ();
4479 XSETPROCESS (proc, wait_proc);
4481 /* Read data from the process, until we exhaust it. */
4482 while (true)
4484 int nread = read_process_output (proc, wait_proc->infd);
4485 if (nread < 0)
4487 if (errno == EIO || errno == EAGAIN)
4488 break;
4489 #ifdef EWOULDBLOCK
4490 if (errno == EWOULDBLOCK)
4491 break;
4492 #endif
4494 else
4496 if (got_some_input < nread)
4497 got_some_input = nread;
4498 if (nread == 0)
4499 break;
4500 read_some_bytes = true;
4503 if (read_some_bytes && do_display)
4504 redisplay_preserve_echo_area (10);
4506 break;
4509 /* Wait till there is something to do. */
4511 if (wait_proc && just_wait_proc)
4513 if (wait_proc->infd < 0) /* Terminated. */
4514 break;
4515 FD_SET (wait_proc->infd, &Available);
4516 check_delay = 0;
4517 check_write = 0;
4519 else if (!NILP (wait_for_cell))
4521 Available = non_process_wait_mask;
4522 check_delay = 0;
4523 check_write = 0;
4525 else
4527 if (! read_kbd)
4528 Available = non_keyboard_wait_mask;
4529 else
4530 Available = input_wait_mask;
4531 Writeok = write_mask;
4532 check_delay = wait_proc ? 0 : process_output_delay_count;
4533 check_write = SELECT_CAN_DO_WRITE_MASK;
4536 /* If frame size has changed or the window is newly mapped,
4537 redisplay now, before we start to wait. There is a race
4538 condition here; if a SIGIO arrives between now and the select
4539 and indicates that a frame is trashed, the select may block
4540 displaying a trashed screen. */
4541 if (frame_garbaged && do_display)
4543 clear_waiting_for_input ();
4544 redisplay_preserve_echo_area (11);
4545 if (read_kbd < 0)
4546 set_waiting_for_input (&timeout);
4549 /* Skip the `select' call if input is available and we're
4550 waiting for keyboard input or a cell change (which can be
4551 triggered by processing X events). In the latter case, set
4552 nfds to 1 to avoid breaking the loop. */
4553 no_avail = 0;
4554 if ((read_kbd || !NILP (wait_for_cell))
4555 && detect_input_pending ())
4557 nfds = read_kbd ? 0 : 1;
4558 no_avail = 1;
4559 FD_ZERO (&Available);
4562 if (!no_avail)
4565 #ifdef ADAPTIVE_READ_BUFFERING
4566 /* Set the timeout for adaptive read buffering if any
4567 process has non-zero read_output_skip and non-zero
4568 read_output_delay, and we are not reading output for a
4569 specific process. It is not executed if
4570 Vprocess_adaptive_read_buffering is nil. */
4571 if (process_output_skip && check_delay > 0)
4573 int nsecs = timeout.tv_nsec;
4574 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4575 nsecs = READ_OUTPUT_DELAY_MAX;
4576 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4578 proc = chan_process[channel];
4579 if (NILP (proc))
4580 continue;
4581 /* Find minimum non-zero read_output_delay among the
4582 processes with non-zero read_output_skip. */
4583 if (XPROCESS (proc)->read_output_delay > 0)
4585 check_delay--;
4586 if (!XPROCESS (proc)->read_output_skip)
4587 continue;
4588 FD_CLR (channel, &Available);
4589 XPROCESS (proc)->read_output_skip = 0;
4590 if (XPROCESS (proc)->read_output_delay < nsecs)
4591 nsecs = XPROCESS (proc)->read_output_delay;
4594 timeout = make_timespec (0, nsecs);
4595 process_output_skip = 0;
4597 #endif
4599 #if defined (HAVE_NS)
4600 nfds = ns_select
4601 #elif defined (HAVE_GLIB)
4602 nfds = xg_select
4603 #else
4604 nfds = pselect
4605 #endif
4606 (max (max_process_desc, max_input_desc) + 1,
4607 &Available,
4608 (check_write ? &Writeok : 0),
4609 NULL, &timeout, NULL);
4611 #ifdef HAVE_GNUTLS
4612 /* GnuTLS buffers data internally. In lowat mode it leaves
4613 some data in the TCP buffers so that select works, but
4614 with custom pull/push functions we need to check if some
4615 data is available in the buffers manually. */
4616 if (nfds == 0)
4618 if (! wait_proc)
4620 /* We're not waiting on a specific process, so loop
4621 through all the channels and check for data.
4622 This is a workaround needed for some versions of
4623 the gnutls library -- 2.12.14 has been confirmed
4624 to need it. See
4625 http://comments.gmane.org/gmane.emacs.devel/145074 */
4626 for (channel = 0; channel < FD_SETSIZE; ++channel)
4627 if (! NILP (chan_process[channel]))
4629 struct Lisp_Process *p =
4630 XPROCESS (chan_process[channel]);
4631 if (p && p->gnutls_p && p->gnutls_state
4632 && ((emacs_gnutls_record_check_pending
4633 (p->gnutls_state))
4634 > 0))
4636 nfds++;
4637 eassert (p->infd == channel);
4638 FD_SET (p->infd, &Available);
4642 else
4644 /* Check this specific channel. */
4645 if (wait_proc->gnutls_p /* Check for valid process. */
4646 && wait_proc->gnutls_state
4647 /* Do we have pending data? */
4648 && ((emacs_gnutls_record_check_pending
4649 (wait_proc->gnutls_state))
4650 > 0))
4652 nfds = 1;
4653 eassert (0 <= wait_proc->infd);
4654 /* Set to Available. */
4655 FD_SET (wait_proc->infd, &Available);
4659 #endif
4662 xerrno = errno;
4664 /* Make C-g and alarm signals set flags again. */
4665 clear_waiting_for_input ();
4667 /* If we woke up due to SIGWINCH, actually change size now. */
4668 do_pending_window_change (0);
4670 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4671 /* We waited the full specified time, so return now. */
4672 break;
4673 if (nfds < 0)
4675 if (xerrno == EINTR)
4676 no_avail = 1;
4677 else if (xerrno == EBADF)
4678 emacs_abort ();
4679 else
4680 report_file_errno ("Failed select", Qnil, xerrno);
4683 /* Check for keyboard input. */
4684 /* If there is any, return immediately
4685 to give it higher priority than subprocesses. */
4687 if (read_kbd != 0)
4689 unsigned old_timers_run = timers_run;
4690 struct buffer *old_buffer = current_buffer;
4691 Lisp_Object old_window = selected_window;
4692 bool leave = false;
4694 if (detect_input_pending_run_timers (do_display))
4696 swallow_events (do_display);
4697 if (detect_input_pending_run_timers (do_display))
4698 leave = true;
4701 /* If a timer has run, this might have changed buffers
4702 an alike. Make read_key_sequence aware of that. */
4703 if (timers_run != old_timers_run
4704 && waiting_for_user_input_p == -1
4705 && (old_buffer != current_buffer
4706 || !EQ (old_window, selected_window)))
4707 record_asynch_buffer_change ();
4709 if (leave)
4710 break;
4713 /* If there is unread keyboard input, also return. */
4714 if (read_kbd != 0
4715 && requeued_events_pending_p ())
4716 break;
4718 /* If we are not checking for keyboard input now,
4719 do process events (but don't run any timers).
4720 This is so that X events will be processed.
4721 Otherwise they may have to wait until polling takes place.
4722 That would causes delays in pasting selections, for example.
4724 (We used to do this only if wait_for_cell.) */
4725 if (read_kbd == 0 && detect_input_pending ())
4727 swallow_events (do_display);
4728 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4729 if (detect_input_pending ())
4730 break;
4731 #endif
4734 /* Exit now if the cell we're waiting for became non-nil. */
4735 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4736 break;
4738 #ifdef USABLE_SIGIO
4739 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4740 go read it. This can happen with X on BSD after logging out.
4741 In that case, there really is no input and no SIGIO,
4742 but select says there is input. */
4744 if (read_kbd && interrupt_input
4745 && keyboard_bit_set (&Available) && ! noninteractive)
4746 handle_input_available_signal (SIGIO);
4747 #endif
4749 /* If checking input just got us a size-change event from X,
4750 obey it now if we should. */
4751 if (read_kbd || ! NILP (wait_for_cell))
4752 do_pending_window_change (0);
4754 /* Check for data from a process. */
4755 if (no_avail || nfds == 0)
4756 continue;
4758 for (channel = 0; channel <= max_input_desc; ++channel)
4760 struct fd_callback_data *d = &fd_callback_info[channel];
4761 if (d->func
4762 && ((d->condition & FOR_READ
4763 && FD_ISSET (channel, &Available))
4764 || (d->condition & FOR_WRITE
4765 && FD_ISSET (channel, &write_mask))))
4766 d->func (channel, d->data);
4769 for (channel = 0; channel <= max_process_desc; channel++)
4771 if (FD_ISSET (channel, &Available)
4772 && FD_ISSET (channel, &non_keyboard_wait_mask)
4773 && !FD_ISSET (channel, &non_process_wait_mask))
4775 int nread;
4777 /* If waiting for this channel, arrange to return as
4778 soon as no more input to be processed. No more
4779 waiting. */
4780 proc = chan_process[channel];
4781 if (NILP (proc))
4782 continue;
4784 /* If this is a server stream socket, accept connection. */
4785 if (EQ (XPROCESS (proc)->status, Qlisten))
4787 server_accept_connection (proc, channel);
4788 continue;
4791 /* Read data from the process, starting with our
4792 buffered-ahead character if we have one. */
4794 nread = read_process_output (proc, channel);
4795 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
4796 got_some_input = nread;
4797 if (nread > 0)
4799 /* Since read_process_output can run a filter,
4800 which can call accept-process-output,
4801 don't try to read from any other processes
4802 before doing the select again. */
4803 FD_ZERO (&Available);
4805 if (do_display)
4806 redisplay_preserve_echo_area (12);
4808 #ifdef EWOULDBLOCK
4809 else if (nread == -1 && errno == EWOULDBLOCK)
4811 #endif
4812 else if (nread == -1 && errno == EAGAIN)
4814 #ifdef WINDOWSNT
4815 /* FIXME: Is this special case still needed? */
4816 /* Note that we cannot distinguish between no input
4817 available now and a closed pipe.
4818 With luck, a closed pipe will be accompanied by
4819 subprocess termination and SIGCHLD. */
4820 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4822 #endif
4823 #ifdef HAVE_PTYS
4824 /* On some OSs with ptys, when the process on one end of
4825 a pty exits, the other end gets an error reading with
4826 errno = EIO instead of getting an EOF (0 bytes read).
4827 Therefore, if we get an error reading and errno =
4828 EIO, just continue, because the child process has
4829 exited and should clean itself up soon (e.g. when we
4830 get a SIGCHLD). */
4831 else if (nread == -1 && errno == EIO)
4833 struct Lisp_Process *p = XPROCESS (proc);
4835 /* Clear the descriptor now, so we only raise the
4836 signal once. */
4837 FD_CLR (channel, &input_wait_mask);
4838 FD_CLR (channel, &non_keyboard_wait_mask);
4840 if (p->pid == -2)
4842 /* If the EIO occurs on a pty, the SIGCHLD handler's
4843 waitpid call will not find the process object to
4844 delete. Do it here. */
4845 p->tick = ++process_tick;
4846 pset_status (p, Qfailed);
4849 #endif /* HAVE_PTYS */
4850 /* If we can detect process termination, don't consider the
4851 process gone just because its pipe is closed. */
4852 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4854 else
4856 /* Preserve status of processes already terminated. */
4857 XPROCESS (proc)->tick = ++process_tick;
4858 deactivate_process (proc);
4859 if (XPROCESS (proc)->raw_status_new)
4860 update_status (XPROCESS (proc));
4861 if (EQ (XPROCESS (proc)->status, Qrun))
4862 pset_status (XPROCESS (proc),
4863 list2 (Qexit, make_number (256)));
4866 #ifdef NON_BLOCKING_CONNECT
4867 if (FD_ISSET (channel, &Writeok)
4868 && FD_ISSET (channel, &connect_wait_mask))
4870 struct Lisp_Process *p;
4872 FD_CLR (channel, &connect_wait_mask);
4873 FD_CLR (channel, &write_mask);
4874 if (--num_pending_connects < 0)
4875 emacs_abort ();
4877 proc = chan_process[channel];
4878 if (NILP (proc))
4879 continue;
4881 p = XPROCESS (proc);
4883 #ifdef GNU_LINUX
4884 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4885 So only use it on systems where it is known to work. */
4887 socklen_t xlen = sizeof (xerrno);
4888 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4889 xerrno = errno;
4891 #else
4893 struct sockaddr pname;
4894 socklen_t pnamelen = sizeof (pname);
4896 /* If connection failed, getpeername will fail. */
4897 xerrno = 0;
4898 if (getpeername (channel, &pname, &pnamelen) < 0)
4900 /* Obtain connect failure code through error slippage. */
4901 char dummy;
4902 xerrno = errno;
4903 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4904 xerrno = errno;
4907 #endif
4908 if (xerrno)
4910 p->tick = ++process_tick;
4911 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4912 deactivate_process (proc);
4914 else
4916 pset_status (p, Qrun);
4917 /* Execute the sentinel here. If we had relied on
4918 status_notify to do it later, it will read input
4919 from the process before calling the sentinel. */
4920 exec_sentinel (proc, build_string ("open\n"));
4921 if (0 <= p->infd && !EQ (p->filter, Qt)
4922 && !EQ (p->command, Qt))
4924 FD_SET (p->infd, &input_wait_mask);
4925 FD_SET (p->infd, &non_keyboard_wait_mask);
4929 #endif /* NON_BLOCKING_CONNECT */
4930 } /* End for each file descriptor. */
4931 } /* End while exit conditions not met. */
4933 unbind_to (count, Qnil);
4935 /* If calling from keyboard input, do not quit
4936 since we want to return C-g as an input character.
4937 Otherwise, do pending quit if requested. */
4938 if (read_kbd >= 0)
4940 /* Prevent input_pending from remaining set if we quit. */
4941 clear_input_pending ();
4942 QUIT;
4945 return got_some_input;
4948 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4950 static Lisp_Object
4951 read_process_output_call (Lisp_Object fun_and_args)
4953 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4956 static Lisp_Object
4957 read_process_output_error_handler (Lisp_Object error_val)
4959 cmd_error_internal (error_val, "error in process filter: ");
4960 Vinhibit_quit = Qt;
4961 update_echo_area ();
4962 Fsleep_for (make_number (2), Qnil);
4963 return Qt;
4966 static void
4967 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4968 ssize_t nbytes,
4969 struct coding_system *coding);
4971 /* Read pending output from the process channel,
4972 starting with our buffered-ahead character if we have one.
4973 Yield number of decoded characters read.
4975 This function reads at most 4096 characters.
4976 If you want to read all available subprocess output,
4977 you must call it repeatedly until it returns zero.
4979 The characters read are decoded according to PROC's coding-system
4980 for decoding. */
4982 static int
4983 read_process_output (Lisp_Object proc, int channel)
4985 ssize_t nbytes;
4986 struct Lisp_Process *p = XPROCESS (proc);
4987 struct coding_system *coding = proc_decode_coding_system[channel];
4988 int carryover = p->decoding_carryover;
4989 enum { readmax = 4096 };
4990 ptrdiff_t count = SPECPDL_INDEX ();
4991 Lisp_Object odeactivate;
4992 char chars[sizeof coding->carryover + readmax];
4994 if (carryover)
4995 /* See the comment above. */
4996 memcpy (chars, SDATA (p->decoding_buf), carryover);
4998 #ifdef DATAGRAM_SOCKETS
4999 /* We have a working select, so proc_buffered_char is always -1. */
5000 if (DATAGRAM_CHAN_P (channel))
5002 socklen_t len = datagram_address[channel].len;
5003 nbytes = recvfrom (channel, chars + carryover, readmax,
5004 0, datagram_address[channel].sa, &len);
5006 else
5007 #endif
5009 bool buffered = proc_buffered_char[channel] >= 0;
5010 if (buffered)
5012 chars[carryover] = proc_buffered_char[channel];
5013 proc_buffered_char[channel] = -1;
5015 #ifdef HAVE_GNUTLS
5016 if (p->gnutls_p && p->gnutls_state)
5017 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5018 readmax - buffered);
5019 else
5020 #endif
5021 nbytes = emacs_read (channel, chars + carryover + buffered,
5022 readmax - buffered);
5023 #ifdef ADAPTIVE_READ_BUFFERING
5024 if (nbytes > 0 && p->adaptive_read_buffering)
5026 int delay = p->read_output_delay;
5027 if (nbytes < 256)
5029 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5031 if (delay == 0)
5032 process_output_delay_count++;
5033 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5036 else if (delay > 0 && nbytes == readmax - buffered)
5038 delay -= READ_OUTPUT_DELAY_INCREMENT;
5039 if (delay == 0)
5040 process_output_delay_count--;
5042 p->read_output_delay = delay;
5043 if (delay)
5045 p->read_output_skip = 1;
5046 process_output_skip = 1;
5049 #endif
5050 nbytes += buffered;
5051 nbytes += buffered && nbytes <= 0;
5054 p->decoding_carryover = 0;
5056 /* At this point, NBYTES holds number of bytes just received
5057 (including the one in proc_buffered_char[channel]). */
5058 if (nbytes <= 0)
5060 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5061 return nbytes;
5062 coding->mode |= CODING_MODE_LAST_BLOCK;
5065 /* Now set NBYTES how many bytes we must decode. */
5066 nbytes += carryover;
5068 odeactivate = Vdeactivate_mark;
5069 /* There's no good reason to let process filters change the current
5070 buffer, and many callers of accept-process-output, sit-for, and
5071 friends don't expect current-buffer to be changed from under them. */
5072 record_unwind_current_buffer ();
5074 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5076 /* Handling the process output should not deactivate the mark. */
5077 Vdeactivate_mark = odeactivate;
5079 unbind_to (count, Qnil);
5080 return nbytes;
5083 static void
5084 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5085 ssize_t nbytes,
5086 struct coding_system *coding)
5088 Lisp_Object outstream = p->filter;
5089 Lisp_Object text;
5090 bool outer_running_asynch_code = running_asynch_code;
5091 int waiting = waiting_for_user_input_p;
5093 /* No need to gcpro these, because all we do with them later
5094 is test them for EQness, and none of them should be a string. */
5095 #if 0
5096 Lisp_Object obuffer, okeymap;
5097 XSETBUFFER (obuffer, current_buffer);
5098 okeymap = BVAR (current_buffer, keymap);
5099 #endif
5101 /* We inhibit quit here instead of just catching it so that
5102 hitting ^G when a filter happens to be running won't screw
5103 it up. */
5104 specbind (Qinhibit_quit, Qt);
5105 specbind (Qlast_nonmenu_event, Qt);
5107 /* In case we get recursively called,
5108 and we already saved the match data nonrecursively,
5109 save the same match data in safely recursive fashion. */
5110 if (outer_running_asynch_code)
5112 Lisp_Object tem;
5113 /* Don't clobber the CURRENT match data, either! */
5114 tem = Fmatch_data (Qnil, Qnil, Qnil);
5115 restore_search_regs ();
5116 record_unwind_save_match_data ();
5117 Fset_match_data (tem, Qt);
5120 /* For speed, if a search happens within this code,
5121 save the match data in a special nonrecursive fashion. */
5122 running_asynch_code = 1;
5124 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5125 text = coding->dst_object;
5126 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5127 /* A new coding system might be found. */
5128 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5130 pset_decode_coding_system (p, Vlast_coding_system_used);
5132 /* Don't call setup_coding_system for
5133 proc_decode_coding_system[channel] here. It is done in
5134 detect_coding called via decode_coding above. */
5136 /* If a coding system for encoding is not yet decided, we set
5137 it as the same as coding-system for decoding.
5139 But, before doing that we must check if
5140 proc_encode_coding_system[p->outfd] surely points to a
5141 valid memory because p->outfd will be changed once EOF is
5142 sent to the process. */
5143 if (NILP (p->encode_coding_system) && p->outfd >= 0
5144 && proc_encode_coding_system[p->outfd])
5146 pset_encode_coding_system
5147 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5148 setup_coding_system (p->encode_coding_system,
5149 proc_encode_coding_system[p->outfd]);
5153 if (coding->carryover_bytes > 0)
5155 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5156 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5157 memcpy (SDATA (p->decoding_buf), coding->carryover,
5158 coding->carryover_bytes);
5159 p->decoding_carryover = coding->carryover_bytes;
5161 if (SBYTES (text) > 0)
5162 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5163 sometimes it's simply wrong to wrap (e.g. when called from
5164 accept-process-output). */
5165 internal_condition_case_1 (read_process_output_call,
5166 list3 (outstream, make_lisp_proc (p), text),
5167 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5168 read_process_output_error_handler);
5170 /* If we saved the match data nonrecursively, restore it now. */
5171 restore_search_regs ();
5172 running_asynch_code = outer_running_asynch_code;
5174 /* Restore waiting_for_user_input_p as it was
5175 when we were called, in case the filter clobbered it. */
5176 waiting_for_user_input_p = waiting;
5178 #if 0 /* Call record_asynch_buffer_change unconditionally,
5179 because we might have changed minor modes or other things
5180 that affect key bindings. */
5181 if (! EQ (Fcurrent_buffer (), obuffer)
5182 || ! EQ (current_buffer->keymap, okeymap))
5183 #endif
5184 /* But do it only if the caller is actually going to read events.
5185 Otherwise there's no need to make him wake up, and it could
5186 cause trouble (for example it would make sit_for return). */
5187 if (waiting_for_user_input_p == -1)
5188 record_asynch_buffer_change ();
5191 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5192 Sinternal_default_process_filter, 2, 2, 0,
5193 doc: /* Function used as default process filter.
5194 This inserts the process's output into its buffer, if there is one.
5195 Otherwise it discards the output. */)
5196 (Lisp_Object proc, Lisp_Object text)
5198 struct Lisp_Process *p;
5199 ptrdiff_t opoint;
5201 CHECK_PROCESS (proc);
5202 p = XPROCESS (proc);
5203 CHECK_STRING (text);
5205 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5207 Lisp_Object old_read_only;
5208 ptrdiff_t old_begv, old_zv;
5209 ptrdiff_t old_begv_byte, old_zv_byte;
5210 ptrdiff_t before, before_byte;
5211 ptrdiff_t opoint_byte;
5212 struct buffer *b;
5214 Fset_buffer (p->buffer);
5215 opoint = PT;
5216 opoint_byte = PT_BYTE;
5217 old_read_only = BVAR (current_buffer, read_only);
5218 old_begv = BEGV;
5219 old_zv = ZV;
5220 old_begv_byte = BEGV_BYTE;
5221 old_zv_byte = ZV_BYTE;
5223 bset_read_only (current_buffer, Qnil);
5225 /* Insert new output into buffer at the current end-of-output
5226 marker, thus preserving logical ordering of input and output. */
5227 if (XMARKER (p->mark)->buffer)
5228 set_point_from_marker (p->mark);
5229 else
5230 SET_PT_BOTH (ZV, ZV_BYTE);
5231 before = PT;
5232 before_byte = PT_BYTE;
5234 /* If the output marker is outside of the visible region, save
5235 the restriction and widen. */
5236 if (! (BEGV <= PT && PT <= ZV))
5237 Fwiden ();
5239 /* Adjust the multibyteness of TEXT to that of the buffer. */
5240 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5241 != ! STRING_MULTIBYTE (text))
5242 text = (STRING_MULTIBYTE (text)
5243 ? Fstring_as_unibyte (text)
5244 : Fstring_to_multibyte (text));
5245 /* Insert before markers in case we are inserting where
5246 the buffer's mark is, and the user's next command is Meta-y. */
5247 insert_from_string_before_markers (text, 0, 0,
5248 SCHARS (text), SBYTES (text), 0);
5250 /* Make sure the process marker's position is valid when the
5251 process buffer is changed in the signal_after_change above.
5252 W3 is known to do that. */
5253 if (BUFFERP (p->buffer)
5254 && (b = XBUFFER (p->buffer), b != current_buffer))
5255 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5256 else
5257 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5259 update_mode_lines = 23;
5261 /* Make sure opoint and the old restrictions
5262 float ahead of any new text just as point would. */
5263 if (opoint >= before)
5265 opoint += PT - before;
5266 opoint_byte += PT_BYTE - before_byte;
5268 if (old_begv > before)
5270 old_begv += PT - before;
5271 old_begv_byte += PT_BYTE - before_byte;
5273 if (old_zv >= before)
5275 old_zv += PT - before;
5276 old_zv_byte += PT_BYTE - before_byte;
5279 /* If the restriction isn't what it should be, set it. */
5280 if (old_begv != BEGV || old_zv != ZV)
5281 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5283 bset_read_only (current_buffer, old_read_only);
5284 SET_PT_BOTH (opoint, opoint_byte);
5286 return Qnil;
5289 /* Sending data to subprocess. */
5291 /* In send_process, when a write fails temporarily,
5292 wait_reading_process_output is called. It may execute user code,
5293 e.g. timers, that attempts to write new data to the same process.
5294 We must ensure that data is sent in the right order, and not
5295 interspersed half-completed with other writes (Bug#10815). This is
5296 handled by the write_queue element of struct process. It is a list
5297 with each entry having the form
5299 (string . (offset . length))
5301 where STRING is a lisp string, OFFSET is the offset into the
5302 string's byte sequence from which we should begin to send, and
5303 LENGTH is the number of bytes left to send. */
5305 /* Create a new entry in write_queue.
5306 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5307 BUF is a pointer to the string sequence of the input_obj or a C
5308 string in case of Qt or Qnil. */
5310 static void
5311 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5312 const char *buf, ptrdiff_t len, bool front)
5314 ptrdiff_t offset;
5315 Lisp_Object entry, obj;
5317 if (STRINGP (input_obj))
5319 offset = buf - SSDATA (input_obj);
5320 obj = input_obj;
5322 else
5324 offset = 0;
5325 obj = make_unibyte_string (buf, len);
5328 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5330 if (front)
5331 pset_write_queue (p, Fcons (entry, p->write_queue));
5332 else
5333 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5336 /* Remove the first element in the write_queue of process P, put its
5337 contents in OBJ, BUF and LEN, and return true. If the
5338 write_queue is empty, return false. */
5340 static bool
5341 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5342 const char **buf, ptrdiff_t *len)
5344 Lisp_Object entry, offset_length;
5345 ptrdiff_t offset;
5347 if (NILP (p->write_queue))
5348 return 0;
5350 entry = XCAR (p->write_queue);
5351 pset_write_queue (p, XCDR (p->write_queue));
5353 *obj = XCAR (entry);
5354 offset_length = XCDR (entry);
5356 *len = XINT (XCDR (offset_length));
5357 offset = XINT (XCAR (offset_length));
5358 *buf = SSDATA (*obj) + offset;
5360 return 1;
5363 /* Send some data to process PROC.
5364 BUF is the beginning of the data; LEN is the number of characters.
5365 OBJECT is the Lisp object that the data comes from. If OBJECT is
5366 nil or t, it means that the data comes from C string.
5368 If OBJECT is not nil, the data is encoded by PROC's coding-system
5369 for encoding before it is sent.
5371 This function can evaluate Lisp code and can garbage collect. */
5373 static void
5374 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5375 Lisp_Object object)
5377 struct Lisp_Process *p = XPROCESS (proc);
5378 ssize_t rv;
5379 struct coding_system *coding;
5381 if (p->raw_status_new)
5382 update_status (p);
5383 if (! EQ (p->status, Qrun))
5384 error ("Process %s not running", SDATA (p->name));
5385 if (p->outfd < 0)
5386 error ("Output file descriptor of %s is closed", SDATA (p->name));
5388 coding = proc_encode_coding_system[p->outfd];
5389 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5391 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5392 || (BUFFERP (object)
5393 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5394 || EQ (object, Qt))
5396 pset_encode_coding_system
5397 (p, complement_process_encoding_system (p->encode_coding_system));
5398 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5400 /* The coding system for encoding was changed to raw-text
5401 because we sent a unibyte text previously. Now we are
5402 sending a multibyte text, thus we must encode it by the
5403 original coding system specified for the current process.
5405 Another reason we come here is that the coding system
5406 was just complemented and a new one was returned by
5407 complement_process_encoding_system. */
5408 setup_coding_system (p->encode_coding_system, coding);
5409 Vlast_coding_system_used = p->encode_coding_system;
5411 coding->src_multibyte = 1;
5413 else
5415 coding->src_multibyte = 0;
5416 /* For sending a unibyte text, character code conversion should
5417 not take place but EOL conversion should. So, setup raw-text
5418 or one of the subsidiary if we have not yet done it. */
5419 if (CODING_REQUIRE_ENCODING (coding))
5421 if (CODING_REQUIRE_FLUSHING (coding))
5423 /* But, before changing the coding, we must flush out data. */
5424 coding->mode |= CODING_MODE_LAST_BLOCK;
5425 send_process (proc, "", 0, Qt);
5426 coding->mode &= CODING_MODE_LAST_BLOCK;
5428 setup_coding_system (raw_text_coding_system
5429 (Vlast_coding_system_used),
5430 coding);
5431 coding->src_multibyte = 0;
5434 coding->dst_multibyte = 0;
5436 if (CODING_REQUIRE_ENCODING (coding))
5438 coding->dst_object = Qt;
5439 if (BUFFERP (object))
5441 ptrdiff_t from_byte, from, to;
5442 ptrdiff_t save_pt, save_pt_byte;
5443 struct buffer *cur = current_buffer;
5445 set_buffer_internal (XBUFFER (object));
5446 save_pt = PT, save_pt_byte = PT_BYTE;
5448 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5449 from = BYTE_TO_CHAR (from_byte);
5450 to = BYTE_TO_CHAR (from_byte + len);
5451 TEMP_SET_PT_BOTH (from, from_byte);
5452 encode_coding_object (coding, object, from, from_byte,
5453 to, from_byte + len, Qt);
5454 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5455 set_buffer_internal (cur);
5457 else if (STRINGP (object))
5459 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5460 SBYTES (object), Qt);
5462 else
5464 coding->dst_object = make_unibyte_string (buf, len);
5465 coding->produced = len;
5468 len = coding->produced;
5469 object = coding->dst_object;
5470 buf = SSDATA (object);
5473 /* If there is already data in the write_queue, put the new data
5474 in the back of queue. Otherwise, ignore it. */
5475 if (!NILP (p->write_queue))
5476 write_queue_push (p, object, buf, len, 0);
5478 do /* while !NILP (p->write_queue) */
5480 ptrdiff_t cur_len = -1;
5481 const char *cur_buf;
5482 Lisp_Object cur_object;
5484 /* If write_queue is empty, ignore it. */
5485 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5487 cur_len = len;
5488 cur_buf = buf;
5489 cur_object = object;
5492 while (cur_len > 0)
5494 /* Send this batch, using one or more write calls. */
5495 ptrdiff_t written = 0;
5496 int outfd = p->outfd;
5497 #ifdef DATAGRAM_SOCKETS
5498 if (DATAGRAM_CHAN_P (outfd))
5500 rv = sendto (outfd, cur_buf, cur_len,
5501 0, datagram_address[outfd].sa,
5502 datagram_address[outfd].len);
5503 if (rv >= 0)
5504 written = rv;
5505 else if (errno == EMSGSIZE)
5506 report_file_error ("Sending datagram", proc);
5508 else
5509 #endif
5511 #ifdef HAVE_GNUTLS
5512 if (p->gnutls_p && p->gnutls_state)
5513 written = emacs_gnutls_write (p, cur_buf, cur_len);
5514 else
5515 #endif
5516 written = emacs_write_sig (outfd, cur_buf, cur_len);
5517 rv = (written ? 0 : -1);
5518 #ifdef ADAPTIVE_READ_BUFFERING
5519 if (p->read_output_delay > 0
5520 && p->adaptive_read_buffering == 1)
5522 p->read_output_delay = 0;
5523 process_output_delay_count--;
5524 p->read_output_skip = 0;
5526 #endif
5529 if (rv < 0)
5531 if (errno == EAGAIN
5532 #ifdef EWOULDBLOCK
5533 || errno == EWOULDBLOCK
5534 #endif
5536 /* Buffer is full. Wait, accepting input;
5537 that may allow the program
5538 to finish doing output and read more. */
5540 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5541 /* A gross hack to work around a bug in FreeBSD.
5542 In the following sequence, read(2) returns
5543 bogus data:
5545 write(2) 1022 bytes
5546 write(2) 954 bytes, get EAGAIN
5547 read(2) 1024 bytes in process_read_output
5548 read(2) 11 bytes in process_read_output
5550 That is, read(2) returns more bytes than have
5551 ever been written successfully. The 1033 bytes
5552 read are the 1022 bytes written successfully
5553 after processing (for example with CRs added if
5554 the terminal is set up that way which it is
5555 here). The same bytes will be seen again in a
5556 later read(2), without the CRs. */
5558 if (errno == EAGAIN)
5560 int flags = FWRITE;
5561 ioctl (p->outfd, TIOCFLUSH, &flags);
5563 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5565 /* Put what we should have written in wait_queue. */
5566 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5567 wait_reading_process_output (0, 20 * 1000 * 1000,
5568 0, 0, Qnil, NULL, 0);
5569 /* Reread queue, to see what is left. */
5570 break;
5572 else if (errno == EPIPE)
5574 p->raw_status_new = 0;
5575 pset_status (p, list2 (Qexit, make_number (256)));
5576 p->tick = ++process_tick;
5577 deactivate_process (proc);
5578 error ("process %s no longer connected to pipe; closed it",
5579 SDATA (p->name));
5581 else
5582 /* This is a real error. */
5583 report_file_error ("Writing to process", proc);
5585 cur_buf += written;
5586 cur_len -= written;
5589 while (!NILP (p->write_queue));
5592 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5593 3, 3, 0,
5594 doc: /* Send current contents of region as input to PROCESS.
5595 PROCESS may be a process, a buffer, the name of a process or buffer, or
5596 nil, indicating the current buffer's process.
5597 Called from program, takes three arguments, PROCESS, START and END.
5598 If the region is more than 500 characters long,
5599 it is sent in several bunches. This may happen even for shorter regions.
5600 Output from processes can arrive in between bunches. */)
5601 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5603 Lisp_Object proc = get_process (process);
5604 ptrdiff_t start_byte, end_byte;
5606 validate_region (&start, &end);
5608 start_byte = CHAR_TO_BYTE (XINT (start));
5609 end_byte = CHAR_TO_BYTE (XINT (end));
5611 if (XINT (start) < GPT && XINT (end) > GPT)
5612 move_gap_both (XINT (start), start_byte);
5614 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5615 end_byte - start_byte, Fcurrent_buffer ());
5617 return Qnil;
5620 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5621 2, 2, 0,
5622 doc: /* Send PROCESS the contents of STRING as input.
5623 PROCESS may be a process, a buffer, the name of a process or buffer, or
5624 nil, indicating the current buffer's process.
5625 If STRING is more than 500 characters long,
5626 it is sent in several bunches. This may happen even for shorter strings.
5627 Output from processes can arrive in between bunches. */)
5628 (Lisp_Object process, Lisp_Object string)
5630 Lisp_Object proc;
5631 CHECK_STRING (string);
5632 proc = get_process (process);
5633 send_process (proc, SSDATA (string),
5634 SBYTES (string), string);
5635 return Qnil;
5638 /* Return the foreground process group for the tty/pty that
5639 the process P uses. */
5640 static pid_t
5641 emacs_get_tty_pgrp (struct Lisp_Process *p)
5643 pid_t gid = -1;
5645 #ifdef TIOCGPGRP
5646 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5648 int fd;
5649 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5650 master side. Try the slave side. */
5651 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5653 if (fd != -1)
5655 ioctl (fd, TIOCGPGRP, &gid);
5656 emacs_close (fd);
5659 #endif /* defined (TIOCGPGRP ) */
5661 return gid;
5664 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5665 Sprocess_running_child_p, 0, 1, 0,
5666 doc: /* Return t if PROCESS has given the terminal to a child.
5667 If the operating system does not make it possible to find out,
5668 return t unconditionally. */)
5669 (Lisp_Object process)
5671 /* Initialize in case ioctl doesn't exist or gives an error,
5672 in a way that will cause returning t. */
5673 pid_t gid;
5674 Lisp_Object proc;
5675 struct Lisp_Process *p;
5677 proc = get_process (process);
5678 p = XPROCESS (proc);
5680 if (!EQ (p->type, Qreal))
5681 error ("Process %s is not a subprocess",
5682 SDATA (p->name));
5683 if (p->infd < 0)
5684 error ("Process %s is not active",
5685 SDATA (p->name));
5687 gid = emacs_get_tty_pgrp (p);
5689 if (gid == p->pid)
5690 return Qnil;
5691 return Qt;
5694 /* Send a signal number SIGNO to PROCESS.
5695 If CURRENT_GROUP is t, that means send to the process group
5696 that currently owns the terminal being used to communicate with PROCESS.
5697 This is used for various commands in shell mode.
5698 If CURRENT_GROUP is lambda, that means send to the process group
5699 that currently owns the terminal, but only if it is NOT the shell itself.
5701 If NOMSG is false, insert signal-announcements into process's buffers
5702 right away.
5704 If we can, we try to signal PROCESS by sending control characters
5705 down the pty. This allows us to signal inferiors who have changed
5706 their uid, for which kill would return an EPERM error. */
5708 static void
5709 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5710 bool nomsg)
5712 Lisp_Object proc;
5713 struct Lisp_Process *p;
5714 pid_t gid;
5715 bool no_pgrp = 0;
5717 proc = get_process (process);
5718 p = XPROCESS (proc);
5720 if (!EQ (p->type, Qreal))
5721 error ("Process %s is not a subprocess",
5722 SDATA (p->name));
5723 if (p->infd < 0)
5724 error ("Process %s is not active",
5725 SDATA (p->name));
5727 if (!p->pty_flag)
5728 current_group = Qnil;
5730 /* If we are using pgrps, get a pgrp number and make it negative. */
5731 if (NILP (current_group))
5732 /* Send the signal to the shell's process group. */
5733 gid = p->pid;
5734 else
5736 #ifdef SIGNALS_VIA_CHARACTERS
5737 /* If possible, send signals to the entire pgrp
5738 by sending an input character to it. */
5740 struct termios t;
5741 cc_t *sig_char = NULL;
5743 tcgetattr (p->infd, &t);
5745 switch (signo)
5747 case SIGINT:
5748 sig_char = &t.c_cc[VINTR];
5749 break;
5751 case SIGQUIT:
5752 sig_char = &t.c_cc[VQUIT];
5753 break;
5755 case SIGTSTP:
5756 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5757 sig_char = &t.c_cc[VSWTCH];
5758 #else
5759 sig_char = &t.c_cc[VSUSP];
5760 #endif
5761 break;
5764 if (sig_char && *sig_char != CDISABLE)
5766 send_process (proc, (char *) sig_char, 1, Qnil);
5767 return;
5769 /* If we can't send the signal with a character,
5770 fall through and send it another way. */
5772 /* The code above may fall through if it can't
5773 handle the signal. */
5774 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5776 #ifdef TIOCGPGRP
5777 /* Get the current pgrp using the tty itself, if we have that.
5778 Otherwise, use the pty to get the pgrp.
5779 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5780 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5781 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5782 His patch indicates that if TIOCGPGRP returns an error, then
5783 we should just assume that p->pid is also the process group id. */
5785 gid = emacs_get_tty_pgrp (p);
5787 if (gid == -1)
5788 /* If we can't get the information, assume
5789 the shell owns the tty. */
5790 gid = p->pid;
5792 /* It is not clear whether anything really can set GID to -1.
5793 Perhaps on some system one of those ioctls can or could do so.
5794 Or perhaps this is vestigial. */
5795 if (gid == -1)
5796 no_pgrp = 1;
5797 #else /* ! defined (TIOCGPGRP) */
5798 /* Can't select pgrps on this system, so we know that
5799 the child itself heads the pgrp. */
5800 gid = p->pid;
5801 #endif /* ! defined (TIOCGPGRP) */
5803 /* If current_group is lambda, and the shell owns the terminal,
5804 don't send any signal. */
5805 if (EQ (current_group, Qlambda) && gid == p->pid)
5806 return;
5809 #ifdef SIGCONT
5810 if (signo == SIGCONT)
5812 p->raw_status_new = 0;
5813 pset_status (p, Qrun);
5814 p->tick = ++process_tick;
5815 if (!nomsg)
5817 status_notify (NULL, NULL);
5818 redisplay_preserve_echo_area (13);
5821 #endif
5823 #ifdef TIOCSIGSEND
5824 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5825 We don't know whether the bug is fixed in later HP-UX versions. */
5826 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
5827 return;
5828 #endif
5830 /* If we don't have process groups, send the signal to the immediate
5831 subprocess. That isn't really right, but it's better than any
5832 obvious alternative. */
5833 pid_t pid = no_pgrp ? gid : - gid;
5835 /* Do not kill an already-reaped process, as that could kill an
5836 innocent bystander that happens to have the same process ID. */
5837 sigset_t oldset;
5838 block_child_signal (&oldset);
5839 if (p->alive)
5840 kill (pid, signo);
5841 unblock_child_signal (&oldset);
5844 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5845 doc: /* Interrupt process PROCESS.
5846 PROCESS may be a process, a buffer, or the name of a process or buffer.
5847 No arg or nil means current buffer's process.
5848 Second arg CURRENT-GROUP non-nil means send signal to
5849 the current process-group of the process's controlling terminal
5850 rather than to the process's own process group.
5851 If the process is a shell, this means interrupt current subjob
5852 rather than the shell.
5854 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5855 don't send the signal. */)
5856 (Lisp_Object process, Lisp_Object current_group)
5858 process_send_signal (process, SIGINT, current_group, 0);
5859 return process;
5862 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5863 doc: /* Kill process PROCESS. May be process or name of one.
5864 See function `interrupt-process' for more details on usage. */)
5865 (Lisp_Object process, Lisp_Object current_group)
5867 process_send_signal (process, SIGKILL, current_group, 0);
5868 return process;
5871 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5872 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5873 See function `interrupt-process' for more details on usage. */)
5874 (Lisp_Object process, Lisp_Object current_group)
5876 process_send_signal (process, SIGQUIT, current_group, 0);
5877 return process;
5880 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5881 doc: /* Stop process PROCESS. May be process or name of one.
5882 See function `interrupt-process' for more details on usage.
5883 If PROCESS is a network or serial process, inhibit handling of incoming
5884 traffic. */)
5885 (Lisp_Object process, Lisp_Object current_group)
5887 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5889 struct Lisp_Process *p;
5891 p = XPROCESS (process);
5892 if (NILP (p->command)
5893 && p->infd >= 0)
5895 FD_CLR (p->infd, &input_wait_mask);
5896 FD_CLR (p->infd, &non_keyboard_wait_mask);
5898 pset_command (p, Qt);
5899 return process;
5901 #ifndef SIGTSTP
5902 error ("No SIGTSTP support");
5903 #else
5904 process_send_signal (process, SIGTSTP, current_group, 0);
5905 #endif
5906 return process;
5909 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5910 doc: /* Continue process PROCESS. May be process or name of one.
5911 See function `interrupt-process' for more details on usage.
5912 If PROCESS is a network or serial process, resume handling of incoming
5913 traffic. */)
5914 (Lisp_Object process, Lisp_Object current_group)
5916 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5918 struct Lisp_Process *p;
5920 p = XPROCESS (process);
5921 if (EQ (p->command, Qt)
5922 && p->infd >= 0
5923 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5925 FD_SET (p->infd, &input_wait_mask);
5926 FD_SET (p->infd, &non_keyboard_wait_mask);
5927 #ifdef WINDOWSNT
5928 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5929 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5930 #else /* not WINDOWSNT */
5931 tcflush (p->infd, TCIFLUSH);
5932 #endif /* not WINDOWSNT */
5934 pset_command (p, Qnil);
5935 return process;
5937 #ifdef SIGCONT
5938 process_send_signal (process, SIGCONT, current_group, 0);
5939 #else
5940 error ("No SIGCONT support");
5941 #endif
5942 return process;
5945 /* Return the integer value of the signal whose abbreviation is ABBR,
5946 or a negative number if there is no such signal. */
5947 static int
5948 abbr_to_signal (char const *name)
5950 int i, signo;
5951 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5953 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5954 name += 3;
5956 for (i = 0; i < sizeof sigbuf; i++)
5958 sigbuf[i] = c_toupper (name[i]);
5959 if (! sigbuf[i])
5960 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5963 return -1;
5966 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5967 2, 2, "sProcess (name or number): \nnSignal code: ",
5968 doc: /* Send PROCESS the signal with code SIGCODE.
5969 PROCESS may also be a number specifying the process id of the
5970 process to signal; in this case, the process need not be a child of
5971 this Emacs.
5972 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5973 (Lisp_Object process, Lisp_Object sigcode)
5975 pid_t pid;
5976 int signo;
5978 if (STRINGP (process))
5980 Lisp_Object tem = Fget_process (process);
5981 if (NILP (tem))
5983 Lisp_Object process_number
5984 = string_to_number (SSDATA (process), 10, 1);
5985 if (INTEGERP (process_number) || FLOATP (process_number))
5986 tem = process_number;
5988 process = tem;
5990 else if (!NUMBERP (process))
5991 process = get_process (process);
5993 if (NILP (process))
5994 return process;
5996 if (NUMBERP (process))
5997 CONS_TO_INTEGER (process, pid_t, pid);
5998 else
6000 CHECK_PROCESS (process);
6001 pid = XPROCESS (process)->pid;
6002 if (pid <= 0)
6003 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6006 if (INTEGERP (sigcode))
6008 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6009 signo = XINT (sigcode);
6011 else
6013 char *name;
6015 CHECK_SYMBOL (sigcode);
6016 name = SSDATA (SYMBOL_NAME (sigcode));
6018 signo = abbr_to_signal (name);
6019 if (signo < 0)
6020 error ("Undefined signal name %s", name);
6023 return make_number (kill (pid, signo));
6026 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6027 doc: /* Make PROCESS see end-of-file in its input.
6028 EOF comes after any text already sent to it.
6029 PROCESS may be a process, a buffer, the name of a process or buffer, or
6030 nil, indicating the current buffer's process.
6031 If PROCESS is a network connection, or is a process communicating
6032 through a pipe (as opposed to a pty), then you cannot send any more
6033 text to PROCESS after you call this function.
6034 If PROCESS is a serial process, wait until all output written to the
6035 process has been transmitted to the serial port. */)
6036 (Lisp_Object process)
6038 Lisp_Object proc;
6039 struct coding_system *coding = NULL;
6040 int outfd;
6042 if (DATAGRAM_CONN_P (process))
6043 return process;
6045 proc = get_process (process);
6046 outfd = XPROCESS (proc)->outfd;
6047 if (outfd >= 0)
6048 coding = proc_encode_coding_system[outfd];
6050 /* Make sure the process is really alive. */
6051 if (XPROCESS (proc)->raw_status_new)
6052 update_status (XPROCESS (proc));
6053 if (! EQ (XPROCESS (proc)->status, Qrun))
6054 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6056 if (coding && CODING_REQUIRE_FLUSHING (coding))
6058 coding->mode |= CODING_MODE_LAST_BLOCK;
6059 send_process (proc, "", 0, Qnil);
6062 if (XPROCESS (proc)->pty_flag)
6063 send_process (proc, "\004", 1, Qnil);
6064 else if (EQ (XPROCESS (proc)->type, Qserial))
6066 #ifndef WINDOWSNT
6067 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6068 report_file_error ("Failed tcdrain", Qnil);
6069 #endif /* not WINDOWSNT */
6070 /* Do nothing on Windows because writes are blocking. */
6072 else
6074 struct Lisp_Process *p = XPROCESS (proc);
6075 int old_outfd = p->outfd;
6076 int new_outfd;
6078 #ifdef HAVE_SHUTDOWN
6079 /* If this is a network connection, or socketpair is used
6080 for communication with the subprocess, call shutdown to cause EOF.
6081 (In some old system, shutdown to socketpair doesn't work.
6082 Then we just can't win.) */
6083 if (0 <= old_outfd
6084 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6085 shutdown (old_outfd, 1);
6086 #endif
6087 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6088 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6089 if (new_outfd < 0)
6090 report_file_error ("Opening null device", Qnil);
6091 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6092 p->outfd = new_outfd;
6094 if (!proc_encode_coding_system[new_outfd])
6095 proc_encode_coding_system[new_outfd]
6096 = xmalloc (sizeof (struct coding_system));
6097 if (old_outfd >= 0)
6099 *proc_encode_coding_system[new_outfd]
6100 = *proc_encode_coding_system[old_outfd];
6101 memset (proc_encode_coding_system[old_outfd], 0,
6102 sizeof (struct coding_system));
6104 else
6105 setup_coding_system (p->encode_coding_system,
6106 proc_encode_coding_system[new_outfd]);
6108 return process;
6111 /* The main Emacs thread records child processes in three places:
6113 - Vprocess_alist, for asynchronous subprocesses, which are child
6114 processes visible to Lisp.
6116 - deleted_pid_list, for child processes invisible to Lisp,
6117 typically because of delete-process. These are recorded so that
6118 the processes can be reaped when they exit, so that the operating
6119 system's process table is not cluttered by zombies.
6121 - the local variable PID in Fcall_process, call_process_cleanup and
6122 call_process_kill, for synchronous subprocesses.
6123 record_unwind_protect is used to make sure this process is not
6124 forgotten: if the user interrupts call-process and the child
6125 process refuses to exit immediately even with two C-g's,
6126 call_process_kill adds PID's contents to deleted_pid_list before
6127 returning.
6129 The main Emacs thread invokes waitpid only on child processes that
6130 it creates and that have not been reaped. This avoid races on
6131 platforms such as GTK, where other threads create their own
6132 subprocesses which the main thread should not reap. For example,
6133 if the main thread attempted to reap an already-reaped child, it
6134 might inadvertently reap a GTK-created process that happened to
6135 have the same process ID. */
6137 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6138 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6139 keep track of its own children. GNUstep is similar. */
6141 static void dummy_handler (int sig) {}
6142 static signal_handler_t volatile lib_child_handler;
6144 /* Handle a SIGCHLD signal by looking for known child processes of
6145 Emacs whose status have changed. For each one found, record its
6146 new status.
6148 All we do is change the status; we do not run sentinels or print
6149 notifications. That is saved for the next time keyboard input is
6150 done, in order to avoid timing errors.
6152 ** WARNING: this can be called during garbage collection.
6153 Therefore, it must not be fooled by the presence of mark bits in
6154 Lisp objects.
6156 ** USG WARNING: Although it is not obvious from the documentation
6157 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6158 signal() before executing at least one wait(), otherwise the
6159 handler will be called again, resulting in an infinite loop. The
6160 relevant portion of the documentation reads "SIGCLD signals will be
6161 queued and the signal-catching function will be continually
6162 reentered until the queue is empty". Invoking signal() causes the
6163 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6164 Inc.
6166 ** Malloc WARNING: This should never call malloc either directly or
6167 indirectly; if it does, that is a bug. */
6169 static void
6170 handle_child_signal (int sig)
6172 Lisp_Object tail, proc;
6174 /* Find the process that signaled us, and record its status. */
6176 /* The process can have been deleted by Fdelete_process, or have
6177 been started asynchronously by Fcall_process. */
6178 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6180 bool all_pids_are_fixnums
6181 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6182 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6183 Lisp_Object head = XCAR (tail);
6184 Lisp_Object xpid;
6185 if (! CONSP (head))
6186 continue;
6187 xpid = XCAR (head);
6188 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6190 pid_t deleted_pid;
6191 if (INTEGERP (xpid))
6192 deleted_pid = XINT (xpid);
6193 else
6194 deleted_pid = XFLOAT_DATA (xpid);
6195 if (child_status_changed (deleted_pid, 0, 0))
6197 if (STRINGP (XCDR (head)))
6198 unlink (SSDATA (XCDR (head)));
6199 XSETCAR (tail, Qnil);
6204 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6205 FOR_EACH_PROCESS (tail, proc)
6207 struct Lisp_Process *p = XPROCESS (proc);
6208 int status;
6210 if (p->alive
6211 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6213 /* Change the status of the process that was found. */
6214 p->tick = ++process_tick;
6215 p->raw_status = status;
6216 p->raw_status_new = 1;
6218 /* If process has terminated, stop waiting for its output. */
6219 if (WIFSIGNALED (status) || WIFEXITED (status))
6221 bool clear_desc_flag = 0;
6222 p->alive = 0;
6223 if (p->infd >= 0)
6224 clear_desc_flag = 1;
6226 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6227 if (clear_desc_flag)
6229 FD_CLR (p->infd, &input_wait_mask);
6230 FD_CLR (p->infd, &non_keyboard_wait_mask);
6236 lib_child_handler (sig);
6237 #ifdef NS_IMPL_GNUSTEP
6238 /* NSTask in GNUstep sets its child handler each time it is called.
6239 So we must re-set ours. */
6240 catch_child_signal ();
6241 #endif
6244 static void
6245 deliver_child_signal (int sig)
6247 deliver_process_signal (sig, handle_child_signal);
6251 static Lisp_Object
6252 exec_sentinel_error_handler (Lisp_Object error_val)
6254 cmd_error_internal (error_val, "error in process sentinel: ");
6255 Vinhibit_quit = Qt;
6256 update_echo_area ();
6257 Fsleep_for (make_number (2), Qnil);
6258 return Qt;
6261 static void
6262 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6264 Lisp_Object sentinel, odeactivate;
6265 struct Lisp_Process *p = XPROCESS (proc);
6266 ptrdiff_t count = SPECPDL_INDEX ();
6267 bool outer_running_asynch_code = running_asynch_code;
6268 int waiting = waiting_for_user_input_p;
6270 if (inhibit_sentinels)
6271 return;
6273 /* No need to gcpro these, because all we do with them later
6274 is test them for EQness, and none of them should be a string. */
6275 odeactivate = Vdeactivate_mark;
6276 #if 0
6277 Lisp_Object obuffer, okeymap;
6278 XSETBUFFER (obuffer, current_buffer);
6279 okeymap = BVAR (current_buffer, keymap);
6280 #endif
6282 /* There's no good reason to let sentinels change the current
6283 buffer, and many callers of accept-process-output, sit-for, and
6284 friends don't expect current-buffer to be changed from under them. */
6285 record_unwind_current_buffer ();
6287 sentinel = p->sentinel;
6289 /* Inhibit quit so that random quits don't screw up a running filter. */
6290 specbind (Qinhibit_quit, Qt);
6291 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6293 /* In case we get recursively called,
6294 and we already saved the match data nonrecursively,
6295 save the same match data in safely recursive fashion. */
6296 if (outer_running_asynch_code)
6298 Lisp_Object tem;
6299 tem = Fmatch_data (Qnil, Qnil, Qnil);
6300 restore_search_regs ();
6301 record_unwind_save_match_data ();
6302 Fset_match_data (tem, Qt);
6305 /* For speed, if a search happens within this code,
6306 save the match data in a special nonrecursive fashion. */
6307 running_asynch_code = 1;
6309 internal_condition_case_1 (read_process_output_call,
6310 list3 (sentinel, proc, reason),
6311 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6312 exec_sentinel_error_handler);
6314 /* If we saved the match data nonrecursively, restore it now. */
6315 restore_search_regs ();
6316 running_asynch_code = outer_running_asynch_code;
6318 Vdeactivate_mark = odeactivate;
6320 /* Restore waiting_for_user_input_p as it was
6321 when we were called, in case the filter clobbered it. */
6322 waiting_for_user_input_p = waiting;
6324 #if 0
6325 if (! EQ (Fcurrent_buffer (), obuffer)
6326 || ! EQ (current_buffer->keymap, okeymap))
6327 #endif
6328 /* But do it only if the caller is actually going to read events.
6329 Otherwise there's no need to make him wake up, and it could
6330 cause trouble (for example it would make sit_for return). */
6331 if (waiting_for_user_input_p == -1)
6332 record_asynch_buffer_change ();
6334 unbind_to (count, Qnil);
6337 /* Report all recent events of a change in process status
6338 (either run the sentinel or output a message).
6339 This is usually done while Emacs is waiting for keyboard input
6340 but can be done at other times.
6342 Return positive if any input was received from WAIT_PROC (or from
6343 any process if WAIT_PROC is null), zero if input was attempted but
6344 none received, and negative if we didn't even try. */
6346 static int
6347 status_notify (struct Lisp_Process *deleting_process,
6348 struct Lisp_Process *wait_proc)
6350 Lisp_Object proc;
6351 Lisp_Object tail, msg;
6352 struct gcpro gcpro1, gcpro2;
6353 int got_some_input = -1;
6355 tail = Qnil;
6356 msg = Qnil;
6357 /* We need to gcpro tail; if read_process_output calls a filter
6358 which deletes a process and removes the cons to which tail points
6359 from Vprocess_alist, and then causes a GC, tail is an unprotected
6360 reference. */
6361 GCPRO2 (tail, msg);
6363 /* Set this now, so that if new processes are created by sentinels
6364 that we run, we get called again to handle their status changes. */
6365 update_tick = process_tick;
6367 FOR_EACH_PROCESS (tail, proc)
6369 Lisp_Object symbol;
6370 register struct Lisp_Process *p = XPROCESS (proc);
6372 if (p->tick != p->update_tick)
6374 p->update_tick = p->tick;
6376 /* If process is still active, read any output that remains. */
6377 while (! EQ (p->filter, Qt)
6378 && ! EQ (p->status, Qconnect)
6379 && ! EQ (p->status, Qlisten)
6380 /* Network or serial process not stopped: */
6381 && ! EQ (p->command, Qt)
6382 && p->infd >= 0
6383 && p != deleting_process)
6385 int nread = read_process_output (proc, p->infd);
6386 if (got_some_input < nread)
6387 got_some_input = nread;
6388 if (nread <= 0)
6389 break;
6392 /* Get the text to use for the message. */
6393 if (p->raw_status_new)
6394 update_status (p);
6395 msg = status_message (p);
6397 /* If process is terminated, deactivate it or delete it. */
6398 symbol = p->status;
6399 if (CONSP (p->status))
6400 symbol = XCAR (p->status);
6402 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6403 || EQ (symbol, Qclosed))
6405 if (delete_exited_processes)
6406 remove_process (proc);
6407 else
6408 deactivate_process (proc);
6411 /* The actions above may have further incremented p->tick.
6412 So set p->update_tick again so that an error in the sentinel will
6413 not cause this code to be run again. */
6414 p->update_tick = p->tick;
6415 /* Now output the message suitably. */
6416 exec_sentinel (proc, msg);
6418 } /* end for */
6420 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6421 UNGCPRO;
6422 return got_some_input;
6425 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6426 Sinternal_default_process_sentinel, 2, 2, 0,
6427 doc: /* Function used as default sentinel for processes.
6428 This inserts a status message into the process's buffer, if there is one. */)
6429 (Lisp_Object proc, Lisp_Object msg)
6431 Lisp_Object buffer, symbol;
6432 struct Lisp_Process *p;
6433 CHECK_PROCESS (proc);
6434 p = XPROCESS (proc);
6435 buffer = p->buffer;
6436 symbol = p->status;
6437 if (CONSP (symbol))
6438 symbol = XCAR (symbol);
6440 if (!EQ (symbol, Qrun) && !NILP (buffer))
6442 Lisp_Object tem;
6443 struct buffer *old = current_buffer;
6444 ptrdiff_t opoint, opoint_byte;
6445 ptrdiff_t before, before_byte;
6447 /* Avoid error if buffer is deleted
6448 (probably that's why the process is dead, too). */
6449 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6450 return Qnil;
6451 Fset_buffer (buffer);
6453 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6454 msg = (code_convert_string_norecord
6455 (msg, Vlocale_coding_system, 1));
6457 opoint = PT;
6458 opoint_byte = PT_BYTE;
6459 /* Insert new output into buffer
6460 at the current end-of-output marker,
6461 thus preserving logical ordering of input and output. */
6462 if (XMARKER (p->mark)->buffer)
6463 Fgoto_char (p->mark);
6464 else
6465 SET_PT_BOTH (ZV, ZV_BYTE);
6467 before = PT;
6468 before_byte = PT_BYTE;
6470 tem = BVAR (current_buffer, read_only);
6471 bset_read_only (current_buffer, Qnil);
6472 insert_string ("\nProcess ");
6473 { /* FIXME: temporary kludge. */
6474 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6475 insert_string (" ");
6476 Finsert (1, &msg);
6477 bset_read_only (current_buffer, tem);
6478 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6480 if (opoint >= before)
6481 SET_PT_BOTH (opoint + (PT - before),
6482 opoint_byte + (PT_BYTE - before_byte));
6483 else
6484 SET_PT_BOTH (opoint, opoint_byte);
6486 set_buffer_internal (old);
6488 return Qnil;
6492 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6493 Sset_process_coding_system, 1, 3, 0,
6494 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6495 DECODING will be used to decode subprocess output and ENCODING to
6496 encode subprocess input. */)
6497 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6499 register struct Lisp_Process *p;
6501 CHECK_PROCESS (process);
6502 p = XPROCESS (process);
6503 if (p->infd < 0)
6504 error ("Input file descriptor of %s closed", SDATA (p->name));
6505 if (p->outfd < 0)
6506 error ("Output file descriptor of %s closed", SDATA (p->name));
6507 Fcheck_coding_system (decoding);
6508 Fcheck_coding_system (encoding);
6509 encoding = coding_inherit_eol_type (encoding, Qnil);
6510 pset_decode_coding_system (p, decoding);
6511 pset_encode_coding_system (p, encoding);
6512 setup_process_coding_systems (process);
6514 return Qnil;
6517 DEFUN ("process-coding-system",
6518 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6519 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6520 (register Lisp_Object process)
6522 CHECK_PROCESS (process);
6523 return Fcons (XPROCESS (process)->decode_coding_system,
6524 XPROCESS (process)->encode_coding_system);
6527 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6528 Sset_process_filter_multibyte, 2, 2, 0,
6529 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6530 If FLAG is non-nil, the filter is given multibyte strings.
6531 If FLAG is nil, the filter is given unibyte strings. In this case,
6532 all character code conversion except for end-of-line conversion is
6533 suppressed. */)
6534 (Lisp_Object process, Lisp_Object flag)
6536 register struct Lisp_Process *p;
6538 CHECK_PROCESS (process);
6539 p = XPROCESS (process);
6540 if (NILP (flag))
6541 pset_decode_coding_system
6542 (p, raw_text_coding_system (p->decode_coding_system));
6543 setup_process_coding_systems (process);
6545 return Qnil;
6548 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6549 Sprocess_filter_multibyte_p, 1, 1, 0,
6550 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6551 (Lisp_Object process)
6553 register struct Lisp_Process *p;
6554 struct coding_system *coding;
6556 CHECK_PROCESS (process);
6557 p = XPROCESS (process);
6558 if (p->infd < 0)
6559 return Qnil;
6560 coding = proc_decode_coding_system[p->infd];
6561 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6567 # ifdef HAVE_GPM
6569 void
6570 add_gpm_wait_descriptor (int desc)
6572 add_keyboard_wait_descriptor (desc);
6575 void
6576 delete_gpm_wait_descriptor (int desc)
6578 delete_keyboard_wait_descriptor (desc);
6581 # endif
6583 # ifdef USABLE_SIGIO
6585 /* Return true if *MASK has a bit set
6586 that corresponds to one of the keyboard input descriptors. */
6588 static bool
6589 keyboard_bit_set (fd_set *mask)
6591 int fd;
6593 for (fd = 0; fd <= max_input_desc; fd++)
6594 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6595 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6596 return 1;
6598 return 0;
6600 # endif
6602 #else /* not subprocesses */
6604 /* Defined in msdos.c. */
6605 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6606 struct timespec *, void *);
6608 /* Implementation of wait_reading_process_output, assuming that there
6609 are no subprocesses. Used only by the MS-DOS build.
6611 Wait for timeout to elapse and/or keyboard input to be available.
6613 TIME_LIMIT is:
6614 timeout in seconds
6615 If negative, gobble data immediately available but don't wait for any.
6617 NSECS is:
6618 an additional duration to wait, measured in nanoseconds
6619 If TIME_LIMIT is zero, then:
6620 If NSECS == 0, there is no limit.
6621 If NSECS > 0, the timeout consists of NSECS only.
6622 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6624 READ_KBD is:
6625 0 to ignore keyboard input, or
6626 1 to return when input is available, or
6627 -1 means caller will actually read the input, so don't throw to
6628 the quit handler.
6630 see full version for other parameters. We know that wait_proc will
6631 always be NULL, since `subprocesses' isn't defined.
6633 DO_DISPLAY means redisplay should be done to show subprocess
6634 output that arrives.
6636 Return positive if we received input from WAIT_PROC (or from any
6637 process if WAIT_PROC is null), zero if we attempted to receive
6638 input but got none, and negative if we didn't even try. */
6641 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6642 bool do_display,
6643 Lisp_Object wait_for_cell,
6644 struct Lisp_Process *wait_proc, int just_wait_proc)
6646 register int nfds;
6647 struct timespec end_time, timeout;
6649 if (time_limit < 0)
6651 time_limit = 0;
6652 nsecs = -1;
6654 else if (TYPE_MAXIMUM (time_t) < time_limit)
6655 time_limit = TYPE_MAXIMUM (time_t);
6657 /* What does time_limit really mean? */
6658 if (time_limit || nsecs > 0)
6660 timeout = make_timespec (time_limit, nsecs);
6661 end_time = timespec_add (current_timespec (), timeout);
6664 /* Turn off periodic alarms (in case they are in use)
6665 and then turn off any other atimers,
6666 because the select emulator uses alarms. */
6667 stop_polling ();
6668 turn_on_atimers (0);
6670 while (1)
6672 bool timeout_reduced_for_timers = false;
6673 fd_set waitchannels;
6674 int xerrno;
6676 /* If calling from keyboard input, do not quit
6677 since we want to return C-g as an input character.
6678 Otherwise, do pending quit if requested. */
6679 if (read_kbd >= 0)
6680 QUIT;
6682 /* Exit now if the cell we're waiting for became non-nil. */
6683 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6684 break;
6686 /* Compute time from now till when time limit is up. */
6687 /* Exit if already run out. */
6688 if (nsecs < 0)
6690 /* A negative timeout means
6691 gobble output available now
6692 but don't wait at all. */
6694 timeout = make_timespec (0, 0);
6696 else if (time_limit || nsecs > 0)
6698 struct timespec now = current_timespec ();
6699 if (timespec_cmp (end_time, now) <= 0)
6700 break;
6701 timeout = timespec_sub (end_time, now);
6703 else
6705 timeout = make_timespec (100000, 0);
6708 /* If our caller will not immediately handle keyboard events,
6709 run timer events directly.
6710 (Callers that will immediately read keyboard events
6711 call timer_delay on their own.) */
6712 if (NILP (wait_for_cell))
6714 struct timespec timer_delay;
6718 unsigned old_timers_run = timers_run;
6719 timer_delay = timer_check ();
6720 if (timers_run != old_timers_run && do_display)
6721 /* We must retry, since a timer may have requeued itself
6722 and that could alter the time delay. */
6723 redisplay_preserve_echo_area (14);
6724 else
6725 break;
6727 while (!detect_input_pending ());
6729 /* If there is unread keyboard input, also return. */
6730 if (read_kbd != 0
6731 && requeued_events_pending_p ())
6732 break;
6734 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6736 if (timespec_cmp (timer_delay, timeout) < 0)
6738 timeout = timer_delay;
6739 timeout_reduced_for_timers = true;
6744 /* Cause C-g and alarm signals to take immediate action,
6745 and cause input available signals to zero out timeout. */
6746 if (read_kbd < 0)
6747 set_waiting_for_input (&timeout);
6749 /* If a frame has been newly mapped and needs updating,
6750 reprocess its display stuff. */
6751 if (frame_garbaged && do_display)
6753 clear_waiting_for_input ();
6754 redisplay_preserve_echo_area (15);
6755 if (read_kbd < 0)
6756 set_waiting_for_input (&timeout);
6759 /* Wait till there is something to do. */
6760 FD_ZERO (&waitchannels);
6761 if (read_kbd && detect_input_pending ())
6762 nfds = 0;
6763 else
6765 if (read_kbd || !NILP (wait_for_cell))
6766 FD_SET (0, &waitchannels);
6767 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6770 xerrno = errno;
6772 /* Make C-g and alarm signals set flags again. */
6773 clear_waiting_for_input ();
6775 /* If we woke up due to SIGWINCH, actually change size now. */
6776 do_pending_window_change (0);
6778 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6779 /* We waited the full specified time, so return now. */
6780 break;
6782 if (nfds == -1)
6784 /* If the system call was interrupted, then go around the
6785 loop again. */
6786 if (xerrno == EINTR)
6787 FD_ZERO (&waitchannels);
6788 else
6789 report_file_errno ("Failed select", Qnil, xerrno);
6792 /* Check for keyboard input. */
6794 if (read_kbd
6795 && detect_input_pending_run_timers (do_display))
6797 swallow_events (do_display);
6798 if (detect_input_pending_run_timers (do_display))
6799 break;
6802 /* If there is unread keyboard input, also return. */
6803 if (read_kbd
6804 && requeued_events_pending_p ())
6805 break;
6807 /* If wait_for_cell. check for keyboard input
6808 but don't run any timers.
6809 ??? (It seems wrong to me to check for keyboard
6810 input at all when wait_for_cell, but the code
6811 has been this way since July 1994.
6812 Try changing this after version 19.31.) */
6813 if (! NILP (wait_for_cell)
6814 && detect_input_pending ())
6816 swallow_events (do_display);
6817 if (detect_input_pending ())
6818 break;
6821 /* Exit now if the cell we're waiting for became non-nil. */
6822 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6823 break;
6826 start_polling ();
6828 return -1;
6831 #endif /* not subprocesses */
6833 /* The following functions are needed even if async subprocesses are
6834 not supported. Some of them are no-op stubs in that case. */
6836 #ifdef HAVE_TIMERFD
6838 /* Add FD, which is a descriptor returned by timerfd_create,
6839 to the set of non-keyboard input descriptors. */
6841 void
6842 add_timer_wait_descriptor (int fd)
6844 FD_SET (fd, &input_wait_mask);
6845 FD_SET (fd, &non_keyboard_wait_mask);
6846 FD_SET (fd, &non_process_wait_mask);
6847 fd_callback_info[fd].func = timerfd_callback;
6848 fd_callback_info[fd].data = NULL;
6849 fd_callback_info[fd].condition |= FOR_READ;
6850 if (fd > max_input_desc)
6851 max_input_desc = fd;
6854 #endif /* HAVE_TIMERFD */
6856 /* Add DESC to the set of keyboard input descriptors. */
6858 void
6859 add_keyboard_wait_descriptor (int desc)
6861 #ifdef subprocesses /* Actually means "not MSDOS". */
6862 FD_SET (desc, &input_wait_mask);
6863 FD_SET (desc, &non_process_wait_mask);
6864 if (desc > max_input_desc)
6865 max_input_desc = desc;
6866 #endif
6869 /* From now on, do not expect DESC to give keyboard input. */
6871 void
6872 delete_keyboard_wait_descriptor (int desc)
6874 #ifdef subprocesses
6875 FD_CLR (desc, &input_wait_mask);
6876 FD_CLR (desc, &non_process_wait_mask);
6877 delete_input_desc (desc);
6878 #endif
6881 /* Setup coding systems of PROCESS. */
6883 void
6884 setup_process_coding_systems (Lisp_Object process)
6886 #ifdef subprocesses
6887 struct Lisp_Process *p = XPROCESS (process);
6888 int inch = p->infd;
6889 int outch = p->outfd;
6890 Lisp_Object coding_system;
6892 if (inch < 0 || outch < 0)
6893 return;
6895 if (!proc_decode_coding_system[inch])
6896 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6897 coding_system = p->decode_coding_system;
6898 if (EQ (p->filter, Qinternal_default_process_filter)
6899 && BUFFERP (p->buffer))
6901 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6902 coding_system = raw_text_coding_system (coding_system);
6904 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6906 if (!proc_encode_coding_system[outch])
6907 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6908 setup_coding_system (p->encode_coding_system,
6909 proc_encode_coding_system[outch]);
6910 #endif
6913 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6914 doc: /* Return the (or a) process associated with BUFFER.
6915 BUFFER may be a buffer or the name of one. */)
6916 (register Lisp_Object buffer)
6918 #ifdef subprocesses
6919 register Lisp_Object buf, tail, proc;
6921 if (NILP (buffer)) return Qnil;
6922 buf = Fget_buffer (buffer);
6923 if (NILP (buf)) return Qnil;
6925 FOR_EACH_PROCESS (tail, proc)
6926 if (EQ (XPROCESS (proc)->buffer, buf))
6927 return proc;
6928 #endif /* subprocesses */
6929 return Qnil;
6932 DEFUN ("process-inherit-coding-system-flag",
6933 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6934 1, 1, 0,
6935 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6936 If this flag is t, `buffer-file-coding-system' of the buffer
6937 associated with PROCESS will inherit the coding system used to decode
6938 the process output. */)
6939 (register Lisp_Object process)
6941 #ifdef subprocesses
6942 CHECK_PROCESS (process);
6943 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6944 #else
6945 /* Ignore the argument and return the value of
6946 inherit-process-coding-system. */
6947 return inherit_process_coding_system ? Qt : Qnil;
6948 #endif
6951 /* Kill all processes associated with `buffer'.
6952 If `buffer' is nil, kill all processes. */
6954 void
6955 kill_buffer_processes (Lisp_Object buffer)
6957 #ifdef subprocesses
6958 Lisp_Object tail, proc;
6960 FOR_EACH_PROCESS (tail, proc)
6961 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6963 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6964 Fdelete_process (proc);
6965 else if (XPROCESS (proc)->infd >= 0)
6966 process_send_signal (proc, SIGHUP, Qnil, 1);
6968 #else /* subprocesses */
6969 /* Since we have no subprocesses, this does nothing. */
6970 #endif /* subprocesses */
6973 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6974 Swaiting_for_user_input_p, 0, 0, 0,
6975 doc: /* Return non-nil if Emacs is waiting for input from the user.
6976 This is intended for use by asynchronous process output filters and sentinels. */)
6977 (void)
6979 #ifdef subprocesses
6980 return (waiting_for_user_input_p ? Qt : Qnil);
6981 #else
6982 return Qnil;
6983 #endif
6986 /* Stop reading input from keyboard sources. */
6988 void
6989 hold_keyboard_input (void)
6991 kbd_is_on_hold = 1;
6994 /* Resume reading input from keyboard sources. */
6996 void
6997 unhold_keyboard_input (void)
6999 kbd_is_on_hold = 0;
7002 /* Return true if keyboard input is on hold, zero otherwise. */
7004 bool
7005 kbd_on_hold_p (void)
7007 return kbd_is_on_hold;
7011 /* Enumeration of and access to system processes a-la ps(1). */
7013 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7014 0, 0, 0,
7015 doc: /* Return a list of numerical process IDs of all running processes.
7016 If this functionality is unsupported, return nil.
7018 See `process-attributes' for getting attributes of a process given its ID. */)
7019 (void)
7021 return list_system_processes ();
7024 DEFUN ("process-attributes", Fprocess_attributes,
7025 Sprocess_attributes, 1, 1, 0,
7026 doc: /* Return attributes of the process given by its PID, a number.
7028 Value is an alist where each element is a cons cell of the form
7030 \(KEY . VALUE)
7032 If this functionality is unsupported, the value is nil.
7034 See `list-system-processes' for getting a list of all process IDs.
7036 The KEYs of the attributes that this function may return are listed
7037 below, together with the type of the associated VALUE (in parentheses).
7038 Not all platforms support all of these attributes; unsupported
7039 attributes will not appear in the returned alist.
7040 Unless explicitly indicated otherwise, numbers can have either
7041 integer or floating point values.
7043 euid -- Effective user User ID of the process (number)
7044 user -- User name corresponding to euid (string)
7045 egid -- Effective user Group ID of the process (number)
7046 group -- Group name corresponding to egid (string)
7047 comm -- Command name (executable name only) (string)
7048 state -- Process state code, such as "S", "R", or "T" (string)
7049 ppid -- Parent process ID (number)
7050 pgrp -- Process group ID (number)
7051 sess -- Session ID, i.e. process ID of session leader (number)
7052 ttname -- Controlling tty name (string)
7053 tpgid -- ID of foreground process group on the process's tty (number)
7054 minflt -- number of minor page faults (number)
7055 majflt -- number of major page faults (number)
7056 cminflt -- cumulative number of minor page faults (number)
7057 cmajflt -- cumulative number of major page faults (number)
7058 utime -- user time used by the process, in (current-time) format,
7059 which is a list of integers (HIGH LOW USEC PSEC)
7060 stime -- system time used by the process (current-time)
7061 time -- sum of utime and stime (current-time)
7062 cutime -- user time used by the process and its children (current-time)
7063 cstime -- system time used by the process and its children (current-time)
7064 ctime -- sum of cutime and cstime (current-time)
7065 pri -- priority of the process (number)
7066 nice -- nice value of the process (number)
7067 thcount -- process thread count (number)
7068 start -- time the process started (current-time)
7069 vsize -- virtual memory size of the process in KB's (number)
7070 rss -- resident set size of the process in KB's (number)
7071 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7072 pcpu -- percents of CPU time used by the process (floating-point number)
7073 pmem -- percents of total physical memory used by process's resident set
7074 (floating-point number)
7075 args -- command line which invoked the process (string). */)
7076 ( Lisp_Object pid)
7078 return system_process_attributes (pid);
7081 #ifdef subprocesses
7082 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7083 Invoke this after init_process_emacs, and after glib and/or GNUstep
7084 futz with the SIGCHLD handler, but before Emacs forks any children.
7085 This function's caller should block SIGCHLD. */
7087 void
7088 catch_child_signal (void)
7090 struct sigaction action, old_action;
7091 sigset_t oldset;
7092 emacs_sigaction_init (&action, deliver_child_signal);
7093 block_child_signal (&oldset);
7094 sigaction (SIGCHLD, &action, &old_action);
7095 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7096 || ! (old_action.sa_flags & SA_SIGINFO));
7098 if (old_action.sa_handler != deliver_child_signal)
7099 lib_child_handler
7100 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7101 ? dummy_handler
7102 : old_action.sa_handler);
7103 unblock_child_signal (&oldset);
7105 #endif /* subprocesses */
7108 /* This is not called "init_process" because that is the name of a
7109 Mach system call, so it would cause problems on Darwin systems. */
7110 void
7111 init_process_emacs (void)
7113 #ifdef subprocesses
7114 register int i;
7116 inhibit_sentinels = 0;
7118 #ifndef CANNOT_DUMP
7119 if (! noninteractive || initialized)
7120 #endif
7122 #if defined HAVE_GLIB && !defined WINDOWSNT
7123 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7124 this should always fail, but is enough to initialize glib's
7125 private SIGCHLD handler, allowing catch_child_signal to copy
7126 it into lib_child_handler. */
7127 g_source_unref (g_child_watch_source_new (getpid ()));
7128 #endif
7129 catch_child_signal ();
7132 FD_ZERO (&input_wait_mask);
7133 FD_ZERO (&non_keyboard_wait_mask);
7134 FD_ZERO (&non_process_wait_mask);
7135 FD_ZERO (&write_mask);
7136 max_process_desc = max_input_desc = -1;
7137 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7139 #ifdef NON_BLOCKING_CONNECT
7140 FD_ZERO (&connect_wait_mask);
7141 num_pending_connects = 0;
7142 #endif
7144 #ifdef ADAPTIVE_READ_BUFFERING
7145 process_output_delay_count = 0;
7146 process_output_skip = 0;
7147 #endif
7149 /* Don't do this, it caused infinite select loops. The display
7150 method should call add_keyboard_wait_descriptor on stdin if it
7151 needs that. */
7152 #if 0
7153 FD_SET (0, &input_wait_mask);
7154 #endif
7156 Vprocess_alist = Qnil;
7157 deleted_pid_list = Qnil;
7158 for (i = 0; i < FD_SETSIZE; i++)
7160 chan_process[i] = Qnil;
7161 proc_buffered_char[i] = -1;
7163 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7164 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7165 #ifdef DATAGRAM_SOCKETS
7166 memset (datagram_address, 0, sizeof datagram_address);
7167 #endif
7170 Lisp_Object subfeatures = Qnil;
7171 const struct socket_options *sopt;
7173 #define ADD_SUBFEATURE(key, val) \
7174 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7176 #ifdef NON_BLOCKING_CONNECT
7177 ADD_SUBFEATURE (QCnowait, Qt);
7178 #endif
7179 #ifdef DATAGRAM_SOCKETS
7180 ADD_SUBFEATURE (QCtype, Qdatagram);
7181 #endif
7182 #ifdef HAVE_SEQPACKET
7183 ADD_SUBFEATURE (QCtype, Qseqpacket);
7184 #endif
7185 #ifdef HAVE_LOCAL_SOCKETS
7186 ADD_SUBFEATURE (QCfamily, Qlocal);
7187 #endif
7188 ADD_SUBFEATURE (QCfamily, Qipv4);
7189 #ifdef AF_INET6
7190 ADD_SUBFEATURE (QCfamily, Qipv6);
7191 #endif
7192 #ifdef HAVE_GETSOCKNAME
7193 ADD_SUBFEATURE (QCservice, Qt);
7194 #endif
7195 ADD_SUBFEATURE (QCserver, Qt);
7197 for (sopt = socket_options; sopt->name; sopt++)
7198 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7200 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7203 #if defined (DARWIN_OS)
7204 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7205 processes. As such, we only change the default value. */
7206 if (initialized)
7208 char const *release = (STRINGP (Voperating_system_release)
7209 ? SSDATA (Voperating_system_release)
7210 : 0);
7211 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7212 Vprocess_connection_type = Qnil;
7215 #endif
7216 #endif /* subprocesses */
7217 kbd_is_on_hold = 0;
7220 void
7221 syms_of_process (void)
7223 #ifdef subprocesses
7225 DEFSYM (Qprocessp, "processp");
7226 DEFSYM (Qrun, "run");
7227 DEFSYM (Qstop, "stop");
7228 DEFSYM (Qsignal, "signal");
7230 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7231 here again.
7233 Qexit = intern_c_string ("exit");
7234 staticpro (&Qexit); */
7236 DEFSYM (Qopen, "open");
7237 DEFSYM (Qclosed, "closed");
7238 DEFSYM (Qconnect, "connect");
7239 DEFSYM (Qfailed, "failed");
7240 DEFSYM (Qlisten, "listen");
7241 DEFSYM (Qlocal, "local");
7242 DEFSYM (Qipv4, "ipv4");
7243 #ifdef AF_INET6
7244 DEFSYM (Qipv6, "ipv6");
7245 #endif
7246 DEFSYM (Qdatagram, "datagram");
7247 DEFSYM (Qseqpacket, "seqpacket");
7249 DEFSYM (QCport, ":port");
7250 DEFSYM (QCspeed, ":speed");
7251 DEFSYM (QCprocess, ":process");
7253 DEFSYM (QCbytesize, ":bytesize");
7254 DEFSYM (QCstopbits, ":stopbits");
7255 DEFSYM (QCparity, ":parity");
7256 DEFSYM (Qodd, "odd");
7257 DEFSYM (Qeven, "even");
7258 DEFSYM (QCflowcontrol, ":flowcontrol");
7259 DEFSYM (Qhw, "hw");
7260 DEFSYM (Qsw, "sw");
7261 DEFSYM (QCsummary, ":summary");
7263 DEFSYM (Qreal, "real");
7264 DEFSYM (Qnetwork, "network");
7265 DEFSYM (Qserial, "serial");
7266 DEFSYM (QCbuffer, ":buffer");
7267 DEFSYM (QChost, ":host");
7268 DEFSYM (QCservice, ":service");
7269 DEFSYM (QClocal, ":local");
7270 DEFSYM (QCremote, ":remote");
7271 DEFSYM (QCcoding, ":coding");
7272 DEFSYM (QCserver, ":server");
7273 DEFSYM (QCnowait, ":nowait");
7274 DEFSYM (QCsentinel, ":sentinel");
7275 DEFSYM (QClog, ":log");
7276 DEFSYM (QCnoquery, ":noquery");
7277 DEFSYM (QCstop, ":stop");
7278 DEFSYM (QCoptions, ":options");
7279 DEFSYM (QCplist, ":plist");
7281 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7283 staticpro (&Vprocess_alist);
7284 staticpro (&deleted_pid_list);
7286 #endif /* subprocesses */
7288 DEFSYM (QCname, ":name");
7289 DEFSYM (QCtype, ":type");
7291 DEFSYM (Qeuid, "euid");
7292 DEFSYM (Qegid, "egid");
7293 DEFSYM (Quser, "user");
7294 DEFSYM (Qgroup, "group");
7295 DEFSYM (Qcomm, "comm");
7296 DEFSYM (Qstate, "state");
7297 DEFSYM (Qppid, "ppid");
7298 DEFSYM (Qpgrp, "pgrp");
7299 DEFSYM (Qsess, "sess");
7300 DEFSYM (Qttname, "ttname");
7301 DEFSYM (Qtpgid, "tpgid");
7302 DEFSYM (Qminflt, "minflt");
7303 DEFSYM (Qmajflt, "majflt");
7304 DEFSYM (Qcminflt, "cminflt");
7305 DEFSYM (Qcmajflt, "cmajflt");
7306 DEFSYM (Qutime, "utime");
7307 DEFSYM (Qstime, "stime");
7308 DEFSYM (Qtime, "time");
7309 DEFSYM (Qcutime, "cutime");
7310 DEFSYM (Qcstime, "cstime");
7311 DEFSYM (Qctime, "ctime");
7312 #ifdef subprocesses
7313 DEFSYM (Qinternal_default_process_sentinel,
7314 "internal-default-process-sentinel");
7315 DEFSYM (Qinternal_default_process_filter,
7316 "internal-default-process-filter");
7317 #endif
7318 DEFSYM (Qpri, "pri");
7319 DEFSYM (Qnice, "nice");
7320 DEFSYM (Qthcount, "thcount");
7321 DEFSYM (Qstart, "start");
7322 DEFSYM (Qvsize, "vsize");
7323 DEFSYM (Qrss, "rss");
7324 DEFSYM (Qetime, "etime");
7325 DEFSYM (Qpcpu, "pcpu");
7326 DEFSYM (Qpmem, "pmem");
7327 DEFSYM (Qargs, "args");
7329 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7330 doc: /* Non-nil means delete processes immediately when they exit.
7331 A value of nil means don't delete them until `list-processes' is run. */);
7333 delete_exited_processes = 1;
7335 #ifdef subprocesses
7336 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7337 doc: /* Control type of device used to communicate with subprocesses.
7338 Values are nil to use a pipe, or t or `pty' to use a pty.
7339 The value has no effect if the system has no ptys or if all ptys are busy:
7340 then a pipe is used in any case.
7341 The value takes effect when `start-process' is called. */);
7342 Vprocess_connection_type = Qt;
7344 #ifdef ADAPTIVE_READ_BUFFERING
7345 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7346 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7347 On some systems, when Emacs reads the output from a subprocess, the output data
7348 is read in very small blocks, potentially resulting in very poor performance.
7349 This behavior can be remedied to some extent by setting this variable to a
7350 non-nil value, as it will automatically delay reading from such processes, to
7351 allow them to produce more output before Emacs tries to read it.
7352 If the value is t, the delay is reset after each write to the process; any other
7353 non-nil value means that the delay is not reset on write.
7354 The variable takes effect when `start-process' is called. */);
7355 Vprocess_adaptive_read_buffering = Qt;
7356 #endif
7358 defsubr (&Sprocessp);
7359 defsubr (&Sget_process);
7360 defsubr (&Sdelete_process);
7361 defsubr (&Sprocess_status);
7362 defsubr (&Sprocess_exit_status);
7363 defsubr (&Sprocess_id);
7364 defsubr (&Sprocess_name);
7365 defsubr (&Sprocess_tty_name);
7366 defsubr (&Sprocess_command);
7367 defsubr (&Sset_process_buffer);
7368 defsubr (&Sprocess_buffer);
7369 defsubr (&Sprocess_mark);
7370 defsubr (&Sset_process_filter);
7371 defsubr (&Sprocess_filter);
7372 defsubr (&Sset_process_sentinel);
7373 defsubr (&Sprocess_sentinel);
7374 defsubr (&Sset_process_window_size);
7375 defsubr (&Sset_process_inherit_coding_system_flag);
7376 defsubr (&Sset_process_query_on_exit_flag);
7377 defsubr (&Sprocess_query_on_exit_flag);
7378 defsubr (&Sprocess_contact);
7379 defsubr (&Sprocess_plist);
7380 defsubr (&Sset_process_plist);
7381 defsubr (&Sprocess_list);
7382 defsubr (&Sstart_process);
7383 defsubr (&Sserial_process_configure);
7384 defsubr (&Smake_serial_process);
7385 defsubr (&Sset_network_process_option);
7386 defsubr (&Smake_network_process);
7387 defsubr (&Sformat_network_address);
7388 defsubr (&Snetwork_interface_list);
7389 defsubr (&Snetwork_interface_info);
7390 #ifdef DATAGRAM_SOCKETS
7391 defsubr (&Sprocess_datagram_address);
7392 defsubr (&Sset_process_datagram_address);
7393 #endif
7394 defsubr (&Saccept_process_output);
7395 defsubr (&Sprocess_send_region);
7396 defsubr (&Sprocess_send_string);
7397 defsubr (&Sinterrupt_process);
7398 defsubr (&Skill_process);
7399 defsubr (&Squit_process);
7400 defsubr (&Sstop_process);
7401 defsubr (&Scontinue_process);
7402 defsubr (&Sprocess_running_child_p);
7403 defsubr (&Sprocess_send_eof);
7404 defsubr (&Ssignal_process);
7405 defsubr (&Swaiting_for_user_input_p);
7406 defsubr (&Sprocess_type);
7407 defsubr (&Sinternal_default_process_sentinel);
7408 defsubr (&Sinternal_default_process_filter);
7409 defsubr (&Sset_process_coding_system);
7410 defsubr (&Sprocess_coding_system);
7411 defsubr (&Sset_process_filter_multibyte);
7412 defsubr (&Sprocess_filter_multibyte_p);
7414 #endif /* subprocesses */
7416 defsubr (&Sget_buffer_process);
7417 defsubr (&Sprocess_inherit_coding_system_flag);
7418 defsubr (&Slist_system_processes);
7419 defsubr (&Sprocess_attributes);