make thread_check_current_buffer return bool
[emacs.git] / src / process.c
blob94ca3d4b1a0ea038c2d1a6744cd3c59ae6397313
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 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "lisp.h"
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 #include "w32.h"
136 #endif
138 #ifndef SOCK_CLOEXEC
139 # define SOCK_CLOEXEC 0
140 #endif
142 #ifndef HAVE_ACCEPT4
144 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
146 static int
147 close_on_exec (int fd)
149 if (0 <= fd)
150 fcntl (fd, F_SETFD, FD_CLOEXEC);
151 return fd;
154 static int
155 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
157 return close_on_exec (accept (sockfd, addr, addrlen));
160 static int
161 process_socket (int domain, int type, int protocol)
163 return close_on_exec (socket (domain, type, protocol));
165 # undef socket
166 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
167 #endif
169 /* Work around GCC 4.7.0 bug with strict overflow checking; see
170 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
171 These lines can be removed once the GCC bug is fixed. */
172 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
173 # pragma GCC diagnostic ignored "-Wstrict-overflow"
174 #endif
176 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
177 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
178 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
179 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
180 Lisp_Object QCname, QCtype;
182 /* True if keyboard input is on hold, zero otherwise. */
184 static bool kbd_is_on_hold;
186 /* Nonzero means don't run process sentinels. This is used
187 when exiting. */
188 bool inhibit_sentinels;
190 #ifdef subprocesses
192 Lisp_Object Qprocessp;
193 static Lisp_Object Qrun, Qstop, Qsignal;
194 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
195 Lisp_Object Qlocal;
196 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
197 static Lisp_Object Qreal, Qnetwork, Qserial;
198 #ifdef AF_INET6
199 static Lisp_Object Qipv6;
200 #endif
201 static Lisp_Object QCport, QCprocess;
202 Lisp_Object QCspeed;
203 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
204 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
205 static Lisp_Object QCbuffer, QChost, QCservice;
206 static Lisp_Object QClocal, QCremote, QCcoding;
207 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
208 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
209 static Lisp_Object Qlast_nonmenu_event;
210 static Lisp_Object Qinternal_default_process_sentinel;
211 static Lisp_Object Qinternal_default_process_filter;
213 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
214 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
215 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
216 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
218 /* Number of events of change of status of a process. */
219 static EMACS_INT process_tick;
220 /* Number of events for which the user or sentinel has been notified. */
221 static EMACS_INT update_tick;
223 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
225 /* Only W32 has this, it really means that select can't take write mask. */
226 #ifdef BROKEN_NON_BLOCKING_CONNECT
227 #undef NON_BLOCKING_CONNECT
228 #define SELECT_CANT_DO_WRITE_MASK
229 #else
230 #ifndef NON_BLOCKING_CONNECT
231 #ifdef HAVE_SELECT
232 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
233 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
234 #define NON_BLOCKING_CONNECT
235 #endif /* EWOULDBLOCK || EINPROGRESS */
236 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
237 #endif /* HAVE_SELECT */
238 #endif /* NON_BLOCKING_CONNECT */
239 #endif /* BROKEN_NON_BLOCKING_CONNECT */
241 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
242 this system. We need to read full packets, so we need a
243 "non-destructive" select. So we require either native select,
244 or emulation of select using FIONREAD. */
246 #ifndef BROKEN_DATAGRAM_SOCKETS
247 # if defined HAVE_SELECT || defined USABLE_FIONREAD
248 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
249 # define DATAGRAM_SOCKETS
250 # endif
251 # endif
252 #endif
254 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
255 # define HAVE_SEQPACKET
256 #endif
258 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
259 #define ADAPTIVE_READ_BUFFERING
260 #endif
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count;
272 /* True if any process has non-nil read_output_skip. */
274 static bool process_output_skip;
276 #else
277 #define process_output_delay_count 0
278 #endif
280 static void create_process (Lisp_Object, char **, Lisp_Object);
281 #ifdef USABLE_SIGIO
282 static bool keyboard_bit_set (SELECT_TYPE *);
283 #endif
284 static void deactivate_process (Lisp_Object);
285 static void status_notify (struct Lisp_Process *);
286 static int read_process_output (Lisp_Object, int);
287 static void handle_child_signal (int);
288 static void create_pty (Lisp_Object);
290 /* If we support a window system, turn on the code to poll periodically
291 to detect C-g. It isn't actually used when doing interrupt input. */
292 #ifdef HAVE_WINDOW_SYSTEM
293 #define POLL_FOR_INPUT
294 #endif
296 static Lisp_Object get_process (register Lisp_Object name);
297 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
299 #ifdef NON_BLOCKING_CONNECT
300 /* Number of bits set in connect_wait_mask. */
301 static int num_pending_connects;
302 #endif /* NON_BLOCKING_CONNECT */
304 /* The largest descriptor currently in use; -1 if none. */
305 static int max_desc;
307 /* Indexed by descriptor, gives the process (if any) for that descriptor */
308 static Lisp_Object chan_process[MAXDESC];
310 /* Alist of elements (NAME . PROCESS) */
311 static Lisp_Object Vprocess_alist;
313 /* Buffered-ahead input char from process, indexed by channel.
314 -1 means empty (no char is buffered).
315 Used on sys V where the only way to tell if there is any
316 output from the process is to read at least one char.
317 Always -1 on systems that support FIONREAD. */
319 static int proc_buffered_char[MAXDESC];
321 /* Table of `struct coding-system' for each process. */
322 static struct coding_system *proc_decode_coding_system[MAXDESC];
323 static struct coding_system *proc_encode_coding_system[MAXDESC];
325 #ifdef DATAGRAM_SOCKETS
326 /* Table of `partner address' for datagram sockets. */
327 static struct sockaddr_and_len {
328 struct sockaddr *sa;
329 int len;
330 } datagram_address[MAXDESC];
331 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
332 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
333 #else
334 #define DATAGRAM_CHAN_P(chan) (0)
335 #define DATAGRAM_CONN_P(proc) (0)
336 #endif
338 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
339 a `for' loop which iterates over processes from Vprocess_alist. */
341 #define FOR_EACH_PROCESS(list_var, proc_var) \
342 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
344 /* These setters are used only in this file, so they can be private. */
345 static void
346 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
348 p->buffer = val;
350 static void
351 pset_command (struct Lisp_Process *p, Lisp_Object val)
353 p->command = val;
355 static void
356 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
358 p->decode_coding_system = val;
360 static void
361 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
363 p->decoding_buf = val;
365 static void
366 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
368 p->encode_coding_system = val;
370 static void
371 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
373 p->encoding_buf = val;
375 static void
376 pset_filter (struct Lisp_Process *p, Lisp_Object val)
378 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
380 static void
381 pset_log (struct Lisp_Process *p, Lisp_Object val)
383 p->log = val;
385 static void
386 pset_mark (struct Lisp_Process *p, Lisp_Object val)
388 p->mark = val;
390 static void
391 pset_thread (struct Lisp_Process *p, Lisp_Object val)
393 p->thread = val;
395 static void
396 pset_name (struct Lisp_Process *p, Lisp_Object val)
398 p->name = val;
400 static void
401 pset_plist (struct Lisp_Process *p, Lisp_Object val)
403 p->plist = val;
405 static void
406 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
408 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
410 static void
411 pset_status (struct Lisp_Process *p, Lisp_Object val)
413 p->status = val;
415 static void
416 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
418 p->tty_name = val;
420 static void
421 pset_type (struct Lisp_Process *p, Lisp_Object val)
423 p->type = val;
425 static void
426 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
428 p->write_queue = val;
433 enum fd_bits
435 /* Read from file descriptor. */
436 FOR_READ = 1,
437 /* Write to file descriptor. */
438 FOR_WRITE = 2,
439 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
440 set. */
441 KEYBOARD_FD = 4,
442 /* This descriptor refers to a process. */
443 PROCESS_FD = 8,
444 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
445 NON_BLOCKING_CONNECT_FD = 16
448 static struct fd_callback_data
450 fd_callback func;
451 void *data;
452 /* Flags from enum fd_bits. */
453 int flags;
454 /* If this fd is locked to a certain thread, this points to it.
455 Otherwise, this is NULL. If an fd is locked to a thread, then
456 only that thread is permitted to wait on it. */
457 struct thread_state *thread;
458 /* If this fd is currently being selected on by a thread, this
459 points to the thread. Otherwise it is NULL. */
460 struct thread_state *waiting_thread;
461 } fd_callback_info[MAXDESC];
464 /* Add a file descriptor FD to be monitored for when read is possible.
465 When read is possible, call FUNC with argument DATA. */
467 void
468 add_read_fd (int fd, fd_callback func, void *data)
470 eassert (fd < MAXDESC);
471 add_keyboard_wait_descriptor (fd);
473 fd_callback_info[fd].func = func;
474 fd_callback_info[fd].data = data;
477 static void
478 add_non_keyboard_read_fd (int fd)
480 eassert (fd >= 0 && fd < MAXDESC);
481 eassert (fd_callback_info[fd].func == NULL);
482 fd_callback_info[fd].flags |= FOR_READ;
483 if (fd > max_desc)
484 max_desc = fd;
487 static void
488 add_process_read_fd (int fd)
490 add_non_keyboard_read_fd (fd);
491 fd_callback_info[fd].flags |= PROCESS_FD;
494 /* Stop monitoring file descriptor FD for when read is possible. */
496 void
497 delete_read_fd (int fd)
499 eassert (fd < MAXDESC);
500 eassert (fd <= max_desc);
501 delete_keyboard_wait_descriptor (fd);
503 if (fd_callback_info[fd].flags == 0)
505 fd_callback_info[fd].func = 0;
506 fd_callback_info[fd].data = 0;
510 /* Add a file descriptor FD to be monitored for when write is possible.
511 When write is possible, call FUNC with argument DATA. */
513 void
514 add_write_fd (int fd, fd_callback func, void *data)
516 eassert (fd < MAXDESC);
517 if (fd > max_desc)
518 max_desc = fd;
520 fd_callback_info[fd].func = func;
521 fd_callback_info[fd].data = data;
522 fd_callback_info[fd].flags |= FOR_WRITE;
525 static void
526 add_non_blocking_write_fd (int fd)
528 eassert (fd >= 0 && fd < MAXDESC);
529 eassert (fd_callback_info[fd].func == NULL);
531 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
532 if (fd > max_desc)
533 max_desc = fd;
534 #ifdef NON_BLOCKING_CONNECT
535 ++num_pending_connects;
536 #endif
539 static void
540 recompute_max_desc (void)
542 int fd;
544 for (fd = max_desc; fd >= 0; --fd)
546 if (fd_callback_info[fd].flags != 0)
548 max_desc = fd;
549 break;
554 /* Stop monitoring file descriptor FD for when write is possible. */
556 void
557 delete_write_fd (int fd)
559 int lim = max_desc;
561 eassert (fd < MAXDESC);
562 eassert (fd <= max_desc);
564 #ifdef NON_BLOCKING_CONNECT
565 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
567 if (--num_pending_connects < 0)
568 abort ();
570 #endif
571 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
572 if (fd_callback_info[fd].flags == 0)
574 fd_callback_info[fd].func = 0;
575 fd_callback_info[fd].data = 0;
577 if (fd == max_desc)
578 recompute_max_desc ();
582 static void
583 compute_input_wait_mask (SELECT_TYPE *mask)
585 int fd;
587 FD_ZERO (mask);
588 for (fd = 0; fd <= max_desc; ++fd)
590 if (fd_callback_info[fd].thread != NULL
591 && fd_callback_info[fd].thread != current_thread)
592 continue;
593 if (fd_callback_info[fd].waiting_thread != NULL
594 && fd_callback_info[fd].waiting_thread != current_thread)
595 continue;
596 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
598 FD_SET (fd, mask);
599 fd_callback_info[fd].waiting_thread = current_thread;
604 static void
605 compute_non_process_wait_mask (SELECT_TYPE *mask)
607 int fd;
609 FD_ZERO (mask);
610 for (fd = 0; fd <= max_desc; ++fd)
612 if (fd_callback_info[fd].thread != NULL
613 && fd_callback_info[fd].thread != current_thread)
614 continue;
615 if (fd_callback_info[fd].waiting_thread != NULL
616 && fd_callback_info[fd].waiting_thread != current_thread)
617 continue;
618 if ((fd_callback_info[fd].flags & FOR_READ) != 0
619 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
621 FD_SET (fd, mask);
622 fd_callback_info[fd].waiting_thread = current_thread;
627 static void
628 compute_non_keyboard_wait_mask (SELECT_TYPE *mask)
630 int fd;
632 FD_ZERO (mask);
633 for (fd = 0; fd <= max_desc; ++fd)
635 if (fd_callback_info[fd].thread != NULL
636 && fd_callback_info[fd].thread != current_thread)
637 continue;
638 if (fd_callback_info[fd].waiting_thread != NULL
639 && fd_callback_info[fd].waiting_thread != current_thread)
640 continue;
641 if ((fd_callback_info[fd].flags & FOR_READ) != 0
642 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
644 FD_SET (fd, mask);
645 fd_callback_info[fd].waiting_thread = current_thread;
650 static void
651 compute_write_mask (SELECT_TYPE *mask)
653 int fd;
655 FD_ZERO (mask);
656 for (fd = 0; fd <= max_desc; ++fd)
658 if (fd_callback_info[fd].thread != NULL
659 && fd_callback_info[fd].thread != current_thread)
660 continue;
661 if (fd_callback_info[fd].waiting_thread != NULL
662 && fd_callback_info[fd].waiting_thread != current_thread)
663 continue;
664 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
666 FD_SET (fd, mask);
667 fd_callback_info[fd].waiting_thread = current_thread;
672 static void
673 clear_waiting_thread_info (void)
675 int fd;
677 for (fd = 0; fd <= max_desc; ++fd)
679 if (fd_callback_info[fd].waiting_thread == current_thread)
680 fd_callback_info[fd].waiting_thread = NULL;
685 /* Compute the Lisp form of the process status, p->status, from
686 the numeric status that was returned by `wait'. */
688 static Lisp_Object status_convert (int);
690 static void
691 update_status (struct Lisp_Process *p)
693 eassert (p->raw_status_new);
694 pset_status (p, status_convert (p->raw_status));
695 p->raw_status_new = 0;
698 /* Convert a process status word in Unix format to
699 the list that we use internally. */
701 static Lisp_Object
702 status_convert (int w)
704 if (WIFSTOPPED (w))
705 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
706 else if (WIFEXITED (w))
707 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
708 WCOREDUMP (w) ? Qt : Qnil));
709 else if (WIFSIGNALED (w))
710 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
711 WCOREDUMP (w) ? Qt : Qnil));
712 else
713 return Qrun;
716 /* Given a status-list, extract the three pieces of information
717 and store them individually through the three pointers. */
719 static void
720 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
722 Lisp_Object tem;
724 if (SYMBOLP (l))
726 *symbol = l;
727 *code = 0;
728 *coredump = 0;
730 else
732 *symbol = XCAR (l);
733 tem = XCDR (l);
734 *code = XFASTINT (XCAR (tem));
735 tem = XCDR (tem);
736 *coredump = !NILP (tem);
740 /* Return a string describing a process status list. */
742 static Lisp_Object
743 status_message (struct Lisp_Process *p)
745 Lisp_Object status = p->status;
746 Lisp_Object symbol;
747 int code;
748 bool coredump;
749 Lisp_Object string, string2;
751 decode_status (status, &symbol, &code, &coredump);
753 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
755 char const *signame;
756 synchronize_system_messages_locale ();
757 signame = strsignal (code);
758 if (signame == 0)
759 string = build_string ("unknown");
760 else
762 int c1, c2;
764 string = build_unibyte_string (signame);
765 if (! NILP (Vlocale_coding_system))
766 string = (code_convert_string_norecord
767 (string, Vlocale_coding_system, 0));
768 c1 = STRING_CHAR (SDATA (string));
769 c2 = downcase (c1);
770 if (c1 != c2)
771 Faset (string, make_number (0), make_number (c2));
773 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
774 return concat2 (string, string2);
776 else if (EQ (symbol, Qexit))
778 if (NETCONN1_P (p))
779 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
780 if (code == 0)
781 return build_string ("finished\n");
782 string = Fnumber_to_string (make_number (code));
783 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
784 return concat3 (build_string ("exited abnormally with code "),
785 string, string2);
787 else if (EQ (symbol, Qfailed))
789 string = Fnumber_to_string (make_number (code));
790 string2 = build_string ("\n");
791 return concat3 (build_string ("failed with code "),
792 string, string2);
794 else
795 return Fcopy_sequence (Fsymbol_name (symbol));
798 enum { PTY_NAME_SIZE = 24 };
800 /* Open an available pty, returning a file descriptor.
801 Store into PTY_NAME the file name of the terminal corresponding to the pty.
802 Return -1 on failure. */
804 static int
805 allocate_pty (char pty_name[PTY_NAME_SIZE])
807 #ifdef HAVE_PTYS
808 int fd;
810 #ifdef PTY_ITERATION
811 PTY_ITERATION
812 #else
813 register int c, i;
814 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
815 for (i = 0; i < 16; i++)
816 #endif
818 #ifdef PTY_NAME_SPRINTF
819 PTY_NAME_SPRINTF
820 #else
821 sprintf (pty_name, "/dev/pty%c%x", c, i);
822 #endif /* no PTY_NAME_SPRINTF */
824 #ifdef PTY_OPEN
825 PTY_OPEN;
826 #else /* no PTY_OPEN */
827 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
828 #endif /* no PTY_OPEN */
830 if (fd >= 0)
832 #ifdef PTY_OPEN
833 /* Set FD's close-on-exec flag. This is needed even if
834 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
835 doesn't require support for that combination.
836 Multithreaded platforms where posix_openpt ignores
837 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
838 have a race condition between the PTY_OPEN and here. */
839 fcntl (fd, F_SETFD, FD_CLOEXEC);
840 #endif
841 /* check to make certain that both sides are available
842 this avoids a nasty yet stupid bug in rlogins */
843 #ifdef PTY_TTY_NAME_SPRINTF
844 PTY_TTY_NAME_SPRINTF
845 #else
846 sprintf (pty_name, "/dev/tty%c%x", c, i);
847 #endif /* no PTY_TTY_NAME_SPRINTF */
848 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
850 emacs_close (fd);
851 # ifndef __sgi
852 continue;
853 # else
854 return -1;
855 # endif /* __sgi */
857 setup_pty (fd);
858 return fd;
861 #endif /* HAVE_PTYS */
862 return -1;
865 static Lisp_Object
866 make_process (Lisp_Object name)
868 register Lisp_Object val, tem, name1;
869 register struct Lisp_Process *p;
870 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
871 printmax_t i;
873 p = allocate_process ();
874 /* Initialize Lisp data. Note that allocate_process initializes all
875 Lisp data to nil, so do it only for slots which should not be nil. */
876 pset_status (p, Qrun);
877 pset_mark (p, Fmake_marker ());
878 pset_thread (p, Fcurrent_thread ());
880 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
881 non-Lisp data, so do it only for slots which should not be zero. */
882 p->infd = -1;
883 p->outfd = -1;
884 for (i = 0; i < PROCESS_OPEN_FDS; i++)
885 p->open_fd[i] = -1;
887 #ifdef HAVE_GNUTLS
888 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
889 #endif
891 /* If name is already in use, modify it until it is unused. */
893 name1 = name;
894 for (i = 1; ; i++)
896 tem = Fget_process (name1);
897 if (NILP (tem)) break;
898 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
900 name = name1;
901 pset_name (p, name);
902 pset_sentinel (p, Qinternal_default_process_sentinel);
903 pset_filter (p, Qinternal_default_process_filter);
904 XSETPROCESS (val, p);
905 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
906 return val;
909 static void
910 remove_process (register Lisp_Object proc)
912 register Lisp_Object pair;
914 pair = Frassq (proc, Vprocess_alist);
915 Vprocess_alist = Fdelq (pair, Vprocess_alist);
917 deactivate_process (proc);
920 void
921 update_processes_for_thread_death (Lisp_Object dying_thread)
923 Lisp_Object pair;
925 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
927 Lisp_Object process = XCDR (XCAR (pair));
928 if (EQ (XPROCESS (process)->thread, dying_thread))
930 struct Lisp_Process *proc = XPROCESS (process);
932 proc->thread = Qnil;
933 if (proc->infd >= 0)
934 fd_callback_info[proc->infd].thread = NULL;
935 if (proc->outfd >= 0)
936 fd_callback_info[proc->outfd].thread = NULL;
942 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
943 doc: /* Return t if OBJECT is a process. */)
944 (Lisp_Object object)
946 return PROCESSP (object) ? Qt : Qnil;
949 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
950 doc: /* Return the process named NAME, or nil if there is none. */)
951 (register Lisp_Object name)
953 if (PROCESSP (name))
954 return name;
955 CHECK_STRING (name);
956 return Fcdr (Fassoc (name, Vprocess_alist));
959 /* This is how commands for the user decode process arguments. It
960 accepts a process, a process name, a buffer, a buffer name, or nil.
961 Buffers denote the first process in the buffer, and nil denotes the
962 current buffer. */
964 static Lisp_Object
965 get_process (register Lisp_Object name)
967 register Lisp_Object proc, obj;
968 if (STRINGP (name))
970 obj = Fget_process (name);
971 if (NILP (obj))
972 obj = Fget_buffer (name);
973 if (NILP (obj))
974 error ("Process %s does not exist", SDATA (name));
976 else if (NILP (name))
977 obj = Fcurrent_buffer ();
978 else
979 obj = name;
981 /* Now obj should be either a buffer object or a process object.
983 if (BUFFERP (obj))
985 proc = Fget_buffer_process (obj);
986 if (NILP (proc))
987 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
989 else
991 CHECK_PROCESS (obj);
992 proc = obj;
994 return proc;
998 /* Fdelete_process promises to immediately forget about the process, but in
999 reality, Emacs needs to remember those processes until they have been
1000 treated by the SIGCHLD handler and waitpid has been invoked on them;
1001 otherwise they might fill up the kernel's process table.
1003 Some processes created by call-process are also put onto this list.
1005 Members of this list are (process-ID . filename) pairs. The
1006 process-ID is a number; the filename, if a string, is a file that
1007 needs to be removed after the process exits. */
1008 static Lisp_Object deleted_pid_list;
1010 void
1011 record_deleted_pid (pid_t pid, Lisp_Object filename)
1013 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
1014 /* GC treated elements set to nil. */
1015 Fdelq (Qnil, deleted_pid_list));
1019 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
1020 doc: /* Delete PROCESS: kill it and forget about it immediately.
1021 PROCESS may be a process, a buffer, the name of a process or buffer, or
1022 nil, indicating the current buffer's process. */)
1023 (register Lisp_Object process)
1025 register struct Lisp_Process *p;
1027 process = get_process (process);
1028 p = XPROCESS (process);
1030 p->raw_status_new = 0;
1031 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1033 pset_status (p, list2 (Qexit, make_number (0)));
1034 p->tick = ++process_tick;
1035 status_notify (p);
1036 redisplay_preserve_echo_area (13);
1038 else
1040 if (p->alive)
1041 record_kill_process (p, Qnil);
1043 if (p->infd >= 0)
1045 /* Update P's status, since record_kill_process will make the
1046 SIGCHLD handler update deleted_pid_list, not *P. */
1047 Lisp_Object symbol;
1048 if (p->raw_status_new)
1049 update_status (p);
1050 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
1051 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
1052 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
1054 p->tick = ++process_tick;
1055 status_notify (p);
1056 redisplay_preserve_echo_area (13);
1059 remove_process (process);
1060 return Qnil;
1063 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
1064 doc: /* Return the status of PROCESS.
1065 The returned value is one of the following symbols:
1066 run -- for a process that is running.
1067 stop -- for a process stopped but continuable.
1068 exit -- for a process that has exited.
1069 signal -- for a process that has got a fatal signal.
1070 open -- for a network stream connection that is open.
1071 listen -- for a network stream server that is listening.
1072 closed -- for a network stream connection that is closed.
1073 connect -- when waiting for a non-blocking connection to complete.
1074 failed -- when a non-blocking connection has failed.
1075 nil -- if arg is a process name and no such process exists.
1076 PROCESS may be a process, a buffer, the name of a process, or
1077 nil, indicating the current buffer's process. */)
1078 (register Lisp_Object process)
1080 register struct Lisp_Process *p;
1081 register Lisp_Object status;
1083 if (STRINGP (process))
1084 process = Fget_process (process);
1085 else
1086 process = get_process (process);
1088 if (NILP (process))
1089 return process;
1091 p = XPROCESS (process);
1092 if (p->raw_status_new)
1093 update_status (p);
1094 status = p->status;
1095 if (CONSP (status))
1096 status = XCAR (status);
1097 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1099 if (EQ (status, Qexit))
1100 status = Qclosed;
1101 else if (EQ (p->command, Qt))
1102 status = Qstop;
1103 else if (EQ (status, Qrun))
1104 status = Qopen;
1106 return status;
1109 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
1110 1, 1, 0,
1111 doc: /* Return the exit status of PROCESS or the signal number that killed it.
1112 If PROCESS has not yet exited or died, return 0. */)
1113 (register Lisp_Object process)
1115 CHECK_PROCESS (process);
1116 if (XPROCESS (process)->raw_status_new)
1117 update_status (XPROCESS (process));
1118 if (CONSP (XPROCESS (process)->status))
1119 return XCAR (XCDR (XPROCESS (process)->status));
1120 return make_number (0);
1123 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1124 doc: /* Return the process id of PROCESS.
1125 This is the pid of the external process which PROCESS uses or talks to.
1126 For a network connection, this value is nil. */)
1127 (register Lisp_Object process)
1129 pid_t pid;
1131 CHECK_PROCESS (process);
1132 pid = XPROCESS (process)->pid;
1133 return (pid ? make_fixnum_or_float (pid) : Qnil);
1136 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1137 doc: /* Return the name of PROCESS, as a string.
1138 This is the name of the program invoked in PROCESS,
1139 possibly modified to make it unique among process names. */)
1140 (register Lisp_Object process)
1142 CHECK_PROCESS (process);
1143 return XPROCESS (process)->name;
1146 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1147 doc: /* Return the command that was executed to start PROCESS.
1148 This is a list of strings, the first string being the program executed
1149 and the rest of the strings being the arguments given to it.
1150 For a network or serial process, this is nil (process is running) or t
1151 \(process is stopped). */)
1152 (register Lisp_Object process)
1154 CHECK_PROCESS (process);
1155 return XPROCESS (process)->command;
1158 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1159 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1160 This is the terminal that the process itself reads and writes on,
1161 not the name of the pty that Emacs uses to talk with that terminal. */)
1162 (register Lisp_Object process)
1164 CHECK_PROCESS (process);
1165 return XPROCESS (process)->tty_name;
1168 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1169 2, 2, 0,
1170 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1171 Return BUFFER. */)
1172 (register Lisp_Object process, Lisp_Object buffer)
1174 struct Lisp_Process *p;
1176 CHECK_PROCESS (process);
1177 if (!NILP (buffer))
1178 CHECK_BUFFER (buffer);
1179 p = XPROCESS (process);
1180 pset_buffer (p, buffer);
1181 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1182 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1183 setup_process_coding_systems (process);
1184 return buffer;
1187 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1188 1, 1, 0,
1189 doc: /* Return the buffer PROCESS is associated with.
1190 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1191 (register Lisp_Object process)
1193 CHECK_PROCESS (process);
1194 return XPROCESS (process)->buffer;
1197 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1198 1, 1, 0,
1199 doc: /* Return the marker for the end of the last output from PROCESS. */)
1200 (register Lisp_Object process)
1202 CHECK_PROCESS (process);
1203 return XPROCESS (process)->mark;
1206 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1207 2, 2, 0,
1208 doc: /* Give PROCESS the filter function FILTER; nil means default.
1209 A value of t means stop accepting output from the process.
1211 When a process has a non-default filter, its buffer is not used for output.
1212 Instead, each time it does output, the entire string of output is
1213 passed to the filter.
1215 The filter gets two arguments: the process and the string of output.
1216 The string argument is normally a multibyte string, except:
1217 - if the process' input coding system is no-conversion or raw-text,
1218 it is a unibyte string (the non-converted input), or else
1219 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1220 string (the result of converting the decoded input multibyte
1221 string to unibyte with `string-make-unibyte'). */)
1222 (register Lisp_Object process, Lisp_Object filter)
1224 struct Lisp_Process *p;
1226 CHECK_PROCESS (process);
1227 p = XPROCESS (process);
1229 /* Don't signal an error if the process' input file descriptor
1230 is closed. This could make debugging Lisp more difficult,
1231 for example when doing something like
1233 (setq process (start-process ...))
1234 (debug)
1235 (set-process-filter process ...) */
1237 if (NILP (filter))
1238 filter = Qinternal_default_process_filter;
1240 if (p->infd >= 0)
1242 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1243 delete_read_fd (p->infd);
1244 else if (EQ (p->filter, Qt)
1245 /* Network or serial process not stopped: */
1246 && !EQ (p->command, Qt))
1247 delete_read_fd (p->infd);
1250 pset_filter (p, filter);
1251 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1252 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1253 setup_process_coding_systems (process);
1254 return filter;
1257 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1258 1, 1, 0,
1259 doc: /* Return the filter function of PROCESS.
1260 See `set-process-filter' for more info on filter functions. */)
1261 (register Lisp_Object process)
1263 CHECK_PROCESS (process);
1264 return XPROCESS (process)->filter;
1267 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1268 2, 2, 0,
1269 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1270 The sentinel is called as a function when the process changes state.
1271 It gets two arguments: the process, and a string describing the change. */)
1272 (register Lisp_Object process, Lisp_Object sentinel)
1274 struct Lisp_Process *p;
1276 CHECK_PROCESS (process);
1277 p = XPROCESS (process);
1279 if (NILP (sentinel))
1280 sentinel = Qinternal_default_process_sentinel;
1282 pset_sentinel (p, sentinel);
1283 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1284 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1285 return sentinel;
1288 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1289 1, 1, 0,
1290 doc: /* Return the sentinel of PROCESS.
1291 See `set-process-sentinel' for more info on sentinels. */)
1292 (register Lisp_Object process)
1294 CHECK_PROCESS (process);
1295 return XPROCESS (process)->sentinel;
1298 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1299 2, 2, 0,
1300 doc: /* FIXME */)
1301 (Lisp_Object process, Lisp_Object thread)
1303 struct Lisp_Process *proc;
1304 struct thread_state *tstate;
1306 CHECK_PROCESS (process);
1307 if (NILP (thread))
1308 tstate = NULL;
1309 else
1311 CHECK_THREAD (thread);
1312 tstate = XTHREAD (thread);
1315 proc = XPROCESS (process);
1316 proc->thread = thread;
1317 if (proc->infd >= 0)
1318 fd_callback_info[proc->infd].thread = tstate;
1319 if (proc->outfd >= 0)
1320 fd_callback_info[proc->outfd].thread = tstate;
1322 return thread;
1325 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1326 1, 1, 0,
1327 doc: /* FIXME */)
1328 (Lisp_Object process)
1330 CHECK_PROCESS (process);
1331 return XPROCESS (process)->thread;
1334 DEFUN ("set-process-window-size", Fset_process_window_size,
1335 Sset_process_window_size, 3, 3, 0,
1336 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1337 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1339 CHECK_PROCESS (process);
1341 /* All known platforms store window sizes as 'unsigned short'. */
1342 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1343 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1345 if (XPROCESS (process)->infd < 0
1346 || (set_window_size (XPROCESS (process)->infd,
1347 XINT (height), XINT (width))
1348 < 0))
1349 return Qnil;
1350 else
1351 return Qt;
1354 DEFUN ("set-process-inherit-coding-system-flag",
1355 Fset_process_inherit_coding_system_flag,
1356 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1357 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1358 If the second argument FLAG is non-nil, then the variable
1359 `buffer-file-coding-system' of the buffer associated with PROCESS
1360 will be bound to the value of the coding system used to decode
1361 the process output.
1363 This is useful when the coding system specified for the process buffer
1364 leaves either the character code conversion or the end-of-line conversion
1365 unspecified, or if the coding system used to decode the process output
1366 is more appropriate for saving the process buffer.
1368 Binding the variable `inherit-process-coding-system' to non-nil before
1369 starting the process is an alternative way of setting the inherit flag
1370 for the process which will run.
1372 This function returns FLAG. */)
1373 (register Lisp_Object process, Lisp_Object flag)
1375 CHECK_PROCESS (process);
1376 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1377 return flag;
1380 DEFUN ("set-process-query-on-exit-flag",
1381 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1382 2, 2, 0,
1383 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1384 If the second argument FLAG is non-nil, Emacs will query the user before
1385 exiting or killing a buffer if PROCESS is running. This function
1386 returns FLAG. */)
1387 (register Lisp_Object process, Lisp_Object flag)
1389 CHECK_PROCESS (process);
1390 XPROCESS (process)->kill_without_query = NILP (flag);
1391 return flag;
1394 DEFUN ("process-query-on-exit-flag",
1395 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1396 1, 1, 0,
1397 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1398 (register Lisp_Object process)
1400 CHECK_PROCESS (process);
1401 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1404 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1405 1, 2, 0,
1406 doc: /* Return the contact info of PROCESS; t for a real child.
1407 For a network or serial connection, the value depends on the optional
1408 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1409 SERVICE) for a network connection or (PORT SPEED) for a serial
1410 connection. If KEY is t, the complete contact information for the
1411 connection is returned, else the specific value for the keyword KEY is
1412 returned. See `make-network-process' or `make-serial-process' for a
1413 list of keywords. */)
1414 (register Lisp_Object process, Lisp_Object key)
1416 Lisp_Object contact;
1418 CHECK_PROCESS (process);
1419 contact = XPROCESS (process)->childp;
1421 #ifdef DATAGRAM_SOCKETS
1422 if (DATAGRAM_CONN_P (process)
1423 && (EQ (key, Qt) || EQ (key, QCremote)))
1424 contact = Fplist_put (contact, QCremote,
1425 Fprocess_datagram_address (process));
1426 #endif
1428 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1429 return contact;
1430 if (NILP (key) && NETCONN_P (process))
1431 return list2 (Fplist_get (contact, QChost),
1432 Fplist_get (contact, QCservice));
1433 if (NILP (key) && SERIALCONN_P (process))
1434 return list2 (Fplist_get (contact, QCport),
1435 Fplist_get (contact, QCspeed));
1436 return Fplist_get (contact, key);
1439 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1440 1, 1, 0,
1441 doc: /* Return the plist of PROCESS. */)
1442 (register Lisp_Object process)
1444 CHECK_PROCESS (process);
1445 return XPROCESS (process)->plist;
1448 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1449 2, 2, 0,
1450 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1451 (register Lisp_Object process, Lisp_Object plist)
1453 CHECK_PROCESS (process);
1454 CHECK_LIST (plist);
1456 pset_plist (XPROCESS (process), plist);
1457 return plist;
1460 #if 0 /* Turned off because we don't currently record this info
1461 in the process. Perhaps add it. */
1462 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1463 doc: /* Return the connection type of PROCESS.
1464 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1465 a socket connection. */)
1466 (Lisp_Object process)
1468 return XPROCESS (process)->type;
1470 #endif
1472 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1473 doc: /* Return the connection type of PROCESS.
1474 The value is either the symbol `real', `network', or `serial'.
1475 PROCESS may be a process, a buffer, the name of a process or buffer, or
1476 nil, indicating the current buffer's process. */)
1477 (Lisp_Object process)
1479 Lisp_Object proc;
1480 proc = get_process (process);
1481 return XPROCESS (proc)->type;
1484 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1485 1, 2, 0,
1486 doc: /* Convert network ADDRESS from internal format to a string.
1487 A 4 or 5 element vector represents an IPv4 address (with port number).
1488 An 8 or 9 element vector represents an IPv6 address (with port number).
1489 If optional second argument OMIT-PORT is non-nil, don't include a port
1490 number in the string, even when present in ADDRESS.
1491 Returns nil if format of ADDRESS is invalid. */)
1492 (Lisp_Object address, Lisp_Object omit_port)
1494 if (NILP (address))
1495 return Qnil;
1497 if (STRINGP (address)) /* AF_LOCAL */
1498 return address;
1500 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1502 register struct Lisp_Vector *p = XVECTOR (address);
1503 ptrdiff_t size = p->header.size;
1504 Lisp_Object args[10];
1505 int nargs, i;
1507 if (size == 4 || (size == 5 && !NILP (omit_port)))
1509 args[0] = build_string ("%d.%d.%d.%d");
1510 nargs = 4;
1512 else if (size == 5)
1514 args[0] = build_string ("%d.%d.%d.%d:%d");
1515 nargs = 5;
1517 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1519 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1520 nargs = 8;
1522 else if (size == 9)
1524 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1525 nargs = 9;
1527 else
1528 return Qnil;
1530 for (i = 0; i < nargs; i++)
1532 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1533 return Qnil;
1535 if (nargs <= 5 /* IPv4 */
1536 && i < 4 /* host, not port */
1537 && XINT (p->contents[i]) > 255)
1538 return Qnil;
1540 args[i+1] = p->contents[i];
1543 return Fformat (nargs+1, args);
1546 if (CONSP (address))
1548 Lisp_Object args[2];
1549 args[0] = build_string ("<Family %d>");
1550 args[1] = Fcar (address);
1551 return Fformat (2, args);
1554 return Qnil;
1557 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1558 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1559 (void)
1561 return Fmapcar (Qcdr, Vprocess_alist);
1564 /* Starting asynchronous inferior processes. */
1566 static void start_process_unwind (Lisp_Object proc);
1568 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1569 doc: /* Start a program in a subprocess. Return the process object for it.
1570 NAME is name for process. It is modified if necessary to make it unique.
1571 BUFFER is the buffer (or buffer name) to associate with the process.
1573 Process output (both standard output and standard error streams) goes
1574 at end of BUFFER, unless you specify an output stream or filter
1575 function to handle the output. BUFFER may also be nil, meaning that
1576 this process is not associated with any buffer.
1578 PROGRAM is the program file name. It is searched for in `exec-path'
1579 (which see). If nil, just associate a pty with the buffer. Remaining
1580 arguments are strings to give program as arguments.
1582 If you want to separate standard output from standard error, invoke
1583 the command through a shell and redirect one of them using the shell
1584 syntax.
1586 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1587 (ptrdiff_t nargs, Lisp_Object *args)
1589 Lisp_Object buffer, name, program, proc, current_dir, tem;
1590 register unsigned char **new_argv;
1591 ptrdiff_t i;
1592 ptrdiff_t count = SPECPDL_INDEX ();
1594 buffer = args[1];
1595 if (!NILP (buffer))
1596 buffer = Fget_buffer_create (buffer);
1598 /* Make sure that the child will be able to chdir to the current
1599 buffer's current directory, or its unhandled equivalent. We
1600 can't just have the child check for an error when it does the
1601 chdir, since it's in a vfork.
1603 We have to GCPRO around this because Fexpand_file_name and
1604 Funhandled_file_name_directory might call a file name handling
1605 function. The argument list is protected by the caller, so all
1606 we really have to worry about is buffer. */
1608 struct gcpro gcpro1;
1609 GCPRO1 (buffer);
1610 current_dir = encode_current_directory ();
1611 UNGCPRO;
1614 name = args[0];
1615 CHECK_STRING (name);
1617 program = args[2];
1619 if (!NILP (program))
1620 CHECK_STRING (program);
1622 proc = make_process (name);
1623 /* If an error occurs and we can't start the process, we want to
1624 remove it from the process list. This means that each error
1625 check in create_process doesn't need to call remove_process
1626 itself; it's all taken care of here. */
1627 record_unwind_protect (start_process_unwind, proc);
1629 pset_childp (XPROCESS (proc), Qt);
1630 pset_plist (XPROCESS (proc), Qnil);
1631 pset_type (XPROCESS (proc), Qreal);
1632 pset_buffer (XPROCESS (proc), buffer);
1633 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1634 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1635 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1637 #ifdef HAVE_GNUTLS
1638 /* AKA GNUTLS_INITSTAGE(proc). */
1639 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1640 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1641 #endif
1643 #ifdef ADAPTIVE_READ_BUFFERING
1644 XPROCESS (proc)->adaptive_read_buffering
1645 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1646 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1647 #endif
1649 /* Make the process marker point into the process buffer (if any). */
1650 if (BUFFERP (buffer))
1651 set_marker_both (XPROCESS (proc)->mark, buffer,
1652 BUF_ZV (XBUFFER (buffer)),
1653 BUF_ZV_BYTE (XBUFFER (buffer)));
1656 /* Decide coding systems for communicating with the process. Here
1657 we don't setup the structure coding_system nor pay attention to
1658 unibyte mode. They are done in create_process. */
1660 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1661 Lisp_Object coding_systems = Qt;
1662 Lisp_Object val, *args2;
1663 struct gcpro gcpro1, gcpro2;
1665 val = Vcoding_system_for_read;
1666 if (NILP (val))
1668 args2 = alloca ((nargs + 1) * sizeof *args2);
1669 args2[0] = Qstart_process;
1670 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1671 GCPRO2 (proc, current_dir);
1672 if (!NILP (program))
1673 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1674 UNGCPRO;
1675 if (CONSP (coding_systems))
1676 val = XCAR (coding_systems);
1677 else if (CONSP (Vdefault_process_coding_system))
1678 val = XCAR (Vdefault_process_coding_system);
1680 pset_decode_coding_system (XPROCESS (proc), val);
1682 val = Vcoding_system_for_write;
1683 if (NILP (val))
1685 if (EQ (coding_systems, Qt))
1687 args2 = alloca ((nargs + 1) * sizeof *args2);
1688 args2[0] = Qstart_process;
1689 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1690 GCPRO2 (proc, current_dir);
1691 if (!NILP (program))
1692 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1693 UNGCPRO;
1695 if (CONSP (coding_systems))
1696 val = XCDR (coding_systems);
1697 else if (CONSP (Vdefault_process_coding_system))
1698 val = XCDR (Vdefault_process_coding_system);
1700 pset_encode_coding_system (XPROCESS (proc), val);
1701 /* Note: At this moment, the above coding system may leave
1702 text-conversion or eol-conversion unspecified. They will be
1703 decided after we read output from the process and decode it by
1704 some coding system, or just before we actually send a text to
1705 the process. */
1709 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1710 XPROCESS (proc)->decoding_carryover = 0;
1711 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1713 XPROCESS (proc)->inherit_coding_system_flag
1714 = !(NILP (buffer) || !inherit_process_coding_system);
1716 if (!NILP (program))
1718 /* If program file name is not absolute, search our path for it.
1719 Put the name we will really use in TEM. */
1720 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1721 && !(SCHARS (program) > 1
1722 && IS_DEVICE_SEP (SREF (program, 1))))
1724 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1726 tem = Qnil;
1727 GCPRO4 (name, program, buffer, current_dir);
1728 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1729 UNGCPRO;
1730 if (NILP (tem))
1731 report_file_error ("Searching for program", program);
1732 tem = Fexpand_file_name (tem, Qnil);
1734 else
1736 if (!NILP (Ffile_directory_p (program)))
1737 error ("Specified program for new process is a directory");
1738 tem = program;
1741 /* If program file name starts with /: for quoting a magic name,
1742 discard that. */
1743 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1744 && SREF (tem, 1) == ':')
1745 tem = Fsubstring (tem, make_number (2), Qnil);
1748 Lisp_Object arg_encoding = Qnil;
1749 struct gcpro gcpro1;
1750 GCPRO1 (tem);
1752 /* Encode the file name and put it in NEW_ARGV.
1753 That's where the child will use it to execute the program. */
1754 tem = list1 (ENCODE_FILE (tem));
1756 /* Here we encode arguments by the coding system used for sending
1757 data to the process. We don't support using different coding
1758 systems for encoding arguments and for encoding data sent to the
1759 process. */
1761 for (i = 3; i < nargs; i++)
1763 tem = Fcons (args[i], tem);
1764 CHECK_STRING (XCAR (tem));
1765 if (STRING_MULTIBYTE (XCAR (tem)))
1767 if (NILP (arg_encoding))
1768 arg_encoding = (complement_process_encoding_system
1769 (XPROCESS (proc)->encode_coding_system));
1770 XSETCAR (tem,
1771 code_convert_string_norecord
1772 (XCAR (tem), arg_encoding, 1));
1776 UNGCPRO;
1779 /* Now that everything is encoded we can collect the strings into
1780 NEW_ARGV. */
1781 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1782 new_argv[nargs - 2] = 0;
1784 for (i = nargs - 2; i-- != 0; )
1786 new_argv[i] = SDATA (XCAR (tem));
1787 tem = XCDR (tem);
1790 create_process (proc, (char **) new_argv, current_dir);
1792 else
1793 create_pty (proc);
1795 return unbind_to (count, proc);
1798 /* This function is the unwind_protect form for Fstart_process. If
1799 PROC doesn't have its pid set, then we know someone has signaled
1800 an error and the process wasn't started successfully, so we should
1801 remove it from the process list. */
1802 static void
1803 start_process_unwind (Lisp_Object proc)
1805 if (!PROCESSP (proc))
1806 emacs_abort ();
1808 /* Was PROC started successfully?
1809 -2 is used for a pty with no process, eg for gdb. */
1810 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1811 remove_process (proc);
1814 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1816 static void
1817 close_process_fd (int *fd_addr)
1819 int fd = *fd_addr;
1820 if (0 <= fd)
1822 *fd_addr = -1;
1823 emacs_close (fd);
1827 /* Indexes of file descriptors in open_fds. */
1828 enum
1830 /* The pipe from Emacs to its subprocess. */
1831 SUBPROCESS_STDIN,
1832 WRITE_TO_SUBPROCESS,
1834 /* The main pipe from the subprocess to Emacs. */
1835 READ_FROM_SUBPROCESS,
1836 SUBPROCESS_STDOUT,
1838 /* The pipe from the subprocess to Emacs that is closed when the
1839 subprocess execs. */
1840 READ_FROM_EXEC_MONITOR,
1841 EXEC_MONITOR_OUTPUT
1844 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1846 static void
1847 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1849 struct Lisp_Process *p = XPROCESS (process);
1850 int inchannel, outchannel;
1851 pid_t pid;
1852 int vfork_errno;
1853 int forkin, forkout;
1854 bool pty_flag = 0;
1855 char pty_name[PTY_NAME_SIZE];
1856 Lisp_Object lisp_pty_name = Qnil;
1858 inchannel = outchannel = -1;
1860 if (!NILP (Vprocess_connection_type))
1861 outchannel = inchannel = allocate_pty (pty_name);
1863 if (inchannel >= 0)
1865 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1866 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1867 /* On most USG systems it does not work to open the pty's tty here,
1868 then close it and reopen it in the child. */
1869 /* Don't let this terminal become our controlling terminal
1870 (in case we don't have one). */
1871 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1872 if (forkin < 0)
1873 report_file_error ("Opening pty", Qnil);
1874 p->open_fd[SUBPROCESS_STDIN] = forkin;
1875 #else
1876 forkin = forkout = -1;
1877 #endif /* not USG, or USG_SUBTTY_WORKS */
1878 pty_flag = 1;
1879 lisp_pty_name = build_string (pty_name);
1881 else
1883 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1884 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1885 report_file_error ("Creating pipe", Qnil);
1886 forkin = p->open_fd[SUBPROCESS_STDIN];
1887 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1888 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1889 forkout = p->open_fd[SUBPROCESS_STDOUT];
1892 #ifndef WINDOWSNT
1893 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1894 report_file_error ("Creating pipe", Qnil);
1895 #endif
1897 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1898 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1900 /* Record this as an active process, with its channels. */
1901 chan_process[inchannel] = process;
1902 p->infd = inchannel;
1903 p->outfd = outchannel;
1905 /* Previously we recorded the tty descriptor used in the subprocess.
1906 It was only used for getting the foreground tty process, so now
1907 we just reopen the device (see emacs_get_tty_pgrp) as this is
1908 more portable (see USG_SUBTTY_WORKS above). */
1910 p->pty_flag = pty_flag;
1911 pset_status (p, Qrun);
1913 add_process_read_fd (inchannel);
1915 /* This may signal an error. */
1916 setup_process_coding_systems (process);
1918 block_input ();
1919 block_child_signal ();
1921 #ifndef WINDOWSNT
1922 /* vfork, and prevent local vars from being clobbered by the vfork. */
1924 Lisp_Object volatile current_dir_volatile = current_dir;
1925 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1926 char **volatile new_argv_volatile = new_argv;
1927 int volatile forkin_volatile = forkin;
1928 int volatile forkout_volatile = forkout;
1929 struct Lisp_Process *p_volatile = p;
1931 pid = vfork ();
1933 current_dir = current_dir_volatile;
1934 lisp_pty_name = lisp_pty_name_volatile;
1935 new_argv = new_argv_volatile;
1936 forkin = forkin_volatile;
1937 forkout = forkout_volatile;
1938 p = p_volatile;
1940 pty_flag = p->pty_flag;
1943 if (pid == 0)
1944 #endif /* not WINDOWSNT */
1946 int xforkin = forkin;
1947 int xforkout = forkout;
1949 /* Make the pty be the controlling terminal of the process. */
1950 #ifdef HAVE_PTYS
1951 /* First, disconnect its current controlling terminal. */
1952 /* We tried doing setsid only if pty_flag, but it caused
1953 process_set_signal to fail on SGI when using a pipe. */
1954 setsid ();
1955 /* Make the pty's terminal the controlling terminal. */
1956 if (pty_flag && xforkin >= 0)
1958 #ifdef TIOCSCTTY
1959 /* We ignore the return value
1960 because faith@cs.unc.edu says that is necessary on Linux. */
1961 ioctl (xforkin, TIOCSCTTY, 0);
1962 #endif
1964 #if defined (LDISC1)
1965 if (pty_flag && xforkin >= 0)
1967 struct termios t;
1968 tcgetattr (xforkin, &t);
1969 t.c_lflag = LDISC1;
1970 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1971 emacs_perror ("create_process/tcsetattr LDISC1");
1973 #else
1974 #if defined (NTTYDISC) && defined (TIOCSETD)
1975 if (pty_flag && xforkin >= 0)
1977 /* Use new line discipline. */
1978 int ldisc = NTTYDISC;
1979 ioctl (xforkin, TIOCSETD, &ldisc);
1981 #endif
1982 #endif
1983 #ifdef TIOCNOTTY
1984 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1985 can do TIOCSPGRP only to the process's controlling tty. */
1986 if (pty_flag)
1988 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1989 I can't test it since I don't have 4.3. */
1990 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1991 if (j >= 0)
1993 ioctl (j, TIOCNOTTY, 0);
1994 emacs_close (j);
1997 #endif /* TIOCNOTTY */
1999 #if !defined (DONT_REOPEN_PTY)
2000 /*** There is a suggestion that this ought to be a
2001 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2002 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2003 that system does seem to need this code, even though
2004 both TIOCSCTTY is defined. */
2005 /* Now close the pty (if we had it open) and reopen it.
2006 This makes the pty the controlling terminal of the subprocess. */
2007 if (pty_flag)
2010 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2011 would work? */
2012 if (xforkin >= 0)
2013 emacs_close (xforkin);
2014 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
2016 if (xforkin < 0)
2018 emacs_perror (SSDATA (lisp_pty_name));
2019 _exit (EXIT_CANCELED);
2023 #endif /* not DONT_REOPEN_PTY */
2025 #ifdef SETUP_SLAVE_PTY
2026 if (pty_flag)
2028 SETUP_SLAVE_PTY;
2030 #endif /* SETUP_SLAVE_PTY */
2031 #endif /* HAVE_PTYS */
2033 signal (SIGINT, SIG_DFL);
2034 signal (SIGQUIT, SIG_DFL);
2036 /* Emacs ignores SIGPIPE, but the child should not. */
2037 signal (SIGPIPE, SIG_DFL);
2039 /* Stop blocking SIGCHLD in the child. */
2040 unblock_child_signal ();
2042 if (pty_flag)
2043 child_setup_tty (xforkout);
2044 #ifdef WINDOWSNT
2045 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
2046 #else /* not WINDOWSNT */
2047 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
2048 #endif /* not WINDOWSNT */
2051 /* Back in the parent process. */
2053 vfork_errno = errno;
2054 p->pid = pid;
2055 if (pid >= 0)
2056 p->alive = 1;
2058 /* Stop blocking in the parent. */
2059 unblock_child_signal ();
2060 unblock_input ();
2062 if (pid < 0)
2063 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2064 else
2066 /* vfork succeeded. */
2068 /* Close the pipe ends that the child uses, or the child's pty. */
2069 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2070 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2072 #ifdef WINDOWSNT
2073 register_child (pid, inchannel);
2074 #endif /* WINDOWSNT */
2076 pset_tty_name (p, lisp_pty_name);
2078 #ifndef WINDOWSNT
2079 /* Wait for child_setup to complete in case that vfork is
2080 actually defined as fork. The descriptor
2081 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2082 of a pipe is closed at the child side either by close-on-exec
2083 on successful execve or the _exit call in child_setup. */
2085 char dummy;
2087 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2088 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2089 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2091 #endif
2095 static void
2096 create_pty (Lisp_Object process)
2098 struct Lisp_Process *p = XPROCESS (process);
2099 char pty_name[PTY_NAME_SIZE];
2100 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
2102 if (pty_fd >= 0)
2104 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2105 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2106 /* On most USG systems it does not work to open the pty's tty here,
2107 then close it and reopen it in the child. */
2108 /* Don't let this terminal become our controlling terminal
2109 (in case we don't have one). */
2110 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2111 if (forkout < 0)
2112 report_file_error ("Opening pty", Qnil);
2113 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2114 #if defined (DONT_REOPEN_PTY)
2115 /* In the case that vfork is defined as fork, the parent process
2116 (Emacs) may send some data before the child process completes
2117 tty options setup. So we setup tty before forking. */
2118 child_setup_tty (forkout);
2119 #endif /* DONT_REOPEN_PTY */
2120 #endif /* not USG, or USG_SUBTTY_WORKS */
2122 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2124 /* Record this as an active process, with its channels.
2125 As a result, child_setup will close Emacs's side of the pipes. */
2126 chan_process[pty_fd] = process;
2127 p->infd = pty_fd;
2128 p->outfd = pty_fd;
2130 /* Previously we recorded the tty descriptor used in the subprocess.
2131 It was only used for getting the foreground tty process, so now
2132 we just reopen the device (see emacs_get_tty_pgrp) as this is
2133 more portable (see USG_SUBTTY_WORKS above). */
2135 p->pty_flag = 1;
2136 pset_status (p, Qrun);
2137 setup_process_coding_systems (process);
2139 add_non_keyboard_read_fd (pty_fd);
2141 pset_tty_name (p, build_string (pty_name));
2144 p->pid = -2;
2148 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2149 The address family of sa is not included in the result. */
2151 static Lisp_Object
2152 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2154 Lisp_Object address;
2155 int i;
2156 unsigned char *cp;
2157 register struct Lisp_Vector *p;
2159 /* Workaround for a bug in getsockname on BSD: Names bound to
2160 sockets in the UNIX domain are inaccessible; getsockname returns
2161 a zero length name. */
2162 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2163 return empty_unibyte_string;
2165 switch (sa->sa_family)
2167 case AF_INET:
2169 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2170 len = sizeof (sin->sin_addr) + 1;
2171 address = Fmake_vector (make_number (len), Qnil);
2172 p = XVECTOR (address);
2173 p->contents[--len] = make_number (ntohs (sin->sin_port));
2174 cp = (unsigned char *) &sin->sin_addr;
2175 break;
2177 #ifdef AF_INET6
2178 case AF_INET6:
2180 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2181 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2182 len = sizeof (sin6->sin6_addr)/2 + 1;
2183 address = Fmake_vector (make_number (len), Qnil);
2184 p = XVECTOR (address);
2185 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2186 for (i = 0; i < len; i++)
2187 p->contents[i] = make_number (ntohs (ip6[i]));
2188 return address;
2190 #endif
2191 #ifdef HAVE_LOCAL_SOCKETS
2192 case AF_LOCAL:
2194 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2195 for (i = 0; i < sizeof (sockun->sun_path); i++)
2196 if (sockun->sun_path[i] == 0)
2197 break;
2198 return make_unibyte_string (sockun->sun_path, i);
2200 #endif
2201 default:
2202 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2203 address = Fcons (make_number (sa->sa_family),
2204 Fmake_vector (make_number (len), Qnil));
2205 p = XVECTOR (XCDR (address));
2206 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2207 break;
2210 i = 0;
2211 while (i < len)
2212 p->contents[i++] = make_number (*cp++);
2214 return address;
2218 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2220 static int
2221 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2223 register struct Lisp_Vector *p;
2225 if (VECTORP (address))
2227 p = XVECTOR (address);
2228 if (p->header.size == 5)
2230 *familyp = AF_INET;
2231 return sizeof (struct sockaddr_in);
2233 #ifdef AF_INET6
2234 else if (p->header.size == 9)
2236 *familyp = AF_INET6;
2237 return sizeof (struct sockaddr_in6);
2239 #endif
2241 #ifdef HAVE_LOCAL_SOCKETS
2242 else if (STRINGP (address))
2244 *familyp = AF_LOCAL;
2245 return sizeof (struct sockaddr_un);
2247 #endif
2248 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2249 && VECTORP (XCDR (address)))
2251 struct sockaddr *sa;
2252 *familyp = XINT (XCAR (address));
2253 p = XVECTOR (XCDR (address));
2254 return p->header.size + sizeof (sa->sa_family);
2256 return 0;
2259 /* Convert an address object (vector or string) to an internal sockaddr.
2261 The address format has been basically validated by
2262 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2263 it could have come from user data. So if FAMILY is not valid,
2264 we return after zeroing *SA. */
2266 static void
2267 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2269 register struct Lisp_Vector *p;
2270 register unsigned char *cp = NULL;
2271 register int i;
2272 EMACS_INT hostport;
2274 memset (sa, 0, len);
2276 if (VECTORP (address))
2278 p = XVECTOR (address);
2279 if (family == AF_INET)
2281 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2282 len = sizeof (sin->sin_addr) + 1;
2283 hostport = XINT (p->contents[--len]);
2284 sin->sin_port = htons (hostport);
2285 cp = (unsigned char *)&sin->sin_addr;
2286 sa->sa_family = family;
2288 #ifdef AF_INET6
2289 else if (family == AF_INET6)
2291 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2292 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2293 len = sizeof (sin6->sin6_addr) + 1;
2294 hostport = XINT (p->contents[--len]);
2295 sin6->sin6_port = htons (hostport);
2296 for (i = 0; i < len; i++)
2297 if (INTEGERP (p->contents[i]))
2299 int j = XFASTINT (p->contents[i]) & 0xffff;
2300 ip6[i] = ntohs (j);
2302 sa->sa_family = family;
2303 return;
2305 #endif
2306 else
2307 return;
2309 else if (STRINGP (address))
2311 #ifdef HAVE_LOCAL_SOCKETS
2312 if (family == AF_LOCAL)
2314 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2315 cp = SDATA (address);
2316 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2317 sockun->sun_path[i] = *cp++;
2318 sa->sa_family = family;
2320 #endif
2321 return;
2323 else
2325 p = XVECTOR (XCDR (address));
2326 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2329 for (i = 0; i < len; i++)
2330 if (INTEGERP (p->contents[i]))
2331 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2334 #ifdef DATAGRAM_SOCKETS
2335 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2336 1, 1, 0,
2337 doc: /* Get the current datagram address associated with PROCESS. */)
2338 (Lisp_Object process)
2340 int channel;
2342 CHECK_PROCESS (process);
2344 if (!DATAGRAM_CONN_P (process))
2345 return Qnil;
2347 channel = XPROCESS (process)->infd;
2348 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2349 datagram_address[channel].len);
2352 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2353 2, 2, 0,
2354 doc: /* Set the datagram address for PROCESS to ADDRESS.
2355 Returns nil upon error setting address, ADDRESS otherwise. */)
2356 (Lisp_Object process, Lisp_Object address)
2358 int channel;
2359 int family, len;
2361 CHECK_PROCESS (process);
2363 if (!DATAGRAM_CONN_P (process))
2364 return Qnil;
2366 channel = XPROCESS (process)->infd;
2368 len = get_lisp_to_sockaddr_size (address, &family);
2369 if (len == 0 || datagram_address[channel].len != len)
2370 return Qnil;
2371 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2372 return address;
2374 #endif
2377 static const struct socket_options {
2378 /* The name of this option. Should be lowercase version of option
2379 name without SO_ prefix. */
2380 const char *name;
2381 /* Option level SOL_... */
2382 int optlevel;
2383 /* Option number SO_... */
2384 int optnum;
2385 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2386 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2387 } socket_options[] =
2389 #ifdef SO_BINDTODEVICE
2390 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2391 #endif
2392 #ifdef SO_BROADCAST
2393 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2394 #endif
2395 #ifdef SO_DONTROUTE
2396 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2397 #endif
2398 #ifdef SO_KEEPALIVE
2399 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2400 #endif
2401 #ifdef SO_LINGER
2402 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2403 #endif
2404 #ifdef SO_OOBINLINE
2405 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2406 #endif
2407 #ifdef SO_PRIORITY
2408 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2409 #endif
2410 #ifdef SO_REUSEADDR
2411 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2412 #endif
2413 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2416 /* Set option OPT to value VAL on socket S.
2418 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2419 Signals an error if setting a known option fails.
2422 static int
2423 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2425 char *name;
2426 const struct socket_options *sopt;
2427 int ret = 0;
2429 CHECK_SYMBOL (opt);
2431 name = SSDATA (SYMBOL_NAME (opt));
2432 for (sopt = socket_options; sopt->name; sopt++)
2433 if (strcmp (name, sopt->name) == 0)
2434 break;
2436 switch (sopt->opttype)
2438 case SOPT_BOOL:
2440 int optval;
2441 optval = NILP (val) ? 0 : 1;
2442 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2443 &optval, sizeof (optval));
2444 break;
2447 case SOPT_INT:
2449 int optval;
2450 if (TYPE_RANGED_INTEGERP (int, val))
2451 optval = XINT (val);
2452 else
2453 error ("Bad option value for %s", name);
2454 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2455 &optval, sizeof (optval));
2456 break;
2459 #ifdef SO_BINDTODEVICE
2460 case SOPT_IFNAME:
2462 char devname[IFNAMSIZ+1];
2464 /* This is broken, at least in the Linux 2.4 kernel.
2465 To unbind, the arg must be a zero integer, not the empty string.
2466 This should work on all systems. KFS. 2003-09-23. */
2467 memset (devname, 0, sizeof devname);
2468 if (STRINGP (val))
2470 char *arg = SSDATA (val);
2471 int len = min (strlen (arg), IFNAMSIZ);
2472 memcpy (devname, arg, len);
2474 else if (!NILP (val))
2475 error ("Bad option value for %s", name);
2476 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2477 devname, IFNAMSIZ);
2478 break;
2480 #endif
2482 #ifdef SO_LINGER
2483 case SOPT_LINGER:
2485 struct linger linger;
2487 linger.l_onoff = 1;
2488 linger.l_linger = 0;
2489 if (TYPE_RANGED_INTEGERP (int, val))
2490 linger.l_linger = XINT (val);
2491 else
2492 linger.l_onoff = NILP (val) ? 0 : 1;
2493 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2494 &linger, sizeof (linger));
2495 break;
2497 #endif
2499 default:
2500 return 0;
2503 if (ret < 0)
2505 int setsockopt_errno = errno;
2506 report_file_errno ("Cannot set network option", list2 (opt, val),
2507 setsockopt_errno);
2510 return (1 << sopt->optbit);
2514 DEFUN ("set-network-process-option",
2515 Fset_network_process_option, Sset_network_process_option,
2516 3, 4, 0,
2517 doc: /* For network process PROCESS set option OPTION to value VALUE.
2518 See `make-network-process' for a list of options and values.
2519 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2520 OPTION is not a supported option, return nil instead; otherwise return t. */)
2521 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2523 int s;
2524 struct Lisp_Process *p;
2526 CHECK_PROCESS (process);
2527 p = XPROCESS (process);
2528 if (!NETCONN1_P (p))
2529 error ("Process is not a network process");
2531 s = p->infd;
2532 if (s < 0)
2533 error ("Process is not running");
2535 if (set_socket_option (s, option, value))
2537 pset_childp (p, Fplist_put (p->childp, option, value));
2538 return Qt;
2541 if (NILP (no_error))
2542 error ("Unknown or unsupported option");
2544 return Qnil;
2548 DEFUN ("serial-process-configure",
2549 Fserial_process_configure,
2550 Sserial_process_configure,
2551 0, MANY, 0,
2552 doc: /* Configure speed, bytesize, etc. of a serial process.
2554 Arguments are specified as keyword/argument pairs. Attributes that
2555 are not given are re-initialized from the process's current
2556 configuration (available via the function `process-contact') or set to
2557 reasonable default values. The following arguments are defined:
2559 :process PROCESS
2560 :name NAME
2561 :buffer BUFFER
2562 :port PORT
2563 -- Any of these arguments can be given to identify the process that is
2564 to be configured. If none of these arguments is given, the current
2565 buffer's process is used.
2567 :speed SPEED -- SPEED is the speed of the serial port in bits per
2568 second, also called baud rate. Any value can be given for SPEED, but
2569 most serial ports work only at a few defined values between 1200 and
2570 115200, with 9600 being the most common value. If SPEED is nil, the
2571 serial port is not configured any further, i.e., all other arguments
2572 are ignored. This may be useful for special serial ports such as
2573 Bluetooth-to-serial converters which can only be configured through AT
2574 commands. A value of nil for SPEED can be used only when passed
2575 through `make-serial-process' or `serial-term'.
2577 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2578 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2580 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2581 `odd' (use odd parity), or the symbol `even' (use even parity). If
2582 PARITY is not given, no parity is used.
2584 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2585 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2586 is not given or nil, 1 stopbit is used.
2588 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2589 flowcontrol to be used, which is either nil (don't use flowcontrol),
2590 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2591 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2592 flowcontrol is used.
2594 `serial-process-configure' is called by `make-serial-process' for the
2595 initial configuration of the serial port.
2597 Examples:
2599 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2601 \(serial-process-configure
2602 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2604 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2606 usage: (serial-process-configure &rest ARGS) */)
2607 (ptrdiff_t nargs, Lisp_Object *args)
2609 struct Lisp_Process *p;
2610 Lisp_Object contact = Qnil;
2611 Lisp_Object proc = Qnil;
2612 struct gcpro gcpro1;
2614 contact = Flist (nargs, args);
2615 GCPRO1 (contact);
2617 proc = Fplist_get (contact, QCprocess);
2618 if (NILP (proc))
2619 proc = Fplist_get (contact, QCname);
2620 if (NILP (proc))
2621 proc = Fplist_get (contact, QCbuffer);
2622 if (NILP (proc))
2623 proc = Fplist_get (contact, QCport);
2624 proc = get_process (proc);
2625 p = XPROCESS (proc);
2626 if (!EQ (p->type, Qserial))
2627 error ("Not a serial process");
2629 if (NILP (Fplist_get (p->childp, QCspeed)))
2631 UNGCPRO;
2632 return Qnil;
2635 serial_configure (p, contact);
2637 UNGCPRO;
2638 return Qnil;
2641 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2642 0, MANY, 0,
2643 doc: /* Create and return a serial port process.
2645 In Emacs, serial port connections are represented by process objects,
2646 so input and output work as for subprocesses, and `delete-process'
2647 closes a serial port connection. However, a serial process has no
2648 process id, it cannot be signaled, and the status codes are different
2649 from normal processes.
2651 `make-serial-process' creates a process and a buffer, on which you
2652 probably want to use `process-send-string'. Try \\[serial-term] for
2653 an interactive terminal. See below for examples.
2655 Arguments are specified as keyword/argument pairs. The following
2656 arguments are defined:
2658 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2659 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2660 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2661 the backslashes in strings).
2663 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2664 which this function calls.
2666 :name NAME -- NAME is the name of the process. If NAME is not given,
2667 the value of PORT is used.
2669 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2670 with the process. Process output goes at the end of that buffer,
2671 unless you specify an output stream or filter function to handle the
2672 output. If BUFFER is not given, the value of NAME is used.
2674 :coding CODING -- If CODING is a symbol, it specifies the coding
2675 system used for both reading and writing for this process. If CODING
2676 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2677 ENCODING is used for writing.
2679 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2680 the process is running. If BOOL is not given, query before exiting.
2682 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2683 In the stopped state, a serial process does not accept incoming data,
2684 but you can send outgoing data. The stopped state is cleared by
2685 `continue-process' and set by `stop-process'.
2687 :filter FILTER -- Install FILTER as the process filter.
2689 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2691 :plist PLIST -- Install PLIST as the initial plist of the process.
2693 :bytesize
2694 :parity
2695 :stopbits
2696 :flowcontrol
2697 -- This function calls `serial-process-configure' to handle these
2698 arguments.
2700 The original argument list, possibly modified by later configuration,
2701 is available via the function `process-contact'.
2703 Examples:
2705 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2707 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2709 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2711 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2713 usage: (make-serial-process &rest ARGS) */)
2714 (ptrdiff_t nargs, Lisp_Object *args)
2716 int fd = -1;
2717 Lisp_Object proc, contact, port;
2718 struct Lisp_Process *p;
2719 struct gcpro gcpro1;
2720 Lisp_Object name, buffer;
2721 Lisp_Object tem, val;
2722 ptrdiff_t specpdl_count;
2724 if (nargs == 0)
2725 return Qnil;
2727 contact = Flist (nargs, args);
2728 GCPRO1 (contact);
2730 port = Fplist_get (contact, QCport);
2731 if (NILP (port))
2732 error ("No port specified");
2733 CHECK_STRING (port);
2735 if (NILP (Fplist_member (contact, QCspeed)))
2736 error (":speed not specified");
2737 if (!NILP (Fplist_get (contact, QCspeed)))
2738 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2740 name = Fplist_get (contact, QCname);
2741 if (NILP (name))
2742 name = port;
2743 CHECK_STRING (name);
2744 proc = make_process (name);
2745 specpdl_count = SPECPDL_INDEX ();
2746 record_unwind_protect (remove_process, proc);
2747 p = XPROCESS (proc);
2749 fd = serial_open (port);
2750 p->open_fd[SUBPROCESS_STDIN] = fd;
2751 p->infd = fd;
2752 p->outfd = fd;
2753 if (fd > max_desc)
2754 max_desc = fd;
2755 chan_process[fd] = proc;
2757 buffer = Fplist_get (contact, QCbuffer);
2758 if (NILP (buffer))
2759 buffer = name;
2760 buffer = Fget_buffer_create (buffer);
2761 pset_buffer (p, buffer);
2763 pset_childp (p, contact);
2764 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2765 pset_type (p, Qserial);
2766 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2767 pset_filter (p, Fplist_get (contact, QCfilter));
2768 pset_log (p, Qnil);
2769 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2770 p->kill_without_query = 1;
2771 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2772 pset_command (p, Qt);
2773 eassert (! p->pty_flag);
2775 if (!EQ (p->command, Qt))
2776 add_non_keyboard_read_fd (fd);
2778 if (BUFFERP (buffer))
2780 set_marker_both (p->mark, buffer,
2781 BUF_ZV (XBUFFER (buffer)),
2782 BUF_ZV_BYTE (XBUFFER (buffer)));
2785 tem = Fplist_member (contact, QCcoding);
2786 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2787 tem = Qnil;
2789 val = Qnil;
2790 if (!NILP (tem))
2792 val = XCAR (XCDR (tem));
2793 if (CONSP (val))
2794 val = XCAR (val);
2796 else if (!NILP (Vcoding_system_for_read))
2797 val = Vcoding_system_for_read;
2798 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2799 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2800 val = Qnil;
2801 pset_decode_coding_system (p, val);
2803 val = Qnil;
2804 if (!NILP (tem))
2806 val = XCAR (XCDR (tem));
2807 if (CONSP (val))
2808 val = XCDR (val);
2810 else if (!NILP (Vcoding_system_for_write))
2811 val = Vcoding_system_for_write;
2812 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2813 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2814 val = Qnil;
2815 pset_encode_coding_system (p, val);
2817 setup_process_coding_systems (proc);
2818 pset_decoding_buf (p, empty_unibyte_string);
2819 p->decoding_carryover = 0;
2820 pset_encoding_buf (p, empty_unibyte_string);
2821 p->inherit_coding_system_flag
2822 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2824 Fserial_process_configure (nargs, args);
2826 specpdl_ptr = specpdl + specpdl_count;
2828 UNGCPRO;
2829 return proc;
2832 /* Create a network stream/datagram client/server process. Treated
2833 exactly like a normal process when reading and writing. Primary
2834 differences are in status display and process deletion. A network
2835 connection has no PID; you cannot signal it. All you can do is
2836 stop/continue it and deactivate/close it via delete-process */
2838 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2839 0, MANY, 0,
2840 doc: /* Create and return a network server or client process.
2842 In Emacs, network connections are represented by process objects, so
2843 input and output work as for subprocesses and `delete-process' closes
2844 a network connection. However, a network process has no process id,
2845 it cannot be signaled, and the status codes are different from normal
2846 processes.
2848 Arguments are specified as keyword/argument pairs. The following
2849 arguments are defined:
2851 :name NAME -- NAME is name for process. It is modified if necessary
2852 to make it unique.
2854 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2855 with the process. Process output goes at end of that buffer, unless
2856 you specify an output stream or filter function to handle the output.
2857 BUFFER may be also nil, meaning that this process is not associated
2858 with any buffer.
2860 :host HOST -- HOST is name of the host to connect to, or its IP
2861 address. The symbol `local' specifies the local host. If specified
2862 for a server process, it must be a valid name or address for the local
2863 host, and only clients connecting to that address will be accepted.
2865 :service SERVICE -- SERVICE is name of the service desired, or an
2866 integer specifying a port number to connect to. If SERVICE is t,
2867 a random port number is selected for the server. (If Emacs was
2868 compiled with getaddrinfo, a port number can also be specified as a
2869 string, e.g. "80", as well as an integer. This is not portable.)
2871 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2872 stream type connection, `datagram' creates a datagram type connection,
2873 `seqpacket' creates a reliable datagram connection.
2875 :family FAMILY -- FAMILY is the address (and protocol) family for the
2876 service specified by HOST and SERVICE. The default (nil) is to use
2877 whatever address family (IPv4 or IPv6) that is defined for the host
2878 and port number specified by HOST and SERVICE. Other address families
2879 supported are:
2880 local -- for a local (i.e. UNIX) address specified by SERVICE.
2881 ipv4 -- use IPv4 address family only.
2882 ipv6 -- use IPv6 address family only.
2884 :local ADDRESS -- ADDRESS is the local address used for the connection.
2885 This parameter is ignored when opening a client process. When specified
2886 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2888 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2889 connection. This parameter is ignored when opening a stream server
2890 process. For a datagram server process, it specifies the initial
2891 setting of the remote datagram address. When specified for a client
2892 process, the FAMILY, HOST, and SERVICE args are ignored.
2894 The format of ADDRESS depends on the address family:
2895 - An IPv4 address is represented as an vector of integers [A B C D P]
2896 corresponding to numeric IP address A.B.C.D and port number P.
2897 - A local address is represented as a string with the address in the
2898 local address space.
2899 - An "unsupported family" address is represented by a cons (F . AV)
2900 where F is the family number and AV is a vector containing the socket
2901 address data with one element per address data byte. Do not rely on
2902 this format in portable code, as it may depend on implementation
2903 defined constants, data sizes, and data structure alignment.
2905 :coding CODING -- If CODING is a symbol, it specifies the coding
2906 system used for both reading and writing for this process. If CODING
2907 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2908 ENCODING is used for writing.
2910 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2911 return without waiting for the connection to complete; instead, the
2912 sentinel function will be called with second arg matching "open" (if
2913 successful) or "failed" when the connect completes. Default is to use
2914 a blocking connect (i.e. wait) for stream type connections.
2916 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2917 running when Emacs is exited.
2919 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2920 In the stopped state, a server process does not accept new
2921 connections, and a client process does not handle incoming traffic.
2922 The stopped state is cleared by `continue-process' and set by
2923 `stop-process'.
2925 :filter FILTER -- Install FILTER as the process filter.
2927 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2928 process filter are multibyte, otherwise they are unibyte.
2929 If this keyword is not specified, the strings are multibyte if
2930 the default value of `enable-multibyte-characters' is non-nil.
2932 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2934 :log LOG -- Install LOG as the server process log function. This
2935 function is called when the server accepts a network connection from a
2936 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2937 is the server process, CLIENT is the new process for the connection,
2938 and MESSAGE is a string.
2940 :plist PLIST -- Install PLIST as the new process' initial plist.
2942 :server QLEN -- if QLEN is non-nil, create a server process for the
2943 specified FAMILY, SERVICE, and connection type (stream or datagram).
2944 If QLEN is an integer, it is used as the max. length of the server's
2945 pending connection queue (also known as the backlog); the default
2946 queue length is 5. Default is to create a client process.
2948 The following network options can be specified for this connection:
2950 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2951 :dontroute BOOL -- Only send to directly connected hosts.
2952 :keepalive BOOL -- Send keep-alive messages on network stream.
2953 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2954 :oobinline BOOL -- Place out-of-band data in receive data stream.
2955 :priority INT -- Set protocol defined priority for sent packets.
2956 :reuseaddr BOOL -- Allow reusing a recently used local address
2957 (this is allowed by default for a server process).
2958 :bindtodevice NAME -- bind to interface NAME. Using this may require
2959 special privileges on some systems.
2961 Consult the relevant system programmer's manual pages for more
2962 information on using these options.
2965 A server process will listen for and accept connections from clients.
2966 When a client connection is accepted, a new network process is created
2967 for the connection with the following parameters:
2969 - The client's process name is constructed by concatenating the server
2970 process' NAME and a client identification string.
2971 - If the FILTER argument is non-nil, the client process will not get a
2972 separate process buffer; otherwise, the client's process buffer is a newly
2973 created buffer named after the server process' BUFFER name or process
2974 NAME concatenated with the client identification string.
2975 - The connection type and the process filter and sentinel parameters are
2976 inherited from the server process' TYPE, FILTER and SENTINEL.
2977 - The client process' contact info is set according to the client's
2978 addressing information (typically an IP address and a port number).
2979 - The client process' plist is initialized from the server's plist.
2981 Notice that the FILTER and SENTINEL args are never used directly by
2982 the server process. Also, the BUFFER argument is not used directly by
2983 the server process, but via the optional :log function, accepted (and
2984 failed) connections may be logged in the server process' buffer.
2986 The original argument list, modified with the actual connection
2987 information, is available via the `process-contact' function.
2989 usage: (make-network-process &rest ARGS) */)
2990 (ptrdiff_t nargs, Lisp_Object *args)
2992 Lisp_Object proc;
2993 Lisp_Object contact;
2994 struct Lisp_Process *p;
2995 #ifdef HAVE_GETADDRINFO
2996 struct addrinfo ai, *res, *lres;
2997 struct addrinfo hints;
2998 const char *portstring;
2999 char portbuf[128];
3000 #else /* HAVE_GETADDRINFO */
3001 struct _emacs_addrinfo
3003 int ai_family;
3004 int ai_socktype;
3005 int ai_protocol;
3006 int ai_addrlen;
3007 struct sockaddr *ai_addr;
3008 struct _emacs_addrinfo *ai_next;
3009 } ai, *res, *lres;
3010 #endif /* HAVE_GETADDRINFO */
3011 struct sockaddr_in address_in;
3012 #ifdef HAVE_LOCAL_SOCKETS
3013 struct sockaddr_un address_un;
3014 #endif
3015 int port;
3016 int ret = 0;
3017 int xerrno = 0;
3018 int s = -1, outch, inch;
3019 struct gcpro gcpro1;
3020 ptrdiff_t count = SPECPDL_INDEX ();
3021 ptrdiff_t count1;
3022 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3023 Lisp_Object tem;
3024 Lisp_Object name, buffer, host, service, address;
3025 Lisp_Object filter, sentinel;
3026 bool is_non_blocking_client = 0;
3027 bool is_server = 0;
3028 int backlog = 5;
3029 int socktype;
3030 int family = -1;
3032 if (nargs == 0)
3033 return Qnil;
3035 /* Save arguments for process-contact and clone-process. */
3036 contact = Flist (nargs, args);
3037 GCPRO1 (contact);
3039 #ifdef WINDOWSNT
3040 /* Ensure socket support is loaded if available. */
3041 init_winsock (TRUE);
3042 #endif
3044 /* :type TYPE (nil: stream, datagram */
3045 tem = Fplist_get (contact, QCtype);
3046 if (NILP (tem))
3047 socktype = SOCK_STREAM;
3048 #ifdef DATAGRAM_SOCKETS
3049 else if (EQ (tem, Qdatagram))
3050 socktype = SOCK_DGRAM;
3051 #endif
3052 #ifdef HAVE_SEQPACKET
3053 else if (EQ (tem, Qseqpacket))
3054 socktype = SOCK_SEQPACKET;
3055 #endif
3056 else
3057 error ("Unsupported connection type");
3059 /* :server BOOL */
3060 tem = Fplist_get (contact, QCserver);
3061 if (!NILP (tem))
3063 /* Don't support network sockets when non-blocking mode is
3064 not available, since a blocked Emacs is not useful. */
3065 is_server = 1;
3066 if (TYPE_RANGED_INTEGERP (int, tem))
3067 backlog = XINT (tem);
3070 /* Make QCaddress an alias for :local (server) or :remote (client). */
3071 QCaddress = is_server ? QClocal : QCremote;
3073 /* :nowait BOOL */
3074 if (!is_server && socktype != SOCK_DGRAM
3075 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3077 #ifndef NON_BLOCKING_CONNECT
3078 error ("Non-blocking connect not supported");
3079 #else
3080 is_non_blocking_client = 1;
3081 #endif
3084 name = Fplist_get (contact, QCname);
3085 buffer = Fplist_get (contact, QCbuffer);
3086 filter = Fplist_get (contact, QCfilter);
3087 sentinel = Fplist_get (contact, QCsentinel);
3089 CHECK_STRING (name);
3091 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3092 ai.ai_socktype = socktype;
3093 ai.ai_protocol = 0;
3094 ai.ai_next = NULL;
3095 res = &ai;
3097 /* :local ADDRESS or :remote ADDRESS */
3098 address = Fplist_get (contact, QCaddress);
3099 if (!NILP (address))
3101 host = service = Qnil;
3103 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3104 error ("Malformed :address");
3105 ai.ai_family = family;
3106 ai.ai_addr = alloca (ai.ai_addrlen);
3107 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3108 goto open_socket;
3111 /* :family FAMILY -- nil (for Inet), local, or integer. */
3112 tem = Fplist_get (contact, QCfamily);
3113 if (NILP (tem))
3115 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3116 family = AF_UNSPEC;
3117 #else
3118 family = AF_INET;
3119 #endif
3121 #ifdef HAVE_LOCAL_SOCKETS
3122 else if (EQ (tem, Qlocal))
3123 family = AF_LOCAL;
3124 #endif
3125 #ifdef AF_INET6
3126 else if (EQ (tem, Qipv6))
3127 family = AF_INET6;
3128 #endif
3129 else if (EQ (tem, Qipv4))
3130 family = AF_INET;
3131 else if (TYPE_RANGED_INTEGERP (int, tem))
3132 family = XINT (tem);
3133 else
3134 error ("Unknown address family");
3136 ai.ai_family = family;
3138 /* :service SERVICE -- string, integer (port number), or t (random port). */
3139 service = Fplist_get (contact, QCservice);
3141 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3142 host = Fplist_get (contact, QChost);
3143 if (!NILP (host))
3145 if (EQ (host, Qlocal))
3146 /* Depending on setup, "localhost" may map to different IPv4 and/or
3147 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3148 host = build_string ("127.0.0.1");
3149 CHECK_STRING (host);
3152 #ifdef HAVE_LOCAL_SOCKETS
3153 if (family == AF_LOCAL)
3155 if (!NILP (host))
3157 message (":family local ignores the :host \"%s\" property",
3158 SDATA (host));
3159 contact = Fplist_put (contact, QChost, Qnil);
3160 host = Qnil;
3162 CHECK_STRING (service);
3163 memset (&address_un, 0, sizeof address_un);
3164 address_un.sun_family = AF_LOCAL;
3165 if (sizeof address_un.sun_path <= SBYTES (service))
3166 error ("Service name too long");
3167 strcpy (address_un.sun_path, SSDATA (service));
3168 ai.ai_addr = (struct sockaddr *) &address_un;
3169 ai.ai_addrlen = sizeof address_un;
3170 goto open_socket;
3172 #endif
3174 /* Slow down polling to every ten seconds.
3175 Some kernels have a bug which causes retrying connect to fail
3176 after a connect. Polling can interfere with gethostbyname too. */
3177 #ifdef POLL_FOR_INPUT
3178 if (socktype != SOCK_DGRAM)
3180 record_unwind_protect_void (run_all_atimers);
3181 bind_polling_period (10);
3183 #endif
3185 #ifdef HAVE_GETADDRINFO
3186 /* If we have a host, use getaddrinfo to resolve both host and service.
3187 Otherwise, use getservbyname to lookup the service. */
3188 if (!NILP (host))
3191 /* SERVICE can either be a string or int.
3192 Convert to a C string for later use by getaddrinfo. */
3193 if (EQ (service, Qt))
3194 portstring = "0";
3195 else if (INTEGERP (service))
3197 sprintf (portbuf, "%"pI"d", XINT (service));
3198 portstring = portbuf;
3200 else
3202 CHECK_STRING (service);
3203 portstring = SSDATA (service);
3206 immediate_quit = 1;
3207 QUIT;
3208 memset (&hints, 0, sizeof (hints));
3209 hints.ai_flags = 0;
3210 hints.ai_family = family;
3211 hints.ai_socktype = socktype;
3212 hints.ai_protocol = 0;
3214 #ifdef HAVE_RES_INIT
3215 res_init ();
3216 #endif
3218 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3219 if (ret)
3220 #ifdef HAVE_GAI_STRERROR
3221 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3222 #else
3223 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3224 #endif
3225 immediate_quit = 0;
3227 goto open_socket;
3229 #endif /* HAVE_GETADDRINFO */
3231 /* We end up here if getaddrinfo is not defined, or in case no hostname
3232 has been specified (e.g. for a local server process). */
3234 if (EQ (service, Qt))
3235 port = 0;
3236 else if (INTEGERP (service))
3237 port = htons ((unsigned short) XINT (service));
3238 else
3240 struct servent *svc_info;
3241 CHECK_STRING (service);
3242 svc_info = getservbyname (SSDATA (service),
3243 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3244 if (svc_info == 0)
3245 error ("Unknown service: %s", SDATA (service));
3246 port = svc_info->s_port;
3249 memset (&address_in, 0, sizeof address_in);
3250 address_in.sin_family = family;
3251 address_in.sin_addr.s_addr = INADDR_ANY;
3252 address_in.sin_port = port;
3254 #ifndef HAVE_GETADDRINFO
3255 if (!NILP (host))
3257 struct hostent *host_info_ptr;
3259 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3260 as it may `hang' Emacs for a very long time. */
3261 immediate_quit = 1;
3262 QUIT;
3264 #ifdef HAVE_RES_INIT
3265 res_init ();
3266 #endif
3268 host_info_ptr = gethostbyname (SDATA (host));
3269 immediate_quit = 0;
3271 if (host_info_ptr)
3273 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3274 host_info_ptr->h_length);
3275 family = host_info_ptr->h_addrtype;
3276 address_in.sin_family = family;
3278 else
3279 /* Attempt to interpret host as numeric inet address */
3281 unsigned long numeric_addr;
3282 numeric_addr = inet_addr (SSDATA (host));
3283 if (numeric_addr == -1)
3284 error ("Unknown host \"%s\"", SDATA (host));
3286 memcpy (&address_in.sin_addr, &numeric_addr,
3287 sizeof (address_in.sin_addr));
3291 #endif /* not HAVE_GETADDRINFO */
3293 ai.ai_family = family;
3294 ai.ai_addr = (struct sockaddr *) &address_in;
3295 ai.ai_addrlen = sizeof address_in;
3297 open_socket:
3299 /* Do this in case we never enter the for-loop below. */
3300 count1 = SPECPDL_INDEX ();
3301 s = -1;
3303 for (lres = res; lres; lres = lres->ai_next)
3305 ptrdiff_t optn;
3306 int optbits;
3308 #ifdef WINDOWSNT
3309 retry_connect:
3310 #endif
3312 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3313 lres->ai_protocol);
3314 if (s < 0)
3316 xerrno = errno;
3317 continue;
3320 #ifdef DATAGRAM_SOCKETS
3321 if (!is_server && socktype == SOCK_DGRAM)
3322 break;
3323 #endif /* DATAGRAM_SOCKETS */
3325 #ifdef NON_BLOCKING_CONNECT
3326 if (is_non_blocking_client)
3328 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3329 if (ret < 0)
3331 xerrno = errno;
3332 emacs_close (s);
3333 s = -1;
3334 continue;
3337 #endif
3339 /* Make us close S if quit. */
3340 record_unwind_protect_int (close_file_unwind, s);
3342 /* Parse network options in the arg list.
3343 We simply ignore anything which isn't a known option (including other keywords).
3344 An error is signaled if setting a known option fails. */
3345 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3346 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3348 if (is_server)
3350 /* Configure as a server socket. */
3352 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3353 explicit :reuseaddr key to override this. */
3354 #ifdef HAVE_LOCAL_SOCKETS
3355 if (family != AF_LOCAL)
3356 #endif
3357 if (!(optbits & (1 << OPIX_REUSEADDR)))
3359 int optval = 1;
3360 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3361 report_file_error ("Cannot set reuse option on server socket", Qnil);
3364 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3365 report_file_error ("Cannot bind server socket", Qnil);
3367 #ifdef HAVE_GETSOCKNAME
3368 if (EQ (service, Qt))
3370 struct sockaddr_in sa1;
3371 socklen_t len1 = sizeof (sa1);
3372 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3374 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3375 service = make_number (ntohs (sa1.sin_port));
3376 contact = Fplist_put (contact, QCservice, service);
3379 #endif
3381 if (socktype != SOCK_DGRAM && listen (s, backlog))
3382 report_file_error ("Cannot listen on server socket", Qnil);
3384 break;
3387 immediate_quit = 1;
3388 QUIT;
3390 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3391 xerrno = errno;
3393 if (ret == 0 || xerrno == EISCONN)
3395 /* The unwind-protect will be discarded afterwards.
3396 Likewise for immediate_quit. */
3397 break;
3400 #ifdef NON_BLOCKING_CONNECT
3401 #ifdef EINPROGRESS
3402 if (is_non_blocking_client && xerrno == EINPROGRESS)
3403 break;
3404 #else
3405 #ifdef EWOULDBLOCK
3406 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3407 break;
3408 #endif
3409 #endif
3410 #endif
3412 #ifndef WINDOWSNT
3413 if (xerrno == EINTR)
3415 /* Unlike most other syscalls connect() cannot be called
3416 again. (That would return EALREADY.) The proper way to
3417 wait for completion is pselect(). */
3418 int sc;
3419 socklen_t len;
3420 SELECT_TYPE fdset;
3421 retry_select:
3422 FD_ZERO (&fdset);
3423 FD_SET (s, &fdset);
3424 QUIT;
3425 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3426 if (sc == -1)
3428 if (errno == EINTR)
3429 goto retry_select;
3430 else
3431 report_file_error ("Failed select", Qnil);
3433 eassert (sc > 0);
3435 len = sizeof xerrno;
3436 eassert (FD_ISSET (s, &fdset));
3437 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3438 report_file_error ("Failed getsockopt", Qnil);
3439 if (xerrno)
3440 report_file_errno ("Failed connect", Qnil, xerrno);
3441 break;
3443 #endif /* !WINDOWSNT */
3445 immediate_quit = 0;
3447 /* Discard the unwind protect closing S. */
3448 specpdl_ptr = specpdl + count1;
3449 emacs_close (s);
3450 s = -1;
3452 #ifdef WINDOWSNT
3453 if (xerrno == EINTR)
3454 goto retry_connect;
3455 #endif
3458 if (s >= 0)
3460 #ifdef DATAGRAM_SOCKETS
3461 if (socktype == SOCK_DGRAM)
3463 if (datagram_address[s].sa)
3464 emacs_abort ();
3465 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3466 datagram_address[s].len = lres->ai_addrlen;
3467 if (is_server)
3469 Lisp_Object remote;
3470 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3471 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3473 int rfamily, rlen;
3474 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3475 if (rlen != 0 && rfamily == lres->ai_family
3476 && rlen == lres->ai_addrlen)
3477 conv_lisp_to_sockaddr (rfamily, remote,
3478 datagram_address[s].sa, rlen);
3481 else
3482 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3484 #endif
3485 contact = Fplist_put (contact, QCaddress,
3486 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3487 #ifdef HAVE_GETSOCKNAME
3488 if (!is_server)
3490 struct sockaddr_in sa1;
3491 socklen_t len1 = sizeof (sa1);
3492 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3493 contact = Fplist_put (contact, QClocal,
3494 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3496 #endif
3499 immediate_quit = 0;
3501 #ifdef HAVE_GETADDRINFO
3502 if (res != &ai)
3504 block_input ();
3505 freeaddrinfo (res);
3506 unblock_input ();
3508 #endif
3510 if (s < 0)
3512 /* If non-blocking got this far - and failed - assume non-blocking is
3513 not supported after all. This is probably a wrong assumption, but
3514 the normal blocking calls to open-network-stream handles this error
3515 better. */
3516 if (is_non_blocking_client)
3517 return Qnil;
3519 report_file_errno ((is_server
3520 ? "make server process failed"
3521 : "make client process failed"),
3522 contact, xerrno);
3525 inch = s;
3526 outch = s;
3528 if (!NILP (buffer))
3529 buffer = Fget_buffer_create (buffer);
3530 proc = make_process (name);
3532 chan_process[inch] = proc;
3534 fcntl (inch, F_SETFL, O_NONBLOCK);
3536 p = XPROCESS (proc);
3538 pset_childp (p, contact);
3539 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3540 pset_type (p, Qnetwork);
3542 pset_buffer (p, buffer);
3543 pset_sentinel (p, sentinel);
3544 pset_filter (p, filter);
3545 pset_log (p, Fplist_get (contact, QClog));
3546 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3547 p->kill_without_query = 1;
3548 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3549 pset_command (p, Qt);
3550 p->pid = 0;
3552 p->open_fd[SUBPROCESS_STDIN] = inch;
3553 p->infd = inch;
3554 p->outfd = outch;
3556 /* Discard the unwind protect for closing S, if any. */
3557 specpdl_ptr = specpdl + count1;
3559 /* Unwind bind_polling_period and request_sigio. */
3560 unbind_to (count, Qnil);
3562 if (is_server && socktype != SOCK_DGRAM)
3563 pset_status (p, Qlisten);
3565 /* Make the process marker point into the process buffer (if any). */
3566 if (BUFFERP (buffer))
3567 set_marker_both (p->mark, buffer,
3568 BUF_ZV (XBUFFER (buffer)),
3569 BUF_ZV_BYTE (XBUFFER (buffer)));
3571 #ifdef NON_BLOCKING_CONNECT
3572 if (is_non_blocking_client)
3574 /* We may get here if connect did succeed immediately. However,
3575 in that case, we still need to signal this like a non-blocking
3576 connection. */
3577 pset_status (p, Qconnect);
3578 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3579 add_non_blocking_write_fd (inch);
3581 else
3582 #endif
3583 /* A server may have a client filter setting of Qt, but it must
3584 still listen for incoming connects unless it is stopped. */
3585 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3586 || (EQ (p->status, Qlisten) && NILP (p->command)))
3587 add_non_keyboard_read_fd (inch);
3589 if (inch > max_desc)
3590 max_desc = inch;
3592 tem = Fplist_member (contact, QCcoding);
3593 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3594 tem = Qnil; /* No error message (too late!). */
3597 /* Setup coding systems for communicating with the network stream. */
3598 struct gcpro gcpro1;
3599 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3600 Lisp_Object coding_systems = Qt;
3601 Lisp_Object fargs[5], val;
3603 if (!NILP (tem))
3605 val = XCAR (XCDR (tem));
3606 if (CONSP (val))
3607 val = XCAR (val);
3609 else if (!NILP (Vcoding_system_for_read))
3610 val = Vcoding_system_for_read;
3611 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3612 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3613 /* We dare not decode end-of-line format by setting VAL to
3614 Qraw_text, because the existing Emacs Lisp libraries
3615 assume that they receive bare code including a sequence of
3616 CR LF. */
3617 val = Qnil;
3618 else
3620 if (NILP (host) || NILP (service))
3621 coding_systems = Qnil;
3622 else
3624 fargs[0] = Qopen_network_stream, fargs[1] = name,
3625 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3626 GCPRO1 (proc);
3627 coding_systems = Ffind_operation_coding_system (5, fargs);
3628 UNGCPRO;
3630 if (CONSP (coding_systems))
3631 val = XCAR (coding_systems);
3632 else if (CONSP (Vdefault_process_coding_system))
3633 val = XCAR (Vdefault_process_coding_system);
3634 else
3635 val = Qnil;
3637 pset_decode_coding_system (p, val);
3639 if (!NILP (tem))
3641 val = XCAR (XCDR (tem));
3642 if (CONSP (val))
3643 val = XCDR (val);
3645 else if (!NILP (Vcoding_system_for_write))
3646 val = Vcoding_system_for_write;
3647 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3648 val = Qnil;
3649 else
3651 if (EQ (coding_systems, Qt))
3653 if (NILP (host) || NILP (service))
3654 coding_systems = Qnil;
3655 else
3657 fargs[0] = Qopen_network_stream, fargs[1] = name,
3658 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3659 GCPRO1 (proc);
3660 coding_systems = Ffind_operation_coding_system (5, fargs);
3661 UNGCPRO;
3664 if (CONSP (coding_systems))
3665 val = XCDR (coding_systems);
3666 else if (CONSP (Vdefault_process_coding_system))
3667 val = XCDR (Vdefault_process_coding_system);
3668 else
3669 val = Qnil;
3671 pset_encode_coding_system (p, val);
3673 setup_process_coding_systems (proc);
3675 pset_decoding_buf (p, empty_unibyte_string);
3676 p->decoding_carryover = 0;
3677 pset_encoding_buf (p, empty_unibyte_string);
3679 p->inherit_coding_system_flag
3680 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3682 UNGCPRO;
3683 return proc;
3687 #if defined (HAVE_NET_IF_H)
3689 #ifdef SIOCGIFCONF
3690 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3691 doc: /* Return an alist of all network interfaces and their network address.
3692 Each element is a cons, the car of which is a string containing the
3693 interface name, and the cdr is the network address in internal
3694 format; see the description of ADDRESS in `make-network-process'. */)
3695 (void)
3697 struct ifconf ifconf;
3698 struct ifreq *ifreq;
3699 void *buf = NULL;
3700 ptrdiff_t buf_size = 512;
3701 int s;
3702 Lisp_Object res;
3703 ptrdiff_t count;
3705 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3706 if (s < 0)
3707 return Qnil;
3708 count = SPECPDL_INDEX ();
3709 record_unwind_protect_int (close_file_unwind, s);
3713 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3714 ifconf.ifc_buf = buf;
3715 ifconf.ifc_len = buf_size;
3716 if (ioctl (s, SIOCGIFCONF, &ifconf))
3718 emacs_close (s);
3719 xfree (buf);
3720 return Qnil;
3723 while (ifconf.ifc_len == buf_size);
3725 res = unbind_to (count, Qnil);
3726 ifreq = ifconf.ifc_req;
3727 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3729 struct ifreq *ifq = ifreq;
3730 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3731 #define SIZEOF_IFREQ(sif) \
3732 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3733 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3735 int len = SIZEOF_IFREQ (ifq);
3736 #else
3737 int len = sizeof (*ifreq);
3738 #endif
3739 char namebuf[sizeof (ifq->ifr_name) + 1];
3740 ifreq = (struct ifreq *) ((char *) ifreq + len);
3742 if (ifq->ifr_addr.sa_family != AF_INET)
3743 continue;
3745 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3746 namebuf[sizeof (ifq->ifr_name)] = 0;
3747 res = Fcons (Fcons (build_string (namebuf),
3748 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3749 sizeof (struct sockaddr))),
3750 res);
3753 xfree (buf);
3754 return res;
3756 #endif /* SIOCGIFCONF */
3758 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3760 struct ifflag_def {
3761 int flag_bit;
3762 const char *flag_sym;
3765 static const struct ifflag_def ifflag_table[] = {
3766 #ifdef IFF_UP
3767 { IFF_UP, "up" },
3768 #endif
3769 #ifdef IFF_BROADCAST
3770 { IFF_BROADCAST, "broadcast" },
3771 #endif
3772 #ifdef IFF_DEBUG
3773 { IFF_DEBUG, "debug" },
3774 #endif
3775 #ifdef IFF_LOOPBACK
3776 { IFF_LOOPBACK, "loopback" },
3777 #endif
3778 #ifdef IFF_POINTOPOINT
3779 { IFF_POINTOPOINT, "pointopoint" },
3780 #endif
3781 #ifdef IFF_RUNNING
3782 { IFF_RUNNING, "running" },
3783 #endif
3784 #ifdef IFF_NOARP
3785 { IFF_NOARP, "noarp" },
3786 #endif
3787 #ifdef IFF_PROMISC
3788 { IFF_PROMISC, "promisc" },
3789 #endif
3790 #ifdef IFF_NOTRAILERS
3791 #ifdef NS_IMPL_COCOA
3792 /* Really means smart, notrailers is obsolete */
3793 { IFF_NOTRAILERS, "smart" },
3794 #else
3795 { IFF_NOTRAILERS, "notrailers" },
3796 #endif
3797 #endif
3798 #ifdef IFF_ALLMULTI
3799 { IFF_ALLMULTI, "allmulti" },
3800 #endif
3801 #ifdef IFF_MASTER
3802 { IFF_MASTER, "master" },
3803 #endif
3804 #ifdef IFF_SLAVE
3805 { IFF_SLAVE, "slave" },
3806 #endif
3807 #ifdef IFF_MULTICAST
3808 { IFF_MULTICAST, "multicast" },
3809 #endif
3810 #ifdef IFF_PORTSEL
3811 { IFF_PORTSEL, "portsel" },
3812 #endif
3813 #ifdef IFF_AUTOMEDIA
3814 { IFF_AUTOMEDIA, "automedia" },
3815 #endif
3816 #ifdef IFF_DYNAMIC
3817 { IFF_DYNAMIC, "dynamic" },
3818 #endif
3819 #ifdef IFF_OACTIVE
3820 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3821 #endif
3822 #ifdef IFF_SIMPLEX
3823 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3824 #endif
3825 #ifdef IFF_LINK0
3826 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3827 #endif
3828 #ifdef IFF_LINK1
3829 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3830 #endif
3831 #ifdef IFF_LINK2
3832 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3833 #endif
3834 { 0, 0 }
3837 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3838 doc: /* Return information about network interface named IFNAME.
3839 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3840 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3841 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3842 FLAGS is the current flags of the interface. */)
3843 (Lisp_Object ifname)
3845 struct ifreq rq;
3846 Lisp_Object res = Qnil;
3847 Lisp_Object elt;
3848 int s;
3849 bool any = 0;
3850 ptrdiff_t count;
3851 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3852 && defined HAVE_GETIFADDRS && defined LLADDR)
3853 struct ifaddrs *ifap;
3854 #endif
3856 CHECK_STRING (ifname);
3858 if (sizeof rq.ifr_name <= SBYTES (ifname))
3859 error ("interface name too long");
3860 strcpy (rq.ifr_name, SSDATA (ifname));
3862 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3863 if (s < 0)
3864 return Qnil;
3865 count = SPECPDL_INDEX ();
3866 record_unwind_protect_int (close_file_unwind, s);
3868 elt = Qnil;
3869 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3870 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3872 int flags = rq.ifr_flags;
3873 const struct ifflag_def *fp;
3874 int fnum;
3876 /* If flags is smaller than int (i.e. short) it may have the high bit set
3877 due to IFF_MULTICAST. In that case, sign extending it into
3878 an int is wrong. */
3879 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3880 flags = (unsigned short) rq.ifr_flags;
3882 any = 1;
3883 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3885 if (flags & fp->flag_bit)
3887 elt = Fcons (intern (fp->flag_sym), elt);
3888 flags -= fp->flag_bit;
3891 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3893 if (flags & 1)
3895 elt = Fcons (make_number (fnum), elt);
3899 #endif
3900 res = Fcons (elt, res);
3902 elt = Qnil;
3903 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3904 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3906 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3907 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3908 int n;
3910 any = 1;
3911 for (n = 0; n < 6; n++)
3912 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3913 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3915 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3916 if (getifaddrs (&ifap) != -1)
3918 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3919 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3920 struct ifaddrs *it;
3922 for (it = ifap; it != NULL; it = it->ifa_next)
3924 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3925 unsigned char linkaddr[6];
3926 int n;
3928 if (it->ifa_addr->sa_family != AF_LINK
3929 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3930 || sdl->sdl_alen != 6)
3931 continue;
3933 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3934 for (n = 0; n < 6; n++)
3935 p->contents[n] = make_number (linkaddr[n]);
3937 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3938 break;
3941 #ifdef HAVE_FREEIFADDRS
3942 freeifaddrs (ifap);
3943 #endif
3945 #endif /* HAVE_GETIFADDRS && LLADDR */
3947 res = Fcons (elt, res);
3949 elt = Qnil;
3950 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3951 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3953 any = 1;
3954 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3955 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3956 #else
3957 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3958 #endif
3960 #endif
3961 res = Fcons (elt, res);
3963 elt = Qnil;
3964 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3965 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3967 any = 1;
3968 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3970 #endif
3971 res = Fcons (elt, res);
3973 elt = Qnil;
3974 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3975 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3977 any = 1;
3978 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3980 #endif
3981 res = Fcons (elt, res);
3983 return unbind_to (count, any ? res : Qnil);
3985 #endif
3986 #endif /* defined (HAVE_NET_IF_H) */
3988 /* Turn off input and output for process PROC. */
3990 static void
3991 deactivate_process (Lisp_Object proc)
3993 int inchannel;
3994 struct Lisp_Process *p = XPROCESS (proc);
3995 int i;
3997 #ifdef HAVE_GNUTLS
3998 /* Delete GnuTLS structures in PROC, if any. */
3999 emacs_gnutls_deinit (proc);
4000 #endif /* HAVE_GNUTLS */
4002 #ifdef ADAPTIVE_READ_BUFFERING
4003 if (p->read_output_delay > 0)
4005 if (--process_output_delay_count < 0)
4006 process_output_delay_count = 0;
4007 p->read_output_delay = 0;
4008 p->read_output_skip = 0;
4010 #endif
4012 /* Beware SIGCHLD hereabouts. */
4014 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4015 close_process_fd (&p->open_fd[i]);
4017 inchannel = p->infd;
4018 if (inchannel >= 0)
4020 p->infd = -1;
4021 p->outfd = -1;
4022 #ifdef DATAGRAM_SOCKETS
4023 if (DATAGRAM_CHAN_P (inchannel))
4025 xfree (datagram_address[inchannel].sa);
4026 datagram_address[inchannel].sa = 0;
4027 datagram_address[inchannel].len = 0;
4029 #endif
4030 chan_process[inchannel] = Qnil;
4031 delete_read_fd (inchannel);
4032 #ifdef NON_BLOCKING_CONNECT
4033 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4034 delete_write_fd (inchannel);
4035 #endif
4036 if (inchannel == max_desc)
4037 recompute_max_desc ();
4042 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4043 0, 4, 0,
4044 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4045 It is read into the process' buffers or given to their filter functions.
4046 Non-nil arg PROCESS means do not return until some output has been received
4047 from PROCESS.
4049 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4050 and milliseconds to wait; return after that much time whether or not
4051 there is any subprocess output. If SECONDS is a floating point number,
4052 it specifies a fractional number of seconds to wait.
4053 The MILLISEC argument is obsolete and should be avoided.
4055 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4056 from PROCESS, suspending reading output from other processes.
4057 If JUST-THIS-ONE is an integer, don't run any timers either.
4058 Return non-nil if we received any output before the timeout expired. */)
4059 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4061 intmax_t secs;
4062 int nsecs;
4064 if (! NILP (process))
4066 struct Lisp_Process *procp;
4068 CHECK_PROCESS (process);
4069 procp = XPROCESS (process);
4071 /* Can't wait for a process that is dedicated to a different
4072 thread. */
4073 if (!EQ (procp->thread, Qnil) && !EQ (procp->thread, Fcurrent_thread ()))
4074 error ("FIXME");
4076 else
4077 just_this_one = Qnil;
4079 if (!NILP (millisec))
4080 { /* Obsolete calling convention using integers rather than floats. */
4081 CHECK_NUMBER (millisec);
4082 if (NILP (seconds))
4083 seconds = make_float (XINT (millisec) / 1000.0);
4084 else
4086 CHECK_NUMBER (seconds);
4087 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4091 secs = 0;
4092 nsecs = -1;
4094 if (!NILP (seconds))
4096 if (INTEGERP (seconds))
4098 if (XINT (seconds) > 0)
4100 secs = XINT (seconds);
4101 nsecs = 0;
4104 else if (FLOATP (seconds))
4106 if (XFLOAT_DATA (seconds) > 0)
4108 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
4109 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
4110 nsecs = EMACS_NSECS (t);
4113 else
4114 wrong_type_argument (Qnumberp, seconds);
4116 else if (! NILP (process))
4117 nsecs = 0;
4119 return
4120 (wait_reading_process_output (secs, nsecs, 0, 0,
4121 Qnil,
4122 !NILP (process) ? XPROCESS (process) : NULL,
4123 NILP (just_this_one) ? 0 :
4124 !INTEGERP (just_this_one) ? 1 : -1)
4125 ? Qt : Qnil);
4128 /* Accept a connection for server process SERVER on CHANNEL. */
4130 static EMACS_INT connect_counter = 0;
4132 static void
4133 server_accept_connection (Lisp_Object server, int channel)
4135 Lisp_Object proc, caller, name, buffer;
4136 Lisp_Object contact, host, service;
4137 struct Lisp_Process *ps= XPROCESS (server);
4138 struct Lisp_Process *p;
4139 int s;
4140 union u_sockaddr {
4141 struct sockaddr sa;
4142 struct sockaddr_in in;
4143 #ifdef AF_INET6
4144 struct sockaddr_in6 in6;
4145 #endif
4146 #ifdef HAVE_LOCAL_SOCKETS
4147 struct sockaddr_un un;
4148 #endif
4149 } saddr;
4150 socklen_t len = sizeof saddr;
4151 ptrdiff_t count;
4153 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4155 if (s < 0)
4157 int code = errno;
4159 if (code == EAGAIN)
4160 return;
4161 #ifdef EWOULDBLOCK
4162 if (code == EWOULDBLOCK)
4163 return;
4164 #endif
4166 if (!NILP (ps->log))
4167 call3 (ps->log, server, Qnil,
4168 concat3 (build_string ("accept failed with code"),
4169 Fnumber_to_string (make_number (code)),
4170 build_string ("\n")));
4171 return;
4174 count = SPECPDL_INDEX ();
4175 record_unwind_protect_int (close_file_unwind, s);
4177 connect_counter++;
4179 /* Setup a new process to handle the connection. */
4181 /* Generate a unique identification of the caller, and build contact
4182 information for this process. */
4183 host = Qt;
4184 service = Qnil;
4185 switch (saddr.sa.sa_family)
4187 case AF_INET:
4189 Lisp_Object args[5];
4190 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4191 args[0] = build_string ("%d.%d.%d.%d");
4192 args[1] = make_number (*ip++);
4193 args[2] = make_number (*ip++);
4194 args[3] = make_number (*ip++);
4195 args[4] = make_number (*ip++);
4196 host = Fformat (5, args);
4197 service = make_number (ntohs (saddr.in.sin_port));
4199 args[0] = build_string (" <%s:%d>");
4200 args[1] = host;
4201 args[2] = service;
4202 caller = Fformat (3, args);
4204 break;
4206 #ifdef AF_INET6
4207 case AF_INET6:
4209 Lisp_Object args[9];
4210 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4211 int i;
4212 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4213 for (i = 0; i < 8; i++)
4214 args[i+1] = make_number (ntohs (ip6[i]));
4215 host = Fformat (9, args);
4216 service = make_number (ntohs (saddr.in.sin_port));
4218 args[0] = build_string (" <[%s]:%d>");
4219 args[1] = host;
4220 args[2] = service;
4221 caller = Fformat (3, args);
4223 break;
4224 #endif
4226 #ifdef HAVE_LOCAL_SOCKETS
4227 case AF_LOCAL:
4228 #endif
4229 default:
4230 caller = Fnumber_to_string (make_number (connect_counter));
4231 caller = concat3 (build_string (" <"), caller, build_string (">"));
4232 break;
4235 /* Create a new buffer name for this process if it doesn't have a
4236 filter. The new buffer name is based on the buffer name or
4237 process name of the server process concatenated with the caller
4238 identification. */
4240 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4241 || EQ (ps->filter, Qt)))
4242 buffer = Qnil;
4243 else
4245 buffer = ps->buffer;
4246 if (!NILP (buffer))
4247 buffer = Fbuffer_name (buffer);
4248 else
4249 buffer = ps->name;
4250 if (!NILP (buffer))
4252 buffer = concat2 (buffer, caller);
4253 buffer = Fget_buffer_create (buffer);
4257 /* Generate a unique name for the new server process. Combine the
4258 server process name with the caller identification. */
4260 name = concat2 (ps->name, caller);
4261 proc = make_process (name);
4263 chan_process[s] = proc;
4265 fcntl (s, F_SETFL, O_NONBLOCK);
4267 p = XPROCESS (proc);
4269 /* Build new contact information for this setup. */
4270 contact = Fcopy_sequence (ps->childp);
4271 contact = Fplist_put (contact, QCserver, Qnil);
4272 contact = Fplist_put (contact, QChost, host);
4273 if (!NILP (service))
4274 contact = Fplist_put (contact, QCservice, service);
4275 contact = Fplist_put (contact, QCremote,
4276 conv_sockaddr_to_lisp (&saddr.sa, len));
4277 #ifdef HAVE_GETSOCKNAME
4278 len = sizeof saddr;
4279 if (getsockname (s, &saddr.sa, &len) == 0)
4280 contact = Fplist_put (contact, QClocal,
4281 conv_sockaddr_to_lisp (&saddr.sa, len));
4282 #endif
4284 pset_childp (p, contact);
4285 pset_plist (p, Fcopy_sequence (ps->plist));
4286 pset_type (p, Qnetwork);
4288 pset_buffer (p, buffer);
4289 pset_sentinel (p, ps->sentinel);
4290 pset_filter (p, ps->filter);
4291 pset_command (p, Qnil);
4292 p->pid = 0;
4294 /* Discard the unwind protect for closing S. */
4295 specpdl_ptr = specpdl + count;
4297 p->open_fd[SUBPROCESS_STDIN] = s;
4298 p->infd = s;
4299 p->outfd = s;
4300 pset_status (p, Qrun);
4302 /* Client processes for accepted connections are not stopped initially. */
4303 if (!EQ (p->filter, Qt))
4304 add_non_keyboard_read_fd (s);
4306 /* Setup coding system for new process based on server process.
4307 This seems to be the proper thing to do, as the coding system
4308 of the new process should reflect the settings at the time the
4309 server socket was opened; not the current settings. */
4311 pset_decode_coding_system (p, ps->decode_coding_system);
4312 pset_encode_coding_system (p, ps->encode_coding_system);
4313 setup_process_coding_systems (proc);
4315 pset_decoding_buf (p, empty_unibyte_string);
4316 p->decoding_carryover = 0;
4317 pset_encoding_buf (p, empty_unibyte_string);
4319 p->inherit_coding_system_flag
4320 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4322 if (!NILP (ps->log))
4323 call3 (ps->log, server, proc,
4324 concat3 (build_string ("accept from "),
4325 (STRINGP (host) ? host : build_string ("-")),
4326 build_string ("\n")));
4328 exec_sentinel (proc,
4329 concat3 (build_string ("open from "),
4330 (STRINGP (host) ? host : build_string ("-")),
4331 build_string ("\n")));
4334 static void
4335 wait_reading_process_output_unwind (int data)
4337 clear_waiting_thread_info ();
4338 waiting_for_user_input_p = data;
4341 /* This is here so breakpoints can be put on it. */
4342 static void
4343 wait_reading_process_output_1 (void)
4347 /* Read and dispose of subprocess output while waiting for timeout to
4348 elapse and/or keyboard input to be available.
4350 TIME_LIMIT is:
4351 timeout in seconds
4352 If negative, gobble data immediately available but don't wait for any.
4354 NSECS is:
4355 an additional duration to wait, measured in nanoseconds
4356 If TIME_LIMIT is zero, then:
4357 If NSECS == 0, there is no limit.
4358 If NSECS > 0, the timeout consists of NSECS only.
4359 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4361 READ_KBD is:
4362 0 to ignore keyboard input, or
4363 1 to return when input is available, or
4364 -1 meaning caller will actually read the input, so don't throw to
4365 the quit handler, or
4367 DO_DISPLAY means redisplay should be done to show subprocess
4368 output that arrives.
4370 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4371 (and gobble terminal input into the buffer if any arrives).
4373 If WAIT_PROC is specified, wait until something arrives from that
4374 process. The return value is true if we read some input from
4375 that process.
4377 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4378 (suspending output from other processes). A negative value
4379 means don't run any timers either.
4381 If WAIT_PROC is specified, then the function returns true if we
4382 received input from that process before the timeout elapsed.
4383 Otherwise, return true if we received input from any process. */
4385 bool
4386 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4387 bool do_display,
4388 Lisp_Object wait_for_cell,
4389 struct Lisp_Process *wait_proc, int just_wait_proc)
4391 int channel, nfds;
4392 SELECT_TYPE Available;
4393 SELECT_TYPE Writeok;
4394 bool check_write;
4395 int check_delay;
4396 bool no_avail;
4397 int xerrno;
4398 Lisp_Object proc;
4399 EMACS_TIME timeout, end_time;
4400 int wait_channel = -1;
4401 bool got_some_input = 0;
4402 ptrdiff_t count = SPECPDL_INDEX ();
4404 eassert (wait_proc == NULL
4405 || EQ (wait_proc->thread, Qnil)
4406 || XTHREAD (wait_proc->thread) == current_thread);
4408 FD_ZERO (&Available);
4409 FD_ZERO (&Writeok);
4411 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4412 && !(CONSP (wait_proc->status)
4413 && EQ (XCAR (wait_proc->status), Qexit)))
4414 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4416 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4417 if (wait_proc != NULL)
4418 wait_channel = wait_proc->infd;
4420 record_unwind_protect_int (wait_reading_process_output_unwind,
4421 waiting_for_user_input_p);
4422 waiting_for_user_input_p = read_kbd;
4424 if (time_limit < 0)
4426 time_limit = 0;
4427 nsecs = -1;
4429 else if (TYPE_MAXIMUM (time_t) < time_limit)
4430 time_limit = TYPE_MAXIMUM (time_t);
4432 /* Since we may need to wait several times,
4433 compute the absolute time to return at. */
4434 if (time_limit || nsecs > 0)
4436 timeout = make_emacs_time (time_limit, nsecs);
4437 end_time = add_emacs_time (current_emacs_time (), timeout);
4440 while (1)
4442 bool timeout_reduced_for_timers = 0;
4444 /* If calling from keyboard input, do not quit
4445 since we want to return C-g as an input character.
4446 Otherwise, do pending quit if requested. */
4447 if (read_kbd >= 0)
4448 QUIT;
4449 else if (pending_signals)
4450 process_pending_signals ();
4452 /* Exit now if the cell we're waiting for became non-nil. */
4453 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4454 break;
4456 /* Compute time from now till when time limit is up. */
4457 /* Exit if already run out. */
4458 if (nsecs < 0)
4460 /* A negative timeout means
4461 gobble output available now
4462 but don't wait at all. */
4464 timeout = make_emacs_time (0, 0);
4466 else if (time_limit || nsecs > 0)
4468 EMACS_TIME now = current_emacs_time ();
4469 if (EMACS_TIME_LE (end_time, now))
4470 break;
4471 timeout = sub_emacs_time (end_time, now);
4473 else
4475 timeout = make_emacs_time (100000, 0);
4478 /* Normally we run timers here.
4479 But not if wait_for_cell; in those cases,
4480 the wait is supposed to be short,
4481 and those callers cannot handle running arbitrary Lisp code here. */
4482 if (NILP (wait_for_cell)
4483 && just_wait_proc >= 0)
4485 EMACS_TIME timer_delay;
4489 unsigned old_timers_run = timers_run;
4490 struct buffer *old_buffer = current_buffer;
4491 Lisp_Object old_window = selected_window;
4493 timer_delay = timer_check ();
4495 /* If a timer has run, this might have changed buffers
4496 an alike. Make read_key_sequence aware of that. */
4497 if (timers_run != old_timers_run
4498 && (old_buffer != current_buffer
4499 || !EQ (old_window, selected_window))
4500 && waiting_for_user_input_p == -1)
4501 record_asynch_buffer_change ();
4503 if (timers_run != old_timers_run && do_display)
4504 /* We must retry, since a timer may have requeued itself
4505 and that could alter the time_delay. */
4506 redisplay_preserve_echo_area (9);
4507 else
4508 break;
4510 while (!detect_input_pending ());
4512 /* If there is unread keyboard input, also return. */
4513 if (read_kbd != 0
4514 && requeued_events_pending_p ())
4515 break;
4517 /* A negative timeout means do not wait at all. */
4518 if (nsecs >= 0)
4520 if (EMACS_TIME_VALID_P (timer_delay))
4522 if (EMACS_TIME_LT (timer_delay, timeout))
4524 timeout = timer_delay;
4525 timeout_reduced_for_timers = 1;
4528 else
4530 /* This is so a breakpoint can be put here. */
4531 wait_reading_process_output_1 ();
4536 /* Cause C-g and alarm signals to take immediate action,
4537 and cause input available signals to zero out timeout.
4539 It is important that we do this before checking for process
4540 activity. If we get a SIGCHLD after the explicit checks for
4541 process activity, timeout is the only way we will know. */
4542 if (read_kbd < 0)
4543 set_waiting_for_input (&timeout);
4545 /* If status of something has changed, and no input is
4546 available, notify the user of the change right away. After
4547 this explicit check, we'll let the SIGCHLD handler zap
4548 timeout to get our attention. */
4549 if (update_tick != process_tick)
4551 SELECT_TYPE Atemp;
4552 SELECT_TYPE Ctemp;
4554 if (kbd_on_hold_p ())
4555 FD_ZERO (&Atemp);
4556 else
4557 compute_input_wait_mask (&Atemp);
4558 compute_write_mask (&Ctemp);
4560 timeout = make_emacs_time (0, 0);
4561 if ((thread_select (pselect, max_desc + 1,
4562 &Atemp,
4563 #ifdef NON_BLOCKING_CONNECT
4564 (num_pending_connects > 0 ? &Ctemp : NULL),
4565 #else
4566 NULL,
4567 #endif
4568 NULL, &timeout, NULL)
4569 <= 0))
4571 /* It's okay for us to do this and then continue with
4572 the loop, since timeout has already been zeroed out. */
4573 clear_waiting_for_input ();
4574 status_notify (NULL);
4575 if (do_display) redisplay_preserve_echo_area (13);
4579 /* Don't wait for output from a non-running process. Just
4580 read whatever data has already been received. */
4581 if (wait_proc && wait_proc->raw_status_new)
4582 update_status (wait_proc);
4583 if (wait_proc
4584 && ! EQ (wait_proc->status, Qrun)
4585 && ! EQ (wait_proc->status, Qconnect))
4587 bool read_some_bytes = 0;
4589 clear_waiting_for_input ();
4590 XSETPROCESS (proc, wait_proc);
4592 /* Read data from the process, until we exhaust it. */
4593 while (wait_proc->infd >= 0)
4595 int nread = read_process_output (proc, wait_proc->infd);
4597 if (nread == 0)
4598 break;
4600 if (nread > 0)
4601 got_some_input = read_some_bytes = 1;
4602 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4603 break;
4604 #ifdef EWOULDBLOCK
4605 else if (nread == -1 && EWOULDBLOCK == errno)
4606 break;
4607 #endif
4609 if (read_some_bytes && do_display)
4610 redisplay_preserve_echo_area (10);
4612 break;
4615 /* Wait till there is something to do */
4617 if (wait_proc && just_wait_proc)
4619 if (wait_proc->infd < 0) /* Terminated */
4620 break;
4621 FD_SET (wait_proc->infd, &Available);
4622 check_delay = 0;
4623 check_write = 0;
4625 else if (!NILP (wait_for_cell))
4627 compute_non_process_wait_mask (&Available);
4628 check_delay = 0;
4629 check_write = 0;
4631 else
4633 if (! read_kbd)
4634 compute_non_keyboard_wait_mask (&Available);
4635 else
4636 compute_input_wait_mask (&Available);
4637 compute_write_mask (&Writeok);
4638 #ifdef SELECT_CANT_DO_WRITE_MASK
4639 check_write = 0;
4640 #else
4641 check_write = 1;
4642 #endif
4643 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4646 /* If frame size has changed or the window is newly mapped,
4647 redisplay now, before we start to wait. There is a race
4648 condition here; if a SIGIO arrives between now and the select
4649 and indicates that a frame is trashed, the select may block
4650 displaying a trashed screen. */
4651 if (frame_garbaged && do_display)
4653 clear_waiting_for_input ();
4654 redisplay_preserve_echo_area (11);
4655 if (read_kbd < 0)
4656 set_waiting_for_input (&timeout);
4659 /* Skip the `select' call if input is available and we're
4660 waiting for keyboard input or a cell change (which can be
4661 triggered by processing X events). In the latter case, set
4662 nfds to 1 to avoid breaking the loop. */
4663 no_avail = 0;
4664 if ((read_kbd || !NILP (wait_for_cell))
4665 && detect_input_pending ())
4667 nfds = read_kbd ? 0 : 1;
4668 no_avail = 1;
4671 if (!no_avail)
4674 #ifdef ADAPTIVE_READ_BUFFERING
4675 /* Set the timeout for adaptive read buffering if any
4676 process has non-zero read_output_skip and non-zero
4677 read_output_delay, and we are not reading output for a
4678 specific wait_channel. It is not executed if
4679 Vprocess_adaptive_read_buffering is nil. */
4680 if (process_output_skip && check_delay > 0)
4682 int nsecs = EMACS_NSECS (timeout);
4683 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4684 nsecs = READ_OUTPUT_DELAY_MAX;
4685 for (channel = 0; check_delay > 0 && channel <= max_desc; channel++)
4687 proc = chan_process[channel];
4688 if (NILP (proc))
4689 continue;
4690 /* Find minimum non-zero read_output_delay among the
4691 processes with non-zero read_output_skip. */
4692 if (XPROCESS (proc)->read_output_delay > 0)
4694 check_delay--;
4695 if (!XPROCESS (proc)->read_output_skip)
4696 continue;
4697 FD_CLR (channel, &Available);
4698 XPROCESS (proc)->read_output_skip = 0;
4699 if (XPROCESS (proc)->read_output_delay < nsecs)
4700 nsecs = XPROCESS (proc)->read_output_delay;
4703 timeout = make_emacs_time (0, nsecs);
4704 process_output_skip = 0;
4706 #endif
4707 nfds = thread_select (
4708 #if defined (HAVE_NS)
4709 ns_select
4710 #elif defined (HAVE_GLIB)
4711 xg_select
4712 #else
4713 pselect
4714 #endif
4715 , max_desc + 1,
4716 &Available,
4717 (check_write ? &Writeok : 0),
4718 NULL, &timeout, NULL);
4720 #ifdef HAVE_GNUTLS
4721 /* GnuTLS buffers data internally. In lowat mode it leaves
4722 some data in the TCP buffers so that select works, but
4723 with custom pull/push functions we need to check if some
4724 data is available in the buffers manually. */
4725 if (nfds == 0)
4727 if (! wait_proc)
4729 /* We're not waiting on a specific process, so loop
4730 through all the channels and check for data.
4731 This is a workaround needed for some versions of
4732 the gnutls library -- 2.12.14 has been confirmed
4733 to need it. See
4734 http://comments.gmane.org/gmane.emacs.devel/145074 */
4735 for (channel = 0; channel < MAXDESC; ++channel)
4736 if (! NILP (chan_process[channel]))
4738 struct Lisp_Process *p =
4739 XPROCESS (chan_process[channel]);
4740 if (p && p->gnutls_p && p->infd
4741 && ((emacs_gnutls_record_check_pending
4742 (p->gnutls_state))
4743 > 0))
4745 nfds++;
4746 FD_SET (p->infd, &Available);
4750 else
4752 /* Check this specific channel. */
4753 if (wait_proc->gnutls_p /* Check for valid process. */
4754 /* Do we have pending data? */
4755 && ((emacs_gnutls_record_check_pending
4756 (wait_proc->gnutls_state))
4757 > 0))
4759 nfds = 1;
4760 /* Set to Available. */
4761 FD_SET (wait_proc->infd, &Available);
4765 #endif
4768 xerrno = errno;
4770 /* Make C-g and alarm signals set flags again */
4771 clear_waiting_for_input ();
4773 /* If we woke up due to SIGWINCH, actually change size now. */
4774 do_pending_window_change (0);
4776 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4777 /* We waited the full specified time, so return now. */
4778 break;
4779 if (nfds < 0)
4781 if (xerrno == EINTR)
4782 no_avail = 1;
4783 else if (xerrno == EBADF)
4784 emacs_abort ();
4785 else
4786 report_file_errno ("Failed select", Qnil, xerrno);
4789 if (no_avail)
4791 FD_ZERO (&Available);
4792 check_write = 0;
4795 /* Check for keyboard input */
4796 /* If there is any, return immediately
4797 to give it higher priority than subprocesses */
4799 if (read_kbd != 0)
4801 unsigned old_timers_run = timers_run;
4802 struct buffer *old_buffer = current_buffer;
4803 Lisp_Object old_window = selected_window;
4804 bool leave = 0;
4806 if (detect_input_pending_run_timers (do_display))
4808 swallow_events (do_display);
4809 if (detect_input_pending_run_timers (do_display))
4810 leave = 1;
4813 /* If a timer has run, this might have changed buffers
4814 an alike. Make read_key_sequence aware of that. */
4815 if (timers_run != old_timers_run
4816 && waiting_for_user_input_p == -1
4817 && (old_buffer != current_buffer
4818 || !EQ (old_window, selected_window)))
4819 record_asynch_buffer_change ();
4821 if (leave)
4822 break;
4825 /* If there is unread keyboard input, also return. */
4826 if (read_kbd != 0
4827 && requeued_events_pending_p ())
4828 break;
4830 /* If we are not checking for keyboard input now,
4831 do process events (but don't run any timers).
4832 This is so that X events will be processed.
4833 Otherwise they may have to wait until polling takes place.
4834 That would causes delays in pasting selections, for example.
4836 (We used to do this only if wait_for_cell.) */
4837 if (read_kbd == 0 && detect_input_pending ())
4839 swallow_events (do_display);
4840 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4841 if (detect_input_pending ())
4842 break;
4843 #endif
4846 /* Exit now if the cell we're waiting for became non-nil. */
4847 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4848 break;
4850 #ifdef USABLE_SIGIO
4851 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4852 go read it. This can happen with X on BSD after logging out.
4853 In that case, there really is no input and no SIGIO,
4854 but select says there is input. */
4856 if (read_kbd && interrupt_input
4857 && keyboard_bit_set (&Available) && ! noninteractive)
4858 handle_input_available_signal (SIGIO);
4859 #endif
4861 if (! wait_proc)
4862 got_some_input |= nfds > 0;
4864 /* If checking input just got us a size-change event from X,
4865 obey it now if we should. */
4866 if (read_kbd || ! NILP (wait_for_cell))
4867 do_pending_window_change (0);
4869 /* Check for data from a process. */
4870 if (no_avail || nfds == 0)
4871 continue;
4873 for (channel = 0; channel <= max_desc; ++channel)
4875 struct fd_callback_data *d = &fd_callback_info[channel];
4876 if (d->func
4877 && ((d->flags & FOR_READ
4878 && FD_ISSET (channel, &Available))
4879 || (d->flags & FOR_WRITE
4880 && FD_ISSET (channel, &Writeok))))
4881 d->func (channel, d->data);
4884 for (channel = 0; channel <= max_desc; channel++)
4886 if (FD_ISSET (channel, &Available)
4887 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
4888 == PROCESS_FD))
4890 int nread;
4892 /* If waiting for this channel, arrange to return as
4893 soon as no more input to be processed. No more
4894 waiting. */
4895 if (wait_channel == channel)
4897 wait_channel = -1;
4898 nsecs = -1;
4899 got_some_input = 1;
4901 proc = chan_process[channel];
4902 if (NILP (proc))
4903 continue;
4905 /* If this is a server stream socket, accept connection. */
4906 if (EQ (XPROCESS (proc)->status, Qlisten))
4908 server_accept_connection (proc, channel);
4909 continue;
4912 /* Read data from the process, starting with our
4913 buffered-ahead character if we have one. */
4915 nread = read_process_output (proc, channel);
4916 if (nread > 0)
4918 /* Since read_process_output can run a filter,
4919 which can call accept-process-output,
4920 don't try to read from any other processes
4921 before doing the select again. */
4922 FD_ZERO (&Available);
4924 if (do_display)
4925 redisplay_preserve_echo_area (12);
4927 #ifdef EWOULDBLOCK
4928 else if (nread == -1 && errno == EWOULDBLOCK)
4930 #endif
4931 else if (nread == -1 && errno == EAGAIN)
4933 #ifdef WINDOWSNT
4934 /* FIXME: Is this special case still needed? */
4935 /* Note that we cannot distinguish between no input
4936 available now and a closed pipe.
4937 With luck, a closed pipe will be accompanied by
4938 subprocess termination and SIGCHLD. */
4939 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4941 #endif
4942 #ifdef HAVE_PTYS
4943 /* On some OSs with ptys, when the process on one end of
4944 a pty exits, the other end gets an error reading with
4945 errno = EIO instead of getting an EOF (0 bytes read).
4946 Therefore, if we get an error reading and errno =
4947 EIO, just continue, because the child process has
4948 exited and should clean itself up soon (e.g. when we
4949 get a SIGCHLD). */
4950 else if (nread == -1 && errno == EIO)
4952 struct Lisp_Process *p = XPROCESS (proc);
4954 /* Clear the descriptor now, so we only raise the
4955 signal once. */
4956 delete_read_fd (channel);
4958 if (p->pid == -2)
4960 /* If the EIO occurs on a pty, the SIGCHLD handler's
4961 waitpid call will not find the process object to
4962 delete. Do it here. */
4963 p->tick = ++process_tick;
4964 pset_status (p, Qfailed);
4967 #endif /* HAVE_PTYS */
4968 /* If we can detect process termination, don't consider the
4969 process gone just because its pipe is closed. */
4970 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4972 else
4974 /* Preserve status of processes already terminated. */
4975 XPROCESS (proc)->tick = ++process_tick;
4976 deactivate_process (proc);
4977 if (XPROCESS (proc)->raw_status_new)
4978 update_status (XPROCESS (proc));
4979 if (EQ (XPROCESS (proc)->status, Qrun))
4980 pset_status (XPROCESS (proc),
4981 list2 (Qexit, make_number (256)));
4984 #ifdef NON_BLOCKING_CONNECT
4985 if (FD_ISSET (channel, &Writeok)
4986 && (fd_callback_info[channel].flags
4987 & NON_BLOCKING_CONNECT_FD) != 0)
4989 struct Lisp_Process *p;
4991 delete_write_fd (channel);
4993 proc = chan_process[channel];
4994 if (NILP (proc))
4995 continue;
4997 p = XPROCESS (proc);
4999 #ifdef GNU_LINUX
5000 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5001 So only use it on systems where it is known to work. */
5003 socklen_t xlen = sizeof (xerrno);
5004 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5005 xerrno = errno;
5007 #else
5009 struct sockaddr pname;
5010 int pnamelen = sizeof (pname);
5012 /* If connection failed, getpeername will fail. */
5013 xerrno = 0;
5014 if (getpeername (channel, &pname, &pnamelen) < 0)
5016 /* Obtain connect failure code through error slippage. */
5017 char dummy;
5018 xerrno = errno;
5019 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5020 xerrno = errno;
5023 #endif
5024 if (xerrno)
5026 p->tick = ++process_tick;
5027 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5028 deactivate_process (proc);
5030 else
5032 pset_status (p, Qrun);
5033 /* Execute the sentinel here. If we had relied on
5034 status_notify to do it later, it will read input
5035 from the process before calling the sentinel. */
5036 exec_sentinel (proc, build_string ("open\n"));
5037 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5038 delete_read_fd (p->infd);
5041 #endif /* NON_BLOCKING_CONNECT */
5042 } /* End for each file descriptor. */
5043 } /* End while exit conditions not met. */
5045 unbind_to (count, Qnil);
5047 /* If calling from keyboard input, do not quit
5048 since we want to return C-g as an input character.
5049 Otherwise, do pending quit if requested. */
5050 if (read_kbd >= 0)
5052 /* Prevent input_pending from remaining set if we quit. */
5053 clear_input_pending ();
5054 QUIT;
5057 return got_some_input;
5060 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5062 static Lisp_Object
5063 read_process_output_call (Lisp_Object fun_and_args)
5065 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5068 static Lisp_Object
5069 read_process_output_error_handler (Lisp_Object error_val)
5071 cmd_error_internal (error_val, "error in process filter: ");
5072 Vinhibit_quit = Qt;
5073 update_echo_area ();
5074 Fsleep_for (make_number (2), Qnil);
5075 return Qt;
5078 static void
5079 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5080 ssize_t nbytes,
5081 struct coding_system *coding);
5083 /* Read pending output from the process channel,
5084 starting with our buffered-ahead character if we have one.
5085 Yield number of decoded characters read.
5087 This function reads at most 4096 characters.
5088 If you want to read all available subprocess output,
5089 you must call it repeatedly until it returns zero.
5091 The characters read are decoded according to PROC's coding-system
5092 for decoding. */
5094 static int
5095 read_process_output (Lisp_Object proc, register int channel)
5097 register ssize_t nbytes;
5098 char *chars;
5099 register struct Lisp_Process *p = XPROCESS (proc);
5100 struct coding_system *coding = proc_decode_coding_system[channel];
5101 int carryover = p->decoding_carryover;
5102 int readmax = 4096;
5103 ptrdiff_t count = SPECPDL_INDEX ();
5104 Lisp_Object odeactivate;
5106 chars = alloca (carryover + readmax);
5107 if (carryover)
5108 /* See the comment above. */
5109 memcpy (chars, SDATA (p->decoding_buf), carryover);
5111 #ifdef DATAGRAM_SOCKETS
5112 /* We have a working select, so proc_buffered_char is always -1. */
5113 if (DATAGRAM_CHAN_P (channel))
5115 socklen_t len = datagram_address[channel].len;
5116 nbytes = recvfrom (channel, chars + carryover, readmax,
5117 0, datagram_address[channel].sa, &len);
5119 else
5120 #endif
5122 bool buffered = proc_buffered_char[channel] >= 0;
5123 if (buffered)
5125 chars[carryover] = proc_buffered_char[channel];
5126 proc_buffered_char[channel] = -1;
5128 #ifdef HAVE_GNUTLS
5129 if (p->gnutls_p)
5130 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5131 readmax - buffered);
5132 else
5133 #endif
5134 nbytes = emacs_read (channel, chars + carryover + buffered,
5135 readmax - buffered);
5136 #ifdef ADAPTIVE_READ_BUFFERING
5137 if (nbytes > 0 && p->adaptive_read_buffering)
5139 int delay = p->read_output_delay;
5140 if (nbytes < 256)
5142 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5144 if (delay == 0)
5145 process_output_delay_count++;
5146 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5149 else if (delay > 0 && nbytes == readmax - buffered)
5151 delay -= READ_OUTPUT_DELAY_INCREMENT;
5152 if (delay == 0)
5153 process_output_delay_count--;
5155 p->read_output_delay = delay;
5156 if (delay)
5158 p->read_output_skip = 1;
5159 process_output_skip = 1;
5162 #endif
5163 nbytes += buffered;
5164 nbytes += buffered && nbytes <= 0;
5167 p->decoding_carryover = 0;
5169 /* At this point, NBYTES holds number of bytes just received
5170 (including the one in proc_buffered_char[channel]). */
5171 if (nbytes <= 0)
5173 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5174 return nbytes;
5175 coding->mode |= CODING_MODE_LAST_BLOCK;
5178 /* Now set NBYTES how many bytes we must decode. */
5179 nbytes += carryover;
5181 odeactivate = Vdeactivate_mark;
5182 /* There's no good reason to let process filters change the current
5183 buffer, and many callers of accept-process-output, sit-for, and
5184 friends don't expect current-buffer to be changed from under them. */
5185 record_unwind_current_buffer ();
5187 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5189 /* Handling the process output should not deactivate the mark. */
5190 Vdeactivate_mark = odeactivate;
5192 unbind_to (count, Qnil);
5193 return nbytes;
5196 static void
5197 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5198 ssize_t nbytes,
5199 struct coding_system *coding)
5201 Lisp_Object outstream = p->filter;
5202 Lisp_Object text;
5203 bool outer_running_asynch_code = running_asynch_code;
5204 int waiting = waiting_for_user_input_p;
5206 /* No need to gcpro these, because all we do with them later
5207 is test them for EQness, and none of them should be a string. */
5208 #if 0
5209 Lisp_Object obuffer, okeymap;
5210 XSETBUFFER (obuffer, current_buffer);
5211 okeymap = BVAR (current_buffer, keymap);
5212 #endif
5214 /* We inhibit quit here instead of just catching it so that
5215 hitting ^G when a filter happens to be running won't screw
5216 it up. */
5217 specbind (Qinhibit_quit, Qt);
5218 specbind (Qlast_nonmenu_event, Qt);
5220 /* In case we get recursively called,
5221 and we already saved the match data nonrecursively,
5222 save the same match data in safely recursive fashion. */
5223 if (outer_running_asynch_code)
5225 Lisp_Object tem;
5226 /* Don't clobber the CURRENT match data, either! */
5227 tem = Fmatch_data (Qnil, Qnil, Qnil);
5228 restore_search_regs ();
5229 record_unwind_save_match_data ();
5230 Fset_match_data (tem, Qt);
5233 /* For speed, if a search happens within this code,
5234 save the match data in a special nonrecursive fashion. */
5235 running_asynch_code = 1;
5237 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5238 text = coding->dst_object;
5239 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5240 /* A new coding system might be found. */
5241 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5243 pset_decode_coding_system (p, Vlast_coding_system_used);
5245 /* Don't call setup_coding_system for
5246 proc_decode_coding_system[channel] here. It is done in
5247 detect_coding called via decode_coding above. */
5249 /* If a coding system for encoding is not yet decided, we set
5250 it as the same as coding-system for decoding.
5252 But, before doing that we must check if
5253 proc_encode_coding_system[p->outfd] surely points to a
5254 valid memory because p->outfd will be changed once EOF is
5255 sent to the process. */
5256 if (NILP (p->encode_coding_system)
5257 && proc_encode_coding_system[p->outfd])
5259 pset_encode_coding_system
5260 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5261 setup_coding_system (p->encode_coding_system,
5262 proc_encode_coding_system[p->outfd]);
5266 if (coding->carryover_bytes > 0)
5268 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5269 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5270 memcpy (SDATA (p->decoding_buf), coding->carryover,
5271 coding->carryover_bytes);
5272 p->decoding_carryover = coding->carryover_bytes;
5274 if (SBYTES (text) > 0)
5275 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5276 sometimes it's simply wrong to wrap (e.g. when called from
5277 accept-process-output). */
5278 internal_condition_case_1 (read_process_output_call,
5279 list3 (outstream, make_lisp_proc (p), text),
5280 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5281 read_process_output_error_handler);
5283 /* If we saved the match data nonrecursively, restore it now. */
5284 restore_search_regs ();
5285 running_asynch_code = outer_running_asynch_code;
5287 /* Restore waiting_for_user_input_p as it was
5288 when we were called, in case the filter clobbered it. */
5289 waiting_for_user_input_p = waiting;
5291 #if 0 /* Call record_asynch_buffer_change unconditionally,
5292 because we might have changed minor modes or other things
5293 that affect key bindings. */
5294 if (! EQ (Fcurrent_buffer (), obuffer)
5295 || ! EQ (current_buffer->keymap, okeymap))
5296 #endif
5297 /* But do it only if the caller is actually going to read events.
5298 Otherwise there's no need to make him wake up, and it could
5299 cause trouble (for example it would make sit_for return). */
5300 if (waiting_for_user_input_p == -1)
5301 record_asynch_buffer_change ();
5304 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5305 Sinternal_default_process_filter, 2, 2, 0,
5306 doc: /* Function used as default process filter. */)
5307 (Lisp_Object proc, Lisp_Object text)
5309 struct Lisp_Process *p;
5310 ptrdiff_t opoint;
5312 CHECK_PROCESS (proc);
5313 p = XPROCESS (proc);
5314 CHECK_STRING (text);
5316 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5318 Lisp_Object old_read_only;
5319 ptrdiff_t old_begv, old_zv;
5320 ptrdiff_t old_begv_byte, old_zv_byte;
5321 ptrdiff_t before, before_byte;
5322 ptrdiff_t opoint_byte;
5323 struct buffer *b;
5325 Fset_buffer (p->buffer);
5326 opoint = PT;
5327 opoint_byte = PT_BYTE;
5328 old_read_only = BVAR (current_buffer, read_only);
5329 old_begv = BEGV;
5330 old_zv = ZV;
5331 old_begv_byte = BEGV_BYTE;
5332 old_zv_byte = ZV_BYTE;
5334 bset_read_only (current_buffer, Qnil);
5336 /* Insert new output into buffer
5337 at the current end-of-output marker,
5338 thus preserving logical ordering of input and output. */
5339 if (XMARKER (p->mark)->buffer)
5340 SET_PT_BOTH (clip_to_bounds (BEGV,
5341 marker_position (p->mark), ZV),
5342 clip_to_bounds (BEGV_BYTE,
5343 marker_byte_position (p->mark),
5344 ZV_BYTE));
5345 else
5346 SET_PT_BOTH (ZV, ZV_BYTE);
5347 before = PT;
5348 before_byte = PT_BYTE;
5350 /* If the output marker is outside of the visible region, save
5351 the restriction and widen. */
5352 if (! (BEGV <= PT && PT <= ZV))
5353 Fwiden ();
5355 /* Adjust the multibyteness of TEXT to that of the buffer. */
5356 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5357 != ! STRING_MULTIBYTE (text))
5358 text = (STRING_MULTIBYTE (text)
5359 ? Fstring_as_unibyte (text)
5360 : Fstring_to_multibyte (text));
5361 /* Insert before markers in case we are inserting where
5362 the buffer's mark is, and the user's next command is Meta-y. */
5363 insert_from_string_before_markers (text, 0, 0,
5364 SCHARS (text), SBYTES (text), 0);
5366 /* Make sure the process marker's position is valid when the
5367 process buffer is changed in the signal_after_change above.
5368 W3 is known to do that. */
5369 if (BUFFERP (p->buffer)
5370 && (b = XBUFFER (p->buffer), b != current_buffer))
5371 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5372 else
5373 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5375 update_mode_lines++;
5377 /* Make sure opoint and the old restrictions
5378 float ahead of any new text just as point would. */
5379 if (opoint >= before)
5381 opoint += PT - before;
5382 opoint_byte += PT_BYTE - before_byte;
5384 if (old_begv > before)
5386 old_begv += PT - before;
5387 old_begv_byte += PT_BYTE - before_byte;
5389 if (old_zv >= before)
5391 old_zv += PT - before;
5392 old_zv_byte += PT_BYTE - before_byte;
5395 /* If the restriction isn't what it should be, set it. */
5396 if (old_begv != BEGV || old_zv != ZV)
5397 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5399 bset_read_only (current_buffer, old_read_only);
5400 SET_PT_BOTH (opoint, opoint_byte);
5402 return Qnil;
5405 /* Sending data to subprocess. */
5407 /* In send_process, when a write fails temporarily,
5408 wait_reading_process_output is called. It may execute user code,
5409 e.g. timers, that attempts to write new data to the same process.
5410 We must ensure that data is sent in the right order, and not
5411 interspersed half-completed with other writes (Bug#10815). This is
5412 handled by the write_queue element of struct process. It is a list
5413 with each entry having the form
5415 (string . (offset . length))
5417 where STRING is a lisp string, OFFSET is the offset into the
5418 string's byte sequence from which we should begin to send, and
5419 LENGTH is the number of bytes left to send. */
5421 /* Create a new entry in write_queue.
5422 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5423 BUF is a pointer to the string sequence of the input_obj or a C
5424 string in case of Qt or Qnil. */
5426 static void
5427 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5428 const char *buf, ptrdiff_t len, bool front)
5430 ptrdiff_t offset;
5431 Lisp_Object entry, obj;
5433 if (STRINGP (input_obj))
5435 offset = buf - SSDATA (input_obj);
5436 obj = input_obj;
5438 else
5440 offset = 0;
5441 obj = make_unibyte_string (buf, len);
5444 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5446 if (front)
5447 pset_write_queue (p, Fcons (entry, p->write_queue));
5448 else
5449 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5452 /* Remove the first element in the write_queue of process P, put its
5453 contents in OBJ, BUF and LEN, and return true. If the
5454 write_queue is empty, return false. */
5456 static bool
5457 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5458 const char **buf, ptrdiff_t *len)
5460 Lisp_Object entry, offset_length;
5461 ptrdiff_t offset;
5463 if (NILP (p->write_queue))
5464 return 0;
5466 entry = XCAR (p->write_queue);
5467 pset_write_queue (p, XCDR (p->write_queue));
5469 *obj = XCAR (entry);
5470 offset_length = XCDR (entry);
5472 *len = XINT (XCDR (offset_length));
5473 offset = XINT (XCAR (offset_length));
5474 *buf = SSDATA (*obj) + offset;
5476 return 1;
5479 /* Send some data to process PROC.
5480 BUF is the beginning of the data; LEN is the number of characters.
5481 OBJECT is the Lisp object that the data comes from. If OBJECT is
5482 nil or t, it means that the data comes from C string.
5484 If OBJECT is not nil, the data is encoded by PROC's coding-system
5485 for encoding before it is sent.
5487 This function can evaluate Lisp code and can garbage collect. */
5489 static void
5490 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5491 Lisp_Object object)
5493 struct Lisp_Process *p = XPROCESS (proc);
5494 ssize_t rv;
5495 struct coding_system *coding;
5497 if (p->raw_status_new)
5498 update_status (p);
5499 if (! EQ (p->status, Qrun))
5500 error ("Process %s not running", SDATA (p->name));
5501 if (p->outfd < 0)
5502 error ("Output file descriptor of %s is closed", SDATA (p->name));
5504 coding = proc_encode_coding_system[p->outfd];
5505 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5507 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5508 || (BUFFERP (object)
5509 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5510 || EQ (object, Qt))
5512 pset_encode_coding_system
5513 (p, complement_process_encoding_system (p->encode_coding_system));
5514 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5516 /* The coding system for encoding was changed to raw-text
5517 because we sent a unibyte text previously. Now we are
5518 sending a multibyte text, thus we must encode it by the
5519 original coding system specified for the current process.
5521 Another reason we come here is that the coding system
5522 was just complemented and a new one was returned by
5523 complement_process_encoding_system. */
5524 setup_coding_system (p->encode_coding_system, coding);
5525 Vlast_coding_system_used = p->encode_coding_system;
5527 coding->src_multibyte = 1;
5529 else
5531 coding->src_multibyte = 0;
5532 /* For sending a unibyte text, character code conversion should
5533 not take place but EOL conversion should. So, setup raw-text
5534 or one of the subsidiary if we have not yet done it. */
5535 if (CODING_REQUIRE_ENCODING (coding))
5537 if (CODING_REQUIRE_FLUSHING (coding))
5539 /* But, before changing the coding, we must flush out data. */
5540 coding->mode |= CODING_MODE_LAST_BLOCK;
5541 send_process (proc, "", 0, Qt);
5542 coding->mode &= CODING_MODE_LAST_BLOCK;
5544 setup_coding_system (raw_text_coding_system
5545 (Vlast_coding_system_used),
5546 coding);
5547 coding->src_multibyte = 0;
5550 coding->dst_multibyte = 0;
5552 if (CODING_REQUIRE_ENCODING (coding))
5554 coding->dst_object = Qt;
5555 if (BUFFERP (object))
5557 ptrdiff_t from_byte, from, to;
5558 ptrdiff_t save_pt, save_pt_byte;
5559 struct buffer *cur = current_buffer;
5561 set_buffer_internal (XBUFFER (object));
5562 save_pt = PT, save_pt_byte = PT_BYTE;
5564 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5565 from = BYTE_TO_CHAR (from_byte);
5566 to = BYTE_TO_CHAR (from_byte + len);
5567 TEMP_SET_PT_BOTH (from, from_byte);
5568 encode_coding_object (coding, object, from, from_byte,
5569 to, from_byte + len, Qt);
5570 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5571 set_buffer_internal (cur);
5573 else if (STRINGP (object))
5575 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5576 SBYTES (object), Qt);
5578 else
5580 coding->dst_object = make_unibyte_string (buf, len);
5581 coding->produced = len;
5584 len = coding->produced;
5585 object = coding->dst_object;
5586 buf = SSDATA (object);
5589 /* If there is already data in the write_queue, put the new data
5590 in the back of queue. Otherwise, ignore it. */
5591 if (!NILP (p->write_queue))
5592 write_queue_push (p, object, buf, len, 0);
5594 do /* while !NILP (p->write_queue) */
5596 ptrdiff_t cur_len = -1;
5597 const char *cur_buf;
5598 Lisp_Object cur_object;
5600 /* If write_queue is empty, ignore it. */
5601 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5603 cur_len = len;
5604 cur_buf = buf;
5605 cur_object = object;
5608 while (cur_len > 0)
5610 /* Send this batch, using one or more write calls. */
5611 ptrdiff_t written = 0;
5612 int outfd = p->outfd;
5613 #ifdef DATAGRAM_SOCKETS
5614 if (DATAGRAM_CHAN_P (outfd))
5616 rv = sendto (outfd, cur_buf, cur_len,
5617 0, datagram_address[outfd].sa,
5618 datagram_address[outfd].len);
5619 if (rv >= 0)
5620 written = rv;
5621 else if (errno == EMSGSIZE)
5622 report_file_error ("Sending datagram", proc);
5624 else
5625 #endif
5627 #ifdef HAVE_GNUTLS
5628 if (p->gnutls_p)
5629 written = emacs_gnutls_write (p, cur_buf, cur_len);
5630 else
5631 #endif
5632 written = emacs_write_sig (outfd, cur_buf, cur_len);
5633 rv = (written ? 0 : -1);
5634 #ifdef ADAPTIVE_READ_BUFFERING
5635 if (p->read_output_delay > 0
5636 && p->adaptive_read_buffering == 1)
5638 p->read_output_delay = 0;
5639 process_output_delay_count--;
5640 p->read_output_skip = 0;
5642 #endif
5645 if (rv < 0)
5647 if (errno == EAGAIN
5648 #ifdef EWOULDBLOCK
5649 || errno == EWOULDBLOCK
5650 #endif
5652 /* Buffer is full. Wait, accepting input;
5653 that may allow the program
5654 to finish doing output and read more. */
5656 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5657 /* A gross hack to work around a bug in FreeBSD.
5658 In the following sequence, read(2) returns
5659 bogus data:
5661 write(2) 1022 bytes
5662 write(2) 954 bytes, get EAGAIN
5663 read(2) 1024 bytes in process_read_output
5664 read(2) 11 bytes in process_read_output
5666 That is, read(2) returns more bytes than have
5667 ever been written successfully. The 1033 bytes
5668 read are the 1022 bytes written successfully
5669 after processing (for example with CRs added if
5670 the terminal is set up that way which it is
5671 here). The same bytes will be seen again in a
5672 later read(2), without the CRs. */
5674 if (errno == EAGAIN)
5676 int flags = FWRITE;
5677 ioctl (p->outfd, TIOCFLUSH, &flags);
5679 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5681 /* Put what we should have written in wait_queue. */
5682 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5683 wait_reading_process_output (0, 20 * 1000 * 1000,
5684 0, 0, Qnil, NULL, 0);
5685 /* Reread queue, to see what is left. */
5686 break;
5688 else if (errno == EPIPE)
5690 p->raw_status_new = 0;
5691 pset_status (p, list2 (Qexit, make_number (256)));
5692 p->tick = ++process_tick;
5693 deactivate_process (proc);
5694 error ("process %s no longer connected to pipe; closed it",
5695 SDATA (p->name));
5697 else
5698 /* This is a real error. */
5699 report_file_error ("Writing to process", proc);
5701 cur_buf += written;
5702 cur_len -= written;
5705 while (!NILP (p->write_queue));
5708 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5709 3, 3, 0,
5710 doc: /* Send current contents of region as input to PROCESS.
5711 PROCESS may be a process, a buffer, the name of a process or buffer, or
5712 nil, indicating the current buffer's process.
5713 Called from program, takes three arguments, PROCESS, START and END.
5714 If the region is more than 500 characters long,
5715 it is sent in several bunches. This may happen even for shorter regions.
5716 Output from processes can arrive in between bunches. */)
5717 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5719 Lisp_Object proc = get_process (process);
5720 ptrdiff_t start_byte, end_byte;
5722 validate_region (&start, &end);
5724 start_byte = CHAR_TO_BYTE (XINT (start));
5725 end_byte = CHAR_TO_BYTE (XINT (end));
5727 if (XINT (start) < GPT && XINT (end) > GPT)
5728 move_gap_both (XINT (start), start_byte);
5730 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5731 end_byte - start_byte, Fcurrent_buffer ());
5733 return Qnil;
5736 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5737 2, 2, 0,
5738 doc: /* Send PROCESS the contents of STRING as input.
5739 PROCESS may be a process, a buffer, the name of a process or buffer, or
5740 nil, indicating the current buffer's process.
5741 If STRING is more than 500 characters long,
5742 it is sent in several bunches. This may happen even for shorter strings.
5743 Output from processes can arrive in between bunches. */)
5744 (Lisp_Object process, Lisp_Object string)
5746 Lisp_Object proc;
5747 CHECK_STRING (string);
5748 proc = get_process (process);
5749 send_process (proc, SSDATA (string),
5750 SBYTES (string), string);
5751 return Qnil;
5754 /* Return the foreground process group for the tty/pty that
5755 the process P uses. */
5756 static pid_t
5757 emacs_get_tty_pgrp (struct Lisp_Process *p)
5759 pid_t gid = -1;
5761 #ifdef TIOCGPGRP
5762 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5764 int fd;
5765 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5766 master side. Try the slave side. */
5767 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5769 if (fd != -1)
5771 ioctl (fd, TIOCGPGRP, &gid);
5772 emacs_close (fd);
5775 #endif /* defined (TIOCGPGRP ) */
5777 return gid;
5780 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5781 Sprocess_running_child_p, 0, 1, 0,
5782 doc: /* Return t if PROCESS has given the terminal to a child.
5783 If the operating system does not make it possible to find out,
5784 return t unconditionally. */)
5785 (Lisp_Object process)
5787 /* Initialize in case ioctl doesn't exist or gives an error,
5788 in a way that will cause returning t. */
5789 pid_t gid;
5790 Lisp_Object proc;
5791 struct Lisp_Process *p;
5793 proc = get_process (process);
5794 p = XPROCESS (proc);
5796 if (!EQ (p->type, Qreal))
5797 error ("Process %s is not a subprocess",
5798 SDATA (p->name));
5799 if (p->infd < 0)
5800 error ("Process %s is not active",
5801 SDATA (p->name));
5803 gid = emacs_get_tty_pgrp (p);
5805 if (gid == p->pid)
5806 return Qnil;
5807 return Qt;
5810 /* send a signal number SIGNO to PROCESS.
5811 If CURRENT_GROUP is t, that means send to the process group
5812 that currently owns the terminal being used to communicate with PROCESS.
5813 This is used for various commands in shell mode.
5814 If CURRENT_GROUP is lambda, that means send to the process group
5815 that currently owns the terminal, but only if it is NOT the shell itself.
5817 If NOMSG is false, insert signal-announcements into process's buffers
5818 right away.
5820 If we can, we try to signal PROCESS by sending control characters
5821 down the pty. This allows us to signal inferiors who have changed
5822 their uid, for which kill would return an EPERM error. */
5824 static void
5825 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5826 bool nomsg)
5828 Lisp_Object proc;
5829 struct Lisp_Process *p;
5830 pid_t gid;
5831 bool no_pgrp = 0;
5833 proc = get_process (process);
5834 p = XPROCESS (proc);
5836 if (!EQ (p->type, Qreal))
5837 error ("Process %s is not a subprocess",
5838 SDATA (p->name));
5839 if (p->infd < 0)
5840 error ("Process %s is not active",
5841 SDATA (p->name));
5843 if (!p->pty_flag)
5844 current_group = Qnil;
5846 /* If we are using pgrps, get a pgrp number and make it negative. */
5847 if (NILP (current_group))
5848 /* Send the signal to the shell's process group. */
5849 gid = p->pid;
5850 else
5852 #ifdef SIGNALS_VIA_CHARACTERS
5853 /* If possible, send signals to the entire pgrp
5854 by sending an input character to it. */
5856 struct termios t;
5857 cc_t *sig_char = NULL;
5859 tcgetattr (p->infd, &t);
5861 switch (signo)
5863 case SIGINT:
5864 sig_char = &t.c_cc[VINTR];
5865 break;
5867 case SIGQUIT:
5868 sig_char = &t.c_cc[VQUIT];
5869 break;
5871 case SIGTSTP:
5872 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5873 sig_char = &t.c_cc[VSWTCH];
5874 #else
5875 sig_char = &t.c_cc[VSUSP];
5876 #endif
5877 break;
5880 if (sig_char && *sig_char != CDISABLE)
5882 send_process (proc, (char *) sig_char, 1, Qnil);
5883 return;
5885 /* If we can't send the signal with a character,
5886 fall through and send it another way. */
5888 /* The code above may fall through if it can't
5889 handle the signal. */
5890 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5892 #ifdef TIOCGPGRP
5893 /* Get the current pgrp using the tty itself, if we have that.
5894 Otherwise, use the pty to get the pgrp.
5895 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5896 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5897 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5898 His patch indicates that if TIOCGPGRP returns an error, then
5899 we should just assume that p->pid is also the process group id. */
5901 gid = emacs_get_tty_pgrp (p);
5903 if (gid == -1)
5904 /* If we can't get the information, assume
5905 the shell owns the tty. */
5906 gid = p->pid;
5908 /* It is not clear whether anything really can set GID to -1.
5909 Perhaps on some system one of those ioctls can or could do so.
5910 Or perhaps this is vestigial. */
5911 if (gid == -1)
5912 no_pgrp = 1;
5913 #else /* ! defined (TIOCGPGRP ) */
5914 /* Can't select pgrps on this system, so we know that
5915 the child itself heads the pgrp. */
5916 gid = p->pid;
5917 #endif /* ! defined (TIOCGPGRP ) */
5919 /* If current_group is lambda, and the shell owns the terminal,
5920 don't send any signal. */
5921 if (EQ (current_group, Qlambda) && gid == p->pid)
5922 return;
5925 #ifdef SIGCONT
5926 if (signo == SIGCONT)
5928 p->raw_status_new = 0;
5929 pset_status (p, Qrun);
5930 p->tick = ++process_tick;
5931 if (!nomsg)
5933 status_notify (NULL);
5934 redisplay_preserve_echo_area (13);
5937 #endif
5939 /* If we don't have process groups, send the signal to the immediate
5940 subprocess. That isn't really right, but it's better than any
5941 obvious alternative. */
5942 if (no_pgrp)
5944 kill (p->pid, signo);
5945 return;
5948 /* gid may be a pid, or minus a pgrp's number */
5949 #ifdef TIOCSIGSEND
5950 if (!NILP (current_group))
5952 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5953 kill (-gid, signo);
5955 else
5957 gid = - p->pid;
5958 kill (gid, signo);
5960 #else /* ! defined (TIOCSIGSEND) */
5961 kill (-gid, signo);
5962 #endif /* ! defined (TIOCSIGSEND) */
5965 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5966 doc: /* Interrupt process PROCESS.
5967 PROCESS may be a process, a buffer, or the name of a process or buffer.
5968 No arg or nil means current buffer's process.
5969 Second arg CURRENT-GROUP non-nil means send signal to
5970 the current process-group of the process's controlling terminal
5971 rather than to the process's own process group.
5972 If the process is a shell, this means interrupt current subjob
5973 rather than the shell.
5975 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5976 don't send the signal. */)
5977 (Lisp_Object process, Lisp_Object current_group)
5979 process_send_signal (process, SIGINT, current_group, 0);
5980 return process;
5983 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5984 doc: /* Kill process PROCESS. May be process or name of one.
5985 See function `interrupt-process' for more details on usage. */)
5986 (Lisp_Object process, Lisp_Object current_group)
5988 process_send_signal (process, SIGKILL, current_group, 0);
5989 return process;
5992 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5993 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5994 See function `interrupt-process' for more details on usage. */)
5995 (Lisp_Object process, Lisp_Object current_group)
5997 process_send_signal (process, SIGQUIT, current_group, 0);
5998 return process;
6001 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6002 doc: /* Stop process PROCESS. May be process or name of one.
6003 See function `interrupt-process' for more details on usage.
6004 If PROCESS is a network or serial process, inhibit handling of incoming
6005 traffic. */)
6006 (Lisp_Object process, Lisp_Object current_group)
6008 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6010 struct Lisp_Process *p;
6012 p = XPROCESS (process);
6013 if (NILP (p->command)
6014 && p->infd >= 0)
6015 delete_read_fd (p->infd);
6016 pset_command (p, Qt);
6017 return process;
6019 #ifndef SIGTSTP
6020 error ("No SIGTSTP support");
6021 #else
6022 process_send_signal (process, SIGTSTP, current_group, 0);
6023 #endif
6024 return process;
6027 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6028 doc: /* Continue process PROCESS. May be process or name of one.
6029 See function `interrupt-process' for more details on usage.
6030 If PROCESS is a network or serial process, resume handling of incoming
6031 traffic. */)
6032 (Lisp_Object process, Lisp_Object current_group)
6034 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6036 struct Lisp_Process *p;
6038 p = XPROCESS (process);
6039 if (EQ (p->command, Qt)
6040 && p->infd >= 0
6041 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6043 add_non_keyboard_read_fd (p->infd);
6044 #ifdef WINDOWSNT
6045 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6046 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6047 #else /* not WINDOWSNT */
6048 tcflush (p->infd, TCIFLUSH);
6049 #endif /* not WINDOWSNT */
6051 pset_command (p, Qnil);
6052 return process;
6054 #ifdef SIGCONT
6055 process_send_signal (process, SIGCONT, current_group, 0);
6056 #else
6057 error ("No SIGCONT support");
6058 #endif
6059 return process;
6062 /* Return the integer value of the signal whose abbreviation is ABBR,
6063 or a negative number if there is no such signal. */
6064 static int
6065 abbr_to_signal (char const *name)
6067 int i, signo;
6068 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6070 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6071 name += 3;
6073 for (i = 0; i < sizeof sigbuf; i++)
6075 sigbuf[i] = c_toupper (name[i]);
6076 if (! sigbuf[i])
6077 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6080 return -1;
6083 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6084 2, 2, "sProcess (name or number): \nnSignal code: ",
6085 doc: /* Send PROCESS the signal with code SIGCODE.
6086 PROCESS may also be a number specifying the process id of the
6087 process to signal; in this case, the process need not be a child of
6088 this Emacs.
6089 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6090 (Lisp_Object process, Lisp_Object sigcode)
6092 pid_t pid;
6093 int signo;
6095 if (STRINGP (process))
6097 Lisp_Object tem = Fget_process (process);
6098 if (NILP (tem))
6100 Lisp_Object process_number =
6101 string_to_number (SSDATA (process), 10, 1);
6102 if (INTEGERP (process_number) || FLOATP (process_number))
6103 tem = process_number;
6105 process = tem;
6107 else if (!NUMBERP (process))
6108 process = get_process (process);
6110 if (NILP (process))
6111 return process;
6113 if (NUMBERP (process))
6114 CONS_TO_INTEGER (process, pid_t, pid);
6115 else
6117 CHECK_PROCESS (process);
6118 pid = XPROCESS (process)->pid;
6119 if (pid <= 0)
6120 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6123 if (INTEGERP (sigcode))
6125 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6126 signo = XINT (sigcode);
6128 else
6130 char *name;
6132 CHECK_SYMBOL (sigcode);
6133 name = SSDATA (SYMBOL_NAME (sigcode));
6135 signo = abbr_to_signal (name);
6136 if (signo < 0)
6137 error ("Undefined signal name %s", name);
6140 return make_number (kill (pid, signo));
6143 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6144 doc: /* Make PROCESS see end-of-file in its input.
6145 EOF comes after any text already sent to it.
6146 PROCESS may be a process, a buffer, the name of a process or buffer, or
6147 nil, indicating the current buffer's process.
6148 If PROCESS is a network connection, or is a process communicating
6149 through a pipe (as opposed to a pty), then you cannot send any more
6150 text to PROCESS after you call this function.
6151 If PROCESS is a serial process, wait until all output written to the
6152 process has been transmitted to the serial port. */)
6153 (Lisp_Object process)
6155 Lisp_Object proc;
6156 struct coding_system *coding;
6158 if (DATAGRAM_CONN_P (process))
6159 return process;
6161 proc = get_process (process);
6162 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6164 /* Make sure the process is really alive. */
6165 if (XPROCESS (proc)->raw_status_new)
6166 update_status (XPROCESS (proc));
6167 if (! EQ (XPROCESS (proc)->status, Qrun))
6168 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6170 if (CODING_REQUIRE_FLUSHING (coding))
6172 coding->mode |= CODING_MODE_LAST_BLOCK;
6173 send_process (proc, "", 0, Qnil);
6176 if (XPROCESS (proc)->pty_flag)
6177 send_process (proc, "\004", 1, Qnil);
6178 else if (EQ (XPROCESS (proc)->type, Qserial))
6180 #ifndef WINDOWSNT
6181 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6182 report_file_error ("Failed tcdrain", Qnil);
6183 #endif /* not WINDOWSNT */
6184 /* Do nothing on Windows because writes are blocking. */
6186 else
6188 int old_outfd = XPROCESS (proc)->outfd;
6189 int new_outfd;
6191 #ifdef HAVE_SHUTDOWN
6192 /* If this is a network connection, or socketpair is used
6193 for communication with the subprocess, call shutdown to cause EOF.
6194 (In some old system, shutdown to socketpair doesn't work.
6195 Then we just can't win.) */
6196 if (EQ (XPROCESS (proc)->type, Qnetwork)
6197 || XPROCESS (proc)->infd == old_outfd)
6198 shutdown (old_outfd, 1);
6199 #endif
6200 close_process_fd (&XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS]);
6201 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6202 if (new_outfd < 0)
6203 report_file_error ("Opening null device", Qnil);
6204 XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6205 XPROCESS (proc)->outfd = new_outfd;
6207 if (!proc_encode_coding_system[new_outfd])
6208 proc_encode_coding_system[new_outfd]
6209 = xmalloc (sizeof (struct coding_system));
6210 *proc_encode_coding_system[new_outfd]
6211 = *proc_encode_coding_system[old_outfd];
6212 memset (proc_encode_coding_system[old_outfd], 0,
6213 sizeof (struct coding_system));
6215 return process;
6218 /* The main Emacs thread records child processes in three places:
6220 - Vprocess_alist, for asynchronous subprocesses, which are child
6221 processes visible to Lisp.
6223 - deleted_pid_list, for child processes invisible to Lisp,
6224 typically because of delete-process. These are recorded so that
6225 the processes can be reaped when they exit, so that the operating
6226 system's process table is not cluttered by zombies.
6228 - the local variable PID in Fcall_process, call_process_cleanup and
6229 call_process_kill, for synchronous subprocesses.
6230 record_unwind_protect is used to make sure this process is not
6231 forgotten: if the user interrupts call-process and the child
6232 process refuses to exit immediately even with two C-g's,
6233 call_process_kill adds PID's contents to deleted_pid_list before
6234 returning.
6236 The main Emacs thread invokes waitpid only on child processes that
6237 it creates and that have not been reaped. This avoid races on
6238 platforms such as GTK, where other threads create their own
6239 subprocesses which the main thread should not reap. For example,
6240 if the main thread attempted to reap an already-reaped child, it
6241 might inadvertently reap a GTK-created process that happened to
6242 have the same process ID. */
6244 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6245 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6246 keep track of its own children. GNUstep is similar. */
6248 static void dummy_handler (int sig) {}
6249 static signal_handler_t volatile lib_child_handler;
6251 /* Handle a SIGCHLD signal by looking for known child processes of
6252 Emacs whose status have changed. For each one found, record its
6253 new status.
6255 All we do is change the status; we do not run sentinels or print
6256 notifications. That is saved for the next time keyboard input is
6257 done, in order to avoid timing errors.
6259 ** WARNING: this can be called during garbage collection.
6260 Therefore, it must not be fooled by the presence of mark bits in
6261 Lisp objects.
6263 ** USG WARNING: Although it is not obvious from the documentation
6264 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6265 signal() before executing at least one wait(), otherwise the
6266 handler will be called again, resulting in an infinite loop. The
6267 relevant portion of the documentation reads "SIGCLD signals will be
6268 queued and the signal-catching function will be continually
6269 reentered until the queue is empty". Invoking signal() causes the
6270 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6271 Inc.
6273 ** Malloc WARNING: This should never call malloc either directly or
6274 indirectly; if it does, that is a bug */
6276 static void
6277 handle_child_signal (int sig)
6279 Lisp_Object tail, proc;
6281 /* Find the process that signaled us, and record its status. */
6283 /* The process can have been deleted by Fdelete_process, or have
6284 been started asynchronously by Fcall_process. */
6285 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6287 bool all_pids_are_fixnums
6288 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6289 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6290 Lisp_Object head = XCAR (tail);
6291 Lisp_Object xpid;
6292 if (! CONSP (head))
6293 continue;
6294 xpid = XCAR (head);
6295 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6297 pid_t deleted_pid;
6298 if (INTEGERP (xpid))
6299 deleted_pid = XINT (xpid);
6300 else
6301 deleted_pid = XFLOAT_DATA (xpid);
6302 if (child_status_changed (deleted_pid, 0, 0))
6304 if (STRINGP (XCDR (head)))
6305 unlink (SSDATA (XCDR (head)));
6306 XSETCAR (tail, Qnil);
6311 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6312 FOR_EACH_PROCESS (tail, proc)
6314 struct Lisp_Process *p = XPROCESS (proc);
6315 int status;
6317 if (p->alive
6318 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6320 /* Change the status of the process that was found. */
6321 p->tick = ++process_tick;
6322 p->raw_status = status;
6323 p->raw_status_new = 1;
6325 /* If process has terminated, stop waiting for its output. */
6326 if (WIFSIGNALED (status) || WIFEXITED (status))
6328 bool clear_desc_flag = 0;
6329 p->alive = 0;
6330 if (p->infd >= 0)
6331 clear_desc_flag = 1;
6333 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6334 if (clear_desc_flag)
6335 delete_read_fd (p->infd);
6340 lib_child_handler (sig);
6341 #ifdef NS_IMPL_GNUSTEP
6342 /* NSTask in GNUStep sets its child handler each time it is called.
6343 So we must re-set ours. */
6344 catch_child_signal();
6345 #endif
6348 static void
6349 deliver_child_signal (int sig)
6351 deliver_process_signal (sig, handle_child_signal);
6355 static Lisp_Object
6356 exec_sentinel_error_handler (Lisp_Object error_val)
6358 cmd_error_internal (error_val, "error in process sentinel: ");
6359 Vinhibit_quit = Qt;
6360 update_echo_area ();
6361 Fsleep_for (make_number (2), Qnil);
6362 return Qt;
6365 static void
6366 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6368 Lisp_Object sentinel, odeactivate;
6369 struct Lisp_Process *p = XPROCESS (proc);
6370 ptrdiff_t count = SPECPDL_INDEX ();
6371 bool outer_running_asynch_code = running_asynch_code;
6372 int waiting = waiting_for_user_input_p;
6374 if (inhibit_sentinels)
6375 return;
6377 /* No need to gcpro these, because all we do with them later
6378 is test them for EQness, and none of them should be a string. */
6379 odeactivate = Vdeactivate_mark;
6380 #if 0
6381 Lisp_Object obuffer, okeymap;
6382 XSETBUFFER (obuffer, current_buffer);
6383 okeymap = BVAR (current_buffer, keymap);
6384 #endif
6386 /* There's no good reason to let sentinels change the current
6387 buffer, and many callers of accept-process-output, sit-for, and
6388 friends don't expect current-buffer to be changed from under them. */
6389 record_unwind_current_buffer ();
6391 sentinel = p->sentinel;
6393 /* Inhibit quit so that random quits don't screw up a running filter. */
6394 specbind (Qinhibit_quit, Qt);
6395 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6397 /* In case we get recursively called,
6398 and we already saved the match data nonrecursively,
6399 save the same match data in safely recursive fashion. */
6400 if (outer_running_asynch_code)
6402 Lisp_Object tem;
6403 tem = Fmatch_data (Qnil, Qnil, Qnil);
6404 restore_search_regs ();
6405 record_unwind_save_match_data ();
6406 Fset_match_data (tem, Qt);
6409 /* For speed, if a search happens within this code,
6410 save the match data in a special nonrecursive fashion. */
6411 running_asynch_code = 1;
6413 internal_condition_case_1 (read_process_output_call,
6414 list3 (sentinel, proc, reason),
6415 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6416 exec_sentinel_error_handler);
6418 /* If we saved the match data nonrecursively, restore it now. */
6419 restore_search_regs ();
6420 running_asynch_code = outer_running_asynch_code;
6422 Vdeactivate_mark = odeactivate;
6424 /* Restore waiting_for_user_input_p as it was
6425 when we were called, in case the filter clobbered it. */
6426 waiting_for_user_input_p = waiting;
6428 #if 0
6429 if (! EQ (Fcurrent_buffer (), obuffer)
6430 || ! EQ (current_buffer->keymap, okeymap))
6431 #endif
6432 /* But do it only if the caller is actually going to read events.
6433 Otherwise there's no need to make him wake up, and it could
6434 cause trouble (for example it would make sit_for return). */
6435 if (waiting_for_user_input_p == -1)
6436 record_asynch_buffer_change ();
6438 unbind_to (count, Qnil);
6441 /* Report all recent events of a change in process status
6442 (either run the sentinel or output a message).
6443 This is usually done while Emacs is waiting for keyboard input
6444 but can be done at other times. */
6446 static void
6447 status_notify (struct Lisp_Process *deleting_process)
6449 register Lisp_Object proc;
6450 Lisp_Object tail, msg;
6451 struct gcpro gcpro1, gcpro2;
6453 tail = Qnil;
6454 msg = Qnil;
6455 /* We need to gcpro tail; if read_process_output calls a filter
6456 which deletes a process and removes the cons to which tail points
6457 from Vprocess_alist, and then causes a GC, tail is an unprotected
6458 reference. */
6459 GCPRO2 (tail, msg);
6461 /* Set this now, so that if new processes are created by sentinels
6462 that we run, we get called again to handle their status changes. */
6463 update_tick = process_tick;
6465 FOR_EACH_PROCESS (tail, proc)
6467 Lisp_Object symbol;
6468 register struct Lisp_Process *p = XPROCESS (proc);
6470 if (p->tick != p->update_tick)
6472 p->update_tick = p->tick;
6474 /* If process is still active, read any output that remains. */
6475 while (! EQ (p->filter, Qt)
6476 && ! EQ (p->status, Qconnect)
6477 && ! EQ (p->status, Qlisten)
6478 /* Network or serial process not stopped: */
6479 && ! EQ (p->command, Qt)
6480 && p->infd >= 0
6481 && p != deleting_process
6482 && read_process_output (proc, p->infd) > 0);
6484 /* Get the text to use for the message. */
6485 if (p->raw_status_new)
6486 update_status (p);
6487 msg = status_message (p);
6489 /* If process is terminated, deactivate it or delete it. */
6490 symbol = p->status;
6491 if (CONSP (p->status))
6492 symbol = XCAR (p->status);
6494 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6495 || EQ (symbol, Qclosed))
6497 if (delete_exited_processes)
6498 remove_process (proc);
6499 else
6500 deactivate_process (proc);
6503 /* The actions above may have further incremented p->tick.
6504 So set p->update_tick again so that an error in the sentinel will
6505 not cause this code to be run again. */
6506 p->update_tick = p->tick;
6507 /* Now output the message suitably. */
6508 exec_sentinel (proc, msg);
6510 } /* end for */
6512 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6513 UNGCPRO;
6516 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6517 Sinternal_default_process_sentinel, 2, 2, 0,
6518 doc: /* Function used as default sentinel for processes. */)
6519 (Lisp_Object proc, Lisp_Object msg)
6521 Lisp_Object buffer, symbol;
6522 struct Lisp_Process *p;
6523 CHECK_PROCESS (proc);
6524 p = XPROCESS (proc);
6525 buffer = p->buffer;
6526 symbol = p->status;
6527 if (CONSP (symbol))
6528 symbol = XCAR (symbol);
6530 if (!EQ (symbol, Qrun) && !NILP (buffer))
6532 Lisp_Object tem;
6533 struct buffer *old = current_buffer;
6534 ptrdiff_t opoint, opoint_byte;
6535 ptrdiff_t before, before_byte;
6537 /* Avoid error if buffer is deleted
6538 (probably that's why the process is dead, too). */
6539 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6540 return Qnil;
6541 Fset_buffer (buffer);
6543 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6544 msg = (code_convert_string_norecord
6545 (msg, Vlocale_coding_system, 1));
6547 opoint = PT;
6548 opoint_byte = PT_BYTE;
6549 /* Insert new output into buffer
6550 at the current end-of-output marker,
6551 thus preserving logical ordering of input and output. */
6552 if (XMARKER (p->mark)->buffer)
6553 Fgoto_char (p->mark);
6554 else
6555 SET_PT_BOTH (ZV, ZV_BYTE);
6557 before = PT;
6558 before_byte = PT_BYTE;
6560 tem = BVAR (current_buffer, read_only);
6561 bset_read_only (current_buffer, Qnil);
6562 insert_string ("\nProcess ");
6563 { /* FIXME: temporary kludge. */
6564 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6565 insert_string (" ");
6566 Finsert (1, &msg);
6567 bset_read_only (current_buffer, tem);
6568 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6570 if (opoint >= before)
6571 SET_PT_BOTH (opoint + (PT - before),
6572 opoint_byte + (PT_BYTE - before_byte));
6573 else
6574 SET_PT_BOTH (opoint, opoint_byte);
6576 set_buffer_internal (old);
6578 return Qnil;
6582 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6583 Sset_process_coding_system, 1, 3, 0,
6584 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6585 DECODING will be used to decode subprocess output and ENCODING to
6586 encode subprocess input. */)
6587 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6589 register struct Lisp_Process *p;
6591 CHECK_PROCESS (process);
6592 p = XPROCESS (process);
6593 if (p->infd < 0)
6594 error ("Input file descriptor of %s closed", SDATA (p->name));
6595 if (p->outfd < 0)
6596 error ("Output file descriptor of %s closed", SDATA (p->name));
6597 Fcheck_coding_system (decoding);
6598 Fcheck_coding_system (encoding);
6599 encoding = coding_inherit_eol_type (encoding, Qnil);
6600 pset_decode_coding_system (p, decoding);
6601 pset_encode_coding_system (p, encoding);
6602 setup_process_coding_systems (process);
6604 return Qnil;
6607 DEFUN ("process-coding-system",
6608 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6609 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6610 (register Lisp_Object process)
6612 CHECK_PROCESS (process);
6613 return Fcons (XPROCESS (process)->decode_coding_system,
6614 XPROCESS (process)->encode_coding_system);
6617 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6618 Sset_process_filter_multibyte, 2, 2, 0,
6619 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6620 If FLAG is non-nil, the filter is given multibyte strings.
6621 If FLAG is nil, the filter is given unibyte strings. In this case,
6622 all character code conversion except for end-of-line conversion is
6623 suppressed. */)
6624 (Lisp_Object process, Lisp_Object flag)
6626 register struct Lisp_Process *p;
6628 CHECK_PROCESS (process);
6629 p = XPROCESS (process);
6630 if (NILP (flag))
6631 pset_decode_coding_system
6632 (p, raw_text_coding_system (p->decode_coding_system));
6633 setup_process_coding_systems (process);
6635 return Qnil;
6638 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6639 Sprocess_filter_multibyte_p, 1, 1, 0,
6640 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6641 (Lisp_Object process)
6643 register struct Lisp_Process *p;
6644 struct coding_system *coding;
6646 CHECK_PROCESS (process);
6647 p = XPROCESS (process);
6648 coding = proc_decode_coding_system[p->infd];
6649 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6655 # ifdef HAVE_GPM
6657 void
6658 add_gpm_wait_descriptor (int desc)
6660 add_keyboard_wait_descriptor (desc);
6663 void
6664 delete_gpm_wait_descriptor (int desc)
6666 delete_keyboard_wait_descriptor (desc);
6669 # endif
6671 # ifdef USABLE_SIGIO
6673 /* Return true if *MASK has a bit set
6674 that corresponds to one of the keyboard input descriptors. */
6676 static bool
6677 keyboard_bit_set (fd_set *mask)
6679 int fd;
6681 for (fd = 0; fd <= max_desc; fd++)
6682 if (FD_ISSET (fd, mask)
6683 && ((fd_callback_info[fd].flags & KEYBOARD_FD) != 0))
6684 return 1;
6686 return 0;
6688 # endif
6690 #else /* not subprocesses */
6692 /* Defined on msdos.c. */
6693 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6694 EMACS_TIME *, void *);
6696 /* Implementation of wait_reading_process_output, assuming that there
6697 are no subprocesses. Used only by the MS-DOS build.
6699 Wait for timeout to elapse and/or keyboard input to be available.
6701 TIME_LIMIT is:
6702 timeout in seconds
6703 If negative, gobble data immediately available but don't wait for any.
6705 NSECS is:
6706 an additional duration to wait, measured in nanoseconds
6707 If TIME_LIMIT is zero, then:
6708 If NSECS == 0, there is no limit.
6709 If NSECS > 0, the timeout consists of NSECS only.
6710 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6712 READ_KBD is:
6713 0 to ignore keyboard input, or
6714 1 to return when input is available, or
6715 -1 means caller will actually read the input, so don't throw to
6716 the quit handler.
6718 see full version for other parameters. We know that wait_proc will
6719 always be NULL, since `subprocesses' isn't defined.
6721 DO_DISPLAY means redisplay should be done to show subprocess
6722 output that arrives.
6724 Return true if we received input from any process. */
6726 bool
6727 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6728 bool do_display,
6729 Lisp_Object wait_for_cell,
6730 struct Lisp_Process *wait_proc, int just_wait_proc)
6732 register int nfds;
6733 EMACS_TIME end_time, timeout;
6735 if (time_limit < 0)
6737 time_limit = 0;
6738 nsecs = -1;
6740 else if (TYPE_MAXIMUM (time_t) < time_limit)
6741 time_limit = TYPE_MAXIMUM (time_t);
6743 /* What does time_limit really mean? */
6744 if (time_limit || nsecs > 0)
6746 timeout = make_emacs_time (time_limit, nsecs);
6747 end_time = add_emacs_time (current_emacs_time (), timeout);
6750 /* Turn off periodic alarms (in case they are in use)
6751 and then turn off any other atimers,
6752 because the select emulator uses alarms. */
6753 stop_polling ();
6754 turn_on_atimers (0);
6756 while (1)
6758 bool timeout_reduced_for_timers = 0;
6759 SELECT_TYPE waitchannels;
6760 int xerrno;
6762 /* If calling from keyboard input, do not quit
6763 since we want to return C-g as an input character.
6764 Otherwise, do pending quit if requested. */
6765 if (read_kbd >= 0)
6766 QUIT;
6768 /* Exit now if the cell we're waiting for became non-nil. */
6769 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6770 break;
6772 /* Compute time from now till when time limit is up. */
6773 /* Exit if already run out. */
6774 if (nsecs < 0)
6776 /* A negative timeout means
6777 gobble output available now
6778 but don't wait at all. */
6780 timeout = make_emacs_time (0, 0);
6782 else if (time_limit || nsecs > 0)
6784 EMACS_TIME now = current_emacs_time ();
6785 if (EMACS_TIME_LE (end_time, now))
6786 break;
6787 timeout = sub_emacs_time (end_time, now);
6789 else
6791 timeout = make_emacs_time (100000, 0);
6794 /* If our caller will not immediately handle keyboard events,
6795 run timer events directly.
6796 (Callers that will immediately read keyboard events
6797 call timer_delay on their own.) */
6798 if (NILP (wait_for_cell))
6800 EMACS_TIME timer_delay;
6804 unsigned old_timers_run = timers_run;
6805 timer_delay = timer_check ();
6806 if (timers_run != old_timers_run && do_display)
6807 /* We must retry, since a timer may have requeued itself
6808 and that could alter the time delay. */
6809 redisplay_preserve_echo_area (14);
6810 else
6811 break;
6813 while (!detect_input_pending ());
6815 /* If there is unread keyboard input, also return. */
6816 if (read_kbd != 0
6817 && requeued_events_pending_p ())
6818 break;
6820 if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
6822 if (EMACS_TIME_LT (timer_delay, timeout))
6824 timeout = timer_delay;
6825 timeout_reduced_for_timers = 1;
6830 /* Cause C-g and alarm signals to take immediate action,
6831 and cause input available signals to zero out timeout. */
6832 if (read_kbd < 0)
6833 set_waiting_for_input (&timeout);
6835 /* If a frame has been newly mapped and needs updating,
6836 reprocess its display stuff. */
6837 if (frame_garbaged && do_display)
6839 clear_waiting_for_input ();
6840 redisplay_preserve_echo_area (15);
6841 if (read_kbd < 0)
6842 set_waiting_for_input (&timeout);
6845 /* Wait till there is something to do. */
6846 FD_ZERO (&waitchannels);
6847 if (read_kbd && detect_input_pending ())
6848 nfds = 0;
6849 else
6851 if (read_kbd || !NILP (wait_for_cell))
6852 FD_SET (0, &waitchannels);
6853 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6856 xerrno = errno;
6858 /* Make C-g and alarm signals set flags again */
6859 clear_waiting_for_input ();
6861 /* If we woke up due to SIGWINCH, actually change size now. */
6862 do_pending_window_change (0);
6864 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6865 /* We waited the full specified time, so return now. */
6866 break;
6868 if (nfds == -1)
6870 /* If the system call was interrupted, then go around the
6871 loop again. */
6872 if (xerrno == EINTR)
6873 FD_ZERO (&waitchannels);
6874 else
6875 report_file_errno ("Failed select", Qnil, xerrno);
6878 /* Check for keyboard input */
6880 if (read_kbd
6881 && detect_input_pending_run_timers (do_display))
6883 swallow_events (do_display);
6884 if (detect_input_pending_run_timers (do_display))
6885 break;
6888 /* If there is unread keyboard input, also return. */
6889 if (read_kbd
6890 && requeued_events_pending_p ())
6891 break;
6893 /* If wait_for_cell. check for keyboard input
6894 but don't run any timers.
6895 ??? (It seems wrong to me to check for keyboard
6896 input at all when wait_for_cell, but the code
6897 has been this way since July 1994.
6898 Try changing this after version 19.31.) */
6899 if (! NILP (wait_for_cell)
6900 && detect_input_pending ())
6902 swallow_events (do_display);
6903 if (detect_input_pending ())
6904 break;
6907 /* Exit now if the cell we're waiting for became non-nil. */
6908 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6909 break;
6912 start_polling ();
6914 return 0;
6917 #endif /* not subprocesses */
6919 /* The following functions are needed even if async subprocesses are
6920 not supported. Some of them are no-op stubs in that case. */
6922 /* Add DESC to the set of keyboard input descriptors. */
6924 void
6925 add_keyboard_wait_descriptor (int desc)
6927 #ifdef subprocesses /* actually means "not MSDOS" */
6928 eassert (desc >= 0 && desc < MAXDESC);
6929 fd_callback_info[desc].flags |= FOR_READ | KEYBOARD_FD;
6930 if (desc > max_desc)
6931 max_desc = desc;
6932 #endif
6935 /* From now on, do not expect DESC to give keyboard input. */
6937 void
6938 delete_keyboard_wait_descriptor (int desc)
6940 #ifdef subprocesses
6941 int fd;
6942 int lim = max_desc;
6944 eassert (desc >= 0 && desc < MAXDESC);
6945 eassert (desc <= max_desc);
6947 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
6949 if (desc == max_desc)
6950 recompute_max_desc ();
6951 #endif
6954 /* Setup coding systems of PROCESS. */
6956 void
6957 setup_process_coding_systems (Lisp_Object process)
6959 #ifdef subprocesses
6960 struct Lisp_Process *p = XPROCESS (process);
6961 int inch = p->infd;
6962 int outch = p->outfd;
6963 Lisp_Object coding_system;
6965 if (inch < 0 || outch < 0)
6966 return;
6968 if (!proc_decode_coding_system[inch])
6969 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6970 coding_system = p->decode_coding_system;
6971 if (EQ (p->filter, Qinternal_default_process_filter)
6972 && BUFFERP (p->buffer))
6974 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6975 coding_system = raw_text_coding_system (coding_system);
6977 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6979 if (!proc_encode_coding_system[outch])
6980 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6981 setup_coding_system (p->encode_coding_system,
6982 proc_encode_coding_system[outch]);
6983 #endif
6986 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6987 doc: /* Return the (or a) process associated with BUFFER.
6988 BUFFER may be a buffer or the name of one. */)
6989 (register Lisp_Object buffer)
6991 #ifdef subprocesses
6992 register Lisp_Object buf, tail, proc;
6994 if (NILP (buffer)) return Qnil;
6995 buf = Fget_buffer (buffer);
6996 if (NILP (buf)) return Qnil;
6998 FOR_EACH_PROCESS (tail, proc)
6999 if (EQ (XPROCESS (proc)->buffer, buf))
7000 return proc;
7001 #endif /* subprocesses */
7002 return Qnil;
7005 DEFUN ("process-inherit-coding-system-flag",
7006 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7007 1, 1, 0,
7008 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7009 If this flag is t, `buffer-file-coding-system' of the buffer
7010 associated with PROCESS will inherit the coding system used to decode
7011 the process output. */)
7012 (register Lisp_Object process)
7014 #ifdef subprocesses
7015 CHECK_PROCESS (process);
7016 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7017 #else
7018 /* Ignore the argument and return the value of
7019 inherit-process-coding-system. */
7020 return inherit_process_coding_system ? Qt : Qnil;
7021 #endif
7024 /* Kill all processes associated with `buffer'.
7025 If `buffer' is nil, kill all processes */
7027 void
7028 kill_buffer_processes (Lisp_Object buffer)
7030 #ifdef subprocesses
7031 Lisp_Object tail, proc;
7033 FOR_EACH_PROCESS (tail, proc)
7034 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7036 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7037 Fdelete_process (proc);
7038 else if (XPROCESS (proc)->infd >= 0)
7039 process_send_signal (proc, SIGHUP, Qnil, 1);
7041 #else /* subprocesses */
7042 /* Since we have no subprocesses, this does nothing. */
7043 #endif /* subprocesses */
7046 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7047 Swaiting_for_user_input_p, 0, 0, 0,
7048 doc: /* Return non-nil if Emacs is waiting for input from the user.
7049 This is intended for use by asynchronous process output filters and sentinels. */)
7050 (void)
7052 #ifdef subprocesses
7053 return (waiting_for_user_input_p ? Qt : Qnil);
7054 #else
7055 return Qnil;
7056 #endif
7059 /* Stop reading input from keyboard sources. */
7061 void
7062 hold_keyboard_input (void)
7064 kbd_is_on_hold = 1;
7067 /* Resume reading input from keyboard sources. */
7069 void
7070 unhold_keyboard_input (void)
7072 kbd_is_on_hold = 0;
7075 /* Return true if keyboard input is on hold, zero otherwise. */
7077 bool
7078 kbd_on_hold_p (void)
7080 return kbd_is_on_hold;
7084 /* Enumeration of and access to system processes a-la ps(1). */
7086 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7087 0, 0, 0,
7088 doc: /* Return a list of numerical process IDs of all running processes.
7089 If this functionality is unsupported, return nil.
7091 See `process-attributes' for getting attributes of a process given its ID. */)
7092 (void)
7094 return list_system_processes ();
7097 DEFUN ("process-attributes", Fprocess_attributes,
7098 Sprocess_attributes, 1, 1, 0,
7099 doc: /* Return attributes of the process given by its PID, a number.
7101 Value is an alist where each element is a cons cell of the form
7103 \(KEY . VALUE)
7105 If this functionality is unsupported, the value is nil.
7107 See `list-system-processes' for getting a list of all process IDs.
7109 The KEYs of the attributes that this function may return are listed
7110 below, together with the type of the associated VALUE (in parentheses).
7111 Not all platforms support all of these attributes; unsupported
7112 attributes will not appear in the returned alist.
7113 Unless explicitly indicated otherwise, numbers can have either
7114 integer or floating point values.
7116 euid -- Effective user User ID of the process (number)
7117 user -- User name corresponding to euid (string)
7118 egid -- Effective user Group ID of the process (number)
7119 group -- Group name corresponding to egid (string)
7120 comm -- Command name (executable name only) (string)
7121 state -- Process state code, such as "S", "R", or "T" (string)
7122 ppid -- Parent process ID (number)
7123 pgrp -- Process group ID (number)
7124 sess -- Session ID, i.e. process ID of session leader (number)
7125 ttname -- Controlling tty name (string)
7126 tpgid -- ID of foreground process group on the process's tty (number)
7127 minflt -- number of minor page faults (number)
7128 majflt -- number of major page faults (number)
7129 cminflt -- cumulative number of minor page faults (number)
7130 cmajflt -- cumulative number of major page faults (number)
7131 utime -- user time used by the process, in (current-time) format,
7132 which is a list of integers (HIGH LOW USEC PSEC)
7133 stime -- system time used by the process (current-time)
7134 time -- sum of utime and stime (current-time)
7135 cutime -- user time used by the process and its children (current-time)
7136 cstime -- system time used by the process and its children (current-time)
7137 ctime -- sum of cutime and cstime (current-time)
7138 pri -- priority of the process (number)
7139 nice -- nice value of the process (number)
7140 thcount -- process thread count (number)
7141 start -- time the process started (current-time)
7142 vsize -- virtual memory size of the process in KB's (number)
7143 rss -- resident set size of the process in KB's (number)
7144 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7145 pcpu -- percents of CPU time used by the process (floating-point number)
7146 pmem -- percents of total physical memory used by process's resident set
7147 (floating-point number)
7148 args -- command line which invoked the process (string). */)
7149 ( Lisp_Object pid)
7151 return system_process_attributes (pid);
7154 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7155 Invoke this after init_process_emacs, and after glib and/or GNUstep
7156 futz with the SIGCHLD handler, but before Emacs forks any children.
7157 This function's caller should block SIGCHLD. */
7159 #ifndef NS_IMPL_GNUSTEP
7160 static
7161 #endif
7162 void
7163 catch_child_signal (void)
7165 struct sigaction action, old_action;
7166 emacs_sigaction_init (&action, deliver_child_signal);
7167 block_child_signal ();
7168 sigaction (SIGCHLD, &action, &old_action);
7169 eassert (! (old_action.sa_flags & SA_SIGINFO));
7171 if (old_action.sa_handler != deliver_child_signal)
7172 lib_child_handler
7173 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7174 ? dummy_handler
7175 : old_action.sa_handler);
7176 unblock_child_signal ();
7180 /* This is not called "init_process" because that is the name of a
7181 Mach system call, so it would cause problems on Darwin systems. */
7182 void
7183 init_process_emacs (void)
7185 #ifdef subprocesses
7186 register int i;
7188 inhibit_sentinels = 0;
7190 #ifndef CANNOT_DUMP
7191 if (! noninteractive || initialized)
7192 #endif
7194 #if defined HAVE_GLIB && !defined WINDOWSNT
7195 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7196 this should always fail, but is enough to initialize glib's
7197 private SIGCHLD handler, allowing catch_child_signal to copy
7198 it into lib_child_handler. */
7199 g_source_unref (g_child_watch_source_new (getpid ()));
7200 #endif
7201 catch_child_signal ();
7204 max_desc = -1;
7205 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7207 #ifdef NON_BLOCKING_CONNECT
7208 num_pending_connects = 0;
7209 #endif
7211 #ifdef ADAPTIVE_READ_BUFFERING
7212 process_output_delay_count = 0;
7213 process_output_skip = 0;
7214 #endif
7216 /* Don't do this, it caused infinite select loops. The display
7217 method should call add_keyboard_wait_descriptor on stdin if it
7218 needs that. */
7219 #if 0
7220 FD_SET (0, &input_wait_mask);
7221 #endif
7223 Vprocess_alist = Qnil;
7224 deleted_pid_list = Qnil;
7225 for (i = 0; i < MAXDESC; i++)
7227 chan_process[i] = Qnil;
7228 proc_buffered_char[i] = -1;
7230 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7231 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7232 #ifdef DATAGRAM_SOCKETS
7233 memset (datagram_address, 0, sizeof datagram_address);
7234 #endif
7237 Lisp_Object subfeatures = Qnil;
7238 const struct socket_options *sopt;
7240 #define ADD_SUBFEATURE(key, val) \
7241 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7243 #ifdef NON_BLOCKING_CONNECT
7244 ADD_SUBFEATURE (QCnowait, Qt);
7245 #endif
7246 #ifdef DATAGRAM_SOCKETS
7247 ADD_SUBFEATURE (QCtype, Qdatagram);
7248 #endif
7249 #ifdef HAVE_SEQPACKET
7250 ADD_SUBFEATURE (QCtype, Qseqpacket);
7251 #endif
7252 #ifdef HAVE_LOCAL_SOCKETS
7253 ADD_SUBFEATURE (QCfamily, Qlocal);
7254 #endif
7255 ADD_SUBFEATURE (QCfamily, Qipv4);
7256 #ifdef AF_INET6
7257 ADD_SUBFEATURE (QCfamily, Qipv6);
7258 #endif
7259 #ifdef HAVE_GETSOCKNAME
7260 ADD_SUBFEATURE (QCservice, Qt);
7261 #endif
7262 ADD_SUBFEATURE (QCserver, Qt);
7264 for (sopt = socket_options; sopt->name; sopt++)
7265 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7267 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7270 #if defined (DARWIN_OS)
7271 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7272 processes. As such, we only change the default value. */
7273 if (initialized)
7275 char const *release = (STRINGP (Voperating_system_release)
7276 ? SSDATA (Voperating_system_release)
7277 : 0);
7278 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7279 Vprocess_connection_type = Qnil;
7282 #endif
7283 #endif /* subprocesses */
7284 kbd_is_on_hold = 0;
7287 void
7288 syms_of_process (void)
7290 #ifdef subprocesses
7292 DEFSYM (Qprocessp, "processp");
7293 DEFSYM (Qrun, "run");
7294 DEFSYM (Qstop, "stop");
7295 DEFSYM (Qsignal, "signal");
7297 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7298 here again.
7300 Qexit = intern_c_string ("exit");
7301 staticpro (&Qexit); */
7303 DEFSYM (Qopen, "open");
7304 DEFSYM (Qclosed, "closed");
7305 DEFSYM (Qconnect, "connect");
7306 DEFSYM (Qfailed, "failed");
7307 DEFSYM (Qlisten, "listen");
7308 DEFSYM (Qlocal, "local");
7309 DEFSYM (Qipv4, "ipv4");
7310 #ifdef AF_INET6
7311 DEFSYM (Qipv6, "ipv6");
7312 #endif
7313 DEFSYM (Qdatagram, "datagram");
7314 DEFSYM (Qseqpacket, "seqpacket");
7316 DEFSYM (QCport, ":port");
7317 DEFSYM (QCspeed, ":speed");
7318 DEFSYM (QCprocess, ":process");
7320 DEFSYM (QCbytesize, ":bytesize");
7321 DEFSYM (QCstopbits, ":stopbits");
7322 DEFSYM (QCparity, ":parity");
7323 DEFSYM (Qodd, "odd");
7324 DEFSYM (Qeven, "even");
7325 DEFSYM (QCflowcontrol, ":flowcontrol");
7326 DEFSYM (Qhw, "hw");
7327 DEFSYM (Qsw, "sw");
7328 DEFSYM (QCsummary, ":summary");
7330 DEFSYM (Qreal, "real");
7331 DEFSYM (Qnetwork, "network");
7332 DEFSYM (Qserial, "serial");
7333 DEFSYM (QCbuffer, ":buffer");
7334 DEFSYM (QChost, ":host");
7335 DEFSYM (QCservice, ":service");
7336 DEFSYM (QClocal, ":local");
7337 DEFSYM (QCremote, ":remote");
7338 DEFSYM (QCcoding, ":coding");
7339 DEFSYM (QCserver, ":server");
7340 DEFSYM (QCnowait, ":nowait");
7341 DEFSYM (QCsentinel, ":sentinel");
7342 DEFSYM (QClog, ":log");
7343 DEFSYM (QCnoquery, ":noquery");
7344 DEFSYM (QCstop, ":stop");
7345 DEFSYM (QCoptions, ":options");
7346 DEFSYM (QCplist, ":plist");
7348 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7350 staticpro (&Vprocess_alist);
7351 staticpro (&deleted_pid_list);
7353 #endif /* subprocesses */
7355 DEFSYM (QCname, ":name");
7356 DEFSYM (QCtype, ":type");
7358 DEFSYM (Qeuid, "euid");
7359 DEFSYM (Qegid, "egid");
7360 DEFSYM (Quser, "user");
7361 DEFSYM (Qgroup, "group");
7362 DEFSYM (Qcomm, "comm");
7363 DEFSYM (Qstate, "state");
7364 DEFSYM (Qppid, "ppid");
7365 DEFSYM (Qpgrp, "pgrp");
7366 DEFSYM (Qsess, "sess");
7367 DEFSYM (Qttname, "ttname");
7368 DEFSYM (Qtpgid, "tpgid");
7369 DEFSYM (Qminflt, "minflt");
7370 DEFSYM (Qmajflt, "majflt");
7371 DEFSYM (Qcminflt, "cminflt");
7372 DEFSYM (Qcmajflt, "cmajflt");
7373 DEFSYM (Qutime, "utime");
7374 DEFSYM (Qstime, "stime");
7375 DEFSYM (Qtime, "time");
7376 DEFSYM (Qcutime, "cutime");
7377 DEFSYM (Qcstime, "cstime");
7378 DEFSYM (Qctime, "ctime");
7379 DEFSYM (Qinternal_default_process_sentinel,
7380 "internal-default-process-sentinel");
7381 DEFSYM (Qinternal_default_process_filter,
7382 "internal-default-process-filter");
7383 DEFSYM (Qpri, "pri");
7384 DEFSYM (Qnice, "nice");
7385 DEFSYM (Qthcount, "thcount");
7386 DEFSYM (Qstart, "start");
7387 DEFSYM (Qvsize, "vsize");
7388 DEFSYM (Qrss, "rss");
7389 DEFSYM (Qetime, "etime");
7390 DEFSYM (Qpcpu, "pcpu");
7391 DEFSYM (Qpmem, "pmem");
7392 DEFSYM (Qargs, "args");
7394 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7395 doc: /* Non-nil means delete processes immediately when they exit.
7396 A value of nil means don't delete them until `list-processes' is run. */);
7398 delete_exited_processes = 1;
7400 #ifdef subprocesses
7401 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7402 doc: /* Control type of device used to communicate with subprocesses.
7403 Values are nil to use a pipe, or t or `pty' to use a pty.
7404 The value has no effect if the system has no ptys or if all ptys are busy:
7405 then a pipe is used in any case.
7406 The value takes effect when `start-process' is called. */);
7407 Vprocess_connection_type = Qt;
7409 #ifdef ADAPTIVE_READ_BUFFERING
7410 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7411 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7412 On some systems, when Emacs reads the output from a subprocess, the output data
7413 is read in very small blocks, potentially resulting in very poor performance.
7414 This behavior can be remedied to some extent by setting this variable to a
7415 non-nil value, as it will automatically delay reading from such processes, to
7416 allow them to produce more output before Emacs tries to read it.
7417 If the value is t, the delay is reset after each write to the process; any other
7418 non-nil value means that the delay is not reset on write.
7419 The variable takes effect when `start-process' is called. */);
7420 Vprocess_adaptive_read_buffering = Qt;
7421 #endif
7423 defsubr (&Sprocessp);
7424 defsubr (&Sget_process);
7425 defsubr (&Sdelete_process);
7426 defsubr (&Sprocess_status);
7427 defsubr (&Sprocess_exit_status);
7428 defsubr (&Sprocess_id);
7429 defsubr (&Sprocess_name);
7430 defsubr (&Sprocess_tty_name);
7431 defsubr (&Sprocess_command);
7432 defsubr (&Sset_process_buffer);
7433 defsubr (&Sprocess_buffer);
7434 defsubr (&Sprocess_mark);
7435 defsubr (&Sset_process_filter);
7436 defsubr (&Sprocess_filter);
7437 defsubr (&Sset_process_sentinel);
7438 defsubr (&Sprocess_sentinel);
7439 defsubr (&Sset_process_thread);
7440 defsubr (&Sprocess_thread);
7441 defsubr (&Sset_process_window_size);
7442 defsubr (&Sset_process_inherit_coding_system_flag);
7443 defsubr (&Sset_process_query_on_exit_flag);
7444 defsubr (&Sprocess_query_on_exit_flag);
7445 defsubr (&Sprocess_contact);
7446 defsubr (&Sprocess_plist);
7447 defsubr (&Sset_process_plist);
7448 defsubr (&Sprocess_list);
7449 defsubr (&Sstart_process);
7450 defsubr (&Sserial_process_configure);
7451 defsubr (&Smake_serial_process);
7452 defsubr (&Sset_network_process_option);
7453 defsubr (&Smake_network_process);
7454 defsubr (&Sformat_network_address);
7455 #if defined (HAVE_NET_IF_H)
7456 #ifdef SIOCGIFCONF
7457 defsubr (&Snetwork_interface_list);
7458 #endif
7459 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7460 defsubr (&Snetwork_interface_info);
7461 #endif
7462 #endif /* defined (HAVE_NET_IF_H) */
7463 #ifdef DATAGRAM_SOCKETS
7464 defsubr (&Sprocess_datagram_address);
7465 defsubr (&Sset_process_datagram_address);
7466 #endif
7467 defsubr (&Saccept_process_output);
7468 defsubr (&Sprocess_send_region);
7469 defsubr (&Sprocess_send_string);
7470 defsubr (&Sinterrupt_process);
7471 defsubr (&Skill_process);
7472 defsubr (&Squit_process);
7473 defsubr (&Sstop_process);
7474 defsubr (&Scontinue_process);
7475 defsubr (&Sprocess_running_child_p);
7476 defsubr (&Sprocess_send_eof);
7477 defsubr (&Ssignal_process);
7478 defsubr (&Swaiting_for_user_input_p);
7479 defsubr (&Sprocess_type);
7480 defsubr (&Sinternal_default_process_sentinel);
7481 defsubr (&Sinternal_default_process_filter);
7482 defsubr (&Sset_process_coding_system);
7483 defsubr (&Sprocess_coding_system);
7484 defsubr (&Sset_process_filter_multibyte);
7485 defsubr (&Sprocess_filter_multibyte_p);
7487 #endif /* subprocesses */
7489 defsubr (&Sget_buffer_process);
7490 defsubr (&Sprocess_inherit_coding_system_flag);
7491 defsubr (&Slist_system_processes);
7492 defsubr (&Sprocess_attributes);