1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2018 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 <https://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>
43 #endif /* subprocesses */
46 # include <sys/resource.h>
48 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
49 NOFILE_LIMIT is the initial limit on the number of open files,
50 which should be restored in child processes. */
51 static struct rlimit nofile_limit
;
56 /* Are local (unix) sockets supported? */
57 #if defined (HAVE_SYS_UN_H)
58 #if !defined (AF_LOCAL) && defined (AF_UNIX)
59 #define AF_LOCAL AF_UNIX
62 #define HAVE_LOCAL_SOCKETS
67 #include <sys/ioctl.h>
68 #if defined (HAVE_NET_IF_H)
70 #endif /* HAVE_NET_IF_H */
72 #if defined (HAVE_IFADDRS_H)
73 /* Must be after net/if.h */
76 /* We only use structs from this header when we use getifaddrs. */
77 #if defined (HAVE_NET_IF_DL_H)
78 #include <net/if_dl.h>
88 # include <sys/stream.h>
89 # include <sys/stropts.h>
101 #include <flexmember.h>
105 #endif /* subprocesses */
111 #include "character.h"
116 #include "termopts.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
120 #include "sysselect.h"
121 #include "syssignal.h"
127 #ifdef HAVE_WINDOW_SYSTEM
129 #endif /* HAVE_WINDOW_SYSTEM */
132 #include "xgselect.h"
138 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
139 /* This is 0.1s in nanoseconds. */
140 #define ASYNC_RETRY_NSEC 100000000
144 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
145 const struct timespec
*, const sigset_t
*);
148 /* Work around GCC 4.3.0 bug with strict overflow checking; see
149 <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
150 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
151 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
152 # pragma GCC diagnostic ignored "-Wstrict-overflow"
155 /* True if keyboard input is on hold, zero otherwise. */
157 static bool kbd_is_on_hold
;
159 /* Nonzero means don't run process sentinels. This is used
161 bool inhibit_sentinels
;
166 struct sockaddr_in in
;
168 struct sockaddr_in6 in6
;
170 #ifdef HAVE_LOCAL_SOCKETS
171 struct sockaddr_un un
;
178 # define SOCK_CLOEXEC 0
180 #ifndef SOCK_NONBLOCK
181 # define SOCK_NONBLOCK 0
184 /* True if ERRNUM represents an error where the system call would
185 block if a blocking variant were used. */
187 would_block (int errnum
)
190 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
193 return errnum
== EAGAIN
;
198 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
201 close_on_exec (int fd
)
204 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
209 # define accept4(sockfd, addr, addrlen, flags) \
210 process_accept4 (sockfd, addr, addrlen, flags)
212 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
214 return close_on_exec (accept (sockfd
, addr
, addrlen
));
218 process_socket (int domain
, int type
, int protocol
)
220 return close_on_exec (socket (domain
, type
, protocol
));
223 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
226 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
227 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
228 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
229 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
230 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
231 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
233 /* Number of events of change of status of a process. */
234 static EMACS_INT process_tick
;
235 /* Number of events for which the user or sentinel has been notified. */
236 static EMACS_INT update_tick
;
238 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
239 this system. We need to read full packets, so we need a
240 "non-destructive" select. So we require either native select,
241 or emulation of select using FIONREAD. */
243 #ifndef BROKEN_DATAGRAM_SOCKETS
244 # if defined HAVE_SELECT || defined USABLE_FIONREAD
245 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
246 # define DATAGRAM_SOCKETS
251 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
252 # define HAVE_SEQPACKET
255 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
256 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
257 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
259 /* Number of processes which have a non-zero read_output_delay,
260 and therefore might be delayed for adaptive read buffering. */
262 static int process_output_delay_count
;
264 /* True if any process has non-nil read_output_skip. */
266 static bool process_output_skip
;
268 static void start_process_unwind (Lisp_Object
);
269 static void create_process (Lisp_Object
, char **, Lisp_Object
);
271 static bool keyboard_bit_set (fd_set
*);
273 static void deactivate_process (Lisp_Object
);
274 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
275 static int read_process_output (Lisp_Object
, int);
276 static void create_pty (Lisp_Object
);
277 static void exec_sentinel (Lisp_Object
, Lisp_Object
);
279 /* Number of bits set in connect_wait_mask. */
280 static int num_pending_connects
;
282 /* The largest descriptor currently in use; -1 if none. */
285 /* Set the external socket descriptor for Emacs to use when
286 `make-network-process' is called with a non-nil
287 `:use-external-socket' option. The value should be either -1, or
288 the file descriptor of a socket that is already bound. */
289 static int external_sock_fd
;
291 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
292 static Lisp_Object chan_process
[FD_SETSIZE
];
293 static void wait_for_socket_fds (Lisp_Object
, char const *);
295 /* Alist of elements (NAME . PROCESS). */
296 static Lisp_Object Vprocess_alist
;
298 /* Buffered-ahead input char from process, indexed by channel.
299 -1 means empty (no char is buffered).
300 Used on sys V where the only way to tell if there is any
301 output from the process is to read at least one char.
302 Always -1 on systems that support FIONREAD. */
304 static int proc_buffered_char
[FD_SETSIZE
];
306 /* Table of `struct coding-system' for each process. */
307 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
308 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
310 #ifdef DATAGRAM_SOCKETS
311 /* Table of `partner address' for datagram sockets. */
312 static struct sockaddr_and_len
{
315 } datagram_address
[FD_SETSIZE
];
316 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
317 #define DATAGRAM_CONN_P(proc) \
318 (PROCESSP (proc) && \
319 XPROCESS (proc)->infd >= 0 && \
320 datagram_address[XPROCESS (proc)->infd].sa != 0)
322 #define DATAGRAM_CONN_P(proc) (0)
325 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
326 a `for' loop which iterates over processes from Vprocess_alist. */
328 #define FOR_EACH_PROCESS(list_var, proc_var) \
329 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
331 /* These setters are used only in this file, so they can be private. */
333 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
338 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
343 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
345 p
->decode_coding_system
= val
;
348 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
350 p
->decoding_buf
= val
;
353 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
355 p
->encode_coding_system
= val
;
358 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
360 p
->encoding_buf
= val
;
363 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
365 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
368 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
373 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_thread (struct Lisp_Process
*p
, Lisp_Object val
)
383 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
388 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
393 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
395 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
398 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
403 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
408 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
410 p
->write_queue
= val
;
413 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
420 make_lisp_proc (struct Lisp_Process
*p
)
422 return make_lisp_ptr (p
, Lisp_Vectorlike
);
427 /* Read from file descriptor. */
429 /* Write to file descriptor. */
431 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
434 /* This descriptor refers to a process. */
436 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
437 NON_BLOCKING_CONNECT_FD
= 16
440 static struct fd_callback_data
444 /* Flags from enum fd_bits. */
446 /* If this fd is locked to a certain thread, this points to it.
447 Otherwise, this is NULL. If an fd is locked to a thread, then
448 only that thread is permitted to wait on it. */
449 struct thread_state
*thread
;
450 /* If this fd is currently being selected on by a thread, this
451 points to the thread. Otherwise it is NULL. */
452 struct thread_state
*waiting_thread
;
453 } fd_callback_info
[FD_SETSIZE
];
456 /* Add a file descriptor FD to be monitored for when read is possible.
457 When read is possible, call FUNC with argument DATA. */
460 add_read_fd (int fd
, fd_callback func
, void *data
)
462 add_keyboard_wait_descriptor (fd
);
464 fd_callback_info
[fd
].func
= func
;
465 fd_callback_info
[fd
].data
= data
;
469 add_non_keyboard_read_fd (int fd
)
471 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
472 eassert (fd_callback_info
[fd
].func
== NULL
);
474 fd_callback_info
[fd
].flags
&= ~KEYBOARD_FD
;
475 fd_callback_info
[fd
].flags
|= FOR_READ
;
481 add_process_read_fd (int fd
)
483 add_non_keyboard_read_fd (fd
);
484 fd_callback_info
[fd
].flags
|= PROCESS_FD
;
487 /* Stop monitoring file descriptor FD for when read is possible. */
490 delete_read_fd (int fd
)
492 delete_keyboard_wait_descriptor (fd
);
494 if (fd_callback_info
[fd
].flags
== 0)
496 fd_callback_info
[fd
].func
= 0;
497 fd_callback_info
[fd
].data
= 0;
501 /* Add a file descriptor FD to be monitored for when write is possible.
502 When write is possible, call FUNC with argument DATA. */
505 add_write_fd (int fd
, fd_callback func
, void *data
)
507 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
509 fd_callback_info
[fd
].func
= func
;
510 fd_callback_info
[fd
].data
= data
;
511 fd_callback_info
[fd
].flags
|= FOR_WRITE
;
517 add_non_blocking_write_fd (int fd
)
519 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
520 eassert (fd_callback_info
[fd
].func
== NULL
);
522 fd_callback_info
[fd
].flags
|= FOR_WRITE
| NON_BLOCKING_CONNECT_FD
;
525 ++num_pending_connects
;
529 recompute_max_desc (void)
533 for (fd
= max_desc
; fd
>= 0; --fd
)
535 if (fd_callback_info
[fd
].flags
!= 0)
543 /* Stop monitoring file descriptor FD for when write is possible. */
546 delete_write_fd (int fd
)
548 if ((fd_callback_info
[fd
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
550 if (--num_pending_connects
< 0)
553 fd_callback_info
[fd
].flags
&= ~(FOR_WRITE
| NON_BLOCKING_CONNECT_FD
);
554 if (fd_callback_info
[fd
].flags
== 0)
556 fd_callback_info
[fd
].func
= 0;
557 fd_callback_info
[fd
].data
= 0;
560 recompute_max_desc ();
565 compute_input_wait_mask (fd_set
*mask
)
570 for (fd
= 0; fd
<= max_desc
; ++fd
)
572 if (fd_callback_info
[fd
].thread
!= NULL
573 && fd_callback_info
[fd
].thread
!= current_thread
)
575 if (fd_callback_info
[fd
].waiting_thread
!= NULL
576 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
578 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0)
581 fd_callback_info
[fd
].waiting_thread
= current_thread
;
587 compute_non_process_wait_mask (fd_set
*mask
)
592 for (fd
= 0; fd
<= max_desc
; ++fd
)
594 if (fd_callback_info
[fd
].thread
!= NULL
595 && fd_callback_info
[fd
].thread
!= current_thread
)
597 if (fd_callback_info
[fd
].waiting_thread
!= NULL
598 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
600 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
601 && (fd_callback_info
[fd
].flags
& PROCESS_FD
) == 0)
604 fd_callback_info
[fd
].waiting_thread
= current_thread
;
610 compute_non_keyboard_wait_mask (fd_set
*mask
)
615 for (fd
= 0; fd
<= max_desc
; ++fd
)
617 if (fd_callback_info
[fd
].thread
!= NULL
618 && fd_callback_info
[fd
].thread
!= current_thread
)
620 if (fd_callback_info
[fd
].waiting_thread
!= NULL
621 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
623 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
624 && (fd_callback_info
[fd
].flags
& KEYBOARD_FD
) == 0)
627 fd_callback_info
[fd
].waiting_thread
= current_thread
;
633 compute_write_mask (fd_set
*mask
)
638 for (fd
= 0; fd
<= max_desc
; ++fd
)
640 if (fd_callback_info
[fd
].thread
!= NULL
641 && fd_callback_info
[fd
].thread
!= current_thread
)
643 if (fd_callback_info
[fd
].waiting_thread
!= NULL
644 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
646 if ((fd_callback_info
[fd
].flags
& FOR_WRITE
) != 0)
649 fd_callback_info
[fd
].waiting_thread
= current_thread
;
655 clear_waiting_thread_info (void)
659 for (fd
= 0; fd
<= max_desc
; ++fd
)
661 if (fd_callback_info
[fd
].waiting_thread
== current_thread
)
662 fd_callback_info
[fd
].waiting_thread
= NULL
;
667 /* Compute the Lisp form of the process status, p->status, from
668 the numeric status that was returned by `wait'. */
670 static Lisp_Object
status_convert (int);
673 update_status (struct Lisp_Process
*p
)
675 eassert (p
->raw_status_new
);
676 pset_status (p
, status_convert (p
->raw_status
));
677 p
->raw_status_new
= 0;
680 /* Convert a process status word in Unix format to
681 the list that we use internally. */
684 status_convert (int w
)
687 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
688 else if (WIFEXITED (w
))
689 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
690 WCOREDUMP (w
) ? Qt
: Qnil
));
691 else if (WIFSIGNALED (w
))
692 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
693 WCOREDUMP (w
) ? Qt
: Qnil
));
698 /* True if STATUS is that of a process attempting connection. */
701 connecting_status (Lisp_Object status
)
703 return CONSP (status
) && EQ (XCAR (status
), Qconnect
);
706 /* Given a status-list, extract the three pieces of information
707 and store them individually through the three pointers. */
710 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, Lisp_Object
*code
,
715 if (connecting_status (l
))
721 *code
= make_number (0);
730 *coredump
= !NILP (tem
);
734 /* Return a string describing a process status list. */
737 status_message (struct Lisp_Process
*p
)
739 Lisp_Object status
= p
->status
;
740 Lisp_Object symbol
, code
;
744 decode_status (status
, &symbol
, &code
, &coredump
);
746 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
749 synchronize_system_messages_locale ();
750 signame
= strsignal (XFASTINT (code
));
752 string
= build_string ("unknown");
757 string
= build_unibyte_string (signame
);
758 if (! NILP (Vlocale_coding_system
))
759 string
= (code_convert_string_norecord
760 (string
, Vlocale_coding_system
, 0));
761 c1
= STRING_CHAR (SDATA (string
));
764 Faset (string
, make_number (0), make_number (c2
));
766 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
767 return concat2 (string
, suffix
);
769 else if (EQ (symbol
, Qexit
))
772 return build_string (XFASTINT (code
) == 0
774 : "connection broken by remote peer\n");
775 if (XFASTINT (code
) == 0)
776 return build_string ("finished\n");
777 AUTO_STRING (prefix
, "exited abnormally with code ");
778 string
= Fnumber_to_string (code
);
779 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
780 return concat3 (prefix
, string
, suffix
);
782 else if (EQ (symbol
, Qfailed
))
784 AUTO_STRING (format
, "failed with code %s\n");
785 return CALLN (Fformat
, format
, code
);
788 return Fcopy_sequence (Fsymbol_name (symbol
));
791 enum { PTY_NAME_SIZE
= 24 };
793 /* Open an available pty, returning a file descriptor.
794 Store into PTY_NAME the file name of the terminal corresponding to the pty.
795 Return -1 on failure. */
798 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
807 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
808 for (i
= 0; i
< 16; i
++)
811 #ifdef PTY_NAME_SPRINTF
814 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
815 #endif /* no PTY_NAME_SPRINTF */
819 #else /* no PTY_OPEN */
820 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
821 #endif /* no PTY_OPEN */
825 #ifdef PTY_TTY_NAME_SPRINTF
828 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
829 #endif /* no PTY_TTY_NAME_SPRINTF */
831 /* Set FD's close-on-exec flag. This is needed even if
832 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
833 doesn't require support for that combination.
834 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
835 doesn't work if the close-on-exec flag is set (Bug#20555).
836 Multithreaded platforms where posix_openpt ignores
837 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
838 have a race condition between the PTY_OPEN and here. */
839 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
841 /* Check to make certain that both sides are available.
842 This avoids a nasty yet stupid bug in rlogins. */
843 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
852 #endif /* HAVE_PTYS */
856 /* Allocate basically initialized process. */
858 static struct Lisp_Process
*
859 allocate_process (void)
861 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
865 make_process (Lisp_Object name
)
867 struct Lisp_Process
*p
= allocate_process ();
868 /* Initialize Lisp data. Note that allocate_process initializes all
869 Lisp data to nil, so do it only for slots which should not be nil. */
870 pset_status (p
, Qrun
);
871 pset_mark (p
, Fmake_marker ());
872 pset_thread (p
, Fcurrent_thread ());
874 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
875 non-Lisp data, so do it only for slots which should not be zero. */
878 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
882 verify (GNUTLS_STAGE_EMPTY
== 0);
883 eassert (p
->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
884 eassert (NILP (p
->gnutls_boot_parameters
));
887 /* If name is already in use, modify it until it is unused. */
889 Lisp_Object name1
= name
;
890 for (printmax_t i
= 1; ; i
++)
892 Lisp_Object tem
= Fget_process (name1
);
895 char const suffix_fmt
[] = "<%"pMd
">";
896 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
897 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
898 name1
= concat2 (name
, lsuffix
);
902 pset_sentinel (p
, Qinternal_default_process_sentinel
);
903 pset_filter (p
, Qinternal_default_process_filter
);
905 XSETPROCESS (val
, p
);
906 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
911 remove_process (register Lisp_Object proc
)
913 register Lisp_Object pair
;
915 pair
= Frassq (proc
, Vprocess_alist
);
916 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
918 deactivate_process (proc
);
922 update_processes_for_thread_death (Lisp_Object dying_thread
)
926 for (pair
= Vprocess_alist
; !NILP (pair
); pair
= XCDR (pair
))
928 Lisp_Object process
= XCDR (XCAR (pair
));
929 if (EQ (XPROCESS (process
)->thread
, dying_thread
))
931 struct Lisp_Process
*proc
= XPROCESS (process
);
933 pset_thread (proc
, Qnil
);
935 fd_callback_info
[proc
->infd
].thread
= NULL
;
936 if (proc
->outfd
>= 0)
937 fd_callback_info
[proc
->outfd
].thread
= NULL
;
942 #ifdef HAVE_GETADDRINFO_A
944 free_dns_request (Lisp_Object proc
)
946 struct Lisp_Process
*p
= XPROCESS (proc
);
948 if (p
->dns_request
->ar_result
)
949 freeaddrinfo (p
->dns_request
->ar_result
);
950 xfree (p
->dns_request
);
951 p
->dns_request
= NULL
;
956 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
957 doc
: /* Return t if OBJECT is a process. */)
960 return PROCESSP (object
) ? Qt
: Qnil
;
963 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
964 doc
: /* Return the process named NAME, or nil if there is none. */)
965 (register Lisp_Object name
)
970 return Fcdr (Fassoc (name
, Vprocess_alist
, Qnil
));
973 /* This is how commands for the user decode process arguments. It
974 accepts a process, a process name, a buffer, a buffer name, or nil.
975 Buffers denote the first process in the buffer, and nil denotes the
979 get_process (register Lisp_Object name
)
981 register Lisp_Object proc
, obj
;
984 obj
= Fget_process (name
);
986 obj
= Fget_buffer (name
);
988 error ("Process %s does not exist", SDATA (name
));
990 else if (NILP (name
))
991 obj
= Fcurrent_buffer ();
995 /* Now obj should be either a buffer object or a process object. */
998 if (NILP (BVAR (XBUFFER (obj
), name
)))
999 error ("Attempt to get process for a dead buffer");
1000 proc
= Fget_buffer_process (obj
);
1002 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
1006 CHECK_PROCESS (obj
);
1013 /* Fdelete_process promises to immediately forget about the process, but in
1014 reality, Emacs needs to remember those processes until they have been
1015 treated by the SIGCHLD handler and waitpid has been invoked on them;
1016 otherwise they might fill up the kernel's process table.
1018 Some processes created by call-process are also put onto this list.
1020 Members of this list are (process-ID . filename) pairs. The
1021 process-ID is a number; the filename, if a string, is a file that
1022 needs to be removed after the process exits. */
1023 static Lisp_Object deleted_pid_list
;
1026 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
1028 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
1029 /* GC treated elements set to nil. */
1030 Fdelq (Qnil
, deleted_pid_list
));
1034 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
1035 doc
: /* Delete PROCESS: kill it and forget about it immediately.
1036 PROCESS may be a process, a buffer, the name of a process or buffer, or
1037 nil, indicating the current buffer's process. */)
1038 (register Lisp_Object process
)
1040 register struct Lisp_Process
*p
;
1042 process
= get_process (process
);
1043 p
= XPROCESS (process
);
1045 #ifdef HAVE_GETADDRINFO_A
1048 /* Cancel the request. Unless shutting down, wait until
1049 completion. Free the request if completely canceled. */
1051 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
1052 if (!canceled
&& !inhibit_sentinels
)
1054 struct gaicb
const *req
= p
->dns_request
;
1055 while (gai_suspend (&req
, 1, NULL
) != 0)
1060 free_dns_request (process
);
1064 p
->raw_status_new
= 0;
1065 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1067 pset_status (p
, list2 (Qexit
, make_number (0)));
1068 p
->tick
= ++process_tick
;
1069 status_notify (p
, NULL
);
1070 redisplay_preserve_echo_area (13);
1075 record_kill_process (p
, Qnil
);
1079 /* Update P's status, since record_kill_process will make the
1080 SIGCHLD handler update deleted_pid_list, not *P. */
1082 if (p
->raw_status_new
)
1084 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
1085 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
1086 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
1088 p
->tick
= ++process_tick
;
1089 status_notify (p
, NULL
);
1090 redisplay_preserve_echo_area (13);
1093 remove_process (process
);
1097 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
1098 doc
: /* Return the status of PROCESS.
1099 The returned value is one of the following symbols:
1100 run -- for a process that is running.
1101 stop -- for a process stopped but continuable.
1102 exit -- for a process that has exited.
1103 signal -- for a process that has got a fatal signal.
1104 open -- for a network stream connection that is open.
1105 listen -- for a network stream server that is listening.
1106 closed -- for a network stream connection that is closed.
1107 connect -- when waiting for a non-blocking connection to complete.
1108 failed -- when a non-blocking connection has failed.
1109 nil -- if arg is a process name and no such process exists.
1110 PROCESS may be a process, a buffer, the name of a process, or
1111 nil, indicating the current buffer's process. */)
1112 (register Lisp_Object process
)
1114 register struct Lisp_Process
*p
;
1115 register Lisp_Object status
;
1117 if (STRINGP (process
))
1118 process
= Fget_process (process
);
1120 process
= get_process (process
);
1125 p
= XPROCESS (process
);
1126 if (p
->raw_status_new
)
1130 status
= XCAR (status
);
1131 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1133 if (EQ (status
, Qexit
))
1135 else if (EQ (p
->command
, Qt
))
1137 else if (EQ (status
, Qrun
))
1143 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
1145 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
1146 If PROCESS has not yet exited or died, return 0. */)
1147 (register Lisp_Object process
)
1149 CHECK_PROCESS (process
);
1150 if (XPROCESS (process
)->raw_status_new
)
1151 update_status (XPROCESS (process
));
1152 if (CONSP (XPROCESS (process
)->status
))
1153 return XCAR (XCDR (XPROCESS (process
)->status
));
1154 return make_number (0);
1157 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
1158 doc
: /* Return the process id of PROCESS.
1159 This is the pid of the external process which PROCESS uses or talks to.
1160 For a network, serial, and pipe connections, this value is nil. */)
1161 (register Lisp_Object process
)
1165 CHECK_PROCESS (process
);
1166 pid
= XPROCESS (process
)->pid
;
1167 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
1170 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
1171 doc
: /* Return the name of PROCESS, as a string.
1172 This is the name of the program invoked in PROCESS,
1173 possibly modified to make it unique among process names. */)
1174 (register Lisp_Object process
)
1176 CHECK_PROCESS (process
);
1177 return XPROCESS (process
)->name
;
1180 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1181 doc
: /* Return the command that was executed to start PROCESS.
1182 This is a list of strings, the first string being the program executed
1183 and the rest of the strings being the arguments given to it.
1184 For a network or serial or pipe connection, this is nil (process is running)
1185 or t (process is stopped). */)
1186 (register Lisp_Object process
)
1188 CHECK_PROCESS (process
);
1189 return XPROCESS (process
)->command
;
1192 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1193 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1194 This is the terminal that the process itself reads and writes on,
1195 not the name of the pty that Emacs uses to talk with that terminal. */)
1196 (register Lisp_Object process
)
1198 CHECK_PROCESS (process
);
1199 return XPROCESS (process
)->tty_name
;
1202 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1204 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1206 (register Lisp_Object process
, Lisp_Object buffer
)
1208 struct Lisp_Process
*p
;
1210 CHECK_PROCESS (process
);
1212 CHECK_BUFFER (buffer
);
1213 p
= XPROCESS (process
);
1214 pset_buffer (p
, buffer
);
1215 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1216 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1217 setup_process_coding_systems (process
);
1221 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1223 doc
: /* Return the buffer PROCESS is associated with.
1224 The default process filter inserts output from PROCESS into this buffer. */)
1225 (register Lisp_Object process
)
1227 CHECK_PROCESS (process
);
1228 return XPROCESS (process
)->buffer
;
1231 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1233 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1234 (register Lisp_Object process
)
1236 CHECK_PROCESS (process
);
1237 return XPROCESS (process
)->mark
;
1241 set_process_filter_masks (struct Lisp_Process
*p
)
1243 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1244 delete_read_fd (p
->infd
);
1245 else if (EQ (p
->filter
, Qt
)
1246 /* Network or serial process not stopped: */
1247 && !EQ (p
->command
, Qt
))
1248 add_process_read_fd (p
->infd
);
1251 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1253 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1254 A value of t means stop accepting output from the process.
1256 When a process has a non-default filter, its buffer is not used for output.
1257 Instead, each time it does output, the entire string of output is
1258 passed to the filter.
1260 The filter gets two arguments: the process and the string of output.
1261 The string argument is normally a multibyte string, except:
1262 - if the process's input coding system is no-conversion or raw-text,
1263 it is a unibyte string (the non-converted input). */)
1264 (Lisp_Object process
, Lisp_Object filter
)
1266 CHECK_PROCESS (process
);
1267 struct Lisp_Process
*p
= XPROCESS (process
);
1269 /* Don't signal an error if the process's input file descriptor
1270 is closed. This could make debugging Lisp more difficult,
1271 for example when doing something like
1273 (setq process (start-process ...))
1275 (set-process-filter process ...) */
1278 filter
= Qinternal_default_process_filter
;
1280 pset_filter (p
, filter
);
1283 set_process_filter_masks (p
);
1285 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1286 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1287 setup_process_coding_systems (process
);
1291 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1293 doc
: /* Return the filter function of PROCESS.
1294 See `set-process-filter' for more info on filter functions. */)
1295 (register Lisp_Object process
)
1297 CHECK_PROCESS (process
);
1298 return XPROCESS (process
)->filter
;
1301 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1303 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1304 The sentinel is called as a function when the process changes state.
1305 It gets two arguments: the process, and a string describing the change. */)
1306 (register Lisp_Object process
, Lisp_Object sentinel
)
1308 struct Lisp_Process
*p
;
1310 CHECK_PROCESS (process
);
1311 p
= XPROCESS (process
);
1313 if (NILP (sentinel
))
1314 sentinel
= Qinternal_default_process_sentinel
;
1316 pset_sentinel (p
, sentinel
);
1317 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1318 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1322 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1324 doc
: /* Return the sentinel of PROCESS.
1325 See `set-process-sentinel' for more info on sentinels. */)
1326 (register Lisp_Object process
)
1328 CHECK_PROCESS (process
);
1329 return XPROCESS (process
)->sentinel
;
1332 DEFUN ("set-process-thread", Fset_process_thread
, Sset_process_thread
,
1334 doc
: /* Set the locking thread of PROCESS to be THREAD.
1335 If THREAD is nil, the process is unlocked. */)
1336 (Lisp_Object process
, Lisp_Object thread
)
1338 struct Lisp_Process
*proc
;
1339 struct thread_state
*tstate
;
1341 CHECK_PROCESS (process
);
1346 CHECK_THREAD (thread
);
1347 tstate
= XTHREAD (thread
);
1350 proc
= XPROCESS (process
);
1351 pset_thread (proc
, thread
);
1352 if (proc
->infd
>= 0)
1353 fd_callback_info
[proc
->infd
].thread
= tstate
;
1354 if (proc
->outfd
>= 0)
1355 fd_callback_info
[proc
->outfd
].thread
= tstate
;
1360 DEFUN ("process-thread", Fprocess_thread
, Sprocess_thread
,
1362 doc
: /* Ret the locking thread of PROCESS.
1363 If PROCESS is unlocked, this function returns nil. */)
1364 (Lisp_Object process
)
1366 CHECK_PROCESS (process
);
1367 return XPROCESS (process
)->thread
;
1370 DEFUN ("set-process-window-size", Fset_process_window_size
,
1371 Sset_process_window_size
, 3, 3, 0,
1372 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1373 Value is t if PROCESS was successfully told about the window size,
1375 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1377 CHECK_PROCESS (process
);
1379 /* All known platforms store window sizes as 'unsigned short'. */
1380 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1381 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1383 if (NETCONN_P (process
)
1384 || XPROCESS (process
)->infd
< 0
1385 || (set_window_size (XPROCESS (process
)->infd
,
1386 XINT (height
), XINT (width
))
1393 DEFUN ("set-process-inherit-coding-system-flag",
1394 Fset_process_inherit_coding_system_flag
,
1395 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1396 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1397 If the second argument FLAG is non-nil, then the variable
1398 `buffer-file-coding-system' of the buffer associated with PROCESS
1399 will be bound to the value of the coding system used to decode
1402 This is useful when the coding system specified for the process buffer
1403 leaves either the character code conversion or the end-of-line conversion
1404 unspecified, or if the coding system used to decode the process output
1405 is more appropriate for saving the process buffer.
1407 Binding the variable `inherit-process-coding-system' to non-nil before
1408 starting the process is an alternative way of setting the inherit flag
1409 for the process which will run.
1411 This function returns FLAG. */)
1412 (register Lisp_Object process
, Lisp_Object flag
)
1414 CHECK_PROCESS (process
);
1415 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1419 DEFUN ("set-process-query-on-exit-flag",
1420 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1422 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1423 If the second argument FLAG is non-nil, Emacs will query the user before
1424 exiting or killing a buffer if PROCESS is running. This function
1426 (register Lisp_Object process
, Lisp_Object flag
)
1428 CHECK_PROCESS (process
);
1429 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1433 DEFUN ("process-query-on-exit-flag",
1434 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1436 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1437 (register Lisp_Object process
)
1439 CHECK_PROCESS (process
);
1440 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1443 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1445 doc
: /* Return the contact info of PROCESS; t for a real child.
1446 For a network or serial or pipe connection, the value depends on the
1447 optional KEY arg. If KEY is nil, value is a cons cell of the form
1448 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1449 connection; it is t for a pipe connection. If KEY is t, the complete
1450 contact information for the connection is returned, else the specific
1451 value for the keyword KEY is returned. See `make-network-process',
1452 `make-serial-process', or `make-pipe-process' for the list of keywords.
1453 If PROCESS is a non-blocking network process that hasn't been fully
1454 set up yet, this function will block until socket setup has completed. */)
1455 (Lisp_Object process
, Lisp_Object key
)
1457 Lisp_Object contact
;
1459 CHECK_PROCESS (process
);
1460 contact
= XPROCESS (process
)->childp
;
1462 #ifdef DATAGRAM_SOCKETS
1464 if (NETCONN_P (process
))
1465 wait_for_socket_fds (process
, "process-contact");
1467 if (DATAGRAM_CONN_P (process
)
1468 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1469 contact
= Fplist_put (contact
, QCremote
,
1470 Fprocess_datagram_address (process
));
1473 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1476 if (NILP (key
) && NETCONN_P (process
))
1477 return list2 (Fplist_get (contact
, QChost
),
1478 Fplist_get (contact
, QCservice
));
1479 if (NILP (key
) && SERIALCONN_P (process
))
1480 return list2 (Fplist_get (contact
, QCport
),
1481 Fplist_get (contact
, QCspeed
));
1482 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1483 if the pipe process is useful for purposes other than receiving
1485 if (NILP (key
) && PIPECONN_P (process
))
1487 return Fplist_get (contact
, key
);
1490 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1492 doc
: /* Return the plist of PROCESS. */)
1493 (register Lisp_Object process
)
1495 CHECK_PROCESS (process
);
1496 return XPROCESS (process
)->plist
;
1499 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1501 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1502 (Lisp_Object process
, Lisp_Object plist
)
1504 CHECK_PROCESS (process
);
1507 pset_plist (XPROCESS (process
), plist
);
1511 #if 0 /* Turned off because we don't currently record this info
1512 in the process. Perhaps add it. */
1513 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1514 doc
: /* Return the connection type of PROCESS.
1515 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1516 a socket connection. */)
1517 (Lisp_Object process
)
1519 return XPROCESS (process
)->type
;
1523 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1524 doc
: /* Return the connection type of PROCESS.
1525 The value is either the symbol `real', `network', `serial', or `pipe'.
1526 PROCESS may be a process, a buffer, the name of a process or buffer, or
1527 nil, indicating the current buffer's process. */)
1528 (Lisp_Object process
)
1531 proc
= get_process (process
);
1532 return XPROCESS (proc
)->type
;
1535 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1537 doc
: /* Convert network ADDRESS from internal format to a string.
1538 A 4 or 5 element vector represents an IPv4 address (with port number).
1539 An 8 or 9 element vector represents an IPv6 address (with port number).
1540 If optional second argument OMIT-PORT is non-nil, don't include a port
1541 number in the string, even when present in ADDRESS.
1542 Return nil if format of ADDRESS is invalid. */)
1543 (Lisp_Object address
, Lisp_Object omit_port
)
1548 if (STRINGP (address
)) /* AF_LOCAL */
1551 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1553 register struct Lisp_Vector
*p
= XVECTOR (address
);
1554 ptrdiff_t size
= p
->header
.size
;
1555 Lisp_Object args
[10];
1559 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1561 format
= "%d.%d.%d.%d";
1566 format
= "%d.%d.%d.%d:%d";
1569 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1571 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1576 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1582 AUTO_STRING (format_obj
, format
);
1583 args
[0] = format_obj
;
1585 for (i
= 0; i
< nargs
; i
++)
1587 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1590 if (nargs
<= 5 /* IPv4 */
1591 && i
< 4 /* host, not port */
1592 && XINT (p
->contents
[i
]) > 255)
1595 args
[i
+ 1] = p
->contents
[i
];
1598 return Fformat (nargs
+ 1, args
);
1601 if (CONSP (address
))
1603 AUTO_STRING (format
, "<Family %d>");
1604 return CALLN (Fformat
, format
, Fcar (address
));
1610 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1611 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1614 return Fmapcar (Qcdr
, Vprocess_alist
);
1617 /* Starting asynchronous inferior processes. */
1619 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1620 doc
: /* Start a program in a subprocess. Return the process object for it.
1622 This is similar to `start-process', but arguments are specified as
1623 keyword/argument pairs. The following arguments are defined:
1625 :name NAME -- NAME is name for process. It is modified if necessary
1628 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1629 with the process. Process output goes at end of that buffer, unless
1630 you specify a filter function to handle the output. BUFFER may be
1631 also nil, meaning that this process is not associated with any buffer.
1633 :command COMMAND -- COMMAND is a list starting with the program file
1634 name, followed by strings to give to the program as arguments.
1636 :coding CODING -- If CODING is a symbol, it specifies the coding
1637 system used for both reading and writing for this process. If CODING
1638 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1639 ENCODING is used for writing.
1641 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1642 the process is running. If BOOL is not given, query before exiting.
1644 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1645 In the stopped state, a process does not accept incoming data, but you
1646 can send outgoing data. The stopped state is cleared by
1647 `continue-process' and set by `stop-process'.
1649 :connection-type TYPE -- TYPE is control type of device used to
1650 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1651 to use a pty, or nil to use the default specified through
1652 `process-connection-type'.
1654 :filter FILTER -- Install FILTER as the process filter.
1656 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1658 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1659 to the standard error of subprocess. Specifying this implies
1660 `:connection-type' is set to `pipe'.
1662 usage: (make-process &rest ARGS) */)
1663 (ptrdiff_t nargs
, Lisp_Object
*args
)
1665 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1666 Lisp_Object xstderr
, stderrproc
;
1667 ptrdiff_t count
= SPECPDL_INDEX ();
1672 /* Save arguments for process-contact and clone-process. */
1673 contact
= Flist (nargs
, args
);
1675 buffer
= Fplist_get (contact
, QCbuffer
);
1677 buffer
= Fget_buffer_create (buffer
);
1679 /* Make sure that the child will be able to chdir to the current
1680 buffer's current directory, or its unhandled equivalent. We
1681 can't just have the child check for an error when it does the
1682 chdir, since it's in a vfork. */
1683 current_dir
= encode_current_directory ();
1685 name
= Fplist_get (contact
, QCname
);
1686 CHECK_STRING (name
);
1688 command
= Fplist_get (contact
, QCcommand
);
1689 if (CONSP (command
))
1690 program
= XCAR (command
);
1694 if (!NILP (program
))
1695 CHECK_STRING (program
);
1697 bool query_on_exit
= NILP (Fplist_get (contact
, QCnoquery
));
1700 xstderr
= Fplist_get (contact
, QCstderr
);
1701 if (PROCESSP (xstderr
))
1703 if (!PIPECONN_P (xstderr
))
1704 error ("Process is not a pipe process");
1705 stderrproc
= xstderr
;
1707 else if (!NILP (xstderr
))
1709 CHECK_STRING (program
);
1710 stderrproc
= CALLN (Fmake_pipe_process
,
1712 concat2 (name
, build_string (" stderr")),
1714 Fget_buffer_create (xstderr
),
1716 query_on_exit
? Qnil
: Qt
);
1719 proc
= make_process (name
);
1720 record_unwind_protect (start_process_unwind
, proc
);
1722 pset_childp (XPROCESS (proc
), Qt
);
1723 eassert (NILP (XPROCESS (proc
)->plist
));
1724 pset_type (XPROCESS (proc
), Qreal
);
1725 pset_buffer (XPROCESS (proc
), buffer
);
1726 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1727 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1728 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1731 XPROCESS (proc
)->kill_without_query
= 1;
1732 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1733 pset_command (XPROCESS (proc
), Qt
);
1735 tem
= Fplist_get (contact
, QCconnection_type
);
1737 XPROCESS (proc
)->pty_flag
= true;
1738 else if (EQ (tem
, Qpipe
))
1739 XPROCESS (proc
)->pty_flag
= false;
1740 else if (NILP (tem
))
1741 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1743 report_file_error ("Unknown connection type", tem
);
1745 if (!NILP (stderrproc
))
1747 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1749 XPROCESS (proc
)->pty_flag
= false;
1753 /* AKA GNUTLS_INITSTAGE(proc). */
1754 verify (GNUTLS_STAGE_EMPTY
== 0);
1755 eassert (XPROCESS (proc
)->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
1756 eassert (NILP (XPROCESS (proc
)->gnutls_cred_type
));
1759 XPROCESS (proc
)->adaptive_read_buffering
1760 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1761 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1763 /* Make the process marker point into the process buffer (if any). */
1764 if (BUFFERP (buffer
))
1765 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1766 BUF_ZV (XBUFFER (buffer
)),
1767 BUF_ZV_BYTE (XBUFFER (buffer
)));
1772 /* Decide coding systems for communicating with the process. Here
1773 we don't setup the structure coding_system nor pay attention to
1774 unibyte mode. They are done in create_process. */
1776 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1777 Lisp_Object coding_systems
= Qt
;
1778 Lisp_Object val
, *args2
;
1780 tem
= Fplist_get (contact
, QCcoding
);
1788 val
= Vcoding_system_for_read
;
1791 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1793 SAFE_ALLOCA_LISP (args2
, nargs2
);
1795 args2
[i
++] = Qstart_process
;
1797 args2
[i
++] = buffer
;
1798 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1799 args2
[i
++] = XCAR (tem2
);
1800 if (!NILP (program
))
1801 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1802 if (CONSP (coding_systems
))
1803 val
= XCAR (coding_systems
);
1804 else if (CONSP (Vdefault_process_coding_system
))
1805 val
= XCAR (Vdefault_process_coding_system
);
1807 pset_decode_coding_system (XPROCESS (proc
), val
);
1816 val
= Vcoding_system_for_write
;
1819 if (EQ (coding_systems
, Qt
))
1821 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1823 SAFE_ALLOCA_LISP (args2
, nargs2
);
1825 args2
[i
++] = Qstart_process
;
1827 args2
[i
++] = buffer
;
1828 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1829 args2
[i
++] = XCAR (tem2
);
1830 if (!NILP (program
))
1831 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1833 if (CONSP (coding_systems
))
1834 val
= XCDR (coding_systems
);
1835 else if (CONSP (Vdefault_process_coding_system
))
1836 val
= XCDR (Vdefault_process_coding_system
);
1838 pset_encode_coding_system (XPROCESS (proc
), val
);
1839 /* Note: At this moment, the above coding system may leave
1840 text-conversion or eol-conversion unspecified. They will be
1841 decided after we read output from the process and decode it by
1842 some coding system, or just before we actually send a text to
1847 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1848 eassert (XPROCESS (proc
)->decoding_carryover
== 0);
1849 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1851 XPROCESS (proc
)->inherit_coding_system_flag
1852 = !(NILP (buffer
) || !inherit_process_coding_system
);
1854 if (!NILP (program
))
1856 Lisp_Object program_args
= XCDR (command
);
1858 /* If program file name is not absolute, search our path for it.
1859 Put the name we will really use in TEM. */
1860 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1861 && !(SCHARS (program
) > 1
1862 && IS_DEVICE_SEP (SREF (program
, 1))))
1865 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1866 make_number (X_OK
), false);
1868 report_file_error ("Searching for program", program
);
1869 tem
= Fexpand_file_name (tem
, Qnil
);
1873 if (!NILP (Ffile_directory_p (program
)))
1874 error ("Specified program for new process is a directory");
1878 /* Remove "/:" from TEM. */
1879 tem
= remove_slash_colon (tem
);
1881 Lisp_Object arg_encoding
= Qnil
;
1883 /* Encode the file name and put it in NEW_ARGV.
1884 That's where the child will use it to execute the program. */
1885 tem
= list1 (ENCODE_FILE (tem
));
1886 ptrdiff_t new_argc
= 1;
1888 /* Here we encode arguments by the coding system used for sending
1889 data to the process. We don't support using different coding
1890 systems for encoding arguments and for encoding data sent to the
1893 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1895 Lisp_Object arg
= XCAR (tem2
);
1897 if (STRING_MULTIBYTE (arg
))
1899 if (NILP (arg_encoding
))
1900 arg_encoding
= (complement_process_encoding_system
1901 (XPROCESS (proc
)->encode_coding_system
));
1902 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1904 tem
= Fcons (arg
, tem
);
1908 /* Now that everything is encoded we can collect the strings into
1911 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1912 new_argv
[new_argc
] = 0;
1914 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1916 new_argv
[i
] = SSDATA (XCAR (tem
));
1920 create_process (proc
, new_argv
, current_dir
);
1926 return unbind_to (count
, proc
);
1929 /* If PROC doesn't have its pid set, then an error was signaled and
1930 the process wasn't started successfully, so remove it. */
1932 start_process_unwind (Lisp_Object proc
)
1934 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1935 remove_process (proc
);
1938 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1941 close_process_fd (int *fd_addr
)
1951 /* Indexes of file descriptors in open_fds. */
1954 /* The pipe from Emacs to its subprocess. */
1956 WRITE_TO_SUBPROCESS
,
1958 /* The main pipe from the subprocess to Emacs. */
1959 READ_FROM_SUBPROCESS
,
1962 /* The pipe from the subprocess to Emacs that is closed when the
1963 subprocess execs. */
1964 READ_FROM_EXEC_MONITOR
,
1968 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1971 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1973 struct Lisp_Process
*p
= XPROCESS (process
);
1974 int inchannel
, outchannel
;
1977 int forkin
, forkout
, forkerr
= -1;
1979 char pty_name
[PTY_NAME_SIZE
];
1980 Lisp_Object lisp_pty_name
= Qnil
;
1983 inchannel
= outchannel
= -1;
1986 outchannel
= inchannel
= allocate_pty (pty_name
);
1990 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1991 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1992 /* On most USG systems it does not work to open the pty's tty here,
1993 then close it and reopen it in the child. */
1994 /* Don't let this terminal become our controlling terminal
1995 (in case we don't have one). */
1996 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1998 report_file_error ("Opening pty", Qnil
);
1999 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
2001 forkin
= forkout
= -1;
2002 #endif /* not USG, or USG_SUBTTY_WORKS */
2004 lisp_pty_name
= build_string (pty_name
);
2008 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2009 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2010 report_file_error ("Creating pipe", Qnil
);
2011 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
2012 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2013 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2014 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
2016 if (!NILP (p
->stderrproc
))
2018 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2020 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
2022 /* Close unnecessary file descriptors. */
2023 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
2024 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
2029 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
2030 report_file_error ("Creating pipe", Qnil
);
2033 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2034 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2036 /* Record this as an active process, with its channels. */
2037 chan_process
[inchannel
] = process
;
2038 p
->infd
= inchannel
;
2039 p
->outfd
= outchannel
;
2041 /* Previously we recorded the tty descriptor used in the subprocess.
2042 It was only used for getting the foreground tty process, so now
2043 we just reopen the device (see emacs_get_tty_pgrp) as this is
2044 more portable (see USG_SUBTTY_WORKS above). */
2046 p
->pty_flag
= pty_flag
;
2047 pset_status (p
, Qrun
);
2049 if (!EQ (p
->command
, Qt
))
2050 add_process_read_fd (inchannel
);
2052 /* This may signal an error. */
2053 setup_process_coding_systems (process
);
2056 block_child_signal (&oldset
);
2059 /* vfork, and prevent local vars from being clobbered by the vfork. */
2060 Lisp_Object
volatile current_dir_volatile
= current_dir
;
2061 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
2062 char **volatile new_argv_volatile
= new_argv
;
2063 int volatile forkin_volatile
= forkin
;
2064 int volatile forkout_volatile
= forkout
;
2065 int volatile forkerr_volatile
= forkerr
;
2066 struct Lisp_Process
*p_volatile
= p
;
2069 /* Darwin doesn't let us run setsid after a vfork, so use fork when
2070 necessary. Also, reset SIGCHLD handling after a vfork, as
2071 apparently macOS can mistakenly deliver SIGCHLD to the child. */
2078 signal (SIGCHLD
, SIG_DFL
);
2084 current_dir
= current_dir_volatile
;
2085 lisp_pty_name
= lisp_pty_name_volatile
;
2086 new_argv
= new_argv_volatile
;
2087 forkin
= forkin_volatile
;
2088 forkout
= forkout_volatile
;
2089 forkerr
= forkerr_volatile
;
2092 pty_flag
= p
->pty_flag
;
2095 #endif /* not WINDOWSNT */
2097 /* Make the pty be the controlling terminal of the process. */
2099 /* First, disconnect its current controlling terminal.
2100 Do this even if !PTY_FLAG; see Bug#30762. */
2102 /* Make the pty's terminal the controlling terminal. */
2103 if (pty_flag
&& forkin
>= 0)
2106 /* We ignore the return value
2107 because faith@cs.unc.edu says that is necessary on Linux. */
2108 ioctl (forkin
, TIOCSCTTY
, 0);
2111 #if defined (LDISC1)
2112 if (pty_flag
&& forkin
>= 0)
2115 tcgetattr (forkin
, &t
);
2117 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
2118 emacs_perror ("create_process/tcsetattr LDISC1");
2121 #if defined (NTTYDISC) && defined (TIOCSETD)
2122 if (pty_flag
&& forkin
>= 0)
2124 /* Use new line discipline. */
2125 int ldisc
= NTTYDISC
;
2126 ioctl (forkin
, TIOCSETD
, &ldisc
);
2131 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2132 can do TIOCSPGRP only to the process's controlling tty. */
2135 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2136 I can't test it since I don't have 4.3. */
2137 int j
= emacs_open (DEV_TTY
, O_RDWR
, 0);
2140 ioctl (j
, TIOCNOTTY
, 0);
2144 #endif /* TIOCNOTTY */
2146 #if !defined (DONT_REOPEN_PTY)
2147 /*** There is a suggestion that this ought to be a
2148 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2149 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2150 that system does seem to need this code, even though
2151 both TIOCSCTTY is defined. */
2152 /* Now close the pty (if we had it open) and reopen it.
2153 This makes the pty the controlling terminal of the subprocess. */
2157 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2160 emacs_close (forkin
);
2161 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
2165 emacs_perror (SSDATA (lisp_pty_name
));
2166 _exit (EXIT_CANCELED
);
2170 #endif /* not DONT_REOPEN_PTY */
2172 #ifdef SETUP_SLAVE_PTY
2177 #endif /* SETUP_SLAVE_PTY */
2178 #endif /* HAVE_PTYS */
2180 signal (SIGINT
, SIG_DFL
);
2181 signal (SIGQUIT
, SIG_DFL
);
2183 signal (SIGPROF
, SIG_DFL
);
2186 /* Emacs ignores SIGPIPE, but the child should not. */
2187 signal (SIGPIPE
, SIG_DFL
);
2189 /* Stop blocking SIGCHLD in the child. */
2190 unblock_child_signal (&oldset
);
2193 child_setup_tty (forkout
);
2198 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
2199 #else /* not WINDOWSNT */
2200 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
2201 #endif /* not WINDOWSNT */
2204 /* Back in the parent process. */
2206 vfork_errno
= errno
;
2211 /* Stop blocking in the parent. */
2212 unblock_child_signal (&oldset
);
2216 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2219 /* vfork succeeded. */
2221 /* Close the pipe ends that the child uses, or the child's pty. */
2222 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2223 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2226 register_child (pid
, inchannel
);
2227 #endif /* WINDOWSNT */
2229 pset_tty_name (p
, lisp_pty_name
);
2232 /* Wait for child_setup to complete in case that vfork is
2233 actually defined as fork. The descriptor
2234 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2235 of a pipe is closed at the child side either by close-on-exec
2236 on successful execve or the _exit call in child_setup. */
2240 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2241 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2242 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2245 if (!NILP (p
->stderrproc
))
2247 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2248 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2254 create_pty (Lisp_Object process
)
2256 struct Lisp_Process
*p
= XPROCESS (process
);
2257 char pty_name
[PTY_NAME_SIZE
];
2258 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2262 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2263 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2264 /* On most USG systems it does not work to open the pty's tty here,
2265 then close it and reopen it in the child. */
2266 /* Don't let this terminal become our controlling terminal
2267 (in case we don't have one). */
2268 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2270 report_file_error ("Opening pty", Qnil
);
2271 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2272 #if defined (DONT_REOPEN_PTY)
2273 /* In the case that vfork is defined as fork, the parent process
2274 (Emacs) may send some data before the child process completes
2275 tty options setup. So we setup tty before forking. */
2276 child_setup_tty (forkout
);
2277 #endif /* DONT_REOPEN_PTY */
2278 #endif /* not USG, or USG_SUBTTY_WORKS */
2280 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2282 /* Record this as an active process, with its channels.
2283 As a result, child_setup will close Emacs's side of the pipes. */
2284 chan_process
[pty_fd
] = process
;
2288 /* Previously we recorded the tty descriptor used in the subprocess.
2289 It was only used for getting the foreground tty process, so now
2290 we just reopen the device (see emacs_get_tty_pgrp) as this is
2291 more portable (see USG_SUBTTY_WORKS above). */
2294 pset_status (p
, Qrun
);
2295 setup_process_coding_systems (process
);
2297 add_process_read_fd (pty_fd
);
2299 pset_tty_name (p
, build_string (pty_name
));
2305 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2307 doc
: /* Create and return a bidirectional pipe process.
2309 In Emacs, pipes are represented by process objects, so input and
2310 output work as for subprocesses, and `delete-process' closes a pipe.
2311 However, a pipe process has no process id, it cannot be signaled,
2312 and the status codes are different from normal processes.
2314 Arguments are specified as keyword/argument pairs. The following
2315 arguments are defined:
2317 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2319 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2320 with the process. Process output goes at the end of that buffer,
2321 unless you specify a filter function to handle the output. If BUFFER
2322 is not given, the value of NAME is used.
2324 :coding CODING -- If CODING is a symbol, it specifies the coding
2325 system used for both reading and writing for this process. If CODING
2326 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2327 ENCODING is used for writing.
2329 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2330 the process is running. If BOOL is not given, query before exiting.
2332 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2333 In the stopped state, a pipe process does not accept incoming data,
2334 but you can send outgoing data. The stopped state is cleared by
2335 `continue-process' and set by `stop-process'.
2337 :filter FILTER -- Install FILTER as the process filter.
2339 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2341 usage: (make-pipe-process &rest ARGS) */)
2342 (ptrdiff_t nargs
, Lisp_Object
*args
)
2344 Lisp_Object proc
, contact
;
2345 struct Lisp_Process
*p
;
2346 Lisp_Object name
, buffer
;
2348 ptrdiff_t specpdl_count
;
2349 int inchannel
, outchannel
;
2354 contact
= Flist (nargs
, args
);
2356 name
= Fplist_get (contact
, QCname
);
2357 CHECK_STRING (name
);
2358 proc
= make_process (name
);
2359 specpdl_count
= SPECPDL_INDEX ();
2360 record_unwind_protect (remove_process
, proc
);
2361 p
= XPROCESS (proc
);
2363 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2364 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2365 report_file_error ("Creating pipe", Qnil
);
2366 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2367 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2369 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2370 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2373 register_aux_fd (inchannel
);
2376 /* Record this as an active process, with its channels. */
2377 chan_process
[inchannel
] = proc
;
2378 p
->infd
= inchannel
;
2379 p
->outfd
= outchannel
;
2381 if (inchannel
> max_desc
)
2382 max_desc
= inchannel
;
2384 buffer
= Fplist_get (contact
, QCbuffer
);
2387 buffer
= Fget_buffer_create (buffer
);
2388 pset_buffer (p
, buffer
);
2390 pset_childp (p
, contact
);
2391 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2392 pset_type (p
, Qpipe
);
2393 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2394 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2395 eassert (NILP (p
->log
));
2396 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2397 p
->kill_without_query
= 1;
2398 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2399 pset_command (p
, Qt
);
2400 eassert (! p
->pty_flag
);
2402 if (!EQ (p
->command
, Qt
))
2403 add_process_read_fd (inchannel
);
2404 p
->adaptive_read_buffering
2405 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2406 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2408 /* Make the process marker point into the process buffer (if any). */
2409 if (BUFFERP (buffer
))
2410 set_marker_both (p
->mark
, buffer
,
2411 BUF_ZV (XBUFFER (buffer
)),
2412 BUF_ZV_BYTE (XBUFFER (buffer
)));
2415 /* Setup coding systems for communicating with the network stream. */
2417 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2418 Lisp_Object coding_systems
= Qt
;
2421 tem
= Fplist_get (contact
, QCcoding
);
2429 else if (!NILP (Vcoding_system_for_read
))
2430 val
= Vcoding_system_for_read
;
2431 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2432 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2433 /* We dare not decode end-of-line format by setting VAL to
2434 Qraw_text, because the existing Emacs Lisp libraries
2435 assume that they receive bare code including a sequence of
2440 if (CONSP (coding_systems
))
2441 val
= XCAR (coding_systems
);
2442 else if (CONSP (Vdefault_process_coding_system
))
2443 val
= XCAR (Vdefault_process_coding_system
);
2447 pset_decode_coding_system (p
, val
);
2455 else if (!NILP (Vcoding_system_for_write
))
2456 val
= Vcoding_system_for_write
;
2457 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2461 if (CONSP (coding_systems
))
2462 val
= XCDR (coding_systems
);
2463 else if (CONSP (Vdefault_process_coding_system
))
2464 val
= XCDR (Vdefault_process_coding_system
);
2468 pset_encode_coding_system (p
, val
);
2470 /* This may signal an error. */
2471 setup_process_coding_systems (proc
);
2473 specpdl_ptr
= specpdl
+ specpdl_count
;
2479 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2480 The address family of sa is not included in the result. */
2483 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2485 Lisp_Object address
;
2488 struct Lisp_Vector
*p
;
2490 /* Workaround for a bug in getsockname on BSD: Names bound to
2491 sockets in the UNIX domain are inaccessible; getsockname returns
2492 a zero length name. */
2493 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2494 return empty_unibyte_string
;
2496 switch (sa
->sa_family
)
2500 DECLARE_POINTER_ALIAS (sin
, struct sockaddr_in
, sa
);
2501 len
= sizeof (sin
->sin_addr
) + 1;
2502 address
= Fmake_vector (make_number (len
), Qnil
);
2503 p
= XVECTOR (address
);
2504 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2505 cp
= (unsigned char *) &sin
->sin_addr
;
2511 DECLARE_POINTER_ALIAS (sin6
, struct sockaddr_in6
, sa
);
2512 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &sin6
->sin6_addr
);
2513 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2514 address
= Fmake_vector (make_number (len
), Qnil
);
2515 p
= XVECTOR (address
);
2516 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2517 for (i
= 0; i
< len
; i
++)
2518 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2522 #ifdef HAVE_LOCAL_SOCKETS
2525 DECLARE_POINTER_ALIAS (sockun
, struct sockaddr_un
, sa
);
2526 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2527 /* If the first byte is NUL, the name is a Linux abstract
2528 socket name, and the name can contain embedded NULs. If
2529 it's not, we have a NUL-terminated string. Be careful not
2530 to walk past the end of the object looking for the name
2531 terminator, however. */
2532 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2534 const char *terminator
2535 = memchr (sockun
->sun_path
, '\0', name_length
);
2538 name_length
= terminator
- (const char *) sockun
->sun_path
;
2541 return make_unibyte_string (sockun
->sun_path
, name_length
);
2545 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2546 address
= Fcons (make_number (sa
->sa_family
),
2547 Fmake_vector (make_number (len
), Qnil
));
2548 p
= XVECTOR (XCDR (address
));
2549 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2555 p
->contents
[i
++] = make_number (*cp
++);
2560 /* Convert an internal struct addrinfo to a Lisp object. */
2563 conv_addrinfo_to_lisp (struct addrinfo
*res
)
2565 Lisp_Object protocol
= make_number (res
->ai_protocol
);
2566 eassert (XINT (protocol
) == res
->ai_protocol
);
2567 return Fcons (protocol
, conv_sockaddr_to_lisp (res
->ai_addr
, res
->ai_addrlen
));
2571 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2574 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2576 struct Lisp_Vector
*p
;
2578 if (VECTORP (address
))
2580 p
= XVECTOR (address
);
2581 if (p
->header
.size
== 5)
2584 return sizeof (struct sockaddr_in
);
2587 else if (p
->header
.size
== 9)
2589 *familyp
= AF_INET6
;
2590 return sizeof (struct sockaddr_in6
);
2594 #ifdef HAVE_LOCAL_SOCKETS
2595 else if (STRINGP (address
))
2597 *familyp
= AF_LOCAL
;
2598 return sizeof (struct sockaddr_un
);
2601 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2602 && VECTORP (XCDR (address
)))
2604 struct sockaddr
*sa
;
2605 p
= XVECTOR (XCDR (address
));
2606 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2608 *familyp
= XINT (XCAR (address
));
2609 return p
->header
.size
+ sizeof (sa
->sa_family
);
2614 /* Convert an address object (vector or string) to an internal sockaddr.
2616 The address format has been basically validated by
2617 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2618 it could have come from user data. So if FAMILY is not valid,
2619 we return after zeroing *SA. */
2622 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2624 register struct Lisp_Vector
*p
;
2625 register unsigned char *cp
= NULL
;
2629 memset (sa
, 0, len
);
2631 if (VECTORP (address
))
2633 p
= XVECTOR (address
);
2634 if (family
== AF_INET
)
2636 DECLARE_POINTER_ALIAS (sin
, struct sockaddr_in
, sa
);
2637 len
= sizeof (sin
->sin_addr
) + 1;
2638 hostport
= XINT (p
->contents
[--len
]);
2639 sin
->sin_port
= htons (hostport
);
2640 cp
= (unsigned char *)&sin
->sin_addr
;
2641 sa
->sa_family
= family
;
2644 else if (family
== AF_INET6
)
2646 DECLARE_POINTER_ALIAS (sin6
, struct sockaddr_in6
, sa
);
2647 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &sin6
->sin6_addr
);
2648 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2649 hostport
= XINT (p
->contents
[--len
]);
2650 sin6
->sin6_port
= htons (hostport
);
2651 for (i
= 0; i
< len
; i
++)
2652 if (INTEGERP (p
->contents
[i
]))
2654 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2657 sa
->sa_family
= family
;
2664 else if (STRINGP (address
))
2666 #ifdef HAVE_LOCAL_SOCKETS
2667 if (family
== AF_LOCAL
)
2669 DECLARE_POINTER_ALIAS (sockun
, struct sockaddr_un
, sa
);
2670 cp
= SDATA (address
);
2671 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2672 sockun
->sun_path
[i
] = *cp
++;
2673 sa
->sa_family
= family
;
2680 p
= XVECTOR (XCDR (address
));
2681 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2684 for (i
= 0; i
< len
; i
++)
2685 if (INTEGERP (p
->contents
[i
]))
2686 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2689 #ifdef DATAGRAM_SOCKETS
2690 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2692 doc
: /* Get the current datagram address associated with PROCESS.
2693 If PROCESS is a non-blocking network process that hasn't been fully
2694 set up yet, this function will block until socket setup has completed. */)
2695 (Lisp_Object process
)
2699 CHECK_PROCESS (process
);
2701 if (NETCONN_P (process
))
2702 wait_for_socket_fds (process
, "process-datagram-address");
2704 if (!DATAGRAM_CONN_P (process
))
2707 channel
= XPROCESS (process
)->infd
;
2708 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2709 datagram_address
[channel
].len
);
2712 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2714 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2715 Return nil upon error setting address, ADDRESS otherwise.
2717 If PROCESS is a non-blocking network process that hasn't been fully
2718 set up yet, this function will block until socket setup has completed. */)
2719 (Lisp_Object process
, Lisp_Object address
)
2725 CHECK_PROCESS (process
);
2727 if (NETCONN_P (process
))
2728 wait_for_socket_fds (process
, "set-process-datagram-address");
2730 if (!DATAGRAM_CONN_P (process
))
2733 channel
= XPROCESS (process
)->infd
;
2735 len
= get_lisp_to_sockaddr_size (address
, &family
);
2736 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2738 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2744 static const struct socket_options
{
2745 /* The name of this option. Should be lowercase version of option
2746 name without SO_ prefix. */
2748 /* Option level SOL_... */
2750 /* Option number SO_... */
2752 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2753 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2754 } socket_options
[] =
2756 #ifdef SO_BINDTODEVICE
2757 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2760 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2763 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2766 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2769 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2772 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2775 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2778 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2780 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2783 /* Set option OPT to value VAL on socket S.
2785 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2786 Signals an error if setting a known option fails.
2790 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2793 const struct socket_options
*sopt
;
2798 name
= SSDATA (SYMBOL_NAME (opt
));
2799 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2800 if (strcmp (name
, sopt
->name
) == 0)
2803 switch (sopt
->opttype
)
2808 optval
= NILP (val
) ? 0 : 1;
2809 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2810 &optval
, sizeof (optval
));
2817 if (TYPE_RANGED_INTEGERP (int, val
))
2818 optval
= XINT (val
);
2820 error ("Bad option value for %s", name
);
2821 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2822 &optval
, sizeof (optval
));
2826 #ifdef SO_BINDTODEVICE
2829 char devname
[IFNAMSIZ
+ 1];
2831 /* This is broken, at least in the Linux 2.4 kernel.
2832 To unbind, the arg must be a zero integer, not the empty string.
2833 This should work on all systems. KFS. 2003-09-23. */
2834 memset (devname
, 0, sizeof devname
);
2837 char *arg
= SSDATA (val
);
2838 int len
= min (strlen (arg
), IFNAMSIZ
);
2839 memcpy (devname
, arg
, len
);
2841 else if (!NILP (val
))
2842 error ("Bad option value for %s", name
);
2843 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2852 struct linger linger
;
2855 linger
.l_linger
= 0;
2856 if (TYPE_RANGED_INTEGERP (int, val
))
2857 linger
.l_linger
= XINT (val
);
2859 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2860 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2861 &linger
, sizeof (linger
));
2872 int setsockopt_errno
= errno
;
2873 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2877 return (1 << sopt
->optbit
);
2881 DEFUN ("set-network-process-option",
2882 Fset_network_process_option
, Sset_network_process_option
,
2884 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2885 See `make-network-process' for a list of options and values.
2886 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2887 OPTION is not a supported option, return nil instead; otherwise return t.
2889 If PROCESS is a non-blocking network process that hasn't been fully
2890 set up yet, this function will block until socket setup has completed. */)
2891 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2894 struct Lisp_Process
*p
;
2896 CHECK_PROCESS (process
);
2897 p
= XPROCESS (process
);
2898 if (!NETCONN1_P (p
))
2899 error ("Process is not a network process");
2901 wait_for_socket_fds (process
, "set-network-process-option");
2905 error ("Process is not running");
2907 if (set_socket_option (s
, option
, value
))
2909 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2913 if (NILP (no_error
))
2914 error ("Unknown or unsupported option");
2920 DEFUN ("serial-process-configure",
2921 Fserial_process_configure
,
2922 Sserial_process_configure
,
2924 doc
: /* Configure speed, bytesize, etc. of a serial process.
2926 Arguments are specified as keyword/argument pairs. Attributes that
2927 are not given are re-initialized from the process's current
2928 configuration (available via the function `process-contact') or set to
2929 reasonable default values. The following arguments are defined:
2935 -- Any of these arguments can be given to identify the process that is
2936 to be configured. If none of these arguments is given, the current
2937 buffer's process is used.
2939 :speed SPEED -- SPEED is the speed of the serial port in bits per
2940 second, also called baud rate. Any value can be given for SPEED, but
2941 most serial ports work only at a few defined values between 1200 and
2942 115200, with 9600 being the most common value. If SPEED is nil, the
2943 serial port is not configured any further, i.e., all other arguments
2944 are ignored. This may be useful for special serial ports such as
2945 Bluetooth-to-serial converters which can only be configured through AT
2946 commands. A value of nil for SPEED can be used only when passed
2947 through `make-serial-process' or `serial-term'.
2949 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2950 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2952 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2953 `odd' (use odd parity), or the symbol `even' (use even parity). If
2954 PARITY is not given, no parity is used.
2956 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2957 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2958 is not given or nil, 1 stopbit is used.
2960 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2961 flowcontrol to be used, which is either nil (don't use flowcontrol),
2962 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2963 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2964 flowcontrol is used.
2966 `serial-process-configure' is called by `make-serial-process' for the
2967 initial configuration of the serial port.
2971 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2973 \(serial-process-configure
2974 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2976 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2978 usage: (serial-process-configure &rest ARGS) */)
2979 (ptrdiff_t nargs
, Lisp_Object
*args
)
2981 struct Lisp_Process
*p
;
2982 Lisp_Object contact
= Qnil
;
2983 Lisp_Object proc
= Qnil
;
2985 contact
= Flist (nargs
, args
);
2987 proc
= Fplist_get (contact
, QCprocess
);
2989 proc
= Fplist_get (contact
, QCname
);
2991 proc
= Fplist_get (contact
, QCbuffer
);
2993 proc
= Fplist_get (contact
, QCport
);
2994 proc
= get_process (proc
);
2995 p
= XPROCESS (proc
);
2996 if (!EQ (p
->type
, Qserial
))
2997 error ("Not a serial process");
2999 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
3002 serial_configure (p
, contact
);
3006 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
3008 doc
: /* Create and return a serial port process.
3010 In Emacs, serial port connections are represented by process objects,
3011 so input and output work as for subprocesses, and `delete-process'
3012 closes a serial port connection. However, a serial process has no
3013 process id, it cannot be signaled, and the status codes are different
3014 from normal processes.
3016 `make-serial-process' creates a process and a buffer, on which you
3017 probably want to use `process-send-string'. Try \\[serial-term] for
3018 an interactive terminal. See below for examples.
3020 Arguments are specified as keyword/argument pairs. The following
3021 arguments are defined:
3023 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3024 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
3025 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3026 the backslashes in strings).
3028 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3029 which this function calls.
3031 :name NAME -- NAME is the name of the process. If NAME is not given,
3032 the value of PORT is used.
3034 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3035 with the process. Process output goes at the end of that buffer,
3036 unless you specify a filter function to handle the output. If BUFFER
3037 is not given, the value of NAME is used.
3039 :coding CODING -- If CODING is a symbol, it specifies the coding
3040 system used for both reading and writing for this process. If CODING
3041 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3042 ENCODING is used for writing.
3044 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3045 the process is running. If BOOL is not given, query before exiting.
3047 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3048 In the stopped state, a serial process does not accept incoming data,
3049 but you can send outgoing data. The stopped state is cleared by
3050 `continue-process' and set by `stop-process'.
3052 :filter FILTER -- Install FILTER as the process filter.
3054 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3056 :plist PLIST -- Install PLIST as the initial plist of the process.
3062 -- This function calls `serial-process-configure' to handle these
3065 The original argument list, possibly modified by later configuration,
3066 is available via the function `process-contact'.
3070 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3072 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3074 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3076 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3078 usage: (make-serial-process &rest ARGS) */)
3079 (ptrdiff_t nargs
, Lisp_Object
*args
)
3082 Lisp_Object proc
, contact
, port
;
3083 struct Lisp_Process
*p
;
3084 Lisp_Object name
, buffer
;
3085 Lisp_Object tem
, val
;
3086 ptrdiff_t specpdl_count
;
3091 contact
= Flist (nargs
, args
);
3093 port
= Fplist_get (contact
, QCport
);
3095 error ("No port specified");
3096 CHECK_STRING (port
);
3098 if (NILP (Fplist_member (contact
, QCspeed
)))
3099 error (":speed not specified");
3100 if (!NILP (Fplist_get (contact
, QCspeed
)))
3101 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
3103 name
= Fplist_get (contact
, QCname
);
3106 CHECK_STRING (name
);
3107 proc
= make_process (name
);
3108 specpdl_count
= SPECPDL_INDEX ();
3109 record_unwind_protect (remove_process
, proc
);
3110 p
= XPROCESS (proc
);
3112 fd
= serial_open (port
);
3113 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
3118 chan_process
[fd
] = proc
;
3120 buffer
= Fplist_get (contact
, QCbuffer
);
3123 buffer
= Fget_buffer_create (buffer
);
3124 pset_buffer (p
, buffer
);
3126 pset_childp (p
, contact
);
3127 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3128 pset_type (p
, Qserial
);
3129 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
3130 pset_filter (p
, Fplist_get (contact
, QCfilter
));
3131 eassert (NILP (p
->log
));
3132 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3133 p
->kill_without_query
= 1;
3134 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
3135 pset_command (p
, Qt
);
3136 eassert (! p
->pty_flag
);
3138 if (!EQ (p
->command
, Qt
))
3139 add_process_read_fd (fd
);
3141 if (BUFFERP (buffer
))
3143 set_marker_both (p
->mark
, buffer
,
3144 BUF_ZV (XBUFFER (buffer
)),
3145 BUF_ZV_BYTE (XBUFFER (buffer
)));
3148 tem
= Fplist_member (contact
, QCcoding
);
3149 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3155 val
= XCAR (XCDR (tem
));
3159 else if (!NILP (Vcoding_system_for_read
))
3160 val
= Vcoding_system_for_read
;
3161 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3162 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3164 pset_decode_coding_system (p
, val
);
3169 val
= XCAR (XCDR (tem
));
3173 else if (!NILP (Vcoding_system_for_write
))
3174 val
= Vcoding_system_for_write
;
3175 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3176 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3178 pset_encode_coding_system (p
, val
);
3180 setup_process_coding_systems (proc
);
3181 pset_decoding_buf (p
, empty_unibyte_string
);
3182 eassert (p
->decoding_carryover
== 0);
3183 pset_encoding_buf (p
, empty_unibyte_string
);
3184 p
->inherit_coding_system_flag
3185 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3187 Fserial_process_configure (nargs
, args
);
3189 specpdl_ptr
= specpdl
+ specpdl_count
;
3195 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
3196 Lisp_Object service
, Lisp_Object name
)
3199 struct Lisp_Process
*p
= XPROCESS (proc
);
3200 Lisp_Object contact
= p
->childp
;
3201 Lisp_Object coding_systems
= Qt
;
3204 tem
= Fplist_member (contact
, QCcoding
);
3205 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3206 tem
= Qnil
; /* No error message (too late!). */
3208 /* Setup coding systems for communicating with the network stream. */
3209 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3213 val
= XCAR (XCDR (tem
));
3217 else if (!NILP (Vcoding_system_for_read
))
3218 val
= Vcoding_system_for_read
;
3219 else if ((!NILP (p
->buffer
)
3220 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3221 || (NILP (p
->buffer
)
3222 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3223 /* We dare not decode end-of-line format by setting VAL to
3224 Qraw_text, because the existing Emacs Lisp libraries
3225 assume that they receive bare code including a sequence of
3230 if (NILP (host
) || NILP (service
))
3231 coding_systems
= Qnil
;
3233 coding_systems
= CALLN (Ffind_operation_coding_system
,
3234 Qopen_network_stream
, name
, p
->buffer
,
3236 if (CONSP (coding_systems
))
3237 val
= XCAR (coding_systems
);
3238 else if (CONSP (Vdefault_process_coding_system
))
3239 val
= XCAR (Vdefault_process_coding_system
);
3243 pset_decode_coding_system (p
, val
);
3247 val
= XCAR (XCDR (tem
));
3251 else if (!NILP (Vcoding_system_for_write
))
3252 val
= Vcoding_system_for_write
;
3253 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3257 if (EQ (coding_systems
, Qt
))
3259 if (NILP (host
) || NILP (service
))
3260 coding_systems
= Qnil
;
3262 coding_systems
= CALLN (Ffind_operation_coding_system
,
3263 Qopen_network_stream
, name
, p
->buffer
,
3266 if (CONSP (coding_systems
))
3267 val
= XCDR (coding_systems
);
3268 else if (CONSP (Vdefault_process_coding_system
))
3269 val
= XCDR (Vdefault_process_coding_system
);
3273 pset_encode_coding_system (p
, val
);
3275 pset_decoding_buf (p
, empty_unibyte_string
);
3276 p
->decoding_carryover
= 0;
3277 pset_encoding_buf (p
, empty_unibyte_string
);
3279 p
->inherit_coding_system_flag
3280 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3285 finish_after_tls_connection (Lisp_Object proc
)
3287 struct Lisp_Process
*p
= XPROCESS (proc
);
3288 Lisp_Object contact
= p
->childp
;
3289 Lisp_Object result
= Qt
;
3291 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3292 result
= call3 (Qnsm_verify_connection
,
3294 Fplist_get (contact
, QChost
),
3295 Fplist_get (contact
, QCservice
));
3299 pset_status (p
, list2 (Qfailed
,
3300 build_string ("The Network Security Manager stopped the connections")));
3301 deactivate_process (proc
);
3303 else if (p
->outfd
< 0)
3305 /* The counterparty may have closed the connection (especially
3306 if the NSM prompt above take a long time), so recheck the file
3308 pset_status (p
, Qfailed
);
3309 deactivate_process (proc
);
3311 else if ((fd_callback_info
[p
->outfd
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3313 /* If we cleared the connection wait mask before we did the TLS
3314 setup, then we have to say that the process is finally "open"
3316 pset_status (p
, Qrun
);
3317 /* Execute the sentinel here. If we had relied on status_notify
3318 to do it later, it will read input from the process before
3319 calling the sentinel. */
3320 exec_sentinel (proc
, build_string ("open\n"));
3326 connect_network_socket (Lisp_Object proc
, Lisp_Object addrinfos
,
3327 Lisp_Object use_external_socket_p
)
3329 ptrdiff_t count
= SPECPDL_INDEX ();
3330 int s
= -1, outch
, inch
;
3333 struct sockaddr
*sa
= NULL
;
3336 struct Lisp_Process
*p
= XPROCESS (proc
);
3337 Lisp_Object contact
= p
->childp
;
3339 int socket_to_use
= -1;
3341 if (!NILP (use_external_socket_p
))
3343 socket_to_use
= external_sock_fd
;
3345 /* Ensure we don't consume the external socket twice. */
3346 external_sock_fd
= -1;
3349 /* Do this in case we never enter the while-loop below. */
3352 while (!NILP (addrinfos
))
3354 Lisp_Object addrinfo
= XCAR (addrinfos
);
3355 addrinfos
= XCDR (addrinfos
);
3356 int protocol
= XINT (XCAR (addrinfo
));
3357 Lisp_Object ip_address
= XCDR (addrinfo
);
3363 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3366 sa
= xmalloc (addrlen
);
3367 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3372 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3373 if (p
->is_non_blocking_client
)
3374 socktype
|= SOCK_NONBLOCK
;
3375 s
= socket (family
, socktype
, protocol
);
3383 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3385 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3391 if (0 <= socket_to_use
)
3397 #ifdef DATAGRAM_SOCKETS
3398 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3400 #endif /* DATAGRAM_SOCKETS */
3402 /* Make us close S if quit. */
3403 record_unwind_protect_int (close_file_unwind
, s
);
3405 /* Parse network options in the arg list. We simply ignore anything
3406 which isn't a known option (including other keywords). An error
3407 is signaled if setting a known option fails. */
3409 Lisp_Object params
= contact
, key
, val
;
3411 while (!NILP (params
))
3413 key
= XCAR (params
);
3414 params
= XCDR (params
);
3415 val
= XCAR (params
);
3416 params
= XCDR (params
);
3417 optbits
|= set_socket_option (s
, key
, val
);
3423 /* Configure as a server socket. */
3425 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3426 explicit :reuseaddr key to override this. */
3427 #ifdef HAVE_LOCAL_SOCKETS
3428 if (family
!= AF_LOCAL
)
3430 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3433 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3434 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3437 /* If passed a socket descriptor, it should be already bound. */
3438 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3439 report_file_error ("Cannot bind server socket", Qnil
);
3441 #ifdef HAVE_GETSOCKNAME
3443 #ifdef HAVE_LOCAL_SOCKETS
3444 && family
!= AF_LOCAL
3448 struct sockaddr_in sa1
;
3449 socklen_t len1
= sizeof (sa1
);
3451 /* The code below assumes the port is at the same offset
3452 and of the same width in both IPv4 and IPv6
3453 structures, but the standards don't guarantee that,
3454 so verify it here. */
3455 struct sockaddr_in6 sa6
;
3456 verify ((offsetof (struct sockaddr_in
, sin_port
)
3457 == offsetof (struct sockaddr_in6
, sin6_port
))
3458 && sizeof (sa1
.sin_port
) == sizeof (sa6
.sin6_port
));
3460 DECLARE_POINTER_ALIAS (psa1
, struct sockaddr
, &sa1
);
3461 if (getsockname (s
, psa1
, &len1
) == 0)
3463 Lisp_Object service
= make_number (ntohs (sa1
.sin_port
));
3464 contact
= Fplist_put (contact
, QCservice
, service
);
3465 /* Save the port number so that we can stash it in
3466 the process object later. */
3467 DECLARE_POINTER_ALIAS (psa
, struct sockaddr_in
, sa
);
3468 psa
->sin_port
= sa1
.sin_port
;
3473 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3474 report_file_error ("Cannot listen on server socket", Qnil
);
3481 ret
= connect (s
, sa
, addrlen
);
3484 if (ret
== 0 || xerrno
== EISCONN
)
3486 /* The unwind-protect will be discarded afterwards. */
3490 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3494 if (xerrno
== EINTR
)
3496 /* Unlike most other syscalls connect() cannot be called
3497 again. (That would return EALREADY.) The proper way to
3498 wait for completion is pselect(). */
3506 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3512 report_file_error ("Failed select", Qnil
);
3516 len
= sizeof xerrno
;
3517 eassert (FD_ISSET (s
, &fdset
));
3518 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3519 report_file_error ("Failed getsockopt", Qnil
);
3522 if (NILP (addrinfos
))
3523 report_file_errno ("Failed connect", Qnil
, xerrno
);
3525 #endif /* !WINDOWSNT */
3527 /* Discard the unwind protect closing S. */
3528 specpdl_ptr
= specpdl
+ count
;
3531 if (0 <= socket_to_use
)
3535 if (xerrno
== EINTR
)
3542 #ifdef DATAGRAM_SOCKETS
3543 if (p
->socktype
== SOCK_DGRAM
)
3545 if (datagram_address
[s
].sa
)
3548 datagram_address
[s
].sa
= xmalloc (addrlen
);
3549 datagram_address
[s
].len
= addrlen
;
3553 memset (datagram_address
[s
].sa
, 0, addrlen
);
3554 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3557 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3558 if (rlen
!= 0 && rfamily
== family
3560 conv_lisp_to_sockaddr (rfamily
, remote
,
3561 datagram_address
[s
].sa
, rlen
);
3565 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3569 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3570 conv_sockaddr_to_lisp (sa
, addrlen
));
3571 #ifdef HAVE_GETSOCKNAME
3574 struct sockaddr_storage sa1
;
3575 socklen_t len1
= sizeof (sa1
);
3576 DECLARE_POINTER_ALIAS (psa1
, struct sockaddr
, &sa1
);
3577 if (getsockname (s
, psa1
, &len1
) == 0)
3578 contact
= Fplist_put (contact
, QClocal
,
3579 conv_sockaddr_to_lisp (psa1
, len1
));
3586 /* If non-blocking got this far - and failed - assume non-blocking is
3587 not supported after all. This is probably a wrong assumption, but
3588 the normal blocking calls to open-network-stream handles this error
3590 if (p
->is_non_blocking_client
)
3593 report_file_errno ((p
->is_server
3594 ? "make server process failed"
3595 : "make client process failed"),
3602 chan_process
[inch
] = proc
;
3604 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3606 p
= XPROCESS (proc
);
3607 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3611 /* Discard the unwind protect for closing S, if any. */
3612 specpdl_ptr
= specpdl
+ count
;
3614 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3615 pset_status (p
, Qlisten
);
3617 /* Make the process marker point into the process buffer (if any). */
3618 if (BUFFERP (p
->buffer
))
3619 set_marker_both (p
->mark
, p
->buffer
,
3620 BUF_ZV (XBUFFER (p
->buffer
)),
3621 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3623 if (p
->is_non_blocking_client
)
3625 /* We may get here if connect did succeed immediately. However,
3626 in that case, we still need to signal this like a non-blocking
3628 if (! (connecting_status (p
->status
)
3629 && EQ (XCDR (p
->status
), addrinfos
)))
3630 pset_status (p
, Fcons (Qconnect
, addrinfos
));
3631 if ((fd_callback_info
[inch
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3632 add_non_blocking_write_fd (inch
);
3635 /* A server may have a client filter setting of Qt, but it must
3636 still listen for incoming connects unless it is stopped. */
3637 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3638 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3639 add_process_read_fd (inch
);
3641 if (inch
> max_desc
)
3644 /* Set up the masks based on the process filter. */
3645 set_process_filter_masks (p
);
3647 setup_process_coding_systems (proc
);
3650 /* Continue the asynchronous connection. */
3651 if (!NILP (p
->gnutls_boot_parameters
))
3653 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3655 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3656 p
->gnutls_boot_parameters
= Qnil
;
3658 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3659 /* Run sentinels, etc. */
3660 finish_after_tls_connection (proc
);
3661 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3663 deactivate_process (proc
);
3665 pset_status (p
, list2 (Qfailed
,
3666 build_string ("TLS negotiation failed")));
3668 pset_status (p
, list2 (Qfailed
, boot
));
3675 /* Create a network stream/datagram client/server process. Treated
3676 exactly like a normal process when reading and writing. Primary
3677 differences are in status display and process deletion. A network
3678 connection has no PID; you cannot signal it. All you can do is
3679 stop/continue it and deactivate/close it via delete-process. */
3681 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3683 doc
: /* Create and return a network server or client process.
3685 In Emacs, network connections are represented by process objects, so
3686 input and output work as for subprocesses and `delete-process' closes
3687 a network connection. However, a network process has no process id,
3688 it cannot be signaled, and the status codes are different from normal
3691 Arguments are specified as keyword/argument pairs. The following
3692 arguments are defined:
3694 :name NAME -- NAME is name for process. It is modified if necessary
3697 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3698 with the process. Process output goes at end of that buffer, unless
3699 you specify a filter function to handle the output. BUFFER may be
3700 also nil, meaning that this process is not associated with any buffer.
3702 :host HOST -- HOST is name of the host to connect to, or its IP
3703 address. The symbol `local' specifies the local host. If specified
3704 for a server process, it must be a valid name or address for the local
3705 host, and only clients connecting to that address will be accepted.
3707 :service SERVICE -- SERVICE is name of the service desired, or an
3708 integer specifying a port number to connect to. If SERVICE is t,
3709 a random port number is selected for the server. A port number can
3710 be specified as an integer string, e.g., "80", as well as an integer.
3712 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3713 stream type connection, `datagram' creates a datagram type connection,
3714 `seqpacket' creates a reliable datagram connection.
3716 :family FAMILY -- FAMILY is the address (and protocol) family for the
3717 service specified by HOST and SERVICE. The default (nil) is to use
3718 whatever address family (IPv4 or IPv6) that is defined for the host
3719 and port number specified by HOST and SERVICE. Other address families
3721 local -- for a local (i.e. UNIX) address specified by SERVICE.
3722 ipv4 -- use IPv4 address family only.
3723 ipv6 -- use IPv6 address family only.
3725 :local ADDRESS -- ADDRESS is the local address used for the connection.
3726 This parameter is ignored when opening a client process. When specified
3727 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3729 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3730 connection. This parameter is ignored when opening a stream server
3731 process. For a datagram server process, it specifies the initial
3732 setting of the remote datagram address. When specified for a client
3733 process, the FAMILY, HOST, and SERVICE args are ignored.
3735 The format of ADDRESS depends on the address family:
3736 - An IPv4 address is represented as a vector of integers [A B C D P]
3737 corresponding to numeric IP address A.B.C.D and port number P.
3738 - A local address is represented as a string with the address in the
3739 local address space.
3740 - An "unsupported family" address is represented by a cons (F . AV)
3741 where F is the family number and AV is a vector containing the socket
3742 address data with one element per address data byte. Do not rely on
3743 this format in portable code, as it may depend on implementation
3744 defined constants, data sizes, and data structure alignment.
3746 :coding CODING -- If CODING is a symbol, it specifies the coding
3747 system used for both reading and writing for this process. If CODING
3748 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3749 ENCODING is used for writing.
3751 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3752 process, return without waiting for the connection to complete;
3753 instead, the sentinel function will be called with second arg matching
3754 "open" (if successful) or "failed" when the connect completes.
3755 Default is to use a blocking connect (i.e. wait) for stream type
3758 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3759 running when Emacs is exited.
3761 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3762 In the stopped state, a server process does not accept new
3763 connections, and a client process does not handle incoming traffic.
3764 The stopped state is cleared by `continue-process' and set by
3767 :filter FILTER -- Install FILTER as the process filter.
3769 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3770 process filter are multibyte, otherwise they are unibyte.
3771 If this keyword is not specified, the strings are multibyte.
3773 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3775 :log LOG -- Install LOG as the server process log function. This
3776 function is called when the server accepts a network connection from a
3777 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3778 is the server process, CLIENT is the new process for the connection,
3779 and MESSAGE is a string.
3781 :plist PLIST -- Install PLIST as the new process's initial plist.
3783 :tls-parameters LIST -- is a list that should be supplied if you're
3784 opening a TLS connection. The first element is the TLS type (either
3785 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3786 be a keyword list accepted by gnutls-boot (as returned by
3787 `gnutls-boot-parameters').
3789 :server QLEN -- if QLEN is non-nil, create a server process for the
3790 specified FAMILY, SERVICE, and connection type (stream or datagram).
3791 If QLEN is an integer, it is used as the max. length of the server's
3792 pending connection queue (also known as the backlog); the default
3793 queue length is 5. Default is to create a client process.
3795 The following network options can be specified for this connection:
3797 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3798 :dontroute BOOL -- Only send to directly connected hosts.
3799 :keepalive BOOL -- Send keep-alive messages on network stream.
3800 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3801 :oobinline BOOL -- Place out-of-band data in receive data stream.
3802 :priority INT -- Set protocol defined priority for sent packets.
3803 :reuseaddr BOOL -- Allow reusing a recently used local address
3804 (this is allowed by default for a server process).
3805 :bindtodevice NAME -- bind to interface NAME. Using this may require
3806 special privileges on some systems.
3807 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3808 been passed to Emacs. If Emacs wasn't
3809 passed a socket, this option is silently
3813 Consult the relevant system programmer's manual pages for more
3814 information on using these options.
3817 A server process will listen for and accept connections from clients.
3818 When a client connection is accepted, a new network process is created
3819 for the connection with the following parameters:
3821 - The client's process name is constructed by concatenating the server
3822 process's NAME and a client identification string.
3823 - If the FILTER argument is non-nil, the client process will not get a
3824 separate process buffer; otherwise, the client's process buffer is a newly
3825 created buffer named after the server process's BUFFER name or process
3826 NAME concatenated with the client identification string.
3827 - The connection type and the process filter and sentinel parameters are
3828 inherited from the server process's TYPE, FILTER and SENTINEL.
3829 - The client process's contact info is set according to the client's
3830 addressing information (typically an IP address and a port number).
3831 - The client process's plist is initialized from the server's plist.
3833 Notice that the FILTER and SENTINEL args are never used directly by
3834 the server process. Also, the BUFFER argument is not used directly by
3835 the server process, but via the optional :log function, accepted (and
3836 failed) connections may be logged in the server process's buffer.
3838 The original argument list, modified with the actual connection
3839 information, is available via the `process-contact' function.
3841 usage: (make-network-process &rest ARGS) */)
3842 (ptrdiff_t nargs
, Lisp_Object
*args
)
3845 Lisp_Object contact
;
3846 struct Lisp_Process
*p
;
3847 const char *portstring UNINIT
;
3848 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3849 #ifdef HAVE_LOCAL_SOCKETS
3850 struct sockaddr_un address_un
;
3854 Lisp_Object name
, buffer
, host
, service
, address
;
3855 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3856 Lisp_Object addrinfos
= Qnil
;
3859 enum { any_protocol
= 0 };
3860 #ifdef HAVE_GETADDRINFO_A
3861 struct gaicb
*dns_request
= NULL
;
3863 ptrdiff_t count
= SPECPDL_INDEX ();
3868 /* Save arguments for process-contact and clone-process. */
3869 contact
= Flist (nargs
, args
);
3872 /* Ensure socket support is loaded if available. */
3873 init_winsock (TRUE
);
3876 /* :type TYPE (nil: stream, datagram */
3877 tem
= Fplist_get (contact
, QCtype
);
3879 socktype
= SOCK_STREAM
;
3880 #ifdef DATAGRAM_SOCKETS
3881 else if (EQ (tem
, Qdatagram
))
3882 socktype
= SOCK_DGRAM
;
3884 #ifdef HAVE_SEQPACKET
3885 else if (EQ (tem
, Qseqpacket
))
3886 socktype
= SOCK_SEQPACKET
;
3889 error ("Unsupported connection type");
3891 name
= Fplist_get (contact
, QCname
);
3892 buffer
= Fplist_get (contact
, QCbuffer
);
3893 filter
= Fplist_get (contact
, QCfilter
);
3894 sentinel
= Fplist_get (contact
, QCsentinel
);
3895 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3897 CHECK_STRING (name
);
3899 /* :local ADDRESS or :remote ADDRESS */
3900 tem
= Fplist_get (contact
, QCserver
);
3902 address
= Fplist_get (contact
, QCremote
);
3904 address
= Fplist_get (contact
, QClocal
);
3905 if (!NILP (address
))
3907 host
= service
= Qnil
;
3909 if (!get_lisp_to_sockaddr_size (address
, &family
))
3910 error ("Malformed :address");
3912 addrinfos
= list1 (Fcons (make_number (any_protocol
), address
));
3916 /* :family FAMILY -- nil (for Inet), local, or integer. */
3917 tem
= Fplist_get (contact
, QCfamily
);
3926 #ifdef HAVE_LOCAL_SOCKETS
3927 else if (EQ (tem
, Qlocal
))
3931 else if (EQ (tem
, Qipv6
))
3934 else if (EQ (tem
, Qipv4
))
3936 else if (TYPE_RANGED_INTEGERP (int, tem
))
3937 family
= XINT (tem
);
3939 error ("Unknown address family");
3941 /* :service SERVICE -- string, integer (port number), or t (random port). */
3942 service
= Fplist_get (contact
, QCservice
);
3944 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3945 host
= Fplist_get (contact
, QChost
);
3948 /* The "connection" function gets it bind info from the address we're
3949 given, so use this dummy address if nothing is specified. */
3950 #ifdef HAVE_LOCAL_SOCKETS
3951 if (family
!= AF_LOCAL
)
3953 host
= build_string ("127.0.0.1");
3957 if (EQ (host
, Qlocal
))
3958 /* Depending on setup, "localhost" may map to different IPv4 and/or
3959 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3960 host
= build_string ("127.0.0.1");
3961 CHECK_STRING (host
);
3964 #ifdef HAVE_LOCAL_SOCKETS
3965 if (family
== AF_LOCAL
)
3969 message (":family local ignores the :host property");
3970 contact
= Fplist_put (contact
, QChost
, Qnil
);
3973 CHECK_STRING (service
);
3974 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3975 error ("Service name too long");
3976 addrinfos
= list1 (Fcons (make_number (any_protocol
), service
));
3981 /* Slow down polling to every ten seconds.
3982 Some kernels have a bug which causes retrying connect to fail
3983 after a connect. Polling can interfere with gethostbyname too. */
3984 #ifdef POLL_FOR_INPUT
3985 if (socktype
!= SOCK_DGRAM
)
3987 record_unwind_protect_void (run_all_atimers
);
3988 bind_polling_period (10);
3994 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3996 /* SERVICE can either be a string or int.
3997 Convert to a C string for later use by getaddrinfo. */
3998 if (EQ (service
, Qt
))
4003 else if (INTEGERP (service
))
4005 portstring
= portbuf
;
4006 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
4010 CHECK_STRING (service
);
4011 portstring
= SSDATA (service
);
4012 portstringlen
= SBYTES (service
);
4015 #ifdef HAVE_GETADDRINFO_A
4016 if (!NILP (Fplist_get (contact
, QCnowait
)))
4018 ptrdiff_t hostlen
= SBYTES (host
);
4022 struct addrinfo hints
;
4023 char str
[FLEXIBLE_ARRAY_MEMBER
];
4024 } *req
= xmalloc (FLEXSIZEOF (struct req
, str
,
4025 hostlen
+ 1 + portstringlen
+ 1));
4026 dns_request
= &req
->gaicb
;
4027 dns_request
->ar_name
= req
->str
;
4028 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
4029 dns_request
->ar_request
= &req
->hints
;
4030 dns_request
->ar_result
= NULL
;
4031 memset (&req
->hints
, 0, sizeof req
->hints
);
4032 req
->hints
.ai_family
= family
;
4033 req
->hints
.ai_socktype
= socktype
;
4034 strcpy (req
->str
, SSDATA (host
));
4035 strcpy (req
->str
+ hostlen
+ 1, portstring
);
4037 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
4039 error ("%s/%s getaddrinfo_a error %d",
4040 SSDATA (host
), portstring
, ret
);
4044 #endif /* HAVE_GETADDRINFO_A */
4047 /* If we have a host, use getaddrinfo to resolve both host and service.
4048 Otherwise, use getservbyname to lookup the service. */
4052 struct addrinfo
*res
, *lres
;
4057 struct addrinfo hints
;
4058 memset (&hints
, 0, sizeof hints
);
4059 hints
.ai_family
= family
;
4060 hints
.ai_socktype
= socktype
;
4062 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
4064 #ifdef HAVE_GAI_STRERROR
4066 synchronize_system_messages_locale ();
4067 char const *str
= gai_strerror (ret
);
4068 if (! NILP (Vlocale_coding_system
))
4069 str
= SSDATA (code_convert_string_norecord
4070 (build_string (str
), Vlocale_coding_system
, 0));
4071 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
4074 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
4077 for (lres
= res
; lres
; lres
= lres
->ai_next
)
4078 addrinfos
= Fcons (conv_addrinfo_to_lisp (lres
), addrinfos
);
4080 addrinfos
= Fnreverse (addrinfos
);
4087 /* No hostname has been specified (e.g., a local server process). */
4089 if (EQ (service
, Qt
))
4091 else if (INTEGERP (service
))
4092 port
= XINT (service
);
4095 CHECK_STRING (service
);
4098 if (SBYTES (service
) != 0)
4100 /* Allow the service to be a string containing the port number,
4101 because that's allowed if you have getaddrbyname. */
4103 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
4104 if (service_end
== SSDATA (service
) + SBYTES (service
))
4108 struct servent
*svc_info
4109 = getservbyname (SSDATA (service
),
4110 socktype
== SOCK_DGRAM
? "udp" : "tcp");
4112 port
= ntohs (svc_info
->s_port
);
4117 if (! (0 <= port
&& port
< 1 << 16))
4119 AUTO_STRING (unknown_service
, "Unknown service: %s");
4120 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
4126 buffer
= Fget_buffer_create (buffer
);
4128 /* Unwind bind_polling_period. */
4129 unbind_to (count
, Qnil
);
4131 proc
= make_process (name
);
4132 record_unwind_protect (remove_process
, proc
);
4133 p
= XPROCESS (proc
);
4134 pset_childp (p
, contact
);
4135 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
4136 pset_type (p
, Qnetwork
);
4138 pset_buffer (p
, buffer
);
4139 pset_sentinel (p
, sentinel
);
4140 pset_filter (p
, filter
);
4141 pset_log (p
, Fplist_get (contact
, QClog
));
4142 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
4143 p
->kill_without_query
= 1;
4144 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
4145 pset_command (p
, Qt
);
4146 eassert (p
->pid
== 0);
4148 eassert (! p
->is_non_blocking_client
);
4149 eassert (! p
->is_server
);
4151 p
->socktype
= socktype
;
4152 #ifdef HAVE_GETADDRINFO_A
4153 eassert (! p
->dns_request
);
4156 tem
= Fplist_get (contact
, QCtls_parameters
);
4158 p
->gnutls_boot_parameters
= tem
;
4161 set_network_socket_coding_system (proc
, host
, service
, name
);
4164 tem
= Fplist_get (contact
, QCserver
);
4167 /* Don't support network sockets when non-blocking mode is
4168 not available, since a blocked Emacs is not useful. */
4169 p
->is_server
= true;
4170 if (TYPE_RANGED_INTEGERP (int, tem
))
4171 p
->backlog
= XINT (tem
);
4175 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
4176 && !NILP (Fplist_get (contact
, QCnowait
)))
4177 p
->is_non_blocking_client
= true;
4179 bool postpone_connection
= false;
4180 #ifdef HAVE_GETADDRINFO_A
4181 /* With async address resolution, the list of addresses is empty, so
4182 postpone connecting to the server. */
4183 if (!p
->is_server
&& NILP (addrinfos
))
4185 p
->dns_request
= dns_request
;
4186 p
->status
= list1 (Qconnect
);
4187 postpone_connection
= true;
4190 if (! postpone_connection
)
4191 connect_network_socket (proc
, addrinfos
, use_external_socket_p
);
4193 specpdl_ptr
= specpdl
+ count
;
4198 #ifdef HAVE_NET_IF_H
4202 network_interface_list (void)
4204 struct ifconf ifconf
;
4205 struct ifreq
*ifreq
;
4207 ptrdiff_t buf_size
= 512;
4212 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4215 count
= SPECPDL_INDEX ();
4216 record_unwind_protect_int (close_file_unwind
, s
);
4220 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4221 ifconf
.ifc_buf
= buf
;
4222 ifconf
.ifc_len
= buf_size
;
4223 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4230 while (ifconf
.ifc_len
== buf_size
);
4232 res
= unbind_to (count
, Qnil
);
4233 ifreq
= ifconf
.ifc_req
;
4234 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4236 struct ifreq
*ifq
= ifreq
;
4237 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4238 #define SIZEOF_IFREQ(sif) \
4239 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4240 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4242 int len
= SIZEOF_IFREQ (ifq
);
4244 int len
= sizeof (*ifreq
);
4246 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4247 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4249 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4252 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4253 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4254 res
= Fcons (Fcons (build_string (namebuf
),
4255 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4256 sizeof (struct sockaddr
))),
4263 #endif /* SIOCGIFCONF */
4265 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4269 const char *flag_sym
;
4272 static const struct ifflag_def ifflag_table
[] = {
4276 #ifdef IFF_BROADCAST
4277 { IFF_BROADCAST
, "broadcast" },
4280 { IFF_DEBUG
, "debug" },
4283 { IFF_LOOPBACK
, "loopback" },
4285 #ifdef IFF_POINTOPOINT
4286 { IFF_POINTOPOINT
, "pointopoint" },
4289 { IFF_RUNNING
, "running" },
4292 { IFF_NOARP
, "noarp" },
4295 { IFF_PROMISC
, "promisc" },
4297 #ifdef IFF_NOTRAILERS
4298 #ifdef NS_IMPL_COCOA
4299 /* Really means smart, notrailers is obsolete. */
4300 { IFF_NOTRAILERS
, "smart" },
4302 { IFF_NOTRAILERS
, "notrailers" },
4306 { IFF_ALLMULTI
, "allmulti" },
4309 { IFF_MASTER
, "master" },
4312 { IFF_SLAVE
, "slave" },
4314 #ifdef IFF_MULTICAST
4315 { IFF_MULTICAST
, "multicast" },
4318 { IFF_PORTSEL
, "portsel" },
4320 #ifdef IFF_AUTOMEDIA
4321 { IFF_AUTOMEDIA
, "automedia" },
4324 { IFF_DYNAMIC
, "dynamic" },
4327 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4330 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4333 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4336 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4339 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4345 network_interface_info (Lisp_Object ifname
)
4348 Lisp_Object res
= Qnil
;
4353 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4354 && defined HAVE_GETIFADDRS && defined LLADDR)
4355 struct ifaddrs
*ifap
;
4358 CHECK_STRING (ifname
);
4360 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4361 error ("interface name too long");
4362 lispstpcpy (rq
.ifr_name
, ifname
);
4364 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4367 count
= SPECPDL_INDEX ();
4368 record_unwind_protect_int (close_file_unwind
, s
);
4371 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4372 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4374 int flags
= rq
.ifr_flags
;
4375 const struct ifflag_def
*fp
;
4378 /* If flags is smaller than int (i.e. short) it may have the high bit set
4379 due to IFF_MULTICAST. In that case, sign extending it into
4381 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4382 flags
= (unsigned short) rq
.ifr_flags
;
4385 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4387 if (flags
& fp
->flag_bit
)
4389 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4390 flags
-= fp
->flag_bit
;
4393 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4397 elt
= Fcons (make_number (fnum
), elt
);
4402 res
= Fcons (elt
, res
);
4405 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4406 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4408 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4409 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4413 for (n
= 0; n
< 6; n
++)
4414 p
->contents
[n
] = make_number (((unsigned char *)
4415 &rq
.ifr_hwaddr
.sa_data
[0])
4417 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4419 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4420 if (getifaddrs (&ifap
) != -1)
4422 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4423 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4426 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4428 DECLARE_POINTER_ALIAS (sdl
, struct sockaddr_dl
, it
->ifa_addr
);
4429 unsigned char linkaddr
[6];
4432 if (it
->ifa_addr
->sa_family
!= AF_LINK
4433 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4434 || sdl
->sdl_alen
!= 6)
4437 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4438 for (n
= 0; n
< 6; n
++)
4439 p
->contents
[n
] = make_number (linkaddr
[n
]);
4441 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4445 #ifdef HAVE_FREEIFADDRS
4449 #endif /* HAVE_GETIFADDRS && LLADDR */
4451 res
= Fcons (elt
, res
);
4454 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4455 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4458 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4459 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4461 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4465 res
= Fcons (elt
, res
);
4468 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4469 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4472 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4475 res
= Fcons (elt
, res
);
4478 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4479 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4482 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4485 res
= Fcons (elt
, res
);
4487 return unbind_to (count
, any
? res
: Qnil
);
4489 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4490 #endif /* defined (HAVE_NET_IF_H) */
4492 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4493 Snetwork_interface_list
, 0, 0, 0,
4494 doc
: /* Return an alist of all network interfaces and their network address.
4495 Each element is a cons, the car of which is a string containing the
4496 interface name, and the cdr is the network address in internal
4497 format; see the description of ADDRESS in `make-network-process'.
4499 If the information is not available, return nil. */)
4502 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4503 return network_interface_list ();
4509 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4510 Snetwork_interface_info
, 1, 1, 0,
4511 doc
: /* Return information about network interface named IFNAME.
4512 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4513 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4514 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4515 FLAGS is the current flags of the interface.
4517 Data that is unavailable is returned as nil. */)
4518 (Lisp_Object ifname
)
4520 #if ((defined HAVE_NET_IF_H \
4521 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4522 || defined SIOCGIFFLAGS)) \
4523 || defined WINDOWSNT)
4524 return network_interface_info (ifname
);
4530 /* Turn off input and output for process PROC. */
4533 deactivate_process (Lisp_Object proc
)
4536 struct Lisp_Process
*p
= XPROCESS (proc
);
4540 /* Delete GnuTLS structures in PROC, if any. */
4541 emacs_gnutls_deinit (proc
);
4542 #endif /* HAVE_GNUTLS */
4544 if (p
->read_output_delay
> 0)
4546 if (--process_output_delay_count
< 0)
4547 process_output_delay_count
= 0;
4548 p
->read_output_delay
= 0;
4549 p
->read_output_skip
= 0;
4552 /* Beware SIGCHLD hereabouts. */
4554 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4555 close_process_fd (&p
->open_fd
[i
]);
4557 inchannel
= p
->infd
;
4562 #ifdef DATAGRAM_SOCKETS
4563 if (DATAGRAM_CHAN_P (inchannel
))
4565 xfree (datagram_address
[inchannel
].sa
);
4566 datagram_address
[inchannel
].sa
= 0;
4567 datagram_address
[inchannel
].len
= 0;
4570 chan_process
[inchannel
] = Qnil
;
4571 delete_read_fd (inchannel
);
4572 if ((fd_callback_info
[inchannel
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
4573 delete_write_fd (inchannel
);
4574 if (inchannel
== max_desc
)
4575 recompute_max_desc ();
4580 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4582 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4583 It is given to their filter functions.
4584 Optional argument PROCESS means do not return until output has been
4585 received from PROCESS.
4587 Optional second argument SECONDS and third argument MILLISEC
4588 specify a timeout; return after that much time even if there is
4589 no subprocess output. If SECONDS is a floating point number,
4590 it specifies a fractional number of seconds to wait.
4591 The MILLISEC argument is obsolete and should be avoided.
4593 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4594 from PROCESS only, suspending reading output from other processes.
4595 If JUST-THIS-ONE is an integer, don't run any timers either.
4596 Return non-nil if we received any output from PROCESS (or, if PROCESS
4597 is nil, from any process) before the timeout expired. */)
4598 (Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
,
4599 Lisp_Object just_this_one
)
4604 if (! NILP (process
))
4606 CHECK_PROCESS (process
);
4607 struct Lisp_Process
*proc
= XPROCESS (process
);
4609 /* Can't wait for a process that is dedicated to a different
4611 if (!EQ (proc
->thread
, Qnil
) && !EQ (proc
->thread
, Fcurrent_thread ()))
4613 Lisp_Object proc_thread_name
= XTHREAD (proc
->thread
)->name
;
4615 if (STRINGP (proc_thread_name
))
4616 error ("Attempt to accept output from process %s locked to thread %s",
4617 SDATA (proc
->name
), SDATA (proc_thread_name
));
4619 error ("Attempt to accept output from process %s locked to thread %p",
4620 SDATA (proc
->name
), XTHREAD (proc
->thread
));
4624 just_this_one
= Qnil
;
4626 if (!NILP (millisec
))
4627 { /* Obsolete calling convention using integers rather than floats. */
4628 CHECK_NUMBER (millisec
);
4630 seconds
= make_float (XINT (millisec
) / 1000.0);
4633 CHECK_NUMBER (seconds
);
4634 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4641 if (!NILP (seconds
))
4643 if (INTEGERP (seconds
))
4645 if (XINT (seconds
) > 0)
4647 secs
= XINT (seconds
);
4651 else if (FLOATP (seconds
))
4653 if (XFLOAT_DATA (seconds
) > 0)
4655 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4656 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4661 wrong_type_argument (Qnumberp
, seconds
);
4663 else if (! NILP (process
))
4667 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4669 !NILP (process
) ? XPROCESS (process
) : NULL
,
4670 (NILP (just_this_one
) ? 0
4671 : !INTEGERP (just_this_one
) ? 1 : -1))
4676 /* Accept a connection for server process SERVER on CHANNEL. */
4678 static EMACS_INT connect_counter
= 0;
4681 server_accept_connection (Lisp_Object server
, int channel
)
4684 Lisp_Object contact
, host
, service
;
4685 struct Lisp_Process
*ps
= XPROCESS (server
);
4686 struct Lisp_Process
*p
;
4688 union u_sockaddr saddr
;
4689 socklen_t len
= sizeof saddr
;
4692 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4697 if (!would_block (code
) && !NILP (ps
->log
))
4698 call3 (ps
->log
, server
, Qnil
,
4699 concat3 (build_string ("accept failed with code"),
4700 Fnumber_to_string (make_number (code
)),
4701 build_string ("\n")));
4705 count
= SPECPDL_INDEX ();
4706 record_unwind_protect_int (close_file_unwind
, s
);
4710 /* Setup a new process to handle the connection. */
4712 /* Generate a unique identification of the caller, and build contact
4713 information for this process. */
4716 Lisp_Object args
[11];
4718 AUTO_STRING (procname_format_in
, "%s <%d.%d.%d.%d:%d>");
4719 AUTO_STRING (procname_format_in6
, "%s <[%x:%x:%x:%x:%x:%x:%x:%x]:%d>");
4720 AUTO_STRING (procname_format_default
, "%s <%d>");
4721 switch (saddr
.sa
.sa_family
)
4725 args
[nargs
++] = procname_format_in
;
4727 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4728 service
= make_number (ntohs (saddr
.in
.sin_port
));
4729 for (int i
= 0; i
< 4; i
++)
4730 args
[nargs
++] = make_number (ip
[i
]);
4731 args
[nargs
++] = service
;
4738 args
[nargs
++] = procname_format_in6
;
4740 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &saddr
.in6
.sin6_addr
);
4741 service
= make_number (ntohs (saddr
.in
.sin_port
));
4742 for (int i
= 0; i
< 8; i
++)
4743 args
[nargs
++] = make_number (ip6
[i
]);
4744 args
[nargs
++] = service
;
4750 args
[nargs
++] = procname_format_default
;
4752 args
[nargs
++] = make_number (connect_counter
);
4756 /* Create a new buffer name for this process if it doesn't have a
4757 filter. The new buffer name is based on the buffer name or
4758 process name of the server process concatenated with the caller
4761 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4762 || EQ (ps
->filter
, Qt
)))
4766 buffer
= ps
->buffer
;
4768 buffer
= Fbuffer_name (buffer
);
4774 buffer
= Fget_buffer_create (Fformat (nargs
, args
));
4778 /* Generate a unique name for the new server process. Combine the
4779 server process name with the caller identification. */
4782 Lisp_Object name
= Fformat (nargs
, args
);
4783 Lisp_Object proc
= make_process (name
);
4785 chan_process
[s
] = proc
;
4787 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4789 p
= XPROCESS (proc
);
4791 /* Build new contact information for this setup. */
4792 contact
= Fcopy_sequence (ps
->childp
);
4793 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4794 contact
= Fplist_put (contact
, QChost
, host
);
4795 if (!NILP (service
))
4796 contact
= Fplist_put (contact
, QCservice
, service
);
4797 contact
= Fplist_put (contact
, QCremote
,
4798 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4799 #ifdef HAVE_GETSOCKNAME
4801 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4802 contact
= Fplist_put (contact
, QClocal
,
4803 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4806 pset_childp (p
, contact
);
4807 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4808 pset_type (p
, Qnetwork
);
4810 pset_buffer (p
, buffer
);
4811 pset_sentinel (p
, ps
->sentinel
);
4812 pset_filter (p
, ps
->filter
);
4813 eassert (NILP (p
->command
));
4814 eassert (p
->pid
== 0);
4816 /* Discard the unwind protect for closing S. */
4817 specpdl_ptr
= specpdl
+ count
;
4819 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4822 pset_status (p
, Qrun
);
4824 /* Client processes for accepted connections are not stopped initially. */
4825 if (!EQ (p
->filter
, Qt
))
4826 add_process_read_fd (s
);
4830 /* Setup coding system for new process based on server process.
4831 This seems to be the proper thing to do, as the coding system
4832 of the new process should reflect the settings at the time the
4833 server socket was opened; not the current settings. */
4835 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4836 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4837 setup_process_coding_systems (proc
);
4839 pset_decoding_buf (p
, empty_unibyte_string
);
4840 eassert (p
->decoding_carryover
== 0);
4841 pset_encoding_buf (p
, empty_unibyte_string
);
4843 p
->inherit_coding_system_flag
4844 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4846 AUTO_STRING (dash
, "-");
4847 AUTO_STRING (nl
, "\n");
4848 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4850 if (!NILP (ps
->log
))
4852 AUTO_STRING (accept_from
, "accept from ");
4853 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4856 AUTO_STRING (open_from
, "open from ");
4857 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4860 #ifdef HAVE_GETADDRINFO_A
4862 check_for_dns (Lisp_Object proc
)
4864 struct Lisp_Process
*p
= XPROCESS (proc
);
4865 Lisp_Object addrinfos
= Qnil
;
4868 if (! p
->dns_request
)
4871 int ret
= gai_error (p
->dns_request
);
4872 if (ret
== EAI_INPROGRESS
)
4875 /* We got a response. */
4878 struct addrinfo
*res
;
4880 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4881 addrinfos
= Fcons (conv_addrinfo_to_lisp (res
), addrinfos
);
4883 addrinfos
= Fnreverse (addrinfos
);
4885 /* The DNS lookup failed. */
4886 else if (connecting_status (p
->status
))
4888 deactivate_process (proc
);
4889 pset_status (p
, (list2
4891 concat3 (build_string ("Name lookup of "),
4892 build_string (p
->dns_request
->ar_name
),
4893 build_string (" failed")))));
4896 free_dns_request (proc
);
4898 /* This process should not already be connected (or killed). */
4899 if (! connecting_status (p
->status
))
4905 #endif /* HAVE_GETADDRINFO_A */
4908 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4910 while (XPROCESS (process
)->infd
< 0
4911 && connecting_status (XPROCESS (process
)->status
))
4913 add_to_log ("Waiting for socket from %s...", build_string (name
));
4914 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4919 wait_while_connecting (Lisp_Object process
)
4921 while (connecting_status (XPROCESS (process
)->status
))
4923 add_to_log ("Waiting for connection...");
4924 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4929 wait_for_tls_negotiation (Lisp_Object process
)
4932 while (XPROCESS (process
)->gnutls_p
4933 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4935 add_to_log ("Waiting for TLS...");
4936 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4942 wait_reading_process_output_unwind (int data
)
4944 clear_waiting_thread_info ();
4945 waiting_for_user_input_p
= data
;
4948 /* This is here so breakpoints can be put on it. */
4950 wait_reading_process_output_1 (void)
4954 /* Read and dispose of subprocess output while waiting for timeout to
4955 elapse and/or keyboard input to be available.
4959 If negative, gobble data immediately available but don't wait for any.
4962 an additional duration to wait, measured in nanoseconds
4963 If TIME_LIMIT is zero, then:
4964 If NSECS == 0, there is no limit.
4965 If NSECS > 0, the timeout consists of NSECS only.
4966 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4969 0 to ignore keyboard input, or
4970 1 to return when input is available, or
4971 -1 meaning caller will actually read the input, so don't throw to
4974 DO_DISPLAY means redisplay should be done to show subprocess
4975 output that arrives.
4977 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4978 (and gobble terminal input into the buffer if any arrives).
4980 If WAIT_PROC is specified, wait until something arrives from that
4983 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4984 (suspending output from other processes). A negative value
4985 means don't run any timers either.
4987 Return positive if we received input from WAIT_PROC (or from any
4988 process if WAIT_PROC is null), zero if we attempted to receive
4989 input but got none, and negative if we didn't even try. */
4992 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4994 Lisp_Object wait_for_cell
,
4995 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
5005 struct timespec timeout
, end_time
, timer_delay
;
5006 struct timespec got_output_end_time
= invalid_timespec ();
5007 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
5008 int got_some_output
= -1;
5009 uintmax_t prev_wait_proc_nbytes_read
= wait_proc
? wait_proc
->nbytes_read
: 0;
5010 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5011 bool retry_for_async
;
5013 ptrdiff_t count
= SPECPDL_INDEX ();
5015 /* Close to the current time if known, an invalid timespec otherwise. */
5016 struct timespec now
= invalid_timespec ();
5018 eassert (wait_proc
== NULL
5019 || EQ (wait_proc
->thread
, Qnil
)
5020 || XTHREAD (wait_proc
->thread
) == current_thread
);
5022 FD_ZERO (&Available
);
5025 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
5026 && !(CONSP (wait_proc
->status
)
5027 && EQ (XCAR (wait_proc
->status
), Qexit
)))
5028 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5030 record_unwind_protect_int (wait_reading_process_output_unwind
,
5031 waiting_for_user_input_p
);
5032 waiting_for_user_input_p
= read_kbd
;
5034 if (TYPE_MAXIMUM (time_t) < time_limit
)
5035 time_limit
= TYPE_MAXIMUM (time_t);
5037 if (time_limit
< 0 || nsecs
< 0)
5039 else if (time_limit
> 0 || nsecs
> 0)
5042 now
= current_timespec ();
5043 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
5050 bool process_skipped
= false;
5052 /* If calling from keyboard input, do not quit
5053 since we want to return C-g as an input character.
5054 Otherwise, do pending quit if requested. */
5057 else if (pending_signals
)
5058 process_pending_signals ();
5060 /* Exit now if the cell we're waiting for became non-nil. */
5061 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5064 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5066 Lisp_Object process_list_head
, aproc
;
5067 struct Lisp_Process
*p
;
5069 retry_for_async
= false;
5070 FOR_EACH_PROCESS(process_list_head
, aproc
)
5072 p
= XPROCESS (aproc
);
5074 if (! wait_proc
|| p
== wait_proc
)
5076 #ifdef HAVE_GETADDRINFO_A
5077 /* Check for pending DNS requests. */
5080 Lisp_Object addrinfos
= check_for_dns (aproc
);
5081 if (!NILP (addrinfos
) && !EQ (addrinfos
, Qt
))
5082 connect_network_socket (aproc
, addrinfos
, Qnil
);
5084 retry_for_async
= true;
5088 /* Continue TLS negotiation. */
5089 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
5090 && p
->is_non_blocking_client
)
5092 gnutls_try_handshake (p
);
5093 p
->gnutls_handshakes_tried
++;
5095 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
5097 gnutls_verify_boot (aproc
, Qnil
);
5098 finish_after_tls_connection (aproc
);
5102 retry_for_async
= true;
5103 if (p
->gnutls_handshakes_tried
5104 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
5106 deactivate_process (aproc
);
5107 pset_status (p
, list2 (Qfailed
,
5108 build_string ("TLS negotiation failed")));
5116 #endif /* GETADDRINFO_A or GNUTLS */
5118 /* Compute time from now till when time limit is up. */
5119 /* Exit if already run out. */
5120 if (wait
== TIMEOUT
)
5122 if (!timespec_valid_p (now
))
5123 now
= current_timespec ();
5124 if (timespec_cmp (end_time
, now
) <= 0)
5126 timeout
= timespec_sub (end_time
, now
);
5129 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
5131 /* Normally we run timers here.
5132 But not if wait_for_cell; in those cases,
5133 the wait is supposed to be short,
5134 and those callers cannot handle running arbitrary Lisp code here. */
5135 if (NILP (wait_for_cell
)
5136 && just_wait_proc
>= 0)
5140 unsigned old_timers_run
= timers_run
;
5141 struct buffer
*old_buffer
= current_buffer
;
5142 Lisp_Object old_window
= selected_window
;
5144 timer_delay
= timer_check ();
5146 /* If a timer has run, this might have changed buffers
5147 an alike. Make read_key_sequence aware of that. */
5148 if (timers_run
!= old_timers_run
5149 && (old_buffer
!= current_buffer
5150 || !EQ (old_window
, selected_window
))
5151 && waiting_for_user_input_p
== -1)
5152 record_asynch_buffer_change ();
5154 if (timers_run
!= old_timers_run
&& do_display
)
5155 /* We must retry, since a timer may have requeued itself
5156 and that could alter the time_delay. */
5157 redisplay_preserve_echo_area (9);
5161 while (!detect_input_pending ());
5163 /* If there is unread keyboard input, also return. */
5165 && requeued_events_pending_p ())
5168 /* This is so a breakpoint can be put here. */
5169 if (!timespec_valid_p (timer_delay
))
5170 wait_reading_process_output_1 ();
5173 /* Cause C-g and alarm signals to take immediate action,
5174 and cause input available signals to zero out timeout.
5176 It is important that we do this before checking for process
5177 activity. If we get a SIGCHLD after the explicit checks for
5178 process activity, timeout is the only way we will know. */
5180 set_waiting_for_input (&timeout
);
5182 /* If status of something has changed, and no input is
5183 available, notify the user of the change right away. After
5184 this explicit check, we'll let the SIGCHLD handler zap
5185 timeout to get our attention. */
5186 if (update_tick
!= process_tick
)
5191 if (kbd_on_hold_p ())
5194 compute_input_wait_mask (&Atemp
);
5195 compute_write_mask (&Ctemp
);
5197 timeout
= make_timespec (0, 0);
5198 if ((thread_select (pselect
, max_desc
+ 1,
5200 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5201 NULL
, &timeout
, NULL
)
5204 /* It's okay for us to do this and then continue with
5205 the loop, since timeout has already been zeroed out. */
5206 clear_waiting_for_input ();
5207 got_some_output
= status_notify (NULL
, wait_proc
);
5208 if (do_display
) redisplay_preserve_echo_area (13);
5212 /* Don't wait for output from a non-running process. Just
5213 read whatever data has already been received. */
5214 if (wait_proc
&& wait_proc
->raw_status_new
)
5215 update_status (wait_proc
);
5217 && ! EQ (wait_proc
->status
, Qrun
)
5218 && ! connecting_status (wait_proc
->status
))
5220 bool read_some_bytes
= false;
5222 clear_waiting_for_input ();
5224 /* If data can be read from the process, do so until exhausted. */
5225 if (wait_proc
->infd
>= 0)
5227 XSETPROCESS (proc
, wait_proc
);
5231 int nread
= read_process_output (proc
, wait_proc
->infd
);
5234 if (errno
== EIO
|| would_block (errno
))
5239 if (got_some_output
< nread
)
5240 got_some_output
= nread
;
5243 read_some_bytes
= true;
5248 if (read_some_bytes
&& do_display
)
5249 redisplay_preserve_echo_area (10);
5254 /* Wait till there is something to do. */
5256 if (wait_proc
&& just_wait_proc
)
5258 if (wait_proc
->infd
< 0) /* Terminated. */
5260 FD_SET (wait_proc
->infd
, &Available
);
5264 else if (!NILP (wait_for_cell
))
5266 compute_non_process_wait_mask (&Available
);
5273 compute_non_keyboard_wait_mask (&Available
);
5275 compute_input_wait_mask (&Available
);
5276 compute_write_mask (&Writeok
);
5277 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5281 /* If frame size has changed or the window is newly mapped,
5282 redisplay now, before we start to wait. There is a race
5283 condition here; if a SIGIO arrives between now and the select
5284 and indicates that a frame is trashed, the select may block
5285 displaying a trashed screen. */
5286 if (frame_garbaged
&& do_display
)
5288 clear_waiting_for_input ();
5289 redisplay_preserve_echo_area (11);
5291 set_waiting_for_input (&timeout
);
5294 /* Skip the `select' call if input is available and we're
5295 waiting for keyboard input or a cell change (which can be
5296 triggered by processing X events). In the latter case, set
5297 nfds to 1 to avoid breaking the loop. */
5299 if ((read_kbd
|| !NILP (wait_for_cell
))
5300 && detect_input_pending ())
5302 nfds
= read_kbd
? 0 : 1;
5304 FD_ZERO (&Available
);
5308 /* Set the timeout for adaptive read buffering if any
5309 process has non-zero read_output_skip and non-zero
5310 read_output_delay, and we are not reading output for a
5311 specific process. It is not executed if
5312 Vprocess_adaptive_read_buffering is nil. */
5313 if (process_output_skip
&& check_delay
> 0)
5315 int adaptive_nsecs
= timeout
.tv_nsec
;
5316 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5317 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5318 for (channel
= 0; check_delay
> 0 && channel
<= max_desc
; channel
++)
5320 proc
= chan_process
[channel
];
5323 /* Find minimum non-zero read_output_delay among the
5324 processes with non-zero read_output_skip. */
5325 if (XPROCESS (proc
)->read_output_delay
> 0)
5328 if (!XPROCESS (proc
)->read_output_skip
)
5330 FD_CLR (channel
, &Available
);
5331 process_skipped
= true;
5332 XPROCESS (proc
)->read_output_skip
= 0;
5333 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5334 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5337 timeout
= make_timespec (0, adaptive_nsecs
);
5338 process_output_skip
= 0;
5341 /* If we've got some output and haven't limited our timeout
5342 with adaptive read buffering, limit it. */
5343 if (got_some_output
> 0 && !process_skipped
5345 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5346 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5349 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5350 && timespec_valid_p (timer_delay
)
5351 && timespec_cmp (timer_delay
, timeout
) < 0)
5353 if (!timespec_valid_p (now
))
5354 now
= current_timespec ();
5355 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5356 if (!timespec_valid_p (got_output_end_time
)
5357 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5358 got_output_end_time
= timeout_abs
;
5359 timeout
= timer_delay
;
5362 got_output_end_time
= invalid_timespec ();
5364 /* NOW can become inaccurate if time can pass during pselect. */
5365 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5366 now
= invalid_timespec ();
5368 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5370 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5373 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5377 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5378 #if defined HAVE_GLIB && !defined HAVE_NS
5379 nfds
= xg_select (max_desc
+ 1,
5380 &Available
, (check_write
? &Writeok
: 0),
5381 NULL
, &timeout
, NULL
);
5382 #elif defined HAVE_NS
5383 /* And NS builds call thread_select in ns_select. */
5384 nfds
= ns_select (max_desc
+ 1,
5385 &Available
, (check_write
? &Writeok
: 0),
5386 NULL
, &timeout
, NULL
);
5387 #else /* !HAVE_GLIB */
5388 nfds
= thread_select (pselect
, max_desc
+ 1,
5390 (check_write
? &Writeok
: 0),
5391 NULL
, &timeout
, NULL
);
5392 #endif /* !HAVE_GLIB */
5395 /* GnuTLS buffers data internally. In lowat mode it leaves
5396 some data in the TCP buffers so that select works, but
5397 with custom pull/push functions we need to check if some
5398 data is available in the buffers manually. */
5401 fd_set tls_available
;
5404 FD_ZERO (&tls_available
);
5407 /* We're not waiting on a specific process, so loop
5408 through all the channels and check for data.
5409 This is a workaround needed for some versions of
5410 the gnutls library -- 2.12.14 has been confirmed
5412 http://comments.gmane.org/gmane.emacs.devel/145074 */
5413 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5414 if (! NILP (chan_process
[channel
]))
5416 struct Lisp_Process
*p
=
5417 XPROCESS (chan_process
[channel
]);
5418 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5419 && ((emacs_gnutls_record_check_pending
5424 eassert (p
->infd
== channel
);
5425 FD_SET (p
->infd
, &tls_available
);
5432 /* Check this specific channel. */
5433 if (wait_proc
->gnutls_p
/* Check for valid process. */
5434 && wait_proc
->gnutls_state
5435 /* Do we have pending data? */
5436 && ((emacs_gnutls_record_check_pending
5437 (wait_proc
->gnutls_state
))
5441 eassert (0 <= wait_proc
->infd
);
5442 /* Set to Available. */
5443 FD_SET (wait_proc
->infd
, &tls_available
);
5448 Available
= tls_available
;
5455 /* Make C-g and alarm signals set flags again. */
5456 clear_waiting_for_input ();
5458 /* If we woke up due to SIGWINCH, actually change size now. */
5459 do_pending_window_change (0);
5463 /* Exit the main loop if we've passed the requested timeout,
5464 or have read some bytes from our wait_proc (either directly
5465 in this call or indirectly through timers / process filters),
5466 or aren't skipping processes and got some output and
5467 haven't lowered our timeout due to timers or SIGIO and
5468 have waited a long amount of time due to repeated
5470 struct timespec huge_timespec
5471 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION
);
5472 struct timespec cmp_time
= huge_timespec
;
5475 && wait_proc
->nbytes_read
!= prev_wait_proc_nbytes_read
))
5477 if (wait
== TIMEOUT
)
5478 cmp_time
= end_time
;
5479 if (!process_skipped
&& got_some_output
> 0
5480 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5482 if (!timespec_valid_p (got_output_end_time
))
5484 if (timespec_cmp (got_output_end_time
, cmp_time
) < 0)
5485 cmp_time
= got_output_end_time
;
5487 if (timespec_cmp (cmp_time
, huge_timespec
) < 0)
5489 now
= current_timespec ();
5490 if (timespec_cmp (cmp_time
, now
) <= 0)
5497 if (xerrno
== EINTR
)
5499 else if (xerrno
== EBADF
)
5502 report_file_errno ("Failed select", Qnil
, xerrno
);
5505 /* Check for keyboard input. */
5506 /* If there is any, return immediately
5507 to give it higher priority than subprocesses. */
5511 unsigned old_timers_run
= timers_run
;
5512 struct buffer
*old_buffer
= current_buffer
;
5513 Lisp_Object old_window
= selected_window
;
5516 if (detect_input_pending_run_timers (do_display
))
5518 swallow_events (do_display
);
5519 if (detect_input_pending_run_timers (do_display
))
5523 /* If a timer has run, this might have changed buffers
5524 an alike. Make read_key_sequence aware of that. */
5525 if (timers_run
!= old_timers_run
5526 && waiting_for_user_input_p
== -1
5527 && (old_buffer
!= current_buffer
5528 || !EQ (old_window
, selected_window
)))
5529 record_asynch_buffer_change ();
5535 /* If there is unread keyboard input, also return. */
5537 && requeued_events_pending_p ())
5540 /* If we are not checking for keyboard input now,
5541 do process events (but don't run any timers).
5542 This is so that X events will be processed.
5543 Otherwise they may have to wait until polling takes place.
5544 That would causes delays in pasting selections, for example.
5546 (We used to do this only if wait_for_cell.) */
5547 if (read_kbd
== 0 && detect_input_pending ())
5549 swallow_events (do_display
);
5550 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5551 if (detect_input_pending ())
5556 /* Exit now if the cell we're waiting for became non-nil. */
5557 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5561 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5562 go read it. This can happen with X on BSD after logging out.
5563 In that case, there really is no input and no SIGIO,
5564 but select says there is input. */
5566 if (read_kbd
&& interrupt_input
5567 && keyboard_bit_set (&Available
) && ! noninteractive
)
5568 handle_input_available_signal (SIGIO
);
5571 /* If checking input just got us a size-change event from X,
5572 obey it now if we should. */
5573 if (read_kbd
|| ! NILP (wait_for_cell
))
5574 do_pending_window_change (0);
5576 /* Check for data from a process. */
5577 if (no_avail
|| nfds
== 0)
5580 for (channel
= 0; channel
<= max_desc
; ++channel
)
5582 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5584 && ((d
->flags
& FOR_READ
5585 && FD_ISSET (channel
, &Available
))
5586 || ((d
->flags
& FOR_WRITE
)
5587 && FD_ISSET (channel
, &Writeok
))))
5588 d
->func (channel
, d
->data
);
5591 for (channel
= 0; channel
<= max_desc
; channel
++)
5593 if (FD_ISSET (channel
, &Available
)
5594 && ((fd_callback_info
[channel
].flags
& (KEYBOARD_FD
| PROCESS_FD
))
5599 /* If waiting for this channel, arrange to return as
5600 soon as no more input to be processed. No more
5602 proc
= chan_process
[channel
];
5606 /* If this is a server stream socket, accept connection. */
5607 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5609 server_accept_connection (proc
, channel
);
5613 /* Read data from the process, starting with our
5614 buffered-ahead character if we have one. */
5616 nread
= read_process_output (proc
, channel
);
5617 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5618 && got_some_output
< nread
)
5619 got_some_output
= nread
;
5622 /* Vacuum up any leftovers without waiting. */
5623 if (wait_proc
== XPROCESS (proc
))
5625 /* Since read_process_output can run a filter,
5626 which can call accept-process-output,
5627 don't try to read from any other processes
5628 before doing the select again. */
5629 FD_ZERO (&Available
);
5632 redisplay_preserve_echo_area (12);
5634 else if (nread
== -1 && would_block (errno
))
5637 /* On some OSs with ptys, when the process on one end of
5638 a pty exits, the other end gets an error reading with
5639 errno = EIO instead of getting an EOF (0 bytes read).
5640 Therefore, if we get an error reading and errno =
5641 EIO, just continue, because the child process has
5642 exited and should clean itself up soon (e.g. when we
5644 else if (nread
== -1 && errno
== EIO
)
5646 struct Lisp_Process
*p
= XPROCESS (proc
);
5648 /* Clear the descriptor now, so we only raise the
5650 delete_read_fd (channel
);
5654 /* If the EIO occurs on a pty, the SIGCHLD handler's
5655 waitpid call will not find the process object to
5656 delete. Do it here. */
5657 p
->tick
= ++process_tick
;
5658 pset_status (p
, Qfailed
);
5661 #endif /* HAVE_PTYS */
5662 /* If we can detect process termination, don't consider the
5663 process gone just because its pipe is closed. */
5664 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5665 && !PIPECONN_P (proc
))
5667 else if (nread
== 0 && PIPECONN_P (proc
))
5669 /* Preserve status of processes already terminated. */
5670 XPROCESS (proc
)->tick
= ++process_tick
;
5671 deactivate_process (proc
);
5672 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5673 pset_status (XPROCESS (proc
),
5674 list2 (Qexit
, make_number (0)));
5678 /* Preserve status of processes already terminated. */
5679 XPROCESS (proc
)->tick
= ++process_tick
;
5680 deactivate_process (proc
);
5681 if (XPROCESS (proc
)->raw_status_new
)
5682 update_status (XPROCESS (proc
));
5683 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5684 pset_status (XPROCESS (proc
),
5685 list2 (Qexit
, make_number (256)));
5688 if (FD_ISSET (channel
, &Writeok
)
5689 && (fd_callback_info
[channel
].flags
5690 & NON_BLOCKING_CONNECT_FD
) != 0)
5692 struct Lisp_Process
*p
;
5694 delete_write_fd (channel
);
5696 proc
= chan_process
[channel
];
5700 p
= XPROCESS (proc
);
5704 socklen_t xlen
= sizeof (xerrno
);
5705 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5709 /* On MS-Windows, getsockopt clears the error for the
5710 entire process, which may not be the right thing; see
5711 w32.c. Use getpeername instead. */
5713 struct sockaddr pname
;
5714 socklen_t pnamelen
= sizeof (pname
);
5716 /* If connection failed, getpeername will fail. */
5718 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5720 /* Obtain connect failure code through error slippage. */
5723 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5730 Lisp_Object addrinfos
5731 = connecting_status (p
->status
) ? XCDR (p
->status
) : Qnil
;
5732 if (!NILP (addrinfos
))
5733 XSETCDR (p
->status
, XCDR (addrinfos
));
5736 p
->tick
= ++process_tick
;
5737 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5739 deactivate_process (proc
);
5740 if (!NILP (addrinfos
))
5741 connect_network_socket (proc
, addrinfos
, Qnil
);
5746 /* If we have an incompletely set up TLS connection,
5747 then defer the sentinel signaling until
5749 if (NILP (p
->gnutls_boot_parameters
)
5753 pset_status (p
, Qrun
);
5754 /* Execute the sentinel here. If we had relied on
5755 status_notify to do it later, it will read input
5756 from the process before calling the sentinel. */
5757 exec_sentinel (proc
, build_string ("open\n"));
5760 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5761 && !EQ (p
->command
, Qt
))
5762 add_process_read_fd (p
->infd
);
5765 } /* End for each file descriptor. */
5766 } /* End while exit conditions not met. */
5768 unbind_to (count
, Qnil
);
5770 /* If calling from keyboard input, do not quit
5771 since we want to return C-g as an input character.
5772 Otherwise, do pending quit if requested. */
5775 /* Prevent input_pending from remaining set if we quit. */
5776 clear_input_pending ();
5780 /* Timers and/or process filters that we have run could have themselves called
5781 `accept-process-output' (and by that indirectly this function), thus
5782 possibly reading some (or all) output of wait_proc without us noticing it.
5783 This could potentially lead to an endless wait (dealt with earlier in the
5784 function) and/or a wrong return value (dealt with here). */
5785 if (wait_proc
&& wait_proc
->nbytes_read
!= prev_wait_proc_nbytes_read
)
5786 got_some_output
= min (INT_MAX
, (wait_proc
->nbytes_read
5787 - prev_wait_proc_nbytes_read
));
5789 return got_some_output
;
5792 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5795 read_process_output_call (Lisp_Object fun_and_args
)
5797 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5801 read_process_output_error_handler (Lisp_Object error_val
)
5803 cmd_error_internal (error_val
, "error in process filter: ");
5805 update_echo_area ();
5806 Fsleep_for (make_number (2), Qnil
);
5811 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5813 struct coding_system
*coding
);
5815 /* Read pending output from the process channel,
5816 starting with our buffered-ahead character if we have one.
5817 Yield number of decoded characters read.
5819 This function reads at most 4096 characters.
5820 If you want to read all available subprocess output,
5821 you must call it repeatedly until it returns zero.
5823 The characters read are decoded according to PROC's coding-system
5827 read_process_output (Lisp_Object proc
, int channel
)
5830 struct Lisp_Process
*p
= XPROCESS (proc
);
5831 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5832 int carryover
= p
->decoding_carryover
;
5833 enum { readmax
= 4096 };
5834 ptrdiff_t count
= SPECPDL_INDEX ();
5835 Lisp_Object odeactivate
;
5836 char chars
[sizeof coding
->carryover
+ readmax
];
5839 /* See the comment above. */
5840 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5842 #ifdef DATAGRAM_SOCKETS
5843 /* We have a working select, so proc_buffered_char is always -1. */
5844 if (DATAGRAM_CHAN_P (channel
))
5846 socklen_t len
= datagram_address
[channel
].len
;
5847 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5848 0, datagram_address
[channel
].sa
, &len
);
5853 bool buffered
= proc_buffered_char
[channel
] >= 0;
5856 chars
[carryover
] = proc_buffered_char
[channel
];
5857 proc_buffered_char
[channel
] = -1;
5860 if (p
->gnutls_p
&& p
->gnutls_state
)
5861 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5862 readmax
- buffered
);
5865 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5866 readmax
- buffered
);
5867 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5869 int delay
= p
->read_output_delay
;
5872 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5875 process_output_delay_count
++;
5876 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5879 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5881 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5883 process_output_delay_count
--;
5885 p
->read_output_delay
= delay
;
5888 p
->read_output_skip
= 1;
5889 process_output_skip
= 1;
5893 nbytes
+= buffered
&& nbytes
<= 0;
5896 p
->decoding_carryover
= 0;
5898 /* At this point, NBYTES holds number of bytes just received
5899 (including the one in proc_buffered_char[channel]). */
5902 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5904 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5907 /* Ignore carryover, it's been added by a previous iteration already. */
5908 p
->nbytes_read
+= nbytes
;
5910 /* Now set NBYTES how many bytes we must decode. */
5911 nbytes
+= carryover
;
5913 odeactivate
= Vdeactivate_mark
;
5914 /* There's no good reason to let process filters change the current
5915 buffer, and many callers of accept-process-output, sit-for, and
5916 friends don't expect current-buffer to be changed from under them. */
5917 record_unwind_current_buffer ();
5919 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5921 /* Handling the process output should not deactivate the mark. */
5922 Vdeactivate_mark
= odeactivate
;
5924 unbind_to (count
, Qnil
);
5929 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5931 struct coding_system
*coding
)
5933 Lisp_Object outstream
= p
->filter
;
5935 bool outer_running_asynch_code
= running_asynch_code
;
5936 int waiting
= waiting_for_user_input_p
;
5939 Lisp_Object obuffer
, okeymap
;
5940 XSETBUFFER (obuffer
, current_buffer
);
5941 okeymap
= BVAR (current_buffer
, keymap
);
5944 /* We inhibit quit here instead of just catching it so that
5945 hitting ^G when a filter happens to be running won't screw
5947 specbind (Qinhibit_quit
, Qt
);
5948 specbind (Qlast_nonmenu_event
, Qt
);
5950 /* In case we get recursively called,
5951 and we already saved the match data nonrecursively,
5952 save the same match data in safely recursive fashion. */
5953 if (outer_running_asynch_code
)
5956 /* Don't clobber the CURRENT match data, either! */
5957 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5958 restore_search_regs ();
5959 record_unwind_save_match_data ();
5960 Fset_match_data (tem
, Qt
);
5963 /* For speed, if a search happens within this code,
5964 save the match data in a special nonrecursive fashion. */
5965 running_asynch_code
= 1;
5967 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5968 text
= coding
->dst_object
;
5969 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5970 /* A new coding system might be found. */
5971 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5973 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5975 /* Don't call setup_coding_system for
5976 proc_decode_coding_system[channel] here. It is done in
5977 detect_coding called via decode_coding above. */
5979 /* If a coding system for encoding is not yet decided, we set
5980 it as the same as coding-system for decoding.
5982 But, before doing that we must check if
5983 proc_encode_coding_system[p->outfd] surely points to a
5984 valid memory because p->outfd will be changed once EOF is
5985 sent to the process. */
5986 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5987 && proc_encode_coding_system
[p
->outfd
])
5989 pset_encode_coding_system
5990 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5991 setup_coding_system (p
->encode_coding_system
,
5992 proc_encode_coding_system
[p
->outfd
]);
5996 if (coding
->carryover_bytes
> 0)
5998 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5999 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
6000 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
6001 coding
->carryover_bytes
);
6002 p
->decoding_carryover
= coding
->carryover_bytes
;
6004 if (SBYTES (text
) > 0)
6005 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6006 sometimes it's simply wrong to wrap (e.g. when called from
6007 accept-process-output). */
6008 internal_condition_case_1 (read_process_output_call
,
6009 list3 (outstream
, make_lisp_proc (p
), text
),
6010 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6011 read_process_output_error_handler
);
6013 /* If we saved the match data nonrecursively, restore it now. */
6014 restore_search_regs ();
6015 running_asynch_code
= outer_running_asynch_code
;
6017 /* Restore waiting_for_user_input_p as it was
6018 when we were called, in case the filter clobbered it. */
6019 waiting_for_user_input_p
= waiting
;
6021 #if 0 /* Call record_asynch_buffer_change unconditionally,
6022 because we might have changed minor modes or other things
6023 that affect key bindings. */
6024 if (! EQ (Fcurrent_buffer (), obuffer
)
6025 || ! EQ (current_buffer
->keymap
, okeymap
))
6027 /* But do it only if the caller is actually going to read events.
6028 Otherwise there's no need to make him wake up, and it could
6029 cause trouble (for example it would make sit_for return). */
6030 if (waiting_for_user_input_p
== -1)
6031 record_asynch_buffer_change ();
6034 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
6035 Sinternal_default_process_filter
, 2, 2, 0,
6036 doc
: /* Function used as default process filter.
6037 This inserts the process's output into its buffer, if there is one.
6038 Otherwise it discards the output. */)
6039 (Lisp_Object proc
, Lisp_Object text
)
6041 struct Lisp_Process
*p
;
6044 CHECK_PROCESS (proc
);
6045 p
= XPROCESS (proc
);
6046 CHECK_STRING (text
);
6048 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
6050 Lisp_Object old_read_only
;
6051 ptrdiff_t old_begv
, old_zv
;
6052 ptrdiff_t old_begv_byte
, old_zv_byte
;
6053 ptrdiff_t before
, before_byte
;
6054 ptrdiff_t opoint_byte
;
6057 Fset_buffer (p
->buffer
);
6059 opoint_byte
= PT_BYTE
;
6060 old_read_only
= BVAR (current_buffer
, read_only
);
6063 old_begv_byte
= BEGV_BYTE
;
6064 old_zv_byte
= ZV_BYTE
;
6066 bset_read_only (current_buffer
, Qnil
);
6068 /* Insert new output into buffer at the current end-of-output
6069 marker, thus preserving logical ordering of input and output. */
6070 if (XMARKER (p
->mark
)->buffer
)
6071 set_point_from_marker (p
->mark
);
6073 SET_PT_BOTH (ZV
, ZV_BYTE
);
6075 before_byte
= PT_BYTE
;
6077 /* If the output marker is outside of the visible region, save
6078 the restriction and widen. */
6079 if (! (BEGV
<= PT
&& PT
<= ZV
))
6082 /* Adjust the multibyteness of TEXT to that of the buffer. */
6083 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
6084 != ! STRING_MULTIBYTE (text
))
6085 text
= (STRING_MULTIBYTE (text
)
6086 ? Fstring_as_unibyte (text
)
6087 : Fstring_to_multibyte (text
));
6088 /* Insert before markers in case we are inserting where
6089 the buffer's mark is, and the user's next command is Meta-y. */
6090 insert_from_string_before_markers (text
, 0, 0,
6091 SCHARS (text
), SBYTES (text
), 0);
6093 /* Make sure the process marker's position is valid when the
6094 process buffer is changed in the signal_after_change above.
6095 W3 is known to do that. */
6096 if (BUFFERP (p
->buffer
)
6097 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
6098 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
6100 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6102 update_mode_lines
= 23;
6104 /* Make sure opoint and the old restrictions
6105 float ahead of any new text just as point would. */
6106 if (opoint
>= before
)
6108 opoint
+= PT
- before
;
6109 opoint_byte
+= PT_BYTE
- before_byte
;
6111 if (old_begv
> before
)
6113 old_begv
+= PT
- before
;
6114 old_begv_byte
+= PT_BYTE
- before_byte
;
6116 if (old_zv
>= before
)
6118 old_zv
+= PT
- before
;
6119 old_zv_byte
+= PT_BYTE
- before_byte
;
6122 /* If the restriction isn't what it should be, set it. */
6123 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
6124 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
6126 bset_read_only (current_buffer
, old_read_only
);
6127 SET_PT_BOTH (opoint
, opoint_byte
);
6132 /* Sending data to subprocess. */
6134 /* In send_process, when a write fails temporarily,
6135 wait_reading_process_output is called. It may execute user code,
6136 e.g. timers, that attempts to write new data to the same process.
6137 We must ensure that data is sent in the right order, and not
6138 interspersed half-completed with other writes (Bug#10815). This is
6139 handled by the write_queue element of struct process. It is a list
6140 with each entry having the form
6142 (string . (offset . length))
6144 where STRING is a lisp string, OFFSET is the offset into the
6145 string's byte sequence from which we should begin to send, and
6146 LENGTH is the number of bytes left to send. */
6148 /* Create a new entry in write_queue.
6149 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6150 BUF is a pointer to the string sequence of the input_obj or a C
6151 string in case of Qt or Qnil. */
6154 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
6155 const char *buf
, ptrdiff_t len
, bool front
)
6158 Lisp_Object entry
, obj
;
6160 if (STRINGP (input_obj
))
6162 offset
= buf
- SSDATA (input_obj
);
6168 obj
= make_unibyte_string (buf
, len
);
6171 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
6174 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
6176 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
6179 /* Remove the first element in the write_queue of process P, put its
6180 contents in OBJ, BUF and LEN, and return true. If the
6181 write_queue is empty, return false. */
6184 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
6185 const char **buf
, ptrdiff_t *len
)
6187 Lisp_Object entry
, offset_length
;
6190 if (NILP (p
->write_queue
))
6193 entry
= XCAR (p
->write_queue
);
6194 pset_write_queue (p
, XCDR (p
->write_queue
));
6196 *obj
= XCAR (entry
);
6197 offset_length
= XCDR (entry
);
6199 *len
= XINT (XCDR (offset_length
));
6200 offset
= XINT (XCAR (offset_length
));
6201 *buf
= SSDATA (*obj
) + offset
;
6206 /* Send some data to process PROC.
6207 BUF is the beginning of the data; LEN is the number of characters.
6208 OBJECT is the Lisp object that the data comes from. If OBJECT is
6209 nil or t, it means that the data comes from C string.
6211 If OBJECT is not nil, the data is encoded by PROC's coding-system
6212 for encoding before it is sent.
6214 This function can evaluate Lisp code and can garbage collect. */
6217 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6220 struct Lisp_Process
*p
= XPROCESS (proc
);
6222 struct coding_system
*coding
;
6224 if (NETCONN_P (proc
))
6226 wait_while_connecting (proc
);
6227 wait_for_tls_negotiation (proc
);
6230 if (p
->raw_status_new
)
6232 if (! EQ (p
->status
, Qrun
))
6233 error ("Process %s not running", SDATA (p
->name
));
6235 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6237 coding
= proc_encode_coding_system
[p
->outfd
];
6238 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6240 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6241 || (BUFFERP (object
)
6242 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6245 pset_encode_coding_system
6246 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6247 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6249 /* The coding system for encoding was changed to raw-text
6250 because we sent a unibyte text previously. Now we are
6251 sending a multibyte text, thus we must encode it by the
6252 original coding system specified for the current process.
6254 Another reason we come here is that the coding system
6255 was just complemented and a new one was returned by
6256 complement_process_encoding_system. */
6257 setup_coding_system (p
->encode_coding_system
, coding
);
6258 Vlast_coding_system_used
= p
->encode_coding_system
;
6260 coding
->src_multibyte
= 1;
6264 coding
->src_multibyte
= 0;
6265 /* For sending a unibyte text, character code conversion should
6266 not take place but EOL conversion should. So, setup raw-text
6267 or one of the subsidiary if we have not yet done it. */
6268 if (CODING_REQUIRE_ENCODING (coding
))
6270 if (CODING_REQUIRE_FLUSHING (coding
))
6272 /* But, before changing the coding, we must flush out data. */
6273 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6274 send_process (proc
, "", 0, Qt
);
6275 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6277 setup_coding_system (raw_text_coding_system
6278 (Vlast_coding_system_used
),
6280 coding
->src_multibyte
= 0;
6283 coding
->dst_multibyte
= 0;
6285 if (CODING_REQUIRE_ENCODING (coding
))
6287 coding
->dst_object
= Qt
;
6288 if (BUFFERP (object
))
6290 ptrdiff_t from_byte
, from
, to
;
6291 ptrdiff_t save_pt
, save_pt_byte
;
6292 struct buffer
*cur
= current_buffer
;
6294 set_buffer_internal (XBUFFER (object
));
6295 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6297 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6298 from
= BYTE_TO_CHAR (from_byte
);
6299 to
= BYTE_TO_CHAR (from_byte
+ len
);
6300 TEMP_SET_PT_BOTH (from
, from_byte
);
6301 encode_coding_object (coding
, object
, from
, from_byte
,
6302 to
, from_byte
+ len
, Qt
);
6303 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6304 set_buffer_internal (cur
);
6306 else if (STRINGP (object
))
6308 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6309 SBYTES (object
), Qt
);
6313 coding
->dst_object
= make_unibyte_string (buf
, len
);
6314 coding
->produced
= len
;
6317 len
= coding
->produced
;
6318 object
= coding
->dst_object
;
6319 buf
= SSDATA (object
);
6322 /* If there is already data in the write_queue, put the new data
6323 in the back of queue. Otherwise, ignore it. */
6324 if (!NILP (p
->write_queue
))
6325 write_queue_push (p
, object
, buf
, len
, 0);
6327 do /* while !NILP (p->write_queue) */
6329 ptrdiff_t cur_len
= -1;
6330 const char *cur_buf
;
6331 Lisp_Object cur_object
;
6333 /* If write_queue is empty, ignore it. */
6334 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6338 cur_object
= object
;
6343 /* Send this batch, using one or more write calls. */
6344 ptrdiff_t written
= 0;
6345 int outfd
= p
->outfd
;
6346 #ifdef DATAGRAM_SOCKETS
6347 if (DATAGRAM_CHAN_P (outfd
))
6349 rv
= sendto (outfd
, cur_buf
, cur_len
,
6350 0, datagram_address
[outfd
].sa
,
6351 datagram_address
[outfd
].len
);
6354 else if (errno
== EMSGSIZE
)
6355 report_file_error ("Sending datagram", proc
);
6361 if (p
->gnutls_p
&& p
->gnutls_state
)
6362 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6365 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6366 rv
= (written
? 0 : -1);
6367 if (p
->read_output_delay
> 0
6368 && p
->adaptive_read_buffering
== 1)
6370 p
->read_output_delay
= 0;
6371 process_output_delay_count
--;
6372 p
->read_output_skip
= 0;
6378 if (would_block (errno
))
6379 /* Buffer is full. Wait, accepting input;
6380 that may allow the program
6381 to finish doing output and read more. */
6383 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6384 /* A gross hack to work around a bug in FreeBSD.
6385 In the following sequence, read(2) returns
6389 write(2) 954 bytes, get EAGAIN
6390 read(2) 1024 bytes in process_read_output
6391 read(2) 11 bytes in process_read_output
6393 That is, read(2) returns more bytes than have
6394 ever been written successfully. The 1033 bytes
6395 read are the 1022 bytes written successfully
6396 after processing (for example with CRs added if
6397 the terminal is set up that way which it is
6398 here). The same bytes will be seen again in a
6399 later read(2), without the CRs. */
6401 if (errno
== EAGAIN
)
6404 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6406 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6408 /* Put what we should have written in wait_queue. */
6409 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6410 wait_reading_process_output (0, 20 * 1000 * 1000,
6411 0, 0, Qnil
, NULL
, 0);
6412 /* Reread queue, to see what is left. */
6415 else if (errno
== EPIPE
)
6417 p
->raw_status_new
= 0;
6418 pset_status (p
, list2 (Qexit
, make_number (256)));
6419 p
->tick
= ++process_tick
;
6420 deactivate_process (proc
);
6421 error ("process %s no longer connected to pipe; closed it",
6425 /* This is a real error. */
6426 report_file_error ("Writing to process", proc
);
6432 while (!NILP (p
->write_queue
));
6435 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6437 doc
: /* Send current contents of region as input to PROCESS.
6438 PROCESS may be a process, a buffer, the name of a process or buffer, or
6439 nil, indicating the current buffer's process.
6440 Called from program, takes three arguments, PROCESS, START and END.
6441 If the region is more than 500 characters long,
6442 it is sent in several bunches. This may happen even for shorter regions.
6443 Output from processes can arrive in between bunches.
6445 If PROCESS is a non-blocking network process that hasn't been fully
6446 set up yet, this function will block until socket setup has completed. */)
6447 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6449 Lisp_Object proc
= get_process (process
);
6450 ptrdiff_t start_byte
, end_byte
;
6452 validate_region (&start
, &end
);
6454 start_byte
= CHAR_TO_BYTE (XINT (start
));
6455 end_byte
= CHAR_TO_BYTE (XINT (end
));
6457 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6458 move_gap_both (XINT (start
), start_byte
);
6460 if (NETCONN_P (proc
))
6461 wait_while_connecting (proc
);
6463 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6464 end_byte
- start_byte
, Fcurrent_buffer ());
6469 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6471 doc
: /* Send PROCESS the contents of STRING as input.
6472 PROCESS may be a process, a buffer, the name of a process or buffer, or
6473 nil, indicating the current buffer's process.
6474 If STRING is more than 500 characters long,
6475 it is sent in several bunches. This may happen even for shorter strings.
6476 Output from processes can arrive in between bunches.
6478 If PROCESS is a non-blocking network process that hasn't been fully
6479 set up yet, this function will block until socket setup has completed. */)
6480 (Lisp_Object process
, Lisp_Object string
)
6482 CHECK_STRING (string
);
6483 Lisp_Object proc
= get_process (process
);
6484 send_process (proc
, SSDATA (string
),
6485 SBYTES (string
), string
);
6489 /* Return the foreground process group for the tty/pty that
6490 the process P uses. */
6492 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6497 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6500 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6501 master side. Try the slave side. */
6502 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6506 ioctl (fd
, TIOCGPGRP
, &gid
);
6510 #endif /* defined (TIOCGPGRP ) */
6515 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6516 Sprocess_running_child_p
, 0, 1, 0,
6517 doc
: /* Return non-nil if PROCESS has given the terminal to a
6518 child. If the operating system does not make it possible to find out,
6519 return t. If we can find out, return the numeric ID of the foreground
6521 (Lisp_Object process
)
6523 /* Initialize in case ioctl doesn't exist or gives an error,
6524 in a way that will cause returning t. */
6525 Lisp_Object proc
= get_process (process
);
6526 struct Lisp_Process
*p
= XPROCESS (proc
);
6528 if (!EQ (p
->type
, Qreal
))
6529 error ("Process %s is not a subprocess",
6532 error ("Process %s is not active",
6535 pid_t gid
= emacs_get_tty_pgrp (p
);
6540 return make_number (gid
);
6544 /* Send a signal number SIGNO to PROCESS.
6545 If CURRENT_GROUP is t, that means send to the process group
6546 that currently owns the terminal being used to communicate with PROCESS.
6547 This is used for various commands in shell mode.
6548 If CURRENT_GROUP is lambda, that means send to the process group
6549 that currently owns the terminal, but only if it is NOT the shell itself.
6551 If NOMSG is false, insert signal-announcements into process's buffers
6554 If we can, we try to signal PROCESS by sending control characters
6555 down the pty. This allows us to signal inferiors who have changed
6556 their uid, for which kill would return an EPERM error. */
6559 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6563 struct Lisp_Process
*p
;
6567 proc
= get_process (process
);
6568 p
= XPROCESS (proc
);
6570 if (!EQ (p
->type
, Qreal
))
6571 error ("Process %s is not a subprocess",
6574 error ("Process %s is not active",
6578 current_group
= Qnil
;
6580 /* If we are using pgrps, get a pgrp number and make it negative. */
6581 if (NILP (current_group
))
6582 /* Send the signal to the shell's process group. */
6586 #ifdef SIGNALS_VIA_CHARACTERS
6587 /* If possible, send signals to the entire pgrp
6588 by sending an input character to it. */
6591 cc_t
*sig_char
= NULL
;
6593 tcgetattr (p
->infd
, &t
);
6598 sig_char
= &t
.c_cc
[VINTR
];
6602 sig_char
= &t
.c_cc
[VQUIT
];
6607 sig_char
= &t
.c_cc
[VSWTCH
];
6609 sig_char
= &t
.c_cc
[VSUSP
];
6614 if (sig_char
&& *sig_char
!= CDISABLE
)
6616 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6619 /* If we can't send the signal with a character,
6620 fall through and send it another way. */
6622 /* The code above may fall through if it can't
6623 handle the signal. */
6624 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6627 /* Get the current pgrp using the tty itself, if we have that.
6628 Otherwise, use the pty to get the pgrp.
6629 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6630 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6631 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6632 His patch indicates that if TIOCGPGRP returns an error, then
6633 we should just assume that p->pid is also the process group id. */
6635 gid
= emacs_get_tty_pgrp (p
);
6638 /* If we can't get the information, assume
6639 the shell owns the tty. */
6642 /* It is not clear whether anything really can set GID to -1.
6643 Perhaps on some system one of those ioctls can or could do so.
6644 Or perhaps this is vestigial. */
6647 #else /* ! defined (TIOCGPGRP) */
6648 /* Can't select pgrps on this system, so we know that
6649 the child itself heads the pgrp. */
6651 #endif /* ! defined (TIOCGPGRP) */
6653 /* If current_group is lambda, and the shell owns the terminal,
6654 don't send any signal. */
6655 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6660 if (signo
== SIGCONT
)
6662 p
->raw_status_new
= 0;
6663 pset_status (p
, Qrun
);
6664 p
->tick
= ++process_tick
;
6667 status_notify (NULL
, NULL
);
6668 redisplay_preserve_echo_area (13);
6674 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6675 We don't know whether the bug is fixed in later HP-UX versions. */
6676 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6680 /* If we don't have process groups, send the signal to the immediate
6681 subprocess. That isn't really right, but it's better than any
6682 obvious alternative. */
6683 pid_t pid
= no_pgrp
? gid
: - gid
;
6685 /* Do not kill an already-reaped process, as that could kill an
6686 innocent bystander that happens to have the same process ID. */
6688 block_child_signal (&oldset
);
6691 unblock_child_signal (&oldset
);
6694 DEFUN ("internal-default-interrupt-process",
6695 Finternal_default_interrupt_process
,
6696 Sinternal_default_interrupt_process
, 0, 2, 0,
6697 doc
: /* Default function to interrupt process PROCESS.
6698 It shall be the last element in list `interrupt-process-functions'.
6699 See function `interrupt-process' for more details on usage. */)
6700 (Lisp_Object process
, Lisp_Object current_group
)
6702 process_send_signal (process
, SIGINT
, current_group
, 0);
6706 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6707 doc
: /* Interrupt process PROCESS.
6708 PROCESS may be a process, a buffer, or the name of a process or buffer.
6709 No arg or nil means current buffer's process.
6710 Second arg CURRENT-GROUP non-nil means send signal to
6711 the current process-group of the process's controlling terminal
6712 rather than to the process's own process group.
6713 If the process is a shell, this means interrupt current subjob
6714 rather than the shell.
6716 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6717 don't send the signal.
6719 This function calls the functions of `interrupt-process-functions' in
6720 the order of the list, until one of them returns non-`nil'. */)
6721 (Lisp_Object process
, Lisp_Object current_group
)
6723 return CALLN (Frun_hook_with_args_until_success
, Qinterrupt_process_functions
,
6724 process
, current_group
);
6727 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6728 doc
: /* Kill process PROCESS. May be process or name of one.
6729 See function `interrupt-process' for more details on usage. */)
6730 (Lisp_Object process
, Lisp_Object current_group
)
6732 process_send_signal (process
, SIGKILL
, current_group
, 0);
6736 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6737 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6738 See function `interrupt-process' for more details on usage. */)
6739 (Lisp_Object process
, Lisp_Object current_group
)
6741 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6745 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6746 doc
: /* Stop process PROCESS. May be process or name of one.
6747 See function `interrupt-process' for more details on usage.
6748 If PROCESS is a network or serial or pipe connection, inhibit handling
6749 of incoming traffic. */)
6750 (Lisp_Object process
, Lisp_Object current_group
)
6752 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6753 || PIPECONN_P (process
)))
6755 struct Lisp_Process
*p
;
6757 p
= XPROCESS (process
);
6758 if (NILP (p
->command
)
6760 delete_read_fd (p
->infd
);
6761 pset_command (p
, Qt
);
6765 error ("No SIGTSTP support");
6767 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6772 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6773 doc
: /* Continue process PROCESS. May be process or name of one.
6774 See function `interrupt-process' for more details on usage.
6775 If PROCESS is a network or serial process, resume handling of incoming
6777 (Lisp_Object process
, Lisp_Object current_group
)
6779 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6780 || PIPECONN_P (process
)))
6782 struct Lisp_Process
*p
;
6784 p
= XPROCESS (process
);
6785 if (EQ (p
->command
, Qt
)
6787 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6789 add_process_read_fd (p
->infd
);
6791 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6792 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6793 #else /* not WINDOWSNT */
6794 tcflush (p
->infd
, TCIFLUSH
);
6795 #endif /* not WINDOWSNT */
6797 pset_command (p
, Qnil
);
6801 process_send_signal (process
, SIGCONT
, current_group
, 0);
6803 error ("No SIGCONT support");
6808 /* Return the integer value of the signal whose abbreviation is ABBR,
6809 or a negative number if there is no such signal. */
6811 abbr_to_signal (char const *name
)
6814 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6816 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6819 for (i
= 0; i
< sizeof sigbuf
; i
++)
6821 sigbuf
[i
] = c_toupper (name
[i
]);
6823 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6829 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6830 2, 2, "sProcess (name or number): \nnSignal code: ",
6831 doc
: /* Send PROCESS the signal with code SIGCODE.
6832 PROCESS may also be a number specifying the process id of the
6833 process to signal; in this case, the process need not be a child of
6835 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6836 (Lisp_Object process
, Lisp_Object sigcode
)
6841 if (STRINGP (process
))
6843 Lisp_Object tem
= Fget_process (process
);
6845 tem
= string_to_number (SSDATA (process
), 10, S2N_OVERFLOW_TO_FLOAT
);
6848 else if (!NUMBERP (process
))
6849 process
= get_process (process
);
6854 if (NUMBERP (process
))
6855 CONS_TO_INTEGER (process
, pid_t
, pid
);
6858 CHECK_PROCESS (process
);
6859 pid
= XPROCESS (process
)->pid
;
6861 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6864 if (INTEGERP (sigcode
))
6866 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6867 signo
= XINT (sigcode
);
6873 CHECK_SYMBOL (sigcode
);
6874 name
= SSDATA (SYMBOL_NAME (sigcode
));
6876 signo
= abbr_to_signal (name
);
6878 error ("Undefined signal name %s", name
);
6881 return make_number (kill (pid
, signo
));
6884 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6885 doc
: /* Make PROCESS see end-of-file in its input.
6886 EOF comes after any text already sent to it.
6887 PROCESS may be a process, a buffer, the name of a process or buffer, or
6888 nil, indicating the current buffer's process.
6889 If PROCESS is a network connection, or is a process communicating
6890 through a pipe (as opposed to a pty), then you cannot send any more
6891 text to PROCESS after you call this function.
6892 If PROCESS is a serial process, wait until all output written to the
6893 process has been transmitted to the serial port. */)
6894 (Lisp_Object process
)
6897 struct coding_system
*coding
= NULL
;
6900 proc
= get_process (process
);
6902 if (NETCONN_P (proc
))
6903 wait_while_connecting (proc
);
6905 if (DATAGRAM_CONN_P (proc
))
6909 outfd
= XPROCESS (proc
)->outfd
;
6911 coding
= proc_encode_coding_system
[outfd
];
6913 /* Make sure the process is really alive. */
6914 if (XPROCESS (proc
)->raw_status_new
)
6915 update_status (XPROCESS (proc
));
6916 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6917 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6919 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6921 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6922 send_process (proc
, "", 0, Qnil
);
6925 if (XPROCESS (proc
)->pty_flag
)
6926 send_process (proc
, "\004", 1, Qnil
);
6927 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6930 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6931 report_file_error ("Failed tcdrain", Qnil
);
6932 #endif /* not WINDOWSNT */
6933 /* Do nothing on Windows because writes are blocking. */
6937 struct Lisp_Process
*p
= XPROCESS (proc
);
6938 int old_outfd
= p
->outfd
;
6941 #ifdef HAVE_SHUTDOWN
6942 /* If this is a network connection, or socketpair is used
6943 for communication with the subprocess, call shutdown to cause EOF.
6944 (In some old system, shutdown to socketpair doesn't work.
6945 Then we just can't win.) */
6947 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6948 shutdown (old_outfd
, 1);
6950 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6951 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6953 report_file_error ("Opening null device", Qnil
);
6954 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6955 p
->outfd
= new_outfd
;
6957 if (!proc_encode_coding_system
[new_outfd
])
6958 proc_encode_coding_system
[new_outfd
]
6959 = xmalloc (sizeof (struct coding_system
));
6962 *proc_encode_coding_system
[new_outfd
]
6963 = *proc_encode_coding_system
[old_outfd
];
6964 memset (proc_encode_coding_system
[old_outfd
], 0,
6965 sizeof (struct coding_system
));
6968 setup_coding_system (p
->encode_coding_system
,
6969 proc_encode_coding_system
[new_outfd
]);
6974 /* The main Emacs thread records child processes in three places:
6976 - Vprocess_alist, for asynchronous subprocesses, which are child
6977 processes visible to Lisp.
6979 - deleted_pid_list, for child processes invisible to Lisp,
6980 typically because of delete-process. These are recorded so that
6981 the processes can be reaped when they exit, so that the operating
6982 system's process table is not cluttered by zombies.
6984 - the local variable PID in Fcall_process, call_process_cleanup and
6985 call_process_kill, for synchronous subprocesses.
6986 record_unwind_protect is used to make sure this process is not
6987 forgotten: if the user interrupts call-process and the child
6988 process refuses to exit immediately even with two C-g's,
6989 call_process_kill adds PID's contents to deleted_pid_list before
6992 The main Emacs thread invokes waitpid only on child processes that
6993 it creates and that have not been reaped. This avoid races on
6994 platforms such as GTK, where other threads create their own
6995 subprocesses which the main thread should not reap. For example,
6996 if the main thread attempted to reap an already-reaped child, it
6997 might inadvertently reap a GTK-created process that happened to
6998 have the same process ID. */
7000 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7001 its own SIGCHLD handling. On POSIXish systems, glib needs this to
7002 keep track of its own children. GNUstep is similar. */
7004 static void dummy_handler (int sig
) {}
7005 static signal_handler_t
volatile lib_child_handler
;
7007 /* Handle a SIGCHLD signal by looking for known child processes of
7008 Emacs whose status have changed. For each one found, record its
7011 All we do is change the status; we do not run sentinels or print
7012 notifications. That is saved for the next time keyboard input is
7013 done, in order to avoid timing errors.
7015 ** WARNING: this can be called during garbage collection.
7016 Therefore, it must not be fooled by the presence of mark bits in
7019 ** USG WARNING: Although it is not obvious from the documentation
7020 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7021 signal() before executing at least one wait(), otherwise the
7022 handler will be called again, resulting in an infinite loop. The
7023 relevant portion of the documentation reads "SIGCLD signals will be
7024 queued and the signal-catching function will be continually
7025 reentered until the queue is empty". Invoking signal() causes the
7026 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7029 ** Malloc WARNING: This should never call malloc either directly or
7030 indirectly; if it does, that is a bug. */
7033 handle_child_signal (int sig
)
7035 Lisp_Object tail
, proc
;
7037 /* Find the process that signaled us, and record its status. */
7039 /* The process can have been deleted by Fdelete_process, or have
7040 been started asynchronously by Fcall_process. */
7041 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
7043 bool all_pids_are_fixnums
7044 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
7045 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
7046 Lisp_Object head
= XCAR (tail
);
7051 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
7054 if (INTEGERP (xpid
))
7055 deleted_pid
= XINT (xpid
);
7057 deleted_pid
= XFLOAT_DATA (xpid
);
7058 if (child_status_changed (deleted_pid
, 0, 0))
7060 if (STRINGP (XCDR (head
)))
7061 unlink (SSDATA (XCDR (head
)));
7062 XSETCAR (tail
, Qnil
);
7067 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7068 FOR_EACH_PROCESS (tail
, proc
)
7070 struct Lisp_Process
*p
= XPROCESS (proc
);
7074 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
7076 /* Change the status of the process that was found. */
7077 p
->tick
= ++process_tick
;
7078 p
->raw_status
= status
;
7079 p
->raw_status_new
= 1;
7081 /* If process has terminated, stop waiting for its output. */
7082 if (WIFSIGNALED (status
) || WIFEXITED (status
))
7084 bool clear_desc_flag
= 0;
7087 clear_desc_flag
= 1;
7089 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7090 if (clear_desc_flag
)
7091 delete_read_fd (p
->infd
);
7096 lib_child_handler (sig
);
7097 #ifdef NS_IMPL_GNUSTEP
7098 /* NSTask in GNUstep sets its child handler each time it is called.
7099 So we must re-set ours. */
7100 catch_child_signal ();
7105 deliver_child_signal (int sig
)
7107 deliver_process_signal (sig
, handle_child_signal
);
7112 exec_sentinel_error_handler (Lisp_Object error_val
)
7114 /* Make sure error_val is a cons cell, as all the rest of error
7115 handling expects that, and will barf otherwise. */
7116 if (!CONSP (error_val
))
7117 error_val
= Fcons (Qerror
, error_val
);
7118 cmd_error_internal (error_val
, "error in process sentinel: ");
7120 update_echo_area ();
7121 Fsleep_for (make_number (2), Qnil
);
7126 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
7128 Lisp_Object sentinel
, odeactivate
;
7129 struct Lisp_Process
*p
= XPROCESS (proc
);
7130 ptrdiff_t count
= SPECPDL_INDEX ();
7131 bool outer_running_asynch_code
= running_asynch_code
;
7132 int waiting
= waiting_for_user_input_p
;
7134 if (inhibit_sentinels
)
7137 odeactivate
= Vdeactivate_mark
;
7139 Lisp_Object obuffer
, okeymap
;
7140 XSETBUFFER (obuffer
, current_buffer
);
7141 okeymap
= BVAR (current_buffer
, keymap
);
7144 /* There's no good reason to let sentinels change the current
7145 buffer, and many callers of accept-process-output, sit-for, and
7146 friends don't expect current-buffer to be changed from under them. */
7147 record_unwind_current_buffer ();
7149 sentinel
= p
->sentinel
;
7151 /* Inhibit quit so that random quits don't screw up a running filter. */
7152 specbind (Qinhibit_quit
, Qt
);
7153 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
7155 /* In case we get recursively called,
7156 and we already saved the match data nonrecursively,
7157 save the same match data in safely recursive fashion. */
7158 if (outer_running_asynch_code
)
7161 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
7162 restore_search_regs ();
7163 record_unwind_save_match_data ();
7164 Fset_match_data (tem
, Qt
);
7167 /* For speed, if a search happens within this code,
7168 save the match data in a special nonrecursive fashion. */
7169 running_asynch_code
= 1;
7171 internal_condition_case_1 (read_process_output_call
,
7172 list3 (sentinel
, proc
, reason
),
7173 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
7174 exec_sentinel_error_handler
);
7176 /* If we saved the match data nonrecursively, restore it now. */
7177 restore_search_regs ();
7178 running_asynch_code
= outer_running_asynch_code
;
7180 Vdeactivate_mark
= odeactivate
;
7182 /* Restore waiting_for_user_input_p as it was
7183 when we were called, in case the filter clobbered it. */
7184 waiting_for_user_input_p
= waiting
;
7187 if (! EQ (Fcurrent_buffer (), obuffer
)
7188 || ! EQ (current_buffer
->keymap
, okeymap
))
7190 /* But do it only if the caller is actually going to read events.
7191 Otherwise there's no need to make him wake up, and it could
7192 cause trouble (for example it would make sit_for return). */
7193 if (waiting_for_user_input_p
== -1)
7194 record_asynch_buffer_change ();
7196 unbind_to (count
, Qnil
);
7199 /* Report all recent events of a change in process status
7200 (either run the sentinel or output a message).
7201 This is usually done while Emacs is waiting for keyboard input
7202 but can be done at other times.
7204 Return positive if any input was received from WAIT_PROC (or from
7205 any process if WAIT_PROC is null), zero if input was attempted but
7206 none received, and negative if we didn't even try. */
7209 status_notify (struct Lisp_Process
*deleting_process
,
7210 struct Lisp_Process
*wait_proc
)
7213 Lisp_Object tail
, msg
;
7214 int got_some_output
= -1;
7219 /* Set this now, so that if new processes are created by sentinels
7220 that we run, we get called again to handle their status changes. */
7221 update_tick
= process_tick
;
7223 FOR_EACH_PROCESS (tail
, proc
)
7226 register struct Lisp_Process
*p
= XPROCESS (proc
);
7228 if (p
->tick
!= p
->update_tick
)
7230 p
->update_tick
= p
->tick
;
7232 /* If process is still active, read any output that remains. */
7233 while (! EQ (p
->filter
, Qt
)
7234 && ! connecting_status (p
->status
)
7235 && ! EQ (p
->status
, Qlisten
)
7236 /* Network or serial process not stopped: */
7237 && ! EQ (p
->command
, Qt
)
7239 && p
!= deleting_process
)
7241 int nread
= read_process_output (proc
, p
->infd
);
7242 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7243 && got_some_output
< nread
)
7244 got_some_output
= nread
;
7249 /* Get the text to use for the message. */
7250 if (p
->raw_status_new
)
7252 msg
= status_message (p
);
7254 /* If process is terminated, deactivate it or delete it. */
7256 if (CONSP (p
->status
))
7257 symbol
= XCAR (p
->status
);
7259 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7260 || EQ (symbol
, Qclosed
))
7262 if (delete_exited_processes
)
7263 remove_process (proc
);
7265 deactivate_process (proc
);
7268 /* The actions above may have further incremented p->tick.
7269 So set p->update_tick again so that an error in the sentinel will
7270 not cause this code to be run again. */
7271 p
->update_tick
= p
->tick
;
7272 /* Now output the message suitably. */
7273 exec_sentinel (proc
, msg
);
7274 if (BUFFERP (p
->buffer
))
7275 /* In case it uses %s in mode-line-format. */
7276 bset_update_mode_line (XBUFFER (p
->buffer
));
7280 return got_some_output
;
7283 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7284 Sinternal_default_process_sentinel
, 2, 2, 0,
7285 doc
: /* Function used as default sentinel for processes.
7286 This inserts a status message into the process's buffer, if there is one. */)
7287 (Lisp_Object proc
, Lisp_Object msg
)
7289 Lisp_Object buffer
, symbol
;
7290 struct Lisp_Process
*p
;
7291 CHECK_PROCESS (proc
);
7292 p
= XPROCESS (proc
);
7296 symbol
= XCAR (symbol
);
7298 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7301 struct buffer
*old
= current_buffer
;
7302 ptrdiff_t opoint
, opoint_byte
;
7303 ptrdiff_t before
, before_byte
;
7305 /* Avoid error if buffer is deleted
7306 (probably that's why the process is dead, too). */
7307 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7309 Fset_buffer (buffer
);
7311 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7312 msg
= (code_convert_string_norecord
7313 (msg
, Vlocale_coding_system
, 1));
7316 opoint_byte
= PT_BYTE
;
7317 /* Insert new output into buffer
7318 at the current end-of-output marker,
7319 thus preserving logical ordering of input and output. */
7320 if (XMARKER (p
->mark
)->buffer
)
7321 Fgoto_char (p
->mark
);
7323 SET_PT_BOTH (ZV
, ZV_BYTE
);
7326 before_byte
= PT_BYTE
;
7328 tem
= BVAR (current_buffer
, read_only
);
7329 bset_read_only (current_buffer
, Qnil
);
7330 insert_string ("\nProcess ");
7331 { /* FIXME: temporary kludge. */
7332 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7333 insert_string (" ");
7335 bset_read_only (current_buffer
, tem
);
7336 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7338 if (opoint
>= before
)
7339 SET_PT_BOTH (opoint
+ (PT
- before
),
7340 opoint_byte
+ (PT_BYTE
- before_byte
));
7342 SET_PT_BOTH (opoint
, opoint_byte
);
7344 set_buffer_internal (old
);
7350 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7351 Sset_process_coding_system
, 1, 3, 0,
7352 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7353 DECODING will be used to decode subprocess output and ENCODING to
7354 encode subprocess input. */)
7355 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7357 CHECK_PROCESS (process
);
7359 struct Lisp_Process
*p
= XPROCESS (process
);
7361 Fcheck_coding_system (decoding
);
7362 Fcheck_coding_system (encoding
);
7363 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7364 pset_decode_coding_system (p
, decoding
);
7365 pset_encode_coding_system (p
, encoding
);
7367 /* If the sockets haven't been set up yet, the final setup part of
7368 this will be called asynchronously. */
7369 if (p
->infd
< 0 || p
->outfd
< 0)
7372 setup_process_coding_systems (process
);
7377 DEFUN ("process-coding-system",
7378 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7379 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7380 (register Lisp_Object process
)
7382 CHECK_PROCESS (process
);
7383 return Fcons (XPROCESS (process
)->decode_coding_system
,
7384 XPROCESS (process
)->encode_coding_system
);
7387 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7388 Sset_process_filter_multibyte
, 2, 2, 0,
7389 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7390 If FLAG is non-nil, the filter is given multibyte strings.
7391 If FLAG is nil, the filter is given unibyte strings. In this case,
7392 all character code conversion except for end-of-line conversion is
7394 (Lisp_Object process
, Lisp_Object flag
)
7396 CHECK_PROCESS (process
);
7398 struct Lisp_Process
*p
= XPROCESS (process
);
7400 pset_decode_coding_system
7401 (p
, raw_text_coding_system (p
->decode_coding_system
));
7403 /* If the sockets haven't been set up yet, the final setup part of
7404 this will be called asynchronously. */
7405 if (p
->infd
< 0 || p
->outfd
< 0)
7408 setup_process_coding_systems (process
);
7413 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7414 Sprocess_filter_multibyte_p
, 1, 1, 0,
7415 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7416 (Lisp_Object process
)
7418 CHECK_PROCESS (process
);
7419 struct Lisp_Process
*p
= XPROCESS (process
);
7422 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7423 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7432 add_gpm_wait_descriptor (int desc
)
7434 add_keyboard_wait_descriptor (desc
);
7438 delete_gpm_wait_descriptor (int desc
)
7440 delete_keyboard_wait_descriptor (desc
);
7445 # ifdef USABLE_SIGIO
7447 /* Return true if *MASK has a bit set
7448 that corresponds to one of the keyboard input descriptors. */
7451 keyboard_bit_set (fd_set
*mask
)
7455 for (fd
= 0; fd
<= max_desc
; fd
++)
7456 if (FD_ISSET (fd
, mask
)
7457 && ((fd_callback_info
[fd
].flags
& (FOR_READ
| KEYBOARD_FD
))
7458 == (FOR_READ
| KEYBOARD_FD
)))
7465 #else /* not subprocesses */
7467 /* This is referenced in thread.c:run_thread (which is never actually
7468 called, since threads are not enabled for this configuration. */
7470 update_processes_for_thread_death (Lisp_Object dying_thread
)
7474 /* Defined in msdos.c. */
7475 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7476 struct timespec
*, void *);
7478 /* Implementation of wait_reading_process_output, assuming that there
7479 are no subprocesses. Used only by the MS-DOS build.
7481 Wait for timeout to elapse and/or keyboard input to be available.
7485 If negative, gobble data immediately available but don't wait for any.
7488 an additional duration to wait, measured in nanoseconds
7489 If TIME_LIMIT is zero, then:
7490 If NSECS == 0, there is no limit.
7491 If NSECS > 0, the timeout consists of NSECS only.
7492 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7495 0 to ignore keyboard input, or
7496 1 to return when input is available, or
7497 -1 means caller will actually read the input, so don't throw to
7500 see full version for other parameters. We know that wait_proc will
7501 always be NULL, since `subprocesses' isn't defined.
7503 DO_DISPLAY means redisplay should be done to show subprocess
7504 output that arrives.
7506 Return -1 signifying we got no output and did not try. */
7509 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7511 Lisp_Object wait_for_cell
,
7512 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7515 struct timespec end_time
, timeout
;
7516 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7518 if (TYPE_MAXIMUM (time_t) < time_limit
)
7519 time_limit
= TYPE_MAXIMUM (time_t);
7521 if (time_limit
< 0 || nsecs
< 0)
7523 else if (time_limit
> 0 || nsecs
> 0)
7526 end_time
= timespec_add (current_timespec (),
7527 make_timespec (time_limit
, nsecs
));
7532 /* Turn off periodic alarms (in case they are in use)
7533 and then turn off any other atimers,
7534 because the select emulator uses alarms. */
7536 turn_on_atimers (0);
7540 bool timeout_reduced_for_timers
= false;
7541 fd_set waitchannels
;
7544 /* If calling from keyboard input, do not quit
7545 since we want to return C-g as an input character.
7546 Otherwise, do pending quit if requested. */
7550 /* Exit now if the cell we're waiting for became non-nil. */
7551 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7554 /* Compute time from now till when time limit is up. */
7555 /* Exit if already run out. */
7556 if (wait
== TIMEOUT
)
7558 struct timespec now
= current_timespec ();
7559 if (timespec_cmp (end_time
, now
) <= 0)
7561 timeout
= timespec_sub (end_time
, now
);
7564 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7566 /* If our caller will not immediately handle keyboard events,
7567 run timer events directly.
7568 (Callers that will immediately read keyboard events
7569 call timer_delay on their own.) */
7570 if (NILP (wait_for_cell
))
7572 struct timespec timer_delay
;
7576 unsigned old_timers_run
= timers_run
;
7577 timer_delay
= timer_check ();
7578 if (timers_run
!= old_timers_run
&& do_display
)
7579 /* We must retry, since a timer may have requeued itself
7580 and that could alter the time delay. */
7581 redisplay_preserve_echo_area (14);
7585 while (!detect_input_pending ());
7587 /* If there is unread keyboard input, also return. */
7589 && requeued_events_pending_p ())
7592 if (timespec_valid_p (timer_delay
))
7594 if (timespec_cmp (timer_delay
, timeout
) < 0)
7596 timeout
= timer_delay
;
7597 timeout_reduced_for_timers
= true;
7602 /* Cause C-g and alarm signals to take immediate action,
7603 and cause input available signals to zero out timeout. */
7605 set_waiting_for_input (&timeout
);
7607 /* If a frame has been newly mapped and needs updating,
7608 reprocess its display stuff. */
7609 if (frame_garbaged
&& do_display
)
7611 clear_waiting_for_input ();
7612 redisplay_preserve_echo_area (15);
7614 set_waiting_for_input (&timeout
);
7617 /* Wait till there is something to do. */
7618 FD_ZERO (&waitchannels
);
7619 if (read_kbd
&& detect_input_pending ())
7623 if (read_kbd
|| !NILP (wait_for_cell
))
7624 FD_SET (0, &waitchannels
);
7625 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7630 /* Make C-g and alarm signals set flags again. */
7631 clear_waiting_for_input ();
7633 /* If we woke up due to SIGWINCH, actually change size now. */
7634 do_pending_window_change (0);
7636 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7637 /* We waited the full specified time, so return now. */
7642 /* If the system call was interrupted, then go around the
7644 if (xerrno
== EINTR
)
7645 FD_ZERO (&waitchannels
);
7647 report_file_errno ("Failed select", Qnil
, xerrno
);
7650 /* Check for keyboard input. */
7653 && detect_input_pending_run_timers (do_display
))
7655 swallow_events (do_display
);
7656 if (detect_input_pending_run_timers (do_display
))
7660 /* If there is unread keyboard input, also return. */
7662 && requeued_events_pending_p ())
7665 /* If wait_for_cell. check for keyboard input
7666 but don't run any timers.
7667 ??? (It seems wrong to me to check for keyboard
7668 input at all when wait_for_cell, but the code
7669 has been this way since July 1994.
7670 Try changing this after version 19.31.) */
7671 if (! NILP (wait_for_cell
)
7672 && detect_input_pending ())
7674 swallow_events (do_display
);
7675 if (detect_input_pending ())
7679 /* Exit now if the cell we're waiting for became non-nil. */
7680 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7689 #endif /* not subprocesses */
7691 /* The following functions are needed even if async subprocesses are
7692 not supported. Some of them are no-op stubs in that case. */
7696 /* Add FD, which is a descriptor returned by timerfd_create,
7697 to the set of non-keyboard input descriptors. */
7700 add_timer_wait_descriptor (int fd
)
7702 add_read_fd (fd
, timerfd_callback
, NULL
);
7703 fd_callback_info
[fd
].flags
&= ~KEYBOARD_FD
;
7706 #endif /* HAVE_TIMERFD */
7708 /* If program file NAME starts with /: for quoting a magic
7709 name, remove that, preserving the multibyteness of NAME. */
7712 remove_slash_colon (Lisp_Object name
)
7715 (SREF (name
, 0) == '/' && SREF (name
, 1) == ':'
7716 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7717 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7721 /* Add DESC to the set of keyboard input descriptors. */
7724 add_keyboard_wait_descriptor (int desc
)
7726 #ifdef subprocesses /* Actually means "not MSDOS". */
7727 eassert (desc
>= 0 && desc
< FD_SETSIZE
);
7728 fd_callback_info
[desc
].flags
&= ~PROCESS_FD
;
7729 fd_callback_info
[desc
].flags
|= (FOR_READ
| KEYBOARD_FD
);
7730 if (desc
> max_desc
)
7735 /* From now on, do not expect DESC to give keyboard input. */
7738 delete_keyboard_wait_descriptor (int desc
)
7741 eassert (desc
>= 0 && desc
< FD_SETSIZE
);
7743 fd_callback_info
[desc
].flags
&= ~(FOR_READ
| KEYBOARD_FD
| PROCESS_FD
);
7745 if (desc
== max_desc
)
7746 recompute_max_desc ();
7750 /* Setup coding systems of PROCESS. */
7753 setup_process_coding_systems (Lisp_Object process
)
7756 struct Lisp_Process
*p
= XPROCESS (process
);
7758 int outch
= p
->outfd
;
7759 Lisp_Object coding_system
;
7761 if (inch
< 0 || outch
< 0)
7764 if (!proc_decode_coding_system
[inch
])
7765 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7766 coding_system
= p
->decode_coding_system
;
7767 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7768 && BUFFERP (p
->buffer
))
7770 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7771 coding_system
= raw_text_coding_system (coding_system
);
7773 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7775 if (!proc_encode_coding_system
[outch
])
7776 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7777 setup_coding_system (p
->encode_coding_system
,
7778 proc_encode_coding_system
[outch
]);
7782 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7783 doc
: /* Return the (or a) live process associated with BUFFER.
7784 BUFFER may be a buffer or the name of one.
7785 Return nil if all processes associated with BUFFER have been
7786 deleted or killed. */)
7787 (register Lisp_Object buffer
)
7790 register Lisp_Object buf
, tail
, proc
;
7792 if (NILP (buffer
)) return Qnil
;
7793 buf
= Fget_buffer (buffer
);
7794 if (NILP (buf
)) return Qnil
;
7796 FOR_EACH_PROCESS (tail
, proc
)
7797 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7799 #endif /* subprocesses */
7803 DEFUN ("process-inherit-coding-system-flag",
7804 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7806 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7807 If this flag is t, `buffer-file-coding-system' of the buffer
7808 associated with PROCESS will inherit the coding system used to decode
7809 the process output. */)
7810 (register Lisp_Object process
)
7813 CHECK_PROCESS (process
);
7814 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7816 /* Ignore the argument and return the value of
7817 inherit-process-coding-system. */
7818 return inherit_process_coding_system
? Qt
: Qnil
;
7822 /* Kill all processes associated with `buffer'.
7823 If `buffer' is nil, kill all processes. */
7826 kill_buffer_processes (Lisp_Object buffer
)
7829 Lisp_Object tail
, proc
;
7831 FOR_EACH_PROCESS (tail
, proc
)
7832 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7834 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7835 Fdelete_process (proc
);
7836 else if (XPROCESS (proc
)->infd
>= 0)
7837 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7839 #else /* subprocesses */
7840 /* Since we have no subprocesses, this does nothing. */
7841 #endif /* subprocesses */
7844 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7845 Swaiting_for_user_input_p
, 0, 0, 0,
7846 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7847 This is intended for use by asynchronous process output filters and sentinels. */)
7851 return (waiting_for_user_input_p
? Qt
: Qnil
);
7857 /* Stop reading input from keyboard sources. */
7860 hold_keyboard_input (void)
7865 /* Resume reading input from keyboard sources. */
7868 unhold_keyboard_input (void)
7873 /* Return true if keyboard input is on hold, zero otherwise. */
7876 kbd_on_hold_p (void)
7878 return kbd_is_on_hold
;
7882 /* Enumeration of and access to system processes a-la ps(1). */
7884 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7886 doc
: /* Return a list of numerical process IDs of all running processes.
7887 If this functionality is unsupported, return nil.
7889 See `process-attributes' for getting attributes of a process given its ID. */)
7892 return list_system_processes ();
7895 DEFUN ("process-attributes", Fprocess_attributes
,
7896 Sprocess_attributes
, 1, 1, 0,
7897 doc
: /* Return attributes of the process given by its PID, a number.
7899 Value is an alist where each element is a cons cell of the form
7903 If this functionality is unsupported, the value is nil.
7905 See `list-system-processes' for getting a list of all process IDs.
7907 The KEYs of the attributes that this function may return are listed
7908 below, together with the type of the associated VALUE (in parentheses).
7909 Not all platforms support all of these attributes; unsupported
7910 attributes will not appear in the returned alist.
7911 Unless explicitly indicated otherwise, numbers can have either
7912 integer or floating point values.
7914 euid -- Effective user User ID of the process (number)
7915 user -- User name corresponding to euid (string)
7916 egid -- Effective user Group ID of the process (number)
7917 group -- Group name corresponding to egid (string)
7918 comm -- Command name (executable name only) (string)
7919 state -- Process state code, such as "S", "R", or "T" (string)
7920 ppid -- Parent process ID (number)
7921 pgrp -- Process group ID (number)
7922 sess -- Session ID, i.e. process ID of session leader (number)
7923 ttname -- Controlling tty name (string)
7924 tpgid -- ID of foreground process group on the process's tty (number)
7925 minflt -- number of minor page faults (number)
7926 majflt -- number of major page faults (number)
7927 cminflt -- cumulative number of minor page faults (number)
7928 cmajflt -- cumulative number of major page faults (number)
7929 utime -- user time used by the process, in (current-time) format,
7930 which is a list of integers (HIGH LOW USEC PSEC)
7931 stime -- system time used by the process (current-time)
7932 time -- sum of utime and stime (current-time)
7933 cutime -- user time used by the process and its children (current-time)
7934 cstime -- system time used by the process and its children (current-time)
7935 ctime -- sum of cutime and cstime (current-time)
7936 pri -- priority of the process (number)
7937 nice -- nice value of the process (number)
7938 thcount -- process thread count (number)
7939 start -- time the process started (current-time)
7940 vsize -- virtual memory size of the process in KB's (number)
7941 rss -- resident set size of the process in KB's (number)
7942 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7943 pcpu -- percents of CPU time used by the process (floating-point number)
7944 pmem -- percents of total physical memory used by process's resident set
7945 (floating-point number)
7946 args -- command line which invoked the process (string). */)
7949 return system_process_attributes (pid
);
7953 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7954 Invoke this after init_process_emacs, and after glib and/or GNUstep
7955 futz with the SIGCHLD handler, but before Emacs forks any children.
7956 This function's caller should block SIGCHLD. */
7959 catch_child_signal (void)
7961 struct sigaction action
, old_action
;
7963 emacs_sigaction_init (&action
, deliver_child_signal
);
7964 block_child_signal (&oldset
);
7965 sigaction (SIGCHLD
, &action
, &old_action
);
7966 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7967 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7969 if (old_action
.sa_handler
!= deliver_child_signal
)
7971 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7973 : old_action
.sa_handler
);
7974 unblock_child_signal (&oldset
);
7976 #endif /* subprocesses */
7978 /* Limit the number of open files to the value it had at startup. */
7981 restore_nofile_limit (void)
7983 #ifdef HAVE_SETRLIMIT
7984 if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
7985 setrlimit (RLIMIT_NOFILE
, &nofile_limit
);
7990 /* This is not called "init_process" because that is the name of a
7991 Mach system call, so it would cause problems on Darwin systems. */
7993 init_process_emacs (int sockfd
)
7998 inhibit_sentinels
= 0;
8001 if (! noninteractive
|| initialized
)
8004 #if defined HAVE_GLIB && !defined WINDOWSNT
8005 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8006 this should always fail, but is enough to initialize glib's
8007 private SIGCHLD handler, allowing catch_child_signal to copy
8008 it into lib_child_handler. */
8009 g_source_unref (g_child_watch_source_new (getpid ()));
8011 catch_child_signal ();
8014 #ifdef HAVE_SETRLIMIT
8015 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8016 if (getrlimit (RLIMIT_NOFILE
, &nofile_limit
) != 0)
8017 nofile_limit
.rlim_cur
= 0;
8018 else if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
8020 struct rlimit rlim
= nofile_limit
;
8021 rlim
.rlim_cur
= FD_SETSIZE
;
8022 if (setrlimit (RLIMIT_NOFILE
, &rlim
) != 0)
8023 nofile_limit
.rlim_cur
= 0;
8027 external_sock_fd
= sockfd
;
8028 Lisp_Object sockname
= Qnil
;
8029 # if HAVE_GETSOCKNAME
8032 union u_sockaddr sa
;
8033 socklen_t salen
= sizeof sa
;
8034 if (getsockname (sockfd
, &sa
.sa
, &salen
) == 0)
8035 sockname
= conv_sockaddr_to_lisp (&sa
.sa
, salen
);
8038 Vinternal__daemon_sockname
= sockname
;
8041 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
8043 num_pending_connects
= 0;
8045 process_output_delay_count
= 0;
8046 process_output_skip
= 0;
8048 /* Don't do this, it caused infinite select loops. The display
8049 method should call add_keyboard_wait_descriptor on stdin if it
8052 FD_SET (0, &input_wait_mask
);
8055 Vprocess_alist
= Qnil
;
8056 deleted_pid_list
= Qnil
;
8057 for (i
= 0; i
< FD_SETSIZE
; i
++)
8059 chan_process
[i
] = Qnil
;
8060 proc_buffered_char
[i
] = -1;
8062 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
8063 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
8064 #ifdef DATAGRAM_SOCKETS
8065 memset (datagram_address
, 0, sizeof datagram_address
);
8068 #if defined (DARWIN_OS)
8069 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8070 processes. As such, we only change the default value. */
8073 char const *release
= (STRINGP (Voperating_system_release
)
8074 ? SSDATA (Voperating_system_release
)
8076 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
8077 Vprocess_connection_type
= Qnil
;
8081 #endif /* subprocesses */
8086 syms_of_process (void)
8090 DEFSYM (Qprocessp
, "processp");
8091 DEFSYM (Qrun
, "run");
8092 DEFSYM (Qstop
, "stop");
8093 DEFSYM (Qsignal
, "signal");
8095 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8098 DEFSYM (Qopen
, "open");
8099 DEFSYM (Qclosed
, "closed");
8100 DEFSYM (Qconnect
, "connect");
8101 DEFSYM (Qfailed
, "failed");
8102 DEFSYM (Qlisten
, "listen");
8103 DEFSYM (Qlocal
, "local");
8104 DEFSYM (Qipv4
, "ipv4");
8106 DEFSYM (Qipv6
, "ipv6");
8108 DEFSYM (Qdatagram
, "datagram");
8109 DEFSYM (Qseqpacket
, "seqpacket");
8111 DEFSYM (QCport
, ":port");
8112 DEFSYM (QCspeed
, ":speed");
8113 DEFSYM (QCprocess
, ":process");
8115 DEFSYM (QCbytesize
, ":bytesize");
8116 DEFSYM (QCstopbits
, ":stopbits");
8117 DEFSYM (QCparity
, ":parity");
8118 DEFSYM (Qodd
, "odd");
8119 DEFSYM (Qeven
, "even");
8120 DEFSYM (QCflowcontrol
, ":flowcontrol");
8123 DEFSYM (QCsummary
, ":summary");
8125 DEFSYM (Qreal
, "real");
8126 DEFSYM (Qnetwork
, "network");
8127 DEFSYM (Qserial
, "serial");
8128 DEFSYM (QCbuffer
, ":buffer");
8129 DEFSYM (QChost
, ":host");
8130 DEFSYM (QCservice
, ":service");
8131 DEFSYM (QClocal
, ":local");
8132 DEFSYM (QCremote
, ":remote");
8133 DEFSYM (QCcoding
, ":coding");
8134 DEFSYM (QCserver
, ":server");
8135 DEFSYM (QCnowait
, ":nowait");
8136 DEFSYM (QCsentinel
, ":sentinel");
8137 DEFSYM (QCuse_external_socket
, ":use-external-socket");
8138 DEFSYM (QCtls_parameters
, ":tls-parameters");
8139 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
8140 DEFSYM (QClog
, ":log");
8141 DEFSYM (QCnoquery
, ":noquery");
8142 DEFSYM (QCstop
, ":stop");
8143 DEFSYM (QCplist
, ":plist");
8144 DEFSYM (QCcommand
, ":command");
8145 DEFSYM (QCconnection_type
, ":connection-type");
8146 DEFSYM (QCstderr
, ":stderr");
8147 DEFSYM (Qpty
, "pty");
8148 DEFSYM (Qpipe
, "pipe");
8150 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
8152 staticpro (&Vprocess_alist
);
8153 staticpro (&deleted_pid_list
);
8155 #endif /* subprocesses */
8157 DEFSYM (QCname
, ":name");
8158 DEFSYM (QCtype
, ":type");
8160 DEFSYM (Qeuid
, "euid");
8161 DEFSYM (Qegid
, "egid");
8162 DEFSYM (Quser
, "user");
8163 DEFSYM (Qgroup
, "group");
8164 DEFSYM (Qcomm
, "comm");
8165 DEFSYM (Qstate
, "state");
8166 DEFSYM (Qppid
, "ppid");
8167 DEFSYM (Qpgrp
, "pgrp");
8168 DEFSYM (Qsess
, "sess");
8169 DEFSYM (Qttname
, "ttname");
8170 DEFSYM (Qtpgid
, "tpgid");
8171 DEFSYM (Qminflt
, "minflt");
8172 DEFSYM (Qmajflt
, "majflt");
8173 DEFSYM (Qcminflt
, "cminflt");
8174 DEFSYM (Qcmajflt
, "cmajflt");
8175 DEFSYM (Qutime
, "utime");
8176 DEFSYM (Qstime
, "stime");
8177 DEFSYM (Qtime
, "time");
8178 DEFSYM (Qcutime
, "cutime");
8179 DEFSYM (Qcstime
, "cstime");
8180 DEFSYM (Qctime
, "ctime");
8182 DEFSYM (Qinternal_default_process_sentinel
,
8183 "internal-default-process-sentinel");
8184 DEFSYM (Qinternal_default_process_filter
,
8185 "internal-default-process-filter");
8187 DEFSYM (Qpri
, "pri");
8188 DEFSYM (Qnice
, "nice");
8189 DEFSYM (Qthcount
, "thcount");
8190 DEFSYM (Qstart
, "start");
8191 DEFSYM (Qvsize
, "vsize");
8192 DEFSYM (Qrss
, "rss");
8193 DEFSYM (Qetime
, "etime");
8194 DEFSYM (Qpcpu
, "pcpu");
8195 DEFSYM (Qpmem
, "pmem");
8196 DEFSYM (Qargs
, "args");
8198 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
8199 doc
: /* Non-nil means delete processes immediately when they exit.
8200 A value of nil means don't delete them until `list-processes' is run. */);
8202 delete_exited_processes
= 1;
8205 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
8206 doc
: /* Control type of device used to communicate with subprocesses.
8207 Values are nil to use a pipe, or t or `pty' to use a pty.
8208 The value has no effect if the system has no ptys or if all ptys are busy:
8209 then a pipe is used in any case.
8210 The value takes effect when `start-process' is called. */);
8211 Vprocess_connection_type
= Qt
;
8213 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
8214 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
8215 On some systems, when Emacs reads the output from a subprocess, the output data
8216 is read in very small blocks, potentially resulting in very poor performance.
8217 This behavior can be remedied to some extent by setting this variable to a
8218 non-nil value, as it will automatically delay reading from such processes, to
8219 allow them to produce more output before Emacs tries to read it.
8220 If the value is t, the delay is reset after each write to the process; any other
8221 non-nil value means that the delay is not reset on write.
8222 The variable takes effect when `start-process' is called. */);
8223 Vprocess_adaptive_read_buffering
= Qt
;
8225 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions
,
8226 doc
: /* List of functions to be called for `interrupt-process'.
8227 The arguments of the functions are the same as for `interrupt-process'.
8228 These functions are called in the order of the list, until one of them
8229 returns non-`nil'. */);
8230 Vinterrupt_process_functions
= list1 (Qinternal_default_interrupt_process
);
8232 DEFVAR_LISP ("internal--daemon-sockname", Vinternal__daemon_sockname
,
8233 doc
: /* Name of external socket passed to Emacs, or nil if none. */);
8234 Vinternal__daemon_sockname
= Qnil
;
8236 DEFSYM (Qinternal_default_interrupt_process
,
8237 "internal-default-interrupt-process");
8238 DEFSYM (Qinterrupt_process_functions
, "interrupt-process-functions");
8240 defsubr (&Sprocessp
);
8241 defsubr (&Sget_process
);
8242 defsubr (&Sdelete_process
);
8243 defsubr (&Sprocess_status
);
8244 defsubr (&Sprocess_exit_status
);
8245 defsubr (&Sprocess_id
);
8246 defsubr (&Sprocess_name
);
8247 defsubr (&Sprocess_tty_name
);
8248 defsubr (&Sprocess_command
);
8249 defsubr (&Sset_process_buffer
);
8250 defsubr (&Sprocess_buffer
);
8251 defsubr (&Sprocess_mark
);
8252 defsubr (&Sset_process_filter
);
8253 defsubr (&Sprocess_filter
);
8254 defsubr (&Sset_process_sentinel
);
8255 defsubr (&Sprocess_sentinel
);
8256 defsubr (&Sset_process_thread
);
8257 defsubr (&Sprocess_thread
);
8258 defsubr (&Sset_process_window_size
);
8259 defsubr (&Sset_process_inherit_coding_system_flag
);
8260 defsubr (&Sset_process_query_on_exit_flag
);
8261 defsubr (&Sprocess_query_on_exit_flag
);
8262 defsubr (&Sprocess_contact
);
8263 defsubr (&Sprocess_plist
);
8264 defsubr (&Sset_process_plist
);
8265 defsubr (&Sprocess_list
);
8266 defsubr (&Smake_process
);
8267 defsubr (&Smake_pipe_process
);
8268 defsubr (&Sserial_process_configure
);
8269 defsubr (&Smake_serial_process
);
8270 defsubr (&Sset_network_process_option
);
8271 defsubr (&Smake_network_process
);
8272 defsubr (&Sformat_network_address
);
8273 defsubr (&Snetwork_interface_list
);
8274 defsubr (&Snetwork_interface_info
);
8275 #ifdef DATAGRAM_SOCKETS
8276 defsubr (&Sprocess_datagram_address
);
8277 defsubr (&Sset_process_datagram_address
);
8279 defsubr (&Saccept_process_output
);
8280 defsubr (&Sprocess_send_region
);
8281 defsubr (&Sprocess_send_string
);
8282 defsubr (&Sinternal_default_interrupt_process
);
8283 defsubr (&Sinterrupt_process
);
8284 defsubr (&Skill_process
);
8285 defsubr (&Squit_process
);
8286 defsubr (&Sstop_process
);
8287 defsubr (&Scontinue_process
);
8288 defsubr (&Sprocess_running_child_p
);
8289 defsubr (&Sprocess_send_eof
);
8290 defsubr (&Ssignal_process
);
8291 defsubr (&Swaiting_for_user_input_p
);
8292 defsubr (&Sprocess_type
);
8293 defsubr (&Sinternal_default_process_sentinel
);
8294 defsubr (&Sinternal_default_process_filter
);
8295 defsubr (&Sset_process_coding_system
);
8296 defsubr (&Sprocess_coding_system
);
8297 defsubr (&Sset_process_filter_multibyte
);
8298 defsubr (&Sprocess_filter_multibyte_p
);
8301 Lisp_Object subfeatures
= Qnil
;
8302 const struct socket_options
*sopt
;
8304 #define ADD_SUBFEATURE(key, val) \
8305 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8307 ADD_SUBFEATURE (QCnowait
, Qt
);
8308 #ifdef DATAGRAM_SOCKETS
8309 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8311 #ifdef HAVE_SEQPACKET
8312 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8314 #ifdef HAVE_LOCAL_SOCKETS
8315 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8317 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8319 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8321 #ifdef HAVE_GETSOCKNAME
8322 ADD_SUBFEATURE (QCservice
, Qt
);
8324 ADD_SUBFEATURE (QCserver
, Qt
);
8326 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8327 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8329 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8332 #endif /* subprocesses */
8334 defsubr (&Sget_buffer_process
);
8335 defsubr (&Sprocess_inherit_coding_system_flag
);
8336 defsubr (&Slist_system_processes
);
8337 defsubr (&Sprocess_attributes
);