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 # define SOCK_CLOEXEC 0
168 #ifndef SOCK_NONBLOCK
169 # define SOCK_NONBLOCK 0
172 /* True if ERRNUM represents an error where the system call would
173 block if a blocking variant were used. */
175 would_block (int errnum
)
178 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
181 return errnum
== EAGAIN
;
186 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
189 close_on_exec (int fd
)
192 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
197 # define accept4(sockfd, addr, addrlen, flags) \
198 process_accept4 (sockfd, addr, addrlen, flags)
200 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
202 return close_on_exec (accept (sockfd
, addr
, addrlen
));
206 process_socket (int domain
, int type
, int protocol
)
208 return close_on_exec (socket (domain
, type
, protocol
));
211 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
218 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
219 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
221 /* Number of events of change of status of a process. */
222 static EMACS_INT process_tick
;
223 /* Number of events for which the user or sentinel has been notified. */
224 static EMACS_INT update_tick
;
226 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
227 this system. We need to read full packets, so we need a
228 "non-destructive" select. So we require either native select,
229 or emulation of select using FIONREAD. */
231 #ifndef BROKEN_DATAGRAM_SOCKETS
232 # if defined HAVE_SELECT || defined USABLE_FIONREAD
233 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
234 # define DATAGRAM_SOCKETS
239 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
240 # define HAVE_SEQPACKET
243 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
244 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
245 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
247 /* Number of processes which have a non-zero read_output_delay,
248 and therefore might be delayed for adaptive read buffering. */
250 static int process_output_delay_count
;
252 /* True if any process has non-nil read_output_skip. */
254 static bool process_output_skip
;
256 static void start_process_unwind (Lisp_Object
);
257 static void create_process (Lisp_Object
, char **, Lisp_Object
);
259 static bool keyboard_bit_set (fd_set
*);
261 static void deactivate_process (Lisp_Object
);
262 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
263 static int read_process_output (Lisp_Object
, int);
264 static void create_pty (Lisp_Object
);
265 static void exec_sentinel (Lisp_Object
, Lisp_Object
);
267 /* Number of bits set in connect_wait_mask. */
268 static int num_pending_connects
;
270 /* The largest descriptor currently in use; -1 if none. */
273 /* Set the external socket descriptor for Emacs to use when
274 `make-network-process' is called with a non-nil
275 `:use-external-socket' option. The value should be either -1, or
276 the file descriptor of a socket that is already bound. */
277 static int external_sock_fd
;
279 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
280 static Lisp_Object chan_process
[FD_SETSIZE
];
281 static void wait_for_socket_fds (Lisp_Object
, char const *);
283 /* Alist of elements (NAME . PROCESS). */
284 static Lisp_Object Vprocess_alist
;
286 /* Buffered-ahead input char from process, indexed by channel.
287 -1 means empty (no char is buffered).
288 Used on sys V where the only way to tell if there is any
289 output from the process is to read at least one char.
290 Always -1 on systems that support FIONREAD. */
292 static int proc_buffered_char
[FD_SETSIZE
];
294 /* Table of `struct coding-system' for each process. */
295 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
296 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
298 #ifdef DATAGRAM_SOCKETS
299 /* Table of `partner address' for datagram sockets. */
300 static struct sockaddr_and_len
{
303 } datagram_address
[FD_SETSIZE
];
304 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
305 #define DATAGRAM_CONN_P(proc) \
306 (PROCESSP (proc) && \
307 XPROCESS (proc)->infd >= 0 && \
308 datagram_address[XPROCESS (proc)->infd].sa != 0)
310 #define DATAGRAM_CONN_P(proc) (0)
313 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
314 a `for' loop which iterates over processes from Vprocess_alist. */
316 #define FOR_EACH_PROCESS(list_var, proc_var) \
317 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
319 /* These setters are used only in this file, so they can be private. */
321 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
326 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
331 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
333 p
->decode_coding_system
= val
;
336 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
338 p
->decoding_buf
= val
;
341 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
343 p
->encode_coding_system
= val
;
346 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
348 p
->encoding_buf
= val
;
351 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
353 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
356 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
361 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
366 pset_thread (struct Lisp_Process
*p
, Lisp_Object val
)
371 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
376 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
381 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
383 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
386 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
391 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
396 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
398 p
->write_queue
= val
;
401 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
408 make_lisp_proc (struct Lisp_Process
*p
)
410 return make_lisp_ptr (p
, Lisp_Vectorlike
);
415 /* Read from file descriptor. */
417 /* Write to file descriptor. */
419 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
422 /* This descriptor refers to a process. */
424 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
425 NON_BLOCKING_CONNECT_FD
= 16
428 static struct fd_callback_data
432 /* Flags from enum fd_bits. */
434 /* If this fd is locked to a certain thread, this points to it.
435 Otherwise, this is NULL. If an fd is locked to a thread, then
436 only that thread is permitted to wait on it. */
437 struct thread_state
*thread
;
438 /* If this fd is currently being selected on by a thread, this
439 points to the thread. Otherwise it is NULL. */
440 struct thread_state
*waiting_thread
;
441 } fd_callback_info
[FD_SETSIZE
];
444 /* Add a file descriptor FD to be monitored for when read is possible.
445 When read is possible, call FUNC with argument DATA. */
448 add_read_fd (int fd
, fd_callback func
, void *data
)
450 add_keyboard_wait_descriptor (fd
);
452 fd_callback_info
[fd
].func
= func
;
453 fd_callback_info
[fd
].data
= data
;
457 add_non_keyboard_read_fd (int fd
)
459 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
460 eassert (fd_callback_info
[fd
].func
== NULL
);
462 fd_callback_info
[fd
].flags
&= ~KEYBOARD_FD
;
463 fd_callback_info
[fd
].flags
|= FOR_READ
;
469 add_process_read_fd (int fd
)
471 add_non_keyboard_read_fd (fd
);
472 fd_callback_info
[fd
].flags
|= PROCESS_FD
;
475 /* Stop monitoring file descriptor FD for when read is possible. */
478 delete_read_fd (int fd
)
480 delete_keyboard_wait_descriptor (fd
);
482 if (fd_callback_info
[fd
].flags
== 0)
484 fd_callback_info
[fd
].func
= 0;
485 fd_callback_info
[fd
].data
= 0;
489 /* Add a file descriptor FD to be monitored for when write is possible.
490 When write is possible, call FUNC with argument DATA. */
493 add_write_fd (int fd
, fd_callback func
, void *data
)
495 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
497 fd_callback_info
[fd
].func
= func
;
498 fd_callback_info
[fd
].data
= data
;
499 fd_callback_info
[fd
].flags
|= FOR_WRITE
;
505 add_non_blocking_write_fd (int fd
)
507 eassert (fd
>= 0 && fd
< FD_SETSIZE
);
508 eassert (fd_callback_info
[fd
].func
== NULL
);
510 fd_callback_info
[fd
].flags
|= FOR_WRITE
| NON_BLOCKING_CONNECT_FD
;
513 ++num_pending_connects
;
517 recompute_max_desc (void)
521 for (fd
= max_desc
; fd
>= 0; --fd
)
523 if (fd_callback_info
[fd
].flags
!= 0)
531 /* Stop monitoring file descriptor FD for when write is possible. */
534 delete_write_fd (int fd
)
536 if ((fd_callback_info
[fd
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
538 if (--num_pending_connects
< 0)
541 fd_callback_info
[fd
].flags
&= ~(FOR_WRITE
| NON_BLOCKING_CONNECT_FD
);
542 if (fd_callback_info
[fd
].flags
== 0)
544 fd_callback_info
[fd
].func
= 0;
545 fd_callback_info
[fd
].data
= 0;
548 recompute_max_desc ();
553 compute_input_wait_mask (fd_set
*mask
)
558 for (fd
= 0; fd
<= max_desc
; ++fd
)
560 if (fd_callback_info
[fd
].thread
!= NULL
561 && fd_callback_info
[fd
].thread
!= current_thread
)
563 if (fd_callback_info
[fd
].waiting_thread
!= NULL
564 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
566 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0)
569 fd_callback_info
[fd
].waiting_thread
= current_thread
;
575 compute_non_process_wait_mask (fd_set
*mask
)
580 for (fd
= 0; fd
<= max_desc
; ++fd
)
582 if (fd_callback_info
[fd
].thread
!= NULL
583 && fd_callback_info
[fd
].thread
!= current_thread
)
585 if (fd_callback_info
[fd
].waiting_thread
!= NULL
586 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
588 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
589 && (fd_callback_info
[fd
].flags
& PROCESS_FD
) == 0)
592 fd_callback_info
[fd
].waiting_thread
= current_thread
;
598 compute_non_keyboard_wait_mask (fd_set
*mask
)
603 for (fd
= 0; fd
<= max_desc
; ++fd
)
605 if (fd_callback_info
[fd
].thread
!= NULL
606 && fd_callback_info
[fd
].thread
!= current_thread
)
608 if (fd_callback_info
[fd
].waiting_thread
!= NULL
609 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
611 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
612 && (fd_callback_info
[fd
].flags
& KEYBOARD_FD
) == 0)
615 fd_callback_info
[fd
].waiting_thread
= current_thread
;
621 compute_write_mask (fd_set
*mask
)
626 for (fd
= 0; fd
<= max_desc
; ++fd
)
628 if (fd_callback_info
[fd
].thread
!= NULL
629 && fd_callback_info
[fd
].thread
!= current_thread
)
631 if (fd_callback_info
[fd
].waiting_thread
!= NULL
632 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
634 if ((fd_callback_info
[fd
].flags
& FOR_WRITE
) != 0)
637 fd_callback_info
[fd
].waiting_thread
= current_thread
;
643 clear_waiting_thread_info (void)
647 for (fd
= 0; fd
<= max_desc
; ++fd
)
649 if (fd_callback_info
[fd
].waiting_thread
== current_thread
)
650 fd_callback_info
[fd
].waiting_thread
= NULL
;
655 /* Compute the Lisp form of the process status, p->status, from
656 the numeric status that was returned by `wait'. */
658 static Lisp_Object
status_convert (int);
661 update_status (struct Lisp_Process
*p
)
663 eassert (p
->raw_status_new
);
664 pset_status (p
, status_convert (p
->raw_status
));
665 p
->raw_status_new
= 0;
668 /* Convert a process status word in Unix format to
669 the list that we use internally. */
672 status_convert (int w
)
675 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
676 else if (WIFEXITED (w
))
677 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
678 WCOREDUMP (w
) ? Qt
: Qnil
));
679 else if (WIFSIGNALED (w
))
680 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
681 WCOREDUMP (w
) ? Qt
: Qnil
));
686 /* True if STATUS is that of a process attempting connection. */
689 connecting_status (Lisp_Object status
)
691 return CONSP (status
) && EQ (XCAR (status
), Qconnect
);
694 /* Given a status-list, extract the three pieces of information
695 and store them individually through the three pointers. */
698 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, Lisp_Object
*code
,
703 if (connecting_status (l
))
709 *code
= make_number (0);
718 *coredump
= !NILP (tem
);
722 /* Return a string describing a process status list. */
725 status_message (struct Lisp_Process
*p
)
727 Lisp_Object status
= p
->status
;
728 Lisp_Object symbol
, code
;
732 decode_status (status
, &symbol
, &code
, &coredump
);
734 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
737 synchronize_system_messages_locale ();
738 signame
= strsignal (XFASTINT (code
));
740 string
= build_string ("unknown");
745 string
= build_unibyte_string (signame
);
746 if (! NILP (Vlocale_coding_system
))
747 string
= (code_convert_string_norecord
748 (string
, Vlocale_coding_system
, 0));
749 c1
= STRING_CHAR (SDATA (string
));
752 Faset (string
, make_number (0), make_number (c2
));
754 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
755 return concat2 (string
, suffix
);
757 else if (EQ (symbol
, Qexit
))
760 return build_string (XFASTINT (code
) == 0
762 : "connection broken by remote peer\n");
763 if (XFASTINT (code
) == 0)
764 return build_string ("finished\n");
765 AUTO_STRING (prefix
, "exited abnormally with code ");
766 string
= Fnumber_to_string (code
);
767 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
768 return concat3 (prefix
, string
, suffix
);
770 else if (EQ (symbol
, Qfailed
))
772 AUTO_STRING (format
, "failed with code %s\n");
773 return CALLN (Fformat
, format
, code
);
776 return Fcopy_sequence (Fsymbol_name (symbol
));
779 enum { PTY_NAME_SIZE
= 24 };
781 /* Open an available pty, returning a file descriptor.
782 Store into PTY_NAME the file name of the terminal corresponding to the pty.
783 Return -1 on failure. */
786 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
795 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
796 for (i
= 0; i
< 16; i
++)
799 #ifdef PTY_NAME_SPRINTF
802 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
803 #endif /* no PTY_NAME_SPRINTF */
807 #else /* no PTY_OPEN */
808 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
809 #endif /* no PTY_OPEN */
813 #ifdef PTY_TTY_NAME_SPRINTF
816 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
817 #endif /* no PTY_TTY_NAME_SPRINTF */
819 /* Set FD's close-on-exec flag. This is needed even if
820 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
821 doesn't require support for that combination.
822 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
823 doesn't work if the close-on-exec flag is set (Bug#20555).
824 Multithreaded platforms where posix_openpt ignores
825 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
826 have a race condition between the PTY_OPEN and here. */
827 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
829 /* Check to make certain that both sides are available.
830 This avoids a nasty yet stupid bug in rlogins. */
831 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
840 #endif /* HAVE_PTYS */
844 /* Allocate basically initialized process. */
846 static struct Lisp_Process
*
847 allocate_process (void)
849 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
853 make_process (Lisp_Object name
)
855 struct Lisp_Process
*p
= allocate_process ();
856 /* Initialize Lisp data. Note that allocate_process initializes all
857 Lisp data to nil, so do it only for slots which should not be nil. */
858 pset_status (p
, Qrun
);
859 pset_mark (p
, Fmake_marker ());
860 pset_thread (p
, Fcurrent_thread ());
862 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
863 non-Lisp data, so do it only for slots which should not be zero. */
866 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
870 verify (GNUTLS_STAGE_EMPTY
== 0);
871 eassert (p
->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
872 eassert (NILP (p
->gnutls_boot_parameters
));
875 /* If name is already in use, modify it until it is unused. */
877 Lisp_Object name1
= name
;
878 for (printmax_t i
= 1; ; i
++)
880 Lisp_Object tem
= Fget_process (name1
);
883 char const suffix_fmt
[] = "<%"pMd
">";
884 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
885 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
886 name1
= concat2 (name
, lsuffix
);
890 pset_sentinel (p
, Qinternal_default_process_sentinel
);
891 pset_filter (p
, Qinternal_default_process_filter
);
893 XSETPROCESS (val
, p
);
894 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
899 remove_process (register Lisp_Object proc
)
901 register Lisp_Object pair
;
903 pair
= Frassq (proc
, Vprocess_alist
);
904 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
906 deactivate_process (proc
);
910 update_processes_for_thread_death (Lisp_Object dying_thread
)
914 for (pair
= Vprocess_alist
; !NILP (pair
); pair
= XCDR (pair
))
916 Lisp_Object process
= XCDR (XCAR (pair
));
917 if (EQ (XPROCESS (process
)->thread
, dying_thread
))
919 struct Lisp_Process
*proc
= XPROCESS (process
);
921 pset_thread (proc
, Qnil
);
923 fd_callback_info
[proc
->infd
].thread
= NULL
;
924 if (proc
->outfd
>= 0)
925 fd_callback_info
[proc
->outfd
].thread
= NULL
;
930 #ifdef HAVE_GETADDRINFO_A
932 free_dns_request (Lisp_Object proc
)
934 struct Lisp_Process
*p
= XPROCESS (proc
);
936 if (p
->dns_request
->ar_result
)
937 freeaddrinfo (p
->dns_request
->ar_result
);
938 xfree (p
->dns_request
);
939 p
->dns_request
= NULL
;
944 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
945 doc
: /* Return t if OBJECT is a process. */)
948 return PROCESSP (object
) ? Qt
: Qnil
;
951 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
952 doc
: /* Return the process named NAME, or nil if there is none. */)
953 (register Lisp_Object name
)
958 return Fcdr (Fassoc (name
, Vprocess_alist
, Qnil
));
961 /* This is how commands for the user decode process arguments. It
962 accepts a process, a process name, a buffer, a buffer name, or nil.
963 Buffers denote the first process in the buffer, and nil denotes the
967 get_process (register Lisp_Object name
)
969 register Lisp_Object proc
, obj
;
972 obj
= Fget_process (name
);
974 obj
= Fget_buffer (name
);
976 error ("Process %s does not exist", SDATA (name
));
978 else if (NILP (name
))
979 obj
= Fcurrent_buffer ();
983 /* Now obj should be either a buffer object or a process object. */
986 if (NILP (BVAR (XBUFFER (obj
), name
)))
987 error ("Attempt to get process for a dead buffer");
988 proc
= Fget_buffer_process (obj
);
990 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
1001 /* Fdelete_process promises to immediately forget about the process, but in
1002 reality, Emacs needs to remember those processes until they have been
1003 treated by the SIGCHLD handler and waitpid has been invoked on them;
1004 otherwise they might fill up the kernel's process table.
1006 Some processes created by call-process are also put onto this list.
1008 Members of this list are (process-ID . filename) pairs. The
1009 process-ID is a number; the filename, if a string, is a file that
1010 needs to be removed after the process exits. */
1011 static Lisp_Object deleted_pid_list
;
1014 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
1016 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
1017 /* GC treated elements set to nil. */
1018 Fdelq (Qnil
, deleted_pid_list
));
1022 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
1023 doc
: /* Delete PROCESS: kill it and forget about it immediately.
1024 PROCESS may be a process, a buffer, the name of a process or buffer, or
1025 nil, indicating the current buffer's process. */)
1026 (register Lisp_Object process
)
1028 register struct Lisp_Process
*p
;
1030 process
= get_process (process
);
1031 p
= XPROCESS (process
);
1033 #ifdef HAVE_GETADDRINFO_A
1036 /* Cancel the request. Unless shutting down, wait until
1037 completion. Free the request if completely canceled. */
1039 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
1040 if (!canceled
&& !inhibit_sentinels
)
1042 struct gaicb
const *req
= p
->dns_request
;
1043 while (gai_suspend (&req
, 1, NULL
) != 0)
1048 free_dns_request (process
);
1052 p
->raw_status_new
= 0;
1053 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1055 pset_status (p
, list2 (Qexit
, make_number (0)));
1056 p
->tick
= ++process_tick
;
1057 status_notify (p
, NULL
);
1058 redisplay_preserve_echo_area (13);
1063 record_kill_process (p
, Qnil
);
1067 /* Update P's status, since record_kill_process will make the
1068 SIGCHLD handler update deleted_pid_list, not *P. */
1070 if (p
->raw_status_new
)
1072 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
1073 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
1074 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
1076 p
->tick
= ++process_tick
;
1077 status_notify (p
, NULL
);
1078 redisplay_preserve_echo_area (13);
1081 remove_process (process
);
1085 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
1086 doc
: /* Return the status of PROCESS.
1087 The returned value is one of the following symbols:
1088 run -- for a process that is running.
1089 stop -- for a process stopped but continuable.
1090 exit -- for a process that has exited.
1091 signal -- for a process that has got a fatal signal.
1092 open -- for a network stream connection that is open.
1093 listen -- for a network stream server that is listening.
1094 closed -- for a network stream connection that is closed.
1095 connect -- when waiting for a non-blocking connection to complete.
1096 failed -- when a non-blocking connection has failed.
1097 nil -- if arg is a process name and no such process exists.
1098 PROCESS may be a process, a buffer, the name of a process, or
1099 nil, indicating the current buffer's process. */)
1100 (register Lisp_Object process
)
1102 register struct Lisp_Process
*p
;
1103 register Lisp_Object status
;
1105 if (STRINGP (process
))
1106 process
= Fget_process (process
);
1108 process
= get_process (process
);
1113 p
= XPROCESS (process
);
1114 if (p
->raw_status_new
)
1118 status
= XCAR (status
);
1119 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1121 if (EQ (status
, Qexit
))
1123 else if (EQ (p
->command
, Qt
))
1125 else if (EQ (status
, Qrun
))
1131 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
1133 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
1134 If PROCESS has not yet exited or died, return 0. */)
1135 (register Lisp_Object process
)
1137 CHECK_PROCESS (process
);
1138 if (XPROCESS (process
)->raw_status_new
)
1139 update_status (XPROCESS (process
));
1140 if (CONSP (XPROCESS (process
)->status
))
1141 return XCAR (XCDR (XPROCESS (process
)->status
));
1142 return make_number (0);
1145 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
1146 doc
: /* Return the process id of PROCESS.
1147 This is the pid of the external process which PROCESS uses or talks to.
1148 For a network, serial, and pipe connections, this value is nil. */)
1149 (register Lisp_Object process
)
1153 CHECK_PROCESS (process
);
1154 pid
= XPROCESS (process
)->pid
;
1155 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
1158 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
1159 doc
: /* Return the name of PROCESS, as a string.
1160 This is the name of the program invoked in PROCESS,
1161 possibly modified to make it unique among process names. */)
1162 (register Lisp_Object process
)
1164 CHECK_PROCESS (process
);
1165 return XPROCESS (process
)->name
;
1168 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1169 doc
: /* Return the command that was executed to start PROCESS.
1170 This is a list of strings, the first string being the program executed
1171 and the rest of the strings being the arguments given to it.
1172 For a network or serial or pipe connection, this is nil (process is running)
1173 or t (process is stopped). */)
1174 (register Lisp_Object process
)
1176 CHECK_PROCESS (process
);
1177 return XPROCESS (process
)->command
;
1180 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1181 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1182 This is the terminal that the process itself reads and writes on,
1183 not the name of the pty that Emacs uses to talk with that terminal. */)
1184 (register Lisp_Object process
)
1186 CHECK_PROCESS (process
);
1187 return XPROCESS (process
)->tty_name
;
1190 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1192 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1194 (register Lisp_Object process
, Lisp_Object buffer
)
1196 struct Lisp_Process
*p
;
1198 CHECK_PROCESS (process
);
1200 CHECK_BUFFER (buffer
);
1201 p
= XPROCESS (process
);
1202 pset_buffer (p
, buffer
);
1203 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1204 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1205 setup_process_coding_systems (process
);
1209 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1211 doc
: /* Return the buffer PROCESS is associated with.
1212 The default process filter inserts output from PROCESS into this buffer. */)
1213 (register Lisp_Object process
)
1215 CHECK_PROCESS (process
);
1216 return XPROCESS (process
)->buffer
;
1219 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1221 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1222 (register Lisp_Object process
)
1224 CHECK_PROCESS (process
);
1225 return XPROCESS (process
)->mark
;
1229 set_process_filter_masks (struct Lisp_Process
*p
)
1231 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1232 delete_read_fd (p
->infd
);
1233 else if (EQ (p
->filter
, Qt
)
1234 /* Network or serial process not stopped: */
1235 && !EQ (p
->command
, Qt
))
1236 add_process_read_fd (p
->infd
);
1239 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1241 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1242 A value of t means stop accepting output from the process.
1244 When a process has a non-default filter, its buffer is not used for output.
1245 Instead, each time it does output, the entire string of output is
1246 passed to the filter.
1248 The filter gets two arguments: the process and the string of output.
1249 The string argument is normally a multibyte string, except:
1250 - if the process's input coding system is no-conversion or raw-text,
1251 it is a unibyte string (the non-converted input), or else
1252 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1253 string (the result of converting the decoded input multibyte
1254 string to unibyte with `string-make-unibyte'). */)
1255 (Lisp_Object process
, Lisp_Object filter
)
1257 CHECK_PROCESS (process
);
1258 struct Lisp_Process
*p
= XPROCESS (process
);
1260 /* Don't signal an error if the process's input file descriptor
1261 is closed. This could make debugging Lisp more difficult,
1262 for example when doing something like
1264 (setq process (start-process ...))
1266 (set-process-filter process ...) */
1269 filter
= Qinternal_default_process_filter
;
1271 pset_filter (p
, filter
);
1274 set_process_filter_masks (p
);
1276 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1277 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1278 setup_process_coding_systems (process
);
1282 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1284 doc
: /* Return the filter function of PROCESS.
1285 See `set-process-filter' for more info on filter functions. */)
1286 (register Lisp_Object process
)
1288 CHECK_PROCESS (process
);
1289 return XPROCESS (process
)->filter
;
1292 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1294 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1295 The sentinel is called as a function when the process changes state.
1296 It gets two arguments: the process, and a string describing the change. */)
1297 (register Lisp_Object process
, Lisp_Object sentinel
)
1299 struct Lisp_Process
*p
;
1301 CHECK_PROCESS (process
);
1302 p
= XPROCESS (process
);
1304 if (NILP (sentinel
))
1305 sentinel
= Qinternal_default_process_sentinel
;
1307 pset_sentinel (p
, sentinel
);
1308 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1309 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1313 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1315 doc
: /* Return the sentinel of PROCESS.
1316 See `set-process-sentinel' for more info on sentinels. */)
1317 (register Lisp_Object process
)
1319 CHECK_PROCESS (process
);
1320 return XPROCESS (process
)->sentinel
;
1323 DEFUN ("set-process-thread", Fset_process_thread
, Sset_process_thread
,
1325 doc
: /* Set the locking thread of PROCESS to be THREAD.
1326 If THREAD is nil, the process is unlocked. */)
1327 (Lisp_Object process
, Lisp_Object thread
)
1329 struct Lisp_Process
*proc
;
1330 struct thread_state
*tstate
;
1332 CHECK_PROCESS (process
);
1337 CHECK_THREAD (thread
);
1338 tstate
= XTHREAD (thread
);
1341 proc
= XPROCESS (process
);
1342 pset_thread (proc
, thread
);
1343 if (proc
->infd
>= 0)
1344 fd_callback_info
[proc
->infd
].thread
= tstate
;
1345 if (proc
->outfd
>= 0)
1346 fd_callback_info
[proc
->outfd
].thread
= tstate
;
1351 DEFUN ("process-thread", Fprocess_thread
, Sprocess_thread
,
1353 doc
: /* Ret the locking thread of PROCESS.
1354 If PROCESS is unlocked, this function returns nil. */)
1355 (Lisp_Object process
)
1357 CHECK_PROCESS (process
);
1358 return XPROCESS (process
)->thread
;
1361 DEFUN ("set-process-window-size", Fset_process_window_size
,
1362 Sset_process_window_size
, 3, 3, 0,
1363 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1364 Value is t if PROCESS was successfully told about the window size,
1366 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1368 CHECK_PROCESS (process
);
1370 /* All known platforms store window sizes as 'unsigned short'. */
1371 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1372 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1374 if (NETCONN_P (process
)
1375 || XPROCESS (process
)->infd
< 0
1376 || (set_window_size (XPROCESS (process
)->infd
,
1377 XINT (height
), XINT (width
))
1384 DEFUN ("set-process-inherit-coding-system-flag",
1385 Fset_process_inherit_coding_system_flag
,
1386 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1387 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1388 If the second argument FLAG is non-nil, then the variable
1389 `buffer-file-coding-system' of the buffer associated with PROCESS
1390 will be bound to the value of the coding system used to decode
1393 This is useful when the coding system specified for the process buffer
1394 leaves either the character code conversion or the end-of-line conversion
1395 unspecified, or if the coding system used to decode the process output
1396 is more appropriate for saving the process buffer.
1398 Binding the variable `inherit-process-coding-system' to non-nil before
1399 starting the process is an alternative way of setting the inherit flag
1400 for the process which will run.
1402 This function returns FLAG. */)
1403 (register Lisp_Object process
, Lisp_Object flag
)
1405 CHECK_PROCESS (process
);
1406 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1410 DEFUN ("set-process-query-on-exit-flag",
1411 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1413 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1414 If the second argument FLAG is non-nil, Emacs will query the user before
1415 exiting or killing a buffer if PROCESS is running. This function
1417 (register Lisp_Object process
, Lisp_Object flag
)
1419 CHECK_PROCESS (process
);
1420 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1424 DEFUN ("process-query-on-exit-flag",
1425 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1427 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1428 (register Lisp_Object process
)
1430 CHECK_PROCESS (process
);
1431 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1434 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1436 doc
: /* Return the contact info of PROCESS; t for a real child.
1437 For a network or serial or pipe connection, the value depends on the
1438 optional KEY arg. If KEY is nil, value is a cons cell of the form
1439 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1440 connection; it is t for a pipe connection. If KEY is t, the complete
1441 contact information for the connection is returned, else the specific
1442 value for the keyword KEY is returned. See `make-network-process',
1443 `make-serial-process', or `make-pipe-process' for the list of keywords.
1444 If PROCESS is a non-blocking network process that hasn't been fully
1445 set up yet, this function will block until socket setup has completed. */)
1446 (Lisp_Object process
, Lisp_Object key
)
1448 Lisp_Object contact
;
1450 CHECK_PROCESS (process
);
1451 contact
= XPROCESS (process
)->childp
;
1453 #ifdef DATAGRAM_SOCKETS
1455 if (NETCONN_P (process
))
1456 wait_for_socket_fds (process
, "process-contact");
1458 if (DATAGRAM_CONN_P (process
)
1459 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1460 contact
= Fplist_put (contact
, QCremote
,
1461 Fprocess_datagram_address (process
));
1464 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1467 if (NILP (key
) && NETCONN_P (process
))
1468 return list2 (Fplist_get (contact
, QChost
),
1469 Fplist_get (contact
, QCservice
));
1470 if (NILP (key
) && SERIALCONN_P (process
))
1471 return list2 (Fplist_get (contact
, QCport
),
1472 Fplist_get (contact
, QCspeed
));
1473 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1474 if the pipe process is useful for purposes other than receiving
1476 if (NILP (key
) && PIPECONN_P (process
))
1478 return Fplist_get (contact
, key
);
1481 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1483 doc
: /* Return the plist of PROCESS. */)
1484 (register Lisp_Object process
)
1486 CHECK_PROCESS (process
);
1487 return XPROCESS (process
)->plist
;
1490 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1492 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1493 (Lisp_Object process
, Lisp_Object plist
)
1495 CHECK_PROCESS (process
);
1498 pset_plist (XPROCESS (process
), plist
);
1502 #if 0 /* Turned off because we don't currently record this info
1503 in the process. Perhaps add it. */
1504 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1505 doc
: /* Return the connection type of PROCESS.
1506 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1507 a socket connection. */)
1508 (Lisp_Object process
)
1510 return XPROCESS (process
)->type
;
1514 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1515 doc
: /* Return the connection type of PROCESS.
1516 The value is either the symbol `real', `network', `serial', or `pipe'.
1517 PROCESS may be a process, a buffer, the name of a process or buffer, or
1518 nil, indicating the current buffer's process. */)
1519 (Lisp_Object process
)
1522 proc
= get_process (process
);
1523 return XPROCESS (proc
)->type
;
1526 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1528 doc
: /* Convert network ADDRESS from internal format to a string.
1529 A 4 or 5 element vector represents an IPv4 address (with port number).
1530 An 8 or 9 element vector represents an IPv6 address (with port number).
1531 If optional second argument OMIT-PORT is non-nil, don't include a port
1532 number in the string, even when present in ADDRESS.
1533 Return nil if format of ADDRESS is invalid. */)
1534 (Lisp_Object address
, Lisp_Object omit_port
)
1539 if (STRINGP (address
)) /* AF_LOCAL */
1542 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1544 register struct Lisp_Vector
*p
= XVECTOR (address
);
1545 ptrdiff_t size
= p
->header
.size
;
1546 Lisp_Object args
[10];
1550 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1552 format
= "%d.%d.%d.%d";
1557 format
= "%d.%d.%d.%d:%d";
1560 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1562 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1567 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1573 AUTO_STRING (format_obj
, format
);
1574 args
[0] = format_obj
;
1576 for (i
= 0; i
< nargs
; i
++)
1578 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1581 if (nargs
<= 5 /* IPv4 */
1582 && i
< 4 /* host, not port */
1583 && XINT (p
->contents
[i
]) > 255)
1586 args
[i
+ 1] = p
->contents
[i
];
1589 return Fformat (nargs
+ 1, args
);
1592 if (CONSP (address
))
1594 AUTO_STRING (format
, "<Family %d>");
1595 return CALLN (Fformat
, format
, Fcar (address
));
1601 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1602 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1605 return Fmapcar (Qcdr
, Vprocess_alist
);
1608 /* Starting asynchronous inferior processes. */
1610 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1611 doc
: /* Start a program in a subprocess. Return the process object for it.
1613 This is similar to `start-process', but arguments are specified as
1614 keyword/argument pairs. The following arguments are defined:
1616 :name NAME -- NAME is name for process. It is modified if necessary
1619 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1620 with the process. Process output goes at end of that buffer, unless
1621 you specify a filter function to handle the output. BUFFER may be
1622 also nil, meaning that this process is not associated with any buffer.
1624 :command COMMAND -- COMMAND is a list starting with the program file
1625 name, followed by strings to give to the program as arguments.
1627 :coding CODING -- If CODING is a symbol, it specifies the coding
1628 system used for both reading and writing for this process. If CODING
1629 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1630 ENCODING is used for writing.
1632 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1633 the process is running. If BOOL is not given, query before exiting.
1635 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1636 In the stopped state, a process does not accept incoming data, but you
1637 can send outgoing data. The stopped state is cleared by
1638 `continue-process' and set by `stop-process'.
1640 :connection-type TYPE -- TYPE is control type of device used to
1641 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1642 to use a pty, or nil to use the default specified through
1643 `process-connection-type'.
1645 :filter FILTER -- Install FILTER as the process filter.
1647 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1649 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1650 to the standard error of subprocess. Specifying this implies
1651 `:connection-type' is set to `pipe'.
1653 usage: (make-process &rest ARGS) */)
1654 (ptrdiff_t nargs
, Lisp_Object
*args
)
1656 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1657 Lisp_Object xstderr
, stderrproc
;
1658 ptrdiff_t count
= SPECPDL_INDEX ();
1663 /* Save arguments for process-contact and clone-process. */
1664 contact
= Flist (nargs
, args
);
1666 buffer
= Fplist_get (contact
, QCbuffer
);
1668 buffer
= Fget_buffer_create (buffer
);
1670 /* Make sure that the child will be able to chdir to the current
1671 buffer's current directory, or its unhandled equivalent. We
1672 can't just have the child check for an error when it does the
1673 chdir, since it's in a vfork. */
1674 current_dir
= encode_current_directory ();
1676 name
= Fplist_get (contact
, QCname
);
1677 CHECK_STRING (name
);
1679 command
= Fplist_get (contact
, QCcommand
);
1680 if (CONSP (command
))
1681 program
= XCAR (command
);
1685 if (!NILP (program
))
1686 CHECK_STRING (program
);
1688 bool query_on_exit
= NILP (Fplist_get (contact
, QCnoquery
));
1691 xstderr
= Fplist_get (contact
, QCstderr
);
1692 if (PROCESSP (xstderr
))
1694 if (!PIPECONN_P (xstderr
))
1695 error ("Process is not a pipe process");
1696 stderrproc
= xstderr
;
1698 else if (!NILP (xstderr
))
1700 CHECK_STRING (program
);
1701 stderrproc
= CALLN (Fmake_pipe_process
,
1703 concat2 (name
, build_string (" stderr")),
1705 Fget_buffer_create (xstderr
),
1707 query_on_exit
? Qnil
: Qt
);
1710 proc
= make_process (name
);
1711 record_unwind_protect (start_process_unwind
, proc
);
1713 pset_childp (XPROCESS (proc
), Qt
);
1714 eassert (NILP (XPROCESS (proc
)->plist
));
1715 pset_type (XPROCESS (proc
), Qreal
);
1716 pset_buffer (XPROCESS (proc
), buffer
);
1717 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1718 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1719 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1722 XPROCESS (proc
)->kill_without_query
= 1;
1723 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1724 pset_command (XPROCESS (proc
), Qt
);
1726 tem
= Fplist_get (contact
, QCconnection_type
);
1728 XPROCESS (proc
)->pty_flag
= true;
1729 else if (EQ (tem
, Qpipe
))
1730 XPROCESS (proc
)->pty_flag
= false;
1731 else if (NILP (tem
))
1732 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1734 report_file_error ("Unknown connection type", tem
);
1736 if (!NILP (stderrproc
))
1738 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1740 XPROCESS (proc
)->pty_flag
= false;
1744 /* AKA GNUTLS_INITSTAGE(proc). */
1745 verify (GNUTLS_STAGE_EMPTY
== 0);
1746 eassert (XPROCESS (proc
)->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
1747 eassert (NILP (XPROCESS (proc
)->gnutls_cred_type
));
1750 XPROCESS (proc
)->adaptive_read_buffering
1751 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1752 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1754 /* Make the process marker point into the process buffer (if any). */
1755 if (BUFFERP (buffer
))
1756 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1757 BUF_ZV (XBUFFER (buffer
)),
1758 BUF_ZV_BYTE (XBUFFER (buffer
)));
1763 /* Decide coding systems for communicating with the process. Here
1764 we don't setup the structure coding_system nor pay attention to
1765 unibyte mode. They are done in create_process. */
1767 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1768 Lisp_Object coding_systems
= Qt
;
1769 Lisp_Object val
, *args2
;
1771 tem
= Fplist_get (contact
, QCcoding
);
1779 val
= Vcoding_system_for_read
;
1782 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1784 SAFE_ALLOCA_LISP (args2
, nargs2
);
1786 args2
[i
++] = Qstart_process
;
1788 args2
[i
++] = buffer
;
1789 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1790 args2
[i
++] = XCAR (tem2
);
1791 if (!NILP (program
))
1792 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1793 if (CONSP (coding_systems
))
1794 val
= XCAR (coding_systems
);
1795 else if (CONSP (Vdefault_process_coding_system
))
1796 val
= XCAR (Vdefault_process_coding_system
);
1798 pset_decode_coding_system (XPROCESS (proc
), val
);
1807 val
= Vcoding_system_for_write
;
1810 if (EQ (coding_systems
, Qt
))
1812 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1814 SAFE_ALLOCA_LISP (args2
, nargs2
);
1816 args2
[i
++] = Qstart_process
;
1818 args2
[i
++] = buffer
;
1819 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1820 args2
[i
++] = XCAR (tem2
);
1821 if (!NILP (program
))
1822 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1824 if (CONSP (coding_systems
))
1825 val
= XCDR (coding_systems
);
1826 else if (CONSP (Vdefault_process_coding_system
))
1827 val
= XCDR (Vdefault_process_coding_system
);
1829 pset_encode_coding_system (XPROCESS (proc
), val
);
1830 /* Note: At this moment, the above coding system may leave
1831 text-conversion or eol-conversion unspecified. They will be
1832 decided after we read output from the process and decode it by
1833 some coding system, or just before we actually send a text to
1838 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1839 eassert (XPROCESS (proc
)->decoding_carryover
== 0);
1840 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1842 XPROCESS (proc
)->inherit_coding_system_flag
1843 = !(NILP (buffer
) || !inherit_process_coding_system
);
1845 if (!NILP (program
))
1847 Lisp_Object program_args
= XCDR (command
);
1849 /* If program file name is not absolute, search our path for it.
1850 Put the name we will really use in TEM. */
1851 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1852 && !(SCHARS (program
) > 1
1853 && IS_DEVICE_SEP (SREF (program
, 1))))
1856 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1857 make_number (X_OK
), false);
1859 report_file_error ("Searching for program", program
);
1860 tem
= Fexpand_file_name (tem
, Qnil
);
1864 if (!NILP (Ffile_directory_p (program
)))
1865 error ("Specified program for new process is a directory");
1869 /* Remove "/:" from TEM. */
1870 tem
= remove_slash_colon (tem
);
1872 Lisp_Object arg_encoding
= Qnil
;
1874 /* Encode the file name and put it in NEW_ARGV.
1875 That's where the child will use it to execute the program. */
1876 tem
= list1 (ENCODE_FILE (tem
));
1877 ptrdiff_t new_argc
= 1;
1879 /* Here we encode arguments by the coding system used for sending
1880 data to the process. We don't support using different coding
1881 systems for encoding arguments and for encoding data sent to the
1884 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1886 Lisp_Object arg
= XCAR (tem2
);
1888 if (STRING_MULTIBYTE (arg
))
1890 if (NILP (arg_encoding
))
1891 arg_encoding
= (complement_process_encoding_system
1892 (XPROCESS (proc
)->encode_coding_system
));
1893 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1895 tem
= Fcons (arg
, tem
);
1899 /* Now that everything is encoded we can collect the strings into
1902 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1903 new_argv
[new_argc
] = 0;
1905 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1907 new_argv
[i
] = SSDATA (XCAR (tem
));
1911 create_process (proc
, new_argv
, current_dir
);
1917 return unbind_to (count
, proc
);
1920 /* If PROC doesn't have its pid set, then an error was signaled and
1921 the process wasn't started successfully, so remove it. */
1923 start_process_unwind (Lisp_Object proc
)
1925 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1926 remove_process (proc
);
1929 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1932 close_process_fd (int *fd_addr
)
1942 /* Indexes of file descriptors in open_fds. */
1945 /* The pipe from Emacs to its subprocess. */
1947 WRITE_TO_SUBPROCESS
,
1949 /* The main pipe from the subprocess to Emacs. */
1950 READ_FROM_SUBPROCESS
,
1953 /* The pipe from the subprocess to Emacs that is closed when the
1954 subprocess execs. */
1955 READ_FROM_EXEC_MONITOR
,
1959 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1962 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1964 struct Lisp_Process
*p
= XPROCESS (process
);
1965 int inchannel
, outchannel
;
1968 int forkin
, forkout
, forkerr
= -1;
1970 char pty_name
[PTY_NAME_SIZE
];
1971 Lisp_Object lisp_pty_name
= Qnil
;
1974 inchannel
= outchannel
= -1;
1977 outchannel
= inchannel
= allocate_pty (pty_name
);
1981 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1982 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1983 /* On most USG systems it does not work to open the pty's tty here,
1984 then close it and reopen it in the child. */
1985 /* Don't let this terminal become our controlling terminal
1986 (in case we don't have one). */
1987 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1989 report_file_error ("Opening pty", Qnil
);
1990 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1992 forkin
= forkout
= -1;
1993 #endif /* not USG, or USG_SUBTTY_WORKS */
1995 lisp_pty_name
= build_string (pty_name
);
1999 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2000 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2001 report_file_error ("Creating pipe", Qnil
);
2002 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
2003 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2004 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2005 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
2007 if (!NILP (p
->stderrproc
))
2009 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2011 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
2013 /* Close unnecessary file descriptors. */
2014 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
2015 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
2020 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
2021 report_file_error ("Creating pipe", Qnil
);
2024 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2025 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2027 /* Record this as an active process, with its channels. */
2028 chan_process
[inchannel
] = process
;
2029 p
->infd
= inchannel
;
2030 p
->outfd
= outchannel
;
2032 /* Previously we recorded the tty descriptor used in the subprocess.
2033 It was only used for getting the foreground tty process, so now
2034 we just reopen the device (see emacs_get_tty_pgrp) as this is
2035 more portable (see USG_SUBTTY_WORKS above). */
2037 p
->pty_flag
= pty_flag
;
2038 pset_status (p
, Qrun
);
2040 if (!EQ (p
->command
, Qt
))
2041 add_process_read_fd (inchannel
);
2043 /* This may signal an error. */
2044 setup_process_coding_systems (process
);
2047 block_child_signal (&oldset
);
2050 /* vfork, and prevent local vars from being clobbered by the vfork. */
2051 Lisp_Object
volatile current_dir_volatile
= current_dir
;
2052 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
2053 char **volatile new_argv_volatile
= new_argv
;
2054 int volatile forkin_volatile
= forkin
;
2055 int volatile forkout_volatile
= forkout
;
2056 int volatile forkerr_volatile
= forkerr
;
2057 struct Lisp_Process
*p_volatile
= p
;
2060 /* Darwin doesn't let us run setsid after a vfork, so use fork when
2061 necessary. Also, reset SIGCHLD handling after a vfork, as
2062 apparently macOS can mistakenly deliver SIGCHLD to the child. */
2069 signal (SIGCHLD
, SIG_DFL
);
2075 current_dir
= current_dir_volatile
;
2076 lisp_pty_name
= lisp_pty_name_volatile
;
2077 new_argv
= new_argv_volatile
;
2078 forkin
= forkin_volatile
;
2079 forkout
= forkout_volatile
;
2080 forkerr
= forkerr_volatile
;
2083 pty_flag
= p
->pty_flag
;
2086 #endif /* not WINDOWSNT */
2088 /* Make the pty be the controlling terminal of the process. */
2090 /* First, disconnect its current controlling terminal.
2091 Do this even if !PTY_FLAG; see Bug#30762. */
2093 /* Make the pty's terminal the controlling terminal. */
2094 if (pty_flag
&& forkin
>= 0)
2097 /* We ignore the return value
2098 because faith@cs.unc.edu says that is necessary on Linux. */
2099 ioctl (forkin
, TIOCSCTTY
, 0);
2102 #if defined (LDISC1)
2103 if (pty_flag
&& forkin
>= 0)
2106 tcgetattr (forkin
, &t
);
2108 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
2109 emacs_perror ("create_process/tcsetattr LDISC1");
2112 #if defined (NTTYDISC) && defined (TIOCSETD)
2113 if (pty_flag
&& forkin
>= 0)
2115 /* Use new line discipline. */
2116 int ldisc
= NTTYDISC
;
2117 ioctl (forkin
, TIOCSETD
, &ldisc
);
2122 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2123 can do TIOCSPGRP only to the process's controlling tty. */
2126 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2127 I can't test it since I don't have 4.3. */
2128 int j
= emacs_open (DEV_TTY
, O_RDWR
, 0);
2131 ioctl (j
, TIOCNOTTY
, 0);
2135 #endif /* TIOCNOTTY */
2137 #if !defined (DONT_REOPEN_PTY)
2138 /*** There is a suggestion that this ought to be a
2139 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2140 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2141 that system does seem to need this code, even though
2142 both TIOCSCTTY is defined. */
2143 /* Now close the pty (if we had it open) and reopen it.
2144 This makes the pty the controlling terminal of the subprocess. */
2148 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2151 emacs_close (forkin
);
2152 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
2156 emacs_perror (SSDATA (lisp_pty_name
));
2157 _exit (EXIT_CANCELED
);
2161 #endif /* not DONT_REOPEN_PTY */
2163 #ifdef SETUP_SLAVE_PTY
2168 #endif /* SETUP_SLAVE_PTY */
2169 #endif /* HAVE_PTYS */
2171 signal (SIGINT
, SIG_DFL
);
2172 signal (SIGQUIT
, SIG_DFL
);
2174 signal (SIGPROF
, SIG_DFL
);
2177 /* Emacs ignores SIGPIPE, but the child should not. */
2178 signal (SIGPIPE
, SIG_DFL
);
2180 /* Stop blocking SIGCHLD in the child. */
2181 unblock_child_signal (&oldset
);
2184 child_setup_tty (forkout
);
2189 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
2190 #else /* not WINDOWSNT */
2191 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
2192 #endif /* not WINDOWSNT */
2195 /* Back in the parent process. */
2197 vfork_errno
= errno
;
2202 /* Stop blocking in the parent. */
2203 unblock_child_signal (&oldset
);
2207 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2210 /* vfork succeeded. */
2212 /* Close the pipe ends that the child uses, or the child's pty. */
2213 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2214 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2217 register_child (pid
, inchannel
);
2218 #endif /* WINDOWSNT */
2220 pset_tty_name (p
, lisp_pty_name
);
2223 /* Wait for child_setup to complete in case that vfork is
2224 actually defined as fork. The descriptor
2225 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2226 of a pipe is closed at the child side either by close-on-exec
2227 on successful execve or the _exit call in child_setup. */
2231 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2232 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2233 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2236 if (!NILP (p
->stderrproc
))
2238 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2239 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2245 create_pty (Lisp_Object process
)
2247 struct Lisp_Process
*p
= XPROCESS (process
);
2248 char pty_name
[PTY_NAME_SIZE
];
2249 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2253 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2254 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2255 /* On most USG systems it does not work to open the pty's tty here,
2256 then close it and reopen it in the child. */
2257 /* Don't let this terminal become our controlling terminal
2258 (in case we don't have one). */
2259 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2261 report_file_error ("Opening pty", Qnil
);
2262 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2263 #if defined (DONT_REOPEN_PTY)
2264 /* In the case that vfork is defined as fork, the parent process
2265 (Emacs) may send some data before the child process completes
2266 tty options setup. So we setup tty before forking. */
2267 child_setup_tty (forkout
);
2268 #endif /* DONT_REOPEN_PTY */
2269 #endif /* not USG, or USG_SUBTTY_WORKS */
2271 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2273 /* Record this as an active process, with its channels.
2274 As a result, child_setup will close Emacs's side of the pipes. */
2275 chan_process
[pty_fd
] = process
;
2279 /* Previously we recorded the tty descriptor used in the subprocess.
2280 It was only used for getting the foreground tty process, so now
2281 we just reopen the device (see emacs_get_tty_pgrp) as this is
2282 more portable (see USG_SUBTTY_WORKS above). */
2285 pset_status (p
, Qrun
);
2286 setup_process_coding_systems (process
);
2288 add_process_read_fd (pty_fd
);
2290 pset_tty_name (p
, build_string (pty_name
));
2296 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2298 doc
: /* Create and return a bidirectional pipe process.
2300 In Emacs, pipes are represented by process objects, so input and
2301 output work as for subprocesses, and `delete-process' closes a pipe.
2302 However, a pipe process has no process id, it cannot be signaled,
2303 and the status codes are different from normal processes.
2305 Arguments are specified as keyword/argument pairs. The following
2306 arguments are defined:
2308 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2310 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2311 with the process. Process output goes at the end of that buffer,
2312 unless you specify a filter function to handle the output. If BUFFER
2313 is not given, the value of NAME is used.
2315 :coding CODING -- If CODING is a symbol, it specifies the coding
2316 system used for both reading and writing for this process. If CODING
2317 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2318 ENCODING is used for writing.
2320 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2321 the process is running. If BOOL is not given, query before exiting.
2323 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2324 In the stopped state, a pipe process does not accept incoming data,
2325 but you can send outgoing data. The stopped state is cleared by
2326 `continue-process' and set by `stop-process'.
2328 :filter FILTER -- Install FILTER as the process filter.
2330 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2332 usage: (make-pipe-process &rest ARGS) */)
2333 (ptrdiff_t nargs
, Lisp_Object
*args
)
2335 Lisp_Object proc
, contact
;
2336 struct Lisp_Process
*p
;
2337 Lisp_Object name
, buffer
;
2339 ptrdiff_t specpdl_count
;
2340 int inchannel
, outchannel
;
2345 contact
= Flist (nargs
, args
);
2347 name
= Fplist_get (contact
, QCname
);
2348 CHECK_STRING (name
);
2349 proc
= make_process (name
);
2350 specpdl_count
= SPECPDL_INDEX ();
2351 record_unwind_protect (remove_process
, proc
);
2352 p
= XPROCESS (proc
);
2354 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2355 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2356 report_file_error ("Creating pipe", Qnil
);
2357 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2358 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2360 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2361 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2364 register_aux_fd (inchannel
);
2367 /* Record this as an active process, with its channels. */
2368 chan_process
[inchannel
] = proc
;
2369 p
->infd
= inchannel
;
2370 p
->outfd
= outchannel
;
2372 if (inchannel
> max_desc
)
2373 max_desc
= inchannel
;
2375 buffer
= Fplist_get (contact
, QCbuffer
);
2378 buffer
= Fget_buffer_create (buffer
);
2379 pset_buffer (p
, buffer
);
2381 pset_childp (p
, contact
);
2382 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2383 pset_type (p
, Qpipe
);
2384 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2385 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2386 eassert (NILP (p
->log
));
2387 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2388 p
->kill_without_query
= 1;
2389 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2390 pset_command (p
, Qt
);
2391 eassert (! p
->pty_flag
);
2393 if (!EQ (p
->command
, Qt
))
2394 add_process_read_fd (inchannel
);
2395 p
->adaptive_read_buffering
2396 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2397 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2399 /* Make the process marker point into the process buffer (if any). */
2400 if (BUFFERP (buffer
))
2401 set_marker_both (p
->mark
, buffer
,
2402 BUF_ZV (XBUFFER (buffer
)),
2403 BUF_ZV_BYTE (XBUFFER (buffer
)));
2406 /* Setup coding systems for communicating with the network stream. */
2408 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2409 Lisp_Object coding_systems
= Qt
;
2412 tem
= Fplist_get (contact
, QCcoding
);
2420 else if (!NILP (Vcoding_system_for_read
))
2421 val
= Vcoding_system_for_read
;
2422 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2423 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2424 /* We dare not decode end-of-line format by setting VAL to
2425 Qraw_text, because the existing Emacs Lisp libraries
2426 assume that they receive bare code including a sequence of
2431 if (CONSP (coding_systems
))
2432 val
= XCAR (coding_systems
);
2433 else if (CONSP (Vdefault_process_coding_system
))
2434 val
= XCAR (Vdefault_process_coding_system
);
2438 pset_decode_coding_system (p
, val
);
2446 else if (!NILP (Vcoding_system_for_write
))
2447 val
= Vcoding_system_for_write
;
2448 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2452 if (CONSP (coding_systems
))
2453 val
= XCDR (coding_systems
);
2454 else if (CONSP (Vdefault_process_coding_system
))
2455 val
= XCDR (Vdefault_process_coding_system
);
2459 pset_encode_coding_system (p
, val
);
2461 /* This may signal an error. */
2462 setup_process_coding_systems (proc
);
2464 pset_decoding_buf (p
, empty_unibyte_string
);
2465 eassert (p
->decoding_carryover
== 0);
2466 pset_encoding_buf (p
, empty_unibyte_string
);
2468 specpdl_ptr
= specpdl
+ specpdl_count
;
2474 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2475 The address family of sa is not included in the result. */
2478 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2480 Lisp_Object address
;
2483 struct Lisp_Vector
*p
;
2485 /* Workaround for a bug in getsockname on BSD: Names bound to
2486 sockets in the UNIX domain are inaccessible; getsockname returns
2487 a zero length name. */
2488 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2489 return empty_unibyte_string
;
2491 switch (sa
->sa_family
)
2495 DECLARE_POINTER_ALIAS (sin
, struct sockaddr_in
, sa
);
2496 len
= sizeof (sin
->sin_addr
) + 1;
2497 address
= Fmake_vector (make_number (len
), Qnil
);
2498 p
= XVECTOR (address
);
2499 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2500 cp
= (unsigned char *) &sin
->sin_addr
;
2506 DECLARE_POINTER_ALIAS (sin6
, struct sockaddr_in6
, sa
);
2507 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &sin6
->sin6_addr
);
2508 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2509 address
= Fmake_vector (make_number (len
), Qnil
);
2510 p
= XVECTOR (address
);
2511 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2512 for (i
= 0; i
< len
; i
++)
2513 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2517 #ifdef HAVE_LOCAL_SOCKETS
2520 DECLARE_POINTER_ALIAS (sockun
, struct sockaddr_un
, sa
);
2521 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2522 /* If the first byte is NUL, the name is a Linux abstract
2523 socket name, and the name can contain embedded NULs. If
2524 it's not, we have a NUL-terminated string. Be careful not
2525 to walk past the end of the object looking for the name
2526 terminator, however. */
2527 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2529 const char *terminator
2530 = memchr (sockun
->sun_path
, '\0', name_length
);
2533 name_length
= terminator
- (const char *) sockun
->sun_path
;
2536 return make_unibyte_string (sockun
->sun_path
, name_length
);
2540 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2541 address
= Fcons (make_number (sa
->sa_family
),
2542 Fmake_vector (make_number (len
), Qnil
));
2543 p
= XVECTOR (XCDR (address
));
2544 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2550 p
->contents
[i
++] = make_number (*cp
++);
2555 /* Convert an internal struct addrinfo to a Lisp object. */
2558 conv_addrinfo_to_lisp (struct addrinfo
*res
)
2560 Lisp_Object protocol
= make_number (res
->ai_protocol
);
2561 eassert (XINT (protocol
) == res
->ai_protocol
);
2562 return Fcons (protocol
, conv_sockaddr_to_lisp (res
->ai_addr
, res
->ai_addrlen
));
2566 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2569 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2571 struct Lisp_Vector
*p
;
2573 if (VECTORP (address
))
2575 p
= XVECTOR (address
);
2576 if (p
->header
.size
== 5)
2579 return sizeof (struct sockaddr_in
);
2582 else if (p
->header
.size
== 9)
2584 *familyp
= AF_INET6
;
2585 return sizeof (struct sockaddr_in6
);
2589 #ifdef HAVE_LOCAL_SOCKETS
2590 else if (STRINGP (address
))
2592 *familyp
= AF_LOCAL
;
2593 return sizeof (struct sockaddr_un
);
2596 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2597 && VECTORP (XCDR (address
)))
2599 struct sockaddr
*sa
;
2600 p
= XVECTOR (XCDR (address
));
2601 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2603 *familyp
= XINT (XCAR (address
));
2604 return p
->header
.size
+ sizeof (sa
->sa_family
);
2609 /* Convert an address object (vector or string) to an internal sockaddr.
2611 The address format has been basically validated by
2612 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2613 it could have come from user data. So if FAMILY is not valid,
2614 we return after zeroing *SA. */
2617 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2619 register struct Lisp_Vector
*p
;
2620 register unsigned char *cp
= NULL
;
2624 memset (sa
, 0, len
);
2626 if (VECTORP (address
))
2628 p
= XVECTOR (address
);
2629 if (family
== AF_INET
)
2631 DECLARE_POINTER_ALIAS (sin
, struct sockaddr_in
, sa
);
2632 len
= sizeof (sin
->sin_addr
) + 1;
2633 hostport
= XINT (p
->contents
[--len
]);
2634 sin
->sin_port
= htons (hostport
);
2635 cp
= (unsigned char *)&sin
->sin_addr
;
2636 sa
->sa_family
= family
;
2639 else if (family
== AF_INET6
)
2641 DECLARE_POINTER_ALIAS (sin6
, struct sockaddr_in6
, sa
);
2642 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &sin6
->sin6_addr
);
2643 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2644 hostport
= XINT (p
->contents
[--len
]);
2645 sin6
->sin6_port
= htons (hostport
);
2646 for (i
= 0; i
< len
; i
++)
2647 if (INTEGERP (p
->contents
[i
]))
2649 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2652 sa
->sa_family
= family
;
2659 else if (STRINGP (address
))
2661 #ifdef HAVE_LOCAL_SOCKETS
2662 if (family
== AF_LOCAL
)
2664 DECLARE_POINTER_ALIAS (sockun
, struct sockaddr_un
, sa
);
2665 cp
= SDATA (address
);
2666 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2667 sockun
->sun_path
[i
] = *cp
++;
2668 sa
->sa_family
= family
;
2675 p
= XVECTOR (XCDR (address
));
2676 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2679 for (i
= 0; i
< len
; i
++)
2680 if (INTEGERP (p
->contents
[i
]))
2681 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2684 #ifdef DATAGRAM_SOCKETS
2685 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2687 doc
: /* Get the current datagram address associated with PROCESS.
2688 If PROCESS is a non-blocking network process that hasn't been fully
2689 set up yet, this function will block until socket setup has completed. */)
2690 (Lisp_Object process
)
2694 CHECK_PROCESS (process
);
2696 if (NETCONN_P (process
))
2697 wait_for_socket_fds (process
, "process-datagram-address");
2699 if (!DATAGRAM_CONN_P (process
))
2702 channel
= XPROCESS (process
)->infd
;
2703 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2704 datagram_address
[channel
].len
);
2707 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2709 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2710 Return nil upon error setting address, ADDRESS otherwise.
2712 If PROCESS is a non-blocking network process that hasn't been fully
2713 set up yet, this function will block until socket setup has completed. */)
2714 (Lisp_Object process
, Lisp_Object address
)
2720 CHECK_PROCESS (process
);
2722 if (NETCONN_P (process
))
2723 wait_for_socket_fds (process
, "set-process-datagram-address");
2725 if (!DATAGRAM_CONN_P (process
))
2728 channel
= XPROCESS (process
)->infd
;
2730 len
= get_lisp_to_sockaddr_size (address
, &family
);
2731 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2733 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2739 static const struct socket_options
{
2740 /* The name of this option. Should be lowercase version of option
2741 name without SO_ prefix. */
2743 /* Option level SOL_... */
2745 /* Option number SO_... */
2747 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2748 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2749 } socket_options
[] =
2751 #ifdef SO_BINDTODEVICE
2752 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2755 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2758 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2761 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2764 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2767 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2770 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2773 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2775 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2778 /* Set option OPT to value VAL on socket S.
2780 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2781 Signals an error if setting a known option fails.
2785 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2788 const struct socket_options
*sopt
;
2793 name
= SSDATA (SYMBOL_NAME (opt
));
2794 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2795 if (strcmp (name
, sopt
->name
) == 0)
2798 switch (sopt
->opttype
)
2803 optval
= NILP (val
) ? 0 : 1;
2804 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2805 &optval
, sizeof (optval
));
2812 if (TYPE_RANGED_INTEGERP (int, val
))
2813 optval
= XINT (val
);
2815 error ("Bad option value for %s", name
);
2816 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2817 &optval
, sizeof (optval
));
2821 #ifdef SO_BINDTODEVICE
2824 char devname
[IFNAMSIZ
+ 1];
2826 /* This is broken, at least in the Linux 2.4 kernel.
2827 To unbind, the arg must be a zero integer, not the empty string.
2828 This should work on all systems. KFS. 2003-09-23. */
2829 memset (devname
, 0, sizeof devname
);
2832 char *arg
= SSDATA (val
);
2833 int len
= min (strlen (arg
), IFNAMSIZ
);
2834 memcpy (devname
, arg
, len
);
2836 else if (!NILP (val
))
2837 error ("Bad option value for %s", name
);
2838 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2847 struct linger linger
;
2850 linger
.l_linger
= 0;
2851 if (TYPE_RANGED_INTEGERP (int, val
))
2852 linger
.l_linger
= XINT (val
);
2854 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2855 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2856 &linger
, sizeof (linger
));
2867 int setsockopt_errno
= errno
;
2868 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2872 return (1 << sopt
->optbit
);
2876 DEFUN ("set-network-process-option",
2877 Fset_network_process_option
, Sset_network_process_option
,
2879 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2880 See `make-network-process' for a list of options and values.
2881 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2882 OPTION is not a supported option, return nil instead; otherwise return t.
2884 If PROCESS is a non-blocking network process that hasn't been fully
2885 set up yet, this function will block until socket setup has completed. */)
2886 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2889 struct Lisp_Process
*p
;
2891 CHECK_PROCESS (process
);
2892 p
= XPROCESS (process
);
2893 if (!NETCONN1_P (p
))
2894 error ("Process is not a network process");
2896 wait_for_socket_fds (process
, "set-network-process-option");
2900 error ("Process is not running");
2902 if (set_socket_option (s
, option
, value
))
2904 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2908 if (NILP (no_error
))
2909 error ("Unknown or unsupported option");
2915 DEFUN ("serial-process-configure",
2916 Fserial_process_configure
,
2917 Sserial_process_configure
,
2919 doc
: /* Configure speed, bytesize, etc. of a serial process.
2921 Arguments are specified as keyword/argument pairs. Attributes that
2922 are not given are re-initialized from the process's current
2923 configuration (available via the function `process-contact') or set to
2924 reasonable default values. The following arguments are defined:
2930 -- Any of these arguments can be given to identify the process that is
2931 to be configured. If none of these arguments is given, the current
2932 buffer's process is used.
2934 :speed SPEED -- SPEED is the speed of the serial port in bits per
2935 second, also called baud rate. Any value can be given for SPEED, but
2936 most serial ports work only at a few defined values between 1200 and
2937 115200, with 9600 being the most common value. If SPEED is nil, the
2938 serial port is not configured any further, i.e., all other arguments
2939 are ignored. This may be useful for special serial ports such as
2940 Bluetooth-to-serial converters which can only be configured through AT
2941 commands. A value of nil for SPEED can be used only when passed
2942 through `make-serial-process' or `serial-term'.
2944 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2945 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2947 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2948 `odd' (use odd parity), or the symbol `even' (use even parity). If
2949 PARITY is not given, no parity is used.
2951 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2952 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2953 is not given or nil, 1 stopbit is used.
2955 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2956 flowcontrol to be used, which is either nil (don't use flowcontrol),
2957 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2958 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2959 flowcontrol is used.
2961 `serial-process-configure' is called by `make-serial-process' for the
2962 initial configuration of the serial port.
2966 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2968 \(serial-process-configure
2969 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2971 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2973 usage: (serial-process-configure &rest ARGS) */)
2974 (ptrdiff_t nargs
, Lisp_Object
*args
)
2976 struct Lisp_Process
*p
;
2977 Lisp_Object contact
= Qnil
;
2978 Lisp_Object proc
= Qnil
;
2980 contact
= Flist (nargs
, args
);
2982 proc
= Fplist_get (contact
, QCprocess
);
2984 proc
= Fplist_get (contact
, QCname
);
2986 proc
= Fplist_get (contact
, QCbuffer
);
2988 proc
= Fplist_get (contact
, QCport
);
2989 proc
= get_process (proc
);
2990 p
= XPROCESS (proc
);
2991 if (!EQ (p
->type
, Qserial
))
2992 error ("Not a serial process");
2994 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2997 serial_configure (p
, contact
);
3001 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
3003 doc
: /* Create and return a serial port process.
3005 In Emacs, serial port connections are represented by process objects,
3006 so input and output work as for subprocesses, and `delete-process'
3007 closes a serial port connection. However, a serial process has no
3008 process id, it cannot be signaled, and the status codes are different
3009 from normal processes.
3011 `make-serial-process' creates a process and a buffer, on which you
3012 probably want to use `process-send-string'. Try \\[serial-term] for
3013 an interactive terminal. See below for examples.
3015 Arguments are specified as keyword/argument pairs. The following
3016 arguments are defined:
3018 :port PORT -- (mandatory) PORT is the path or name of the serial port.
3019 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
3020 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
3021 the backslashes in strings).
3023 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
3024 which this function calls.
3026 :name NAME -- NAME is the name of the process. If NAME is not given,
3027 the value of PORT is used.
3029 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3030 with the process. Process output goes at the end of that buffer,
3031 unless you specify a filter function to handle the output. If BUFFER
3032 is not given, the value of NAME is used.
3034 :coding CODING -- If CODING is a symbol, it specifies the coding
3035 system used for both reading and writing for this process. If CODING
3036 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3037 ENCODING is used for writing.
3039 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
3040 the process is running. If BOOL is not given, query before exiting.
3042 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
3043 In the stopped state, a serial process does not accept incoming data,
3044 but you can send outgoing data. The stopped state is cleared by
3045 `continue-process' and set by `stop-process'.
3047 :filter FILTER -- Install FILTER as the process filter.
3049 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3051 :plist PLIST -- Install PLIST as the initial plist of the process.
3057 -- This function calls `serial-process-configure' to handle these
3060 The original argument list, possibly modified by later configuration,
3061 is available via the function `process-contact'.
3065 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
3067 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
3069 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
3071 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
3073 usage: (make-serial-process &rest ARGS) */)
3074 (ptrdiff_t nargs
, Lisp_Object
*args
)
3077 Lisp_Object proc
, contact
, port
;
3078 struct Lisp_Process
*p
;
3079 Lisp_Object name
, buffer
;
3080 Lisp_Object tem
, val
;
3081 ptrdiff_t specpdl_count
;
3086 contact
= Flist (nargs
, args
);
3088 port
= Fplist_get (contact
, QCport
);
3090 error ("No port specified");
3091 CHECK_STRING (port
);
3093 if (NILP (Fplist_member (contact
, QCspeed
)))
3094 error (":speed not specified");
3095 if (!NILP (Fplist_get (contact
, QCspeed
)))
3096 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
3098 name
= Fplist_get (contact
, QCname
);
3101 CHECK_STRING (name
);
3102 proc
= make_process (name
);
3103 specpdl_count
= SPECPDL_INDEX ();
3104 record_unwind_protect (remove_process
, proc
);
3105 p
= XPROCESS (proc
);
3107 fd
= serial_open (port
);
3108 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
3113 chan_process
[fd
] = proc
;
3115 buffer
= Fplist_get (contact
, QCbuffer
);
3118 buffer
= Fget_buffer_create (buffer
);
3119 pset_buffer (p
, buffer
);
3121 pset_childp (p
, contact
);
3122 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3123 pset_type (p
, Qserial
);
3124 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
3125 pset_filter (p
, Fplist_get (contact
, QCfilter
));
3126 eassert (NILP (p
->log
));
3127 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3128 p
->kill_without_query
= 1;
3129 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
3130 pset_command (p
, Qt
);
3131 eassert (! p
->pty_flag
);
3133 if (!EQ (p
->command
, Qt
))
3134 add_process_read_fd (fd
);
3136 if (BUFFERP (buffer
))
3138 set_marker_both (p
->mark
, buffer
,
3139 BUF_ZV (XBUFFER (buffer
)),
3140 BUF_ZV_BYTE (XBUFFER (buffer
)));
3143 tem
= Fplist_member (contact
, QCcoding
);
3144 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3150 val
= XCAR (XCDR (tem
));
3154 else if (!NILP (Vcoding_system_for_read
))
3155 val
= Vcoding_system_for_read
;
3156 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3157 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3159 pset_decode_coding_system (p
, val
);
3164 val
= XCAR (XCDR (tem
));
3168 else if (!NILP (Vcoding_system_for_write
))
3169 val
= Vcoding_system_for_write
;
3170 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3171 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3173 pset_encode_coding_system (p
, val
);
3175 setup_process_coding_systems (proc
);
3176 pset_decoding_buf (p
, empty_unibyte_string
);
3177 eassert (p
->decoding_carryover
== 0);
3178 pset_encoding_buf (p
, empty_unibyte_string
);
3179 p
->inherit_coding_system_flag
3180 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3182 Fserial_process_configure (nargs
, args
);
3184 specpdl_ptr
= specpdl
+ specpdl_count
;
3190 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
3191 Lisp_Object service
, Lisp_Object name
)
3194 struct Lisp_Process
*p
= XPROCESS (proc
);
3195 Lisp_Object contact
= p
->childp
;
3196 Lisp_Object coding_systems
= Qt
;
3199 tem
= Fplist_member (contact
, QCcoding
);
3200 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3201 tem
= Qnil
; /* No error message (too late!). */
3203 /* Setup coding systems for communicating with the network stream. */
3204 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3208 val
= XCAR (XCDR (tem
));
3212 else if (!NILP (Vcoding_system_for_read
))
3213 val
= Vcoding_system_for_read
;
3214 else if ((!NILP (p
->buffer
)
3215 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3216 || (NILP (p
->buffer
)
3217 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3218 /* We dare not decode end-of-line format by setting VAL to
3219 Qraw_text, because the existing Emacs Lisp libraries
3220 assume that they receive bare code including a sequence of
3225 if (NILP (host
) || NILP (service
))
3226 coding_systems
= Qnil
;
3228 coding_systems
= CALLN (Ffind_operation_coding_system
,
3229 Qopen_network_stream
, name
, p
->buffer
,
3231 if (CONSP (coding_systems
))
3232 val
= XCAR (coding_systems
);
3233 else if (CONSP (Vdefault_process_coding_system
))
3234 val
= XCAR (Vdefault_process_coding_system
);
3238 pset_decode_coding_system (p
, val
);
3242 val
= XCAR (XCDR (tem
));
3246 else if (!NILP (Vcoding_system_for_write
))
3247 val
= Vcoding_system_for_write
;
3248 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3252 if (EQ (coding_systems
, Qt
))
3254 if (NILP (host
) || NILP (service
))
3255 coding_systems
= Qnil
;
3257 coding_systems
= CALLN (Ffind_operation_coding_system
,
3258 Qopen_network_stream
, name
, p
->buffer
,
3261 if (CONSP (coding_systems
))
3262 val
= XCDR (coding_systems
);
3263 else if (CONSP (Vdefault_process_coding_system
))
3264 val
= XCDR (Vdefault_process_coding_system
);
3268 pset_encode_coding_system (p
, val
);
3270 pset_decoding_buf (p
, empty_unibyte_string
);
3271 p
->decoding_carryover
= 0;
3272 pset_encoding_buf (p
, empty_unibyte_string
);
3274 p
->inherit_coding_system_flag
3275 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3280 finish_after_tls_connection (Lisp_Object proc
)
3282 struct Lisp_Process
*p
= XPROCESS (proc
);
3283 Lisp_Object contact
= p
->childp
;
3284 Lisp_Object result
= Qt
;
3286 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3287 result
= call3 (Qnsm_verify_connection
,
3289 Fplist_get (contact
, QChost
),
3290 Fplist_get (contact
, QCservice
));
3294 pset_status (p
, list2 (Qfailed
,
3295 build_string ("The Network Security Manager stopped the connections")));
3296 deactivate_process (proc
);
3298 else if (p
->outfd
< 0)
3300 /* The counterparty may have closed the connection (especially
3301 if the NSM prompt above take a long time), so recheck the file
3303 pset_status (p
, Qfailed
);
3304 deactivate_process (proc
);
3306 else if ((fd_callback_info
[p
->outfd
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3308 /* If we cleared the connection wait mask before we did the TLS
3309 setup, then we have to say that the process is finally "open"
3311 pset_status (p
, Qrun
);
3312 /* Execute the sentinel here. If we had relied on status_notify
3313 to do it later, it will read input from the process before
3314 calling the sentinel. */
3315 exec_sentinel (proc
, build_string ("open\n"));
3321 connect_network_socket (Lisp_Object proc
, Lisp_Object addrinfos
,
3322 Lisp_Object use_external_socket_p
)
3324 ptrdiff_t count
= SPECPDL_INDEX ();
3325 int s
= -1, outch
, inch
;
3328 struct sockaddr
*sa
= NULL
;
3331 struct Lisp_Process
*p
= XPROCESS (proc
);
3332 Lisp_Object contact
= p
->childp
;
3334 int socket_to_use
= -1;
3336 if (!NILP (use_external_socket_p
))
3338 socket_to_use
= external_sock_fd
;
3340 /* Ensure we don't consume the external socket twice. */
3341 external_sock_fd
= -1;
3344 /* Do this in case we never enter the while-loop below. */
3347 while (!NILP (addrinfos
))
3349 Lisp_Object addrinfo
= XCAR (addrinfos
);
3350 addrinfos
= XCDR (addrinfos
);
3351 int protocol
= XINT (XCAR (addrinfo
));
3352 Lisp_Object ip_address
= XCDR (addrinfo
);
3358 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3361 sa
= xmalloc (addrlen
);
3362 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3367 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3368 if (p
->is_non_blocking_client
)
3369 socktype
|= SOCK_NONBLOCK
;
3370 s
= socket (family
, socktype
, protocol
);
3378 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3380 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3386 if (0 <= socket_to_use
)
3392 #ifdef DATAGRAM_SOCKETS
3393 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3395 #endif /* DATAGRAM_SOCKETS */
3397 /* Make us close S if quit. */
3398 record_unwind_protect_int (close_file_unwind
, s
);
3400 /* Parse network options in the arg list. We simply ignore anything
3401 which isn't a known option (including other keywords). An error
3402 is signaled if setting a known option fails. */
3404 Lisp_Object params
= contact
, key
, val
;
3406 while (!NILP (params
))
3408 key
= XCAR (params
);
3409 params
= XCDR (params
);
3410 val
= XCAR (params
);
3411 params
= XCDR (params
);
3412 optbits
|= set_socket_option (s
, key
, val
);
3418 /* Configure as a server socket. */
3420 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3421 explicit :reuseaddr key to override this. */
3422 #ifdef HAVE_LOCAL_SOCKETS
3423 if (family
!= AF_LOCAL
)
3425 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3428 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3429 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3432 /* If passed a socket descriptor, it should be already bound. */
3433 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3434 report_file_error ("Cannot bind server socket", Qnil
);
3436 #ifdef HAVE_GETSOCKNAME
3438 #ifdef HAVE_LOCAL_SOCKETS
3439 && family
!= AF_LOCAL
3443 struct sockaddr_in sa1
;
3444 socklen_t len1
= sizeof (sa1
);
3446 /* The code below assumes the port is at the same offset
3447 and of the same width in both IPv4 and IPv6
3448 structures, but the standards don't guarantee that,
3449 so verify it here. */
3450 struct sockaddr_in6 sa6
;
3451 verify ((offsetof (struct sockaddr_in
, sin_port
)
3452 == offsetof (struct sockaddr_in6
, sin6_port
))
3453 && sizeof (sa1
.sin_port
) == sizeof (sa6
.sin6_port
));
3455 DECLARE_POINTER_ALIAS (psa1
, struct sockaddr
, &sa1
);
3456 if (getsockname (s
, psa1
, &len1
) == 0)
3458 Lisp_Object service
= make_number (ntohs (sa1
.sin_port
));
3459 contact
= Fplist_put (contact
, QCservice
, service
);
3460 /* Save the port number so that we can stash it in
3461 the process object later. */
3462 DECLARE_POINTER_ALIAS (psa
, struct sockaddr_in
, sa
);
3463 psa
->sin_port
= sa1
.sin_port
;
3468 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3469 report_file_error ("Cannot listen on server socket", Qnil
);
3476 ret
= connect (s
, sa
, addrlen
);
3479 if (ret
== 0 || xerrno
== EISCONN
)
3481 /* The unwind-protect will be discarded afterwards. */
3485 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3489 if (xerrno
== EINTR
)
3491 /* Unlike most other syscalls connect() cannot be called
3492 again. (That would return EALREADY.) The proper way to
3493 wait for completion is pselect(). */
3501 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3507 report_file_error ("Failed select", Qnil
);
3511 len
= sizeof xerrno
;
3512 eassert (FD_ISSET (s
, &fdset
));
3513 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3514 report_file_error ("Failed getsockopt", Qnil
);
3517 if (NILP (addrinfos
))
3518 report_file_errno ("Failed connect", Qnil
, xerrno
);
3520 #endif /* !WINDOWSNT */
3522 /* Discard the unwind protect closing S. */
3523 specpdl_ptr
= specpdl
+ count
;
3526 if (0 <= socket_to_use
)
3530 if (xerrno
== EINTR
)
3537 #ifdef DATAGRAM_SOCKETS
3538 if (p
->socktype
== SOCK_DGRAM
)
3540 if (datagram_address
[s
].sa
)
3543 datagram_address
[s
].sa
= xmalloc (addrlen
);
3544 datagram_address
[s
].len
= addrlen
;
3548 memset (datagram_address
[s
].sa
, 0, addrlen
);
3549 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3552 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3553 if (rlen
!= 0 && rfamily
== family
3555 conv_lisp_to_sockaddr (rfamily
, remote
,
3556 datagram_address
[s
].sa
, rlen
);
3560 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3564 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3565 conv_sockaddr_to_lisp (sa
, addrlen
));
3566 #ifdef HAVE_GETSOCKNAME
3569 struct sockaddr_storage sa1
;
3570 socklen_t len1
= sizeof (sa1
);
3571 DECLARE_POINTER_ALIAS (psa1
, struct sockaddr
, &sa1
);
3572 if (getsockname (s
, psa1
, &len1
) == 0)
3573 contact
= Fplist_put (contact
, QClocal
,
3574 conv_sockaddr_to_lisp (psa1
, len1
));
3581 /* If non-blocking got this far - and failed - assume non-blocking is
3582 not supported after all. This is probably a wrong assumption, but
3583 the normal blocking calls to open-network-stream handles this error
3585 if (p
->is_non_blocking_client
)
3588 report_file_errno ((p
->is_server
3589 ? "make server process failed"
3590 : "make client process failed"),
3597 chan_process
[inch
] = proc
;
3599 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3601 p
= XPROCESS (proc
);
3602 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3606 /* Discard the unwind protect for closing S, if any. */
3607 specpdl_ptr
= specpdl
+ count
;
3609 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3610 pset_status (p
, Qlisten
);
3612 /* Make the process marker point into the process buffer (if any). */
3613 if (BUFFERP (p
->buffer
))
3614 set_marker_both (p
->mark
, p
->buffer
,
3615 BUF_ZV (XBUFFER (p
->buffer
)),
3616 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3618 if (p
->is_non_blocking_client
)
3620 /* We may get here if connect did succeed immediately. However,
3621 in that case, we still need to signal this like a non-blocking
3623 if (! (connecting_status (p
->status
)
3624 && EQ (XCDR (p
->status
), addrinfos
)))
3625 pset_status (p
, Fcons (Qconnect
, addrinfos
));
3626 if ((fd_callback_info
[inch
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3627 add_non_blocking_write_fd (inch
);
3630 /* A server may have a client filter setting of Qt, but it must
3631 still listen for incoming connects unless it is stopped. */
3632 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3633 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3634 add_process_read_fd (inch
);
3636 if (inch
> max_desc
)
3639 /* Set up the masks based on the process filter. */
3640 set_process_filter_masks (p
);
3642 setup_process_coding_systems (proc
);
3645 /* Continue the asynchronous connection. */
3646 if (!NILP (p
->gnutls_boot_parameters
))
3648 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3650 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3651 p
->gnutls_boot_parameters
= Qnil
;
3653 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3654 /* Run sentinels, etc. */
3655 finish_after_tls_connection (proc
);
3656 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3658 deactivate_process (proc
);
3660 pset_status (p
, list2 (Qfailed
,
3661 build_string ("TLS negotiation failed")));
3663 pset_status (p
, list2 (Qfailed
, boot
));
3670 /* Create a network stream/datagram client/server process. Treated
3671 exactly like a normal process when reading and writing. Primary
3672 differences are in status display and process deletion. A network
3673 connection has no PID; you cannot signal it. All you can do is
3674 stop/continue it and deactivate/close it via delete-process. */
3676 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3678 doc
: /* Create and return a network server or client process.
3680 In Emacs, network connections are represented by process objects, so
3681 input and output work as for subprocesses and `delete-process' closes
3682 a network connection. However, a network process has no process id,
3683 it cannot be signaled, and the status codes are different from normal
3686 Arguments are specified as keyword/argument pairs. The following
3687 arguments are defined:
3689 :name NAME -- NAME is name for process. It is modified if necessary
3692 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3693 with the process. Process output goes at end of that buffer, unless
3694 you specify a filter function to handle the output. BUFFER may be
3695 also nil, meaning that this process is not associated with any buffer.
3697 :host HOST -- HOST is name of the host to connect to, or its IP
3698 address. The symbol `local' specifies the local host. If specified
3699 for a server process, it must be a valid name or address for the local
3700 host, and only clients connecting to that address will be accepted.
3702 :service SERVICE -- SERVICE is name of the service desired, or an
3703 integer specifying a port number to connect to. If SERVICE is t,
3704 a random port number is selected for the server. A port number can
3705 be specified as an integer string, e.g., "80", as well as an integer.
3707 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3708 stream type connection, `datagram' creates a datagram type connection,
3709 `seqpacket' creates a reliable datagram connection.
3711 :family FAMILY -- FAMILY is the address (and protocol) family for the
3712 service specified by HOST and SERVICE. The default (nil) is to use
3713 whatever address family (IPv4 or IPv6) that is defined for the host
3714 and port number specified by HOST and SERVICE. Other address families
3716 local -- for a local (i.e. UNIX) address specified by SERVICE.
3717 ipv4 -- use IPv4 address family only.
3718 ipv6 -- use IPv6 address family only.
3720 :local ADDRESS -- ADDRESS is the local address used for the connection.
3721 This parameter is ignored when opening a client process. When specified
3722 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3724 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3725 connection. This parameter is ignored when opening a stream server
3726 process. For a datagram server process, it specifies the initial
3727 setting of the remote datagram address. When specified for a client
3728 process, the FAMILY, HOST, and SERVICE args are ignored.
3730 The format of ADDRESS depends on the address family:
3731 - An IPv4 address is represented as a vector of integers [A B C D P]
3732 corresponding to numeric IP address A.B.C.D and port number P.
3733 - A local address is represented as a string with the address in the
3734 local address space.
3735 - An "unsupported family" address is represented by a cons (F . AV)
3736 where F is the family number and AV is a vector containing the socket
3737 address data with one element per address data byte. Do not rely on
3738 this format in portable code, as it may depend on implementation
3739 defined constants, data sizes, and data structure alignment.
3741 :coding CODING -- If CODING is a symbol, it specifies the coding
3742 system used for both reading and writing for this process. If CODING
3743 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3744 ENCODING is used for writing.
3746 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3747 process, return without waiting for the connection to complete;
3748 instead, the sentinel function will be called with second arg matching
3749 "open" (if successful) or "failed" when the connect completes.
3750 Default is to use a blocking connect (i.e. wait) for stream type
3753 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3754 running when Emacs is exited.
3756 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3757 In the stopped state, a server process does not accept new
3758 connections, and a client process does not handle incoming traffic.
3759 The stopped state is cleared by `continue-process' and set by
3762 :filter FILTER -- Install FILTER as the process filter.
3764 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3765 process filter are multibyte, otherwise they are unibyte.
3766 If this keyword is not specified, the strings are multibyte if
3767 the default value of `enable-multibyte-characters' is non-nil.
3769 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3771 :log LOG -- Install LOG as the server process log function. This
3772 function is called when the server accepts a network connection from a
3773 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3774 is the server process, CLIENT is the new process for the connection,
3775 and MESSAGE is a string.
3777 :plist PLIST -- Install PLIST as the new process's initial plist.
3779 :tls-parameters LIST -- is a list that should be supplied if you're
3780 opening a TLS connection. The first element is the TLS type (either
3781 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3782 be a keyword list accepted by gnutls-boot (as returned by
3783 `gnutls-boot-parameters').
3785 :server QLEN -- if QLEN is non-nil, create a server process for the
3786 specified FAMILY, SERVICE, and connection type (stream or datagram).
3787 If QLEN is an integer, it is used as the max. length of the server's
3788 pending connection queue (also known as the backlog); the default
3789 queue length is 5. Default is to create a client process.
3791 The following network options can be specified for this connection:
3793 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3794 :dontroute BOOL -- Only send to directly connected hosts.
3795 :keepalive BOOL -- Send keep-alive messages on network stream.
3796 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3797 :oobinline BOOL -- Place out-of-band data in receive data stream.
3798 :priority INT -- Set protocol defined priority for sent packets.
3799 :reuseaddr BOOL -- Allow reusing a recently used local address
3800 (this is allowed by default for a server process).
3801 :bindtodevice NAME -- bind to interface NAME. Using this may require
3802 special privileges on some systems.
3803 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3804 been passed to Emacs. If Emacs wasn't
3805 passed a socket, this option is silently
3809 Consult the relevant system programmer's manual pages for more
3810 information on using these options.
3813 A server process will listen for and accept connections from clients.
3814 When a client connection is accepted, a new network process is created
3815 for the connection with the following parameters:
3817 - The client's process name is constructed by concatenating the server
3818 process's NAME and a client identification string.
3819 - If the FILTER argument is non-nil, the client process will not get a
3820 separate process buffer; otherwise, the client's process buffer is a newly
3821 created buffer named after the server process's BUFFER name or process
3822 NAME concatenated with the client identification string.
3823 - The connection type and the process filter and sentinel parameters are
3824 inherited from the server process's TYPE, FILTER and SENTINEL.
3825 - The client process's contact info is set according to the client's
3826 addressing information (typically an IP address and a port number).
3827 - The client process's plist is initialized from the server's plist.
3829 Notice that the FILTER and SENTINEL args are never used directly by
3830 the server process. Also, the BUFFER argument is not used directly by
3831 the server process, but via the optional :log function, accepted (and
3832 failed) connections may be logged in the server process's buffer.
3834 The original argument list, modified with the actual connection
3835 information, is available via the `process-contact' function.
3837 usage: (make-network-process &rest ARGS) */)
3838 (ptrdiff_t nargs
, Lisp_Object
*args
)
3841 Lisp_Object contact
;
3842 struct Lisp_Process
*p
;
3843 const char *portstring UNINIT
;
3844 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3845 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3846 #ifdef HAVE_LOCAL_SOCKETS
3847 struct sockaddr_un address_un
;
3851 Lisp_Object name
, buffer
, host
, service
, address
;
3852 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3853 Lisp_Object addrinfos
= Qnil
;
3856 enum { any_protocol
= 0 };
3857 #ifdef HAVE_GETADDRINFO_A
3858 struct gaicb
*dns_request
= NULL
;
3860 ptrdiff_t count
= SPECPDL_INDEX ();
3865 /* Save arguments for process-contact and clone-process. */
3866 contact
= Flist (nargs
, args
);
3869 /* Ensure socket support is loaded if available. */
3870 init_winsock (TRUE
);
3873 /* :type TYPE (nil: stream, datagram */
3874 tem
= Fplist_get (contact
, QCtype
);
3876 socktype
= SOCK_STREAM
;
3877 #ifdef DATAGRAM_SOCKETS
3878 else if (EQ (tem
, Qdatagram
))
3879 socktype
= SOCK_DGRAM
;
3881 #ifdef HAVE_SEQPACKET
3882 else if (EQ (tem
, Qseqpacket
))
3883 socktype
= SOCK_SEQPACKET
;
3886 error ("Unsupported connection type");
3888 name
= Fplist_get (contact
, QCname
);
3889 buffer
= Fplist_get (contact
, QCbuffer
);
3890 filter
= Fplist_get (contact
, QCfilter
);
3891 sentinel
= Fplist_get (contact
, QCsentinel
);
3892 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3894 CHECK_STRING (name
);
3896 /* :local ADDRESS or :remote ADDRESS */
3897 tem
= Fplist_get (contact
, QCserver
);
3899 address
= Fplist_get (contact
, QCremote
);
3901 address
= Fplist_get (contact
, QClocal
);
3902 if (!NILP (address
))
3904 host
= service
= Qnil
;
3906 if (!get_lisp_to_sockaddr_size (address
, &family
))
3907 error ("Malformed :address");
3909 addrinfos
= list1 (Fcons (make_number (any_protocol
), address
));
3913 /* :family FAMILY -- nil (for Inet), local, or integer. */
3914 tem
= Fplist_get (contact
, QCfamily
);
3923 #ifdef HAVE_LOCAL_SOCKETS
3924 else if (EQ (tem
, Qlocal
))
3928 else if (EQ (tem
, Qipv6
))
3931 else if (EQ (tem
, Qipv4
))
3933 else if (TYPE_RANGED_INTEGERP (int, tem
))
3934 family
= XINT (tem
);
3936 error ("Unknown address family");
3938 /* :service SERVICE -- string, integer (port number), or t (random port). */
3939 service
= Fplist_get (contact
, QCservice
);
3941 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3942 host
= Fplist_get (contact
, QChost
);
3945 /* The "connection" function gets it bind info from the address we're
3946 given, so use this dummy address if nothing is specified. */
3947 #ifdef HAVE_LOCAL_SOCKETS
3948 if (family
!= AF_LOCAL
)
3950 host
= build_string ("127.0.0.1");
3954 if (EQ (host
, Qlocal
))
3955 /* Depending on setup, "localhost" may map to different IPv4 and/or
3956 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3957 host
= build_string ("127.0.0.1");
3958 CHECK_STRING (host
);
3961 #ifdef HAVE_LOCAL_SOCKETS
3962 if (family
== AF_LOCAL
)
3966 message (":family local ignores the :host property");
3967 contact
= Fplist_put (contact
, QChost
, Qnil
);
3970 CHECK_STRING (service
);
3971 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3972 error ("Service name too long");
3973 addrinfos
= list1 (Fcons (make_number (any_protocol
), service
));
3978 /* Slow down polling to every ten seconds.
3979 Some kernels have a bug which causes retrying connect to fail
3980 after a connect. Polling can interfere with gethostbyname too. */
3981 #ifdef POLL_FOR_INPUT
3982 if (socktype
!= SOCK_DGRAM
)
3984 record_unwind_protect_void (run_all_atimers
);
3985 bind_polling_period (10);
3991 /* SERVICE can either be a string or int.
3992 Convert to a C string for later use by getaddrinfo. */
3993 if (EQ (service
, Qt
))
3998 else if (INTEGERP (service
))
4000 portstring
= portbuf
;
4001 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
4005 CHECK_STRING (service
);
4006 portstring
= SSDATA (service
);
4007 portstringlen
= SBYTES (service
);
4011 #ifdef HAVE_GETADDRINFO_A
4012 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
4014 ptrdiff_t hostlen
= SBYTES (host
);
4018 struct addrinfo hints
;
4019 char str
[FLEXIBLE_ARRAY_MEMBER
];
4020 } *req
= xmalloc (FLEXSIZEOF (struct req
, str
,
4021 hostlen
+ 1 + portstringlen
+ 1));
4022 dns_request
= &req
->gaicb
;
4023 dns_request
->ar_name
= req
->str
;
4024 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
4025 dns_request
->ar_request
= &req
->hints
;
4026 dns_request
->ar_result
= NULL
;
4027 memset (&req
->hints
, 0, sizeof req
->hints
);
4028 req
->hints
.ai_family
= family
;
4029 req
->hints
.ai_socktype
= socktype
;
4030 strcpy (req
->str
, SSDATA (host
));
4031 strcpy (req
->str
+ hostlen
+ 1, portstring
);
4033 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
4035 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
4039 #endif /* HAVE_GETADDRINFO_A */
4041 /* If we have a host, use getaddrinfo to resolve both host and service.
4042 Otherwise, use getservbyname to lookup the service. */
4046 struct addrinfo
*res
, *lres
;
4051 struct addrinfo hints
;
4052 memset (&hints
, 0, sizeof hints
);
4053 hints
.ai_family
= family
;
4054 hints
.ai_socktype
= socktype
;
4056 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
4058 #ifdef HAVE_GAI_STRERROR
4060 synchronize_system_messages_locale ();
4061 char const *str
= gai_strerror (ret
);
4062 if (! NILP (Vlocale_coding_system
))
4063 str
= SSDATA (code_convert_string_norecord
4064 (build_string (str
), Vlocale_coding_system
, 0));
4065 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
4068 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
4071 for (lres
= res
; lres
; lres
= lres
->ai_next
)
4072 addrinfos
= Fcons (conv_addrinfo_to_lisp (lres
), addrinfos
);
4074 addrinfos
= Fnreverse (addrinfos
);
4081 /* No hostname has been specified (e.g., a local server process). */
4083 if (EQ (service
, Qt
))
4085 else if (INTEGERP (service
))
4086 port
= XINT (service
);
4089 CHECK_STRING (service
);
4092 if (SBYTES (service
) != 0)
4094 /* Allow the service to be a string containing the port number,
4095 because that's allowed if you have getaddrbyname. */
4097 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
4098 if (service_end
== SSDATA (service
) + SBYTES (service
))
4102 struct servent
*svc_info
4103 = getservbyname (SSDATA (service
),
4104 socktype
== SOCK_DGRAM
? "udp" : "tcp");
4106 port
= ntohs (svc_info
->s_port
);
4111 if (! (0 <= port
&& port
< 1 << 16))
4113 AUTO_STRING (unknown_service
, "Unknown service: %s");
4114 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
4120 buffer
= Fget_buffer_create (buffer
);
4122 /* Unwind bind_polling_period. */
4123 unbind_to (count
, Qnil
);
4125 proc
= make_process (name
);
4126 record_unwind_protect (remove_process
, proc
);
4127 p
= XPROCESS (proc
);
4128 pset_childp (p
, contact
);
4129 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
4130 pset_type (p
, Qnetwork
);
4132 pset_buffer (p
, buffer
);
4133 pset_sentinel (p
, sentinel
);
4134 pset_filter (p
, filter
);
4135 pset_log (p
, Fplist_get (contact
, QClog
));
4136 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
4137 p
->kill_without_query
= 1;
4138 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
4139 pset_command (p
, Qt
);
4140 eassert (p
->pid
== 0);
4142 eassert (! p
->is_non_blocking_client
);
4143 eassert (! p
->is_server
);
4145 p
->socktype
= socktype
;
4146 #ifdef HAVE_GETADDRINFO_A
4147 eassert (! p
->dns_request
);
4150 tem
= Fplist_get (contact
, QCtls_parameters
);
4152 p
->gnutls_boot_parameters
= tem
;
4155 set_network_socket_coding_system (proc
, host
, service
, name
);
4158 tem
= Fplist_get (contact
, QCserver
);
4161 /* Don't support network sockets when non-blocking mode is
4162 not available, since a blocked Emacs is not useful. */
4163 p
->is_server
= true;
4164 if (TYPE_RANGED_INTEGERP (int, tem
))
4165 p
->backlog
= XINT (tem
);
4169 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
4170 && !NILP (Fplist_get (contact
, QCnowait
)))
4171 p
->is_non_blocking_client
= true;
4173 bool postpone_connection
= false;
4174 #ifdef HAVE_GETADDRINFO_A
4175 /* With async address resolution, the list of addresses is empty, so
4176 postpone connecting to the server. */
4177 if (!p
->is_server
&& NILP (addrinfos
))
4179 p
->dns_request
= dns_request
;
4180 p
->status
= list1 (Qconnect
);
4181 postpone_connection
= true;
4184 if (! postpone_connection
)
4185 connect_network_socket (proc
, addrinfos
, use_external_socket_p
);
4187 specpdl_ptr
= specpdl
+ count
;
4192 #ifdef HAVE_NET_IF_H
4196 network_interface_list (void)
4198 struct ifconf ifconf
;
4199 struct ifreq
*ifreq
;
4201 ptrdiff_t buf_size
= 512;
4206 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4209 count
= SPECPDL_INDEX ();
4210 record_unwind_protect_int (close_file_unwind
, s
);
4214 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4215 ifconf
.ifc_buf
= buf
;
4216 ifconf
.ifc_len
= buf_size
;
4217 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4224 while (ifconf
.ifc_len
== buf_size
);
4226 res
= unbind_to (count
, Qnil
);
4227 ifreq
= ifconf
.ifc_req
;
4228 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4230 struct ifreq
*ifq
= ifreq
;
4231 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4232 #define SIZEOF_IFREQ(sif) \
4233 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4234 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4236 int len
= SIZEOF_IFREQ (ifq
);
4238 int len
= sizeof (*ifreq
);
4240 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4241 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4243 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4246 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4247 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4248 res
= Fcons (Fcons (build_string (namebuf
),
4249 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4250 sizeof (struct sockaddr
))),
4257 #endif /* SIOCGIFCONF */
4259 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4263 const char *flag_sym
;
4266 static const struct ifflag_def ifflag_table
[] = {
4270 #ifdef IFF_BROADCAST
4271 { IFF_BROADCAST
, "broadcast" },
4274 { IFF_DEBUG
, "debug" },
4277 { IFF_LOOPBACK
, "loopback" },
4279 #ifdef IFF_POINTOPOINT
4280 { IFF_POINTOPOINT
, "pointopoint" },
4283 { IFF_RUNNING
, "running" },
4286 { IFF_NOARP
, "noarp" },
4289 { IFF_PROMISC
, "promisc" },
4291 #ifdef IFF_NOTRAILERS
4292 #ifdef NS_IMPL_COCOA
4293 /* Really means smart, notrailers is obsolete. */
4294 { IFF_NOTRAILERS
, "smart" },
4296 { IFF_NOTRAILERS
, "notrailers" },
4300 { IFF_ALLMULTI
, "allmulti" },
4303 { IFF_MASTER
, "master" },
4306 { IFF_SLAVE
, "slave" },
4308 #ifdef IFF_MULTICAST
4309 { IFF_MULTICAST
, "multicast" },
4312 { IFF_PORTSEL
, "portsel" },
4314 #ifdef IFF_AUTOMEDIA
4315 { IFF_AUTOMEDIA
, "automedia" },
4318 { IFF_DYNAMIC
, "dynamic" },
4321 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4324 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4327 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4330 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4333 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4339 network_interface_info (Lisp_Object ifname
)
4342 Lisp_Object res
= Qnil
;
4347 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4348 && defined HAVE_GETIFADDRS && defined LLADDR)
4349 struct ifaddrs
*ifap
;
4352 CHECK_STRING (ifname
);
4354 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4355 error ("interface name too long");
4356 lispstpcpy (rq
.ifr_name
, ifname
);
4358 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4361 count
= SPECPDL_INDEX ();
4362 record_unwind_protect_int (close_file_unwind
, s
);
4365 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4366 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4368 int flags
= rq
.ifr_flags
;
4369 const struct ifflag_def
*fp
;
4372 /* If flags is smaller than int (i.e. short) it may have the high bit set
4373 due to IFF_MULTICAST. In that case, sign extending it into
4375 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4376 flags
= (unsigned short) rq
.ifr_flags
;
4379 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4381 if (flags
& fp
->flag_bit
)
4383 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4384 flags
-= fp
->flag_bit
;
4387 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4391 elt
= Fcons (make_number (fnum
), elt
);
4396 res
= Fcons (elt
, res
);
4399 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4400 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4402 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4403 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4407 for (n
= 0; n
< 6; n
++)
4408 p
->contents
[n
] = make_number (((unsigned char *)
4409 &rq
.ifr_hwaddr
.sa_data
[0])
4411 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4413 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4414 if (getifaddrs (&ifap
) != -1)
4416 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4417 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4420 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4422 DECLARE_POINTER_ALIAS (sdl
, struct sockaddr_dl
, it
->ifa_addr
);
4423 unsigned char linkaddr
[6];
4426 if (it
->ifa_addr
->sa_family
!= AF_LINK
4427 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4428 || sdl
->sdl_alen
!= 6)
4431 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4432 for (n
= 0; n
< 6; n
++)
4433 p
->contents
[n
] = make_number (linkaddr
[n
]);
4435 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4439 #ifdef HAVE_FREEIFADDRS
4443 #endif /* HAVE_GETIFADDRS && LLADDR */
4445 res
= Fcons (elt
, res
);
4448 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4449 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4452 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4453 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4455 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4459 res
= Fcons (elt
, res
);
4462 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4463 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4466 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4469 res
= Fcons (elt
, res
);
4472 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4473 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4476 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4479 res
= Fcons (elt
, res
);
4481 return unbind_to (count
, any
? res
: Qnil
);
4483 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4484 #endif /* defined (HAVE_NET_IF_H) */
4486 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4487 Snetwork_interface_list
, 0, 0, 0,
4488 doc
: /* Return an alist of all network interfaces and their network address.
4489 Each element is a cons, the car of which is a string containing the
4490 interface name, and the cdr is the network address in internal
4491 format; see the description of ADDRESS in `make-network-process'.
4493 If the information is not available, return nil. */)
4496 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4497 return network_interface_list ();
4503 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4504 Snetwork_interface_info
, 1, 1, 0,
4505 doc
: /* Return information about network interface named IFNAME.
4506 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4507 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4508 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4509 FLAGS is the current flags of the interface.
4511 Data that is unavailable is returned as nil. */)
4512 (Lisp_Object ifname
)
4514 #if ((defined HAVE_NET_IF_H \
4515 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4516 || defined SIOCGIFFLAGS)) \
4517 || defined WINDOWSNT)
4518 return network_interface_info (ifname
);
4524 /* Turn off input and output for process PROC. */
4527 deactivate_process (Lisp_Object proc
)
4530 struct Lisp_Process
*p
= XPROCESS (proc
);
4534 /* Delete GnuTLS structures in PROC, if any. */
4535 emacs_gnutls_deinit (proc
);
4536 #endif /* HAVE_GNUTLS */
4538 if (p
->read_output_delay
> 0)
4540 if (--process_output_delay_count
< 0)
4541 process_output_delay_count
= 0;
4542 p
->read_output_delay
= 0;
4543 p
->read_output_skip
= 0;
4546 /* Beware SIGCHLD hereabouts. */
4548 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4549 close_process_fd (&p
->open_fd
[i
]);
4551 inchannel
= p
->infd
;
4556 #ifdef DATAGRAM_SOCKETS
4557 if (DATAGRAM_CHAN_P (inchannel
))
4559 xfree (datagram_address
[inchannel
].sa
);
4560 datagram_address
[inchannel
].sa
= 0;
4561 datagram_address
[inchannel
].len
= 0;
4564 chan_process
[inchannel
] = Qnil
;
4565 delete_read_fd (inchannel
);
4566 if ((fd_callback_info
[inchannel
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
4567 delete_write_fd (inchannel
);
4568 if (inchannel
== max_desc
)
4569 recompute_max_desc ();
4574 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4576 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4577 It is given to their filter functions.
4578 Optional argument PROCESS means do not return until output has been
4579 received from PROCESS.
4581 Optional second argument SECONDS and third argument MILLISEC
4582 specify a timeout; return after that much time even if there is
4583 no subprocess output. If SECONDS is a floating point number,
4584 it specifies a fractional number of seconds to wait.
4585 The MILLISEC argument is obsolete and should be avoided.
4587 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4588 from PROCESS only, suspending reading output from other processes.
4589 If JUST-THIS-ONE is an integer, don't run any timers either.
4590 Return non-nil if we received any output from PROCESS (or, if PROCESS
4591 is nil, from any process) before the timeout expired. */)
4592 (Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
,
4593 Lisp_Object just_this_one
)
4598 if (! NILP (process
))
4600 CHECK_PROCESS (process
);
4601 struct Lisp_Process
*proc
= XPROCESS (process
);
4603 /* Can't wait for a process that is dedicated to a different
4605 if (!EQ (proc
->thread
, Qnil
) && !EQ (proc
->thread
, Fcurrent_thread ()))
4607 Lisp_Object proc_thread_name
= XTHREAD (proc
->thread
)->name
;
4609 if (STRINGP (proc_thread_name
))
4610 error ("Attempt to accept output from process %s locked to thread %s",
4611 SDATA (proc
->name
), SDATA (proc_thread_name
));
4613 error ("Attempt to accept output from process %s locked to thread %p",
4614 SDATA (proc
->name
), XTHREAD (proc
->thread
));
4618 just_this_one
= Qnil
;
4620 if (!NILP (millisec
))
4621 { /* Obsolete calling convention using integers rather than floats. */
4622 CHECK_NUMBER (millisec
);
4624 seconds
= make_float (XINT (millisec
) / 1000.0);
4627 CHECK_NUMBER (seconds
);
4628 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4635 if (!NILP (seconds
))
4637 if (INTEGERP (seconds
))
4639 if (XINT (seconds
) > 0)
4641 secs
= XINT (seconds
);
4645 else if (FLOATP (seconds
))
4647 if (XFLOAT_DATA (seconds
) > 0)
4649 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4650 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4655 wrong_type_argument (Qnumberp
, seconds
);
4657 else if (! NILP (process
))
4661 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4663 !NILP (process
) ? XPROCESS (process
) : NULL
,
4664 (NILP (just_this_one
) ? 0
4665 : !INTEGERP (just_this_one
) ? 1 : -1))
4670 /* Accept a connection for server process SERVER on CHANNEL. */
4672 static EMACS_INT connect_counter
= 0;
4675 server_accept_connection (Lisp_Object server
, int channel
)
4678 Lisp_Object contact
, host
, service
;
4679 struct Lisp_Process
*ps
= XPROCESS (server
);
4680 struct Lisp_Process
*p
;
4684 struct sockaddr_in in
;
4686 struct sockaddr_in6 in6
;
4688 #ifdef HAVE_LOCAL_SOCKETS
4689 struct sockaddr_un un
;
4692 socklen_t len
= sizeof saddr
;
4695 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4700 if (!would_block (code
) && !NILP (ps
->log
))
4701 call3 (ps
->log
, server
, Qnil
,
4702 concat3 (build_string ("accept failed with code"),
4703 Fnumber_to_string (make_number (code
)),
4704 build_string ("\n")));
4708 count
= SPECPDL_INDEX ();
4709 record_unwind_protect_int (close_file_unwind
, s
);
4713 /* Setup a new process to handle the connection. */
4715 /* Generate a unique identification of the caller, and build contact
4716 information for this process. */
4719 Lisp_Object args
[11];
4721 AUTO_STRING (procname_format_in
, "%s <%d.%d.%d.%d:%d>");
4722 AUTO_STRING (procname_format_in6
, "%s <[%x:%x:%x:%x:%x:%x:%x:%x]:%d>");
4723 AUTO_STRING (procname_format_default
, "%s <%d>");
4724 switch (saddr
.sa
.sa_family
)
4728 args
[nargs
++] = procname_format_in
;
4730 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4731 service
= make_number (ntohs (saddr
.in
.sin_port
));
4732 for (int i
= 0; i
< 4; i
++)
4733 args
[nargs
++] = make_number (ip
[i
]);
4734 args
[nargs
++] = service
;
4741 args
[nargs
++] = procname_format_in6
;
4743 DECLARE_POINTER_ALIAS (ip6
, uint16_t, &saddr
.in6
.sin6_addr
);
4744 service
= make_number (ntohs (saddr
.in
.sin_port
));
4745 for (int i
= 0; i
< 8; i
++)
4746 args
[nargs
++] = make_number (ip6
[i
]);
4747 args
[nargs
++] = service
;
4753 args
[nargs
++] = procname_format_default
;
4755 args
[nargs
++] = make_number (connect_counter
);
4759 /* Create a new buffer name for this process if it doesn't have a
4760 filter. The new buffer name is based on the buffer name or
4761 process name of the server process concatenated with the caller
4764 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4765 || EQ (ps
->filter
, Qt
)))
4769 buffer
= ps
->buffer
;
4771 buffer
= Fbuffer_name (buffer
);
4777 buffer
= Fget_buffer_create (Fformat (nargs
, args
));
4781 /* Generate a unique name for the new server process. Combine the
4782 server process name with the caller identification. */
4785 Lisp_Object name
= Fformat (nargs
, args
);
4786 Lisp_Object proc
= make_process (name
);
4788 chan_process
[s
] = proc
;
4790 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4792 p
= XPROCESS (proc
);
4794 /* Build new contact information for this setup. */
4795 contact
= Fcopy_sequence (ps
->childp
);
4796 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4797 contact
= Fplist_put (contact
, QChost
, host
);
4798 if (!NILP (service
))
4799 contact
= Fplist_put (contact
, QCservice
, service
);
4800 contact
= Fplist_put (contact
, QCremote
,
4801 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4802 #ifdef HAVE_GETSOCKNAME
4804 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4805 contact
= Fplist_put (contact
, QClocal
,
4806 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4809 pset_childp (p
, contact
);
4810 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4811 pset_type (p
, Qnetwork
);
4813 pset_buffer (p
, buffer
);
4814 pset_sentinel (p
, ps
->sentinel
);
4815 pset_filter (p
, ps
->filter
);
4816 eassert (NILP (p
->command
));
4817 eassert (p
->pid
== 0);
4819 /* Discard the unwind protect for closing S. */
4820 specpdl_ptr
= specpdl
+ count
;
4822 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4825 pset_status (p
, Qrun
);
4827 /* Client processes for accepted connections are not stopped initially. */
4828 if (!EQ (p
->filter
, Qt
))
4829 add_process_read_fd (s
);
4833 /* Setup coding system for new process based on server process.
4834 This seems to be the proper thing to do, as the coding system
4835 of the new process should reflect the settings at the time the
4836 server socket was opened; not the current settings. */
4838 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4839 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4840 setup_process_coding_systems (proc
);
4842 pset_decoding_buf (p
, empty_unibyte_string
);
4843 eassert (p
->decoding_carryover
== 0);
4844 pset_encoding_buf (p
, empty_unibyte_string
);
4846 p
->inherit_coding_system_flag
4847 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4849 AUTO_STRING (dash
, "-");
4850 AUTO_STRING (nl
, "\n");
4851 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4853 if (!NILP (ps
->log
))
4855 AUTO_STRING (accept_from
, "accept from ");
4856 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4859 AUTO_STRING (open_from
, "open from ");
4860 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4863 #ifdef HAVE_GETADDRINFO_A
4865 check_for_dns (Lisp_Object proc
)
4867 struct Lisp_Process
*p
= XPROCESS (proc
);
4868 Lisp_Object addrinfos
= Qnil
;
4871 if (! p
->dns_request
)
4874 int ret
= gai_error (p
->dns_request
);
4875 if (ret
== EAI_INPROGRESS
)
4878 /* We got a response. */
4881 struct addrinfo
*res
;
4883 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4884 addrinfos
= Fcons (conv_addrinfo_to_lisp (res
), addrinfos
);
4886 addrinfos
= Fnreverse (addrinfos
);
4888 /* The DNS lookup failed. */
4889 else if (connecting_status (p
->status
))
4891 deactivate_process (proc
);
4892 pset_status (p
, (list2
4894 concat3 (build_string ("Name lookup of "),
4895 build_string (p
->dns_request
->ar_name
),
4896 build_string (" failed")))));
4899 free_dns_request (proc
);
4901 /* This process should not already be connected (or killed). */
4902 if (! connecting_status (p
->status
))
4908 #endif /* HAVE_GETADDRINFO_A */
4911 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4913 while (XPROCESS (process
)->infd
< 0
4914 && connecting_status (XPROCESS (process
)->status
))
4916 add_to_log ("Waiting for socket from %s...", build_string (name
));
4917 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4922 wait_while_connecting (Lisp_Object process
)
4924 while (connecting_status (XPROCESS (process
)->status
))
4926 add_to_log ("Waiting for connection...");
4927 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4932 wait_for_tls_negotiation (Lisp_Object process
)
4935 while (XPROCESS (process
)->gnutls_p
4936 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4938 add_to_log ("Waiting for TLS...");
4939 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4945 wait_reading_process_output_unwind (int data
)
4947 clear_waiting_thread_info ();
4948 waiting_for_user_input_p
= data
;
4951 /* This is here so breakpoints can be put on it. */
4953 wait_reading_process_output_1 (void)
4957 /* Read and dispose of subprocess output while waiting for timeout to
4958 elapse and/or keyboard input to be available.
4962 If negative, gobble data immediately available but don't wait for any.
4965 an additional duration to wait, measured in nanoseconds
4966 If TIME_LIMIT is zero, then:
4967 If NSECS == 0, there is no limit.
4968 If NSECS > 0, the timeout consists of NSECS only.
4969 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4972 0 to ignore keyboard input, or
4973 1 to return when input is available, or
4974 -1 meaning caller will actually read the input, so don't throw to
4977 DO_DISPLAY means redisplay should be done to show subprocess
4978 output that arrives.
4980 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4981 (and gobble terminal input into the buffer if any arrives).
4983 If WAIT_PROC is specified, wait until something arrives from that
4986 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4987 (suspending output from other processes). A negative value
4988 means don't run any timers either.
4990 Return positive if we received input from WAIT_PROC (or from any
4991 process if WAIT_PROC is null), zero if we attempted to receive
4992 input but got none, and negative if we didn't even try. */
4995 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4997 Lisp_Object wait_for_cell
,
4998 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
5008 struct timespec timeout
, end_time
, timer_delay
;
5009 struct timespec got_output_end_time
= invalid_timespec ();
5010 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
5011 int got_some_output
= -1;
5012 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5013 bool retry_for_async
;
5015 ptrdiff_t count
= SPECPDL_INDEX ();
5017 /* Close to the current time if known, an invalid timespec otherwise. */
5018 struct timespec now
= invalid_timespec ();
5020 eassert (wait_proc
== NULL
5021 || EQ (wait_proc
->thread
, Qnil
)
5022 || XTHREAD (wait_proc
->thread
) == current_thread
);
5024 FD_ZERO (&Available
);
5027 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
5028 && !(CONSP (wait_proc
->status
)
5029 && EQ (XCAR (wait_proc
->status
), Qexit
)))
5030 message1 ("Blocking call to accept-process-output with quit inhibited!!");
5032 record_unwind_protect_int (wait_reading_process_output_unwind
,
5033 waiting_for_user_input_p
);
5034 waiting_for_user_input_p
= read_kbd
;
5036 if (TYPE_MAXIMUM (time_t) < time_limit
)
5037 time_limit
= TYPE_MAXIMUM (time_t);
5039 if (time_limit
< 0 || nsecs
< 0)
5041 else if (time_limit
> 0 || nsecs
> 0)
5044 now
= current_timespec ();
5045 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
5052 bool process_skipped
= false;
5054 /* If calling from keyboard input, do not quit
5055 since we want to return C-g as an input character.
5056 Otherwise, do pending quit if requested. */
5059 else if (pending_signals
)
5060 process_pending_signals ();
5062 /* Exit now if the cell we're waiting for became non-nil. */
5063 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5066 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5068 Lisp_Object process_list_head
, aproc
;
5069 struct Lisp_Process
*p
;
5071 retry_for_async
= false;
5072 FOR_EACH_PROCESS(process_list_head
, aproc
)
5074 p
= XPROCESS (aproc
);
5076 if (! wait_proc
|| p
== wait_proc
)
5078 #ifdef HAVE_GETADDRINFO_A
5079 /* Check for pending DNS requests. */
5082 Lisp_Object addrinfos
= check_for_dns (aproc
);
5083 if (!NILP (addrinfos
) && !EQ (addrinfos
, Qt
))
5084 connect_network_socket (aproc
, addrinfos
, Qnil
);
5086 retry_for_async
= true;
5090 /* Continue TLS negotiation. */
5091 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
5092 && p
->is_non_blocking_client
)
5094 gnutls_try_handshake (p
);
5095 p
->gnutls_handshakes_tried
++;
5097 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
5099 gnutls_verify_boot (aproc
, Qnil
);
5100 finish_after_tls_connection (aproc
);
5104 retry_for_async
= true;
5105 if (p
->gnutls_handshakes_tried
5106 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
5108 deactivate_process (aproc
);
5109 pset_status (p
, list2 (Qfailed
,
5110 build_string ("TLS negotiation failed")));
5118 #endif /* GETADDRINFO_A or GNUTLS */
5120 /* Compute time from now till when time limit is up. */
5121 /* Exit if already run out. */
5122 if (wait
== TIMEOUT
)
5124 if (!timespec_valid_p (now
))
5125 now
= current_timespec ();
5126 if (timespec_cmp (end_time
, now
) <= 0)
5128 timeout
= timespec_sub (end_time
, now
);
5131 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
5133 /* Normally we run timers here.
5134 But not if wait_for_cell; in those cases,
5135 the wait is supposed to be short,
5136 and those callers cannot handle running arbitrary Lisp code here. */
5137 if (NILP (wait_for_cell
)
5138 && just_wait_proc
>= 0)
5142 unsigned old_timers_run
= timers_run
;
5143 struct buffer
*old_buffer
= current_buffer
;
5144 Lisp_Object old_window
= selected_window
;
5146 timer_delay
= timer_check ();
5148 /* If a timer has run, this might have changed buffers
5149 an alike. Make read_key_sequence aware of that. */
5150 if (timers_run
!= old_timers_run
5151 && (old_buffer
!= current_buffer
5152 || !EQ (old_window
, selected_window
))
5153 && waiting_for_user_input_p
== -1)
5154 record_asynch_buffer_change ();
5156 if (timers_run
!= old_timers_run
&& do_display
)
5157 /* We must retry, since a timer may have requeued itself
5158 and that could alter the time_delay. */
5159 redisplay_preserve_echo_area (9);
5163 while (!detect_input_pending ());
5165 /* If there is unread keyboard input, also return. */
5167 && requeued_events_pending_p ())
5170 /* This is so a breakpoint can be put here. */
5171 if (!timespec_valid_p (timer_delay
))
5172 wait_reading_process_output_1 ();
5175 /* Cause C-g and alarm signals to take immediate action,
5176 and cause input available signals to zero out timeout.
5178 It is important that we do this before checking for process
5179 activity. If we get a SIGCHLD after the explicit checks for
5180 process activity, timeout is the only way we will know. */
5182 set_waiting_for_input (&timeout
);
5184 /* If status of something has changed, and no input is
5185 available, notify the user of the change right away. After
5186 this explicit check, we'll let the SIGCHLD handler zap
5187 timeout to get our attention. */
5188 if (update_tick
!= process_tick
)
5193 if (kbd_on_hold_p ())
5196 compute_input_wait_mask (&Atemp
);
5197 compute_write_mask (&Ctemp
);
5199 timeout
= make_timespec (0, 0);
5200 if ((thread_select (pselect
, max_desc
+ 1,
5202 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5203 NULL
, &timeout
, NULL
)
5206 /* It's okay for us to do this and then continue with
5207 the loop, since timeout has already been zeroed out. */
5208 clear_waiting_for_input ();
5209 got_some_output
= status_notify (NULL
, wait_proc
);
5210 if (do_display
) redisplay_preserve_echo_area (13);
5214 /* Don't wait for output from a non-running process. Just
5215 read whatever data has already been received. */
5216 if (wait_proc
&& wait_proc
->raw_status_new
)
5217 update_status (wait_proc
);
5219 && ! EQ (wait_proc
->status
, Qrun
)
5220 && ! connecting_status (wait_proc
->status
))
5222 bool read_some_bytes
= false;
5224 clear_waiting_for_input ();
5226 /* If data can be read from the process, do so until exhausted. */
5227 if (wait_proc
->infd
>= 0)
5229 XSETPROCESS (proc
, wait_proc
);
5233 int nread
= read_process_output (proc
, wait_proc
->infd
);
5236 if (errno
== EIO
|| would_block (errno
))
5241 if (got_some_output
< nread
)
5242 got_some_output
= nread
;
5245 read_some_bytes
= true;
5250 if (read_some_bytes
&& do_display
)
5251 redisplay_preserve_echo_area (10);
5256 /* Wait till there is something to do. */
5258 if (wait_proc
&& just_wait_proc
)
5260 if (wait_proc
->infd
< 0) /* Terminated. */
5262 FD_SET (wait_proc
->infd
, &Available
);
5266 else if (!NILP (wait_for_cell
))
5268 compute_non_process_wait_mask (&Available
);
5275 compute_non_keyboard_wait_mask (&Available
);
5277 compute_input_wait_mask (&Available
);
5278 compute_write_mask (&Writeok
);
5279 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5283 /* If frame size has changed or the window is newly mapped,
5284 redisplay now, before we start to wait. There is a race
5285 condition here; if a SIGIO arrives between now and the select
5286 and indicates that a frame is trashed, the select may block
5287 displaying a trashed screen. */
5288 if (frame_garbaged
&& do_display
)
5290 clear_waiting_for_input ();
5291 redisplay_preserve_echo_area (11);
5293 set_waiting_for_input (&timeout
);
5296 /* Skip the `select' call if input is available and we're
5297 waiting for keyboard input or a cell change (which can be
5298 triggered by processing X events). In the latter case, set
5299 nfds to 1 to avoid breaking the loop. */
5301 if ((read_kbd
|| !NILP (wait_for_cell
))
5302 && detect_input_pending ())
5304 nfds
= read_kbd
? 0 : 1;
5306 FD_ZERO (&Available
);
5310 /* Set the timeout for adaptive read buffering if any
5311 process has non-zero read_output_skip and non-zero
5312 read_output_delay, and we are not reading output for a
5313 specific process. It is not executed if
5314 Vprocess_adaptive_read_buffering is nil. */
5315 if (process_output_skip
&& check_delay
> 0)
5317 int adaptive_nsecs
= timeout
.tv_nsec
;
5318 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5319 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5320 for (channel
= 0; check_delay
> 0 && channel
<= max_desc
; channel
++)
5322 proc
= chan_process
[channel
];
5325 /* Find minimum non-zero read_output_delay among the
5326 processes with non-zero read_output_skip. */
5327 if (XPROCESS (proc
)->read_output_delay
> 0)
5330 if (!XPROCESS (proc
)->read_output_skip
)
5332 FD_CLR (channel
, &Available
);
5333 process_skipped
= true;
5334 XPROCESS (proc
)->read_output_skip
= 0;
5335 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5336 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5339 timeout
= make_timespec (0, adaptive_nsecs
);
5340 process_output_skip
= 0;
5343 /* If we've got some output and haven't limited our timeout
5344 with adaptive read buffering, limit it. */
5345 if (got_some_output
> 0 && !process_skipped
5347 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5348 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5351 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5352 && timespec_valid_p (timer_delay
)
5353 && timespec_cmp (timer_delay
, timeout
) < 0)
5355 if (!timespec_valid_p (now
))
5356 now
= current_timespec ();
5357 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5358 if (!timespec_valid_p (got_output_end_time
)
5359 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5360 got_output_end_time
= timeout_abs
;
5361 timeout
= timer_delay
;
5364 got_output_end_time
= invalid_timespec ();
5366 /* NOW can become inaccurate if time can pass during pselect. */
5367 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5368 now
= invalid_timespec ();
5370 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5372 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5375 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5379 /* Non-macOS HAVE_GLIB builds call thread_select in xgselect.c. */
5380 #if defined HAVE_GLIB && !defined HAVE_NS
5381 nfds
= xg_select (max_desc
+ 1,
5382 &Available
, (check_write
? &Writeok
: 0),
5383 NULL
, &timeout
, NULL
);
5384 #elif defined HAVE_NS
5385 /* And NS builds call thread_select in ns_select. */
5386 nfds
= ns_select (max_desc
+ 1,
5387 &Available
, (check_write
? &Writeok
: 0),
5388 NULL
, &timeout
, NULL
);
5389 #else /* !HAVE_GLIB */
5390 nfds
= thread_select (pselect
, max_desc
+ 1,
5392 (check_write
? &Writeok
: 0),
5393 NULL
, &timeout
, NULL
);
5394 #endif /* !HAVE_GLIB */
5397 /* GnuTLS buffers data internally. In lowat mode it leaves
5398 some data in the TCP buffers so that select works, but
5399 with custom pull/push functions we need to check if some
5400 data is available in the buffers manually. */
5403 fd_set tls_available
;
5406 FD_ZERO (&tls_available
);
5409 /* We're not waiting on a specific process, so loop
5410 through all the channels and check for data.
5411 This is a workaround needed for some versions of
5412 the gnutls library -- 2.12.14 has been confirmed
5414 http://comments.gmane.org/gmane.emacs.devel/145074 */
5415 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5416 if (! NILP (chan_process
[channel
]))
5418 struct Lisp_Process
*p
=
5419 XPROCESS (chan_process
[channel
]);
5420 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5421 && ((emacs_gnutls_record_check_pending
5426 eassert (p
->infd
== channel
);
5427 FD_SET (p
->infd
, &tls_available
);
5434 /* Check this specific channel. */
5435 if (wait_proc
->gnutls_p
/* Check for valid process. */
5436 && wait_proc
->gnutls_state
5437 /* Do we have pending data? */
5438 && ((emacs_gnutls_record_check_pending
5439 (wait_proc
->gnutls_state
))
5443 eassert (0 <= wait_proc
->infd
);
5444 /* Set to Available. */
5445 FD_SET (wait_proc
->infd
, &tls_available
);
5450 Available
= tls_available
;
5457 /* Make C-g and alarm signals set flags again. */
5458 clear_waiting_for_input ();
5460 /* If we woke up due to SIGWINCH, actually change size now. */
5461 do_pending_window_change (0);
5465 /* Exit the main loop if we've passed the requested timeout,
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 if (wait
== TIMEOUT
)
5476 cmp_time
= end_time
;
5477 if (!process_skipped
&& got_some_output
> 0
5478 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5480 if (!timespec_valid_p (got_output_end_time
))
5482 if (timespec_cmp (got_output_end_time
, cmp_time
) < 0)
5483 cmp_time
= got_output_end_time
;
5485 if (timespec_cmp (cmp_time
, huge_timespec
) < 0)
5487 now
= current_timespec ();
5488 if (timespec_cmp (cmp_time
, now
) <= 0)
5495 if (xerrno
== EINTR
)
5497 else if (xerrno
== EBADF
)
5500 report_file_errno ("Failed select", Qnil
, xerrno
);
5503 /* Check for keyboard input. */
5504 /* If there is any, return immediately
5505 to give it higher priority than subprocesses. */
5509 unsigned old_timers_run
= timers_run
;
5510 struct buffer
*old_buffer
= current_buffer
;
5511 Lisp_Object old_window
= selected_window
;
5514 if (detect_input_pending_run_timers (do_display
))
5516 swallow_events (do_display
);
5517 if (detect_input_pending_run_timers (do_display
))
5521 /* If a timer has run, this might have changed buffers
5522 an alike. Make read_key_sequence aware of that. */
5523 if (timers_run
!= old_timers_run
5524 && waiting_for_user_input_p
== -1
5525 && (old_buffer
!= current_buffer
5526 || !EQ (old_window
, selected_window
)))
5527 record_asynch_buffer_change ();
5533 /* If there is unread keyboard input, also return. */
5535 && requeued_events_pending_p ())
5538 /* If we are not checking for keyboard input now,
5539 do process events (but don't run any timers).
5540 This is so that X events will be processed.
5541 Otherwise they may have to wait until polling takes place.
5542 That would causes delays in pasting selections, for example.
5544 (We used to do this only if wait_for_cell.) */
5545 if (read_kbd
== 0 && detect_input_pending ())
5547 swallow_events (do_display
);
5548 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5549 if (detect_input_pending ())
5554 /* Exit now if the cell we're waiting for became non-nil. */
5555 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5559 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5560 go read it. This can happen with X on BSD after logging out.
5561 In that case, there really is no input and no SIGIO,
5562 but select says there is input. */
5564 if (read_kbd
&& interrupt_input
5565 && keyboard_bit_set (&Available
) && ! noninteractive
)
5566 handle_input_available_signal (SIGIO
);
5569 /* If checking input just got us a size-change event from X,
5570 obey it now if we should. */
5571 if (read_kbd
|| ! NILP (wait_for_cell
))
5572 do_pending_window_change (0);
5574 /* Check for data from a process. */
5575 if (no_avail
|| nfds
== 0)
5578 for (channel
= 0; channel
<= max_desc
; ++channel
)
5580 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5582 && ((d
->flags
& FOR_READ
5583 && FD_ISSET (channel
, &Available
))
5584 || ((d
->flags
& FOR_WRITE
)
5585 && FD_ISSET (channel
, &Writeok
))))
5586 d
->func (channel
, d
->data
);
5589 for (channel
= 0; channel
<= max_desc
; channel
++)
5591 if (FD_ISSET (channel
, &Available
)
5592 && ((fd_callback_info
[channel
].flags
& (KEYBOARD_FD
| PROCESS_FD
))
5597 /* If waiting for this channel, arrange to return as
5598 soon as no more input to be processed. No more
5600 proc
= chan_process
[channel
];
5604 /* If this is a server stream socket, accept connection. */
5605 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5607 server_accept_connection (proc
, channel
);
5611 /* Read data from the process, starting with our
5612 buffered-ahead character if we have one. */
5614 nread
= read_process_output (proc
, channel
);
5615 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5616 && got_some_output
< nread
)
5617 got_some_output
= nread
;
5620 /* Vacuum up any leftovers without waiting. */
5621 if (wait_proc
== XPROCESS (proc
))
5623 /* Since read_process_output can run a filter,
5624 which can call accept-process-output,
5625 don't try to read from any other processes
5626 before doing the select again. */
5627 FD_ZERO (&Available
);
5630 redisplay_preserve_echo_area (12);
5632 else if (nread
== -1 && would_block (errno
))
5635 /* FIXME: Is this special case still needed? */
5636 /* Note that we cannot distinguish between no input
5637 available now and a closed pipe.
5638 With luck, a closed pipe will be accompanied by
5639 subprocess termination and SIGCHLD. */
5640 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5641 && !PIPECONN_P (proc
))
5645 /* On some OSs with ptys, when the process on one end of
5646 a pty exits, the other end gets an error reading with
5647 errno = EIO instead of getting an EOF (0 bytes read).
5648 Therefore, if we get an error reading and errno =
5649 EIO, just continue, because the child process has
5650 exited and should clean itself up soon (e.g. when we
5652 else if (nread
== -1 && errno
== EIO
)
5654 struct Lisp_Process
*p
= XPROCESS (proc
);
5656 /* Clear the descriptor now, so we only raise the
5658 delete_read_fd (channel
);
5662 /* If the EIO occurs on a pty, the SIGCHLD handler's
5663 waitpid call will not find the process object to
5664 delete. Do it here. */
5665 p
->tick
= ++process_tick
;
5666 pset_status (p
, Qfailed
);
5669 #endif /* HAVE_PTYS */
5670 /* If we can detect process termination, don't consider the
5671 process gone just because its pipe is closed. */
5672 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5673 && !PIPECONN_P (proc
))
5675 else if (nread
== 0 && PIPECONN_P (proc
))
5677 /* Preserve status of processes already terminated. */
5678 XPROCESS (proc
)->tick
= ++process_tick
;
5679 deactivate_process (proc
);
5680 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5681 pset_status (XPROCESS (proc
),
5682 list2 (Qexit
, make_number (0)));
5686 /* Preserve status of processes already terminated. */
5687 XPROCESS (proc
)->tick
= ++process_tick
;
5688 deactivate_process (proc
);
5689 if (XPROCESS (proc
)->raw_status_new
)
5690 update_status (XPROCESS (proc
));
5691 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5692 pset_status (XPROCESS (proc
),
5693 list2 (Qexit
, make_number (256)));
5696 if (FD_ISSET (channel
, &Writeok
)
5697 && (fd_callback_info
[channel
].flags
5698 & NON_BLOCKING_CONNECT_FD
) != 0)
5700 struct Lisp_Process
*p
;
5702 delete_write_fd (channel
);
5704 proc
= chan_process
[channel
];
5708 p
= XPROCESS (proc
);
5712 socklen_t xlen
= sizeof (xerrno
);
5713 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5717 /* On MS-Windows, getsockopt clears the error for the
5718 entire process, which may not be the right thing; see
5719 w32.c. Use getpeername instead. */
5721 struct sockaddr pname
;
5722 socklen_t pnamelen
= sizeof (pname
);
5724 /* If connection failed, getpeername will fail. */
5726 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5728 /* Obtain connect failure code through error slippage. */
5731 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5738 Lisp_Object addrinfos
5739 = connecting_status (p
->status
) ? XCDR (p
->status
) : Qnil
;
5740 if (!NILP (addrinfos
))
5741 XSETCDR (p
->status
, XCDR (addrinfos
));
5744 p
->tick
= ++process_tick
;
5745 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5747 deactivate_process (proc
);
5748 if (!NILP (addrinfos
))
5749 connect_network_socket (proc
, addrinfos
, Qnil
);
5754 /* If we have an incompletely set up TLS connection,
5755 then defer the sentinel signaling until
5757 if (NILP (p
->gnutls_boot_parameters
)
5761 pset_status (p
, Qrun
);
5762 /* Execute the sentinel here. If we had relied on
5763 status_notify to do it later, it will read input
5764 from the process before calling the sentinel. */
5765 exec_sentinel (proc
, build_string ("open\n"));
5768 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5769 && !EQ (p
->command
, Qt
))
5770 add_process_read_fd (p
->infd
);
5773 } /* End for each file descriptor. */
5774 } /* End while exit conditions not met. */
5776 unbind_to (count
, Qnil
);
5778 /* If calling from keyboard input, do not quit
5779 since we want to return C-g as an input character.
5780 Otherwise, do pending quit if requested. */
5783 /* Prevent input_pending from remaining set if we quit. */
5784 clear_input_pending ();
5788 return got_some_output
;
5791 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5794 read_process_output_call (Lisp_Object fun_and_args
)
5796 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5800 read_process_output_error_handler (Lisp_Object error_val
)
5802 cmd_error_internal (error_val
, "error in process filter: ");
5804 update_echo_area ();
5805 Fsleep_for (make_number (2), Qnil
);
5810 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5812 struct coding_system
*coding
);
5814 /* Read pending output from the process channel,
5815 starting with our buffered-ahead character if we have one.
5816 Yield number of decoded characters read.
5818 This function reads at most 4096 characters.
5819 If you want to read all available subprocess output,
5820 you must call it repeatedly until it returns zero.
5822 The characters read are decoded according to PROC's coding-system
5826 read_process_output (Lisp_Object proc
, int channel
)
5829 struct Lisp_Process
*p
= XPROCESS (proc
);
5830 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5831 int carryover
= p
->decoding_carryover
;
5832 enum { readmax
= 4096 };
5833 ptrdiff_t count
= SPECPDL_INDEX ();
5834 Lisp_Object odeactivate
;
5835 char chars
[sizeof coding
->carryover
+ readmax
];
5838 /* See the comment above. */
5839 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5841 #ifdef DATAGRAM_SOCKETS
5842 /* We have a working select, so proc_buffered_char is always -1. */
5843 if (DATAGRAM_CHAN_P (channel
))
5845 socklen_t len
= datagram_address
[channel
].len
;
5846 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5847 0, datagram_address
[channel
].sa
, &len
);
5852 bool buffered
= proc_buffered_char
[channel
] >= 0;
5855 chars
[carryover
] = proc_buffered_char
[channel
];
5856 proc_buffered_char
[channel
] = -1;
5859 if (p
->gnutls_p
&& p
->gnutls_state
)
5860 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5861 readmax
- buffered
);
5864 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5865 readmax
- buffered
);
5866 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5868 int delay
= p
->read_output_delay
;
5871 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5874 process_output_delay_count
++;
5875 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5878 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5880 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5882 process_output_delay_count
--;
5884 p
->read_output_delay
= delay
;
5887 p
->read_output_skip
= 1;
5888 process_output_skip
= 1;
5892 nbytes
+= buffered
&& nbytes
<= 0;
5895 p
->decoding_carryover
= 0;
5897 /* At this point, NBYTES holds number of bytes just received
5898 (including the one in proc_buffered_char[channel]). */
5901 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5903 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5906 /* Now set NBYTES how many bytes we must decode. */
5907 nbytes
+= carryover
;
5909 odeactivate
= Vdeactivate_mark
;
5910 /* There's no good reason to let process filters change the current
5911 buffer, and many callers of accept-process-output, sit-for, and
5912 friends don't expect current-buffer to be changed from under them. */
5913 record_unwind_current_buffer ();
5915 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5917 /* Handling the process output should not deactivate the mark. */
5918 Vdeactivate_mark
= odeactivate
;
5920 unbind_to (count
, Qnil
);
5925 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5927 struct coding_system
*coding
)
5929 Lisp_Object outstream
= p
->filter
;
5931 bool outer_running_asynch_code
= running_asynch_code
;
5932 int waiting
= waiting_for_user_input_p
;
5935 Lisp_Object obuffer
, okeymap
;
5936 XSETBUFFER (obuffer
, current_buffer
);
5937 okeymap
= BVAR (current_buffer
, keymap
);
5940 /* We inhibit quit here instead of just catching it so that
5941 hitting ^G when a filter happens to be running won't screw
5943 specbind (Qinhibit_quit
, Qt
);
5944 specbind (Qlast_nonmenu_event
, Qt
);
5946 /* In case we get recursively called,
5947 and we already saved the match data nonrecursively,
5948 save the same match data in safely recursive fashion. */
5949 if (outer_running_asynch_code
)
5952 /* Don't clobber the CURRENT match data, either! */
5953 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5954 restore_search_regs ();
5955 record_unwind_save_match_data ();
5956 Fset_match_data (tem
, Qt
);
5959 /* For speed, if a search happens within this code,
5960 save the match data in a special nonrecursive fashion. */
5961 running_asynch_code
= 1;
5963 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5964 text
= coding
->dst_object
;
5965 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5966 /* A new coding system might be found. */
5967 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5969 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5971 /* Don't call setup_coding_system for
5972 proc_decode_coding_system[channel] here. It is done in
5973 detect_coding called via decode_coding above. */
5975 /* If a coding system for encoding is not yet decided, we set
5976 it as the same as coding-system for decoding.
5978 But, before doing that we must check if
5979 proc_encode_coding_system[p->outfd] surely points to a
5980 valid memory because p->outfd will be changed once EOF is
5981 sent to the process. */
5982 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5983 && proc_encode_coding_system
[p
->outfd
])
5985 pset_encode_coding_system
5986 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5987 setup_coding_system (p
->encode_coding_system
,
5988 proc_encode_coding_system
[p
->outfd
]);
5992 if (coding
->carryover_bytes
> 0)
5994 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5995 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5996 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5997 coding
->carryover_bytes
);
5998 p
->decoding_carryover
= coding
->carryover_bytes
;
6000 if (SBYTES (text
) > 0)
6001 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
6002 sometimes it's simply wrong to wrap (e.g. when called from
6003 accept-process-output). */
6004 internal_condition_case_1 (read_process_output_call
,
6005 list3 (outstream
, make_lisp_proc (p
), text
),
6006 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6007 read_process_output_error_handler
);
6009 /* If we saved the match data nonrecursively, restore it now. */
6010 restore_search_regs ();
6011 running_asynch_code
= outer_running_asynch_code
;
6013 /* Restore waiting_for_user_input_p as it was
6014 when we were called, in case the filter clobbered it. */
6015 waiting_for_user_input_p
= waiting
;
6017 #if 0 /* Call record_asynch_buffer_change unconditionally,
6018 because we might have changed minor modes or other things
6019 that affect key bindings. */
6020 if (! EQ (Fcurrent_buffer (), obuffer
)
6021 || ! EQ (current_buffer
->keymap
, okeymap
))
6023 /* But do it only if the caller is actually going to read events.
6024 Otherwise there's no need to make him wake up, and it could
6025 cause trouble (for example it would make sit_for return). */
6026 if (waiting_for_user_input_p
== -1)
6027 record_asynch_buffer_change ();
6030 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
6031 Sinternal_default_process_filter
, 2, 2, 0,
6032 doc
: /* Function used as default process filter.
6033 This inserts the process's output into its buffer, if there is one.
6034 Otherwise it discards the output. */)
6035 (Lisp_Object proc
, Lisp_Object text
)
6037 struct Lisp_Process
*p
;
6040 CHECK_PROCESS (proc
);
6041 p
= XPROCESS (proc
);
6042 CHECK_STRING (text
);
6044 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
6046 Lisp_Object old_read_only
;
6047 ptrdiff_t old_begv
, old_zv
;
6048 ptrdiff_t old_begv_byte
, old_zv_byte
;
6049 ptrdiff_t before
, before_byte
;
6050 ptrdiff_t opoint_byte
;
6053 Fset_buffer (p
->buffer
);
6055 opoint_byte
= PT_BYTE
;
6056 old_read_only
= BVAR (current_buffer
, read_only
);
6059 old_begv_byte
= BEGV_BYTE
;
6060 old_zv_byte
= ZV_BYTE
;
6062 bset_read_only (current_buffer
, Qnil
);
6064 /* Insert new output into buffer at the current end-of-output
6065 marker, thus preserving logical ordering of input and output. */
6066 if (XMARKER (p
->mark
)->buffer
)
6067 set_point_from_marker (p
->mark
);
6069 SET_PT_BOTH (ZV
, ZV_BYTE
);
6071 before_byte
= PT_BYTE
;
6073 /* If the output marker is outside of the visible region, save
6074 the restriction and widen. */
6075 if (! (BEGV
<= PT
&& PT
<= ZV
))
6078 /* Adjust the multibyteness of TEXT to that of the buffer. */
6079 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
6080 != ! STRING_MULTIBYTE (text
))
6081 text
= (STRING_MULTIBYTE (text
)
6082 ? Fstring_as_unibyte (text
)
6083 : Fstring_to_multibyte (text
));
6084 /* Insert before markers in case we are inserting where
6085 the buffer's mark is, and the user's next command is Meta-y. */
6086 insert_from_string_before_markers (text
, 0, 0,
6087 SCHARS (text
), SBYTES (text
), 0);
6089 /* Make sure the process marker's position is valid when the
6090 process buffer is changed in the signal_after_change above.
6091 W3 is known to do that. */
6092 if (BUFFERP (p
->buffer
)
6093 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
6094 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
6096 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6098 update_mode_lines
= 23;
6100 /* Make sure opoint and the old restrictions
6101 float ahead of any new text just as point would. */
6102 if (opoint
>= before
)
6104 opoint
+= PT
- before
;
6105 opoint_byte
+= PT_BYTE
- before_byte
;
6107 if (old_begv
> before
)
6109 old_begv
+= PT
- before
;
6110 old_begv_byte
+= PT_BYTE
- before_byte
;
6112 if (old_zv
>= before
)
6114 old_zv
+= PT
- before
;
6115 old_zv_byte
+= PT_BYTE
- before_byte
;
6118 /* If the restriction isn't what it should be, set it. */
6119 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
6120 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
6122 bset_read_only (current_buffer
, old_read_only
);
6123 SET_PT_BOTH (opoint
, opoint_byte
);
6128 /* Sending data to subprocess. */
6130 /* In send_process, when a write fails temporarily,
6131 wait_reading_process_output is called. It may execute user code,
6132 e.g. timers, that attempts to write new data to the same process.
6133 We must ensure that data is sent in the right order, and not
6134 interspersed half-completed with other writes (Bug#10815). This is
6135 handled by the write_queue element of struct process. It is a list
6136 with each entry having the form
6138 (string . (offset . length))
6140 where STRING is a lisp string, OFFSET is the offset into the
6141 string's byte sequence from which we should begin to send, and
6142 LENGTH is the number of bytes left to send. */
6144 /* Create a new entry in write_queue.
6145 INPUT_OBJ should be a buffer, string Qt, or Qnil.
6146 BUF is a pointer to the string sequence of the input_obj or a C
6147 string in case of Qt or Qnil. */
6150 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
6151 const char *buf
, ptrdiff_t len
, bool front
)
6154 Lisp_Object entry
, obj
;
6156 if (STRINGP (input_obj
))
6158 offset
= buf
- SSDATA (input_obj
);
6164 obj
= make_unibyte_string (buf
, len
);
6167 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
6170 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
6172 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
6175 /* Remove the first element in the write_queue of process P, put its
6176 contents in OBJ, BUF and LEN, and return true. If the
6177 write_queue is empty, return false. */
6180 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
6181 const char **buf
, ptrdiff_t *len
)
6183 Lisp_Object entry
, offset_length
;
6186 if (NILP (p
->write_queue
))
6189 entry
= XCAR (p
->write_queue
);
6190 pset_write_queue (p
, XCDR (p
->write_queue
));
6192 *obj
= XCAR (entry
);
6193 offset_length
= XCDR (entry
);
6195 *len
= XINT (XCDR (offset_length
));
6196 offset
= XINT (XCAR (offset_length
));
6197 *buf
= SSDATA (*obj
) + offset
;
6202 /* Send some data to process PROC.
6203 BUF is the beginning of the data; LEN is the number of characters.
6204 OBJECT is the Lisp object that the data comes from. If OBJECT is
6205 nil or t, it means that the data comes from C string.
6207 If OBJECT is not nil, the data is encoded by PROC's coding-system
6208 for encoding before it is sent.
6210 This function can evaluate Lisp code and can garbage collect. */
6213 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6216 struct Lisp_Process
*p
= XPROCESS (proc
);
6218 struct coding_system
*coding
;
6220 if (NETCONN_P (proc
))
6222 wait_while_connecting (proc
);
6223 wait_for_tls_negotiation (proc
);
6226 if (p
->raw_status_new
)
6228 if (! EQ (p
->status
, Qrun
))
6229 error ("Process %s not running", SDATA (p
->name
));
6231 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6233 coding
= proc_encode_coding_system
[p
->outfd
];
6234 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6236 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6237 || (BUFFERP (object
)
6238 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6241 pset_encode_coding_system
6242 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6243 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6245 /* The coding system for encoding was changed to raw-text
6246 because we sent a unibyte text previously. Now we are
6247 sending a multibyte text, thus we must encode it by the
6248 original coding system specified for the current process.
6250 Another reason we come here is that the coding system
6251 was just complemented and a new one was returned by
6252 complement_process_encoding_system. */
6253 setup_coding_system (p
->encode_coding_system
, coding
);
6254 Vlast_coding_system_used
= p
->encode_coding_system
;
6256 coding
->src_multibyte
= 1;
6260 coding
->src_multibyte
= 0;
6261 /* For sending a unibyte text, character code conversion should
6262 not take place but EOL conversion should. So, setup raw-text
6263 or one of the subsidiary if we have not yet done it. */
6264 if (CODING_REQUIRE_ENCODING (coding
))
6266 if (CODING_REQUIRE_FLUSHING (coding
))
6268 /* But, before changing the coding, we must flush out data. */
6269 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6270 send_process (proc
, "", 0, Qt
);
6271 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6273 setup_coding_system (raw_text_coding_system
6274 (Vlast_coding_system_used
),
6276 coding
->src_multibyte
= 0;
6279 coding
->dst_multibyte
= 0;
6281 if (CODING_REQUIRE_ENCODING (coding
))
6283 coding
->dst_object
= Qt
;
6284 if (BUFFERP (object
))
6286 ptrdiff_t from_byte
, from
, to
;
6287 ptrdiff_t save_pt
, save_pt_byte
;
6288 struct buffer
*cur
= current_buffer
;
6290 set_buffer_internal (XBUFFER (object
));
6291 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6293 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6294 from
= BYTE_TO_CHAR (from_byte
);
6295 to
= BYTE_TO_CHAR (from_byte
+ len
);
6296 TEMP_SET_PT_BOTH (from
, from_byte
);
6297 encode_coding_object (coding
, object
, from
, from_byte
,
6298 to
, from_byte
+ len
, Qt
);
6299 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6300 set_buffer_internal (cur
);
6302 else if (STRINGP (object
))
6304 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6305 SBYTES (object
), Qt
);
6309 coding
->dst_object
= make_unibyte_string (buf
, len
);
6310 coding
->produced
= len
;
6313 len
= coding
->produced
;
6314 object
= coding
->dst_object
;
6315 buf
= SSDATA (object
);
6318 /* If there is already data in the write_queue, put the new data
6319 in the back of queue. Otherwise, ignore it. */
6320 if (!NILP (p
->write_queue
))
6321 write_queue_push (p
, object
, buf
, len
, 0);
6323 do /* while !NILP (p->write_queue) */
6325 ptrdiff_t cur_len
= -1;
6326 const char *cur_buf
;
6327 Lisp_Object cur_object
;
6329 /* If write_queue is empty, ignore it. */
6330 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6334 cur_object
= object
;
6339 /* Send this batch, using one or more write calls. */
6340 ptrdiff_t written
= 0;
6341 int outfd
= p
->outfd
;
6342 #ifdef DATAGRAM_SOCKETS
6343 if (DATAGRAM_CHAN_P (outfd
))
6345 rv
= sendto (outfd
, cur_buf
, cur_len
,
6346 0, datagram_address
[outfd
].sa
,
6347 datagram_address
[outfd
].len
);
6350 else if (errno
== EMSGSIZE
)
6351 report_file_error ("Sending datagram", proc
);
6357 if (p
->gnutls_p
&& p
->gnutls_state
)
6358 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6361 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6362 rv
= (written
? 0 : -1);
6363 if (p
->read_output_delay
> 0
6364 && p
->adaptive_read_buffering
== 1)
6366 p
->read_output_delay
= 0;
6367 process_output_delay_count
--;
6368 p
->read_output_skip
= 0;
6374 if (would_block (errno
))
6375 /* Buffer is full. Wait, accepting input;
6376 that may allow the program
6377 to finish doing output and read more. */
6379 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6380 /* A gross hack to work around a bug in FreeBSD.
6381 In the following sequence, read(2) returns
6385 write(2) 954 bytes, get EAGAIN
6386 read(2) 1024 bytes in process_read_output
6387 read(2) 11 bytes in process_read_output
6389 That is, read(2) returns more bytes than have
6390 ever been written successfully. The 1033 bytes
6391 read are the 1022 bytes written successfully
6392 after processing (for example with CRs added if
6393 the terminal is set up that way which it is
6394 here). The same bytes will be seen again in a
6395 later read(2), without the CRs. */
6397 if (errno
== EAGAIN
)
6400 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6402 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6404 /* Put what we should have written in wait_queue. */
6405 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6406 wait_reading_process_output (0, 20 * 1000 * 1000,
6407 0, 0, Qnil
, NULL
, 0);
6408 /* Reread queue, to see what is left. */
6411 else if (errno
== EPIPE
)
6413 p
->raw_status_new
= 0;
6414 pset_status (p
, list2 (Qexit
, make_number (256)));
6415 p
->tick
= ++process_tick
;
6416 deactivate_process (proc
);
6417 error ("process %s no longer connected to pipe; closed it",
6421 /* This is a real error. */
6422 report_file_error ("Writing to process", proc
);
6428 while (!NILP (p
->write_queue
));
6431 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6433 doc
: /* Send current contents of region as input to PROCESS.
6434 PROCESS may be a process, a buffer, the name of a process or buffer, or
6435 nil, indicating the current buffer's process.
6436 Called from program, takes three arguments, PROCESS, START and END.
6437 If the region is more than 500 characters long,
6438 it is sent in several bunches. This may happen even for shorter regions.
6439 Output from processes can arrive in between bunches.
6441 If PROCESS is a non-blocking network process that hasn't been fully
6442 set up yet, this function will block until socket setup has completed. */)
6443 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6445 Lisp_Object proc
= get_process (process
);
6446 ptrdiff_t start_byte
, end_byte
;
6448 validate_region (&start
, &end
);
6450 start_byte
= CHAR_TO_BYTE (XINT (start
));
6451 end_byte
= CHAR_TO_BYTE (XINT (end
));
6453 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6454 move_gap_both (XINT (start
), start_byte
);
6456 if (NETCONN_P (proc
))
6457 wait_while_connecting (proc
);
6459 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6460 end_byte
- start_byte
, Fcurrent_buffer ());
6465 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6467 doc
: /* Send PROCESS the contents of STRING as input.
6468 PROCESS may be a process, a buffer, the name of a process or buffer, or
6469 nil, indicating the current buffer's process.
6470 If STRING is more than 500 characters long,
6471 it is sent in several bunches. This may happen even for shorter strings.
6472 Output from processes can arrive in between bunches.
6474 If PROCESS is a non-blocking network process that hasn't been fully
6475 set up yet, this function will block until socket setup has completed. */)
6476 (Lisp_Object process
, Lisp_Object string
)
6478 CHECK_STRING (string
);
6479 Lisp_Object proc
= get_process (process
);
6480 send_process (proc
, SSDATA (string
),
6481 SBYTES (string
), string
);
6485 /* Return the foreground process group for the tty/pty that
6486 the process P uses. */
6488 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6493 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6496 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6497 master side. Try the slave side. */
6498 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6502 ioctl (fd
, TIOCGPGRP
, &gid
);
6506 #endif /* defined (TIOCGPGRP ) */
6511 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6512 Sprocess_running_child_p
, 0, 1, 0,
6513 doc
: /* Return non-nil if PROCESS has given the terminal to a
6514 child. If the operating system does not make it possible to find out,
6515 return t. If we can find out, return the numeric ID of the foreground
6517 (Lisp_Object process
)
6519 /* Initialize in case ioctl doesn't exist or gives an error,
6520 in a way that will cause returning t. */
6521 Lisp_Object proc
= get_process (process
);
6522 struct Lisp_Process
*p
= XPROCESS (proc
);
6524 if (!EQ (p
->type
, Qreal
))
6525 error ("Process %s is not a subprocess",
6528 error ("Process %s is not active",
6531 pid_t gid
= emacs_get_tty_pgrp (p
);
6536 return make_number (gid
);
6540 /* Send a signal number SIGNO to PROCESS.
6541 If CURRENT_GROUP is t, that means send to the process group
6542 that currently owns the terminal being used to communicate with PROCESS.
6543 This is used for various commands in shell mode.
6544 If CURRENT_GROUP is lambda, that means send to the process group
6545 that currently owns the terminal, but only if it is NOT the shell itself.
6547 If NOMSG is false, insert signal-announcements into process's buffers
6550 If we can, we try to signal PROCESS by sending control characters
6551 down the pty. This allows us to signal inferiors who have changed
6552 their uid, for which kill would return an EPERM error. */
6555 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6559 struct Lisp_Process
*p
;
6563 proc
= get_process (process
);
6564 p
= XPROCESS (proc
);
6566 if (!EQ (p
->type
, Qreal
))
6567 error ("Process %s is not a subprocess",
6570 error ("Process %s is not active",
6574 current_group
= Qnil
;
6576 /* If we are using pgrps, get a pgrp number and make it negative. */
6577 if (NILP (current_group
))
6578 /* Send the signal to the shell's process group. */
6582 #ifdef SIGNALS_VIA_CHARACTERS
6583 /* If possible, send signals to the entire pgrp
6584 by sending an input character to it. */
6587 cc_t
*sig_char
= NULL
;
6589 tcgetattr (p
->infd
, &t
);
6594 sig_char
= &t
.c_cc
[VINTR
];
6598 sig_char
= &t
.c_cc
[VQUIT
];
6603 sig_char
= &t
.c_cc
[VSWTCH
];
6605 sig_char
= &t
.c_cc
[VSUSP
];
6610 if (sig_char
&& *sig_char
!= CDISABLE
)
6612 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6615 /* If we can't send the signal with a character,
6616 fall through and send it another way. */
6618 /* The code above may fall through if it can't
6619 handle the signal. */
6620 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6623 /* Get the current pgrp using the tty itself, if we have that.
6624 Otherwise, use the pty to get the pgrp.
6625 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6626 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6627 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6628 His patch indicates that if TIOCGPGRP returns an error, then
6629 we should just assume that p->pid is also the process group id. */
6631 gid
= emacs_get_tty_pgrp (p
);
6634 /* If we can't get the information, assume
6635 the shell owns the tty. */
6638 /* It is not clear whether anything really can set GID to -1.
6639 Perhaps on some system one of those ioctls can or could do so.
6640 Or perhaps this is vestigial. */
6643 #else /* ! defined (TIOCGPGRP) */
6644 /* Can't select pgrps on this system, so we know that
6645 the child itself heads the pgrp. */
6647 #endif /* ! defined (TIOCGPGRP) */
6649 /* If current_group is lambda, and the shell owns the terminal,
6650 don't send any signal. */
6651 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6656 if (signo
== SIGCONT
)
6658 p
->raw_status_new
= 0;
6659 pset_status (p
, Qrun
);
6660 p
->tick
= ++process_tick
;
6663 status_notify (NULL
, NULL
);
6664 redisplay_preserve_echo_area (13);
6670 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6671 We don't know whether the bug is fixed in later HP-UX versions. */
6672 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6676 /* If we don't have process groups, send the signal to the immediate
6677 subprocess. That isn't really right, but it's better than any
6678 obvious alternative. */
6679 pid_t pid
= no_pgrp
? gid
: - gid
;
6681 /* Do not kill an already-reaped process, as that could kill an
6682 innocent bystander that happens to have the same process ID. */
6684 block_child_signal (&oldset
);
6687 unblock_child_signal (&oldset
);
6690 DEFUN ("internal-default-interrupt-process",
6691 Finternal_default_interrupt_process
,
6692 Sinternal_default_interrupt_process
, 0, 2, 0,
6693 doc
: /* Default function to interrupt process PROCESS.
6694 It shall be the last element in list `interrupt-process-functions'.
6695 See function `interrupt-process' for more details on usage. */)
6696 (Lisp_Object process
, Lisp_Object current_group
)
6698 process_send_signal (process
, SIGINT
, current_group
, 0);
6702 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6703 doc
: /* Interrupt process PROCESS.
6704 PROCESS may be a process, a buffer, or the name of a process or buffer.
6705 No arg or nil means current buffer's process.
6706 Second arg CURRENT-GROUP non-nil means send signal to
6707 the current process-group of the process's controlling terminal
6708 rather than to the process's own process group.
6709 If the process is a shell, this means interrupt current subjob
6710 rather than the shell.
6712 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6713 don't send the signal.
6715 This function calls the functions of `interrupt-process-functions' in
6716 the order of the list, until one of them returns non-`nil'. */)
6717 (Lisp_Object process
, Lisp_Object current_group
)
6719 return CALLN (Frun_hook_with_args_until_success
, Qinterrupt_process_functions
,
6720 process
, current_group
);
6723 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6724 doc
: /* Kill process PROCESS. May be process or name of one.
6725 See function `interrupt-process' for more details on usage. */)
6726 (Lisp_Object process
, Lisp_Object current_group
)
6728 process_send_signal (process
, SIGKILL
, current_group
, 0);
6732 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6733 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6734 See function `interrupt-process' for more details on usage. */)
6735 (Lisp_Object process
, Lisp_Object current_group
)
6737 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6741 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6742 doc
: /* Stop process PROCESS. May be process or name of one.
6743 See function `interrupt-process' for more details on usage.
6744 If PROCESS is a network or serial or pipe connection, inhibit handling
6745 of incoming traffic. */)
6746 (Lisp_Object process
, Lisp_Object current_group
)
6748 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6749 || PIPECONN_P (process
)))
6751 struct Lisp_Process
*p
;
6753 p
= XPROCESS (process
);
6754 if (NILP (p
->command
)
6756 delete_read_fd (p
->infd
);
6757 pset_command (p
, Qt
);
6761 error ("No SIGTSTP support");
6763 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6768 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6769 doc
: /* Continue process PROCESS. May be process or name of one.
6770 See function `interrupt-process' for more details on usage.
6771 If PROCESS is a network or serial process, resume handling of incoming
6773 (Lisp_Object process
, Lisp_Object current_group
)
6775 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6776 || PIPECONN_P (process
)))
6778 struct Lisp_Process
*p
;
6780 p
= XPROCESS (process
);
6781 if (EQ (p
->command
, Qt
)
6783 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6785 add_process_read_fd (p
->infd
);
6787 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6788 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6789 #else /* not WINDOWSNT */
6790 tcflush (p
->infd
, TCIFLUSH
);
6791 #endif /* not WINDOWSNT */
6793 pset_command (p
, Qnil
);
6797 process_send_signal (process
, SIGCONT
, current_group
, 0);
6799 error ("No SIGCONT support");
6804 /* Return the integer value of the signal whose abbreviation is ABBR,
6805 or a negative number if there is no such signal. */
6807 abbr_to_signal (char const *name
)
6810 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6812 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6815 for (i
= 0; i
< sizeof sigbuf
; i
++)
6817 sigbuf
[i
] = c_toupper (name
[i
]);
6819 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6825 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6826 2, 2, "sProcess (name or number): \nnSignal code: ",
6827 doc
: /* Send PROCESS the signal with code SIGCODE.
6828 PROCESS may also be a number specifying the process id of the
6829 process to signal; in this case, the process need not be a child of
6831 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6832 (Lisp_Object process
, Lisp_Object sigcode
)
6837 if (STRINGP (process
))
6839 Lisp_Object tem
= Fget_process (process
);
6842 Lisp_Object process_number
6843 = string_to_number (SSDATA (process
), 10, 1);
6844 if (NUMBERP (process_number
))
6845 tem
= process_number
;
6849 else if (!NUMBERP (process
))
6850 process
= get_process (process
);
6855 if (NUMBERP (process
))
6856 CONS_TO_INTEGER (process
, pid_t
, pid
);
6859 CHECK_PROCESS (process
);
6860 pid
= XPROCESS (process
)->pid
;
6862 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6865 if (INTEGERP (sigcode
))
6867 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6868 signo
= XINT (sigcode
);
6874 CHECK_SYMBOL (sigcode
);
6875 name
= SSDATA (SYMBOL_NAME (sigcode
));
6877 signo
= abbr_to_signal (name
);
6879 error ("Undefined signal name %s", name
);
6882 return make_number (kill (pid
, signo
));
6885 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6886 doc
: /* Make PROCESS see end-of-file in its input.
6887 EOF comes after any text already sent to it.
6888 PROCESS may be a process, a buffer, the name of a process or buffer, or
6889 nil, indicating the current buffer's process.
6890 If PROCESS is a network connection, or is a process communicating
6891 through a pipe (as opposed to a pty), then you cannot send any more
6892 text to PROCESS after you call this function.
6893 If PROCESS is a serial process, wait until all output written to the
6894 process has been transmitted to the serial port. */)
6895 (Lisp_Object process
)
6898 struct coding_system
*coding
= NULL
;
6901 proc
= get_process (process
);
6903 if (NETCONN_P (proc
))
6904 wait_while_connecting (proc
);
6906 if (DATAGRAM_CONN_P (proc
))
6910 outfd
= XPROCESS (proc
)->outfd
;
6912 coding
= proc_encode_coding_system
[outfd
];
6914 /* Make sure the process is really alive. */
6915 if (XPROCESS (proc
)->raw_status_new
)
6916 update_status (XPROCESS (proc
));
6917 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6918 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6920 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6922 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6923 send_process (proc
, "", 0, Qnil
);
6926 if (XPROCESS (proc
)->pty_flag
)
6927 send_process (proc
, "\004", 1, Qnil
);
6928 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6931 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6932 report_file_error ("Failed tcdrain", Qnil
);
6933 #endif /* not WINDOWSNT */
6934 /* Do nothing on Windows because writes are blocking. */
6938 struct Lisp_Process
*p
= XPROCESS (proc
);
6939 int old_outfd
= p
->outfd
;
6942 #ifdef HAVE_SHUTDOWN
6943 /* If this is a network connection, or socketpair is used
6944 for communication with the subprocess, call shutdown to cause EOF.
6945 (In some old system, shutdown to socketpair doesn't work.
6946 Then we just can't win.) */
6948 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6949 shutdown (old_outfd
, 1);
6951 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6952 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6954 report_file_error ("Opening null device", Qnil
);
6955 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6956 p
->outfd
= new_outfd
;
6958 if (!proc_encode_coding_system
[new_outfd
])
6959 proc_encode_coding_system
[new_outfd
]
6960 = xmalloc (sizeof (struct coding_system
));
6963 *proc_encode_coding_system
[new_outfd
]
6964 = *proc_encode_coding_system
[old_outfd
];
6965 memset (proc_encode_coding_system
[old_outfd
], 0,
6966 sizeof (struct coding_system
));
6969 setup_coding_system (p
->encode_coding_system
,
6970 proc_encode_coding_system
[new_outfd
]);
6975 /* The main Emacs thread records child processes in three places:
6977 - Vprocess_alist, for asynchronous subprocesses, which are child
6978 processes visible to Lisp.
6980 - deleted_pid_list, for child processes invisible to Lisp,
6981 typically because of delete-process. These are recorded so that
6982 the processes can be reaped when they exit, so that the operating
6983 system's process table is not cluttered by zombies.
6985 - the local variable PID in Fcall_process, call_process_cleanup and
6986 call_process_kill, for synchronous subprocesses.
6987 record_unwind_protect is used to make sure this process is not
6988 forgotten: if the user interrupts call-process and the child
6989 process refuses to exit immediately even with two C-g's,
6990 call_process_kill adds PID's contents to deleted_pid_list before
6993 The main Emacs thread invokes waitpid only on child processes that
6994 it creates and that have not been reaped. This avoid races on
6995 platforms such as GTK, where other threads create their own
6996 subprocesses which the main thread should not reap. For example,
6997 if the main thread attempted to reap an already-reaped child, it
6998 might inadvertently reap a GTK-created process that happened to
6999 have the same process ID. */
7001 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
7002 its own SIGCHLD handling. On POSIXish systems, glib needs this to
7003 keep track of its own children. GNUstep is similar. */
7005 static void dummy_handler (int sig
) {}
7006 static signal_handler_t
volatile lib_child_handler
;
7008 /* Handle a SIGCHLD signal by looking for known child processes of
7009 Emacs whose status have changed. For each one found, record its
7012 All we do is change the status; we do not run sentinels or print
7013 notifications. That is saved for the next time keyboard input is
7014 done, in order to avoid timing errors.
7016 ** WARNING: this can be called during garbage collection.
7017 Therefore, it must not be fooled by the presence of mark bits in
7020 ** USG WARNING: Although it is not obvious from the documentation
7021 in signal(2), on a USG system the SIGCLD handler MUST NOT call
7022 signal() before executing at least one wait(), otherwise the
7023 handler will be called again, resulting in an infinite loop. The
7024 relevant portion of the documentation reads "SIGCLD signals will be
7025 queued and the signal-catching function will be continually
7026 reentered until the queue is empty". Invoking signal() causes the
7027 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
7030 ** Malloc WARNING: This should never call malloc either directly or
7031 indirectly; if it does, that is a bug. */
7034 handle_child_signal (int sig
)
7036 Lisp_Object tail
, proc
;
7038 /* Find the process that signaled us, and record its status. */
7040 /* The process can have been deleted by Fdelete_process, or have
7041 been started asynchronously by Fcall_process. */
7042 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
7044 bool all_pids_are_fixnums
7045 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
7046 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
7047 Lisp_Object head
= XCAR (tail
);
7052 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
7055 if (INTEGERP (xpid
))
7056 deleted_pid
= XINT (xpid
);
7058 deleted_pid
= XFLOAT_DATA (xpid
);
7059 if (child_status_changed (deleted_pid
, 0, 0))
7061 if (STRINGP (XCDR (head
)))
7062 unlink (SSDATA (XCDR (head
)));
7063 XSETCAR (tail
, Qnil
);
7068 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
7069 FOR_EACH_PROCESS (tail
, proc
)
7071 struct Lisp_Process
*p
= XPROCESS (proc
);
7075 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
7077 /* Change the status of the process that was found. */
7078 p
->tick
= ++process_tick
;
7079 p
->raw_status
= status
;
7080 p
->raw_status_new
= 1;
7082 /* If process has terminated, stop waiting for its output. */
7083 if (WIFSIGNALED (status
) || WIFEXITED (status
))
7085 bool clear_desc_flag
= 0;
7088 clear_desc_flag
= 1;
7090 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
7091 if (clear_desc_flag
)
7092 delete_read_fd (p
->infd
);
7097 lib_child_handler (sig
);
7098 #ifdef NS_IMPL_GNUSTEP
7099 /* NSTask in GNUstep sets its child handler each time it is called.
7100 So we must re-set ours. */
7101 catch_child_signal ();
7106 deliver_child_signal (int sig
)
7108 deliver_process_signal (sig
, handle_child_signal
);
7113 exec_sentinel_error_handler (Lisp_Object error_val
)
7115 /* Make sure error_val is a cons cell, as all the rest of error
7116 handling expects that, and will barf otherwise. */
7117 if (!CONSP (error_val
))
7118 error_val
= Fcons (Qerror
, error_val
);
7119 cmd_error_internal (error_val
, "error in process sentinel: ");
7121 update_echo_area ();
7122 Fsleep_for (make_number (2), Qnil
);
7127 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
7129 Lisp_Object sentinel
, odeactivate
;
7130 struct Lisp_Process
*p
= XPROCESS (proc
);
7131 ptrdiff_t count
= SPECPDL_INDEX ();
7132 bool outer_running_asynch_code
= running_asynch_code
;
7133 int waiting
= waiting_for_user_input_p
;
7135 if (inhibit_sentinels
)
7138 odeactivate
= Vdeactivate_mark
;
7140 Lisp_Object obuffer
, okeymap
;
7141 XSETBUFFER (obuffer
, current_buffer
);
7142 okeymap
= BVAR (current_buffer
, keymap
);
7145 /* There's no good reason to let sentinels change the current
7146 buffer, and many callers of accept-process-output, sit-for, and
7147 friends don't expect current-buffer to be changed from under them. */
7148 record_unwind_current_buffer ();
7150 sentinel
= p
->sentinel
;
7152 /* Inhibit quit so that random quits don't screw up a running filter. */
7153 specbind (Qinhibit_quit
, Qt
);
7154 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
7156 /* In case we get recursively called,
7157 and we already saved the match data nonrecursively,
7158 save the same match data in safely recursive fashion. */
7159 if (outer_running_asynch_code
)
7162 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
7163 restore_search_regs ();
7164 record_unwind_save_match_data ();
7165 Fset_match_data (tem
, Qt
);
7168 /* For speed, if a search happens within this code,
7169 save the match data in a special nonrecursive fashion. */
7170 running_asynch_code
= 1;
7172 internal_condition_case_1 (read_process_output_call
,
7173 list3 (sentinel
, proc
, reason
),
7174 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
7175 exec_sentinel_error_handler
);
7177 /* If we saved the match data nonrecursively, restore it now. */
7178 restore_search_regs ();
7179 running_asynch_code
= outer_running_asynch_code
;
7181 Vdeactivate_mark
= odeactivate
;
7183 /* Restore waiting_for_user_input_p as it was
7184 when we were called, in case the filter clobbered it. */
7185 waiting_for_user_input_p
= waiting
;
7188 if (! EQ (Fcurrent_buffer (), obuffer
)
7189 || ! EQ (current_buffer
->keymap
, okeymap
))
7191 /* But do it only if the caller is actually going to read events.
7192 Otherwise there's no need to make him wake up, and it could
7193 cause trouble (for example it would make sit_for return). */
7194 if (waiting_for_user_input_p
== -1)
7195 record_asynch_buffer_change ();
7197 unbind_to (count
, Qnil
);
7200 /* Report all recent events of a change in process status
7201 (either run the sentinel or output a message).
7202 This is usually done while Emacs is waiting for keyboard input
7203 but can be done at other times.
7205 Return positive if any input was received from WAIT_PROC (or from
7206 any process if WAIT_PROC is null), zero if input was attempted but
7207 none received, and negative if we didn't even try. */
7210 status_notify (struct Lisp_Process
*deleting_process
,
7211 struct Lisp_Process
*wait_proc
)
7214 Lisp_Object tail
, msg
;
7215 int got_some_output
= -1;
7220 /* Set this now, so that if new processes are created by sentinels
7221 that we run, we get called again to handle their status changes. */
7222 update_tick
= process_tick
;
7224 FOR_EACH_PROCESS (tail
, proc
)
7227 register struct Lisp_Process
*p
= XPROCESS (proc
);
7229 if (p
->tick
!= p
->update_tick
)
7231 p
->update_tick
= p
->tick
;
7233 /* If process is still active, read any output that remains. */
7234 while (! EQ (p
->filter
, Qt
)
7235 && ! connecting_status (p
->status
)
7236 && ! EQ (p
->status
, Qlisten
)
7237 /* Network or serial process not stopped: */
7238 && ! EQ (p
->command
, Qt
)
7240 && p
!= deleting_process
)
7242 int nread
= read_process_output (proc
, p
->infd
);
7243 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7244 && got_some_output
< nread
)
7245 got_some_output
= nread
;
7250 /* Get the text to use for the message. */
7251 if (p
->raw_status_new
)
7253 msg
= status_message (p
);
7255 /* If process is terminated, deactivate it or delete it. */
7257 if (CONSP (p
->status
))
7258 symbol
= XCAR (p
->status
);
7260 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7261 || EQ (symbol
, Qclosed
))
7263 if (delete_exited_processes
)
7264 remove_process (proc
);
7266 deactivate_process (proc
);
7269 /* The actions above may have further incremented p->tick.
7270 So set p->update_tick again so that an error in the sentinel will
7271 not cause this code to be run again. */
7272 p
->update_tick
= p
->tick
;
7273 /* Now output the message suitably. */
7274 exec_sentinel (proc
, msg
);
7275 if (BUFFERP (p
->buffer
))
7276 /* In case it uses %s in mode-line-format. */
7277 bset_update_mode_line (XBUFFER (p
->buffer
));
7281 return got_some_output
;
7284 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7285 Sinternal_default_process_sentinel
, 2, 2, 0,
7286 doc
: /* Function used as default sentinel for processes.
7287 This inserts a status message into the process's buffer, if there is one. */)
7288 (Lisp_Object proc
, Lisp_Object msg
)
7290 Lisp_Object buffer
, symbol
;
7291 struct Lisp_Process
*p
;
7292 CHECK_PROCESS (proc
);
7293 p
= XPROCESS (proc
);
7297 symbol
= XCAR (symbol
);
7299 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7302 struct buffer
*old
= current_buffer
;
7303 ptrdiff_t opoint
, opoint_byte
;
7304 ptrdiff_t before
, before_byte
;
7306 /* Avoid error if buffer is deleted
7307 (probably that's why the process is dead, too). */
7308 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7310 Fset_buffer (buffer
);
7312 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7313 msg
= (code_convert_string_norecord
7314 (msg
, Vlocale_coding_system
, 1));
7317 opoint_byte
= PT_BYTE
;
7318 /* Insert new output into buffer
7319 at the current end-of-output marker,
7320 thus preserving logical ordering of input and output. */
7321 if (XMARKER (p
->mark
)->buffer
)
7322 Fgoto_char (p
->mark
);
7324 SET_PT_BOTH (ZV
, ZV_BYTE
);
7327 before_byte
= PT_BYTE
;
7329 tem
= BVAR (current_buffer
, read_only
);
7330 bset_read_only (current_buffer
, Qnil
);
7331 insert_string ("\nProcess ");
7332 { /* FIXME: temporary kludge. */
7333 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7334 insert_string (" ");
7336 bset_read_only (current_buffer
, tem
);
7337 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7339 if (opoint
>= before
)
7340 SET_PT_BOTH (opoint
+ (PT
- before
),
7341 opoint_byte
+ (PT_BYTE
- before_byte
));
7343 SET_PT_BOTH (opoint
, opoint_byte
);
7345 set_buffer_internal (old
);
7351 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7352 Sset_process_coding_system
, 1, 3, 0,
7353 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7354 DECODING will be used to decode subprocess output and ENCODING to
7355 encode subprocess input. */)
7356 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7358 CHECK_PROCESS (process
);
7360 struct Lisp_Process
*p
= XPROCESS (process
);
7362 Fcheck_coding_system (decoding
);
7363 Fcheck_coding_system (encoding
);
7364 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7365 pset_decode_coding_system (p
, decoding
);
7366 pset_encode_coding_system (p
, encoding
);
7368 /* If the sockets haven't been set up yet, the final setup part of
7369 this will be called asynchronously. */
7370 if (p
->infd
< 0 || p
->outfd
< 0)
7373 setup_process_coding_systems (process
);
7378 DEFUN ("process-coding-system",
7379 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7380 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7381 (register Lisp_Object process
)
7383 CHECK_PROCESS (process
);
7384 return Fcons (XPROCESS (process
)->decode_coding_system
,
7385 XPROCESS (process
)->encode_coding_system
);
7388 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7389 Sset_process_filter_multibyte
, 2, 2, 0,
7390 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7391 If FLAG is non-nil, the filter is given multibyte strings.
7392 If FLAG is nil, the filter is given unibyte strings. In this case,
7393 all character code conversion except for end-of-line conversion is
7395 (Lisp_Object process
, Lisp_Object flag
)
7397 CHECK_PROCESS (process
);
7399 struct Lisp_Process
*p
= XPROCESS (process
);
7401 pset_decode_coding_system
7402 (p
, raw_text_coding_system (p
->decode_coding_system
));
7404 /* If the sockets haven't been set up yet, the final setup part of
7405 this will be called asynchronously. */
7406 if (p
->infd
< 0 || p
->outfd
< 0)
7409 setup_process_coding_systems (process
);
7414 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7415 Sprocess_filter_multibyte_p
, 1, 1, 0,
7416 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7417 (Lisp_Object process
)
7419 CHECK_PROCESS (process
);
7420 struct Lisp_Process
*p
= XPROCESS (process
);
7423 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7424 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7433 add_gpm_wait_descriptor (int desc
)
7435 add_keyboard_wait_descriptor (desc
);
7439 delete_gpm_wait_descriptor (int desc
)
7441 delete_keyboard_wait_descriptor (desc
);
7446 # ifdef USABLE_SIGIO
7448 /* Return true if *MASK has a bit set
7449 that corresponds to one of the keyboard input descriptors. */
7452 keyboard_bit_set (fd_set
*mask
)
7456 for (fd
= 0; fd
<= max_desc
; fd
++)
7457 if (FD_ISSET (fd
, mask
)
7458 && ((fd_callback_info
[fd
].flags
& (FOR_READ
| KEYBOARD_FD
))
7459 == (FOR_READ
| KEYBOARD_FD
)))
7466 #else /* not subprocesses */
7468 /* This is referenced in thread.c:run_thread (which is never actually
7469 called, since threads are not enabled for this configuration. */
7471 update_processes_for_thread_death (Lisp_Object dying_thread
)
7475 /* Defined in msdos.c. */
7476 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7477 struct timespec
*, void *);
7479 /* Implementation of wait_reading_process_output, assuming that there
7480 are no subprocesses. Used only by the MS-DOS build.
7482 Wait for timeout to elapse and/or keyboard input to be available.
7486 If negative, gobble data immediately available but don't wait for any.
7489 an additional duration to wait, measured in nanoseconds
7490 If TIME_LIMIT is zero, then:
7491 If NSECS == 0, there is no limit.
7492 If NSECS > 0, the timeout consists of NSECS only.
7493 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7496 0 to ignore keyboard input, or
7497 1 to return when input is available, or
7498 -1 means caller will actually read the input, so don't throw to
7501 see full version for other parameters. We know that wait_proc will
7502 always be NULL, since `subprocesses' isn't defined.
7504 DO_DISPLAY means redisplay should be done to show subprocess
7505 output that arrives.
7507 Return -1 signifying we got no output and did not try. */
7510 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7512 Lisp_Object wait_for_cell
,
7513 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7516 struct timespec end_time
, timeout
;
7517 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7519 if (TYPE_MAXIMUM (time_t) < time_limit
)
7520 time_limit
= TYPE_MAXIMUM (time_t);
7522 if (time_limit
< 0 || nsecs
< 0)
7524 else if (time_limit
> 0 || nsecs
> 0)
7527 end_time
= timespec_add (current_timespec (),
7528 make_timespec (time_limit
, nsecs
));
7533 /* Turn off periodic alarms (in case they are in use)
7534 and then turn off any other atimers,
7535 because the select emulator uses alarms. */
7537 turn_on_atimers (0);
7541 bool timeout_reduced_for_timers
= false;
7542 fd_set waitchannels
;
7545 /* If calling from keyboard input, do not quit
7546 since we want to return C-g as an input character.
7547 Otherwise, do pending quit if requested. */
7551 /* Exit now if the cell we're waiting for became non-nil. */
7552 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7555 /* Compute time from now till when time limit is up. */
7556 /* Exit if already run out. */
7557 if (wait
== TIMEOUT
)
7559 struct timespec now
= current_timespec ();
7560 if (timespec_cmp (end_time
, now
) <= 0)
7562 timeout
= timespec_sub (end_time
, now
);
7565 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7567 /* If our caller will not immediately handle keyboard events,
7568 run timer events directly.
7569 (Callers that will immediately read keyboard events
7570 call timer_delay on their own.) */
7571 if (NILP (wait_for_cell
))
7573 struct timespec timer_delay
;
7577 unsigned old_timers_run
= timers_run
;
7578 timer_delay
= timer_check ();
7579 if (timers_run
!= old_timers_run
&& do_display
)
7580 /* We must retry, since a timer may have requeued itself
7581 and that could alter the time delay. */
7582 redisplay_preserve_echo_area (14);
7586 while (!detect_input_pending ());
7588 /* If there is unread keyboard input, also return. */
7590 && requeued_events_pending_p ())
7593 if (timespec_valid_p (timer_delay
))
7595 if (timespec_cmp (timer_delay
, timeout
) < 0)
7597 timeout
= timer_delay
;
7598 timeout_reduced_for_timers
= true;
7603 /* Cause C-g and alarm signals to take immediate action,
7604 and cause input available signals to zero out timeout. */
7606 set_waiting_for_input (&timeout
);
7608 /* If a frame has been newly mapped and needs updating,
7609 reprocess its display stuff. */
7610 if (frame_garbaged
&& do_display
)
7612 clear_waiting_for_input ();
7613 redisplay_preserve_echo_area (15);
7615 set_waiting_for_input (&timeout
);
7618 /* Wait till there is something to do. */
7619 FD_ZERO (&waitchannels
);
7620 if (read_kbd
&& detect_input_pending ())
7624 if (read_kbd
|| !NILP (wait_for_cell
))
7625 FD_SET (0, &waitchannels
);
7626 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7631 /* Make C-g and alarm signals set flags again. */
7632 clear_waiting_for_input ();
7634 /* If we woke up due to SIGWINCH, actually change size now. */
7635 do_pending_window_change (0);
7637 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7638 /* We waited the full specified time, so return now. */
7643 /* If the system call was interrupted, then go around the
7645 if (xerrno
== EINTR
)
7646 FD_ZERO (&waitchannels
);
7648 report_file_errno ("Failed select", Qnil
, xerrno
);
7651 /* Check for keyboard input. */
7654 && detect_input_pending_run_timers (do_display
))
7656 swallow_events (do_display
);
7657 if (detect_input_pending_run_timers (do_display
))
7661 /* If there is unread keyboard input, also return. */
7663 && requeued_events_pending_p ())
7666 /* If wait_for_cell. check for keyboard input
7667 but don't run any timers.
7668 ??? (It seems wrong to me to check for keyboard
7669 input at all when wait_for_cell, but the code
7670 has been this way since July 1994.
7671 Try changing this after version 19.31.) */
7672 if (! NILP (wait_for_cell
)
7673 && detect_input_pending ())
7675 swallow_events (do_display
);
7676 if (detect_input_pending ())
7680 /* Exit now if the cell we're waiting for became non-nil. */
7681 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7690 #endif /* not subprocesses */
7692 /* The following functions are needed even if async subprocesses are
7693 not supported. Some of them are no-op stubs in that case. */
7697 /* Add FD, which is a descriptor returned by timerfd_create,
7698 to the set of non-keyboard input descriptors. */
7701 add_timer_wait_descriptor (int fd
)
7703 add_read_fd (fd
, timerfd_callback
, NULL
);
7704 fd_callback_info
[fd
].flags
&= ~KEYBOARD_FD
;
7707 #endif /* HAVE_TIMERFD */
7709 /* If program file NAME starts with /: for quoting a magic
7710 name, remove that, preserving the multibyteness of NAME. */
7713 remove_slash_colon (Lisp_Object name
)
7716 (SREF (name
, 0) == '/' && SREF (name
, 1) == ':'
7717 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7718 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7722 /* Add DESC to the set of keyboard input descriptors. */
7725 add_keyboard_wait_descriptor (int desc
)
7727 #ifdef subprocesses /* Actually means "not MSDOS". */
7728 eassert (desc
>= 0 && desc
< FD_SETSIZE
);
7729 fd_callback_info
[desc
].flags
&= ~PROCESS_FD
;
7730 fd_callback_info
[desc
].flags
|= (FOR_READ
| KEYBOARD_FD
);
7731 if (desc
> max_desc
)
7736 /* From now on, do not expect DESC to give keyboard input. */
7739 delete_keyboard_wait_descriptor (int desc
)
7742 eassert (desc
>= 0 && desc
< FD_SETSIZE
);
7744 fd_callback_info
[desc
].flags
&= ~(FOR_READ
| KEYBOARD_FD
| PROCESS_FD
);
7746 if (desc
== max_desc
)
7747 recompute_max_desc ();
7751 /* Setup coding systems of PROCESS. */
7754 setup_process_coding_systems (Lisp_Object process
)
7757 struct Lisp_Process
*p
= XPROCESS (process
);
7759 int outch
= p
->outfd
;
7760 Lisp_Object coding_system
;
7762 if (inch
< 0 || outch
< 0)
7765 if (!proc_decode_coding_system
[inch
])
7766 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7767 coding_system
= p
->decode_coding_system
;
7768 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7769 && BUFFERP (p
->buffer
))
7771 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7772 coding_system
= raw_text_coding_system (coding_system
);
7774 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7776 if (!proc_encode_coding_system
[outch
])
7777 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7778 setup_coding_system (p
->encode_coding_system
,
7779 proc_encode_coding_system
[outch
]);
7783 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7784 doc
: /* Return the (or a) live process associated with BUFFER.
7785 BUFFER may be a buffer or the name of one.
7786 Return nil if all processes associated with BUFFER have been
7787 deleted or killed. */)
7788 (register Lisp_Object buffer
)
7791 register Lisp_Object buf
, tail
, proc
;
7793 if (NILP (buffer
)) return Qnil
;
7794 buf
= Fget_buffer (buffer
);
7795 if (NILP (buf
)) return Qnil
;
7797 FOR_EACH_PROCESS (tail
, proc
)
7798 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7800 #endif /* subprocesses */
7804 DEFUN ("process-inherit-coding-system-flag",
7805 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7807 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7808 If this flag is t, `buffer-file-coding-system' of the buffer
7809 associated with PROCESS will inherit the coding system used to decode
7810 the process output. */)
7811 (register Lisp_Object process
)
7814 CHECK_PROCESS (process
);
7815 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7817 /* Ignore the argument and return the value of
7818 inherit-process-coding-system. */
7819 return inherit_process_coding_system
? Qt
: Qnil
;
7823 /* Kill all processes associated with `buffer'.
7824 If `buffer' is nil, kill all processes. */
7827 kill_buffer_processes (Lisp_Object buffer
)
7830 Lisp_Object tail
, proc
;
7832 FOR_EACH_PROCESS (tail
, proc
)
7833 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7835 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7836 Fdelete_process (proc
);
7837 else if (XPROCESS (proc
)->infd
>= 0)
7838 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7840 #else /* subprocesses */
7841 /* Since we have no subprocesses, this does nothing. */
7842 #endif /* subprocesses */
7845 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7846 Swaiting_for_user_input_p
, 0, 0, 0,
7847 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7848 This is intended for use by asynchronous process output filters and sentinels. */)
7852 return (waiting_for_user_input_p
? Qt
: Qnil
);
7858 /* Stop reading input from keyboard sources. */
7861 hold_keyboard_input (void)
7866 /* Resume reading input from keyboard sources. */
7869 unhold_keyboard_input (void)
7874 /* Return true if keyboard input is on hold, zero otherwise. */
7877 kbd_on_hold_p (void)
7879 return kbd_is_on_hold
;
7883 /* Enumeration of and access to system processes a-la ps(1). */
7885 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7887 doc
: /* Return a list of numerical process IDs of all running processes.
7888 If this functionality is unsupported, return nil.
7890 See `process-attributes' for getting attributes of a process given its ID. */)
7893 return list_system_processes ();
7896 DEFUN ("process-attributes", Fprocess_attributes
,
7897 Sprocess_attributes
, 1, 1, 0,
7898 doc
: /* Return attributes of the process given by its PID, a number.
7900 Value is an alist where each element is a cons cell of the form
7904 If this functionality is unsupported, the value is nil.
7906 See `list-system-processes' for getting a list of all process IDs.
7908 The KEYs of the attributes that this function may return are listed
7909 below, together with the type of the associated VALUE (in parentheses).
7910 Not all platforms support all of these attributes; unsupported
7911 attributes will not appear in the returned alist.
7912 Unless explicitly indicated otherwise, numbers can have either
7913 integer or floating point values.
7915 euid -- Effective user User ID of the process (number)
7916 user -- User name corresponding to euid (string)
7917 egid -- Effective user Group ID of the process (number)
7918 group -- Group name corresponding to egid (string)
7919 comm -- Command name (executable name only) (string)
7920 state -- Process state code, such as "S", "R", or "T" (string)
7921 ppid -- Parent process ID (number)
7922 pgrp -- Process group ID (number)
7923 sess -- Session ID, i.e. process ID of session leader (number)
7924 ttname -- Controlling tty name (string)
7925 tpgid -- ID of foreground process group on the process's tty (number)
7926 minflt -- number of minor page faults (number)
7927 majflt -- number of major page faults (number)
7928 cminflt -- cumulative number of minor page faults (number)
7929 cmajflt -- cumulative number of major page faults (number)
7930 utime -- user time used by the process, in (current-time) format,
7931 which is a list of integers (HIGH LOW USEC PSEC)
7932 stime -- system time used by the process (current-time)
7933 time -- sum of utime and stime (current-time)
7934 cutime -- user time used by the process and its children (current-time)
7935 cstime -- system time used by the process and its children (current-time)
7936 ctime -- sum of cutime and cstime (current-time)
7937 pri -- priority of the process (number)
7938 nice -- nice value of the process (number)
7939 thcount -- process thread count (number)
7940 start -- time the process started (current-time)
7941 vsize -- virtual memory size of the process in KB's (number)
7942 rss -- resident set size of the process in KB's (number)
7943 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7944 pcpu -- percents of CPU time used by the process (floating-point number)
7945 pmem -- percents of total physical memory used by process's resident set
7946 (floating-point number)
7947 args -- command line which invoked the process (string). */)
7950 return system_process_attributes (pid
);
7954 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7955 Invoke this after init_process_emacs, and after glib and/or GNUstep
7956 futz with the SIGCHLD handler, but before Emacs forks any children.
7957 This function's caller should block SIGCHLD. */
7960 catch_child_signal (void)
7962 struct sigaction action
, old_action
;
7964 emacs_sigaction_init (&action
, deliver_child_signal
);
7965 block_child_signal (&oldset
);
7966 sigaction (SIGCHLD
, &action
, &old_action
);
7967 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7968 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7970 if (old_action
.sa_handler
!= deliver_child_signal
)
7972 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7974 : old_action
.sa_handler
);
7975 unblock_child_signal (&oldset
);
7977 #endif /* subprocesses */
7979 /* Limit the number of open files to the value it had at startup. */
7982 restore_nofile_limit (void)
7984 #ifdef HAVE_SETRLIMIT
7985 if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
7986 setrlimit (RLIMIT_NOFILE
, &nofile_limit
);
7991 /* This is not called "init_process" because that is the name of a
7992 Mach system call, so it would cause problems on Darwin systems. */
7994 init_process_emacs (int sockfd
)
7999 inhibit_sentinels
= 0;
8002 if (! noninteractive
|| initialized
)
8005 #if defined HAVE_GLIB && !defined WINDOWSNT
8006 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
8007 this should always fail, but is enough to initialize glib's
8008 private SIGCHLD handler, allowing catch_child_signal to copy
8009 it into lib_child_handler. */
8010 g_source_unref (g_child_watch_source_new (getpid ()));
8012 catch_child_signal ();
8015 #ifdef HAVE_SETRLIMIT
8016 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
8017 if (getrlimit (RLIMIT_NOFILE
, &nofile_limit
) != 0)
8018 nofile_limit
.rlim_cur
= 0;
8019 else if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
8021 struct rlimit rlim
= nofile_limit
;
8022 rlim
.rlim_cur
= FD_SETSIZE
;
8023 if (setrlimit (RLIMIT_NOFILE
, &rlim
) != 0)
8024 nofile_limit
.rlim_cur
= 0;
8028 external_sock_fd
= sockfd
;
8030 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
8032 num_pending_connects
= 0;
8034 process_output_delay_count
= 0;
8035 process_output_skip
= 0;
8037 /* Don't do this, it caused infinite select loops. The display
8038 method should call add_keyboard_wait_descriptor on stdin if it
8041 FD_SET (0, &input_wait_mask
);
8044 Vprocess_alist
= Qnil
;
8045 deleted_pid_list
= Qnil
;
8046 for (i
= 0; i
< FD_SETSIZE
; i
++)
8048 chan_process
[i
] = Qnil
;
8049 proc_buffered_char
[i
] = -1;
8051 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
8052 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
8053 #ifdef DATAGRAM_SOCKETS
8054 memset (datagram_address
, 0, sizeof datagram_address
);
8057 #if defined (DARWIN_OS)
8058 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
8059 processes. As such, we only change the default value. */
8062 char const *release
= (STRINGP (Voperating_system_release
)
8063 ? SSDATA (Voperating_system_release
)
8065 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
8066 Vprocess_connection_type
= Qnil
;
8070 #endif /* subprocesses */
8075 syms_of_process (void)
8079 DEFSYM (Qprocessp
, "processp");
8080 DEFSYM (Qrun
, "run");
8081 DEFSYM (Qstop
, "stop");
8082 DEFSYM (Qsignal
, "signal");
8084 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
8087 DEFSYM (Qopen
, "open");
8088 DEFSYM (Qclosed
, "closed");
8089 DEFSYM (Qconnect
, "connect");
8090 DEFSYM (Qfailed
, "failed");
8091 DEFSYM (Qlisten
, "listen");
8092 DEFSYM (Qlocal
, "local");
8093 DEFSYM (Qipv4
, "ipv4");
8095 DEFSYM (Qipv6
, "ipv6");
8097 DEFSYM (Qdatagram
, "datagram");
8098 DEFSYM (Qseqpacket
, "seqpacket");
8100 DEFSYM (QCport
, ":port");
8101 DEFSYM (QCspeed
, ":speed");
8102 DEFSYM (QCprocess
, ":process");
8104 DEFSYM (QCbytesize
, ":bytesize");
8105 DEFSYM (QCstopbits
, ":stopbits");
8106 DEFSYM (QCparity
, ":parity");
8107 DEFSYM (Qodd
, "odd");
8108 DEFSYM (Qeven
, "even");
8109 DEFSYM (QCflowcontrol
, ":flowcontrol");
8112 DEFSYM (QCsummary
, ":summary");
8114 DEFSYM (Qreal
, "real");
8115 DEFSYM (Qnetwork
, "network");
8116 DEFSYM (Qserial
, "serial");
8117 DEFSYM (QCbuffer
, ":buffer");
8118 DEFSYM (QChost
, ":host");
8119 DEFSYM (QCservice
, ":service");
8120 DEFSYM (QClocal
, ":local");
8121 DEFSYM (QCremote
, ":remote");
8122 DEFSYM (QCcoding
, ":coding");
8123 DEFSYM (QCserver
, ":server");
8124 DEFSYM (QCnowait
, ":nowait");
8125 DEFSYM (QCsentinel
, ":sentinel");
8126 DEFSYM (QCuse_external_socket
, ":use-external-socket");
8127 DEFSYM (QCtls_parameters
, ":tls-parameters");
8128 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
8129 DEFSYM (QClog
, ":log");
8130 DEFSYM (QCnoquery
, ":noquery");
8131 DEFSYM (QCstop
, ":stop");
8132 DEFSYM (QCplist
, ":plist");
8133 DEFSYM (QCcommand
, ":command");
8134 DEFSYM (QCconnection_type
, ":connection-type");
8135 DEFSYM (QCstderr
, ":stderr");
8136 DEFSYM (Qpty
, "pty");
8137 DEFSYM (Qpipe
, "pipe");
8139 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
8141 staticpro (&Vprocess_alist
);
8142 staticpro (&deleted_pid_list
);
8144 #endif /* subprocesses */
8146 DEFSYM (QCname
, ":name");
8147 DEFSYM (QCtype
, ":type");
8149 DEFSYM (Qeuid
, "euid");
8150 DEFSYM (Qegid
, "egid");
8151 DEFSYM (Quser
, "user");
8152 DEFSYM (Qgroup
, "group");
8153 DEFSYM (Qcomm
, "comm");
8154 DEFSYM (Qstate
, "state");
8155 DEFSYM (Qppid
, "ppid");
8156 DEFSYM (Qpgrp
, "pgrp");
8157 DEFSYM (Qsess
, "sess");
8158 DEFSYM (Qttname
, "ttname");
8159 DEFSYM (Qtpgid
, "tpgid");
8160 DEFSYM (Qminflt
, "minflt");
8161 DEFSYM (Qmajflt
, "majflt");
8162 DEFSYM (Qcminflt
, "cminflt");
8163 DEFSYM (Qcmajflt
, "cmajflt");
8164 DEFSYM (Qutime
, "utime");
8165 DEFSYM (Qstime
, "stime");
8166 DEFSYM (Qtime
, "time");
8167 DEFSYM (Qcutime
, "cutime");
8168 DEFSYM (Qcstime
, "cstime");
8169 DEFSYM (Qctime
, "ctime");
8171 DEFSYM (Qinternal_default_process_sentinel
,
8172 "internal-default-process-sentinel");
8173 DEFSYM (Qinternal_default_process_filter
,
8174 "internal-default-process-filter");
8176 DEFSYM (Qpri
, "pri");
8177 DEFSYM (Qnice
, "nice");
8178 DEFSYM (Qthcount
, "thcount");
8179 DEFSYM (Qstart
, "start");
8180 DEFSYM (Qvsize
, "vsize");
8181 DEFSYM (Qrss
, "rss");
8182 DEFSYM (Qetime
, "etime");
8183 DEFSYM (Qpcpu
, "pcpu");
8184 DEFSYM (Qpmem
, "pmem");
8185 DEFSYM (Qargs
, "args");
8187 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
8188 doc
: /* Non-nil means delete processes immediately when they exit.
8189 A value of nil means don't delete them until `list-processes' is run. */);
8191 delete_exited_processes
= 1;
8194 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
8195 doc
: /* Control type of device used to communicate with subprocesses.
8196 Values are nil to use a pipe, or t or `pty' to use a pty.
8197 The value has no effect if the system has no ptys or if all ptys are busy:
8198 then a pipe is used in any case.
8199 The value takes effect when `start-process' is called. */);
8200 Vprocess_connection_type
= Qt
;
8202 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
8203 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
8204 On some systems, when Emacs reads the output from a subprocess, the output data
8205 is read in very small blocks, potentially resulting in very poor performance.
8206 This behavior can be remedied to some extent by setting this variable to a
8207 non-nil value, as it will automatically delay reading from such processes, to
8208 allow them to produce more output before Emacs tries to read it.
8209 If the value is t, the delay is reset after each write to the process; any other
8210 non-nil value means that the delay is not reset on write.
8211 The variable takes effect when `start-process' is called. */);
8212 Vprocess_adaptive_read_buffering
= Qt
;
8214 DEFVAR_LISP ("interrupt-process-functions", Vinterrupt_process_functions
,
8215 doc
: /* List of functions to be called for `interrupt-process'.
8216 The arguments of the functions are the same as for `interrupt-process'.
8217 These functions are called in the order of the list, until one of them
8218 returns non-`nil'. */);
8219 Vinterrupt_process_functions
= list1 (Qinternal_default_interrupt_process
);
8221 DEFSYM (Qinternal_default_interrupt_process
,
8222 "internal-default-interrupt-process");
8223 DEFSYM (Qinterrupt_process_functions
, "interrupt-process-functions");
8225 defsubr (&Sprocessp
);
8226 defsubr (&Sget_process
);
8227 defsubr (&Sdelete_process
);
8228 defsubr (&Sprocess_status
);
8229 defsubr (&Sprocess_exit_status
);
8230 defsubr (&Sprocess_id
);
8231 defsubr (&Sprocess_name
);
8232 defsubr (&Sprocess_tty_name
);
8233 defsubr (&Sprocess_command
);
8234 defsubr (&Sset_process_buffer
);
8235 defsubr (&Sprocess_buffer
);
8236 defsubr (&Sprocess_mark
);
8237 defsubr (&Sset_process_filter
);
8238 defsubr (&Sprocess_filter
);
8239 defsubr (&Sset_process_sentinel
);
8240 defsubr (&Sprocess_sentinel
);
8241 defsubr (&Sset_process_thread
);
8242 defsubr (&Sprocess_thread
);
8243 defsubr (&Sset_process_window_size
);
8244 defsubr (&Sset_process_inherit_coding_system_flag
);
8245 defsubr (&Sset_process_query_on_exit_flag
);
8246 defsubr (&Sprocess_query_on_exit_flag
);
8247 defsubr (&Sprocess_contact
);
8248 defsubr (&Sprocess_plist
);
8249 defsubr (&Sset_process_plist
);
8250 defsubr (&Sprocess_list
);
8251 defsubr (&Smake_process
);
8252 defsubr (&Smake_pipe_process
);
8253 defsubr (&Sserial_process_configure
);
8254 defsubr (&Smake_serial_process
);
8255 defsubr (&Sset_network_process_option
);
8256 defsubr (&Smake_network_process
);
8257 defsubr (&Sformat_network_address
);
8258 defsubr (&Snetwork_interface_list
);
8259 defsubr (&Snetwork_interface_info
);
8260 #ifdef DATAGRAM_SOCKETS
8261 defsubr (&Sprocess_datagram_address
);
8262 defsubr (&Sset_process_datagram_address
);
8264 defsubr (&Saccept_process_output
);
8265 defsubr (&Sprocess_send_region
);
8266 defsubr (&Sprocess_send_string
);
8267 defsubr (&Sinternal_default_interrupt_process
);
8268 defsubr (&Sinterrupt_process
);
8269 defsubr (&Skill_process
);
8270 defsubr (&Squit_process
);
8271 defsubr (&Sstop_process
);
8272 defsubr (&Scontinue_process
);
8273 defsubr (&Sprocess_running_child_p
);
8274 defsubr (&Sprocess_send_eof
);
8275 defsubr (&Ssignal_process
);
8276 defsubr (&Swaiting_for_user_input_p
);
8277 defsubr (&Sprocess_type
);
8278 defsubr (&Sinternal_default_process_sentinel
);
8279 defsubr (&Sinternal_default_process_filter
);
8280 defsubr (&Sset_process_coding_system
);
8281 defsubr (&Sprocess_coding_system
);
8282 defsubr (&Sset_process_filter_multibyte
);
8283 defsubr (&Sprocess_filter_multibyte_p
);
8286 Lisp_Object subfeatures
= Qnil
;
8287 const struct socket_options
*sopt
;
8289 #define ADD_SUBFEATURE(key, val) \
8290 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8292 ADD_SUBFEATURE (QCnowait
, Qt
);
8293 #ifdef DATAGRAM_SOCKETS
8294 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8296 #ifdef HAVE_SEQPACKET
8297 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8299 #ifdef HAVE_LOCAL_SOCKETS
8300 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8302 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8304 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8306 #ifdef HAVE_GETSOCKNAME
8307 ADD_SUBFEATURE (QCservice
, Qt
);
8309 ADD_SUBFEATURE (QCserver
, Qt
);
8311 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8312 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8314 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8317 #endif /* subprocesses */
8319 defsubr (&Sget_buffer_process
);
8320 defsubr (&Sprocess_inherit_coding_system_flag
);
8321 defsubr (&Slist_system_processes
);
8322 defsubr (&Sprocess_attributes
);