merge from trunk
[emacs.git] / src / process.c
blob91483e5839fb081cc10df065a9b5fc362c591152
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #define PROCESS_INLINE EXTERN_INLINE
26 #include <stdio.h>
27 #include <errno.h>
28 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
29 #include <sys/file.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <fcntl.h>
34 #include "lisp.h"
36 /* Only MS-DOS does not define `subprocesses'. */
37 #ifdef subprocesses
39 #include <sys/socket.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
44 /* Are local (unix) sockets supported? */
45 #if defined (HAVE_SYS_UN_H)
46 #if !defined (AF_LOCAL) && defined (AF_UNIX)
47 #define AF_LOCAL AF_UNIX
48 #endif
49 #ifdef AF_LOCAL
50 #define HAVE_LOCAL_SOCKETS
51 #include <sys/un.h>
52 #endif
53 #endif
55 #include <sys/ioctl.h>
56 #if defined (HAVE_NET_IF_H)
57 #include <net/if.h>
58 #endif /* HAVE_NET_IF_H */
60 #if defined (HAVE_IFADDRS_H)
61 /* Must be after net/if.h */
62 #include <ifaddrs.h>
64 /* We only use structs from this header when we use getifaddrs. */
65 #if defined (HAVE_NET_IF_DL_H)
66 #include <net/if_dl.h>
67 #endif
69 #endif
71 #ifdef NEED_BSDTTY
72 #include <bsdtty.h>
73 #endif
75 #ifdef USG5_4
76 # include <sys/stream.h>
77 # include <sys/stropts.h>
78 #endif
80 #ifdef HAVE_RES_INIT
81 #include <arpa/nameser.h>
82 #include <resolv.h>
83 #endif
85 #ifdef HAVE_UTIL_H
86 #include <util.h>
87 #endif
89 #ifdef HAVE_PTY_H
90 #include <pty.h>
91 #endif
93 #include <c-ctype.h>
94 #include <sig2str.h>
95 #include <verify.h>
97 #endif /* subprocesses */
99 #include "systime.h"
100 #include "systty.h"
102 #include "window.h"
103 #include "character.h"
104 #include "buffer.h"
105 #include "coding.h"
106 #include "process.h"
107 #include "frame.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
127 #ifdef HAVE_GLIB
128 #include "xgselect.h"
129 #ifndef WINDOWSNT
130 #include <glib.h>
131 #endif
132 #endif
134 #ifdef WINDOWSNT
135 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
136 EMACS_TIME *, void *);
137 #endif
139 #ifndef SOCK_CLOEXEC
140 # define SOCK_CLOEXEC 0
141 #endif
143 #ifndef HAVE_ACCEPT4
145 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
147 static int
148 close_on_exec (int fd)
150 if (0 <= fd)
151 fcntl (fd, F_SETFD, FD_CLOEXEC);
152 return fd;
155 static int
156 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
158 return close_on_exec (accept (sockfd, addr, addrlen));
161 static int
162 process_socket (int domain, int type, int protocol)
164 return close_on_exec (socket (domain, type, protocol));
166 # undef socket
167 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
168 #endif
170 /* Work around GCC 4.7.0 bug with strict overflow checking; see
171 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
172 These lines can be removed once the GCC bug is fixed. */
173 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
174 # pragma GCC diagnostic ignored "-Wstrict-overflow"
175 #endif
177 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
178 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
179 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
180 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
181 Lisp_Object QCname, QCtype;
183 /* True if keyboard input is on hold, zero otherwise. */
185 static bool kbd_is_on_hold;
187 /* Nonzero means don't run process sentinels. This is used
188 when exiting. */
189 bool inhibit_sentinels;
191 #ifdef subprocesses
193 Lisp_Object Qprocessp;
194 static Lisp_Object Qrun, Qstop, Qsignal;
195 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
196 Lisp_Object Qlocal;
197 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
198 static Lisp_Object Qreal, Qnetwork, Qserial;
199 #ifdef AF_INET6
200 static Lisp_Object Qipv6;
201 #endif
202 static Lisp_Object QCport, QCprocess;
203 Lisp_Object QCspeed;
204 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
205 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
206 static Lisp_Object QCbuffer, QChost, QCservice;
207 static Lisp_Object QClocal, QCremote, QCcoding;
208 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
209 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
210 static Lisp_Object Qlast_nonmenu_event;
211 static Lisp_Object Qinternal_default_process_sentinel;
212 static Lisp_Object Qinternal_default_process_filter;
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
219 /* Number of events of change of status of a process. */
220 static EMACS_INT process_tick;
221 /* Number of events for which the user or sentinel has been notified. */
222 static EMACS_INT update_tick;
224 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
226 /* Only W32 has this, it really means that select can't take write mask. */
227 #ifdef BROKEN_NON_BLOCKING_CONNECT
228 #undef NON_BLOCKING_CONNECT
229 #define SELECT_CANT_DO_WRITE_MASK
230 #else
231 #ifndef NON_BLOCKING_CONNECT
232 #ifdef HAVE_SELECT
233 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
234 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
235 #define NON_BLOCKING_CONNECT
236 #endif /* EWOULDBLOCK || EINPROGRESS */
237 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
238 #endif /* HAVE_SELECT */
239 #endif /* NON_BLOCKING_CONNECT */
240 #endif /* BROKEN_NON_BLOCKING_CONNECT */
242 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
243 this system. We need to read full packets, so we need a
244 "non-destructive" select. So we require either native select,
245 or emulation of select using FIONREAD. */
247 #ifndef BROKEN_DATAGRAM_SOCKETS
248 # if defined HAVE_SELECT || defined USABLE_FIONREAD
249 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
250 # define DATAGRAM_SOCKETS
251 # endif
252 # endif
253 #endif
255 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
256 # define HAVE_SEQPACKET
257 #endif
259 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
260 #define ADAPTIVE_READ_BUFFERING
261 #endif
263 #ifdef ADAPTIVE_READ_BUFFERING
264 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
265 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
266 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
268 /* Number of processes which have a non-zero read_output_delay,
269 and therefore might be delayed for adaptive read buffering. */
271 static int process_output_delay_count;
273 /* True if any process has non-nil read_output_skip. */
275 static bool process_output_skip;
277 #else
278 #define process_output_delay_count 0
279 #endif
281 static void create_process (Lisp_Object, char **, Lisp_Object);
282 #ifdef USABLE_SIGIO
283 static bool keyboard_bit_set (SELECT_TYPE *);
284 #endif
285 static void deactivate_process (Lisp_Object);
286 static void status_notify (struct Lisp_Process *);
287 static int read_process_output (Lisp_Object, int);
288 static void handle_child_signal (int);
289 static void create_pty (Lisp_Object);
291 /* If we support a window system, turn on the code to poll periodically
292 to detect C-g. It isn't actually used when doing interrupt input. */
293 #ifdef HAVE_WINDOW_SYSTEM
294 #define POLL_FOR_INPUT
295 #endif
297 static Lisp_Object get_process (register Lisp_Object name);
298 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
300 #ifdef NON_BLOCKING_CONNECT
301 /* Number of bits set in connect_wait_mask. */
302 static int num_pending_connects;
303 #endif /* NON_BLOCKING_CONNECT */
305 /* The largest descriptor currently in use; -1 if none. */
306 static int max_desc;
308 /* Indexed by descriptor, gives the process (if any) for that descriptor */
309 static Lisp_Object chan_process[MAXDESC];
311 /* Alist of elements (NAME . PROCESS) */
312 static Lisp_Object Vprocess_alist;
314 /* Buffered-ahead input char from process, indexed by channel.
315 -1 means empty (no char is buffered).
316 Used on sys V where the only way to tell if there is any
317 output from the process is to read at least one char.
318 Always -1 on systems that support FIONREAD. */
320 static int proc_buffered_char[MAXDESC];
322 /* Table of `struct coding-system' for each process. */
323 static struct coding_system *proc_decode_coding_system[MAXDESC];
324 static struct coding_system *proc_encode_coding_system[MAXDESC];
326 #ifdef DATAGRAM_SOCKETS
327 /* Table of `partner address' for datagram sockets. */
328 static struct sockaddr_and_len {
329 struct sockaddr *sa;
330 int len;
331 } datagram_address[MAXDESC];
332 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
333 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
334 #else
335 #define DATAGRAM_CHAN_P(chan) (0)
336 #define DATAGRAM_CONN_P(proc) (0)
337 #endif
339 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
340 a `for' loop which iterates over processes from Vprocess_alist. */
342 #define FOR_EACH_PROCESS(list_var, proc_var) \
343 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
345 /* These setters are used only in this file, so they can be private. */
346 static void
347 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
349 p->buffer = val;
351 static void
352 pset_command (struct Lisp_Process *p, Lisp_Object val)
354 p->command = val;
356 static void
357 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
359 p->decode_coding_system = val;
361 static void
362 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
364 p->decoding_buf = val;
366 static void
367 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
369 p->encode_coding_system = val;
371 static void
372 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
374 p->encoding_buf = val;
376 static void
377 pset_filter (struct Lisp_Process *p, Lisp_Object val)
379 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
381 static void
382 pset_log (struct Lisp_Process *p, Lisp_Object val)
384 p->log = val;
386 static void
387 pset_mark (struct Lisp_Process *p, Lisp_Object val)
389 p->mark = val;
391 static void
392 pset_thread (struct Lisp_Process *p, Lisp_Object val)
394 p->thread = val;
396 static void
397 pset_name (struct Lisp_Process *p, Lisp_Object val)
399 p->name = val;
401 static void
402 pset_plist (struct Lisp_Process *p, Lisp_Object val)
404 p->plist = val;
406 static void
407 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
409 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
411 static void
412 pset_status (struct Lisp_Process *p, Lisp_Object val)
414 p->status = val;
416 static void
417 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
419 p->tty_name = val;
421 static void
422 pset_type (struct Lisp_Process *p, Lisp_Object val)
424 p->type = val;
426 static void
427 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
429 p->write_queue = val;
434 enum fd_bits
436 /* Read from file descriptor. */
437 FOR_READ = 1,
438 /* Write to file descriptor. */
439 FOR_WRITE = 2,
440 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
441 set. */
442 KEYBOARD_FD = 4,
443 /* This descriptor refers to a process. */
444 PROCESS_FD = 8,
445 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
446 NON_BLOCKING_CONNECT_FD = 16
449 static struct fd_callback_data
451 fd_callback func;
452 void *data;
453 /* Flags from enum fd_bits. */
454 int flags;
455 /* If this fd is locked to a certain thread, this points to it.
456 Otherwise, this is NULL. If an fd is locked to a thread, then
457 only that thread is permitted to wait on it. */
458 struct thread_state *thread;
459 /* If this fd is currently being selected on by a thread, this
460 points to the thread. Otherwise it is NULL. */
461 struct thread_state *waiting_thread;
462 } fd_callback_info[MAXDESC];
465 /* Add a file descriptor FD to be monitored for when read is possible.
466 When read is possible, call FUNC with argument DATA. */
468 void
469 add_read_fd (int fd, fd_callback func, void *data)
471 eassert (fd < MAXDESC);
472 add_keyboard_wait_descriptor (fd);
474 fd_callback_info[fd].func = func;
475 fd_callback_info[fd].data = data;
478 static void
479 add_non_keyboard_read_fd (int fd)
481 eassert (fd >= 0 && fd < MAXDESC);
482 eassert (fd_callback_info[fd].func == NULL);
483 fd_callback_info[fd].flags |= FOR_READ;
484 if (fd > max_desc)
485 max_desc = fd;
488 static void
489 add_process_read_fd (int fd)
491 add_non_keyboard_read_fd (fd);
492 fd_callback_info[fd].flags |= PROCESS_FD;
495 /* Stop monitoring file descriptor FD for when read is possible. */
497 void
498 delete_read_fd (int fd)
500 eassert (fd < MAXDESC);
501 eassert (fd <= max_desc);
502 delete_keyboard_wait_descriptor (fd);
504 if (fd_callback_info[fd].flags == 0)
506 fd_callback_info[fd].func = 0;
507 fd_callback_info[fd].data = 0;
511 /* Add a file descriptor FD to be monitored for when write is possible.
512 When write is possible, call FUNC with argument DATA. */
514 void
515 add_write_fd (int fd, fd_callback func, void *data)
517 eassert (fd < MAXDESC);
518 if (fd > max_desc)
519 max_desc = fd;
521 fd_callback_info[fd].func = func;
522 fd_callback_info[fd].data = data;
523 fd_callback_info[fd].flags |= FOR_WRITE;
526 static void
527 add_non_blocking_write_fd (int fd)
529 eassert (fd >= 0 && fd < MAXDESC);
530 eassert (fd_callback_info[fd].func == NULL);
532 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
533 if (fd > max_desc)
534 max_desc = fd;
535 ++num_pending_connects;
538 static void
539 recompute_max_desc (void)
541 int fd;
543 for (fd = max_desc; fd >= 0; --fd)
545 if (fd_callback_info[fd].flags != 0)
547 max_desc = fd;
548 break;
553 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
555 static void
556 delete_input_desc (int fd)
558 if (fd == max_input_desc)
561 fd--;
562 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
563 || FD_ISSET (fd, &write_mask)));
565 max_input_desc = fd;
569 /* Stop monitoring file descriptor FD for when write is possible. */
571 void
572 delete_write_fd (int fd)
574 int lim = max_desc;
576 eassert (fd < MAXDESC);
577 eassert (fd <= max_desc);
579 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
581 if (--num_pending_connects < 0)
582 abort ();
584 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
585 if (fd_callback_info[fd].flags == 0)
587 fd_callback_info[fd].func = 0;
588 fd_callback_info[fd].data = 0;
590 if (fd == max_desc)
591 recompute_max_desc ();
595 static void
596 compute_input_wait_mask (SELECT_TYPE *mask)
598 int fd;
600 FD_ZERO (mask);
601 for (fd = 0; fd <= max_desc; ++fd)
603 if (fd_callback_info[fd].thread != NULL
604 && fd_callback_info[fd].thread != current_thread)
605 continue;
606 if (fd_callback_info[fd].waiting_thread != NULL
607 && fd_callback_info[fd].waiting_thread != current_thread)
608 continue;
609 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
611 FD_SET (fd, mask);
612 fd_callback_info[fd].waiting_thread = current_thread;
617 static void
618 compute_non_process_wait_mask (SELECT_TYPE *mask)
620 int fd;
622 FD_ZERO (mask);
623 for (fd = 0; fd <= max_desc; ++fd)
625 if (fd_callback_info[fd].thread != NULL
626 && fd_callback_info[fd].thread != current_thread)
627 continue;
628 if (fd_callback_info[fd].waiting_thread != NULL
629 && fd_callback_info[fd].waiting_thread != current_thread)
630 continue;
631 if ((fd_callback_info[fd].flags & FOR_READ) != 0
632 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
634 FD_SET (fd, mask);
635 fd_callback_info[fd].waiting_thread = current_thread;
640 static void
641 compute_non_keyboard_wait_mask (SELECT_TYPE *mask)
643 int fd;
645 FD_ZERO (mask);
646 for (fd = 0; fd <= max_desc; ++fd)
648 if (fd_callback_info[fd].thread != NULL
649 && fd_callback_info[fd].thread != current_thread)
650 continue;
651 if (fd_callback_info[fd].waiting_thread != NULL
652 && fd_callback_info[fd].waiting_thread != current_thread)
653 continue;
654 if ((fd_callback_info[fd].flags & FOR_READ) != 0
655 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
657 FD_SET (fd, mask);
658 fd_callback_info[fd].waiting_thread = current_thread;
663 static void
664 compute_write_mask (SELECT_TYPE *mask)
666 int fd;
668 FD_ZERO (mask);
669 for (fd = 0; fd <= max_desc; ++fd)
671 if (fd_callback_info[fd].thread != NULL
672 && fd_callback_info[fd].thread != current_thread)
673 continue;
674 if (fd_callback_info[fd].waiting_thread != NULL
675 && fd_callback_info[fd].waiting_thread != current_thread)
676 continue;
677 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
679 FD_SET (fd, mask);
680 fd_callback_info[fd].waiting_thread = current_thread;
685 static void
686 clear_waiting_thread_info (void)
688 int fd;
690 for (fd = 0; fd <= max_desc; ++fd)
692 if (fd_callback_info[fd].waiting_thread == current_thread)
693 fd_callback_info[fd].waiting_thread = NULL;
698 /* Compute the Lisp form of the process status, p->status, from
699 the numeric status that was returned by `wait'. */
701 static Lisp_Object status_convert (int);
703 static void
704 update_status (struct Lisp_Process *p)
706 eassert (p->raw_status_new);
707 pset_status (p, status_convert (p->raw_status));
708 p->raw_status_new = 0;
711 /* Convert a process status word in Unix format to
712 the list that we use internally. */
714 static Lisp_Object
715 status_convert (int w)
717 if (WIFSTOPPED (w))
718 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
719 else if (WIFEXITED (w))
720 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
721 WCOREDUMP (w) ? Qt : Qnil));
722 else if (WIFSIGNALED (w))
723 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
724 WCOREDUMP (w) ? Qt : Qnil));
725 else
726 return Qrun;
729 /* Given a status-list, extract the three pieces of information
730 and store them individually through the three pointers. */
732 static void
733 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
735 Lisp_Object tem;
737 if (SYMBOLP (l))
739 *symbol = l;
740 *code = 0;
741 *coredump = 0;
743 else
745 *symbol = XCAR (l);
746 tem = XCDR (l);
747 *code = XFASTINT (XCAR (tem));
748 tem = XCDR (tem);
749 *coredump = !NILP (tem);
753 /* Return a string describing a process status list. */
755 static Lisp_Object
756 status_message (struct Lisp_Process *p)
758 Lisp_Object status = p->status;
759 Lisp_Object symbol;
760 int code;
761 bool coredump;
762 Lisp_Object string, string2;
764 decode_status (status, &symbol, &code, &coredump);
766 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
768 char const *signame;
769 synchronize_system_messages_locale ();
770 signame = strsignal (code);
771 if (signame == 0)
772 string = build_string ("unknown");
773 else
775 int c1, c2;
777 string = build_unibyte_string (signame);
778 if (! NILP (Vlocale_coding_system))
779 string = (code_convert_string_norecord
780 (string, Vlocale_coding_system, 0));
781 c1 = STRING_CHAR (SDATA (string));
782 c2 = downcase (c1);
783 if (c1 != c2)
784 Faset (string, make_number (0), make_number (c2));
786 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
787 return concat2 (string, string2);
789 else if (EQ (symbol, Qexit))
791 if (NETCONN1_P (p))
792 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
793 if (code == 0)
794 return build_string ("finished\n");
795 string = Fnumber_to_string (make_number (code));
796 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
797 return concat3 (build_string ("exited abnormally with code "),
798 string, string2);
800 else if (EQ (symbol, Qfailed))
802 string = Fnumber_to_string (make_number (code));
803 string2 = build_string ("\n");
804 return concat3 (build_string ("failed with code "),
805 string, string2);
807 else
808 return Fcopy_sequence (Fsymbol_name (symbol));
811 enum { PTY_NAME_SIZE = 24 };
813 /* Open an available pty, returning a file descriptor.
814 Store into PTY_NAME the file name of the terminal corresponding to the pty.
815 Return -1 on failure. */
817 static int
818 allocate_pty (char pty_name[PTY_NAME_SIZE])
820 #ifdef HAVE_PTYS
821 int fd;
823 #ifdef PTY_ITERATION
824 PTY_ITERATION
825 #else
826 register int c, i;
827 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
828 for (i = 0; i < 16; i++)
829 #endif
831 #ifdef PTY_NAME_SPRINTF
832 PTY_NAME_SPRINTF
833 #else
834 sprintf (pty_name, "/dev/pty%c%x", c, i);
835 #endif /* no PTY_NAME_SPRINTF */
837 #ifdef PTY_OPEN
838 PTY_OPEN;
839 #else /* no PTY_OPEN */
840 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
841 #endif /* no PTY_OPEN */
843 if (fd >= 0)
845 /* check to make certain that both sides are available
846 this avoids a nasty yet stupid bug in rlogins */
847 #ifdef PTY_TTY_NAME_SPRINTF
848 PTY_TTY_NAME_SPRINTF
849 #else
850 sprintf (pty_name, "/dev/tty%c%x", c, i);
851 #endif /* no PTY_TTY_NAME_SPRINTF */
852 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
854 emacs_close (fd);
855 # ifndef __sgi
856 continue;
857 # else
858 return -1;
859 # endif /* __sgi */
861 setup_pty (fd);
862 return fd;
865 #endif /* HAVE_PTYS */
866 return -1;
869 static Lisp_Object
870 make_process (Lisp_Object name)
872 register Lisp_Object val, tem, name1;
873 register struct Lisp_Process *p;
874 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
875 printmax_t i;
877 p = allocate_process ();
878 /* Initialize Lisp data. Note that allocate_process initializes all
879 Lisp data to nil, so do it only for slots which should not be nil. */
880 pset_status (p, Qrun);
881 pset_mark (p, Fmake_marker ());
882 pset_thread (p, Fcurrent_thread ());
884 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
885 non-Lisp data, so do it only for slots which should not be zero. */
886 p->infd = -1;
887 p->outfd = -1;
888 for (i = 0; i < PROCESS_OPEN_FDS; i++)
889 p->open_fd[i] = -1;
891 #ifdef HAVE_GNUTLS
892 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
893 #endif
895 /* If name is already in use, modify it until it is unused. */
897 name1 = name;
898 for (i = 1; ; i++)
900 tem = Fget_process (name1);
901 if (NILP (tem)) break;
902 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
904 name = name1;
905 pset_name (p, name);
906 pset_sentinel (p, Qinternal_default_process_sentinel);
907 pset_filter (p, Qinternal_default_process_filter);
908 XSETPROCESS (val, p);
909 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
910 return val;
913 static void
914 remove_process (register Lisp_Object proc)
916 register Lisp_Object pair;
918 pair = Frassq (proc, Vprocess_alist);
919 Vprocess_alist = Fdelq (pair, Vprocess_alist);
921 deactivate_process (proc);
924 void
925 update_processes_for_thread_death (Lisp_Object dying_thread)
927 Lisp_Object pair;
929 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
931 Lisp_Object process = XCDR (XCAR (pair));
932 if (EQ (XPROCESS (process)->thread, dying_thread))
934 struct Lisp_Process *proc = XPROCESS (process);
936 proc->thread = Qnil;
937 if (proc->infd >= 0)
938 fd_callback_info[proc->infd].thread = NULL;
939 if (proc->outfd >= 0)
940 fd_callback_info[proc->outfd].thread = NULL;
946 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
947 doc: /* Return t if OBJECT is a process. */)
948 (Lisp_Object object)
950 return PROCESSP (object) ? Qt : Qnil;
953 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
954 doc: /* Return the process named NAME, or nil if there is none. */)
955 (register Lisp_Object name)
957 if (PROCESSP (name))
958 return name;
959 CHECK_STRING (name);
960 return Fcdr (Fassoc (name, Vprocess_alist));
963 /* This is how commands for the user decode process arguments. It
964 accepts a process, a process name, a buffer, a buffer name, or nil.
965 Buffers denote the first process in the buffer, and nil denotes the
966 current buffer. */
968 static Lisp_Object
969 get_process (register Lisp_Object name)
971 register Lisp_Object proc, obj;
972 if (STRINGP (name))
974 obj = Fget_process (name);
975 if (NILP (obj))
976 obj = Fget_buffer (name);
977 if (NILP (obj))
978 error ("Process %s does not exist", SDATA (name));
980 else if (NILP (name))
981 obj = Fcurrent_buffer ();
982 else
983 obj = name;
985 /* Now obj should be either a buffer object or a process object.
987 if (BUFFERP (obj))
989 proc = Fget_buffer_process (obj);
990 if (NILP (proc))
991 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
993 else
995 CHECK_PROCESS (obj);
996 proc = obj;
998 return proc;
1002 /* Fdelete_process promises to immediately forget about the process, but in
1003 reality, Emacs needs to remember those processes until they have been
1004 treated by the SIGCHLD handler and waitpid has been invoked on them;
1005 otherwise they might fill up the kernel's process table.
1007 Some processes created by call-process are also put onto this list.
1009 Members of this list are (process-ID . filename) pairs. The
1010 process-ID is a number; the filename, if a string, is a file that
1011 needs to be removed after the process exits. */
1012 static Lisp_Object deleted_pid_list;
1014 void
1015 record_deleted_pid (pid_t pid, Lisp_Object filename)
1017 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1018 /* GC treated elements set to nil. */
1019 Fdelq (Qnil, deleted_pid_list));
1023 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1024 doc: /* Delete PROCESS: kill it and forget about it immediately.
1025 PROCESS may be a process, a buffer, the name of a process or buffer, or
1026 nil, indicating the current buffer's process. */)
1027 (register Lisp_Object process)
1029 register struct Lisp_Process *p;
1031 process = get_process (process);
1032 p = XPROCESS (process);
1034 p->raw_status_new = 0;
1035 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1037 pset_status (p, list2 (Qexit, make_number (0)));
1038 p->tick = ++process_tick;
1039 status_notify (p);
1040 redisplay_preserve_echo_area (13);
1042 else
1044 if (p->alive)
1045 record_kill_process (p, Qnil);
1047 if (p->infd >= 0)
1049 /* Update P's status, since record_kill_process will make the
1050 SIGCHLD handler update deleted_pid_list, not *P. */
1051 Lisp_Object symbol;
1052 if (p->raw_status_new)
1053 update_status (p);
1054 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1055 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1056 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1058 p->tick = ++process_tick;
1059 status_notify (p);
1060 redisplay_preserve_echo_area (13);
1063 remove_process (process);
1064 return Qnil;
1067 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1068 doc: /* Return the status of PROCESS.
1069 The returned value is one of the following symbols:
1070 run -- for a process that is running.
1071 stop -- for a process stopped but continuable.
1072 exit -- for a process that has exited.
1073 signal -- for a process that has got a fatal signal.
1074 open -- for a network stream connection that is open.
1075 listen -- for a network stream server that is listening.
1076 closed -- for a network stream connection that is closed.
1077 connect -- when waiting for a non-blocking connection to complete.
1078 failed -- when a non-blocking connection has failed.
1079 nil -- if arg is a process name and no such process exists.
1080 PROCESS may be a process, a buffer, the name of a process, or
1081 nil, indicating the current buffer's process. */)
1082 (register Lisp_Object process)
1084 register struct Lisp_Process *p;
1085 register Lisp_Object status;
1087 if (STRINGP (process))
1088 process = Fget_process (process);
1089 else
1090 process = get_process (process);
1092 if (NILP (process))
1093 return process;
1095 p = XPROCESS (process);
1096 if (p->raw_status_new)
1097 update_status (p);
1098 status = p->status;
1099 if (CONSP (status))
1100 status = XCAR (status);
1101 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1103 if (EQ (status, Qexit))
1104 status = Qclosed;
1105 else if (EQ (p->command, Qt))
1106 status = Qstop;
1107 else if (EQ (status, Qrun))
1108 status = Qopen;
1110 return status;
1113 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1114 1, 1, 0,
1115 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1116 If PROCESS has not yet exited or died, return 0. */)
1117 (register Lisp_Object process)
1119 CHECK_PROCESS (process);
1120 if (XPROCESS (process)->raw_status_new)
1121 update_status (XPROCESS (process));
1122 if (CONSP (XPROCESS (process)->status))
1123 return XCAR (XCDR (XPROCESS (process)->status));
1124 return make_number (0);
1127 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1128 doc: /* Return the process id of PROCESS.
1129 This is the pid of the external process which PROCESS uses or talks to.
1130 For a network connection, this value is nil. */)
1131 (register Lisp_Object process)
1133 pid_t pid;
1135 CHECK_PROCESS (process);
1136 pid = XPROCESS (process)->pid;
1137 return (pid ? make_fixnum_or_float (pid) : Qnil);
1140 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1141 doc: /* Return the name of PROCESS, as a string.
1142 This is the name of the program invoked in PROCESS,
1143 possibly modified to make it unique among process names. */)
1144 (register Lisp_Object process)
1146 CHECK_PROCESS (process);
1147 return XPROCESS (process)->name;
1150 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1151 doc: /* Return the command that was executed to start PROCESS.
1152 This is a list of strings, the first string being the program executed
1153 and the rest of the strings being the arguments given to it.
1154 For a network or serial process, this is nil (process is running) or t
1155 \(process is stopped). */)
1156 (register Lisp_Object process)
1158 CHECK_PROCESS (process);
1159 return XPROCESS (process)->command;
1162 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1163 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1164 This is the terminal that the process itself reads and writes on,
1165 not the name of the pty that Emacs uses to talk with that terminal. */)
1166 (register Lisp_Object process)
1168 CHECK_PROCESS (process);
1169 return XPROCESS (process)->tty_name;
1172 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1173 2, 2, 0,
1174 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1175 Return BUFFER. */)
1176 (register Lisp_Object process, Lisp_Object buffer)
1178 struct Lisp_Process *p;
1180 CHECK_PROCESS (process);
1181 if (!NILP (buffer))
1182 CHECK_BUFFER (buffer);
1183 p = XPROCESS (process);
1184 pset_buffer (p, buffer);
1185 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1186 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1187 setup_process_coding_systems (process);
1188 return buffer;
1191 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1192 1, 1, 0,
1193 doc: /* Return the buffer PROCESS is associated with.
1194 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1195 (register Lisp_Object process)
1197 CHECK_PROCESS (process);
1198 return XPROCESS (process)->buffer;
1201 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1202 1, 1, 0,
1203 doc: /* Return the marker for the end of the last output from PROCESS. */)
1204 (register Lisp_Object process)
1206 CHECK_PROCESS (process);
1207 return XPROCESS (process)->mark;
1210 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1211 2, 2, 0,
1212 doc: /* Give PROCESS the filter function FILTER; nil means default.
1213 A value of t means stop accepting output from the process.
1215 When a process has a non-default filter, its buffer is not used for output.
1216 Instead, each time it does output, the entire string of output is
1217 passed to the filter.
1219 The filter gets two arguments: the process and the string of output.
1220 The string argument is normally a multibyte string, except:
1221 - if the process' input coding system is no-conversion or raw-text,
1222 it is a unibyte string (the non-converted input), or else
1223 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1224 string (the result of converting the decoded input multibyte
1225 string to unibyte with `string-make-unibyte'). */)
1226 (register Lisp_Object process, Lisp_Object filter)
1228 struct Lisp_Process *p;
1230 CHECK_PROCESS (process);
1231 p = XPROCESS (process);
1233 /* Don't signal an error if the process' input file descriptor
1234 is closed. This could make debugging Lisp more difficult,
1235 for example when doing something like
1237 (setq process (start-process ...))
1238 (debug)
1239 (set-process-filter process ...) */
1241 if (NILP (filter))
1242 filter = Qinternal_default_process_filter;
1244 if (p->infd >= 0)
1246 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1247 delete_read_fd (p->infd);
1248 else if (EQ (p->filter, Qt)
1249 /* Network or serial process not stopped: */
1250 && !EQ (p->command, Qt))
1251 delete_read_fd (p->infd);
1254 pset_filter (p, filter);
1255 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1256 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1257 setup_process_coding_systems (process);
1258 return filter;
1261 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1262 1, 1, 0,
1263 doc: /* Return the filter function of PROCESS.
1264 See `set-process-filter' for more info on filter functions. */)
1265 (register Lisp_Object process)
1267 CHECK_PROCESS (process);
1268 return XPROCESS (process)->filter;
1271 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1272 2, 2, 0,
1273 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1274 The sentinel is called as a function when the process changes state.
1275 It gets two arguments: the process, and a string describing the change. */)
1276 (register Lisp_Object process, Lisp_Object sentinel)
1278 struct Lisp_Process *p;
1280 CHECK_PROCESS (process);
1281 p = XPROCESS (process);
1283 if (NILP (sentinel))
1284 sentinel = Qinternal_default_process_sentinel;
1286 pset_sentinel (p, sentinel);
1287 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1288 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1289 return sentinel;
1292 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1293 1, 1, 0,
1294 doc: /* Return the sentinel of PROCESS.
1295 See `set-process-sentinel' for more info on sentinels. */)
1296 (register Lisp_Object process)
1298 CHECK_PROCESS (process);
1299 return XPROCESS (process)->sentinel;
1302 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1303 2, 2, 0,
1304 doc: /* FIXME */)
1305 (Lisp_Object process, Lisp_Object thread)
1307 struct Lisp_Process *proc;
1308 struct thread_state *tstate;
1310 CHECK_PROCESS (process);
1311 if (NILP (thread))
1312 tstate = NULL;
1313 else
1315 CHECK_THREAD (thread);
1316 tstate = XTHREAD (thread);
1319 proc = XPROCESS (process);
1320 proc->thread = thread;
1321 if (proc->infd >= 0)
1322 fd_callback_info[proc->infd].thread = tstate;
1323 if (proc->outfd >= 0)
1324 fd_callback_info[proc->outfd].thread = tstate;
1326 return thread;
1329 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1330 1, 1, 0,
1331 doc: /* FIXME */)
1332 (Lisp_Object process)
1334 CHECK_PROCESS (process);
1335 return XPROCESS (process)->thread;
1338 DEFUN ("set-process-window-size", Fset_process_window_size,
1339 Sset_process_window_size, 3, 3, 0,
1340 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1341 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1343 CHECK_PROCESS (process);
1344 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1345 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1347 if (XPROCESS (process)->infd < 0
1348 || set_window_size (XPROCESS (process)->infd,
1349 XINT (height), XINT (width)) <= 0)
1350 return Qnil;
1351 else
1352 return Qt;
1355 DEFUN ("set-process-inherit-coding-system-flag",
1356 Fset_process_inherit_coding_system_flag,
1357 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1358 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1359 If the second argument FLAG is non-nil, then the variable
1360 `buffer-file-coding-system' of the buffer associated with PROCESS
1361 will be bound to the value of the coding system used to decode
1362 the process output.
1364 This is useful when the coding system specified for the process buffer
1365 leaves either the character code conversion or the end-of-line conversion
1366 unspecified, or if the coding system used to decode the process output
1367 is more appropriate for saving the process buffer.
1369 Binding the variable `inherit-process-coding-system' to non-nil before
1370 starting the process is an alternative way of setting the inherit flag
1371 for the process which will run.
1373 This function returns FLAG. */)
1374 (register Lisp_Object process, Lisp_Object flag)
1376 CHECK_PROCESS (process);
1377 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1378 return flag;
1381 DEFUN ("set-process-query-on-exit-flag",
1382 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1383 2, 2, 0,
1384 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1385 If the second argument FLAG is non-nil, Emacs will query the user before
1386 exiting or killing a buffer if PROCESS is running. This function
1387 returns FLAG. */)
1388 (register Lisp_Object process, Lisp_Object flag)
1390 CHECK_PROCESS (process);
1391 XPROCESS (process)->kill_without_query = NILP (flag);
1392 return flag;
1395 DEFUN ("process-query-on-exit-flag",
1396 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1397 1, 1, 0,
1398 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1399 (register Lisp_Object process)
1401 CHECK_PROCESS (process);
1402 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1405 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1406 1, 2, 0,
1407 doc: /* Return the contact info of PROCESS; t for a real child.
1408 For a network or serial connection, the value depends on the optional
1409 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1410 SERVICE) for a network connection or (PORT SPEED) for a serial
1411 connection. If KEY is t, the complete contact information for the
1412 connection is returned, else the specific value for the keyword KEY is
1413 returned. See `make-network-process' or `make-serial-process' for a
1414 list of keywords. */)
1415 (register Lisp_Object process, Lisp_Object key)
1417 Lisp_Object contact;
1419 CHECK_PROCESS (process);
1420 contact = XPROCESS (process)->childp;
1422 #ifdef DATAGRAM_SOCKETS
1423 if (DATAGRAM_CONN_P (process)
1424 && (EQ (key, Qt) || EQ (key, QCremote)))
1425 contact = Fplist_put (contact, QCremote,
1426 Fprocess_datagram_address (process));
1427 #endif
1429 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1430 return contact;
1431 if (NILP (key) && NETCONN_P (process))
1432 return list2 (Fplist_get (contact, QChost),
1433 Fplist_get (contact, QCservice));
1434 if (NILP (key) && SERIALCONN_P (process))
1435 return list2 (Fplist_get (contact, QCport),
1436 Fplist_get (contact, QCspeed));
1437 return Fplist_get (contact, key);
1440 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1441 1, 1, 0,
1442 doc: /* Return the plist of PROCESS. */)
1443 (register Lisp_Object process)
1445 CHECK_PROCESS (process);
1446 return XPROCESS (process)->plist;
1449 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1450 2, 2, 0,
1451 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1452 (register Lisp_Object process, Lisp_Object plist)
1454 CHECK_PROCESS (process);
1455 CHECK_LIST (plist);
1457 pset_plist (XPROCESS (process), plist);
1458 return plist;
1461 #if 0 /* Turned off because we don't currently record this info
1462 in the process. Perhaps add it. */
1463 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1464 doc: /* Return the connection type of PROCESS.
1465 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1466 a socket connection. */)
1467 (Lisp_Object process)
1469 return XPROCESS (process)->type;
1471 #endif
1473 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1474 doc: /* Return the connection type of PROCESS.
1475 The value is either the symbol `real', `network', or `serial'.
1476 PROCESS may be a process, a buffer, the name of a process or buffer, or
1477 nil, indicating the current buffer's process. */)
1478 (Lisp_Object process)
1480 Lisp_Object proc;
1481 proc = get_process (process);
1482 return XPROCESS (proc)->type;
1485 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1486 1, 2, 0,
1487 doc: /* Convert network ADDRESS from internal format to a string.
1488 A 4 or 5 element vector represents an IPv4 address (with port number).
1489 An 8 or 9 element vector represents an IPv6 address (with port number).
1490 If optional second argument OMIT-PORT is non-nil, don't include a port
1491 number in the string, even when present in ADDRESS.
1492 Returns nil if format of ADDRESS is invalid. */)
1493 (Lisp_Object address, Lisp_Object omit_port)
1495 if (NILP (address))
1496 return Qnil;
1498 if (STRINGP (address)) /* AF_LOCAL */
1499 return address;
1501 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1503 register struct Lisp_Vector *p = XVECTOR (address);
1504 ptrdiff_t size = p->header.size;
1505 Lisp_Object args[10];
1506 int nargs, i;
1508 if (size == 4 || (size == 5 && !NILP (omit_port)))
1510 args[0] = build_string ("%d.%d.%d.%d");
1511 nargs = 4;
1513 else if (size == 5)
1515 args[0] = build_string ("%d.%d.%d.%d:%d");
1516 nargs = 5;
1518 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1520 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1521 nargs = 8;
1523 else if (size == 9)
1525 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1526 nargs = 9;
1528 else
1529 return Qnil;
1531 for (i = 0; i < nargs; i++)
1533 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1534 return Qnil;
1536 if (nargs <= 5 /* IPv4 */
1537 && i < 4 /* host, not port */
1538 && XINT (p->contents[i]) > 255)
1539 return Qnil;
1541 args[i+1] = p->contents[i];
1544 return Fformat (nargs+1, args);
1547 if (CONSP (address))
1549 Lisp_Object args[2];
1550 args[0] = build_string ("<Family %d>");
1551 args[1] = Fcar (address);
1552 return Fformat (2, args);
1555 return Qnil;
1558 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1559 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1560 (void)
1562 return Fmapcar (Qcdr, Vprocess_alist);
1565 /* Starting asynchronous inferior processes. */
1567 static void start_process_unwind (Lisp_Object proc);
1569 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1570 doc: /* Start a program in a subprocess. Return the process object for it.
1571 NAME is name for process. It is modified if necessary to make it unique.
1572 BUFFER is the buffer (or buffer name) to associate with the process.
1574 Process output (both standard output and standard error streams) goes
1575 at end of BUFFER, unless you specify an output stream or filter
1576 function to handle the output. BUFFER may also be nil, meaning that
1577 this process is not associated with any buffer.
1579 PROGRAM is the program file name. It is searched for in `exec-path'
1580 (which see). If nil, just associate a pty with the buffer. Remaining
1581 arguments are strings to give program as arguments.
1583 If you want to separate standard output from standard error, invoke
1584 the command through a shell and redirect one of them using the shell
1585 syntax.
1587 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1588 (ptrdiff_t nargs, Lisp_Object *args)
1590 Lisp_Object buffer, name, program, proc, current_dir, tem;
1591 register unsigned char **new_argv;
1592 ptrdiff_t i;
1593 ptrdiff_t count = SPECPDL_INDEX ();
1595 buffer = args[1];
1596 if (!NILP (buffer))
1597 buffer = Fget_buffer_create (buffer);
1599 /* Make sure that the child will be able to chdir to the current
1600 buffer's current directory, or its unhandled equivalent. We
1601 can't just have the child check for an error when it does the
1602 chdir, since it's in a vfork.
1604 We have to GCPRO around this because Fexpand_file_name and
1605 Funhandled_file_name_directory might call a file name handling
1606 function. The argument list is protected by the caller, so all
1607 we really have to worry about is buffer. */
1609 struct gcpro gcpro1, gcpro2;
1611 current_dir = BVAR (current_buffer, directory);
1613 GCPRO2 (buffer, current_dir);
1615 current_dir = Funhandled_file_name_directory (current_dir);
1616 if (NILP (current_dir))
1617 /* If the file name handler says that current_dir is unreachable, use
1618 a sensible default. */
1619 current_dir = build_string ("~/");
1620 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1621 if (NILP (Ffile_accessible_directory_p (current_dir)))
1622 report_file_error ("Setting current directory",
1623 BVAR (current_buffer, directory));
1625 UNGCPRO;
1628 name = args[0];
1629 CHECK_STRING (name);
1631 program = args[2];
1633 if (!NILP (program))
1634 CHECK_STRING (program);
1636 proc = make_process (name);
1637 /* If an error occurs and we can't start the process, we want to
1638 remove it from the process list. This means that each error
1639 check in create_process doesn't need to call remove_process
1640 itself; it's all taken care of here. */
1641 record_unwind_protect (start_process_unwind, proc);
1643 pset_childp (XPROCESS (proc), Qt);
1644 pset_plist (XPROCESS (proc), Qnil);
1645 pset_type (XPROCESS (proc), Qreal);
1646 pset_buffer (XPROCESS (proc), buffer);
1647 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1648 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1649 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1651 #ifdef HAVE_GNUTLS
1652 /* AKA GNUTLS_INITSTAGE(proc). */
1653 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1654 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1655 #endif
1657 #ifdef ADAPTIVE_READ_BUFFERING
1658 XPROCESS (proc)->adaptive_read_buffering
1659 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1660 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1661 #endif
1663 /* Make the process marker point into the process buffer (if any). */
1664 if (BUFFERP (buffer))
1665 set_marker_both (XPROCESS (proc)->mark, buffer,
1666 BUF_ZV (XBUFFER (buffer)),
1667 BUF_ZV_BYTE (XBUFFER (buffer)));
1670 /* Decide coding systems for communicating with the process. Here
1671 we don't setup the structure coding_system nor pay attention to
1672 unibyte mode. They are done in create_process. */
1674 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1675 Lisp_Object coding_systems = Qt;
1676 Lisp_Object val, *args2;
1677 struct gcpro gcpro1, gcpro2;
1679 val = Vcoding_system_for_read;
1680 if (NILP (val))
1682 args2 = alloca ((nargs + 1) * sizeof *args2);
1683 args2[0] = Qstart_process;
1684 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1685 GCPRO2 (proc, current_dir);
1686 if (!NILP (program))
1687 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1688 UNGCPRO;
1689 if (CONSP (coding_systems))
1690 val = XCAR (coding_systems);
1691 else if (CONSP (Vdefault_process_coding_system))
1692 val = XCAR (Vdefault_process_coding_system);
1694 pset_decode_coding_system (XPROCESS (proc), val);
1696 val = Vcoding_system_for_write;
1697 if (NILP (val))
1699 if (EQ (coding_systems, Qt))
1701 args2 = alloca ((nargs + 1) * sizeof *args2);
1702 args2[0] = Qstart_process;
1703 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1704 GCPRO2 (proc, current_dir);
1705 if (!NILP (program))
1706 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1707 UNGCPRO;
1709 if (CONSP (coding_systems))
1710 val = XCDR (coding_systems);
1711 else if (CONSP (Vdefault_process_coding_system))
1712 val = XCDR (Vdefault_process_coding_system);
1714 pset_encode_coding_system (XPROCESS (proc), val);
1715 /* Note: At this moment, the above coding system may leave
1716 text-conversion or eol-conversion unspecified. They will be
1717 decided after we read output from the process and decode it by
1718 some coding system, or just before we actually send a text to
1719 the process. */
1723 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1724 XPROCESS (proc)->decoding_carryover = 0;
1725 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1727 XPROCESS (proc)->inherit_coding_system_flag
1728 = !(NILP (buffer) || !inherit_process_coding_system);
1730 if (!NILP (program))
1732 /* If program file name is not absolute, search our path for it.
1733 Put the name we will really use in TEM. */
1734 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1735 && !(SCHARS (program) > 1
1736 && IS_DEVICE_SEP (SREF (program, 1))))
1738 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1740 tem = Qnil;
1741 GCPRO4 (name, program, buffer, current_dir);
1742 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1743 UNGCPRO;
1744 if (NILP (tem))
1745 report_file_error ("Searching for program", program);
1746 tem = Fexpand_file_name (tem, Qnil);
1748 else
1750 if (!NILP (Ffile_directory_p (program)))
1751 error ("Specified program for new process is a directory");
1752 tem = program;
1755 /* If program file name starts with /: for quoting a magic name,
1756 discard that. */
1757 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1758 && SREF (tem, 1) == ':')
1759 tem = Fsubstring (tem, make_number (2), Qnil);
1762 Lisp_Object arg_encoding = Qnil;
1763 struct gcpro gcpro1;
1764 GCPRO1 (tem);
1766 /* Encode the file name and put it in NEW_ARGV.
1767 That's where the child will use it to execute the program. */
1768 tem = list1 (ENCODE_FILE (tem));
1770 /* Here we encode arguments by the coding system used for sending
1771 data to the process. We don't support using different coding
1772 systems for encoding arguments and for encoding data sent to the
1773 process. */
1775 for (i = 3; i < nargs; i++)
1777 tem = Fcons (args[i], tem);
1778 CHECK_STRING (XCAR (tem));
1779 if (STRING_MULTIBYTE (XCAR (tem)))
1781 if (NILP (arg_encoding))
1782 arg_encoding = (complement_process_encoding_system
1783 (XPROCESS (proc)->encode_coding_system));
1784 XSETCAR (tem,
1785 code_convert_string_norecord
1786 (XCAR (tem), arg_encoding, 1));
1790 UNGCPRO;
1793 /* Now that everything is encoded we can collect the strings into
1794 NEW_ARGV. */
1795 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1796 new_argv[nargs - 2] = 0;
1798 for (i = nargs - 2; i-- != 0; )
1800 new_argv[i] = SDATA (XCAR (tem));
1801 tem = XCDR (tem);
1804 create_process (proc, (char **) new_argv, current_dir);
1806 else
1807 create_pty (proc);
1809 return unbind_to (count, proc);
1812 /* This function is the unwind_protect form for Fstart_process. If
1813 PROC doesn't have its pid set, then we know someone has signaled
1814 an error and the process wasn't started successfully, so we should
1815 remove it from the process list. */
1816 static void
1817 start_process_unwind (Lisp_Object proc)
1819 if (!PROCESSP (proc))
1820 emacs_abort ();
1822 /* Was PROC started successfully?
1823 -2 is used for a pty with no process, eg for gdb. */
1824 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1825 remove_process (proc);
1828 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1830 static void
1831 close_process_fd (int *fd_addr)
1833 int fd = *fd_addr;
1834 if (0 <= fd)
1836 *fd_addr = -1;
1837 emacs_close (fd);
1841 /* Indexes of file descriptors in open_fds. */
1842 enum
1844 /* The pipe from Emacs to its subprocess. */
1845 SUBPROCESS_STDIN,
1846 WRITE_TO_SUBPROCESS,
1848 /* The main pipe from the subprocess to Emacs. */
1849 READ_FROM_SUBPROCESS,
1850 SUBPROCESS_STDOUT,
1852 /* The pipe from the subprocess to Emacs that is closed when the
1853 subprocess execs. */
1854 READ_FROM_EXEC_MONITOR,
1855 EXEC_MONITOR_OUTPUT
1858 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1860 static void
1861 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1863 struct Lisp_Process *p = XPROCESS (process);
1864 int inchannel, outchannel;
1865 pid_t pid;
1866 int vfork_errno;
1867 int forkin, forkout;
1868 bool pty_flag = 0;
1869 char pty_name[PTY_NAME_SIZE];
1870 Lisp_Object lisp_pty_name = Qnil;
1871 Lisp_Object encoded_current_dir;
1873 inchannel = outchannel = -1;
1875 if (!NILP (Vprocess_connection_type))
1876 outchannel = inchannel = allocate_pty (pty_name);
1878 if (inchannel >= 0)
1880 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1881 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1882 /* On most USG systems it does not work to open the pty's tty here,
1883 then close it and reopen it in the child. */
1884 /* Don't let this terminal become our controlling terminal
1885 (in case we don't have one). */
1886 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1887 if (forkin < 0)
1888 report_file_error ("Opening pty", Qnil);
1889 p->open_fd[SUBPROCESS_STDIN] = forkin;
1890 #else
1891 forkin = forkout = -1;
1892 #endif /* not USG, or USG_SUBTTY_WORKS */
1893 pty_flag = 1;
1894 lisp_pty_name = build_string (pty_name);
1896 else
1898 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1899 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1900 report_file_error ("Creating pipe", Qnil);
1901 forkin = p->open_fd[SUBPROCESS_STDIN];
1902 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1903 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1904 forkout = p->open_fd[SUBPROCESS_STDOUT];
1907 #ifndef WINDOWSNT
1908 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1909 report_file_error ("Creating pipe", Qnil);
1910 #endif
1912 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1913 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1915 /* Record this as an active process, with its channels. */
1916 chan_process[inchannel] = process;
1917 p->infd = inchannel;
1918 p->outfd = outchannel;
1920 /* Previously we recorded the tty descriptor used in the subprocess.
1921 It was only used for getting the foreground tty process, so now
1922 we just reopen the device (see emacs_get_tty_pgrp) as this is
1923 more portable (see USG_SUBTTY_WORKS above). */
1925 p->pty_flag = pty_flag;
1926 pset_status (p, Qrun);
1928 add_process_read_fd (inchannel);
1930 /* This may signal an error. */
1931 setup_process_coding_systems (process);
1933 encoded_current_dir = ENCODE_FILE (current_dir);
1935 block_input ();
1936 block_child_signal ();
1938 #ifndef WINDOWSNT
1939 /* vfork, and prevent local vars from being clobbered by the vfork. */
1941 Lisp_Object volatile encoded_current_dir_volatile = encoded_current_dir;
1942 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1943 char **volatile new_argv_volatile = new_argv;
1944 int volatile forkin_volatile = forkin;
1945 int volatile forkout_volatile = forkout;
1946 struct Lisp_Process *p_volatile = p;
1948 pid = vfork ();
1950 encoded_current_dir = encoded_current_dir_volatile;
1951 lisp_pty_name = lisp_pty_name_volatile;
1952 new_argv = new_argv_volatile;
1953 forkin = forkin_volatile;
1954 forkout = forkout_volatile;
1955 p = p_volatile;
1957 pty_flag = p->pty_flag;
1960 if (pid == 0)
1961 #endif /* not WINDOWSNT */
1963 int xforkin = forkin;
1964 int xforkout = forkout;
1966 /* Make the pty be the controlling terminal of the process. */
1967 #ifdef HAVE_PTYS
1968 /* First, disconnect its current controlling terminal. */
1969 /* We tried doing setsid only if pty_flag, but it caused
1970 process_set_signal to fail on SGI when using a pipe. */
1971 setsid ();
1972 /* Make the pty's terminal the controlling terminal. */
1973 if (pty_flag && xforkin >= 0)
1975 #ifdef TIOCSCTTY
1976 /* We ignore the return value
1977 because faith@cs.unc.edu says that is necessary on Linux. */
1978 ioctl (xforkin, TIOCSCTTY, 0);
1979 #endif
1981 #if defined (LDISC1)
1982 if (pty_flag && xforkin >= 0)
1984 struct termios t;
1985 tcgetattr (xforkin, &t);
1986 t.c_lflag = LDISC1;
1987 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1988 emacs_perror ("create_process/tcsetattr LDISC1");
1990 #else
1991 #if defined (NTTYDISC) && defined (TIOCSETD)
1992 if (pty_flag && xforkin >= 0)
1994 /* Use new line discipline. */
1995 int ldisc = NTTYDISC;
1996 ioctl (xforkin, TIOCSETD, &ldisc);
1998 #endif
1999 #endif
2000 #ifdef TIOCNOTTY
2001 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2002 can do TIOCSPGRP only to the process's controlling tty. */
2003 if (pty_flag)
2005 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2006 I can't test it since I don't have 4.3. */
2007 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2008 if (j >= 0)
2010 ioctl (j, TIOCNOTTY, 0);
2011 emacs_close (j);
2014 #endif /* TIOCNOTTY */
2016 #if !defined (DONT_REOPEN_PTY)
2017 /*** There is a suggestion that this ought to be a
2018 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2019 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2020 that system does seem to need this code, even though
2021 both TIOCSCTTY is defined. */
2022 /* Now close the pty (if we had it open) and reopen it.
2023 This makes the pty the controlling terminal of the subprocess. */
2024 if (pty_flag)
2027 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2028 would work? */
2029 if (xforkin >= 0)
2030 emacs_close (xforkin);
2031 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2033 if (xforkin < 0)
2035 emacs_perror (SSDATA (lisp_pty_name));
2036 _exit (EXIT_CANCELED);
2040 #endif /* not DONT_REOPEN_PTY */
2042 #ifdef SETUP_SLAVE_PTY
2043 if (pty_flag)
2045 SETUP_SLAVE_PTY;
2047 #endif /* SETUP_SLAVE_PTY */
2048 #endif /* HAVE_PTYS */
2050 signal (SIGINT, SIG_DFL);
2051 signal (SIGQUIT, SIG_DFL);
2053 /* Emacs ignores SIGPIPE, but the child should not. */
2054 signal (SIGPIPE, SIG_DFL);
2056 /* Stop blocking SIGCHLD in the child. */
2057 unblock_child_signal ();
2059 if (pty_flag)
2060 child_setup_tty (xforkout);
2061 #ifdef WINDOWSNT
2062 pid = child_setup (xforkin, xforkout, xforkout,
2063 new_argv, 1, encoded_current_dir);
2064 #else /* not WINDOWSNT */
2065 child_setup (xforkin, xforkout, xforkout,
2066 new_argv, 1, encoded_current_dir);
2067 #endif /* not WINDOWSNT */
2070 /* Back in the parent process. */
2072 vfork_errno = errno;
2073 p->pid = pid;
2074 if (pid >= 0)
2075 p->alive = 1;
2077 /* Stop blocking in the parent. */
2078 unblock_child_signal ();
2079 unblock_input ();
2081 if (pid < 0)
2082 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2083 else
2085 /* vfork succeeded. */
2087 /* Close the pipe ends that the child uses, or the child's pty. */
2088 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2089 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2091 #ifdef WINDOWSNT
2092 register_child (pid, inchannel);
2093 #endif /* WINDOWSNT */
2095 pset_tty_name (p, lisp_pty_name);
2097 #ifndef WINDOWSNT
2098 /* Wait for child_setup to complete in case that vfork is
2099 actually defined as fork. The descriptor
2100 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2101 of a pipe is closed at the child side either by close-on-exec
2102 on successful execve or the _exit call in child_setup. */
2104 char dummy;
2106 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2107 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2108 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2110 #endif
2114 static void
2115 create_pty (Lisp_Object process)
2117 struct Lisp_Process *p = XPROCESS (process);
2118 char pty_name[PTY_NAME_SIZE];
2119 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
2121 if (pty_fd >= 0)
2123 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2124 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2125 /* On most USG systems it does not work to open the pty's tty here,
2126 then close it and reopen it in the child. */
2127 /* Don't let this terminal become our controlling terminal
2128 (in case we don't have one). */
2129 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2130 if (forkout < 0)
2131 report_file_error ("Opening pty", Qnil);
2132 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2133 #if defined (DONT_REOPEN_PTY)
2134 /* In the case that vfork is defined as fork, the parent process
2135 (Emacs) may send some data before the child process completes
2136 tty options setup. So we setup tty before forking. */
2137 child_setup_tty (forkout);
2138 #endif /* DONT_REOPEN_PTY */
2139 #endif /* not USG, or USG_SUBTTY_WORKS */
2141 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2143 /* Record this as an active process, with its channels.
2144 As a result, child_setup will close Emacs's side of the pipes. */
2145 chan_process[pty_fd] = process;
2146 p->infd = pty_fd;
2147 p->outfd = pty_fd;
2149 /* Previously we recorded the tty descriptor used in the subprocess.
2150 It was only used for getting the foreground tty process, so now
2151 we just reopen the device (see emacs_get_tty_pgrp) as this is
2152 more portable (see USG_SUBTTY_WORKS above). */
2154 p->pty_flag = 1;
2155 pset_status (p, Qrun);
2156 setup_process_coding_systems (process);
2158 fixme;
2160 pset_tty_name (p, build_string (pty_name));
2163 p->pid = -2;
2167 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2168 The address family of sa is not included in the result. */
2170 static Lisp_Object
2171 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2173 Lisp_Object address;
2174 int i;
2175 unsigned char *cp;
2176 register struct Lisp_Vector *p;
2178 /* Workaround for a bug in getsockname on BSD: Names bound to
2179 sockets in the UNIX domain are inaccessible; getsockname returns
2180 a zero length name. */
2181 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2182 return empty_unibyte_string;
2184 switch (sa->sa_family)
2186 case AF_INET:
2188 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2189 len = sizeof (sin->sin_addr) + 1;
2190 address = Fmake_vector (make_number (len), Qnil);
2191 p = XVECTOR (address);
2192 p->contents[--len] = make_number (ntohs (sin->sin_port));
2193 cp = (unsigned char *) &sin->sin_addr;
2194 break;
2196 #ifdef AF_INET6
2197 case AF_INET6:
2199 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2200 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2201 len = sizeof (sin6->sin6_addr)/2 + 1;
2202 address = Fmake_vector (make_number (len), Qnil);
2203 p = XVECTOR (address);
2204 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2205 for (i = 0; i < len; i++)
2206 p->contents[i] = make_number (ntohs (ip6[i]));
2207 return address;
2209 #endif
2210 #ifdef HAVE_LOCAL_SOCKETS
2211 case AF_LOCAL:
2213 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2214 for (i = 0; i < sizeof (sockun->sun_path); i++)
2215 if (sockun->sun_path[i] == 0)
2216 break;
2217 return make_unibyte_string (sockun->sun_path, i);
2219 #endif
2220 default:
2221 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2222 address = Fcons (make_number (sa->sa_family),
2223 Fmake_vector (make_number (len), Qnil));
2224 p = XVECTOR (XCDR (address));
2225 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2226 break;
2229 i = 0;
2230 while (i < len)
2231 p->contents[i++] = make_number (*cp++);
2233 return address;
2237 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2239 static int
2240 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2242 register struct Lisp_Vector *p;
2244 if (VECTORP (address))
2246 p = XVECTOR (address);
2247 if (p->header.size == 5)
2249 *familyp = AF_INET;
2250 return sizeof (struct sockaddr_in);
2252 #ifdef AF_INET6
2253 else if (p->header.size == 9)
2255 *familyp = AF_INET6;
2256 return sizeof (struct sockaddr_in6);
2258 #endif
2260 #ifdef HAVE_LOCAL_SOCKETS
2261 else if (STRINGP (address))
2263 *familyp = AF_LOCAL;
2264 return sizeof (struct sockaddr_un);
2266 #endif
2267 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2268 && VECTORP (XCDR (address)))
2270 struct sockaddr *sa;
2271 *familyp = XINT (XCAR (address));
2272 p = XVECTOR (XCDR (address));
2273 return p->header.size + sizeof (sa->sa_family);
2275 return 0;
2278 /* Convert an address object (vector or string) to an internal sockaddr.
2280 The address format has been basically validated by
2281 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2282 it could have come from user data. So if FAMILY is not valid,
2283 we return after zeroing *SA. */
2285 static void
2286 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2288 register struct Lisp_Vector *p;
2289 register unsigned char *cp = NULL;
2290 register int i;
2291 EMACS_INT hostport;
2293 memset (sa, 0, len);
2295 if (VECTORP (address))
2297 p = XVECTOR (address);
2298 if (family == AF_INET)
2300 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2301 len = sizeof (sin->sin_addr) + 1;
2302 hostport = XINT (p->contents[--len]);
2303 sin->sin_port = htons (hostport);
2304 cp = (unsigned char *)&sin->sin_addr;
2305 sa->sa_family = family;
2307 #ifdef AF_INET6
2308 else if (family == AF_INET6)
2310 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2311 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2312 len = sizeof (sin6->sin6_addr) + 1;
2313 hostport = XINT (p->contents[--len]);
2314 sin6->sin6_port = htons (hostport);
2315 for (i = 0; i < len; i++)
2316 if (INTEGERP (p->contents[i]))
2318 int j = XFASTINT (p->contents[i]) & 0xffff;
2319 ip6[i] = ntohs (j);
2321 sa->sa_family = family;
2322 return;
2324 #endif
2325 else
2326 return;
2328 else if (STRINGP (address))
2330 #ifdef HAVE_LOCAL_SOCKETS
2331 if (family == AF_LOCAL)
2333 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2334 cp = SDATA (address);
2335 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2336 sockun->sun_path[i] = *cp++;
2337 sa->sa_family = family;
2339 #endif
2340 return;
2342 else
2344 p = XVECTOR (XCDR (address));
2345 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2348 for (i = 0; i < len; i++)
2349 if (INTEGERP (p->contents[i]))
2350 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2353 #ifdef DATAGRAM_SOCKETS
2354 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2355 1, 1, 0,
2356 doc: /* Get the current datagram address associated with PROCESS. */)
2357 (Lisp_Object process)
2359 int channel;
2361 CHECK_PROCESS (process);
2363 if (!DATAGRAM_CONN_P (process))
2364 return Qnil;
2366 channel = XPROCESS (process)->infd;
2367 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2368 datagram_address[channel].len);
2371 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2372 2, 2, 0,
2373 doc: /* Set the datagram address for PROCESS to ADDRESS.
2374 Returns nil upon error setting address, ADDRESS otherwise. */)
2375 (Lisp_Object process, Lisp_Object address)
2377 int channel;
2378 int family, len;
2380 CHECK_PROCESS (process);
2382 if (!DATAGRAM_CONN_P (process))
2383 return Qnil;
2385 channel = XPROCESS (process)->infd;
2387 len = get_lisp_to_sockaddr_size (address, &family);
2388 if (len == 0 || datagram_address[channel].len != len)
2389 return Qnil;
2390 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2391 return address;
2393 #endif
2396 static const struct socket_options {
2397 /* The name of this option. Should be lowercase version of option
2398 name without SO_ prefix. */
2399 const char *name;
2400 /* Option level SOL_... */
2401 int optlevel;
2402 /* Option number SO_... */
2403 int optnum;
2404 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2405 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2406 } socket_options[] =
2408 #ifdef SO_BINDTODEVICE
2409 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2410 #endif
2411 #ifdef SO_BROADCAST
2412 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2413 #endif
2414 #ifdef SO_DONTROUTE
2415 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2416 #endif
2417 #ifdef SO_KEEPALIVE
2418 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2419 #endif
2420 #ifdef SO_LINGER
2421 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2422 #endif
2423 #ifdef SO_OOBINLINE
2424 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2425 #endif
2426 #ifdef SO_PRIORITY
2427 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2428 #endif
2429 #ifdef SO_REUSEADDR
2430 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2431 #endif
2432 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2435 /* Set option OPT to value VAL on socket S.
2437 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2438 Signals an error if setting a known option fails.
2441 static int
2442 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2444 char *name;
2445 const struct socket_options *sopt;
2446 int ret = 0;
2448 CHECK_SYMBOL (opt);
2450 name = SSDATA (SYMBOL_NAME (opt));
2451 for (sopt = socket_options; sopt->name; sopt++)
2452 if (strcmp (name, sopt->name) == 0)
2453 break;
2455 switch (sopt->opttype)
2457 case SOPT_BOOL:
2459 int optval;
2460 optval = NILP (val) ? 0 : 1;
2461 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2462 &optval, sizeof (optval));
2463 break;
2466 case SOPT_INT:
2468 int optval;
2469 if (TYPE_RANGED_INTEGERP (int, val))
2470 optval = XINT (val);
2471 else
2472 error ("Bad option value for %s", name);
2473 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2474 &optval, sizeof (optval));
2475 break;
2478 #ifdef SO_BINDTODEVICE
2479 case SOPT_IFNAME:
2481 char devname[IFNAMSIZ+1];
2483 /* This is broken, at least in the Linux 2.4 kernel.
2484 To unbind, the arg must be a zero integer, not the empty string.
2485 This should work on all systems. KFS. 2003-09-23. */
2486 memset (devname, 0, sizeof devname);
2487 if (STRINGP (val))
2489 char *arg = SSDATA (val);
2490 int len = min (strlen (arg), IFNAMSIZ);
2491 memcpy (devname, arg, len);
2493 else if (!NILP (val))
2494 error ("Bad option value for %s", name);
2495 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2496 devname, IFNAMSIZ);
2497 break;
2499 #endif
2501 #ifdef SO_LINGER
2502 case SOPT_LINGER:
2504 struct linger linger;
2506 linger.l_onoff = 1;
2507 linger.l_linger = 0;
2508 if (TYPE_RANGED_INTEGERP (int, val))
2509 linger.l_linger = XINT (val);
2510 else
2511 linger.l_onoff = NILP (val) ? 0 : 1;
2512 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2513 &linger, sizeof (linger));
2514 break;
2516 #endif
2518 default:
2519 return 0;
2522 if (ret < 0)
2524 int setsockopt_errno = errno;
2525 report_file_errno ("Cannot set network option", list2 (opt, val),
2526 setsockopt_errno);
2529 return (1 << sopt->optbit);
2533 DEFUN ("set-network-process-option",
2534 Fset_network_process_option, Sset_network_process_option,
2535 3, 4, 0,
2536 doc: /* For network process PROCESS set option OPTION to value VALUE.
2537 See `make-network-process' for a list of options and values.
2538 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2539 OPTION is not a supported option, return nil instead; otherwise return t. */)
2540 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2542 int s;
2543 struct Lisp_Process *p;
2545 CHECK_PROCESS (process);
2546 p = XPROCESS (process);
2547 if (!NETCONN1_P (p))
2548 error ("Process is not a network process");
2550 s = p->infd;
2551 if (s < 0)
2552 error ("Process is not running");
2554 if (set_socket_option (s, option, value))
2556 pset_childp (p, Fplist_put (p->childp, option, value));
2557 return Qt;
2560 if (NILP (no_error))
2561 error ("Unknown or unsupported option");
2563 return Qnil;
2567 DEFUN ("serial-process-configure",
2568 Fserial_process_configure,
2569 Sserial_process_configure,
2570 0, MANY, 0,
2571 doc: /* Configure speed, bytesize, etc. of a serial process.
2573 Arguments are specified as keyword/argument pairs. Attributes that
2574 are not given are re-initialized from the process's current
2575 configuration (available via the function `process-contact') or set to
2576 reasonable default values. The following arguments are defined:
2578 :process PROCESS
2579 :name NAME
2580 :buffer BUFFER
2581 :port PORT
2582 -- Any of these arguments can be given to identify the process that is
2583 to be configured. If none of these arguments is given, the current
2584 buffer's process is used.
2586 :speed SPEED -- SPEED is the speed of the serial port in bits per
2587 second, also called baud rate. Any value can be given for SPEED, but
2588 most serial ports work only at a few defined values between 1200 and
2589 115200, with 9600 being the most common value. If SPEED is nil, the
2590 serial port is not configured any further, i.e., all other arguments
2591 are ignored. This may be useful for special serial ports such as
2592 Bluetooth-to-serial converters which can only be configured through AT
2593 commands. A value of nil for SPEED can be used only when passed
2594 through `make-serial-process' or `serial-term'.
2596 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2597 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2599 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2600 `odd' (use odd parity), or the symbol `even' (use even parity). If
2601 PARITY is not given, no parity is used.
2603 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2604 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2605 is not given or nil, 1 stopbit is used.
2607 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2608 flowcontrol to be used, which is either nil (don't use flowcontrol),
2609 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2610 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2611 flowcontrol is used.
2613 `serial-process-configure' is called by `make-serial-process' for the
2614 initial configuration of the serial port.
2616 Examples:
2618 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2620 \(serial-process-configure
2621 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2623 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2625 usage: (serial-process-configure &rest ARGS) */)
2626 (ptrdiff_t nargs, Lisp_Object *args)
2628 struct Lisp_Process *p;
2629 Lisp_Object contact = Qnil;
2630 Lisp_Object proc = Qnil;
2631 struct gcpro gcpro1;
2633 contact = Flist (nargs, args);
2634 GCPRO1 (contact);
2636 proc = Fplist_get (contact, QCprocess);
2637 if (NILP (proc))
2638 proc = Fplist_get (contact, QCname);
2639 if (NILP (proc))
2640 proc = Fplist_get (contact, QCbuffer);
2641 if (NILP (proc))
2642 proc = Fplist_get (contact, QCport);
2643 proc = get_process (proc);
2644 p = XPROCESS (proc);
2645 if (!EQ (p->type, Qserial))
2646 error ("Not a serial process");
2648 if (NILP (Fplist_get (p->childp, QCspeed)))
2650 UNGCPRO;
2651 return Qnil;
2654 serial_configure (p, contact);
2656 UNGCPRO;
2657 return Qnil;
2660 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2661 0, MANY, 0,
2662 doc: /* Create and return a serial port process.
2664 In Emacs, serial port connections are represented by process objects,
2665 so input and output work as for subprocesses, and `delete-process'
2666 closes a serial port connection. However, a serial process has no
2667 process id, it cannot be signaled, and the status codes are different
2668 from normal processes.
2670 `make-serial-process' creates a process and a buffer, on which you
2671 probably want to use `process-send-string'. Try \\[serial-term] for
2672 an interactive terminal. See below for examples.
2674 Arguments are specified as keyword/argument pairs. The following
2675 arguments are defined:
2677 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2678 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2679 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2680 the backslashes in strings).
2682 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2683 which this function calls.
2685 :name NAME -- NAME is the name of the process. If NAME is not given,
2686 the value of PORT is used.
2688 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2689 with the process. Process output goes at the end of that buffer,
2690 unless you specify an output stream or filter function to handle the
2691 output. If BUFFER is not given, the value of NAME is used.
2693 :coding CODING -- If CODING is a symbol, it specifies the coding
2694 system used for both reading and writing for this process. If CODING
2695 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2696 ENCODING is used for writing.
2698 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2699 the process is running. If BOOL is not given, query before exiting.
2701 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2702 In the stopped state, a serial process does not accept incoming data,
2703 but you can send outgoing data. The stopped state is cleared by
2704 `continue-process' and set by `stop-process'.
2706 :filter FILTER -- Install FILTER as the process filter.
2708 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2710 :plist PLIST -- Install PLIST as the initial plist of the process.
2712 :bytesize
2713 :parity
2714 :stopbits
2715 :flowcontrol
2716 -- This function calls `serial-process-configure' to handle these
2717 arguments.
2719 The original argument list, possibly modified by later configuration,
2720 is available via the function `process-contact'.
2722 Examples:
2724 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2726 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2728 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2730 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2732 usage: (make-serial-process &rest ARGS) */)
2733 (ptrdiff_t nargs, Lisp_Object *args)
2735 int fd = -1;
2736 Lisp_Object proc, contact, port;
2737 struct Lisp_Process *p;
2738 struct gcpro gcpro1;
2739 Lisp_Object name, buffer;
2740 Lisp_Object tem, val;
2741 ptrdiff_t specpdl_count;
2743 if (nargs == 0)
2744 return Qnil;
2746 contact = Flist (nargs, args);
2747 GCPRO1 (contact);
2749 port = Fplist_get (contact, QCport);
2750 if (NILP (port))
2751 error ("No port specified");
2752 CHECK_STRING (port);
2754 if (NILP (Fplist_member (contact, QCspeed)))
2755 error (":speed not specified");
2756 if (!NILP (Fplist_get (contact, QCspeed)))
2757 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2759 name = Fplist_get (contact, QCname);
2760 if (NILP (name))
2761 name = port;
2762 CHECK_STRING (name);
2763 proc = make_process (name);
2764 specpdl_count = SPECPDL_INDEX ();
2765 record_unwind_protect (remove_process, proc);
2766 p = XPROCESS (proc);
2768 fd = serial_open (port);
2769 p->open_fd[SUBPROCESS_STDIN] = fd;
2770 p->infd = fd;
2771 p->outfd = fd;
2772 if (fd > max_desc)
2773 max_desc = fd;
2774 chan_process[fd] = proc;
2776 buffer = Fplist_get (contact, QCbuffer);
2777 if (NILP (buffer))
2778 buffer = name;
2779 buffer = Fget_buffer_create (buffer);
2780 pset_buffer (p, buffer);
2782 pset_childp (p, contact);
2783 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2784 pset_type (p, Qserial);
2785 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2786 pset_filter (p, Fplist_get (contact, QCfilter));
2787 pset_log (p, Qnil);
2788 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2789 p->kill_without_query = 1;
2790 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2791 pset_command (p, Qt);
2792 eassert (! p->pty_flag);
2794 if (!EQ (p->command, Qt))
2795 add_non_keyboard_read_fd (fd);
2797 if (BUFFERP (buffer))
2799 set_marker_both (p->mark, buffer,
2800 BUF_ZV (XBUFFER (buffer)),
2801 BUF_ZV_BYTE (XBUFFER (buffer)));
2804 tem = Fplist_member (contact, QCcoding);
2805 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2806 tem = Qnil;
2808 val = Qnil;
2809 if (!NILP (tem))
2811 val = XCAR (XCDR (tem));
2812 if (CONSP (val))
2813 val = XCAR (val);
2815 else if (!NILP (Vcoding_system_for_read))
2816 val = Vcoding_system_for_read;
2817 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2818 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2819 val = Qnil;
2820 pset_decode_coding_system (p, val);
2822 val = Qnil;
2823 if (!NILP (tem))
2825 val = XCAR (XCDR (tem));
2826 if (CONSP (val))
2827 val = XCDR (val);
2829 else if (!NILP (Vcoding_system_for_write))
2830 val = Vcoding_system_for_write;
2831 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2832 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2833 val = Qnil;
2834 pset_encode_coding_system (p, val);
2836 setup_process_coding_systems (proc);
2837 pset_decoding_buf (p, empty_unibyte_string);
2838 p->decoding_carryover = 0;
2839 pset_encoding_buf (p, empty_unibyte_string);
2840 p->inherit_coding_system_flag
2841 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2843 Fserial_process_configure (nargs, args);
2845 specpdl_ptr = specpdl + specpdl_count;
2847 UNGCPRO;
2848 return proc;
2851 /* Create a network stream/datagram client/server process. Treated
2852 exactly like a normal process when reading and writing. Primary
2853 differences are in status display and process deletion. A network
2854 connection has no PID; you cannot signal it. All you can do is
2855 stop/continue it and deactivate/close it via delete-process */
2857 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2858 0, MANY, 0,
2859 doc: /* Create and return a network server or client process.
2861 In Emacs, network connections are represented by process objects, so
2862 input and output work as for subprocesses and `delete-process' closes
2863 a network connection. However, a network process has no process id,
2864 it cannot be signaled, and the status codes are different from normal
2865 processes.
2867 Arguments are specified as keyword/argument pairs. The following
2868 arguments are defined:
2870 :name NAME -- NAME is name for process. It is modified if necessary
2871 to make it unique.
2873 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2874 with the process. Process output goes at end of that buffer, unless
2875 you specify an output stream or filter function to handle the output.
2876 BUFFER may be also nil, meaning that this process is not associated
2877 with any buffer.
2879 :host HOST -- HOST is name of the host to connect to, or its IP
2880 address. The symbol `local' specifies the local host. If specified
2881 for a server process, it must be a valid name or address for the local
2882 host, and only clients connecting to that address will be accepted.
2884 :service SERVICE -- SERVICE is name of the service desired, or an
2885 integer specifying a port number to connect to. If SERVICE is t,
2886 a random port number is selected for the server. (If Emacs was
2887 compiled with getaddrinfo, a port number can also be specified as a
2888 string, e.g. "80", as well as an integer. This is not portable.)
2890 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2891 stream type connection, `datagram' creates a datagram type connection,
2892 `seqpacket' creates a reliable datagram connection.
2894 :family FAMILY -- FAMILY is the address (and protocol) family for the
2895 service specified by HOST and SERVICE. The default (nil) is to use
2896 whatever address family (IPv4 or IPv6) that is defined for the host
2897 and port number specified by HOST and SERVICE. Other address families
2898 supported are:
2899 local -- for a local (i.e. UNIX) address specified by SERVICE.
2900 ipv4 -- use IPv4 address family only.
2901 ipv6 -- use IPv6 address family only.
2903 :local ADDRESS -- ADDRESS is the local address used for the connection.
2904 This parameter is ignored when opening a client process. When specified
2905 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2907 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2908 connection. This parameter is ignored when opening a stream server
2909 process. For a datagram server process, it specifies the initial
2910 setting of the remote datagram address. When specified for a client
2911 process, the FAMILY, HOST, and SERVICE args are ignored.
2913 The format of ADDRESS depends on the address family:
2914 - An IPv4 address is represented as an vector of integers [A B C D P]
2915 corresponding to numeric IP address A.B.C.D and port number P.
2916 - A local address is represented as a string with the address in the
2917 local address space.
2918 - An "unsupported family" address is represented by a cons (F . AV)
2919 where F is the family number and AV is a vector containing the socket
2920 address data with one element per address data byte. Do not rely on
2921 this format in portable code, as it may depend on implementation
2922 defined constants, data sizes, and data structure alignment.
2924 :coding CODING -- If CODING is a symbol, it specifies the coding
2925 system used for both reading and writing for this process. If CODING
2926 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2927 ENCODING is used for writing.
2929 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2930 return without waiting for the connection to complete; instead, the
2931 sentinel function will be called with second arg matching "open" (if
2932 successful) or "failed" when the connect completes. Default is to use
2933 a blocking connect (i.e. wait) for stream type connections.
2935 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2936 running when Emacs is exited.
2938 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2939 In the stopped state, a server process does not accept new
2940 connections, and a client process does not handle incoming traffic.
2941 The stopped state is cleared by `continue-process' and set by
2942 `stop-process'.
2944 :filter FILTER -- Install FILTER as the process filter.
2946 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2947 process filter are multibyte, otherwise they are unibyte.
2948 If this keyword is not specified, the strings are multibyte if
2949 the default value of `enable-multibyte-characters' is non-nil.
2951 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2953 :log LOG -- Install LOG as the server process log function. This
2954 function is called when the server accepts a network connection from a
2955 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2956 is the server process, CLIENT is the new process for the connection,
2957 and MESSAGE is a string.
2959 :plist PLIST -- Install PLIST as the new process' initial plist.
2961 :server QLEN -- if QLEN is non-nil, create a server process for the
2962 specified FAMILY, SERVICE, and connection type (stream or datagram).
2963 If QLEN is an integer, it is used as the max. length of the server's
2964 pending connection queue (also known as the backlog); the default
2965 queue length is 5. Default is to create a client process.
2967 The following network options can be specified for this connection:
2969 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2970 :dontroute BOOL -- Only send to directly connected hosts.
2971 :keepalive BOOL -- Send keep-alive messages on network stream.
2972 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2973 :oobinline BOOL -- Place out-of-band data in receive data stream.
2974 :priority INT -- Set protocol defined priority for sent packets.
2975 :reuseaddr BOOL -- Allow reusing a recently used local address
2976 (this is allowed by default for a server process).
2977 :bindtodevice NAME -- bind to interface NAME. Using this may require
2978 special privileges on some systems.
2980 Consult the relevant system programmer's manual pages for more
2981 information on using these options.
2984 A server process will listen for and accept connections from clients.
2985 When a client connection is accepted, a new network process is created
2986 for the connection with the following parameters:
2988 - The client's process name is constructed by concatenating the server
2989 process' NAME and a client identification string.
2990 - If the FILTER argument is non-nil, the client process will not get a
2991 separate process buffer; otherwise, the client's process buffer is a newly
2992 created buffer named after the server process' BUFFER name or process
2993 NAME concatenated with the client identification string.
2994 - The connection type and the process filter and sentinel parameters are
2995 inherited from the server process' TYPE, FILTER and SENTINEL.
2996 - The client process' contact info is set according to the client's
2997 addressing information (typically an IP address and a port number).
2998 - The client process' plist is initialized from the server's plist.
3000 Notice that the FILTER and SENTINEL args are never used directly by
3001 the server process. Also, the BUFFER argument is not used directly by
3002 the server process, but via the optional :log function, accepted (and
3003 failed) connections may be logged in the server process' buffer.
3005 The original argument list, modified with the actual connection
3006 information, is available via the `process-contact' function.
3008 usage: (make-network-process &rest ARGS) */)
3009 (ptrdiff_t nargs, Lisp_Object *args)
3011 Lisp_Object proc;
3012 Lisp_Object contact;
3013 struct Lisp_Process *p;
3014 #ifdef HAVE_GETADDRINFO
3015 struct addrinfo ai, *res, *lres;
3016 struct addrinfo hints;
3017 const char *portstring;
3018 char portbuf[128];
3019 #else /* HAVE_GETADDRINFO */
3020 struct _emacs_addrinfo
3022 int ai_family;
3023 int ai_socktype;
3024 int ai_protocol;
3025 int ai_addrlen;
3026 struct sockaddr *ai_addr;
3027 struct _emacs_addrinfo *ai_next;
3028 } ai, *res, *lres;
3029 #endif /* HAVE_GETADDRINFO */
3030 struct sockaddr_in address_in;
3031 #ifdef HAVE_LOCAL_SOCKETS
3032 struct sockaddr_un address_un;
3033 #endif
3034 int port;
3035 int ret = 0;
3036 int xerrno = 0;
3037 int s = -1, outch, inch;
3038 struct gcpro gcpro1;
3039 ptrdiff_t count = SPECPDL_INDEX ();
3040 ptrdiff_t count1;
3041 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3042 Lisp_Object tem;
3043 Lisp_Object name, buffer, host, service, address;
3044 Lisp_Object filter, sentinel;
3045 bool is_non_blocking_client = 0;
3046 bool is_server = 0;
3047 int backlog = 5;
3048 int socktype;
3049 int family = -1;
3051 if (nargs == 0)
3052 return Qnil;
3054 /* Save arguments for process-contact and clone-process. */
3055 contact = Flist (nargs, args);
3056 GCPRO1 (contact);
3058 #ifdef WINDOWSNT
3059 /* Ensure socket support is loaded if available. */
3060 init_winsock (TRUE);
3061 #endif
3063 /* :type TYPE (nil: stream, datagram */
3064 tem = Fplist_get (contact, QCtype);
3065 if (NILP (tem))
3066 socktype = SOCK_STREAM;
3067 #ifdef DATAGRAM_SOCKETS
3068 else if (EQ (tem, Qdatagram))
3069 socktype = SOCK_DGRAM;
3070 #endif
3071 #ifdef HAVE_SEQPACKET
3072 else if (EQ (tem, Qseqpacket))
3073 socktype = SOCK_SEQPACKET;
3074 #endif
3075 else
3076 error ("Unsupported connection type");
3078 /* :server BOOL */
3079 tem = Fplist_get (contact, QCserver);
3080 if (!NILP (tem))
3082 /* Don't support network sockets when non-blocking mode is
3083 not available, since a blocked Emacs is not useful. */
3084 is_server = 1;
3085 if (TYPE_RANGED_INTEGERP (int, tem))
3086 backlog = XINT (tem);
3089 /* Make QCaddress an alias for :local (server) or :remote (client). */
3090 QCaddress = is_server ? QClocal : QCremote;
3092 /* :nowait BOOL */
3093 if (!is_server && socktype != SOCK_DGRAM
3094 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3096 #ifndef NON_BLOCKING_CONNECT
3097 error ("Non-blocking connect not supported");
3098 #else
3099 is_non_blocking_client = 1;
3100 #endif
3103 name = Fplist_get (contact, QCname);
3104 buffer = Fplist_get (contact, QCbuffer);
3105 filter = Fplist_get (contact, QCfilter);
3106 sentinel = Fplist_get (contact, QCsentinel);
3108 CHECK_STRING (name);
3110 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3111 ai.ai_socktype = socktype;
3112 ai.ai_protocol = 0;
3113 ai.ai_next = NULL;
3114 res = &ai;
3116 /* :local ADDRESS or :remote ADDRESS */
3117 address = Fplist_get (contact, QCaddress);
3118 if (!NILP (address))
3120 host = service = Qnil;
3122 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3123 error ("Malformed :address");
3124 ai.ai_family = family;
3125 ai.ai_addr = alloca (ai.ai_addrlen);
3126 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3127 goto open_socket;
3130 /* :family FAMILY -- nil (for Inet), local, or integer. */
3131 tem = Fplist_get (contact, QCfamily);
3132 if (NILP (tem))
3134 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3135 family = AF_UNSPEC;
3136 #else
3137 family = AF_INET;
3138 #endif
3140 #ifdef HAVE_LOCAL_SOCKETS
3141 else if (EQ (tem, Qlocal))
3142 family = AF_LOCAL;
3143 #endif
3144 #ifdef AF_INET6
3145 else if (EQ (tem, Qipv6))
3146 family = AF_INET6;
3147 #endif
3148 else if (EQ (tem, Qipv4))
3149 family = AF_INET;
3150 else if (TYPE_RANGED_INTEGERP (int, tem))
3151 family = XINT (tem);
3152 else
3153 error ("Unknown address family");
3155 ai.ai_family = family;
3157 /* :service SERVICE -- string, integer (port number), or t (random port). */
3158 service = Fplist_get (contact, QCservice);
3160 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3161 host = Fplist_get (contact, QChost);
3162 if (!NILP (host))
3164 if (EQ (host, Qlocal))
3165 /* Depending on setup, "localhost" may map to different IPv4 and/or
3166 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3167 host = build_string ("127.0.0.1");
3168 CHECK_STRING (host);
3171 #ifdef HAVE_LOCAL_SOCKETS
3172 if (family == AF_LOCAL)
3174 if (!NILP (host))
3176 message (":family local ignores the :host \"%s\" property",
3177 SDATA (host));
3178 contact = Fplist_put (contact, QChost, Qnil);
3179 host = Qnil;
3181 CHECK_STRING (service);
3182 memset (&address_un, 0, sizeof address_un);
3183 address_un.sun_family = AF_LOCAL;
3184 if (sizeof address_un.sun_path <= SBYTES (service))
3185 error ("Service name too long");
3186 strcpy (address_un.sun_path, SSDATA (service));
3187 ai.ai_addr = (struct sockaddr *) &address_un;
3188 ai.ai_addrlen = sizeof address_un;
3189 goto open_socket;
3191 #endif
3193 /* Slow down polling to every ten seconds.
3194 Some kernels have a bug which causes retrying connect to fail
3195 after a connect. Polling can interfere with gethostbyname too. */
3196 #ifdef POLL_FOR_INPUT
3197 if (socktype != SOCK_DGRAM)
3199 record_unwind_protect_void (run_all_atimers);
3200 bind_polling_period (10);
3202 #endif
3204 #ifdef HAVE_GETADDRINFO
3205 /* If we have a host, use getaddrinfo to resolve both host and service.
3206 Otherwise, use getservbyname to lookup the service. */
3207 if (!NILP (host))
3210 /* SERVICE can either be a string or int.
3211 Convert to a C string for later use by getaddrinfo. */
3212 if (EQ (service, Qt))
3213 portstring = "0";
3214 else if (INTEGERP (service))
3216 sprintf (portbuf, "%"pI"d", XINT (service));
3217 portstring = portbuf;
3219 else
3221 CHECK_STRING (service);
3222 portstring = SSDATA (service);
3225 immediate_quit = 1;
3226 QUIT;
3227 memset (&hints, 0, sizeof (hints));
3228 hints.ai_flags = 0;
3229 hints.ai_family = family;
3230 hints.ai_socktype = socktype;
3231 hints.ai_protocol = 0;
3233 #ifdef HAVE_RES_INIT
3234 res_init ();
3235 #endif
3237 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3238 if (ret)
3239 #ifdef HAVE_GAI_STRERROR
3240 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3241 #else
3242 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3243 #endif
3244 immediate_quit = 0;
3246 goto open_socket;
3248 #endif /* HAVE_GETADDRINFO */
3250 /* We end up here if getaddrinfo is not defined, or in case no hostname
3251 has been specified (e.g. for a local server process). */
3253 if (EQ (service, Qt))
3254 port = 0;
3255 else if (INTEGERP (service))
3256 port = htons ((unsigned short) XINT (service));
3257 else
3259 struct servent *svc_info;
3260 CHECK_STRING (service);
3261 svc_info = getservbyname (SSDATA (service),
3262 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3263 if (svc_info == 0)
3264 error ("Unknown service: %s", SDATA (service));
3265 port = svc_info->s_port;
3268 memset (&address_in, 0, sizeof address_in);
3269 address_in.sin_family = family;
3270 address_in.sin_addr.s_addr = INADDR_ANY;
3271 address_in.sin_port = port;
3273 #ifndef HAVE_GETADDRINFO
3274 if (!NILP (host))
3276 struct hostent *host_info_ptr;
3278 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3279 as it may `hang' Emacs for a very long time. */
3280 immediate_quit = 1;
3281 QUIT;
3283 #ifdef HAVE_RES_INIT
3284 res_init ();
3285 #endif
3287 host_info_ptr = gethostbyname (SDATA (host));
3288 immediate_quit = 0;
3290 if (host_info_ptr)
3292 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3293 host_info_ptr->h_length);
3294 family = host_info_ptr->h_addrtype;
3295 address_in.sin_family = family;
3297 else
3298 /* Attempt to interpret host as numeric inet address */
3300 unsigned long numeric_addr;
3301 numeric_addr = inet_addr (SSDATA (host));
3302 if (numeric_addr == -1)
3303 error ("Unknown host \"%s\"", SDATA (host));
3305 memcpy (&address_in.sin_addr, &numeric_addr,
3306 sizeof (address_in.sin_addr));
3310 #endif /* not HAVE_GETADDRINFO */
3312 ai.ai_family = family;
3313 ai.ai_addr = (struct sockaddr *) &address_in;
3314 ai.ai_addrlen = sizeof address_in;
3316 open_socket:
3318 /* Do this in case we never enter the for-loop below. */
3319 count1 = SPECPDL_INDEX ();
3320 s = -1;
3322 for (lres = res; lres; lres = lres->ai_next)
3324 ptrdiff_t optn;
3325 int optbits;
3327 #ifdef WINDOWSNT
3328 retry_connect:
3329 #endif
3331 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3332 lres->ai_protocol);
3333 if (s < 0)
3335 xerrno = errno;
3336 continue;
3339 #ifdef DATAGRAM_SOCKETS
3340 if (!is_server && socktype == SOCK_DGRAM)
3341 break;
3342 #endif /* DATAGRAM_SOCKETS */
3344 #ifdef NON_BLOCKING_CONNECT
3345 if (is_non_blocking_client)
3347 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3348 if (ret < 0)
3350 xerrno = errno;
3351 emacs_close (s);
3352 s = -1;
3353 continue;
3356 #endif
3358 /* Make us close S if quit. */
3359 record_unwind_protect_int (close_file_unwind, s);
3361 /* Parse network options in the arg list.
3362 We simply ignore anything which isn't a known option (including other keywords).
3363 An error is signaled if setting a known option fails. */
3364 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3365 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3367 if (is_server)
3369 /* Configure as a server socket. */
3371 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3372 explicit :reuseaddr key to override this. */
3373 #ifdef HAVE_LOCAL_SOCKETS
3374 if (family != AF_LOCAL)
3375 #endif
3376 if (!(optbits & (1 << OPIX_REUSEADDR)))
3378 int optval = 1;
3379 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3380 report_file_error ("Cannot set reuse option on server socket", Qnil);
3383 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3384 report_file_error ("Cannot bind server socket", Qnil);
3386 #ifdef HAVE_GETSOCKNAME
3387 if (EQ (service, Qt))
3389 struct sockaddr_in sa1;
3390 socklen_t len1 = sizeof (sa1);
3391 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3393 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3394 service = make_number (ntohs (sa1.sin_port));
3395 contact = Fplist_put (contact, QCservice, service);
3398 #endif
3400 if (socktype != SOCK_DGRAM && listen (s, backlog))
3401 report_file_error ("Cannot listen on server socket", Qnil);
3403 break;
3406 immediate_quit = 1;
3407 QUIT;
3409 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3410 xerrno = errno;
3412 if (ret == 0 || xerrno == EISCONN)
3414 /* The unwind-protect will be discarded afterwards.
3415 Likewise for immediate_quit. */
3416 break;
3419 #ifdef NON_BLOCKING_CONNECT
3420 #ifdef EINPROGRESS
3421 if (is_non_blocking_client && xerrno == EINPROGRESS)
3422 break;
3423 #else
3424 #ifdef EWOULDBLOCK
3425 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3426 break;
3427 #endif
3428 #endif
3429 #endif
3431 #ifndef WINDOWSNT
3432 if (xerrno == EINTR)
3434 /* Unlike most other syscalls connect() cannot be called
3435 again. (That would return EALREADY.) The proper way to
3436 wait for completion is pselect(). */
3437 int sc;
3438 socklen_t len;
3439 SELECT_TYPE fdset;
3440 retry_select:
3441 FD_ZERO (&fdset);
3442 FD_SET (s, &fdset);
3443 QUIT;
3444 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3445 if (sc == -1)
3447 if (errno == EINTR)
3448 goto retry_select;
3449 else
3450 report_file_error ("Failed select", Qnil);
3452 eassert (sc > 0);
3454 len = sizeof xerrno;
3455 eassert (FD_ISSET (s, &fdset));
3456 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3457 report_file_error ("Failed getsockopt", Qnil);
3458 if (xerrno)
3459 report_file_errno ("Failed connect", Qnil, xerrno);
3460 break;
3462 #endif /* !WINDOWSNT */
3464 immediate_quit = 0;
3466 /* Discard the unwind protect closing S. */
3467 specpdl_ptr = specpdl + count1;
3468 emacs_close (s);
3469 s = -1;
3471 #ifdef WINDOWSNT
3472 if (xerrno == EINTR)
3473 goto retry_connect;
3474 #endif
3477 if (s >= 0)
3479 #ifdef DATAGRAM_SOCKETS
3480 if (socktype == SOCK_DGRAM)
3482 if (datagram_address[s].sa)
3483 emacs_abort ();
3484 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3485 datagram_address[s].len = lres->ai_addrlen;
3486 if (is_server)
3488 Lisp_Object remote;
3489 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3490 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3492 int rfamily, rlen;
3493 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3494 if (rlen != 0 && rfamily == lres->ai_family
3495 && rlen == lres->ai_addrlen)
3496 conv_lisp_to_sockaddr (rfamily, remote,
3497 datagram_address[s].sa, rlen);
3500 else
3501 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3503 #endif
3504 contact = Fplist_put (contact, QCaddress,
3505 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3506 #ifdef HAVE_GETSOCKNAME
3507 if (!is_server)
3509 struct sockaddr_in sa1;
3510 socklen_t len1 = sizeof (sa1);
3511 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3512 contact = Fplist_put (contact, QClocal,
3513 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3515 #endif
3518 immediate_quit = 0;
3520 #ifdef HAVE_GETADDRINFO
3521 if (res != &ai)
3523 block_input ();
3524 freeaddrinfo (res);
3525 unblock_input ();
3527 #endif
3529 if (s < 0)
3531 /* If non-blocking got this far - and failed - assume non-blocking is
3532 not supported after all. This is probably a wrong assumption, but
3533 the normal blocking calls to open-network-stream handles this error
3534 better. */
3535 if (is_non_blocking_client)
3536 return Qnil;
3538 report_file_errno ((is_server
3539 ? "make server process failed"
3540 : "make client process failed"),
3541 contact, xerrno);
3544 inch = s;
3545 outch = s;
3547 if (!NILP (buffer))
3548 buffer = Fget_buffer_create (buffer);
3549 proc = make_process (name);
3551 chan_process[inch] = proc;
3553 fcntl (inch, F_SETFL, O_NONBLOCK);
3555 p = XPROCESS (proc);
3557 pset_childp (p, contact);
3558 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3559 pset_type (p, Qnetwork);
3561 pset_buffer (p, buffer);
3562 pset_sentinel (p, sentinel);
3563 pset_filter (p, filter);
3564 pset_log (p, Fplist_get (contact, QClog));
3565 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3566 p->kill_without_query = 1;
3567 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3568 pset_command (p, Qt);
3569 p->pid = 0;
3571 p->open_fd[SUBPROCESS_STDIN] = inch;
3572 p->infd = inch;
3573 p->outfd = outch;
3575 /* Discard the unwind protect for closing S, if any. */
3576 specpdl_ptr = specpdl + count1;
3578 /* Unwind bind_polling_period and request_sigio. */
3579 unbind_to (count, Qnil);
3581 if (is_server && socktype != SOCK_DGRAM)
3582 pset_status (p, Qlisten);
3584 /* Make the process marker point into the process buffer (if any). */
3585 if (BUFFERP (buffer))
3586 set_marker_both (p->mark, buffer,
3587 BUF_ZV (XBUFFER (buffer)),
3588 BUF_ZV_BYTE (XBUFFER (buffer)));
3590 #ifdef NON_BLOCKING_CONNECT
3591 if (is_non_blocking_client)
3593 /* We may get here if connect did succeed immediately. However,
3594 in that case, we still need to signal this like a non-blocking
3595 connection. */
3596 pset_status (p, Qconnect);
3597 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3598 add_non_blocking_write_fd (inch);
3600 else
3601 #endif
3602 /* A server may have a client filter setting of Qt, but it must
3603 still listen for incoming connects unless it is stopped. */
3604 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3605 || (EQ (p->status, Qlisten) && NILP (p->command)))
3606 add_non_keyboard_read_fd (inch);
3608 if (inch > max_desc)
3609 max_desc = inch;
3611 tem = Fplist_member (contact, QCcoding);
3612 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3613 tem = Qnil; /* No error message (too late!). */
3616 /* Setup coding systems for communicating with the network stream. */
3617 struct gcpro gcpro1;
3618 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3619 Lisp_Object coding_systems = Qt;
3620 Lisp_Object fargs[5], val;
3622 if (!NILP (tem))
3624 val = XCAR (XCDR (tem));
3625 if (CONSP (val))
3626 val = XCAR (val);
3628 else if (!NILP (Vcoding_system_for_read))
3629 val = Vcoding_system_for_read;
3630 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3631 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3632 /* We dare not decode end-of-line format by setting VAL to
3633 Qraw_text, because the existing Emacs Lisp libraries
3634 assume that they receive bare code including a sequence of
3635 CR LF. */
3636 val = Qnil;
3637 else
3639 if (NILP (host) || NILP (service))
3640 coding_systems = Qnil;
3641 else
3643 fargs[0] = Qopen_network_stream, fargs[1] = name,
3644 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3645 GCPRO1 (proc);
3646 coding_systems = Ffind_operation_coding_system (5, fargs);
3647 UNGCPRO;
3649 if (CONSP (coding_systems))
3650 val = XCAR (coding_systems);
3651 else if (CONSP (Vdefault_process_coding_system))
3652 val = XCAR (Vdefault_process_coding_system);
3653 else
3654 val = Qnil;
3656 pset_decode_coding_system (p, val);
3658 if (!NILP (tem))
3660 val = XCAR (XCDR (tem));
3661 if (CONSP (val))
3662 val = XCDR (val);
3664 else if (!NILP (Vcoding_system_for_write))
3665 val = Vcoding_system_for_write;
3666 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3667 val = Qnil;
3668 else
3670 if (EQ (coding_systems, Qt))
3672 if (NILP (host) || NILP (service))
3673 coding_systems = Qnil;
3674 else
3676 fargs[0] = Qopen_network_stream, fargs[1] = name,
3677 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3678 GCPRO1 (proc);
3679 coding_systems = Ffind_operation_coding_system (5, fargs);
3680 UNGCPRO;
3683 if (CONSP (coding_systems))
3684 val = XCDR (coding_systems);
3685 else if (CONSP (Vdefault_process_coding_system))
3686 val = XCDR (Vdefault_process_coding_system);
3687 else
3688 val = Qnil;
3690 pset_encode_coding_system (p, val);
3692 setup_process_coding_systems (proc);
3694 pset_decoding_buf (p, empty_unibyte_string);
3695 p->decoding_carryover = 0;
3696 pset_encoding_buf (p, empty_unibyte_string);
3698 p->inherit_coding_system_flag
3699 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3701 UNGCPRO;
3702 return proc;
3706 #if defined (HAVE_NET_IF_H)
3708 #ifdef SIOCGIFCONF
3709 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3710 doc: /* Return an alist of all network interfaces and their network address.
3711 Each element is a cons, the car of which is a string containing the
3712 interface name, and the cdr is the network address in internal
3713 format; see the description of ADDRESS in `make-network-process'. */)
3714 (void)
3716 struct ifconf ifconf;
3717 struct ifreq *ifreq;
3718 void *buf = NULL;
3719 ptrdiff_t buf_size = 512;
3720 int s;
3721 Lisp_Object res;
3722 ptrdiff_t count;
3724 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3725 if (s < 0)
3726 return Qnil;
3727 count = SPECPDL_INDEX ();
3728 record_unwind_protect_int (close_file_unwind, s);
3732 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3733 ifconf.ifc_buf = buf;
3734 ifconf.ifc_len = buf_size;
3735 if (ioctl (s, SIOCGIFCONF, &ifconf))
3737 emacs_close (s);
3738 xfree (buf);
3739 return Qnil;
3742 while (ifconf.ifc_len == buf_size);
3744 res = unbind_to (count, Qnil);
3745 ifreq = ifconf.ifc_req;
3746 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3748 struct ifreq *ifq = ifreq;
3749 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3750 #define SIZEOF_IFREQ(sif) \
3751 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3752 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3754 int len = SIZEOF_IFREQ (ifq);
3755 #else
3756 int len = sizeof (*ifreq);
3757 #endif
3758 char namebuf[sizeof (ifq->ifr_name) + 1];
3759 ifreq = (struct ifreq *) ((char *) ifreq + len);
3761 if (ifq->ifr_addr.sa_family != AF_INET)
3762 continue;
3764 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3765 namebuf[sizeof (ifq->ifr_name)] = 0;
3766 res = Fcons (Fcons (build_string (namebuf),
3767 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3768 sizeof (struct sockaddr))),
3769 res);
3772 xfree (buf);
3773 return res;
3775 #endif /* SIOCGIFCONF */
3777 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3779 struct ifflag_def {
3780 int flag_bit;
3781 const char *flag_sym;
3784 static const struct ifflag_def ifflag_table[] = {
3785 #ifdef IFF_UP
3786 { IFF_UP, "up" },
3787 #endif
3788 #ifdef IFF_BROADCAST
3789 { IFF_BROADCAST, "broadcast" },
3790 #endif
3791 #ifdef IFF_DEBUG
3792 { IFF_DEBUG, "debug" },
3793 #endif
3794 #ifdef IFF_LOOPBACK
3795 { IFF_LOOPBACK, "loopback" },
3796 #endif
3797 #ifdef IFF_POINTOPOINT
3798 { IFF_POINTOPOINT, "pointopoint" },
3799 #endif
3800 #ifdef IFF_RUNNING
3801 { IFF_RUNNING, "running" },
3802 #endif
3803 #ifdef IFF_NOARP
3804 { IFF_NOARP, "noarp" },
3805 #endif
3806 #ifdef IFF_PROMISC
3807 { IFF_PROMISC, "promisc" },
3808 #endif
3809 #ifdef IFF_NOTRAILERS
3810 #ifdef NS_IMPL_COCOA
3811 /* Really means smart, notrailers is obsolete */
3812 { IFF_NOTRAILERS, "smart" },
3813 #else
3814 { IFF_NOTRAILERS, "notrailers" },
3815 #endif
3816 #endif
3817 #ifdef IFF_ALLMULTI
3818 { IFF_ALLMULTI, "allmulti" },
3819 #endif
3820 #ifdef IFF_MASTER
3821 { IFF_MASTER, "master" },
3822 #endif
3823 #ifdef IFF_SLAVE
3824 { IFF_SLAVE, "slave" },
3825 #endif
3826 #ifdef IFF_MULTICAST
3827 { IFF_MULTICAST, "multicast" },
3828 #endif
3829 #ifdef IFF_PORTSEL
3830 { IFF_PORTSEL, "portsel" },
3831 #endif
3832 #ifdef IFF_AUTOMEDIA
3833 { IFF_AUTOMEDIA, "automedia" },
3834 #endif
3835 #ifdef IFF_DYNAMIC
3836 { IFF_DYNAMIC, "dynamic" },
3837 #endif
3838 #ifdef IFF_OACTIVE
3839 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3840 #endif
3841 #ifdef IFF_SIMPLEX
3842 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3843 #endif
3844 #ifdef IFF_LINK0
3845 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3846 #endif
3847 #ifdef IFF_LINK1
3848 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3849 #endif
3850 #ifdef IFF_LINK2
3851 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3852 #endif
3853 { 0, 0 }
3856 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3857 doc: /* Return information about network interface named IFNAME.
3858 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3859 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3860 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3861 FLAGS is the current flags of the interface. */)
3862 (Lisp_Object ifname)
3864 struct ifreq rq;
3865 Lisp_Object res = Qnil;
3866 Lisp_Object elt;
3867 int s;
3868 bool any = 0;
3869 ptrdiff_t count;
3870 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3871 && defined HAVE_GETIFADDRS && defined LLADDR)
3872 struct ifaddrs *ifap;
3873 #endif
3875 CHECK_STRING (ifname);
3877 if (sizeof rq.ifr_name <= SBYTES (ifname))
3878 error ("interface name too long");
3879 strcpy (rq.ifr_name, SSDATA (ifname));
3881 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3882 if (s < 0)
3883 return Qnil;
3884 count = SPECPDL_INDEX ();
3885 record_unwind_protect_int (close_file_unwind, s);
3887 elt = Qnil;
3888 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3889 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3891 int flags = rq.ifr_flags;
3892 const struct ifflag_def *fp;
3893 int fnum;
3895 /* If flags is smaller than int (i.e. short) it may have the high bit set
3896 due to IFF_MULTICAST. In that case, sign extending it into
3897 an int is wrong. */
3898 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3899 flags = (unsigned short) rq.ifr_flags;
3901 any = 1;
3902 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3904 if (flags & fp->flag_bit)
3906 elt = Fcons (intern (fp->flag_sym), elt);
3907 flags -= fp->flag_bit;
3910 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3912 if (flags & 1)
3914 elt = Fcons (make_number (fnum), elt);
3918 #endif
3919 res = Fcons (elt, res);
3921 elt = Qnil;
3922 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3923 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3925 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3926 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3927 int n;
3929 any = 1;
3930 for (n = 0; n < 6; n++)
3931 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3932 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3934 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3935 if (getifaddrs (&ifap) != -1)
3937 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3938 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3939 struct ifaddrs *it;
3941 for (it = ifap; it != NULL; it = it->ifa_next)
3943 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3944 unsigned char linkaddr[6];
3945 int n;
3947 if (it->ifa_addr->sa_family != AF_LINK
3948 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3949 || sdl->sdl_alen != 6)
3950 continue;
3952 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3953 for (n = 0; n < 6; n++)
3954 p->contents[n] = make_number (linkaddr[n]);
3956 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3957 break;
3960 #ifdef HAVE_FREEIFADDRS
3961 freeifaddrs (ifap);
3962 #endif
3964 #endif /* HAVE_GETIFADDRS && LLADDR */
3966 res = Fcons (elt, res);
3968 elt = Qnil;
3969 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3970 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3972 any = 1;
3973 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3974 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3975 #else
3976 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3977 #endif
3979 #endif
3980 res = Fcons (elt, res);
3982 elt = Qnil;
3983 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3984 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3986 any = 1;
3987 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3989 #endif
3990 res = Fcons (elt, res);
3992 elt = Qnil;
3993 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3994 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3996 any = 1;
3997 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3999 #endif
4000 res = Fcons (elt, res);
4002 return unbind_to (count, any ? res : Qnil);
4004 #endif
4005 #endif /* defined (HAVE_NET_IF_H) */
4007 /* Turn off input and output for process PROC. */
4009 static void
4010 deactivate_process (Lisp_Object proc)
4012 int inchannel;
4013 struct Lisp_Process *p = XPROCESS (proc);
4014 int i;
4016 #ifdef HAVE_GNUTLS
4017 /* Delete GnuTLS structures in PROC, if any. */
4018 emacs_gnutls_deinit (proc);
4019 #endif /* HAVE_GNUTLS */
4021 #ifdef ADAPTIVE_READ_BUFFERING
4022 if (p->read_output_delay > 0)
4024 if (--process_output_delay_count < 0)
4025 process_output_delay_count = 0;
4026 p->read_output_delay = 0;
4027 p->read_output_skip = 0;
4029 #endif
4031 inchannel = p->infd;
4033 /* Beware SIGCHLD hereabouts. */
4034 if (inchannel >= 0)
4035 flush_pending_output (inchannel);
4037 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4038 close_process_fd (&p->open_fd[i]);
4040 if (inchannel >= 0)
4042 p->infd = -1;
4043 p->outfd = -1;
4044 #ifdef DATAGRAM_SOCKETS
4045 if (DATAGRAM_CHAN_P (inchannel))
4047 xfree (datagram_address[inchannel].sa);
4048 datagram_address[inchannel].sa = 0;
4049 datagram_address[inchannel].len = 0;
4051 #endif
4052 chan_process[inchannel] = Qnil;
4053 delete_read_fd (inchannel);
4054 #ifdef NON_BLOCKING_CONNECT
4055 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4056 delete_write_fd (inchannel);
4057 #endif
4058 if (inchannel == max_desc)
4059 recompute_max_desc ();
4064 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4065 0, 4, 0,
4066 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4067 It is read into the process' buffers or given to their filter functions.
4068 Non-nil arg PROCESS means do not return until some output has been received
4069 from PROCESS.
4071 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4072 and milliseconds to wait; return after that much time whether or not
4073 there is any subprocess output. If SECONDS is a floating point number,
4074 it specifies a fractional number of seconds to wait.
4075 The MILLISEC argument is obsolete and should be avoided.
4077 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4078 from PROCESS, suspending reading output from other processes.
4079 If JUST-THIS-ONE is an integer, don't run any timers either.
4080 Return non-nil if we received any output before the timeout expired. */)
4081 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4083 intmax_t secs;
4084 int nsecs;
4086 if (! NILP (process))
4088 struct Lisp_Process *procp;
4090 CHECK_PROCESS (process);
4091 procp = XPROCESS (process);
4093 /* Can't wait for a process that is dedicated to a different
4094 thread. */
4095 if (!EQ (procp->thread, Qnil) && !EQ (procp->thread, Fcurrent_thread ()))
4096 error ("FIXME");
4098 else
4099 just_this_one = Qnil;
4101 if (!NILP (millisec))
4102 { /* Obsolete calling convention using integers rather than floats. */
4103 CHECK_NUMBER (millisec);
4104 if (NILP (seconds))
4105 seconds = make_float (XINT (millisec) / 1000.0);
4106 else
4108 CHECK_NUMBER (seconds);
4109 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4113 secs = 0;
4114 nsecs = -1;
4116 if (!NILP (seconds))
4118 if (INTEGERP (seconds))
4120 if (XINT (seconds) > 0)
4122 secs = XINT (seconds);
4123 nsecs = 0;
4126 else if (FLOATP (seconds))
4128 if (XFLOAT_DATA (seconds) > 0)
4130 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
4131 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
4132 nsecs = EMACS_NSECS (t);
4135 else
4136 wrong_type_argument (Qnumberp, seconds);
4138 else if (! NILP (process))
4139 nsecs = 0;
4141 return
4142 (wait_reading_process_output (secs, nsecs, 0, 0,
4143 Qnil,
4144 !NILP (process) ? XPROCESS (process) : NULL,
4145 NILP (just_this_one) ? 0 :
4146 !INTEGERP (just_this_one) ? 1 : -1)
4147 ? Qt : Qnil);
4150 /* Accept a connection for server process SERVER on CHANNEL. */
4152 static EMACS_INT connect_counter = 0;
4154 static void
4155 server_accept_connection (Lisp_Object server, int channel)
4157 Lisp_Object proc, caller, name, buffer;
4158 Lisp_Object contact, host, service;
4159 struct Lisp_Process *ps= XPROCESS (server);
4160 struct Lisp_Process *p;
4161 int s;
4162 union u_sockaddr {
4163 struct sockaddr sa;
4164 struct sockaddr_in in;
4165 #ifdef AF_INET6
4166 struct sockaddr_in6 in6;
4167 #endif
4168 #ifdef HAVE_LOCAL_SOCKETS
4169 struct sockaddr_un un;
4170 #endif
4171 } saddr;
4172 socklen_t len = sizeof saddr;
4173 ptrdiff_t count;
4175 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4177 if (s < 0)
4179 int code = errno;
4181 if (code == EAGAIN)
4182 return;
4183 #ifdef EWOULDBLOCK
4184 if (code == EWOULDBLOCK)
4185 return;
4186 #endif
4188 if (!NILP (ps->log))
4189 call3 (ps->log, server, Qnil,
4190 concat3 (build_string ("accept failed with code"),
4191 Fnumber_to_string (make_number (code)),
4192 build_string ("\n")));
4193 return;
4196 count = SPECPDL_INDEX ();
4197 record_unwind_protect_int (close_file_unwind, s);
4199 connect_counter++;
4201 /* Setup a new process to handle the connection. */
4203 /* Generate a unique identification of the caller, and build contact
4204 information for this process. */
4205 host = Qt;
4206 service = Qnil;
4207 switch (saddr.sa.sa_family)
4209 case AF_INET:
4211 Lisp_Object args[5];
4212 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4213 args[0] = build_string ("%d.%d.%d.%d");
4214 args[1] = make_number (*ip++);
4215 args[2] = make_number (*ip++);
4216 args[3] = make_number (*ip++);
4217 args[4] = make_number (*ip++);
4218 host = Fformat (5, args);
4219 service = make_number (ntohs (saddr.in.sin_port));
4221 args[0] = build_string (" <%s:%d>");
4222 args[1] = host;
4223 args[2] = service;
4224 caller = Fformat (3, args);
4226 break;
4228 #ifdef AF_INET6
4229 case AF_INET6:
4231 Lisp_Object args[9];
4232 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4233 int i;
4234 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4235 for (i = 0; i < 8; i++)
4236 args[i+1] = make_number (ntohs (ip6[i]));
4237 host = Fformat (9, args);
4238 service = make_number (ntohs (saddr.in.sin_port));
4240 args[0] = build_string (" <[%s]:%d>");
4241 args[1] = host;
4242 args[2] = service;
4243 caller = Fformat (3, args);
4245 break;
4246 #endif
4248 #ifdef HAVE_LOCAL_SOCKETS
4249 case AF_LOCAL:
4250 #endif
4251 default:
4252 caller = Fnumber_to_string (make_number (connect_counter));
4253 caller = concat3 (build_string (" <"), caller, build_string (">"));
4254 break;
4257 /* Create a new buffer name for this process if it doesn't have a
4258 filter. The new buffer name is based on the buffer name or
4259 process name of the server process concatenated with the caller
4260 identification. */
4262 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4263 || EQ (ps->filter, Qt)))
4264 buffer = Qnil;
4265 else
4267 buffer = ps->buffer;
4268 if (!NILP (buffer))
4269 buffer = Fbuffer_name (buffer);
4270 else
4271 buffer = ps->name;
4272 if (!NILP (buffer))
4274 buffer = concat2 (buffer, caller);
4275 buffer = Fget_buffer_create (buffer);
4279 /* Generate a unique name for the new server process. Combine the
4280 server process name with the caller identification. */
4282 name = concat2 (ps->name, caller);
4283 proc = make_process (name);
4285 chan_process[s] = proc;
4287 fcntl (s, F_SETFL, O_NONBLOCK);
4289 p = XPROCESS (proc);
4291 /* Build new contact information for this setup. */
4292 contact = Fcopy_sequence (ps->childp);
4293 contact = Fplist_put (contact, QCserver, Qnil);
4294 contact = Fplist_put (contact, QChost, host);
4295 if (!NILP (service))
4296 contact = Fplist_put (contact, QCservice, service);
4297 contact = Fplist_put (contact, QCremote,
4298 conv_sockaddr_to_lisp (&saddr.sa, len));
4299 #ifdef HAVE_GETSOCKNAME
4300 len = sizeof saddr;
4301 if (getsockname (s, &saddr.sa, &len) == 0)
4302 contact = Fplist_put (contact, QClocal,
4303 conv_sockaddr_to_lisp (&saddr.sa, len));
4304 #endif
4306 pset_childp (p, contact);
4307 pset_plist (p, Fcopy_sequence (ps->plist));
4308 pset_type (p, Qnetwork);
4310 pset_buffer (p, buffer);
4311 pset_sentinel (p, ps->sentinel);
4312 pset_filter (p, ps->filter);
4313 pset_command (p, Qnil);
4314 p->pid = 0;
4316 /* Discard the unwind protect for closing S. */
4317 specpdl_ptr = specpdl + count;
4319 p->open_fd[SUBPROCESS_STDIN] = s;
4320 p->infd = s;
4321 p->outfd = s;
4322 pset_status (p, Qrun);
4324 /* Client processes for accepted connections are not stopped initially. */
4325 if (!EQ (p->filter, Qt))
4326 add_non_keyboard_read_fd (s);
4328 /* Setup coding system for new process based on server process.
4329 This seems to be the proper thing to do, as the coding system
4330 of the new process should reflect the settings at the time the
4331 server socket was opened; not the current settings. */
4333 pset_decode_coding_system (p, ps->decode_coding_system);
4334 pset_encode_coding_system (p, ps->encode_coding_system);
4335 setup_process_coding_systems (proc);
4337 pset_decoding_buf (p, empty_unibyte_string);
4338 p->decoding_carryover = 0;
4339 pset_encoding_buf (p, empty_unibyte_string);
4341 p->inherit_coding_system_flag
4342 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4344 if (!NILP (ps->log))
4345 call3 (ps->log, server, proc,
4346 concat3 (build_string ("accept from "),
4347 (STRINGP (host) ? host : build_string ("-")),
4348 build_string ("\n")));
4350 exec_sentinel (proc,
4351 concat3 (build_string ("open from "),
4352 (STRINGP (host) ? host : build_string ("-")),
4353 build_string ("\n")));
4356 static void
4357 wait_reading_process_output_unwind (int data)
4359 clear_waiting_thread_info ();
4360 waiting_for_user_input_p = data;
4363 /* This is here so breakpoints can be put on it. */
4364 static void
4365 wait_reading_process_output_1 (void)
4369 /* Read and dispose of subprocess output while waiting for timeout to
4370 elapse and/or keyboard input to be available.
4372 TIME_LIMIT is:
4373 timeout in seconds
4374 If negative, gobble data immediately available but don't wait for any.
4376 NSECS is:
4377 an additional duration to wait, measured in nanoseconds
4378 If TIME_LIMIT is zero, then:
4379 If NSECS == 0, there is no limit.
4380 If NSECS > 0, the timeout consists of NSECS only.
4381 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4383 READ_KBD is:
4384 0 to ignore keyboard input, or
4385 1 to return when input is available, or
4386 -1 meaning caller will actually read the input, so don't throw to
4387 the quit handler, or
4389 DO_DISPLAY means redisplay should be done to show subprocess
4390 output that arrives.
4392 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4393 (and gobble terminal input into the buffer if any arrives).
4395 If WAIT_PROC is specified, wait until something arrives from that
4396 process. The return value is true if we read some input from
4397 that process.
4399 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4400 (suspending output from other processes). A negative value
4401 means don't run any timers either.
4403 If WAIT_PROC is specified, then the function returns true if we
4404 received input from that process before the timeout elapsed.
4405 Otherwise, return true if we received input from any process. */
4407 bool
4408 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4409 bool do_display,
4410 Lisp_Object wait_for_cell,
4411 struct Lisp_Process *wait_proc, int just_wait_proc)
4413 int channel, nfds;
4414 SELECT_TYPE Available;
4415 SELECT_TYPE Writeok;
4416 bool check_write;
4417 int check_delay;
4418 bool no_avail;
4419 int xerrno;
4420 Lisp_Object proc;
4421 EMACS_TIME timeout, end_time;
4422 int wait_channel = -1;
4423 bool got_some_input = 0;
4424 ptrdiff_t count = SPECPDL_INDEX ();
4426 eassert (wait_proc == NULL
4427 || EQ (wait_proc->thread, Qnil)
4428 || XTHREAD (wait_proc->thread) == current_thread);
4430 FD_ZERO (&Available);
4431 FD_ZERO (&Writeok);
4433 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4434 && !(CONSP (wait_proc->status)
4435 && EQ (XCAR (wait_proc->status), Qexit)))
4436 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4438 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4439 if (wait_proc != NULL)
4440 wait_channel = wait_proc->infd;
4442 record_unwind_protect_int (wait_reading_process_output_unwind,
4443 waiting_for_user_input_p);
4444 waiting_for_user_input_p = read_kbd;
4446 if (time_limit < 0)
4448 time_limit = 0;
4449 nsecs = -1;
4451 else if (TYPE_MAXIMUM (time_t) < time_limit)
4452 time_limit = TYPE_MAXIMUM (time_t);
4454 /* Since we may need to wait several times,
4455 compute the absolute time to return at. */
4456 if (time_limit || nsecs > 0)
4458 timeout = make_emacs_time (time_limit, nsecs);
4459 end_time = add_emacs_time (current_emacs_time (), timeout);
4462 while (1)
4464 bool timeout_reduced_for_timers = 0;
4466 /* If calling from keyboard input, do not quit
4467 since we want to return C-g as an input character.
4468 Otherwise, do pending quit if requested. */
4469 if (read_kbd >= 0)
4470 QUIT;
4471 else if (pending_signals)
4472 process_pending_signals ();
4474 /* Exit now if the cell we're waiting for became non-nil. */
4475 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4476 break;
4478 /* Compute time from now till when time limit is up. */
4479 /* Exit if already run out. */
4480 if (nsecs < 0)
4482 /* A negative timeout means
4483 gobble output available now
4484 but don't wait at all. */
4486 timeout = make_emacs_time (0, 0);
4488 else if (time_limit || nsecs > 0)
4490 EMACS_TIME now = current_emacs_time ();
4491 if (EMACS_TIME_LE (end_time, now))
4492 break;
4493 timeout = sub_emacs_time (end_time, now);
4495 else
4497 timeout = make_emacs_time (100000, 0);
4500 /* Normally we run timers here.
4501 But not if wait_for_cell; in those cases,
4502 the wait is supposed to be short,
4503 and those callers cannot handle running arbitrary Lisp code here. */
4504 if (NILP (wait_for_cell)
4505 && just_wait_proc >= 0)
4507 EMACS_TIME timer_delay;
4511 unsigned old_timers_run = timers_run;
4512 struct buffer *old_buffer = current_buffer;
4513 Lisp_Object old_window = selected_window;
4515 timer_delay = timer_check ();
4517 /* If a timer has run, this might have changed buffers
4518 an alike. Make read_key_sequence aware of that. */
4519 if (timers_run != old_timers_run
4520 && (old_buffer != current_buffer
4521 || !EQ (old_window, selected_window))
4522 && waiting_for_user_input_p == -1)
4523 record_asynch_buffer_change ();
4525 if (timers_run != old_timers_run && do_display)
4526 /* We must retry, since a timer may have requeued itself
4527 and that could alter the time_delay. */
4528 redisplay_preserve_echo_area (9);
4529 else
4530 break;
4532 while (!detect_input_pending ());
4534 /* If there is unread keyboard input, also return. */
4535 if (read_kbd != 0
4536 && requeued_events_pending_p ())
4537 break;
4539 /* A negative timeout means do not wait at all. */
4540 if (nsecs >= 0)
4542 if (EMACS_TIME_VALID_P (timer_delay))
4544 if (EMACS_TIME_LT (timer_delay, timeout))
4546 timeout = timer_delay;
4547 timeout_reduced_for_timers = 1;
4550 else
4552 /* This is so a breakpoint can be put here. */
4553 wait_reading_process_output_1 ();
4558 /* Cause C-g and alarm signals to take immediate action,
4559 and cause input available signals to zero out timeout.
4561 It is important that we do this before checking for process
4562 activity. If we get a SIGCHLD after the explicit checks for
4563 process activity, timeout is the only way we will know. */
4564 if (read_kbd < 0)
4565 set_waiting_for_input (&timeout);
4567 /* If status of something has changed, and no input is
4568 available, notify the user of the change right away. After
4569 this explicit check, we'll let the SIGCHLD handler zap
4570 timeout to get our attention. */
4571 if (update_tick != process_tick)
4573 SELECT_TYPE Atemp;
4574 SELECT_TYPE Ctemp;
4576 if (kbd_on_hold_p ())
4577 FD_ZERO (&Atemp);
4578 else
4579 compute_input_wait_mask (&Atemp);
4580 compute_write_mask (&Ctemp);
4582 timeout = make_emacs_time (0, 0);
4583 if ((thread_select (pselect, max_desc + 1,
4584 &Atemp,
4585 #ifdef NON_BLOCKING_CONNECT
4586 (num_pending_connects > 0 ? &Ctemp : NULL),
4587 #else
4588 NULL,
4589 #endif
4590 NULL, &timeout, NULL)
4591 <= 0))
4593 /* It's okay for us to do this and then continue with
4594 the loop, since timeout has already been zeroed out. */
4595 clear_waiting_for_input ();
4596 status_notify (NULL);
4597 if (do_display) redisplay_preserve_echo_area (13);
4601 /* Don't wait for output from a non-running process. Just
4602 read whatever data has already been received. */
4603 if (wait_proc && wait_proc->raw_status_new)
4604 update_status (wait_proc);
4605 if (wait_proc
4606 && ! EQ (wait_proc->status, Qrun)
4607 && ! EQ (wait_proc->status, Qconnect))
4609 bool read_some_bytes = 0;
4611 clear_waiting_for_input ();
4612 XSETPROCESS (proc, wait_proc);
4614 /* Read data from the process, until we exhaust it. */
4615 while (wait_proc->infd >= 0)
4617 int nread = read_process_output (proc, wait_proc->infd);
4619 if (nread == 0)
4620 break;
4622 if (nread > 0)
4623 got_some_input = read_some_bytes = 1;
4624 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4625 break;
4626 #ifdef EWOULDBLOCK
4627 else if (nread == -1 && EWOULDBLOCK == errno)
4628 break;
4629 #endif
4631 if (read_some_bytes && do_display)
4632 redisplay_preserve_echo_area (10);
4634 break;
4637 /* Wait till there is something to do */
4639 if (wait_proc && just_wait_proc)
4641 if (wait_proc->infd < 0) /* Terminated */
4642 break;
4643 FD_SET (wait_proc->infd, &Available);
4644 check_delay = 0;
4645 check_write = 0;
4647 else if (!NILP (wait_for_cell))
4649 compute_non_process_wait_mask (&Available);
4650 check_delay = 0;
4651 check_write = 0;
4653 else
4655 if (! read_kbd)
4656 compute_non_keyboard_wait_mask (&Available);
4657 else
4658 compute_input_wait_mask (&Available);
4659 compute_write_mask (&Writeok);
4660 #ifdef SELECT_CANT_DO_WRITE_MASK
4661 check_write = 0;
4662 #else
4663 check_write = 1;
4664 #endif
4665 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4668 /* If frame size has changed or the window is newly mapped,
4669 redisplay now, before we start to wait. There is a race
4670 condition here; if a SIGIO arrives between now and the select
4671 and indicates that a frame is trashed, the select may block
4672 displaying a trashed screen. */
4673 if (frame_garbaged && do_display)
4675 clear_waiting_for_input ();
4676 redisplay_preserve_echo_area (11);
4677 if (read_kbd < 0)
4678 set_waiting_for_input (&timeout);
4681 /* Skip the `select' call if input is available and we're
4682 waiting for keyboard input or a cell change (which can be
4683 triggered by processing X events). In the latter case, set
4684 nfds to 1 to avoid breaking the loop. */
4685 no_avail = 0;
4686 if ((read_kbd || !NILP (wait_for_cell))
4687 && detect_input_pending ())
4689 nfds = read_kbd ? 0 : 1;
4690 no_avail = 1;
4693 if (!no_avail)
4696 #ifdef ADAPTIVE_READ_BUFFERING
4697 /* Set the timeout for adaptive read buffering if any
4698 process has non-zero read_output_skip and non-zero
4699 read_output_delay, and we are not reading output for a
4700 specific wait_channel. It is not executed if
4701 Vprocess_adaptive_read_buffering is nil. */
4702 if (process_output_skip && check_delay > 0)
4704 int nsecs = EMACS_NSECS (timeout);
4705 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4706 nsecs = READ_OUTPUT_DELAY_MAX;
4707 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
4709 proc = chan_process[channel];
4710 if (NILP (proc))
4711 continue;
4712 /* Find minimum non-zero read_output_delay among the
4713 processes with non-zero read_output_skip. */
4714 if (XPROCESS (proc)->read_output_delay > 0)
4716 check_delay--;
4717 if (!XPROCESS (proc)->read_output_skip)
4718 continue;
4719 FD_CLR (channel, &Available);
4720 XPROCESS (proc)->read_output_skip = 0;
4721 if (XPROCESS (proc)->read_output_delay < nsecs)
4722 nsecs = XPROCESS (proc)->read_output_delay;
4725 timeout = make_emacs_time (0, nsecs);
4726 process_output_skip = 0;
4728 #endif
4729 nfds = thread_select (
4730 #if defined (HAVE_NS)
4731 ns_select
4732 #elif defined (HAVE_GLIB)
4733 xg_select
4734 #else
4735 pselect
4736 #endif
4737 , max_desc + 1,
4738 &Available,
4739 (check_write ? &Writeok : 0),
4740 NULL, &timeout, NULL);
4742 #ifdef HAVE_GNUTLS
4743 /* GnuTLS buffers data internally. In lowat mode it leaves
4744 some data in the TCP buffers so that select works, but
4745 with custom pull/push functions we need to check if some
4746 data is available in the buffers manually. */
4747 if (nfds == 0)
4749 if (! wait_proc)
4751 /* We're not waiting on a specific process, so loop
4752 through all the channels and check for data.
4753 This is a workaround needed for some versions of
4754 the gnutls library -- 2.12.14 has been confirmed
4755 to need it. See
4756 http://comments.gmane.org/gmane.emacs.devel/145074 */
4757 for (channel = 0; channel < MAXDESC; ++channel)
4758 if (! NILP (chan_process[channel]))
4760 struct Lisp_Process *p =
4761 XPROCESS (chan_process[channel]);
4762 if (p && p->gnutls_p && p->infd
4763 && ((emacs_gnutls_record_check_pending
4764 (p->gnutls_state))
4765 > 0))
4767 nfds++;
4768 FD_SET (p->infd, &Available);
4772 else
4774 /* Check this specific channel. */
4775 if (wait_proc->gnutls_p /* Check for valid process. */
4776 /* Do we have pending data? */
4777 && ((emacs_gnutls_record_check_pending
4778 (wait_proc->gnutls_state))
4779 > 0))
4781 nfds = 1;
4782 /* Set to Available. */
4783 FD_SET (wait_proc->infd, &Available);
4787 #endif
4790 xerrno = errno;
4792 /* Make C-g and alarm signals set flags again */
4793 clear_waiting_for_input ();
4795 /* If we woke up due to SIGWINCH, actually change size now. */
4796 do_pending_window_change (0);
4798 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4799 /* We waited the full specified time, so return now. */
4800 break;
4801 if (nfds < 0)
4803 if (xerrno == EINTR)
4804 no_avail = 1;
4805 else if (xerrno == EBADF)
4806 emacs_abort ();
4807 else
4808 report_file_errno ("Failed select", Qnil, xerrno);
4811 if (no_avail)
4813 FD_ZERO (&Available);
4814 check_write = 0;
4817 /* Check for keyboard input */
4818 /* If there is any, return immediately
4819 to give it higher priority than subprocesses */
4821 if (read_kbd != 0)
4823 unsigned old_timers_run = timers_run;
4824 struct buffer *old_buffer = current_buffer;
4825 Lisp_Object old_window = selected_window;
4826 bool leave = 0;
4828 if (detect_input_pending_run_timers (do_display))
4830 swallow_events (do_display);
4831 if (detect_input_pending_run_timers (do_display))
4832 leave = 1;
4835 /* If a timer has run, this might have changed buffers
4836 an alike. Make read_key_sequence aware of that. */
4837 if (timers_run != old_timers_run
4838 && waiting_for_user_input_p == -1
4839 && (old_buffer != current_buffer
4840 || !EQ (old_window, selected_window)))
4841 record_asynch_buffer_change ();
4843 if (leave)
4844 break;
4847 /* If there is unread keyboard input, also return. */
4848 if (read_kbd != 0
4849 && requeued_events_pending_p ())
4850 break;
4852 /* If we are not checking for keyboard input now,
4853 do process events (but don't run any timers).
4854 This is so that X events will be processed.
4855 Otherwise they may have to wait until polling takes place.
4856 That would causes delays in pasting selections, for example.
4858 (We used to do this only if wait_for_cell.) */
4859 if (read_kbd == 0 && detect_input_pending ())
4861 swallow_events (do_display);
4862 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4863 if (detect_input_pending ())
4864 break;
4865 #endif
4868 /* Exit now if the cell we're waiting for became non-nil. */
4869 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4870 break;
4872 #ifdef USABLE_SIGIO
4873 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4874 go read it. This can happen with X on BSD after logging out.
4875 In that case, there really is no input and no SIGIO,
4876 but select says there is input. */
4878 if (read_kbd && interrupt_input
4879 && keyboard_bit_set (&Available) && ! noninteractive)
4880 handle_input_available_signal (SIGIO);
4881 #endif
4883 if (! wait_proc)
4884 got_some_input |= nfds > 0;
4886 /* If checking input just got us a size-change event from X,
4887 obey it now if we should. */
4888 if (read_kbd || ! NILP (wait_for_cell))
4889 do_pending_window_change (0);
4891 /* Check for data from a process. */
4892 if (no_avail || nfds == 0)
4893 continue;
4895 for (channel = 0; channel <= max_desc; ++channel)
4897 struct fd_callback_data *d = &fd_callback_info[channel];
4898 if (d->func
4899 && ((d->flags & FOR_READ
4900 && FD_ISSET (channel, &Available))
4901 || (d->flags & FOR_WRITE
4902 && FD_ISSET (channel, &Writeok))))
4903 d->func (channel, d->data);
4906 for (channel = 0; channel <= max_desc; channel++)
4908 if (FD_ISSET (channel, &Available)
4909 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
4910 == PROCESS_FD))
4912 int nread;
4914 /* If waiting for this channel, arrange to return as
4915 soon as no more input to be processed. No more
4916 waiting. */
4917 if (wait_channel == channel)
4919 wait_channel = -1;
4920 nsecs = -1;
4921 got_some_input = 1;
4923 proc = chan_process[channel];
4924 if (NILP (proc))
4925 continue;
4927 /* If this is a server stream socket, accept connection. */
4928 if (EQ (XPROCESS (proc)->status, Qlisten))
4930 server_accept_connection (proc, channel);
4931 continue;
4934 /* Read data from the process, starting with our
4935 buffered-ahead character if we have one. */
4937 nread = read_process_output (proc, channel);
4938 if (nread > 0)
4940 /* Since read_process_output can run a filter,
4941 which can call accept-process-output,
4942 don't try to read from any other processes
4943 before doing the select again. */
4944 FD_ZERO (&Available);
4946 if (do_display)
4947 redisplay_preserve_echo_area (12);
4949 #ifdef EWOULDBLOCK
4950 else if (nread == -1 && errno == EWOULDBLOCK)
4952 #endif
4953 else if (nread == -1 && errno == EAGAIN)
4955 #ifdef WINDOWSNT
4956 /* FIXME: Is this special case still needed? */
4957 /* Note that we cannot distinguish between no input
4958 available now and a closed pipe.
4959 With luck, a closed pipe will be accompanied by
4960 subprocess termination and SIGCHLD. */
4961 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4963 #endif
4964 #ifdef HAVE_PTYS
4965 /* On some OSs with ptys, when the process on one end of
4966 a pty exits, the other end gets an error reading with
4967 errno = EIO instead of getting an EOF (0 bytes read).
4968 Therefore, if we get an error reading and errno =
4969 EIO, just continue, because the child process has
4970 exited and should clean itself up soon (e.g. when we
4971 get a SIGCHLD). */
4972 else if (nread == -1 && errno == EIO)
4974 struct Lisp_Process *p = XPROCESS (proc);
4976 /* Clear the descriptor now, so we only raise the
4977 signal once. */
4978 delete_read_fd (channel);
4980 if (p->pid == -2)
4982 /* If the EIO occurs on a pty, the SIGCHLD handler's
4983 waitpid call will not find the process object to
4984 delete. Do it here. */
4985 p->tick = ++process_tick;
4986 pset_status (p, Qfailed);
4989 #endif /* HAVE_PTYS */
4990 /* If we can detect process termination, don't consider the
4991 process gone just because its pipe is closed. */
4992 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4994 else
4996 /* Preserve status of processes already terminated. */
4997 XPROCESS (proc)->tick = ++process_tick;
4998 deactivate_process (proc);
4999 if (XPROCESS (proc)->raw_status_new)
5000 update_status (XPROCESS (proc));
5001 if (EQ (XPROCESS (proc)->status, Qrun))
5002 pset_status (XPROCESS (proc),
5003 list2 (Qexit, make_number (256)));
5006 #ifdef NON_BLOCKING_CONNECT
5007 if (FD_ISSET (channel, &Writeok)
5008 && (fd_callback_info[channel].flags
5009 & NON_BLOCKING_CONNECT_FD) != 0)
5011 struct Lisp_Process *p;
5013 delete_write_fd (channel);
5015 proc = chan_process[channel];
5016 if (NILP (proc))
5017 continue;
5019 p = XPROCESS (proc);
5021 #ifdef GNU_LINUX
5022 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5023 So only use it on systems where it is known to work. */
5025 socklen_t xlen = sizeof (xerrno);
5026 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5027 xerrno = errno;
5029 #else
5031 struct sockaddr pname;
5032 int pnamelen = sizeof (pname);
5034 /* If connection failed, getpeername will fail. */
5035 xerrno = 0;
5036 if (getpeername (channel, &pname, &pnamelen) < 0)
5038 /* Obtain connect failure code through error slippage. */
5039 char dummy;
5040 xerrno = errno;
5041 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5042 xerrno = errno;
5045 #endif
5046 if (xerrno)
5048 p->tick = ++process_tick;
5049 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5050 deactivate_process (proc);
5052 else
5054 pset_status (p, Qrun);
5055 /* Execute the sentinel here. If we had relied on
5056 status_notify to do it later, it will read input
5057 from the process before calling the sentinel. */
5058 exec_sentinel (proc, build_string ("open\n"));
5059 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5060 delete_read_fd (p->infd);
5063 #endif /* NON_BLOCKING_CONNECT */
5064 } /* End for each file descriptor. */
5065 } /* End while exit conditions not met. */
5067 unbind_to (count, Qnil);
5069 /* If calling from keyboard input, do not quit
5070 since we want to return C-g as an input character.
5071 Otherwise, do pending quit if requested. */
5072 if (read_kbd >= 0)
5074 /* Prevent input_pending from remaining set if we quit. */
5075 clear_input_pending ();
5076 QUIT;
5079 return got_some_input;
5082 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5084 static Lisp_Object
5085 read_process_output_call (Lisp_Object fun_and_args)
5087 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5090 static Lisp_Object
5091 read_process_output_error_handler (Lisp_Object error_val)
5093 cmd_error_internal (error_val, "error in process filter: ");
5094 Vinhibit_quit = Qt;
5095 update_echo_area ();
5096 Fsleep_for (make_number (2), Qnil);
5097 return Qt;
5100 static void
5101 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5102 ssize_t nbytes,
5103 struct coding_system *coding);
5105 /* Read pending output from the process channel,
5106 starting with our buffered-ahead character if we have one.
5107 Yield number of decoded characters read.
5109 This function reads at most 4096 characters.
5110 If you want to read all available subprocess output,
5111 you must call it repeatedly until it returns zero.
5113 The characters read are decoded according to PROC's coding-system
5114 for decoding. */
5116 static int
5117 read_process_output (Lisp_Object proc, register int channel)
5119 register ssize_t nbytes;
5120 char *chars;
5121 register struct Lisp_Process *p = XPROCESS (proc);
5122 struct coding_system *coding = proc_decode_coding_system[channel];
5123 int carryover = p->decoding_carryover;
5124 int readmax = 4096;
5125 ptrdiff_t count = SPECPDL_INDEX ();
5126 Lisp_Object odeactivate;
5128 chars = alloca (carryover + readmax);
5129 if (carryover)
5130 /* See the comment above. */
5131 memcpy (chars, SDATA (p->decoding_buf), carryover);
5133 #ifdef DATAGRAM_SOCKETS
5134 /* We have a working select, so proc_buffered_char is always -1. */
5135 if (DATAGRAM_CHAN_P (channel))
5137 socklen_t len = datagram_address[channel].len;
5138 nbytes = recvfrom (channel, chars + carryover, readmax,
5139 0, datagram_address[channel].sa, &len);
5141 else
5142 #endif
5144 bool buffered = proc_buffered_char[channel] >= 0;
5145 if (buffered)
5147 chars[carryover] = proc_buffered_char[channel];
5148 proc_buffered_char[channel] = -1;
5150 #ifdef HAVE_GNUTLS
5151 if (p->gnutls_p)
5152 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5153 readmax - buffered);
5154 else
5155 #endif
5156 nbytes = emacs_read (channel, chars + carryover + buffered,
5157 readmax - buffered);
5158 #ifdef ADAPTIVE_READ_BUFFERING
5159 if (nbytes > 0 && p->adaptive_read_buffering)
5161 int delay = p->read_output_delay;
5162 if (nbytes < 256)
5164 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5166 if (delay == 0)
5167 process_output_delay_count++;
5168 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5171 else if (delay > 0 && nbytes == readmax - buffered)
5173 delay -= READ_OUTPUT_DELAY_INCREMENT;
5174 if (delay == 0)
5175 process_output_delay_count--;
5177 p->read_output_delay = delay;
5178 if (delay)
5180 p->read_output_skip = 1;
5181 process_output_skip = 1;
5184 #endif
5185 nbytes += buffered;
5186 nbytes += buffered && nbytes <= 0;
5189 p->decoding_carryover = 0;
5191 /* At this point, NBYTES holds number of bytes just received
5192 (including the one in proc_buffered_char[channel]). */
5193 if (nbytes <= 0)
5195 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5196 return nbytes;
5197 coding->mode |= CODING_MODE_LAST_BLOCK;
5200 /* Now set NBYTES how many bytes we must decode. */
5201 nbytes += carryover;
5203 odeactivate = Vdeactivate_mark;
5204 /* There's no good reason to let process filters change the current
5205 buffer, and many callers of accept-process-output, sit-for, and
5206 friends don't expect current-buffer to be changed from under them. */
5207 record_unwind_current_buffer ();
5209 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5211 /* Handling the process output should not deactivate the mark. */
5212 Vdeactivate_mark = odeactivate;
5214 unbind_to (count, Qnil);
5215 return nbytes;
5218 static void
5219 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5220 ssize_t nbytes,
5221 struct coding_system *coding)
5223 Lisp_Object outstream = p->filter;
5224 Lisp_Object text;
5225 bool outer_running_asynch_code = running_asynch_code;
5226 int waiting = waiting_for_user_input_p;
5228 /* No need to gcpro these, because all we do with them later
5229 is test them for EQness, and none of them should be a string. */
5230 #if 0
5231 Lisp_Object obuffer, okeymap;
5232 XSETBUFFER (obuffer, current_buffer);
5233 okeymap = BVAR (current_buffer, keymap);
5234 #endif
5236 /* We inhibit quit here instead of just catching it so that
5237 hitting ^G when a filter happens to be running won't screw
5238 it up. */
5239 specbind (Qinhibit_quit, Qt);
5240 specbind (Qlast_nonmenu_event, Qt);
5242 /* In case we get recursively called,
5243 and we already saved the match data nonrecursively,
5244 save the same match data in safely recursive fashion. */
5245 if (outer_running_asynch_code)
5247 Lisp_Object tem;
5248 /* Don't clobber the CURRENT match data, either! */
5249 tem = Fmatch_data (Qnil, Qnil, Qnil);
5250 restore_search_regs ();
5251 record_unwind_save_match_data ();
5252 Fset_match_data (tem, Qt);
5255 /* For speed, if a search happens within this code,
5256 save the match data in a special nonrecursive fashion. */
5257 running_asynch_code = 1;
5259 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5260 text = coding->dst_object;
5261 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5262 /* A new coding system might be found. */
5263 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5265 pset_decode_coding_system (p, Vlast_coding_system_used);
5267 /* Don't call setup_coding_system for
5268 proc_decode_coding_system[channel] here. It is done in
5269 detect_coding called via decode_coding above. */
5271 /* If a coding system for encoding is not yet decided, we set
5272 it as the same as coding-system for decoding.
5274 But, before doing that we must check if
5275 proc_encode_coding_system[p->outfd] surely points to a
5276 valid memory because p->outfd will be changed once EOF is
5277 sent to the process. */
5278 if (NILP (p->encode_coding_system)
5279 && proc_encode_coding_system[p->outfd])
5281 pset_encode_coding_system
5282 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5283 setup_coding_system (p->encode_coding_system,
5284 proc_encode_coding_system[p->outfd]);
5288 if (coding->carryover_bytes > 0)
5290 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5291 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5292 memcpy (SDATA (p->decoding_buf), coding->carryover,
5293 coding->carryover_bytes);
5294 p->decoding_carryover = coding->carryover_bytes;
5296 if (SBYTES (text) > 0)
5297 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5298 sometimes it's simply wrong to wrap (e.g. when called from
5299 accept-process-output). */
5300 internal_condition_case_1 (read_process_output_call,
5301 list3 (outstream, make_lisp_proc (p), text),
5302 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5303 read_process_output_error_handler);
5305 /* If we saved the match data nonrecursively, restore it now. */
5306 restore_search_regs ();
5307 running_asynch_code = outer_running_asynch_code;
5309 /* Restore waiting_for_user_input_p as it was
5310 when we were called, in case the filter clobbered it. */
5311 waiting_for_user_input_p = waiting;
5313 #if 0 /* Call record_asynch_buffer_change unconditionally,
5314 because we might have changed minor modes or other things
5315 that affect key bindings. */
5316 if (! EQ (Fcurrent_buffer (), obuffer)
5317 || ! EQ (current_buffer->keymap, okeymap))
5318 #endif
5319 /* But do it only if the caller is actually going to read events.
5320 Otherwise there's no need to make him wake up, and it could
5321 cause trouble (for example it would make sit_for return). */
5322 if (waiting_for_user_input_p == -1)
5323 record_asynch_buffer_change ();
5326 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5327 Sinternal_default_process_filter, 2, 2, 0,
5328 doc: /* Function used as default process filter. */)
5329 (Lisp_Object proc, Lisp_Object text)
5331 struct Lisp_Process *p;
5332 ptrdiff_t opoint;
5334 CHECK_PROCESS (proc);
5335 p = XPROCESS (proc);
5336 CHECK_STRING (text);
5338 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5340 Lisp_Object old_read_only;
5341 ptrdiff_t old_begv, old_zv;
5342 ptrdiff_t old_begv_byte, old_zv_byte;
5343 ptrdiff_t before, before_byte;
5344 ptrdiff_t opoint_byte;
5345 struct buffer *b;
5347 Fset_buffer (p->buffer);
5348 opoint = PT;
5349 opoint_byte = PT_BYTE;
5350 old_read_only = BVAR (current_buffer, read_only);
5351 old_begv = BEGV;
5352 old_zv = ZV;
5353 old_begv_byte = BEGV_BYTE;
5354 old_zv_byte = ZV_BYTE;
5356 bset_read_only (current_buffer, Qnil);
5358 /* Insert new output into buffer
5359 at the current end-of-output marker,
5360 thus preserving logical ordering of input and output. */
5361 if (XMARKER (p->mark)->buffer)
5362 SET_PT_BOTH (clip_to_bounds (BEGV,
5363 marker_position (p->mark), ZV),
5364 clip_to_bounds (BEGV_BYTE,
5365 marker_byte_position (p->mark),
5366 ZV_BYTE));
5367 else
5368 SET_PT_BOTH (ZV, ZV_BYTE);
5369 before = PT;
5370 before_byte = PT_BYTE;
5372 /* If the output marker is outside of the visible region, save
5373 the restriction and widen. */
5374 if (! (BEGV <= PT && PT <= ZV))
5375 Fwiden ();
5377 /* Adjust the multibyteness of TEXT to that of the buffer. */
5378 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5379 != ! STRING_MULTIBYTE (text))
5380 text = (STRING_MULTIBYTE (text)
5381 ? Fstring_as_unibyte (text)
5382 : Fstring_to_multibyte (text));
5383 /* Insert before markers in case we are inserting where
5384 the buffer's mark is, and the user's next command is Meta-y. */
5385 insert_from_string_before_markers (text, 0, 0,
5386 SCHARS (text), SBYTES (text), 0);
5388 /* Make sure the process marker's position is valid when the
5389 process buffer is changed in the signal_after_change above.
5390 W3 is known to do that. */
5391 if (BUFFERP (p->buffer)
5392 && (b = XBUFFER (p->buffer), b != current_buffer))
5393 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5394 else
5395 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5397 update_mode_lines++;
5399 /* Make sure opoint and the old restrictions
5400 float ahead of any new text just as point would. */
5401 if (opoint >= before)
5403 opoint += PT - before;
5404 opoint_byte += PT_BYTE - before_byte;
5406 if (old_begv > before)
5408 old_begv += PT - before;
5409 old_begv_byte += PT_BYTE - before_byte;
5411 if (old_zv >= before)
5413 old_zv += PT - before;
5414 old_zv_byte += PT_BYTE - before_byte;
5417 /* If the restriction isn't what it should be, set it. */
5418 if (old_begv != BEGV || old_zv != ZV)
5419 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5421 bset_read_only (current_buffer, old_read_only);
5422 SET_PT_BOTH (opoint, opoint_byte);
5424 return Qnil;
5427 /* Sending data to subprocess. */
5429 /* In send_process, when a write fails temporarily,
5430 wait_reading_process_output is called. It may execute user code,
5431 e.g. timers, that attempts to write new data to the same process.
5432 We must ensure that data is sent in the right order, and not
5433 interspersed half-completed with other writes (Bug#10815). This is
5434 handled by the write_queue element of struct process. It is a list
5435 with each entry having the form
5437 (string . (offset . length))
5439 where STRING is a lisp string, OFFSET is the offset into the
5440 string's byte sequence from which we should begin to send, and
5441 LENGTH is the number of bytes left to send. */
5443 /* Create a new entry in write_queue.
5444 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5445 BUF is a pointer to the string sequence of the input_obj or a C
5446 string in case of Qt or Qnil. */
5448 static void
5449 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5450 const char *buf, ptrdiff_t len, bool front)
5452 ptrdiff_t offset;
5453 Lisp_Object entry, obj;
5455 if (STRINGP (input_obj))
5457 offset = buf - SSDATA (input_obj);
5458 obj = input_obj;
5460 else
5462 offset = 0;
5463 obj = make_unibyte_string (buf, len);
5466 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5468 if (front)
5469 pset_write_queue (p, Fcons (entry, p->write_queue));
5470 else
5471 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5474 /* Remove the first element in the write_queue of process P, put its
5475 contents in OBJ, BUF and LEN, and return true. If the
5476 write_queue is empty, return false. */
5478 static bool
5479 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5480 const char **buf, ptrdiff_t *len)
5482 Lisp_Object entry, offset_length;
5483 ptrdiff_t offset;
5485 if (NILP (p->write_queue))
5486 return 0;
5488 entry = XCAR (p->write_queue);
5489 pset_write_queue (p, XCDR (p->write_queue));
5491 *obj = XCAR (entry);
5492 offset_length = XCDR (entry);
5494 *len = XINT (XCDR (offset_length));
5495 offset = XINT (XCAR (offset_length));
5496 *buf = SSDATA (*obj) + offset;
5498 return 1;
5501 /* Send some data to process PROC.
5502 BUF is the beginning of the data; LEN is the number of characters.
5503 OBJECT is the Lisp object that the data comes from. If OBJECT is
5504 nil or t, it means that the data comes from C string.
5506 If OBJECT is not nil, the data is encoded by PROC's coding-system
5507 for encoding before it is sent.
5509 This function can evaluate Lisp code and can garbage collect. */
5511 static void
5512 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5513 Lisp_Object object)
5515 struct Lisp_Process *p = XPROCESS (proc);
5516 ssize_t rv;
5517 struct coding_system *coding;
5519 if (p->raw_status_new)
5520 update_status (p);
5521 if (! EQ (p->status, Qrun))
5522 error ("Process %s not running", SDATA (p->name));
5523 if (p->outfd < 0)
5524 error ("Output file descriptor of %s is closed", SDATA (p->name));
5526 coding = proc_encode_coding_system[p->outfd];
5527 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5529 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5530 || (BUFFERP (object)
5531 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5532 || EQ (object, Qt))
5534 pset_encode_coding_system
5535 (p, complement_process_encoding_system (p->encode_coding_system));
5536 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5538 /* The coding system for encoding was changed to raw-text
5539 because we sent a unibyte text previously. Now we are
5540 sending a multibyte text, thus we must encode it by the
5541 original coding system specified for the current process.
5543 Another reason we come here is that the coding system
5544 was just complemented and a new one was returned by
5545 complement_process_encoding_system. */
5546 setup_coding_system (p->encode_coding_system, coding);
5547 Vlast_coding_system_used = p->encode_coding_system;
5549 coding->src_multibyte = 1;
5551 else
5553 coding->src_multibyte = 0;
5554 /* For sending a unibyte text, character code conversion should
5555 not take place but EOL conversion should. So, setup raw-text
5556 or one of the subsidiary if we have not yet done it. */
5557 if (CODING_REQUIRE_ENCODING (coding))
5559 if (CODING_REQUIRE_FLUSHING (coding))
5561 /* But, before changing the coding, we must flush out data. */
5562 coding->mode |= CODING_MODE_LAST_BLOCK;
5563 send_process (proc, "", 0, Qt);
5564 coding->mode &= CODING_MODE_LAST_BLOCK;
5566 setup_coding_system (raw_text_coding_system
5567 (Vlast_coding_system_used),
5568 coding);
5569 coding->src_multibyte = 0;
5572 coding->dst_multibyte = 0;
5574 if (CODING_REQUIRE_ENCODING (coding))
5576 coding->dst_object = Qt;
5577 if (BUFFERP (object))
5579 ptrdiff_t from_byte, from, to;
5580 ptrdiff_t save_pt, save_pt_byte;
5581 struct buffer *cur = current_buffer;
5583 set_buffer_internal (XBUFFER (object));
5584 save_pt = PT, save_pt_byte = PT_BYTE;
5586 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5587 from = BYTE_TO_CHAR (from_byte);
5588 to = BYTE_TO_CHAR (from_byte + len);
5589 TEMP_SET_PT_BOTH (from, from_byte);
5590 encode_coding_object (coding, object, from, from_byte,
5591 to, from_byte + len, Qt);
5592 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5593 set_buffer_internal (cur);
5595 else if (STRINGP (object))
5597 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5598 SBYTES (object), Qt);
5600 else
5602 coding->dst_object = make_unibyte_string (buf, len);
5603 coding->produced = len;
5606 len = coding->produced;
5607 object = coding->dst_object;
5608 buf = SSDATA (object);
5611 /* If there is already data in the write_queue, put the new data
5612 in the back of queue. Otherwise, ignore it. */
5613 if (!NILP (p->write_queue))
5614 write_queue_push (p, object, buf, len, 0);
5616 do /* while !NILP (p->write_queue) */
5618 ptrdiff_t cur_len = -1;
5619 const char *cur_buf;
5620 Lisp_Object cur_object;
5622 /* If write_queue is empty, ignore it. */
5623 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5625 cur_len = len;
5626 cur_buf = buf;
5627 cur_object = object;
5630 while (cur_len > 0)
5632 /* Send this batch, using one or more write calls. */
5633 ptrdiff_t written = 0;
5634 int outfd = p->outfd;
5635 #ifdef DATAGRAM_SOCKETS
5636 if (DATAGRAM_CHAN_P (outfd))
5638 rv = sendto (outfd, cur_buf, cur_len,
5639 0, datagram_address[outfd].sa,
5640 datagram_address[outfd].len);
5641 if (rv >= 0)
5642 written = rv;
5643 else if (errno == EMSGSIZE)
5644 report_file_error ("Sending datagram", proc);
5646 else
5647 #endif
5649 #ifdef HAVE_GNUTLS
5650 if (p->gnutls_p)
5651 written = emacs_gnutls_write (p, cur_buf, cur_len);
5652 else
5653 #endif
5654 written = emacs_write_sig (outfd, cur_buf, cur_len);
5655 rv = (written ? 0 : -1);
5656 #ifdef ADAPTIVE_READ_BUFFERING
5657 if (p->read_output_delay > 0
5658 && p->adaptive_read_buffering == 1)
5660 p->read_output_delay = 0;
5661 process_output_delay_count--;
5662 p->read_output_skip = 0;
5664 #endif
5667 if (rv < 0)
5669 if (errno == EAGAIN
5670 #ifdef EWOULDBLOCK
5671 || errno == EWOULDBLOCK
5672 #endif
5674 /* Buffer is full. Wait, accepting input;
5675 that may allow the program
5676 to finish doing output and read more. */
5678 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5679 /* A gross hack to work around a bug in FreeBSD.
5680 In the following sequence, read(2) returns
5681 bogus data:
5683 write(2) 1022 bytes
5684 write(2) 954 bytes, get EAGAIN
5685 read(2) 1024 bytes in process_read_output
5686 read(2) 11 bytes in process_read_output
5688 That is, read(2) returns more bytes than have
5689 ever been written successfully. The 1033 bytes
5690 read are the 1022 bytes written successfully
5691 after processing (for example with CRs added if
5692 the terminal is set up that way which it is
5693 here). The same bytes will be seen again in a
5694 later read(2), without the CRs. */
5696 if (errno == EAGAIN)
5698 int flags = FWRITE;
5699 ioctl (p->outfd, TIOCFLUSH, &flags);
5701 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5703 /* Put what we should have written in wait_queue. */
5704 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5705 wait_reading_process_output (0, 20 * 1000 * 1000,
5706 0, 0, Qnil, NULL, 0);
5707 /* Reread queue, to see what is left. */
5708 break;
5710 else if (errno == EPIPE)
5712 p->raw_status_new = 0;
5713 pset_status (p, list2 (Qexit, make_number (256)));
5714 p->tick = ++process_tick;
5715 deactivate_process (proc);
5716 error ("process %s no longer connected to pipe; closed it",
5717 SDATA (p->name));
5719 else
5720 /* This is a real error. */
5721 report_file_error ("Writing to process", proc);
5723 cur_buf += written;
5724 cur_len -= written;
5727 while (!NILP (p->write_queue));
5730 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5731 3, 3, 0,
5732 doc: /* Send current contents of region as input to PROCESS.
5733 PROCESS may be a process, a buffer, the name of a process or buffer, or
5734 nil, indicating the current buffer's process.
5735 Called from program, takes three arguments, PROCESS, START and END.
5736 If the region is more than 500 characters long,
5737 it is sent in several bunches. This may happen even for shorter regions.
5738 Output from processes can arrive in between bunches. */)
5739 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5741 Lisp_Object proc = get_process (process);
5742 ptrdiff_t start_byte, end_byte;
5744 validate_region (&start, &end);
5746 start_byte = CHAR_TO_BYTE (XINT (start));
5747 end_byte = CHAR_TO_BYTE (XINT (end));
5749 if (XINT (start) < GPT && XINT (end) > GPT)
5750 move_gap_both (XINT (start), start_byte);
5752 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5753 end_byte - start_byte, Fcurrent_buffer ());
5755 return Qnil;
5758 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5759 2, 2, 0,
5760 doc: /* Send PROCESS the contents of STRING as input.
5761 PROCESS may be a process, a buffer, the name of a process or buffer, or
5762 nil, indicating the current buffer's process.
5763 If STRING is more than 500 characters long,
5764 it is sent in several bunches. This may happen even for shorter strings.
5765 Output from processes can arrive in between bunches. */)
5766 (Lisp_Object process, Lisp_Object string)
5768 Lisp_Object proc;
5769 CHECK_STRING (string);
5770 proc = get_process (process);
5771 send_process (proc, SSDATA (string),
5772 SBYTES (string), string);
5773 return Qnil;
5776 /* Return the foreground process group for the tty/pty that
5777 the process P uses. */
5778 static pid_t
5779 emacs_get_tty_pgrp (struct Lisp_Process *p)
5781 pid_t gid = -1;
5783 #ifdef TIOCGPGRP
5784 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5786 int fd;
5787 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5788 master side. Try the slave side. */
5789 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5791 if (fd != -1)
5793 ioctl (fd, TIOCGPGRP, &gid);
5794 emacs_close (fd);
5797 #endif /* defined (TIOCGPGRP ) */
5799 return gid;
5802 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5803 Sprocess_running_child_p, 0, 1, 0,
5804 doc: /* Return t if PROCESS has given the terminal to a child.
5805 If the operating system does not make it possible to find out,
5806 return t unconditionally. */)
5807 (Lisp_Object process)
5809 /* Initialize in case ioctl doesn't exist or gives an error,
5810 in a way that will cause returning t. */
5811 pid_t gid;
5812 Lisp_Object proc;
5813 struct Lisp_Process *p;
5815 proc = get_process (process);
5816 p = XPROCESS (proc);
5818 if (!EQ (p->type, Qreal))
5819 error ("Process %s is not a subprocess",
5820 SDATA (p->name));
5821 if (p->infd < 0)
5822 error ("Process %s is not active",
5823 SDATA (p->name));
5825 gid = emacs_get_tty_pgrp (p);
5827 if (gid == p->pid)
5828 return Qnil;
5829 return Qt;
5832 /* send a signal number SIGNO to PROCESS.
5833 If CURRENT_GROUP is t, that means send to the process group
5834 that currently owns the terminal being used to communicate with PROCESS.
5835 This is used for various commands in shell mode.
5836 If CURRENT_GROUP is lambda, that means send to the process group
5837 that currently owns the terminal, but only if it is NOT the shell itself.
5839 If NOMSG is false, insert signal-announcements into process's buffers
5840 right away.
5842 If we can, we try to signal PROCESS by sending control characters
5843 down the pty. This allows us to signal inferiors who have changed
5844 their uid, for which kill would return an EPERM error. */
5846 static void
5847 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5848 bool nomsg)
5850 Lisp_Object proc;
5851 struct Lisp_Process *p;
5852 pid_t gid;
5853 bool no_pgrp = 0;
5855 proc = get_process (process);
5856 p = XPROCESS (proc);
5858 if (!EQ (p->type, Qreal))
5859 error ("Process %s is not a subprocess",
5860 SDATA (p->name));
5861 if (p->infd < 0)
5862 error ("Process %s is not active",
5863 SDATA (p->name));
5865 if (!p->pty_flag)
5866 current_group = Qnil;
5868 /* If we are using pgrps, get a pgrp number and make it negative. */
5869 if (NILP (current_group))
5870 /* Send the signal to the shell's process group. */
5871 gid = p->pid;
5872 else
5874 #ifdef SIGNALS_VIA_CHARACTERS
5875 /* If possible, send signals to the entire pgrp
5876 by sending an input character to it. */
5878 struct termios t;
5879 cc_t *sig_char = NULL;
5881 tcgetattr (p->infd, &t);
5883 switch (signo)
5885 case SIGINT:
5886 sig_char = &t.c_cc[VINTR];
5887 break;
5889 case SIGQUIT:
5890 sig_char = &t.c_cc[VQUIT];
5891 break;
5893 case SIGTSTP:
5894 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5895 sig_char = &t.c_cc[VSWTCH];
5896 #else
5897 sig_char = &t.c_cc[VSUSP];
5898 #endif
5899 break;
5902 if (sig_char && *sig_char != CDISABLE)
5904 send_process (proc, (char *) sig_char, 1, Qnil);
5905 return;
5907 /* If we can't send the signal with a character,
5908 fall through and send it another way. */
5910 /* The code above may fall through if it can't
5911 handle the signal. */
5912 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5914 #ifdef TIOCGPGRP
5915 /* Get the current pgrp using the tty itself, if we have that.
5916 Otherwise, use the pty to get the pgrp.
5917 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5918 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5919 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5920 His patch indicates that if TIOCGPGRP returns an error, then
5921 we should just assume that p->pid is also the process group id. */
5923 gid = emacs_get_tty_pgrp (p);
5925 if (gid == -1)
5926 /* If we can't get the information, assume
5927 the shell owns the tty. */
5928 gid = p->pid;
5930 /* It is not clear whether anything really can set GID to -1.
5931 Perhaps on some system one of those ioctls can or could do so.
5932 Or perhaps this is vestigial. */
5933 if (gid == -1)
5934 no_pgrp = 1;
5935 #else /* ! defined (TIOCGPGRP ) */
5936 /* Can't select pgrps on this system, so we know that
5937 the child itself heads the pgrp. */
5938 gid = p->pid;
5939 #endif /* ! defined (TIOCGPGRP ) */
5941 /* If current_group is lambda, and the shell owns the terminal,
5942 don't send any signal. */
5943 if (EQ (current_group, Qlambda) && gid == p->pid)
5944 return;
5947 switch (signo)
5949 #ifdef SIGCONT
5950 case SIGCONT:
5951 p->raw_status_new = 0;
5952 pset_status (p, Qrun);
5953 p->tick = ++process_tick;
5954 if (!nomsg)
5956 status_notify (NULL);
5957 redisplay_preserve_echo_area (13);
5959 break;
5960 #endif /* ! defined (SIGCONT) */
5961 case SIGINT:
5962 case SIGQUIT:
5963 case SIGKILL:
5964 flush_pending_output (p->infd);
5965 break;
5968 /* If we don't have process groups, send the signal to the immediate
5969 subprocess. That isn't really right, but it's better than any
5970 obvious alternative. */
5971 if (no_pgrp)
5973 kill (p->pid, signo);
5974 return;
5977 /* gid may be a pid, or minus a pgrp's number */
5978 #ifdef TIOCSIGSEND
5979 if (!NILP (current_group))
5981 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5982 kill (-gid, signo);
5984 else
5986 gid = - p->pid;
5987 kill (gid, signo);
5989 #else /* ! defined (TIOCSIGSEND) */
5990 kill (-gid, signo);
5991 #endif /* ! defined (TIOCSIGSEND) */
5994 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5995 doc: /* Interrupt process PROCESS.
5996 PROCESS may be a process, a buffer, or the name of a process or buffer.
5997 No arg or nil means current buffer's process.
5998 Second arg CURRENT-GROUP non-nil means send signal to
5999 the current process-group of the process's controlling terminal
6000 rather than to the process's own process group.
6001 If the process is a shell, this means interrupt current subjob
6002 rather than the shell.
6004 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6005 don't send the signal. */)
6006 (Lisp_Object process, Lisp_Object current_group)
6008 process_send_signal (process, SIGINT, current_group, 0);
6009 return process;
6012 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6013 doc: /* Kill process PROCESS. May be process or name of one.
6014 See function `interrupt-process' for more details on usage. */)
6015 (Lisp_Object process, Lisp_Object current_group)
6017 process_send_signal (process, SIGKILL, current_group, 0);
6018 return process;
6021 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6022 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6023 See function `interrupt-process' for more details on usage. */)
6024 (Lisp_Object process, Lisp_Object current_group)
6026 process_send_signal (process, SIGQUIT, current_group, 0);
6027 return process;
6030 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6031 doc: /* Stop process PROCESS. May be process or name of one.
6032 See function `interrupt-process' for more details on usage.
6033 If PROCESS is a network or serial process, inhibit handling of incoming
6034 traffic. */)
6035 (Lisp_Object process, Lisp_Object current_group)
6037 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6039 struct Lisp_Process *p;
6041 p = XPROCESS (process);
6042 if (NILP (p->command)
6043 && p->infd >= 0)
6044 delete_read_fd (p->infd);
6045 pset_command (p, Qt);
6046 return process;
6048 #ifndef SIGTSTP
6049 error ("No SIGTSTP support");
6050 #else
6051 process_send_signal (process, SIGTSTP, current_group, 0);
6052 #endif
6053 return process;
6056 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6057 doc: /* Continue process PROCESS. May be process or name of one.
6058 See function `interrupt-process' for more details on usage.
6059 If PROCESS is a network or serial process, resume handling of incoming
6060 traffic. */)
6061 (Lisp_Object process, Lisp_Object current_group)
6063 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6065 struct Lisp_Process *p;
6067 p = XPROCESS (process);
6068 if (EQ (p->command, Qt)
6069 && p->infd >= 0
6070 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6072 add_non_keyboard_read_fd (p->infd);
6073 #ifdef WINDOWSNT
6074 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6075 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6076 #else /* not WINDOWSNT */
6077 tcflush (p->infd, TCIFLUSH);
6078 #endif /* not WINDOWSNT */
6080 pset_command (p, Qnil);
6081 return process;
6083 #ifdef SIGCONT
6084 process_send_signal (process, SIGCONT, current_group, 0);
6085 #else
6086 error ("No SIGCONT support");
6087 #endif
6088 return process;
6091 /* Return the integer value of the signal whose abbreviation is ABBR,
6092 or a negative number if there is no such signal. */
6093 static int
6094 abbr_to_signal (char const *name)
6096 int i, signo;
6097 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6099 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6100 name += 3;
6102 for (i = 0; i < sizeof sigbuf; i++)
6104 sigbuf[i] = c_toupper (name[i]);
6105 if (! sigbuf[i])
6106 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6109 return -1;
6112 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6113 2, 2, "sProcess (name or number): \nnSignal code: ",
6114 doc: /* Send PROCESS the signal with code SIGCODE.
6115 PROCESS may also be a number specifying the process id of the
6116 process to signal; in this case, the process need not be a child of
6117 this Emacs.
6118 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6119 (Lisp_Object process, Lisp_Object sigcode)
6121 pid_t pid;
6122 int signo;
6124 if (STRINGP (process))
6126 Lisp_Object tem = Fget_process (process);
6127 if (NILP (tem))
6129 Lisp_Object process_number =
6130 string_to_number (SSDATA (process), 10, 1);
6131 if (INTEGERP (process_number) || FLOATP (process_number))
6132 tem = process_number;
6134 process = tem;
6136 else if (!NUMBERP (process))
6137 process = get_process (process);
6139 if (NILP (process))
6140 return process;
6142 if (NUMBERP (process))
6143 CONS_TO_INTEGER (process, pid_t, pid);
6144 else
6146 CHECK_PROCESS (process);
6147 pid = XPROCESS (process)->pid;
6148 if (pid <= 0)
6149 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6152 if (INTEGERP (sigcode))
6154 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6155 signo = XINT (sigcode);
6157 else
6159 char *name;
6161 CHECK_SYMBOL (sigcode);
6162 name = SSDATA (SYMBOL_NAME (sigcode));
6164 signo = abbr_to_signal (name);
6165 if (signo < 0)
6166 error ("Undefined signal name %s", name);
6169 return make_number (kill (pid, signo));
6172 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6173 doc: /* Make PROCESS see end-of-file in its input.
6174 EOF comes after any text already sent to it.
6175 PROCESS may be a process, a buffer, the name of a process or buffer, or
6176 nil, indicating the current buffer's process.
6177 If PROCESS is a network connection, or is a process communicating
6178 through a pipe (as opposed to a pty), then you cannot send any more
6179 text to PROCESS after you call this function.
6180 If PROCESS is a serial process, wait until all output written to the
6181 process has been transmitted to the serial port. */)
6182 (Lisp_Object process)
6184 Lisp_Object proc;
6185 struct coding_system *coding;
6187 if (DATAGRAM_CONN_P (process))
6188 return process;
6190 proc = get_process (process);
6191 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6193 /* Make sure the process is really alive. */
6194 if (XPROCESS (proc)->raw_status_new)
6195 update_status (XPROCESS (proc));
6196 if (! EQ (XPROCESS (proc)->status, Qrun))
6197 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6199 if (CODING_REQUIRE_FLUSHING (coding))
6201 coding->mode |= CODING_MODE_LAST_BLOCK;
6202 send_process (proc, "", 0, Qnil);
6205 if (XPROCESS (proc)->pty_flag)
6206 send_process (proc, "\004", 1, Qnil);
6207 else if (EQ (XPROCESS (proc)->type, Qserial))
6209 #ifndef WINDOWSNT
6210 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6211 report_file_error ("Failed tcdrain", Qnil);
6212 #endif /* not WINDOWSNT */
6213 /* Do nothing on Windows because writes are blocking. */
6215 else
6217 int old_outfd = XPROCESS (proc)->outfd;
6218 int new_outfd;
6220 #ifdef HAVE_SHUTDOWN
6221 /* If this is a network connection, or socketpair is used
6222 for communication with the subprocess, call shutdown to cause EOF.
6223 (In some old system, shutdown to socketpair doesn't work.
6224 Then we just can't win.) */
6225 if (EQ (XPROCESS (proc)->type, Qnetwork)
6226 || XPROCESS (proc)->infd == old_outfd)
6227 shutdown (old_outfd, 1);
6228 #endif
6229 close_process_fd (&XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS]);
6230 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6231 if (new_outfd < 0)
6232 report_file_error ("Opening null device", Qnil);
6233 XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6234 XPROCESS (proc)->outfd = new_outfd;
6236 if (!proc_encode_coding_system[new_outfd])
6237 proc_encode_coding_system[new_outfd]
6238 = xmalloc (sizeof (struct coding_system));
6239 *proc_encode_coding_system[new_outfd]
6240 = *proc_encode_coding_system[old_outfd];
6241 memset (proc_encode_coding_system[old_outfd], 0,
6242 sizeof (struct coding_system));
6244 return process;
6247 /* The main Emacs thread records child processes in three places:
6249 - Vprocess_alist, for asynchronous subprocesses, which are child
6250 processes visible to Lisp.
6252 - deleted_pid_list, for child processes invisible to Lisp,
6253 typically because of delete-process. These are recorded so that
6254 the processes can be reaped when they exit, so that the operating
6255 system's process table is not cluttered by zombies.
6257 - the local variable PID in Fcall_process, call_process_cleanup and
6258 call_process_kill, for synchronous subprocesses.
6259 record_unwind_protect is used to make sure this process is not
6260 forgotten: if the user interrupts call-process and the child
6261 process refuses to exit immediately even with two C-g's,
6262 call_process_kill adds PID's contents to deleted_pid_list before
6263 returning.
6265 The main Emacs thread invokes waitpid only on child processes that
6266 it creates and that have not been reaped. This avoid races on
6267 platforms such as GTK, where other threads create their own
6268 subprocesses which the main thread should not reap. For example,
6269 if the main thread attempted to reap an already-reaped child, it
6270 might inadvertently reap a GTK-created process that happened to
6271 have the same process ID. */
6273 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6274 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6275 keep track of its own children. GNUstep is similar. */
6277 static void dummy_handler (int sig) {}
6278 static signal_handler_t volatile lib_child_handler;
6280 /* Handle a SIGCHLD signal by looking for known child processes of
6281 Emacs whose status have changed. For each one found, record its
6282 new status.
6284 All we do is change the status; we do not run sentinels or print
6285 notifications. That is saved for the next time keyboard input is
6286 done, in order to avoid timing errors.
6288 ** WARNING: this can be called during garbage collection.
6289 Therefore, it must not be fooled by the presence of mark bits in
6290 Lisp objects.
6292 ** USG WARNING: Although it is not obvious from the documentation
6293 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6294 signal() before executing at least one wait(), otherwise the
6295 handler will be called again, resulting in an infinite loop. The
6296 relevant portion of the documentation reads "SIGCLD signals will be
6297 queued and the signal-catching function will be continually
6298 reentered until the queue is empty". Invoking signal() causes the
6299 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6300 Inc.
6302 ** Malloc WARNING: This should never call malloc either directly or
6303 indirectly; if it does, that is a bug */
6305 static void
6306 handle_child_signal (int sig)
6308 Lisp_Object tail, proc;
6310 /* Find the process that signaled us, and record its status. */
6312 /* The process can have been deleted by Fdelete_process, or have
6313 been started asynchronously by Fcall_process. */
6314 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6316 bool all_pids_are_fixnums
6317 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6318 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6319 Lisp_Object head = XCAR (tail);
6320 Lisp_Object xpid;
6321 if (! CONSP (head))
6322 continue;
6323 xpid = XCAR (head);
6324 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6326 pid_t deleted_pid;
6327 if (INTEGERP (xpid))
6328 deleted_pid = XINT (xpid);
6329 else
6330 deleted_pid = XFLOAT_DATA (xpid);
6331 if (child_status_changed (deleted_pid, 0, 0))
6333 if (STRINGP (XCDR (head)))
6334 unlink (SSDATA (XCDR (head)));
6335 XSETCAR (tail, Qnil);
6340 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6341 FOR_EACH_PROCESS (tail, proc)
6343 struct Lisp_Process *p = XPROCESS (proc);
6344 int status;
6346 if (p->alive
6347 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6349 /* Change the status of the process that was found. */
6350 p->tick = ++process_tick;
6351 p->raw_status = status;
6352 p->raw_status_new = 1;
6354 /* If process has terminated, stop waiting for its output. */
6355 if (WIFSIGNALED (status) || WIFEXITED (status))
6357 bool clear_desc_flag = 0;
6358 p->alive = 0;
6359 if (p->infd >= 0)
6360 clear_desc_flag = 1;
6362 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6363 if (clear_desc_flag)
6364 delete_read_fd (p->infd);
6369 lib_child_handler (sig);
6370 #ifdef NS_IMPL_GNUSTEP
6371 /* NSTask in GNUStep sets its child handler each time it is called.
6372 So we must re-set ours. */
6373 catch_child_signal();
6374 #endif
6377 static void
6378 deliver_child_signal (int sig)
6380 deliver_process_signal (sig, handle_child_signal);
6384 static Lisp_Object
6385 exec_sentinel_error_handler (Lisp_Object error_val)
6387 cmd_error_internal (error_val, "error in process sentinel: ");
6388 Vinhibit_quit = Qt;
6389 update_echo_area ();
6390 Fsleep_for (make_number (2), Qnil);
6391 return Qt;
6394 static void
6395 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6397 Lisp_Object sentinel, odeactivate;
6398 struct Lisp_Process *p = XPROCESS (proc);
6399 ptrdiff_t count = SPECPDL_INDEX ();
6400 bool outer_running_asynch_code = running_asynch_code;
6401 int waiting = waiting_for_user_input_p;
6403 if (inhibit_sentinels)
6404 return;
6406 /* No need to gcpro these, because all we do with them later
6407 is test them for EQness, and none of them should be a string. */
6408 odeactivate = Vdeactivate_mark;
6409 #if 0
6410 Lisp_Object obuffer, okeymap;
6411 XSETBUFFER (obuffer, current_buffer);
6412 okeymap = BVAR (current_buffer, keymap);
6413 #endif
6415 /* There's no good reason to let sentinels change the current
6416 buffer, and many callers of accept-process-output, sit-for, and
6417 friends don't expect current-buffer to be changed from under them. */
6418 record_unwind_current_buffer ();
6420 sentinel = p->sentinel;
6422 /* Inhibit quit so that random quits don't screw up a running filter. */
6423 specbind (Qinhibit_quit, Qt);
6424 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6426 /* In case we get recursively called,
6427 and we already saved the match data nonrecursively,
6428 save the same match data in safely recursive fashion. */
6429 if (outer_running_asynch_code)
6431 Lisp_Object tem;
6432 tem = Fmatch_data (Qnil, Qnil, Qnil);
6433 restore_search_regs ();
6434 record_unwind_save_match_data ();
6435 Fset_match_data (tem, Qt);
6438 /* For speed, if a search happens within this code,
6439 save the match data in a special nonrecursive fashion. */
6440 running_asynch_code = 1;
6442 internal_condition_case_1 (read_process_output_call,
6443 list3 (sentinel, proc, reason),
6444 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6445 exec_sentinel_error_handler);
6447 /* If we saved the match data nonrecursively, restore it now. */
6448 restore_search_regs ();
6449 running_asynch_code = outer_running_asynch_code;
6451 Vdeactivate_mark = odeactivate;
6453 /* Restore waiting_for_user_input_p as it was
6454 when we were called, in case the filter clobbered it. */
6455 waiting_for_user_input_p = waiting;
6457 #if 0
6458 if (! EQ (Fcurrent_buffer (), obuffer)
6459 || ! EQ (current_buffer->keymap, okeymap))
6460 #endif
6461 /* But do it only if the caller is actually going to read events.
6462 Otherwise there's no need to make him wake up, and it could
6463 cause trouble (for example it would make sit_for return). */
6464 if (waiting_for_user_input_p == -1)
6465 record_asynch_buffer_change ();
6467 unbind_to (count, Qnil);
6470 /* Report all recent events of a change in process status
6471 (either run the sentinel or output a message).
6472 This is usually done while Emacs is waiting for keyboard input
6473 but can be done at other times. */
6475 static void
6476 status_notify (struct Lisp_Process *deleting_process)
6478 register Lisp_Object proc;
6479 Lisp_Object tail, msg;
6480 struct gcpro gcpro1, gcpro2;
6482 tail = Qnil;
6483 msg = Qnil;
6484 /* We need to gcpro tail; if read_process_output calls a filter
6485 which deletes a process and removes the cons to which tail points
6486 from Vprocess_alist, and then causes a GC, tail is an unprotected
6487 reference. */
6488 GCPRO2 (tail, msg);
6490 /* Set this now, so that if new processes are created by sentinels
6491 that we run, we get called again to handle their status changes. */
6492 update_tick = process_tick;
6494 FOR_EACH_PROCESS (tail, proc)
6496 Lisp_Object symbol;
6497 register struct Lisp_Process *p = XPROCESS (proc);
6499 if (p->tick != p->update_tick)
6501 p->update_tick = p->tick;
6503 /* If process is still active, read any output that remains. */
6504 while (! EQ (p->filter, Qt)
6505 && ! EQ (p->status, Qconnect)
6506 && ! EQ (p->status, Qlisten)
6507 /* Network or serial process not stopped: */
6508 && ! EQ (p->command, Qt)
6509 && p->infd >= 0
6510 && p != deleting_process
6511 && read_process_output (proc, p->infd) > 0);
6513 /* Get the text to use for the message. */
6514 if (p->raw_status_new)
6515 update_status (p);
6516 msg = status_message (p);
6518 /* If process is terminated, deactivate it or delete it. */
6519 symbol = p->status;
6520 if (CONSP (p->status))
6521 symbol = XCAR (p->status);
6523 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6524 || EQ (symbol, Qclosed))
6526 if (delete_exited_processes)
6527 remove_process (proc);
6528 else
6529 deactivate_process (proc);
6532 /* The actions above may have further incremented p->tick.
6533 So set p->update_tick again so that an error in the sentinel will
6534 not cause this code to be run again. */
6535 p->update_tick = p->tick;
6536 /* Now output the message suitably. */
6537 exec_sentinel (proc, msg);
6539 } /* end for */
6541 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6542 UNGCPRO;
6545 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6546 Sinternal_default_process_sentinel, 2, 2, 0,
6547 doc: /* Function used as default sentinel for processes. */)
6548 (Lisp_Object proc, Lisp_Object msg)
6550 Lisp_Object buffer, symbol;
6551 struct Lisp_Process *p;
6552 CHECK_PROCESS (proc);
6553 p = XPROCESS (proc);
6554 buffer = p->buffer;
6555 symbol = p->status;
6556 if (CONSP (symbol))
6557 symbol = XCAR (symbol);
6559 if (!EQ (symbol, Qrun) && !NILP (buffer))
6561 Lisp_Object tem;
6562 struct buffer *old = current_buffer;
6563 ptrdiff_t opoint, opoint_byte;
6564 ptrdiff_t before, before_byte;
6566 /* Avoid error if buffer is deleted
6567 (probably that's why the process is dead, too). */
6568 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6569 return Qnil;
6570 Fset_buffer (buffer);
6572 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6573 msg = (code_convert_string_norecord
6574 (msg, Vlocale_coding_system, 1));
6576 opoint = PT;
6577 opoint_byte = PT_BYTE;
6578 /* Insert new output into buffer
6579 at the current end-of-output marker,
6580 thus preserving logical ordering of input and output. */
6581 if (XMARKER (p->mark)->buffer)
6582 Fgoto_char (p->mark);
6583 else
6584 SET_PT_BOTH (ZV, ZV_BYTE);
6586 before = PT;
6587 before_byte = PT_BYTE;
6589 tem = BVAR (current_buffer, read_only);
6590 bset_read_only (current_buffer, Qnil);
6591 insert_string ("\nProcess ");
6592 { /* FIXME: temporary kludge. */
6593 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6594 insert_string (" ");
6595 Finsert (1, &msg);
6596 bset_read_only (current_buffer, tem);
6597 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6599 if (opoint >= before)
6600 SET_PT_BOTH (opoint + (PT - before),
6601 opoint_byte + (PT_BYTE - before_byte));
6602 else
6603 SET_PT_BOTH (opoint, opoint_byte);
6605 set_buffer_internal (old);
6607 return Qnil;
6611 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6612 Sset_process_coding_system, 1, 3, 0,
6613 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6614 DECODING will be used to decode subprocess output and ENCODING to
6615 encode subprocess input. */)
6616 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6618 register struct Lisp_Process *p;
6620 CHECK_PROCESS (process);
6621 p = XPROCESS (process);
6622 if (p->infd < 0)
6623 error ("Input file descriptor of %s closed", SDATA (p->name));
6624 if (p->outfd < 0)
6625 error ("Output file descriptor of %s closed", SDATA (p->name));
6626 Fcheck_coding_system (decoding);
6627 Fcheck_coding_system (encoding);
6628 encoding = coding_inherit_eol_type (encoding, Qnil);
6629 pset_decode_coding_system (p, decoding);
6630 pset_encode_coding_system (p, encoding);
6631 setup_process_coding_systems (process);
6633 return Qnil;
6636 DEFUN ("process-coding-system",
6637 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6638 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6639 (register Lisp_Object process)
6641 CHECK_PROCESS (process);
6642 return Fcons (XPROCESS (process)->decode_coding_system,
6643 XPROCESS (process)->encode_coding_system);
6646 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6647 Sset_process_filter_multibyte, 2, 2, 0,
6648 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6649 If FLAG is non-nil, the filter is given multibyte strings.
6650 If FLAG is nil, the filter is given unibyte strings. In this case,
6651 all character code conversion except for end-of-line conversion is
6652 suppressed. */)
6653 (Lisp_Object process, Lisp_Object flag)
6655 register struct Lisp_Process *p;
6657 CHECK_PROCESS (process);
6658 p = XPROCESS (process);
6659 if (NILP (flag))
6660 pset_decode_coding_system
6661 (p, raw_text_coding_system (p->decode_coding_system));
6662 setup_process_coding_systems (process);
6664 return Qnil;
6667 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6668 Sprocess_filter_multibyte_p, 1, 1, 0,
6669 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6670 (Lisp_Object process)
6672 register struct Lisp_Process *p;
6673 struct coding_system *coding;
6675 CHECK_PROCESS (process);
6676 p = XPROCESS (process);
6677 coding = proc_decode_coding_system[p->infd];
6678 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6684 # ifdef HAVE_GPM
6686 void
6687 add_gpm_wait_descriptor (int desc)
6689 add_keyboard_wait_descriptor (desc);
6692 void
6693 delete_gpm_wait_descriptor (int desc)
6695 delete_keyboard_wait_descriptor (desc);
6698 # endif
6700 # ifdef USABLE_SIGIO
6702 /* Return true if *MASK has a bit set
6703 that corresponds to one of the keyboard input descriptors. */
6705 static bool
6706 keyboard_bit_set (fd_set *mask)
6708 int fd;
6710 for (fd = 0; fd <= max_desc; fd++)
6711 if (FD_ISSET (fd, mask)
6712 && ((fd_callback_info[fd].flags & KEYBOARD_FD) != 0))
6713 return 1;
6715 return 0;
6717 # endif
6719 #else /* not subprocesses */
6721 /* Defined on msdos.c. */
6722 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6723 EMACS_TIME *, void *);
6725 /* Implementation of wait_reading_process_output, assuming that there
6726 are no subprocesses. Used only by the MS-DOS build.
6728 Wait for timeout to elapse and/or keyboard input to be available.
6730 TIME_LIMIT is:
6731 timeout in seconds
6732 If negative, gobble data immediately available but don't wait for any.
6734 NSECS is:
6735 an additional duration to wait, measured in nanoseconds
6736 If TIME_LIMIT is zero, then:
6737 If NSECS == 0, there is no limit.
6738 If NSECS > 0, the timeout consists of NSECS only.
6739 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6741 READ_KBD is:
6742 0 to ignore keyboard input, or
6743 1 to return when input is available, or
6744 -1 means caller will actually read the input, so don't throw to
6745 the quit handler.
6747 see full version for other parameters. We know that wait_proc will
6748 always be NULL, since `subprocesses' isn't defined.
6750 DO_DISPLAY means redisplay should be done to show subprocess
6751 output that arrives.
6753 Return true if we received input from any process. */
6755 bool
6756 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6757 bool do_display,
6758 Lisp_Object wait_for_cell,
6759 struct Lisp_Process *wait_proc, int just_wait_proc)
6761 register int nfds;
6762 EMACS_TIME end_time, timeout;
6764 if (time_limit < 0)
6766 time_limit = 0;
6767 nsecs = -1;
6769 else if (TYPE_MAXIMUM (time_t) < time_limit)
6770 time_limit = TYPE_MAXIMUM (time_t);
6772 /* What does time_limit really mean? */
6773 if (time_limit || nsecs > 0)
6775 timeout = make_emacs_time (time_limit, nsecs);
6776 end_time = add_emacs_time (current_emacs_time (), timeout);
6779 /* Turn off periodic alarms (in case they are in use)
6780 and then turn off any other atimers,
6781 because the select emulator uses alarms. */
6782 stop_polling ();
6783 turn_on_atimers (0);
6785 while (1)
6787 bool timeout_reduced_for_timers = 0;
6788 SELECT_TYPE waitchannels;
6789 int xerrno;
6791 /* If calling from keyboard input, do not quit
6792 since we want to return C-g as an input character.
6793 Otherwise, do pending quit if requested. */
6794 if (read_kbd >= 0)
6795 QUIT;
6797 /* Exit now if the cell we're waiting for became non-nil. */
6798 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6799 break;
6801 /* Compute time from now till when time limit is up. */
6802 /* Exit if already run out. */
6803 if (nsecs < 0)
6805 /* A negative timeout means
6806 gobble output available now
6807 but don't wait at all. */
6809 timeout = make_emacs_time (0, 0);
6811 else if (time_limit || nsecs > 0)
6813 EMACS_TIME now = current_emacs_time ();
6814 if (EMACS_TIME_LE (end_time, now))
6815 break;
6816 timeout = sub_emacs_time (end_time, now);
6818 else
6820 timeout = make_emacs_time (100000, 0);
6823 /* If our caller will not immediately handle keyboard events,
6824 run timer events directly.
6825 (Callers that will immediately read keyboard events
6826 call timer_delay on their own.) */
6827 if (NILP (wait_for_cell))
6829 EMACS_TIME timer_delay;
6833 unsigned old_timers_run = timers_run;
6834 timer_delay = timer_check ();
6835 if (timers_run != old_timers_run && do_display)
6836 /* We must retry, since a timer may have requeued itself
6837 and that could alter the time delay. */
6838 redisplay_preserve_echo_area (14);
6839 else
6840 break;
6842 while (!detect_input_pending ());
6844 /* If there is unread keyboard input, also return. */
6845 if (read_kbd != 0
6846 && requeued_events_pending_p ())
6847 break;
6849 if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
6851 if (EMACS_TIME_LT (timer_delay, timeout))
6853 timeout = timer_delay;
6854 timeout_reduced_for_timers = 1;
6859 /* Cause C-g and alarm signals to take immediate action,
6860 and cause input available signals to zero out timeout. */
6861 if (read_kbd < 0)
6862 set_waiting_for_input (&timeout);
6864 /* If a frame has been newly mapped and needs updating,
6865 reprocess its display stuff. */
6866 if (frame_garbaged && do_display)
6868 clear_waiting_for_input ();
6869 redisplay_preserve_echo_area (15);
6870 if (read_kbd < 0)
6871 set_waiting_for_input (&timeout);
6874 /* Wait till there is something to do. */
6875 FD_ZERO (&waitchannels);
6876 if (read_kbd && detect_input_pending ())
6877 nfds = 0;
6878 else
6880 if (read_kbd || !NILP (wait_for_cell))
6881 FD_SET (0, &waitchannels);
6882 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6885 xerrno = errno;
6887 /* Make C-g and alarm signals set flags again */
6888 clear_waiting_for_input ();
6890 /* If we woke up due to SIGWINCH, actually change size now. */
6891 do_pending_window_change (0);
6893 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6894 /* We waited the full specified time, so return now. */
6895 break;
6897 if (nfds == -1)
6899 /* If the system call was interrupted, then go around the
6900 loop again. */
6901 if (xerrno == EINTR)
6902 FD_ZERO (&waitchannels);
6903 else
6904 report_file_errno ("Failed select", Qnil, xerrno);
6907 /* Check for keyboard input */
6909 if (read_kbd
6910 && detect_input_pending_run_timers (do_display))
6912 swallow_events (do_display);
6913 if (detect_input_pending_run_timers (do_display))
6914 break;
6917 /* If there is unread keyboard input, also return. */
6918 if (read_kbd
6919 && requeued_events_pending_p ())
6920 break;
6922 /* If wait_for_cell. check for keyboard input
6923 but don't run any timers.
6924 ??? (It seems wrong to me to check for keyboard
6925 input at all when wait_for_cell, but the code
6926 has been this way since July 1994.
6927 Try changing this after version 19.31.) */
6928 if (! NILP (wait_for_cell)
6929 && detect_input_pending ())
6931 swallow_events (do_display);
6932 if (detect_input_pending ())
6933 break;
6936 /* Exit now if the cell we're waiting for became non-nil. */
6937 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6938 break;
6941 start_polling ();
6943 return 0;
6946 #endif /* not subprocesses */
6948 /* The following functions are needed even if async subprocesses are
6949 not supported. Some of them are no-op stubs in that case. */
6951 /* Add DESC to the set of keyboard input descriptors. */
6953 void
6954 add_keyboard_wait_descriptor (int desc)
6956 #ifdef subprocesses /* actually means "not MSDOS" */
6957 eassert (desc >= 0 && desc < MAXDESC);
6958 fd_callback_info[desc].flags |= FOR_READ | KEYBOARD_FD;
6959 if (desc > max_desc)
6960 max_desc = desc;
6961 #endif
6964 /* From now on, do not expect DESC to give keyboard input. */
6966 void
6967 delete_keyboard_wait_descriptor (int desc)
6969 #ifdef subprocesses
6970 int fd;
6971 int lim = max_desc;
6973 eassert (desc >= 0 && desc < MAXDESC);
6974 eassert (desc <= max_desc);
6976 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
6978 if (desc == max_desc)
6979 recompute_max_desc ();
6980 #endif
6983 /* Setup coding systems of PROCESS. */
6985 void
6986 setup_process_coding_systems (Lisp_Object process)
6988 #ifdef subprocesses
6989 struct Lisp_Process *p = XPROCESS (process);
6990 int inch = p->infd;
6991 int outch = p->outfd;
6992 Lisp_Object coding_system;
6994 if (inch < 0 || outch < 0)
6995 return;
6997 if (!proc_decode_coding_system[inch])
6998 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6999 coding_system = p->decode_coding_system;
7000 if (EQ (p->filter, Qinternal_default_process_filter)
7001 && BUFFERP (p->buffer))
7003 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7004 coding_system = raw_text_coding_system (coding_system);
7006 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7008 if (!proc_encode_coding_system[outch])
7009 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7010 setup_coding_system (p->encode_coding_system,
7011 proc_encode_coding_system[outch]);
7012 #endif
7015 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7016 doc: /* Return the (or a) process associated with BUFFER.
7017 BUFFER may be a buffer or the name of one. */)
7018 (register Lisp_Object buffer)
7020 #ifdef subprocesses
7021 register Lisp_Object buf, tail, proc;
7023 if (NILP (buffer)) return Qnil;
7024 buf = Fget_buffer (buffer);
7025 if (NILP (buf)) return Qnil;
7027 FOR_EACH_PROCESS (tail, proc)
7028 if (EQ (XPROCESS (proc)->buffer, buf))
7029 return proc;
7030 #endif /* subprocesses */
7031 return Qnil;
7034 DEFUN ("process-inherit-coding-system-flag",
7035 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7036 1, 1, 0,
7037 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7038 If this flag is t, `buffer-file-coding-system' of the buffer
7039 associated with PROCESS will inherit the coding system used to decode
7040 the process output. */)
7041 (register Lisp_Object process)
7043 #ifdef subprocesses
7044 CHECK_PROCESS (process);
7045 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7046 #else
7047 /* Ignore the argument and return the value of
7048 inherit-process-coding-system. */
7049 return inherit_process_coding_system ? Qt : Qnil;
7050 #endif
7053 /* Kill all processes associated with `buffer'.
7054 If `buffer' is nil, kill all processes */
7056 void
7057 kill_buffer_processes (Lisp_Object buffer)
7059 #ifdef subprocesses
7060 Lisp_Object tail, proc;
7062 FOR_EACH_PROCESS (tail, proc)
7063 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7065 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7066 Fdelete_process (proc);
7067 else if (XPROCESS (proc)->infd >= 0)
7068 process_send_signal (proc, SIGHUP, Qnil, 1);
7070 #else /* subprocesses */
7071 /* Since we have no subprocesses, this does nothing. */
7072 #endif /* subprocesses */
7075 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7076 Swaiting_for_user_input_p, 0, 0, 0,
7077 doc: /* Return non-nil if Emacs is waiting for input from the user.
7078 This is intended for use by asynchronous process output filters and sentinels. */)
7079 (void)
7081 #ifdef subprocesses
7082 return (waiting_for_user_input_p ? Qt : Qnil);
7083 #else
7084 return Qnil;
7085 #endif
7088 /* Stop reading input from keyboard sources. */
7090 void
7091 hold_keyboard_input (void)
7093 kbd_is_on_hold = 1;
7096 /* Resume reading input from keyboard sources. */
7098 void
7099 unhold_keyboard_input (void)
7101 kbd_is_on_hold = 0;
7104 /* Return true if keyboard input is on hold, zero otherwise. */
7106 bool
7107 kbd_on_hold_p (void)
7109 return kbd_is_on_hold;
7113 /* Enumeration of and access to system processes a-la ps(1). */
7115 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7116 0, 0, 0,
7117 doc: /* Return a list of numerical process IDs of all running processes.
7118 If this functionality is unsupported, return nil.
7120 See `process-attributes' for getting attributes of a process given its ID. */)
7121 (void)
7123 return list_system_processes ();
7126 DEFUN ("process-attributes", Fprocess_attributes,
7127 Sprocess_attributes, 1, 1, 0,
7128 doc: /* Return attributes of the process given by its PID, a number.
7130 Value is an alist where each element is a cons cell of the form
7132 \(KEY . VALUE)
7134 If this functionality is unsupported, the value is nil.
7136 See `list-system-processes' for getting a list of all process IDs.
7138 The KEYs of the attributes that this function may return are listed
7139 below, together with the type of the associated VALUE (in parentheses).
7140 Not all platforms support all of these attributes; unsupported
7141 attributes will not appear in the returned alist.
7142 Unless explicitly indicated otherwise, numbers can have either
7143 integer or floating point values.
7145 euid -- Effective user User ID of the process (number)
7146 user -- User name corresponding to euid (string)
7147 egid -- Effective user Group ID of the process (number)
7148 group -- Group name corresponding to egid (string)
7149 comm -- Command name (executable name only) (string)
7150 state -- Process state code, such as "S", "R", or "T" (string)
7151 ppid -- Parent process ID (number)
7152 pgrp -- Process group ID (number)
7153 sess -- Session ID, i.e. process ID of session leader (number)
7154 ttname -- Controlling tty name (string)
7155 tpgid -- ID of foreground process group on the process's tty (number)
7156 minflt -- number of minor page faults (number)
7157 majflt -- number of major page faults (number)
7158 cminflt -- cumulative number of minor page faults (number)
7159 cmajflt -- cumulative number of major page faults (number)
7160 utime -- user time used by the process, in (current-time) format,
7161 which is a list of integers (HIGH LOW USEC PSEC)
7162 stime -- system time used by the process (current-time)
7163 time -- sum of utime and stime (current-time)
7164 cutime -- user time used by the process and its children (current-time)
7165 cstime -- system time used by the process and its children (current-time)
7166 ctime -- sum of cutime and cstime (current-time)
7167 pri -- priority of the process (number)
7168 nice -- nice value of the process (number)
7169 thcount -- process thread count (number)
7170 start -- time the process started (current-time)
7171 vsize -- virtual memory size of the process in KB's (number)
7172 rss -- resident set size of the process in KB's (number)
7173 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7174 pcpu -- percents of CPU time used by the process (floating-point number)
7175 pmem -- percents of total physical memory used by process's resident set
7176 (floating-point number)
7177 args -- command line which invoked the process (string). */)
7178 ( Lisp_Object pid)
7180 return system_process_attributes (pid);
7183 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7184 Invoke this after init_process_emacs, and after glib and/or GNUstep
7185 futz with the SIGCHLD handler, but before Emacs forks any children.
7186 This function's caller should block SIGCHLD. */
7188 #ifndef NS_IMPL_GNUSTEP
7189 static
7190 #endif
7191 void
7192 catch_child_signal (void)
7194 struct sigaction action, old_action;
7195 emacs_sigaction_init (&action, deliver_child_signal);
7196 block_child_signal ();
7197 sigaction (SIGCHLD, &action, &old_action);
7198 eassert (! (old_action.sa_flags & SA_SIGINFO));
7200 if (old_action.sa_handler != deliver_child_signal)
7201 lib_child_handler
7202 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7203 ? dummy_handler
7204 : old_action.sa_handler);
7205 unblock_child_signal ();
7209 /* This is not called "init_process" because that is the name of a
7210 Mach system call, so it would cause problems on Darwin systems. */
7211 void
7212 init_process_emacs (void)
7214 #ifdef subprocesses
7215 register int i;
7217 inhibit_sentinels = 0;
7219 #ifndef CANNOT_DUMP
7220 if (! noninteractive || initialized)
7221 #endif
7223 #if defined HAVE_GLIB && !defined WINDOWSNT
7224 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7225 this should always fail, but is enough to initialize glib's
7226 private SIGCHLD handler, allowing catch_child_signal to copy
7227 it into lib_child_handler. */
7228 g_source_unref (g_child_watch_source_new (getpid ()));
7229 #endif
7230 catch_child_signal ();
7233 max_desc = -1;
7234 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7236 #ifdef NON_BLOCKING_CONNECT
7237 num_pending_connects = 0;
7238 #endif
7240 #ifdef ADAPTIVE_READ_BUFFERING
7241 process_output_delay_count = 0;
7242 process_output_skip = 0;
7243 #endif
7245 /* Don't do this, it caused infinite select loops. The display
7246 method should call add_keyboard_wait_descriptor on stdin if it
7247 needs that. */
7248 #if 0
7249 FD_SET (0, &input_wait_mask);
7250 #endif
7252 Vprocess_alist = Qnil;
7253 deleted_pid_list = Qnil;
7254 for (i = 0; i < MAXDESC; i++)
7256 chan_process[i] = Qnil;
7257 proc_buffered_char[i] = -1;
7259 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7260 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7261 #ifdef DATAGRAM_SOCKETS
7262 memset (datagram_address, 0, sizeof datagram_address);
7263 #endif
7266 Lisp_Object subfeatures = Qnil;
7267 const struct socket_options *sopt;
7269 #define ADD_SUBFEATURE(key, val) \
7270 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7272 #ifdef NON_BLOCKING_CONNECT
7273 ADD_SUBFEATURE (QCnowait, Qt);
7274 #endif
7275 #ifdef DATAGRAM_SOCKETS
7276 ADD_SUBFEATURE (QCtype, Qdatagram);
7277 #endif
7278 #ifdef HAVE_SEQPACKET
7279 ADD_SUBFEATURE (QCtype, Qseqpacket);
7280 #endif
7281 #ifdef HAVE_LOCAL_SOCKETS
7282 ADD_SUBFEATURE (QCfamily, Qlocal);
7283 #endif
7284 ADD_SUBFEATURE (QCfamily, Qipv4);
7285 #ifdef AF_INET6
7286 ADD_SUBFEATURE (QCfamily, Qipv6);
7287 #endif
7288 #ifdef HAVE_GETSOCKNAME
7289 ADD_SUBFEATURE (QCservice, Qt);
7290 #endif
7291 ADD_SUBFEATURE (QCserver, Qt);
7293 for (sopt = socket_options; sopt->name; sopt++)
7294 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7296 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7299 #if defined (DARWIN_OS)
7300 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7301 processes. As such, we only change the default value. */
7302 if (initialized)
7304 char const *release = (STRINGP (Voperating_system_release)
7305 ? SSDATA (Voperating_system_release)
7306 : 0);
7307 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7308 Vprocess_connection_type = Qnil;
7311 #endif
7312 #endif /* subprocesses */
7313 kbd_is_on_hold = 0;
7316 void
7317 syms_of_process (void)
7319 #ifdef subprocesses
7321 DEFSYM (Qprocessp, "processp");
7322 DEFSYM (Qrun, "run");
7323 DEFSYM (Qstop, "stop");
7324 DEFSYM (Qsignal, "signal");
7326 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7327 here again.
7329 Qexit = intern_c_string ("exit");
7330 staticpro (&Qexit); */
7332 DEFSYM (Qopen, "open");
7333 DEFSYM (Qclosed, "closed");
7334 DEFSYM (Qconnect, "connect");
7335 DEFSYM (Qfailed, "failed");
7336 DEFSYM (Qlisten, "listen");
7337 DEFSYM (Qlocal, "local");
7338 DEFSYM (Qipv4, "ipv4");
7339 #ifdef AF_INET6
7340 DEFSYM (Qipv6, "ipv6");
7341 #endif
7342 DEFSYM (Qdatagram, "datagram");
7343 DEFSYM (Qseqpacket, "seqpacket");
7345 DEFSYM (QCport, ":port");
7346 DEFSYM (QCspeed, ":speed");
7347 DEFSYM (QCprocess, ":process");
7349 DEFSYM (QCbytesize, ":bytesize");
7350 DEFSYM (QCstopbits, ":stopbits");
7351 DEFSYM (QCparity, ":parity");
7352 DEFSYM (Qodd, "odd");
7353 DEFSYM (Qeven, "even");
7354 DEFSYM (QCflowcontrol, ":flowcontrol");
7355 DEFSYM (Qhw, "hw");
7356 DEFSYM (Qsw, "sw");
7357 DEFSYM (QCsummary, ":summary");
7359 DEFSYM (Qreal, "real");
7360 DEFSYM (Qnetwork, "network");
7361 DEFSYM (Qserial, "serial");
7362 DEFSYM (QCbuffer, ":buffer");
7363 DEFSYM (QChost, ":host");
7364 DEFSYM (QCservice, ":service");
7365 DEFSYM (QClocal, ":local");
7366 DEFSYM (QCremote, ":remote");
7367 DEFSYM (QCcoding, ":coding");
7368 DEFSYM (QCserver, ":server");
7369 DEFSYM (QCnowait, ":nowait");
7370 DEFSYM (QCsentinel, ":sentinel");
7371 DEFSYM (QClog, ":log");
7372 DEFSYM (QCnoquery, ":noquery");
7373 DEFSYM (QCstop, ":stop");
7374 DEFSYM (QCoptions, ":options");
7375 DEFSYM (QCplist, ":plist");
7377 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7379 staticpro (&Vprocess_alist);
7380 staticpro (&deleted_pid_list);
7382 #endif /* subprocesses */
7384 DEFSYM (QCname, ":name");
7385 DEFSYM (QCtype, ":type");
7387 DEFSYM (Qeuid, "euid");
7388 DEFSYM (Qegid, "egid");
7389 DEFSYM (Quser, "user");
7390 DEFSYM (Qgroup, "group");
7391 DEFSYM (Qcomm, "comm");
7392 DEFSYM (Qstate, "state");
7393 DEFSYM (Qppid, "ppid");
7394 DEFSYM (Qpgrp, "pgrp");
7395 DEFSYM (Qsess, "sess");
7396 DEFSYM (Qttname, "ttname");
7397 DEFSYM (Qtpgid, "tpgid");
7398 DEFSYM (Qminflt, "minflt");
7399 DEFSYM (Qmajflt, "majflt");
7400 DEFSYM (Qcminflt, "cminflt");
7401 DEFSYM (Qcmajflt, "cmajflt");
7402 DEFSYM (Qutime, "utime");
7403 DEFSYM (Qstime, "stime");
7404 DEFSYM (Qtime, "time");
7405 DEFSYM (Qcutime, "cutime");
7406 DEFSYM (Qcstime, "cstime");
7407 DEFSYM (Qctime, "ctime");
7408 DEFSYM (Qinternal_default_process_sentinel,
7409 "internal-default-process-sentinel");
7410 DEFSYM (Qinternal_default_process_filter,
7411 "internal-default-process-filter");
7412 DEFSYM (Qpri, "pri");
7413 DEFSYM (Qnice, "nice");
7414 DEFSYM (Qthcount, "thcount");
7415 DEFSYM (Qstart, "start");
7416 DEFSYM (Qvsize, "vsize");
7417 DEFSYM (Qrss, "rss");
7418 DEFSYM (Qetime, "etime");
7419 DEFSYM (Qpcpu, "pcpu");
7420 DEFSYM (Qpmem, "pmem");
7421 DEFSYM (Qargs, "args");
7423 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7424 doc: /* Non-nil means delete processes immediately when they exit.
7425 A value of nil means don't delete them until `list-processes' is run. */);
7427 delete_exited_processes = 1;
7429 #ifdef subprocesses
7430 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7431 doc: /* Control type of device used to communicate with subprocesses.
7432 Values are nil to use a pipe, or t or `pty' to use a pty.
7433 The value has no effect if the system has no ptys or if all ptys are busy:
7434 then a pipe is used in any case.
7435 The value takes effect when `start-process' is called. */);
7436 Vprocess_connection_type = Qt;
7438 #ifdef ADAPTIVE_READ_BUFFERING
7439 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7440 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7441 On some systems, when Emacs reads the output from a subprocess, the output data
7442 is read in very small blocks, potentially resulting in very poor performance.
7443 This behavior can be remedied to some extent by setting this variable to a
7444 non-nil value, as it will automatically delay reading from such processes, to
7445 allow them to produce more output before Emacs tries to read it.
7446 If the value is t, the delay is reset after each write to the process; any other
7447 non-nil value means that the delay is not reset on write.
7448 The variable takes effect when `start-process' is called. */);
7449 Vprocess_adaptive_read_buffering = Qt;
7450 #endif
7452 defsubr (&Sprocessp);
7453 defsubr (&Sget_process);
7454 defsubr (&Sdelete_process);
7455 defsubr (&Sprocess_status);
7456 defsubr (&Sprocess_exit_status);
7457 defsubr (&Sprocess_id);
7458 defsubr (&Sprocess_name);
7459 defsubr (&Sprocess_tty_name);
7460 defsubr (&Sprocess_command);
7461 defsubr (&Sset_process_buffer);
7462 defsubr (&Sprocess_buffer);
7463 defsubr (&Sprocess_mark);
7464 defsubr (&Sset_process_filter);
7465 defsubr (&Sprocess_filter);
7466 defsubr (&Sset_process_sentinel);
7467 defsubr (&Sprocess_sentinel);
7468 defsubr (&Sset_process_thread);
7469 defsubr (&Sprocess_thread);
7470 defsubr (&Sset_process_window_size);
7471 defsubr (&Sset_process_inherit_coding_system_flag);
7472 defsubr (&Sset_process_query_on_exit_flag);
7473 defsubr (&Sprocess_query_on_exit_flag);
7474 defsubr (&Sprocess_contact);
7475 defsubr (&Sprocess_plist);
7476 defsubr (&Sset_process_plist);
7477 defsubr (&Sprocess_list);
7478 defsubr (&Sstart_process);
7479 defsubr (&Sserial_process_configure);
7480 defsubr (&Smake_serial_process);
7481 defsubr (&Sset_network_process_option);
7482 defsubr (&Smake_network_process);
7483 defsubr (&Sformat_network_address);
7484 #if defined (HAVE_NET_IF_H)
7485 #ifdef SIOCGIFCONF
7486 defsubr (&Snetwork_interface_list);
7487 #endif
7488 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7489 defsubr (&Snetwork_interface_info);
7490 #endif
7491 #endif /* defined (HAVE_NET_IF_H) */
7492 #ifdef DATAGRAM_SOCKETS
7493 defsubr (&Sprocess_datagram_address);
7494 defsubr (&Sset_process_datagram_address);
7495 #endif
7496 defsubr (&Saccept_process_output);
7497 defsubr (&Sprocess_send_region);
7498 defsubr (&Sprocess_send_string);
7499 defsubr (&Sinterrupt_process);
7500 defsubr (&Skill_process);
7501 defsubr (&Squit_process);
7502 defsubr (&Sstop_process);
7503 defsubr (&Scontinue_process);
7504 defsubr (&Sprocess_running_child_p);
7505 defsubr (&Sprocess_send_eof);
7506 defsubr (&Ssignal_process);
7507 defsubr (&Swaiting_for_user_input_p);
7508 defsubr (&Sprocess_type);
7509 defsubr (&Sinternal_default_process_sentinel);
7510 defsubr (&Sinternal_default_process_filter);
7511 defsubr (&Sset_process_coding_system);
7512 defsubr (&Sprocess_coding_system);
7513 defsubr (&Sset_process_filter_multibyte);
7514 defsubr (&Sprocess_filter_multibyte_p);
7516 #endif /* subprocesses */
7518 defsubr (&Sget_buffer_process);
7519 defsubr (&Sprocess_inherit_coding_system_flag);
7520 defsubr (&Slist_system_processes);
7521 defsubr (&Sprocess_attributes);