1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
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 (at
11 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/>. */
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
35 /* Only MS-DOS does not define `subprocesses'. */
38 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
44 # include <sys/resource.h>
47 /* Are local (unix) sockets supported? */
48 #if defined (HAVE_SYS_UN_H)
49 #if !defined (AF_LOCAL) && defined (AF_UNIX)
50 #define AF_LOCAL AF_UNIX
53 #define HAVE_LOCAL_SOCKETS
58 #include <sys/ioctl.h>
59 #if defined (HAVE_NET_IF_H)
61 #endif /* HAVE_NET_IF_H */
63 #if defined (HAVE_IFADDRS_H)
64 /* Must be after net/if.h */
67 /* We only use structs from this header when we use getifaddrs. */
68 #if defined (HAVE_NET_IF_DL_H)
69 #include <net/if_dl.h>
79 # include <sys/stream.h>
80 # include <sys/stropts.h>
92 #include <flexmember.h>
96 #endif /* subprocesses */
102 #include "character.h"
107 #include "termopts.h"
108 #include "keyboard.h"
109 #include "blockinput.h"
111 #include "sysselect.h"
112 #include "syssignal.h"
118 #ifdef HAVE_WINDOW_SYSTEM
120 #endif /* HAVE_WINDOW_SYSTEM */
123 #include "xgselect.h"
129 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
130 /* This is 0.1s in nanoseconds. */
131 #define ASYNC_RETRY_NSEC 100000000
135 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
136 struct timespec
*, void *);
139 /* Work around GCC 4.3.0 bug with strict overflow checking; see
140 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
141 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
142 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
143 # pragma GCC diagnostic ignored "-Wstrict-overflow"
146 /* True if keyboard input is on hold, zero otherwise. */
148 static bool kbd_is_on_hold
;
150 /* Nonzero means don't run process sentinels. This is used
152 bool inhibit_sentinels
;
157 # define SOCK_CLOEXEC 0
159 #ifndef SOCK_NONBLOCK
160 # define SOCK_NONBLOCK 0
163 /* True if ERRNUM represents an error where the system call would
164 block if a blocking variant were used. */
166 would_block (int errnum
)
169 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
172 return errnum
== EAGAIN
;
177 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
180 close_on_exec (int fd
)
183 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
188 # define accept4(sockfd, addr, addrlen, flags) \
189 process_accept4 (sockfd, addr, addrlen, flags)
191 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
193 return close_on_exec (accept (sockfd
, addr
, addrlen
));
197 process_socket (int domain
, int type
, int protocol
)
199 return close_on_exec (socket (domain
, type
, protocol
));
202 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
205 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
206 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
207 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
208 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
209 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
210 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
212 /* Number of events of change of status of a process. */
213 static EMACS_INT process_tick
;
214 /* Number of events for which the user or sentinel has been notified. */
215 static EMACS_INT update_tick
;
217 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
222 #ifndef BROKEN_DATAGRAM_SOCKETS
223 # if defined HAVE_SELECT || defined USABLE_FIONREAD
224 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
225 # define DATAGRAM_SOCKETS
230 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
231 # define HAVE_SEQPACKET
234 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
235 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
236 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
238 /* Number of processes which have a non-zero read_output_delay,
239 and therefore might be delayed for adaptive read buffering. */
241 static int process_output_delay_count
;
243 /* True if any process has non-nil read_output_skip. */
245 static bool process_output_skip
;
247 static void start_process_unwind (Lisp_Object
);
248 static void create_process (Lisp_Object
, char **, Lisp_Object
);
250 static bool keyboard_bit_set (fd_set
*);
252 static void deactivate_process (Lisp_Object
);
253 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
254 static int read_process_output (Lisp_Object
, int);
255 static void create_pty (Lisp_Object
);
256 static void exec_sentinel (Lisp_Object
, Lisp_Object
);
258 /* Mask of bits indicating the descriptors that we wait for input on. */
260 static fd_set input_wait_mask
;
262 /* Mask that excludes keyboard input descriptor(s). */
264 static fd_set non_keyboard_wait_mask
;
266 /* Mask that excludes process input descriptor(s). */
268 static fd_set non_process_wait_mask
;
270 /* Mask for selecting for write. */
272 static fd_set write_mask
;
274 /* Mask of bits indicating the descriptors that we wait for connect to
275 complete on. Once they complete, they are removed from this mask
276 and added to the input_wait_mask and non_keyboard_wait_mask. */
278 static fd_set connect_wait_mask
;
280 /* Number of bits set in connect_wait_mask. */
281 static int num_pending_connects
;
283 /* The largest descriptor currently in use for a process object; -1 if none. */
284 static int max_process_desc
;
286 /* The largest descriptor currently in use for input; -1 if none. */
287 static int max_input_desc
;
289 /* Set the external socket descriptor for Emacs to use when
290 `make-network-process' is called with a non-nil
291 `:use-external-socket' option. The value should be either -1, or
292 the file descriptor of a socket that is already bound. */
293 static int external_sock_fd
;
295 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
296 static Lisp_Object chan_process
[FD_SETSIZE
];
297 static void wait_for_socket_fds (Lisp_Object
, char const *);
299 /* Alist of elements (NAME . PROCESS). */
300 static Lisp_Object Vprocess_alist
;
302 /* Buffered-ahead input char from process, indexed by channel.
303 -1 means empty (no char is buffered).
304 Used on sys V where the only way to tell if there is any
305 output from the process is to read at least one char.
306 Always -1 on systems that support FIONREAD. */
308 static int proc_buffered_char
[FD_SETSIZE
];
310 /* Table of `struct coding-system' for each process. */
311 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
312 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
314 #ifdef DATAGRAM_SOCKETS
315 /* Table of `partner address' for datagram sockets. */
316 static struct sockaddr_and_len
{
319 } datagram_address
[FD_SETSIZE
];
320 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
321 #define DATAGRAM_CONN_P(proc) \
322 (PROCESSP (proc) && \
323 XPROCESS (proc)->infd >= 0 && \
324 datagram_address[XPROCESS (proc)->infd].sa != 0)
326 #define DATAGRAM_CONN_P(proc) (0)
329 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
330 a `for' loop which iterates over processes from Vprocess_alist. */
332 #define FOR_EACH_PROCESS(list_var, proc_var) \
333 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
335 /* These setters are used only in this file, so they can be private. */
337 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
342 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
347 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
349 p
->decode_coding_system
= val
;
352 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
354 p
->decoding_buf
= val
;
357 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
359 p
->encode_coding_system
= val
;
362 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
364 p
->encoding_buf
= val
;
367 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
369 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
372 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
377 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
382 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
387 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
392 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
394 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
397 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
402 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
407 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
409 p
->write_queue
= val
;
412 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
419 make_lisp_proc (struct Lisp_Process
*p
)
421 return make_lisp_ptr (p
, Lisp_Vectorlike
);
424 static struct fd_callback_data
430 int condition
; /* Mask of the defines above. */
431 } fd_callback_info
[FD_SETSIZE
];
434 /* Add a file descriptor FD to be monitored for when read is possible.
435 When read is possible, call FUNC with argument DATA. */
438 add_read_fd (int fd
, fd_callback func
, void *data
)
440 add_keyboard_wait_descriptor (fd
);
442 fd_callback_info
[fd
].func
= func
;
443 fd_callback_info
[fd
].data
= data
;
444 fd_callback_info
[fd
].condition
|= FOR_READ
;
447 /* Stop monitoring file descriptor FD for when read is possible. */
450 delete_read_fd (int fd
)
452 delete_keyboard_wait_descriptor (fd
);
454 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
455 if (fd_callback_info
[fd
].condition
== 0)
457 fd_callback_info
[fd
].func
= 0;
458 fd_callback_info
[fd
].data
= 0;
462 /* Add a file descriptor FD to be monitored for when write is possible.
463 When write is possible, call FUNC with argument DATA. */
466 add_write_fd (int fd
, fd_callback func
, void *data
)
468 FD_SET (fd
, &write_mask
);
469 if (fd
> max_input_desc
)
472 fd_callback_info
[fd
].func
= func
;
473 fd_callback_info
[fd
].data
= data
;
474 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
477 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
480 delete_input_desc (int fd
)
482 if (fd
== max_input_desc
)
486 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
487 || FD_ISSET (fd
, &write_mask
)));
493 /* Stop monitoring file descriptor FD for when write is possible. */
496 delete_write_fd (int fd
)
498 FD_CLR (fd
, &write_mask
);
499 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
500 if (fd_callback_info
[fd
].condition
== 0)
502 fd_callback_info
[fd
].func
= 0;
503 fd_callback_info
[fd
].data
= 0;
504 delete_input_desc (fd
);
509 /* Compute the Lisp form of the process status, p->status, from
510 the numeric status that was returned by `wait'. */
512 static Lisp_Object
status_convert (int);
515 update_status (struct Lisp_Process
*p
)
517 eassert (p
->raw_status_new
);
518 pset_status (p
, status_convert (p
->raw_status
));
519 p
->raw_status_new
= 0;
522 /* Convert a process status word in Unix format to
523 the list that we use internally. */
526 status_convert (int w
)
529 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
530 else if (WIFEXITED (w
))
531 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
532 WCOREDUMP (w
) ? Qt
: Qnil
));
533 else if (WIFSIGNALED (w
))
534 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
535 WCOREDUMP (w
) ? Qt
: Qnil
));
540 /* True if STATUS is that of a process attempting connection. */
543 connecting_status (Lisp_Object status
)
545 return CONSP (status
) && EQ (XCAR (status
), Qconnect
);
548 /* Given a status-list, extract the three pieces of information
549 and store them individually through the three pointers. */
552 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, Lisp_Object
*code
,
557 if (connecting_status (l
))
563 *code
= make_number (0);
572 *coredump
= !NILP (tem
);
576 /* Return a string describing a process status list. */
579 status_message (struct Lisp_Process
*p
)
581 Lisp_Object status
= p
->status
;
582 Lisp_Object symbol
, code
;
586 decode_status (status
, &symbol
, &code
, &coredump
);
588 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
591 synchronize_system_messages_locale ();
592 signame
= strsignal (XFASTINT (code
));
594 string
= build_string ("unknown");
599 string
= build_unibyte_string (signame
);
600 if (! NILP (Vlocale_coding_system
))
601 string
= (code_convert_string_norecord
602 (string
, Vlocale_coding_system
, 0));
603 c1
= STRING_CHAR (SDATA (string
));
606 Faset (string
, make_number (0), make_number (c2
));
608 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
609 return concat2 (string
, suffix
);
611 else if (EQ (symbol
, Qexit
))
614 return build_string (XFASTINT (code
) == 0
616 : "connection broken by remote peer\n");
617 if (XFASTINT (code
) == 0)
618 return build_string ("finished\n");
619 AUTO_STRING (prefix
, "exited abnormally with code ");
620 string
= Fnumber_to_string (code
);
621 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
622 return concat3 (prefix
, string
, suffix
);
624 else if (EQ (symbol
, Qfailed
))
626 AUTO_STRING (format
, "failed with code %s\n");
627 return CALLN (Fformat
, format
, code
);
630 return Fcopy_sequence (Fsymbol_name (symbol
));
633 enum { PTY_NAME_SIZE
= 24 };
635 /* Open an available pty, returning a file descriptor.
636 Store into PTY_NAME the file name of the terminal corresponding to the pty.
637 Return -1 on failure. */
640 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
649 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
650 for (i
= 0; i
< 16; i
++)
653 #ifdef PTY_NAME_SPRINTF
656 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
657 #endif /* no PTY_NAME_SPRINTF */
661 #else /* no PTY_OPEN */
662 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
663 #endif /* no PTY_OPEN */
667 #ifdef PTY_TTY_NAME_SPRINTF
670 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
671 #endif /* no PTY_TTY_NAME_SPRINTF */
673 /* Set FD's close-on-exec flag. This is needed even if
674 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
675 doesn't require support for that combination.
676 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
677 doesn't work if the close-on-exec flag is set (Bug#20555).
678 Multithreaded platforms where posix_openpt ignores
679 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
680 have a race condition between the PTY_OPEN and here. */
681 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
683 /* Check to make certain that both sides are available.
684 This avoids a nasty yet stupid bug in rlogins. */
685 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
698 #endif /* HAVE_PTYS */
702 /* Allocate basically initialized process. */
704 static struct Lisp_Process
*
705 allocate_process (void)
707 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
711 make_process (Lisp_Object name
)
713 struct Lisp_Process
*p
= allocate_process ();
714 /* Initialize Lisp data. Note that allocate_process initializes all
715 Lisp data to nil, so do it only for slots which should not be nil. */
716 pset_status (p
, Qrun
);
717 pset_mark (p
, Fmake_marker ());
719 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
720 non-Lisp data, so do it only for slots which should not be zero. */
723 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
727 verify (GNUTLS_STAGE_EMPTY
== 0);
728 eassert (p
->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
729 eassert (NILP (p
->gnutls_boot_parameters
));
732 /* If name is already in use, modify it until it is unused. */
734 Lisp_Object name1
= name
;
735 for (printmax_t i
= 1; ; i
++)
737 Lisp_Object tem
= Fget_process (name1
);
740 char const suffix_fmt
[] = "<%"pMd
">";
741 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
742 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
743 name1
= concat2 (name
, lsuffix
);
747 pset_sentinel (p
, Qinternal_default_process_sentinel
);
748 pset_filter (p
, Qinternal_default_process_filter
);
750 XSETPROCESS (val
, p
);
751 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
756 remove_process (register Lisp_Object proc
)
758 register Lisp_Object pair
;
760 pair
= Frassq (proc
, Vprocess_alist
);
761 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
763 deactivate_process (proc
);
766 #ifdef HAVE_GETADDRINFO_A
768 free_dns_request (Lisp_Object proc
)
770 struct Lisp_Process
*p
= XPROCESS (proc
);
772 if (p
->dns_request
->ar_result
)
773 freeaddrinfo (p
->dns_request
->ar_result
);
774 xfree (p
->dns_request
);
775 p
->dns_request
= NULL
;
780 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
781 doc
: /* Return t if OBJECT is a process. */)
784 return PROCESSP (object
) ? Qt
: Qnil
;
787 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
788 doc
: /* Return the process named NAME, or nil if there is none. */)
789 (register Lisp_Object name
)
794 return Fcdr (Fassoc (name
, Vprocess_alist
));
797 /* This is how commands for the user decode process arguments. It
798 accepts a process, a process name, a buffer, a buffer name, or nil.
799 Buffers denote the first process in the buffer, and nil denotes the
803 get_process (register Lisp_Object name
)
805 register Lisp_Object proc
, obj
;
808 obj
= Fget_process (name
);
810 obj
= Fget_buffer (name
);
812 error ("Process %s does not exist", SDATA (name
));
814 else if (NILP (name
))
815 obj
= Fcurrent_buffer ();
819 /* Now obj should be either a buffer object or a process object. */
822 if (NILP (BVAR (XBUFFER (obj
), name
)))
823 error ("Attempt to get process for a dead buffer");
824 proc
= Fget_buffer_process (obj
);
826 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
837 /* Fdelete_process promises to immediately forget about the process, but in
838 reality, Emacs needs to remember those processes until they have been
839 treated by the SIGCHLD handler and waitpid has been invoked on them;
840 otherwise they might fill up the kernel's process table.
842 Some processes created by call-process are also put onto this list.
844 Members of this list are (process-ID . filename) pairs. The
845 process-ID is a number; the filename, if a string, is a file that
846 needs to be removed after the process exits. */
847 static Lisp_Object deleted_pid_list
;
850 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
852 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
853 /* GC treated elements set to nil. */
854 Fdelq (Qnil
, deleted_pid_list
));
858 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
859 doc
: /* Delete PROCESS: kill it and forget about it immediately.
860 PROCESS may be a process, a buffer, the name of a process or buffer, or
861 nil, indicating the current buffer's process. */)
862 (register Lisp_Object process
)
864 register struct Lisp_Process
*p
;
866 process
= get_process (process
);
867 p
= XPROCESS (process
);
869 #ifdef HAVE_GETADDRINFO_A
872 /* Cancel the request. Unless shutting down, wait until
873 completion. Free the request if completely canceled. */
875 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
876 if (!canceled
&& !inhibit_sentinels
)
878 struct gaicb
const *req
= p
->dns_request
;
879 while (gai_suspend (&req
, 1, NULL
) != 0)
884 free_dns_request (process
);
888 p
->raw_status_new
= 0;
889 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
891 pset_status (p
, list2 (Qexit
, make_number (0)));
892 p
->tick
= ++process_tick
;
893 status_notify (p
, NULL
);
894 redisplay_preserve_echo_area (13);
899 record_kill_process (p
, Qnil
);
903 /* Update P's status, since record_kill_process will make the
904 SIGCHLD handler update deleted_pid_list, not *P. */
906 if (p
->raw_status_new
)
908 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
909 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
910 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
912 p
->tick
= ++process_tick
;
913 status_notify (p
, NULL
);
914 redisplay_preserve_echo_area (13);
917 remove_process (process
);
921 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
922 doc
: /* Return the status of PROCESS.
923 The returned value is one of the following symbols:
924 run -- for a process that is running.
925 stop -- for a process stopped but continuable.
926 exit -- for a process that has exited.
927 signal -- for a process that has got a fatal signal.
928 open -- for a network stream connection that is open.
929 listen -- for a network stream server that is listening.
930 closed -- for a network stream connection that is closed.
931 connect -- when waiting for a non-blocking connection to complete.
932 failed -- when a non-blocking connection has failed.
933 nil -- if arg is a process name and no such process exists.
934 PROCESS may be a process, a buffer, the name of a process, or
935 nil, indicating the current buffer's process. */)
936 (register Lisp_Object process
)
938 register struct Lisp_Process
*p
;
939 register Lisp_Object status
;
941 if (STRINGP (process
))
942 process
= Fget_process (process
);
944 process
= get_process (process
);
949 p
= XPROCESS (process
);
950 if (p
->raw_status_new
)
954 status
= XCAR (status
);
955 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
957 if (EQ (status
, Qexit
))
959 else if (EQ (p
->command
, Qt
))
961 else if (EQ (status
, Qrun
))
967 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
969 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
970 If PROCESS has not yet exited or died, return 0. */)
971 (register Lisp_Object process
)
973 CHECK_PROCESS (process
);
974 if (XPROCESS (process
)->raw_status_new
)
975 update_status (XPROCESS (process
));
976 if (CONSP (XPROCESS (process
)->status
))
977 return XCAR (XCDR (XPROCESS (process
)->status
));
978 return make_number (0);
981 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
982 doc
: /* Return the process id of PROCESS.
983 This is the pid of the external process which PROCESS uses or talks to.
984 For a network, serial, and pipe connections, this value is nil. */)
985 (register Lisp_Object process
)
989 CHECK_PROCESS (process
);
990 pid
= XPROCESS (process
)->pid
;
991 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
994 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
995 doc
: /* Return the name of PROCESS, as a string.
996 This is the name of the program invoked in PROCESS,
997 possibly modified to make it unique among process names. */)
998 (register Lisp_Object process
)
1000 CHECK_PROCESS (process
);
1001 return XPROCESS (process
)->name
;
1004 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1005 doc
: /* Return the command that was executed to start PROCESS.
1006 This is a list of strings, the first string being the program executed
1007 and the rest of the strings being the arguments given to it.
1008 For a network or serial or pipe connection, this is nil (process is running)
1009 or t (process is stopped). */)
1010 (register Lisp_Object process
)
1012 CHECK_PROCESS (process
);
1013 return XPROCESS (process
)->command
;
1016 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1017 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1018 This is the terminal that the process itself reads and writes on,
1019 not the name of the pty that Emacs uses to talk with that terminal. */)
1020 (register Lisp_Object process
)
1022 CHECK_PROCESS (process
);
1023 return XPROCESS (process
)->tty_name
;
1026 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1028 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1030 (register Lisp_Object process
, Lisp_Object buffer
)
1032 struct Lisp_Process
*p
;
1034 CHECK_PROCESS (process
);
1036 CHECK_BUFFER (buffer
);
1037 p
= XPROCESS (process
);
1038 pset_buffer (p
, buffer
);
1039 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1040 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1041 setup_process_coding_systems (process
);
1045 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1047 doc
: /* Return the buffer PROCESS is associated with.
1048 The default process filter inserts output from PROCESS into this buffer. */)
1049 (register Lisp_Object process
)
1051 CHECK_PROCESS (process
);
1052 return XPROCESS (process
)->buffer
;
1055 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1057 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1058 (register Lisp_Object process
)
1060 CHECK_PROCESS (process
);
1061 return XPROCESS (process
)->mark
;
1065 set_process_filter_masks (struct Lisp_Process
*p
)
1067 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1069 FD_CLR (p
->infd
, &input_wait_mask
);
1070 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1072 else if (EQ (p
->filter
, Qt
)
1073 /* Network or serial process not stopped: */
1074 && !EQ (p
->command
, Qt
))
1076 FD_SET (p
->infd
, &input_wait_mask
);
1077 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1081 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1083 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1084 A value of t means stop accepting output from the process.
1086 When a process has a non-default filter, its buffer is not used for output.
1087 Instead, each time it does output, the entire string of output is
1088 passed to the filter.
1090 The filter gets two arguments: the process and the string of output.
1091 The string argument is normally a multibyte string, except:
1092 - if the process's input coding system is no-conversion or raw-text,
1093 it is a unibyte string (the non-converted input), or else
1094 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1095 string (the result of converting the decoded input multibyte
1096 string to unibyte with `string-make-unibyte'). */)
1097 (Lisp_Object process
, Lisp_Object filter
)
1099 CHECK_PROCESS (process
);
1100 struct Lisp_Process
*p
= XPROCESS (process
);
1102 /* Don't signal an error if the process's input file descriptor
1103 is closed. This could make debugging Lisp more difficult,
1104 for example when doing something like
1106 (setq process (start-process ...))
1108 (set-process-filter process ...) */
1111 filter
= Qinternal_default_process_filter
;
1113 pset_filter (p
, filter
);
1116 set_process_filter_masks (p
);
1118 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1119 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1120 setup_process_coding_systems (process
);
1124 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1126 doc
: /* Return the filter function of PROCESS.
1127 See `set-process-filter' for more info on filter functions. */)
1128 (register Lisp_Object process
)
1130 CHECK_PROCESS (process
);
1131 return XPROCESS (process
)->filter
;
1134 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1136 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1137 The sentinel is called as a function when the process changes state.
1138 It gets two arguments: the process, and a string describing the change. */)
1139 (register Lisp_Object process
, Lisp_Object sentinel
)
1141 struct Lisp_Process
*p
;
1143 CHECK_PROCESS (process
);
1144 p
= XPROCESS (process
);
1146 if (NILP (sentinel
))
1147 sentinel
= Qinternal_default_process_sentinel
;
1149 pset_sentinel (p
, sentinel
);
1150 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1151 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1155 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1157 doc
: /* Return the sentinel of PROCESS.
1158 See `set-process-sentinel' for more info on sentinels. */)
1159 (register Lisp_Object process
)
1161 CHECK_PROCESS (process
);
1162 return XPROCESS (process
)->sentinel
;
1165 DEFUN ("set-process-window-size", Fset_process_window_size
,
1166 Sset_process_window_size
, 3, 3, 0,
1167 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1168 Value is t if PROCESS was successfully told about the window size,
1170 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1172 CHECK_PROCESS (process
);
1174 /* All known platforms store window sizes as 'unsigned short'. */
1175 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1176 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1178 if (NETCONN_P (process
)
1179 || XPROCESS (process
)->infd
< 0
1180 || (set_window_size (XPROCESS (process
)->infd
,
1181 XINT (height
), XINT (width
))
1188 DEFUN ("set-process-inherit-coding-system-flag",
1189 Fset_process_inherit_coding_system_flag
,
1190 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1191 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1192 If the second argument FLAG is non-nil, then the variable
1193 `buffer-file-coding-system' of the buffer associated with PROCESS
1194 will be bound to the value of the coding system used to decode
1197 This is useful when the coding system specified for the process buffer
1198 leaves either the character code conversion or the end-of-line conversion
1199 unspecified, or if the coding system used to decode the process output
1200 is more appropriate for saving the process buffer.
1202 Binding the variable `inherit-process-coding-system' to non-nil before
1203 starting the process is an alternative way of setting the inherit flag
1204 for the process which will run.
1206 This function returns FLAG. */)
1207 (register Lisp_Object process
, Lisp_Object flag
)
1209 CHECK_PROCESS (process
);
1210 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1214 DEFUN ("set-process-query-on-exit-flag",
1215 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1217 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1218 If the second argument FLAG is non-nil, Emacs will query the user before
1219 exiting or killing a buffer if PROCESS is running. This function
1221 (register Lisp_Object process
, Lisp_Object flag
)
1223 CHECK_PROCESS (process
);
1224 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1228 DEFUN ("process-query-on-exit-flag",
1229 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1231 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1232 (register Lisp_Object process
)
1234 CHECK_PROCESS (process
);
1235 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1238 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1240 doc
: /* Return the contact info of PROCESS; t for a real child.
1241 For a network or serial or pipe connection, the value depends on the
1242 optional KEY arg. If KEY is nil, value is a cons cell of the form
1243 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1244 connection; it is t for a pipe connection. If KEY is t, the complete
1245 contact information for the connection is returned, else the specific
1246 value for the keyword KEY is returned. See `make-network-process',
1247 `make-serial-process', or `make pipe-process' for the list of keywords.
1248 If PROCESS is a non-blocking network process that hasn't been fully
1249 set up yet, this function will block until socket setup has completed. */)
1250 (Lisp_Object process
, Lisp_Object key
)
1252 Lisp_Object contact
;
1254 CHECK_PROCESS (process
);
1255 contact
= XPROCESS (process
)->childp
;
1257 #ifdef DATAGRAM_SOCKETS
1259 if (NETCONN_P (process
))
1260 wait_for_socket_fds (process
, "process-contact");
1262 if (DATAGRAM_CONN_P (process
)
1263 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1264 contact
= Fplist_put (contact
, QCremote
,
1265 Fprocess_datagram_address (process
));
1268 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1271 if (NILP (key
) && NETCONN_P (process
))
1272 return list2 (Fplist_get (contact
, QChost
),
1273 Fplist_get (contact
, QCservice
));
1274 if (NILP (key
) && SERIALCONN_P (process
))
1275 return list2 (Fplist_get (contact
, QCport
),
1276 Fplist_get (contact
, QCspeed
));
1277 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1278 if the pipe process is useful for purposes other than receiving
1280 if (NILP (key
) && PIPECONN_P (process
))
1282 return Fplist_get (contact
, key
);
1285 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1287 doc
: /* Return the plist of PROCESS. */)
1288 (register Lisp_Object process
)
1290 CHECK_PROCESS (process
);
1291 return XPROCESS (process
)->plist
;
1294 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1296 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1297 (Lisp_Object process
, Lisp_Object plist
)
1299 CHECK_PROCESS (process
);
1302 pset_plist (XPROCESS (process
), plist
);
1306 #if 0 /* Turned off because we don't currently record this info
1307 in the process. Perhaps add it. */
1308 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1309 doc
: /* Return the connection type of PROCESS.
1310 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1311 a socket connection. */)
1312 (Lisp_Object process
)
1314 return XPROCESS (process
)->type
;
1318 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1319 doc
: /* Return the connection type of PROCESS.
1320 The value is either the symbol `real', `network', `serial', or `pipe'.
1321 PROCESS may be a process, a buffer, the name of a process or buffer, or
1322 nil, indicating the current buffer's process. */)
1323 (Lisp_Object process
)
1326 proc
= get_process (process
);
1327 return XPROCESS (proc
)->type
;
1330 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1332 doc
: /* Convert network ADDRESS from internal format to a string.
1333 A 4 or 5 element vector represents an IPv4 address (with port number).
1334 An 8 or 9 element vector represents an IPv6 address (with port number).
1335 If optional second argument OMIT-PORT is non-nil, don't include a port
1336 number in the string, even when present in ADDRESS.
1337 Return nil if format of ADDRESS is invalid. */)
1338 (Lisp_Object address
, Lisp_Object omit_port
)
1343 if (STRINGP (address
)) /* AF_LOCAL */
1346 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1348 register struct Lisp_Vector
*p
= XVECTOR (address
);
1349 ptrdiff_t size
= p
->header
.size
;
1350 Lisp_Object args
[10];
1354 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1356 format
= "%d.%d.%d.%d";
1361 format
= "%d.%d.%d.%d:%d";
1364 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1366 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1371 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1377 AUTO_STRING (format_obj
, format
);
1378 args
[0] = format_obj
;
1380 for (i
= 0; i
< nargs
; i
++)
1382 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1385 if (nargs
<= 5 /* IPv4 */
1386 && i
< 4 /* host, not port */
1387 && XINT (p
->contents
[i
]) > 255)
1390 args
[i
+ 1] = p
->contents
[i
];
1393 return Fformat (nargs
+ 1, args
);
1396 if (CONSP (address
))
1398 AUTO_STRING (format
, "<Family %d>");
1399 return CALLN (Fformat
, format
, Fcar (address
));
1405 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1406 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1409 return Fmapcar (Qcdr
, Vprocess_alist
);
1412 /* Starting asynchronous inferior processes. */
1414 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1415 doc
: /* Start a program in a subprocess. Return the process object for it.
1417 This is similar to `start-process', but arguments are specified as
1418 keyword/argument pairs. The following arguments are defined:
1420 :name NAME -- NAME is name for process. It is modified if necessary
1423 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1424 with the process. Process output goes at end of that buffer, unless
1425 you specify an output stream or filter function to handle the output.
1426 BUFFER may be also nil, meaning that this process is not associated
1429 :command COMMAND -- COMMAND is a list starting with the program file
1430 name, followed by strings to give to the program as arguments.
1432 :coding CODING -- If CODING is a symbol, it specifies the coding
1433 system used for both reading and writing for this process. If CODING
1434 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1435 ENCODING is used for writing.
1437 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1438 the process is running. If BOOL is not given, query before exiting.
1440 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1441 In the stopped state, a process does not accept incoming data, but you
1442 can send outgoing data. The stopped state is cleared by
1443 `continue-process' and set by `stop-process'.
1445 :connection-type TYPE -- TYPE is control type of device used to
1446 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1447 to use a pty, or nil to use the default specified through
1448 `process-connection-type'.
1450 :filter FILTER -- Install FILTER as the process filter.
1452 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1454 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1455 to the standard error of subprocess. Specifying this implies
1456 `:connection-type' is set to `pipe'.
1458 usage: (make-process &rest ARGS) */)
1459 (ptrdiff_t nargs
, Lisp_Object
*args
)
1461 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1462 Lisp_Object xstderr
, stderrproc
;
1463 ptrdiff_t count
= SPECPDL_INDEX ();
1468 /* Save arguments for process-contact and clone-process. */
1469 contact
= Flist (nargs
, args
);
1471 buffer
= Fplist_get (contact
, QCbuffer
);
1473 buffer
= Fget_buffer_create (buffer
);
1475 /* Make sure that the child will be able to chdir to the current
1476 buffer's current directory, or its unhandled equivalent. We
1477 can't just have the child check for an error when it does the
1478 chdir, since it's in a vfork. */
1479 current_dir
= encode_current_directory ();
1481 name
= Fplist_get (contact
, QCname
);
1482 CHECK_STRING (name
);
1484 command
= Fplist_get (contact
, QCcommand
);
1485 if (CONSP (command
))
1486 program
= XCAR (command
);
1490 if (!NILP (program
))
1491 CHECK_STRING (program
);
1494 xstderr
= Fplist_get (contact
, QCstderr
);
1495 if (PROCESSP (xstderr
))
1497 if (!PIPECONN_P (xstderr
))
1498 error ("Process is not a pipe process");
1499 stderrproc
= xstderr
;
1501 else if (!NILP (xstderr
))
1503 CHECK_STRING (program
);
1504 stderrproc
= CALLN (Fmake_pipe_process
,
1506 concat2 (name
, build_string (" stderr")),
1508 Fget_buffer_create (xstderr
));
1511 proc
= make_process (name
);
1512 record_unwind_protect (start_process_unwind
, proc
);
1514 pset_childp (XPROCESS (proc
), Qt
);
1515 eassert (NILP (XPROCESS (proc
)->plist
));
1516 pset_type (XPROCESS (proc
), Qreal
);
1517 pset_buffer (XPROCESS (proc
), buffer
);
1518 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1519 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1520 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1522 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1523 XPROCESS (proc
)->kill_without_query
= 1;
1524 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1525 pset_command (XPROCESS (proc
), Qt
);
1527 tem
= Fplist_get (contact
, QCconnection_type
);
1529 XPROCESS (proc
)->pty_flag
= true;
1530 else if (EQ (tem
, Qpipe
))
1531 XPROCESS (proc
)->pty_flag
= false;
1532 else if (NILP (tem
))
1533 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1535 report_file_error ("Unknown connection type", tem
);
1537 if (!NILP (stderrproc
))
1539 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1541 XPROCESS (proc
)->pty_flag
= false;
1545 /* AKA GNUTLS_INITSTAGE(proc). */
1546 verify (GNUTLS_STAGE_EMPTY
== 0);
1547 eassert (XPROCESS (proc
)->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
1548 eassert (NILP (XPROCESS (proc
)->gnutls_cred_type
));
1551 XPROCESS (proc
)->adaptive_read_buffering
1552 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1553 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1555 /* Make the process marker point into the process buffer (if any). */
1556 if (BUFFERP (buffer
))
1557 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1558 BUF_ZV (XBUFFER (buffer
)),
1559 BUF_ZV_BYTE (XBUFFER (buffer
)));
1564 /* Decide coding systems for communicating with the process. Here
1565 we don't setup the structure coding_system nor pay attention to
1566 unibyte mode. They are done in create_process. */
1568 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1569 Lisp_Object coding_systems
= Qt
;
1570 Lisp_Object val
, *args2
;
1572 tem
= Fplist_get (contact
, QCcoding
);
1580 val
= Vcoding_system_for_read
;
1583 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1585 SAFE_ALLOCA_LISP (args2
, nargs2
);
1587 args2
[i
++] = Qstart_process
;
1589 args2
[i
++] = buffer
;
1590 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1591 args2
[i
++] = XCAR (tem2
);
1592 if (!NILP (program
))
1593 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1594 if (CONSP (coding_systems
))
1595 val
= XCAR (coding_systems
);
1596 else if (CONSP (Vdefault_process_coding_system
))
1597 val
= XCAR (Vdefault_process_coding_system
);
1599 pset_decode_coding_system (XPROCESS (proc
), val
);
1608 val
= Vcoding_system_for_write
;
1611 if (EQ (coding_systems
, Qt
))
1613 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1615 SAFE_ALLOCA_LISP (args2
, nargs2
);
1617 args2
[i
++] = Qstart_process
;
1619 args2
[i
++] = buffer
;
1620 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1621 args2
[i
++] = XCAR (tem2
);
1622 if (!NILP (program
))
1623 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1625 if (CONSP (coding_systems
))
1626 val
= XCDR (coding_systems
);
1627 else if (CONSP (Vdefault_process_coding_system
))
1628 val
= XCDR (Vdefault_process_coding_system
);
1630 pset_encode_coding_system (XPROCESS (proc
), val
);
1631 /* Note: At this moment, the above coding system may leave
1632 text-conversion or eol-conversion unspecified. They will be
1633 decided after we read output from the process and decode it by
1634 some coding system, or just before we actually send a text to
1639 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1640 eassert (XPROCESS (proc
)->decoding_carryover
== 0);
1641 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1643 XPROCESS (proc
)->inherit_coding_system_flag
1644 = !(NILP (buffer
) || !inherit_process_coding_system
);
1646 if (!NILP (program
))
1648 Lisp_Object program_args
= XCDR (command
);
1650 /* If program file name is not absolute, search our path for it.
1651 Put the name we will really use in TEM. */
1652 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1653 && !(SCHARS (program
) > 1
1654 && IS_DEVICE_SEP (SREF (program
, 1))))
1657 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1658 make_number (X_OK
), false);
1660 report_file_error ("Searching for program", program
);
1661 tem
= Fexpand_file_name (tem
, Qnil
);
1665 if (!NILP (Ffile_directory_p (program
)))
1666 error ("Specified program for new process is a directory");
1670 /* Remove "/:" from TEM. */
1671 tem
= remove_slash_colon (tem
);
1673 Lisp_Object arg_encoding
= Qnil
;
1675 /* Encode the file name and put it in NEW_ARGV.
1676 That's where the child will use it to execute the program. */
1677 tem
= list1 (ENCODE_FILE (tem
));
1678 ptrdiff_t new_argc
= 1;
1680 /* Here we encode arguments by the coding system used for sending
1681 data to the process. We don't support using different coding
1682 systems for encoding arguments and for encoding data sent to the
1685 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1687 Lisp_Object arg
= XCAR (tem2
);
1689 if (STRING_MULTIBYTE (arg
))
1691 if (NILP (arg_encoding
))
1692 arg_encoding
= (complement_process_encoding_system
1693 (XPROCESS (proc
)->encode_coding_system
));
1694 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1696 tem
= Fcons (arg
, tem
);
1700 /* Now that everything is encoded we can collect the strings into
1703 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1704 new_argv
[new_argc
] = 0;
1706 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1708 new_argv
[i
] = SSDATA (XCAR (tem
));
1712 create_process (proc
, new_argv
, current_dir
);
1718 return unbind_to (count
, proc
);
1721 /* If PROC doesn't have its pid set, then an error was signaled and
1722 the process wasn't started successfully, so remove it. */
1724 start_process_unwind (Lisp_Object proc
)
1726 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1727 remove_process (proc
);
1730 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1733 close_process_fd (int *fd_addr
)
1743 /* Indexes of file descriptors in open_fds. */
1746 /* The pipe from Emacs to its subprocess. */
1748 WRITE_TO_SUBPROCESS
,
1750 /* The main pipe from the subprocess to Emacs. */
1751 READ_FROM_SUBPROCESS
,
1754 /* The pipe from the subprocess to Emacs that is closed when the
1755 subprocess execs. */
1756 READ_FROM_EXEC_MONITOR
,
1760 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1763 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1765 struct Lisp_Process
*p
= XPROCESS (process
);
1766 int inchannel
, outchannel
;
1769 int forkin
, forkout
, forkerr
= -1;
1771 char pty_name
[PTY_NAME_SIZE
];
1772 Lisp_Object lisp_pty_name
= Qnil
;
1775 inchannel
= outchannel
= -1;
1778 outchannel
= inchannel
= allocate_pty (pty_name
);
1782 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1783 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1784 /* On most USG systems it does not work to open the pty's tty here,
1785 then close it and reopen it in the child. */
1786 /* Don't let this terminal become our controlling terminal
1787 (in case we don't have one). */
1788 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1790 report_file_error ("Opening pty", Qnil
);
1791 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1793 forkin
= forkout
= -1;
1794 #endif /* not USG, or USG_SUBTTY_WORKS */
1796 lisp_pty_name
= build_string (pty_name
);
1800 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1801 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1802 report_file_error ("Creating pipe", Qnil
);
1803 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1804 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1805 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1806 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1808 if (!NILP (p
->stderrproc
))
1810 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1812 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1814 /* Close unnecessary file descriptors. */
1815 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1816 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1821 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1822 report_file_error ("Creating pipe", Qnil
);
1825 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1826 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1828 /* Record this as an active process, with its channels. */
1829 chan_process
[inchannel
] = process
;
1830 p
->infd
= inchannel
;
1831 p
->outfd
= outchannel
;
1833 /* Previously we recorded the tty descriptor used in the subprocess.
1834 It was only used for getting the foreground tty process, so now
1835 we just reopen the device (see emacs_get_tty_pgrp) as this is
1836 more portable (see USG_SUBTTY_WORKS above). */
1838 p
->pty_flag
= pty_flag
;
1839 pset_status (p
, Qrun
);
1841 if (!EQ (p
->command
, Qt
))
1843 FD_SET (inchannel
, &input_wait_mask
);
1844 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1847 if (inchannel
> max_process_desc
)
1848 max_process_desc
= inchannel
;
1850 /* This may signal an error. */
1851 setup_process_coding_systems (process
);
1854 block_child_signal (&oldset
);
1857 /* vfork, and prevent local vars from being clobbered by the vfork. */
1858 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1859 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1860 char **volatile new_argv_volatile
= new_argv
;
1861 int volatile forkin_volatile
= forkin
;
1862 int volatile forkout_volatile
= forkout
;
1863 int volatile forkerr_volatile
= forkerr
;
1864 struct Lisp_Process
*p_volatile
= p
;
1868 current_dir
= current_dir_volatile
;
1869 lisp_pty_name
= lisp_pty_name_volatile
;
1870 new_argv
= new_argv_volatile
;
1871 forkin
= forkin_volatile
;
1872 forkout
= forkout_volatile
;
1873 forkerr
= forkerr_volatile
;
1876 pty_flag
= p
->pty_flag
;
1879 #endif /* not WINDOWSNT */
1881 /* Make the pty be the controlling terminal of the process. */
1883 /* First, disconnect its current controlling terminal. */
1884 /* We tried doing setsid only if pty_flag, but it caused
1885 process_set_signal to fail on SGI when using a pipe. */
1887 /* Make the pty's terminal the controlling terminal. */
1888 if (pty_flag
&& forkin
>= 0)
1891 /* We ignore the return value
1892 because faith@cs.unc.edu says that is necessary on Linux. */
1893 ioctl (forkin
, TIOCSCTTY
, 0);
1896 #if defined (LDISC1)
1897 if (pty_flag
&& forkin
>= 0)
1900 tcgetattr (forkin
, &t
);
1902 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1903 emacs_perror ("create_process/tcsetattr LDISC1");
1906 #if defined (NTTYDISC) && defined (TIOCSETD)
1907 if (pty_flag
&& forkin
>= 0)
1909 /* Use new line discipline. */
1910 int ldisc
= NTTYDISC
;
1911 ioctl (forkin
, TIOCSETD
, &ldisc
);
1916 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1917 can do TIOCSPGRP only to the process's controlling tty. */
1920 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1921 I can't test it since I don't have 4.3. */
1922 int j
= emacs_open (DEV_TTY
, O_RDWR
, 0);
1925 ioctl (j
, TIOCNOTTY
, 0);
1929 #endif /* TIOCNOTTY */
1931 #if !defined (DONT_REOPEN_PTY)
1932 /*** There is a suggestion that this ought to be a
1933 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1934 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1935 that system does seem to need this code, even though
1936 both TIOCSCTTY is defined. */
1937 /* Now close the pty (if we had it open) and reopen it.
1938 This makes the pty the controlling terminal of the subprocess. */
1942 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1945 emacs_close (forkin
);
1946 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1950 emacs_perror (SSDATA (lisp_pty_name
));
1951 _exit (EXIT_CANCELED
);
1955 #endif /* not DONT_REOPEN_PTY */
1957 #ifdef SETUP_SLAVE_PTY
1962 #endif /* SETUP_SLAVE_PTY */
1963 #endif /* HAVE_PTYS */
1965 signal (SIGINT
, SIG_DFL
);
1966 signal (SIGQUIT
, SIG_DFL
);
1968 signal (SIGPROF
, SIG_DFL
);
1971 /* Emacs ignores SIGPIPE, but the child should not. */
1972 signal (SIGPIPE
, SIG_DFL
);
1974 /* Stop blocking SIGCHLD in the child. */
1975 unblock_child_signal (&oldset
);
1978 child_setup_tty (forkout
);
1983 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1984 #else /* not WINDOWSNT */
1985 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1986 #endif /* not WINDOWSNT */
1989 /* Back in the parent process. */
1991 vfork_errno
= errno
;
1996 /* Stop blocking in the parent. */
1997 unblock_child_signal (&oldset
);
2001 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2004 /* vfork succeeded. */
2006 /* Close the pipe ends that the child uses, or the child's pty. */
2007 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2008 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2011 register_child (pid
, inchannel
);
2012 #endif /* WINDOWSNT */
2014 pset_tty_name (p
, lisp_pty_name
);
2017 /* Wait for child_setup to complete in case that vfork is
2018 actually defined as fork. The descriptor
2019 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2020 of a pipe is closed at the child side either by close-on-exec
2021 on successful execve or the _exit call in child_setup. */
2025 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2026 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2027 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2030 if (!NILP (p
->stderrproc
))
2032 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2033 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2039 create_pty (Lisp_Object process
)
2041 struct Lisp_Process
*p
= XPROCESS (process
);
2042 char pty_name
[PTY_NAME_SIZE
];
2043 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2047 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2048 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2049 /* On most USG systems it does not work to open the pty's tty here,
2050 then close it and reopen it in the child. */
2051 /* Don't let this terminal become our controlling terminal
2052 (in case we don't have one). */
2053 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2055 report_file_error ("Opening pty", Qnil
);
2056 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2057 #if defined (DONT_REOPEN_PTY)
2058 /* In the case that vfork is defined as fork, the parent process
2059 (Emacs) may send some data before the child process completes
2060 tty options setup. So we setup tty before forking. */
2061 child_setup_tty (forkout
);
2062 #endif /* DONT_REOPEN_PTY */
2063 #endif /* not USG, or USG_SUBTTY_WORKS */
2065 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2067 /* Record this as an active process, with its channels.
2068 As a result, child_setup will close Emacs's side of the pipes. */
2069 chan_process
[pty_fd
] = process
;
2073 /* Previously we recorded the tty descriptor used in the subprocess.
2074 It was only used for getting the foreground tty process, so now
2075 we just reopen the device (see emacs_get_tty_pgrp) as this is
2076 more portable (see USG_SUBTTY_WORKS above). */
2079 pset_status (p
, Qrun
);
2080 setup_process_coding_systems (process
);
2082 FD_SET (pty_fd
, &input_wait_mask
);
2083 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2084 if (pty_fd
> max_process_desc
)
2085 max_process_desc
= pty_fd
;
2087 pset_tty_name (p
, build_string (pty_name
));
2093 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2095 doc
: /* Create and return a bidirectional pipe process.
2097 In Emacs, pipes are represented by process objects, so input and
2098 output work as for subprocesses, and `delete-process' closes a pipe.
2099 However, a pipe process has no process id, it cannot be signaled,
2100 and the status codes are different from normal processes.
2102 Arguments are specified as keyword/argument pairs. The following
2103 arguments are defined:
2105 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2107 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2108 with the process. Process output goes at the end of that buffer,
2109 unless you specify an output stream or filter function to handle the
2110 output. If BUFFER is not given, the value of NAME is used.
2112 :coding CODING -- If CODING is a symbol, it specifies the coding
2113 system used for both reading and writing for this process. If CODING
2114 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2115 ENCODING is used for writing.
2117 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2118 the process is running. If BOOL is not given, query before exiting.
2120 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2121 In the stopped state, a pipe process does not accept incoming data,
2122 but you can send outgoing data. The stopped state is cleared by
2123 `continue-process' and set by `stop-process'.
2125 :filter FILTER -- Install FILTER as the process filter.
2127 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2129 usage: (make-pipe-process &rest ARGS) */)
2130 (ptrdiff_t nargs
, Lisp_Object
*args
)
2132 Lisp_Object proc
, contact
;
2133 struct Lisp_Process
*p
;
2134 Lisp_Object name
, buffer
;
2136 ptrdiff_t specpdl_count
;
2137 int inchannel
, outchannel
;
2142 contact
= Flist (nargs
, args
);
2144 name
= Fplist_get (contact
, QCname
);
2145 CHECK_STRING (name
);
2146 proc
= make_process (name
);
2147 specpdl_count
= SPECPDL_INDEX ();
2148 record_unwind_protect (remove_process
, proc
);
2149 p
= XPROCESS (proc
);
2151 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2152 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2153 report_file_error ("Creating pipe", Qnil
);
2154 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2155 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2157 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2158 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2161 register_aux_fd (inchannel
);
2164 /* Record this as an active process, with its channels. */
2165 chan_process
[inchannel
] = proc
;
2166 p
->infd
= inchannel
;
2167 p
->outfd
= outchannel
;
2169 if (inchannel
> max_process_desc
)
2170 max_process_desc
= inchannel
;
2172 buffer
= Fplist_get (contact
, QCbuffer
);
2175 buffer
= Fget_buffer_create (buffer
);
2176 pset_buffer (p
, buffer
);
2178 pset_childp (p
, contact
);
2179 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2180 pset_type (p
, Qpipe
);
2181 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2182 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2183 eassert (NILP (p
->log
));
2184 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2185 p
->kill_without_query
= 1;
2186 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2187 pset_command (p
, Qt
);
2188 eassert (! p
->pty_flag
);
2190 if (!EQ (p
->command
, Qt
))
2192 FD_SET (inchannel
, &input_wait_mask
);
2193 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2195 p
->adaptive_read_buffering
2196 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2197 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2199 /* Make the process marker point into the process buffer (if any). */
2200 if (BUFFERP (buffer
))
2201 set_marker_both (p
->mark
, buffer
,
2202 BUF_ZV (XBUFFER (buffer
)),
2203 BUF_ZV_BYTE (XBUFFER (buffer
)));
2206 /* Setup coding systems for communicating with the network stream. */
2208 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2209 Lisp_Object coding_systems
= Qt
;
2212 tem
= Fplist_get (contact
, QCcoding
);
2220 else if (!NILP (Vcoding_system_for_read
))
2221 val
= Vcoding_system_for_read
;
2222 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2223 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2224 /* We dare not decode end-of-line format by setting VAL to
2225 Qraw_text, because the existing Emacs Lisp libraries
2226 assume that they receive bare code including a sequence of
2231 if (CONSP (coding_systems
))
2232 val
= XCAR (coding_systems
);
2233 else if (CONSP (Vdefault_process_coding_system
))
2234 val
= XCAR (Vdefault_process_coding_system
);
2238 pset_decode_coding_system (p
, val
);
2246 else if (!NILP (Vcoding_system_for_write
))
2247 val
= Vcoding_system_for_write
;
2248 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2252 if (CONSP (coding_systems
))
2253 val
= XCDR (coding_systems
);
2254 else if (CONSP (Vdefault_process_coding_system
))
2255 val
= XCDR (Vdefault_process_coding_system
);
2259 pset_encode_coding_system (p
, val
);
2261 /* This may signal an error. */
2262 setup_process_coding_systems (proc
);
2264 specpdl_ptr
= specpdl
+ specpdl_count
;
2270 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2271 The address family of sa is not included in the result. */
2274 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2276 Lisp_Object address
;
2279 struct Lisp_Vector
*p
;
2281 /* Workaround for a bug in getsockname on BSD: Names bound to
2282 sockets in the UNIX domain are inaccessible; getsockname returns
2283 a zero length name. */
2284 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2285 return empty_unibyte_string
;
2287 switch (sa
->sa_family
)
2291 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2292 len
= sizeof (sin
->sin_addr
) + 1;
2293 address
= Fmake_vector (make_number (len
), Qnil
);
2294 p
= XVECTOR (address
);
2295 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2296 cp
= (unsigned char *) &sin
->sin_addr
;
2302 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2303 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2304 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2305 address
= Fmake_vector (make_number (len
), Qnil
);
2306 p
= XVECTOR (address
);
2307 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2308 for (i
= 0; i
< len
; i
++)
2309 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2313 #ifdef HAVE_LOCAL_SOCKETS
2316 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2317 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2318 /* If the first byte is NUL, the name is a Linux abstract
2319 socket name, and the name can contain embedded NULs. If
2320 it's not, we have a NUL-terminated string. Be careful not
2321 to walk past the end of the object looking for the name
2322 terminator, however. */
2323 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2325 const char *terminator
2326 = memchr (sockun
->sun_path
, '\0', name_length
);
2329 name_length
= terminator
- (const char *) sockun
->sun_path
;
2332 return make_unibyte_string (sockun
->sun_path
, name_length
);
2336 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2337 address
= Fcons (make_number (sa
->sa_family
),
2338 Fmake_vector (make_number (len
), Qnil
));
2339 p
= XVECTOR (XCDR (address
));
2340 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2346 p
->contents
[i
++] = make_number (*cp
++);
2351 /* Convert an internal struct addrinfo to a Lisp object. */
2354 conv_addrinfo_to_lisp (struct addrinfo
*res
)
2356 Lisp_Object protocol
= make_number (res
->ai_protocol
);
2357 eassert (XINT (protocol
) == res
->ai_protocol
);
2358 return Fcons (protocol
, conv_sockaddr_to_lisp (res
->ai_addr
, res
->ai_addrlen
));
2362 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2365 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2367 struct Lisp_Vector
*p
;
2369 if (VECTORP (address
))
2371 p
= XVECTOR (address
);
2372 if (p
->header
.size
== 5)
2375 return sizeof (struct sockaddr_in
);
2378 else if (p
->header
.size
== 9)
2380 *familyp
= AF_INET6
;
2381 return sizeof (struct sockaddr_in6
);
2385 #ifdef HAVE_LOCAL_SOCKETS
2386 else if (STRINGP (address
))
2388 *familyp
= AF_LOCAL
;
2389 return sizeof (struct sockaddr_un
);
2392 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2393 && VECTORP (XCDR (address
)))
2395 struct sockaddr
*sa
;
2396 p
= XVECTOR (XCDR (address
));
2397 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2399 *familyp
= XINT (XCAR (address
));
2400 return p
->header
.size
+ sizeof (sa
->sa_family
);
2405 /* Convert an address object (vector or string) to an internal sockaddr.
2407 The address format has been basically validated by
2408 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2409 it could have come from user data. So if FAMILY is not valid,
2410 we return after zeroing *SA. */
2413 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2415 register struct Lisp_Vector
*p
;
2416 register unsigned char *cp
= NULL
;
2420 memset (sa
, 0, len
);
2422 if (VECTORP (address
))
2424 p
= XVECTOR (address
);
2425 if (family
== AF_INET
)
2427 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2428 len
= sizeof (sin
->sin_addr
) + 1;
2429 hostport
= XINT (p
->contents
[--len
]);
2430 sin
->sin_port
= htons (hostport
);
2431 cp
= (unsigned char *)&sin
->sin_addr
;
2432 sa
->sa_family
= family
;
2435 else if (family
== AF_INET6
)
2437 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2438 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2439 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2440 hostport
= XINT (p
->contents
[--len
]);
2441 sin6
->sin6_port
= htons (hostport
);
2442 for (i
= 0; i
< len
; i
++)
2443 if (INTEGERP (p
->contents
[i
]))
2445 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2448 sa
->sa_family
= family
;
2455 else if (STRINGP (address
))
2457 #ifdef HAVE_LOCAL_SOCKETS
2458 if (family
== AF_LOCAL
)
2460 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2461 cp
= SDATA (address
);
2462 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2463 sockun
->sun_path
[i
] = *cp
++;
2464 sa
->sa_family
= family
;
2471 p
= XVECTOR (XCDR (address
));
2472 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2475 for (i
= 0; i
< len
; i
++)
2476 if (INTEGERP (p
->contents
[i
]))
2477 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2480 #ifdef DATAGRAM_SOCKETS
2481 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2483 doc
: /* Get the current datagram address associated with PROCESS.
2484 If PROCESS is a non-blocking network process that hasn't been fully
2485 set up yet, this function will block until socket setup has completed. */)
2486 (Lisp_Object process
)
2490 CHECK_PROCESS (process
);
2492 if (NETCONN_P (process
))
2493 wait_for_socket_fds (process
, "process-datagram-address");
2495 if (!DATAGRAM_CONN_P (process
))
2498 channel
= XPROCESS (process
)->infd
;
2499 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2500 datagram_address
[channel
].len
);
2503 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2505 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2506 Return nil upon error setting address, ADDRESS otherwise.
2508 If PROCESS is a non-blocking network process that hasn't been fully
2509 set up yet, this function will block until socket setup has completed. */)
2510 (Lisp_Object process
, Lisp_Object address
)
2516 CHECK_PROCESS (process
);
2518 if (NETCONN_P (process
))
2519 wait_for_socket_fds (process
, "set-process-datagram-address");
2521 if (!DATAGRAM_CONN_P (process
))
2524 channel
= XPROCESS (process
)->infd
;
2526 len
= get_lisp_to_sockaddr_size (address
, &family
);
2527 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2529 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2535 static const struct socket_options
{
2536 /* The name of this option. Should be lowercase version of option
2537 name without SO_ prefix. */
2539 /* Option level SOL_... */
2541 /* Option number SO_... */
2543 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2544 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2545 } socket_options
[] =
2547 #ifdef SO_BINDTODEVICE
2548 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2551 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2554 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2557 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2560 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2563 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2566 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2569 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2571 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2574 /* Set option OPT to value VAL on socket S.
2576 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2577 Signals an error if setting a known option fails.
2581 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2584 const struct socket_options
*sopt
;
2589 name
= SSDATA (SYMBOL_NAME (opt
));
2590 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2591 if (strcmp (name
, sopt
->name
) == 0)
2594 switch (sopt
->opttype
)
2599 optval
= NILP (val
) ? 0 : 1;
2600 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2601 &optval
, sizeof (optval
));
2608 if (TYPE_RANGED_INTEGERP (int, val
))
2609 optval
= XINT (val
);
2611 error ("Bad option value for %s", name
);
2612 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2613 &optval
, sizeof (optval
));
2617 #ifdef SO_BINDTODEVICE
2620 char devname
[IFNAMSIZ
+ 1];
2622 /* This is broken, at least in the Linux 2.4 kernel.
2623 To unbind, the arg must be a zero integer, not the empty string.
2624 This should work on all systems. KFS. 2003-09-23. */
2625 memset (devname
, 0, sizeof devname
);
2628 char *arg
= SSDATA (val
);
2629 int len
= min (strlen (arg
), IFNAMSIZ
);
2630 memcpy (devname
, arg
, len
);
2632 else if (!NILP (val
))
2633 error ("Bad option value for %s", name
);
2634 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2643 struct linger linger
;
2646 linger
.l_linger
= 0;
2647 if (TYPE_RANGED_INTEGERP (int, val
))
2648 linger
.l_linger
= XINT (val
);
2650 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2651 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2652 &linger
, sizeof (linger
));
2663 int setsockopt_errno
= errno
;
2664 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2668 return (1 << sopt
->optbit
);
2672 DEFUN ("set-network-process-option",
2673 Fset_network_process_option
, Sset_network_process_option
,
2675 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2676 See `make-network-process' for a list of options and values.
2677 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2678 OPTION is not a supported option, return nil instead; otherwise return t.
2680 If PROCESS is a non-blocking network process that hasn't been fully
2681 set up yet, this function will block until socket setup has completed. */)
2682 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2685 struct Lisp_Process
*p
;
2687 CHECK_PROCESS (process
);
2688 p
= XPROCESS (process
);
2689 if (!NETCONN1_P (p
))
2690 error ("Process is not a network process");
2692 wait_for_socket_fds (process
, "set-network-process-option");
2696 error ("Process is not running");
2698 if (set_socket_option (s
, option
, value
))
2700 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2704 if (NILP (no_error
))
2705 error ("Unknown or unsupported option");
2711 DEFUN ("serial-process-configure",
2712 Fserial_process_configure
,
2713 Sserial_process_configure
,
2715 doc
: /* Configure speed, bytesize, etc. of a serial process.
2717 Arguments are specified as keyword/argument pairs. Attributes that
2718 are not given are re-initialized from the process's current
2719 configuration (available via the function `process-contact') or set to
2720 reasonable default values. The following arguments are defined:
2726 -- Any of these arguments can be given to identify the process that is
2727 to be configured. If none of these arguments is given, the current
2728 buffer's process is used.
2730 :speed SPEED -- SPEED is the speed of the serial port in bits per
2731 second, also called baud rate. Any value can be given for SPEED, but
2732 most serial ports work only at a few defined values between 1200 and
2733 115200, with 9600 being the most common value. If SPEED is nil, the
2734 serial port is not configured any further, i.e., all other arguments
2735 are ignored. This may be useful for special serial ports such as
2736 Bluetooth-to-serial converters which can only be configured through AT
2737 commands. A value of nil for SPEED can be used only when passed
2738 through `make-serial-process' or `serial-term'.
2740 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2741 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2743 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2744 `odd' (use odd parity), or the symbol `even' (use even parity). If
2745 PARITY is not given, no parity is used.
2747 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2748 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2749 is not given or nil, 1 stopbit is used.
2751 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2752 flowcontrol to be used, which is either nil (don't use flowcontrol),
2753 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2754 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2755 flowcontrol is used.
2757 `serial-process-configure' is called by `make-serial-process' for the
2758 initial configuration of the serial port.
2762 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2764 \(serial-process-configure
2765 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2767 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2769 usage: (serial-process-configure &rest ARGS) */)
2770 (ptrdiff_t nargs
, Lisp_Object
*args
)
2772 struct Lisp_Process
*p
;
2773 Lisp_Object contact
= Qnil
;
2774 Lisp_Object proc
= Qnil
;
2776 contact
= Flist (nargs
, args
);
2778 proc
= Fplist_get (contact
, QCprocess
);
2780 proc
= Fplist_get (contact
, QCname
);
2782 proc
= Fplist_get (contact
, QCbuffer
);
2784 proc
= Fplist_get (contact
, QCport
);
2785 proc
= get_process (proc
);
2786 p
= XPROCESS (proc
);
2787 if (!EQ (p
->type
, Qserial
))
2788 error ("Not a serial process");
2790 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2793 serial_configure (p
, contact
);
2797 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2799 doc
: /* Create and return a serial port process.
2801 In Emacs, serial port connections are represented by process objects,
2802 so input and output work as for subprocesses, and `delete-process'
2803 closes a serial port connection. However, a serial process has no
2804 process id, it cannot be signaled, and the status codes are different
2805 from normal processes.
2807 `make-serial-process' creates a process and a buffer, on which you
2808 probably want to use `process-send-string'. Try \\[serial-term] for
2809 an interactive terminal. See below for examples.
2811 Arguments are specified as keyword/argument pairs. The following
2812 arguments are defined:
2814 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2815 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2816 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2817 the backslashes in strings).
2819 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2820 which this function calls.
2822 :name NAME -- NAME is the name of the process. If NAME is not given,
2823 the value of PORT is used.
2825 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2826 with the process. Process output goes at the end of that buffer,
2827 unless you specify an output stream or filter function to handle the
2828 output. If BUFFER is not given, the value of NAME is used.
2830 :coding CODING -- If CODING is a symbol, it specifies the coding
2831 system used for both reading and writing for this process. If CODING
2832 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2833 ENCODING is used for writing.
2835 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2836 the process is running. If BOOL is not given, query before exiting.
2838 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2839 In the stopped state, a serial process does not accept incoming data,
2840 but you can send outgoing data. The stopped state is cleared by
2841 `continue-process' and set by `stop-process'.
2843 :filter FILTER -- Install FILTER as the process filter.
2845 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2847 :plist PLIST -- Install PLIST as the initial plist of the process.
2853 -- This function calls `serial-process-configure' to handle these
2856 The original argument list, possibly modified by later configuration,
2857 is available via the function `process-contact'.
2861 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2863 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2865 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2867 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2869 usage: (make-serial-process &rest ARGS) */)
2870 (ptrdiff_t nargs
, Lisp_Object
*args
)
2873 Lisp_Object proc
, contact
, port
;
2874 struct Lisp_Process
*p
;
2875 Lisp_Object name
, buffer
;
2876 Lisp_Object tem
, val
;
2877 ptrdiff_t specpdl_count
;
2882 contact
= Flist (nargs
, args
);
2884 port
= Fplist_get (contact
, QCport
);
2886 error ("No port specified");
2887 CHECK_STRING (port
);
2889 if (NILP (Fplist_member (contact
, QCspeed
)))
2890 error (":speed not specified");
2891 if (!NILP (Fplist_get (contact
, QCspeed
)))
2892 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2894 name
= Fplist_get (contact
, QCname
);
2897 CHECK_STRING (name
);
2898 proc
= make_process (name
);
2899 specpdl_count
= SPECPDL_INDEX ();
2900 record_unwind_protect (remove_process
, proc
);
2901 p
= XPROCESS (proc
);
2903 fd
= serial_open (port
);
2904 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2907 if (fd
> max_process_desc
)
2908 max_process_desc
= fd
;
2909 chan_process
[fd
] = proc
;
2911 buffer
= Fplist_get (contact
, QCbuffer
);
2914 buffer
= Fget_buffer_create (buffer
);
2915 pset_buffer (p
, buffer
);
2917 pset_childp (p
, contact
);
2918 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2919 pset_type (p
, Qserial
);
2920 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2921 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2922 eassert (NILP (p
->log
));
2923 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2924 p
->kill_without_query
= 1;
2925 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2926 pset_command (p
, Qt
);
2927 eassert (! p
->pty_flag
);
2929 if (!EQ (p
->command
, Qt
))
2931 FD_SET (fd
, &input_wait_mask
);
2932 FD_SET (fd
, &non_keyboard_wait_mask
);
2935 if (BUFFERP (buffer
))
2937 set_marker_both (p
->mark
, buffer
,
2938 BUF_ZV (XBUFFER (buffer
)),
2939 BUF_ZV_BYTE (XBUFFER (buffer
)));
2942 tem
= Fplist_member (contact
, QCcoding
);
2943 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2949 val
= XCAR (XCDR (tem
));
2953 else if (!NILP (Vcoding_system_for_read
))
2954 val
= Vcoding_system_for_read
;
2955 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2956 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2958 pset_decode_coding_system (p
, val
);
2963 val
= XCAR (XCDR (tem
));
2967 else if (!NILP (Vcoding_system_for_write
))
2968 val
= Vcoding_system_for_write
;
2969 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2970 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2972 pset_encode_coding_system (p
, val
);
2974 setup_process_coding_systems (proc
);
2975 pset_decoding_buf (p
, empty_unibyte_string
);
2976 eassert (p
->decoding_carryover
== 0);
2977 pset_encoding_buf (p
, empty_unibyte_string
);
2978 p
->inherit_coding_system_flag
2979 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2981 Fserial_process_configure (nargs
, args
);
2983 specpdl_ptr
= specpdl
+ specpdl_count
;
2989 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2990 Lisp_Object service
, Lisp_Object name
)
2993 struct Lisp_Process
*p
= XPROCESS (proc
);
2994 Lisp_Object contact
= p
->childp
;
2995 Lisp_Object coding_systems
= Qt
;
2998 tem
= Fplist_member (contact
, QCcoding
);
2999 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3000 tem
= Qnil
; /* No error message (too late!). */
3002 /* Setup coding systems for communicating with the network stream. */
3003 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3007 val
= XCAR (XCDR (tem
));
3011 else if (!NILP (Vcoding_system_for_read
))
3012 val
= Vcoding_system_for_read
;
3013 else if ((!NILP (p
->buffer
)
3014 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3015 || (NILP (p
->buffer
)
3016 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3017 /* We dare not decode end-of-line format by setting VAL to
3018 Qraw_text, because the existing Emacs Lisp libraries
3019 assume that they receive bare code including a sequence of
3024 if (NILP (host
) || NILP (service
))
3025 coding_systems
= Qnil
;
3027 coding_systems
= CALLN (Ffind_operation_coding_system
,
3028 Qopen_network_stream
, name
, p
->buffer
,
3030 if (CONSP (coding_systems
))
3031 val
= XCAR (coding_systems
);
3032 else if (CONSP (Vdefault_process_coding_system
))
3033 val
= XCAR (Vdefault_process_coding_system
);
3037 pset_decode_coding_system (p
, val
);
3041 val
= XCAR (XCDR (tem
));
3045 else if (!NILP (Vcoding_system_for_write
))
3046 val
= Vcoding_system_for_write
;
3047 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3051 if (EQ (coding_systems
, Qt
))
3053 if (NILP (host
) || NILP (service
))
3054 coding_systems
= Qnil
;
3056 coding_systems
= CALLN (Ffind_operation_coding_system
,
3057 Qopen_network_stream
, name
, p
->buffer
,
3060 if (CONSP (coding_systems
))
3061 val
= XCDR (coding_systems
);
3062 else if (CONSP (Vdefault_process_coding_system
))
3063 val
= XCDR (Vdefault_process_coding_system
);
3067 pset_encode_coding_system (p
, val
);
3069 pset_decoding_buf (p
, empty_unibyte_string
);
3070 p
->decoding_carryover
= 0;
3071 pset_encoding_buf (p
, empty_unibyte_string
);
3073 p
->inherit_coding_system_flag
3074 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3079 finish_after_tls_connection (Lisp_Object proc
)
3081 struct Lisp_Process
*p
= XPROCESS (proc
);
3082 Lisp_Object contact
= p
->childp
;
3083 Lisp_Object result
= Qt
;
3085 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3086 result
= call3 (Qnsm_verify_connection
,
3088 Fplist_get (contact
, QChost
),
3089 Fplist_get (contact
, QCservice
));
3093 pset_status (p
, list2 (Qfailed
,
3094 build_string ("The Network Security Manager stopped the connections")));
3095 deactivate_process (proc
);
3099 /* If we cleared the connection wait mask before we did
3100 the TLS setup, then we have to say that the process
3101 is finally "open" here. */
3102 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3104 pset_status (p
, Qrun
);
3105 /* Execute the sentinel here. If we had relied on
3106 status_notify to do it later, it will read input
3107 from the process before calling the sentinel. */
3108 exec_sentinel (proc
, build_string ("open\n"));
3115 connect_network_socket (Lisp_Object proc
, Lisp_Object addrinfos
,
3116 Lisp_Object use_external_socket_p
)
3118 ptrdiff_t count
= SPECPDL_INDEX ();
3119 int s
= -1, outch
, inch
;
3122 struct sockaddr
*sa
= NULL
;
3125 struct Lisp_Process
*p
= XPROCESS (proc
);
3126 Lisp_Object contact
= p
->childp
;
3128 int socket_to_use
= -1;
3130 if (!NILP (use_external_socket_p
))
3132 socket_to_use
= external_sock_fd
;
3134 /* Ensure we don't consume the external socket twice. */
3135 external_sock_fd
= -1;
3138 /* Do this in case we never enter the while-loop below. */
3141 while (!NILP (addrinfos
))
3143 Lisp_Object addrinfo
= XCAR (addrinfos
);
3144 addrinfos
= XCDR (addrinfos
);
3145 int protocol
= XINT (XCAR (addrinfo
));
3146 Lisp_Object ip_address
= XCDR (addrinfo
);
3152 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3155 sa
= xmalloc (addrlen
);
3156 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3161 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3162 if (p
->is_non_blocking_client
)
3163 socktype
|= SOCK_NONBLOCK
;
3164 s
= socket (family
, socktype
, protocol
);
3172 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3174 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3180 if (0 <= socket_to_use
)
3186 #ifdef DATAGRAM_SOCKETS
3187 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3189 #endif /* DATAGRAM_SOCKETS */
3191 /* Make us close S if quit. */
3192 record_unwind_protect_int (close_file_unwind
, s
);
3194 /* Parse network options in the arg list. We simply ignore anything
3195 which isn't a known option (including other keywords). An error
3196 is signaled if setting a known option fails. */
3198 Lisp_Object params
= contact
, key
, val
;
3200 while (!NILP (params
))
3202 key
= XCAR (params
);
3203 params
= XCDR (params
);
3204 val
= XCAR (params
);
3205 params
= XCDR (params
);
3206 optbits
|= set_socket_option (s
, key
, val
);
3212 /* Configure as a server socket. */
3214 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3215 explicit :reuseaddr key to override this. */
3216 #ifdef HAVE_LOCAL_SOCKETS
3217 if (family
!= AF_LOCAL
)
3219 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3222 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3223 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3226 /* If passed a socket descriptor, it should be already bound. */
3227 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3228 report_file_error ("Cannot bind server socket", Qnil
);
3230 #ifdef HAVE_GETSOCKNAME
3233 struct sockaddr_in sa1
;
3234 socklen_t len1
= sizeof (sa1
);
3235 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3237 Lisp_Object service
;
3238 service
= make_number (ntohs (sa1
.sin_port
));
3239 contact
= Fplist_put (contact
, QCservice
, service
);
3240 /* Save the port number so that we can stash it in
3241 the process object later. */
3242 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3247 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3248 report_file_error ("Cannot listen on server socket", Qnil
);
3256 ret
= connect (s
, sa
, addrlen
);
3259 if (ret
== 0 || xerrno
== EISCONN
)
3261 /* The unwind-protect will be discarded afterwards.
3262 Likewise for immediate_quit. */
3266 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3270 if (xerrno
== EINTR
)
3272 /* Unlike most other syscalls connect() cannot be called
3273 again. (That would return EALREADY.) The proper way to
3274 wait for completion is pselect(). */
3282 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3288 report_file_error ("Failed select", Qnil
);
3292 len
= sizeof xerrno
;
3293 eassert (FD_ISSET (s
, &fdset
));
3294 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3295 report_file_error ("Failed getsockopt", Qnil
);
3298 if (NILP (addrinfos
))
3299 report_file_errno ("Failed connect", Qnil
, xerrno
);
3301 #endif /* !WINDOWSNT */
3305 /* Discard the unwind protect closing S. */
3306 specpdl_ptr
= specpdl
+ count
;
3309 if (0 <= socket_to_use
)
3313 if (xerrno
== EINTR
)
3320 #ifdef DATAGRAM_SOCKETS
3321 if (p
->socktype
== SOCK_DGRAM
)
3323 if (datagram_address
[s
].sa
)
3326 datagram_address
[s
].sa
= xmalloc (addrlen
);
3327 datagram_address
[s
].len
= addrlen
;
3331 memset (datagram_address
[s
].sa
, 0, addrlen
);
3332 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3335 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3336 if (rlen
!= 0 && rfamily
== family
3338 conv_lisp_to_sockaddr (rfamily
, remote
,
3339 datagram_address
[s
].sa
, rlen
);
3343 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3347 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3348 conv_sockaddr_to_lisp (sa
, addrlen
));
3349 #ifdef HAVE_GETSOCKNAME
3352 struct sockaddr_in sa1
;
3353 socklen_t len1
= sizeof (sa1
);
3354 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3355 contact
= Fplist_put (contact
, QClocal
,
3356 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3365 /* If non-blocking got this far - and failed - assume non-blocking is
3366 not supported after all. This is probably a wrong assumption, but
3367 the normal blocking calls to open-network-stream handles this error
3369 if (p
->is_non_blocking_client
)
3372 report_file_errno ((p
->is_server
3373 ? "make server process failed"
3374 : "make client process failed"),
3381 chan_process
[inch
] = proc
;
3383 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3385 p
= XPROCESS (proc
);
3386 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3390 /* Discard the unwind protect for closing S, if any. */
3391 specpdl_ptr
= specpdl
+ count
;
3393 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3394 pset_status (p
, Qlisten
);
3396 /* Make the process marker point into the process buffer (if any). */
3397 if (BUFFERP (p
->buffer
))
3398 set_marker_both (p
->mark
, p
->buffer
,
3399 BUF_ZV (XBUFFER (p
->buffer
)),
3400 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3402 if (p
->is_non_blocking_client
)
3404 /* We may get here if connect did succeed immediately. However,
3405 in that case, we still need to signal this like a non-blocking
3407 if (! (connecting_status (p
->status
)
3408 && EQ (XCDR (p
->status
), addrinfos
)))
3409 pset_status (p
, Fcons (Qconnect
, addrinfos
));
3410 if (!FD_ISSET (inch
, &connect_wait_mask
))
3412 FD_SET (inch
, &connect_wait_mask
);
3413 FD_SET (inch
, &write_mask
);
3414 num_pending_connects
++;
3418 /* A server may have a client filter setting of Qt, but it must
3419 still listen for incoming connects unless it is stopped. */
3420 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3421 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3423 FD_SET (inch
, &input_wait_mask
);
3424 FD_SET (inch
, &non_keyboard_wait_mask
);
3427 if (inch
> max_process_desc
)
3428 max_process_desc
= inch
;
3430 /* Set up the masks based on the process filter. */
3431 set_process_filter_masks (p
);
3433 setup_process_coding_systems (proc
);
3436 /* Continue the asynchronous connection. */
3437 if (!NILP (p
->gnutls_boot_parameters
))
3439 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3441 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3442 p
->gnutls_boot_parameters
= Qnil
;
3444 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3445 /* Run sentinels, etc. */
3446 finish_after_tls_connection (proc
);
3447 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3449 deactivate_process (proc
);
3451 pset_status (p
, list2 (Qfailed
,
3452 build_string ("TLS negotiation failed")));
3454 pset_status (p
, list2 (Qfailed
, boot
));
3461 /* Create a network stream/datagram client/server process. Treated
3462 exactly like a normal process when reading and writing. Primary
3463 differences are in status display and process deletion. A network
3464 connection has no PID; you cannot signal it. All you can do is
3465 stop/continue it and deactivate/close it via delete-process. */
3467 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3469 doc
: /* Create and return a network server or client process.
3471 In Emacs, network connections are represented by process objects, so
3472 input and output work as for subprocesses and `delete-process' closes
3473 a network connection. However, a network process has no process id,
3474 it cannot be signaled, and the status codes are different from normal
3477 Arguments are specified as keyword/argument pairs. The following
3478 arguments are defined:
3480 :name NAME -- NAME is name for process. It is modified if necessary
3483 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3484 with the process. Process output goes at end of that buffer, unless
3485 you specify an output stream or filter function to handle the output.
3486 BUFFER may be also nil, meaning that this process is not associated
3489 :host HOST -- HOST is name of the host to connect to, or its IP
3490 address. The symbol `local' specifies the local host. If specified
3491 for a server process, it must be a valid name or address for the local
3492 host, and only clients connecting to that address will be accepted.
3494 :service SERVICE -- SERVICE is name of the service desired, or an
3495 integer specifying a port number to connect to. If SERVICE is t,
3496 a random port number is selected for the server. A port number can
3497 be specified as an integer string, e.g., "80", as well as an integer.
3499 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3500 stream type connection, `datagram' creates a datagram type connection,
3501 `seqpacket' creates a reliable datagram connection.
3503 :family FAMILY -- FAMILY is the address (and protocol) family for the
3504 service specified by HOST and SERVICE. The default (nil) is to use
3505 whatever address family (IPv4 or IPv6) that is defined for the host
3506 and port number specified by HOST and SERVICE. Other address families
3508 local -- for a local (i.e. UNIX) address specified by SERVICE.
3509 ipv4 -- use IPv4 address family only.
3510 ipv6 -- use IPv6 address family only.
3512 :local ADDRESS -- ADDRESS is the local address used for the connection.
3513 This parameter is ignored when opening a client process. When specified
3514 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3516 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3517 connection. This parameter is ignored when opening a stream server
3518 process. For a datagram server process, it specifies the initial
3519 setting of the remote datagram address. When specified for a client
3520 process, the FAMILY, HOST, and SERVICE args are ignored.
3522 The format of ADDRESS depends on the address family:
3523 - An IPv4 address is represented as an vector of integers [A B C D P]
3524 corresponding to numeric IP address A.B.C.D and port number P.
3525 - A local address is represented as a string with the address in the
3526 local address space.
3527 - An "unsupported family" address is represented by a cons (F . AV)
3528 where F is the family number and AV is a vector containing the socket
3529 address data with one element per address data byte. Do not rely on
3530 this format in portable code, as it may depend on implementation
3531 defined constants, data sizes, and data structure alignment.
3533 :coding CODING -- If CODING is a symbol, it specifies the coding
3534 system used for both reading and writing for this process. If CODING
3535 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3536 ENCODING is used for writing.
3538 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3539 process, return without waiting for the connection to complete;
3540 instead, the sentinel function will be called with second arg matching
3541 "open" (if successful) or "failed" when the connect completes.
3542 Default is to use a blocking connect (i.e. wait) for stream type
3545 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3546 running when Emacs is exited.
3548 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3549 In the stopped state, a server process does not accept new
3550 connections, and a client process does not handle incoming traffic.
3551 The stopped state is cleared by `continue-process' and set by
3554 :filter FILTER -- Install FILTER as the process filter.
3556 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3557 process filter are multibyte, otherwise they are unibyte.
3558 If this keyword is not specified, the strings are multibyte if
3559 the default value of `enable-multibyte-characters' is non-nil.
3561 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3563 :log LOG -- Install LOG as the server process log function. This
3564 function is called when the server accepts a network connection from a
3565 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3566 is the server process, CLIENT is the new process for the connection,
3567 and MESSAGE is a string.
3569 :plist PLIST -- Install PLIST as the new process's initial plist.
3571 :tls-parameters LIST -- is a list that should be supplied if you're
3572 opening a TLS connection. The first element is the TLS type (either
3573 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3574 be a keyword list accepted by gnutls-boot (as returned by
3575 `gnutls-boot-parameters').
3577 :server QLEN -- if QLEN is non-nil, create a server process for the
3578 specified FAMILY, SERVICE, and connection type (stream or datagram).
3579 If QLEN is an integer, it is used as the max. length of the server's
3580 pending connection queue (also known as the backlog); the default
3581 queue length is 5. Default is to create a client process.
3583 The following network options can be specified for this connection:
3585 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3586 :dontroute BOOL -- Only send to directly connected hosts.
3587 :keepalive BOOL -- Send keep-alive messages on network stream.
3588 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3589 :oobinline BOOL -- Place out-of-band data in receive data stream.
3590 :priority INT -- Set protocol defined priority for sent packets.
3591 :reuseaddr BOOL -- Allow reusing a recently used local address
3592 (this is allowed by default for a server process).
3593 :bindtodevice NAME -- bind to interface NAME. Using this may require
3594 special privileges on some systems.
3595 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3596 been passed to Emacs. If Emacs wasn't
3597 passed a socket, this option is silently
3601 Consult the relevant system programmer's manual pages for more
3602 information on using these options.
3605 A server process will listen for and accept connections from clients.
3606 When a client connection is accepted, a new network process is created
3607 for the connection with the following parameters:
3609 - The client's process name is constructed by concatenating the server
3610 process's NAME and a client identification string.
3611 - If the FILTER argument is non-nil, the client process will not get a
3612 separate process buffer; otherwise, the client's process buffer is a newly
3613 created buffer named after the server process's BUFFER name or process
3614 NAME concatenated with the client identification string.
3615 - The connection type and the process filter and sentinel parameters are
3616 inherited from the server process's TYPE, FILTER and SENTINEL.
3617 - The client process's contact info is set according to the client's
3618 addressing information (typically an IP address and a port number).
3619 - The client process's plist is initialized from the server's plist.
3621 Notice that the FILTER and SENTINEL args are never used directly by
3622 the server process. Also, the BUFFER argument is not used directly by
3623 the server process, but via the optional :log function, accepted (and
3624 failed) connections may be logged in the server process's buffer.
3626 The original argument list, modified with the actual connection
3627 information, is available via the `process-contact' function.
3629 usage: (make-network-process &rest ARGS) */)
3630 (ptrdiff_t nargs
, Lisp_Object
*args
)
3633 Lisp_Object contact
;
3634 struct Lisp_Process
*p
;
3635 const char *portstring
;
3636 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3637 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3638 #ifdef HAVE_LOCAL_SOCKETS
3639 struct sockaddr_un address_un
;
3643 Lisp_Object name
, buffer
, host
, service
, address
;
3644 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3645 Lisp_Object addrinfos
= Qnil
;
3648 enum { any_protocol
= 0 };
3649 #ifdef HAVE_GETADDRINFO_A
3650 struct gaicb
*dns_request
= NULL
;
3652 ptrdiff_t count
= SPECPDL_INDEX ();
3657 /* Save arguments for process-contact and clone-process. */
3658 contact
= Flist (nargs
, args
);
3661 /* Ensure socket support is loaded if available. */
3662 init_winsock (TRUE
);
3665 /* :type TYPE (nil: stream, datagram */
3666 tem
= Fplist_get (contact
, QCtype
);
3668 socktype
= SOCK_STREAM
;
3669 #ifdef DATAGRAM_SOCKETS
3670 else if (EQ (tem
, Qdatagram
))
3671 socktype
= SOCK_DGRAM
;
3673 #ifdef HAVE_SEQPACKET
3674 else if (EQ (tem
, Qseqpacket
))
3675 socktype
= SOCK_SEQPACKET
;
3678 error ("Unsupported connection type");
3680 name
= Fplist_get (contact
, QCname
);
3681 buffer
= Fplist_get (contact
, QCbuffer
);
3682 filter
= Fplist_get (contact
, QCfilter
);
3683 sentinel
= Fplist_get (contact
, QCsentinel
);
3684 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3686 CHECK_STRING (name
);
3688 /* :local ADDRESS or :remote ADDRESS */
3689 tem
= Fplist_get (contact
, QCserver
);
3691 address
= Fplist_get (contact
, QCremote
);
3693 address
= Fplist_get (contact
, QClocal
);
3694 if (!NILP (address
))
3696 host
= service
= Qnil
;
3698 if (!get_lisp_to_sockaddr_size (address
, &family
))
3699 error ("Malformed :address");
3701 addrinfos
= list1 (Fcons (make_number (any_protocol
), address
));
3705 /* :family FAMILY -- nil (for Inet), local, or integer. */
3706 tem
= Fplist_get (contact
, QCfamily
);
3715 #ifdef HAVE_LOCAL_SOCKETS
3716 else if (EQ (tem
, Qlocal
))
3720 else if (EQ (tem
, Qipv6
))
3723 else if (EQ (tem
, Qipv4
))
3725 else if (TYPE_RANGED_INTEGERP (int, tem
))
3726 family
= XINT (tem
);
3728 error ("Unknown address family");
3730 /* :service SERVICE -- string, integer (port number), or t (random port). */
3731 service
= Fplist_get (contact
, QCservice
);
3733 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3734 host
= Fplist_get (contact
, QChost
);
3737 /* The "connection" function gets it bind info from the address we're
3738 given, so use this dummy address if nothing is specified. */
3739 #ifdef HAVE_LOCAL_SOCKETS
3740 if (family
!= AF_LOCAL
)
3742 host
= build_string ("127.0.0.1");
3746 if (EQ (host
, Qlocal
))
3747 /* Depending on setup, "localhost" may map to different IPv4 and/or
3748 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3749 host
= build_string ("127.0.0.1");
3750 CHECK_STRING (host
);
3753 #ifdef HAVE_LOCAL_SOCKETS
3754 if (family
== AF_LOCAL
)
3758 message (":family local ignores the :host property");
3759 contact
= Fplist_put (contact
, QChost
, Qnil
);
3762 CHECK_STRING (service
);
3763 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3764 error ("Service name too long");
3765 addrinfos
= list1 (Fcons (make_number (any_protocol
), service
));
3770 /* Slow down polling to every ten seconds.
3771 Some kernels have a bug which causes retrying connect to fail
3772 after a connect. Polling can interfere with gethostbyname too. */
3773 #ifdef POLL_FOR_INPUT
3774 if (socktype
!= SOCK_DGRAM
)
3776 record_unwind_protect_void (run_all_atimers
);
3777 bind_polling_period (10);
3783 /* SERVICE can either be a string or int.
3784 Convert to a C string for later use by getaddrinfo. */
3785 if (EQ (service
, Qt
))
3790 else if (INTEGERP (service
))
3792 portstring
= portbuf
;
3793 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3797 CHECK_STRING (service
);
3798 portstring
= SSDATA (service
);
3799 portstringlen
= SBYTES (service
);
3803 #ifdef HAVE_GETADDRINFO_A
3804 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3806 ptrdiff_t hostlen
= SBYTES (host
);
3810 struct addrinfo hints
;
3811 char str
[FLEXIBLE_ARRAY_MEMBER
];
3812 } *req
= xmalloc (FLEXSIZEOF (struct req
, str
,
3813 hostlen
+ 1 + portstringlen
+ 1));
3814 dns_request
= &req
->gaicb
;
3815 dns_request
->ar_name
= req
->str
;
3816 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3817 dns_request
->ar_request
= &req
->hints
;
3818 dns_request
->ar_result
= NULL
;
3819 memset (&req
->hints
, 0, sizeof req
->hints
);
3820 req
->hints
.ai_family
= family
;
3821 req
->hints
.ai_socktype
= socktype
;
3822 strcpy (req
->str
, SSDATA (host
));
3823 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3825 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3827 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3831 #endif /* HAVE_GETADDRINFO_A */
3833 /* If we have a host, use getaddrinfo to resolve both host and service.
3834 Otherwise, use getservbyname to lookup the service. */
3838 struct addrinfo
*res
, *lres
;
3844 struct addrinfo hints
;
3845 memset (&hints
, 0, sizeof hints
);
3846 hints
.ai_family
= family
;
3847 hints
.ai_socktype
= socktype
;
3849 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3851 #ifdef HAVE_GAI_STRERROR
3853 synchronize_system_messages_locale ();
3854 char const *str
= gai_strerror (ret
);
3855 if (! NILP (Vlocale_coding_system
))
3856 str
= SSDATA (code_convert_string_norecord
3857 (build_string (str
), Vlocale_coding_system
, 0));
3858 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3861 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3865 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3866 addrinfos
= Fcons (conv_addrinfo_to_lisp (lres
), addrinfos
);
3868 addrinfos
= Fnreverse (addrinfos
);
3875 /* No hostname has been specified (e.g., a local server process). */
3877 if (EQ (service
, Qt
))
3879 else if (INTEGERP (service
))
3880 port
= XINT (service
);
3883 CHECK_STRING (service
);
3886 if (SBYTES (service
) != 0)
3888 /* Allow the service to be a string containing the port number,
3889 because that's allowed if you have getaddrbyname. */
3891 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3892 if (service_end
== SSDATA (service
) + SBYTES (service
))
3896 struct servent
*svc_info
3897 = getservbyname (SSDATA (service
),
3898 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3900 port
= ntohs (svc_info
->s_port
);
3905 if (! (0 <= port
&& port
< 1 << 16))
3907 AUTO_STRING (unknown_service
, "Unknown service: %s");
3908 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3914 buffer
= Fget_buffer_create (buffer
);
3916 /* Unwind bind_polling_period. */
3917 unbind_to (count
, Qnil
);
3919 proc
= make_process (name
);
3920 record_unwind_protect (remove_process
, proc
);
3921 p
= XPROCESS (proc
);
3922 pset_childp (p
, contact
);
3923 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3924 pset_type (p
, Qnetwork
);
3926 pset_buffer (p
, buffer
);
3927 pset_sentinel (p
, sentinel
);
3928 pset_filter (p
, filter
);
3929 pset_log (p
, Fplist_get (contact
, QClog
));
3930 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3931 p
->kill_without_query
= 1;
3932 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3933 pset_command (p
, Qt
);
3934 eassert (p
->pid
== 0);
3936 eassert (! p
->is_non_blocking_client
);
3937 eassert (! p
->is_server
);
3939 p
->socktype
= socktype
;
3940 #ifdef HAVE_GETADDRINFO_A
3941 eassert (! p
->dns_request
);
3944 tem
= Fplist_get (contact
, QCtls_parameters
);
3946 p
->gnutls_boot_parameters
= tem
;
3949 set_network_socket_coding_system (proc
, host
, service
, name
);
3952 tem
= Fplist_get (contact
, QCserver
);
3955 /* Don't support network sockets when non-blocking mode is
3956 not available, since a blocked Emacs is not useful. */
3957 p
->is_server
= true;
3958 if (TYPE_RANGED_INTEGERP (int, tem
))
3959 p
->backlog
= XINT (tem
);
3963 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3964 && !NILP (Fplist_get (contact
, QCnowait
)))
3965 p
->is_non_blocking_client
= true;
3967 bool postpone_connection
= false;
3968 #ifdef HAVE_GETADDRINFO_A
3969 /* With async address resolution, the list of addresses is empty, so
3970 postpone connecting to the server. */
3971 if (!p
->is_server
&& NILP (addrinfos
))
3973 p
->dns_request
= dns_request
;
3974 p
->status
= list1 (Qconnect
);
3975 postpone_connection
= true;
3978 if (! postpone_connection
)
3979 connect_network_socket (proc
, addrinfos
, use_external_socket_p
);
3981 specpdl_ptr
= specpdl
+ count
;
3986 #ifdef HAVE_NET_IF_H
3990 network_interface_list (void)
3992 struct ifconf ifconf
;
3993 struct ifreq
*ifreq
;
3995 ptrdiff_t buf_size
= 512;
4000 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4003 count
= SPECPDL_INDEX ();
4004 record_unwind_protect_int (close_file_unwind
, s
);
4008 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4009 ifconf
.ifc_buf
= buf
;
4010 ifconf
.ifc_len
= buf_size
;
4011 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4018 while (ifconf
.ifc_len
== buf_size
);
4020 res
= unbind_to (count
, Qnil
);
4021 ifreq
= ifconf
.ifc_req
;
4022 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4024 struct ifreq
*ifq
= ifreq
;
4025 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4026 #define SIZEOF_IFREQ(sif) \
4027 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4028 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4030 int len
= SIZEOF_IFREQ (ifq
);
4032 int len
= sizeof (*ifreq
);
4034 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4035 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4037 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4040 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4041 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4042 res
= Fcons (Fcons (build_string (namebuf
),
4043 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4044 sizeof (struct sockaddr
))),
4051 #endif /* SIOCGIFCONF */
4053 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4057 const char *flag_sym
;
4060 static const struct ifflag_def ifflag_table
[] = {
4064 #ifdef IFF_BROADCAST
4065 { IFF_BROADCAST
, "broadcast" },
4068 { IFF_DEBUG
, "debug" },
4071 { IFF_LOOPBACK
, "loopback" },
4073 #ifdef IFF_POINTOPOINT
4074 { IFF_POINTOPOINT
, "pointopoint" },
4077 { IFF_RUNNING
, "running" },
4080 { IFF_NOARP
, "noarp" },
4083 { IFF_PROMISC
, "promisc" },
4085 #ifdef IFF_NOTRAILERS
4086 #ifdef NS_IMPL_COCOA
4087 /* Really means smart, notrailers is obsolete. */
4088 { IFF_NOTRAILERS
, "smart" },
4090 { IFF_NOTRAILERS
, "notrailers" },
4094 { IFF_ALLMULTI
, "allmulti" },
4097 { IFF_MASTER
, "master" },
4100 { IFF_SLAVE
, "slave" },
4102 #ifdef IFF_MULTICAST
4103 { IFF_MULTICAST
, "multicast" },
4106 { IFF_PORTSEL
, "portsel" },
4108 #ifdef IFF_AUTOMEDIA
4109 { IFF_AUTOMEDIA
, "automedia" },
4112 { IFF_DYNAMIC
, "dynamic" },
4115 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4118 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4121 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4124 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4127 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4133 network_interface_info (Lisp_Object ifname
)
4136 Lisp_Object res
= Qnil
;
4141 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4142 && defined HAVE_GETIFADDRS && defined LLADDR)
4143 struct ifaddrs
*ifap
;
4146 CHECK_STRING (ifname
);
4148 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4149 error ("interface name too long");
4150 lispstpcpy (rq
.ifr_name
, ifname
);
4152 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4155 count
= SPECPDL_INDEX ();
4156 record_unwind_protect_int (close_file_unwind
, s
);
4159 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4160 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4162 int flags
= rq
.ifr_flags
;
4163 const struct ifflag_def
*fp
;
4166 /* If flags is smaller than int (i.e. short) it may have the high bit set
4167 due to IFF_MULTICAST. In that case, sign extending it into
4169 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4170 flags
= (unsigned short) rq
.ifr_flags
;
4173 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4175 if (flags
& fp
->flag_bit
)
4177 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4178 flags
-= fp
->flag_bit
;
4181 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4185 elt
= Fcons (make_number (fnum
), elt
);
4190 res
= Fcons (elt
, res
);
4193 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4194 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4196 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4197 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4201 for (n
= 0; n
< 6; n
++)
4202 p
->contents
[n
] = make_number (((unsigned char *)
4203 &rq
.ifr_hwaddr
.sa_data
[0])
4205 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4207 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4208 if (getifaddrs (&ifap
) != -1)
4210 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4211 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4214 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4216 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4217 unsigned char linkaddr
[6];
4220 if (it
->ifa_addr
->sa_family
!= AF_LINK
4221 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4222 || sdl
->sdl_alen
!= 6)
4225 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4226 for (n
= 0; n
< 6; n
++)
4227 p
->contents
[n
] = make_number (linkaddr
[n
]);
4229 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4233 #ifdef HAVE_FREEIFADDRS
4237 #endif /* HAVE_GETIFADDRS && LLADDR */
4239 res
= Fcons (elt
, res
);
4242 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4243 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4246 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4247 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4249 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4253 res
= Fcons (elt
, res
);
4256 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4257 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4260 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4263 res
= Fcons (elt
, res
);
4266 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4267 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4270 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4273 res
= Fcons (elt
, res
);
4275 return unbind_to (count
, any
? res
: Qnil
);
4277 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4278 #endif /* defined (HAVE_NET_IF_H) */
4280 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4281 Snetwork_interface_list
, 0, 0, 0,
4282 doc
: /* Return an alist of all network interfaces and their network address.
4283 Each element is a cons, the car of which is a string containing the
4284 interface name, and the cdr is the network address in internal
4285 format; see the description of ADDRESS in `make-network-process'.
4287 If the information is not available, return nil. */)
4290 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4291 return network_interface_list ();
4297 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4298 Snetwork_interface_info
, 1, 1, 0,
4299 doc
: /* Return information about network interface named IFNAME.
4300 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4301 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4302 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4303 FLAGS is the current flags of the interface.
4305 Data that is unavailable is returned as nil. */)
4306 (Lisp_Object ifname
)
4308 #if ((defined HAVE_NET_IF_H \
4309 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4310 || defined SIOCGIFFLAGS)) \
4311 || defined WINDOWSNT)
4312 return network_interface_info (ifname
);
4318 /* Turn off input and output for process PROC. */
4321 deactivate_process (Lisp_Object proc
)
4324 struct Lisp_Process
*p
= XPROCESS (proc
);
4328 /* Delete GnuTLS structures in PROC, if any. */
4329 emacs_gnutls_deinit (proc
);
4330 #endif /* HAVE_GNUTLS */
4332 if (p
->read_output_delay
> 0)
4334 if (--process_output_delay_count
< 0)
4335 process_output_delay_count
= 0;
4336 p
->read_output_delay
= 0;
4337 p
->read_output_skip
= 0;
4340 /* Beware SIGCHLD hereabouts. */
4342 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4343 close_process_fd (&p
->open_fd
[i
]);
4345 inchannel
= p
->infd
;
4350 #ifdef DATAGRAM_SOCKETS
4351 if (DATAGRAM_CHAN_P (inchannel
))
4353 xfree (datagram_address
[inchannel
].sa
);
4354 datagram_address
[inchannel
].sa
= 0;
4355 datagram_address
[inchannel
].len
= 0;
4358 chan_process
[inchannel
] = Qnil
;
4359 FD_CLR (inchannel
, &input_wait_mask
);
4360 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4361 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4363 FD_CLR (inchannel
, &connect_wait_mask
);
4364 FD_CLR (inchannel
, &write_mask
);
4365 if (--num_pending_connects
< 0)
4368 if (inchannel
== max_process_desc
)
4370 /* We just closed the highest-numbered process input descriptor,
4371 so recompute the highest-numbered one now. */
4375 while (0 <= i
&& NILP (chan_process
[i
]));
4377 max_process_desc
= i
;
4383 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4385 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4386 It is given to their filter functions.
4387 Optional argument PROCESS means do not return until output has been
4388 received from PROCESS.
4390 Optional second argument SECONDS and third argument MILLISEC
4391 specify a timeout; return after that much time even if there is
4392 no subprocess output. If SECONDS is a floating point number,
4393 it specifies a fractional number of seconds to wait.
4394 The MILLISEC argument is obsolete and should be avoided.
4396 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4397 from PROCESS only, suspending reading output from other processes.
4398 If JUST-THIS-ONE is an integer, don't run any timers either.
4399 Return non-nil if we received any output from PROCESS (or, if PROCESS
4400 is nil, from any process) before the timeout expired. */)
4401 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4406 if (! NILP (process
))
4407 CHECK_PROCESS (process
);
4409 just_this_one
= Qnil
;
4411 if (!NILP (millisec
))
4412 { /* Obsolete calling convention using integers rather than floats. */
4413 CHECK_NUMBER (millisec
);
4415 seconds
= make_float (XINT (millisec
) / 1000.0);
4418 CHECK_NUMBER (seconds
);
4419 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4426 if (!NILP (seconds
))
4428 if (INTEGERP (seconds
))
4430 if (XINT (seconds
) > 0)
4432 secs
= XINT (seconds
);
4436 else if (FLOATP (seconds
))
4438 if (XFLOAT_DATA (seconds
) > 0)
4440 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4441 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4446 wrong_type_argument (Qnumberp
, seconds
);
4448 else if (! NILP (process
))
4452 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4454 !NILP (process
) ? XPROCESS (process
) : NULL
,
4455 (NILP (just_this_one
) ? 0
4456 : !INTEGERP (just_this_one
) ? 1 : -1))
4461 /* Accept a connection for server process SERVER on CHANNEL. */
4463 static EMACS_INT connect_counter
= 0;
4466 server_accept_connection (Lisp_Object server
, int channel
)
4468 Lisp_Object proc
, caller
, name
, buffer
;
4469 Lisp_Object contact
, host
, service
;
4470 struct Lisp_Process
*ps
= XPROCESS (server
);
4471 struct Lisp_Process
*p
;
4475 struct sockaddr_in in
;
4477 struct sockaddr_in6 in6
;
4479 #ifdef HAVE_LOCAL_SOCKETS
4480 struct sockaddr_un un
;
4483 socklen_t len
= sizeof saddr
;
4486 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4491 if (!would_block (code
) && !NILP (ps
->log
))
4492 call3 (ps
->log
, server
, Qnil
,
4493 concat3 (build_string ("accept failed with code"),
4494 Fnumber_to_string (make_number (code
)),
4495 build_string ("\n")));
4499 count
= SPECPDL_INDEX ();
4500 record_unwind_protect_int (close_file_unwind
, s
);
4504 /* Setup a new process to handle the connection. */
4506 /* Generate a unique identification of the caller, and build contact
4507 information for this process. */
4510 switch (saddr
.sa
.sa_family
)
4514 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4516 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4517 host
= CALLN (Fformat
, ipv4_format
,
4518 make_number (ip
[0]), make_number (ip
[1]),
4519 make_number (ip
[2]), make_number (ip
[3]));
4520 service
= make_number (ntohs (saddr
.in
.sin_port
));
4521 AUTO_STRING (caller_format
, " <%s:%d>");
4522 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4529 Lisp_Object args
[9];
4530 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4533 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4534 args
[0] = ipv6_format
;
4535 for (i
= 0; i
< 8; i
++)
4536 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4537 host
= CALLMANY (Fformat
, args
);
4538 service
= make_number (ntohs (saddr
.in
.sin_port
));
4539 AUTO_STRING (caller_format
, " <[%s]:%d>");
4540 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4545 #ifdef HAVE_LOCAL_SOCKETS
4549 caller
= Fnumber_to_string (make_number (connect_counter
));
4550 AUTO_STRING (space_less_than
, " <");
4551 AUTO_STRING (greater_than
, ">");
4552 caller
= concat3 (space_less_than
, caller
, greater_than
);
4556 /* Create a new buffer name for this process if it doesn't have a
4557 filter. The new buffer name is based on the buffer name or
4558 process name of the server process concatenated with the caller
4561 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4562 || EQ (ps
->filter
, Qt
)))
4566 buffer
= ps
->buffer
;
4568 buffer
= Fbuffer_name (buffer
);
4573 buffer
= concat2 (buffer
, caller
);
4574 buffer
= Fget_buffer_create (buffer
);
4578 /* Generate a unique name for the new server process. Combine the
4579 server process name with the caller identification. */
4581 name
= concat2 (ps
->name
, caller
);
4582 proc
= make_process (name
);
4584 chan_process
[s
] = proc
;
4586 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4588 p
= XPROCESS (proc
);
4590 /* Build new contact information for this setup. */
4591 contact
= Fcopy_sequence (ps
->childp
);
4592 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4593 contact
= Fplist_put (contact
, QChost
, host
);
4594 if (!NILP (service
))
4595 contact
= Fplist_put (contact
, QCservice
, service
);
4596 contact
= Fplist_put (contact
, QCremote
,
4597 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4598 #ifdef HAVE_GETSOCKNAME
4600 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4601 contact
= Fplist_put (contact
, QClocal
,
4602 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4605 pset_childp (p
, contact
);
4606 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4607 pset_type (p
, Qnetwork
);
4609 pset_buffer (p
, buffer
);
4610 pset_sentinel (p
, ps
->sentinel
);
4611 pset_filter (p
, ps
->filter
);
4612 eassert (NILP (p
->command
));
4613 eassert (p
->pid
== 0);
4615 /* Discard the unwind protect for closing S. */
4616 specpdl_ptr
= specpdl
+ count
;
4618 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4621 pset_status (p
, Qrun
);
4623 /* Client processes for accepted connections are not stopped initially. */
4624 if (!EQ (p
->filter
, Qt
))
4626 FD_SET (s
, &input_wait_mask
);
4627 FD_SET (s
, &non_keyboard_wait_mask
);
4630 if (s
> max_process_desc
)
4631 max_process_desc
= s
;
4633 /* Setup coding system for new process based on server process.
4634 This seems to be the proper thing to do, as the coding system
4635 of the new process should reflect the settings at the time the
4636 server socket was opened; not the current settings. */
4638 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4639 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4640 setup_process_coding_systems (proc
);
4642 pset_decoding_buf (p
, empty_unibyte_string
);
4643 eassert (p
->decoding_carryover
== 0);
4644 pset_encoding_buf (p
, empty_unibyte_string
);
4646 p
->inherit_coding_system_flag
4647 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4649 AUTO_STRING (dash
, "-");
4650 AUTO_STRING (nl
, "\n");
4651 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4653 if (!NILP (ps
->log
))
4655 AUTO_STRING (accept_from
, "accept from ");
4656 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4659 AUTO_STRING (open_from
, "open from ");
4660 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4663 #ifdef HAVE_GETADDRINFO_A
4665 check_for_dns (Lisp_Object proc
)
4667 struct Lisp_Process
*p
= XPROCESS (proc
);
4668 Lisp_Object addrinfos
= Qnil
;
4671 if (! p
->dns_request
)
4674 int ret
= gai_error (p
->dns_request
);
4675 if (ret
== EAI_INPROGRESS
)
4678 /* We got a response. */
4681 struct addrinfo
*res
;
4683 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4684 addrinfos
= Fcons (conv_addrinfo_to_lisp (res
), addrinfos
);
4686 addrinfos
= Fnreverse (addrinfos
);
4688 /* The DNS lookup failed. */
4689 else if (connecting_status (p
->status
))
4691 deactivate_process (proc
);
4692 pset_status (p
, (list2
4694 concat3 (build_string ("Name lookup of "),
4695 build_string (p
->dns_request
->ar_name
),
4696 build_string (" failed")))));
4699 free_dns_request (proc
);
4701 /* This process should not already be connected (or killed). */
4702 if (! connecting_status (p
->status
))
4708 #endif /* HAVE_GETADDRINFO_A */
4711 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4713 while (XPROCESS (process
)->infd
< 0
4714 && connecting_status (XPROCESS (process
)->status
))
4716 add_to_log ("Waiting for socket from %s...", build_string (name
));
4717 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4722 wait_while_connecting (Lisp_Object process
)
4724 while (connecting_status (XPROCESS (process
)->status
))
4726 add_to_log ("Waiting for connection...");
4727 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4732 wait_for_tls_negotiation (Lisp_Object process
)
4735 while (XPROCESS (process
)->gnutls_p
4736 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4738 add_to_log ("Waiting for TLS...");
4739 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4744 /* This variable is different from waiting_for_input in keyboard.c.
4745 It is used to communicate to a lisp process-filter/sentinel (via the
4746 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4747 for user-input when that process-filter was called.
4748 waiting_for_input cannot be used as that is by definition 0 when
4749 lisp code is being evalled.
4750 This is also used in record_asynch_buffer_change.
4751 For that purpose, this must be 0
4752 when not inside wait_reading_process_output. */
4753 static int waiting_for_user_input_p
;
4756 wait_reading_process_output_unwind (int data
)
4758 waiting_for_user_input_p
= data
;
4761 /* This is here so breakpoints can be put on it. */
4763 wait_reading_process_output_1 (void)
4767 /* Read and dispose of subprocess output while waiting for timeout to
4768 elapse and/or keyboard input to be available.
4772 If negative, gobble data immediately available but don't wait for any.
4775 an additional duration to wait, measured in nanoseconds
4776 If TIME_LIMIT is zero, then:
4777 If NSECS == 0, there is no limit.
4778 If NSECS > 0, the timeout consists of NSECS only.
4779 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4782 0 to ignore keyboard input, or
4783 1 to return when input is available, or
4784 -1 meaning caller will actually read the input, so don't throw to
4785 the quit handler, or
4787 DO_DISPLAY means redisplay should be done to show subprocess
4788 output that arrives.
4790 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4791 (and gobble terminal input into the buffer if any arrives).
4793 If WAIT_PROC is specified, wait until something arrives from that
4796 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4797 (suspending output from other processes). A negative value
4798 means don't run any timers either.
4800 Return positive if we received input from WAIT_PROC (or from any
4801 process if WAIT_PROC is null), zero if we attempted to receive
4802 input but got none, and negative if we didn't even try. */
4805 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4807 Lisp_Object wait_for_cell
,
4808 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4818 struct timespec timeout
, end_time
, timer_delay
;
4819 struct timespec got_output_end_time
= invalid_timespec ();
4820 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4821 int got_some_output
= -1;
4822 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4823 bool retry_for_async
;
4825 ptrdiff_t count
= SPECPDL_INDEX ();
4827 /* Close to the current time if known, an invalid timespec otherwise. */
4828 struct timespec now
= invalid_timespec ();
4830 FD_ZERO (&Available
);
4833 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4834 && !(CONSP (wait_proc
->status
)
4835 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4836 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4838 record_unwind_protect_int (wait_reading_process_output_unwind
,
4839 waiting_for_user_input_p
);
4840 waiting_for_user_input_p
= read_kbd
;
4842 if (TYPE_MAXIMUM (time_t) < time_limit
)
4843 time_limit
= TYPE_MAXIMUM (time_t);
4845 if (time_limit
< 0 || nsecs
< 0)
4847 else if (time_limit
> 0 || nsecs
> 0)
4850 now
= current_timespec ();
4851 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4858 bool process_skipped
= false;
4860 /* If calling from keyboard input, do not quit
4861 since we want to return C-g as an input character.
4862 Otherwise, do pending quit if requested. */
4865 else if (pending_signals
)
4866 process_pending_signals ();
4868 /* Exit now if the cell we're waiting for became non-nil. */
4869 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4872 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4874 Lisp_Object process_list_head
, aproc
;
4875 struct Lisp_Process
*p
;
4877 retry_for_async
= false;
4878 FOR_EACH_PROCESS(process_list_head
, aproc
)
4880 p
= XPROCESS (aproc
);
4882 if (! wait_proc
|| p
== wait_proc
)
4884 #ifdef HAVE_GETADDRINFO_A
4885 /* Check for pending DNS requests. */
4888 Lisp_Object addrinfos
= check_for_dns (aproc
);
4889 if (!NILP (addrinfos
) && !EQ (addrinfos
, Qt
))
4890 connect_network_socket (aproc
, addrinfos
, Qnil
);
4892 retry_for_async
= true;
4896 /* Continue TLS negotiation. */
4897 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4898 && p
->is_non_blocking_client
)
4900 gnutls_try_handshake (p
);
4901 p
->gnutls_handshakes_tried
++;
4903 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4905 gnutls_verify_boot (aproc
, Qnil
);
4906 finish_after_tls_connection (aproc
);
4910 retry_for_async
= true;
4911 if (p
->gnutls_handshakes_tried
4912 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4914 deactivate_process (aproc
);
4915 pset_status (p
, list2 (Qfailed
,
4916 build_string ("TLS negotiation failed")));
4924 #endif /* GETADDRINFO_A or GNUTLS */
4926 /* Compute time from now till when time limit is up. */
4927 /* Exit if already run out. */
4928 if (wait
== TIMEOUT
)
4930 if (!timespec_valid_p (now
))
4931 now
= current_timespec ();
4932 if (timespec_cmp (end_time
, now
) <= 0)
4934 timeout
= timespec_sub (end_time
, now
);
4937 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4939 /* Normally we run timers here.
4940 But not if wait_for_cell; in those cases,
4941 the wait is supposed to be short,
4942 and those callers cannot handle running arbitrary Lisp code here. */
4943 if (NILP (wait_for_cell
)
4944 && just_wait_proc
>= 0)
4948 unsigned old_timers_run
= timers_run
;
4949 struct buffer
*old_buffer
= current_buffer
;
4950 Lisp_Object old_window
= selected_window
;
4952 timer_delay
= timer_check ();
4954 /* If a timer has run, this might have changed buffers
4955 an alike. Make read_key_sequence aware of that. */
4956 if (timers_run
!= old_timers_run
4957 && (old_buffer
!= current_buffer
4958 || !EQ (old_window
, selected_window
))
4959 && waiting_for_user_input_p
== -1)
4960 record_asynch_buffer_change ();
4962 if (timers_run
!= old_timers_run
&& do_display
)
4963 /* We must retry, since a timer may have requeued itself
4964 and that could alter the time_delay. */
4965 redisplay_preserve_echo_area (9);
4969 while (!detect_input_pending ());
4971 /* If there is unread keyboard input, also return. */
4973 && requeued_events_pending_p ())
4976 /* This is so a breakpoint can be put here. */
4977 if (!timespec_valid_p (timer_delay
))
4978 wait_reading_process_output_1 ();
4981 /* Cause C-g and alarm signals to take immediate action,
4982 and cause input available signals to zero out timeout.
4984 It is important that we do this before checking for process
4985 activity. If we get a SIGCHLD after the explicit checks for
4986 process activity, timeout is the only way we will know. */
4988 set_waiting_for_input (&timeout
);
4990 /* If status of something has changed, and no input is
4991 available, notify the user of the change right away. After
4992 this explicit check, we'll let the SIGCHLD handler zap
4993 timeout to get our attention. */
4994 if (update_tick
!= process_tick
)
4999 if (kbd_on_hold_p ())
5002 Atemp
= input_wait_mask
;
5005 timeout
= make_timespec (0, 0);
5006 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
5008 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5009 NULL
, &timeout
, NULL
)
5012 /* It's okay for us to do this and then continue with
5013 the loop, since timeout has already been zeroed out. */
5014 clear_waiting_for_input ();
5015 got_some_output
= status_notify (NULL
, wait_proc
);
5016 if (do_display
) redisplay_preserve_echo_area (13);
5020 /* Don't wait for output from a non-running process. Just
5021 read whatever data has already been received. */
5022 if (wait_proc
&& wait_proc
->raw_status_new
)
5023 update_status (wait_proc
);
5025 && ! EQ (wait_proc
->status
, Qrun
)
5026 && ! connecting_status (wait_proc
->status
))
5028 bool read_some_bytes
= false;
5030 clear_waiting_for_input ();
5032 /* If data can be read from the process, do so until exhausted. */
5033 if (wait_proc
->infd
>= 0)
5035 XSETPROCESS (proc
, wait_proc
);
5039 int nread
= read_process_output (proc
, wait_proc
->infd
);
5042 if (errno
== EIO
|| would_block (errno
))
5047 if (got_some_output
< nread
)
5048 got_some_output
= nread
;
5051 read_some_bytes
= true;
5056 if (read_some_bytes
&& do_display
)
5057 redisplay_preserve_echo_area (10);
5062 /* Wait till there is something to do. */
5064 if (wait_proc
&& just_wait_proc
)
5066 if (wait_proc
->infd
< 0) /* Terminated. */
5068 FD_SET (wait_proc
->infd
, &Available
);
5072 else if (!NILP (wait_for_cell
))
5074 Available
= non_process_wait_mask
;
5081 Available
= non_keyboard_wait_mask
;
5083 Available
= input_wait_mask
;
5084 Writeok
= write_mask
;
5085 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5089 /* If frame size has changed or the window is newly mapped,
5090 redisplay now, before we start to wait. There is a race
5091 condition here; if a SIGIO arrives between now and the select
5092 and indicates that a frame is trashed, the select may block
5093 displaying a trashed screen. */
5094 if (frame_garbaged
&& do_display
)
5096 clear_waiting_for_input ();
5097 redisplay_preserve_echo_area (11);
5099 set_waiting_for_input (&timeout
);
5102 /* Skip the `select' call if input is available and we're
5103 waiting for keyboard input or a cell change (which can be
5104 triggered by processing X events). In the latter case, set
5105 nfds to 1 to avoid breaking the loop. */
5107 if ((read_kbd
|| !NILP (wait_for_cell
))
5108 && detect_input_pending ())
5110 nfds
= read_kbd
? 0 : 1;
5112 FD_ZERO (&Available
);
5116 /* Set the timeout for adaptive read buffering if any
5117 process has non-zero read_output_skip and non-zero
5118 read_output_delay, and we are not reading output for a
5119 specific process. It is not executed if
5120 Vprocess_adaptive_read_buffering is nil. */
5121 if (process_output_skip
&& check_delay
> 0)
5123 int adaptive_nsecs
= timeout
.tv_nsec
;
5124 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5125 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5126 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5128 proc
= chan_process
[channel
];
5131 /* Find minimum non-zero read_output_delay among the
5132 processes with non-zero read_output_skip. */
5133 if (XPROCESS (proc
)->read_output_delay
> 0)
5136 if (!XPROCESS (proc
)->read_output_skip
)
5138 FD_CLR (channel
, &Available
);
5139 process_skipped
= true;
5140 XPROCESS (proc
)->read_output_skip
= 0;
5141 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5142 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5145 timeout
= make_timespec (0, adaptive_nsecs
);
5146 process_output_skip
= 0;
5149 /* If we've got some output and haven't limited our timeout
5150 with adaptive read buffering, limit it. */
5151 if (got_some_output
> 0 && !process_skipped
5153 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5154 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5157 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5158 && timespec_valid_p (timer_delay
)
5159 && timespec_cmp (timer_delay
, timeout
) < 0)
5161 if (!timespec_valid_p (now
))
5162 now
= current_timespec ();
5163 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5164 if (!timespec_valid_p (got_output_end_time
)
5165 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5166 got_output_end_time
= timeout_abs
;
5167 timeout
= timer_delay
;
5170 got_output_end_time
= invalid_timespec ();
5172 /* NOW can become inaccurate if time can pass during pselect. */
5173 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5174 now
= invalid_timespec ();
5176 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5178 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5181 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5185 #if defined (HAVE_NS)
5187 #elif defined (HAVE_GLIB)
5192 (max (max_process_desc
, max_input_desc
) + 1,
5194 (check_write
? &Writeok
: 0),
5195 NULL
, &timeout
, NULL
);
5198 /* GnuTLS buffers data internally. In lowat mode it leaves
5199 some data in the TCP buffers so that select works, but
5200 with custom pull/push functions we need to check if some
5201 data is available in the buffers manually. */
5204 fd_set tls_available
;
5207 FD_ZERO (&tls_available
);
5210 /* We're not waiting on a specific process, so loop
5211 through all the channels and check for data.
5212 This is a workaround needed for some versions of
5213 the gnutls library -- 2.12.14 has been confirmed
5215 http://comments.gmane.org/gmane.emacs.devel/145074 */
5216 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5217 if (! NILP (chan_process
[channel
]))
5219 struct Lisp_Process
*p
=
5220 XPROCESS (chan_process
[channel
]);
5221 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5222 && ((emacs_gnutls_record_check_pending
5227 eassert (p
->infd
== channel
);
5228 FD_SET (p
->infd
, &tls_available
);
5235 /* Check this specific channel. */
5236 if (wait_proc
->gnutls_p
/* Check for valid process. */
5237 && wait_proc
->gnutls_state
5238 /* Do we have pending data? */
5239 && ((emacs_gnutls_record_check_pending
5240 (wait_proc
->gnutls_state
))
5244 eassert (0 <= wait_proc
->infd
);
5245 /* Set to Available. */
5246 FD_SET (wait_proc
->infd
, &tls_available
);
5251 Available
= tls_available
;
5258 /* Make C-g and alarm signals set flags again. */
5259 clear_waiting_for_input ();
5261 /* If we woke up due to SIGWINCH, actually change size now. */
5262 do_pending_window_change (0);
5266 /* Exit the main loop if we've passed the requested timeout,
5267 or aren't skipping processes and got some output and
5268 haven't lowered our timeout due to timers or SIGIO and
5269 have waited a long amount of time due to repeated
5271 struct timespec huge_timespec
5272 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION
);
5273 struct timespec cmp_time
= huge_timespec
;
5276 if (wait
== TIMEOUT
)
5277 cmp_time
= end_time
;
5278 if (!process_skipped
&& got_some_output
> 0
5279 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5281 if (!timespec_valid_p (got_output_end_time
))
5283 if (timespec_cmp (got_output_end_time
, cmp_time
) < 0)
5284 cmp_time
= got_output_end_time
;
5286 if (timespec_cmp (cmp_time
, huge_timespec
) < 0)
5288 now
= current_timespec ();
5289 if (timespec_cmp (cmp_time
, now
) <= 0)
5296 if (xerrno
== EINTR
)
5298 else if (xerrno
== EBADF
)
5301 report_file_errno ("Failed select", Qnil
, xerrno
);
5304 /* Check for keyboard input. */
5305 /* If there is any, return immediately
5306 to give it higher priority than subprocesses. */
5310 unsigned old_timers_run
= timers_run
;
5311 struct buffer
*old_buffer
= current_buffer
;
5312 Lisp_Object old_window
= selected_window
;
5315 if (detect_input_pending_run_timers (do_display
))
5317 swallow_events (do_display
);
5318 if (detect_input_pending_run_timers (do_display
))
5322 /* If a timer has run, this might have changed buffers
5323 an alike. Make read_key_sequence aware of that. */
5324 if (timers_run
!= old_timers_run
5325 && waiting_for_user_input_p
== -1
5326 && (old_buffer
!= current_buffer
5327 || !EQ (old_window
, selected_window
)))
5328 record_asynch_buffer_change ();
5334 /* If there is unread keyboard input, also return. */
5336 && requeued_events_pending_p ())
5339 /* If we are not checking for keyboard input now,
5340 do process events (but don't run any timers).
5341 This is so that X events will be processed.
5342 Otherwise they may have to wait until polling takes place.
5343 That would causes delays in pasting selections, for example.
5345 (We used to do this only if wait_for_cell.) */
5346 if (read_kbd
== 0 && detect_input_pending ())
5348 swallow_events (do_display
);
5349 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5350 if (detect_input_pending ())
5355 /* Exit now if the cell we're waiting for became non-nil. */
5356 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5360 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5361 go read it. This can happen with X on BSD after logging out.
5362 In that case, there really is no input and no SIGIO,
5363 but select says there is input. */
5365 if (read_kbd
&& interrupt_input
5366 && keyboard_bit_set (&Available
) && ! noninteractive
)
5367 handle_input_available_signal (SIGIO
);
5370 /* If checking input just got us a size-change event from X,
5371 obey it now if we should. */
5372 if (read_kbd
|| ! NILP (wait_for_cell
))
5373 do_pending_window_change (0);
5375 /* Check for data from a process. */
5376 if (no_avail
|| nfds
== 0)
5379 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5381 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5383 && ((d
->condition
& FOR_READ
5384 && FD_ISSET (channel
, &Available
))
5385 || (d
->condition
& FOR_WRITE
5386 && FD_ISSET (channel
, &write_mask
))))
5387 d
->func (channel
, d
->data
);
5390 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5392 if (FD_ISSET (channel
, &Available
)
5393 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5394 && !FD_ISSET (channel
, &non_process_wait_mask
))
5398 /* If waiting for this channel, arrange to return as
5399 soon as no more input to be processed. No more
5401 proc
= chan_process
[channel
];
5405 /* If this is a server stream socket, accept connection. */
5406 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5408 server_accept_connection (proc
, channel
);
5412 /* Read data from the process, starting with our
5413 buffered-ahead character if we have one. */
5415 nread
= read_process_output (proc
, channel
);
5416 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5417 && got_some_output
< nread
)
5418 got_some_output
= nread
;
5421 /* Vacuum up any leftovers without waiting. */
5422 if (wait_proc
== XPROCESS (proc
))
5424 /* Since read_process_output can run a filter,
5425 which can call accept-process-output,
5426 don't try to read from any other processes
5427 before doing the select again. */
5428 FD_ZERO (&Available
);
5431 redisplay_preserve_echo_area (12);
5433 else if (nread
== -1 && would_block (errno
))
5436 /* FIXME: Is this special case still needed? */
5437 /* Note that we cannot distinguish between no input
5438 available now and a closed pipe.
5439 With luck, a closed pipe will be accompanied by
5440 subprocess termination and SIGCHLD. */
5441 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5442 && !PIPECONN_P (proc
))
5446 /* On some OSs with ptys, when the process on one end of
5447 a pty exits, the other end gets an error reading with
5448 errno = EIO instead of getting an EOF (0 bytes read).
5449 Therefore, if we get an error reading and errno =
5450 EIO, just continue, because the child process has
5451 exited and should clean itself up soon (e.g. when we
5453 else if (nread
== -1 && errno
== EIO
)
5455 struct Lisp_Process
*p
= XPROCESS (proc
);
5457 /* Clear the descriptor now, so we only raise the
5459 FD_CLR (channel
, &input_wait_mask
);
5460 FD_CLR (channel
, &non_keyboard_wait_mask
);
5464 /* If the EIO occurs on a pty, the SIGCHLD handler's
5465 waitpid call will not find the process object to
5466 delete. Do it here. */
5467 p
->tick
= ++process_tick
;
5468 pset_status (p
, Qfailed
);
5471 #endif /* HAVE_PTYS */
5472 /* If we can detect process termination, don't consider the
5473 process gone just because its pipe is closed. */
5474 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5475 && !PIPECONN_P (proc
))
5477 else if (nread
== 0 && PIPECONN_P (proc
))
5479 /* Preserve status of processes already terminated. */
5480 XPROCESS (proc
)->tick
= ++process_tick
;
5481 deactivate_process (proc
);
5482 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5483 pset_status (XPROCESS (proc
),
5484 list2 (Qexit
, make_number (0)));
5488 /* Preserve status of processes already terminated. */
5489 XPROCESS (proc
)->tick
= ++process_tick
;
5490 deactivate_process (proc
);
5491 if (XPROCESS (proc
)->raw_status_new
)
5492 update_status (XPROCESS (proc
));
5493 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5494 pset_status (XPROCESS (proc
),
5495 list2 (Qexit
, make_number (256)));
5498 if (FD_ISSET (channel
, &Writeok
)
5499 && FD_ISSET (channel
, &connect_wait_mask
))
5501 struct Lisp_Process
*p
;
5503 FD_CLR (channel
, &connect_wait_mask
);
5504 FD_CLR (channel
, &write_mask
);
5505 if (--num_pending_connects
< 0)
5508 proc
= chan_process
[channel
];
5512 p
= XPROCESS (proc
);
5516 socklen_t xlen
= sizeof (xerrno
);
5517 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5521 /* On MS-Windows, getsockopt clears the error for the
5522 entire process, which may not be the right thing; see
5523 w32.c. Use getpeername instead. */
5525 struct sockaddr pname
;
5526 socklen_t pnamelen
= sizeof (pname
);
5528 /* If connection failed, getpeername will fail. */
5530 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5532 /* Obtain connect failure code through error slippage. */
5535 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5542 Lisp_Object addrinfos
5543 = connecting_status (p
->status
) ? XCDR (p
->status
) : Qnil
;
5544 if (!NILP (addrinfos
))
5545 XSETCDR (p
->status
, XCDR (addrinfos
));
5548 p
->tick
= ++process_tick
;
5549 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5551 deactivate_process (proc
);
5552 if (!NILP (addrinfos
))
5553 connect_network_socket (proc
, addrinfos
, Qnil
);
5558 /* If we have an incompletely set up TLS connection,
5559 then defer the sentinel signaling until
5561 if (NILP (p
->gnutls_boot_parameters
)
5565 pset_status (p
, Qrun
);
5566 /* Execute the sentinel here. If we had relied on
5567 status_notify to do it later, it will read input
5568 from the process before calling the sentinel. */
5569 exec_sentinel (proc
, build_string ("open\n"));
5572 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5573 && !EQ (p
->command
, Qt
))
5575 FD_SET (p
->infd
, &input_wait_mask
);
5576 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5580 } /* End for each file descriptor. */
5581 } /* End while exit conditions not met. */
5583 unbind_to (count
, Qnil
);
5585 /* If calling from keyboard input, do not quit
5586 since we want to return C-g as an input character.
5587 Otherwise, do pending quit if requested. */
5590 /* Prevent input_pending from remaining set if we quit. */
5591 clear_input_pending ();
5595 return got_some_output
;
5598 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5601 read_process_output_call (Lisp_Object fun_and_args
)
5603 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5607 read_process_output_error_handler (Lisp_Object error_val
)
5609 cmd_error_internal (error_val
, "error in process filter: ");
5611 update_echo_area ();
5612 Fsleep_for (make_number (2), Qnil
);
5617 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5619 struct coding_system
*coding
);
5621 /* Read pending output from the process channel,
5622 starting with our buffered-ahead character if we have one.
5623 Yield number of decoded characters read.
5625 This function reads at most 4096 characters.
5626 If you want to read all available subprocess output,
5627 you must call it repeatedly until it returns zero.
5629 The characters read are decoded according to PROC's coding-system
5633 read_process_output (Lisp_Object proc
, int channel
)
5636 struct Lisp_Process
*p
= XPROCESS (proc
);
5637 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5638 int carryover
= p
->decoding_carryover
;
5639 enum { readmax
= 4096 };
5640 ptrdiff_t count
= SPECPDL_INDEX ();
5641 Lisp_Object odeactivate
;
5642 char chars
[sizeof coding
->carryover
+ readmax
];
5645 /* See the comment above. */
5646 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5648 #ifdef DATAGRAM_SOCKETS
5649 /* We have a working select, so proc_buffered_char is always -1. */
5650 if (DATAGRAM_CHAN_P (channel
))
5652 socklen_t len
= datagram_address
[channel
].len
;
5653 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5654 0, datagram_address
[channel
].sa
, &len
);
5659 bool buffered
= proc_buffered_char
[channel
] >= 0;
5662 chars
[carryover
] = proc_buffered_char
[channel
];
5663 proc_buffered_char
[channel
] = -1;
5666 if (p
->gnutls_p
&& p
->gnutls_state
)
5667 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5668 readmax
- buffered
);
5671 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5672 readmax
- buffered
);
5673 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5675 int delay
= p
->read_output_delay
;
5678 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5681 process_output_delay_count
++;
5682 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5685 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5687 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5689 process_output_delay_count
--;
5691 p
->read_output_delay
= delay
;
5694 p
->read_output_skip
= 1;
5695 process_output_skip
= 1;
5699 nbytes
+= buffered
&& nbytes
<= 0;
5702 p
->decoding_carryover
= 0;
5704 /* At this point, NBYTES holds number of bytes just received
5705 (including the one in proc_buffered_char[channel]). */
5708 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5710 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5713 /* Now set NBYTES how many bytes we must decode. */
5714 nbytes
+= carryover
;
5716 odeactivate
= Vdeactivate_mark
;
5717 /* There's no good reason to let process filters change the current
5718 buffer, and many callers of accept-process-output, sit-for, and
5719 friends don't expect current-buffer to be changed from under them. */
5720 record_unwind_current_buffer ();
5722 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5724 /* Handling the process output should not deactivate the mark. */
5725 Vdeactivate_mark
= odeactivate
;
5727 unbind_to (count
, Qnil
);
5732 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5734 struct coding_system
*coding
)
5736 Lisp_Object outstream
= p
->filter
;
5738 bool outer_running_asynch_code
= running_asynch_code
;
5739 int waiting
= waiting_for_user_input_p
;
5742 Lisp_Object obuffer
, okeymap
;
5743 XSETBUFFER (obuffer
, current_buffer
);
5744 okeymap
= BVAR (current_buffer
, keymap
);
5747 /* We inhibit quit here instead of just catching it so that
5748 hitting ^G when a filter happens to be running won't screw
5750 specbind (Qinhibit_quit
, Qt
);
5751 specbind (Qlast_nonmenu_event
, Qt
);
5753 /* In case we get recursively called,
5754 and we already saved the match data nonrecursively,
5755 save the same match data in safely recursive fashion. */
5756 if (outer_running_asynch_code
)
5759 /* Don't clobber the CURRENT match data, either! */
5760 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5761 restore_search_regs ();
5762 record_unwind_save_match_data ();
5763 Fset_match_data (tem
, Qt
);
5766 /* For speed, if a search happens within this code,
5767 save the match data in a special nonrecursive fashion. */
5768 running_asynch_code
= 1;
5770 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5771 text
= coding
->dst_object
;
5772 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5773 /* A new coding system might be found. */
5774 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5776 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5778 /* Don't call setup_coding_system for
5779 proc_decode_coding_system[channel] here. It is done in
5780 detect_coding called via decode_coding above. */
5782 /* If a coding system for encoding is not yet decided, we set
5783 it as the same as coding-system for decoding.
5785 But, before doing that we must check if
5786 proc_encode_coding_system[p->outfd] surely points to a
5787 valid memory because p->outfd will be changed once EOF is
5788 sent to the process. */
5789 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5790 && proc_encode_coding_system
[p
->outfd
])
5792 pset_encode_coding_system
5793 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5794 setup_coding_system (p
->encode_coding_system
,
5795 proc_encode_coding_system
[p
->outfd
]);
5799 if (coding
->carryover_bytes
> 0)
5801 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5802 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5803 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5804 coding
->carryover_bytes
);
5805 p
->decoding_carryover
= coding
->carryover_bytes
;
5807 if (SBYTES (text
) > 0)
5808 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5809 sometimes it's simply wrong to wrap (e.g. when called from
5810 accept-process-output). */
5811 internal_condition_case_1 (read_process_output_call
,
5812 list3 (outstream
, make_lisp_proc (p
), text
),
5813 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5814 read_process_output_error_handler
);
5816 /* If we saved the match data nonrecursively, restore it now. */
5817 restore_search_regs ();
5818 running_asynch_code
= outer_running_asynch_code
;
5820 /* Restore waiting_for_user_input_p as it was
5821 when we were called, in case the filter clobbered it. */
5822 waiting_for_user_input_p
= waiting
;
5824 #if 0 /* Call record_asynch_buffer_change unconditionally,
5825 because we might have changed minor modes or other things
5826 that affect key bindings. */
5827 if (! EQ (Fcurrent_buffer (), obuffer
)
5828 || ! EQ (current_buffer
->keymap
, okeymap
))
5830 /* But do it only if the caller is actually going to read events.
5831 Otherwise there's no need to make him wake up, and it could
5832 cause trouble (for example it would make sit_for return). */
5833 if (waiting_for_user_input_p
== -1)
5834 record_asynch_buffer_change ();
5837 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5838 Sinternal_default_process_filter
, 2, 2, 0,
5839 doc
: /* Function used as default process filter.
5840 This inserts the process's output into its buffer, if there is one.
5841 Otherwise it discards the output. */)
5842 (Lisp_Object proc
, Lisp_Object text
)
5844 struct Lisp_Process
*p
;
5847 CHECK_PROCESS (proc
);
5848 p
= XPROCESS (proc
);
5849 CHECK_STRING (text
);
5851 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5853 Lisp_Object old_read_only
;
5854 ptrdiff_t old_begv
, old_zv
;
5855 ptrdiff_t old_begv_byte
, old_zv_byte
;
5856 ptrdiff_t before
, before_byte
;
5857 ptrdiff_t opoint_byte
;
5860 Fset_buffer (p
->buffer
);
5862 opoint_byte
= PT_BYTE
;
5863 old_read_only
= BVAR (current_buffer
, read_only
);
5866 old_begv_byte
= BEGV_BYTE
;
5867 old_zv_byte
= ZV_BYTE
;
5869 bset_read_only (current_buffer
, Qnil
);
5871 /* Insert new output into buffer at the current end-of-output
5872 marker, thus preserving logical ordering of input and output. */
5873 if (XMARKER (p
->mark
)->buffer
)
5874 set_point_from_marker (p
->mark
);
5876 SET_PT_BOTH (ZV
, ZV_BYTE
);
5878 before_byte
= PT_BYTE
;
5880 /* If the output marker is outside of the visible region, save
5881 the restriction and widen. */
5882 if (! (BEGV
<= PT
&& PT
<= ZV
))
5885 /* Adjust the multibyteness of TEXT to that of the buffer. */
5886 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5887 != ! STRING_MULTIBYTE (text
))
5888 text
= (STRING_MULTIBYTE (text
)
5889 ? Fstring_as_unibyte (text
)
5890 : Fstring_to_multibyte (text
));
5891 /* Insert before markers in case we are inserting where
5892 the buffer's mark is, and the user's next command is Meta-y. */
5893 insert_from_string_before_markers (text
, 0, 0,
5894 SCHARS (text
), SBYTES (text
), 0);
5896 /* Make sure the process marker's position is valid when the
5897 process buffer is changed in the signal_after_change above.
5898 W3 is known to do that. */
5899 if (BUFFERP (p
->buffer
)
5900 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5901 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5903 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5905 update_mode_lines
= 23;
5907 /* Make sure opoint and the old restrictions
5908 float ahead of any new text just as point would. */
5909 if (opoint
>= before
)
5911 opoint
+= PT
- before
;
5912 opoint_byte
+= PT_BYTE
- before_byte
;
5914 if (old_begv
> before
)
5916 old_begv
+= PT
- before
;
5917 old_begv_byte
+= PT_BYTE
- before_byte
;
5919 if (old_zv
>= before
)
5921 old_zv
+= PT
- before
;
5922 old_zv_byte
+= PT_BYTE
- before_byte
;
5925 /* If the restriction isn't what it should be, set it. */
5926 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5927 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5929 bset_read_only (current_buffer
, old_read_only
);
5930 SET_PT_BOTH (opoint
, opoint_byte
);
5935 /* Sending data to subprocess. */
5937 /* In send_process, when a write fails temporarily,
5938 wait_reading_process_output is called. It may execute user code,
5939 e.g. timers, that attempts to write new data to the same process.
5940 We must ensure that data is sent in the right order, and not
5941 interspersed half-completed with other writes (Bug#10815). This is
5942 handled by the write_queue element of struct process. It is a list
5943 with each entry having the form
5945 (string . (offset . length))
5947 where STRING is a lisp string, OFFSET is the offset into the
5948 string's byte sequence from which we should begin to send, and
5949 LENGTH is the number of bytes left to send. */
5951 /* Create a new entry in write_queue.
5952 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5953 BUF is a pointer to the string sequence of the input_obj or a C
5954 string in case of Qt or Qnil. */
5957 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5958 const char *buf
, ptrdiff_t len
, bool front
)
5961 Lisp_Object entry
, obj
;
5963 if (STRINGP (input_obj
))
5965 offset
= buf
- SSDATA (input_obj
);
5971 obj
= make_unibyte_string (buf
, len
);
5974 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5977 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5979 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5982 /* Remove the first element in the write_queue of process P, put its
5983 contents in OBJ, BUF and LEN, and return true. If the
5984 write_queue is empty, return false. */
5987 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5988 const char **buf
, ptrdiff_t *len
)
5990 Lisp_Object entry
, offset_length
;
5993 if (NILP (p
->write_queue
))
5996 entry
= XCAR (p
->write_queue
);
5997 pset_write_queue (p
, XCDR (p
->write_queue
));
5999 *obj
= XCAR (entry
);
6000 offset_length
= XCDR (entry
);
6002 *len
= XINT (XCDR (offset_length
));
6003 offset
= XINT (XCAR (offset_length
));
6004 *buf
= SSDATA (*obj
) + offset
;
6009 /* Send some data to process PROC.
6010 BUF is the beginning of the data; LEN is the number of characters.
6011 OBJECT is the Lisp object that the data comes from. If OBJECT is
6012 nil or t, it means that the data comes from C string.
6014 If OBJECT is not nil, the data is encoded by PROC's coding-system
6015 for encoding before it is sent.
6017 This function can evaluate Lisp code and can garbage collect. */
6020 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6023 struct Lisp_Process
*p
= XPROCESS (proc
);
6025 struct coding_system
*coding
;
6027 if (NETCONN_P (proc
))
6029 wait_while_connecting (proc
);
6030 wait_for_tls_negotiation (proc
);
6033 if (p
->raw_status_new
)
6035 if (! EQ (p
->status
, Qrun
))
6036 error ("Process %s not running", SDATA (p
->name
));
6038 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6040 coding
= proc_encode_coding_system
[p
->outfd
];
6041 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6043 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6044 || (BUFFERP (object
)
6045 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6048 pset_encode_coding_system
6049 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6050 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6052 /* The coding system for encoding was changed to raw-text
6053 because we sent a unibyte text previously. Now we are
6054 sending a multibyte text, thus we must encode it by the
6055 original coding system specified for the current process.
6057 Another reason we come here is that the coding system
6058 was just complemented and a new one was returned by
6059 complement_process_encoding_system. */
6060 setup_coding_system (p
->encode_coding_system
, coding
);
6061 Vlast_coding_system_used
= p
->encode_coding_system
;
6063 coding
->src_multibyte
= 1;
6067 coding
->src_multibyte
= 0;
6068 /* For sending a unibyte text, character code conversion should
6069 not take place but EOL conversion should. So, setup raw-text
6070 or one of the subsidiary if we have not yet done it. */
6071 if (CODING_REQUIRE_ENCODING (coding
))
6073 if (CODING_REQUIRE_FLUSHING (coding
))
6075 /* But, before changing the coding, we must flush out data. */
6076 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6077 send_process (proc
, "", 0, Qt
);
6078 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6080 setup_coding_system (raw_text_coding_system
6081 (Vlast_coding_system_used
),
6083 coding
->src_multibyte
= 0;
6086 coding
->dst_multibyte
= 0;
6088 if (CODING_REQUIRE_ENCODING (coding
))
6090 coding
->dst_object
= Qt
;
6091 if (BUFFERP (object
))
6093 ptrdiff_t from_byte
, from
, to
;
6094 ptrdiff_t save_pt
, save_pt_byte
;
6095 struct buffer
*cur
= current_buffer
;
6097 set_buffer_internal (XBUFFER (object
));
6098 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6100 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6101 from
= BYTE_TO_CHAR (from_byte
);
6102 to
= BYTE_TO_CHAR (from_byte
+ len
);
6103 TEMP_SET_PT_BOTH (from
, from_byte
);
6104 encode_coding_object (coding
, object
, from
, from_byte
,
6105 to
, from_byte
+ len
, Qt
);
6106 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6107 set_buffer_internal (cur
);
6109 else if (STRINGP (object
))
6111 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6112 SBYTES (object
), Qt
);
6116 coding
->dst_object
= make_unibyte_string (buf
, len
);
6117 coding
->produced
= len
;
6120 len
= coding
->produced
;
6121 object
= coding
->dst_object
;
6122 buf
= SSDATA (object
);
6125 /* If there is already data in the write_queue, put the new data
6126 in the back of queue. Otherwise, ignore it. */
6127 if (!NILP (p
->write_queue
))
6128 write_queue_push (p
, object
, buf
, len
, 0);
6130 do /* while !NILP (p->write_queue) */
6132 ptrdiff_t cur_len
= -1;
6133 const char *cur_buf
;
6134 Lisp_Object cur_object
;
6136 /* If write_queue is empty, ignore it. */
6137 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6141 cur_object
= object
;
6146 /* Send this batch, using one or more write calls. */
6147 ptrdiff_t written
= 0;
6148 int outfd
= p
->outfd
;
6149 #ifdef DATAGRAM_SOCKETS
6150 if (DATAGRAM_CHAN_P (outfd
))
6152 rv
= sendto (outfd
, cur_buf
, cur_len
,
6153 0, datagram_address
[outfd
].sa
,
6154 datagram_address
[outfd
].len
);
6157 else if (errno
== EMSGSIZE
)
6158 report_file_error ("Sending datagram", proc
);
6164 if (p
->gnutls_p
&& p
->gnutls_state
)
6165 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6168 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6169 rv
= (written
? 0 : -1);
6170 if (p
->read_output_delay
> 0
6171 && p
->adaptive_read_buffering
== 1)
6173 p
->read_output_delay
= 0;
6174 process_output_delay_count
--;
6175 p
->read_output_skip
= 0;
6181 if (would_block (errno
))
6182 /* Buffer is full. Wait, accepting input;
6183 that may allow the program
6184 to finish doing output and read more. */
6186 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6187 /* A gross hack to work around a bug in FreeBSD.
6188 In the following sequence, read(2) returns
6192 write(2) 954 bytes, get EAGAIN
6193 read(2) 1024 bytes in process_read_output
6194 read(2) 11 bytes in process_read_output
6196 That is, read(2) returns more bytes than have
6197 ever been written successfully. The 1033 bytes
6198 read are the 1022 bytes written successfully
6199 after processing (for example with CRs added if
6200 the terminal is set up that way which it is
6201 here). The same bytes will be seen again in a
6202 later read(2), without the CRs. */
6204 if (errno
== EAGAIN
)
6207 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6209 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6211 /* Put what we should have written in wait_queue. */
6212 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6213 wait_reading_process_output (0, 20 * 1000 * 1000,
6214 0, 0, Qnil
, NULL
, 0);
6215 /* Reread queue, to see what is left. */
6218 else if (errno
== EPIPE
)
6220 p
->raw_status_new
= 0;
6221 pset_status (p
, list2 (Qexit
, make_number (256)));
6222 p
->tick
= ++process_tick
;
6223 deactivate_process (proc
);
6224 error ("process %s no longer connected to pipe; closed it",
6228 /* This is a real error. */
6229 report_file_error ("Writing to process", proc
);
6235 while (!NILP (p
->write_queue
));
6238 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6240 doc
: /* Send current contents of region as input to PROCESS.
6241 PROCESS may be a process, a buffer, the name of a process or buffer, or
6242 nil, indicating the current buffer's process.
6243 Called from program, takes three arguments, PROCESS, START and END.
6244 If the region is more than 500 characters long,
6245 it is sent in several bunches. This may happen even for shorter regions.
6246 Output from processes can arrive in between bunches.
6248 If PROCESS is a non-blocking network process that hasn't been fully
6249 set up yet, this function will block until socket setup has completed. */)
6250 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6252 Lisp_Object proc
= get_process (process
);
6253 ptrdiff_t start_byte
, end_byte
;
6255 validate_region (&start
, &end
);
6257 start_byte
= CHAR_TO_BYTE (XINT (start
));
6258 end_byte
= CHAR_TO_BYTE (XINT (end
));
6260 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6261 move_gap_both (XINT (start
), start_byte
);
6263 if (NETCONN_P (proc
))
6264 wait_while_connecting (proc
);
6266 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6267 end_byte
- start_byte
, Fcurrent_buffer ());
6272 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6274 doc
: /* Send PROCESS the contents of STRING as input.
6275 PROCESS may be a process, a buffer, the name of a process or buffer, or
6276 nil, indicating the current buffer's process.
6277 If STRING is more than 500 characters long,
6278 it is sent in several bunches. This may happen even for shorter strings.
6279 Output from processes can arrive in between bunches.
6281 If PROCESS is a non-blocking network process that hasn't been fully
6282 set up yet, this function will block until socket setup has completed. */)
6283 (Lisp_Object process
, Lisp_Object string
)
6285 CHECK_STRING (string
);
6286 Lisp_Object proc
= get_process (process
);
6287 send_process (proc
, SSDATA (string
),
6288 SBYTES (string
), string
);
6292 /* Return the foreground process group for the tty/pty that
6293 the process P uses. */
6295 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6300 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6303 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6304 master side. Try the slave side. */
6305 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6309 ioctl (fd
, TIOCGPGRP
, &gid
);
6313 #endif /* defined (TIOCGPGRP ) */
6318 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6319 Sprocess_running_child_p
, 0, 1, 0,
6320 doc
: /* Return non-nil if PROCESS has given the terminal to a
6321 child. If the operating system does not make it possible to find out,
6322 return t. If we can find out, return the numeric ID of the foreground
6324 (Lisp_Object process
)
6326 /* Initialize in case ioctl doesn't exist or gives an error,
6327 in a way that will cause returning t. */
6328 Lisp_Object proc
= get_process (process
);
6329 struct Lisp_Process
*p
= XPROCESS (proc
);
6331 if (!EQ (p
->type
, Qreal
))
6332 error ("Process %s is not a subprocess",
6335 error ("Process %s is not active",
6338 pid_t gid
= emacs_get_tty_pgrp (p
);
6343 return make_number (gid
);
6347 /* Send a signal number SIGNO to PROCESS.
6348 If CURRENT_GROUP is t, that means send to the process group
6349 that currently owns the terminal being used to communicate with PROCESS.
6350 This is used for various commands in shell mode.
6351 If CURRENT_GROUP is lambda, that means send to the process group
6352 that currently owns the terminal, but only if it is NOT the shell itself.
6354 If NOMSG is false, insert signal-announcements into process's buffers
6357 If we can, we try to signal PROCESS by sending control characters
6358 down the pty. This allows us to signal inferiors who have changed
6359 their uid, for which kill would return an EPERM error. */
6362 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6366 struct Lisp_Process
*p
;
6370 proc
= get_process (process
);
6371 p
= XPROCESS (proc
);
6373 if (!EQ (p
->type
, Qreal
))
6374 error ("Process %s is not a subprocess",
6377 error ("Process %s is not active",
6381 current_group
= Qnil
;
6383 /* If we are using pgrps, get a pgrp number and make it negative. */
6384 if (NILP (current_group
))
6385 /* Send the signal to the shell's process group. */
6389 #ifdef SIGNALS_VIA_CHARACTERS
6390 /* If possible, send signals to the entire pgrp
6391 by sending an input character to it. */
6394 cc_t
*sig_char
= NULL
;
6396 tcgetattr (p
->infd
, &t
);
6401 sig_char
= &t
.c_cc
[VINTR
];
6405 sig_char
= &t
.c_cc
[VQUIT
];
6410 sig_char
= &t
.c_cc
[VSWTCH
];
6412 sig_char
= &t
.c_cc
[VSUSP
];
6417 if (sig_char
&& *sig_char
!= CDISABLE
)
6419 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6422 /* If we can't send the signal with a character,
6423 fall through and send it another way. */
6425 /* The code above may fall through if it can't
6426 handle the signal. */
6427 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6430 /* Get the current pgrp using the tty itself, if we have that.
6431 Otherwise, use the pty to get the pgrp.
6432 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6433 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6434 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6435 His patch indicates that if TIOCGPGRP returns an error, then
6436 we should just assume that p->pid is also the process group id. */
6438 gid
= emacs_get_tty_pgrp (p
);
6441 /* If we can't get the information, assume
6442 the shell owns the tty. */
6445 /* It is not clear whether anything really can set GID to -1.
6446 Perhaps on some system one of those ioctls can or could do so.
6447 Or perhaps this is vestigial. */
6450 #else /* ! defined (TIOCGPGRP) */
6451 /* Can't select pgrps on this system, so we know that
6452 the child itself heads the pgrp. */
6454 #endif /* ! defined (TIOCGPGRP) */
6456 /* If current_group is lambda, and the shell owns the terminal,
6457 don't send any signal. */
6458 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6463 if (signo
== SIGCONT
)
6465 p
->raw_status_new
= 0;
6466 pset_status (p
, Qrun
);
6467 p
->tick
= ++process_tick
;
6470 status_notify (NULL
, NULL
);
6471 redisplay_preserve_echo_area (13);
6477 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6478 We don't know whether the bug is fixed in later HP-UX versions. */
6479 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6483 /* If we don't have process groups, send the signal to the immediate
6484 subprocess. That isn't really right, but it's better than any
6485 obvious alternative. */
6486 pid_t pid
= no_pgrp
? gid
: - gid
;
6488 /* Do not kill an already-reaped process, as that could kill an
6489 innocent bystander that happens to have the same process ID. */
6491 block_child_signal (&oldset
);
6494 unblock_child_signal (&oldset
);
6497 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6498 doc
: /* Interrupt process PROCESS.
6499 PROCESS may be a process, a buffer, or the name of a process or buffer.
6500 No arg or nil means current buffer's process.
6501 Second arg CURRENT-GROUP non-nil means send signal to
6502 the current process-group of the process's controlling terminal
6503 rather than to the process's own process group.
6504 If the process is a shell, this means interrupt current subjob
6505 rather than the shell.
6507 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6508 don't send the signal. */)
6509 (Lisp_Object process
, Lisp_Object current_group
)
6511 process_send_signal (process
, SIGINT
, current_group
, 0);
6515 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6516 doc
: /* Kill process PROCESS. May be process or name of one.
6517 See function `interrupt-process' for more details on usage. */)
6518 (Lisp_Object process
, Lisp_Object current_group
)
6520 process_send_signal (process
, SIGKILL
, current_group
, 0);
6524 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6525 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6526 See function `interrupt-process' for more details on usage. */)
6527 (Lisp_Object process
, Lisp_Object current_group
)
6529 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6533 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6534 doc
: /* Stop process PROCESS. May be process or name of one.
6535 See function `interrupt-process' for more details on usage.
6536 If PROCESS is a network or serial or pipe connection, inhibit handling
6537 of incoming traffic. */)
6538 (Lisp_Object process
, Lisp_Object current_group
)
6540 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6541 || PIPECONN_P (process
)))
6543 struct Lisp_Process
*p
;
6545 p
= XPROCESS (process
);
6546 if (NILP (p
->command
)
6549 FD_CLR (p
->infd
, &input_wait_mask
);
6550 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6552 pset_command (p
, Qt
);
6556 error ("No SIGTSTP support");
6558 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6563 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6564 doc
: /* Continue process PROCESS. May be process or name of one.
6565 See function `interrupt-process' for more details on usage.
6566 If PROCESS is a network or serial process, resume handling of incoming
6568 (Lisp_Object process
, Lisp_Object current_group
)
6570 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6571 || PIPECONN_P (process
)))
6573 struct Lisp_Process
*p
;
6575 p
= XPROCESS (process
);
6576 if (EQ (p
->command
, Qt
)
6578 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6580 FD_SET (p
->infd
, &input_wait_mask
);
6581 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6583 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6584 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6585 #else /* not WINDOWSNT */
6586 tcflush (p
->infd
, TCIFLUSH
);
6587 #endif /* not WINDOWSNT */
6589 pset_command (p
, Qnil
);
6593 process_send_signal (process
, SIGCONT
, current_group
, 0);
6595 error ("No SIGCONT support");
6600 /* Return the integer value of the signal whose abbreviation is ABBR,
6601 or a negative number if there is no such signal. */
6603 abbr_to_signal (char const *name
)
6606 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6608 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6611 for (i
= 0; i
< sizeof sigbuf
; i
++)
6613 sigbuf
[i
] = c_toupper (name
[i
]);
6615 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6621 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6622 2, 2, "sProcess (name or number): \nnSignal code: ",
6623 doc
: /* Send PROCESS the signal with code SIGCODE.
6624 PROCESS may also be a number specifying the process id of the
6625 process to signal; in this case, the process need not be a child of
6627 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6628 (Lisp_Object process
, Lisp_Object sigcode
)
6633 if (STRINGP (process
))
6635 Lisp_Object tem
= Fget_process (process
);
6638 Lisp_Object process_number
6639 = string_to_number (SSDATA (process
), 10, 1);
6640 if (NUMBERP (process_number
))
6641 tem
= process_number
;
6645 else if (!NUMBERP (process
))
6646 process
= get_process (process
);
6651 if (NUMBERP (process
))
6652 CONS_TO_INTEGER (process
, pid_t
, pid
);
6655 CHECK_PROCESS (process
);
6656 pid
= XPROCESS (process
)->pid
;
6658 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6661 if (INTEGERP (sigcode
))
6663 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6664 signo
= XINT (sigcode
);
6670 CHECK_SYMBOL (sigcode
);
6671 name
= SSDATA (SYMBOL_NAME (sigcode
));
6673 signo
= abbr_to_signal (name
);
6675 error ("Undefined signal name %s", name
);
6678 return make_number (kill (pid
, signo
));
6681 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6682 doc
: /* Make PROCESS see end-of-file in its input.
6683 EOF comes after any text already sent to it.
6684 PROCESS may be a process, a buffer, the name of a process or buffer, or
6685 nil, indicating the current buffer's process.
6686 If PROCESS is a network connection, or is a process communicating
6687 through a pipe (as opposed to a pty), then you cannot send any more
6688 text to PROCESS after you call this function.
6689 If PROCESS is a serial process, wait until all output written to the
6690 process has been transmitted to the serial port. */)
6691 (Lisp_Object process
)
6694 struct coding_system
*coding
= NULL
;
6697 proc
= get_process (process
);
6699 if (NETCONN_P (proc
))
6700 wait_while_connecting (proc
);
6702 if (DATAGRAM_CONN_P (proc
))
6706 outfd
= XPROCESS (proc
)->outfd
;
6708 coding
= proc_encode_coding_system
[outfd
];
6710 /* Make sure the process is really alive. */
6711 if (XPROCESS (proc
)->raw_status_new
)
6712 update_status (XPROCESS (proc
));
6713 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6714 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6716 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6718 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6719 send_process (proc
, "", 0, Qnil
);
6722 if (XPROCESS (proc
)->pty_flag
)
6723 send_process (proc
, "\004", 1, Qnil
);
6724 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6727 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6728 report_file_error ("Failed tcdrain", Qnil
);
6729 #endif /* not WINDOWSNT */
6730 /* Do nothing on Windows because writes are blocking. */
6734 struct Lisp_Process
*p
= XPROCESS (proc
);
6735 int old_outfd
= p
->outfd
;
6738 #ifdef HAVE_SHUTDOWN
6739 /* If this is a network connection, or socketpair is used
6740 for communication with the subprocess, call shutdown to cause EOF.
6741 (In some old system, shutdown to socketpair doesn't work.
6742 Then we just can't win.) */
6744 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6745 shutdown (old_outfd
, 1);
6747 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6748 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6750 report_file_error ("Opening null device", Qnil
);
6751 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6752 p
->outfd
= new_outfd
;
6754 if (!proc_encode_coding_system
[new_outfd
])
6755 proc_encode_coding_system
[new_outfd
]
6756 = xmalloc (sizeof (struct coding_system
));
6759 *proc_encode_coding_system
[new_outfd
]
6760 = *proc_encode_coding_system
[old_outfd
];
6761 memset (proc_encode_coding_system
[old_outfd
], 0,
6762 sizeof (struct coding_system
));
6765 setup_coding_system (p
->encode_coding_system
,
6766 proc_encode_coding_system
[new_outfd
]);
6771 /* The main Emacs thread records child processes in three places:
6773 - Vprocess_alist, for asynchronous subprocesses, which are child
6774 processes visible to Lisp.
6776 - deleted_pid_list, for child processes invisible to Lisp,
6777 typically because of delete-process. These are recorded so that
6778 the processes can be reaped when they exit, so that the operating
6779 system's process table is not cluttered by zombies.
6781 - the local variable PID in Fcall_process, call_process_cleanup and
6782 call_process_kill, for synchronous subprocesses.
6783 record_unwind_protect is used to make sure this process is not
6784 forgotten: if the user interrupts call-process and the child
6785 process refuses to exit immediately even with two C-g's,
6786 call_process_kill adds PID's contents to deleted_pid_list before
6789 The main Emacs thread invokes waitpid only on child processes that
6790 it creates and that have not been reaped. This avoid races on
6791 platforms such as GTK, where other threads create their own
6792 subprocesses which the main thread should not reap. For example,
6793 if the main thread attempted to reap an already-reaped child, it
6794 might inadvertently reap a GTK-created process that happened to
6795 have the same process ID. */
6797 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6798 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6799 keep track of its own children. GNUstep is similar. */
6801 static void dummy_handler (int sig
) {}
6802 static signal_handler_t
volatile lib_child_handler
;
6804 /* Handle a SIGCHLD signal by looking for known child processes of
6805 Emacs whose status have changed. For each one found, record its
6808 All we do is change the status; we do not run sentinels or print
6809 notifications. That is saved for the next time keyboard input is
6810 done, in order to avoid timing errors.
6812 ** WARNING: this can be called during garbage collection.
6813 Therefore, it must not be fooled by the presence of mark bits in
6816 ** USG WARNING: Although it is not obvious from the documentation
6817 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6818 signal() before executing at least one wait(), otherwise the
6819 handler will be called again, resulting in an infinite loop. The
6820 relevant portion of the documentation reads "SIGCLD signals will be
6821 queued and the signal-catching function will be continually
6822 reentered until the queue is empty". Invoking signal() causes the
6823 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6826 ** Malloc WARNING: This should never call malloc either directly or
6827 indirectly; if it does, that is a bug. */
6830 handle_child_signal (int sig
)
6832 Lisp_Object tail
, proc
;
6834 /* Find the process that signaled us, and record its status. */
6836 /* The process can have been deleted by Fdelete_process, or have
6837 been started asynchronously by Fcall_process. */
6838 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6840 bool all_pids_are_fixnums
6841 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6842 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6843 Lisp_Object head
= XCAR (tail
);
6848 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6851 if (INTEGERP (xpid
))
6852 deleted_pid
= XINT (xpid
);
6854 deleted_pid
= XFLOAT_DATA (xpid
);
6855 if (child_status_changed (deleted_pid
, 0, 0))
6857 if (STRINGP (XCDR (head
)))
6858 unlink (SSDATA (XCDR (head
)));
6859 XSETCAR (tail
, Qnil
);
6864 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6865 FOR_EACH_PROCESS (tail
, proc
)
6867 struct Lisp_Process
*p
= XPROCESS (proc
);
6871 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6873 /* Change the status of the process that was found. */
6874 p
->tick
= ++process_tick
;
6875 p
->raw_status
= status
;
6876 p
->raw_status_new
= 1;
6878 /* If process has terminated, stop waiting for its output. */
6879 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6881 bool clear_desc_flag
= 0;
6884 clear_desc_flag
= 1;
6886 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6887 if (clear_desc_flag
)
6889 FD_CLR (p
->infd
, &input_wait_mask
);
6890 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6896 lib_child_handler (sig
);
6897 #ifdef NS_IMPL_GNUSTEP
6898 /* NSTask in GNUstep sets its child handler each time it is called.
6899 So we must re-set ours. */
6900 catch_child_signal ();
6905 deliver_child_signal (int sig
)
6907 deliver_process_signal (sig
, handle_child_signal
);
6912 exec_sentinel_error_handler (Lisp_Object error_val
)
6914 cmd_error_internal (error_val
, "error in process sentinel: ");
6916 update_echo_area ();
6917 Fsleep_for (make_number (2), Qnil
);
6922 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6924 Lisp_Object sentinel
, odeactivate
;
6925 struct Lisp_Process
*p
= XPROCESS (proc
);
6926 ptrdiff_t count
= SPECPDL_INDEX ();
6927 bool outer_running_asynch_code
= running_asynch_code
;
6928 int waiting
= waiting_for_user_input_p
;
6930 if (inhibit_sentinels
)
6933 odeactivate
= Vdeactivate_mark
;
6935 Lisp_Object obuffer
, okeymap
;
6936 XSETBUFFER (obuffer
, current_buffer
);
6937 okeymap
= BVAR (current_buffer
, keymap
);
6940 /* There's no good reason to let sentinels change the current
6941 buffer, and many callers of accept-process-output, sit-for, and
6942 friends don't expect current-buffer to be changed from under them. */
6943 record_unwind_current_buffer ();
6945 sentinel
= p
->sentinel
;
6947 /* Inhibit quit so that random quits don't screw up a running filter. */
6948 specbind (Qinhibit_quit
, Qt
);
6949 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6951 /* In case we get recursively called,
6952 and we already saved the match data nonrecursively,
6953 save the same match data in safely recursive fashion. */
6954 if (outer_running_asynch_code
)
6957 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6958 restore_search_regs ();
6959 record_unwind_save_match_data ();
6960 Fset_match_data (tem
, Qt
);
6963 /* For speed, if a search happens within this code,
6964 save the match data in a special nonrecursive fashion. */
6965 running_asynch_code
= 1;
6967 internal_condition_case_1 (read_process_output_call
,
6968 list3 (sentinel
, proc
, reason
),
6969 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6970 exec_sentinel_error_handler
);
6972 /* If we saved the match data nonrecursively, restore it now. */
6973 restore_search_regs ();
6974 running_asynch_code
= outer_running_asynch_code
;
6976 Vdeactivate_mark
= odeactivate
;
6978 /* Restore waiting_for_user_input_p as it was
6979 when we were called, in case the filter clobbered it. */
6980 waiting_for_user_input_p
= waiting
;
6983 if (! EQ (Fcurrent_buffer (), obuffer
)
6984 || ! EQ (current_buffer
->keymap
, okeymap
))
6986 /* But do it only if the caller is actually going to read events.
6987 Otherwise there's no need to make him wake up, and it could
6988 cause trouble (for example it would make sit_for return). */
6989 if (waiting_for_user_input_p
== -1)
6990 record_asynch_buffer_change ();
6992 unbind_to (count
, Qnil
);
6995 /* Report all recent events of a change in process status
6996 (either run the sentinel or output a message).
6997 This is usually done while Emacs is waiting for keyboard input
6998 but can be done at other times.
7000 Return positive if any input was received from WAIT_PROC (or from
7001 any process if WAIT_PROC is null), zero if input was attempted but
7002 none received, and negative if we didn't even try. */
7005 status_notify (struct Lisp_Process
*deleting_process
,
7006 struct Lisp_Process
*wait_proc
)
7009 Lisp_Object tail
, msg
;
7010 int got_some_output
= -1;
7015 /* Set this now, so that if new processes are created by sentinels
7016 that we run, we get called again to handle their status changes. */
7017 update_tick
= process_tick
;
7019 FOR_EACH_PROCESS (tail
, proc
)
7022 register struct Lisp_Process
*p
= XPROCESS (proc
);
7024 if (p
->tick
!= p
->update_tick
)
7026 p
->update_tick
= p
->tick
;
7028 /* If process is still active, read any output that remains. */
7029 while (! EQ (p
->filter
, Qt
)
7030 && ! connecting_status (p
->status
)
7031 && ! EQ (p
->status
, Qlisten
)
7032 /* Network or serial process not stopped: */
7033 && ! EQ (p
->command
, Qt
)
7035 && p
!= deleting_process
)
7037 int nread
= read_process_output (proc
, p
->infd
);
7038 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7039 && got_some_output
< nread
)
7040 got_some_output
= nread
;
7045 /* Get the text to use for the message. */
7046 if (p
->raw_status_new
)
7048 msg
= status_message (p
);
7050 /* If process is terminated, deactivate it or delete it. */
7052 if (CONSP (p
->status
))
7053 symbol
= XCAR (p
->status
);
7055 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7056 || EQ (symbol
, Qclosed
))
7058 if (delete_exited_processes
)
7059 remove_process (proc
);
7061 deactivate_process (proc
);
7064 /* The actions above may have further incremented p->tick.
7065 So set p->update_tick again so that an error in the sentinel will
7066 not cause this code to be run again. */
7067 p
->update_tick
= p
->tick
;
7068 /* Now output the message suitably. */
7069 exec_sentinel (proc
, msg
);
7070 if (BUFFERP (p
->buffer
))
7071 /* In case it uses %s in mode-line-format. */
7072 bset_update_mode_line (XBUFFER (p
->buffer
));
7076 return got_some_output
;
7079 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7080 Sinternal_default_process_sentinel
, 2, 2, 0,
7081 doc
: /* Function used as default sentinel for processes.
7082 This inserts a status message into the process's buffer, if there is one. */)
7083 (Lisp_Object proc
, Lisp_Object msg
)
7085 Lisp_Object buffer
, symbol
;
7086 struct Lisp_Process
*p
;
7087 CHECK_PROCESS (proc
);
7088 p
= XPROCESS (proc
);
7092 symbol
= XCAR (symbol
);
7094 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7097 struct buffer
*old
= current_buffer
;
7098 ptrdiff_t opoint
, opoint_byte
;
7099 ptrdiff_t before
, before_byte
;
7101 /* Avoid error if buffer is deleted
7102 (probably that's why the process is dead, too). */
7103 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7105 Fset_buffer (buffer
);
7107 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7108 msg
= (code_convert_string_norecord
7109 (msg
, Vlocale_coding_system
, 1));
7112 opoint_byte
= PT_BYTE
;
7113 /* Insert new output into buffer
7114 at the current end-of-output marker,
7115 thus preserving logical ordering of input and output. */
7116 if (XMARKER (p
->mark
)->buffer
)
7117 Fgoto_char (p
->mark
);
7119 SET_PT_BOTH (ZV
, ZV_BYTE
);
7122 before_byte
= PT_BYTE
;
7124 tem
= BVAR (current_buffer
, read_only
);
7125 bset_read_only (current_buffer
, Qnil
);
7126 insert_string ("\nProcess ");
7127 { /* FIXME: temporary kludge. */
7128 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7129 insert_string (" ");
7131 bset_read_only (current_buffer
, tem
);
7132 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7134 if (opoint
>= before
)
7135 SET_PT_BOTH (opoint
+ (PT
- before
),
7136 opoint_byte
+ (PT_BYTE
- before_byte
));
7138 SET_PT_BOTH (opoint
, opoint_byte
);
7140 set_buffer_internal (old
);
7146 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7147 Sset_process_coding_system
, 1, 3, 0,
7148 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7149 DECODING will be used to decode subprocess output and ENCODING to
7150 encode subprocess input. */)
7151 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7153 CHECK_PROCESS (process
);
7155 struct Lisp_Process
*p
= XPROCESS (process
);
7157 Fcheck_coding_system (decoding
);
7158 Fcheck_coding_system (encoding
);
7159 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7160 pset_decode_coding_system (p
, decoding
);
7161 pset_encode_coding_system (p
, encoding
);
7163 /* If the sockets haven't been set up yet, the final setup part of
7164 this will be called asynchronously. */
7165 if (p
->infd
< 0 || p
->outfd
< 0)
7168 setup_process_coding_systems (process
);
7173 DEFUN ("process-coding-system",
7174 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7175 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7176 (register Lisp_Object process
)
7178 CHECK_PROCESS (process
);
7179 return Fcons (XPROCESS (process
)->decode_coding_system
,
7180 XPROCESS (process
)->encode_coding_system
);
7183 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7184 Sset_process_filter_multibyte
, 2, 2, 0,
7185 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7186 If FLAG is non-nil, the filter is given multibyte strings.
7187 If FLAG is nil, the filter is given unibyte strings. In this case,
7188 all character code conversion except for end-of-line conversion is
7190 (Lisp_Object process
, Lisp_Object flag
)
7192 CHECK_PROCESS (process
);
7194 struct Lisp_Process
*p
= XPROCESS (process
);
7196 pset_decode_coding_system
7197 (p
, raw_text_coding_system (p
->decode_coding_system
));
7199 /* If the sockets haven't been set up yet, the final setup part of
7200 this will be called asynchronously. */
7201 if (p
->infd
< 0 || p
->outfd
< 0)
7204 setup_process_coding_systems (process
);
7209 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7210 Sprocess_filter_multibyte_p
, 1, 1, 0,
7211 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7212 (Lisp_Object process
)
7214 CHECK_PROCESS (process
);
7215 struct Lisp_Process
*p
= XPROCESS (process
);
7218 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7219 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7228 add_gpm_wait_descriptor (int desc
)
7230 add_keyboard_wait_descriptor (desc
);
7234 delete_gpm_wait_descriptor (int desc
)
7236 delete_keyboard_wait_descriptor (desc
);
7241 # ifdef USABLE_SIGIO
7243 /* Return true if *MASK has a bit set
7244 that corresponds to one of the keyboard input descriptors. */
7247 keyboard_bit_set (fd_set
*mask
)
7251 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7252 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7253 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7260 #else /* not subprocesses */
7262 /* Defined in msdos.c. */
7263 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7264 struct timespec
*, void *);
7266 /* Implementation of wait_reading_process_output, assuming that there
7267 are no subprocesses. Used only by the MS-DOS build.
7269 Wait for timeout to elapse and/or keyboard input to be available.
7273 If negative, gobble data immediately available but don't wait for any.
7276 an additional duration to wait, measured in nanoseconds
7277 If TIME_LIMIT is zero, then:
7278 If NSECS == 0, there is no limit.
7279 If NSECS > 0, the timeout consists of NSECS only.
7280 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7283 0 to ignore keyboard input, or
7284 1 to return when input is available, or
7285 -1 means caller will actually read the input, so don't throw to
7288 see full version for other parameters. We know that wait_proc will
7289 always be NULL, since `subprocesses' isn't defined.
7291 DO_DISPLAY means redisplay should be done to show subprocess
7292 output that arrives.
7294 Return -1 signifying we got no output and did not try. */
7297 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7299 Lisp_Object wait_for_cell
,
7300 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7303 struct timespec end_time
, timeout
;
7304 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7306 if (TYPE_MAXIMUM (time_t) < time_limit
)
7307 time_limit
= TYPE_MAXIMUM (time_t);
7309 if (time_limit
< 0 || nsecs
< 0)
7311 else if (time_limit
> 0 || nsecs
> 0)
7314 end_time
= timespec_add (current_timespec (),
7315 make_timespec (time_limit
, nsecs
));
7320 /* Turn off periodic alarms (in case they are in use)
7321 and then turn off any other atimers,
7322 because the select emulator uses alarms. */
7324 turn_on_atimers (0);
7328 bool timeout_reduced_for_timers
= false;
7329 fd_set waitchannels
;
7332 /* If calling from keyboard input, do not quit
7333 since we want to return C-g as an input character.
7334 Otherwise, do pending quit if requested. */
7338 /* Exit now if the cell we're waiting for became non-nil. */
7339 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7342 /* Compute time from now till when time limit is up. */
7343 /* Exit if already run out. */
7344 if (wait
== TIMEOUT
)
7346 struct timespec now
= current_timespec ();
7347 if (timespec_cmp (end_time
, now
) <= 0)
7349 timeout
= timespec_sub (end_time
, now
);
7352 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7354 /* If our caller will not immediately handle keyboard events,
7355 run timer events directly.
7356 (Callers that will immediately read keyboard events
7357 call timer_delay on their own.) */
7358 if (NILP (wait_for_cell
))
7360 struct timespec timer_delay
;
7364 unsigned old_timers_run
= timers_run
;
7365 timer_delay
= timer_check ();
7366 if (timers_run
!= old_timers_run
&& do_display
)
7367 /* We must retry, since a timer may have requeued itself
7368 and that could alter the time delay. */
7369 redisplay_preserve_echo_area (14);
7373 while (!detect_input_pending ());
7375 /* If there is unread keyboard input, also return. */
7377 && requeued_events_pending_p ())
7380 if (timespec_valid_p (timer_delay
))
7382 if (timespec_cmp (timer_delay
, timeout
) < 0)
7384 timeout
= timer_delay
;
7385 timeout_reduced_for_timers
= true;
7390 /* Cause C-g and alarm signals to take immediate action,
7391 and cause input available signals to zero out timeout. */
7393 set_waiting_for_input (&timeout
);
7395 /* If a frame has been newly mapped and needs updating,
7396 reprocess its display stuff. */
7397 if (frame_garbaged
&& do_display
)
7399 clear_waiting_for_input ();
7400 redisplay_preserve_echo_area (15);
7402 set_waiting_for_input (&timeout
);
7405 /* Wait till there is something to do. */
7406 FD_ZERO (&waitchannels
);
7407 if (read_kbd
&& detect_input_pending ())
7411 if (read_kbd
|| !NILP (wait_for_cell
))
7412 FD_SET (0, &waitchannels
);
7413 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7418 /* Make C-g and alarm signals set flags again. */
7419 clear_waiting_for_input ();
7421 /* If we woke up due to SIGWINCH, actually change size now. */
7422 do_pending_window_change (0);
7424 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7425 /* We waited the full specified time, so return now. */
7430 /* If the system call was interrupted, then go around the
7432 if (xerrno
== EINTR
)
7433 FD_ZERO (&waitchannels
);
7435 report_file_errno ("Failed select", Qnil
, xerrno
);
7438 /* Check for keyboard input. */
7441 && detect_input_pending_run_timers (do_display
))
7443 swallow_events (do_display
);
7444 if (detect_input_pending_run_timers (do_display
))
7448 /* If there is unread keyboard input, also return. */
7450 && requeued_events_pending_p ())
7453 /* If wait_for_cell. check for keyboard input
7454 but don't run any timers.
7455 ??? (It seems wrong to me to check for keyboard
7456 input at all when wait_for_cell, but the code
7457 has been this way since July 1994.
7458 Try changing this after version 19.31.) */
7459 if (! NILP (wait_for_cell
)
7460 && detect_input_pending ())
7462 swallow_events (do_display
);
7463 if (detect_input_pending ())
7467 /* Exit now if the cell we're waiting for became non-nil. */
7468 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7477 #endif /* not subprocesses */
7479 /* The following functions are needed even if async subprocesses are
7480 not supported. Some of them are no-op stubs in that case. */
7484 /* Add FD, which is a descriptor returned by timerfd_create,
7485 to the set of non-keyboard input descriptors. */
7488 add_timer_wait_descriptor (int fd
)
7490 FD_SET (fd
, &input_wait_mask
);
7491 FD_SET (fd
, &non_keyboard_wait_mask
);
7492 FD_SET (fd
, &non_process_wait_mask
);
7493 fd_callback_info
[fd
].func
= timerfd_callback
;
7494 fd_callback_info
[fd
].data
= NULL
;
7495 fd_callback_info
[fd
].condition
|= FOR_READ
;
7496 if (fd
> max_input_desc
)
7497 max_input_desc
= fd
;
7500 #endif /* HAVE_TIMERFD */
7502 /* If program file NAME starts with /: for quoting a magic
7503 name, remove that, preserving the multibyteness of NAME. */
7506 remove_slash_colon (Lisp_Object name
)
7509 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7510 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7511 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7515 /* Add DESC to the set of keyboard input descriptors. */
7518 add_keyboard_wait_descriptor (int desc
)
7520 #ifdef subprocesses /* Actually means "not MSDOS". */
7521 FD_SET (desc
, &input_wait_mask
);
7522 FD_SET (desc
, &non_process_wait_mask
);
7523 if (desc
> max_input_desc
)
7524 max_input_desc
= desc
;
7528 /* From now on, do not expect DESC to give keyboard input. */
7531 delete_keyboard_wait_descriptor (int desc
)
7534 FD_CLR (desc
, &input_wait_mask
);
7535 FD_CLR (desc
, &non_process_wait_mask
);
7536 delete_input_desc (desc
);
7540 /* Setup coding systems of PROCESS. */
7543 setup_process_coding_systems (Lisp_Object process
)
7546 struct Lisp_Process
*p
= XPROCESS (process
);
7548 int outch
= p
->outfd
;
7549 Lisp_Object coding_system
;
7551 if (inch
< 0 || outch
< 0)
7554 if (!proc_decode_coding_system
[inch
])
7555 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7556 coding_system
= p
->decode_coding_system
;
7557 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7558 && BUFFERP (p
->buffer
))
7560 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7561 coding_system
= raw_text_coding_system (coding_system
);
7563 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7565 if (!proc_encode_coding_system
[outch
])
7566 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7567 setup_coding_system (p
->encode_coding_system
,
7568 proc_encode_coding_system
[outch
]);
7572 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7573 doc
: /* Return the (or a) live process associated with BUFFER.
7574 BUFFER may be a buffer or the name of one.
7575 Return nil if all processes associated with BUFFER have been
7576 deleted or killed. */)
7577 (register Lisp_Object buffer
)
7580 register Lisp_Object buf
, tail
, proc
;
7582 if (NILP (buffer
)) return Qnil
;
7583 buf
= Fget_buffer (buffer
);
7584 if (NILP (buf
)) return Qnil
;
7586 FOR_EACH_PROCESS (tail
, proc
)
7587 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7589 #endif /* subprocesses */
7593 DEFUN ("process-inherit-coding-system-flag",
7594 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7596 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7597 If this flag is t, `buffer-file-coding-system' of the buffer
7598 associated with PROCESS will inherit the coding system used to decode
7599 the process output. */)
7600 (register Lisp_Object process
)
7603 CHECK_PROCESS (process
);
7604 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7606 /* Ignore the argument and return the value of
7607 inherit-process-coding-system. */
7608 return inherit_process_coding_system
? Qt
: Qnil
;
7612 /* Kill all processes associated with `buffer'.
7613 If `buffer' is nil, kill all processes. */
7616 kill_buffer_processes (Lisp_Object buffer
)
7619 Lisp_Object tail
, proc
;
7621 FOR_EACH_PROCESS (tail
, proc
)
7622 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7624 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7625 Fdelete_process (proc
);
7626 else if (XPROCESS (proc
)->infd
>= 0)
7627 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7629 #else /* subprocesses */
7630 /* Since we have no subprocesses, this does nothing. */
7631 #endif /* subprocesses */
7634 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7635 Swaiting_for_user_input_p
, 0, 0, 0,
7636 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7637 This is intended for use by asynchronous process output filters and sentinels. */)
7641 return (waiting_for_user_input_p
? Qt
: Qnil
);
7647 /* Stop reading input from keyboard sources. */
7650 hold_keyboard_input (void)
7655 /* Resume reading input from keyboard sources. */
7658 unhold_keyboard_input (void)
7663 /* Return true if keyboard input is on hold, zero otherwise. */
7666 kbd_on_hold_p (void)
7668 return kbd_is_on_hold
;
7672 /* Enumeration of and access to system processes a-la ps(1). */
7674 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7676 doc
: /* Return a list of numerical process IDs of all running processes.
7677 If this functionality is unsupported, return nil.
7679 See `process-attributes' for getting attributes of a process given its ID. */)
7682 return list_system_processes ();
7685 DEFUN ("process-attributes", Fprocess_attributes
,
7686 Sprocess_attributes
, 1, 1, 0,
7687 doc
: /* Return attributes of the process given by its PID, a number.
7689 Value is an alist where each element is a cons cell of the form
7693 If this functionality is unsupported, the value is nil.
7695 See `list-system-processes' for getting a list of all process IDs.
7697 The KEYs of the attributes that this function may return are listed
7698 below, together with the type of the associated VALUE (in parentheses).
7699 Not all platforms support all of these attributes; unsupported
7700 attributes will not appear in the returned alist.
7701 Unless explicitly indicated otherwise, numbers can have either
7702 integer or floating point values.
7704 euid -- Effective user User ID of the process (number)
7705 user -- User name corresponding to euid (string)
7706 egid -- Effective user Group ID of the process (number)
7707 group -- Group name corresponding to egid (string)
7708 comm -- Command name (executable name only) (string)
7709 state -- Process state code, such as "S", "R", or "T" (string)
7710 ppid -- Parent process ID (number)
7711 pgrp -- Process group ID (number)
7712 sess -- Session ID, i.e. process ID of session leader (number)
7713 ttname -- Controlling tty name (string)
7714 tpgid -- ID of foreground process group on the process's tty (number)
7715 minflt -- number of minor page faults (number)
7716 majflt -- number of major page faults (number)
7717 cminflt -- cumulative number of minor page faults (number)
7718 cmajflt -- cumulative number of major page faults (number)
7719 utime -- user time used by the process, in (current-time) format,
7720 which is a list of integers (HIGH LOW USEC PSEC)
7721 stime -- system time used by the process (current-time)
7722 time -- sum of utime and stime (current-time)
7723 cutime -- user time used by the process and its children (current-time)
7724 cstime -- system time used by the process and its children (current-time)
7725 ctime -- sum of cutime and cstime (current-time)
7726 pri -- priority of the process (number)
7727 nice -- nice value of the process (number)
7728 thcount -- process thread count (number)
7729 start -- time the process started (current-time)
7730 vsize -- virtual memory size of the process in KB's (number)
7731 rss -- resident set size of the process in KB's (number)
7732 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7733 pcpu -- percents of CPU time used by the process (floating-point number)
7734 pmem -- percents of total physical memory used by process's resident set
7735 (floating-point number)
7736 args -- command line which invoked the process (string). */)
7739 return system_process_attributes (pid
);
7743 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7744 Invoke this after init_process_emacs, and after glib and/or GNUstep
7745 futz with the SIGCHLD handler, but before Emacs forks any children.
7746 This function's caller should block SIGCHLD. */
7749 catch_child_signal (void)
7751 struct sigaction action
, old_action
;
7753 emacs_sigaction_init (&action
, deliver_child_signal
);
7754 block_child_signal (&oldset
);
7755 sigaction (SIGCHLD
, &action
, &old_action
);
7756 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7757 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7759 if (old_action
.sa_handler
!= deliver_child_signal
)
7761 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7763 : old_action
.sa_handler
);
7764 unblock_child_signal (&oldset
);
7766 #endif /* subprocesses */
7769 /* This is not called "init_process" because that is the name of a
7770 Mach system call, so it would cause problems on Darwin systems. */
7772 init_process_emacs (int sockfd
)
7777 inhibit_sentinels
= 0;
7780 if (! noninteractive
|| initialized
)
7783 #if defined HAVE_GLIB && !defined WINDOWSNT
7784 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7785 this should always fail, but is enough to initialize glib's
7786 private SIGCHLD handler, allowing catch_child_signal to copy
7787 it into lib_child_handler. */
7788 g_source_unref (g_child_watch_source_new (getpid ()));
7790 catch_child_signal ();
7793 #ifdef HAVE_SETRLIMIT
7794 /* Don't allocate more than FD_SETSIZE file descriptors. */
7796 if (getrlimit (RLIMIT_NOFILE
, &rlim
) == 0 && FD_SETSIZE
< rlim
.rlim_cur
)
7798 rlim
.rlim_cur
= FD_SETSIZE
;
7799 setrlimit (RLIMIT_NOFILE
, &rlim
);
7803 FD_ZERO (&input_wait_mask
);
7804 FD_ZERO (&non_keyboard_wait_mask
);
7805 FD_ZERO (&non_process_wait_mask
);
7806 FD_ZERO (&write_mask
);
7807 max_process_desc
= max_input_desc
= -1;
7808 external_sock_fd
= sockfd
;
7809 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7811 FD_ZERO (&connect_wait_mask
);
7812 num_pending_connects
= 0;
7814 process_output_delay_count
= 0;
7815 process_output_skip
= 0;
7817 /* Don't do this, it caused infinite select loops. The display
7818 method should call add_keyboard_wait_descriptor on stdin if it
7821 FD_SET (0, &input_wait_mask
);
7824 Vprocess_alist
= Qnil
;
7825 deleted_pid_list
= Qnil
;
7826 for (i
= 0; i
< FD_SETSIZE
; i
++)
7828 chan_process
[i
] = Qnil
;
7829 proc_buffered_char
[i
] = -1;
7831 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7832 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7833 #ifdef DATAGRAM_SOCKETS
7834 memset (datagram_address
, 0, sizeof datagram_address
);
7837 #if defined (DARWIN_OS)
7838 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7839 processes. As such, we only change the default value. */
7842 char const *release
= (STRINGP (Voperating_system_release
)
7843 ? SSDATA (Voperating_system_release
)
7845 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7846 Vprocess_connection_type
= Qnil
;
7850 #endif /* subprocesses */
7855 syms_of_process (void)
7859 DEFSYM (Qprocessp
, "processp");
7860 DEFSYM (Qrun
, "run");
7861 DEFSYM (Qstop
, "stop");
7862 DEFSYM (Qsignal
, "signal");
7864 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7867 DEFSYM (Qopen
, "open");
7868 DEFSYM (Qclosed
, "closed");
7869 DEFSYM (Qconnect
, "connect");
7870 DEFSYM (Qfailed
, "failed");
7871 DEFSYM (Qlisten
, "listen");
7872 DEFSYM (Qlocal
, "local");
7873 DEFSYM (Qipv4
, "ipv4");
7875 DEFSYM (Qipv6
, "ipv6");
7877 DEFSYM (Qdatagram
, "datagram");
7878 DEFSYM (Qseqpacket
, "seqpacket");
7880 DEFSYM (QCport
, ":port");
7881 DEFSYM (QCspeed
, ":speed");
7882 DEFSYM (QCprocess
, ":process");
7884 DEFSYM (QCbytesize
, ":bytesize");
7885 DEFSYM (QCstopbits
, ":stopbits");
7886 DEFSYM (QCparity
, ":parity");
7887 DEFSYM (Qodd
, "odd");
7888 DEFSYM (Qeven
, "even");
7889 DEFSYM (QCflowcontrol
, ":flowcontrol");
7892 DEFSYM (QCsummary
, ":summary");
7894 DEFSYM (Qreal
, "real");
7895 DEFSYM (Qnetwork
, "network");
7896 DEFSYM (Qserial
, "serial");
7897 DEFSYM (Qpipe
, "pipe");
7898 DEFSYM (QCbuffer
, ":buffer");
7899 DEFSYM (QChost
, ":host");
7900 DEFSYM (QCservice
, ":service");
7901 DEFSYM (QClocal
, ":local");
7902 DEFSYM (QCremote
, ":remote");
7903 DEFSYM (QCcoding
, ":coding");
7904 DEFSYM (QCserver
, ":server");
7905 DEFSYM (QCnowait
, ":nowait");
7906 DEFSYM (QCsentinel
, ":sentinel");
7907 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7908 DEFSYM (QCtls_parameters
, ":tls-parameters");
7909 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7910 DEFSYM (QClog
, ":log");
7911 DEFSYM (QCnoquery
, ":noquery");
7912 DEFSYM (QCstop
, ":stop");
7913 DEFSYM (QCplist
, ":plist");
7914 DEFSYM (QCcommand
, ":command");
7915 DEFSYM (QCconnection_type
, ":connection-type");
7916 DEFSYM (QCstderr
, ":stderr");
7917 DEFSYM (Qpty
, "pty");
7918 DEFSYM (Qpipe
, "pipe");
7920 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7922 staticpro (&Vprocess_alist
);
7923 staticpro (&deleted_pid_list
);
7925 #endif /* subprocesses */
7927 DEFSYM (QCname
, ":name");
7928 DEFSYM (QCtype
, ":type");
7930 DEFSYM (Qeuid
, "euid");
7931 DEFSYM (Qegid
, "egid");
7932 DEFSYM (Quser
, "user");
7933 DEFSYM (Qgroup
, "group");
7934 DEFSYM (Qcomm
, "comm");
7935 DEFSYM (Qstate
, "state");
7936 DEFSYM (Qppid
, "ppid");
7937 DEFSYM (Qpgrp
, "pgrp");
7938 DEFSYM (Qsess
, "sess");
7939 DEFSYM (Qttname
, "ttname");
7940 DEFSYM (Qtpgid
, "tpgid");
7941 DEFSYM (Qminflt
, "minflt");
7942 DEFSYM (Qmajflt
, "majflt");
7943 DEFSYM (Qcminflt
, "cminflt");
7944 DEFSYM (Qcmajflt
, "cmajflt");
7945 DEFSYM (Qutime
, "utime");
7946 DEFSYM (Qstime
, "stime");
7947 DEFSYM (Qtime
, "time");
7948 DEFSYM (Qcutime
, "cutime");
7949 DEFSYM (Qcstime
, "cstime");
7950 DEFSYM (Qctime
, "ctime");
7952 DEFSYM (Qinternal_default_process_sentinel
,
7953 "internal-default-process-sentinel");
7954 DEFSYM (Qinternal_default_process_filter
,
7955 "internal-default-process-filter");
7957 DEFSYM (Qpri
, "pri");
7958 DEFSYM (Qnice
, "nice");
7959 DEFSYM (Qthcount
, "thcount");
7960 DEFSYM (Qstart
, "start");
7961 DEFSYM (Qvsize
, "vsize");
7962 DEFSYM (Qrss
, "rss");
7963 DEFSYM (Qetime
, "etime");
7964 DEFSYM (Qpcpu
, "pcpu");
7965 DEFSYM (Qpmem
, "pmem");
7966 DEFSYM (Qargs
, "args");
7968 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7969 doc
: /* Non-nil means delete processes immediately when they exit.
7970 A value of nil means don't delete them until `list-processes' is run. */);
7972 delete_exited_processes
= 1;
7975 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7976 doc
: /* Control type of device used to communicate with subprocesses.
7977 Values are nil to use a pipe, or t or `pty' to use a pty.
7978 The value has no effect if the system has no ptys or if all ptys are busy:
7979 then a pipe is used in any case.
7980 The value takes effect when `start-process' is called. */);
7981 Vprocess_connection_type
= Qt
;
7983 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7984 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7985 On some systems, when Emacs reads the output from a subprocess, the output data
7986 is read in very small blocks, potentially resulting in very poor performance.
7987 This behavior can be remedied to some extent by setting this variable to a
7988 non-nil value, as it will automatically delay reading from such processes, to
7989 allow them to produce more output before Emacs tries to read it.
7990 If the value is t, the delay is reset after each write to the process; any other
7991 non-nil value means that the delay is not reset on write.
7992 The variable takes effect when `start-process' is called. */);
7993 Vprocess_adaptive_read_buffering
= Qt
;
7995 defsubr (&Sprocessp
);
7996 defsubr (&Sget_process
);
7997 defsubr (&Sdelete_process
);
7998 defsubr (&Sprocess_status
);
7999 defsubr (&Sprocess_exit_status
);
8000 defsubr (&Sprocess_id
);
8001 defsubr (&Sprocess_name
);
8002 defsubr (&Sprocess_tty_name
);
8003 defsubr (&Sprocess_command
);
8004 defsubr (&Sset_process_buffer
);
8005 defsubr (&Sprocess_buffer
);
8006 defsubr (&Sprocess_mark
);
8007 defsubr (&Sset_process_filter
);
8008 defsubr (&Sprocess_filter
);
8009 defsubr (&Sset_process_sentinel
);
8010 defsubr (&Sprocess_sentinel
);
8011 defsubr (&Sset_process_window_size
);
8012 defsubr (&Sset_process_inherit_coding_system_flag
);
8013 defsubr (&Sset_process_query_on_exit_flag
);
8014 defsubr (&Sprocess_query_on_exit_flag
);
8015 defsubr (&Sprocess_contact
);
8016 defsubr (&Sprocess_plist
);
8017 defsubr (&Sset_process_plist
);
8018 defsubr (&Sprocess_list
);
8019 defsubr (&Smake_process
);
8020 defsubr (&Smake_pipe_process
);
8021 defsubr (&Sserial_process_configure
);
8022 defsubr (&Smake_serial_process
);
8023 defsubr (&Sset_network_process_option
);
8024 defsubr (&Smake_network_process
);
8025 defsubr (&Sformat_network_address
);
8026 defsubr (&Snetwork_interface_list
);
8027 defsubr (&Snetwork_interface_info
);
8028 #ifdef DATAGRAM_SOCKETS
8029 defsubr (&Sprocess_datagram_address
);
8030 defsubr (&Sset_process_datagram_address
);
8032 defsubr (&Saccept_process_output
);
8033 defsubr (&Sprocess_send_region
);
8034 defsubr (&Sprocess_send_string
);
8035 defsubr (&Sinterrupt_process
);
8036 defsubr (&Skill_process
);
8037 defsubr (&Squit_process
);
8038 defsubr (&Sstop_process
);
8039 defsubr (&Scontinue_process
);
8040 defsubr (&Sprocess_running_child_p
);
8041 defsubr (&Sprocess_send_eof
);
8042 defsubr (&Ssignal_process
);
8043 defsubr (&Swaiting_for_user_input_p
);
8044 defsubr (&Sprocess_type
);
8045 defsubr (&Sinternal_default_process_sentinel
);
8046 defsubr (&Sinternal_default_process_filter
);
8047 defsubr (&Sset_process_coding_system
);
8048 defsubr (&Sprocess_coding_system
);
8049 defsubr (&Sset_process_filter_multibyte
);
8050 defsubr (&Sprocess_filter_multibyte_p
);
8053 Lisp_Object subfeatures
= Qnil
;
8054 const struct socket_options
*sopt
;
8056 #define ADD_SUBFEATURE(key, val) \
8057 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8059 ADD_SUBFEATURE (QCnowait
, Qt
);
8060 #ifdef DATAGRAM_SOCKETS
8061 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8063 #ifdef HAVE_SEQPACKET
8064 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8066 #ifdef HAVE_LOCAL_SOCKETS
8067 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8069 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8071 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8073 #ifdef HAVE_GETSOCKNAME
8074 ADD_SUBFEATURE (QCservice
, Qt
);
8076 ADD_SUBFEATURE (QCserver
, Qt
);
8078 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8079 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8081 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8084 #endif /* subprocesses */
8086 defsubr (&Sget_buffer_process
);
8087 defsubr (&Sprocess_inherit_coding_system_flag
);
8088 defsubr (&Slist_system_processes
);
8089 defsubr (&Sprocess_attributes
);