1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
34 /* Only MS-DOS does not define `subprocesses'. */
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
48 #define HAVE_LOCAL_SOCKETS
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
90 #endif /* subprocesses */
96 #include "character.h"
101 #include "termopts.h"
102 #include "keyboard.h"
103 #include "blockinput.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
112 #ifdef HAVE_WINDOW_SYSTEM
114 #endif /* HAVE_WINDOW_SYSTEM */
117 #include "xgselect.h"
123 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
124 /* This is 0.1s in nanoseconds. */
125 #define ASYNC_RETRY_NSEC 100000000
129 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
130 struct timespec
*, void *);
133 /* Work around GCC 4.7.0 bug with strict overflow checking; see
134 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
135 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
136 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
137 # pragma GCC diagnostic ignored "-Wstrict-overflow"
140 /* True if keyboard input is on hold, zero otherwise. */
142 static bool kbd_is_on_hold
;
144 /* Nonzero means don't run process sentinels. This is used
146 bool inhibit_sentinels
;
151 # define SOCK_CLOEXEC 0
153 #ifndef SOCK_NONBLOCK
154 # define SOCK_NONBLOCK 0
157 /* True if ERRNUM represents an error where the system call would
158 block if a blocking variant were used. */
160 would_block (int errnum
)
163 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
166 return errnum
== EAGAIN
;
171 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
174 close_on_exec (int fd
)
177 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
182 # define accept4(sockfd, addr, addrlen, flags) \
183 process_accept4 (sockfd, addr, addrlen, flags)
185 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
187 return close_on_exec (accept (sockfd
, addr
, addrlen
));
191 process_socket (int domain
, int type
, int protocol
)
193 return close_on_exec (socket (domain
, type
, protocol
));
196 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
199 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
200 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
201 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
202 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
203 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
204 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
206 /* Number of events of change of status of a process. */
207 static EMACS_INT process_tick
;
208 /* Number of events for which the user or sentinel has been notified. */
209 static EMACS_INT update_tick
;
211 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
212 this system. We need to read full packets, so we need a
213 "non-destructive" select. So we require either native select,
214 or emulation of select using FIONREAD. */
216 #ifndef BROKEN_DATAGRAM_SOCKETS
217 # if defined HAVE_SELECT || defined USABLE_FIONREAD
218 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
219 # define DATAGRAM_SOCKETS
224 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
225 # define HAVE_SEQPACKET
228 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
229 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
230 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
232 /* Number of processes which have a non-zero read_output_delay,
233 and therefore might be delayed for adaptive read buffering. */
235 static int process_output_delay_count
;
237 /* True if any process has non-nil read_output_skip. */
239 static bool process_output_skip
;
241 static void create_process (Lisp_Object
, char **, Lisp_Object
);
243 static bool keyboard_bit_set (fd_set
*);
245 static void deactivate_process (Lisp_Object
);
246 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
247 static int read_process_output (Lisp_Object
, int);
248 static void handle_child_signal (int);
249 static void create_pty (Lisp_Object
);
251 static Lisp_Object
get_process (register Lisp_Object name
);
252 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
254 /* Mask of bits indicating the descriptors that we wait for input on. */
256 static fd_set input_wait_mask
;
258 /* Mask that excludes keyboard input descriptor(s). */
260 static fd_set non_keyboard_wait_mask
;
262 /* Mask that excludes process input descriptor(s). */
264 static fd_set non_process_wait_mask
;
266 /* Mask for selecting for write. */
268 static fd_set write_mask
;
270 /* Mask of bits indicating the descriptors that we wait for connect to
271 complete on. Once they complete, they are removed from this mask
272 and added to the input_wait_mask and non_keyboard_wait_mask. */
274 static fd_set connect_wait_mask
;
276 /* Number of bits set in connect_wait_mask. */
277 static int num_pending_connects
;
279 /* The largest descriptor currently in use for a process object; -1 if none. */
280 static int max_process_desc
;
282 /* The largest descriptor currently in use for input; -1 if none. */
283 static int max_input_desc
;
285 /* Set the external socket descriptor for Emacs to use when
286 `make-network-process' is called with a non-nil
287 `:use-external-socket' option. The value should be either -1, or
288 the file descriptor of a socket that is already bound. */
289 static int external_sock_fd
;
291 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
292 static Lisp_Object chan_process
[FD_SETSIZE
];
293 static void wait_for_socket_fds (Lisp_Object
, char const *);
295 /* Alist of elements (NAME . PROCESS). */
296 static Lisp_Object Vprocess_alist
;
298 /* Buffered-ahead input char from process, indexed by channel.
299 -1 means empty (no char is buffered).
300 Used on sys V where the only way to tell if there is any
301 output from the process is to read at least one char.
302 Always -1 on systems that support FIONREAD. */
304 static int proc_buffered_char
[FD_SETSIZE
];
306 /* Table of `struct coding-system' for each process. */
307 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
308 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
310 #ifdef DATAGRAM_SOCKETS
311 /* Table of `partner address' for datagram sockets. */
312 static struct sockaddr_and_len
{
315 } datagram_address
[FD_SETSIZE
];
316 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
317 #define DATAGRAM_CONN_P(proc) \
318 (PROCESSP (proc) && \
319 XPROCESS (proc)->infd >= 0 && \
320 datagram_address[XPROCESS (proc)->infd].sa != 0)
322 #define DATAGRAM_CONN_P(proc) (0)
325 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
326 a `for' loop which iterates over processes from Vprocess_alist. */
328 #define FOR_EACH_PROCESS(list_var, proc_var) \
329 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
331 /* These setters are used only in this file, so they can be private. */
333 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
338 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
343 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
345 p
->decode_coding_system
= val
;
348 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
350 p
->decoding_buf
= val
;
353 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
355 p
->encode_coding_system
= val
;
358 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
360 p
->encoding_buf
= val
;
363 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
365 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
368 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
373 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
383 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
388 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
390 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
393 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
398 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
403 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
405 p
->write_queue
= val
;
408 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
415 make_lisp_proc (struct Lisp_Process
*p
)
417 return make_lisp_ptr (p
, Lisp_Vectorlike
);
420 static struct fd_callback_data
426 int condition
; /* Mask of the defines above. */
427 } fd_callback_info
[FD_SETSIZE
];
430 /* Add a file descriptor FD to be monitored for when read is possible.
431 When read is possible, call FUNC with argument DATA. */
434 add_read_fd (int fd
, fd_callback func
, void *data
)
436 add_keyboard_wait_descriptor (fd
);
438 fd_callback_info
[fd
].func
= func
;
439 fd_callback_info
[fd
].data
= data
;
440 fd_callback_info
[fd
].condition
|= FOR_READ
;
443 /* Stop monitoring file descriptor FD for when read is possible. */
446 delete_read_fd (int fd
)
448 delete_keyboard_wait_descriptor (fd
);
450 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
451 if (fd_callback_info
[fd
].condition
== 0)
453 fd_callback_info
[fd
].func
= 0;
454 fd_callback_info
[fd
].data
= 0;
458 /* Add a file descriptor FD to be monitored for when write is possible.
459 When write is possible, call FUNC with argument DATA. */
462 add_write_fd (int fd
, fd_callback func
, void *data
)
464 FD_SET (fd
, &write_mask
);
465 if (fd
> max_input_desc
)
468 fd_callback_info
[fd
].func
= func
;
469 fd_callback_info
[fd
].data
= data
;
470 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
473 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
476 delete_input_desc (int fd
)
478 if (fd
== max_input_desc
)
482 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
483 || FD_ISSET (fd
, &write_mask
)));
489 /* Stop monitoring file descriptor FD for when write is possible. */
492 delete_write_fd (int fd
)
494 FD_CLR (fd
, &write_mask
);
495 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
496 if (fd_callback_info
[fd
].condition
== 0)
498 fd_callback_info
[fd
].func
= 0;
499 fd_callback_info
[fd
].data
= 0;
500 delete_input_desc (fd
);
505 /* Compute the Lisp form of the process status, p->status, from
506 the numeric status that was returned by `wait'. */
508 static Lisp_Object
status_convert (int);
511 update_status (struct Lisp_Process
*p
)
513 eassert (p
->raw_status_new
);
514 pset_status (p
, status_convert (p
->raw_status
));
515 p
->raw_status_new
= 0;
518 /* Convert a process status word in Unix format to
519 the list that we use internally. */
522 status_convert (int w
)
525 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
526 else if (WIFEXITED (w
))
527 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
528 WCOREDUMP (w
) ? Qt
: Qnil
));
529 else if (WIFSIGNALED (w
))
530 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
531 WCOREDUMP (w
) ? Qt
: Qnil
));
536 /* Given a status-list, extract the three pieces of information
537 and store them individually through the three pointers. */
540 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, Lisp_Object
*code
,
548 *code
= make_number (0);
557 *coredump
= !NILP (tem
);
561 /* Return a string describing a process status list. */
564 status_message (struct Lisp_Process
*p
)
566 Lisp_Object status
= p
->status
;
567 Lisp_Object symbol
, code
;
571 decode_status (status
, &symbol
, &code
, &coredump
);
573 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
576 synchronize_system_messages_locale ();
577 signame
= strsignal (XFASTINT (code
));
579 string
= build_string ("unknown");
584 string
= build_unibyte_string (signame
);
585 if (! NILP (Vlocale_coding_system
))
586 string
= (code_convert_string_norecord
587 (string
, Vlocale_coding_system
, 0));
588 c1
= STRING_CHAR (SDATA (string
));
591 Faset (string
, make_number (0), make_number (c2
));
593 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
594 return concat2 (string
, suffix
);
596 else if (EQ (symbol
, Qexit
))
599 return build_string (XFASTINT (code
) == 0
601 : "connection broken by remote peer\n");
602 if (XFASTINT (code
) == 0)
603 return build_string ("finished\n");
604 AUTO_STRING (prefix
, "exited abnormally with code ");
605 string
= Fnumber_to_string (code
);
606 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
607 return concat3 (prefix
, string
, suffix
);
609 else if (EQ (symbol
, Qfailed
))
611 AUTO_STRING (format
, "failed with code %s\n");
612 return CALLN (Fformat
, format
, code
);
615 return Fcopy_sequence (Fsymbol_name (symbol
));
618 enum { PTY_NAME_SIZE
= 24 };
620 /* Open an available pty, returning a file descriptor.
621 Store into PTY_NAME the file name of the terminal corresponding to the pty.
622 Return -1 on failure. */
625 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
634 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
635 for (i
= 0; i
< 16; i
++)
638 #ifdef PTY_NAME_SPRINTF
641 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
642 #endif /* no PTY_NAME_SPRINTF */
646 #else /* no PTY_OPEN */
647 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
648 #endif /* no PTY_OPEN */
652 #ifdef PTY_TTY_NAME_SPRINTF
655 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
656 #endif /* no PTY_TTY_NAME_SPRINTF */
658 /* Set FD's close-on-exec flag. This is needed even if
659 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
660 doesn't require support for that combination.
661 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
662 doesn't work if the close-on-exec flag is set (Bug#20555).
663 Multithreaded platforms where posix_openpt ignores
664 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
665 have a race condition between the PTY_OPEN and here. */
666 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
668 /* Check to make certain that both sides are available.
669 This avoids a nasty yet stupid bug in rlogins. */
670 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
683 #endif /* HAVE_PTYS */
687 /* Allocate basically initialized process. */
689 static struct Lisp_Process
*
690 allocate_process (void)
692 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
696 make_process (Lisp_Object name
)
698 struct Lisp_Process
*p
= allocate_process ();
699 /* Initialize Lisp data. Note that allocate_process initializes all
700 Lisp data to nil, so do it only for slots which should not be nil. */
701 pset_status (p
, Qrun
);
702 pset_mark (p
, Fmake_marker ());
704 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
705 non-Lisp data, so do it only for slots which should not be zero. */
708 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
712 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
713 p
->gnutls_boot_parameters
= Qnil
;
716 /* If name is already in use, modify it until it is unused. */
718 Lisp_Object name1
= name
;
719 for (printmax_t i
= 1; ; i
++)
721 Lisp_Object tem
= Fget_process (name1
);
724 char const suffix_fmt
[] = "<%"pMd
">";
725 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
726 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
727 name1
= concat2 (name
, lsuffix
);
731 pset_sentinel (p
, Qinternal_default_process_sentinel
);
732 pset_filter (p
, Qinternal_default_process_filter
);
734 XSETPROCESS (val
, p
);
735 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
740 remove_process (register Lisp_Object proc
)
742 register Lisp_Object pair
;
744 pair
= Frassq (proc
, Vprocess_alist
);
745 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
747 deactivate_process (proc
);
750 #ifdef HAVE_GETADDRINFO_A
752 free_dns_request (Lisp_Object proc
)
754 struct Lisp_Process
*p
= XPROCESS (proc
);
756 if (p
->dns_request
->ar_result
)
757 freeaddrinfo (p
->dns_request
->ar_result
);
758 xfree (p
->dns_request
);
759 p
->dns_request
= NULL
;
764 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
765 doc
: /* Return t if OBJECT is a process. */)
768 return PROCESSP (object
) ? Qt
: Qnil
;
771 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
772 doc
: /* Return the process named NAME, or nil if there is none. */)
773 (register Lisp_Object name
)
778 return Fcdr (Fassoc (name
, Vprocess_alist
));
781 /* This is how commands for the user decode process arguments. It
782 accepts a process, a process name, a buffer, a buffer name, or nil.
783 Buffers denote the first process in the buffer, and nil denotes the
787 get_process (register Lisp_Object name
)
789 register Lisp_Object proc
, obj
;
792 obj
= Fget_process (name
);
794 obj
= Fget_buffer (name
);
796 error ("Process %s does not exist", SDATA (name
));
798 else if (NILP (name
))
799 obj
= Fcurrent_buffer ();
803 /* Now obj should be either a buffer object or a process object. */
806 if (NILP (BVAR (XBUFFER (obj
), name
)))
807 error ("Attempt to get process for a dead buffer");
808 proc
= Fget_buffer_process (obj
);
810 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
821 /* Fdelete_process promises to immediately forget about the process, but in
822 reality, Emacs needs to remember those processes until they have been
823 treated by the SIGCHLD handler and waitpid has been invoked on them;
824 otherwise they might fill up the kernel's process table.
826 Some processes created by call-process are also put onto this list.
828 Members of this list are (process-ID . filename) pairs. The
829 process-ID is a number; the filename, if a string, is a file that
830 needs to be removed after the process exits. */
831 static Lisp_Object deleted_pid_list
;
834 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
836 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
837 /* GC treated elements set to nil. */
838 Fdelq (Qnil
, deleted_pid_list
));
842 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
843 doc
: /* Delete PROCESS: kill it and forget about it immediately.
844 PROCESS may be a process, a buffer, the name of a process or buffer, or
845 nil, indicating the current buffer's process. */)
846 (register Lisp_Object process
)
848 register struct Lisp_Process
*p
;
850 process
= get_process (process
);
851 p
= XPROCESS (process
);
853 #ifdef HAVE_GETADDRINFO_A
856 /* Cancel the request. Unless shutting down, wait until
857 completion. Free the request if completely canceled. */
859 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
860 if (!canceled
&& !inhibit_sentinels
)
862 struct gaicb
const *req
= p
->dns_request
;
863 while (gai_suspend (&req
, 1, NULL
) != 0)
868 free_dns_request (process
);
872 p
->raw_status_new
= 0;
873 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
875 pset_status (p
, list2 (Qexit
, make_number (0)));
876 p
->tick
= ++process_tick
;
877 status_notify (p
, NULL
);
878 redisplay_preserve_echo_area (13);
883 record_kill_process (p
, Qnil
);
887 /* Update P's status, since record_kill_process will make the
888 SIGCHLD handler update deleted_pid_list, not *P. */
890 if (p
->raw_status_new
)
892 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
893 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
894 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
896 p
->tick
= ++process_tick
;
897 status_notify (p
, NULL
);
898 redisplay_preserve_echo_area (13);
901 remove_process (process
);
905 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
906 doc
: /* Return the status of PROCESS.
907 The returned value is one of the following symbols:
908 run -- for a process that is running.
909 stop -- for a process stopped but continuable.
910 exit -- for a process that has exited.
911 signal -- for a process that has got a fatal signal.
912 open -- for a network stream connection that is open.
913 listen -- for a network stream server that is listening.
914 closed -- for a network stream connection that is closed.
915 connect -- when waiting for a non-blocking connection to complete.
916 failed -- when a non-blocking connection has failed.
917 nil -- if arg is a process name and no such process exists.
918 PROCESS may be a process, a buffer, the name of a process, or
919 nil, indicating the current buffer's process. */)
920 (register Lisp_Object process
)
922 register struct Lisp_Process
*p
;
923 register Lisp_Object status
;
925 if (STRINGP (process
))
926 process
= Fget_process (process
);
928 process
= get_process (process
);
933 p
= XPROCESS (process
);
934 if (p
->raw_status_new
)
938 status
= XCAR (status
);
939 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
941 if (EQ (status
, Qexit
))
943 else if (EQ (p
->command
, Qt
))
945 else if (EQ (status
, Qrun
))
951 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
953 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
954 If PROCESS has not yet exited or died, return 0. */)
955 (register Lisp_Object process
)
957 CHECK_PROCESS (process
);
958 if (XPROCESS (process
)->raw_status_new
)
959 update_status (XPROCESS (process
));
960 if (CONSP (XPROCESS (process
)->status
))
961 return XCAR (XCDR (XPROCESS (process
)->status
));
962 return make_number (0);
965 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
966 doc
: /* Return the process id of PROCESS.
967 This is the pid of the external process which PROCESS uses or talks to.
968 For a network connection, this value is nil. */)
969 (register Lisp_Object process
)
973 CHECK_PROCESS (process
);
974 pid
= XPROCESS (process
)->pid
;
975 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
978 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
979 doc
: /* Return the name of PROCESS, as a string.
980 This is the name of the program invoked in PROCESS,
981 possibly modified to make it unique among process names. */)
982 (register Lisp_Object process
)
984 CHECK_PROCESS (process
);
985 return XPROCESS (process
)->name
;
988 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
989 doc
: /* Return the command that was executed to start PROCESS.
990 This is a list of strings, the first string being the program executed
991 and the rest of the strings being the arguments given to it.
992 For a network or serial process, this is nil (process is running) or t
993 \(process is stopped). */)
994 (register Lisp_Object process
)
996 CHECK_PROCESS (process
);
997 return XPROCESS (process
)->command
;
1000 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1001 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1002 This is the terminal that the process itself reads and writes on,
1003 not the name of the pty that Emacs uses to talk with that terminal. */)
1004 (register Lisp_Object process
)
1006 CHECK_PROCESS (process
);
1007 return XPROCESS (process
)->tty_name
;
1010 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1012 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1014 (register Lisp_Object process
, Lisp_Object buffer
)
1016 struct Lisp_Process
*p
;
1018 CHECK_PROCESS (process
);
1020 CHECK_BUFFER (buffer
);
1021 p
= XPROCESS (process
);
1022 pset_buffer (p
, buffer
);
1023 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1024 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1025 setup_process_coding_systems (process
);
1029 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1031 doc
: /* Return the buffer PROCESS is associated with.
1032 The default process filter inserts output from PROCESS into this buffer. */)
1033 (register Lisp_Object process
)
1035 CHECK_PROCESS (process
);
1036 return XPROCESS (process
)->buffer
;
1039 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1041 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1042 (register Lisp_Object process
)
1044 CHECK_PROCESS (process
);
1045 return XPROCESS (process
)->mark
;
1049 set_process_filter_masks (struct Lisp_Process
*p
)
1051 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1053 FD_CLR (p
->infd
, &input_wait_mask
);
1054 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1056 else if (EQ (p
->filter
, Qt
)
1057 /* Network or serial process not stopped: */
1058 && !EQ (p
->command
, Qt
))
1060 FD_SET (p
->infd
, &input_wait_mask
);
1061 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1065 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1067 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1068 A value of t means stop accepting output from the process.
1070 When a process has a non-default filter, its buffer is not used for output.
1071 Instead, each time it does output, the entire string of output is
1072 passed to the filter.
1074 The filter gets two arguments: the process and the string of output.
1075 The string argument is normally a multibyte string, except:
1076 - if the process's input coding system is no-conversion or raw-text,
1077 it is a unibyte string (the non-converted input), or else
1078 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1079 string (the result of converting the decoded input multibyte
1080 string to unibyte with `string-make-unibyte'). */)
1081 (Lisp_Object process
, Lisp_Object filter
)
1083 CHECK_PROCESS (process
);
1084 struct Lisp_Process
*p
= XPROCESS (process
);
1086 /* Don't signal an error if the process's input file descriptor
1087 is closed. This could make debugging Lisp more difficult,
1088 for example when doing something like
1090 (setq process (start-process ...))
1092 (set-process-filter process ...) */
1095 filter
= Qinternal_default_process_filter
;
1097 pset_filter (p
, filter
);
1100 set_process_filter_masks (p
);
1102 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1103 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1104 setup_process_coding_systems (process
);
1108 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1110 doc
: /* Return the filter function of PROCESS.
1111 See `set-process-filter' for more info on filter functions. */)
1112 (register Lisp_Object process
)
1114 CHECK_PROCESS (process
);
1115 return XPROCESS (process
)->filter
;
1118 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1120 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1121 The sentinel is called as a function when the process changes state.
1122 It gets two arguments: the process, and a string describing the change. */)
1123 (register Lisp_Object process
, Lisp_Object sentinel
)
1125 struct Lisp_Process
*p
;
1127 CHECK_PROCESS (process
);
1128 p
= XPROCESS (process
);
1130 if (NILP (sentinel
))
1131 sentinel
= Qinternal_default_process_sentinel
;
1133 pset_sentinel (p
, sentinel
);
1134 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1135 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1139 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1141 doc
: /* Return the sentinel of PROCESS.
1142 See `set-process-sentinel' for more info on sentinels. */)
1143 (register Lisp_Object process
)
1145 CHECK_PROCESS (process
);
1146 return XPROCESS (process
)->sentinel
;
1149 DEFUN ("set-process-window-size", Fset_process_window_size
,
1150 Sset_process_window_size
, 3, 3, 0,
1151 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1152 Value is t if PROCESS was successfully told about the window size,
1154 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1156 CHECK_PROCESS (process
);
1158 /* All known platforms store window sizes as 'unsigned short'. */
1159 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1160 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1162 if (NETCONN_P (process
)
1163 || XPROCESS (process
)->infd
< 0
1164 || (set_window_size (XPROCESS (process
)->infd
,
1165 XINT (height
), XINT (width
))
1172 DEFUN ("set-process-inherit-coding-system-flag",
1173 Fset_process_inherit_coding_system_flag
,
1174 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1175 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1176 If the second argument FLAG is non-nil, then the variable
1177 `buffer-file-coding-system' of the buffer associated with PROCESS
1178 will be bound to the value of the coding system used to decode
1181 This is useful when the coding system specified for the process buffer
1182 leaves either the character code conversion or the end-of-line conversion
1183 unspecified, or if the coding system used to decode the process output
1184 is more appropriate for saving the process buffer.
1186 Binding the variable `inherit-process-coding-system' to non-nil before
1187 starting the process is an alternative way of setting the inherit flag
1188 for the process which will run.
1190 This function returns FLAG. */)
1191 (register Lisp_Object process
, Lisp_Object flag
)
1193 CHECK_PROCESS (process
);
1194 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1198 DEFUN ("set-process-query-on-exit-flag",
1199 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1201 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1202 If the second argument FLAG is non-nil, Emacs will query the user before
1203 exiting or killing a buffer if PROCESS is running. This function
1205 (register Lisp_Object process
, Lisp_Object flag
)
1207 CHECK_PROCESS (process
);
1208 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1212 DEFUN ("process-query-on-exit-flag",
1213 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1215 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1216 (register Lisp_Object process
)
1218 CHECK_PROCESS (process
);
1219 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1222 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1224 doc
: /* Return the contact info of PROCESS; t for a real child.
1225 For a network or serial connection, the value depends on the optional
1226 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1227 SERVICE) for a network connection or (PORT SPEED) for a serial
1228 connection. If KEY is t, the complete contact information for the
1229 connection is returned, else the specific value for the keyword KEY is
1230 returned. See `make-network-process' or `make-serial-process' for a
1232 If PROCESS is a non-blocking network process that hasn't been fully
1233 set up yet, this function will block until socket setup has completed. */)
1234 (Lisp_Object process
, Lisp_Object key
)
1236 Lisp_Object contact
;
1238 CHECK_PROCESS (process
);
1239 contact
= XPROCESS (process
)->childp
;
1241 #ifdef DATAGRAM_SOCKETS
1243 if (NETCONN_P (process
))
1244 wait_for_socket_fds (process
, "process-contact");
1246 if (DATAGRAM_CONN_P (process
)
1247 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1248 contact
= Fplist_put (contact
, QCremote
,
1249 Fprocess_datagram_address (process
));
1252 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1255 if (NILP (key
) && NETCONN_P (process
))
1256 return list2 (Fplist_get (contact
, QChost
),
1257 Fplist_get (contact
, QCservice
));
1258 if (NILP (key
) && SERIALCONN_P (process
))
1259 return list2 (Fplist_get (contact
, QCport
),
1260 Fplist_get (contact
, QCspeed
));
1261 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1262 if the pipe process is useful for purposes other than receiving
1264 if (NILP (key
) && PIPECONN_P (process
))
1266 return Fplist_get (contact
, key
);
1269 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1271 doc
: /* Return the plist of PROCESS. */)
1272 (register Lisp_Object process
)
1274 CHECK_PROCESS (process
);
1275 return XPROCESS (process
)->plist
;
1278 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1280 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1281 (Lisp_Object process
, Lisp_Object plist
)
1283 CHECK_PROCESS (process
);
1286 pset_plist (XPROCESS (process
), plist
);
1290 #if 0 /* Turned off because we don't currently record this info
1291 in the process. Perhaps add it. */
1292 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1293 doc
: /* Return the connection type of PROCESS.
1294 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1295 a socket connection. */)
1296 (Lisp_Object process
)
1298 return XPROCESS (process
)->type
;
1302 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1303 doc
: /* Return the connection type of PROCESS.
1304 The value is either the symbol `real', `network', or `serial'.
1305 PROCESS may be a process, a buffer, the name of a process or buffer, or
1306 nil, indicating the current buffer's process. */)
1307 (Lisp_Object process
)
1310 proc
= get_process (process
);
1311 return XPROCESS (proc
)->type
;
1314 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1316 doc
: /* Convert network ADDRESS from internal format to a string.
1317 A 4 or 5 element vector represents an IPv4 address (with port number).
1318 An 8 or 9 element vector represents an IPv6 address (with port number).
1319 If optional second argument OMIT-PORT is non-nil, don't include a port
1320 number in the string, even when present in ADDRESS.
1321 Return nil if format of ADDRESS is invalid. */)
1322 (Lisp_Object address
, Lisp_Object omit_port
)
1327 if (STRINGP (address
)) /* AF_LOCAL */
1330 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1332 register struct Lisp_Vector
*p
= XVECTOR (address
);
1333 ptrdiff_t size
= p
->header
.size
;
1334 Lisp_Object args
[10];
1338 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1340 format
= "%d.%d.%d.%d";
1345 format
= "%d.%d.%d.%d:%d";
1348 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1350 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1355 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1361 AUTO_STRING (format_obj
, format
);
1362 args
[0] = format_obj
;
1364 for (i
= 0; i
< nargs
; i
++)
1366 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1369 if (nargs
<= 5 /* IPv4 */
1370 && i
< 4 /* host, not port */
1371 && XINT (p
->contents
[i
]) > 255)
1374 args
[i
+ 1] = p
->contents
[i
];
1377 return Fformat (nargs
+ 1, args
);
1380 if (CONSP (address
))
1382 AUTO_STRING (format
, "<Family %d>");
1383 return CALLN (Fformat
, format
, Fcar (address
));
1389 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1390 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1393 return Fmapcar (Qcdr
, Vprocess_alist
);
1396 /* Starting asynchronous inferior processes. */
1398 static void start_process_unwind (Lisp_Object proc
);
1400 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1401 doc
: /* Start a program in a subprocess. Return the process object for it.
1403 This is similar to `start-process', but arguments are specified as
1404 keyword/argument pairs. The following arguments are defined:
1406 :name NAME -- NAME is name for process. It is modified if necessary
1409 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1410 with the process. Process output goes at end of that buffer, unless
1411 you specify an output stream or filter function to handle the output.
1412 BUFFER may be also nil, meaning that this process is not associated
1415 :command COMMAND -- COMMAND is a list starting with the program file
1416 name, followed by strings to give to the program as arguments.
1418 :coding CODING -- If CODING is a symbol, it specifies the coding
1419 system used for both reading and writing for this process. If CODING
1420 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1421 ENCODING is used for writing.
1423 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1424 the process is running. If BOOL is not given, query before exiting.
1426 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1427 In the stopped state, a process does not accept incoming data, but you
1428 can send outgoing data. The stopped state is cleared by
1429 `continue-process' and set by `stop-process'.
1431 :connection-type TYPE -- TYPE is control type of device used to
1432 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1433 to use a pty, or nil to use the default specified through
1434 `process-connection-type'.
1436 :filter FILTER -- Install FILTER as the process filter.
1438 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1440 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1441 to the standard error of subprocess. Specifying this implies
1442 `:connection-type' is set to `pipe'.
1444 usage: (make-process &rest ARGS) */)
1445 (ptrdiff_t nargs
, Lisp_Object
*args
)
1447 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1448 Lisp_Object xstderr
, stderrproc
;
1449 ptrdiff_t count
= SPECPDL_INDEX ();
1455 /* Save arguments for process-contact and clone-process. */
1456 contact
= Flist (nargs
, args
);
1458 buffer
= Fplist_get (contact
, QCbuffer
);
1460 buffer
= Fget_buffer_create (buffer
);
1462 /* Make sure that the child will be able to chdir to the current
1463 buffer's current directory, or its unhandled equivalent. We
1464 can't just have the child check for an error when it does the
1465 chdir, since it's in a vfork. */
1466 current_dir
= encode_current_directory ();
1468 name
= Fplist_get (contact
, QCname
);
1469 CHECK_STRING (name
);
1471 command
= Fplist_get (contact
, QCcommand
);
1472 if (CONSP (command
))
1473 program
= XCAR (command
);
1477 if (!NILP (program
))
1478 CHECK_STRING (program
);
1481 xstderr
= Fplist_get (contact
, QCstderr
);
1482 if (PROCESSP (xstderr
))
1484 if (!PIPECONN_P (xstderr
))
1485 error ("Process is not a pipe process");
1486 stderrproc
= xstderr
;
1488 else if (!NILP (xstderr
))
1490 CHECK_STRING (program
);
1491 stderrproc
= CALLN (Fmake_pipe_process
,
1493 concat2 (name
, build_string (" stderr")),
1495 Fget_buffer_create (xstderr
));
1498 proc
= make_process (name
);
1499 /* If an error occurs and we can't start the process, we want to
1500 remove it from the process list. This means that each error
1501 check in create_process doesn't need to call remove_process
1502 itself; it's all taken care of here. */
1503 record_unwind_protect (start_process_unwind
, proc
);
1505 pset_childp (XPROCESS (proc
), Qt
);
1506 pset_plist (XPROCESS (proc
), Qnil
);
1507 pset_type (XPROCESS (proc
), Qreal
);
1508 pset_buffer (XPROCESS (proc
), buffer
);
1509 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1510 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1511 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1513 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1514 XPROCESS (proc
)->kill_without_query
= 1;
1515 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1516 pset_command (XPROCESS (proc
), Qt
);
1518 tem
= Fplist_get (contact
, QCconnection_type
);
1520 XPROCESS (proc
)->pty_flag
= true;
1521 else if (EQ (tem
, Qpipe
))
1522 XPROCESS (proc
)->pty_flag
= false;
1523 else if (NILP (tem
))
1524 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1526 report_file_error ("Unknown connection type", tem
);
1528 if (!NILP (stderrproc
))
1530 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1532 XPROCESS (proc
)->pty_flag
= false;
1536 /* AKA GNUTLS_INITSTAGE(proc). */
1537 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1538 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1541 XPROCESS (proc
)->adaptive_read_buffering
1542 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1543 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1545 /* Make the process marker point into the process buffer (if any). */
1546 if (BUFFERP (buffer
))
1547 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1548 BUF_ZV (XBUFFER (buffer
)),
1549 BUF_ZV_BYTE (XBUFFER (buffer
)));
1552 /* Decide coding systems for communicating with the process. Here
1553 we don't setup the structure coding_system nor pay attention to
1554 unibyte mode. They are done in create_process. */
1556 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1557 Lisp_Object coding_systems
= Qt
;
1558 Lisp_Object val
, *args2
;
1560 tem
= Fplist_get (contact
, QCcoding
);
1568 val
= Vcoding_system_for_read
;
1571 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1573 SAFE_ALLOCA_LISP (args2
, nargs2
);
1575 args2
[i
++] = Qstart_process
;
1577 args2
[i
++] = buffer
;
1578 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1579 args2
[i
++] = XCAR (tem2
);
1580 if (!NILP (program
))
1581 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1582 if (CONSP (coding_systems
))
1583 val
= XCAR (coding_systems
);
1584 else if (CONSP (Vdefault_process_coding_system
))
1585 val
= XCAR (Vdefault_process_coding_system
);
1587 pset_decode_coding_system (XPROCESS (proc
), val
);
1596 val
= Vcoding_system_for_write
;
1599 if (EQ (coding_systems
, Qt
))
1601 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1603 SAFE_ALLOCA_LISP (args2
, nargs2
);
1605 args2
[i
++] = Qstart_process
;
1607 args2
[i
++] = buffer
;
1608 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1609 args2
[i
++] = XCAR (tem2
);
1610 if (!NILP (program
))
1611 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1613 if (CONSP (coding_systems
))
1614 val
= XCDR (coding_systems
);
1615 else if (CONSP (Vdefault_process_coding_system
))
1616 val
= XCDR (Vdefault_process_coding_system
);
1618 pset_encode_coding_system (XPROCESS (proc
), val
);
1619 /* Note: At this moment, the above coding system may leave
1620 text-conversion or eol-conversion unspecified. They will be
1621 decided after we read output from the process and decode it by
1622 some coding system, or just before we actually send a text to
1627 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1628 XPROCESS (proc
)->decoding_carryover
= 0;
1629 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1631 XPROCESS (proc
)->inherit_coding_system_flag
1632 = !(NILP (buffer
) || !inherit_process_coding_system
);
1634 if (!NILP (program
))
1636 Lisp_Object program_args
= XCDR (command
);
1638 /* If program file name is not absolute, search our path for it.
1639 Put the name we will really use in TEM. */
1640 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1641 && !(SCHARS (program
) > 1
1642 && IS_DEVICE_SEP (SREF (program
, 1))))
1645 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1646 make_number (X_OK
), false);
1648 report_file_error ("Searching for program", program
);
1649 tem
= Fexpand_file_name (tem
, Qnil
);
1653 if (!NILP (Ffile_directory_p (program
)))
1654 error ("Specified program for new process is a directory");
1658 /* Remove "/:" from TEM. */
1659 tem
= remove_slash_colon (tem
);
1661 Lisp_Object arg_encoding
= Qnil
;
1663 /* Encode the file name and put it in NEW_ARGV.
1664 That's where the child will use it to execute the program. */
1665 tem
= list1 (ENCODE_FILE (tem
));
1666 ptrdiff_t new_argc
= 1;
1668 /* Here we encode arguments by the coding system used for sending
1669 data to the process. We don't support using different coding
1670 systems for encoding arguments and for encoding data sent to the
1673 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1675 Lisp_Object arg
= XCAR (tem2
);
1677 if (STRING_MULTIBYTE (arg
))
1679 if (NILP (arg_encoding
))
1680 arg_encoding
= (complement_process_encoding_system
1681 (XPROCESS (proc
)->encode_coding_system
));
1682 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1684 tem
= Fcons (arg
, tem
);
1688 /* Now that everything is encoded we can collect the strings into
1691 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1692 new_argv
[new_argc
] = 0;
1694 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1696 new_argv
[i
] = SSDATA (XCAR (tem
));
1700 create_process (proc
, new_argv
, current_dir
);
1706 return unbind_to (count
, proc
);
1709 /* This function is the unwind_protect form for Fstart_process. If
1710 PROC doesn't have its pid set, then we know someone has signaled
1711 an error and the process wasn't started successfully, so we should
1712 remove it from the process list. */
1714 start_process_unwind (Lisp_Object proc
)
1716 if (!PROCESSP (proc
))
1719 /* Was PROC started successfully?
1720 -2 is used for a pty with no process, eg for gdb. */
1721 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1722 remove_process (proc
);
1725 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1728 close_process_fd (int *fd_addr
)
1738 /* Indexes of file descriptors in open_fds. */
1741 /* The pipe from Emacs to its subprocess. */
1743 WRITE_TO_SUBPROCESS
,
1745 /* The main pipe from the subprocess to Emacs. */
1746 READ_FROM_SUBPROCESS
,
1749 /* The pipe from the subprocess to Emacs that is closed when the
1750 subprocess execs. */
1751 READ_FROM_EXEC_MONITOR
,
1755 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1758 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1760 struct Lisp_Process
*p
= XPROCESS (process
);
1761 int inchannel
, outchannel
;
1764 int forkin
, forkout
, forkerr
= -1;
1766 char pty_name
[PTY_NAME_SIZE
];
1767 Lisp_Object lisp_pty_name
= Qnil
;
1770 inchannel
= outchannel
= -1;
1773 outchannel
= inchannel
= allocate_pty (pty_name
);
1777 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1778 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1779 /* On most USG systems it does not work to open the pty's tty here,
1780 then close it and reopen it in the child. */
1781 /* Don't let this terminal become our controlling terminal
1782 (in case we don't have one). */
1783 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1785 report_file_error ("Opening pty", Qnil
);
1786 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1788 forkin
= forkout
= -1;
1789 #endif /* not USG, or USG_SUBTTY_WORKS */
1791 lisp_pty_name
= build_string (pty_name
);
1795 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1796 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1797 report_file_error ("Creating pipe", Qnil
);
1798 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1799 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1800 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1801 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1803 if (!NILP (p
->stderrproc
))
1805 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1807 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1809 /* Close unnecessary file descriptors. */
1810 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1811 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1816 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1817 report_file_error ("Creating pipe", Qnil
);
1820 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1821 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1823 /* Record this as an active process, with its channels. */
1824 chan_process
[inchannel
] = process
;
1825 p
->infd
= inchannel
;
1826 p
->outfd
= outchannel
;
1828 /* Previously we recorded the tty descriptor used in the subprocess.
1829 It was only used for getting the foreground tty process, so now
1830 we just reopen the device (see emacs_get_tty_pgrp) as this is
1831 more portable (see USG_SUBTTY_WORKS above). */
1833 p
->pty_flag
= pty_flag
;
1834 pset_status (p
, Qrun
);
1836 if (!EQ (p
->command
, Qt
))
1838 FD_SET (inchannel
, &input_wait_mask
);
1839 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1842 if (inchannel
> max_process_desc
)
1843 max_process_desc
= inchannel
;
1845 /* This may signal an error. */
1846 setup_process_coding_systems (process
);
1849 block_child_signal (&oldset
);
1852 /* vfork, and prevent local vars from being clobbered by the vfork. */
1853 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1854 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1855 char **volatile new_argv_volatile
= new_argv
;
1856 int volatile forkin_volatile
= forkin
;
1857 int volatile forkout_volatile
= forkout
;
1858 int volatile forkerr_volatile
= forkerr
;
1859 struct Lisp_Process
*p_volatile
= p
;
1863 current_dir
= current_dir_volatile
;
1864 lisp_pty_name
= lisp_pty_name_volatile
;
1865 new_argv
= new_argv_volatile
;
1866 forkin
= forkin_volatile
;
1867 forkout
= forkout_volatile
;
1868 forkerr
= forkerr_volatile
;
1871 pty_flag
= p
->pty_flag
;
1874 #endif /* not WINDOWSNT */
1876 /* Make the pty be the controlling terminal of the process. */
1878 /* First, disconnect its current controlling terminal. */
1879 /* We tried doing setsid only if pty_flag, but it caused
1880 process_set_signal to fail on SGI when using a pipe. */
1882 /* Make the pty's terminal the controlling terminal. */
1883 if (pty_flag
&& forkin
>= 0)
1886 /* We ignore the return value
1887 because faith@cs.unc.edu says that is necessary on Linux. */
1888 ioctl (forkin
, TIOCSCTTY
, 0);
1891 #if defined (LDISC1)
1892 if (pty_flag
&& forkin
>= 0)
1895 tcgetattr (forkin
, &t
);
1897 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1898 emacs_perror ("create_process/tcsetattr LDISC1");
1901 #if defined (NTTYDISC) && defined (TIOCSETD)
1902 if (pty_flag
&& forkin
>= 0)
1904 /* Use new line discipline. */
1905 int ldisc
= NTTYDISC
;
1906 ioctl (forkin
, TIOCSETD
, &ldisc
);
1911 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1912 can do TIOCSPGRP only to the process's controlling tty. */
1915 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1916 I can't test it since I don't have 4.3. */
1917 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1920 ioctl (j
, TIOCNOTTY
, 0);
1924 #endif /* TIOCNOTTY */
1926 #if !defined (DONT_REOPEN_PTY)
1927 /*** There is a suggestion that this ought to be a
1928 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1929 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1930 that system does seem to need this code, even though
1931 both TIOCSCTTY is defined. */
1932 /* Now close the pty (if we had it open) and reopen it.
1933 This makes the pty the controlling terminal of the subprocess. */
1937 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1940 emacs_close (forkin
);
1941 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1945 emacs_perror (SSDATA (lisp_pty_name
));
1946 _exit (EXIT_CANCELED
);
1950 #endif /* not DONT_REOPEN_PTY */
1952 #ifdef SETUP_SLAVE_PTY
1957 #endif /* SETUP_SLAVE_PTY */
1958 #endif /* HAVE_PTYS */
1960 signal (SIGINT
, SIG_DFL
);
1961 signal (SIGQUIT
, SIG_DFL
);
1963 signal (SIGPROF
, SIG_DFL
);
1966 /* Emacs ignores SIGPIPE, but the child should not. */
1967 signal (SIGPIPE
, SIG_DFL
);
1969 /* Stop blocking SIGCHLD in the child. */
1970 unblock_child_signal (&oldset
);
1973 child_setup_tty (forkout
);
1978 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1979 #else /* not WINDOWSNT */
1980 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1981 #endif /* not WINDOWSNT */
1984 /* Back in the parent process. */
1986 vfork_errno
= errno
;
1991 /* Stop blocking in the parent. */
1992 unblock_child_signal (&oldset
);
1996 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1999 /* vfork succeeded. */
2001 /* Close the pipe ends that the child uses, or the child's pty. */
2002 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2003 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2006 register_child (pid
, inchannel
);
2007 #endif /* WINDOWSNT */
2009 pset_tty_name (p
, lisp_pty_name
);
2012 /* Wait for child_setup to complete in case that vfork is
2013 actually defined as fork. The descriptor
2014 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2015 of a pipe is closed at the child side either by close-on-exec
2016 on successful execve or the _exit call in child_setup. */
2020 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2021 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2022 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2025 if (!NILP (p
->stderrproc
))
2027 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2028 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2034 create_pty (Lisp_Object process
)
2036 struct Lisp_Process
*p
= XPROCESS (process
);
2037 char pty_name
[PTY_NAME_SIZE
];
2038 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2042 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2043 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2044 /* On most USG systems it does not work to open the pty's tty here,
2045 then close it and reopen it in the child. */
2046 /* Don't let this terminal become our controlling terminal
2047 (in case we don't have one). */
2048 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2050 report_file_error ("Opening pty", Qnil
);
2051 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2052 #if defined (DONT_REOPEN_PTY)
2053 /* In the case that vfork is defined as fork, the parent process
2054 (Emacs) may send some data before the child process completes
2055 tty options setup. So we setup tty before forking. */
2056 child_setup_tty (forkout
);
2057 #endif /* DONT_REOPEN_PTY */
2058 #endif /* not USG, or USG_SUBTTY_WORKS */
2060 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2062 /* Record this as an active process, with its channels.
2063 As a result, child_setup will close Emacs's side of the pipes. */
2064 chan_process
[pty_fd
] = process
;
2068 /* Previously we recorded the tty descriptor used in the subprocess.
2069 It was only used for getting the foreground tty process, so now
2070 we just reopen the device (see emacs_get_tty_pgrp) as this is
2071 more portable (see USG_SUBTTY_WORKS above). */
2074 pset_status (p
, Qrun
);
2075 setup_process_coding_systems (process
);
2077 FD_SET (pty_fd
, &input_wait_mask
);
2078 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2079 if (pty_fd
> max_process_desc
)
2080 max_process_desc
= pty_fd
;
2082 pset_tty_name (p
, build_string (pty_name
));
2088 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2090 doc
: /* Create and return a bidirectional pipe process.
2092 In Emacs, pipes are represented by process objects, so input and
2093 output work as for subprocesses, and `delete-process' closes a pipe.
2094 However, a pipe process has no process id, it cannot be signaled,
2095 and the status codes are different from normal processes.
2097 Arguments are specified as keyword/argument pairs. The following
2098 arguments are defined:
2100 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2102 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2103 with the process. Process output goes at the end of that buffer,
2104 unless you specify an output stream or filter function to handle the
2105 output. If BUFFER is not given, the value of NAME is used.
2107 :coding CODING -- If CODING is a symbol, it specifies the coding
2108 system used for both reading and writing for this process. If CODING
2109 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2110 ENCODING is used for writing.
2112 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2113 the process is running. If BOOL is not given, query before exiting.
2115 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2116 In the stopped state, a pipe process does not accept incoming data,
2117 but you can send outgoing data. The stopped state is cleared by
2118 `continue-process' and set by `stop-process'.
2120 :filter FILTER -- Install FILTER as the process filter.
2122 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2124 usage: (make-pipe-process &rest ARGS) */)
2125 (ptrdiff_t nargs
, Lisp_Object
*args
)
2127 Lisp_Object proc
, contact
;
2128 struct Lisp_Process
*p
;
2129 Lisp_Object name
, buffer
;
2131 ptrdiff_t specpdl_count
;
2132 int inchannel
, outchannel
;
2137 contact
= Flist (nargs
, args
);
2139 name
= Fplist_get (contact
, QCname
);
2140 CHECK_STRING (name
);
2141 proc
= make_process (name
);
2142 specpdl_count
= SPECPDL_INDEX ();
2143 record_unwind_protect (remove_process
, proc
);
2144 p
= XPROCESS (proc
);
2146 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2147 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2148 report_file_error ("Creating pipe", Qnil
);
2149 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2150 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2152 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2153 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2156 register_aux_fd (inchannel
);
2159 /* Record this as an active process, with its channels. */
2160 chan_process
[inchannel
] = proc
;
2161 p
->infd
= inchannel
;
2162 p
->outfd
= outchannel
;
2164 if (inchannel
> max_process_desc
)
2165 max_process_desc
= inchannel
;
2167 buffer
= Fplist_get (contact
, QCbuffer
);
2170 buffer
= Fget_buffer_create (buffer
);
2171 pset_buffer (p
, buffer
);
2173 pset_childp (p
, contact
);
2174 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2175 pset_type (p
, Qpipe
);
2176 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2177 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2179 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2180 p
->kill_without_query
= 1;
2181 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2182 pset_command (p
, Qt
);
2183 eassert (! p
->pty_flag
);
2185 if (!EQ (p
->command
, Qt
))
2187 FD_SET (inchannel
, &input_wait_mask
);
2188 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2190 p
->adaptive_read_buffering
2191 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2192 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2194 /* Make the process marker point into the process buffer (if any). */
2195 if (BUFFERP (buffer
))
2196 set_marker_both (p
->mark
, buffer
,
2197 BUF_ZV (XBUFFER (buffer
)),
2198 BUF_ZV_BYTE (XBUFFER (buffer
)));
2201 /* Setup coding systems for communicating with the network stream. */
2203 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2204 Lisp_Object coding_systems
= Qt
;
2207 tem
= Fplist_get (contact
, QCcoding
);
2215 else if (!NILP (Vcoding_system_for_read
))
2216 val
= Vcoding_system_for_read
;
2217 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2218 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2219 /* We dare not decode end-of-line format by setting VAL to
2220 Qraw_text, because the existing Emacs Lisp libraries
2221 assume that they receive bare code including a sequence of
2226 if (CONSP (coding_systems
))
2227 val
= XCAR (coding_systems
);
2228 else if (CONSP (Vdefault_process_coding_system
))
2229 val
= XCAR (Vdefault_process_coding_system
);
2233 pset_decode_coding_system (p
, val
);
2241 else if (!NILP (Vcoding_system_for_write
))
2242 val
= Vcoding_system_for_write
;
2243 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2247 if (CONSP (coding_systems
))
2248 val
= XCDR (coding_systems
);
2249 else if (CONSP (Vdefault_process_coding_system
))
2250 val
= XCDR (Vdefault_process_coding_system
);
2254 pset_encode_coding_system (p
, val
);
2256 /* This may signal an error. */
2257 setup_process_coding_systems (proc
);
2259 specpdl_ptr
= specpdl
+ specpdl_count
;
2265 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2266 The address family of sa is not included in the result. */
2269 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2271 Lisp_Object address
;
2274 struct Lisp_Vector
*p
;
2276 /* Workaround for a bug in getsockname on BSD: Names bound to
2277 sockets in the UNIX domain are inaccessible; getsockname returns
2278 a zero length name. */
2279 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2280 return empty_unibyte_string
;
2282 switch (sa
->sa_family
)
2286 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2287 len
= sizeof (sin
->sin_addr
) + 1;
2288 address
= Fmake_vector (make_number (len
), Qnil
);
2289 p
= XVECTOR (address
);
2290 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2291 cp
= (unsigned char *) &sin
->sin_addr
;
2297 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2298 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2299 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2300 address
= Fmake_vector (make_number (len
), Qnil
);
2301 p
= XVECTOR (address
);
2302 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2303 for (i
= 0; i
< len
; i
++)
2304 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2308 #ifdef HAVE_LOCAL_SOCKETS
2311 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2312 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2313 /* If the first byte is NUL, the name is a Linux abstract
2314 socket name, and the name can contain embedded NULs. If
2315 it's not, we have a NUL-terminated string. Be careful not
2316 to walk past the end of the object looking for the name
2317 terminator, however. */
2318 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2320 const char *terminator
2321 = memchr (sockun
->sun_path
, '\0', name_length
);
2324 name_length
= terminator
- (const char *) sockun
->sun_path
;
2327 return make_unibyte_string (sockun
->sun_path
, name_length
);
2331 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2332 address
= Fcons (make_number (sa
->sa_family
),
2333 Fmake_vector (make_number (len
), Qnil
));
2334 p
= XVECTOR (XCDR (address
));
2335 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2341 p
->contents
[i
++] = make_number (*cp
++);
2346 /* Convert an internal struct addrinfo to a Lisp object. */
2349 conv_addrinfo_to_lisp (struct addrinfo
*res
)
2351 Lisp_Object protocol
= make_number (res
->ai_protocol
);
2352 eassert (XINT (protocol
) == res
->ai_protocol
);
2353 return Fcons (protocol
, conv_sockaddr_to_lisp (res
->ai_addr
, res
->ai_addrlen
));
2357 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2360 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2362 struct Lisp_Vector
*p
;
2364 if (VECTORP (address
))
2366 p
= XVECTOR (address
);
2367 if (p
->header
.size
== 5)
2370 return sizeof (struct sockaddr_in
);
2373 else if (p
->header
.size
== 9)
2375 *familyp
= AF_INET6
;
2376 return sizeof (struct sockaddr_in6
);
2380 #ifdef HAVE_LOCAL_SOCKETS
2381 else if (STRINGP (address
))
2383 *familyp
= AF_LOCAL
;
2384 return sizeof (struct sockaddr_un
);
2387 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2388 && VECTORP (XCDR (address
)))
2390 struct sockaddr
*sa
;
2391 p
= XVECTOR (XCDR (address
));
2392 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2394 *familyp
= XINT (XCAR (address
));
2395 return p
->header
.size
+ sizeof (sa
->sa_family
);
2400 /* Convert an address object (vector or string) to an internal sockaddr.
2402 The address format has been basically validated by
2403 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2404 it could have come from user data. So if FAMILY is not valid,
2405 we return after zeroing *SA. */
2408 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2410 register struct Lisp_Vector
*p
;
2411 register unsigned char *cp
= NULL
;
2415 memset (sa
, 0, len
);
2417 if (VECTORP (address
))
2419 p
= XVECTOR (address
);
2420 if (family
== AF_INET
)
2422 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2423 len
= sizeof (sin
->sin_addr
) + 1;
2424 hostport
= XINT (p
->contents
[--len
]);
2425 sin
->sin_port
= htons (hostport
);
2426 cp
= (unsigned char *)&sin
->sin_addr
;
2427 sa
->sa_family
= family
;
2430 else if (family
== AF_INET6
)
2432 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2433 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2434 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2435 hostport
= XINT (p
->contents
[--len
]);
2436 sin6
->sin6_port
= htons (hostport
);
2437 for (i
= 0; i
< len
; i
++)
2438 if (INTEGERP (p
->contents
[i
]))
2440 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2443 sa
->sa_family
= family
;
2450 else if (STRINGP (address
))
2452 #ifdef HAVE_LOCAL_SOCKETS
2453 if (family
== AF_LOCAL
)
2455 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2456 cp
= SDATA (address
);
2457 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2458 sockun
->sun_path
[i
] = *cp
++;
2459 sa
->sa_family
= family
;
2466 p
= XVECTOR (XCDR (address
));
2467 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2470 for (i
= 0; i
< len
; i
++)
2471 if (INTEGERP (p
->contents
[i
]))
2472 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2475 #ifdef DATAGRAM_SOCKETS
2476 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2478 doc
: /* Get the current datagram address associated with PROCESS.
2479 If PROCESS is a non-blocking network process that hasn't been fully
2480 set up yet, this function will block until socket setup has completed. */)
2481 (Lisp_Object process
)
2485 CHECK_PROCESS (process
);
2487 if (NETCONN_P (process
))
2488 wait_for_socket_fds (process
, "process-datagram-address");
2490 if (!DATAGRAM_CONN_P (process
))
2493 channel
= XPROCESS (process
)->infd
;
2494 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2495 datagram_address
[channel
].len
);
2498 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2500 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2501 Return nil upon error setting address, ADDRESS otherwise.
2503 If PROCESS is a non-blocking network process that hasn't been fully
2504 set up yet, this function will block until socket setup has completed. */)
2505 (Lisp_Object process
, Lisp_Object address
)
2511 CHECK_PROCESS (process
);
2513 if (NETCONN_P (process
))
2514 wait_for_socket_fds (process
, "set-process-datagram-address");
2516 if (!DATAGRAM_CONN_P (process
))
2519 channel
= XPROCESS (process
)->infd
;
2521 len
= get_lisp_to_sockaddr_size (address
, &family
);
2522 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2524 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2530 static const struct socket_options
{
2531 /* The name of this option. Should be lowercase version of option
2532 name without SO_ prefix. */
2534 /* Option level SOL_... */
2536 /* Option number SO_... */
2538 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2539 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2540 } socket_options
[] =
2542 #ifdef SO_BINDTODEVICE
2543 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2546 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2549 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2552 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2555 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2558 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2561 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2564 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2566 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2569 /* Set option OPT to value VAL on socket S.
2571 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2572 Signals an error if setting a known option fails.
2576 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2579 const struct socket_options
*sopt
;
2584 name
= SSDATA (SYMBOL_NAME (opt
));
2585 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2586 if (strcmp (name
, sopt
->name
) == 0)
2589 switch (sopt
->opttype
)
2594 optval
= NILP (val
) ? 0 : 1;
2595 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2596 &optval
, sizeof (optval
));
2603 if (TYPE_RANGED_INTEGERP (int, val
))
2604 optval
= XINT (val
);
2606 error ("Bad option value for %s", name
);
2607 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2608 &optval
, sizeof (optval
));
2612 #ifdef SO_BINDTODEVICE
2615 char devname
[IFNAMSIZ
+ 1];
2617 /* This is broken, at least in the Linux 2.4 kernel.
2618 To unbind, the arg must be a zero integer, not the empty string.
2619 This should work on all systems. KFS. 2003-09-23. */
2620 memset (devname
, 0, sizeof devname
);
2623 char *arg
= SSDATA (val
);
2624 int len
= min (strlen (arg
), IFNAMSIZ
);
2625 memcpy (devname
, arg
, len
);
2627 else if (!NILP (val
))
2628 error ("Bad option value for %s", name
);
2629 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2638 struct linger linger
;
2641 linger
.l_linger
= 0;
2642 if (TYPE_RANGED_INTEGERP (int, val
))
2643 linger
.l_linger
= XINT (val
);
2645 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2646 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2647 &linger
, sizeof (linger
));
2658 int setsockopt_errno
= errno
;
2659 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2663 return (1 << sopt
->optbit
);
2667 DEFUN ("set-network-process-option",
2668 Fset_network_process_option
, Sset_network_process_option
,
2670 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2671 See `make-network-process' for a list of options and values.
2672 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2673 OPTION is not a supported option, return nil instead; otherwise return t.
2675 If PROCESS is a non-blocking network process that hasn't been fully
2676 set up yet, this function will block until socket setup has completed. */)
2677 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2680 struct Lisp_Process
*p
;
2682 CHECK_PROCESS (process
);
2683 p
= XPROCESS (process
);
2684 if (!NETCONN1_P (p
))
2685 error ("Process is not a network process");
2687 wait_for_socket_fds (process
, "set-network-process-option");
2691 error ("Process is not running");
2693 if (set_socket_option (s
, option
, value
))
2695 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2699 if (NILP (no_error
))
2700 error ("Unknown or unsupported option");
2706 DEFUN ("serial-process-configure",
2707 Fserial_process_configure
,
2708 Sserial_process_configure
,
2710 doc
: /* Configure speed, bytesize, etc. of a serial process.
2712 Arguments are specified as keyword/argument pairs. Attributes that
2713 are not given are re-initialized from the process's current
2714 configuration (available via the function `process-contact') or set to
2715 reasonable default values. The following arguments are defined:
2721 -- Any of these arguments can be given to identify the process that is
2722 to be configured. If none of these arguments is given, the current
2723 buffer's process is used.
2725 :speed SPEED -- SPEED is the speed of the serial port in bits per
2726 second, also called baud rate. Any value can be given for SPEED, but
2727 most serial ports work only at a few defined values between 1200 and
2728 115200, with 9600 being the most common value. If SPEED is nil, the
2729 serial port is not configured any further, i.e., all other arguments
2730 are ignored. This may be useful for special serial ports such as
2731 Bluetooth-to-serial converters which can only be configured through AT
2732 commands. A value of nil for SPEED can be used only when passed
2733 through `make-serial-process' or `serial-term'.
2735 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2736 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2738 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2739 `odd' (use odd parity), or the symbol `even' (use even parity). If
2740 PARITY is not given, no parity is used.
2742 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2743 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2744 is not given or nil, 1 stopbit is used.
2746 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2747 flowcontrol to be used, which is either nil (don't use flowcontrol),
2748 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2749 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2750 flowcontrol is used.
2752 `serial-process-configure' is called by `make-serial-process' for the
2753 initial configuration of the serial port.
2757 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2759 \(serial-process-configure
2760 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2762 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2764 usage: (serial-process-configure &rest ARGS) */)
2765 (ptrdiff_t nargs
, Lisp_Object
*args
)
2767 struct Lisp_Process
*p
;
2768 Lisp_Object contact
= Qnil
;
2769 Lisp_Object proc
= Qnil
;
2771 contact
= Flist (nargs
, args
);
2773 proc
= Fplist_get (contact
, QCprocess
);
2775 proc
= Fplist_get (contact
, QCname
);
2777 proc
= Fplist_get (contact
, QCbuffer
);
2779 proc
= Fplist_get (contact
, QCport
);
2780 proc
= get_process (proc
);
2781 p
= XPROCESS (proc
);
2782 if (!EQ (p
->type
, Qserial
))
2783 error ("Not a serial process");
2785 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2788 serial_configure (p
, contact
);
2792 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2794 doc
: /* Create and return a serial port process.
2796 In Emacs, serial port connections are represented by process objects,
2797 so input and output work as for subprocesses, and `delete-process'
2798 closes a serial port connection. However, a serial process has no
2799 process id, it cannot be signaled, and the status codes are different
2800 from normal processes.
2802 `make-serial-process' creates a process and a buffer, on which you
2803 probably want to use `process-send-string'. Try \\[serial-term] for
2804 an interactive terminal. See below for examples.
2806 Arguments are specified as keyword/argument pairs. The following
2807 arguments are defined:
2809 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2810 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2811 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2812 the backslashes in strings).
2814 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2815 which this function calls.
2817 :name NAME -- NAME is the name of the process. If NAME is not given,
2818 the value of PORT is used.
2820 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2821 with the process. Process output goes at the end of that buffer,
2822 unless you specify an output stream or filter function to handle the
2823 output. If BUFFER is not given, the value of NAME is used.
2825 :coding CODING -- If CODING is a symbol, it specifies the coding
2826 system used for both reading and writing for this process. If CODING
2827 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2828 ENCODING is used for writing.
2830 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2831 the process is running. If BOOL is not given, query before exiting.
2833 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2834 In the stopped state, a serial process does not accept incoming data,
2835 but you can send outgoing data. The stopped state is cleared by
2836 `continue-process' and set by `stop-process'.
2838 :filter FILTER -- Install FILTER as the process filter.
2840 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2842 :plist PLIST -- Install PLIST as the initial plist of the process.
2848 -- This function calls `serial-process-configure' to handle these
2851 The original argument list, possibly modified by later configuration,
2852 is available via the function `process-contact'.
2856 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2858 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2860 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2862 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2864 usage: (make-serial-process &rest ARGS) */)
2865 (ptrdiff_t nargs
, Lisp_Object
*args
)
2868 Lisp_Object proc
, contact
, port
;
2869 struct Lisp_Process
*p
;
2870 Lisp_Object name
, buffer
;
2871 Lisp_Object tem
, val
;
2872 ptrdiff_t specpdl_count
;
2877 contact
= Flist (nargs
, args
);
2879 port
= Fplist_get (contact
, QCport
);
2881 error ("No port specified");
2882 CHECK_STRING (port
);
2884 if (NILP (Fplist_member (contact
, QCspeed
)))
2885 error (":speed not specified");
2886 if (!NILP (Fplist_get (contact
, QCspeed
)))
2887 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2889 name
= Fplist_get (contact
, QCname
);
2892 CHECK_STRING (name
);
2893 proc
= make_process (name
);
2894 specpdl_count
= SPECPDL_INDEX ();
2895 record_unwind_protect (remove_process
, proc
);
2896 p
= XPROCESS (proc
);
2898 fd
= serial_open (port
);
2899 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2902 if (fd
> max_process_desc
)
2903 max_process_desc
= fd
;
2904 chan_process
[fd
] = proc
;
2906 buffer
= Fplist_get (contact
, QCbuffer
);
2909 buffer
= Fget_buffer_create (buffer
);
2910 pset_buffer (p
, buffer
);
2912 pset_childp (p
, contact
);
2913 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2914 pset_type (p
, Qserial
);
2915 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2916 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2918 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2919 p
->kill_without_query
= 1;
2920 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2921 pset_command (p
, Qt
);
2922 eassert (! p
->pty_flag
);
2924 if (!EQ (p
->command
, Qt
))
2926 FD_SET (fd
, &input_wait_mask
);
2927 FD_SET (fd
, &non_keyboard_wait_mask
);
2930 if (BUFFERP (buffer
))
2932 set_marker_both (p
->mark
, buffer
,
2933 BUF_ZV (XBUFFER (buffer
)),
2934 BUF_ZV_BYTE (XBUFFER (buffer
)));
2937 tem
= Fplist_member (contact
, QCcoding
);
2938 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2944 val
= XCAR (XCDR (tem
));
2948 else if (!NILP (Vcoding_system_for_read
))
2949 val
= Vcoding_system_for_read
;
2950 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2951 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2953 pset_decode_coding_system (p
, val
);
2958 val
= XCAR (XCDR (tem
));
2962 else if (!NILP (Vcoding_system_for_write
))
2963 val
= Vcoding_system_for_write
;
2964 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2965 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2967 pset_encode_coding_system (p
, val
);
2969 setup_process_coding_systems (proc
);
2970 pset_decoding_buf (p
, empty_unibyte_string
);
2971 p
->decoding_carryover
= 0;
2972 pset_encoding_buf (p
, empty_unibyte_string
);
2973 p
->inherit_coding_system_flag
2974 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2976 Fserial_process_configure (nargs
, args
);
2978 specpdl_ptr
= specpdl
+ specpdl_count
;
2984 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2985 Lisp_Object service
, Lisp_Object name
)
2988 struct Lisp_Process
*p
= XPROCESS (proc
);
2989 Lisp_Object contact
= p
->childp
;
2990 Lisp_Object coding_systems
= Qt
;
2993 tem
= Fplist_member (contact
, QCcoding
);
2994 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2995 tem
= Qnil
; /* No error message (too late!). */
2997 /* Setup coding systems for communicating with the network stream. */
2998 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3002 val
= XCAR (XCDR (tem
));
3006 else if (!NILP (Vcoding_system_for_read
))
3007 val
= Vcoding_system_for_read
;
3008 else if ((!NILP (p
->buffer
)
3009 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3010 || (NILP (p
->buffer
)
3011 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3012 /* We dare not decode end-of-line format by setting VAL to
3013 Qraw_text, because the existing Emacs Lisp libraries
3014 assume that they receive bare code including a sequence of
3019 if (NILP (host
) || NILP (service
))
3020 coding_systems
= Qnil
;
3022 coding_systems
= CALLN (Ffind_operation_coding_system
,
3023 Qopen_network_stream
, name
, p
->buffer
,
3025 if (CONSP (coding_systems
))
3026 val
= XCAR (coding_systems
);
3027 else if (CONSP (Vdefault_process_coding_system
))
3028 val
= XCAR (Vdefault_process_coding_system
);
3032 pset_decode_coding_system (p
, val
);
3036 val
= XCAR (XCDR (tem
));
3040 else if (!NILP (Vcoding_system_for_write
))
3041 val
= Vcoding_system_for_write
;
3042 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3046 if (EQ (coding_systems
, Qt
))
3048 if (NILP (host
) || NILP (service
))
3049 coding_systems
= Qnil
;
3051 coding_systems
= CALLN (Ffind_operation_coding_system
,
3052 Qopen_network_stream
, name
, p
->buffer
,
3055 if (CONSP (coding_systems
))
3056 val
= XCDR (coding_systems
);
3057 else if (CONSP (Vdefault_process_coding_system
))
3058 val
= XCDR (Vdefault_process_coding_system
);
3062 pset_encode_coding_system (p
, val
);
3064 pset_decoding_buf (p
, empty_unibyte_string
);
3065 p
->decoding_carryover
= 0;
3066 pset_encoding_buf (p
, empty_unibyte_string
);
3068 p
->inherit_coding_system_flag
3069 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3074 finish_after_tls_connection (Lisp_Object proc
)
3076 struct Lisp_Process
*p
= XPROCESS (proc
);
3077 Lisp_Object contact
= p
->childp
;
3078 Lisp_Object result
= Qt
;
3080 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3081 result
= call3 (Qnsm_verify_connection
,
3083 Fplist_get (contact
, QChost
),
3084 Fplist_get (contact
, QCservice
));
3088 pset_status (p
, list2 (Qfailed
,
3089 build_string ("The Network Security Manager stopped the connections")));
3090 deactivate_process (proc
);
3094 /* If we cleared the connection wait mask before we did
3095 the TLS setup, then we have to say that the process
3096 is finally "open" here. */
3097 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3099 pset_status (p
, Qrun
);
3100 /* Execute the sentinel here. If we had relied on
3101 status_notify to do it later, it will read input
3102 from the process before calling the sentinel. */
3103 exec_sentinel (proc
, build_string ("open\n"));
3110 connect_network_socket (Lisp_Object proc
, Lisp_Object addrinfos
,
3111 Lisp_Object use_external_socket_p
)
3113 ptrdiff_t count
= SPECPDL_INDEX ();
3115 int s
= -1, outch
, inch
;
3118 struct sockaddr
*sa
= NULL
;
3121 struct Lisp_Process
*p
= XPROCESS (proc
);
3122 Lisp_Object contact
= p
->childp
;
3124 int socket_to_use
= -1;
3126 if (!NILP (use_external_socket_p
))
3128 socket_to_use
= external_sock_fd
;
3130 /* Ensure we don't consume the external socket twice. */
3131 external_sock_fd
= -1;
3134 /* Do this in case we never enter the while-loop below. */
3135 count1
= SPECPDL_INDEX ();
3138 while (!NILP (addrinfos
))
3140 Lisp_Object addrinfo
= XCAR (addrinfos
);
3141 addrinfos
= XCDR (addrinfos
);
3142 int protocol
= XINT (XCAR (addrinfo
));
3143 Lisp_Object ip_address
= XCDR (addrinfo
);
3149 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3152 sa
= xmalloc (addrlen
);
3153 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3158 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3159 if (p
->is_non_blocking_client
)
3160 socktype
|= SOCK_NONBLOCK
;
3161 s
= socket (family
, socktype
, protocol
);
3169 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3171 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3181 #ifdef DATAGRAM_SOCKETS
3182 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3184 #endif /* DATAGRAM_SOCKETS */
3186 /* Make us close S if quit. */
3187 record_unwind_protect_int (close_file_unwind
, s
);
3189 /* Parse network options in the arg list. We simply ignore anything
3190 which isn't a known option (including other keywords). An error
3191 is signaled if setting a known option fails. */
3193 Lisp_Object params
= contact
, key
, val
;
3195 while (!NILP (params
))
3197 key
= XCAR (params
);
3198 params
= XCDR (params
);
3199 val
= XCAR (params
);
3200 params
= XCDR (params
);
3201 optbits
|= set_socket_option (s
, key
, val
);
3207 /* Configure as a server socket. */
3209 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3210 explicit :reuseaddr key to override this. */
3211 #ifdef HAVE_LOCAL_SOCKETS
3212 if (family
!= AF_LOCAL
)
3214 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3217 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3218 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3221 /* If passed a socket descriptor, it should be already bound. */
3222 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3223 report_file_error ("Cannot bind server socket", Qnil
);
3225 #ifdef HAVE_GETSOCKNAME
3228 struct sockaddr_in sa1
;
3229 socklen_t len1
= sizeof (sa1
);
3230 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3232 Lisp_Object service
;
3233 service
= make_number (ntohs (sa1
.sin_port
));
3234 contact
= Fplist_put (contact
, QCservice
, service
);
3235 /* Save the port number so that we can stash it in
3236 the process object later. */
3237 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3242 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3243 report_file_error ("Cannot listen on server socket", Qnil
);
3251 ret
= connect (s
, sa
, addrlen
);
3254 if (ret
== 0 || xerrno
== EISCONN
)
3256 /* The unwind-protect will be discarded afterwards.
3257 Likewise for immediate_quit. */
3261 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3265 if (xerrno
== EINTR
)
3267 /* Unlike most other syscalls connect() cannot be called
3268 again. (That would return EALREADY.) The proper way to
3269 wait for completion is pselect(). */
3277 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3283 report_file_error ("Failed select", Qnil
);
3287 len
= sizeof xerrno
;
3288 eassert (FD_ISSET (s
, &fdset
));
3289 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3290 report_file_error ("Failed getsockopt", Qnil
);
3292 report_file_errno ("Failed connect", Qnil
, xerrno
);
3295 #endif /* !WINDOWSNT */
3299 /* Discard the unwind protect closing S. */
3300 specpdl_ptr
= specpdl
+ count1
;
3305 if (xerrno
== EINTR
)
3312 #ifdef DATAGRAM_SOCKETS
3313 if (p
->socktype
== SOCK_DGRAM
)
3315 if (datagram_address
[s
].sa
)
3318 datagram_address
[s
].sa
= xmalloc (addrlen
);
3319 datagram_address
[s
].len
= addrlen
;
3323 memset (datagram_address
[s
].sa
, 0, addrlen
);
3324 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3327 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3328 if (rlen
!= 0 && rfamily
== family
3330 conv_lisp_to_sockaddr (rfamily
, remote
,
3331 datagram_address
[s
].sa
, rlen
);
3335 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3339 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3340 conv_sockaddr_to_lisp (sa
, addrlen
));
3341 #ifdef HAVE_GETSOCKNAME
3344 struct sockaddr_in sa1
;
3345 socklen_t len1
= sizeof (sa1
);
3346 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3347 contact
= Fplist_put (contact
, QClocal
,
3348 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3357 /* If non-blocking got this far - and failed - assume non-blocking is
3358 not supported after all. This is probably a wrong assumption, but
3359 the normal blocking calls to open-network-stream handles this error
3361 if (p
->is_non_blocking_client
)
3364 report_file_errno ((p
->is_server
3365 ? "make server process failed"
3366 : "make client process failed"),
3373 chan_process
[inch
] = proc
;
3375 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3377 p
= XPROCESS (proc
);
3378 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3382 /* Discard the unwind protect for closing S, if any. */
3383 specpdl_ptr
= specpdl
+ count1
;
3385 /* Unwind bind_polling_period and request_sigio. */
3386 unbind_to (count
, Qnil
);
3388 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3389 pset_status (p
, Qlisten
);
3391 /* Make the process marker point into the process buffer (if any). */
3392 if (BUFFERP (p
->buffer
))
3393 set_marker_both (p
->mark
, p
->buffer
,
3394 BUF_ZV (XBUFFER (p
->buffer
)),
3395 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3397 if (p
->is_non_blocking_client
)
3399 /* We may get here if connect did succeed immediately. However,
3400 in that case, we still need to signal this like a non-blocking
3402 pset_status (p
, Qconnect
);
3403 if (!FD_ISSET (inch
, &connect_wait_mask
))
3405 FD_SET (inch
, &connect_wait_mask
);
3406 FD_SET (inch
, &write_mask
);
3407 num_pending_connects
++;
3411 /* A server may have a client filter setting of Qt, but it must
3412 still listen for incoming connects unless it is stopped. */
3413 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3414 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3416 FD_SET (inch
, &input_wait_mask
);
3417 FD_SET (inch
, &non_keyboard_wait_mask
);
3420 if (inch
> max_process_desc
)
3421 max_process_desc
= inch
;
3423 /* Set up the masks based on the process filter. */
3424 set_process_filter_masks (p
);
3426 setup_process_coding_systems (proc
);
3429 /* Continue the asynchronous connection. */
3430 if (!NILP (p
->gnutls_boot_parameters
))
3432 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3434 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3435 p
->gnutls_boot_parameters
= Qnil
;
3437 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3438 /* Run sentinels, etc. */
3439 finish_after_tls_connection (proc
);
3440 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3442 deactivate_process (proc
);
3444 pset_status (p
, list2 (Qfailed
,
3445 build_string ("TLS negotiation failed")));
3447 pset_status (p
, list2 (Qfailed
, boot
));
3454 /* Create a network stream/datagram client/server process. Treated
3455 exactly like a normal process when reading and writing. Primary
3456 differences are in status display and process deletion. A network
3457 connection has no PID; you cannot signal it. All you can do is
3458 stop/continue it and deactivate/close it via delete-process. */
3460 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3462 doc
: /* Create and return a network server or client process.
3464 In Emacs, network connections are represented by process objects, so
3465 input and output work as for subprocesses and `delete-process' closes
3466 a network connection. However, a network process has no process id,
3467 it cannot be signaled, and the status codes are different from normal
3470 Arguments are specified as keyword/argument pairs. The following
3471 arguments are defined:
3473 :name NAME -- NAME is name for process. It is modified if necessary
3476 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3477 with the process. Process output goes at end of that buffer, unless
3478 you specify an output stream or filter function to handle the output.
3479 BUFFER may be also nil, meaning that this process is not associated
3482 :host HOST -- HOST is name of the host to connect to, or its IP
3483 address. The symbol `local' specifies the local host. If specified
3484 for a server process, it must be a valid name or address for the local
3485 host, and only clients connecting to that address will be accepted.
3487 :service SERVICE -- SERVICE is name of the service desired, or an
3488 integer specifying a port number to connect to. If SERVICE is t,
3489 a random port number is selected for the server. A port number can
3490 be specified as an integer string, e.g., "80", as well as an integer.
3492 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3493 stream type connection, `datagram' creates a datagram type connection,
3494 `seqpacket' creates a reliable datagram connection.
3496 :family FAMILY -- FAMILY is the address (and protocol) family for the
3497 service specified by HOST and SERVICE. The default (nil) is to use
3498 whatever address family (IPv4 or IPv6) that is defined for the host
3499 and port number specified by HOST and SERVICE. Other address families
3501 local -- for a local (i.e. UNIX) address specified by SERVICE.
3502 ipv4 -- use IPv4 address family only.
3503 ipv6 -- use IPv6 address family only.
3505 :local ADDRESS -- ADDRESS is the local address used for the connection.
3506 This parameter is ignored when opening a client process. When specified
3507 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3509 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3510 connection. This parameter is ignored when opening a stream server
3511 process. For a datagram server process, it specifies the initial
3512 setting of the remote datagram address. When specified for a client
3513 process, the FAMILY, HOST, and SERVICE args are ignored.
3515 The format of ADDRESS depends on the address family:
3516 - An IPv4 address is represented as an vector of integers [A B C D P]
3517 corresponding to numeric IP address A.B.C.D and port number P.
3518 - A local address is represented as a string with the address in the
3519 local address space.
3520 - An "unsupported family" address is represented by a cons (F . AV)
3521 where F is the family number and AV is a vector containing the socket
3522 address data with one element per address data byte. Do not rely on
3523 this format in portable code, as it may depend on implementation
3524 defined constants, data sizes, and data structure alignment.
3526 :coding CODING -- If CODING is a symbol, it specifies the coding
3527 system used for both reading and writing for this process. If CODING
3528 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3529 ENCODING is used for writing.
3531 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3532 process, return without waiting for the connection to complete;
3533 instead, the sentinel function will be called with second arg matching
3534 "open" (if successful) or "failed" when the connect completes.
3535 Default is to use a blocking connect (i.e. wait) for stream type
3538 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3539 running when Emacs is exited.
3541 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3542 In the stopped state, a server process does not accept new
3543 connections, and a client process does not handle incoming traffic.
3544 The stopped state is cleared by `continue-process' and set by
3547 :filter FILTER -- Install FILTER as the process filter.
3549 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3550 process filter are multibyte, otherwise they are unibyte.
3551 If this keyword is not specified, the strings are multibyte if
3552 the default value of `enable-multibyte-characters' is non-nil.
3554 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3556 :log LOG -- Install LOG as the server process log function. This
3557 function is called when the server accepts a network connection from a
3558 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3559 is the server process, CLIENT is the new process for the connection,
3560 and MESSAGE is a string.
3562 :plist PLIST -- Install PLIST as the new process's initial plist.
3564 :tls-parameters LIST -- is a list that should be supplied if you're
3565 opening a TLS connection. The first element is the TLS type (either
3566 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3567 be a keyword list accepted by gnutls-boot (as returned by
3568 `gnutls-boot-parameters').
3570 :server QLEN -- if QLEN is non-nil, create a server process for the
3571 specified FAMILY, SERVICE, and connection type (stream or datagram).
3572 If QLEN is an integer, it is used as the max. length of the server's
3573 pending connection queue (also known as the backlog); the default
3574 queue length is 5. Default is to create a client process.
3576 The following network options can be specified for this connection:
3578 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3579 :dontroute BOOL -- Only send to directly connected hosts.
3580 :keepalive BOOL -- Send keep-alive messages on network stream.
3581 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3582 :oobinline BOOL -- Place out-of-band data in receive data stream.
3583 :priority INT -- Set protocol defined priority for sent packets.
3584 :reuseaddr BOOL -- Allow reusing a recently used local address
3585 (this is allowed by default for a server process).
3586 :bindtodevice NAME -- bind to interface NAME. Using this may require
3587 special privileges on some systems.
3588 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3589 been passed to Emacs. If Emacs wasn't
3590 passed a socket, this option is silently
3594 Consult the relevant system programmer's manual pages for more
3595 information on using these options.
3598 A server process will listen for and accept connections from clients.
3599 When a client connection is accepted, a new network process is created
3600 for the connection with the following parameters:
3602 - The client's process name is constructed by concatenating the server
3603 process's NAME and a client identification string.
3604 - If the FILTER argument is non-nil, the client process will not get a
3605 separate process buffer; otherwise, the client's process buffer is a newly
3606 created buffer named after the server process's BUFFER name or process
3607 NAME concatenated with the client identification string.
3608 - The connection type and the process filter and sentinel parameters are
3609 inherited from the server process's TYPE, FILTER and SENTINEL.
3610 - The client process's contact info is set according to the client's
3611 addressing information (typically an IP address and a port number).
3612 - The client process's plist is initialized from the server's plist.
3614 Notice that the FILTER and SENTINEL args are never used directly by
3615 the server process. Also, the BUFFER argument is not used directly by
3616 the server process, but via the optional :log function, accepted (and
3617 failed) connections may be logged in the server process's buffer.
3619 The original argument list, modified with the actual connection
3620 information, is available via the `process-contact' function.
3622 usage: (make-network-process &rest ARGS) */)
3623 (ptrdiff_t nargs
, Lisp_Object
*args
)
3626 Lisp_Object contact
;
3627 struct Lisp_Process
*p
;
3628 const char *portstring
;
3629 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3630 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3631 #ifdef HAVE_LOCAL_SOCKETS
3632 struct sockaddr_un address_un
;
3636 Lisp_Object name
, buffer
, host
, service
, address
;
3637 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3638 Lisp_Object addrinfos
= Qnil
;
3641 enum { any_protocol
= 0 };
3642 #ifdef HAVE_GETADDRINFO_A
3643 struct gaicb
*dns_request
= NULL
;
3645 ptrdiff_t count
= SPECPDL_INDEX ();
3650 /* Save arguments for process-contact and clone-process. */
3651 contact
= Flist (nargs
, args
);
3654 /* Ensure socket support is loaded if available. */
3655 init_winsock (TRUE
);
3658 /* :type TYPE (nil: stream, datagram */
3659 tem
= Fplist_get (contact
, QCtype
);
3661 socktype
= SOCK_STREAM
;
3662 #ifdef DATAGRAM_SOCKETS
3663 else if (EQ (tem
, Qdatagram
))
3664 socktype
= SOCK_DGRAM
;
3666 #ifdef HAVE_SEQPACKET
3667 else if (EQ (tem
, Qseqpacket
))
3668 socktype
= SOCK_SEQPACKET
;
3671 error ("Unsupported connection type");
3673 name
= Fplist_get (contact
, QCname
);
3674 buffer
= Fplist_get (contact
, QCbuffer
);
3675 filter
= Fplist_get (contact
, QCfilter
);
3676 sentinel
= Fplist_get (contact
, QCsentinel
);
3677 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3679 CHECK_STRING (name
);
3681 /* :local ADDRESS or :remote ADDRESS */
3682 tem
= Fplist_get (contact
, QCserver
);
3684 address
= Fplist_get (contact
, QCremote
);
3686 address
= Fplist_get (contact
, QClocal
);
3687 if (!NILP (address
))
3689 host
= service
= Qnil
;
3691 if (!get_lisp_to_sockaddr_size (address
, &family
))
3692 error ("Malformed :address");
3694 addrinfos
= list1 (Fcons (make_number (any_protocol
), address
));
3698 /* :family FAMILY -- nil (for Inet), local, or integer. */
3699 tem
= Fplist_get (contact
, QCfamily
);
3708 #ifdef HAVE_LOCAL_SOCKETS
3709 else if (EQ (tem
, Qlocal
))
3713 else if (EQ (tem
, Qipv6
))
3716 else if (EQ (tem
, Qipv4
))
3718 else if (TYPE_RANGED_INTEGERP (int, tem
))
3719 family
= XINT (tem
);
3721 error ("Unknown address family");
3723 /* :service SERVICE -- string, integer (port number), or t (random port). */
3724 service
= Fplist_get (contact
, QCservice
);
3726 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3727 host
= Fplist_get (contact
, QChost
);
3730 /* The "connection" function gets it bind info from the address we're
3731 given, so use this dummy address if nothing is specified. */
3732 #ifdef HAVE_LOCAL_SOCKETS
3733 if (family
!= AF_LOCAL
)
3735 host
= build_string ("127.0.0.1");
3739 if (EQ (host
, Qlocal
))
3740 /* Depending on setup, "localhost" may map to different IPv4 and/or
3741 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3742 host
= build_string ("127.0.0.1");
3743 CHECK_STRING (host
);
3746 #ifdef HAVE_LOCAL_SOCKETS
3747 if (family
== AF_LOCAL
)
3751 message (":family local ignores the :host property");
3752 contact
= Fplist_put (contact
, QChost
, Qnil
);
3755 CHECK_STRING (service
);
3756 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3757 error ("Service name too long");
3758 addrinfos
= list1 (Fcons (make_number (any_protocol
), service
));
3763 /* Slow down polling to every ten seconds.
3764 Some kernels have a bug which causes retrying connect to fail
3765 after a connect. Polling can interfere with gethostbyname too. */
3766 #ifdef POLL_FOR_INPUT
3767 if (socktype
!= SOCK_DGRAM
)
3769 record_unwind_protect_void (run_all_atimers
);
3770 bind_polling_period (10);
3776 /* SERVICE can either be a string or int.
3777 Convert to a C string for later use by getaddrinfo. */
3778 if (EQ (service
, Qt
))
3783 else if (INTEGERP (service
))
3785 portstring
= portbuf
;
3786 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3790 CHECK_STRING (service
);
3791 portstring
= SSDATA (service
);
3792 portstringlen
= SBYTES (service
);
3796 #ifdef HAVE_GETADDRINFO_A
3797 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3799 ptrdiff_t hostlen
= SBYTES (host
);
3803 struct addrinfo hints
;
3804 char str
[FLEXIBLE_ARRAY_MEMBER
];
3805 } *req
= xmalloc (offsetof (struct req
, str
)
3806 + hostlen
+ 1 + portstringlen
+ 1);
3807 dns_request
= &req
->gaicb
;
3808 dns_request
->ar_name
= req
->str
;
3809 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3810 dns_request
->ar_request
= &req
->hints
;
3811 dns_request
->ar_result
= NULL
;
3812 memset (&req
->hints
, 0, sizeof req
->hints
);
3813 req
->hints
.ai_family
= family
;
3814 req
->hints
.ai_socktype
= socktype
;
3815 strcpy (req
->str
, SSDATA (host
));
3816 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3818 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3820 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3824 #endif /* HAVE_GETADDRINFO_A */
3826 /* If we have a host, use getaddrinfo to resolve both host and service.
3827 Otherwise, use getservbyname to lookup the service. */
3831 struct addrinfo
*res
, *lres
;
3837 struct addrinfo hints
;
3838 memset (&hints
, 0, sizeof hints
);
3839 hints
.ai_family
= family
;
3840 hints
.ai_socktype
= socktype
;
3842 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3844 #ifdef HAVE_GAI_STRERROR
3846 synchronize_system_messages_locale ();
3847 char const *str
= gai_strerror (ret
);
3848 if (! NILP (Vlocale_coding_system
))
3849 str
= SSDATA (code_convert_string_norecord
3850 (build_string (str
), Vlocale_coding_system
, 0));
3851 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3854 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3858 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3859 addrinfos
= Fcons (conv_addrinfo_to_lisp (lres
), addrinfos
);
3861 addrinfos
= Fnreverse (addrinfos
);
3868 /* No hostname has been specified (e.g., a local server process). */
3870 if (EQ (service
, Qt
))
3872 else if (INTEGERP (service
))
3873 port
= XINT (service
);
3876 CHECK_STRING (service
);
3879 if (SBYTES (service
) != 0)
3881 /* Allow the service to be a string containing the port number,
3882 because that's allowed if you have getaddrbyname. */
3884 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3885 if (service_end
== SSDATA (service
) + SBYTES (service
))
3889 struct servent
*svc_info
3890 = getservbyname (SSDATA (service
),
3891 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3893 port
= ntohs (svc_info
->s_port
);
3898 if (! (0 <= port
&& port
< 1 << 16))
3900 AUTO_STRING (unknown_service
, "Unknown service: %s");
3901 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3907 buffer
= Fget_buffer_create (buffer
);
3908 proc
= make_process (name
);
3909 p
= XPROCESS (proc
);
3910 pset_childp (p
, contact
);
3911 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3912 pset_type (p
, Qnetwork
);
3914 pset_buffer (p
, buffer
);
3915 pset_sentinel (p
, sentinel
);
3916 pset_filter (p
, filter
);
3917 pset_log (p
, Fplist_get (contact
, QClog
));
3918 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3919 p
->kill_without_query
= 1;
3920 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3921 pset_command (p
, Qt
);
3924 p
->is_non_blocking_client
= false;
3925 p
->is_server
= false;
3927 p
->socktype
= socktype
;
3928 #ifdef HAVE_GETADDRINFO_A
3929 p
->dns_request
= NULL
;
3932 tem
= Fplist_get (contact
, QCtls_parameters
);
3934 p
->gnutls_boot_parameters
= tem
;
3937 set_network_socket_coding_system (proc
, host
, service
, name
);
3939 unbind_to (count
, Qnil
);
3942 tem
= Fplist_get (contact
, QCserver
);
3945 /* Don't support network sockets when non-blocking mode is
3946 not available, since a blocked Emacs is not useful. */
3947 p
->is_server
= true;
3948 if (TYPE_RANGED_INTEGERP (int, tem
))
3949 p
->backlog
= XINT (tem
);
3953 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3954 && !NILP (Fplist_get (contact
, QCnowait
)))
3955 p
->is_non_blocking_client
= true;
3957 #ifdef HAVE_GETADDRINFO_A
3958 /* With async address resolution, the list of addresses is empty, so
3959 postpone connecting to the server. */
3960 if (!p
->is_server
&& NILP (addrinfos
))
3962 p
->dns_request
= dns_request
;
3963 p
->status
= Qconnect
;
3968 connect_network_socket (proc
, addrinfos
, use_external_socket_p
);
3973 #ifdef HAVE_NET_IF_H
3977 network_interface_list (void)
3979 struct ifconf ifconf
;
3980 struct ifreq
*ifreq
;
3982 ptrdiff_t buf_size
= 512;
3987 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3990 count
= SPECPDL_INDEX ();
3991 record_unwind_protect_int (close_file_unwind
, s
);
3995 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3996 ifconf
.ifc_buf
= buf
;
3997 ifconf
.ifc_len
= buf_size
;
3998 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4005 while (ifconf
.ifc_len
== buf_size
);
4007 res
= unbind_to (count
, Qnil
);
4008 ifreq
= ifconf
.ifc_req
;
4009 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4011 struct ifreq
*ifq
= ifreq
;
4012 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4013 #define SIZEOF_IFREQ(sif) \
4014 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4015 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4017 int len
= SIZEOF_IFREQ (ifq
);
4019 int len
= sizeof (*ifreq
);
4021 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4022 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4024 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4027 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4028 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4029 res
= Fcons (Fcons (build_string (namebuf
),
4030 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4031 sizeof (struct sockaddr
))),
4038 #endif /* SIOCGIFCONF */
4040 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4044 const char *flag_sym
;
4047 static const struct ifflag_def ifflag_table
[] = {
4051 #ifdef IFF_BROADCAST
4052 { IFF_BROADCAST
, "broadcast" },
4055 { IFF_DEBUG
, "debug" },
4058 { IFF_LOOPBACK
, "loopback" },
4060 #ifdef IFF_POINTOPOINT
4061 { IFF_POINTOPOINT
, "pointopoint" },
4064 { IFF_RUNNING
, "running" },
4067 { IFF_NOARP
, "noarp" },
4070 { IFF_PROMISC
, "promisc" },
4072 #ifdef IFF_NOTRAILERS
4073 #ifdef NS_IMPL_COCOA
4074 /* Really means smart, notrailers is obsolete. */
4075 { IFF_NOTRAILERS
, "smart" },
4077 { IFF_NOTRAILERS
, "notrailers" },
4081 { IFF_ALLMULTI
, "allmulti" },
4084 { IFF_MASTER
, "master" },
4087 { IFF_SLAVE
, "slave" },
4089 #ifdef IFF_MULTICAST
4090 { IFF_MULTICAST
, "multicast" },
4093 { IFF_PORTSEL
, "portsel" },
4095 #ifdef IFF_AUTOMEDIA
4096 { IFF_AUTOMEDIA
, "automedia" },
4099 { IFF_DYNAMIC
, "dynamic" },
4102 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4105 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4108 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4111 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4114 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4120 network_interface_info (Lisp_Object ifname
)
4123 Lisp_Object res
= Qnil
;
4128 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4129 && defined HAVE_GETIFADDRS && defined LLADDR)
4130 struct ifaddrs
*ifap
;
4133 CHECK_STRING (ifname
);
4135 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4136 error ("interface name too long");
4137 lispstpcpy (rq
.ifr_name
, ifname
);
4139 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4142 count
= SPECPDL_INDEX ();
4143 record_unwind_protect_int (close_file_unwind
, s
);
4146 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4147 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4149 int flags
= rq
.ifr_flags
;
4150 const struct ifflag_def
*fp
;
4153 /* If flags is smaller than int (i.e. short) it may have the high bit set
4154 due to IFF_MULTICAST. In that case, sign extending it into
4156 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4157 flags
= (unsigned short) rq
.ifr_flags
;
4160 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4162 if (flags
& fp
->flag_bit
)
4164 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4165 flags
-= fp
->flag_bit
;
4168 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4172 elt
= Fcons (make_number (fnum
), elt
);
4177 res
= Fcons (elt
, res
);
4180 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4181 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4183 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4184 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4188 for (n
= 0; n
< 6; n
++)
4189 p
->contents
[n
] = make_number (((unsigned char *)
4190 &rq
.ifr_hwaddr
.sa_data
[0])
4192 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4194 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4195 if (getifaddrs (&ifap
) != -1)
4197 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4198 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4201 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4203 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4204 unsigned char linkaddr
[6];
4207 if (it
->ifa_addr
->sa_family
!= AF_LINK
4208 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4209 || sdl
->sdl_alen
!= 6)
4212 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4213 for (n
= 0; n
< 6; n
++)
4214 p
->contents
[n
] = make_number (linkaddr
[n
]);
4216 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4220 #ifdef HAVE_FREEIFADDRS
4224 #endif /* HAVE_GETIFADDRS && LLADDR */
4226 res
= Fcons (elt
, res
);
4229 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4230 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4233 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4234 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4236 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4240 res
= Fcons (elt
, res
);
4243 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4244 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4247 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4250 res
= Fcons (elt
, res
);
4253 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4254 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4257 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4260 res
= Fcons (elt
, res
);
4262 return unbind_to (count
, any
? res
: Qnil
);
4264 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4265 #endif /* defined (HAVE_NET_IF_H) */
4267 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4268 Snetwork_interface_list
, 0, 0, 0,
4269 doc
: /* Return an alist of all network interfaces and their network address.
4270 Each element is a cons, the car of which is a string containing the
4271 interface name, and the cdr is the network address in internal
4272 format; see the description of ADDRESS in `make-network-process'.
4274 If the information is not available, return nil. */)
4277 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4278 return network_interface_list ();
4284 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4285 Snetwork_interface_info
, 1, 1, 0,
4286 doc
: /* Return information about network interface named IFNAME.
4287 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4288 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4289 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4290 FLAGS is the current flags of the interface.
4292 Data that is unavailable is returned as nil. */)
4293 (Lisp_Object ifname
)
4295 #if ((defined HAVE_NET_IF_H \
4296 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4297 || defined SIOCGIFFLAGS)) \
4298 || defined WINDOWSNT)
4299 return network_interface_info (ifname
);
4305 /* Turn off input and output for process PROC. */
4308 deactivate_process (Lisp_Object proc
)
4311 struct Lisp_Process
*p
= XPROCESS (proc
);
4315 /* Delete GnuTLS structures in PROC, if any. */
4316 emacs_gnutls_deinit (proc
);
4317 #endif /* HAVE_GNUTLS */
4319 if (p
->read_output_delay
> 0)
4321 if (--process_output_delay_count
< 0)
4322 process_output_delay_count
= 0;
4323 p
->read_output_delay
= 0;
4324 p
->read_output_skip
= 0;
4327 /* Beware SIGCHLD hereabouts. */
4329 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4330 close_process_fd (&p
->open_fd
[i
]);
4332 inchannel
= p
->infd
;
4337 #ifdef DATAGRAM_SOCKETS
4338 if (DATAGRAM_CHAN_P (inchannel
))
4340 xfree (datagram_address
[inchannel
].sa
);
4341 datagram_address
[inchannel
].sa
= 0;
4342 datagram_address
[inchannel
].len
= 0;
4345 chan_process
[inchannel
] = Qnil
;
4346 FD_CLR (inchannel
, &input_wait_mask
);
4347 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4348 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4350 FD_CLR (inchannel
, &connect_wait_mask
);
4351 FD_CLR (inchannel
, &write_mask
);
4352 if (--num_pending_connects
< 0)
4355 if (inchannel
== max_process_desc
)
4357 /* We just closed the highest-numbered process input descriptor,
4358 so recompute the highest-numbered one now. */
4362 while (0 <= i
&& NILP (chan_process
[i
]));
4364 max_process_desc
= i
;
4370 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4372 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4373 It is given to their filter functions.
4374 Optional argument PROCESS means do not return until output has been
4375 received from PROCESS.
4377 Optional second argument SECONDS and third argument MILLISEC
4378 specify a timeout; return after that much time even if there is
4379 no subprocess output. If SECONDS is a floating point number,
4380 it specifies a fractional number of seconds to wait.
4381 The MILLISEC argument is obsolete and should be avoided.
4383 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4384 from PROCESS only, suspending reading output from other processes.
4385 If JUST-THIS-ONE is an integer, don't run any timers either.
4386 Return non-nil if we received any output from PROCESS (or, if PROCESS
4387 is nil, from any process) before the timeout expired. */)
4388 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4393 if (! NILP (process
))
4394 CHECK_PROCESS (process
);
4396 just_this_one
= Qnil
;
4398 if (!NILP (millisec
))
4399 { /* Obsolete calling convention using integers rather than floats. */
4400 CHECK_NUMBER (millisec
);
4402 seconds
= make_float (XINT (millisec
) / 1000.0);
4405 CHECK_NUMBER (seconds
);
4406 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4413 if (!NILP (seconds
))
4415 if (INTEGERP (seconds
))
4417 if (XINT (seconds
) > 0)
4419 secs
= XINT (seconds
);
4423 else if (FLOATP (seconds
))
4425 if (XFLOAT_DATA (seconds
) > 0)
4427 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4428 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4433 wrong_type_argument (Qnumberp
, seconds
);
4435 else if (! NILP (process
))
4439 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4441 !NILP (process
) ? XPROCESS (process
) : NULL
,
4442 (NILP (just_this_one
) ? 0
4443 : !INTEGERP (just_this_one
) ? 1 : -1))
4448 /* Accept a connection for server process SERVER on CHANNEL. */
4450 static EMACS_INT connect_counter
= 0;
4453 server_accept_connection (Lisp_Object server
, int channel
)
4455 Lisp_Object proc
, caller
, name
, buffer
;
4456 Lisp_Object contact
, host
, service
;
4457 struct Lisp_Process
*ps
= XPROCESS (server
);
4458 struct Lisp_Process
*p
;
4462 struct sockaddr_in in
;
4464 struct sockaddr_in6 in6
;
4466 #ifdef HAVE_LOCAL_SOCKETS
4467 struct sockaddr_un un
;
4470 socklen_t len
= sizeof saddr
;
4473 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4478 if (!would_block (code
) && !NILP (ps
->log
))
4479 call3 (ps
->log
, server
, Qnil
,
4480 concat3 (build_string ("accept failed with code"),
4481 Fnumber_to_string (make_number (code
)),
4482 build_string ("\n")));
4486 count
= SPECPDL_INDEX ();
4487 record_unwind_protect_int (close_file_unwind
, s
);
4491 /* Setup a new process to handle the connection. */
4493 /* Generate a unique identification of the caller, and build contact
4494 information for this process. */
4497 switch (saddr
.sa
.sa_family
)
4501 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4503 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4504 host
= CALLN (Fformat
, ipv4_format
,
4505 make_number (ip
[0]), make_number (ip
[1]),
4506 make_number (ip
[2]), make_number (ip
[3]));
4507 service
= make_number (ntohs (saddr
.in
.sin_port
));
4508 AUTO_STRING (caller_format
, " <%s:%d>");
4509 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4516 Lisp_Object args
[9];
4517 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4520 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4521 args
[0] = ipv6_format
;
4522 for (i
= 0; i
< 8; i
++)
4523 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4524 host
= CALLMANY (Fformat
, args
);
4525 service
= make_number (ntohs (saddr
.in
.sin_port
));
4526 AUTO_STRING (caller_format
, " <[%s]:%d>");
4527 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4532 #ifdef HAVE_LOCAL_SOCKETS
4536 caller
= Fnumber_to_string (make_number (connect_counter
));
4537 AUTO_STRING (space_less_than
, " <");
4538 AUTO_STRING (greater_than
, ">");
4539 caller
= concat3 (space_less_than
, caller
, greater_than
);
4543 /* Create a new buffer name for this process if it doesn't have a
4544 filter. The new buffer name is based on the buffer name or
4545 process name of the server process concatenated with the caller
4548 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4549 || EQ (ps
->filter
, Qt
)))
4553 buffer
= ps
->buffer
;
4555 buffer
= Fbuffer_name (buffer
);
4560 buffer
= concat2 (buffer
, caller
);
4561 buffer
= Fget_buffer_create (buffer
);
4565 /* Generate a unique name for the new server process. Combine the
4566 server process name with the caller identification. */
4568 name
= concat2 (ps
->name
, caller
);
4569 proc
= make_process (name
);
4571 chan_process
[s
] = proc
;
4573 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4575 p
= XPROCESS (proc
);
4577 /* Build new contact information for this setup. */
4578 contact
= Fcopy_sequence (ps
->childp
);
4579 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4580 contact
= Fplist_put (contact
, QChost
, host
);
4581 if (!NILP (service
))
4582 contact
= Fplist_put (contact
, QCservice
, service
);
4583 contact
= Fplist_put (contact
, QCremote
,
4584 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4585 #ifdef HAVE_GETSOCKNAME
4587 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4588 contact
= Fplist_put (contact
, QClocal
,
4589 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4592 pset_childp (p
, contact
);
4593 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4594 pset_type (p
, Qnetwork
);
4596 pset_buffer (p
, buffer
);
4597 pset_sentinel (p
, ps
->sentinel
);
4598 pset_filter (p
, ps
->filter
);
4599 pset_command (p
, Qnil
);
4602 /* Discard the unwind protect for closing S. */
4603 specpdl_ptr
= specpdl
+ count
;
4605 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4608 pset_status (p
, Qrun
);
4610 /* Client processes for accepted connections are not stopped initially. */
4611 if (!EQ (p
->filter
, Qt
))
4613 FD_SET (s
, &input_wait_mask
);
4614 FD_SET (s
, &non_keyboard_wait_mask
);
4617 if (s
> max_process_desc
)
4618 max_process_desc
= s
;
4620 /* Setup coding system for new process based on server process.
4621 This seems to be the proper thing to do, as the coding system
4622 of the new process should reflect the settings at the time the
4623 server socket was opened; not the current settings. */
4625 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4626 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4627 setup_process_coding_systems (proc
);
4629 pset_decoding_buf (p
, empty_unibyte_string
);
4630 p
->decoding_carryover
= 0;
4631 pset_encoding_buf (p
, empty_unibyte_string
);
4633 p
->inherit_coding_system_flag
4634 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4636 AUTO_STRING (dash
, "-");
4637 AUTO_STRING (nl
, "\n");
4638 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4640 if (!NILP (ps
->log
))
4642 AUTO_STRING (accept_from
, "accept from ");
4643 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4646 AUTO_STRING (open_from
, "open from ");
4647 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4650 #ifdef HAVE_GETADDRINFO_A
4652 check_for_dns (Lisp_Object proc
)
4654 struct Lisp_Process
*p
= XPROCESS (proc
);
4655 Lisp_Object addrinfos
= Qnil
;
4658 if (! p
->dns_request
)
4661 int ret
= gai_error (p
->dns_request
);
4662 if (ret
== EAI_INPROGRESS
)
4665 /* We got a response. */
4668 struct addrinfo
*res
;
4670 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4671 addrinfos
= Fcons (conv_addrinfo_to_lisp (res
), addrinfos
);
4673 addrinfos
= Fnreverse (addrinfos
);
4675 /* The DNS lookup failed. */
4676 else if (EQ (p
->status
, Qconnect
))
4678 deactivate_process (proc
);
4679 pset_status (p
, (list2
4681 concat3 (build_string ("Name lookup of "),
4682 build_string (p
->dns_request
->ar_name
),
4683 build_string (" failed")))));
4686 free_dns_request (proc
);
4688 /* This process should not already be connected (or killed). */
4689 if (!EQ (p
->status
, Qconnect
))
4695 #endif /* HAVE_GETADDRINFO_A */
4698 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4700 while (XPROCESS (process
)->infd
< 0
4701 && EQ (XPROCESS (process
)->status
, Qconnect
))
4703 add_to_log ("Waiting for socket from %s...", build_string (name
));
4704 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4709 wait_while_connecting (Lisp_Object process
)
4711 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4713 add_to_log ("Waiting for connection...");
4714 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4719 wait_for_tls_negotiation (Lisp_Object process
)
4722 while (XPROCESS (process
)->gnutls_p
4723 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4725 add_to_log ("Waiting for TLS...");
4726 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4731 /* This variable is different from waiting_for_input in keyboard.c.
4732 It is used to communicate to a lisp process-filter/sentinel (via the
4733 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4734 for user-input when that process-filter was called.
4735 waiting_for_input cannot be used as that is by definition 0 when
4736 lisp code is being evalled.
4737 This is also used in record_asynch_buffer_change.
4738 For that purpose, this must be 0
4739 when not inside wait_reading_process_output. */
4740 static int waiting_for_user_input_p
;
4743 wait_reading_process_output_unwind (int data
)
4745 waiting_for_user_input_p
= data
;
4748 /* This is here so breakpoints can be put on it. */
4750 wait_reading_process_output_1 (void)
4754 /* Read and dispose of subprocess output while waiting for timeout to
4755 elapse and/or keyboard input to be available.
4759 If negative, gobble data immediately available but don't wait for any.
4762 an additional duration to wait, measured in nanoseconds
4763 If TIME_LIMIT is zero, then:
4764 If NSECS == 0, there is no limit.
4765 If NSECS > 0, the timeout consists of NSECS only.
4766 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4769 0 to ignore keyboard input, or
4770 1 to return when input is available, or
4771 -1 meaning caller will actually read the input, so don't throw to
4772 the quit handler, or
4774 DO_DISPLAY means redisplay should be done to show subprocess
4775 output that arrives.
4777 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4778 (and gobble terminal input into the buffer if any arrives).
4780 If WAIT_PROC is specified, wait until something arrives from that
4783 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4784 (suspending output from other processes). A negative value
4785 means don't run any timers either.
4787 Return positive if we received input from WAIT_PROC (or from any
4788 process if WAIT_PROC is null), zero if we attempted to receive
4789 input but got none, and negative if we didn't even try. */
4792 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4794 Lisp_Object wait_for_cell
,
4795 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4805 struct timespec timeout
, end_time
, timer_delay
;
4806 struct timespec got_output_end_time
= invalid_timespec ();
4807 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4808 int got_some_output
= -1;
4809 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4810 bool retry_for_async
;
4812 ptrdiff_t count
= SPECPDL_INDEX ();
4814 /* Close to the current time if known, an invalid timespec otherwise. */
4815 struct timespec now
= invalid_timespec ();
4817 FD_ZERO (&Available
);
4820 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4821 && !(CONSP (wait_proc
->status
)
4822 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4823 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4825 record_unwind_protect_int (wait_reading_process_output_unwind
,
4826 waiting_for_user_input_p
);
4827 waiting_for_user_input_p
= read_kbd
;
4829 if (TYPE_MAXIMUM (time_t) < time_limit
)
4830 time_limit
= TYPE_MAXIMUM (time_t);
4832 if (time_limit
< 0 || nsecs
< 0)
4834 else if (time_limit
> 0 || nsecs
> 0)
4837 now
= current_timespec ();
4838 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4845 bool process_skipped
= false;
4847 /* If calling from keyboard input, do not quit
4848 since we want to return C-g as an input character.
4849 Otherwise, do pending quit if requested. */
4852 else if (pending_signals
)
4853 process_pending_signals ();
4855 /* Exit now if the cell we're waiting for became non-nil. */
4856 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4859 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4861 Lisp_Object process_list_head
, aproc
;
4862 struct Lisp_Process
*p
;
4864 retry_for_async
= false;
4865 FOR_EACH_PROCESS(process_list_head
, aproc
)
4867 p
= XPROCESS (aproc
);
4869 if (! wait_proc
|| p
== wait_proc
)
4871 #ifdef HAVE_GETADDRINFO_A
4872 /* Check for pending DNS requests. */
4875 Lisp_Object addrinfos
= check_for_dns (aproc
);
4876 if (!NILP (addrinfos
) && !EQ (addrinfos
, Qt
))
4877 connect_network_socket (aproc
, addrinfos
, Qnil
);
4879 retry_for_async
= true;
4883 /* Continue TLS negotiation. */
4884 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4885 && p
->is_non_blocking_client
)
4887 gnutls_try_handshake (p
);
4888 p
->gnutls_handshakes_tried
++;
4890 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4892 gnutls_verify_boot (aproc
, Qnil
);
4893 finish_after_tls_connection (aproc
);
4897 retry_for_async
= true;
4898 if (p
->gnutls_handshakes_tried
4899 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4901 deactivate_process (aproc
);
4902 pset_status (p
, list2 (Qfailed
,
4903 build_string ("TLS negotiation failed")));
4911 #endif /* GETADDRINFO_A or GNUTLS */
4913 /* Compute time from now till when time limit is up. */
4914 /* Exit if already run out. */
4915 if (wait
== TIMEOUT
)
4917 if (!timespec_valid_p (now
))
4918 now
= current_timespec ();
4919 if (timespec_cmp (end_time
, now
) <= 0)
4921 timeout
= timespec_sub (end_time
, now
);
4924 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4926 /* Normally we run timers here.
4927 But not if wait_for_cell; in those cases,
4928 the wait is supposed to be short,
4929 and those callers cannot handle running arbitrary Lisp code here. */
4930 if (NILP (wait_for_cell
)
4931 && just_wait_proc
>= 0)
4935 unsigned old_timers_run
= timers_run
;
4936 struct buffer
*old_buffer
= current_buffer
;
4937 Lisp_Object old_window
= selected_window
;
4939 timer_delay
= timer_check ();
4941 /* If a timer has run, this might have changed buffers
4942 an alike. Make read_key_sequence aware of that. */
4943 if (timers_run
!= old_timers_run
4944 && (old_buffer
!= current_buffer
4945 || !EQ (old_window
, selected_window
))
4946 && waiting_for_user_input_p
== -1)
4947 record_asynch_buffer_change ();
4949 if (timers_run
!= old_timers_run
&& do_display
)
4950 /* We must retry, since a timer may have requeued itself
4951 and that could alter the time_delay. */
4952 redisplay_preserve_echo_area (9);
4956 while (!detect_input_pending ());
4958 /* If there is unread keyboard input, also return. */
4960 && requeued_events_pending_p ())
4963 /* This is so a breakpoint can be put here. */
4964 if (!timespec_valid_p (timer_delay
))
4965 wait_reading_process_output_1 ();
4968 /* Cause C-g and alarm signals to take immediate action,
4969 and cause input available signals to zero out timeout.
4971 It is important that we do this before checking for process
4972 activity. If we get a SIGCHLD after the explicit checks for
4973 process activity, timeout is the only way we will know. */
4975 set_waiting_for_input (&timeout
);
4977 /* If status of something has changed, and no input is
4978 available, notify the user of the change right away. After
4979 this explicit check, we'll let the SIGCHLD handler zap
4980 timeout to get our attention. */
4981 if (update_tick
!= process_tick
)
4986 if (kbd_on_hold_p ())
4989 Atemp
= input_wait_mask
;
4992 timeout
= make_timespec (0, 0);
4993 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4995 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4996 NULL
, &timeout
, NULL
)
4999 /* It's okay for us to do this and then continue with
5000 the loop, since timeout has already been zeroed out. */
5001 clear_waiting_for_input ();
5002 got_some_output
= status_notify (NULL
, wait_proc
);
5003 if (do_display
) redisplay_preserve_echo_area (13);
5007 /* Don't wait for output from a non-running process. Just
5008 read whatever data has already been received. */
5009 if (wait_proc
&& wait_proc
->raw_status_new
)
5010 update_status (wait_proc
);
5012 && ! EQ (wait_proc
->status
, Qrun
)
5013 && ! EQ (wait_proc
->status
, Qconnect
))
5015 bool read_some_bytes
= false;
5017 clear_waiting_for_input ();
5019 /* If data can be read from the process, do so until exhausted. */
5020 if (wait_proc
->infd
>= 0)
5022 XSETPROCESS (proc
, wait_proc
);
5026 int nread
= read_process_output (proc
, wait_proc
->infd
);
5029 if (errno
== EIO
|| would_block (errno
))
5034 if (got_some_output
< nread
)
5035 got_some_output
= nread
;
5038 read_some_bytes
= true;
5043 if (read_some_bytes
&& do_display
)
5044 redisplay_preserve_echo_area (10);
5049 /* Wait till there is something to do. */
5051 if (wait_proc
&& just_wait_proc
)
5053 if (wait_proc
->infd
< 0) /* Terminated. */
5055 FD_SET (wait_proc
->infd
, &Available
);
5059 else if (!NILP (wait_for_cell
))
5061 Available
= non_process_wait_mask
;
5068 Available
= non_keyboard_wait_mask
;
5070 Available
= input_wait_mask
;
5071 Writeok
= write_mask
;
5072 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5076 /* If frame size has changed or the window is newly mapped,
5077 redisplay now, before we start to wait. There is a race
5078 condition here; if a SIGIO arrives between now and the select
5079 and indicates that a frame is trashed, the select may block
5080 displaying a trashed screen. */
5081 if (frame_garbaged
&& do_display
)
5083 clear_waiting_for_input ();
5084 redisplay_preserve_echo_area (11);
5086 set_waiting_for_input (&timeout
);
5089 /* Skip the `select' call if input is available and we're
5090 waiting for keyboard input or a cell change (which can be
5091 triggered by processing X events). In the latter case, set
5092 nfds to 1 to avoid breaking the loop. */
5094 if ((read_kbd
|| !NILP (wait_for_cell
))
5095 && detect_input_pending ())
5097 nfds
= read_kbd
? 0 : 1;
5099 FD_ZERO (&Available
);
5103 /* Set the timeout for adaptive read buffering if any
5104 process has non-zero read_output_skip and non-zero
5105 read_output_delay, and we are not reading output for a
5106 specific process. It is not executed if
5107 Vprocess_adaptive_read_buffering is nil. */
5108 if (process_output_skip
&& check_delay
> 0)
5110 int adaptive_nsecs
= timeout
.tv_nsec
;
5111 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5112 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5113 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5115 proc
= chan_process
[channel
];
5118 /* Find minimum non-zero read_output_delay among the
5119 processes with non-zero read_output_skip. */
5120 if (XPROCESS (proc
)->read_output_delay
> 0)
5123 if (!XPROCESS (proc
)->read_output_skip
)
5125 FD_CLR (channel
, &Available
);
5126 process_skipped
= true;
5127 XPROCESS (proc
)->read_output_skip
= 0;
5128 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5129 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5132 timeout
= make_timespec (0, adaptive_nsecs
);
5133 process_output_skip
= 0;
5136 /* If we've got some output and haven't limited our timeout
5137 with adaptive read buffering, limit it. */
5138 if (got_some_output
> 0 && !process_skipped
5140 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5141 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5144 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5145 && timespec_valid_p (timer_delay
)
5146 && timespec_cmp (timer_delay
, timeout
) < 0)
5148 if (!timespec_valid_p (now
))
5149 now
= current_timespec ();
5150 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5151 if (!timespec_valid_p (got_output_end_time
)
5152 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5153 got_output_end_time
= timeout_abs
;
5154 timeout
= timer_delay
;
5157 got_output_end_time
= invalid_timespec ();
5159 /* NOW can become inaccurate if time can pass during pselect. */
5160 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5161 now
= invalid_timespec ();
5163 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5165 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5168 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5172 #if defined (HAVE_NS)
5174 #elif defined (HAVE_GLIB)
5179 (max (max_process_desc
, max_input_desc
) + 1,
5181 (check_write
? &Writeok
: 0),
5182 NULL
, &timeout
, NULL
);
5185 /* GnuTLS buffers data internally. In lowat mode it leaves
5186 some data in the TCP buffers so that select works, but
5187 with custom pull/push functions we need to check if some
5188 data is available in the buffers manually. */
5191 fd_set tls_available
;
5194 FD_ZERO (&tls_available
);
5197 /* We're not waiting on a specific process, so loop
5198 through all the channels and check for data.
5199 This is a workaround needed for some versions of
5200 the gnutls library -- 2.12.14 has been confirmed
5202 http://comments.gmane.org/gmane.emacs.devel/145074 */
5203 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5204 if (! NILP (chan_process
[channel
]))
5206 struct Lisp_Process
*p
=
5207 XPROCESS (chan_process
[channel
]);
5208 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5209 && ((emacs_gnutls_record_check_pending
5214 eassert (p
->infd
== channel
);
5215 FD_SET (p
->infd
, &tls_available
);
5222 /* Check this specific channel. */
5223 if (wait_proc
->gnutls_p
/* Check for valid process. */
5224 && wait_proc
->gnutls_state
5225 /* Do we have pending data? */
5226 && ((emacs_gnutls_record_check_pending
5227 (wait_proc
->gnutls_state
))
5231 eassert (0 <= wait_proc
->infd
);
5232 /* Set to Available. */
5233 FD_SET (wait_proc
->infd
, &tls_available
);
5238 Available
= tls_available
;
5245 /* Make C-g and alarm signals set flags again. */
5246 clear_waiting_for_input ();
5248 /* If we woke up due to SIGWINCH, actually change size now. */
5249 do_pending_window_change (0);
5253 /* Exit the main loop if we've passed the requested timeout,
5254 or aren't skipping processes and got some output and
5255 haven't lowered our timeout due to timers or SIGIO and
5256 have waited a long amount of time due to repeated
5260 struct timespec cmp_time
5263 : (!process_skipped
&& got_some_output
> 0
5264 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5265 ? got_output_end_time
5266 : invalid_timespec ());
5267 if (timespec_valid_p (cmp_time
))
5269 now
= current_timespec ();
5270 if (timespec_cmp (cmp_time
, now
) <= 0)
5277 if (xerrno
== EINTR
)
5279 else if (xerrno
== EBADF
)
5282 report_file_errno ("Failed select", Qnil
, xerrno
);
5285 /* Check for keyboard input. */
5286 /* If there is any, return immediately
5287 to give it higher priority than subprocesses. */
5291 unsigned old_timers_run
= timers_run
;
5292 struct buffer
*old_buffer
= current_buffer
;
5293 Lisp_Object old_window
= selected_window
;
5296 if (detect_input_pending_run_timers (do_display
))
5298 swallow_events (do_display
);
5299 if (detect_input_pending_run_timers (do_display
))
5303 /* If a timer has run, this might have changed buffers
5304 an alike. Make read_key_sequence aware of that. */
5305 if (timers_run
!= old_timers_run
5306 && waiting_for_user_input_p
== -1
5307 && (old_buffer
!= current_buffer
5308 || !EQ (old_window
, selected_window
)))
5309 record_asynch_buffer_change ();
5315 /* If there is unread keyboard input, also return. */
5317 && requeued_events_pending_p ())
5320 /* If we are not checking for keyboard input now,
5321 do process events (but don't run any timers).
5322 This is so that X events will be processed.
5323 Otherwise they may have to wait until polling takes place.
5324 That would causes delays in pasting selections, for example.
5326 (We used to do this only if wait_for_cell.) */
5327 if (read_kbd
== 0 && detect_input_pending ())
5329 swallow_events (do_display
);
5330 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5331 if (detect_input_pending ())
5336 /* Exit now if the cell we're waiting for became non-nil. */
5337 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5341 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5342 go read it. This can happen with X on BSD after logging out.
5343 In that case, there really is no input and no SIGIO,
5344 but select says there is input. */
5346 if (read_kbd
&& interrupt_input
5347 && keyboard_bit_set (&Available
) && ! noninteractive
)
5348 handle_input_available_signal (SIGIO
);
5351 /* If checking input just got us a size-change event from X,
5352 obey it now if we should. */
5353 if (read_kbd
|| ! NILP (wait_for_cell
))
5354 do_pending_window_change (0);
5356 /* Check for data from a process. */
5357 if (no_avail
|| nfds
== 0)
5360 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5362 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5364 && ((d
->condition
& FOR_READ
5365 && FD_ISSET (channel
, &Available
))
5366 || (d
->condition
& FOR_WRITE
5367 && FD_ISSET (channel
, &write_mask
))))
5368 d
->func (channel
, d
->data
);
5371 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5373 if (FD_ISSET (channel
, &Available
)
5374 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5375 && !FD_ISSET (channel
, &non_process_wait_mask
))
5379 /* If waiting for this channel, arrange to return as
5380 soon as no more input to be processed. No more
5382 proc
= chan_process
[channel
];
5386 /* If this is a server stream socket, accept connection. */
5387 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5389 server_accept_connection (proc
, channel
);
5393 /* Read data from the process, starting with our
5394 buffered-ahead character if we have one. */
5396 nread
= read_process_output (proc
, channel
);
5397 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5398 && got_some_output
< nread
)
5399 got_some_output
= nread
;
5402 /* Vacuum up any leftovers without waiting. */
5403 if (wait_proc
== XPROCESS (proc
))
5405 /* Since read_process_output can run a filter,
5406 which can call accept-process-output,
5407 don't try to read from any other processes
5408 before doing the select again. */
5409 FD_ZERO (&Available
);
5412 redisplay_preserve_echo_area (12);
5414 else if (nread
== -1 && would_block (errno
))
5417 /* FIXME: Is this special case still needed? */
5418 /* Note that we cannot distinguish between no input
5419 available now and a closed pipe.
5420 With luck, a closed pipe will be accompanied by
5421 subprocess termination and SIGCHLD. */
5422 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5423 && !PIPECONN_P (proc
))
5427 /* On some OSs with ptys, when the process on one end of
5428 a pty exits, the other end gets an error reading with
5429 errno = EIO instead of getting an EOF (0 bytes read).
5430 Therefore, if we get an error reading and errno =
5431 EIO, just continue, because the child process has
5432 exited and should clean itself up soon (e.g. when we
5434 else if (nread
== -1 && errno
== EIO
)
5436 struct Lisp_Process
*p
= XPROCESS (proc
);
5438 /* Clear the descriptor now, so we only raise the
5440 FD_CLR (channel
, &input_wait_mask
);
5441 FD_CLR (channel
, &non_keyboard_wait_mask
);
5445 /* If the EIO occurs on a pty, the SIGCHLD handler's
5446 waitpid call will not find the process object to
5447 delete. Do it here. */
5448 p
->tick
= ++process_tick
;
5449 pset_status (p
, Qfailed
);
5452 #endif /* HAVE_PTYS */
5453 /* If we can detect process termination, don't consider the
5454 process gone just because its pipe is closed. */
5455 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5456 && !PIPECONN_P (proc
))
5458 else if (nread
== 0 && PIPECONN_P (proc
))
5460 /* Preserve status of processes already terminated. */
5461 XPROCESS (proc
)->tick
= ++process_tick
;
5462 deactivate_process (proc
);
5463 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5464 pset_status (XPROCESS (proc
),
5465 list2 (Qexit
, make_number (0)));
5469 /* Preserve status of processes already terminated. */
5470 XPROCESS (proc
)->tick
= ++process_tick
;
5471 deactivate_process (proc
);
5472 if (XPROCESS (proc
)->raw_status_new
)
5473 update_status (XPROCESS (proc
));
5474 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5475 pset_status (XPROCESS (proc
),
5476 list2 (Qexit
, make_number (256)));
5479 if (FD_ISSET (channel
, &Writeok
)
5480 && FD_ISSET (channel
, &connect_wait_mask
))
5482 struct Lisp_Process
*p
;
5484 FD_CLR (channel
, &connect_wait_mask
);
5485 FD_CLR (channel
, &write_mask
);
5486 if (--num_pending_connects
< 0)
5489 proc
= chan_process
[channel
];
5493 p
= XPROCESS (proc
);
5497 socklen_t xlen
= sizeof (xerrno
);
5498 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5502 /* On MS-Windows, getsockopt clears the error for the
5503 entire process, which may not be the right thing; see
5504 w32.c. Use getpeername instead. */
5506 struct sockaddr pname
;
5507 socklen_t pnamelen
= sizeof (pname
);
5509 /* If connection failed, getpeername will fail. */
5511 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5513 /* Obtain connect failure code through error slippage. */
5516 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5523 p
->tick
= ++process_tick
;
5524 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5525 deactivate_process (proc
);
5530 /* If we have an incompletely set up TLS connection,
5531 then defer the sentinel signaling until
5533 if (NILP (p
->gnutls_boot_parameters
)
5537 pset_status (p
, Qrun
);
5538 /* Execute the sentinel here. If we had relied on
5539 status_notify to do it later, it will read input
5540 from the process before calling the sentinel. */
5541 exec_sentinel (proc
, build_string ("open\n"));
5544 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5545 && !EQ (p
->command
, Qt
))
5547 FD_SET (p
->infd
, &input_wait_mask
);
5548 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5552 } /* End for each file descriptor. */
5553 } /* End while exit conditions not met. */
5555 unbind_to (count
, Qnil
);
5557 /* If calling from keyboard input, do not quit
5558 since we want to return C-g as an input character.
5559 Otherwise, do pending quit if requested. */
5562 /* Prevent input_pending from remaining set if we quit. */
5563 clear_input_pending ();
5567 return got_some_output
;
5570 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5573 read_process_output_call (Lisp_Object fun_and_args
)
5575 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5579 read_process_output_error_handler (Lisp_Object error_val
)
5581 cmd_error_internal (error_val
, "error in process filter: ");
5583 update_echo_area ();
5584 Fsleep_for (make_number (2), Qnil
);
5589 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5591 struct coding_system
*coding
);
5593 /* Read pending output from the process channel,
5594 starting with our buffered-ahead character if we have one.
5595 Yield number of decoded characters read.
5597 This function reads at most 4096 characters.
5598 If you want to read all available subprocess output,
5599 you must call it repeatedly until it returns zero.
5601 The characters read are decoded according to PROC's coding-system
5605 read_process_output (Lisp_Object proc
, int channel
)
5608 struct Lisp_Process
*p
= XPROCESS (proc
);
5609 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5610 int carryover
= p
->decoding_carryover
;
5611 enum { readmax
= 4096 };
5612 ptrdiff_t count
= SPECPDL_INDEX ();
5613 Lisp_Object odeactivate
;
5614 char chars
[sizeof coding
->carryover
+ readmax
];
5617 /* See the comment above. */
5618 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5620 #ifdef DATAGRAM_SOCKETS
5621 /* We have a working select, so proc_buffered_char is always -1. */
5622 if (DATAGRAM_CHAN_P (channel
))
5624 socklen_t len
= datagram_address
[channel
].len
;
5625 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5626 0, datagram_address
[channel
].sa
, &len
);
5631 bool buffered
= proc_buffered_char
[channel
] >= 0;
5634 chars
[carryover
] = proc_buffered_char
[channel
];
5635 proc_buffered_char
[channel
] = -1;
5638 if (p
->gnutls_p
&& p
->gnutls_state
)
5639 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5640 readmax
- buffered
);
5643 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5644 readmax
- buffered
);
5645 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5647 int delay
= p
->read_output_delay
;
5650 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5653 process_output_delay_count
++;
5654 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5657 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5659 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5661 process_output_delay_count
--;
5663 p
->read_output_delay
= delay
;
5666 p
->read_output_skip
= 1;
5667 process_output_skip
= 1;
5671 nbytes
+= buffered
&& nbytes
<= 0;
5674 p
->decoding_carryover
= 0;
5676 /* At this point, NBYTES holds number of bytes just received
5677 (including the one in proc_buffered_char[channel]). */
5680 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5682 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5685 /* Now set NBYTES how many bytes we must decode. */
5686 nbytes
+= carryover
;
5688 odeactivate
= Vdeactivate_mark
;
5689 /* There's no good reason to let process filters change the current
5690 buffer, and many callers of accept-process-output, sit-for, and
5691 friends don't expect current-buffer to be changed from under them. */
5692 record_unwind_current_buffer ();
5694 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5696 /* Handling the process output should not deactivate the mark. */
5697 Vdeactivate_mark
= odeactivate
;
5699 unbind_to (count
, Qnil
);
5704 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5706 struct coding_system
*coding
)
5708 Lisp_Object outstream
= p
->filter
;
5710 bool outer_running_asynch_code
= running_asynch_code
;
5711 int waiting
= waiting_for_user_input_p
;
5714 Lisp_Object obuffer
, okeymap
;
5715 XSETBUFFER (obuffer
, current_buffer
);
5716 okeymap
= BVAR (current_buffer
, keymap
);
5719 /* We inhibit quit here instead of just catching it so that
5720 hitting ^G when a filter happens to be running won't screw
5722 specbind (Qinhibit_quit
, Qt
);
5723 specbind (Qlast_nonmenu_event
, Qt
);
5725 /* In case we get recursively called,
5726 and we already saved the match data nonrecursively,
5727 save the same match data in safely recursive fashion. */
5728 if (outer_running_asynch_code
)
5731 /* Don't clobber the CURRENT match data, either! */
5732 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5733 restore_search_regs ();
5734 record_unwind_save_match_data ();
5735 Fset_match_data (tem
, Qt
);
5738 /* For speed, if a search happens within this code,
5739 save the match data in a special nonrecursive fashion. */
5740 running_asynch_code
= 1;
5742 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5743 text
= coding
->dst_object
;
5744 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5745 /* A new coding system might be found. */
5746 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5748 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5750 /* Don't call setup_coding_system for
5751 proc_decode_coding_system[channel] here. It is done in
5752 detect_coding called via decode_coding above. */
5754 /* If a coding system for encoding is not yet decided, we set
5755 it as the same as coding-system for decoding.
5757 But, before doing that we must check if
5758 proc_encode_coding_system[p->outfd] surely points to a
5759 valid memory because p->outfd will be changed once EOF is
5760 sent to the process. */
5761 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5762 && proc_encode_coding_system
[p
->outfd
])
5764 pset_encode_coding_system
5765 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5766 setup_coding_system (p
->encode_coding_system
,
5767 proc_encode_coding_system
[p
->outfd
]);
5771 if (coding
->carryover_bytes
> 0)
5773 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5774 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5775 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5776 coding
->carryover_bytes
);
5777 p
->decoding_carryover
= coding
->carryover_bytes
;
5779 if (SBYTES (text
) > 0)
5780 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5781 sometimes it's simply wrong to wrap (e.g. when called from
5782 accept-process-output). */
5783 internal_condition_case_1 (read_process_output_call
,
5784 list3 (outstream
, make_lisp_proc (p
), text
),
5785 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5786 read_process_output_error_handler
);
5788 /* If we saved the match data nonrecursively, restore it now. */
5789 restore_search_regs ();
5790 running_asynch_code
= outer_running_asynch_code
;
5792 /* Restore waiting_for_user_input_p as it was
5793 when we were called, in case the filter clobbered it. */
5794 waiting_for_user_input_p
= waiting
;
5796 #if 0 /* Call record_asynch_buffer_change unconditionally,
5797 because we might have changed minor modes or other things
5798 that affect key bindings. */
5799 if (! EQ (Fcurrent_buffer (), obuffer
)
5800 || ! EQ (current_buffer
->keymap
, okeymap
))
5802 /* But do it only if the caller is actually going to read events.
5803 Otherwise there's no need to make him wake up, and it could
5804 cause trouble (for example it would make sit_for return). */
5805 if (waiting_for_user_input_p
== -1)
5806 record_asynch_buffer_change ();
5809 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5810 Sinternal_default_process_filter
, 2, 2, 0,
5811 doc
: /* Function used as default process filter.
5812 This inserts the process's output into its buffer, if there is one.
5813 Otherwise it discards the output. */)
5814 (Lisp_Object proc
, Lisp_Object text
)
5816 struct Lisp_Process
*p
;
5819 CHECK_PROCESS (proc
);
5820 p
= XPROCESS (proc
);
5821 CHECK_STRING (text
);
5823 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5825 Lisp_Object old_read_only
;
5826 ptrdiff_t old_begv
, old_zv
;
5827 ptrdiff_t old_begv_byte
, old_zv_byte
;
5828 ptrdiff_t before
, before_byte
;
5829 ptrdiff_t opoint_byte
;
5832 Fset_buffer (p
->buffer
);
5834 opoint_byte
= PT_BYTE
;
5835 old_read_only
= BVAR (current_buffer
, read_only
);
5838 old_begv_byte
= BEGV_BYTE
;
5839 old_zv_byte
= ZV_BYTE
;
5841 bset_read_only (current_buffer
, Qnil
);
5843 /* Insert new output into buffer at the current end-of-output
5844 marker, thus preserving logical ordering of input and output. */
5845 if (XMARKER (p
->mark
)->buffer
)
5846 set_point_from_marker (p
->mark
);
5848 SET_PT_BOTH (ZV
, ZV_BYTE
);
5850 before_byte
= PT_BYTE
;
5852 /* If the output marker is outside of the visible region, save
5853 the restriction and widen. */
5854 if (! (BEGV
<= PT
&& PT
<= ZV
))
5857 /* Adjust the multibyteness of TEXT to that of the buffer. */
5858 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5859 != ! STRING_MULTIBYTE (text
))
5860 text
= (STRING_MULTIBYTE (text
)
5861 ? Fstring_as_unibyte (text
)
5862 : Fstring_to_multibyte (text
));
5863 /* Insert before markers in case we are inserting where
5864 the buffer's mark is, and the user's next command is Meta-y. */
5865 insert_from_string_before_markers (text
, 0, 0,
5866 SCHARS (text
), SBYTES (text
), 0);
5868 /* Make sure the process marker's position is valid when the
5869 process buffer is changed in the signal_after_change above.
5870 W3 is known to do that. */
5871 if (BUFFERP (p
->buffer
)
5872 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5873 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5875 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5877 update_mode_lines
= 23;
5879 /* Make sure opoint and the old restrictions
5880 float ahead of any new text just as point would. */
5881 if (opoint
>= before
)
5883 opoint
+= PT
- before
;
5884 opoint_byte
+= PT_BYTE
- before_byte
;
5886 if (old_begv
> before
)
5888 old_begv
+= PT
- before
;
5889 old_begv_byte
+= PT_BYTE
- before_byte
;
5891 if (old_zv
>= before
)
5893 old_zv
+= PT
- before
;
5894 old_zv_byte
+= PT_BYTE
- before_byte
;
5897 /* If the restriction isn't what it should be, set it. */
5898 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5899 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5901 bset_read_only (current_buffer
, old_read_only
);
5902 SET_PT_BOTH (opoint
, opoint_byte
);
5907 /* Sending data to subprocess. */
5909 /* In send_process, when a write fails temporarily,
5910 wait_reading_process_output is called. It may execute user code,
5911 e.g. timers, that attempts to write new data to the same process.
5912 We must ensure that data is sent in the right order, and not
5913 interspersed half-completed with other writes (Bug#10815). This is
5914 handled by the write_queue element of struct process. It is a list
5915 with each entry having the form
5917 (string . (offset . length))
5919 where STRING is a lisp string, OFFSET is the offset into the
5920 string's byte sequence from which we should begin to send, and
5921 LENGTH is the number of bytes left to send. */
5923 /* Create a new entry in write_queue.
5924 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5925 BUF is a pointer to the string sequence of the input_obj or a C
5926 string in case of Qt or Qnil. */
5929 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5930 const char *buf
, ptrdiff_t len
, bool front
)
5933 Lisp_Object entry
, obj
;
5935 if (STRINGP (input_obj
))
5937 offset
= buf
- SSDATA (input_obj
);
5943 obj
= make_unibyte_string (buf
, len
);
5946 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5949 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5951 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5954 /* Remove the first element in the write_queue of process P, put its
5955 contents in OBJ, BUF and LEN, and return true. If the
5956 write_queue is empty, return false. */
5959 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5960 const char **buf
, ptrdiff_t *len
)
5962 Lisp_Object entry
, offset_length
;
5965 if (NILP (p
->write_queue
))
5968 entry
= XCAR (p
->write_queue
);
5969 pset_write_queue (p
, XCDR (p
->write_queue
));
5971 *obj
= XCAR (entry
);
5972 offset_length
= XCDR (entry
);
5974 *len
= XINT (XCDR (offset_length
));
5975 offset
= XINT (XCAR (offset_length
));
5976 *buf
= SSDATA (*obj
) + offset
;
5981 /* Send some data to process PROC.
5982 BUF is the beginning of the data; LEN is the number of characters.
5983 OBJECT is the Lisp object that the data comes from. If OBJECT is
5984 nil or t, it means that the data comes from C string.
5986 If OBJECT is not nil, the data is encoded by PROC's coding-system
5987 for encoding before it is sent.
5989 This function can evaluate Lisp code and can garbage collect. */
5992 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5995 struct Lisp_Process
*p
= XPROCESS (proc
);
5997 struct coding_system
*coding
;
5999 if (NETCONN_P (proc
))
6001 wait_while_connecting (proc
);
6002 wait_for_tls_negotiation (proc
);
6005 if (p
->raw_status_new
)
6007 if (! EQ (p
->status
, Qrun
))
6008 error ("Process %s not running", SDATA (p
->name
));
6010 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6012 coding
= proc_encode_coding_system
[p
->outfd
];
6013 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6015 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6016 || (BUFFERP (object
)
6017 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6020 pset_encode_coding_system
6021 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6022 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6024 /* The coding system for encoding was changed to raw-text
6025 because we sent a unibyte text previously. Now we are
6026 sending a multibyte text, thus we must encode it by the
6027 original coding system specified for the current process.
6029 Another reason we come here is that the coding system
6030 was just complemented and a new one was returned by
6031 complement_process_encoding_system. */
6032 setup_coding_system (p
->encode_coding_system
, coding
);
6033 Vlast_coding_system_used
= p
->encode_coding_system
;
6035 coding
->src_multibyte
= 1;
6039 coding
->src_multibyte
= 0;
6040 /* For sending a unibyte text, character code conversion should
6041 not take place but EOL conversion should. So, setup raw-text
6042 or one of the subsidiary if we have not yet done it. */
6043 if (CODING_REQUIRE_ENCODING (coding
))
6045 if (CODING_REQUIRE_FLUSHING (coding
))
6047 /* But, before changing the coding, we must flush out data. */
6048 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6049 send_process (proc
, "", 0, Qt
);
6050 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6052 setup_coding_system (raw_text_coding_system
6053 (Vlast_coding_system_used
),
6055 coding
->src_multibyte
= 0;
6058 coding
->dst_multibyte
= 0;
6060 if (CODING_REQUIRE_ENCODING (coding
))
6062 coding
->dst_object
= Qt
;
6063 if (BUFFERP (object
))
6065 ptrdiff_t from_byte
, from
, to
;
6066 ptrdiff_t save_pt
, save_pt_byte
;
6067 struct buffer
*cur
= current_buffer
;
6069 set_buffer_internal (XBUFFER (object
));
6070 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6072 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6073 from
= BYTE_TO_CHAR (from_byte
);
6074 to
= BYTE_TO_CHAR (from_byte
+ len
);
6075 TEMP_SET_PT_BOTH (from
, from_byte
);
6076 encode_coding_object (coding
, object
, from
, from_byte
,
6077 to
, from_byte
+ len
, Qt
);
6078 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6079 set_buffer_internal (cur
);
6081 else if (STRINGP (object
))
6083 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6084 SBYTES (object
), Qt
);
6088 coding
->dst_object
= make_unibyte_string (buf
, len
);
6089 coding
->produced
= len
;
6092 len
= coding
->produced
;
6093 object
= coding
->dst_object
;
6094 buf
= SSDATA (object
);
6097 /* If there is already data in the write_queue, put the new data
6098 in the back of queue. Otherwise, ignore it. */
6099 if (!NILP (p
->write_queue
))
6100 write_queue_push (p
, object
, buf
, len
, 0);
6102 do /* while !NILP (p->write_queue) */
6104 ptrdiff_t cur_len
= -1;
6105 const char *cur_buf
;
6106 Lisp_Object cur_object
;
6108 /* If write_queue is empty, ignore it. */
6109 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6113 cur_object
= object
;
6118 /* Send this batch, using one or more write calls. */
6119 ptrdiff_t written
= 0;
6120 int outfd
= p
->outfd
;
6121 #ifdef DATAGRAM_SOCKETS
6122 if (DATAGRAM_CHAN_P (outfd
))
6124 rv
= sendto (outfd
, cur_buf
, cur_len
,
6125 0, datagram_address
[outfd
].sa
,
6126 datagram_address
[outfd
].len
);
6129 else if (errno
== EMSGSIZE
)
6130 report_file_error ("Sending datagram", proc
);
6136 if (p
->gnutls_p
&& p
->gnutls_state
)
6137 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6140 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6141 rv
= (written
? 0 : -1);
6142 if (p
->read_output_delay
> 0
6143 && p
->adaptive_read_buffering
== 1)
6145 p
->read_output_delay
= 0;
6146 process_output_delay_count
--;
6147 p
->read_output_skip
= 0;
6153 if (would_block (errno
))
6154 /* Buffer is full. Wait, accepting input;
6155 that may allow the program
6156 to finish doing output and read more. */
6158 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6159 /* A gross hack to work around a bug in FreeBSD.
6160 In the following sequence, read(2) returns
6164 write(2) 954 bytes, get EAGAIN
6165 read(2) 1024 bytes in process_read_output
6166 read(2) 11 bytes in process_read_output
6168 That is, read(2) returns more bytes than have
6169 ever been written successfully. The 1033 bytes
6170 read are the 1022 bytes written successfully
6171 after processing (for example with CRs added if
6172 the terminal is set up that way which it is
6173 here). The same bytes will be seen again in a
6174 later read(2), without the CRs. */
6176 if (errno
== EAGAIN
)
6179 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6181 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6183 /* Put what we should have written in wait_queue. */
6184 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6185 wait_reading_process_output (0, 20 * 1000 * 1000,
6186 0, 0, Qnil
, NULL
, 0);
6187 /* Reread queue, to see what is left. */
6190 else if (errno
== EPIPE
)
6192 p
->raw_status_new
= 0;
6193 pset_status (p
, list2 (Qexit
, make_number (256)));
6194 p
->tick
= ++process_tick
;
6195 deactivate_process (proc
);
6196 error ("process %s no longer connected to pipe; closed it",
6200 /* This is a real error. */
6201 report_file_error ("Writing to process", proc
);
6207 while (!NILP (p
->write_queue
));
6210 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6212 doc
: /* Send current contents of region as input to PROCESS.
6213 PROCESS may be a process, a buffer, the name of a process or buffer, or
6214 nil, indicating the current buffer's process.
6215 Called from program, takes three arguments, PROCESS, START and END.
6216 If the region is more than 500 characters long,
6217 it is sent in several bunches. This may happen even for shorter regions.
6218 Output from processes can arrive in between bunches.
6220 If PROCESS is a non-blocking network process that hasn't been fully
6221 set up yet, this function will block until socket setup has completed. */)
6222 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6224 Lisp_Object proc
= get_process (process
);
6225 ptrdiff_t start_byte
, end_byte
;
6227 validate_region (&start
, &end
);
6229 start_byte
= CHAR_TO_BYTE (XINT (start
));
6230 end_byte
= CHAR_TO_BYTE (XINT (end
));
6232 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6233 move_gap_both (XINT (start
), start_byte
);
6235 if (NETCONN_P (proc
))
6236 wait_while_connecting (proc
);
6238 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6239 end_byte
- start_byte
, Fcurrent_buffer ());
6244 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6246 doc
: /* Send PROCESS the contents of STRING as input.
6247 PROCESS may be a process, a buffer, the name of a process or buffer, or
6248 nil, indicating the current buffer's process.
6249 If STRING is more than 500 characters long,
6250 it is sent in several bunches. This may happen even for shorter strings.
6251 Output from processes can arrive in between bunches.
6253 If PROCESS is a non-blocking network process that hasn't been fully
6254 set up yet, this function will block until socket setup has completed. */)
6255 (Lisp_Object process
, Lisp_Object string
)
6257 CHECK_STRING (string
);
6258 Lisp_Object proc
= get_process (process
);
6259 send_process (proc
, SSDATA (string
),
6260 SBYTES (string
), string
);
6264 /* Return the foreground process group for the tty/pty that
6265 the process P uses. */
6267 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6272 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6275 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6276 master side. Try the slave side. */
6277 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6281 ioctl (fd
, TIOCGPGRP
, &gid
);
6285 #endif /* defined (TIOCGPGRP ) */
6290 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6291 Sprocess_running_child_p
, 0, 1, 0,
6292 doc
: /* Return non-nil if PROCESS has given the terminal to a
6293 child. If the operating system does not make it possible to find out,
6294 return t. If we can find out, return the numeric ID of the foreground
6296 (Lisp_Object process
)
6298 /* Initialize in case ioctl doesn't exist or gives an error,
6299 in a way that will cause returning t. */
6300 Lisp_Object proc
= get_process (process
);
6301 struct Lisp_Process
*p
= XPROCESS (proc
);
6303 if (!EQ (p
->type
, Qreal
))
6304 error ("Process %s is not a subprocess",
6307 error ("Process %s is not active",
6310 pid_t gid
= emacs_get_tty_pgrp (p
);
6315 return make_number (gid
);
6319 /* Send a signal number SIGNO to PROCESS.
6320 If CURRENT_GROUP is t, that means send to the process group
6321 that currently owns the terminal being used to communicate with PROCESS.
6322 This is used for various commands in shell mode.
6323 If CURRENT_GROUP is lambda, that means send to the process group
6324 that currently owns the terminal, but only if it is NOT the shell itself.
6326 If NOMSG is false, insert signal-announcements into process's buffers
6329 If we can, we try to signal PROCESS by sending control characters
6330 down the pty. This allows us to signal inferiors who have changed
6331 their uid, for which kill would return an EPERM error. */
6334 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6338 struct Lisp_Process
*p
;
6342 proc
= get_process (process
);
6343 p
= XPROCESS (proc
);
6345 if (!EQ (p
->type
, Qreal
))
6346 error ("Process %s is not a subprocess",
6349 error ("Process %s is not active",
6353 current_group
= Qnil
;
6355 /* If we are using pgrps, get a pgrp number and make it negative. */
6356 if (NILP (current_group
))
6357 /* Send the signal to the shell's process group. */
6361 #ifdef SIGNALS_VIA_CHARACTERS
6362 /* If possible, send signals to the entire pgrp
6363 by sending an input character to it. */
6366 cc_t
*sig_char
= NULL
;
6368 tcgetattr (p
->infd
, &t
);
6373 sig_char
= &t
.c_cc
[VINTR
];
6377 sig_char
= &t
.c_cc
[VQUIT
];
6382 sig_char
= &t
.c_cc
[VSWTCH
];
6384 sig_char
= &t
.c_cc
[VSUSP
];
6389 if (sig_char
&& *sig_char
!= CDISABLE
)
6391 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6394 /* If we can't send the signal with a character,
6395 fall through and send it another way. */
6397 /* The code above may fall through if it can't
6398 handle the signal. */
6399 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6402 /* Get the current pgrp using the tty itself, if we have that.
6403 Otherwise, use the pty to get the pgrp.
6404 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6405 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6406 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6407 His patch indicates that if TIOCGPGRP returns an error, then
6408 we should just assume that p->pid is also the process group id. */
6410 gid
= emacs_get_tty_pgrp (p
);
6413 /* If we can't get the information, assume
6414 the shell owns the tty. */
6417 /* It is not clear whether anything really can set GID to -1.
6418 Perhaps on some system one of those ioctls can or could do so.
6419 Or perhaps this is vestigial. */
6422 #else /* ! defined (TIOCGPGRP) */
6423 /* Can't select pgrps on this system, so we know that
6424 the child itself heads the pgrp. */
6426 #endif /* ! defined (TIOCGPGRP) */
6428 /* If current_group is lambda, and the shell owns the terminal,
6429 don't send any signal. */
6430 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6435 if (signo
== SIGCONT
)
6437 p
->raw_status_new
= 0;
6438 pset_status (p
, Qrun
);
6439 p
->tick
= ++process_tick
;
6442 status_notify (NULL
, NULL
);
6443 redisplay_preserve_echo_area (13);
6449 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6450 We don't know whether the bug is fixed in later HP-UX versions. */
6451 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6455 /* If we don't have process groups, send the signal to the immediate
6456 subprocess. That isn't really right, but it's better than any
6457 obvious alternative. */
6458 pid_t pid
= no_pgrp
? gid
: - gid
;
6460 /* Do not kill an already-reaped process, as that could kill an
6461 innocent bystander that happens to have the same process ID. */
6463 block_child_signal (&oldset
);
6466 unblock_child_signal (&oldset
);
6469 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6470 doc
: /* Interrupt process PROCESS.
6471 PROCESS may be a process, a buffer, or the name of a process or buffer.
6472 No arg or nil means current buffer's process.
6473 Second arg CURRENT-GROUP non-nil means send signal to
6474 the current process-group of the process's controlling terminal
6475 rather than to the process's own process group.
6476 If the process is a shell, this means interrupt current subjob
6477 rather than the shell.
6479 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6480 don't send the signal. */)
6481 (Lisp_Object process
, Lisp_Object current_group
)
6483 process_send_signal (process
, SIGINT
, current_group
, 0);
6487 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6488 doc
: /* Kill process PROCESS. May be process or name of one.
6489 See function `interrupt-process' for more details on usage. */)
6490 (Lisp_Object process
, Lisp_Object current_group
)
6492 process_send_signal (process
, SIGKILL
, current_group
, 0);
6496 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6497 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6498 See function `interrupt-process' for more details on usage. */)
6499 (Lisp_Object process
, Lisp_Object current_group
)
6501 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6505 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6506 doc
: /* Stop process PROCESS. May be process or name of one.
6507 See function `interrupt-process' for more details on usage.
6508 If PROCESS is a network or serial process, inhibit handling of incoming
6510 (Lisp_Object process
, Lisp_Object current_group
)
6512 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6513 || PIPECONN_P (process
)))
6515 struct Lisp_Process
*p
;
6517 p
= XPROCESS (process
);
6518 if (NILP (p
->command
)
6521 FD_CLR (p
->infd
, &input_wait_mask
);
6522 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6524 pset_command (p
, Qt
);
6528 error ("No SIGTSTP support");
6530 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6535 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6536 doc
: /* Continue process PROCESS. May be process or name of one.
6537 See function `interrupt-process' for more details on usage.
6538 If PROCESS is a network or serial process, resume handling of incoming
6540 (Lisp_Object process
, Lisp_Object current_group
)
6542 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6543 || PIPECONN_P (process
)))
6545 struct Lisp_Process
*p
;
6547 p
= XPROCESS (process
);
6548 if (EQ (p
->command
, Qt
)
6550 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6552 FD_SET (p
->infd
, &input_wait_mask
);
6553 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6555 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6556 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6557 #else /* not WINDOWSNT */
6558 tcflush (p
->infd
, TCIFLUSH
);
6559 #endif /* not WINDOWSNT */
6561 pset_command (p
, Qnil
);
6565 process_send_signal (process
, SIGCONT
, current_group
, 0);
6567 error ("No SIGCONT support");
6572 /* Return the integer value of the signal whose abbreviation is ABBR,
6573 or a negative number if there is no such signal. */
6575 abbr_to_signal (char const *name
)
6578 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6580 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6583 for (i
= 0; i
< sizeof sigbuf
; i
++)
6585 sigbuf
[i
] = c_toupper (name
[i
]);
6587 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6593 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6594 2, 2, "sProcess (name or number): \nnSignal code: ",
6595 doc
: /* Send PROCESS the signal with code SIGCODE.
6596 PROCESS may also be a number specifying the process id of the
6597 process to signal; in this case, the process need not be a child of
6599 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6600 (Lisp_Object process
, Lisp_Object sigcode
)
6605 if (STRINGP (process
))
6607 Lisp_Object tem
= Fget_process (process
);
6610 Lisp_Object process_number
6611 = string_to_number (SSDATA (process
), 10, 1);
6612 if (NUMBERP (process_number
))
6613 tem
= process_number
;
6617 else if (!NUMBERP (process
))
6618 process
= get_process (process
);
6623 if (NUMBERP (process
))
6624 CONS_TO_INTEGER (process
, pid_t
, pid
);
6627 CHECK_PROCESS (process
);
6628 pid
= XPROCESS (process
)->pid
;
6630 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6633 if (INTEGERP (sigcode
))
6635 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6636 signo
= XINT (sigcode
);
6642 CHECK_SYMBOL (sigcode
);
6643 name
= SSDATA (SYMBOL_NAME (sigcode
));
6645 signo
= abbr_to_signal (name
);
6647 error ("Undefined signal name %s", name
);
6650 return make_number (kill (pid
, signo
));
6653 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6654 doc
: /* Make PROCESS see end-of-file in its input.
6655 EOF comes after any text already sent to it.
6656 PROCESS may be a process, a buffer, the name of a process or buffer, or
6657 nil, indicating the current buffer's process.
6658 If PROCESS is a network connection, or is a process communicating
6659 through a pipe (as opposed to a pty), then you cannot send any more
6660 text to PROCESS after you call this function.
6661 If PROCESS is a serial process, wait until all output written to the
6662 process has been transmitted to the serial port. */)
6663 (Lisp_Object process
)
6666 struct coding_system
*coding
= NULL
;
6669 proc
= get_process (process
);
6671 if (NETCONN_P (proc
))
6672 wait_while_connecting (proc
);
6674 if (DATAGRAM_CONN_P (proc
))
6678 outfd
= XPROCESS (proc
)->outfd
;
6680 coding
= proc_encode_coding_system
[outfd
];
6682 /* Make sure the process is really alive. */
6683 if (XPROCESS (proc
)->raw_status_new
)
6684 update_status (XPROCESS (proc
));
6685 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6686 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6688 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6690 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6691 send_process (proc
, "", 0, Qnil
);
6694 if (XPROCESS (proc
)->pty_flag
)
6695 send_process (proc
, "\004", 1, Qnil
);
6696 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6699 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6700 report_file_error ("Failed tcdrain", Qnil
);
6701 #endif /* not WINDOWSNT */
6702 /* Do nothing on Windows because writes are blocking. */
6706 struct Lisp_Process
*p
= XPROCESS (proc
);
6707 int old_outfd
= p
->outfd
;
6710 #ifdef HAVE_SHUTDOWN
6711 /* If this is a network connection, or socketpair is used
6712 for communication with the subprocess, call shutdown to cause EOF.
6713 (In some old system, shutdown to socketpair doesn't work.
6714 Then we just can't win.) */
6716 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6717 shutdown (old_outfd
, 1);
6719 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6720 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6722 report_file_error ("Opening null device", Qnil
);
6723 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6724 p
->outfd
= new_outfd
;
6726 if (!proc_encode_coding_system
[new_outfd
])
6727 proc_encode_coding_system
[new_outfd
]
6728 = xmalloc (sizeof (struct coding_system
));
6731 *proc_encode_coding_system
[new_outfd
]
6732 = *proc_encode_coding_system
[old_outfd
];
6733 memset (proc_encode_coding_system
[old_outfd
], 0,
6734 sizeof (struct coding_system
));
6737 setup_coding_system (p
->encode_coding_system
,
6738 proc_encode_coding_system
[new_outfd
]);
6743 /* The main Emacs thread records child processes in three places:
6745 - Vprocess_alist, for asynchronous subprocesses, which are child
6746 processes visible to Lisp.
6748 - deleted_pid_list, for child processes invisible to Lisp,
6749 typically because of delete-process. These are recorded so that
6750 the processes can be reaped when they exit, so that the operating
6751 system's process table is not cluttered by zombies.
6753 - the local variable PID in Fcall_process, call_process_cleanup and
6754 call_process_kill, for synchronous subprocesses.
6755 record_unwind_protect is used to make sure this process is not
6756 forgotten: if the user interrupts call-process and the child
6757 process refuses to exit immediately even with two C-g's,
6758 call_process_kill adds PID's contents to deleted_pid_list before
6761 The main Emacs thread invokes waitpid only on child processes that
6762 it creates and that have not been reaped. This avoid races on
6763 platforms such as GTK, where other threads create their own
6764 subprocesses which the main thread should not reap. For example,
6765 if the main thread attempted to reap an already-reaped child, it
6766 might inadvertently reap a GTK-created process that happened to
6767 have the same process ID. */
6769 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6770 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6771 keep track of its own children. GNUstep is similar. */
6773 static void dummy_handler (int sig
) {}
6774 static signal_handler_t
volatile lib_child_handler
;
6776 /* Handle a SIGCHLD signal by looking for known child processes of
6777 Emacs whose status have changed. For each one found, record its
6780 All we do is change the status; we do not run sentinels or print
6781 notifications. That is saved for the next time keyboard input is
6782 done, in order to avoid timing errors.
6784 ** WARNING: this can be called during garbage collection.
6785 Therefore, it must not be fooled by the presence of mark bits in
6788 ** USG WARNING: Although it is not obvious from the documentation
6789 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6790 signal() before executing at least one wait(), otherwise the
6791 handler will be called again, resulting in an infinite loop. The
6792 relevant portion of the documentation reads "SIGCLD signals will be
6793 queued and the signal-catching function will be continually
6794 reentered until the queue is empty". Invoking signal() causes the
6795 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6798 ** Malloc WARNING: This should never call malloc either directly or
6799 indirectly; if it does, that is a bug. */
6802 handle_child_signal (int sig
)
6804 Lisp_Object tail
, proc
;
6806 /* Find the process that signaled us, and record its status. */
6808 /* The process can have been deleted by Fdelete_process, or have
6809 been started asynchronously by Fcall_process. */
6810 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6812 bool all_pids_are_fixnums
6813 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6814 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6815 Lisp_Object head
= XCAR (tail
);
6820 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6823 if (INTEGERP (xpid
))
6824 deleted_pid
= XINT (xpid
);
6826 deleted_pid
= XFLOAT_DATA (xpid
);
6827 if (child_status_changed (deleted_pid
, 0, 0))
6829 if (STRINGP (XCDR (head
)))
6830 unlink (SSDATA (XCDR (head
)));
6831 XSETCAR (tail
, Qnil
);
6836 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6837 FOR_EACH_PROCESS (tail
, proc
)
6839 struct Lisp_Process
*p
= XPROCESS (proc
);
6843 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6845 /* Change the status of the process that was found. */
6846 p
->tick
= ++process_tick
;
6847 p
->raw_status
= status
;
6848 p
->raw_status_new
= 1;
6850 /* If process has terminated, stop waiting for its output. */
6851 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6853 bool clear_desc_flag
= 0;
6856 clear_desc_flag
= 1;
6858 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6859 if (clear_desc_flag
)
6861 FD_CLR (p
->infd
, &input_wait_mask
);
6862 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6868 lib_child_handler (sig
);
6869 #ifdef NS_IMPL_GNUSTEP
6870 /* NSTask in GNUstep sets its child handler each time it is called.
6871 So we must re-set ours. */
6872 catch_child_signal ();
6877 deliver_child_signal (int sig
)
6879 deliver_process_signal (sig
, handle_child_signal
);
6884 exec_sentinel_error_handler (Lisp_Object error_val
)
6886 cmd_error_internal (error_val
, "error in process sentinel: ");
6888 update_echo_area ();
6889 Fsleep_for (make_number (2), Qnil
);
6894 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6896 Lisp_Object sentinel
, odeactivate
;
6897 struct Lisp_Process
*p
= XPROCESS (proc
);
6898 ptrdiff_t count
= SPECPDL_INDEX ();
6899 bool outer_running_asynch_code
= running_asynch_code
;
6900 int waiting
= waiting_for_user_input_p
;
6902 if (inhibit_sentinels
)
6905 odeactivate
= Vdeactivate_mark
;
6907 Lisp_Object obuffer
, okeymap
;
6908 XSETBUFFER (obuffer
, current_buffer
);
6909 okeymap
= BVAR (current_buffer
, keymap
);
6912 /* There's no good reason to let sentinels change the current
6913 buffer, and many callers of accept-process-output, sit-for, and
6914 friends don't expect current-buffer to be changed from under them. */
6915 record_unwind_current_buffer ();
6917 sentinel
= p
->sentinel
;
6919 /* Inhibit quit so that random quits don't screw up a running filter. */
6920 specbind (Qinhibit_quit
, Qt
);
6921 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6923 /* In case we get recursively called,
6924 and we already saved the match data nonrecursively,
6925 save the same match data in safely recursive fashion. */
6926 if (outer_running_asynch_code
)
6929 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6930 restore_search_regs ();
6931 record_unwind_save_match_data ();
6932 Fset_match_data (tem
, Qt
);
6935 /* For speed, if a search happens within this code,
6936 save the match data in a special nonrecursive fashion. */
6937 running_asynch_code
= 1;
6939 internal_condition_case_1 (read_process_output_call
,
6940 list3 (sentinel
, proc
, reason
),
6941 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6942 exec_sentinel_error_handler
);
6944 /* If we saved the match data nonrecursively, restore it now. */
6945 restore_search_regs ();
6946 running_asynch_code
= outer_running_asynch_code
;
6948 Vdeactivate_mark
= odeactivate
;
6950 /* Restore waiting_for_user_input_p as it was
6951 when we were called, in case the filter clobbered it. */
6952 waiting_for_user_input_p
= waiting
;
6955 if (! EQ (Fcurrent_buffer (), obuffer
)
6956 || ! EQ (current_buffer
->keymap
, okeymap
))
6958 /* But do it only if the caller is actually going to read events.
6959 Otherwise there's no need to make him wake up, and it could
6960 cause trouble (for example it would make sit_for return). */
6961 if (waiting_for_user_input_p
== -1)
6962 record_asynch_buffer_change ();
6964 unbind_to (count
, Qnil
);
6967 /* Report all recent events of a change in process status
6968 (either run the sentinel or output a message).
6969 This is usually done while Emacs is waiting for keyboard input
6970 but can be done at other times.
6972 Return positive if any input was received from WAIT_PROC (or from
6973 any process if WAIT_PROC is null), zero if input was attempted but
6974 none received, and negative if we didn't even try. */
6977 status_notify (struct Lisp_Process
*deleting_process
,
6978 struct Lisp_Process
*wait_proc
)
6981 Lisp_Object tail
, msg
;
6982 int got_some_output
= -1;
6987 /* Set this now, so that if new processes are created by sentinels
6988 that we run, we get called again to handle their status changes. */
6989 update_tick
= process_tick
;
6991 FOR_EACH_PROCESS (tail
, proc
)
6994 register struct Lisp_Process
*p
= XPROCESS (proc
);
6996 if (p
->tick
!= p
->update_tick
)
6998 p
->update_tick
= p
->tick
;
7000 /* If process is still active, read any output that remains. */
7001 while (! EQ (p
->filter
, Qt
)
7002 && ! EQ (p
->status
, Qconnect
)
7003 && ! EQ (p
->status
, Qlisten
)
7004 /* Network or serial process not stopped: */
7005 && ! EQ (p
->command
, Qt
)
7007 && p
!= deleting_process
)
7009 int nread
= read_process_output (proc
, p
->infd
);
7010 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7011 && got_some_output
< nread
)
7012 got_some_output
= nread
;
7017 /* Get the text to use for the message. */
7018 if (p
->raw_status_new
)
7020 msg
= status_message (p
);
7022 /* If process is terminated, deactivate it or delete it. */
7024 if (CONSP (p
->status
))
7025 symbol
= XCAR (p
->status
);
7027 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7028 || EQ (symbol
, Qclosed
))
7030 if (delete_exited_processes
)
7031 remove_process (proc
);
7033 deactivate_process (proc
);
7036 /* The actions above may have further incremented p->tick.
7037 So set p->update_tick again so that an error in the sentinel will
7038 not cause this code to be run again. */
7039 p
->update_tick
= p
->tick
;
7040 /* Now output the message suitably. */
7041 exec_sentinel (proc
, msg
);
7042 if (BUFFERP (p
->buffer
))
7043 /* In case it uses %s in mode-line-format. */
7044 bset_update_mode_line (XBUFFER (p
->buffer
));
7048 return got_some_output
;
7051 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7052 Sinternal_default_process_sentinel
, 2, 2, 0,
7053 doc
: /* Function used as default sentinel for processes.
7054 This inserts a status message into the process's buffer, if there is one. */)
7055 (Lisp_Object proc
, Lisp_Object msg
)
7057 Lisp_Object buffer
, symbol
;
7058 struct Lisp_Process
*p
;
7059 CHECK_PROCESS (proc
);
7060 p
= XPROCESS (proc
);
7064 symbol
= XCAR (symbol
);
7066 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7069 struct buffer
*old
= current_buffer
;
7070 ptrdiff_t opoint
, opoint_byte
;
7071 ptrdiff_t before
, before_byte
;
7073 /* Avoid error if buffer is deleted
7074 (probably that's why the process is dead, too). */
7075 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7077 Fset_buffer (buffer
);
7079 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7080 msg
= (code_convert_string_norecord
7081 (msg
, Vlocale_coding_system
, 1));
7084 opoint_byte
= PT_BYTE
;
7085 /* Insert new output into buffer
7086 at the current end-of-output marker,
7087 thus preserving logical ordering of input and output. */
7088 if (XMARKER (p
->mark
)->buffer
)
7089 Fgoto_char (p
->mark
);
7091 SET_PT_BOTH (ZV
, ZV_BYTE
);
7094 before_byte
= PT_BYTE
;
7096 tem
= BVAR (current_buffer
, read_only
);
7097 bset_read_only (current_buffer
, Qnil
);
7098 insert_string ("\nProcess ");
7099 { /* FIXME: temporary kludge. */
7100 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7101 insert_string (" ");
7103 bset_read_only (current_buffer
, tem
);
7104 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7106 if (opoint
>= before
)
7107 SET_PT_BOTH (opoint
+ (PT
- before
),
7108 opoint_byte
+ (PT_BYTE
- before_byte
));
7110 SET_PT_BOTH (opoint
, opoint_byte
);
7112 set_buffer_internal (old
);
7118 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7119 Sset_process_coding_system
, 1, 3, 0,
7120 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7121 DECODING will be used to decode subprocess output and ENCODING to
7122 encode subprocess input. */)
7123 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7125 CHECK_PROCESS (process
);
7127 struct Lisp_Process
*p
= XPROCESS (process
);
7129 Fcheck_coding_system (decoding
);
7130 Fcheck_coding_system (encoding
);
7131 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7132 pset_decode_coding_system (p
, decoding
);
7133 pset_encode_coding_system (p
, encoding
);
7135 /* If the sockets haven't been set up yet, the final setup part of
7136 this will be called asynchronously. */
7137 if (p
->infd
< 0 || p
->outfd
< 0)
7140 setup_process_coding_systems (process
);
7145 DEFUN ("process-coding-system",
7146 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7147 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7148 (register Lisp_Object process
)
7150 CHECK_PROCESS (process
);
7151 return Fcons (XPROCESS (process
)->decode_coding_system
,
7152 XPROCESS (process
)->encode_coding_system
);
7155 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7156 Sset_process_filter_multibyte
, 2, 2, 0,
7157 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7158 If FLAG is non-nil, the filter is given multibyte strings.
7159 If FLAG is nil, the filter is given unibyte strings. In this case,
7160 all character code conversion except for end-of-line conversion is
7162 (Lisp_Object process
, Lisp_Object flag
)
7164 CHECK_PROCESS (process
);
7166 struct Lisp_Process
*p
= XPROCESS (process
);
7168 pset_decode_coding_system
7169 (p
, raw_text_coding_system (p
->decode_coding_system
));
7171 /* If the sockets haven't been set up yet, the final setup part of
7172 this will be called asynchronously. */
7173 if (p
->infd
< 0 || p
->outfd
< 0)
7176 setup_process_coding_systems (process
);
7181 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7182 Sprocess_filter_multibyte_p
, 1, 1, 0,
7183 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7184 (Lisp_Object process
)
7186 CHECK_PROCESS (process
);
7187 struct Lisp_Process
*p
= XPROCESS (process
);
7190 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7191 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7200 add_gpm_wait_descriptor (int desc
)
7202 add_keyboard_wait_descriptor (desc
);
7206 delete_gpm_wait_descriptor (int desc
)
7208 delete_keyboard_wait_descriptor (desc
);
7213 # ifdef USABLE_SIGIO
7215 /* Return true if *MASK has a bit set
7216 that corresponds to one of the keyboard input descriptors. */
7219 keyboard_bit_set (fd_set
*mask
)
7223 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7224 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7225 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7232 #else /* not subprocesses */
7234 /* Defined in msdos.c. */
7235 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7236 struct timespec
*, void *);
7238 /* Implementation of wait_reading_process_output, assuming that there
7239 are no subprocesses. Used only by the MS-DOS build.
7241 Wait for timeout to elapse and/or keyboard input to be available.
7245 If negative, gobble data immediately available but don't wait for any.
7248 an additional duration to wait, measured in nanoseconds
7249 If TIME_LIMIT is zero, then:
7250 If NSECS == 0, there is no limit.
7251 If NSECS > 0, the timeout consists of NSECS only.
7252 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7255 0 to ignore keyboard input, or
7256 1 to return when input is available, or
7257 -1 means caller will actually read the input, so don't throw to
7260 see full version for other parameters. We know that wait_proc will
7261 always be NULL, since `subprocesses' isn't defined.
7263 DO_DISPLAY means redisplay should be done to show subprocess
7264 output that arrives.
7266 Return -1 signifying we got no output and did not try. */
7269 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7271 Lisp_Object wait_for_cell
,
7272 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7275 struct timespec end_time
, timeout
;
7276 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7278 if (TYPE_MAXIMUM (time_t) < time_limit
)
7279 time_limit
= TYPE_MAXIMUM (time_t);
7281 if (time_limit
< 0 || nsecs
< 0)
7283 else if (time_limit
> 0 || nsecs
> 0)
7286 end_time
= timespec_add (current_timespec (),
7287 make_timespec (time_limit
, nsecs
));
7292 /* Turn off periodic alarms (in case they are in use)
7293 and then turn off any other atimers,
7294 because the select emulator uses alarms. */
7296 turn_on_atimers (0);
7300 bool timeout_reduced_for_timers
= false;
7301 fd_set waitchannels
;
7304 /* If calling from keyboard input, do not quit
7305 since we want to return C-g as an input character.
7306 Otherwise, do pending quit if requested. */
7310 /* Exit now if the cell we're waiting for became non-nil. */
7311 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7314 /* Compute time from now till when time limit is up. */
7315 /* Exit if already run out. */
7316 if (wait
== TIMEOUT
)
7318 struct timespec now
= current_timespec ();
7319 if (timespec_cmp (end_time
, now
) <= 0)
7321 timeout
= timespec_sub (end_time
, now
);
7324 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7326 /* If our caller will not immediately handle keyboard events,
7327 run timer events directly.
7328 (Callers that will immediately read keyboard events
7329 call timer_delay on their own.) */
7330 if (NILP (wait_for_cell
))
7332 struct timespec timer_delay
;
7336 unsigned old_timers_run
= timers_run
;
7337 timer_delay
= timer_check ();
7338 if (timers_run
!= old_timers_run
&& do_display
)
7339 /* We must retry, since a timer may have requeued itself
7340 and that could alter the time delay. */
7341 redisplay_preserve_echo_area (14);
7345 while (!detect_input_pending ());
7347 /* If there is unread keyboard input, also return. */
7349 && requeued_events_pending_p ())
7352 if (timespec_valid_p (timer_delay
))
7354 if (timespec_cmp (timer_delay
, timeout
) < 0)
7356 timeout
= timer_delay
;
7357 timeout_reduced_for_timers
= true;
7362 /* Cause C-g and alarm signals to take immediate action,
7363 and cause input available signals to zero out timeout. */
7365 set_waiting_for_input (&timeout
);
7367 /* If a frame has been newly mapped and needs updating,
7368 reprocess its display stuff. */
7369 if (frame_garbaged
&& do_display
)
7371 clear_waiting_for_input ();
7372 redisplay_preserve_echo_area (15);
7374 set_waiting_for_input (&timeout
);
7377 /* Wait till there is something to do. */
7378 FD_ZERO (&waitchannels
);
7379 if (read_kbd
&& detect_input_pending ())
7383 if (read_kbd
|| !NILP (wait_for_cell
))
7384 FD_SET (0, &waitchannels
);
7385 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7390 /* Make C-g and alarm signals set flags again. */
7391 clear_waiting_for_input ();
7393 /* If we woke up due to SIGWINCH, actually change size now. */
7394 do_pending_window_change (0);
7396 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7397 /* We waited the full specified time, so return now. */
7402 /* If the system call was interrupted, then go around the
7404 if (xerrno
== EINTR
)
7405 FD_ZERO (&waitchannels
);
7407 report_file_errno ("Failed select", Qnil
, xerrno
);
7410 /* Check for keyboard input. */
7413 && detect_input_pending_run_timers (do_display
))
7415 swallow_events (do_display
);
7416 if (detect_input_pending_run_timers (do_display
))
7420 /* If there is unread keyboard input, also return. */
7422 && requeued_events_pending_p ())
7425 /* If wait_for_cell. check for keyboard input
7426 but don't run any timers.
7427 ??? (It seems wrong to me to check for keyboard
7428 input at all when wait_for_cell, but the code
7429 has been this way since July 1994.
7430 Try changing this after version 19.31.) */
7431 if (! NILP (wait_for_cell
)
7432 && detect_input_pending ())
7434 swallow_events (do_display
);
7435 if (detect_input_pending ())
7439 /* Exit now if the cell we're waiting for became non-nil. */
7440 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7449 #endif /* not subprocesses */
7451 /* The following functions are needed even if async subprocesses are
7452 not supported. Some of them are no-op stubs in that case. */
7456 /* Add FD, which is a descriptor returned by timerfd_create,
7457 to the set of non-keyboard input descriptors. */
7460 add_timer_wait_descriptor (int fd
)
7462 FD_SET (fd
, &input_wait_mask
);
7463 FD_SET (fd
, &non_keyboard_wait_mask
);
7464 FD_SET (fd
, &non_process_wait_mask
);
7465 fd_callback_info
[fd
].func
= timerfd_callback
;
7466 fd_callback_info
[fd
].data
= NULL
;
7467 fd_callback_info
[fd
].condition
|= FOR_READ
;
7468 if (fd
> max_input_desc
)
7469 max_input_desc
= fd
;
7472 #endif /* HAVE_TIMERFD */
7474 /* If program file NAME starts with /: for quoting a magic
7475 name, remove that, preserving the multibyteness of NAME. */
7478 remove_slash_colon (Lisp_Object name
)
7481 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7482 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7483 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7487 /* Add DESC to the set of keyboard input descriptors. */
7490 add_keyboard_wait_descriptor (int desc
)
7492 #ifdef subprocesses /* Actually means "not MSDOS". */
7493 FD_SET (desc
, &input_wait_mask
);
7494 FD_SET (desc
, &non_process_wait_mask
);
7495 if (desc
> max_input_desc
)
7496 max_input_desc
= desc
;
7500 /* From now on, do not expect DESC to give keyboard input. */
7503 delete_keyboard_wait_descriptor (int desc
)
7506 FD_CLR (desc
, &input_wait_mask
);
7507 FD_CLR (desc
, &non_process_wait_mask
);
7508 delete_input_desc (desc
);
7512 /* Setup coding systems of PROCESS. */
7515 setup_process_coding_systems (Lisp_Object process
)
7518 struct Lisp_Process
*p
= XPROCESS (process
);
7520 int outch
= p
->outfd
;
7521 Lisp_Object coding_system
;
7523 if (inch
< 0 || outch
< 0)
7526 if (!proc_decode_coding_system
[inch
])
7527 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7528 coding_system
= p
->decode_coding_system
;
7529 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7530 && BUFFERP (p
->buffer
))
7532 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7533 coding_system
= raw_text_coding_system (coding_system
);
7535 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7537 if (!proc_encode_coding_system
[outch
])
7538 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7539 setup_coding_system (p
->encode_coding_system
,
7540 proc_encode_coding_system
[outch
]);
7544 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7545 doc
: /* Return the (or a) live process associated with BUFFER.
7546 BUFFER may be a buffer or the name of one.
7547 Return nil if all processes associated with BUFFER have been
7548 deleted or killed. */)
7549 (register Lisp_Object buffer
)
7552 register Lisp_Object buf
, tail
, proc
;
7554 if (NILP (buffer
)) return Qnil
;
7555 buf
= Fget_buffer (buffer
);
7556 if (NILP (buf
)) return Qnil
;
7558 FOR_EACH_PROCESS (tail
, proc
)
7559 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7561 #endif /* subprocesses */
7565 DEFUN ("process-inherit-coding-system-flag",
7566 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7568 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7569 If this flag is t, `buffer-file-coding-system' of the buffer
7570 associated with PROCESS will inherit the coding system used to decode
7571 the process output. */)
7572 (register Lisp_Object process
)
7575 CHECK_PROCESS (process
);
7576 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7578 /* Ignore the argument and return the value of
7579 inherit-process-coding-system. */
7580 return inherit_process_coding_system
? Qt
: Qnil
;
7584 /* Kill all processes associated with `buffer'.
7585 If `buffer' is nil, kill all processes. */
7588 kill_buffer_processes (Lisp_Object buffer
)
7591 Lisp_Object tail
, proc
;
7593 FOR_EACH_PROCESS (tail
, proc
)
7594 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7596 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7597 Fdelete_process (proc
);
7598 else if (XPROCESS (proc
)->infd
>= 0)
7599 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7601 #else /* subprocesses */
7602 /* Since we have no subprocesses, this does nothing. */
7603 #endif /* subprocesses */
7606 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7607 Swaiting_for_user_input_p
, 0, 0, 0,
7608 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7609 This is intended for use by asynchronous process output filters and sentinels. */)
7613 return (waiting_for_user_input_p
? Qt
: Qnil
);
7619 /* Stop reading input from keyboard sources. */
7622 hold_keyboard_input (void)
7627 /* Resume reading input from keyboard sources. */
7630 unhold_keyboard_input (void)
7635 /* Return true if keyboard input is on hold, zero otherwise. */
7638 kbd_on_hold_p (void)
7640 return kbd_is_on_hold
;
7644 /* Enumeration of and access to system processes a-la ps(1). */
7646 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7648 doc
: /* Return a list of numerical process IDs of all running processes.
7649 If this functionality is unsupported, return nil.
7651 See `process-attributes' for getting attributes of a process given its ID. */)
7654 return list_system_processes ();
7657 DEFUN ("process-attributes", Fprocess_attributes
,
7658 Sprocess_attributes
, 1, 1, 0,
7659 doc
: /* Return attributes of the process given by its PID, a number.
7661 Value is an alist where each element is a cons cell of the form
7665 If this functionality is unsupported, the value is nil.
7667 See `list-system-processes' for getting a list of all process IDs.
7669 The KEYs of the attributes that this function may return are listed
7670 below, together with the type of the associated VALUE (in parentheses).
7671 Not all platforms support all of these attributes; unsupported
7672 attributes will not appear in the returned alist.
7673 Unless explicitly indicated otherwise, numbers can have either
7674 integer or floating point values.
7676 euid -- Effective user User ID of the process (number)
7677 user -- User name corresponding to euid (string)
7678 egid -- Effective user Group ID of the process (number)
7679 group -- Group name corresponding to egid (string)
7680 comm -- Command name (executable name only) (string)
7681 state -- Process state code, such as "S", "R", or "T" (string)
7682 ppid -- Parent process ID (number)
7683 pgrp -- Process group ID (number)
7684 sess -- Session ID, i.e. process ID of session leader (number)
7685 ttname -- Controlling tty name (string)
7686 tpgid -- ID of foreground process group on the process's tty (number)
7687 minflt -- number of minor page faults (number)
7688 majflt -- number of major page faults (number)
7689 cminflt -- cumulative number of minor page faults (number)
7690 cmajflt -- cumulative number of major page faults (number)
7691 utime -- user time used by the process, in (current-time) format,
7692 which is a list of integers (HIGH LOW USEC PSEC)
7693 stime -- system time used by the process (current-time)
7694 time -- sum of utime and stime (current-time)
7695 cutime -- user time used by the process and its children (current-time)
7696 cstime -- system time used by the process and its children (current-time)
7697 ctime -- sum of cutime and cstime (current-time)
7698 pri -- priority of the process (number)
7699 nice -- nice value of the process (number)
7700 thcount -- process thread count (number)
7701 start -- time the process started (current-time)
7702 vsize -- virtual memory size of the process in KB's (number)
7703 rss -- resident set size of the process in KB's (number)
7704 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7705 pcpu -- percents of CPU time used by the process (floating-point number)
7706 pmem -- percents of total physical memory used by process's resident set
7707 (floating-point number)
7708 args -- command line which invoked the process (string). */)
7711 return system_process_attributes (pid
);
7715 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7716 Invoke this after init_process_emacs, and after glib and/or GNUstep
7717 futz with the SIGCHLD handler, but before Emacs forks any children.
7718 This function's caller should block SIGCHLD. */
7721 catch_child_signal (void)
7723 struct sigaction action
, old_action
;
7725 emacs_sigaction_init (&action
, deliver_child_signal
);
7726 block_child_signal (&oldset
);
7727 sigaction (SIGCHLD
, &action
, &old_action
);
7728 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7729 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7731 if (old_action
.sa_handler
!= deliver_child_signal
)
7733 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7735 : old_action
.sa_handler
);
7736 unblock_child_signal (&oldset
);
7738 #endif /* subprocesses */
7741 /* This is not called "init_process" because that is the name of a
7742 Mach system call, so it would cause problems on Darwin systems. */
7744 init_process_emacs (int sockfd
)
7749 inhibit_sentinels
= 0;
7752 if (! noninteractive
|| initialized
)
7755 #if defined HAVE_GLIB && !defined WINDOWSNT
7756 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7757 this should always fail, but is enough to initialize glib's
7758 private SIGCHLD handler, allowing catch_child_signal to copy
7759 it into lib_child_handler. */
7760 g_source_unref (g_child_watch_source_new (getpid ()));
7762 catch_child_signal ();
7765 FD_ZERO (&input_wait_mask
);
7766 FD_ZERO (&non_keyboard_wait_mask
);
7767 FD_ZERO (&non_process_wait_mask
);
7768 FD_ZERO (&write_mask
);
7769 max_process_desc
= max_input_desc
= -1;
7770 external_sock_fd
= sockfd
;
7771 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7773 FD_ZERO (&connect_wait_mask
);
7774 num_pending_connects
= 0;
7776 process_output_delay_count
= 0;
7777 process_output_skip
= 0;
7779 /* Don't do this, it caused infinite select loops. The display
7780 method should call add_keyboard_wait_descriptor on stdin if it
7783 FD_SET (0, &input_wait_mask
);
7786 Vprocess_alist
= Qnil
;
7787 deleted_pid_list
= Qnil
;
7788 for (i
= 0; i
< FD_SETSIZE
; i
++)
7790 chan_process
[i
] = Qnil
;
7791 proc_buffered_char
[i
] = -1;
7793 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7794 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7795 #ifdef DATAGRAM_SOCKETS
7796 memset (datagram_address
, 0, sizeof datagram_address
);
7799 #if defined (DARWIN_OS)
7800 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7801 processes. As such, we only change the default value. */
7804 char const *release
= (STRINGP (Voperating_system_release
)
7805 ? SSDATA (Voperating_system_release
)
7807 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7808 Vprocess_connection_type
= Qnil
;
7812 #endif /* subprocesses */
7817 syms_of_process (void)
7821 DEFSYM (Qprocessp
, "processp");
7822 DEFSYM (Qrun
, "run");
7823 DEFSYM (Qstop
, "stop");
7824 DEFSYM (Qsignal
, "signal");
7826 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7829 DEFSYM (Qopen
, "open");
7830 DEFSYM (Qclosed
, "closed");
7831 DEFSYM (Qconnect
, "connect");
7832 DEFSYM (Qfailed
, "failed");
7833 DEFSYM (Qlisten
, "listen");
7834 DEFSYM (Qlocal
, "local");
7835 DEFSYM (Qipv4
, "ipv4");
7837 DEFSYM (Qipv6
, "ipv6");
7839 DEFSYM (Qdatagram
, "datagram");
7840 DEFSYM (Qseqpacket
, "seqpacket");
7842 DEFSYM (QCport
, ":port");
7843 DEFSYM (QCspeed
, ":speed");
7844 DEFSYM (QCprocess
, ":process");
7846 DEFSYM (QCbytesize
, ":bytesize");
7847 DEFSYM (QCstopbits
, ":stopbits");
7848 DEFSYM (QCparity
, ":parity");
7849 DEFSYM (Qodd
, "odd");
7850 DEFSYM (Qeven
, "even");
7851 DEFSYM (QCflowcontrol
, ":flowcontrol");
7854 DEFSYM (QCsummary
, ":summary");
7856 DEFSYM (Qreal
, "real");
7857 DEFSYM (Qnetwork
, "network");
7858 DEFSYM (Qserial
, "serial");
7859 DEFSYM (Qpipe
, "pipe");
7860 DEFSYM (QCbuffer
, ":buffer");
7861 DEFSYM (QChost
, ":host");
7862 DEFSYM (QCservice
, ":service");
7863 DEFSYM (QClocal
, ":local");
7864 DEFSYM (QCremote
, ":remote");
7865 DEFSYM (QCcoding
, ":coding");
7866 DEFSYM (QCserver
, ":server");
7867 DEFSYM (QCnowait
, ":nowait");
7868 DEFSYM (QCsentinel
, ":sentinel");
7869 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7870 DEFSYM (QCtls_parameters
, ":tls-parameters");
7871 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7872 DEFSYM (QClog
, ":log");
7873 DEFSYM (QCnoquery
, ":noquery");
7874 DEFSYM (QCstop
, ":stop");
7875 DEFSYM (QCplist
, ":plist");
7876 DEFSYM (QCcommand
, ":command");
7877 DEFSYM (QCconnection_type
, ":connection-type");
7878 DEFSYM (QCstderr
, ":stderr");
7879 DEFSYM (Qpty
, "pty");
7880 DEFSYM (Qpipe
, "pipe");
7882 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7884 staticpro (&Vprocess_alist
);
7885 staticpro (&deleted_pid_list
);
7887 #endif /* subprocesses */
7889 DEFSYM (QCname
, ":name");
7890 DEFSYM (QCtype
, ":type");
7892 DEFSYM (Qeuid
, "euid");
7893 DEFSYM (Qegid
, "egid");
7894 DEFSYM (Quser
, "user");
7895 DEFSYM (Qgroup
, "group");
7896 DEFSYM (Qcomm
, "comm");
7897 DEFSYM (Qstate
, "state");
7898 DEFSYM (Qppid
, "ppid");
7899 DEFSYM (Qpgrp
, "pgrp");
7900 DEFSYM (Qsess
, "sess");
7901 DEFSYM (Qttname
, "ttname");
7902 DEFSYM (Qtpgid
, "tpgid");
7903 DEFSYM (Qminflt
, "minflt");
7904 DEFSYM (Qmajflt
, "majflt");
7905 DEFSYM (Qcminflt
, "cminflt");
7906 DEFSYM (Qcmajflt
, "cmajflt");
7907 DEFSYM (Qutime
, "utime");
7908 DEFSYM (Qstime
, "stime");
7909 DEFSYM (Qtime
, "time");
7910 DEFSYM (Qcutime
, "cutime");
7911 DEFSYM (Qcstime
, "cstime");
7912 DEFSYM (Qctime
, "ctime");
7914 DEFSYM (Qinternal_default_process_sentinel
,
7915 "internal-default-process-sentinel");
7916 DEFSYM (Qinternal_default_process_filter
,
7917 "internal-default-process-filter");
7919 DEFSYM (Qpri
, "pri");
7920 DEFSYM (Qnice
, "nice");
7921 DEFSYM (Qthcount
, "thcount");
7922 DEFSYM (Qstart
, "start");
7923 DEFSYM (Qvsize
, "vsize");
7924 DEFSYM (Qrss
, "rss");
7925 DEFSYM (Qetime
, "etime");
7926 DEFSYM (Qpcpu
, "pcpu");
7927 DEFSYM (Qpmem
, "pmem");
7928 DEFSYM (Qargs
, "args");
7930 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7931 doc
: /* Non-nil means delete processes immediately when they exit.
7932 A value of nil means don't delete them until `list-processes' is run. */);
7934 delete_exited_processes
= 1;
7937 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7938 doc
: /* Control type of device used to communicate with subprocesses.
7939 Values are nil to use a pipe, or t or `pty' to use a pty.
7940 The value has no effect if the system has no ptys or if all ptys are busy:
7941 then a pipe is used in any case.
7942 The value takes effect when `start-process' is called. */);
7943 Vprocess_connection_type
= Qt
;
7945 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7946 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7947 On some systems, when Emacs reads the output from a subprocess, the output data
7948 is read in very small blocks, potentially resulting in very poor performance.
7949 This behavior can be remedied to some extent by setting this variable to a
7950 non-nil value, as it will automatically delay reading from such processes, to
7951 allow them to produce more output before Emacs tries to read it.
7952 If the value is t, the delay is reset after each write to the process; any other
7953 non-nil value means that the delay is not reset on write.
7954 The variable takes effect when `start-process' is called. */);
7955 Vprocess_adaptive_read_buffering
= Qt
;
7957 defsubr (&Sprocessp
);
7958 defsubr (&Sget_process
);
7959 defsubr (&Sdelete_process
);
7960 defsubr (&Sprocess_status
);
7961 defsubr (&Sprocess_exit_status
);
7962 defsubr (&Sprocess_id
);
7963 defsubr (&Sprocess_name
);
7964 defsubr (&Sprocess_tty_name
);
7965 defsubr (&Sprocess_command
);
7966 defsubr (&Sset_process_buffer
);
7967 defsubr (&Sprocess_buffer
);
7968 defsubr (&Sprocess_mark
);
7969 defsubr (&Sset_process_filter
);
7970 defsubr (&Sprocess_filter
);
7971 defsubr (&Sset_process_sentinel
);
7972 defsubr (&Sprocess_sentinel
);
7973 defsubr (&Sset_process_window_size
);
7974 defsubr (&Sset_process_inherit_coding_system_flag
);
7975 defsubr (&Sset_process_query_on_exit_flag
);
7976 defsubr (&Sprocess_query_on_exit_flag
);
7977 defsubr (&Sprocess_contact
);
7978 defsubr (&Sprocess_plist
);
7979 defsubr (&Sset_process_plist
);
7980 defsubr (&Sprocess_list
);
7981 defsubr (&Smake_process
);
7982 defsubr (&Smake_pipe_process
);
7983 defsubr (&Sserial_process_configure
);
7984 defsubr (&Smake_serial_process
);
7985 defsubr (&Sset_network_process_option
);
7986 defsubr (&Smake_network_process
);
7987 defsubr (&Sformat_network_address
);
7988 defsubr (&Snetwork_interface_list
);
7989 defsubr (&Snetwork_interface_info
);
7990 #ifdef DATAGRAM_SOCKETS
7991 defsubr (&Sprocess_datagram_address
);
7992 defsubr (&Sset_process_datagram_address
);
7994 defsubr (&Saccept_process_output
);
7995 defsubr (&Sprocess_send_region
);
7996 defsubr (&Sprocess_send_string
);
7997 defsubr (&Sinterrupt_process
);
7998 defsubr (&Skill_process
);
7999 defsubr (&Squit_process
);
8000 defsubr (&Sstop_process
);
8001 defsubr (&Scontinue_process
);
8002 defsubr (&Sprocess_running_child_p
);
8003 defsubr (&Sprocess_send_eof
);
8004 defsubr (&Ssignal_process
);
8005 defsubr (&Swaiting_for_user_input_p
);
8006 defsubr (&Sprocess_type
);
8007 defsubr (&Sinternal_default_process_sentinel
);
8008 defsubr (&Sinternal_default_process_filter
);
8009 defsubr (&Sset_process_coding_system
);
8010 defsubr (&Sprocess_coding_system
);
8011 defsubr (&Sset_process_filter_multibyte
);
8012 defsubr (&Sprocess_filter_multibyte_p
);
8015 Lisp_Object subfeatures
= Qnil
;
8016 const struct socket_options
*sopt
;
8018 #define ADD_SUBFEATURE(key, val) \
8019 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8021 ADD_SUBFEATURE (QCnowait
, Qt
);
8022 #ifdef DATAGRAM_SOCKETS
8023 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8025 #ifdef HAVE_SEQPACKET
8026 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8028 #ifdef HAVE_LOCAL_SOCKETS
8029 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8031 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8033 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8035 #ifdef HAVE_GETSOCKNAME
8036 ADD_SUBFEATURE (QCservice
, Qt
);
8038 ADD_SUBFEATURE (QCserver
, Qt
);
8040 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8041 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8043 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8046 #endif /* subprocesses */
8048 defsubr (&Sget_buffer_process
);
8049 defsubr (&Sprocess_inherit_coding_system_flag
);
8050 defsubr (&Slist_system_processes
);
8051 defsubr (&Sprocess_attributes
);