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
, int *code
, bool *coredump
)
554 *code
= XFASTINT (XCAR (tem
));
556 *coredump
= !NILP (tem
);
560 /* Return a string describing a process status list. */
563 status_message (struct Lisp_Process
*p
)
565 Lisp_Object status
= p
->status
;
571 decode_status (status
, &symbol
, &code
, &coredump
);
573 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
576 synchronize_system_messages_locale ();
577 signame
= strsignal (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 (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
601 return build_string ("finished\n");
602 AUTO_STRING (prefix
, "exited abnormally with code ");
603 string
= Fnumber_to_string (make_number (code
));
604 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
605 return concat3 (prefix
, string
, suffix
);
607 else if (EQ (symbol
, Qfailed
))
609 AUTO_STRING (prefix
, "failed with code ");
610 string
= Fnumber_to_string (make_number (code
));
611 AUTO_STRING (suffix
, "\n");
612 return concat3 (prefix
, string
, suffix
);
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
++);
2347 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2350 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2352 struct Lisp_Vector
*p
;
2354 if (VECTORP (address
))
2356 p
= XVECTOR (address
);
2357 if (p
->header
.size
== 5)
2360 return sizeof (struct sockaddr_in
);
2363 else if (p
->header
.size
== 9)
2365 *familyp
= AF_INET6
;
2366 return sizeof (struct sockaddr_in6
);
2370 #ifdef HAVE_LOCAL_SOCKETS
2371 else if (STRINGP (address
))
2373 *familyp
= AF_LOCAL
;
2374 return sizeof (struct sockaddr_un
);
2377 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2378 && VECTORP (XCDR (address
)))
2380 struct sockaddr
*sa
;
2381 p
= XVECTOR (XCDR (address
));
2382 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2384 *familyp
= XINT (XCAR (address
));
2385 return p
->header
.size
+ sizeof (sa
->sa_family
);
2390 /* Convert an address object (vector or string) to an internal sockaddr.
2392 The address format has been basically validated by
2393 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2394 it could have come from user data. So if FAMILY is not valid,
2395 we return after zeroing *SA. */
2398 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2400 register struct Lisp_Vector
*p
;
2401 register unsigned char *cp
= NULL
;
2405 memset (sa
, 0, len
);
2407 if (VECTORP (address
))
2409 p
= XVECTOR (address
);
2410 if (family
== AF_INET
)
2412 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2413 len
= sizeof (sin
->sin_addr
) + 1;
2414 hostport
= XINT (p
->contents
[--len
]);
2415 sin
->sin_port
= htons (hostport
);
2416 cp
= (unsigned char *)&sin
->sin_addr
;
2417 sa
->sa_family
= family
;
2420 else if (family
== AF_INET6
)
2422 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2423 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2424 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2425 hostport
= XINT (p
->contents
[--len
]);
2426 sin6
->sin6_port
= htons (hostport
);
2427 for (i
= 0; i
< len
; i
++)
2428 if (INTEGERP (p
->contents
[i
]))
2430 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2433 sa
->sa_family
= family
;
2440 else if (STRINGP (address
))
2442 #ifdef HAVE_LOCAL_SOCKETS
2443 if (family
== AF_LOCAL
)
2445 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2446 cp
= SDATA (address
);
2447 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2448 sockun
->sun_path
[i
] = *cp
++;
2449 sa
->sa_family
= family
;
2456 p
= XVECTOR (XCDR (address
));
2457 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2460 for (i
= 0; i
< len
; i
++)
2461 if (INTEGERP (p
->contents
[i
]))
2462 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2465 #ifdef DATAGRAM_SOCKETS
2466 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2468 doc
: /* Get the current datagram address associated with PROCESS.
2469 If PROCESS is a non-blocking network process that hasn't been fully
2470 set up yet, this function will block until socket setup has completed. */)
2471 (Lisp_Object process
)
2475 CHECK_PROCESS (process
);
2477 if (NETCONN_P (process
))
2478 wait_for_socket_fds (process
, "process-datagram-address");
2480 if (!DATAGRAM_CONN_P (process
))
2483 channel
= XPROCESS (process
)->infd
;
2484 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2485 datagram_address
[channel
].len
);
2488 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2490 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2491 Return nil upon error setting address, ADDRESS otherwise.
2493 If PROCESS is a non-blocking network process that hasn't been fully
2494 set up yet, this function will block until socket setup has completed. */)
2495 (Lisp_Object process
, Lisp_Object address
)
2501 CHECK_PROCESS (process
);
2503 if (NETCONN_P (process
))
2504 wait_for_socket_fds (process
, "set-process-datagram-address");
2506 if (!DATAGRAM_CONN_P (process
))
2509 channel
= XPROCESS (process
)->infd
;
2511 len
= get_lisp_to_sockaddr_size (address
, &family
);
2512 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2514 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2520 static const struct socket_options
{
2521 /* The name of this option. Should be lowercase version of option
2522 name without SO_ prefix. */
2524 /* Option level SOL_... */
2526 /* Option number SO_... */
2528 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2529 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2530 } socket_options
[] =
2532 #ifdef SO_BINDTODEVICE
2533 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2536 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2539 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2542 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2545 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2548 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2551 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2554 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2556 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2559 /* Set option OPT to value VAL on socket S.
2561 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2562 Signals an error if setting a known option fails.
2566 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2569 const struct socket_options
*sopt
;
2574 name
= SSDATA (SYMBOL_NAME (opt
));
2575 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2576 if (strcmp (name
, sopt
->name
) == 0)
2579 switch (sopt
->opttype
)
2584 optval
= NILP (val
) ? 0 : 1;
2585 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2586 &optval
, sizeof (optval
));
2593 if (TYPE_RANGED_INTEGERP (int, val
))
2594 optval
= XINT (val
);
2596 error ("Bad option value for %s", name
);
2597 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2598 &optval
, sizeof (optval
));
2602 #ifdef SO_BINDTODEVICE
2605 char devname
[IFNAMSIZ
+ 1];
2607 /* This is broken, at least in the Linux 2.4 kernel.
2608 To unbind, the arg must be a zero integer, not the empty string.
2609 This should work on all systems. KFS. 2003-09-23. */
2610 memset (devname
, 0, sizeof devname
);
2613 char *arg
= SSDATA (val
);
2614 int len
= min (strlen (arg
), IFNAMSIZ
);
2615 memcpy (devname
, arg
, len
);
2617 else if (!NILP (val
))
2618 error ("Bad option value for %s", name
);
2619 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2628 struct linger linger
;
2631 linger
.l_linger
= 0;
2632 if (TYPE_RANGED_INTEGERP (int, val
))
2633 linger
.l_linger
= XINT (val
);
2635 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2636 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2637 &linger
, sizeof (linger
));
2648 int setsockopt_errno
= errno
;
2649 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2653 return (1 << sopt
->optbit
);
2657 DEFUN ("set-network-process-option",
2658 Fset_network_process_option
, Sset_network_process_option
,
2660 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2661 See `make-network-process' for a list of options and values.
2662 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2663 OPTION is not a supported option, return nil instead; otherwise return t.
2665 If PROCESS is a non-blocking network process that hasn't been fully
2666 set up yet, this function will block until socket setup has completed. */)
2667 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2670 struct Lisp_Process
*p
;
2672 CHECK_PROCESS (process
);
2673 p
= XPROCESS (process
);
2674 if (!NETCONN1_P (p
))
2675 error ("Process is not a network process");
2677 wait_for_socket_fds (process
, "set-network-process-option");
2681 error ("Process is not running");
2683 if (set_socket_option (s
, option
, value
))
2685 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2689 if (NILP (no_error
))
2690 error ("Unknown or unsupported option");
2696 DEFUN ("serial-process-configure",
2697 Fserial_process_configure
,
2698 Sserial_process_configure
,
2700 doc
: /* Configure speed, bytesize, etc. of a serial process.
2702 Arguments are specified as keyword/argument pairs. Attributes that
2703 are not given are re-initialized from the process's current
2704 configuration (available via the function `process-contact') or set to
2705 reasonable default values. The following arguments are defined:
2711 -- Any of these arguments can be given to identify the process that is
2712 to be configured. If none of these arguments is given, the current
2713 buffer's process is used.
2715 :speed SPEED -- SPEED is the speed of the serial port in bits per
2716 second, also called baud rate. Any value can be given for SPEED, but
2717 most serial ports work only at a few defined values between 1200 and
2718 115200, with 9600 being the most common value. If SPEED is nil, the
2719 serial port is not configured any further, i.e., all other arguments
2720 are ignored. This may be useful for special serial ports such as
2721 Bluetooth-to-serial converters which can only be configured through AT
2722 commands. A value of nil for SPEED can be used only when passed
2723 through `make-serial-process' or `serial-term'.
2725 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2726 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2728 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2729 `odd' (use odd parity), or the symbol `even' (use even parity). If
2730 PARITY is not given, no parity is used.
2732 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2733 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2734 is not given or nil, 1 stopbit is used.
2736 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2737 flowcontrol to be used, which is either nil (don't use flowcontrol),
2738 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2739 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2740 flowcontrol is used.
2742 `serial-process-configure' is called by `make-serial-process' for the
2743 initial configuration of the serial port.
2747 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2749 \(serial-process-configure
2750 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2752 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2754 usage: (serial-process-configure &rest ARGS) */)
2755 (ptrdiff_t nargs
, Lisp_Object
*args
)
2757 struct Lisp_Process
*p
;
2758 Lisp_Object contact
= Qnil
;
2759 Lisp_Object proc
= Qnil
;
2761 contact
= Flist (nargs
, args
);
2763 proc
= Fplist_get (contact
, QCprocess
);
2765 proc
= Fplist_get (contact
, QCname
);
2767 proc
= Fplist_get (contact
, QCbuffer
);
2769 proc
= Fplist_get (contact
, QCport
);
2770 proc
= get_process (proc
);
2771 p
= XPROCESS (proc
);
2772 if (!EQ (p
->type
, Qserial
))
2773 error ("Not a serial process");
2775 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2778 serial_configure (p
, contact
);
2782 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2784 doc
: /* Create and return a serial port process.
2786 In Emacs, serial port connections are represented by process objects,
2787 so input and output work as for subprocesses, and `delete-process'
2788 closes a serial port connection. However, a serial process has no
2789 process id, it cannot be signaled, and the status codes are different
2790 from normal processes.
2792 `make-serial-process' creates a process and a buffer, on which you
2793 probably want to use `process-send-string'. Try \\[serial-term] for
2794 an interactive terminal. See below for examples.
2796 Arguments are specified as keyword/argument pairs. The following
2797 arguments are defined:
2799 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2800 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2801 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2802 the backslashes in strings).
2804 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2805 which this function calls.
2807 :name NAME -- NAME is the name of the process. If NAME is not given,
2808 the value of PORT is used.
2810 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2811 with the process. Process output goes at the end of that buffer,
2812 unless you specify an output stream or filter function to handle the
2813 output. If BUFFER is not given, the value of NAME is used.
2815 :coding CODING -- If CODING is a symbol, it specifies the coding
2816 system used for both reading and writing for this process. If CODING
2817 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2818 ENCODING is used for writing.
2820 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2821 the process is running. If BOOL is not given, query before exiting.
2823 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2824 In the stopped state, a serial process does not accept incoming data,
2825 but you can send outgoing data. The stopped state is cleared by
2826 `continue-process' and set by `stop-process'.
2828 :filter FILTER -- Install FILTER as the process filter.
2830 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2832 :plist PLIST -- Install PLIST as the initial plist of the process.
2838 -- This function calls `serial-process-configure' to handle these
2841 The original argument list, possibly modified by later configuration,
2842 is available via the function `process-contact'.
2846 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2848 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2850 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2852 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2854 usage: (make-serial-process &rest ARGS) */)
2855 (ptrdiff_t nargs
, Lisp_Object
*args
)
2858 Lisp_Object proc
, contact
, port
;
2859 struct Lisp_Process
*p
;
2860 Lisp_Object name
, buffer
;
2861 Lisp_Object tem
, val
;
2862 ptrdiff_t specpdl_count
;
2867 contact
= Flist (nargs
, args
);
2869 port
= Fplist_get (contact
, QCport
);
2871 error ("No port specified");
2872 CHECK_STRING (port
);
2874 if (NILP (Fplist_member (contact
, QCspeed
)))
2875 error (":speed not specified");
2876 if (!NILP (Fplist_get (contact
, QCspeed
)))
2877 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2879 name
= Fplist_get (contact
, QCname
);
2882 CHECK_STRING (name
);
2883 proc
= make_process (name
);
2884 specpdl_count
= SPECPDL_INDEX ();
2885 record_unwind_protect (remove_process
, proc
);
2886 p
= XPROCESS (proc
);
2888 fd
= serial_open (port
);
2889 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2892 if (fd
> max_process_desc
)
2893 max_process_desc
= fd
;
2894 chan_process
[fd
] = proc
;
2896 buffer
= Fplist_get (contact
, QCbuffer
);
2899 buffer
= Fget_buffer_create (buffer
);
2900 pset_buffer (p
, buffer
);
2902 pset_childp (p
, contact
);
2903 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2904 pset_type (p
, Qserial
);
2905 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2906 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2908 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2909 p
->kill_without_query
= 1;
2910 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2911 pset_command (p
, Qt
);
2912 eassert (! p
->pty_flag
);
2914 if (!EQ (p
->command
, Qt
))
2916 FD_SET (fd
, &input_wait_mask
);
2917 FD_SET (fd
, &non_keyboard_wait_mask
);
2920 if (BUFFERP (buffer
))
2922 set_marker_both (p
->mark
, buffer
,
2923 BUF_ZV (XBUFFER (buffer
)),
2924 BUF_ZV_BYTE (XBUFFER (buffer
)));
2927 tem
= Fplist_member (contact
, QCcoding
);
2928 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2934 val
= XCAR (XCDR (tem
));
2938 else if (!NILP (Vcoding_system_for_read
))
2939 val
= Vcoding_system_for_read
;
2940 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2941 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2943 pset_decode_coding_system (p
, val
);
2948 val
= XCAR (XCDR (tem
));
2952 else if (!NILP (Vcoding_system_for_write
))
2953 val
= Vcoding_system_for_write
;
2954 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2955 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2957 pset_encode_coding_system (p
, val
);
2959 setup_process_coding_systems (proc
);
2960 pset_decoding_buf (p
, empty_unibyte_string
);
2961 p
->decoding_carryover
= 0;
2962 pset_encoding_buf (p
, empty_unibyte_string
);
2963 p
->inherit_coding_system_flag
2964 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2966 Fserial_process_configure (nargs
, args
);
2968 specpdl_ptr
= specpdl
+ specpdl_count
;
2974 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2975 Lisp_Object service
, Lisp_Object name
)
2978 struct Lisp_Process
*p
= XPROCESS (proc
);
2979 Lisp_Object contact
= p
->childp
;
2980 Lisp_Object coding_systems
= Qt
;
2983 tem
= Fplist_member (contact
, QCcoding
);
2984 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2985 tem
= Qnil
; /* No error message (too late!). */
2987 /* Setup coding systems for communicating with the network stream. */
2988 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2992 val
= XCAR (XCDR (tem
));
2996 else if (!NILP (Vcoding_system_for_read
))
2997 val
= Vcoding_system_for_read
;
2998 else if ((!NILP (p
->buffer
)
2999 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3000 || (NILP (p
->buffer
)
3001 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3002 /* We dare not decode end-of-line format by setting VAL to
3003 Qraw_text, because the existing Emacs Lisp libraries
3004 assume that they receive bare code including a sequence of
3009 if (NILP (host
) || NILP (service
))
3010 coding_systems
= Qnil
;
3012 coding_systems
= CALLN (Ffind_operation_coding_system
,
3013 Qopen_network_stream
, name
, p
->buffer
,
3015 if (CONSP (coding_systems
))
3016 val
= XCAR (coding_systems
);
3017 else if (CONSP (Vdefault_process_coding_system
))
3018 val
= XCAR (Vdefault_process_coding_system
);
3022 pset_decode_coding_system (p
, val
);
3026 val
= XCAR (XCDR (tem
));
3030 else if (!NILP (Vcoding_system_for_write
))
3031 val
= Vcoding_system_for_write
;
3032 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3036 if (EQ (coding_systems
, Qt
))
3038 if (NILP (host
) || NILP (service
))
3039 coding_systems
= Qnil
;
3041 coding_systems
= CALLN (Ffind_operation_coding_system
,
3042 Qopen_network_stream
, name
, p
->buffer
,
3045 if (CONSP (coding_systems
))
3046 val
= XCDR (coding_systems
);
3047 else if (CONSP (Vdefault_process_coding_system
))
3048 val
= XCDR (Vdefault_process_coding_system
);
3052 pset_encode_coding_system (p
, val
);
3054 pset_decoding_buf (p
, empty_unibyte_string
);
3055 p
->decoding_carryover
= 0;
3056 pset_encoding_buf (p
, empty_unibyte_string
);
3058 p
->inherit_coding_system_flag
3059 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3064 finish_after_tls_connection (Lisp_Object proc
)
3066 struct Lisp_Process
*p
= XPROCESS (proc
);
3067 Lisp_Object contact
= p
->childp
;
3068 Lisp_Object result
= Qt
;
3070 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3071 result
= call3 (Qnsm_verify_connection
,
3073 Fplist_get (contact
, QChost
),
3074 Fplist_get (contact
, QCservice
));
3078 pset_status (p
, list2 (Qfailed
,
3079 build_string ("The Network Security Manager stopped the connections")));
3080 deactivate_process (proc
);
3084 /* If we cleared the connection wait mask before we did
3085 the TLS setup, then we have to say that the process
3086 is finally "open" here. */
3087 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3089 pset_status (p
, Qrun
);
3090 /* Execute the sentinel here. If we had relied on
3091 status_notify to do it later, it will read input
3092 from the process before calling the sentinel. */
3093 exec_sentinel (proc
, build_string ("open\n"));
3100 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
,
3101 Lisp_Object use_external_socket_p
)
3103 ptrdiff_t count
= SPECPDL_INDEX ();
3105 int s
= -1, outch
, inch
;
3107 Lisp_Object ip_address
;
3109 struct sockaddr
*sa
= NULL
;
3112 struct Lisp_Process
*p
= XPROCESS (proc
);
3113 Lisp_Object contact
= p
->childp
;
3115 int socket_to_use
= -1;
3117 if (!NILP (use_external_socket_p
))
3119 socket_to_use
= external_sock_fd
;
3121 /* Ensure we don't consume the external socket twice. */
3122 external_sock_fd
= -1;
3125 /* Do this in case we never enter the while-loop below. */
3126 count1
= SPECPDL_INDEX ();
3129 while (!NILP (ip_addresses
))
3131 ip_address
= XCAR (ip_addresses
);
3132 ip_addresses
= XCDR (ip_addresses
);
3138 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3141 sa
= xmalloc (addrlen
);
3142 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3147 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3148 if (p
->is_non_blocking_client
)
3149 socktype
|= SOCK_NONBLOCK
;
3150 s
= socket (family
, socktype
, p
->ai_protocol
);
3158 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3160 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3170 #ifdef DATAGRAM_SOCKETS
3171 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3173 #endif /* DATAGRAM_SOCKETS */
3175 /* Make us close S if quit. */
3176 record_unwind_protect_int (close_file_unwind
, s
);
3178 /* Parse network options in the arg list. We simply ignore anything
3179 which isn't a known option (including other keywords). An error
3180 is signaled if setting a known option fails. */
3182 Lisp_Object params
= contact
, key
, val
;
3184 while (!NILP (params
))
3186 key
= XCAR (params
);
3187 params
= XCDR (params
);
3188 val
= XCAR (params
);
3189 params
= XCDR (params
);
3190 optbits
|= set_socket_option (s
, key
, val
);
3196 /* Configure as a server socket. */
3198 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3199 explicit :reuseaddr key to override this. */
3200 #ifdef HAVE_LOCAL_SOCKETS
3201 if (family
!= AF_LOCAL
)
3203 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3206 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3207 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3210 /* If passed a socket descriptor, it should be already bound. */
3211 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3212 report_file_error ("Cannot bind server socket", Qnil
);
3214 #ifdef HAVE_GETSOCKNAME
3217 struct sockaddr_in sa1
;
3218 socklen_t len1
= sizeof (sa1
);
3219 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3221 Lisp_Object service
;
3222 service
= make_number (ntohs (sa1
.sin_port
));
3223 contact
= Fplist_put (contact
, QCservice
, service
);
3224 /* Save the port number so that we can stash it in
3225 the process object later. */
3226 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3231 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3232 report_file_error ("Cannot listen on server socket", Qnil
);
3240 ret
= connect (s
, sa
, addrlen
);
3243 if (ret
== 0 || xerrno
== EISCONN
)
3245 /* The unwind-protect will be discarded afterwards.
3246 Likewise for immediate_quit. */
3250 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3254 if (xerrno
== EINTR
)
3256 /* Unlike most other syscalls connect() cannot be called
3257 again. (That would return EALREADY.) The proper way to
3258 wait for completion is pselect(). */
3266 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3272 report_file_error ("Failed select", Qnil
);
3276 len
= sizeof xerrno
;
3277 eassert (FD_ISSET (s
, &fdset
));
3278 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3279 report_file_error ("Failed getsockopt", Qnil
);
3281 report_file_errno ("Failed connect", Qnil
, xerrno
);
3284 #endif /* !WINDOWSNT */
3288 /* Discard the unwind protect closing S. */
3289 specpdl_ptr
= specpdl
+ count1
;
3294 if (xerrno
== EINTR
)
3301 #ifdef DATAGRAM_SOCKETS
3302 if (p
->socktype
== SOCK_DGRAM
)
3304 if (datagram_address
[s
].sa
)
3307 datagram_address
[s
].sa
= xmalloc (addrlen
);
3308 datagram_address
[s
].len
= addrlen
;
3312 memset (datagram_address
[s
].sa
, 0, addrlen
);
3313 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3316 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3317 if (rlen
!= 0 && rfamily
== family
3319 conv_lisp_to_sockaddr (rfamily
, remote
,
3320 datagram_address
[s
].sa
, rlen
);
3324 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3328 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3329 conv_sockaddr_to_lisp (sa
, addrlen
));
3330 #ifdef HAVE_GETSOCKNAME
3333 struct sockaddr_in sa1
;
3334 socklen_t len1
= sizeof (sa1
);
3335 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3336 contact
= Fplist_put (contact
, QClocal
,
3337 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3346 /* If non-blocking got this far - and failed - assume non-blocking is
3347 not supported after all. This is probably a wrong assumption, but
3348 the normal blocking calls to open-network-stream handles this error
3350 if (p
->is_non_blocking_client
)
3353 report_file_errno ((p
->is_server
3354 ? "make server process failed"
3355 : "make client process failed"),
3362 chan_process
[inch
] = proc
;
3364 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3366 p
= XPROCESS (proc
);
3367 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3371 /* Discard the unwind protect for closing S, if any. */
3372 specpdl_ptr
= specpdl
+ count1
;
3374 /* Unwind bind_polling_period and request_sigio. */
3375 unbind_to (count
, Qnil
);
3377 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3378 pset_status (p
, Qlisten
);
3380 /* Make the process marker point into the process buffer (if any). */
3381 if (BUFFERP (p
->buffer
))
3382 set_marker_both (p
->mark
, p
->buffer
,
3383 BUF_ZV (XBUFFER (p
->buffer
)),
3384 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3386 if (p
->is_non_blocking_client
)
3388 /* We may get here if connect did succeed immediately. However,
3389 in that case, we still need to signal this like a non-blocking
3391 pset_status (p
, Qconnect
);
3392 if (!FD_ISSET (inch
, &connect_wait_mask
))
3394 FD_SET (inch
, &connect_wait_mask
);
3395 FD_SET (inch
, &write_mask
);
3396 num_pending_connects
++;
3400 /* A server may have a client filter setting of Qt, but it must
3401 still listen for incoming connects unless it is stopped. */
3402 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3403 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3405 FD_SET (inch
, &input_wait_mask
);
3406 FD_SET (inch
, &non_keyboard_wait_mask
);
3409 if (inch
> max_process_desc
)
3410 max_process_desc
= inch
;
3412 /* Set up the masks based on the process filter. */
3413 set_process_filter_masks (p
);
3415 setup_process_coding_systems (proc
);
3418 /* Continue the asynchronous connection. */
3419 if (!NILP (p
->gnutls_boot_parameters
))
3421 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3423 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3424 p
->gnutls_boot_parameters
= Qnil
;
3426 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3427 /* Run sentinels, etc. */
3428 finish_after_tls_connection (proc
);
3429 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3431 deactivate_process (proc
);
3433 pset_status (p
, list2 (Qfailed
,
3434 build_string ("TLS negotiation failed")));
3436 pset_status (p
, list2 (Qfailed
, boot
));
3443 /* Create a network stream/datagram client/server process. Treated
3444 exactly like a normal process when reading and writing. Primary
3445 differences are in status display and process deletion. A network
3446 connection has no PID; you cannot signal it. All you can do is
3447 stop/continue it and deactivate/close it via delete-process. */
3449 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3451 doc
: /* Create and return a network server or client process.
3453 In Emacs, network connections are represented by process objects, so
3454 input and output work as for subprocesses and `delete-process' closes
3455 a network connection. However, a network process has no process id,
3456 it cannot be signaled, and the status codes are different from normal
3459 Arguments are specified as keyword/argument pairs. The following
3460 arguments are defined:
3462 :name NAME -- NAME is name for process. It is modified if necessary
3465 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3466 with the process. Process output goes at end of that buffer, unless
3467 you specify an output stream or filter function to handle the output.
3468 BUFFER may be also nil, meaning that this process is not associated
3471 :host HOST -- HOST is name of the host to connect to, or its IP
3472 address. The symbol `local' specifies the local host. If specified
3473 for a server process, it must be a valid name or address for the local
3474 host, and only clients connecting to that address will be accepted.
3476 :service SERVICE -- SERVICE is name of the service desired, or an
3477 integer specifying a port number to connect to. If SERVICE is t,
3478 a random port number is selected for the server. A port number can
3479 be specified as an integer string, e.g., "80", as well as an integer.
3481 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3482 stream type connection, `datagram' creates a datagram type connection,
3483 `seqpacket' creates a reliable datagram connection.
3485 :family FAMILY -- FAMILY is the address (and protocol) family for the
3486 service specified by HOST and SERVICE. The default (nil) is to use
3487 whatever address family (IPv4 or IPv6) that is defined for the host
3488 and port number specified by HOST and SERVICE. Other address families
3490 local -- for a local (i.e. UNIX) address specified by SERVICE.
3491 ipv4 -- use IPv4 address family only.
3492 ipv6 -- use IPv6 address family only.
3494 :local ADDRESS -- ADDRESS is the local address used for the connection.
3495 This parameter is ignored when opening a client process. When specified
3496 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3498 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3499 connection. This parameter is ignored when opening a stream server
3500 process. For a datagram server process, it specifies the initial
3501 setting of the remote datagram address. When specified for a client
3502 process, the FAMILY, HOST, and SERVICE args are ignored.
3504 The format of ADDRESS depends on the address family:
3505 - An IPv4 address is represented as an vector of integers [A B C D P]
3506 corresponding to numeric IP address A.B.C.D and port number P.
3507 - A local address is represented as a string with the address in the
3508 local address space.
3509 - An "unsupported family" address is represented by a cons (F . AV)
3510 where F is the family number and AV is a vector containing the socket
3511 address data with one element per address data byte. Do not rely on
3512 this format in portable code, as it may depend on implementation
3513 defined constants, data sizes, and data structure alignment.
3515 :coding CODING -- If CODING is a symbol, it specifies the coding
3516 system used for both reading and writing for this process. If CODING
3517 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3518 ENCODING is used for writing.
3520 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3521 process, return without waiting for the connection to complete;
3522 instead, the sentinel function will be called with second arg matching
3523 "open" (if successful) or "failed" when the connect completes.
3524 Default is to use a blocking connect (i.e. wait) for stream type
3527 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3528 running when Emacs is exited.
3530 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3531 In the stopped state, a server process does not accept new
3532 connections, and a client process does not handle incoming traffic.
3533 The stopped state is cleared by `continue-process' and set by
3536 :filter FILTER -- Install FILTER as the process filter.
3538 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3539 process filter are multibyte, otherwise they are unibyte.
3540 If this keyword is not specified, the strings are multibyte if
3541 the default value of `enable-multibyte-characters' is non-nil.
3543 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3545 :log LOG -- Install LOG as the server process log function. This
3546 function is called when the server accepts a network connection from a
3547 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3548 is the server process, CLIENT is the new process for the connection,
3549 and MESSAGE is a string.
3551 :plist PLIST -- Install PLIST as the new process's initial plist.
3553 :tls-parameters LIST -- is a list that should be supplied if you're
3554 opening a TLS connection. The first element is the TLS type (either
3555 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3556 be a keyword list accepted by gnutls-boot (as returned by
3557 `gnutls-boot-parameters').
3559 :server QLEN -- if QLEN is non-nil, create a server process for the
3560 specified FAMILY, SERVICE, and connection type (stream or datagram).
3561 If QLEN is an integer, it is used as the max. length of the server's
3562 pending connection queue (also known as the backlog); the default
3563 queue length is 5. Default is to create a client process.
3565 The following network options can be specified for this connection:
3567 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3568 :dontroute BOOL -- Only send to directly connected hosts.
3569 :keepalive BOOL -- Send keep-alive messages on network stream.
3570 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3571 :oobinline BOOL -- Place out-of-band data in receive data stream.
3572 :priority INT -- Set protocol defined priority for sent packets.
3573 :reuseaddr BOOL -- Allow reusing a recently used local address
3574 (this is allowed by default for a server process).
3575 :bindtodevice NAME -- bind to interface NAME. Using this may require
3576 special privileges on some systems.
3577 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3578 been passed to Emacs. If Emacs wasn't
3579 passed a socket, this option is silently
3583 Consult the relevant system programmer's manual pages for more
3584 information on using these options.
3587 A server process will listen for and accept connections from clients.
3588 When a client connection is accepted, a new network process is created
3589 for the connection with the following parameters:
3591 - The client's process name is constructed by concatenating the server
3592 process's NAME and a client identification string.
3593 - If the FILTER argument is non-nil, the client process will not get a
3594 separate process buffer; otherwise, the client's process buffer is a newly
3595 created buffer named after the server process's BUFFER name or process
3596 NAME concatenated with the client identification string.
3597 - The connection type and the process filter and sentinel parameters are
3598 inherited from the server process's TYPE, FILTER and SENTINEL.
3599 - The client process's contact info is set according to the client's
3600 addressing information (typically an IP address and a port number).
3601 - The client process's plist is initialized from the server's plist.
3603 Notice that the FILTER and SENTINEL args are never used directly by
3604 the server process. Also, the BUFFER argument is not used directly by
3605 the server process, but via the optional :log function, accepted (and
3606 failed) connections may be logged in the server process's buffer.
3608 The original argument list, modified with the actual connection
3609 information, is available via the `process-contact' function.
3611 usage: (make-network-process &rest ARGS) */)
3612 (ptrdiff_t nargs
, Lisp_Object
*args
)
3615 Lisp_Object contact
;
3616 struct Lisp_Process
*p
;
3617 const char *portstring
;
3618 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3619 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3620 #ifdef HAVE_LOCAL_SOCKETS
3621 struct sockaddr_un address_un
;
3625 Lisp_Object name
, buffer
, host
, service
, address
;
3626 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3627 Lisp_Object ip_addresses
= Qnil
;
3630 int ai_protocol
= 0;
3631 #ifdef HAVE_GETADDRINFO_A
3632 struct gaicb
*dns_request
= NULL
;
3634 ptrdiff_t count
= SPECPDL_INDEX ();
3639 /* Save arguments for process-contact and clone-process. */
3640 contact
= Flist (nargs
, args
);
3643 /* Ensure socket support is loaded if available. */
3644 init_winsock (TRUE
);
3647 /* :type TYPE (nil: stream, datagram */
3648 tem
= Fplist_get (contact
, QCtype
);
3650 socktype
= SOCK_STREAM
;
3651 #ifdef DATAGRAM_SOCKETS
3652 else if (EQ (tem
, Qdatagram
))
3653 socktype
= SOCK_DGRAM
;
3655 #ifdef HAVE_SEQPACKET
3656 else if (EQ (tem
, Qseqpacket
))
3657 socktype
= SOCK_SEQPACKET
;
3660 error ("Unsupported connection type");
3662 name
= Fplist_get (contact
, QCname
);
3663 buffer
= Fplist_get (contact
, QCbuffer
);
3664 filter
= Fplist_get (contact
, QCfilter
);
3665 sentinel
= Fplist_get (contact
, QCsentinel
);
3666 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3668 CHECK_STRING (name
);
3670 /* :local ADDRESS or :remote ADDRESS */
3671 tem
= Fplist_get (contact
, QCserver
);
3673 address
= Fplist_get (contact
, QCremote
);
3675 address
= Fplist_get (contact
, QClocal
);
3676 if (!NILP (address
))
3678 host
= service
= Qnil
;
3680 if (!get_lisp_to_sockaddr_size (address
, &family
))
3681 error ("Malformed :address");
3683 ip_addresses
= list1 (address
);
3687 /* :family FAMILY -- nil (for Inet), local, or integer. */
3688 tem
= Fplist_get (contact
, QCfamily
);
3697 #ifdef HAVE_LOCAL_SOCKETS
3698 else if (EQ (tem
, Qlocal
))
3702 else if (EQ (tem
, Qipv6
))
3705 else if (EQ (tem
, Qipv4
))
3707 else if (TYPE_RANGED_INTEGERP (int, tem
))
3708 family
= XINT (tem
);
3710 error ("Unknown address family");
3712 /* :service SERVICE -- string, integer (port number), or t (random port). */
3713 service
= Fplist_get (contact
, QCservice
);
3715 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3716 host
= Fplist_get (contact
, QChost
);
3719 /* The "connection" function gets it bind info from the address we're
3720 given, so use this dummy address if nothing is specified. */
3721 #ifdef HAVE_LOCAL_SOCKETS
3722 if (family
!= AF_LOCAL
)
3724 host
= build_string ("127.0.0.1");
3728 if (EQ (host
, Qlocal
))
3729 /* Depending on setup, "localhost" may map to different IPv4 and/or
3730 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3731 host
= build_string ("127.0.0.1");
3732 CHECK_STRING (host
);
3735 #ifdef HAVE_LOCAL_SOCKETS
3736 if (family
== AF_LOCAL
)
3740 message (":family local ignores the :host property");
3741 contact
= Fplist_put (contact
, QChost
, Qnil
);
3744 CHECK_STRING (service
);
3745 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3746 error ("Service name too long");
3747 ip_addresses
= list1 (service
);
3752 /* Slow down polling to every ten seconds.
3753 Some kernels have a bug which causes retrying connect to fail
3754 after a connect. Polling can interfere with gethostbyname too. */
3755 #ifdef POLL_FOR_INPUT
3756 if (socktype
!= SOCK_DGRAM
)
3758 record_unwind_protect_void (run_all_atimers
);
3759 bind_polling_period (10);
3765 /* SERVICE can either be a string or int.
3766 Convert to a C string for later use by getaddrinfo. */
3767 if (EQ (service
, Qt
))
3772 else if (INTEGERP (service
))
3774 portstring
= portbuf
;
3775 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3779 CHECK_STRING (service
);
3780 portstring
= SSDATA (service
);
3781 portstringlen
= SBYTES (service
);
3785 #ifdef HAVE_GETADDRINFO_A
3786 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3788 ptrdiff_t hostlen
= SBYTES (host
);
3792 struct addrinfo hints
;
3793 char str
[FLEXIBLE_ARRAY_MEMBER
];
3794 } *req
= xmalloc (offsetof (struct req
, str
)
3795 + hostlen
+ 1 + portstringlen
+ 1);
3796 dns_request
= &req
->gaicb
;
3797 dns_request
->ar_name
= req
->str
;
3798 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3799 dns_request
->ar_request
= &req
->hints
;
3800 dns_request
->ar_result
= NULL
;
3801 memset (&req
->hints
, 0, sizeof req
->hints
);
3802 req
->hints
.ai_family
= family
;
3803 req
->hints
.ai_socktype
= socktype
;
3804 strcpy (req
->str
, SSDATA (host
));
3805 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3807 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3809 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3813 #endif /* HAVE_GETADDRINFO_A */
3815 /* If we have a host, use getaddrinfo to resolve both host and service.
3816 Otherwise, use getservbyname to lookup the service. */
3820 struct addrinfo
*res
, *lres
;
3826 struct addrinfo hints
;
3827 memset (&hints
, 0, sizeof hints
);
3828 hints
.ai_family
= family
;
3829 hints
.ai_socktype
= socktype
;
3831 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3833 #ifdef HAVE_GAI_STRERROR
3835 synchronize_system_messages_locale ();
3836 char const *str
= gai_strerror (ret
);
3837 if (! NILP (Vlocale_coding_system
))
3838 str
= SSDATA (code_convert_string_norecord
3839 (build_string (str
), Vlocale_coding_system
, 0));
3840 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3843 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3847 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3849 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3850 (lres
->ai_addr
, lres
->ai_addrlen
),
3852 ai_protocol
= lres
->ai_protocol
;
3855 ip_addresses
= Fnreverse (ip_addresses
);
3862 /* No hostname has been specified (e.g., a local server process). */
3864 if (EQ (service
, Qt
))
3866 else if (INTEGERP (service
))
3867 port
= XINT (service
);
3870 CHECK_STRING (service
);
3873 if (SBYTES (service
) != 0)
3875 /* Allow the service to be a string containing the port number,
3876 because that's allowed if you have getaddrbyname. */
3878 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3879 if (service_end
== SSDATA (service
) + SBYTES (service
))
3883 struct servent
*svc_info
3884 = getservbyname (SSDATA (service
),
3885 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3887 port
= ntohs (svc_info
->s_port
);
3892 if (! (0 <= port
&& port
< 1 << 16))
3894 AUTO_STRING (unknown_service
, "Unknown service: %s");
3895 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3901 buffer
= Fget_buffer_create (buffer
);
3902 proc
= make_process (name
);
3903 p
= XPROCESS (proc
);
3904 pset_childp (p
, contact
);
3905 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3906 pset_type (p
, Qnetwork
);
3908 pset_buffer (p
, buffer
);
3909 pset_sentinel (p
, sentinel
);
3910 pset_filter (p
, filter
);
3911 pset_log (p
, Fplist_get (contact
, QClog
));
3912 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3913 p
->kill_without_query
= 1;
3914 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3915 pset_command (p
, Qt
);
3918 p
->is_non_blocking_client
= false;
3919 p
->is_server
= false;
3921 p
->socktype
= socktype
;
3922 p
->ai_protocol
= ai_protocol
;
3923 #ifdef HAVE_GETADDRINFO_A
3924 p
->dns_request
= NULL
;
3927 tem
= Fplist_get (contact
, QCtls_parameters
);
3929 p
->gnutls_boot_parameters
= tem
;
3932 set_network_socket_coding_system (proc
, host
, service
, name
);
3934 unbind_to (count
, Qnil
);
3937 tem
= Fplist_get (contact
, QCserver
);
3940 /* Don't support network sockets when non-blocking mode is
3941 not available, since a blocked Emacs is not useful. */
3942 p
->is_server
= true;
3943 if (TYPE_RANGED_INTEGERP (int, tem
))
3944 p
->backlog
= XINT (tem
);
3948 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3949 && !NILP (Fplist_get (contact
, QCnowait
)))
3950 p
->is_non_blocking_client
= true;
3952 #ifdef HAVE_GETADDRINFO_A
3953 /* With async address resolution, the list of addresses is empty, so
3954 postpone connecting to the server. */
3955 if (!p
->is_server
&& NILP (ip_addresses
))
3957 p
->dns_request
= dns_request
;
3958 p
->status
= Qconnect
;
3963 connect_network_socket (proc
, ip_addresses
, use_external_socket_p
);
3968 #ifdef HAVE_NET_IF_H
3972 network_interface_list (void)
3974 struct ifconf ifconf
;
3975 struct ifreq
*ifreq
;
3977 ptrdiff_t buf_size
= 512;
3982 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3985 count
= SPECPDL_INDEX ();
3986 record_unwind_protect_int (close_file_unwind
, s
);
3990 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3991 ifconf
.ifc_buf
= buf
;
3992 ifconf
.ifc_len
= buf_size
;
3993 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4000 while (ifconf
.ifc_len
== buf_size
);
4002 res
= unbind_to (count
, Qnil
);
4003 ifreq
= ifconf
.ifc_req
;
4004 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4006 struct ifreq
*ifq
= ifreq
;
4007 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4008 #define SIZEOF_IFREQ(sif) \
4009 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4010 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4012 int len
= SIZEOF_IFREQ (ifq
);
4014 int len
= sizeof (*ifreq
);
4016 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4017 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4019 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4022 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4023 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4024 res
= Fcons (Fcons (build_string (namebuf
),
4025 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4026 sizeof (struct sockaddr
))),
4033 #endif /* SIOCGIFCONF */
4035 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4039 const char *flag_sym
;
4042 static const struct ifflag_def ifflag_table
[] = {
4046 #ifdef IFF_BROADCAST
4047 { IFF_BROADCAST
, "broadcast" },
4050 { IFF_DEBUG
, "debug" },
4053 { IFF_LOOPBACK
, "loopback" },
4055 #ifdef IFF_POINTOPOINT
4056 { IFF_POINTOPOINT
, "pointopoint" },
4059 { IFF_RUNNING
, "running" },
4062 { IFF_NOARP
, "noarp" },
4065 { IFF_PROMISC
, "promisc" },
4067 #ifdef IFF_NOTRAILERS
4068 #ifdef NS_IMPL_COCOA
4069 /* Really means smart, notrailers is obsolete. */
4070 { IFF_NOTRAILERS
, "smart" },
4072 { IFF_NOTRAILERS
, "notrailers" },
4076 { IFF_ALLMULTI
, "allmulti" },
4079 { IFF_MASTER
, "master" },
4082 { IFF_SLAVE
, "slave" },
4084 #ifdef IFF_MULTICAST
4085 { IFF_MULTICAST
, "multicast" },
4088 { IFF_PORTSEL
, "portsel" },
4090 #ifdef IFF_AUTOMEDIA
4091 { IFF_AUTOMEDIA
, "automedia" },
4094 { IFF_DYNAMIC
, "dynamic" },
4097 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4100 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4103 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4106 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4109 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4115 network_interface_info (Lisp_Object ifname
)
4118 Lisp_Object res
= Qnil
;
4123 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4124 && defined HAVE_GETIFADDRS && defined LLADDR)
4125 struct ifaddrs
*ifap
;
4128 CHECK_STRING (ifname
);
4130 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4131 error ("interface name too long");
4132 lispstpcpy (rq
.ifr_name
, ifname
);
4134 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4137 count
= SPECPDL_INDEX ();
4138 record_unwind_protect_int (close_file_unwind
, s
);
4141 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4142 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4144 int flags
= rq
.ifr_flags
;
4145 const struct ifflag_def
*fp
;
4148 /* If flags is smaller than int (i.e. short) it may have the high bit set
4149 due to IFF_MULTICAST. In that case, sign extending it into
4151 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4152 flags
= (unsigned short) rq
.ifr_flags
;
4155 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4157 if (flags
& fp
->flag_bit
)
4159 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4160 flags
-= fp
->flag_bit
;
4163 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4167 elt
= Fcons (make_number (fnum
), elt
);
4172 res
= Fcons (elt
, res
);
4175 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4176 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4178 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4179 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4183 for (n
= 0; n
< 6; n
++)
4184 p
->contents
[n
] = make_number (((unsigned char *)
4185 &rq
.ifr_hwaddr
.sa_data
[0])
4187 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4189 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4190 if (getifaddrs (&ifap
) != -1)
4192 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4193 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4196 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4198 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4199 unsigned char linkaddr
[6];
4202 if (it
->ifa_addr
->sa_family
!= AF_LINK
4203 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4204 || sdl
->sdl_alen
!= 6)
4207 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4208 for (n
= 0; n
< 6; n
++)
4209 p
->contents
[n
] = make_number (linkaddr
[n
]);
4211 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4215 #ifdef HAVE_FREEIFADDRS
4219 #endif /* HAVE_GETIFADDRS && LLADDR */
4221 res
= Fcons (elt
, res
);
4224 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4225 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4228 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4229 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4231 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4235 res
= Fcons (elt
, res
);
4238 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4239 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4242 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4245 res
= Fcons (elt
, res
);
4248 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4249 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4252 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4255 res
= Fcons (elt
, res
);
4257 return unbind_to (count
, any
? res
: Qnil
);
4259 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4260 #endif /* defined (HAVE_NET_IF_H) */
4262 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4263 Snetwork_interface_list
, 0, 0, 0,
4264 doc
: /* Return an alist of all network interfaces and their network address.
4265 Each element is a cons, the car of which is a string containing the
4266 interface name, and the cdr is the network address in internal
4267 format; see the description of ADDRESS in `make-network-process'.
4269 If the information is not available, return nil. */)
4272 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4273 return network_interface_list ();
4279 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4280 Snetwork_interface_info
, 1, 1, 0,
4281 doc
: /* Return information about network interface named IFNAME.
4282 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4283 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4284 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4285 FLAGS is the current flags of the interface.
4287 Data that is unavailable is returned as nil. */)
4288 (Lisp_Object ifname
)
4290 #if ((defined HAVE_NET_IF_H \
4291 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4292 || defined SIOCGIFFLAGS)) \
4293 || defined WINDOWSNT)
4294 return network_interface_info (ifname
);
4300 /* Turn off input and output for process PROC. */
4303 deactivate_process (Lisp_Object proc
)
4306 struct Lisp_Process
*p
= XPROCESS (proc
);
4310 /* Delete GnuTLS structures in PROC, if any. */
4311 emacs_gnutls_deinit (proc
);
4312 #endif /* HAVE_GNUTLS */
4314 if (p
->read_output_delay
> 0)
4316 if (--process_output_delay_count
< 0)
4317 process_output_delay_count
= 0;
4318 p
->read_output_delay
= 0;
4319 p
->read_output_skip
= 0;
4322 /* Beware SIGCHLD hereabouts. */
4324 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4325 close_process_fd (&p
->open_fd
[i
]);
4327 inchannel
= p
->infd
;
4332 #ifdef DATAGRAM_SOCKETS
4333 if (DATAGRAM_CHAN_P (inchannel
))
4335 xfree (datagram_address
[inchannel
].sa
);
4336 datagram_address
[inchannel
].sa
= 0;
4337 datagram_address
[inchannel
].len
= 0;
4340 chan_process
[inchannel
] = Qnil
;
4341 FD_CLR (inchannel
, &input_wait_mask
);
4342 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4343 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4345 FD_CLR (inchannel
, &connect_wait_mask
);
4346 FD_CLR (inchannel
, &write_mask
);
4347 if (--num_pending_connects
< 0)
4350 if (inchannel
== max_process_desc
)
4352 /* We just closed the highest-numbered process input descriptor,
4353 so recompute the highest-numbered one now. */
4357 while (0 <= i
&& NILP (chan_process
[i
]));
4359 max_process_desc
= i
;
4365 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4367 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4368 It is given to their filter functions.
4369 Optional argument PROCESS means do not return until output has been
4370 received from PROCESS.
4372 Optional second argument SECONDS and third argument MILLISEC
4373 specify a timeout; return after that much time even if there is
4374 no subprocess output. If SECONDS is a floating point number,
4375 it specifies a fractional number of seconds to wait.
4376 The MILLISEC argument is obsolete and should be avoided.
4378 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4379 from PROCESS only, suspending reading output from other processes.
4380 If JUST-THIS-ONE is an integer, don't run any timers either.
4381 Return non-nil if we received any output from PROCESS (or, if PROCESS
4382 is nil, from any process) before the timeout expired. */)
4383 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4388 if (! NILP (process
))
4389 CHECK_PROCESS (process
);
4391 just_this_one
= Qnil
;
4393 if (!NILP (millisec
))
4394 { /* Obsolete calling convention using integers rather than floats. */
4395 CHECK_NUMBER (millisec
);
4397 seconds
= make_float (XINT (millisec
) / 1000.0);
4400 CHECK_NUMBER (seconds
);
4401 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4408 if (!NILP (seconds
))
4410 if (INTEGERP (seconds
))
4412 if (XINT (seconds
) > 0)
4414 secs
= XINT (seconds
);
4418 else if (FLOATP (seconds
))
4420 if (XFLOAT_DATA (seconds
) > 0)
4422 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4423 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4428 wrong_type_argument (Qnumberp
, seconds
);
4430 else if (! NILP (process
))
4434 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4436 !NILP (process
) ? XPROCESS (process
) : NULL
,
4437 (NILP (just_this_one
) ? 0
4438 : !INTEGERP (just_this_one
) ? 1 : -1))
4443 /* Accept a connection for server process SERVER on CHANNEL. */
4445 static EMACS_INT connect_counter
= 0;
4448 server_accept_connection (Lisp_Object server
, int channel
)
4450 Lisp_Object proc
, caller
, name
, buffer
;
4451 Lisp_Object contact
, host
, service
;
4452 struct Lisp_Process
*ps
= XPROCESS (server
);
4453 struct Lisp_Process
*p
;
4457 struct sockaddr_in in
;
4459 struct sockaddr_in6 in6
;
4461 #ifdef HAVE_LOCAL_SOCKETS
4462 struct sockaddr_un un
;
4465 socklen_t len
= sizeof saddr
;
4468 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4473 if (!would_block (code
) && !NILP (ps
->log
))
4474 call3 (ps
->log
, server
, Qnil
,
4475 concat3 (build_string ("accept failed with code"),
4476 Fnumber_to_string (make_number (code
)),
4477 build_string ("\n")));
4481 count
= SPECPDL_INDEX ();
4482 record_unwind_protect_int (close_file_unwind
, s
);
4486 /* Setup a new process to handle the connection. */
4488 /* Generate a unique identification of the caller, and build contact
4489 information for this process. */
4492 switch (saddr
.sa
.sa_family
)
4496 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4498 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4499 host
= CALLN (Fformat
, ipv4_format
,
4500 make_number (ip
[0]), make_number (ip
[1]),
4501 make_number (ip
[2]), make_number (ip
[3]));
4502 service
= make_number (ntohs (saddr
.in
.sin_port
));
4503 AUTO_STRING (caller_format
, " <%s:%d>");
4504 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4511 Lisp_Object args
[9];
4512 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4515 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4516 args
[0] = ipv6_format
;
4517 for (i
= 0; i
< 8; i
++)
4518 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4519 host
= CALLMANY (Fformat
, args
);
4520 service
= make_number (ntohs (saddr
.in
.sin_port
));
4521 AUTO_STRING (caller_format
, " <[%s]:%d>");
4522 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4527 #ifdef HAVE_LOCAL_SOCKETS
4531 caller
= Fnumber_to_string (make_number (connect_counter
));
4532 AUTO_STRING (space_less_than
, " <");
4533 AUTO_STRING (greater_than
, ">");
4534 caller
= concat3 (space_less_than
, caller
, greater_than
);
4538 /* Create a new buffer name for this process if it doesn't have a
4539 filter. The new buffer name is based on the buffer name or
4540 process name of the server process concatenated with the caller
4543 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4544 || EQ (ps
->filter
, Qt
)))
4548 buffer
= ps
->buffer
;
4550 buffer
= Fbuffer_name (buffer
);
4555 buffer
= concat2 (buffer
, caller
);
4556 buffer
= Fget_buffer_create (buffer
);
4560 /* Generate a unique name for the new server process. Combine the
4561 server process name with the caller identification. */
4563 name
= concat2 (ps
->name
, caller
);
4564 proc
= make_process (name
);
4566 chan_process
[s
] = proc
;
4568 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4570 p
= XPROCESS (proc
);
4572 /* Build new contact information for this setup. */
4573 contact
= Fcopy_sequence (ps
->childp
);
4574 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4575 contact
= Fplist_put (contact
, QChost
, host
);
4576 if (!NILP (service
))
4577 contact
= Fplist_put (contact
, QCservice
, service
);
4578 contact
= Fplist_put (contact
, QCremote
,
4579 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4580 #ifdef HAVE_GETSOCKNAME
4582 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4583 contact
= Fplist_put (contact
, QClocal
,
4584 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4587 pset_childp (p
, contact
);
4588 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4589 pset_type (p
, Qnetwork
);
4591 pset_buffer (p
, buffer
);
4592 pset_sentinel (p
, ps
->sentinel
);
4593 pset_filter (p
, ps
->filter
);
4594 pset_command (p
, Qnil
);
4597 /* Discard the unwind protect for closing S. */
4598 specpdl_ptr
= specpdl
+ count
;
4600 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4603 pset_status (p
, Qrun
);
4605 /* Client processes for accepted connections are not stopped initially. */
4606 if (!EQ (p
->filter
, Qt
))
4608 FD_SET (s
, &input_wait_mask
);
4609 FD_SET (s
, &non_keyboard_wait_mask
);
4612 if (s
> max_process_desc
)
4613 max_process_desc
= s
;
4615 /* Setup coding system for new process based on server process.
4616 This seems to be the proper thing to do, as the coding system
4617 of the new process should reflect the settings at the time the
4618 server socket was opened; not the current settings. */
4620 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4621 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4622 setup_process_coding_systems (proc
);
4624 pset_decoding_buf (p
, empty_unibyte_string
);
4625 p
->decoding_carryover
= 0;
4626 pset_encoding_buf (p
, empty_unibyte_string
);
4628 p
->inherit_coding_system_flag
4629 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4631 AUTO_STRING (dash
, "-");
4632 AUTO_STRING (nl
, "\n");
4633 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4635 if (!NILP (ps
->log
))
4637 AUTO_STRING (accept_from
, "accept from ");
4638 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4641 AUTO_STRING (open_from
, "open from ");
4642 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4645 #ifdef HAVE_GETADDRINFO_A
4647 check_for_dns (Lisp_Object proc
)
4649 struct Lisp_Process
*p
= XPROCESS (proc
);
4650 Lisp_Object ip_addresses
= Qnil
;
4653 if (! p
->dns_request
)
4656 int ret
= gai_error (p
->dns_request
);
4657 if (ret
== EAI_INPROGRESS
)
4660 /* We got a response. */
4663 struct addrinfo
*res
;
4665 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4667 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4668 (res
->ai_addr
, res
->ai_addrlen
),
4672 ip_addresses
= Fnreverse (ip_addresses
);
4674 /* The DNS lookup failed. */
4675 else if (EQ (p
->status
, Qconnect
))
4677 deactivate_process (proc
);
4678 pset_status (p
, (list2
4680 concat3 (build_string ("Name lookup of "),
4681 build_string (p
->dns_request
->ar_name
),
4682 build_string (" failed")))));
4685 free_dns_request (proc
);
4687 /* This process should not already be connected (or killed). */
4688 if (!EQ (p
->status
, Qconnect
))
4691 return ip_addresses
;
4694 #endif /* HAVE_GETADDRINFO_A */
4697 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4699 while (XPROCESS (process
)->infd
< 0
4700 && EQ (XPROCESS (process
)->status
, Qconnect
))
4702 add_to_log ("Waiting for socket from %s...", build_string (name
));
4703 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4708 wait_while_connecting (Lisp_Object process
)
4710 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4712 add_to_log ("Waiting for connection...");
4713 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4718 wait_for_tls_negotiation (Lisp_Object process
)
4721 while (XPROCESS (process
)->gnutls_p
4722 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4724 add_to_log ("Waiting for TLS...");
4725 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4730 /* This variable is different from waiting_for_input in keyboard.c.
4731 It is used to communicate to a lisp process-filter/sentinel (via the
4732 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4733 for user-input when that process-filter was called.
4734 waiting_for_input cannot be used as that is by definition 0 when
4735 lisp code is being evalled.
4736 This is also used in record_asynch_buffer_change.
4737 For that purpose, this must be 0
4738 when not inside wait_reading_process_output. */
4739 static int waiting_for_user_input_p
;
4742 wait_reading_process_output_unwind (int data
)
4744 waiting_for_user_input_p
= data
;
4747 /* This is here so breakpoints can be put on it. */
4749 wait_reading_process_output_1 (void)
4753 /* Read and dispose of subprocess output while waiting for timeout to
4754 elapse and/or keyboard input to be available.
4758 If negative, gobble data immediately available but don't wait for any.
4761 an additional duration to wait, measured in nanoseconds
4762 If TIME_LIMIT is zero, then:
4763 If NSECS == 0, there is no limit.
4764 If NSECS > 0, the timeout consists of NSECS only.
4765 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4768 0 to ignore keyboard input, or
4769 1 to return when input is available, or
4770 -1 meaning caller will actually read the input, so don't throw to
4771 the quit handler, or
4773 DO_DISPLAY means redisplay should be done to show subprocess
4774 output that arrives.
4776 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4777 (and gobble terminal input into the buffer if any arrives).
4779 If WAIT_PROC is specified, wait until something arrives from that
4782 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4783 (suspending output from other processes). A negative value
4784 means don't run any timers either.
4786 Return positive if we received input from WAIT_PROC (or from any
4787 process if WAIT_PROC is null), zero if we attempted to receive
4788 input but got none, and negative if we didn't even try. */
4791 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4793 Lisp_Object wait_for_cell
,
4794 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4804 struct timespec timeout
, end_time
, timer_delay
;
4805 struct timespec got_output_end_time
= invalid_timespec ();
4806 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4807 int got_some_output
= -1;
4808 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4809 bool retry_for_async
;
4811 ptrdiff_t count
= SPECPDL_INDEX ();
4813 /* Close to the current time if known, an invalid timespec otherwise. */
4814 struct timespec now
= invalid_timespec ();
4816 FD_ZERO (&Available
);
4819 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4820 && !(CONSP (wait_proc
->status
)
4821 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4822 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4824 record_unwind_protect_int (wait_reading_process_output_unwind
,
4825 waiting_for_user_input_p
);
4826 waiting_for_user_input_p
= read_kbd
;
4828 if (TYPE_MAXIMUM (time_t) < time_limit
)
4829 time_limit
= TYPE_MAXIMUM (time_t);
4831 if (time_limit
< 0 || nsecs
< 0)
4833 else if (time_limit
> 0 || nsecs
> 0)
4836 now
= current_timespec ();
4837 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4844 bool process_skipped
= false;
4846 /* If calling from keyboard input, do not quit
4847 since we want to return C-g as an input character.
4848 Otherwise, do pending quit if requested. */
4851 else if (pending_signals
)
4852 process_pending_signals ();
4854 /* Exit now if the cell we're waiting for became non-nil. */
4855 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4858 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4860 Lisp_Object process_list_head
, aproc
;
4861 struct Lisp_Process
*p
;
4863 retry_for_async
= false;
4864 FOR_EACH_PROCESS(process_list_head
, aproc
)
4866 p
= XPROCESS (aproc
);
4868 if (! wait_proc
|| p
== wait_proc
)
4870 #ifdef HAVE_GETADDRINFO_A
4871 /* Check for pending DNS requests. */
4874 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4875 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4876 connect_network_socket (aproc
, ip_addresses
, Qnil
);
4878 retry_for_async
= true;
4882 /* Continue TLS negotiation. */
4883 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4884 && p
->is_non_blocking_client
)
4886 gnutls_try_handshake (p
);
4887 p
->gnutls_handshakes_tried
++;
4889 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4891 gnutls_verify_boot (aproc
, Qnil
);
4892 finish_after_tls_connection (aproc
);
4896 retry_for_async
= true;
4897 if (p
->gnutls_handshakes_tried
4898 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4900 deactivate_process (aproc
);
4901 pset_status (p
, list2 (Qfailed
,
4902 build_string ("TLS negotiation failed")));
4910 #endif /* GETADDRINFO_A or GNUTLS */
4912 /* Compute time from now till when time limit is up. */
4913 /* Exit if already run out. */
4914 if (wait
== TIMEOUT
)
4916 if (!timespec_valid_p (now
))
4917 now
= current_timespec ();
4918 if (timespec_cmp (end_time
, now
) <= 0)
4920 timeout
= timespec_sub (end_time
, now
);
4923 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4925 /* Normally we run timers here.
4926 But not if wait_for_cell; in those cases,
4927 the wait is supposed to be short,
4928 and those callers cannot handle running arbitrary Lisp code here. */
4929 if (NILP (wait_for_cell
)
4930 && just_wait_proc
>= 0)
4934 unsigned old_timers_run
= timers_run
;
4935 struct buffer
*old_buffer
= current_buffer
;
4936 Lisp_Object old_window
= selected_window
;
4938 timer_delay
= timer_check ();
4940 /* If a timer has run, this might have changed buffers
4941 an alike. Make read_key_sequence aware of that. */
4942 if (timers_run
!= old_timers_run
4943 && (old_buffer
!= current_buffer
4944 || !EQ (old_window
, selected_window
))
4945 && waiting_for_user_input_p
== -1)
4946 record_asynch_buffer_change ();
4948 if (timers_run
!= old_timers_run
&& do_display
)
4949 /* We must retry, since a timer may have requeued itself
4950 and that could alter the time_delay. */
4951 redisplay_preserve_echo_area (9);
4955 while (!detect_input_pending ());
4957 /* If there is unread keyboard input, also return. */
4959 && requeued_events_pending_p ())
4962 /* This is so a breakpoint can be put here. */
4963 if (!timespec_valid_p (timer_delay
))
4964 wait_reading_process_output_1 ();
4967 /* Cause C-g and alarm signals to take immediate action,
4968 and cause input available signals to zero out timeout.
4970 It is important that we do this before checking for process
4971 activity. If we get a SIGCHLD after the explicit checks for
4972 process activity, timeout is the only way we will know. */
4974 set_waiting_for_input (&timeout
);
4976 /* If status of something has changed, and no input is
4977 available, notify the user of the change right away. After
4978 this explicit check, we'll let the SIGCHLD handler zap
4979 timeout to get our attention. */
4980 if (update_tick
!= process_tick
)
4985 if (kbd_on_hold_p ())
4988 Atemp
= input_wait_mask
;
4991 timeout
= make_timespec (0, 0);
4992 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4994 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4995 NULL
, &timeout
, NULL
)
4998 /* It's okay for us to do this and then continue with
4999 the loop, since timeout has already been zeroed out. */
5000 clear_waiting_for_input ();
5001 got_some_output
= status_notify (NULL
, wait_proc
);
5002 if (do_display
) redisplay_preserve_echo_area (13);
5006 /* Don't wait for output from a non-running process. Just
5007 read whatever data has already been received. */
5008 if (wait_proc
&& wait_proc
->raw_status_new
)
5009 update_status (wait_proc
);
5011 && ! EQ (wait_proc
->status
, Qrun
)
5012 && ! EQ (wait_proc
->status
, Qconnect
))
5014 bool read_some_bytes
= false;
5016 clear_waiting_for_input ();
5018 /* If data can be read from the process, do so until exhausted. */
5019 if (wait_proc
->infd
>= 0)
5021 XSETPROCESS (proc
, wait_proc
);
5025 int nread
= read_process_output (proc
, wait_proc
->infd
);
5028 if (errno
== EIO
|| would_block (errno
))
5033 if (got_some_output
< nread
)
5034 got_some_output
= nread
;
5037 read_some_bytes
= true;
5042 if (read_some_bytes
&& do_display
)
5043 redisplay_preserve_echo_area (10);
5048 /* Wait till there is something to do. */
5050 if (wait_proc
&& just_wait_proc
)
5052 if (wait_proc
->infd
< 0) /* Terminated. */
5054 FD_SET (wait_proc
->infd
, &Available
);
5058 else if (!NILP (wait_for_cell
))
5060 Available
= non_process_wait_mask
;
5067 Available
= non_keyboard_wait_mask
;
5069 Available
= input_wait_mask
;
5070 Writeok
= write_mask
;
5071 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5075 /* If frame size has changed or the window is newly mapped,
5076 redisplay now, before we start to wait. There is a race
5077 condition here; if a SIGIO arrives between now and the select
5078 and indicates that a frame is trashed, the select may block
5079 displaying a trashed screen. */
5080 if (frame_garbaged
&& do_display
)
5082 clear_waiting_for_input ();
5083 redisplay_preserve_echo_area (11);
5085 set_waiting_for_input (&timeout
);
5088 /* Skip the `select' call if input is available and we're
5089 waiting for keyboard input or a cell change (which can be
5090 triggered by processing X events). In the latter case, set
5091 nfds to 1 to avoid breaking the loop. */
5093 if ((read_kbd
|| !NILP (wait_for_cell
))
5094 && detect_input_pending ())
5096 nfds
= read_kbd
? 0 : 1;
5098 FD_ZERO (&Available
);
5102 /* Set the timeout for adaptive read buffering if any
5103 process has non-zero read_output_skip and non-zero
5104 read_output_delay, and we are not reading output for a
5105 specific process. It is not executed if
5106 Vprocess_adaptive_read_buffering is nil. */
5107 if (process_output_skip
&& check_delay
> 0)
5109 int adaptive_nsecs
= timeout
.tv_nsec
;
5110 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5111 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5112 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5114 proc
= chan_process
[channel
];
5117 /* Find minimum non-zero read_output_delay among the
5118 processes with non-zero read_output_skip. */
5119 if (XPROCESS (proc
)->read_output_delay
> 0)
5122 if (!XPROCESS (proc
)->read_output_skip
)
5124 FD_CLR (channel
, &Available
);
5125 process_skipped
= true;
5126 XPROCESS (proc
)->read_output_skip
= 0;
5127 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5128 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5131 timeout
= make_timespec (0, adaptive_nsecs
);
5132 process_output_skip
= 0;
5135 /* If we've got some output and haven't limited our timeout
5136 with adaptive read buffering, limit it. */
5137 if (got_some_output
> 0 && !process_skipped
5139 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5140 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5143 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5144 && timespec_valid_p (timer_delay
)
5145 && timespec_cmp (timer_delay
, timeout
) < 0)
5147 if (!timespec_valid_p (now
))
5148 now
= current_timespec ();
5149 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5150 if (!timespec_valid_p (got_output_end_time
)
5151 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5152 got_output_end_time
= timeout_abs
;
5153 timeout
= timer_delay
;
5156 got_output_end_time
= invalid_timespec ();
5158 /* NOW can become inaccurate if time can pass during pselect. */
5159 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5160 now
= invalid_timespec ();
5162 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5164 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5167 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5171 #if defined (HAVE_NS)
5173 #elif defined (HAVE_GLIB)
5178 (max (max_process_desc
, max_input_desc
) + 1,
5180 (check_write
? &Writeok
: 0),
5181 NULL
, &timeout
, NULL
);
5184 /* GnuTLS buffers data internally. In lowat mode it leaves
5185 some data in the TCP buffers so that select works, but
5186 with custom pull/push functions we need to check if some
5187 data is available in the buffers manually. */
5190 fd_set tls_available
;
5193 FD_ZERO (&tls_available
);
5196 /* We're not waiting on a specific process, so loop
5197 through all the channels and check for data.
5198 This is a workaround needed for some versions of
5199 the gnutls library -- 2.12.14 has been confirmed
5201 http://comments.gmane.org/gmane.emacs.devel/145074 */
5202 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5203 if (! NILP (chan_process
[channel
]))
5205 struct Lisp_Process
*p
=
5206 XPROCESS (chan_process
[channel
]);
5207 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5208 && ((emacs_gnutls_record_check_pending
5213 eassert (p
->infd
== channel
);
5214 FD_SET (p
->infd
, &tls_available
);
5221 /* Check this specific channel. */
5222 if (wait_proc
->gnutls_p
/* Check for valid process. */
5223 && wait_proc
->gnutls_state
5224 /* Do we have pending data? */
5225 && ((emacs_gnutls_record_check_pending
5226 (wait_proc
->gnutls_state
))
5230 eassert (0 <= wait_proc
->infd
);
5231 /* Set to Available. */
5232 FD_SET (wait_proc
->infd
, &tls_available
);
5237 Available
= tls_available
;
5244 /* Make C-g and alarm signals set flags again. */
5245 clear_waiting_for_input ();
5247 /* If we woke up due to SIGWINCH, actually change size now. */
5248 do_pending_window_change (0);
5252 /* Exit the main loop if we've passed the requested timeout,
5253 or aren't skipping processes and got some output and
5254 haven't lowered our timeout due to timers or SIGIO and
5255 have waited a long amount of time due to repeated
5259 struct timespec cmp_time
5262 : (!process_skipped
&& got_some_output
> 0
5263 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5264 ? got_output_end_time
5265 : invalid_timespec ());
5266 if (timespec_valid_p (cmp_time
))
5268 now
= current_timespec ();
5269 if (timespec_cmp (cmp_time
, now
) <= 0)
5276 if (xerrno
== EINTR
)
5278 else if (xerrno
== EBADF
)
5281 report_file_errno ("Failed select", Qnil
, xerrno
);
5284 /* Check for keyboard input. */
5285 /* If there is any, return immediately
5286 to give it higher priority than subprocesses. */
5290 unsigned old_timers_run
= timers_run
;
5291 struct buffer
*old_buffer
= current_buffer
;
5292 Lisp_Object old_window
= selected_window
;
5295 if (detect_input_pending_run_timers (do_display
))
5297 swallow_events (do_display
);
5298 if (detect_input_pending_run_timers (do_display
))
5302 /* If a timer has run, this might have changed buffers
5303 an alike. Make read_key_sequence aware of that. */
5304 if (timers_run
!= old_timers_run
5305 && waiting_for_user_input_p
== -1
5306 && (old_buffer
!= current_buffer
5307 || !EQ (old_window
, selected_window
)))
5308 record_asynch_buffer_change ();
5314 /* If there is unread keyboard input, also return. */
5316 && requeued_events_pending_p ())
5319 /* If we are not checking for keyboard input now,
5320 do process events (but don't run any timers).
5321 This is so that X events will be processed.
5322 Otherwise they may have to wait until polling takes place.
5323 That would causes delays in pasting selections, for example.
5325 (We used to do this only if wait_for_cell.) */
5326 if (read_kbd
== 0 && detect_input_pending ())
5328 swallow_events (do_display
);
5329 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5330 if (detect_input_pending ())
5335 /* Exit now if the cell we're waiting for became non-nil. */
5336 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5340 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5341 go read it. This can happen with X on BSD after logging out.
5342 In that case, there really is no input and no SIGIO,
5343 but select says there is input. */
5345 if (read_kbd
&& interrupt_input
5346 && keyboard_bit_set (&Available
) && ! noninteractive
)
5347 handle_input_available_signal (SIGIO
);
5350 /* If checking input just got us a size-change event from X,
5351 obey it now if we should. */
5352 if (read_kbd
|| ! NILP (wait_for_cell
))
5353 do_pending_window_change (0);
5355 /* Check for data from a process. */
5356 if (no_avail
|| nfds
== 0)
5359 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5361 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5363 && ((d
->condition
& FOR_READ
5364 && FD_ISSET (channel
, &Available
))
5365 || (d
->condition
& FOR_WRITE
5366 && FD_ISSET (channel
, &write_mask
))))
5367 d
->func (channel
, d
->data
);
5370 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5372 if (FD_ISSET (channel
, &Available
)
5373 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5374 && !FD_ISSET (channel
, &non_process_wait_mask
))
5378 /* If waiting for this channel, arrange to return as
5379 soon as no more input to be processed. No more
5381 proc
= chan_process
[channel
];
5385 /* If this is a server stream socket, accept connection. */
5386 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5388 server_accept_connection (proc
, channel
);
5392 /* Read data from the process, starting with our
5393 buffered-ahead character if we have one. */
5395 nread
= read_process_output (proc
, channel
);
5396 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5397 && got_some_output
< nread
)
5398 got_some_output
= nread
;
5401 /* Vacuum up any leftovers without waiting. */
5402 if (wait_proc
== XPROCESS (proc
))
5404 /* Since read_process_output can run a filter,
5405 which can call accept-process-output,
5406 don't try to read from any other processes
5407 before doing the select again. */
5408 FD_ZERO (&Available
);
5411 redisplay_preserve_echo_area (12);
5413 else if (nread
== -1 && would_block (errno
))
5416 /* FIXME: Is this special case still needed? */
5417 /* Note that we cannot distinguish between no input
5418 available now and a closed pipe.
5419 With luck, a closed pipe will be accompanied by
5420 subprocess termination and SIGCHLD. */
5421 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5422 && !PIPECONN_P (proc
))
5426 /* On some OSs with ptys, when the process on one end of
5427 a pty exits, the other end gets an error reading with
5428 errno = EIO instead of getting an EOF (0 bytes read).
5429 Therefore, if we get an error reading and errno =
5430 EIO, just continue, because the child process has
5431 exited and should clean itself up soon (e.g. when we
5433 else if (nread
== -1 && errno
== EIO
)
5435 struct Lisp_Process
*p
= XPROCESS (proc
);
5437 /* Clear the descriptor now, so we only raise the
5439 FD_CLR (channel
, &input_wait_mask
);
5440 FD_CLR (channel
, &non_keyboard_wait_mask
);
5444 /* If the EIO occurs on a pty, the SIGCHLD handler's
5445 waitpid call will not find the process object to
5446 delete. Do it here. */
5447 p
->tick
= ++process_tick
;
5448 pset_status (p
, Qfailed
);
5451 #endif /* HAVE_PTYS */
5452 /* If we can detect process termination, don't consider the
5453 process gone just because its pipe is closed. */
5454 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5455 && !PIPECONN_P (proc
))
5457 else if (nread
== 0 && PIPECONN_P (proc
))
5459 /* Preserve status of processes already terminated. */
5460 XPROCESS (proc
)->tick
= ++process_tick
;
5461 deactivate_process (proc
);
5462 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5463 pset_status (XPROCESS (proc
),
5464 list2 (Qexit
, make_number (0)));
5468 /* Preserve status of processes already terminated. */
5469 XPROCESS (proc
)->tick
= ++process_tick
;
5470 deactivate_process (proc
);
5471 if (XPROCESS (proc
)->raw_status_new
)
5472 update_status (XPROCESS (proc
));
5473 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5474 pset_status (XPROCESS (proc
),
5475 list2 (Qexit
, make_number (256)));
5478 if (FD_ISSET (channel
, &Writeok
)
5479 && FD_ISSET (channel
, &connect_wait_mask
))
5481 struct Lisp_Process
*p
;
5483 FD_CLR (channel
, &connect_wait_mask
);
5484 FD_CLR (channel
, &write_mask
);
5485 if (--num_pending_connects
< 0)
5488 proc
= chan_process
[channel
];
5492 p
= XPROCESS (proc
);
5495 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5496 So only use it on systems where it is known to work. */
5498 socklen_t xlen
= sizeof (xerrno
);
5499 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5504 struct sockaddr pname
;
5505 socklen_t pnamelen
= sizeof (pname
);
5507 /* If connection failed, getpeername will fail. */
5509 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5511 /* Obtain connect failure code through error slippage. */
5514 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5521 p
->tick
= ++process_tick
;
5522 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5523 deactivate_process (proc
);
5528 /* If we have an incompletely set up TLS connection,
5529 then defer the sentinel signaling until
5531 if (NILP (p
->gnutls_boot_parameters
)
5535 pset_status (p
, Qrun
);
5536 /* Execute the sentinel here. If we had relied on
5537 status_notify to do it later, it will read input
5538 from the process before calling the sentinel. */
5539 exec_sentinel (proc
, build_string ("open\n"));
5542 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5543 && !EQ (p
->command
, Qt
))
5545 FD_SET (p
->infd
, &input_wait_mask
);
5546 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5550 } /* End for each file descriptor. */
5551 } /* End while exit conditions not met. */
5553 unbind_to (count
, Qnil
);
5555 /* If calling from keyboard input, do not quit
5556 since we want to return C-g as an input character.
5557 Otherwise, do pending quit if requested. */
5560 /* Prevent input_pending from remaining set if we quit. */
5561 clear_input_pending ();
5565 return got_some_output
;
5568 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5571 read_process_output_call (Lisp_Object fun_and_args
)
5573 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5577 read_process_output_error_handler (Lisp_Object error_val
)
5579 cmd_error_internal (error_val
, "error in process filter: ");
5581 update_echo_area ();
5582 Fsleep_for (make_number (2), Qnil
);
5587 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5589 struct coding_system
*coding
);
5591 /* Read pending output from the process channel,
5592 starting with our buffered-ahead character if we have one.
5593 Yield number of decoded characters read.
5595 This function reads at most 4096 characters.
5596 If you want to read all available subprocess output,
5597 you must call it repeatedly until it returns zero.
5599 The characters read are decoded according to PROC's coding-system
5603 read_process_output (Lisp_Object proc
, int channel
)
5606 struct Lisp_Process
*p
= XPROCESS (proc
);
5607 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5608 int carryover
= p
->decoding_carryover
;
5609 enum { readmax
= 4096 };
5610 ptrdiff_t count
= SPECPDL_INDEX ();
5611 Lisp_Object odeactivate
;
5612 char chars
[sizeof coding
->carryover
+ readmax
];
5615 /* See the comment above. */
5616 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5618 #ifdef DATAGRAM_SOCKETS
5619 /* We have a working select, so proc_buffered_char is always -1. */
5620 if (DATAGRAM_CHAN_P (channel
))
5622 socklen_t len
= datagram_address
[channel
].len
;
5623 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5624 0, datagram_address
[channel
].sa
, &len
);
5629 bool buffered
= proc_buffered_char
[channel
] >= 0;
5632 chars
[carryover
] = proc_buffered_char
[channel
];
5633 proc_buffered_char
[channel
] = -1;
5636 if (p
->gnutls_p
&& p
->gnutls_state
)
5637 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5638 readmax
- buffered
);
5641 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5642 readmax
- buffered
);
5643 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5645 int delay
= p
->read_output_delay
;
5648 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5651 process_output_delay_count
++;
5652 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5655 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5657 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5659 process_output_delay_count
--;
5661 p
->read_output_delay
= delay
;
5664 p
->read_output_skip
= 1;
5665 process_output_skip
= 1;
5669 nbytes
+= buffered
&& nbytes
<= 0;
5672 p
->decoding_carryover
= 0;
5674 /* At this point, NBYTES holds number of bytes just received
5675 (including the one in proc_buffered_char[channel]). */
5678 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5680 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5683 /* Now set NBYTES how many bytes we must decode. */
5684 nbytes
+= carryover
;
5686 odeactivate
= Vdeactivate_mark
;
5687 /* There's no good reason to let process filters change the current
5688 buffer, and many callers of accept-process-output, sit-for, and
5689 friends don't expect current-buffer to be changed from under them. */
5690 record_unwind_current_buffer ();
5692 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5694 /* Handling the process output should not deactivate the mark. */
5695 Vdeactivate_mark
= odeactivate
;
5697 unbind_to (count
, Qnil
);
5702 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5704 struct coding_system
*coding
)
5706 Lisp_Object outstream
= p
->filter
;
5708 bool outer_running_asynch_code
= running_asynch_code
;
5709 int waiting
= waiting_for_user_input_p
;
5712 Lisp_Object obuffer
, okeymap
;
5713 XSETBUFFER (obuffer
, current_buffer
);
5714 okeymap
= BVAR (current_buffer
, keymap
);
5717 /* We inhibit quit here instead of just catching it so that
5718 hitting ^G when a filter happens to be running won't screw
5720 specbind (Qinhibit_quit
, Qt
);
5721 specbind (Qlast_nonmenu_event
, Qt
);
5723 /* In case we get recursively called,
5724 and we already saved the match data nonrecursively,
5725 save the same match data in safely recursive fashion. */
5726 if (outer_running_asynch_code
)
5729 /* Don't clobber the CURRENT match data, either! */
5730 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5731 restore_search_regs ();
5732 record_unwind_save_match_data ();
5733 Fset_match_data (tem
, Qt
);
5736 /* For speed, if a search happens within this code,
5737 save the match data in a special nonrecursive fashion. */
5738 running_asynch_code
= 1;
5740 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5741 text
= coding
->dst_object
;
5742 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5743 /* A new coding system might be found. */
5744 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5746 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5748 /* Don't call setup_coding_system for
5749 proc_decode_coding_system[channel] here. It is done in
5750 detect_coding called via decode_coding above. */
5752 /* If a coding system for encoding is not yet decided, we set
5753 it as the same as coding-system for decoding.
5755 But, before doing that we must check if
5756 proc_encode_coding_system[p->outfd] surely points to a
5757 valid memory because p->outfd will be changed once EOF is
5758 sent to the process. */
5759 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5760 && proc_encode_coding_system
[p
->outfd
])
5762 pset_encode_coding_system
5763 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5764 setup_coding_system (p
->encode_coding_system
,
5765 proc_encode_coding_system
[p
->outfd
]);
5769 if (coding
->carryover_bytes
> 0)
5771 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5772 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5773 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5774 coding
->carryover_bytes
);
5775 p
->decoding_carryover
= coding
->carryover_bytes
;
5777 if (SBYTES (text
) > 0)
5778 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5779 sometimes it's simply wrong to wrap (e.g. when called from
5780 accept-process-output). */
5781 internal_condition_case_1 (read_process_output_call
,
5782 list3 (outstream
, make_lisp_proc (p
), text
),
5783 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5784 read_process_output_error_handler
);
5786 /* If we saved the match data nonrecursively, restore it now. */
5787 restore_search_regs ();
5788 running_asynch_code
= outer_running_asynch_code
;
5790 /* Restore waiting_for_user_input_p as it was
5791 when we were called, in case the filter clobbered it. */
5792 waiting_for_user_input_p
= waiting
;
5794 #if 0 /* Call record_asynch_buffer_change unconditionally,
5795 because we might have changed minor modes or other things
5796 that affect key bindings. */
5797 if (! EQ (Fcurrent_buffer (), obuffer
)
5798 || ! EQ (current_buffer
->keymap
, okeymap
))
5800 /* But do it only if the caller is actually going to read events.
5801 Otherwise there's no need to make him wake up, and it could
5802 cause trouble (for example it would make sit_for return). */
5803 if (waiting_for_user_input_p
== -1)
5804 record_asynch_buffer_change ();
5807 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5808 Sinternal_default_process_filter
, 2, 2, 0,
5809 doc
: /* Function used as default process filter.
5810 This inserts the process's output into its buffer, if there is one.
5811 Otherwise it discards the output. */)
5812 (Lisp_Object proc
, Lisp_Object text
)
5814 struct Lisp_Process
*p
;
5817 CHECK_PROCESS (proc
);
5818 p
= XPROCESS (proc
);
5819 CHECK_STRING (text
);
5821 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5823 Lisp_Object old_read_only
;
5824 ptrdiff_t old_begv
, old_zv
;
5825 ptrdiff_t old_begv_byte
, old_zv_byte
;
5826 ptrdiff_t before
, before_byte
;
5827 ptrdiff_t opoint_byte
;
5830 Fset_buffer (p
->buffer
);
5832 opoint_byte
= PT_BYTE
;
5833 old_read_only
= BVAR (current_buffer
, read_only
);
5836 old_begv_byte
= BEGV_BYTE
;
5837 old_zv_byte
= ZV_BYTE
;
5839 bset_read_only (current_buffer
, Qnil
);
5841 /* Insert new output into buffer at the current end-of-output
5842 marker, thus preserving logical ordering of input and output. */
5843 if (XMARKER (p
->mark
)->buffer
)
5844 set_point_from_marker (p
->mark
);
5846 SET_PT_BOTH (ZV
, ZV_BYTE
);
5848 before_byte
= PT_BYTE
;
5850 /* If the output marker is outside of the visible region, save
5851 the restriction and widen. */
5852 if (! (BEGV
<= PT
&& PT
<= ZV
))
5855 /* Adjust the multibyteness of TEXT to that of the buffer. */
5856 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5857 != ! STRING_MULTIBYTE (text
))
5858 text
= (STRING_MULTIBYTE (text
)
5859 ? Fstring_as_unibyte (text
)
5860 : Fstring_to_multibyte (text
));
5861 /* Insert before markers in case we are inserting where
5862 the buffer's mark is, and the user's next command is Meta-y. */
5863 insert_from_string_before_markers (text
, 0, 0,
5864 SCHARS (text
), SBYTES (text
), 0);
5866 /* Make sure the process marker's position is valid when the
5867 process buffer is changed in the signal_after_change above.
5868 W3 is known to do that. */
5869 if (BUFFERP (p
->buffer
)
5870 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5871 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5873 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5875 update_mode_lines
= 23;
5877 /* Make sure opoint and the old restrictions
5878 float ahead of any new text just as point would. */
5879 if (opoint
>= before
)
5881 opoint
+= PT
- before
;
5882 opoint_byte
+= PT_BYTE
- before_byte
;
5884 if (old_begv
> before
)
5886 old_begv
+= PT
- before
;
5887 old_begv_byte
+= PT_BYTE
- before_byte
;
5889 if (old_zv
>= before
)
5891 old_zv
+= PT
- before
;
5892 old_zv_byte
+= PT_BYTE
- before_byte
;
5895 /* If the restriction isn't what it should be, set it. */
5896 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5897 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5899 bset_read_only (current_buffer
, old_read_only
);
5900 SET_PT_BOTH (opoint
, opoint_byte
);
5905 /* Sending data to subprocess. */
5907 /* In send_process, when a write fails temporarily,
5908 wait_reading_process_output is called. It may execute user code,
5909 e.g. timers, that attempts to write new data to the same process.
5910 We must ensure that data is sent in the right order, and not
5911 interspersed half-completed with other writes (Bug#10815). This is
5912 handled by the write_queue element of struct process. It is a list
5913 with each entry having the form
5915 (string . (offset . length))
5917 where STRING is a lisp string, OFFSET is the offset into the
5918 string's byte sequence from which we should begin to send, and
5919 LENGTH is the number of bytes left to send. */
5921 /* Create a new entry in write_queue.
5922 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5923 BUF is a pointer to the string sequence of the input_obj or a C
5924 string in case of Qt or Qnil. */
5927 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5928 const char *buf
, ptrdiff_t len
, bool front
)
5931 Lisp_Object entry
, obj
;
5933 if (STRINGP (input_obj
))
5935 offset
= buf
- SSDATA (input_obj
);
5941 obj
= make_unibyte_string (buf
, len
);
5944 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5947 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5949 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5952 /* Remove the first element in the write_queue of process P, put its
5953 contents in OBJ, BUF and LEN, and return true. If the
5954 write_queue is empty, return false. */
5957 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5958 const char **buf
, ptrdiff_t *len
)
5960 Lisp_Object entry
, offset_length
;
5963 if (NILP (p
->write_queue
))
5966 entry
= XCAR (p
->write_queue
);
5967 pset_write_queue (p
, XCDR (p
->write_queue
));
5969 *obj
= XCAR (entry
);
5970 offset_length
= XCDR (entry
);
5972 *len
= XINT (XCDR (offset_length
));
5973 offset
= XINT (XCAR (offset_length
));
5974 *buf
= SSDATA (*obj
) + offset
;
5979 /* Send some data to process PROC.
5980 BUF is the beginning of the data; LEN is the number of characters.
5981 OBJECT is the Lisp object that the data comes from. If OBJECT is
5982 nil or t, it means that the data comes from C string.
5984 If OBJECT is not nil, the data is encoded by PROC's coding-system
5985 for encoding before it is sent.
5987 This function can evaluate Lisp code and can garbage collect. */
5990 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5993 struct Lisp_Process
*p
= XPROCESS (proc
);
5995 struct coding_system
*coding
;
5997 if (NETCONN_P (proc
))
5999 wait_while_connecting (proc
);
6000 wait_for_tls_negotiation (proc
);
6003 if (p
->raw_status_new
)
6005 if (! EQ (p
->status
, Qrun
))
6006 error ("Process %s not running", SDATA (p
->name
));
6008 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6010 coding
= proc_encode_coding_system
[p
->outfd
];
6011 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6013 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6014 || (BUFFERP (object
)
6015 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6018 pset_encode_coding_system
6019 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6020 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6022 /* The coding system for encoding was changed to raw-text
6023 because we sent a unibyte text previously. Now we are
6024 sending a multibyte text, thus we must encode it by the
6025 original coding system specified for the current process.
6027 Another reason we come here is that the coding system
6028 was just complemented and a new one was returned by
6029 complement_process_encoding_system. */
6030 setup_coding_system (p
->encode_coding_system
, coding
);
6031 Vlast_coding_system_used
= p
->encode_coding_system
;
6033 coding
->src_multibyte
= 1;
6037 coding
->src_multibyte
= 0;
6038 /* For sending a unibyte text, character code conversion should
6039 not take place but EOL conversion should. So, setup raw-text
6040 or one of the subsidiary if we have not yet done it. */
6041 if (CODING_REQUIRE_ENCODING (coding
))
6043 if (CODING_REQUIRE_FLUSHING (coding
))
6045 /* But, before changing the coding, we must flush out data. */
6046 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6047 send_process (proc
, "", 0, Qt
);
6048 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6050 setup_coding_system (raw_text_coding_system
6051 (Vlast_coding_system_used
),
6053 coding
->src_multibyte
= 0;
6056 coding
->dst_multibyte
= 0;
6058 if (CODING_REQUIRE_ENCODING (coding
))
6060 coding
->dst_object
= Qt
;
6061 if (BUFFERP (object
))
6063 ptrdiff_t from_byte
, from
, to
;
6064 ptrdiff_t save_pt
, save_pt_byte
;
6065 struct buffer
*cur
= current_buffer
;
6067 set_buffer_internal (XBUFFER (object
));
6068 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6070 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6071 from
= BYTE_TO_CHAR (from_byte
);
6072 to
= BYTE_TO_CHAR (from_byte
+ len
);
6073 TEMP_SET_PT_BOTH (from
, from_byte
);
6074 encode_coding_object (coding
, object
, from
, from_byte
,
6075 to
, from_byte
+ len
, Qt
);
6076 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6077 set_buffer_internal (cur
);
6079 else if (STRINGP (object
))
6081 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6082 SBYTES (object
), Qt
);
6086 coding
->dst_object
= make_unibyte_string (buf
, len
);
6087 coding
->produced
= len
;
6090 len
= coding
->produced
;
6091 object
= coding
->dst_object
;
6092 buf
= SSDATA (object
);
6095 /* If there is already data in the write_queue, put the new data
6096 in the back of queue. Otherwise, ignore it. */
6097 if (!NILP (p
->write_queue
))
6098 write_queue_push (p
, object
, buf
, len
, 0);
6100 do /* while !NILP (p->write_queue) */
6102 ptrdiff_t cur_len
= -1;
6103 const char *cur_buf
;
6104 Lisp_Object cur_object
;
6106 /* If write_queue is empty, ignore it. */
6107 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6111 cur_object
= object
;
6116 /* Send this batch, using one or more write calls. */
6117 ptrdiff_t written
= 0;
6118 int outfd
= p
->outfd
;
6119 #ifdef DATAGRAM_SOCKETS
6120 if (DATAGRAM_CHAN_P (outfd
))
6122 rv
= sendto (outfd
, cur_buf
, cur_len
,
6123 0, datagram_address
[outfd
].sa
,
6124 datagram_address
[outfd
].len
);
6127 else if (errno
== EMSGSIZE
)
6128 report_file_error ("Sending datagram", proc
);
6134 if (p
->gnutls_p
&& p
->gnutls_state
)
6135 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6138 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6139 rv
= (written
? 0 : -1);
6140 if (p
->read_output_delay
> 0
6141 && p
->adaptive_read_buffering
== 1)
6143 p
->read_output_delay
= 0;
6144 process_output_delay_count
--;
6145 p
->read_output_skip
= 0;
6151 if (would_block (errno
))
6152 /* Buffer is full. Wait, accepting input;
6153 that may allow the program
6154 to finish doing output and read more. */
6156 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6157 /* A gross hack to work around a bug in FreeBSD.
6158 In the following sequence, read(2) returns
6162 write(2) 954 bytes, get EAGAIN
6163 read(2) 1024 bytes in process_read_output
6164 read(2) 11 bytes in process_read_output
6166 That is, read(2) returns more bytes than have
6167 ever been written successfully. The 1033 bytes
6168 read are the 1022 bytes written successfully
6169 after processing (for example with CRs added if
6170 the terminal is set up that way which it is
6171 here). The same bytes will be seen again in a
6172 later read(2), without the CRs. */
6174 if (errno
== EAGAIN
)
6177 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6179 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6181 /* Put what we should have written in wait_queue. */
6182 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6183 wait_reading_process_output (0, 20 * 1000 * 1000,
6184 0, 0, Qnil
, NULL
, 0);
6185 /* Reread queue, to see what is left. */
6188 else if (errno
== EPIPE
)
6190 p
->raw_status_new
= 0;
6191 pset_status (p
, list2 (Qexit
, make_number (256)));
6192 p
->tick
= ++process_tick
;
6193 deactivate_process (proc
);
6194 error ("process %s no longer connected to pipe; closed it",
6198 /* This is a real error. */
6199 report_file_error ("Writing to process", proc
);
6205 while (!NILP (p
->write_queue
));
6208 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6210 doc
: /* Send current contents of region as input to PROCESS.
6211 PROCESS may be a process, a buffer, the name of a process or buffer, or
6212 nil, indicating the current buffer's process.
6213 Called from program, takes three arguments, PROCESS, START and END.
6214 If the region is more than 500 characters long,
6215 it is sent in several bunches. This may happen even for shorter regions.
6216 Output from processes can arrive in between bunches.
6218 If PROCESS is a non-blocking network process that hasn't been fully
6219 set up yet, this function will block until socket setup has completed. */)
6220 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6222 Lisp_Object proc
= get_process (process
);
6223 ptrdiff_t start_byte
, end_byte
;
6225 validate_region (&start
, &end
);
6227 start_byte
= CHAR_TO_BYTE (XINT (start
));
6228 end_byte
= CHAR_TO_BYTE (XINT (end
));
6230 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6231 move_gap_both (XINT (start
), start_byte
);
6233 if (NETCONN_P (proc
))
6234 wait_while_connecting (proc
);
6236 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6237 end_byte
- start_byte
, Fcurrent_buffer ());
6242 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6244 doc
: /* Send PROCESS the contents of STRING as input.
6245 PROCESS may be a process, a buffer, the name of a process or buffer, or
6246 nil, indicating the current buffer's process.
6247 If STRING is more than 500 characters long,
6248 it is sent in several bunches. This may happen even for shorter strings.
6249 Output from processes can arrive in between bunches.
6251 If PROCESS is a non-blocking network process that hasn't been fully
6252 set up yet, this function will block until socket setup has completed. */)
6253 (Lisp_Object process
, Lisp_Object string
)
6255 CHECK_STRING (string
);
6256 Lisp_Object proc
= get_process (process
);
6257 send_process (proc
, SSDATA (string
),
6258 SBYTES (string
), string
);
6262 /* Return the foreground process group for the tty/pty that
6263 the process P uses. */
6265 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6270 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6273 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6274 master side. Try the slave side. */
6275 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6279 ioctl (fd
, TIOCGPGRP
, &gid
);
6283 #endif /* defined (TIOCGPGRP ) */
6288 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6289 Sprocess_running_child_p
, 0, 1, 0,
6290 doc
: /* Return non-nil if PROCESS has given the terminal to a
6291 child. If the operating system does not make it possible to find out,
6292 return t. If we can find out, return the numeric ID of the foreground
6294 (Lisp_Object process
)
6296 /* Initialize in case ioctl doesn't exist or gives an error,
6297 in a way that will cause returning t. */
6298 Lisp_Object proc
= get_process (process
);
6299 struct Lisp_Process
*p
= XPROCESS (proc
);
6301 if (!EQ (p
->type
, Qreal
))
6302 error ("Process %s is not a subprocess",
6305 error ("Process %s is not active",
6308 pid_t gid
= emacs_get_tty_pgrp (p
);
6313 return make_number (gid
);
6317 /* Send a signal number SIGNO to PROCESS.
6318 If CURRENT_GROUP is t, that means send to the process group
6319 that currently owns the terminal being used to communicate with PROCESS.
6320 This is used for various commands in shell mode.
6321 If CURRENT_GROUP is lambda, that means send to the process group
6322 that currently owns the terminal, but only if it is NOT the shell itself.
6324 If NOMSG is false, insert signal-announcements into process's buffers
6327 If we can, we try to signal PROCESS by sending control characters
6328 down the pty. This allows us to signal inferiors who have changed
6329 their uid, for which kill would return an EPERM error. */
6332 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6336 struct Lisp_Process
*p
;
6340 proc
= get_process (process
);
6341 p
= XPROCESS (proc
);
6343 if (!EQ (p
->type
, Qreal
))
6344 error ("Process %s is not a subprocess",
6347 error ("Process %s is not active",
6351 current_group
= Qnil
;
6353 /* If we are using pgrps, get a pgrp number and make it negative. */
6354 if (NILP (current_group
))
6355 /* Send the signal to the shell's process group. */
6359 #ifdef SIGNALS_VIA_CHARACTERS
6360 /* If possible, send signals to the entire pgrp
6361 by sending an input character to it. */
6364 cc_t
*sig_char
= NULL
;
6366 tcgetattr (p
->infd
, &t
);
6371 sig_char
= &t
.c_cc
[VINTR
];
6375 sig_char
= &t
.c_cc
[VQUIT
];
6380 sig_char
= &t
.c_cc
[VSWTCH
];
6382 sig_char
= &t
.c_cc
[VSUSP
];
6387 if (sig_char
&& *sig_char
!= CDISABLE
)
6389 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6392 /* If we can't send the signal with a character,
6393 fall through and send it another way. */
6395 /* The code above may fall through if it can't
6396 handle the signal. */
6397 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6400 /* Get the current pgrp using the tty itself, if we have that.
6401 Otherwise, use the pty to get the pgrp.
6402 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6403 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6404 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6405 His patch indicates that if TIOCGPGRP returns an error, then
6406 we should just assume that p->pid is also the process group id. */
6408 gid
= emacs_get_tty_pgrp (p
);
6411 /* If we can't get the information, assume
6412 the shell owns the tty. */
6415 /* It is not clear whether anything really can set GID to -1.
6416 Perhaps on some system one of those ioctls can or could do so.
6417 Or perhaps this is vestigial. */
6420 #else /* ! defined (TIOCGPGRP) */
6421 /* Can't select pgrps on this system, so we know that
6422 the child itself heads the pgrp. */
6424 #endif /* ! defined (TIOCGPGRP) */
6426 /* If current_group is lambda, and the shell owns the terminal,
6427 don't send any signal. */
6428 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6433 if (signo
== SIGCONT
)
6435 p
->raw_status_new
= 0;
6436 pset_status (p
, Qrun
);
6437 p
->tick
= ++process_tick
;
6440 status_notify (NULL
, NULL
);
6441 redisplay_preserve_echo_area (13);
6447 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6448 We don't know whether the bug is fixed in later HP-UX versions. */
6449 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6453 /* If we don't have process groups, send the signal to the immediate
6454 subprocess. That isn't really right, but it's better than any
6455 obvious alternative. */
6456 pid_t pid
= no_pgrp
? gid
: - gid
;
6458 /* Do not kill an already-reaped process, as that could kill an
6459 innocent bystander that happens to have the same process ID. */
6461 block_child_signal (&oldset
);
6464 unblock_child_signal (&oldset
);
6467 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6468 doc
: /* Interrupt process PROCESS.
6469 PROCESS may be a process, a buffer, or the name of a process or buffer.
6470 No arg or nil means current buffer's process.
6471 Second arg CURRENT-GROUP non-nil means send signal to
6472 the current process-group of the process's controlling terminal
6473 rather than to the process's own process group.
6474 If the process is a shell, this means interrupt current subjob
6475 rather than the shell.
6477 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6478 don't send the signal. */)
6479 (Lisp_Object process
, Lisp_Object current_group
)
6481 process_send_signal (process
, SIGINT
, current_group
, 0);
6485 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6486 doc
: /* Kill process PROCESS. May be process or name of one.
6487 See function `interrupt-process' for more details on usage. */)
6488 (Lisp_Object process
, Lisp_Object current_group
)
6490 process_send_signal (process
, SIGKILL
, current_group
, 0);
6494 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6495 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6496 See function `interrupt-process' for more details on usage. */)
6497 (Lisp_Object process
, Lisp_Object current_group
)
6499 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6503 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6504 doc
: /* Stop process PROCESS. May be process or name of one.
6505 See function `interrupt-process' for more details on usage.
6506 If PROCESS is a network or serial process, inhibit handling of incoming
6508 (Lisp_Object process
, Lisp_Object current_group
)
6510 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6511 || PIPECONN_P (process
)))
6513 struct Lisp_Process
*p
;
6515 p
= XPROCESS (process
);
6516 if (NILP (p
->command
)
6519 FD_CLR (p
->infd
, &input_wait_mask
);
6520 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6522 pset_command (p
, Qt
);
6526 error ("No SIGTSTP support");
6528 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6533 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6534 doc
: /* Continue process PROCESS. May be process or name of one.
6535 See function `interrupt-process' for more details on usage.
6536 If PROCESS is a network or serial process, resume handling of incoming
6538 (Lisp_Object process
, Lisp_Object current_group
)
6540 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6541 || PIPECONN_P (process
)))
6543 struct Lisp_Process
*p
;
6545 p
= XPROCESS (process
);
6546 if (EQ (p
->command
, Qt
)
6548 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6550 FD_SET (p
->infd
, &input_wait_mask
);
6551 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6553 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6554 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6555 #else /* not WINDOWSNT */
6556 tcflush (p
->infd
, TCIFLUSH
);
6557 #endif /* not WINDOWSNT */
6559 pset_command (p
, Qnil
);
6563 process_send_signal (process
, SIGCONT
, current_group
, 0);
6565 error ("No SIGCONT support");
6570 /* Return the integer value of the signal whose abbreviation is ABBR,
6571 or a negative number if there is no such signal. */
6573 abbr_to_signal (char const *name
)
6576 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6578 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6581 for (i
= 0; i
< sizeof sigbuf
; i
++)
6583 sigbuf
[i
] = c_toupper (name
[i
]);
6585 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6591 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6592 2, 2, "sProcess (name or number): \nnSignal code: ",
6593 doc
: /* Send PROCESS the signal with code SIGCODE.
6594 PROCESS may also be a number specifying the process id of the
6595 process to signal; in this case, the process need not be a child of
6597 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6598 (Lisp_Object process
, Lisp_Object sigcode
)
6603 if (STRINGP (process
))
6605 Lisp_Object tem
= Fget_process (process
);
6608 Lisp_Object process_number
6609 = string_to_number (SSDATA (process
), 10, 1);
6610 if (NUMBERP (process_number
))
6611 tem
= process_number
;
6615 else if (!NUMBERP (process
))
6616 process
= get_process (process
);
6621 if (NUMBERP (process
))
6622 CONS_TO_INTEGER (process
, pid_t
, pid
);
6625 CHECK_PROCESS (process
);
6626 pid
= XPROCESS (process
)->pid
;
6628 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6631 if (INTEGERP (sigcode
))
6633 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6634 signo
= XINT (sigcode
);
6640 CHECK_SYMBOL (sigcode
);
6641 name
= SSDATA (SYMBOL_NAME (sigcode
));
6643 signo
= abbr_to_signal (name
);
6645 error ("Undefined signal name %s", name
);
6648 return make_number (kill (pid
, signo
));
6651 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6652 doc
: /* Make PROCESS see end-of-file in its input.
6653 EOF comes after any text already sent to it.
6654 PROCESS may be a process, a buffer, the name of a process or buffer, or
6655 nil, indicating the current buffer's process.
6656 If PROCESS is a network connection, or is a process communicating
6657 through a pipe (as opposed to a pty), then you cannot send any more
6658 text to PROCESS after you call this function.
6659 If PROCESS is a serial process, wait until all output written to the
6660 process has been transmitted to the serial port. */)
6661 (Lisp_Object process
)
6664 struct coding_system
*coding
= NULL
;
6667 proc
= get_process (process
);
6669 if (NETCONN_P (proc
))
6670 wait_while_connecting (proc
);
6672 if (DATAGRAM_CONN_P (proc
))
6676 outfd
= XPROCESS (proc
)->outfd
;
6678 coding
= proc_encode_coding_system
[outfd
];
6680 /* Make sure the process is really alive. */
6681 if (XPROCESS (proc
)->raw_status_new
)
6682 update_status (XPROCESS (proc
));
6683 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6684 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6686 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6688 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6689 send_process (proc
, "", 0, Qnil
);
6692 if (XPROCESS (proc
)->pty_flag
)
6693 send_process (proc
, "\004", 1, Qnil
);
6694 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6697 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6698 report_file_error ("Failed tcdrain", Qnil
);
6699 #endif /* not WINDOWSNT */
6700 /* Do nothing on Windows because writes are blocking. */
6704 struct Lisp_Process
*p
= XPROCESS (proc
);
6705 int old_outfd
= p
->outfd
;
6708 #ifdef HAVE_SHUTDOWN
6709 /* If this is a network connection, or socketpair is used
6710 for communication with the subprocess, call shutdown to cause EOF.
6711 (In some old system, shutdown to socketpair doesn't work.
6712 Then we just can't win.) */
6714 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6715 shutdown (old_outfd
, 1);
6717 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6718 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6720 report_file_error ("Opening null device", Qnil
);
6721 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6722 p
->outfd
= new_outfd
;
6724 if (!proc_encode_coding_system
[new_outfd
])
6725 proc_encode_coding_system
[new_outfd
]
6726 = xmalloc (sizeof (struct coding_system
));
6729 *proc_encode_coding_system
[new_outfd
]
6730 = *proc_encode_coding_system
[old_outfd
];
6731 memset (proc_encode_coding_system
[old_outfd
], 0,
6732 sizeof (struct coding_system
));
6735 setup_coding_system (p
->encode_coding_system
,
6736 proc_encode_coding_system
[new_outfd
]);
6741 /* The main Emacs thread records child processes in three places:
6743 - Vprocess_alist, for asynchronous subprocesses, which are child
6744 processes visible to Lisp.
6746 - deleted_pid_list, for child processes invisible to Lisp,
6747 typically because of delete-process. These are recorded so that
6748 the processes can be reaped when they exit, so that the operating
6749 system's process table is not cluttered by zombies.
6751 - the local variable PID in Fcall_process, call_process_cleanup and
6752 call_process_kill, for synchronous subprocesses.
6753 record_unwind_protect is used to make sure this process is not
6754 forgotten: if the user interrupts call-process and the child
6755 process refuses to exit immediately even with two C-g's,
6756 call_process_kill adds PID's contents to deleted_pid_list before
6759 The main Emacs thread invokes waitpid only on child processes that
6760 it creates and that have not been reaped. This avoid races on
6761 platforms such as GTK, where other threads create their own
6762 subprocesses which the main thread should not reap. For example,
6763 if the main thread attempted to reap an already-reaped child, it
6764 might inadvertently reap a GTK-created process that happened to
6765 have the same process ID. */
6767 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6768 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6769 keep track of its own children. GNUstep is similar. */
6771 static void dummy_handler (int sig
) {}
6772 static signal_handler_t
volatile lib_child_handler
;
6774 /* Handle a SIGCHLD signal by looking for known child processes of
6775 Emacs whose status have changed. For each one found, record its
6778 All we do is change the status; we do not run sentinels or print
6779 notifications. That is saved for the next time keyboard input is
6780 done, in order to avoid timing errors.
6782 ** WARNING: this can be called during garbage collection.
6783 Therefore, it must not be fooled by the presence of mark bits in
6786 ** USG WARNING: Although it is not obvious from the documentation
6787 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6788 signal() before executing at least one wait(), otherwise the
6789 handler will be called again, resulting in an infinite loop. The
6790 relevant portion of the documentation reads "SIGCLD signals will be
6791 queued and the signal-catching function will be continually
6792 reentered until the queue is empty". Invoking signal() causes the
6793 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6796 ** Malloc WARNING: This should never call malloc either directly or
6797 indirectly; if it does, that is a bug. */
6800 handle_child_signal (int sig
)
6802 Lisp_Object tail
, proc
;
6804 /* Find the process that signaled us, and record its status. */
6806 /* The process can have been deleted by Fdelete_process, or have
6807 been started asynchronously by Fcall_process. */
6808 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6810 bool all_pids_are_fixnums
6811 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6812 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6813 Lisp_Object head
= XCAR (tail
);
6818 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6821 if (INTEGERP (xpid
))
6822 deleted_pid
= XINT (xpid
);
6824 deleted_pid
= XFLOAT_DATA (xpid
);
6825 if (child_status_changed (deleted_pid
, 0, 0))
6827 if (STRINGP (XCDR (head
)))
6828 unlink (SSDATA (XCDR (head
)));
6829 XSETCAR (tail
, Qnil
);
6834 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6835 FOR_EACH_PROCESS (tail
, proc
)
6837 struct Lisp_Process
*p
= XPROCESS (proc
);
6841 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6843 /* Change the status of the process that was found. */
6844 p
->tick
= ++process_tick
;
6845 p
->raw_status
= status
;
6846 p
->raw_status_new
= 1;
6848 /* If process has terminated, stop waiting for its output. */
6849 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6851 bool clear_desc_flag
= 0;
6854 clear_desc_flag
= 1;
6856 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6857 if (clear_desc_flag
)
6859 FD_CLR (p
->infd
, &input_wait_mask
);
6860 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6866 lib_child_handler (sig
);
6867 #ifdef NS_IMPL_GNUSTEP
6868 /* NSTask in GNUstep sets its child handler each time it is called.
6869 So we must re-set ours. */
6870 catch_child_signal ();
6875 deliver_child_signal (int sig
)
6877 deliver_process_signal (sig
, handle_child_signal
);
6882 exec_sentinel_error_handler (Lisp_Object error_val
)
6884 cmd_error_internal (error_val
, "error in process sentinel: ");
6886 update_echo_area ();
6887 Fsleep_for (make_number (2), Qnil
);
6892 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6894 Lisp_Object sentinel
, odeactivate
;
6895 struct Lisp_Process
*p
= XPROCESS (proc
);
6896 ptrdiff_t count
= SPECPDL_INDEX ();
6897 bool outer_running_asynch_code
= running_asynch_code
;
6898 int waiting
= waiting_for_user_input_p
;
6900 if (inhibit_sentinels
)
6903 odeactivate
= Vdeactivate_mark
;
6905 Lisp_Object obuffer
, okeymap
;
6906 XSETBUFFER (obuffer
, current_buffer
);
6907 okeymap
= BVAR (current_buffer
, keymap
);
6910 /* There's no good reason to let sentinels change the current
6911 buffer, and many callers of accept-process-output, sit-for, and
6912 friends don't expect current-buffer to be changed from under them. */
6913 record_unwind_current_buffer ();
6915 sentinel
= p
->sentinel
;
6917 /* Inhibit quit so that random quits don't screw up a running filter. */
6918 specbind (Qinhibit_quit
, Qt
);
6919 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6921 /* In case we get recursively called,
6922 and we already saved the match data nonrecursively,
6923 save the same match data in safely recursive fashion. */
6924 if (outer_running_asynch_code
)
6927 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6928 restore_search_regs ();
6929 record_unwind_save_match_data ();
6930 Fset_match_data (tem
, Qt
);
6933 /* For speed, if a search happens within this code,
6934 save the match data in a special nonrecursive fashion. */
6935 running_asynch_code
= 1;
6937 internal_condition_case_1 (read_process_output_call
,
6938 list3 (sentinel
, proc
, reason
),
6939 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6940 exec_sentinel_error_handler
);
6942 /* If we saved the match data nonrecursively, restore it now. */
6943 restore_search_regs ();
6944 running_asynch_code
= outer_running_asynch_code
;
6946 Vdeactivate_mark
= odeactivate
;
6948 /* Restore waiting_for_user_input_p as it was
6949 when we were called, in case the filter clobbered it. */
6950 waiting_for_user_input_p
= waiting
;
6953 if (! EQ (Fcurrent_buffer (), obuffer
)
6954 || ! EQ (current_buffer
->keymap
, okeymap
))
6956 /* But do it only if the caller is actually going to read events.
6957 Otherwise there's no need to make him wake up, and it could
6958 cause trouble (for example it would make sit_for return). */
6959 if (waiting_for_user_input_p
== -1)
6960 record_asynch_buffer_change ();
6962 unbind_to (count
, Qnil
);
6965 /* Report all recent events of a change in process status
6966 (either run the sentinel or output a message).
6967 This is usually done while Emacs is waiting for keyboard input
6968 but can be done at other times.
6970 Return positive if any input was received from WAIT_PROC (or from
6971 any process if WAIT_PROC is null), zero if input was attempted but
6972 none received, and negative if we didn't even try. */
6975 status_notify (struct Lisp_Process
*deleting_process
,
6976 struct Lisp_Process
*wait_proc
)
6979 Lisp_Object tail
, msg
;
6980 int got_some_output
= -1;
6985 /* Set this now, so that if new processes are created by sentinels
6986 that we run, we get called again to handle their status changes. */
6987 update_tick
= process_tick
;
6989 FOR_EACH_PROCESS (tail
, proc
)
6992 register struct Lisp_Process
*p
= XPROCESS (proc
);
6994 if (p
->tick
!= p
->update_tick
)
6996 p
->update_tick
= p
->tick
;
6998 /* If process is still active, read any output that remains. */
6999 while (! EQ (p
->filter
, Qt
)
7000 && ! EQ (p
->status
, Qconnect
)
7001 && ! EQ (p
->status
, Qlisten
)
7002 /* Network or serial process not stopped: */
7003 && ! EQ (p
->command
, Qt
)
7005 && p
!= deleting_process
)
7007 int nread
= read_process_output (proc
, p
->infd
);
7008 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7009 && got_some_output
< nread
)
7010 got_some_output
= nread
;
7015 /* Get the text to use for the message. */
7016 if (p
->raw_status_new
)
7018 msg
= status_message (p
);
7020 /* If process is terminated, deactivate it or delete it. */
7022 if (CONSP (p
->status
))
7023 symbol
= XCAR (p
->status
);
7025 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7026 || EQ (symbol
, Qclosed
))
7028 if (delete_exited_processes
)
7029 remove_process (proc
);
7031 deactivate_process (proc
);
7034 /* The actions above may have further incremented p->tick.
7035 So set p->update_tick again so that an error in the sentinel will
7036 not cause this code to be run again. */
7037 p
->update_tick
= p
->tick
;
7038 /* Now output the message suitably. */
7039 exec_sentinel (proc
, msg
);
7040 if (BUFFERP (p
->buffer
))
7041 /* In case it uses %s in mode-line-format. */
7042 bset_update_mode_line (XBUFFER (p
->buffer
));
7046 return got_some_output
;
7049 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7050 Sinternal_default_process_sentinel
, 2, 2, 0,
7051 doc
: /* Function used as default sentinel for processes.
7052 This inserts a status message into the process's buffer, if there is one. */)
7053 (Lisp_Object proc
, Lisp_Object msg
)
7055 Lisp_Object buffer
, symbol
;
7056 struct Lisp_Process
*p
;
7057 CHECK_PROCESS (proc
);
7058 p
= XPROCESS (proc
);
7062 symbol
= XCAR (symbol
);
7064 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7067 struct buffer
*old
= current_buffer
;
7068 ptrdiff_t opoint
, opoint_byte
;
7069 ptrdiff_t before
, before_byte
;
7071 /* Avoid error if buffer is deleted
7072 (probably that's why the process is dead, too). */
7073 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7075 Fset_buffer (buffer
);
7077 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7078 msg
= (code_convert_string_norecord
7079 (msg
, Vlocale_coding_system
, 1));
7082 opoint_byte
= PT_BYTE
;
7083 /* Insert new output into buffer
7084 at the current end-of-output marker,
7085 thus preserving logical ordering of input and output. */
7086 if (XMARKER (p
->mark
)->buffer
)
7087 Fgoto_char (p
->mark
);
7089 SET_PT_BOTH (ZV
, ZV_BYTE
);
7092 before_byte
= PT_BYTE
;
7094 tem
= BVAR (current_buffer
, read_only
);
7095 bset_read_only (current_buffer
, Qnil
);
7096 insert_string ("\nProcess ");
7097 { /* FIXME: temporary kludge. */
7098 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7099 insert_string (" ");
7101 bset_read_only (current_buffer
, tem
);
7102 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7104 if (opoint
>= before
)
7105 SET_PT_BOTH (opoint
+ (PT
- before
),
7106 opoint_byte
+ (PT_BYTE
- before_byte
));
7108 SET_PT_BOTH (opoint
, opoint_byte
);
7110 set_buffer_internal (old
);
7116 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7117 Sset_process_coding_system
, 1, 3, 0,
7118 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7119 DECODING will be used to decode subprocess output and ENCODING to
7120 encode subprocess input. */)
7121 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7123 CHECK_PROCESS (process
);
7125 struct Lisp_Process
*p
= XPROCESS (process
);
7127 Fcheck_coding_system (decoding
);
7128 Fcheck_coding_system (encoding
);
7129 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7130 pset_decode_coding_system (p
, decoding
);
7131 pset_encode_coding_system (p
, encoding
);
7133 /* If the sockets haven't been set up yet, the final setup part of
7134 this will be called asynchronously. */
7135 if (p
->infd
< 0 || p
->outfd
< 0)
7138 setup_process_coding_systems (process
);
7143 DEFUN ("process-coding-system",
7144 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7145 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7146 (register Lisp_Object process
)
7148 CHECK_PROCESS (process
);
7149 return Fcons (XPROCESS (process
)->decode_coding_system
,
7150 XPROCESS (process
)->encode_coding_system
);
7153 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7154 Sset_process_filter_multibyte
, 2, 2, 0,
7155 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7156 If FLAG is non-nil, the filter is given multibyte strings.
7157 If FLAG is nil, the filter is given unibyte strings. In this case,
7158 all character code conversion except for end-of-line conversion is
7160 (Lisp_Object process
, Lisp_Object flag
)
7162 CHECK_PROCESS (process
);
7164 struct Lisp_Process
*p
= XPROCESS (process
);
7166 pset_decode_coding_system
7167 (p
, raw_text_coding_system (p
->decode_coding_system
));
7169 /* If the sockets haven't been set up yet, the final setup part of
7170 this will be called asynchronously. */
7171 if (p
->infd
< 0 || p
->outfd
< 0)
7174 setup_process_coding_systems (process
);
7179 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7180 Sprocess_filter_multibyte_p
, 1, 1, 0,
7181 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7182 (Lisp_Object process
)
7184 CHECK_PROCESS (process
);
7185 struct Lisp_Process
*p
= XPROCESS (process
);
7188 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7189 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7198 add_gpm_wait_descriptor (int desc
)
7200 add_keyboard_wait_descriptor (desc
);
7204 delete_gpm_wait_descriptor (int desc
)
7206 delete_keyboard_wait_descriptor (desc
);
7211 # ifdef USABLE_SIGIO
7213 /* Return true if *MASK has a bit set
7214 that corresponds to one of the keyboard input descriptors. */
7217 keyboard_bit_set (fd_set
*mask
)
7221 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7222 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7223 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7230 #else /* not subprocesses */
7232 /* Defined in msdos.c. */
7233 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7234 struct timespec
*, void *);
7236 /* Implementation of wait_reading_process_output, assuming that there
7237 are no subprocesses. Used only by the MS-DOS build.
7239 Wait for timeout to elapse and/or keyboard input to be available.
7243 If negative, gobble data immediately available but don't wait for any.
7246 an additional duration to wait, measured in nanoseconds
7247 If TIME_LIMIT is zero, then:
7248 If NSECS == 0, there is no limit.
7249 If NSECS > 0, the timeout consists of NSECS only.
7250 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7253 0 to ignore keyboard input, or
7254 1 to return when input is available, or
7255 -1 means caller will actually read the input, so don't throw to
7258 see full version for other parameters. We know that wait_proc will
7259 always be NULL, since `subprocesses' isn't defined.
7261 DO_DISPLAY means redisplay should be done to show subprocess
7262 output that arrives.
7264 Return -1 signifying we got no output and did not try. */
7267 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7269 Lisp_Object wait_for_cell
,
7270 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7273 struct timespec end_time
, timeout
;
7274 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7276 if (TYPE_MAXIMUM (time_t) < time_limit
)
7277 time_limit
= TYPE_MAXIMUM (time_t);
7279 if (time_limit
< 0 || nsecs
< 0)
7281 else if (time_limit
> 0 || nsecs
> 0)
7284 end_time
= timespec_add (current_timespec (),
7285 make_timespec (time_limit
, nsecs
));
7290 /* Turn off periodic alarms (in case they are in use)
7291 and then turn off any other atimers,
7292 because the select emulator uses alarms. */
7294 turn_on_atimers (0);
7298 bool timeout_reduced_for_timers
= false;
7299 fd_set waitchannels
;
7302 /* If calling from keyboard input, do not quit
7303 since we want to return C-g as an input character.
7304 Otherwise, do pending quit if requested. */
7308 /* Exit now if the cell we're waiting for became non-nil. */
7309 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7312 /* Compute time from now till when time limit is up. */
7313 /* Exit if already run out. */
7314 if (wait
== TIMEOUT
)
7316 struct timespec now
= current_timespec ();
7317 if (timespec_cmp (end_time
, now
) <= 0)
7319 timeout
= timespec_sub (end_time
, now
);
7322 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7324 /* If our caller will not immediately handle keyboard events,
7325 run timer events directly.
7326 (Callers that will immediately read keyboard events
7327 call timer_delay on their own.) */
7328 if (NILP (wait_for_cell
))
7330 struct timespec timer_delay
;
7334 unsigned old_timers_run
= timers_run
;
7335 timer_delay
= timer_check ();
7336 if (timers_run
!= old_timers_run
&& do_display
)
7337 /* We must retry, since a timer may have requeued itself
7338 and that could alter the time delay. */
7339 redisplay_preserve_echo_area (14);
7343 while (!detect_input_pending ());
7345 /* If there is unread keyboard input, also return. */
7347 && requeued_events_pending_p ())
7350 if (timespec_valid_p (timer_delay
))
7352 if (timespec_cmp (timer_delay
, timeout
) < 0)
7354 timeout
= timer_delay
;
7355 timeout_reduced_for_timers
= true;
7360 /* Cause C-g and alarm signals to take immediate action,
7361 and cause input available signals to zero out timeout. */
7363 set_waiting_for_input (&timeout
);
7365 /* If a frame has been newly mapped and needs updating,
7366 reprocess its display stuff. */
7367 if (frame_garbaged
&& do_display
)
7369 clear_waiting_for_input ();
7370 redisplay_preserve_echo_area (15);
7372 set_waiting_for_input (&timeout
);
7375 /* Wait till there is something to do. */
7376 FD_ZERO (&waitchannels
);
7377 if (read_kbd
&& detect_input_pending ())
7381 if (read_kbd
|| !NILP (wait_for_cell
))
7382 FD_SET (0, &waitchannels
);
7383 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7388 /* Make C-g and alarm signals set flags again. */
7389 clear_waiting_for_input ();
7391 /* If we woke up due to SIGWINCH, actually change size now. */
7392 do_pending_window_change (0);
7394 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7395 /* We waited the full specified time, so return now. */
7400 /* If the system call was interrupted, then go around the
7402 if (xerrno
== EINTR
)
7403 FD_ZERO (&waitchannels
);
7405 report_file_errno ("Failed select", Qnil
, xerrno
);
7408 /* Check for keyboard input. */
7411 && detect_input_pending_run_timers (do_display
))
7413 swallow_events (do_display
);
7414 if (detect_input_pending_run_timers (do_display
))
7418 /* If there is unread keyboard input, also return. */
7420 && requeued_events_pending_p ())
7423 /* If wait_for_cell. check for keyboard input
7424 but don't run any timers.
7425 ??? (It seems wrong to me to check for keyboard
7426 input at all when wait_for_cell, but the code
7427 has been this way since July 1994.
7428 Try changing this after version 19.31.) */
7429 if (! NILP (wait_for_cell
)
7430 && detect_input_pending ())
7432 swallow_events (do_display
);
7433 if (detect_input_pending ())
7437 /* Exit now if the cell we're waiting for became non-nil. */
7438 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7447 #endif /* not subprocesses */
7449 /* The following functions are needed even if async subprocesses are
7450 not supported. Some of them are no-op stubs in that case. */
7454 /* Add FD, which is a descriptor returned by timerfd_create,
7455 to the set of non-keyboard input descriptors. */
7458 add_timer_wait_descriptor (int fd
)
7460 FD_SET (fd
, &input_wait_mask
);
7461 FD_SET (fd
, &non_keyboard_wait_mask
);
7462 FD_SET (fd
, &non_process_wait_mask
);
7463 fd_callback_info
[fd
].func
= timerfd_callback
;
7464 fd_callback_info
[fd
].data
= NULL
;
7465 fd_callback_info
[fd
].condition
|= FOR_READ
;
7466 if (fd
> max_input_desc
)
7467 max_input_desc
= fd
;
7470 #endif /* HAVE_TIMERFD */
7472 /* If program file NAME starts with /: for quoting a magic
7473 name, remove that, preserving the multibyteness of NAME. */
7476 remove_slash_colon (Lisp_Object name
)
7479 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7480 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7481 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7485 /* Add DESC to the set of keyboard input descriptors. */
7488 add_keyboard_wait_descriptor (int desc
)
7490 #ifdef subprocesses /* Actually means "not MSDOS". */
7491 FD_SET (desc
, &input_wait_mask
);
7492 FD_SET (desc
, &non_process_wait_mask
);
7493 if (desc
> max_input_desc
)
7494 max_input_desc
= desc
;
7498 /* From now on, do not expect DESC to give keyboard input. */
7501 delete_keyboard_wait_descriptor (int desc
)
7504 FD_CLR (desc
, &input_wait_mask
);
7505 FD_CLR (desc
, &non_process_wait_mask
);
7506 delete_input_desc (desc
);
7510 /* Setup coding systems of PROCESS. */
7513 setup_process_coding_systems (Lisp_Object process
)
7516 struct Lisp_Process
*p
= XPROCESS (process
);
7518 int outch
= p
->outfd
;
7519 Lisp_Object coding_system
;
7521 if (inch
< 0 || outch
< 0)
7524 if (!proc_decode_coding_system
[inch
])
7525 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7526 coding_system
= p
->decode_coding_system
;
7527 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7528 && BUFFERP (p
->buffer
))
7530 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7531 coding_system
= raw_text_coding_system (coding_system
);
7533 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7535 if (!proc_encode_coding_system
[outch
])
7536 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7537 setup_coding_system (p
->encode_coding_system
,
7538 proc_encode_coding_system
[outch
]);
7542 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7543 doc
: /* Return the (or a) live process associated with BUFFER.
7544 BUFFER may be a buffer or the name of one.
7545 Return nil if all processes associated with BUFFER have been
7546 deleted or killed. */)
7547 (register Lisp_Object buffer
)
7550 register Lisp_Object buf
, tail
, proc
;
7552 if (NILP (buffer
)) return Qnil
;
7553 buf
= Fget_buffer (buffer
);
7554 if (NILP (buf
)) return Qnil
;
7556 FOR_EACH_PROCESS (tail
, proc
)
7557 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7559 #endif /* subprocesses */
7563 DEFUN ("process-inherit-coding-system-flag",
7564 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7566 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7567 If this flag is t, `buffer-file-coding-system' of the buffer
7568 associated with PROCESS will inherit the coding system used to decode
7569 the process output. */)
7570 (register Lisp_Object process
)
7573 CHECK_PROCESS (process
);
7574 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7576 /* Ignore the argument and return the value of
7577 inherit-process-coding-system. */
7578 return inherit_process_coding_system
? Qt
: Qnil
;
7582 /* Kill all processes associated with `buffer'.
7583 If `buffer' is nil, kill all processes. */
7586 kill_buffer_processes (Lisp_Object buffer
)
7589 Lisp_Object tail
, proc
;
7591 FOR_EACH_PROCESS (tail
, proc
)
7592 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7594 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7595 Fdelete_process (proc
);
7596 else if (XPROCESS (proc
)->infd
>= 0)
7597 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7599 #else /* subprocesses */
7600 /* Since we have no subprocesses, this does nothing. */
7601 #endif /* subprocesses */
7604 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7605 Swaiting_for_user_input_p
, 0, 0, 0,
7606 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7607 This is intended for use by asynchronous process output filters and sentinels. */)
7611 return (waiting_for_user_input_p
? Qt
: Qnil
);
7617 /* Stop reading input from keyboard sources. */
7620 hold_keyboard_input (void)
7625 /* Resume reading input from keyboard sources. */
7628 unhold_keyboard_input (void)
7633 /* Return true if keyboard input is on hold, zero otherwise. */
7636 kbd_on_hold_p (void)
7638 return kbd_is_on_hold
;
7642 /* Enumeration of and access to system processes a-la ps(1). */
7644 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7646 doc
: /* Return a list of numerical process IDs of all running processes.
7647 If this functionality is unsupported, return nil.
7649 See `process-attributes' for getting attributes of a process given its ID. */)
7652 return list_system_processes ();
7655 DEFUN ("process-attributes", Fprocess_attributes
,
7656 Sprocess_attributes
, 1, 1, 0,
7657 doc
: /* Return attributes of the process given by its PID, a number.
7659 Value is an alist where each element is a cons cell of the form
7663 If this functionality is unsupported, the value is nil.
7665 See `list-system-processes' for getting a list of all process IDs.
7667 The KEYs of the attributes that this function may return are listed
7668 below, together with the type of the associated VALUE (in parentheses).
7669 Not all platforms support all of these attributes; unsupported
7670 attributes will not appear in the returned alist.
7671 Unless explicitly indicated otherwise, numbers can have either
7672 integer or floating point values.
7674 euid -- Effective user User ID of the process (number)
7675 user -- User name corresponding to euid (string)
7676 egid -- Effective user Group ID of the process (number)
7677 group -- Group name corresponding to egid (string)
7678 comm -- Command name (executable name only) (string)
7679 state -- Process state code, such as "S", "R", or "T" (string)
7680 ppid -- Parent process ID (number)
7681 pgrp -- Process group ID (number)
7682 sess -- Session ID, i.e. process ID of session leader (number)
7683 ttname -- Controlling tty name (string)
7684 tpgid -- ID of foreground process group on the process's tty (number)
7685 minflt -- number of minor page faults (number)
7686 majflt -- number of major page faults (number)
7687 cminflt -- cumulative number of minor page faults (number)
7688 cmajflt -- cumulative number of major page faults (number)
7689 utime -- user time used by the process, in (current-time) format,
7690 which is a list of integers (HIGH LOW USEC PSEC)
7691 stime -- system time used by the process (current-time)
7692 time -- sum of utime and stime (current-time)
7693 cutime -- user time used by the process and its children (current-time)
7694 cstime -- system time used by the process and its children (current-time)
7695 ctime -- sum of cutime and cstime (current-time)
7696 pri -- priority of the process (number)
7697 nice -- nice value of the process (number)
7698 thcount -- process thread count (number)
7699 start -- time the process started (current-time)
7700 vsize -- virtual memory size of the process in KB's (number)
7701 rss -- resident set size of the process in KB's (number)
7702 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7703 pcpu -- percents of CPU time used by the process (floating-point number)
7704 pmem -- percents of total physical memory used by process's resident set
7705 (floating-point number)
7706 args -- command line which invoked the process (string). */)
7709 return system_process_attributes (pid
);
7713 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7714 Invoke this after init_process_emacs, and after glib and/or GNUstep
7715 futz with the SIGCHLD handler, but before Emacs forks any children.
7716 This function's caller should block SIGCHLD. */
7719 catch_child_signal (void)
7721 struct sigaction action
, old_action
;
7723 emacs_sigaction_init (&action
, deliver_child_signal
);
7724 block_child_signal (&oldset
);
7725 sigaction (SIGCHLD
, &action
, &old_action
);
7726 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7727 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7729 if (old_action
.sa_handler
!= deliver_child_signal
)
7731 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7733 : old_action
.sa_handler
);
7734 unblock_child_signal (&oldset
);
7736 #endif /* subprocesses */
7739 /* This is not called "init_process" because that is the name of a
7740 Mach system call, so it would cause problems on Darwin systems. */
7742 init_process_emacs (int sockfd
)
7747 inhibit_sentinels
= 0;
7750 if (! noninteractive
|| initialized
)
7753 #if defined HAVE_GLIB && !defined WINDOWSNT
7754 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7755 this should always fail, but is enough to initialize glib's
7756 private SIGCHLD handler, allowing catch_child_signal to copy
7757 it into lib_child_handler. */
7758 g_source_unref (g_child_watch_source_new (getpid ()));
7760 catch_child_signal ();
7763 FD_ZERO (&input_wait_mask
);
7764 FD_ZERO (&non_keyboard_wait_mask
);
7765 FD_ZERO (&non_process_wait_mask
);
7766 FD_ZERO (&write_mask
);
7767 max_process_desc
= max_input_desc
= -1;
7768 external_sock_fd
= sockfd
;
7769 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7771 FD_ZERO (&connect_wait_mask
);
7772 num_pending_connects
= 0;
7774 process_output_delay_count
= 0;
7775 process_output_skip
= 0;
7777 /* Don't do this, it caused infinite select loops. The display
7778 method should call add_keyboard_wait_descriptor on stdin if it
7781 FD_SET (0, &input_wait_mask
);
7784 Vprocess_alist
= Qnil
;
7785 deleted_pid_list
= Qnil
;
7786 for (i
= 0; i
< FD_SETSIZE
; i
++)
7788 chan_process
[i
] = Qnil
;
7789 proc_buffered_char
[i
] = -1;
7791 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7792 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7793 #ifdef DATAGRAM_SOCKETS
7794 memset (datagram_address
, 0, sizeof datagram_address
);
7797 #if defined (DARWIN_OS)
7798 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7799 processes. As such, we only change the default value. */
7802 char const *release
= (STRINGP (Voperating_system_release
)
7803 ? SSDATA (Voperating_system_release
)
7805 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7806 Vprocess_connection_type
= Qnil
;
7810 #endif /* subprocesses */
7815 syms_of_process (void)
7819 DEFSYM (Qprocessp
, "processp");
7820 DEFSYM (Qrun
, "run");
7821 DEFSYM (Qstop
, "stop");
7822 DEFSYM (Qsignal
, "signal");
7824 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7827 DEFSYM (Qopen
, "open");
7828 DEFSYM (Qclosed
, "closed");
7829 DEFSYM (Qconnect
, "connect");
7830 DEFSYM (Qfailed
, "failed");
7831 DEFSYM (Qlisten
, "listen");
7832 DEFSYM (Qlocal
, "local");
7833 DEFSYM (Qipv4
, "ipv4");
7835 DEFSYM (Qipv6
, "ipv6");
7837 DEFSYM (Qdatagram
, "datagram");
7838 DEFSYM (Qseqpacket
, "seqpacket");
7840 DEFSYM (QCport
, ":port");
7841 DEFSYM (QCspeed
, ":speed");
7842 DEFSYM (QCprocess
, ":process");
7844 DEFSYM (QCbytesize
, ":bytesize");
7845 DEFSYM (QCstopbits
, ":stopbits");
7846 DEFSYM (QCparity
, ":parity");
7847 DEFSYM (Qodd
, "odd");
7848 DEFSYM (Qeven
, "even");
7849 DEFSYM (QCflowcontrol
, ":flowcontrol");
7852 DEFSYM (QCsummary
, ":summary");
7854 DEFSYM (Qreal
, "real");
7855 DEFSYM (Qnetwork
, "network");
7856 DEFSYM (Qserial
, "serial");
7857 DEFSYM (Qpipe
, "pipe");
7858 DEFSYM (QCbuffer
, ":buffer");
7859 DEFSYM (QChost
, ":host");
7860 DEFSYM (QCservice
, ":service");
7861 DEFSYM (QClocal
, ":local");
7862 DEFSYM (QCremote
, ":remote");
7863 DEFSYM (QCcoding
, ":coding");
7864 DEFSYM (QCserver
, ":server");
7865 DEFSYM (QCnowait
, ":nowait");
7866 DEFSYM (QCsentinel
, ":sentinel");
7867 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7868 DEFSYM (QCtls_parameters
, ":tls-parameters");
7869 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7870 DEFSYM (QClog
, ":log");
7871 DEFSYM (QCnoquery
, ":noquery");
7872 DEFSYM (QCstop
, ":stop");
7873 DEFSYM (QCplist
, ":plist");
7874 DEFSYM (QCcommand
, ":command");
7875 DEFSYM (QCconnection_type
, ":connection-type");
7876 DEFSYM (QCstderr
, ":stderr");
7877 DEFSYM (Qpty
, "pty");
7878 DEFSYM (Qpipe
, "pipe");
7880 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7882 staticpro (&Vprocess_alist
);
7883 staticpro (&deleted_pid_list
);
7885 #endif /* subprocesses */
7887 DEFSYM (QCname
, ":name");
7888 DEFSYM (QCtype
, ":type");
7890 DEFSYM (Qeuid
, "euid");
7891 DEFSYM (Qegid
, "egid");
7892 DEFSYM (Quser
, "user");
7893 DEFSYM (Qgroup
, "group");
7894 DEFSYM (Qcomm
, "comm");
7895 DEFSYM (Qstate
, "state");
7896 DEFSYM (Qppid
, "ppid");
7897 DEFSYM (Qpgrp
, "pgrp");
7898 DEFSYM (Qsess
, "sess");
7899 DEFSYM (Qttname
, "ttname");
7900 DEFSYM (Qtpgid
, "tpgid");
7901 DEFSYM (Qminflt
, "minflt");
7902 DEFSYM (Qmajflt
, "majflt");
7903 DEFSYM (Qcminflt
, "cminflt");
7904 DEFSYM (Qcmajflt
, "cmajflt");
7905 DEFSYM (Qutime
, "utime");
7906 DEFSYM (Qstime
, "stime");
7907 DEFSYM (Qtime
, "time");
7908 DEFSYM (Qcutime
, "cutime");
7909 DEFSYM (Qcstime
, "cstime");
7910 DEFSYM (Qctime
, "ctime");
7912 DEFSYM (Qinternal_default_process_sentinel
,
7913 "internal-default-process-sentinel");
7914 DEFSYM (Qinternal_default_process_filter
,
7915 "internal-default-process-filter");
7917 DEFSYM (Qpri
, "pri");
7918 DEFSYM (Qnice
, "nice");
7919 DEFSYM (Qthcount
, "thcount");
7920 DEFSYM (Qstart
, "start");
7921 DEFSYM (Qvsize
, "vsize");
7922 DEFSYM (Qrss
, "rss");
7923 DEFSYM (Qetime
, "etime");
7924 DEFSYM (Qpcpu
, "pcpu");
7925 DEFSYM (Qpmem
, "pmem");
7926 DEFSYM (Qargs
, "args");
7928 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7929 doc
: /* Non-nil means delete processes immediately when they exit.
7930 A value of nil means don't delete them until `list-processes' is run. */);
7932 delete_exited_processes
= 1;
7935 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7936 doc
: /* Control type of device used to communicate with subprocesses.
7937 Values are nil to use a pipe, or t or `pty' to use a pty.
7938 The value has no effect if the system has no ptys or if all ptys are busy:
7939 then a pipe is used in any case.
7940 The value takes effect when `start-process' is called. */);
7941 Vprocess_connection_type
= Qt
;
7943 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7944 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7945 On some systems, when Emacs reads the output from a subprocess, the output data
7946 is read in very small blocks, potentially resulting in very poor performance.
7947 This behavior can be remedied to some extent by setting this variable to a
7948 non-nil value, as it will automatically delay reading from such processes, to
7949 allow them to produce more output before Emacs tries to read it.
7950 If the value is t, the delay is reset after each write to the process; any other
7951 non-nil value means that the delay is not reset on write.
7952 The variable takes effect when `start-process' is called. */);
7953 Vprocess_adaptive_read_buffering
= Qt
;
7955 defsubr (&Sprocessp
);
7956 defsubr (&Sget_process
);
7957 defsubr (&Sdelete_process
);
7958 defsubr (&Sprocess_status
);
7959 defsubr (&Sprocess_exit_status
);
7960 defsubr (&Sprocess_id
);
7961 defsubr (&Sprocess_name
);
7962 defsubr (&Sprocess_tty_name
);
7963 defsubr (&Sprocess_command
);
7964 defsubr (&Sset_process_buffer
);
7965 defsubr (&Sprocess_buffer
);
7966 defsubr (&Sprocess_mark
);
7967 defsubr (&Sset_process_filter
);
7968 defsubr (&Sprocess_filter
);
7969 defsubr (&Sset_process_sentinel
);
7970 defsubr (&Sprocess_sentinel
);
7971 defsubr (&Sset_process_window_size
);
7972 defsubr (&Sset_process_inherit_coding_system_flag
);
7973 defsubr (&Sset_process_query_on_exit_flag
);
7974 defsubr (&Sprocess_query_on_exit_flag
);
7975 defsubr (&Sprocess_contact
);
7976 defsubr (&Sprocess_plist
);
7977 defsubr (&Sset_process_plist
);
7978 defsubr (&Sprocess_list
);
7979 defsubr (&Smake_process
);
7980 defsubr (&Smake_pipe_process
);
7981 defsubr (&Sserial_process_configure
);
7982 defsubr (&Smake_serial_process
);
7983 defsubr (&Sset_network_process_option
);
7984 defsubr (&Smake_network_process
);
7985 defsubr (&Sformat_network_address
);
7986 defsubr (&Snetwork_interface_list
);
7987 defsubr (&Snetwork_interface_info
);
7988 #ifdef DATAGRAM_SOCKETS
7989 defsubr (&Sprocess_datagram_address
);
7990 defsubr (&Sset_process_datagram_address
);
7992 defsubr (&Saccept_process_output
);
7993 defsubr (&Sprocess_send_region
);
7994 defsubr (&Sprocess_send_string
);
7995 defsubr (&Sinterrupt_process
);
7996 defsubr (&Skill_process
);
7997 defsubr (&Squit_process
);
7998 defsubr (&Sstop_process
);
7999 defsubr (&Scontinue_process
);
8000 defsubr (&Sprocess_running_child_p
);
8001 defsubr (&Sprocess_send_eof
);
8002 defsubr (&Ssignal_process
);
8003 defsubr (&Swaiting_for_user_input_p
);
8004 defsubr (&Sprocess_type
);
8005 defsubr (&Sinternal_default_process_sentinel
);
8006 defsubr (&Sinternal_default_process_filter
);
8007 defsubr (&Sset_process_coding_system
);
8008 defsubr (&Sprocess_coding_system
);
8009 defsubr (&Sset_process_filter_multibyte
);
8010 defsubr (&Sprocess_filter_multibyte_p
);
8013 Lisp_Object subfeatures
= Qnil
;
8014 const struct socket_options
*sopt
;
8016 #define ADD_SUBFEATURE(key, val) \
8017 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8019 ADD_SUBFEATURE (QCnowait
, Qt
);
8020 #ifdef DATAGRAM_SOCKETS
8021 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8023 #ifdef HAVE_SEQPACKET
8024 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8026 #ifdef HAVE_LOCAL_SOCKETS
8027 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8029 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8031 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8033 #ifdef HAVE_GETSOCKNAME
8034 ADD_SUBFEATURE (QCservice
, Qt
);
8036 ADD_SUBFEATURE (QCserver
, Qt
);
8038 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8039 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8041 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8044 #endif /* subprocesses */
8046 defsubr (&Sget_buffer_process
);
8047 defsubr (&Sprocess_inherit_coding_system_flag
);
8048 defsubr (&Slist_system_processes
);
8049 defsubr (&Sprocess_attributes
);