1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
35 /* Only MS-DOS does not define `subprocesses'. */
38 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
44 # include <sys/resource.h>
46 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
47 NOFILE_LIMIT is the initial limit on the number of open files,
48 which should be restored in child processes. */
49 static struct rlimit nofile_limit
;
52 /* Are local (unix) sockets supported? */
53 #if defined (HAVE_SYS_UN_H)
54 #if !defined (AF_LOCAL) && defined (AF_UNIX)
55 #define AF_LOCAL AF_UNIX
58 #define HAVE_LOCAL_SOCKETS
63 #include <sys/ioctl.h>
64 #if defined (HAVE_NET_IF_H)
66 #endif /* HAVE_NET_IF_H */
68 #if defined (HAVE_IFADDRS_H)
69 /* Must be after net/if.h */
72 /* We only use structs from this header when we use getifaddrs. */
73 #if defined (HAVE_NET_IF_DL_H)
74 #include <net/if_dl.h>
84 # include <sys/stream.h>
85 # include <sys/stropts.h>
97 #include <flexmember.h>
101 #endif /* subprocesses */
107 #include "character.h"
112 #include "termopts.h"
113 #include "keyboard.h"
114 #include "blockinput.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
123 #ifdef HAVE_WINDOW_SYSTEM
125 #endif /* HAVE_WINDOW_SYSTEM */
128 #include "xgselect.h"
134 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
135 /* This is 0.1s in nanoseconds. */
136 #define ASYNC_RETRY_NSEC 100000000
140 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
141 struct timespec
*, void *);
144 /* Work around GCC 4.3.0 bug with strict overflow checking; see
145 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
146 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
147 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
148 # pragma GCC diagnostic ignored "-Wstrict-overflow"
151 /* True if keyboard input is on hold, zero otherwise. */
153 static bool kbd_is_on_hold
;
155 /* Nonzero means don't run process sentinels. This is used
157 bool inhibit_sentinels
;
162 # define SOCK_CLOEXEC 0
164 #ifndef SOCK_NONBLOCK
165 # define SOCK_NONBLOCK 0
168 /* True if ERRNUM represents an error where the system call would
169 block if a blocking variant were used. */
171 would_block (int errnum
)
174 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
177 return errnum
== EAGAIN
;
182 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
185 close_on_exec (int fd
)
188 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
193 # define accept4(sockfd, addr, addrlen, flags) \
194 process_accept4 (sockfd, addr, addrlen, flags)
196 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
198 return close_on_exec (accept (sockfd
, addr
, addrlen
));
202 process_socket (int domain
, int type
, int protocol
)
204 return close_on_exec (socket (domain
, type
, protocol
));
207 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
210 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
211 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
212 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
213 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
214 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
215 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick
;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick
;
222 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
223 this system. We need to read full packets, so we need a
224 "non-destructive" select. So we require either native select,
225 or emulation of select using FIONREAD. */
227 #ifndef BROKEN_DATAGRAM_SOCKETS
228 # if defined HAVE_SELECT || defined USABLE_FIONREAD
229 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
230 # define DATAGRAM_SOCKETS
235 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
236 # define HAVE_SEQPACKET
239 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
240 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
241 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
243 /* Number of processes which have a non-zero read_output_delay,
244 and therefore might be delayed for adaptive read buffering. */
246 static int process_output_delay_count
;
248 /* True if any process has non-nil read_output_skip. */
250 static bool process_output_skip
;
252 static void start_process_unwind (Lisp_Object
);
253 static void create_process (Lisp_Object
, char **, Lisp_Object
);
255 static bool keyboard_bit_set (fd_set
*);
257 static void deactivate_process (Lisp_Object
);
258 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
259 static int read_process_output (Lisp_Object
, int);
260 static void create_pty (Lisp_Object
);
261 static void exec_sentinel (Lisp_Object
, Lisp_Object
);
263 /* Mask of bits indicating the descriptors that we wait for input on. */
265 static fd_set input_wait_mask
;
267 /* Mask that excludes keyboard input descriptor(s). */
269 static fd_set non_keyboard_wait_mask
;
271 /* Mask that excludes process input descriptor(s). */
273 static fd_set non_process_wait_mask
;
275 /* Mask for selecting for write. */
277 static fd_set write_mask
;
279 /* Mask of bits indicating the descriptors that we wait for connect to
280 complete on. Once they complete, they are removed from this mask
281 and added to the input_wait_mask and non_keyboard_wait_mask. */
283 static fd_set connect_wait_mask
;
285 /* Number of bits set in connect_wait_mask. */
286 static int num_pending_connects
;
288 /* The largest descriptor currently in use for a process object; -1 if none. */
289 static int max_process_desc
;
291 /* The largest descriptor currently in use for input; -1 if none. */
292 static int max_input_desc
;
294 /* Set the external socket descriptor for Emacs to use when
295 `make-network-process' is called with a non-nil
296 `:use-external-socket' option. The value should be either -1, or
297 the file descriptor of a socket that is already bound. */
298 static int external_sock_fd
;
300 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
301 static Lisp_Object chan_process
[FD_SETSIZE
];
302 static void wait_for_socket_fds (Lisp_Object
, char const *);
304 /* Alist of elements (NAME . PROCESS). */
305 static Lisp_Object Vprocess_alist
;
307 /* Buffered-ahead input char from process, indexed by channel.
308 -1 means empty (no char is buffered).
309 Used on sys V where the only way to tell if there is any
310 output from the process is to read at least one char.
311 Always -1 on systems that support FIONREAD. */
313 static int proc_buffered_char
[FD_SETSIZE
];
315 /* Table of `struct coding-system' for each process. */
316 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
317 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
319 #ifdef DATAGRAM_SOCKETS
320 /* Table of `partner address' for datagram sockets. */
321 static struct sockaddr_and_len
{
324 } datagram_address
[FD_SETSIZE
];
325 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
326 #define DATAGRAM_CONN_P(proc) \
327 (PROCESSP (proc) && \
328 XPROCESS (proc)->infd >= 0 && \
329 datagram_address[XPROCESS (proc)->infd].sa != 0)
331 #define DATAGRAM_CONN_P(proc) (0)
334 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
335 a `for' loop which iterates over processes from Vprocess_alist. */
337 #define FOR_EACH_PROCESS(list_var, proc_var) \
338 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
340 /* These setters are used only in this file, so they can be private. */
342 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
347 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
352 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
354 p
->decode_coding_system
= val
;
357 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
359 p
->decoding_buf
= val
;
362 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
364 p
->encode_coding_system
= val
;
367 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
369 p
->encoding_buf
= val
;
372 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
374 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
377 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
382 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
387 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
392 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
397 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
399 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
402 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
407 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
412 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
414 p
->write_queue
= val
;
417 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
424 make_lisp_proc (struct Lisp_Process
*p
)
426 return make_lisp_ptr (p
, Lisp_Vectorlike
);
429 static struct fd_callback_data
435 int condition
; /* Mask of the defines above. */
436 } fd_callback_info
[FD_SETSIZE
];
439 /* Add a file descriptor FD to be monitored for when read is possible.
440 When read is possible, call FUNC with argument DATA. */
443 add_read_fd (int fd
, fd_callback func
, void *data
)
445 add_keyboard_wait_descriptor (fd
);
447 fd_callback_info
[fd
].func
= func
;
448 fd_callback_info
[fd
].data
= data
;
449 fd_callback_info
[fd
].condition
|= FOR_READ
;
452 /* Stop monitoring file descriptor FD for when read is possible. */
455 delete_read_fd (int fd
)
457 delete_keyboard_wait_descriptor (fd
);
459 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
460 if (fd_callback_info
[fd
].condition
== 0)
462 fd_callback_info
[fd
].func
= 0;
463 fd_callback_info
[fd
].data
= 0;
467 /* Add a file descriptor FD to be monitored for when write is possible.
468 When write is possible, call FUNC with argument DATA. */
471 add_write_fd (int fd
, fd_callback func
, void *data
)
473 FD_SET (fd
, &write_mask
);
474 if (fd
> max_input_desc
)
477 fd_callback_info
[fd
].func
= func
;
478 fd_callback_info
[fd
].data
= data
;
479 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
482 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
485 delete_input_desc (int fd
)
487 if (fd
== max_input_desc
)
491 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
492 || FD_ISSET (fd
, &write_mask
)));
498 /* Stop monitoring file descriptor FD for when write is possible. */
501 delete_write_fd (int fd
)
503 FD_CLR (fd
, &write_mask
);
504 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
505 if (fd_callback_info
[fd
].condition
== 0)
507 fd_callback_info
[fd
].func
= 0;
508 fd_callback_info
[fd
].data
= 0;
509 delete_input_desc (fd
);
514 /* Compute the Lisp form of the process status, p->status, from
515 the numeric status that was returned by `wait'. */
517 static Lisp_Object
status_convert (int);
520 update_status (struct Lisp_Process
*p
)
522 eassert (p
->raw_status_new
);
523 pset_status (p
, status_convert (p
->raw_status
));
524 p
->raw_status_new
= 0;
527 /* Convert a process status word in Unix format to
528 the list that we use internally. */
531 status_convert (int w
)
534 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
535 else if (WIFEXITED (w
))
536 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
537 WCOREDUMP (w
) ? Qt
: Qnil
));
538 else if (WIFSIGNALED (w
))
539 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
540 WCOREDUMP (w
) ? Qt
: Qnil
));
545 /* True if STATUS is that of a process attempting connection. */
548 connecting_status (Lisp_Object status
)
550 return CONSP (status
) && EQ (XCAR (status
), Qconnect
);
553 /* Given a status-list, extract the three pieces of information
554 and store them individually through the three pointers. */
557 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, Lisp_Object
*code
,
562 if (connecting_status (l
))
568 *code
= make_number (0);
577 *coredump
= !NILP (tem
);
581 /* Return a string describing a process status list. */
584 status_message (struct Lisp_Process
*p
)
586 Lisp_Object status
= p
->status
;
587 Lisp_Object symbol
, code
;
591 decode_status (status
, &symbol
, &code
, &coredump
);
593 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
596 synchronize_system_messages_locale ();
597 signame
= strsignal (XFASTINT (code
));
599 string
= build_string ("unknown");
604 string
= build_unibyte_string (signame
);
605 if (! NILP (Vlocale_coding_system
))
606 string
= (code_convert_string_norecord
607 (string
, Vlocale_coding_system
, 0));
608 c1
= STRING_CHAR (SDATA (string
));
611 Faset (string
, make_number (0), make_number (c2
));
613 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
614 return concat2 (string
, suffix
);
616 else if (EQ (symbol
, Qexit
))
619 return build_string (XFASTINT (code
) == 0
621 : "connection broken by remote peer\n");
622 if (XFASTINT (code
) == 0)
623 return build_string ("finished\n");
624 AUTO_STRING (prefix
, "exited abnormally with code ");
625 string
= Fnumber_to_string (code
);
626 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
627 return concat3 (prefix
, string
, suffix
);
629 else if (EQ (symbol
, Qfailed
))
631 AUTO_STRING (format
, "failed with code %s\n");
632 return CALLN (Fformat
, format
, code
);
635 return Fcopy_sequence (Fsymbol_name (symbol
));
638 enum { PTY_NAME_SIZE
= 24 };
640 /* Open an available pty, returning a file descriptor.
641 Store into PTY_NAME the file name of the terminal corresponding to the pty.
642 Return -1 on failure. */
645 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
654 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
655 for (i
= 0; i
< 16; i
++)
658 #ifdef PTY_NAME_SPRINTF
661 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
662 #endif /* no PTY_NAME_SPRINTF */
666 #else /* no PTY_OPEN */
667 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
668 #endif /* no PTY_OPEN */
672 #ifdef PTY_TTY_NAME_SPRINTF
675 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
676 #endif /* no PTY_TTY_NAME_SPRINTF */
678 /* Set FD's close-on-exec flag. This is needed even if
679 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
680 doesn't require support for that combination.
681 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
682 doesn't work if the close-on-exec flag is set (Bug#20555).
683 Multithreaded platforms where posix_openpt ignores
684 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
685 have a race condition between the PTY_OPEN and here. */
686 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
688 /* Check to make certain that both sides are available.
689 This avoids a nasty yet stupid bug in rlogins. */
690 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
703 #endif /* HAVE_PTYS */
707 /* Allocate basically initialized process. */
709 static struct Lisp_Process
*
710 allocate_process (void)
712 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
716 make_process (Lisp_Object name
)
718 struct Lisp_Process
*p
= allocate_process ();
719 /* Initialize Lisp data. Note that allocate_process initializes all
720 Lisp data to nil, so do it only for slots which should not be nil. */
721 pset_status (p
, Qrun
);
722 pset_mark (p
, Fmake_marker ());
724 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
725 non-Lisp data, so do it only for slots which should not be zero. */
728 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
732 verify (GNUTLS_STAGE_EMPTY
== 0);
733 eassert (p
->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
734 eassert (NILP (p
->gnutls_boot_parameters
));
737 /* If name is already in use, modify it until it is unused. */
739 Lisp_Object name1
= name
;
740 for (printmax_t i
= 1; ; i
++)
742 Lisp_Object tem
= Fget_process (name1
);
745 char const suffix_fmt
[] = "<%"pMd
">";
746 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
747 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
748 name1
= concat2 (name
, lsuffix
);
752 pset_sentinel (p
, Qinternal_default_process_sentinel
);
753 pset_filter (p
, Qinternal_default_process_filter
);
755 XSETPROCESS (val
, p
);
756 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
761 remove_process (register Lisp_Object proc
)
763 register Lisp_Object pair
;
765 pair
= Frassq (proc
, Vprocess_alist
);
766 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
768 deactivate_process (proc
);
771 #ifdef HAVE_GETADDRINFO_A
773 free_dns_request (Lisp_Object proc
)
775 struct Lisp_Process
*p
= XPROCESS (proc
);
777 if (p
->dns_request
->ar_result
)
778 freeaddrinfo (p
->dns_request
->ar_result
);
779 xfree (p
->dns_request
);
780 p
->dns_request
= NULL
;
785 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
786 doc
: /* Return t if OBJECT is a process. */)
789 return PROCESSP (object
) ? Qt
: Qnil
;
792 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
793 doc
: /* Return the process named NAME, or nil if there is none. */)
794 (register Lisp_Object name
)
799 return Fcdr (Fassoc (name
, Vprocess_alist
));
802 /* This is how commands for the user decode process arguments. It
803 accepts a process, a process name, a buffer, a buffer name, or nil.
804 Buffers denote the first process in the buffer, and nil denotes the
808 get_process (register Lisp_Object name
)
810 register Lisp_Object proc
, obj
;
813 obj
= Fget_process (name
);
815 obj
= Fget_buffer (name
);
817 error ("Process %s does not exist", SDATA (name
));
819 else if (NILP (name
))
820 obj
= Fcurrent_buffer ();
824 /* Now obj should be either a buffer object or a process object. */
827 if (NILP (BVAR (XBUFFER (obj
), name
)))
828 error ("Attempt to get process for a dead buffer");
829 proc
= Fget_buffer_process (obj
);
831 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
842 /* Fdelete_process promises to immediately forget about the process, but in
843 reality, Emacs needs to remember those processes until they have been
844 treated by the SIGCHLD handler and waitpid has been invoked on them;
845 otherwise they might fill up the kernel's process table.
847 Some processes created by call-process are also put onto this list.
849 Members of this list are (process-ID . filename) pairs. The
850 process-ID is a number; the filename, if a string, is a file that
851 needs to be removed after the process exits. */
852 static Lisp_Object deleted_pid_list
;
855 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
857 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
858 /* GC treated elements set to nil. */
859 Fdelq (Qnil
, deleted_pid_list
));
863 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
864 doc
: /* Delete PROCESS: kill it and forget about it immediately.
865 PROCESS may be a process, a buffer, the name of a process or buffer, or
866 nil, indicating the current buffer's process. */)
867 (register Lisp_Object process
)
869 register struct Lisp_Process
*p
;
871 process
= get_process (process
);
872 p
= XPROCESS (process
);
874 #ifdef HAVE_GETADDRINFO_A
877 /* Cancel the request. Unless shutting down, wait until
878 completion. Free the request if completely canceled. */
880 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
881 if (!canceled
&& !inhibit_sentinels
)
883 struct gaicb
const *req
= p
->dns_request
;
884 while (gai_suspend (&req
, 1, NULL
) != 0)
889 free_dns_request (process
);
893 p
->raw_status_new
= 0;
894 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
896 pset_status (p
, list2 (Qexit
, make_number (0)));
897 p
->tick
= ++process_tick
;
898 status_notify (p
, NULL
);
899 redisplay_preserve_echo_area (13);
904 record_kill_process (p
, Qnil
);
908 /* Update P's status, since record_kill_process will make the
909 SIGCHLD handler update deleted_pid_list, not *P. */
911 if (p
->raw_status_new
)
913 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
914 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
915 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
917 p
->tick
= ++process_tick
;
918 status_notify (p
, NULL
);
919 redisplay_preserve_echo_area (13);
922 remove_process (process
);
926 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
927 doc
: /* Return the status of PROCESS.
928 The returned value is one of the following symbols:
929 run -- for a process that is running.
930 stop -- for a process stopped but continuable.
931 exit -- for a process that has exited.
932 signal -- for a process that has got a fatal signal.
933 open -- for a network stream connection that is open.
934 listen -- for a network stream server that is listening.
935 closed -- for a network stream connection that is closed.
936 connect -- when waiting for a non-blocking connection to complete.
937 failed -- when a non-blocking connection has failed.
938 nil -- if arg is a process name and no such process exists.
939 PROCESS may be a process, a buffer, the name of a process, or
940 nil, indicating the current buffer's process. */)
941 (register Lisp_Object process
)
943 register struct Lisp_Process
*p
;
944 register Lisp_Object status
;
946 if (STRINGP (process
))
947 process
= Fget_process (process
);
949 process
= get_process (process
);
954 p
= XPROCESS (process
);
955 if (p
->raw_status_new
)
959 status
= XCAR (status
);
960 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
962 if (EQ (status
, Qexit
))
964 else if (EQ (p
->command
, Qt
))
966 else if (EQ (status
, Qrun
))
972 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
974 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
975 If PROCESS has not yet exited or died, return 0. */)
976 (register Lisp_Object process
)
978 CHECK_PROCESS (process
);
979 if (XPROCESS (process
)->raw_status_new
)
980 update_status (XPROCESS (process
));
981 if (CONSP (XPROCESS (process
)->status
))
982 return XCAR (XCDR (XPROCESS (process
)->status
));
983 return make_number (0);
986 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
987 doc
: /* Return the process id of PROCESS.
988 This is the pid of the external process which PROCESS uses or talks to.
989 For a network, serial, and pipe connections, this value is nil. */)
990 (register Lisp_Object process
)
994 CHECK_PROCESS (process
);
995 pid
= XPROCESS (process
)->pid
;
996 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
999 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
1000 doc
: /* Return the name of PROCESS, as a string.
1001 This is the name of the program invoked in PROCESS,
1002 possibly modified to make it unique among process names. */)
1003 (register Lisp_Object process
)
1005 CHECK_PROCESS (process
);
1006 return XPROCESS (process
)->name
;
1009 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1010 doc
: /* Return the command that was executed to start PROCESS.
1011 This is a list of strings, the first string being the program executed
1012 and the rest of the strings being the arguments given to it.
1013 For a network or serial or pipe connection, this is nil (process is running)
1014 or t (process is stopped). */)
1015 (register Lisp_Object process
)
1017 CHECK_PROCESS (process
);
1018 return XPROCESS (process
)->command
;
1021 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1022 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1023 This is the terminal that the process itself reads and writes on,
1024 not the name of the pty that Emacs uses to talk with that terminal. */)
1025 (register Lisp_Object process
)
1027 CHECK_PROCESS (process
);
1028 return XPROCESS (process
)->tty_name
;
1031 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1033 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1035 (register Lisp_Object process
, Lisp_Object buffer
)
1037 struct Lisp_Process
*p
;
1039 CHECK_PROCESS (process
);
1041 CHECK_BUFFER (buffer
);
1042 p
= XPROCESS (process
);
1043 pset_buffer (p
, buffer
);
1044 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1045 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1046 setup_process_coding_systems (process
);
1050 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1052 doc
: /* Return the buffer PROCESS is associated with.
1053 The default process filter inserts output from PROCESS into this buffer. */)
1054 (register Lisp_Object process
)
1056 CHECK_PROCESS (process
);
1057 return XPROCESS (process
)->buffer
;
1060 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1062 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1063 (register Lisp_Object process
)
1065 CHECK_PROCESS (process
);
1066 return XPROCESS (process
)->mark
;
1070 set_process_filter_masks (struct Lisp_Process
*p
)
1072 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1074 FD_CLR (p
->infd
, &input_wait_mask
);
1075 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1077 else if (EQ (p
->filter
, Qt
)
1078 /* Network or serial process not stopped: */
1079 && !EQ (p
->command
, Qt
))
1081 FD_SET (p
->infd
, &input_wait_mask
);
1082 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1086 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1088 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1089 A value of t means stop accepting output from the process.
1091 When a process has a non-default filter, its buffer is not used for output.
1092 Instead, each time it does output, the entire string of output is
1093 passed to the filter.
1095 The filter gets two arguments: the process and the string of output.
1096 The string argument is normally a multibyte string, except:
1097 - if the process's input coding system is no-conversion or raw-text,
1098 it is a unibyte string (the non-converted input), or else
1099 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1100 string (the result of converting the decoded input multibyte
1101 string to unibyte with `string-make-unibyte'). */)
1102 (Lisp_Object process
, Lisp_Object filter
)
1104 CHECK_PROCESS (process
);
1105 struct Lisp_Process
*p
= XPROCESS (process
);
1107 /* Don't signal an error if the process's input file descriptor
1108 is closed. This could make debugging Lisp more difficult,
1109 for example when doing something like
1111 (setq process (start-process ...))
1113 (set-process-filter process ...) */
1116 filter
= Qinternal_default_process_filter
;
1118 pset_filter (p
, filter
);
1121 set_process_filter_masks (p
);
1123 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1124 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1125 setup_process_coding_systems (process
);
1129 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1131 doc
: /* Return the filter function of PROCESS.
1132 See `set-process-filter' for more info on filter functions. */)
1133 (register Lisp_Object process
)
1135 CHECK_PROCESS (process
);
1136 return XPROCESS (process
)->filter
;
1139 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1141 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1142 The sentinel is called as a function when the process changes state.
1143 It gets two arguments: the process, and a string describing the change. */)
1144 (register Lisp_Object process
, Lisp_Object sentinel
)
1146 struct Lisp_Process
*p
;
1148 CHECK_PROCESS (process
);
1149 p
= XPROCESS (process
);
1151 if (NILP (sentinel
))
1152 sentinel
= Qinternal_default_process_sentinel
;
1154 pset_sentinel (p
, sentinel
);
1155 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1156 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1160 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1162 doc
: /* Return the sentinel of PROCESS.
1163 See `set-process-sentinel' for more info on sentinels. */)
1164 (register Lisp_Object process
)
1166 CHECK_PROCESS (process
);
1167 return XPROCESS (process
)->sentinel
;
1170 DEFUN ("set-process-window-size", Fset_process_window_size
,
1171 Sset_process_window_size
, 3, 3, 0,
1172 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1173 Value is t if PROCESS was successfully told about the window size,
1175 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1177 CHECK_PROCESS (process
);
1179 /* All known platforms store window sizes as 'unsigned short'. */
1180 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1181 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1183 if (NETCONN_P (process
)
1184 || XPROCESS (process
)->infd
< 0
1185 || (set_window_size (XPROCESS (process
)->infd
,
1186 XINT (height
), XINT (width
))
1193 DEFUN ("set-process-inherit-coding-system-flag",
1194 Fset_process_inherit_coding_system_flag
,
1195 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1196 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1197 If the second argument FLAG is non-nil, then the variable
1198 `buffer-file-coding-system' of the buffer associated with PROCESS
1199 will be bound to the value of the coding system used to decode
1202 This is useful when the coding system specified for the process buffer
1203 leaves either the character code conversion or the end-of-line conversion
1204 unspecified, or if the coding system used to decode the process output
1205 is more appropriate for saving the process buffer.
1207 Binding the variable `inherit-process-coding-system' to non-nil before
1208 starting the process is an alternative way of setting the inherit flag
1209 for the process which will run.
1211 This function returns FLAG. */)
1212 (register Lisp_Object process
, Lisp_Object flag
)
1214 CHECK_PROCESS (process
);
1215 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1219 DEFUN ("set-process-query-on-exit-flag",
1220 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1222 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1223 If the second argument FLAG is non-nil, Emacs will query the user before
1224 exiting or killing a buffer if PROCESS is running. This function
1226 (register Lisp_Object process
, Lisp_Object flag
)
1228 CHECK_PROCESS (process
);
1229 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1233 DEFUN ("process-query-on-exit-flag",
1234 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1236 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1237 (register Lisp_Object process
)
1239 CHECK_PROCESS (process
);
1240 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1243 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1245 doc
: /* Return the contact info of PROCESS; t for a real child.
1246 For a network or serial or pipe connection, the value depends on the
1247 optional KEY arg. If KEY is nil, value is a cons cell of the form
1248 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1249 connection; it is t for a pipe connection. If KEY is t, the complete
1250 contact information for the connection is returned, else the specific
1251 value for the keyword KEY is returned. See `make-network-process',
1252 `make-serial-process', or `make pipe-process' for the list of keywords.
1253 If PROCESS is a non-blocking network process that hasn't been fully
1254 set up yet, this function will block until socket setup has completed. */)
1255 (Lisp_Object process
, Lisp_Object key
)
1257 Lisp_Object contact
;
1259 CHECK_PROCESS (process
);
1260 contact
= XPROCESS (process
)->childp
;
1262 #ifdef DATAGRAM_SOCKETS
1264 if (NETCONN_P (process
))
1265 wait_for_socket_fds (process
, "process-contact");
1267 if (DATAGRAM_CONN_P (process
)
1268 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1269 contact
= Fplist_put (contact
, QCremote
,
1270 Fprocess_datagram_address (process
));
1273 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1276 if (NILP (key
) && NETCONN_P (process
))
1277 return list2 (Fplist_get (contact
, QChost
),
1278 Fplist_get (contact
, QCservice
));
1279 if (NILP (key
) && SERIALCONN_P (process
))
1280 return list2 (Fplist_get (contact
, QCport
),
1281 Fplist_get (contact
, QCspeed
));
1282 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1283 if the pipe process is useful for purposes other than receiving
1285 if (NILP (key
) && PIPECONN_P (process
))
1287 return Fplist_get (contact
, key
);
1290 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1292 doc
: /* Return the plist of PROCESS. */)
1293 (register Lisp_Object process
)
1295 CHECK_PROCESS (process
);
1296 return XPROCESS (process
)->plist
;
1299 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1301 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1302 (Lisp_Object process
, Lisp_Object plist
)
1304 CHECK_PROCESS (process
);
1307 pset_plist (XPROCESS (process
), plist
);
1311 #if 0 /* Turned off because we don't currently record this info
1312 in the process. Perhaps add it. */
1313 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1314 doc
: /* Return the connection type of PROCESS.
1315 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1316 a socket connection. */)
1317 (Lisp_Object process
)
1319 return XPROCESS (process
)->type
;
1323 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1324 doc
: /* Return the connection type of PROCESS.
1325 The value is either the symbol `real', `network', `serial', or `pipe'.
1326 PROCESS may be a process, a buffer, the name of a process or buffer, or
1327 nil, indicating the current buffer's process. */)
1328 (Lisp_Object process
)
1331 proc
= get_process (process
);
1332 return XPROCESS (proc
)->type
;
1335 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1337 doc
: /* Convert network ADDRESS from internal format to a string.
1338 A 4 or 5 element vector represents an IPv4 address (with port number).
1339 An 8 or 9 element vector represents an IPv6 address (with port number).
1340 If optional second argument OMIT-PORT is non-nil, don't include a port
1341 number in the string, even when present in ADDRESS.
1342 Return nil if format of ADDRESS is invalid. */)
1343 (Lisp_Object address
, Lisp_Object omit_port
)
1348 if (STRINGP (address
)) /* AF_LOCAL */
1351 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1353 register struct Lisp_Vector
*p
= XVECTOR (address
);
1354 ptrdiff_t size
= p
->header
.size
;
1355 Lisp_Object args
[10];
1359 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1361 format
= "%d.%d.%d.%d";
1366 format
= "%d.%d.%d.%d:%d";
1369 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1371 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1376 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1382 AUTO_STRING (format_obj
, format
);
1383 args
[0] = format_obj
;
1385 for (i
= 0; i
< nargs
; i
++)
1387 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1390 if (nargs
<= 5 /* IPv4 */
1391 && i
< 4 /* host, not port */
1392 && XINT (p
->contents
[i
]) > 255)
1395 args
[i
+ 1] = p
->contents
[i
];
1398 return Fformat (nargs
+ 1, args
);
1401 if (CONSP (address
))
1403 AUTO_STRING (format
, "<Family %d>");
1404 return CALLN (Fformat
, format
, Fcar (address
));
1410 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1411 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1414 return Fmapcar (Qcdr
, Vprocess_alist
);
1417 /* Starting asynchronous inferior processes. */
1419 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1420 doc
: /* Start a program in a subprocess. Return the process object for it.
1422 This is similar to `start-process', but arguments are specified as
1423 keyword/argument pairs. The following arguments are defined:
1425 :name NAME -- NAME is name for process. It is modified if necessary
1428 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1429 with the process. Process output goes at end of that buffer, unless
1430 you specify an output stream or filter function to handle the output.
1431 BUFFER may be also nil, meaning that this process is not associated
1434 :command COMMAND -- COMMAND is a list starting with the program file
1435 name, followed by strings to give to the program as arguments.
1437 :coding CODING -- If CODING is a symbol, it specifies the coding
1438 system used for both reading and writing for this process. If CODING
1439 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1440 ENCODING is used for writing.
1442 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1443 the process is running. If BOOL is not given, query before exiting.
1445 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1446 In the stopped state, a process does not accept incoming data, but you
1447 can send outgoing data. The stopped state is cleared by
1448 `continue-process' and set by `stop-process'.
1450 :connection-type TYPE -- TYPE is control type of device used to
1451 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1452 to use a pty, or nil to use the default specified through
1453 `process-connection-type'.
1455 :filter FILTER -- Install FILTER as the process filter.
1457 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1459 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1460 to the standard error of subprocess. Specifying this implies
1461 `:connection-type' is set to `pipe'.
1463 usage: (make-process &rest ARGS) */)
1464 (ptrdiff_t nargs
, Lisp_Object
*args
)
1466 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1467 Lisp_Object xstderr
, stderrproc
;
1468 ptrdiff_t count
= SPECPDL_INDEX ();
1473 /* Save arguments for process-contact and clone-process. */
1474 contact
= Flist (nargs
, args
);
1476 buffer
= Fplist_get (contact
, QCbuffer
);
1478 buffer
= Fget_buffer_create (buffer
);
1480 /* Make sure that the child will be able to chdir to the current
1481 buffer's current directory, or its unhandled equivalent. We
1482 can't just have the child check for an error when it does the
1483 chdir, since it's in a vfork. */
1484 current_dir
= encode_current_directory ();
1486 name
= Fplist_get (contact
, QCname
);
1487 CHECK_STRING (name
);
1489 command
= Fplist_get (contact
, QCcommand
);
1490 if (CONSP (command
))
1491 program
= XCAR (command
);
1495 if (!NILP (program
))
1496 CHECK_STRING (program
);
1499 xstderr
= Fplist_get (contact
, QCstderr
);
1500 if (PROCESSP (xstderr
))
1502 if (!PIPECONN_P (xstderr
))
1503 error ("Process is not a pipe process");
1504 stderrproc
= xstderr
;
1506 else if (!NILP (xstderr
))
1508 CHECK_STRING (program
);
1509 stderrproc
= CALLN (Fmake_pipe_process
,
1511 concat2 (name
, build_string (" stderr")),
1513 Fget_buffer_create (xstderr
));
1516 proc
= make_process (name
);
1517 record_unwind_protect (start_process_unwind
, proc
);
1519 pset_childp (XPROCESS (proc
), Qt
);
1520 eassert (NILP (XPROCESS (proc
)->plist
));
1521 pset_type (XPROCESS (proc
), Qreal
);
1522 pset_buffer (XPROCESS (proc
), buffer
);
1523 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1524 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1525 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1527 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1528 XPROCESS (proc
)->kill_without_query
= 1;
1529 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1530 pset_command (XPROCESS (proc
), Qt
);
1532 tem
= Fplist_get (contact
, QCconnection_type
);
1534 XPROCESS (proc
)->pty_flag
= true;
1535 else if (EQ (tem
, Qpipe
))
1536 XPROCESS (proc
)->pty_flag
= false;
1537 else if (NILP (tem
))
1538 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1540 report_file_error ("Unknown connection type", tem
);
1542 if (!NILP (stderrproc
))
1544 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1546 XPROCESS (proc
)->pty_flag
= false;
1550 /* AKA GNUTLS_INITSTAGE(proc). */
1551 verify (GNUTLS_STAGE_EMPTY
== 0);
1552 eassert (XPROCESS (proc
)->gnutls_initstage
== GNUTLS_STAGE_EMPTY
);
1553 eassert (NILP (XPROCESS (proc
)->gnutls_cred_type
));
1556 XPROCESS (proc
)->adaptive_read_buffering
1557 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1558 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1560 /* Make the process marker point into the process buffer (if any). */
1561 if (BUFFERP (buffer
))
1562 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1563 BUF_ZV (XBUFFER (buffer
)),
1564 BUF_ZV_BYTE (XBUFFER (buffer
)));
1569 /* Decide coding systems for communicating with the process. Here
1570 we don't setup the structure coding_system nor pay attention to
1571 unibyte mode. They are done in create_process. */
1573 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1574 Lisp_Object coding_systems
= Qt
;
1575 Lisp_Object val
, *args2
;
1577 tem
= Fplist_get (contact
, QCcoding
);
1585 val
= Vcoding_system_for_read
;
1588 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1590 SAFE_ALLOCA_LISP (args2
, nargs2
);
1592 args2
[i
++] = Qstart_process
;
1594 args2
[i
++] = buffer
;
1595 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1596 args2
[i
++] = XCAR (tem2
);
1597 if (!NILP (program
))
1598 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1599 if (CONSP (coding_systems
))
1600 val
= XCAR (coding_systems
);
1601 else if (CONSP (Vdefault_process_coding_system
))
1602 val
= XCAR (Vdefault_process_coding_system
);
1604 pset_decode_coding_system (XPROCESS (proc
), val
);
1613 val
= Vcoding_system_for_write
;
1616 if (EQ (coding_systems
, Qt
))
1618 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1620 SAFE_ALLOCA_LISP (args2
, nargs2
);
1622 args2
[i
++] = Qstart_process
;
1624 args2
[i
++] = buffer
;
1625 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1626 args2
[i
++] = XCAR (tem2
);
1627 if (!NILP (program
))
1628 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1630 if (CONSP (coding_systems
))
1631 val
= XCDR (coding_systems
);
1632 else if (CONSP (Vdefault_process_coding_system
))
1633 val
= XCDR (Vdefault_process_coding_system
);
1635 pset_encode_coding_system (XPROCESS (proc
), val
);
1636 /* Note: At this moment, the above coding system may leave
1637 text-conversion or eol-conversion unspecified. They will be
1638 decided after we read output from the process and decode it by
1639 some coding system, or just before we actually send a text to
1644 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1645 eassert (XPROCESS (proc
)->decoding_carryover
== 0);
1646 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1648 XPROCESS (proc
)->inherit_coding_system_flag
1649 = !(NILP (buffer
) || !inherit_process_coding_system
);
1651 if (!NILP (program
))
1653 Lisp_Object program_args
= XCDR (command
);
1655 /* If program file name is not absolute, search our path for it.
1656 Put the name we will really use in TEM. */
1657 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1658 && !(SCHARS (program
) > 1
1659 && IS_DEVICE_SEP (SREF (program
, 1))))
1662 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1663 make_number (X_OK
), false);
1665 report_file_error ("Searching for program", program
);
1666 tem
= Fexpand_file_name (tem
, Qnil
);
1670 if (!NILP (Ffile_directory_p (program
)))
1671 error ("Specified program for new process is a directory");
1675 /* Remove "/:" from TEM. */
1676 tem
= remove_slash_colon (tem
);
1678 Lisp_Object arg_encoding
= Qnil
;
1680 /* Encode the file name and put it in NEW_ARGV.
1681 That's where the child will use it to execute the program. */
1682 tem
= list1 (ENCODE_FILE (tem
));
1683 ptrdiff_t new_argc
= 1;
1685 /* Here we encode arguments by the coding system used for sending
1686 data to the process. We don't support using different coding
1687 systems for encoding arguments and for encoding data sent to the
1690 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1692 Lisp_Object arg
= XCAR (tem2
);
1694 if (STRING_MULTIBYTE (arg
))
1696 if (NILP (arg_encoding
))
1697 arg_encoding
= (complement_process_encoding_system
1698 (XPROCESS (proc
)->encode_coding_system
));
1699 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1701 tem
= Fcons (arg
, tem
);
1705 /* Now that everything is encoded we can collect the strings into
1708 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1709 new_argv
[new_argc
] = 0;
1711 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1713 new_argv
[i
] = SSDATA (XCAR (tem
));
1717 create_process (proc
, new_argv
, current_dir
);
1723 return unbind_to (count
, proc
);
1726 /* If PROC doesn't have its pid set, then an error was signaled and
1727 the process wasn't started successfully, so remove it. */
1729 start_process_unwind (Lisp_Object proc
)
1731 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1732 remove_process (proc
);
1735 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1738 close_process_fd (int *fd_addr
)
1748 /* Indexes of file descriptors in open_fds. */
1751 /* The pipe from Emacs to its subprocess. */
1753 WRITE_TO_SUBPROCESS
,
1755 /* The main pipe from the subprocess to Emacs. */
1756 READ_FROM_SUBPROCESS
,
1759 /* The pipe from the subprocess to Emacs that is closed when the
1760 subprocess execs. */
1761 READ_FROM_EXEC_MONITOR
,
1765 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1768 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1770 struct Lisp_Process
*p
= XPROCESS (process
);
1771 int inchannel
, outchannel
;
1774 int forkin
, forkout
, forkerr
= -1;
1776 char pty_name
[PTY_NAME_SIZE
];
1777 Lisp_Object lisp_pty_name
= Qnil
;
1780 inchannel
= outchannel
= -1;
1783 outchannel
= inchannel
= allocate_pty (pty_name
);
1787 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1788 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1789 /* On most USG systems it does not work to open the pty's tty here,
1790 then close it and reopen it in the child. */
1791 /* Don't let this terminal become our controlling terminal
1792 (in case we don't have one). */
1793 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1795 report_file_error ("Opening pty", Qnil
);
1796 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1798 forkin
= forkout
= -1;
1799 #endif /* not USG, or USG_SUBTTY_WORKS */
1801 lisp_pty_name
= build_string (pty_name
);
1805 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1806 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1807 report_file_error ("Creating pipe", Qnil
);
1808 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1809 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1810 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1811 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1813 if (!NILP (p
->stderrproc
))
1815 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1817 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1819 /* Close unnecessary file descriptors. */
1820 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1821 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1826 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1827 report_file_error ("Creating pipe", Qnil
);
1830 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1831 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1833 /* Record this as an active process, with its channels. */
1834 chan_process
[inchannel
] = process
;
1835 p
->infd
= inchannel
;
1836 p
->outfd
= outchannel
;
1838 /* Previously we recorded the tty descriptor used in the subprocess.
1839 It was only used for getting the foreground tty process, so now
1840 we just reopen the device (see emacs_get_tty_pgrp) as this is
1841 more portable (see USG_SUBTTY_WORKS above). */
1843 p
->pty_flag
= pty_flag
;
1844 pset_status (p
, Qrun
);
1846 if (!EQ (p
->command
, Qt
))
1848 FD_SET (inchannel
, &input_wait_mask
);
1849 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1852 if (inchannel
> max_process_desc
)
1853 max_process_desc
= inchannel
;
1855 /* This may signal an error. */
1856 setup_process_coding_systems (process
);
1859 block_child_signal (&oldset
);
1862 /* vfork, and prevent local vars from being clobbered by the vfork. */
1863 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1864 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1865 char **volatile new_argv_volatile
= new_argv
;
1866 int volatile forkin_volatile
= forkin
;
1867 int volatile forkout_volatile
= forkout
;
1868 int volatile forkerr_volatile
= forkerr
;
1869 struct Lisp_Process
*p_volatile
= p
;
1873 current_dir
= current_dir_volatile
;
1874 lisp_pty_name
= lisp_pty_name_volatile
;
1875 new_argv
= new_argv_volatile
;
1876 forkin
= forkin_volatile
;
1877 forkout
= forkout_volatile
;
1878 forkerr
= forkerr_volatile
;
1881 pty_flag
= p
->pty_flag
;
1884 #endif /* not WINDOWSNT */
1886 /* Make the pty be the controlling terminal of the process. */
1888 /* First, disconnect its current controlling terminal. */
1889 /* We tried doing setsid only if pty_flag, but it caused
1890 process_set_signal to fail on SGI when using a pipe. */
1892 /* Make the pty's terminal the controlling terminal. */
1893 if (pty_flag
&& forkin
>= 0)
1896 /* We ignore the return value
1897 because faith@cs.unc.edu says that is necessary on Linux. */
1898 ioctl (forkin
, TIOCSCTTY
, 0);
1901 #if defined (LDISC1)
1902 if (pty_flag
&& forkin
>= 0)
1905 tcgetattr (forkin
, &t
);
1907 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1908 emacs_perror ("create_process/tcsetattr LDISC1");
1911 #if defined (NTTYDISC) && defined (TIOCSETD)
1912 if (pty_flag
&& forkin
>= 0)
1914 /* Use new line discipline. */
1915 int ldisc
= NTTYDISC
;
1916 ioctl (forkin
, TIOCSETD
, &ldisc
);
1921 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1922 can do TIOCSPGRP only to the process's controlling tty. */
1925 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1926 I can't test it since I don't have 4.3. */
1927 int j
= emacs_open (DEV_TTY
, O_RDWR
, 0);
1930 ioctl (j
, TIOCNOTTY
, 0);
1934 #endif /* TIOCNOTTY */
1936 #if !defined (DONT_REOPEN_PTY)
1937 /*** There is a suggestion that this ought to be a
1938 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1939 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1940 that system does seem to need this code, even though
1941 both TIOCSCTTY is defined. */
1942 /* Now close the pty (if we had it open) and reopen it.
1943 This makes the pty the controlling terminal of the subprocess. */
1947 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1950 emacs_close (forkin
);
1951 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1955 emacs_perror (SSDATA (lisp_pty_name
));
1956 _exit (EXIT_CANCELED
);
1960 #endif /* not DONT_REOPEN_PTY */
1962 #ifdef SETUP_SLAVE_PTY
1967 #endif /* SETUP_SLAVE_PTY */
1968 #endif /* HAVE_PTYS */
1970 signal (SIGINT
, SIG_DFL
);
1971 signal (SIGQUIT
, SIG_DFL
);
1973 signal (SIGPROF
, SIG_DFL
);
1976 /* Emacs ignores SIGPIPE, but the child should not. */
1977 signal (SIGPIPE
, SIG_DFL
);
1979 /* Stop blocking SIGCHLD in the child. */
1980 unblock_child_signal (&oldset
);
1983 child_setup_tty (forkout
);
1988 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1989 #else /* not WINDOWSNT */
1990 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1991 #endif /* not WINDOWSNT */
1994 /* Back in the parent process. */
1996 vfork_errno
= errno
;
2001 /* Stop blocking in the parent. */
2002 unblock_child_signal (&oldset
);
2006 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2009 /* vfork succeeded. */
2011 /* Close the pipe ends that the child uses, or the child's pty. */
2012 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2013 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2016 register_child (pid
, inchannel
);
2017 #endif /* WINDOWSNT */
2019 pset_tty_name (p
, lisp_pty_name
);
2022 /* Wait for child_setup to complete in case that vfork is
2023 actually defined as fork. The descriptor
2024 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2025 of a pipe is closed at the child side either by close-on-exec
2026 on successful execve or the _exit call in child_setup. */
2030 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2031 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2032 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2035 if (!NILP (p
->stderrproc
))
2037 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2038 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2044 create_pty (Lisp_Object process
)
2046 struct Lisp_Process
*p
= XPROCESS (process
);
2047 char pty_name
[PTY_NAME_SIZE
];
2048 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2052 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2053 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2054 /* On most USG systems it does not work to open the pty's tty here,
2055 then close it and reopen it in the child. */
2056 /* Don't let this terminal become our controlling terminal
2057 (in case we don't have one). */
2058 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2060 report_file_error ("Opening pty", Qnil
);
2061 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2062 #if defined (DONT_REOPEN_PTY)
2063 /* In the case that vfork is defined as fork, the parent process
2064 (Emacs) may send some data before the child process completes
2065 tty options setup. So we setup tty before forking. */
2066 child_setup_tty (forkout
);
2067 #endif /* DONT_REOPEN_PTY */
2068 #endif /* not USG, or USG_SUBTTY_WORKS */
2070 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2072 /* Record this as an active process, with its channels.
2073 As a result, child_setup will close Emacs's side of the pipes. */
2074 chan_process
[pty_fd
] = process
;
2078 /* Previously we recorded the tty descriptor used in the subprocess.
2079 It was only used for getting the foreground tty process, so now
2080 we just reopen the device (see emacs_get_tty_pgrp) as this is
2081 more portable (see USG_SUBTTY_WORKS above). */
2084 pset_status (p
, Qrun
);
2085 setup_process_coding_systems (process
);
2087 FD_SET (pty_fd
, &input_wait_mask
);
2088 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2089 if (pty_fd
> max_process_desc
)
2090 max_process_desc
= pty_fd
;
2092 pset_tty_name (p
, build_string (pty_name
));
2098 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2100 doc
: /* Create and return a bidirectional pipe process.
2102 In Emacs, pipes are represented by process objects, so input and
2103 output work as for subprocesses, and `delete-process' closes a pipe.
2104 However, a pipe process has no process id, it cannot be signaled,
2105 and the status codes are different from normal processes.
2107 Arguments are specified as keyword/argument pairs. The following
2108 arguments are defined:
2110 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2112 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2113 with the process. Process output goes at the end of that buffer,
2114 unless you specify an output stream or filter function to handle the
2115 output. If BUFFER is not given, the value of NAME is used.
2117 :coding CODING -- If CODING is a symbol, it specifies the coding
2118 system used for both reading and writing for this process. If CODING
2119 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2120 ENCODING is used for writing.
2122 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2123 the process is running. If BOOL is not given, query before exiting.
2125 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2126 In the stopped state, a pipe process does not accept incoming data,
2127 but you can send outgoing data. The stopped state is cleared by
2128 `continue-process' and set by `stop-process'.
2130 :filter FILTER -- Install FILTER as the process filter.
2132 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2134 usage: (make-pipe-process &rest ARGS) */)
2135 (ptrdiff_t nargs
, Lisp_Object
*args
)
2137 Lisp_Object proc
, contact
;
2138 struct Lisp_Process
*p
;
2139 Lisp_Object name
, buffer
;
2141 ptrdiff_t specpdl_count
;
2142 int inchannel
, outchannel
;
2147 contact
= Flist (nargs
, args
);
2149 name
= Fplist_get (contact
, QCname
);
2150 CHECK_STRING (name
);
2151 proc
= make_process (name
);
2152 specpdl_count
= SPECPDL_INDEX ();
2153 record_unwind_protect (remove_process
, proc
);
2154 p
= XPROCESS (proc
);
2156 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2157 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2158 report_file_error ("Creating pipe", Qnil
);
2159 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2160 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2162 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2163 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2166 register_aux_fd (inchannel
);
2169 /* Record this as an active process, with its channels. */
2170 chan_process
[inchannel
] = proc
;
2171 p
->infd
= inchannel
;
2172 p
->outfd
= outchannel
;
2174 if (inchannel
> max_process_desc
)
2175 max_process_desc
= inchannel
;
2177 buffer
= Fplist_get (contact
, QCbuffer
);
2180 buffer
= Fget_buffer_create (buffer
);
2181 pset_buffer (p
, buffer
);
2183 pset_childp (p
, contact
);
2184 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2185 pset_type (p
, Qpipe
);
2186 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2187 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2188 eassert (NILP (p
->log
));
2189 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2190 p
->kill_without_query
= 1;
2191 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2192 pset_command (p
, Qt
);
2193 eassert (! p
->pty_flag
);
2195 if (!EQ (p
->command
, Qt
))
2197 FD_SET (inchannel
, &input_wait_mask
);
2198 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2200 p
->adaptive_read_buffering
2201 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2202 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2204 /* Make the process marker point into the process buffer (if any). */
2205 if (BUFFERP (buffer
))
2206 set_marker_both (p
->mark
, buffer
,
2207 BUF_ZV (XBUFFER (buffer
)),
2208 BUF_ZV_BYTE (XBUFFER (buffer
)));
2211 /* Setup coding systems for communicating with the network stream. */
2213 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2214 Lisp_Object coding_systems
= Qt
;
2217 tem
= Fplist_get (contact
, QCcoding
);
2225 else if (!NILP (Vcoding_system_for_read
))
2226 val
= Vcoding_system_for_read
;
2227 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2228 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2229 /* We dare not decode end-of-line format by setting VAL to
2230 Qraw_text, because the existing Emacs Lisp libraries
2231 assume that they receive bare code including a sequence of
2236 if (CONSP (coding_systems
))
2237 val
= XCAR (coding_systems
);
2238 else if (CONSP (Vdefault_process_coding_system
))
2239 val
= XCAR (Vdefault_process_coding_system
);
2243 pset_decode_coding_system (p
, val
);
2251 else if (!NILP (Vcoding_system_for_write
))
2252 val
= Vcoding_system_for_write
;
2253 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2257 if (CONSP (coding_systems
))
2258 val
= XCDR (coding_systems
);
2259 else if (CONSP (Vdefault_process_coding_system
))
2260 val
= XCDR (Vdefault_process_coding_system
);
2264 pset_encode_coding_system (p
, val
);
2266 /* This may signal an error. */
2267 setup_process_coding_systems (proc
);
2269 specpdl_ptr
= specpdl
+ specpdl_count
;
2275 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2276 The address family of sa is not included in the result. */
2279 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2281 Lisp_Object address
;
2284 struct Lisp_Vector
*p
;
2286 /* Workaround for a bug in getsockname on BSD: Names bound to
2287 sockets in the UNIX domain are inaccessible; getsockname returns
2288 a zero length name. */
2289 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2290 return empty_unibyte_string
;
2292 switch (sa
->sa_family
)
2296 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2297 len
= sizeof (sin
->sin_addr
) + 1;
2298 address
= Fmake_vector (make_number (len
), Qnil
);
2299 p
= XVECTOR (address
);
2300 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2301 cp
= (unsigned char *) &sin
->sin_addr
;
2307 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2308 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2309 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2310 address
= Fmake_vector (make_number (len
), Qnil
);
2311 p
= XVECTOR (address
);
2312 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2313 for (i
= 0; i
< len
; i
++)
2314 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2318 #ifdef HAVE_LOCAL_SOCKETS
2321 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2322 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2323 /* If the first byte is NUL, the name is a Linux abstract
2324 socket name, and the name can contain embedded NULs. If
2325 it's not, we have a NUL-terminated string. Be careful not
2326 to walk past the end of the object looking for the name
2327 terminator, however. */
2328 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2330 const char *terminator
2331 = memchr (sockun
->sun_path
, '\0', name_length
);
2334 name_length
= terminator
- (const char *) sockun
->sun_path
;
2337 return make_unibyte_string (sockun
->sun_path
, name_length
);
2341 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2342 address
= Fcons (make_number (sa
->sa_family
),
2343 Fmake_vector (make_number (len
), Qnil
));
2344 p
= XVECTOR (XCDR (address
));
2345 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2351 p
->contents
[i
++] = make_number (*cp
++);
2356 /* Convert an internal struct addrinfo to a Lisp object. */
2359 conv_addrinfo_to_lisp (struct addrinfo
*res
)
2361 Lisp_Object protocol
= make_number (res
->ai_protocol
);
2362 eassert (XINT (protocol
) == res
->ai_protocol
);
2363 return Fcons (protocol
, conv_sockaddr_to_lisp (res
->ai_addr
, res
->ai_addrlen
));
2367 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2370 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2372 struct Lisp_Vector
*p
;
2374 if (VECTORP (address
))
2376 p
= XVECTOR (address
);
2377 if (p
->header
.size
== 5)
2380 return sizeof (struct sockaddr_in
);
2383 else if (p
->header
.size
== 9)
2385 *familyp
= AF_INET6
;
2386 return sizeof (struct sockaddr_in6
);
2390 #ifdef HAVE_LOCAL_SOCKETS
2391 else if (STRINGP (address
))
2393 *familyp
= AF_LOCAL
;
2394 return sizeof (struct sockaddr_un
);
2397 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2398 && VECTORP (XCDR (address
)))
2400 struct sockaddr
*sa
;
2401 p
= XVECTOR (XCDR (address
));
2402 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2404 *familyp
= XINT (XCAR (address
));
2405 return p
->header
.size
+ sizeof (sa
->sa_family
);
2410 /* Convert an address object (vector or string) to an internal sockaddr.
2412 The address format has been basically validated by
2413 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2414 it could have come from user data. So if FAMILY is not valid,
2415 we return after zeroing *SA. */
2418 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2420 register struct Lisp_Vector
*p
;
2421 register unsigned char *cp
= NULL
;
2425 memset (sa
, 0, len
);
2427 if (VECTORP (address
))
2429 p
= XVECTOR (address
);
2430 if (family
== AF_INET
)
2432 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2433 len
= sizeof (sin
->sin_addr
) + 1;
2434 hostport
= XINT (p
->contents
[--len
]);
2435 sin
->sin_port
= htons (hostport
);
2436 cp
= (unsigned char *)&sin
->sin_addr
;
2437 sa
->sa_family
= family
;
2440 else if (family
== AF_INET6
)
2442 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2443 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2444 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2445 hostport
= XINT (p
->contents
[--len
]);
2446 sin6
->sin6_port
= htons (hostport
);
2447 for (i
= 0; i
< len
; i
++)
2448 if (INTEGERP (p
->contents
[i
]))
2450 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2453 sa
->sa_family
= family
;
2460 else if (STRINGP (address
))
2462 #ifdef HAVE_LOCAL_SOCKETS
2463 if (family
== AF_LOCAL
)
2465 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2466 cp
= SDATA (address
);
2467 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2468 sockun
->sun_path
[i
] = *cp
++;
2469 sa
->sa_family
= family
;
2476 p
= XVECTOR (XCDR (address
));
2477 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2480 for (i
= 0; i
< len
; i
++)
2481 if (INTEGERP (p
->contents
[i
]))
2482 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2485 #ifdef DATAGRAM_SOCKETS
2486 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2488 doc
: /* Get the current datagram address associated with PROCESS.
2489 If PROCESS is a non-blocking network process that hasn't been fully
2490 set up yet, this function will block until socket setup has completed. */)
2491 (Lisp_Object process
)
2495 CHECK_PROCESS (process
);
2497 if (NETCONN_P (process
))
2498 wait_for_socket_fds (process
, "process-datagram-address");
2500 if (!DATAGRAM_CONN_P (process
))
2503 channel
= XPROCESS (process
)->infd
;
2504 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2505 datagram_address
[channel
].len
);
2508 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2510 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2511 Return nil upon error setting address, ADDRESS otherwise.
2513 If PROCESS is a non-blocking network process that hasn't been fully
2514 set up yet, this function will block until socket setup has completed. */)
2515 (Lisp_Object process
, Lisp_Object address
)
2521 CHECK_PROCESS (process
);
2523 if (NETCONN_P (process
))
2524 wait_for_socket_fds (process
, "set-process-datagram-address");
2526 if (!DATAGRAM_CONN_P (process
))
2529 channel
= XPROCESS (process
)->infd
;
2531 len
= get_lisp_to_sockaddr_size (address
, &family
);
2532 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2534 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2540 static const struct socket_options
{
2541 /* The name of this option. Should be lowercase version of option
2542 name without SO_ prefix. */
2544 /* Option level SOL_... */
2546 /* Option number SO_... */
2548 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2549 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2550 } socket_options
[] =
2552 #ifdef SO_BINDTODEVICE
2553 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2556 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2559 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2562 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2565 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2568 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2571 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2574 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2576 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2579 /* Set option OPT to value VAL on socket S.
2581 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2582 Signals an error if setting a known option fails.
2586 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2589 const struct socket_options
*sopt
;
2594 name
= SSDATA (SYMBOL_NAME (opt
));
2595 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2596 if (strcmp (name
, sopt
->name
) == 0)
2599 switch (sopt
->opttype
)
2604 optval
= NILP (val
) ? 0 : 1;
2605 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2606 &optval
, sizeof (optval
));
2613 if (TYPE_RANGED_INTEGERP (int, val
))
2614 optval
= XINT (val
);
2616 error ("Bad option value for %s", name
);
2617 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2618 &optval
, sizeof (optval
));
2622 #ifdef SO_BINDTODEVICE
2625 char devname
[IFNAMSIZ
+ 1];
2627 /* This is broken, at least in the Linux 2.4 kernel.
2628 To unbind, the arg must be a zero integer, not the empty string.
2629 This should work on all systems. KFS. 2003-09-23. */
2630 memset (devname
, 0, sizeof devname
);
2633 char *arg
= SSDATA (val
);
2634 int len
= min (strlen (arg
), IFNAMSIZ
);
2635 memcpy (devname
, arg
, len
);
2637 else if (!NILP (val
))
2638 error ("Bad option value for %s", name
);
2639 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2648 struct linger linger
;
2651 linger
.l_linger
= 0;
2652 if (TYPE_RANGED_INTEGERP (int, val
))
2653 linger
.l_linger
= XINT (val
);
2655 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2656 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2657 &linger
, sizeof (linger
));
2668 int setsockopt_errno
= errno
;
2669 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2673 return (1 << sopt
->optbit
);
2677 DEFUN ("set-network-process-option",
2678 Fset_network_process_option
, Sset_network_process_option
,
2680 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2681 See `make-network-process' for a list of options and values.
2682 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2683 OPTION is not a supported option, return nil instead; otherwise return t.
2685 If PROCESS is a non-blocking network process that hasn't been fully
2686 set up yet, this function will block until socket setup has completed. */)
2687 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2690 struct Lisp_Process
*p
;
2692 CHECK_PROCESS (process
);
2693 p
= XPROCESS (process
);
2694 if (!NETCONN1_P (p
))
2695 error ("Process is not a network process");
2697 wait_for_socket_fds (process
, "set-network-process-option");
2701 error ("Process is not running");
2703 if (set_socket_option (s
, option
, value
))
2705 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2709 if (NILP (no_error
))
2710 error ("Unknown or unsupported option");
2716 DEFUN ("serial-process-configure",
2717 Fserial_process_configure
,
2718 Sserial_process_configure
,
2720 doc
: /* Configure speed, bytesize, etc. of a serial process.
2722 Arguments are specified as keyword/argument pairs. Attributes that
2723 are not given are re-initialized from the process's current
2724 configuration (available via the function `process-contact') or set to
2725 reasonable default values. The following arguments are defined:
2731 -- Any of these arguments can be given to identify the process that is
2732 to be configured. If none of these arguments is given, the current
2733 buffer's process is used.
2735 :speed SPEED -- SPEED is the speed of the serial port in bits per
2736 second, also called baud rate. Any value can be given for SPEED, but
2737 most serial ports work only at a few defined values between 1200 and
2738 115200, with 9600 being the most common value. If SPEED is nil, the
2739 serial port is not configured any further, i.e., all other arguments
2740 are ignored. This may be useful for special serial ports such as
2741 Bluetooth-to-serial converters which can only be configured through AT
2742 commands. A value of nil for SPEED can be used only when passed
2743 through `make-serial-process' or `serial-term'.
2745 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2746 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2748 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2749 `odd' (use odd parity), or the symbol `even' (use even parity). If
2750 PARITY is not given, no parity is used.
2752 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2753 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2754 is not given or nil, 1 stopbit is used.
2756 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2757 flowcontrol to be used, which is either nil (don't use flowcontrol),
2758 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2759 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2760 flowcontrol is used.
2762 `serial-process-configure' is called by `make-serial-process' for the
2763 initial configuration of the serial port.
2767 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2769 \(serial-process-configure
2770 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2772 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2774 usage: (serial-process-configure &rest ARGS) */)
2775 (ptrdiff_t nargs
, Lisp_Object
*args
)
2777 struct Lisp_Process
*p
;
2778 Lisp_Object contact
= Qnil
;
2779 Lisp_Object proc
= Qnil
;
2781 contact
= Flist (nargs
, args
);
2783 proc
= Fplist_get (contact
, QCprocess
);
2785 proc
= Fplist_get (contact
, QCname
);
2787 proc
= Fplist_get (contact
, QCbuffer
);
2789 proc
= Fplist_get (contact
, QCport
);
2790 proc
= get_process (proc
);
2791 p
= XPROCESS (proc
);
2792 if (!EQ (p
->type
, Qserial
))
2793 error ("Not a serial process");
2795 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2798 serial_configure (p
, contact
);
2802 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2804 doc
: /* Create and return a serial port process.
2806 In Emacs, serial port connections are represented by process objects,
2807 so input and output work as for subprocesses, and `delete-process'
2808 closes a serial port connection. However, a serial process has no
2809 process id, it cannot be signaled, and the status codes are different
2810 from normal processes.
2812 `make-serial-process' creates a process and a buffer, on which you
2813 probably want to use `process-send-string'. Try \\[serial-term] for
2814 an interactive terminal. See below for examples.
2816 Arguments are specified as keyword/argument pairs. The following
2817 arguments are defined:
2819 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2820 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2821 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2822 the backslashes in strings).
2824 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2825 which this function calls.
2827 :name NAME -- NAME is the name of the process. If NAME is not given,
2828 the value of PORT is used.
2830 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2831 with the process. Process output goes at the end of that buffer,
2832 unless you specify an output stream or filter function to handle the
2833 output. If BUFFER is not given, the value of NAME is used.
2835 :coding CODING -- If CODING is a symbol, it specifies the coding
2836 system used for both reading and writing for this process. If CODING
2837 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2838 ENCODING is used for writing.
2840 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2841 the process is running. If BOOL is not given, query before exiting.
2843 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2844 In the stopped state, a serial process does not accept incoming data,
2845 but you can send outgoing data. The stopped state is cleared by
2846 `continue-process' and set by `stop-process'.
2848 :filter FILTER -- Install FILTER as the process filter.
2850 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2852 :plist PLIST -- Install PLIST as the initial plist of the process.
2858 -- This function calls `serial-process-configure' to handle these
2861 The original argument list, possibly modified by later configuration,
2862 is available via the function `process-contact'.
2866 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2868 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2870 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2872 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2874 usage: (make-serial-process &rest ARGS) */)
2875 (ptrdiff_t nargs
, Lisp_Object
*args
)
2878 Lisp_Object proc
, contact
, port
;
2879 struct Lisp_Process
*p
;
2880 Lisp_Object name
, buffer
;
2881 Lisp_Object tem
, val
;
2882 ptrdiff_t specpdl_count
;
2887 contact
= Flist (nargs
, args
);
2889 port
= Fplist_get (contact
, QCport
);
2891 error ("No port specified");
2892 CHECK_STRING (port
);
2894 if (NILP (Fplist_member (contact
, QCspeed
)))
2895 error (":speed not specified");
2896 if (!NILP (Fplist_get (contact
, QCspeed
)))
2897 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2899 name
= Fplist_get (contact
, QCname
);
2902 CHECK_STRING (name
);
2903 proc
= make_process (name
);
2904 specpdl_count
= SPECPDL_INDEX ();
2905 record_unwind_protect (remove_process
, proc
);
2906 p
= XPROCESS (proc
);
2908 fd
= serial_open (port
);
2909 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2912 if (fd
> max_process_desc
)
2913 max_process_desc
= fd
;
2914 chan_process
[fd
] = proc
;
2916 buffer
= Fplist_get (contact
, QCbuffer
);
2919 buffer
= Fget_buffer_create (buffer
);
2920 pset_buffer (p
, buffer
);
2922 pset_childp (p
, contact
);
2923 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2924 pset_type (p
, Qserial
);
2925 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2926 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2927 eassert (NILP (p
->log
));
2928 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2929 p
->kill_without_query
= 1;
2930 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2931 pset_command (p
, Qt
);
2932 eassert (! p
->pty_flag
);
2934 if (!EQ (p
->command
, Qt
))
2936 FD_SET (fd
, &input_wait_mask
);
2937 FD_SET (fd
, &non_keyboard_wait_mask
);
2940 if (BUFFERP (buffer
))
2942 set_marker_both (p
->mark
, buffer
,
2943 BUF_ZV (XBUFFER (buffer
)),
2944 BUF_ZV_BYTE (XBUFFER (buffer
)));
2947 tem
= Fplist_member (contact
, QCcoding
);
2948 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2954 val
= XCAR (XCDR (tem
));
2958 else if (!NILP (Vcoding_system_for_read
))
2959 val
= Vcoding_system_for_read
;
2960 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2961 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2963 pset_decode_coding_system (p
, val
);
2968 val
= XCAR (XCDR (tem
));
2972 else if (!NILP (Vcoding_system_for_write
))
2973 val
= Vcoding_system_for_write
;
2974 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2975 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2977 pset_encode_coding_system (p
, val
);
2979 setup_process_coding_systems (proc
);
2980 pset_decoding_buf (p
, empty_unibyte_string
);
2981 eassert (p
->decoding_carryover
== 0);
2982 pset_encoding_buf (p
, empty_unibyte_string
);
2983 p
->inherit_coding_system_flag
2984 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2986 Fserial_process_configure (nargs
, args
);
2988 specpdl_ptr
= specpdl
+ specpdl_count
;
2994 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2995 Lisp_Object service
, Lisp_Object name
)
2998 struct Lisp_Process
*p
= XPROCESS (proc
);
2999 Lisp_Object contact
= p
->childp
;
3000 Lisp_Object coding_systems
= Qt
;
3003 tem
= Fplist_member (contact
, QCcoding
);
3004 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3005 tem
= Qnil
; /* No error message (too late!). */
3007 /* Setup coding systems for communicating with the network stream. */
3008 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3012 val
= XCAR (XCDR (tem
));
3016 else if (!NILP (Vcoding_system_for_read
))
3017 val
= Vcoding_system_for_read
;
3018 else if ((!NILP (p
->buffer
)
3019 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
3020 || (NILP (p
->buffer
)
3021 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3022 /* We dare not decode end-of-line format by setting VAL to
3023 Qraw_text, because the existing Emacs Lisp libraries
3024 assume that they receive bare code including a sequence of
3029 if (NILP (host
) || NILP (service
))
3030 coding_systems
= Qnil
;
3032 coding_systems
= CALLN (Ffind_operation_coding_system
,
3033 Qopen_network_stream
, name
, p
->buffer
,
3035 if (CONSP (coding_systems
))
3036 val
= XCAR (coding_systems
);
3037 else if (CONSP (Vdefault_process_coding_system
))
3038 val
= XCAR (Vdefault_process_coding_system
);
3042 pset_decode_coding_system (p
, val
);
3046 val
= XCAR (XCDR (tem
));
3050 else if (!NILP (Vcoding_system_for_write
))
3051 val
= Vcoding_system_for_write
;
3052 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3056 if (EQ (coding_systems
, Qt
))
3058 if (NILP (host
) || NILP (service
))
3059 coding_systems
= Qnil
;
3061 coding_systems
= CALLN (Ffind_operation_coding_system
,
3062 Qopen_network_stream
, name
, p
->buffer
,
3065 if (CONSP (coding_systems
))
3066 val
= XCDR (coding_systems
);
3067 else if (CONSP (Vdefault_process_coding_system
))
3068 val
= XCDR (Vdefault_process_coding_system
);
3072 pset_encode_coding_system (p
, val
);
3074 pset_decoding_buf (p
, empty_unibyte_string
);
3075 p
->decoding_carryover
= 0;
3076 pset_encoding_buf (p
, empty_unibyte_string
);
3078 p
->inherit_coding_system_flag
3079 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3084 finish_after_tls_connection (Lisp_Object proc
)
3086 struct Lisp_Process
*p
= XPROCESS (proc
);
3087 Lisp_Object contact
= p
->childp
;
3088 Lisp_Object result
= Qt
;
3090 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3091 result
= call3 (Qnsm_verify_connection
,
3093 Fplist_get (contact
, QChost
),
3094 Fplist_get (contact
, QCservice
));
3098 pset_status (p
, list2 (Qfailed
,
3099 build_string ("The Network Security Manager stopped the connections")));
3100 deactivate_process (proc
);
3102 else if (p
->outfd
< 0)
3104 /* The counterparty may have closed the connection (especially
3105 if the NSM prompt above take a long time), so recheck the file
3107 pset_status (p
, Qfailed
);
3108 deactivate_process (proc
);
3110 else if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3112 /* If we cleared the connection wait mask before we did the TLS
3113 setup, then we have to say that the process is finally "open"
3115 pset_status (p
, Qrun
);
3116 /* Execute the sentinel here. If we had relied on status_notify
3117 to do it later, it will read input from the process before
3118 calling the sentinel. */
3119 exec_sentinel (proc
, build_string ("open\n"));
3125 connect_network_socket (Lisp_Object proc
, Lisp_Object addrinfos
,
3126 Lisp_Object use_external_socket_p
)
3128 ptrdiff_t count
= SPECPDL_INDEX ();
3129 int s
= -1, outch
, inch
;
3132 struct sockaddr
*sa
= NULL
;
3135 struct Lisp_Process
*p
= XPROCESS (proc
);
3136 Lisp_Object contact
= p
->childp
;
3138 int socket_to_use
= -1;
3140 if (!NILP (use_external_socket_p
))
3142 socket_to_use
= external_sock_fd
;
3144 /* Ensure we don't consume the external socket twice. */
3145 external_sock_fd
= -1;
3148 /* Do this in case we never enter the while-loop below. */
3151 while (!NILP (addrinfos
))
3153 Lisp_Object addrinfo
= XCAR (addrinfos
);
3154 addrinfos
= XCDR (addrinfos
);
3155 int protocol
= XINT (XCAR (addrinfo
));
3156 Lisp_Object ip_address
= XCDR (addrinfo
);
3162 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3165 sa
= xmalloc (addrlen
);
3166 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3171 int socktype
= p
->socktype
| SOCK_CLOEXEC
;
3172 if (p
->is_non_blocking_client
)
3173 socktype
|= SOCK_NONBLOCK
;
3174 s
= socket (family
, socktype
, protocol
);
3182 if (p
->is_non_blocking_client
&& ! (SOCK_NONBLOCK
&& socket_to_use
< 0))
3184 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3190 if (0 <= socket_to_use
)
3196 #ifdef DATAGRAM_SOCKETS
3197 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3199 #endif /* DATAGRAM_SOCKETS */
3201 /* Make us close S if quit. */
3202 record_unwind_protect_int (close_file_unwind
, s
);
3204 /* Parse network options in the arg list. We simply ignore anything
3205 which isn't a known option (including other keywords). An error
3206 is signaled if setting a known option fails. */
3208 Lisp_Object params
= contact
, key
, val
;
3210 while (!NILP (params
))
3212 key
= XCAR (params
);
3213 params
= XCDR (params
);
3214 val
= XCAR (params
);
3215 params
= XCDR (params
);
3216 optbits
|= set_socket_option (s
, key
, val
);
3222 /* Configure as a server socket. */
3224 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3225 explicit :reuseaddr key to override this. */
3226 #ifdef HAVE_LOCAL_SOCKETS
3227 if (family
!= AF_LOCAL
)
3229 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3232 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3233 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3236 /* If passed a socket descriptor, it should be already bound. */
3237 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3238 report_file_error ("Cannot bind server socket", Qnil
);
3240 #ifdef HAVE_GETSOCKNAME
3243 struct sockaddr_in sa1
;
3244 socklen_t len1
= sizeof (sa1
);
3245 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3247 Lisp_Object service
;
3248 service
= make_number (ntohs (sa1
.sin_port
));
3249 contact
= Fplist_put (contact
, QCservice
, service
);
3250 /* Save the port number so that we can stash it in
3251 the process object later. */
3252 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3257 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3258 report_file_error ("Cannot listen on server socket", Qnil
);
3266 ret
= connect (s
, sa
, addrlen
);
3269 if (ret
== 0 || xerrno
== EISCONN
)
3271 /* The unwind-protect will be discarded afterwards.
3272 Likewise for immediate_quit. */
3276 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3280 if (xerrno
== EINTR
)
3282 /* Unlike most other syscalls connect() cannot be called
3283 again. (That would return EALREADY.) The proper way to
3284 wait for completion is pselect(). */
3292 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3298 report_file_error ("Failed select", Qnil
);
3302 len
= sizeof xerrno
;
3303 eassert (FD_ISSET (s
, &fdset
));
3304 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3305 report_file_error ("Failed getsockopt", Qnil
);
3308 if (NILP (addrinfos
))
3309 report_file_errno ("Failed connect", Qnil
, xerrno
);
3311 #endif /* !WINDOWSNT */
3315 /* Discard the unwind protect closing S. */
3316 specpdl_ptr
= specpdl
+ count
;
3319 if (0 <= socket_to_use
)
3323 if (xerrno
== EINTR
)
3330 #ifdef DATAGRAM_SOCKETS
3331 if (p
->socktype
== SOCK_DGRAM
)
3333 if (datagram_address
[s
].sa
)
3336 datagram_address
[s
].sa
= xmalloc (addrlen
);
3337 datagram_address
[s
].len
= addrlen
;
3341 memset (datagram_address
[s
].sa
, 0, addrlen
);
3342 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3345 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3346 if (rlen
!= 0 && rfamily
== family
3348 conv_lisp_to_sockaddr (rfamily
, remote
,
3349 datagram_address
[s
].sa
, rlen
);
3353 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3357 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3358 conv_sockaddr_to_lisp (sa
, addrlen
));
3359 #ifdef HAVE_GETSOCKNAME
3362 struct sockaddr_in sa1
;
3363 socklen_t len1
= sizeof (sa1
);
3364 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3365 contact
= Fplist_put (contact
, QClocal
,
3366 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3375 /* If non-blocking got this far - and failed - assume non-blocking is
3376 not supported after all. This is probably a wrong assumption, but
3377 the normal blocking calls to open-network-stream handles this error
3379 if (p
->is_non_blocking_client
)
3382 report_file_errno ((p
->is_server
3383 ? "make server process failed"
3384 : "make client process failed"),
3391 chan_process
[inch
] = proc
;
3393 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3395 p
= XPROCESS (proc
);
3396 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3400 /* Discard the unwind protect for closing S, if any. */
3401 specpdl_ptr
= specpdl
+ count
;
3403 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3404 pset_status (p
, Qlisten
);
3406 /* Make the process marker point into the process buffer (if any). */
3407 if (BUFFERP (p
->buffer
))
3408 set_marker_both (p
->mark
, p
->buffer
,
3409 BUF_ZV (XBUFFER (p
->buffer
)),
3410 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3412 if (p
->is_non_blocking_client
)
3414 /* We may get here if connect did succeed immediately. However,
3415 in that case, we still need to signal this like a non-blocking
3417 if (! (connecting_status (p
->status
)
3418 && EQ (XCDR (p
->status
), addrinfos
)))
3419 pset_status (p
, Fcons (Qconnect
, addrinfos
));
3420 if (!FD_ISSET (inch
, &connect_wait_mask
))
3422 FD_SET (inch
, &connect_wait_mask
);
3423 FD_SET (inch
, &write_mask
);
3424 num_pending_connects
++;
3428 /* A server may have a client filter setting of Qt, but it must
3429 still listen for incoming connects unless it is stopped. */
3430 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3431 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3433 FD_SET (inch
, &input_wait_mask
);
3434 FD_SET (inch
, &non_keyboard_wait_mask
);
3437 if (inch
> max_process_desc
)
3438 max_process_desc
= inch
;
3440 /* Set up the masks based on the process filter. */
3441 set_process_filter_masks (p
);
3443 setup_process_coding_systems (proc
);
3446 /* Continue the asynchronous connection. */
3447 if (!NILP (p
->gnutls_boot_parameters
))
3449 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3451 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3452 p
->gnutls_boot_parameters
= Qnil
;
3454 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3455 /* Run sentinels, etc. */
3456 finish_after_tls_connection (proc
);
3457 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3459 deactivate_process (proc
);
3461 pset_status (p
, list2 (Qfailed
,
3462 build_string ("TLS negotiation failed")));
3464 pset_status (p
, list2 (Qfailed
, boot
));
3471 /* Create a network stream/datagram client/server process. Treated
3472 exactly like a normal process when reading and writing. Primary
3473 differences are in status display and process deletion. A network
3474 connection has no PID; you cannot signal it. All you can do is
3475 stop/continue it and deactivate/close it via delete-process. */
3477 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3479 doc
: /* Create and return a network server or client process.
3481 In Emacs, network connections are represented by process objects, so
3482 input and output work as for subprocesses and `delete-process' closes
3483 a network connection. However, a network process has no process id,
3484 it cannot be signaled, and the status codes are different from normal
3487 Arguments are specified as keyword/argument pairs. The following
3488 arguments are defined:
3490 :name NAME -- NAME is name for process. It is modified if necessary
3493 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3494 with the process. Process output goes at end of that buffer, unless
3495 you specify an output stream or filter function to handle the output.
3496 BUFFER may be also nil, meaning that this process is not associated
3499 :host HOST -- HOST is name of the host to connect to, or its IP
3500 address. The symbol `local' specifies the local host. If specified
3501 for a server process, it must be a valid name or address for the local
3502 host, and only clients connecting to that address will be accepted.
3504 :service SERVICE -- SERVICE is name of the service desired, or an
3505 integer specifying a port number to connect to. If SERVICE is t,
3506 a random port number is selected for the server. A port number can
3507 be specified as an integer string, e.g., "80", as well as an integer.
3509 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3510 stream type connection, `datagram' creates a datagram type connection,
3511 `seqpacket' creates a reliable datagram connection.
3513 :family FAMILY -- FAMILY is the address (and protocol) family for the
3514 service specified by HOST and SERVICE. The default (nil) is to use
3515 whatever address family (IPv4 or IPv6) that is defined for the host
3516 and port number specified by HOST and SERVICE. Other address families
3518 local -- for a local (i.e. UNIX) address specified by SERVICE.
3519 ipv4 -- use IPv4 address family only.
3520 ipv6 -- use IPv6 address family only.
3522 :local ADDRESS -- ADDRESS is the local address used for the connection.
3523 This parameter is ignored when opening a client process. When specified
3524 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3526 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3527 connection. This parameter is ignored when opening a stream server
3528 process. For a datagram server process, it specifies the initial
3529 setting of the remote datagram address. When specified for a client
3530 process, the FAMILY, HOST, and SERVICE args are ignored.
3532 The format of ADDRESS depends on the address family:
3533 - An IPv4 address is represented as an vector of integers [A B C D P]
3534 corresponding to numeric IP address A.B.C.D and port number P.
3535 - A local address is represented as a string with the address in the
3536 local address space.
3537 - An "unsupported family" address is represented by a cons (F . AV)
3538 where F is the family number and AV is a vector containing the socket
3539 address data with one element per address data byte. Do not rely on
3540 this format in portable code, as it may depend on implementation
3541 defined constants, data sizes, and data structure alignment.
3543 :coding CODING -- If CODING is a symbol, it specifies the coding
3544 system used for both reading and writing for this process. If CODING
3545 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3546 ENCODING is used for writing.
3548 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3549 process, return without waiting for the connection to complete;
3550 instead, the sentinel function will be called with second arg matching
3551 "open" (if successful) or "failed" when the connect completes.
3552 Default is to use a blocking connect (i.e. wait) for stream type
3555 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3556 running when Emacs is exited.
3558 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3559 In the stopped state, a server process does not accept new
3560 connections, and a client process does not handle incoming traffic.
3561 The stopped state is cleared by `continue-process' and set by
3564 :filter FILTER -- Install FILTER as the process filter.
3566 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3567 process filter are multibyte, otherwise they are unibyte.
3568 If this keyword is not specified, the strings are multibyte if
3569 the default value of `enable-multibyte-characters' is non-nil.
3571 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3573 :log LOG -- Install LOG as the server process log function. This
3574 function is called when the server accepts a network connection from a
3575 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3576 is the server process, CLIENT is the new process for the connection,
3577 and MESSAGE is a string.
3579 :plist PLIST -- Install PLIST as the new process's initial plist.
3581 :tls-parameters LIST -- is a list that should be supplied if you're
3582 opening a TLS connection. The first element is the TLS type (either
3583 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3584 be a keyword list accepted by gnutls-boot (as returned by
3585 `gnutls-boot-parameters').
3587 :server QLEN -- if QLEN is non-nil, create a server process for the
3588 specified FAMILY, SERVICE, and connection type (stream or datagram).
3589 If QLEN is an integer, it is used as the max. length of the server's
3590 pending connection queue (also known as the backlog); the default
3591 queue length is 5. Default is to create a client process.
3593 The following network options can be specified for this connection:
3595 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3596 :dontroute BOOL -- Only send to directly connected hosts.
3597 :keepalive BOOL -- Send keep-alive messages on network stream.
3598 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3599 :oobinline BOOL -- Place out-of-band data in receive data stream.
3600 :priority INT -- Set protocol defined priority for sent packets.
3601 :reuseaddr BOOL -- Allow reusing a recently used local address
3602 (this is allowed by default for a server process).
3603 :bindtodevice NAME -- bind to interface NAME. Using this may require
3604 special privileges on some systems.
3605 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3606 been passed to Emacs. If Emacs wasn't
3607 passed a socket, this option is silently
3611 Consult the relevant system programmer's manual pages for more
3612 information on using these options.
3615 A server process will listen for and accept connections from clients.
3616 When a client connection is accepted, a new network process is created
3617 for the connection with the following parameters:
3619 - The client's process name is constructed by concatenating the server
3620 process's NAME and a client identification string.
3621 - If the FILTER argument is non-nil, the client process will not get a
3622 separate process buffer; otherwise, the client's process buffer is a newly
3623 created buffer named after the server process's BUFFER name or process
3624 NAME concatenated with the client identification string.
3625 - The connection type and the process filter and sentinel parameters are
3626 inherited from the server process's TYPE, FILTER and SENTINEL.
3627 - The client process's contact info is set according to the client's
3628 addressing information (typically an IP address and a port number).
3629 - The client process's plist is initialized from the server's plist.
3631 Notice that the FILTER and SENTINEL args are never used directly by
3632 the server process. Also, the BUFFER argument is not used directly by
3633 the server process, but via the optional :log function, accepted (and
3634 failed) connections may be logged in the server process's buffer.
3636 The original argument list, modified with the actual connection
3637 information, is available via the `process-contact' function.
3639 usage: (make-network-process &rest ARGS) */)
3640 (ptrdiff_t nargs
, Lisp_Object
*args
)
3643 Lisp_Object contact
;
3644 struct Lisp_Process
*p
;
3645 const char *portstring
;
3646 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3647 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3648 #ifdef HAVE_LOCAL_SOCKETS
3649 struct sockaddr_un address_un
;
3653 Lisp_Object name
, buffer
, host
, service
, address
;
3654 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3655 Lisp_Object addrinfos
= Qnil
;
3658 enum { any_protocol
= 0 };
3659 #ifdef HAVE_GETADDRINFO_A
3660 struct gaicb
*dns_request
= NULL
;
3662 ptrdiff_t count
= SPECPDL_INDEX ();
3667 /* Save arguments for process-contact and clone-process. */
3668 contact
= Flist (nargs
, args
);
3671 /* Ensure socket support is loaded if available. */
3672 init_winsock (TRUE
);
3675 /* :type TYPE (nil: stream, datagram */
3676 tem
= Fplist_get (contact
, QCtype
);
3678 socktype
= SOCK_STREAM
;
3679 #ifdef DATAGRAM_SOCKETS
3680 else if (EQ (tem
, Qdatagram
))
3681 socktype
= SOCK_DGRAM
;
3683 #ifdef HAVE_SEQPACKET
3684 else if (EQ (tem
, Qseqpacket
))
3685 socktype
= SOCK_SEQPACKET
;
3688 error ("Unsupported connection type");
3690 name
= Fplist_get (contact
, QCname
);
3691 buffer
= Fplist_get (contact
, QCbuffer
);
3692 filter
= Fplist_get (contact
, QCfilter
);
3693 sentinel
= Fplist_get (contact
, QCsentinel
);
3694 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3696 CHECK_STRING (name
);
3698 /* :local ADDRESS or :remote ADDRESS */
3699 tem
= Fplist_get (contact
, QCserver
);
3701 address
= Fplist_get (contact
, QCremote
);
3703 address
= Fplist_get (contact
, QClocal
);
3704 if (!NILP (address
))
3706 host
= service
= Qnil
;
3708 if (!get_lisp_to_sockaddr_size (address
, &family
))
3709 error ("Malformed :address");
3711 addrinfos
= list1 (Fcons (make_number (any_protocol
), address
));
3715 /* :family FAMILY -- nil (for Inet), local, or integer. */
3716 tem
= Fplist_get (contact
, QCfamily
);
3725 #ifdef HAVE_LOCAL_SOCKETS
3726 else if (EQ (tem
, Qlocal
))
3730 else if (EQ (tem
, Qipv6
))
3733 else if (EQ (tem
, Qipv4
))
3735 else if (TYPE_RANGED_INTEGERP (int, tem
))
3736 family
= XINT (tem
);
3738 error ("Unknown address family");
3740 /* :service SERVICE -- string, integer (port number), or t (random port). */
3741 service
= Fplist_get (contact
, QCservice
);
3743 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3744 host
= Fplist_get (contact
, QChost
);
3747 /* The "connection" function gets it bind info from the address we're
3748 given, so use this dummy address if nothing is specified. */
3749 #ifdef HAVE_LOCAL_SOCKETS
3750 if (family
!= AF_LOCAL
)
3752 host
= build_string ("127.0.0.1");
3756 if (EQ (host
, Qlocal
))
3757 /* Depending on setup, "localhost" may map to different IPv4 and/or
3758 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3759 host
= build_string ("127.0.0.1");
3760 CHECK_STRING (host
);
3763 #ifdef HAVE_LOCAL_SOCKETS
3764 if (family
== AF_LOCAL
)
3768 message (":family local ignores the :host property");
3769 contact
= Fplist_put (contact
, QChost
, Qnil
);
3772 CHECK_STRING (service
);
3773 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3774 error ("Service name too long");
3775 addrinfos
= list1 (Fcons (make_number (any_protocol
), service
));
3780 /* Slow down polling to every ten seconds.
3781 Some kernels have a bug which causes retrying connect to fail
3782 after a connect. Polling can interfere with gethostbyname too. */
3783 #ifdef POLL_FOR_INPUT
3784 if (socktype
!= SOCK_DGRAM
)
3786 record_unwind_protect_void (run_all_atimers
);
3787 bind_polling_period (10);
3793 /* SERVICE can either be a string or int.
3794 Convert to a C string for later use by getaddrinfo. */
3795 if (EQ (service
, Qt
))
3800 else if (INTEGERP (service
))
3802 portstring
= portbuf
;
3803 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3807 CHECK_STRING (service
);
3808 portstring
= SSDATA (service
);
3809 portstringlen
= SBYTES (service
);
3813 #ifdef HAVE_GETADDRINFO_A
3814 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3816 ptrdiff_t hostlen
= SBYTES (host
);
3820 struct addrinfo hints
;
3821 char str
[FLEXIBLE_ARRAY_MEMBER
];
3822 } *req
= xmalloc (FLEXSIZEOF (struct req
, str
,
3823 hostlen
+ 1 + portstringlen
+ 1));
3824 dns_request
= &req
->gaicb
;
3825 dns_request
->ar_name
= req
->str
;
3826 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3827 dns_request
->ar_request
= &req
->hints
;
3828 dns_request
->ar_result
= NULL
;
3829 memset (&req
->hints
, 0, sizeof req
->hints
);
3830 req
->hints
.ai_family
= family
;
3831 req
->hints
.ai_socktype
= socktype
;
3832 strcpy (req
->str
, SSDATA (host
));
3833 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3835 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3837 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3841 #endif /* HAVE_GETADDRINFO_A */
3843 /* If we have a host, use getaddrinfo to resolve both host and service.
3844 Otherwise, use getservbyname to lookup the service. */
3848 struct addrinfo
*res
, *lres
;
3854 struct addrinfo hints
;
3855 memset (&hints
, 0, sizeof hints
);
3856 hints
.ai_family
= family
;
3857 hints
.ai_socktype
= socktype
;
3859 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3861 #ifdef HAVE_GAI_STRERROR
3863 synchronize_system_messages_locale ();
3864 char const *str
= gai_strerror (ret
);
3865 if (! NILP (Vlocale_coding_system
))
3866 str
= SSDATA (code_convert_string_norecord
3867 (build_string (str
), Vlocale_coding_system
, 0));
3868 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3871 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3875 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3876 addrinfos
= Fcons (conv_addrinfo_to_lisp (lres
), addrinfos
);
3878 addrinfos
= Fnreverse (addrinfos
);
3885 /* No hostname has been specified (e.g., a local server process). */
3887 if (EQ (service
, Qt
))
3889 else if (INTEGERP (service
))
3890 port
= XINT (service
);
3893 CHECK_STRING (service
);
3896 if (SBYTES (service
) != 0)
3898 /* Allow the service to be a string containing the port number,
3899 because that's allowed if you have getaddrbyname. */
3901 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3902 if (service_end
== SSDATA (service
) + SBYTES (service
))
3906 struct servent
*svc_info
3907 = getservbyname (SSDATA (service
),
3908 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3910 port
= ntohs (svc_info
->s_port
);
3915 if (! (0 <= port
&& port
< 1 << 16))
3917 AUTO_STRING (unknown_service
, "Unknown service: %s");
3918 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3924 buffer
= Fget_buffer_create (buffer
);
3926 /* Unwind bind_polling_period. */
3927 unbind_to (count
, Qnil
);
3929 proc
= make_process (name
);
3930 record_unwind_protect (remove_process
, proc
);
3931 p
= XPROCESS (proc
);
3932 pset_childp (p
, contact
);
3933 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3934 pset_type (p
, Qnetwork
);
3936 pset_buffer (p
, buffer
);
3937 pset_sentinel (p
, sentinel
);
3938 pset_filter (p
, filter
);
3939 pset_log (p
, Fplist_get (contact
, QClog
));
3940 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3941 p
->kill_without_query
= 1;
3942 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3943 pset_command (p
, Qt
);
3944 eassert (p
->pid
== 0);
3946 eassert (! p
->is_non_blocking_client
);
3947 eassert (! p
->is_server
);
3949 p
->socktype
= socktype
;
3950 #ifdef HAVE_GETADDRINFO_A
3951 eassert (! p
->dns_request
);
3954 tem
= Fplist_get (contact
, QCtls_parameters
);
3956 p
->gnutls_boot_parameters
= tem
;
3959 set_network_socket_coding_system (proc
, host
, service
, name
);
3962 tem
= Fplist_get (contact
, QCserver
);
3965 /* Don't support network sockets when non-blocking mode is
3966 not available, since a blocked Emacs is not useful. */
3967 p
->is_server
= true;
3968 if (TYPE_RANGED_INTEGERP (int, tem
))
3969 p
->backlog
= XINT (tem
);
3973 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3974 && !NILP (Fplist_get (contact
, QCnowait
)))
3975 p
->is_non_blocking_client
= true;
3977 bool postpone_connection
= false;
3978 #ifdef HAVE_GETADDRINFO_A
3979 /* With async address resolution, the list of addresses is empty, so
3980 postpone connecting to the server. */
3981 if (!p
->is_server
&& NILP (addrinfos
))
3983 p
->dns_request
= dns_request
;
3984 p
->status
= list1 (Qconnect
);
3985 postpone_connection
= true;
3988 if (! postpone_connection
)
3989 connect_network_socket (proc
, addrinfos
, use_external_socket_p
);
3991 specpdl_ptr
= specpdl
+ count
;
3996 #ifdef HAVE_NET_IF_H
4000 network_interface_list (void)
4002 struct ifconf ifconf
;
4003 struct ifreq
*ifreq
;
4005 ptrdiff_t buf_size
= 512;
4010 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4013 count
= SPECPDL_INDEX ();
4014 record_unwind_protect_int (close_file_unwind
, s
);
4018 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4019 ifconf
.ifc_buf
= buf
;
4020 ifconf
.ifc_len
= buf_size
;
4021 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4028 while (ifconf
.ifc_len
== buf_size
);
4030 res
= unbind_to (count
, Qnil
);
4031 ifreq
= ifconf
.ifc_req
;
4032 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4034 struct ifreq
*ifq
= ifreq
;
4035 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4036 #define SIZEOF_IFREQ(sif) \
4037 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4038 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4040 int len
= SIZEOF_IFREQ (ifq
);
4042 int len
= sizeof (*ifreq
);
4044 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4045 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4047 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4050 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4051 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4052 res
= Fcons (Fcons (build_string (namebuf
),
4053 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4054 sizeof (struct sockaddr
))),
4061 #endif /* SIOCGIFCONF */
4063 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4067 const char *flag_sym
;
4070 static const struct ifflag_def ifflag_table
[] = {
4074 #ifdef IFF_BROADCAST
4075 { IFF_BROADCAST
, "broadcast" },
4078 { IFF_DEBUG
, "debug" },
4081 { IFF_LOOPBACK
, "loopback" },
4083 #ifdef IFF_POINTOPOINT
4084 { IFF_POINTOPOINT
, "pointopoint" },
4087 { IFF_RUNNING
, "running" },
4090 { IFF_NOARP
, "noarp" },
4093 { IFF_PROMISC
, "promisc" },
4095 #ifdef IFF_NOTRAILERS
4096 #ifdef NS_IMPL_COCOA
4097 /* Really means smart, notrailers is obsolete. */
4098 { IFF_NOTRAILERS
, "smart" },
4100 { IFF_NOTRAILERS
, "notrailers" },
4104 { IFF_ALLMULTI
, "allmulti" },
4107 { IFF_MASTER
, "master" },
4110 { IFF_SLAVE
, "slave" },
4112 #ifdef IFF_MULTICAST
4113 { IFF_MULTICAST
, "multicast" },
4116 { IFF_PORTSEL
, "portsel" },
4118 #ifdef IFF_AUTOMEDIA
4119 { IFF_AUTOMEDIA
, "automedia" },
4122 { IFF_DYNAMIC
, "dynamic" },
4125 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4128 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4131 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4134 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4137 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4143 network_interface_info (Lisp_Object ifname
)
4146 Lisp_Object res
= Qnil
;
4151 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4152 && defined HAVE_GETIFADDRS && defined LLADDR)
4153 struct ifaddrs
*ifap
;
4156 CHECK_STRING (ifname
);
4158 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4159 error ("interface name too long");
4160 lispstpcpy (rq
.ifr_name
, ifname
);
4162 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4165 count
= SPECPDL_INDEX ();
4166 record_unwind_protect_int (close_file_unwind
, s
);
4169 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4170 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4172 int flags
= rq
.ifr_flags
;
4173 const struct ifflag_def
*fp
;
4176 /* If flags is smaller than int (i.e. short) it may have the high bit set
4177 due to IFF_MULTICAST. In that case, sign extending it into
4179 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4180 flags
= (unsigned short) rq
.ifr_flags
;
4183 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4185 if (flags
& fp
->flag_bit
)
4187 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4188 flags
-= fp
->flag_bit
;
4191 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4195 elt
= Fcons (make_number (fnum
), elt
);
4200 res
= Fcons (elt
, res
);
4203 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4204 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4206 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4207 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4211 for (n
= 0; n
< 6; n
++)
4212 p
->contents
[n
] = make_number (((unsigned char *)
4213 &rq
.ifr_hwaddr
.sa_data
[0])
4215 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4217 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4218 if (getifaddrs (&ifap
) != -1)
4220 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4221 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4224 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4226 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4227 unsigned char linkaddr
[6];
4230 if (it
->ifa_addr
->sa_family
!= AF_LINK
4231 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4232 || sdl
->sdl_alen
!= 6)
4235 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4236 for (n
= 0; n
< 6; n
++)
4237 p
->contents
[n
] = make_number (linkaddr
[n
]);
4239 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4243 #ifdef HAVE_FREEIFADDRS
4247 #endif /* HAVE_GETIFADDRS && LLADDR */
4249 res
= Fcons (elt
, res
);
4252 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4253 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4256 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4257 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4259 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4263 res
= Fcons (elt
, res
);
4266 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4267 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4270 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4273 res
= Fcons (elt
, res
);
4276 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4277 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4280 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4283 res
= Fcons (elt
, res
);
4285 return unbind_to (count
, any
? res
: Qnil
);
4287 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4288 #endif /* defined (HAVE_NET_IF_H) */
4290 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4291 Snetwork_interface_list
, 0, 0, 0,
4292 doc
: /* Return an alist of all network interfaces and their network address.
4293 Each element is a cons, the car of which is a string containing the
4294 interface name, and the cdr is the network address in internal
4295 format; see the description of ADDRESS in `make-network-process'.
4297 If the information is not available, return nil. */)
4300 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4301 return network_interface_list ();
4307 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4308 Snetwork_interface_info
, 1, 1, 0,
4309 doc
: /* Return information about network interface named IFNAME.
4310 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4311 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4312 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4313 FLAGS is the current flags of the interface.
4315 Data that is unavailable is returned as nil. */)
4316 (Lisp_Object ifname
)
4318 #if ((defined HAVE_NET_IF_H \
4319 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4320 || defined SIOCGIFFLAGS)) \
4321 || defined WINDOWSNT)
4322 return network_interface_info (ifname
);
4328 /* Turn off input and output for process PROC. */
4331 deactivate_process (Lisp_Object proc
)
4334 struct Lisp_Process
*p
= XPROCESS (proc
);
4338 /* Delete GnuTLS structures in PROC, if any. */
4339 emacs_gnutls_deinit (proc
);
4340 #endif /* HAVE_GNUTLS */
4342 if (p
->read_output_delay
> 0)
4344 if (--process_output_delay_count
< 0)
4345 process_output_delay_count
= 0;
4346 p
->read_output_delay
= 0;
4347 p
->read_output_skip
= 0;
4350 /* Beware SIGCHLD hereabouts. */
4352 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4353 close_process_fd (&p
->open_fd
[i
]);
4355 inchannel
= p
->infd
;
4360 #ifdef DATAGRAM_SOCKETS
4361 if (DATAGRAM_CHAN_P (inchannel
))
4363 xfree (datagram_address
[inchannel
].sa
);
4364 datagram_address
[inchannel
].sa
= 0;
4365 datagram_address
[inchannel
].len
= 0;
4368 chan_process
[inchannel
] = Qnil
;
4369 FD_CLR (inchannel
, &input_wait_mask
);
4370 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4371 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4373 FD_CLR (inchannel
, &connect_wait_mask
);
4374 FD_CLR (inchannel
, &write_mask
);
4375 if (--num_pending_connects
< 0)
4378 if (inchannel
== max_process_desc
)
4380 /* We just closed the highest-numbered process input descriptor,
4381 so recompute the highest-numbered one now. */
4385 while (0 <= i
&& NILP (chan_process
[i
]));
4387 max_process_desc
= i
;
4393 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4395 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4396 It is given to their filter functions.
4397 Optional argument PROCESS means do not return until output has been
4398 received from PROCESS.
4400 Optional second argument SECONDS and third argument MILLISEC
4401 specify a timeout; return after that much time even if there is
4402 no subprocess output. If SECONDS is a floating point number,
4403 it specifies a fractional number of seconds to wait.
4404 The MILLISEC argument is obsolete and should be avoided.
4406 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4407 from PROCESS only, suspending reading output from other processes.
4408 If JUST-THIS-ONE is an integer, don't run any timers either.
4409 Return non-nil if we received any output from PROCESS (or, if PROCESS
4410 is nil, from any process) before the timeout expired. */)
4411 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4416 if (! NILP (process
))
4417 CHECK_PROCESS (process
);
4419 just_this_one
= Qnil
;
4421 if (!NILP (millisec
))
4422 { /* Obsolete calling convention using integers rather than floats. */
4423 CHECK_NUMBER (millisec
);
4425 seconds
= make_float (XINT (millisec
) / 1000.0);
4428 CHECK_NUMBER (seconds
);
4429 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4436 if (!NILP (seconds
))
4438 if (INTEGERP (seconds
))
4440 if (XINT (seconds
) > 0)
4442 secs
= XINT (seconds
);
4446 else if (FLOATP (seconds
))
4448 if (XFLOAT_DATA (seconds
) > 0)
4450 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4451 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4456 wrong_type_argument (Qnumberp
, seconds
);
4458 else if (! NILP (process
))
4462 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4464 !NILP (process
) ? XPROCESS (process
) : NULL
,
4465 (NILP (just_this_one
) ? 0
4466 : !INTEGERP (just_this_one
) ? 1 : -1))
4471 /* Accept a connection for server process SERVER on CHANNEL. */
4473 static EMACS_INT connect_counter
= 0;
4476 server_accept_connection (Lisp_Object server
, int channel
)
4478 Lisp_Object proc
, caller
, name
, buffer
;
4479 Lisp_Object contact
, host
, service
;
4480 struct Lisp_Process
*ps
= XPROCESS (server
);
4481 struct Lisp_Process
*p
;
4485 struct sockaddr_in in
;
4487 struct sockaddr_in6 in6
;
4489 #ifdef HAVE_LOCAL_SOCKETS
4490 struct sockaddr_un un
;
4493 socklen_t len
= sizeof saddr
;
4496 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4501 if (!would_block (code
) && !NILP (ps
->log
))
4502 call3 (ps
->log
, server
, Qnil
,
4503 concat3 (build_string ("accept failed with code"),
4504 Fnumber_to_string (make_number (code
)),
4505 build_string ("\n")));
4509 count
= SPECPDL_INDEX ();
4510 record_unwind_protect_int (close_file_unwind
, s
);
4514 /* Setup a new process to handle the connection. */
4516 /* Generate a unique identification of the caller, and build contact
4517 information for this process. */
4520 switch (saddr
.sa
.sa_family
)
4524 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4526 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4527 host
= CALLN (Fformat
, ipv4_format
,
4528 make_number (ip
[0]), make_number (ip
[1]),
4529 make_number (ip
[2]), make_number (ip
[3]));
4530 service
= make_number (ntohs (saddr
.in
.sin_port
));
4531 AUTO_STRING (caller_format
, " <%s:%d>");
4532 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4539 Lisp_Object args
[9];
4540 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4543 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4544 args
[0] = ipv6_format
;
4545 for (i
= 0; i
< 8; i
++)
4546 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4547 host
= CALLMANY (Fformat
, args
);
4548 service
= make_number (ntohs (saddr
.in
.sin_port
));
4549 AUTO_STRING (caller_format
, " <[%s]:%d>");
4550 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4555 #ifdef HAVE_LOCAL_SOCKETS
4559 caller
= Fnumber_to_string (make_number (connect_counter
));
4560 AUTO_STRING (space_less_than
, " <");
4561 AUTO_STRING (greater_than
, ">");
4562 caller
= concat3 (space_less_than
, caller
, greater_than
);
4566 /* Create a new buffer name for this process if it doesn't have a
4567 filter. The new buffer name is based on the buffer name or
4568 process name of the server process concatenated with the caller
4571 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4572 || EQ (ps
->filter
, Qt
)))
4576 buffer
= ps
->buffer
;
4578 buffer
= Fbuffer_name (buffer
);
4583 buffer
= concat2 (buffer
, caller
);
4584 buffer
= Fget_buffer_create (buffer
);
4588 /* Generate a unique name for the new server process. Combine the
4589 server process name with the caller identification. */
4591 name
= concat2 (ps
->name
, caller
);
4592 proc
= make_process (name
);
4594 chan_process
[s
] = proc
;
4596 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4598 p
= XPROCESS (proc
);
4600 /* Build new contact information for this setup. */
4601 contact
= Fcopy_sequence (ps
->childp
);
4602 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4603 contact
= Fplist_put (contact
, QChost
, host
);
4604 if (!NILP (service
))
4605 contact
= Fplist_put (contact
, QCservice
, service
);
4606 contact
= Fplist_put (contact
, QCremote
,
4607 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4608 #ifdef HAVE_GETSOCKNAME
4610 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4611 contact
= Fplist_put (contact
, QClocal
,
4612 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4615 pset_childp (p
, contact
);
4616 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4617 pset_type (p
, Qnetwork
);
4619 pset_buffer (p
, buffer
);
4620 pset_sentinel (p
, ps
->sentinel
);
4621 pset_filter (p
, ps
->filter
);
4622 eassert (NILP (p
->command
));
4623 eassert (p
->pid
== 0);
4625 /* Discard the unwind protect for closing S. */
4626 specpdl_ptr
= specpdl
+ count
;
4628 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4631 pset_status (p
, Qrun
);
4633 /* Client processes for accepted connections are not stopped initially. */
4634 if (!EQ (p
->filter
, Qt
))
4636 FD_SET (s
, &input_wait_mask
);
4637 FD_SET (s
, &non_keyboard_wait_mask
);
4640 if (s
> max_process_desc
)
4641 max_process_desc
= s
;
4643 /* Setup coding system for new process based on server process.
4644 This seems to be the proper thing to do, as the coding system
4645 of the new process should reflect the settings at the time the
4646 server socket was opened; not the current settings. */
4648 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4649 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4650 setup_process_coding_systems (proc
);
4652 pset_decoding_buf (p
, empty_unibyte_string
);
4653 eassert (p
->decoding_carryover
== 0);
4654 pset_encoding_buf (p
, empty_unibyte_string
);
4656 p
->inherit_coding_system_flag
4657 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4659 AUTO_STRING (dash
, "-");
4660 AUTO_STRING (nl
, "\n");
4661 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4663 if (!NILP (ps
->log
))
4665 AUTO_STRING (accept_from
, "accept from ");
4666 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4669 AUTO_STRING (open_from
, "open from ");
4670 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4673 #ifdef HAVE_GETADDRINFO_A
4675 check_for_dns (Lisp_Object proc
)
4677 struct Lisp_Process
*p
= XPROCESS (proc
);
4678 Lisp_Object addrinfos
= Qnil
;
4681 if (! p
->dns_request
)
4684 int ret
= gai_error (p
->dns_request
);
4685 if (ret
== EAI_INPROGRESS
)
4688 /* We got a response. */
4691 struct addrinfo
*res
;
4693 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4694 addrinfos
= Fcons (conv_addrinfo_to_lisp (res
), addrinfos
);
4696 addrinfos
= Fnreverse (addrinfos
);
4698 /* The DNS lookup failed. */
4699 else if (connecting_status (p
->status
))
4701 deactivate_process (proc
);
4702 pset_status (p
, (list2
4704 concat3 (build_string ("Name lookup of "),
4705 build_string (p
->dns_request
->ar_name
),
4706 build_string (" failed")))));
4709 free_dns_request (proc
);
4711 /* This process should not already be connected (or killed). */
4712 if (! connecting_status (p
->status
))
4718 #endif /* HAVE_GETADDRINFO_A */
4721 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4723 while (XPROCESS (process
)->infd
< 0
4724 && connecting_status (XPROCESS (process
)->status
))
4726 add_to_log ("Waiting for socket from %s...", build_string (name
));
4727 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4732 wait_while_connecting (Lisp_Object process
)
4734 while (connecting_status (XPROCESS (process
)->status
))
4736 add_to_log ("Waiting for connection...");
4737 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4742 wait_for_tls_negotiation (Lisp_Object process
)
4745 while (XPROCESS (process
)->gnutls_p
4746 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4748 add_to_log ("Waiting for TLS...");
4749 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4754 /* This variable is different from waiting_for_input in keyboard.c.
4755 It is used to communicate to a lisp process-filter/sentinel (via the
4756 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4757 for user-input when that process-filter was called.
4758 waiting_for_input cannot be used as that is by definition 0 when
4759 lisp code is being evalled.
4760 This is also used in record_asynch_buffer_change.
4761 For that purpose, this must be 0
4762 when not inside wait_reading_process_output. */
4763 static int waiting_for_user_input_p
;
4766 wait_reading_process_output_unwind (int data
)
4768 waiting_for_user_input_p
= data
;
4771 /* This is here so breakpoints can be put on it. */
4773 wait_reading_process_output_1 (void)
4777 /* Read and dispose of subprocess output while waiting for timeout to
4778 elapse and/or keyboard input to be available.
4782 If negative, gobble data immediately available but don't wait for any.
4785 an additional duration to wait, measured in nanoseconds
4786 If TIME_LIMIT is zero, then:
4787 If NSECS == 0, there is no limit.
4788 If NSECS > 0, the timeout consists of NSECS only.
4789 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4792 0 to ignore keyboard input, or
4793 1 to return when input is available, or
4794 -1 meaning caller will actually read the input, so don't throw to
4795 the quit handler, or
4797 DO_DISPLAY means redisplay should be done to show subprocess
4798 output that arrives.
4800 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4801 (and gobble terminal input into the buffer if any arrives).
4803 If WAIT_PROC is specified, wait until something arrives from that
4806 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4807 (suspending output from other processes). A negative value
4808 means don't run any timers either.
4810 Return positive if we received input from WAIT_PROC (or from any
4811 process if WAIT_PROC is null), zero if we attempted to receive
4812 input but got none, and negative if we didn't even try. */
4815 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4817 Lisp_Object wait_for_cell
,
4818 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4828 struct timespec timeout
, end_time
, timer_delay
;
4829 struct timespec got_output_end_time
= invalid_timespec ();
4830 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4831 int got_some_output
= -1;
4832 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4833 bool retry_for_async
;
4835 ptrdiff_t count
= SPECPDL_INDEX ();
4837 /* Close to the current time if known, an invalid timespec otherwise. */
4838 struct timespec now
= invalid_timespec ();
4840 FD_ZERO (&Available
);
4843 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4844 && !(CONSP (wait_proc
->status
)
4845 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4846 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4848 record_unwind_protect_int (wait_reading_process_output_unwind
,
4849 waiting_for_user_input_p
);
4850 waiting_for_user_input_p
= read_kbd
;
4852 if (TYPE_MAXIMUM (time_t) < time_limit
)
4853 time_limit
= TYPE_MAXIMUM (time_t);
4855 if (time_limit
< 0 || nsecs
< 0)
4857 else if (time_limit
> 0 || nsecs
> 0)
4860 now
= current_timespec ();
4861 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4868 bool process_skipped
= false;
4870 /* If calling from keyboard input, do not quit
4871 since we want to return C-g as an input character.
4872 Otherwise, do pending quit if requested. */
4875 else if (pending_signals
)
4876 process_pending_signals ();
4878 /* Exit now if the cell we're waiting for became non-nil. */
4879 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4882 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4884 Lisp_Object process_list_head
, aproc
;
4885 struct Lisp_Process
*p
;
4887 retry_for_async
= false;
4888 FOR_EACH_PROCESS(process_list_head
, aproc
)
4890 p
= XPROCESS (aproc
);
4892 if (! wait_proc
|| p
== wait_proc
)
4894 #ifdef HAVE_GETADDRINFO_A
4895 /* Check for pending DNS requests. */
4898 Lisp_Object addrinfos
= check_for_dns (aproc
);
4899 if (!NILP (addrinfos
) && !EQ (addrinfos
, Qt
))
4900 connect_network_socket (aproc
, addrinfos
, Qnil
);
4902 retry_for_async
= true;
4906 /* Continue TLS negotiation. */
4907 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4908 && p
->is_non_blocking_client
)
4910 gnutls_try_handshake (p
);
4911 p
->gnutls_handshakes_tried
++;
4913 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4915 gnutls_verify_boot (aproc
, Qnil
);
4916 finish_after_tls_connection (aproc
);
4920 retry_for_async
= true;
4921 if (p
->gnutls_handshakes_tried
4922 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4924 deactivate_process (aproc
);
4925 pset_status (p
, list2 (Qfailed
,
4926 build_string ("TLS negotiation failed")));
4934 #endif /* GETADDRINFO_A or GNUTLS */
4936 /* Compute time from now till when time limit is up. */
4937 /* Exit if already run out. */
4938 if (wait
== TIMEOUT
)
4940 if (!timespec_valid_p (now
))
4941 now
= current_timespec ();
4942 if (timespec_cmp (end_time
, now
) <= 0)
4944 timeout
= timespec_sub (end_time
, now
);
4947 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4949 /* Normally we run timers here.
4950 But not if wait_for_cell; in those cases,
4951 the wait is supposed to be short,
4952 and those callers cannot handle running arbitrary Lisp code here. */
4953 if (NILP (wait_for_cell
)
4954 && just_wait_proc
>= 0)
4958 unsigned old_timers_run
= timers_run
;
4959 struct buffer
*old_buffer
= current_buffer
;
4960 Lisp_Object old_window
= selected_window
;
4962 timer_delay
= timer_check ();
4964 /* If a timer has run, this might have changed buffers
4965 an alike. Make read_key_sequence aware of that. */
4966 if (timers_run
!= old_timers_run
4967 && (old_buffer
!= current_buffer
4968 || !EQ (old_window
, selected_window
))
4969 && waiting_for_user_input_p
== -1)
4970 record_asynch_buffer_change ();
4972 if (timers_run
!= old_timers_run
&& do_display
)
4973 /* We must retry, since a timer may have requeued itself
4974 and that could alter the time_delay. */
4975 redisplay_preserve_echo_area (9);
4979 while (!detect_input_pending ());
4981 /* If there is unread keyboard input, also return. */
4983 && requeued_events_pending_p ())
4986 /* This is so a breakpoint can be put here. */
4987 if (!timespec_valid_p (timer_delay
))
4988 wait_reading_process_output_1 ();
4991 /* Cause C-g and alarm signals to take immediate action,
4992 and cause input available signals to zero out timeout.
4994 It is important that we do this before checking for process
4995 activity. If we get a SIGCHLD after the explicit checks for
4996 process activity, timeout is the only way we will know. */
4998 set_waiting_for_input (&timeout
);
5000 /* If status of something has changed, and no input is
5001 available, notify the user of the change right away. After
5002 this explicit check, we'll let the SIGCHLD handler zap
5003 timeout to get our attention. */
5004 if (update_tick
!= process_tick
)
5009 if (kbd_on_hold_p ())
5012 Atemp
= input_wait_mask
;
5015 timeout
= make_timespec (0, 0);
5016 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
5018 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5019 NULL
, &timeout
, NULL
)
5022 /* It's okay for us to do this and then continue with
5023 the loop, since timeout has already been zeroed out. */
5024 clear_waiting_for_input ();
5025 got_some_output
= status_notify (NULL
, wait_proc
);
5026 if (do_display
) redisplay_preserve_echo_area (13);
5030 /* Don't wait for output from a non-running process. Just
5031 read whatever data has already been received. */
5032 if (wait_proc
&& wait_proc
->raw_status_new
)
5033 update_status (wait_proc
);
5035 && ! EQ (wait_proc
->status
, Qrun
)
5036 && ! connecting_status (wait_proc
->status
))
5038 bool read_some_bytes
= false;
5040 clear_waiting_for_input ();
5042 /* If data can be read from the process, do so until exhausted. */
5043 if (wait_proc
->infd
>= 0)
5045 XSETPROCESS (proc
, wait_proc
);
5049 int nread
= read_process_output (proc
, wait_proc
->infd
);
5052 if (errno
== EIO
|| would_block (errno
))
5057 if (got_some_output
< nread
)
5058 got_some_output
= nread
;
5061 read_some_bytes
= true;
5066 if (read_some_bytes
&& do_display
)
5067 redisplay_preserve_echo_area (10);
5072 /* Wait till there is something to do. */
5074 if (wait_proc
&& just_wait_proc
)
5076 if (wait_proc
->infd
< 0) /* Terminated. */
5078 FD_SET (wait_proc
->infd
, &Available
);
5082 else if (!NILP (wait_for_cell
))
5084 Available
= non_process_wait_mask
;
5091 Available
= non_keyboard_wait_mask
;
5093 Available
= input_wait_mask
;
5094 Writeok
= write_mask
;
5095 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5099 /* If frame size has changed or the window is newly mapped,
5100 redisplay now, before we start to wait. There is a race
5101 condition here; if a SIGIO arrives between now and the select
5102 and indicates that a frame is trashed, the select may block
5103 displaying a trashed screen. */
5104 if (frame_garbaged
&& do_display
)
5106 clear_waiting_for_input ();
5107 redisplay_preserve_echo_area (11);
5109 set_waiting_for_input (&timeout
);
5112 /* Skip the `select' call if input is available and we're
5113 waiting for keyboard input or a cell change (which can be
5114 triggered by processing X events). In the latter case, set
5115 nfds to 1 to avoid breaking the loop. */
5117 if ((read_kbd
|| !NILP (wait_for_cell
))
5118 && detect_input_pending ())
5120 nfds
= read_kbd
? 0 : 1;
5122 FD_ZERO (&Available
);
5126 /* Set the timeout for adaptive read buffering if any
5127 process has non-zero read_output_skip and non-zero
5128 read_output_delay, and we are not reading output for a
5129 specific process. It is not executed if
5130 Vprocess_adaptive_read_buffering is nil. */
5131 if (process_output_skip
&& check_delay
> 0)
5133 int adaptive_nsecs
= timeout
.tv_nsec
;
5134 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5135 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5136 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5138 proc
= chan_process
[channel
];
5141 /* Find minimum non-zero read_output_delay among the
5142 processes with non-zero read_output_skip. */
5143 if (XPROCESS (proc
)->read_output_delay
> 0)
5146 if (!XPROCESS (proc
)->read_output_skip
)
5148 FD_CLR (channel
, &Available
);
5149 process_skipped
= true;
5150 XPROCESS (proc
)->read_output_skip
= 0;
5151 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5152 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5155 timeout
= make_timespec (0, adaptive_nsecs
);
5156 process_output_skip
= 0;
5159 /* If we've got some output and haven't limited our timeout
5160 with adaptive read buffering, limit it. */
5161 if (got_some_output
> 0 && !process_skipped
5163 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5164 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5167 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5168 && timespec_valid_p (timer_delay
)
5169 && timespec_cmp (timer_delay
, timeout
) < 0)
5171 if (!timespec_valid_p (now
))
5172 now
= current_timespec ();
5173 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5174 if (!timespec_valid_p (got_output_end_time
)
5175 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5176 got_output_end_time
= timeout_abs
;
5177 timeout
= timer_delay
;
5180 got_output_end_time
= invalid_timespec ();
5182 /* NOW can become inaccurate if time can pass during pselect. */
5183 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5184 now
= invalid_timespec ();
5186 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5188 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5191 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5195 #if defined (HAVE_NS)
5197 #elif defined (HAVE_GLIB)
5202 (max (max_process_desc
, max_input_desc
) + 1,
5204 (check_write
? &Writeok
: 0),
5205 NULL
, &timeout
, NULL
);
5208 /* GnuTLS buffers data internally. In lowat mode it leaves
5209 some data in the TCP buffers so that select works, but
5210 with custom pull/push functions we need to check if some
5211 data is available in the buffers manually. */
5214 fd_set tls_available
;
5217 FD_ZERO (&tls_available
);
5220 /* We're not waiting on a specific process, so loop
5221 through all the channels and check for data.
5222 This is a workaround needed for some versions of
5223 the gnutls library -- 2.12.14 has been confirmed
5225 http://comments.gmane.org/gmane.emacs.devel/145074 */
5226 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5227 if (! NILP (chan_process
[channel
]))
5229 struct Lisp_Process
*p
=
5230 XPROCESS (chan_process
[channel
]);
5231 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5232 && ((emacs_gnutls_record_check_pending
5237 eassert (p
->infd
== channel
);
5238 FD_SET (p
->infd
, &tls_available
);
5245 /* Check this specific channel. */
5246 if (wait_proc
->gnutls_p
/* Check for valid process. */
5247 && wait_proc
->gnutls_state
5248 /* Do we have pending data? */
5249 && ((emacs_gnutls_record_check_pending
5250 (wait_proc
->gnutls_state
))
5254 eassert (0 <= wait_proc
->infd
);
5255 /* Set to Available. */
5256 FD_SET (wait_proc
->infd
, &tls_available
);
5261 Available
= tls_available
;
5268 /* Make C-g and alarm signals set flags again. */
5269 clear_waiting_for_input ();
5271 /* If we woke up due to SIGWINCH, actually change size now. */
5272 do_pending_window_change (0);
5276 /* Exit the main loop if we've passed the requested timeout,
5277 or aren't skipping processes and got some output and
5278 haven't lowered our timeout due to timers or SIGIO and
5279 have waited a long amount of time due to repeated
5281 struct timespec huge_timespec
5282 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION
);
5283 struct timespec cmp_time
= huge_timespec
;
5286 if (wait
== TIMEOUT
)
5287 cmp_time
= end_time
;
5288 if (!process_skipped
&& got_some_output
> 0
5289 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5291 if (!timespec_valid_p (got_output_end_time
))
5293 if (timespec_cmp (got_output_end_time
, cmp_time
) < 0)
5294 cmp_time
= got_output_end_time
;
5296 if (timespec_cmp (cmp_time
, huge_timespec
) < 0)
5298 now
= current_timespec ();
5299 if (timespec_cmp (cmp_time
, now
) <= 0)
5306 if (xerrno
== EINTR
)
5308 else if (xerrno
== EBADF
)
5311 report_file_errno ("Failed select", Qnil
, xerrno
);
5314 /* Check for keyboard input. */
5315 /* If there is any, return immediately
5316 to give it higher priority than subprocesses. */
5320 unsigned old_timers_run
= timers_run
;
5321 struct buffer
*old_buffer
= current_buffer
;
5322 Lisp_Object old_window
= selected_window
;
5325 if (detect_input_pending_run_timers (do_display
))
5327 swallow_events (do_display
);
5328 if (detect_input_pending_run_timers (do_display
))
5332 /* If a timer has run, this might have changed buffers
5333 an alike. Make read_key_sequence aware of that. */
5334 if (timers_run
!= old_timers_run
5335 && waiting_for_user_input_p
== -1
5336 && (old_buffer
!= current_buffer
5337 || !EQ (old_window
, selected_window
)))
5338 record_asynch_buffer_change ();
5344 /* If there is unread keyboard input, also return. */
5346 && requeued_events_pending_p ())
5349 /* If we are not checking for keyboard input now,
5350 do process events (but don't run any timers).
5351 This is so that X events will be processed.
5352 Otherwise they may have to wait until polling takes place.
5353 That would causes delays in pasting selections, for example.
5355 (We used to do this only if wait_for_cell.) */
5356 if (read_kbd
== 0 && detect_input_pending ())
5358 swallow_events (do_display
);
5359 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5360 if (detect_input_pending ())
5365 /* Exit now if the cell we're waiting for became non-nil. */
5366 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5370 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5371 go read it. This can happen with X on BSD after logging out.
5372 In that case, there really is no input and no SIGIO,
5373 but select says there is input. */
5375 if (read_kbd
&& interrupt_input
5376 && keyboard_bit_set (&Available
) && ! noninteractive
)
5377 handle_input_available_signal (SIGIO
);
5380 /* If checking input just got us a size-change event from X,
5381 obey it now if we should. */
5382 if (read_kbd
|| ! NILP (wait_for_cell
))
5383 do_pending_window_change (0);
5385 /* Check for data from a process. */
5386 if (no_avail
|| nfds
== 0)
5389 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5391 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5393 && ((d
->condition
& FOR_READ
5394 && FD_ISSET (channel
, &Available
))
5395 || (d
->condition
& FOR_WRITE
5396 && FD_ISSET (channel
, &write_mask
))))
5397 d
->func (channel
, d
->data
);
5400 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5402 if (FD_ISSET (channel
, &Available
)
5403 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5404 && !FD_ISSET (channel
, &non_process_wait_mask
))
5408 /* If waiting for this channel, arrange to return as
5409 soon as no more input to be processed. No more
5411 proc
= chan_process
[channel
];
5415 /* If this is a server stream socket, accept connection. */
5416 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5418 server_accept_connection (proc
, channel
);
5422 /* Read data from the process, starting with our
5423 buffered-ahead character if we have one. */
5425 nread
= read_process_output (proc
, channel
);
5426 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5427 && got_some_output
< nread
)
5428 got_some_output
= nread
;
5431 /* Vacuum up any leftovers without waiting. */
5432 if (wait_proc
== XPROCESS (proc
))
5434 /* Since read_process_output can run a filter,
5435 which can call accept-process-output,
5436 don't try to read from any other processes
5437 before doing the select again. */
5438 FD_ZERO (&Available
);
5441 redisplay_preserve_echo_area (12);
5443 else if (nread
== -1 && would_block (errno
))
5446 /* FIXME: Is this special case still needed? */
5447 /* Note that we cannot distinguish between no input
5448 available now and a closed pipe.
5449 With luck, a closed pipe will be accompanied by
5450 subprocess termination and SIGCHLD. */
5451 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5452 && !PIPECONN_P (proc
))
5456 /* On some OSs with ptys, when the process on one end of
5457 a pty exits, the other end gets an error reading with
5458 errno = EIO instead of getting an EOF (0 bytes read).
5459 Therefore, if we get an error reading and errno =
5460 EIO, just continue, because the child process has
5461 exited and should clean itself up soon (e.g. when we
5463 else if (nread
== -1 && errno
== EIO
)
5465 struct Lisp_Process
*p
= XPROCESS (proc
);
5467 /* Clear the descriptor now, so we only raise the
5469 FD_CLR (channel
, &input_wait_mask
);
5470 FD_CLR (channel
, &non_keyboard_wait_mask
);
5474 /* If the EIO occurs on a pty, the SIGCHLD handler's
5475 waitpid call will not find the process object to
5476 delete. Do it here. */
5477 p
->tick
= ++process_tick
;
5478 pset_status (p
, Qfailed
);
5481 #endif /* HAVE_PTYS */
5482 /* If we can detect process termination, don't consider the
5483 process gone just because its pipe is closed. */
5484 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5485 && !PIPECONN_P (proc
))
5487 else if (nread
== 0 && PIPECONN_P (proc
))
5489 /* Preserve status of processes already terminated. */
5490 XPROCESS (proc
)->tick
= ++process_tick
;
5491 deactivate_process (proc
);
5492 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5493 pset_status (XPROCESS (proc
),
5494 list2 (Qexit
, make_number (0)));
5498 /* Preserve status of processes already terminated. */
5499 XPROCESS (proc
)->tick
= ++process_tick
;
5500 deactivate_process (proc
);
5501 if (XPROCESS (proc
)->raw_status_new
)
5502 update_status (XPROCESS (proc
));
5503 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5504 pset_status (XPROCESS (proc
),
5505 list2 (Qexit
, make_number (256)));
5508 if (FD_ISSET (channel
, &Writeok
)
5509 && FD_ISSET (channel
, &connect_wait_mask
))
5511 struct Lisp_Process
*p
;
5513 FD_CLR (channel
, &connect_wait_mask
);
5514 FD_CLR (channel
, &write_mask
);
5515 if (--num_pending_connects
< 0)
5518 proc
= chan_process
[channel
];
5522 p
= XPROCESS (proc
);
5526 socklen_t xlen
= sizeof (xerrno
);
5527 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5531 /* On MS-Windows, getsockopt clears the error for the
5532 entire process, which may not be the right thing; see
5533 w32.c. Use getpeername instead. */
5535 struct sockaddr pname
;
5536 socklen_t pnamelen
= sizeof (pname
);
5538 /* If connection failed, getpeername will fail. */
5540 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5542 /* Obtain connect failure code through error slippage. */
5545 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5552 Lisp_Object addrinfos
5553 = connecting_status (p
->status
) ? XCDR (p
->status
) : Qnil
;
5554 if (!NILP (addrinfos
))
5555 XSETCDR (p
->status
, XCDR (addrinfos
));
5558 p
->tick
= ++process_tick
;
5559 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5561 deactivate_process (proc
);
5562 if (!NILP (addrinfos
))
5563 connect_network_socket (proc
, addrinfos
, Qnil
);
5568 /* If we have an incompletely set up TLS connection,
5569 then defer the sentinel signaling until
5571 if (NILP (p
->gnutls_boot_parameters
)
5575 pset_status (p
, Qrun
);
5576 /* Execute the sentinel here. If we had relied on
5577 status_notify to do it later, it will read input
5578 from the process before calling the sentinel. */
5579 exec_sentinel (proc
, build_string ("open\n"));
5582 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5583 && !EQ (p
->command
, Qt
))
5585 FD_SET (p
->infd
, &input_wait_mask
);
5586 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5590 } /* End for each file descriptor. */
5591 } /* End while exit conditions not met. */
5593 unbind_to (count
, Qnil
);
5595 /* If calling from keyboard input, do not quit
5596 since we want to return C-g as an input character.
5597 Otherwise, do pending quit if requested. */
5600 /* Prevent input_pending from remaining set if we quit. */
5601 clear_input_pending ();
5605 return got_some_output
;
5608 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5611 read_process_output_call (Lisp_Object fun_and_args
)
5613 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5617 read_process_output_error_handler (Lisp_Object error_val
)
5619 cmd_error_internal (error_val
, "error in process filter: ");
5621 update_echo_area ();
5622 Fsleep_for (make_number (2), Qnil
);
5627 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5629 struct coding_system
*coding
);
5631 /* Read pending output from the process channel,
5632 starting with our buffered-ahead character if we have one.
5633 Yield number of decoded characters read.
5635 This function reads at most 4096 characters.
5636 If you want to read all available subprocess output,
5637 you must call it repeatedly until it returns zero.
5639 The characters read are decoded according to PROC's coding-system
5643 read_process_output (Lisp_Object proc
, int channel
)
5646 struct Lisp_Process
*p
= XPROCESS (proc
);
5647 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5648 int carryover
= p
->decoding_carryover
;
5649 enum { readmax
= 4096 };
5650 ptrdiff_t count
= SPECPDL_INDEX ();
5651 Lisp_Object odeactivate
;
5652 char chars
[sizeof coding
->carryover
+ readmax
];
5655 /* See the comment above. */
5656 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5658 #ifdef DATAGRAM_SOCKETS
5659 /* We have a working select, so proc_buffered_char is always -1. */
5660 if (DATAGRAM_CHAN_P (channel
))
5662 socklen_t len
= datagram_address
[channel
].len
;
5663 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5664 0, datagram_address
[channel
].sa
, &len
);
5669 bool buffered
= proc_buffered_char
[channel
] >= 0;
5672 chars
[carryover
] = proc_buffered_char
[channel
];
5673 proc_buffered_char
[channel
] = -1;
5676 if (p
->gnutls_p
&& p
->gnutls_state
)
5677 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5678 readmax
- buffered
);
5681 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5682 readmax
- buffered
);
5683 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5685 int delay
= p
->read_output_delay
;
5688 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5691 process_output_delay_count
++;
5692 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5695 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5697 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5699 process_output_delay_count
--;
5701 p
->read_output_delay
= delay
;
5704 p
->read_output_skip
= 1;
5705 process_output_skip
= 1;
5709 nbytes
+= buffered
&& nbytes
<= 0;
5712 p
->decoding_carryover
= 0;
5714 /* At this point, NBYTES holds number of bytes just received
5715 (including the one in proc_buffered_char[channel]). */
5718 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5720 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5723 /* Now set NBYTES how many bytes we must decode. */
5724 nbytes
+= carryover
;
5726 odeactivate
= Vdeactivate_mark
;
5727 /* There's no good reason to let process filters change the current
5728 buffer, and many callers of accept-process-output, sit-for, and
5729 friends don't expect current-buffer to be changed from under them. */
5730 record_unwind_current_buffer ();
5732 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5734 /* Handling the process output should not deactivate the mark. */
5735 Vdeactivate_mark
= odeactivate
;
5737 unbind_to (count
, Qnil
);
5742 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5744 struct coding_system
*coding
)
5746 Lisp_Object outstream
= p
->filter
;
5748 bool outer_running_asynch_code
= running_asynch_code
;
5749 int waiting
= waiting_for_user_input_p
;
5752 Lisp_Object obuffer
, okeymap
;
5753 XSETBUFFER (obuffer
, current_buffer
);
5754 okeymap
= BVAR (current_buffer
, keymap
);
5757 /* We inhibit quit here instead of just catching it so that
5758 hitting ^G when a filter happens to be running won't screw
5760 specbind (Qinhibit_quit
, Qt
);
5761 specbind (Qlast_nonmenu_event
, Qt
);
5763 /* In case we get recursively called,
5764 and we already saved the match data nonrecursively,
5765 save the same match data in safely recursive fashion. */
5766 if (outer_running_asynch_code
)
5769 /* Don't clobber the CURRENT match data, either! */
5770 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5771 restore_search_regs ();
5772 record_unwind_save_match_data ();
5773 Fset_match_data (tem
, Qt
);
5776 /* For speed, if a search happens within this code,
5777 save the match data in a special nonrecursive fashion. */
5778 running_asynch_code
= 1;
5780 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5781 text
= coding
->dst_object
;
5782 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5783 /* A new coding system might be found. */
5784 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5786 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5788 /* Don't call setup_coding_system for
5789 proc_decode_coding_system[channel] here. It is done in
5790 detect_coding called via decode_coding above. */
5792 /* If a coding system for encoding is not yet decided, we set
5793 it as the same as coding-system for decoding.
5795 But, before doing that we must check if
5796 proc_encode_coding_system[p->outfd] surely points to a
5797 valid memory because p->outfd will be changed once EOF is
5798 sent to the process. */
5799 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5800 && proc_encode_coding_system
[p
->outfd
])
5802 pset_encode_coding_system
5803 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5804 setup_coding_system (p
->encode_coding_system
,
5805 proc_encode_coding_system
[p
->outfd
]);
5809 if (coding
->carryover_bytes
> 0)
5811 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5812 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5813 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5814 coding
->carryover_bytes
);
5815 p
->decoding_carryover
= coding
->carryover_bytes
;
5817 if (SBYTES (text
) > 0)
5818 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5819 sometimes it's simply wrong to wrap (e.g. when called from
5820 accept-process-output). */
5821 internal_condition_case_1 (read_process_output_call
,
5822 list3 (outstream
, make_lisp_proc (p
), text
),
5823 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5824 read_process_output_error_handler
);
5826 /* If we saved the match data nonrecursively, restore it now. */
5827 restore_search_regs ();
5828 running_asynch_code
= outer_running_asynch_code
;
5830 /* Restore waiting_for_user_input_p as it was
5831 when we were called, in case the filter clobbered it. */
5832 waiting_for_user_input_p
= waiting
;
5834 #if 0 /* Call record_asynch_buffer_change unconditionally,
5835 because we might have changed minor modes or other things
5836 that affect key bindings. */
5837 if (! EQ (Fcurrent_buffer (), obuffer
)
5838 || ! EQ (current_buffer
->keymap
, okeymap
))
5840 /* But do it only if the caller is actually going to read events.
5841 Otherwise there's no need to make him wake up, and it could
5842 cause trouble (for example it would make sit_for return). */
5843 if (waiting_for_user_input_p
== -1)
5844 record_asynch_buffer_change ();
5847 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5848 Sinternal_default_process_filter
, 2, 2, 0,
5849 doc
: /* Function used as default process filter.
5850 This inserts the process's output into its buffer, if there is one.
5851 Otherwise it discards the output. */)
5852 (Lisp_Object proc
, Lisp_Object text
)
5854 struct Lisp_Process
*p
;
5857 CHECK_PROCESS (proc
);
5858 p
= XPROCESS (proc
);
5859 CHECK_STRING (text
);
5861 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5863 Lisp_Object old_read_only
;
5864 ptrdiff_t old_begv
, old_zv
;
5865 ptrdiff_t old_begv_byte
, old_zv_byte
;
5866 ptrdiff_t before
, before_byte
;
5867 ptrdiff_t opoint_byte
;
5870 Fset_buffer (p
->buffer
);
5872 opoint_byte
= PT_BYTE
;
5873 old_read_only
= BVAR (current_buffer
, read_only
);
5876 old_begv_byte
= BEGV_BYTE
;
5877 old_zv_byte
= ZV_BYTE
;
5879 bset_read_only (current_buffer
, Qnil
);
5881 /* Insert new output into buffer at the current end-of-output
5882 marker, thus preserving logical ordering of input and output. */
5883 if (XMARKER (p
->mark
)->buffer
)
5884 set_point_from_marker (p
->mark
);
5886 SET_PT_BOTH (ZV
, ZV_BYTE
);
5888 before_byte
= PT_BYTE
;
5890 /* If the output marker is outside of the visible region, save
5891 the restriction and widen. */
5892 if (! (BEGV
<= PT
&& PT
<= ZV
))
5895 /* Adjust the multibyteness of TEXT to that of the buffer. */
5896 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5897 != ! STRING_MULTIBYTE (text
))
5898 text
= (STRING_MULTIBYTE (text
)
5899 ? Fstring_as_unibyte (text
)
5900 : Fstring_to_multibyte (text
));
5901 /* Insert before markers in case we are inserting where
5902 the buffer's mark is, and the user's next command is Meta-y. */
5903 insert_from_string_before_markers (text
, 0, 0,
5904 SCHARS (text
), SBYTES (text
), 0);
5906 /* Make sure the process marker's position is valid when the
5907 process buffer is changed in the signal_after_change above.
5908 W3 is known to do that. */
5909 if (BUFFERP (p
->buffer
)
5910 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5911 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5913 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5915 update_mode_lines
= 23;
5917 /* Make sure opoint and the old restrictions
5918 float ahead of any new text just as point would. */
5919 if (opoint
>= before
)
5921 opoint
+= PT
- before
;
5922 opoint_byte
+= PT_BYTE
- before_byte
;
5924 if (old_begv
> before
)
5926 old_begv
+= PT
- before
;
5927 old_begv_byte
+= PT_BYTE
- before_byte
;
5929 if (old_zv
>= before
)
5931 old_zv
+= PT
- before
;
5932 old_zv_byte
+= PT_BYTE
- before_byte
;
5935 /* If the restriction isn't what it should be, set it. */
5936 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5937 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5939 bset_read_only (current_buffer
, old_read_only
);
5940 SET_PT_BOTH (opoint
, opoint_byte
);
5945 /* Sending data to subprocess. */
5947 /* In send_process, when a write fails temporarily,
5948 wait_reading_process_output is called. It may execute user code,
5949 e.g. timers, that attempts to write new data to the same process.
5950 We must ensure that data is sent in the right order, and not
5951 interspersed half-completed with other writes (Bug#10815). This is
5952 handled by the write_queue element of struct process. It is a list
5953 with each entry having the form
5955 (string . (offset . length))
5957 where STRING is a lisp string, OFFSET is the offset into the
5958 string's byte sequence from which we should begin to send, and
5959 LENGTH is the number of bytes left to send. */
5961 /* Create a new entry in write_queue.
5962 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5963 BUF is a pointer to the string sequence of the input_obj or a C
5964 string in case of Qt or Qnil. */
5967 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5968 const char *buf
, ptrdiff_t len
, bool front
)
5971 Lisp_Object entry
, obj
;
5973 if (STRINGP (input_obj
))
5975 offset
= buf
- SSDATA (input_obj
);
5981 obj
= make_unibyte_string (buf
, len
);
5984 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5987 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5989 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5992 /* Remove the first element in the write_queue of process P, put its
5993 contents in OBJ, BUF and LEN, and return true. If the
5994 write_queue is empty, return false. */
5997 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5998 const char **buf
, ptrdiff_t *len
)
6000 Lisp_Object entry
, offset_length
;
6003 if (NILP (p
->write_queue
))
6006 entry
= XCAR (p
->write_queue
);
6007 pset_write_queue (p
, XCDR (p
->write_queue
));
6009 *obj
= XCAR (entry
);
6010 offset_length
= XCDR (entry
);
6012 *len
= XINT (XCDR (offset_length
));
6013 offset
= XINT (XCAR (offset_length
));
6014 *buf
= SSDATA (*obj
) + offset
;
6019 /* Send some data to process PROC.
6020 BUF is the beginning of the data; LEN is the number of characters.
6021 OBJECT is the Lisp object that the data comes from. If OBJECT is
6022 nil or t, it means that the data comes from C string.
6024 If OBJECT is not nil, the data is encoded by PROC's coding-system
6025 for encoding before it is sent.
6027 This function can evaluate Lisp code and can garbage collect. */
6030 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6033 struct Lisp_Process
*p
= XPROCESS (proc
);
6035 struct coding_system
*coding
;
6037 if (NETCONN_P (proc
))
6039 wait_while_connecting (proc
);
6040 wait_for_tls_negotiation (proc
);
6043 if (p
->raw_status_new
)
6045 if (! EQ (p
->status
, Qrun
))
6046 error ("Process %s not running", SDATA (p
->name
));
6048 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6050 coding
= proc_encode_coding_system
[p
->outfd
];
6051 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6053 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6054 || (BUFFERP (object
)
6055 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6058 pset_encode_coding_system
6059 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6060 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6062 /* The coding system for encoding was changed to raw-text
6063 because we sent a unibyte text previously. Now we are
6064 sending a multibyte text, thus we must encode it by the
6065 original coding system specified for the current process.
6067 Another reason we come here is that the coding system
6068 was just complemented and a new one was returned by
6069 complement_process_encoding_system. */
6070 setup_coding_system (p
->encode_coding_system
, coding
);
6071 Vlast_coding_system_used
= p
->encode_coding_system
;
6073 coding
->src_multibyte
= 1;
6077 coding
->src_multibyte
= 0;
6078 /* For sending a unibyte text, character code conversion should
6079 not take place but EOL conversion should. So, setup raw-text
6080 or one of the subsidiary if we have not yet done it. */
6081 if (CODING_REQUIRE_ENCODING (coding
))
6083 if (CODING_REQUIRE_FLUSHING (coding
))
6085 /* But, before changing the coding, we must flush out data. */
6086 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6087 send_process (proc
, "", 0, Qt
);
6088 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6090 setup_coding_system (raw_text_coding_system
6091 (Vlast_coding_system_used
),
6093 coding
->src_multibyte
= 0;
6096 coding
->dst_multibyte
= 0;
6098 if (CODING_REQUIRE_ENCODING (coding
))
6100 coding
->dst_object
= Qt
;
6101 if (BUFFERP (object
))
6103 ptrdiff_t from_byte
, from
, to
;
6104 ptrdiff_t save_pt
, save_pt_byte
;
6105 struct buffer
*cur
= current_buffer
;
6107 set_buffer_internal (XBUFFER (object
));
6108 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6110 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6111 from
= BYTE_TO_CHAR (from_byte
);
6112 to
= BYTE_TO_CHAR (from_byte
+ len
);
6113 TEMP_SET_PT_BOTH (from
, from_byte
);
6114 encode_coding_object (coding
, object
, from
, from_byte
,
6115 to
, from_byte
+ len
, Qt
);
6116 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6117 set_buffer_internal (cur
);
6119 else if (STRINGP (object
))
6121 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6122 SBYTES (object
), Qt
);
6126 coding
->dst_object
= make_unibyte_string (buf
, len
);
6127 coding
->produced
= len
;
6130 len
= coding
->produced
;
6131 object
= coding
->dst_object
;
6132 buf
= SSDATA (object
);
6135 /* If there is already data in the write_queue, put the new data
6136 in the back of queue. Otherwise, ignore it. */
6137 if (!NILP (p
->write_queue
))
6138 write_queue_push (p
, object
, buf
, len
, 0);
6140 do /* while !NILP (p->write_queue) */
6142 ptrdiff_t cur_len
= -1;
6143 const char *cur_buf
;
6144 Lisp_Object cur_object
;
6146 /* If write_queue is empty, ignore it. */
6147 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6151 cur_object
= object
;
6156 /* Send this batch, using one or more write calls. */
6157 ptrdiff_t written
= 0;
6158 int outfd
= p
->outfd
;
6159 #ifdef DATAGRAM_SOCKETS
6160 if (DATAGRAM_CHAN_P (outfd
))
6162 rv
= sendto (outfd
, cur_buf
, cur_len
,
6163 0, datagram_address
[outfd
].sa
,
6164 datagram_address
[outfd
].len
);
6167 else if (errno
== EMSGSIZE
)
6168 report_file_error ("Sending datagram", proc
);
6174 if (p
->gnutls_p
&& p
->gnutls_state
)
6175 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6178 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6179 rv
= (written
? 0 : -1);
6180 if (p
->read_output_delay
> 0
6181 && p
->adaptive_read_buffering
== 1)
6183 p
->read_output_delay
= 0;
6184 process_output_delay_count
--;
6185 p
->read_output_skip
= 0;
6191 if (would_block (errno
))
6192 /* Buffer is full. Wait, accepting input;
6193 that may allow the program
6194 to finish doing output and read more. */
6196 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6197 /* A gross hack to work around a bug in FreeBSD.
6198 In the following sequence, read(2) returns
6202 write(2) 954 bytes, get EAGAIN
6203 read(2) 1024 bytes in process_read_output
6204 read(2) 11 bytes in process_read_output
6206 That is, read(2) returns more bytes than have
6207 ever been written successfully. The 1033 bytes
6208 read are the 1022 bytes written successfully
6209 after processing (for example with CRs added if
6210 the terminal is set up that way which it is
6211 here). The same bytes will be seen again in a
6212 later read(2), without the CRs. */
6214 if (errno
== EAGAIN
)
6217 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6219 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6221 /* Put what we should have written in wait_queue. */
6222 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6223 wait_reading_process_output (0, 20 * 1000 * 1000,
6224 0, 0, Qnil
, NULL
, 0);
6225 /* Reread queue, to see what is left. */
6228 else if (errno
== EPIPE
)
6230 p
->raw_status_new
= 0;
6231 pset_status (p
, list2 (Qexit
, make_number (256)));
6232 p
->tick
= ++process_tick
;
6233 deactivate_process (proc
);
6234 error ("process %s no longer connected to pipe; closed it",
6238 /* This is a real error. */
6239 report_file_error ("Writing to process", proc
);
6245 while (!NILP (p
->write_queue
));
6248 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6250 doc
: /* Send current contents of region as input to PROCESS.
6251 PROCESS may be a process, a buffer, the name of a process or buffer, or
6252 nil, indicating the current buffer's process.
6253 Called from program, takes three arguments, PROCESS, START and END.
6254 If the region is more than 500 characters long,
6255 it is sent in several bunches. This may happen even for shorter regions.
6256 Output from processes can arrive in between bunches.
6258 If PROCESS is a non-blocking network process that hasn't been fully
6259 set up yet, this function will block until socket setup has completed. */)
6260 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6262 Lisp_Object proc
= get_process (process
);
6263 ptrdiff_t start_byte
, end_byte
;
6265 validate_region (&start
, &end
);
6267 start_byte
= CHAR_TO_BYTE (XINT (start
));
6268 end_byte
= CHAR_TO_BYTE (XINT (end
));
6270 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6271 move_gap_both (XINT (start
), start_byte
);
6273 if (NETCONN_P (proc
))
6274 wait_while_connecting (proc
);
6276 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6277 end_byte
- start_byte
, Fcurrent_buffer ());
6282 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6284 doc
: /* Send PROCESS the contents of STRING as input.
6285 PROCESS may be a process, a buffer, the name of a process or buffer, or
6286 nil, indicating the current buffer's process.
6287 If STRING is more than 500 characters long,
6288 it is sent in several bunches. This may happen even for shorter strings.
6289 Output from processes can arrive in between bunches.
6291 If PROCESS is a non-blocking network process that hasn't been fully
6292 set up yet, this function will block until socket setup has completed. */)
6293 (Lisp_Object process
, Lisp_Object string
)
6295 CHECK_STRING (string
);
6296 Lisp_Object proc
= get_process (process
);
6297 send_process (proc
, SSDATA (string
),
6298 SBYTES (string
), string
);
6302 /* Return the foreground process group for the tty/pty that
6303 the process P uses. */
6305 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6310 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6313 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6314 master side. Try the slave side. */
6315 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6319 ioctl (fd
, TIOCGPGRP
, &gid
);
6323 #endif /* defined (TIOCGPGRP ) */
6328 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6329 Sprocess_running_child_p
, 0, 1, 0,
6330 doc
: /* Return non-nil if PROCESS has given the terminal to a
6331 child. If the operating system does not make it possible to find out,
6332 return t. If we can find out, return the numeric ID of the foreground
6334 (Lisp_Object process
)
6336 /* Initialize in case ioctl doesn't exist or gives an error,
6337 in a way that will cause returning t. */
6338 Lisp_Object proc
= get_process (process
);
6339 struct Lisp_Process
*p
= XPROCESS (proc
);
6341 if (!EQ (p
->type
, Qreal
))
6342 error ("Process %s is not a subprocess",
6345 error ("Process %s is not active",
6348 pid_t gid
= emacs_get_tty_pgrp (p
);
6353 return make_number (gid
);
6357 /* Send a signal number SIGNO to PROCESS.
6358 If CURRENT_GROUP is t, that means send to the process group
6359 that currently owns the terminal being used to communicate with PROCESS.
6360 This is used for various commands in shell mode.
6361 If CURRENT_GROUP is lambda, that means send to the process group
6362 that currently owns the terminal, but only if it is NOT the shell itself.
6364 If NOMSG is false, insert signal-announcements into process's buffers
6367 If we can, we try to signal PROCESS by sending control characters
6368 down the pty. This allows us to signal inferiors who have changed
6369 their uid, for which kill would return an EPERM error. */
6372 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6376 struct Lisp_Process
*p
;
6380 proc
= get_process (process
);
6381 p
= XPROCESS (proc
);
6383 if (!EQ (p
->type
, Qreal
))
6384 error ("Process %s is not a subprocess",
6387 error ("Process %s is not active",
6391 current_group
= Qnil
;
6393 /* If we are using pgrps, get a pgrp number and make it negative. */
6394 if (NILP (current_group
))
6395 /* Send the signal to the shell's process group. */
6399 #ifdef SIGNALS_VIA_CHARACTERS
6400 /* If possible, send signals to the entire pgrp
6401 by sending an input character to it. */
6404 cc_t
*sig_char
= NULL
;
6406 tcgetattr (p
->infd
, &t
);
6411 sig_char
= &t
.c_cc
[VINTR
];
6415 sig_char
= &t
.c_cc
[VQUIT
];
6420 sig_char
= &t
.c_cc
[VSWTCH
];
6422 sig_char
= &t
.c_cc
[VSUSP
];
6427 if (sig_char
&& *sig_char
!= CDISABLE
)
6429 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6432 /* If we can't send the signal with a character,
6433 fall through and send it another way. */
6435 /* The code above may fall through if it can't
6436 handle the signal. */
6437 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6440 /* Get the current pgrp using the tty itself, if we have that.
6441 Otherwise, use the pty to get the pgrp.
6442 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6443 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6444 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6445 His patch indicates that if TIOCGPGRP returns an error, then
6446 we should just assume that p->pid is also the process group id. */
6448 gid
= emacs_get_tty_pgrp (p
);
6451 /* If we can't get the information, assume
6452 the shell owns the tty. */
6455 /* It is not clear whether anything really can set GID to -1.
6456 Perhaps on some system one of those ioctls can or could do so.
6457 Or perhaps this is vestigial. */
6460 #else /* ! defined (TIOCGPGRP) */
6461 /* Can't select pgrps on this system, so we know that
6462 the child itself heads the pgrp. */
6464 #endif /* ! defined (TIOCGPGRP) */
6466 /* If current_group is lambda, and the shell owns the terminal,
6467 don't send any signal. */
6468 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6473 if (signo
== SIGCONT
)
6475 p
->raw_status_new
= 0;
6476 pset_status (p
, Qrun
);
6477 p
->tick
= ++process_tick
;
6480 status_notify (NULL
, NULL
);
6481 redisplay_preserve_echo_area (13);
6487 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6488 We don't know whether the bug is fixed in later HP-UX versions. */
6489 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6493 /* If we don't have process groups, send the signal to the immediate
6494 subprocess. That isn't really right, but it's better than any
6495 obvious alternative. */
6496 pid_t pid
= no_pgrp
? gid
: - gid
;
6498 /* Do not kill an already-reaped process, as that could kill an
6499 innocent bystander that happens to have the same process ID. */
6501 block_child_signal (&oldset
);
6504 unblock_child_signal (&oldset
);
6507 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6508 doc
: /* Interrupt process PROCESS.
6509 PROCESS may be a process, a buffer, or the name of a process or buffer.
6510 No arg or nil means current buffer's process.
6511 Second arg CURRENT-GROUP non-nil means send signal to
6512 the current process-group of the process's controlling terminal
6513 rather than to the process's own process group.
6514 If the process is a shell, this means interrupt current subjob
6515 rather than the shell.
6517 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6518 don't send the signal. */)
6519 (Lisp_Object process
, Lisp_Object current_group
)
6521 process_send_signal (process
, SIGINT
, current_group
, 0);
6525 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6526 doc
: /* Kill process PROCESS. May be process or name of one.
6527 See function `interrupt-process' for more details on usage. */)
6528 (Lisp_Object process
, Lisp_Object current_group
)
6530 process_send_signal (process
, SIGKILL
, current_group
, 0);
6534 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6535 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6536 See function `interrupt-process' for more details on usage. */)
6537 (Lisp_Object process
, Lisp_Object current_group
)
6539 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6543 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6544 doc
: /* Stop process PROCESS. May be process or name of one.
6545 See function `interrupt-process' for more details on usage.
6546 If PROCESS is a network or serial or pipe connection, inhibit handling
6547 of incoming traffic. */)
6548 (Lisp_Object process
, Lisp_Object current_group
)
6550 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6551 || PIPECONN_P (process
)))
6553 struct Lisp_Process
*p
;
6555 p
= XPROCESS (process
);
6556 if (NILP (p
->command
)
6559 FD_CLR (p
->infd
, &input_wait_mask
);
6560 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6562 pset_command (p
, Qt
);
6566 error ("No SIGTSTP support");
6568 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6573 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6574 doc
: /* Continue process PROCESS. May be process or name of one.
6575 See function `interrupt-process' for more details on usage.
6576 If PROCESS is a network or serial process, resume handling of incoming
6578 (Lisp_Object process
, Lisp_Object current_group
)
6580 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6581 || PIPECONN_P (process
)))
6583 struct Lisp_Process
*p
;
6585 p
= XPROCESS (process
);
6586 if (EQ (p
->command
, Qt
)
6588 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6590 FD_SET (p
->infd
, &input_wait_mask
);
6591 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6593 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6594 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6595 #else /* not WINDOWSNT */
6596 tcflush (p
->infd
, TCIFLUSH
);
6597 #endif /* not WINDOWSNT */
6599 pset_command (p
, Qnil
);
6603 process_send_signal (process
, SIGCONT
, current_group
, 0);
6605 error ("No SIGCONT support");
6610 /* Return the integer value of the signal whose abbreviation is ABBR,
6611 or a negative number if there is no such signal. */
6613 abbr_to_signal (char const *name
)
6616 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6618 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6621 for (i
= 0; i
< sizeof sigbuf
; i
++)
6623 sigbuf
[i
] = c_toupper (name
[i
]);
6625 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6631 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6632 2, 2, "sProcess (name or number): \nnSignal code: ",
6633 doc
: /* Send PROCESS the signal with code SIGCODE.
6634 PROCESS may also be a number specifying the process id of the
6635 process to signal; in this case, the process need not be a child of
6637 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6638 (Lisp_Object process
, Lisp_Object sigcode
)
6643 if (STRINGP (process
))
6645 Lisp_Object tem
= Fget_process (process
);
6648 Lisp_Object process_number
6649 = string_to_number (SSDATA (process
), 10, 1);
6650 if (NUMBERP (process_number
))
6651 tem
= process_number
;
6655 else if (!NUMBERP (process
))
6656 process
= get_process (process
);
6661 if (NUMBERP (process
))
6662 CONS_TO_INTEGER (process
, pid_t
, pid
);
6665 CHECK_PROCESS (process
);
6666 pid
= XPROCESS (process
)->pid
;
6668 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6671 if (INTEGERP (sigcode
))
6673 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6674 signo
= XINT (sigcode
);
6680 CHECK_SYMBOL (sigcode
);
6681 name
= SSDATA (SYMBOL_NAME (sigcode
));
6683 signo
= abbr_to_signal (name
);
6685 error ("Undefined signal name %s", name
);
6688 return make_number (kill (pid
, signo
));
6691 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6692 doc
: /* Make PROCESS see end-of-file in its input.
6693 EOF comes after any text already sent to it.
6694 PROCESS may be a process, a buffer, the name of a process or buffer, or
6695 nil, indicating the current buffer's process.
6696 If PROCESS is a network connection, or is a process communicating
6697 through a pipe (as opposed to a pty), then you cannot send any more
6698 text to PROCESS after you call this function.
6699 If PROCESS is a serial process, wait until all output written to the
6700 process has been transmitted to the serial port. */)
6701 (Lisp_Object process
)
6704 struct coding_system
*coding
= NULL
;
6707 proc
= get_process (process
);
6709 if (NETCONN_P (proc
))
6710 wait_while_connecting (proc
);
6712 if (DATAGRAM_CONN_P (proc
))
6716 outfd
= XPROCESS (proc
)->outfd
;
6718 coding
= proc_encode_coding_system
[outfd
];
6720 /* Make sure the process is really alive. */
6721 if (XPROCESS (proc
)->raw_status_new
)
6722 update_status (XPROCESS (proc
));
6723 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6724 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6726 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6728 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6729 send_process (proc
, "", 0, Qnil
);
6732 if (XPROCESS (proc
)->pty_flag
)
6733 send_process (proc
, "\004", 1, Qnil
);
6734 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6737 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6738 report_file_error ("Failed tcdrain", Qnil
);
6739 #endif /* not WINDOWSNT */
6740 /* Do nothing on Windows because writes are blocking. */
6744 struct Lisp_Process
*p
= XPROCESS (proc
);
6745 int old_outfd
= p
->outfd
;
6748 #ifdef HAVE_SHUTDOWN
6749 /* If this is a network connection, or socketpair is used
6750 for communication with the subprocess, call shutdown to cause EOF.
6751 (In some old system, shutdown to socketpair doesn't work.
6752 Then we just can't win.) */
6754 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6755 shutdown (old_outfd
, 1);
6757 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6758 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6760 report_file_error ("Opening null device", Qnil
);
6761 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6762 p
->outfd
= new_outfd
;
6764 if (!proc_encode_coding_system
[new_outfd
])
6765 proc_encode_coding_system
[new_outfd
]
6766 = xmalloc (sizeof (struct coding_system
));
6769 *proc_encode_coding_system
[new_outfd
]
6770 = *proc_encode_coding_system
[old_outfd
];
6771 memset (proc_encode_coding_system
[old_outfd
], 0,
6772 sizeof (struct coding_system
));
6775 setup_coding_system (p
->encode_coding_system
,
6776 proc_encode_coding_system
[new_outfd
]);
6781 /* The main Emacs thread records child processes in three places:
6783 - Vprocess_alist, for asynchronous subprocesses, which are child
6784 processes visible to Lisp.
6786 - deleted_pid_list, for child processes invisible to Lisp,
6787 typically because of delete-process. These are recorded so that
6788 the processes can be reaped when they exit, so that the operating
6789 system's process table is not cluttered by zombies.
6791 - the local variable PID in Fcall_process, call_process_cleanup and
6792 call_process_kill, for synchronous subprocesses.
6793 record_unwind_protect is used to make sure this process is not
6794 forgotten: if the user interrupts call-process and the child
6795 process refuses to exit immediately even with two C-g's,
6796 call_process_kill adds PID's contents to deleted_pid_list before
6799 The main Emacs thread invokes waitpid only on child processes that
6800 it creates and that have not been reaped. This avoid races on
6801 platforms such as GTK, where other threads create their own
6802 subprocesses which the main thread should not reap. For example,
6803 if the main thread attempted to reap an already-reaped child, it
6804 might inadvertently reap a GTK-created process that happened to
6805 have the same process ID. */
6807 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6808 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6809 keep track of its own children. GNUstep is similar. */
6811 static void dummy_handler (int sig
) {}
6812 static signal_handler_t
volatile lib_child_handler
;
6814 /* Handle a SIGCHLD signal by looking for known child processes of
6815 Emacs whose status have changed. For each one found, record its
6818 All we do is change the status; we do not run sentinels or print
6819 notifications. That is saved for the next time keyboard input is
6820 done, in order to avoid timing errors.
6822 ** WARNING: this can be called during garbage collection.
6823 Therefore, it must not be fooled by the presence of mark bits in
6826 ** USG WARNING: Although it is not obvious from the documentation
6827 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6828 signal() before executing at least one wait(), otherwise the
6829 handler will be called again, resulting in an infinite loop. The
6830 relevant portion of the documentation reads "SIGCLD signals will be
6831 queued and the signal-catching function will be continually
6832 reentered until the queue is empty". Invoking signal() causes the
6833 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6836 ** Malloc WARNING: This should never call malloc either directly or
6837 indirectly; if it does, that is a bug. */
6840 handle_child_signal (int sig
)
6842 Lisp_Object tail
, proc
;
6844 /* Find the process that signaled us, and record its status. */
6846 /* The process can have been deleted by Fdelete_process, or have
6847 been started asynchronously by Fcall_process. */
6848 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6850 bool all_pids_are_fixnums
6851 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6852 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6853 Lisp_Object head
= XCAR (tail
);
6858 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6861 if (INTEGERP (xpid
))
6862 deleted_pid
= XINT (xpid
);
6864 deleted_pid
= XFLOAT_DATA (xpid
);
6865 if (child_status_changed (deleted_pid
, 0, 0))
6867 if (STRINGP (XCDR (head
)))
6868 unlink (SSDATA (XCDR (head
)));
6869 XSETCAR (tail
, Qnil
);
6874 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6875 FOR_EACH_PROCESS (tail
, proc
)
6877 struct Lisp_Process
*p
= XPROCESS (proc
);
6881 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6883 /* Change the status of the process that was found. */
6884 p
->tick
= ++process_tick
;
6885 p
->raw_status
= status
;
6886 p
->raw_status_new
= 1;
6888 /* If process has terminated, stop waiting for its output. */
6889 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6891 bool clear_desc_flag
= 0;
6894 clear_desc_flag
= 1;
6896 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6897 if (clear_desc_flag
)
6899 FD_CLR (p
->infd
, &input_wait_mask
);
6900 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6906 lib_child_handler (sig
);
6907 #ifdef NS_IMPL_GNUSTEP
6908 /* NSTask in GNUstep sets its child handler each time it is called.
6909 So we must re-set ours. */
6910 catch_child_signal ();
6915 deliver_child_signal (int sig
)
6917 deliver_process_signal (sig
, handle_child_signal
);
6922 exec_sentinel_error_handler (Lisp_Object error_val
)
6924 cmd_error_internal (error_val
, "error in process sentinel: ");
6926 update_echo_area ();
6927 Fsleep_for (make_number (2), Qnil
);
6932 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6934 Lisp_Object sentinel
, odeactivate
;
6935 struct Lisp_Process
*p
= XPROCESS (proc
);
6936 ptrdiff_t count
= SPECPDL_INDEX ();
6937 bool outer_running_asynch_code
= running_asynch_code
;
6938 int waiting
= waiting_for_user_input_p
;
6940 if (inhibit_sentinels
)
6943 odeactivate
= Vdeactivate_mark
;
6945 Lisp_Object obuffer
, okeymap
;
6946 XSETBUFFER (obuffer
, current_buffer
);
6947 okeymap
= BVAR (current_buffer
, keymap
);
6950 /* There's no good reason to let sentinels change the current
6951 buffer, and many callers of accept-process-output, sit-for, and
6952 friends don't expect current-buffer to be changed from under them. */
6953 record_unwind_current_buffer ();
6955 sentinel
= p
->sentinel
;
6957 /* Inhibit quit so that random quits don't screw up a running filter. */
6958 specbind (Qinhibit_quit
, Qt
);
6959 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6961 /* In case we get recursively called,
6962 and we already saved the match data nonrecursively,
6963 save the same match data in safely recursive fashion. */
6964 if (outer_running_asynch_code
)
6967 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6968 restore_search_regs ();
6969 record_unwind_save_match_data ();
6970 Fset_match_data (tem
, Qt
);
6973 /* For speed, if a search happens within this code,
6974 save the match data in a special nonrecursive fashion. */
6975 running_asynch_code
= 1;
6977 internal_condition_case_1 (read_process_output_call
,
6978 list3 (sentinel
, proc
, reason
),
6979 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6980 exec_sentinel_error_handler
);
6982 /* If we saved the match data nonrecursively, restore it now. */
6983 restore_search_regs ();
6984 running_asynch_code
= outer_running_asynch_code
;
6986 Vdeactivate_mark
= odeactivate
;
6988 /* Restore waiting_for_user_input_p as it was
6989 when we were called, in case the filter clobbered it. */
6990 waiting_for_user_input_p
= waiting
;
6993 if (! EQ (Fcurrent_buffer (), obuffer
)
6994 || ! EQ (current_buffer
->keymap
, okeymap
))
6996 /* But do it only if the caller is actually going to read events.
6997 Otherwise there's no need to make him wake up, and it could
6998 cause trouble (for example it would make sit_for return). */
6999 if (waiting_for_user_input_p
== -1)
7000 record_asynch_buffer_change ();
7002 unbind_to (count
, Qnil
);
7005 /* Report all recent events of a change in process status
7006 (either run the sentinel or output a message).
7007 This is usually done while Emacs is waiting for keyboard input
7008 but can be done at other times.
7010 Return positive if any input was received from WAIT_PROC (or from
7011 any process if WAIT_PROC is null), zero if input was attempted but
7012 none received, and negative if we didn't even try. */
7015 status_notify (struct Lisp_Process
*deleting_process
,
7016 struct Lisp_Process
*wait_proc
)
7019 Lisp_Object tail
, msg
;
7020 int got_some_output
= -1;
7025 /* Set this now, so that if new processes are created by sentinels
7026 that we run, we get called again to handle their status changes. */
7027 update_tick
= process_tick
;
7029 FOR_EACH_PROCESS (tail
, proc
)
7032 register struct Lisp_Process
*p
= XPROCESS (proc
);
7034 if (p
->tick
!= p
->update_tick
)
7036 p
->update_tick
= p
->tick
;
7038 /* If process is still active, read any output that remains. */
7039 while (! EQ (p
->filter
, Qt
)
7040 && ! connecting_status (p
->status
)
7041 && ! EQ (p
->status
, Qlisten
)
7042 /* Network or serial process not stopped: */
7043 && ! EQ (p
->command
, Qt
)
7045 && p
!= deleting_process
)
7047 int nread
= read_process_output (proc
, p
->infd
);
7048 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7049 && got_some_output
< nread
)
7050 got_some_output
= nread
;
7055 /* Get the text to use for the message. */
7056 if (p
->raw_status_new
)
7058 msg
= status_message (p
);
7060 /* If process is terminated, deactivate it or delete it. */
7062 if (CONSP (p
->status
))
7063 symbol
= XCAR (p
->status
);
7065 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7066 || EQ (symbol
, Qclosed
))
7068 if (delete_exited_processes
)
7069 remove_process (proc
);
7071 deactivate_process (proc
);
7074 /* The actions above may have further incremented p->tick.
7075 So set p->update_tick again so that an error in the sentinel will
7076 not cause this code to be run again. */
7077 p
->update_tick
= p
->tick
;
7078 /* Now output the message suitably. */
7079 exec_sentinel (proc
, msg
);
7080 if (BUFFERP (p
->buffer
))
7081 /* In case it uses %s in mode-line-format. */
7082 bset_update_mode_line (XBUFFER (p
->buffer
));
7086 return got_some_output
;
7089 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7090 Sinternal_default_process_sentinel
, 2, 2, 0,
7091 doc
: /* Function used as default sentinel for processes.
7092 This inserts a status message into the process's buffer, if there is one. */)
7093 (Lisp_Object proc
, Lisp_Object msg
)
7095 Lisp_Object buffer
, symbol
;
7096 struct Lisp_Process
*p
;
7097 CHECK_PROCESS (proc
);
7098 p
= XPROCESS (proc
);
7102 symbol
= XCAR (symbol
);
7104 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7107 struct buffer
*old
= current_buffer
;
7108 ptrdiff_t opoint
, opoint_byte
;
7109 ptrdiff_t before
, before_byte
;
7111 /* Avoid error if buffer is deleted
7112 (probably that's why the process is dead, too). */
7113 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7115 Fset_buffer (buffer
);
7117 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7118 msg
= (code_convert_string_norecord
7119 (msg
, Vlocale_coding_system
, 1));
7122 opoint_byte
= PT_BYTE
;
7123 /* Insert new output into buffer
7124 at the current end-of-output marker,
7125 thus preserving logical ordering of input and output. */
7126 if (XMARKER (p
->mark
)->buffer
)
7127 Fgoto_char (p
->mark
);
7129 SET_PT_BOTH (ZV
, ZV_BYTE
);
7132 before_byte
= PT_BYTE
;
7134 tem
= BVAR (current_buffer
, read_only
);
7135 bset_read_only (current_buffer
, Qnil
);
7136 insert_string ("\nProcess ");
7137 { /* FIXME: temporary kludge. */
7138 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7139 insert_string (" ");
7141 bset_read_only (current_buffer
, tem
);
7142 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7144 if (opoint
>= before
)
7145 SET_PT_BOTH (opoint
+ (PT
- before
),
7146 opoint_byte
+ (PT_BYTE
- before_byte
));
7148 SET_PT_BOTH (opoint
, opoint_byte
);
7150 set_buffer_internal (old
);
7156 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7157 Sset_process_coding_system
, 1, 3, 0,
7158 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7159 DECODING will be used to decode subprocess output and ENCODING to
7160 encode subprocess input. */)
7161 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7163 CHECK_PROCESS (process
);
7165 struct Lisp_Process
*p
= XPROCESS (process
);
7167 Fcheck_coding_system (decoding
);
7168 Fcheck_coding_system (encoding
);
7169 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7170 pset_decode_coding_system (p
, decoding
);
7171 pset_encode_coding_system (p
, encoding
);
7173 /* If the sockets haven't been set up yet, the final setup part of
7174 this will be called asynchronously. */
7175 if (p
->infd
< 0 || p
->outfd
< 0)
7178 setup_process_coding_systems (process
);
7183 DEFUN ("process-coding-system",
7184 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7185 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7186 (register Lisp_Object process
)
7188 CHECK_PROCESS (process
);
7189 return Fcons (XPROCESS (process
)->decode_coding_system
,
7190 XPROCESS (process
)->encode_coding_system
);
7193 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7194 Sset_process_filter_multibyte
, 2, 2, 0,
7195 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7196 If FLAG is non-nil, the filter is given multibyte strings.
7197 If FLAG is nil, the filter is given unibyte strings. In this case,
7198 all character code conversion except for end-of-line conversion is
7200 (Lisp_Object process
, Lisp_Object flag
)
7202 CHECK_PROCESS (process
);
7204 struct Lisp_Process
*p
= XPROCESS (process
);
7206 pset_decode_coding_system
7207 (p
, raw_text_coding_system (p
->decode_coding_system
));
7209 /* If the sockets haven't been set up yet, the final setup part of
7210 this will be called asynchronously. */
7211 if (p
->infd
< 0 || p
->outfd
< 0)
7214 setup_process_coding_systems (process
);
7219 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7220 Sprocess_filter_multibyte_p
, 1, 1, 0,
7221 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7222 (Lisp_Object process
)
7224 CHECK_PROCESS (process
);
7225 struct Lisp_Process
*p
= XPROCESS (process
);
7228 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7229 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7238 add_gpm_wait_descriptor (int desc
)
7240 add_keyboard_wait_descriptor (desc
);
7244 delete_gpm_wait_descriptor (int desc
)
7246 delete_keyboard_wait_descriptor (desc
);
7251 # ifdef USABLE_SIGIO
7253 /* Return true if *MASK has a bit set
7254 that corresponds to one of the keyboard input descriptors. */
7257 keyboard_bit_set (fd_set
*mask
)
7261 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7262 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7263 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7270 #else /* not subprocesses */
7272 /* Defined in msdos.c. */
7273 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7274 struct timespec
*, void *);
7276 /* Implementation of wait_reading_process_output, assuming that there
7277 are no subprocesses. Used only by the MS-DOS build.
7279 Wait for timeout to elapse and/or keyboard input to be available.
7283 If negative, gobble data immediately available but don't wait for any.
7286 an additional duration to wait, measured in nanoseconds
7287 If TIME_LIMIT is zero, then:
7288 If NSECS == 0, there is no limit.
7289 If NSECS > 0, the timeout consists of NSECS only.
7290 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7293 0 to ignore keyboard input, or
7294 1 to return when input is available, or
7295 -1 means caller will actually read the input, so don't throw to
7298 see full version for other parameters. We know that wait_proc will
7299 always be NULL, since `subprocesses' isn't defined.
7301 DO_DISPLAY means redisplay should be done to show subprocess
7302 output that arrives.
7304 Return -1 signifying we got no output and did not try. */
7307 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7309 Lisp_Object wait_for_cell
,
7310 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7313 struct timespec end_time
, timeout
;
7314 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7316 if (TYPE_MAXIMUM (time_t) < time_limit
)
7317 time_limit
= TYPE_MAXIMUM (time_t);
7319 if (time_limit
< 0 || nsecs
< 0)
7321 else if (time_limit
> 0 || nsecs
> 0)
7324 end_time
= timespec_add (current_timespec (),
7325 make_timespec (time_limit
, nsecs
));
7330 /* Turn off periodic alarms (in case they are in use)
7331 and then turn off any other atimers,
7332 because the select emulator uses alarms. */
7334 turn_on_atimers (0);
7338 bool timeout_reduced_for_timers
= false;
7339 fd_set waitchannels
;
7342 /* If calling from keyboard input, do not quit
7343 since we want to return C-g as an input character.
7344 Otherwise, do pending quit if requested. */
7348 /* Exit now if the cell we're waiting for became non-nil. */
7349 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7352 /* Compute time from now till when time limit is up. */
7353 /* Exit if already run out. */
7354 if (wait
== TIMEOUT
)
7356 struct timespec now
= current_timespec ();
7357 if (timespec_cmp (end_time
, now
) <= 0)
7359 timeout
= timespec_sub (end_time
, now
);
7362 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7364 /* If our caller will not immediately handle keyboard events,
7365 run timer events directly.
7366 (Callers that will immediately read keyboard events
7367 call timer_delay on their own.) */
7368 if (NILP (wait_for_cell
))
7370 struct timespec timer_delay
;
7374 unsigned old_timers_run
= timers_run
;
7375 timer_delay
= timer_check ();
7376 if (timers_run
!= old_timers_run
&& do_display
)
7377 /* We must retry, since a timer may have requeued itself
7378 and that could alter the time delay. */
7379 redisplay_preserve_echo_area (14);
7383 while (!detect_input_pending ());
7385 /* If there is unread keyboard input, also return. */
7387 && requeued_events_pending_p ())
7390 if (timespec_valid_p (timer_delay
))
7392 if (timespec_cmp (timer_delay
, timeout
) < 0)
7394 timeout
= timer_delay
;
7395 timeout_reduced_for_timers
= true;
7400 /* Cause C-g and alarm signals to take immediate action,
7401 and cause input available signals to zero out timeout. */
7403 set_waiting_for_input (&timeout
);
7405 /* If a frame has been newly mapped and needs updating,
7406 reprocess its display stuff. */
7407 if (frame_garbaged
&& do_display
)
7409 clear_waiting_for_input ();
7410 redisplay_preserve_echo_area (15);
7412 set_waiting_for_input (&timeout
);
7415 /* Wait till there is something to do. */
7416 FD_ZERO (&waitchannels
);
7417 if (read_kbd
&& detect_input_pending ())
7421 if (read_kbd
|| !NILP (wait_for_cell
))
7422 FD_SET (0, &waitchannels
);
7423 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7428 /* Make C-g and alarm signals set flags again. */
7429 clear_waiting_for_input ();
7431 /* If we woke up due to SIGWINCH, actually change size now. */
7432 do_pending_window_change (0);
7434 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7435 /* We waited the full specified time, so return now. */
7440 /* If the system call was interrupted, then go around the
7442 if (xerrno
== EINTR
)
7443 FD_ZERO (&waitchannels
);
7445 report_file_errno ("Failed select", Qnil
, xerrno
);
7448 /* Check for keyboard input. */
7451 && detect_input_pending_run_timers (do_display
))
7453 swallow_events (do_display
);
7454 if (detect_input_pending_run_timers (do_display
))
7458 /* If there is unread keyboard input, also return. */
7460 && requeued_events_pending_p ())
7463 /* If wait_for_cell. check for keyboard input
7464 but don't run any timers.
7465 ??? (It seems wrong to me to check for keyboard
7466 input at all when wait_for_cell, but the code
7467 has been this way since July 1994.
7468 Try changing this after version 19.31.) */
7469 if (! NILP (wait_for_cell
)
7470 && detect_input_pending ())
7472 swallow_events (do_display
);
7473 if (detect_input_pending ())
7477 /* Exit now if the cell we're waiting for became non-nil. */
7478 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7487 #endif /* not subprocesses */
7489 /* The following functions are needed even if async subprocesses are
7490 not supported. Some of them are no-op stubs in that case. */
7494 /* Add FD, which is a descriptor returned by timerfd_create,
7495 to the set of non-keyboard input descriptors. */
7498 add_timer_wait_descriptor (int fd
)
7500 FD_SET (fd
, &input_wait_mask
);
7501 FD_SET (fd
, &non_keyboard_wait_mask
);
7502 FD_SET (fd
, &non_process_wait_mask
);
7503 fd_callback_info
[fd
].func
= timerfd_callback
;
7504 fd_callback_info
[fd
].data
= NULL
;
7505 fd_callback_info
[fd
].condition
|= FOR_READ
;
7506 if (fd
> max_input_desc
)
7507 max_input_desc
= fd
;
7510 #endif /* HAVE_TIMERFD */
7512 /* If program file NAME starts with /: for quoting a magic
7513 name, remove that, preserving the multibyteness of NAME. */
7516 remove_slash_colon (Lisp_Object name
)
7519 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7520 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7521 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7525 /* Add DESC to the set of keyboard input descriptors. */
7528 add_keyboard_wait_descriptor (int desc
)
7530 #ifdef subprocesses /* Actually means "not MSDOS". */
7531 FD_SET (desc
, &input_wait_mask
);
7532 FD_SET (desc
, &non_process_wait_mask
);
7533 if (desc
> max_input_desc
)
7534 max_input_desc
= desc
;
7538 /* From now on, do not expect DESC to give keyboard input. */
7541 delete_keyboard_wait_descriptor (int desc
)
7544 FD_CLR (desc
, &input_wait_mask
);
7545 FD_CLR (desc
, &non_process_wait_mask
);
7546 delete_input_desc (desc
);
7550 /* Setup coding systems of PROCESS. */
7553 setup_process_coding_systems (Lisp_Object process
)
7556 struct Lisp_Process
*p
= XPROCESS (process
);
7558 int outch
= p
->outfd
;
7559 Lisp_Object coding_system
;
7561 if (inch
< 0 || outch
< 0)
7564 if (!proc_decode_coding_system
[inch
])
7565 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7566 coding_system
= p
->decode_coding_system
;
7567 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7568 && BUFFERP (p
->buffer
))
7570 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7571 coding_system
= raw_text_coding_system (coding_system
);
7573 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7575 if (!proc_encode_coding_system
[outch
])
7576 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7577 setup_coding_system (p
->encode_coding_system
,
7578 proc_encode_coding_system
[outch
]);
7582 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7583 doc
: /* Return the (or a) live process associated with BUFFER.
7584 BUFFER may be a buffer or the name of one.
7585 Return nil if all processes associated with BUFFER have been
7586 deleted or killed. */)
7587 (register Lisp_Object buffer
)
7590 register Lisp_Object buf
, tail
, proc
;
7592 if (NILP (buffer
)) return Qnil
;
7593 buf
= Fget_buffer (buffer
);
7594 if (NILP (buf
)) return Qnil
;
7596 FOR_EACH_PROCESS (tail
, proc
)
7597 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7599 #endif /* subprocesses */
7603 DEFUN ("process-inherit-coding-system-flag",
7604 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7606 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7607 If this flag is t, `buffer-file-coding-system' of the buffer
7608 associated with PROCESS will inherit the coding system used to decode
7609 the process output. */)
7610 (register Lisp_Object process
)
7613 CHECK_PROCESS (process
);
7614 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7616 /* Ignore the argument and return the value of
7617 inherit-process-coding-system. */
7618 return inherit_process_coding_system
? Qt
: Qnil
;
7622 /* Kill all processes associated with `buffer'.
7623 If `buffer' is nil, kill all processes. */
7626 kill_buffer_processes (Lisp_Object buffer
)
7629 Lisp_Object tail
, proc
;
7631 FOR_EACH_PROCESS (tail
, proc
)
7632 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7634 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7635 Fdelete_process (proc
);
7636 else if (XPROCESS (proc
)->infd
>= 0)
7637 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7639 #else /* subprocesses */
7640 /* Since we have no subprocesses, this does nothing. */
7641 #endif /* subprocesses */
7644 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7645 Swaiting_for_user_input_p
, 0, 0, 0,
7646 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7647 This is intended for use by asynchronous process output filters and sentinels. */)
7651 return (waiting_for_user_input_p
? Qt
: Qnil
);
7657 /* Stop reading input from keyboard sources. */
7660 hold_keyboard_input (void)
7665 /* Resume reading input from keyboard sources. */
7668 unhold_keyboard_input (void)
7673 /* Return true if keyboard input is on hold, zero otherwise. */
7676 kbd_on_hold_p (void)
7678 return kbd_is_on_hold
;
7682 /* Enumeration of and access to system processes a-la ps(1). */
7684 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7686 doc
: /* Return a list of numerical process IDs of all running processes.
7687 If this functionality is unsupported, return nil.
7689 See `process-attributes' for getting attributes of a process given its ID. */)
7692 return list_system_processes ();
7695 DEFUN ("process-attributes", Fprocess_attributes
,
7696 Sprocess_attributes
, 1, 1, 0,
7697 doc
: /* Return attributes of the process given by its PID, a number.
7699 Value is an alist where each element is a cons cell of the form
7703 If this functionality is unsupported, the value is nil.
7705 See `list-system-processes' for getting a list of all process IDs.
7707 The KEYs of the attributes that this function may return are listed
7708 below, together with the type of the associated VALUE (in parentheses).
7709 Not all platforms support all of these attributes; unsupported
7710 attributes will not appear in the returned alist.
7711 Unless explicitly indicated otherwise, numbers can have either
7712 integer or floating point values.
7714 euid -- Effective user User ID of the process (number)
7715 user -- User name corresponding to euid (string)
7716 egid -- Effective user Group ID of the process (number)
7717 group -- Group name corresponding to egid (string)
7718 comm -- Command name (executable name only) (string)
7719 state -- Process state code, such as "S", "R", or "T" (string)
7720 ppid -- Parent process ID (number)
7721 pgrp -- Process group ID (number)
7722 sess -- Session ID, i.e. process ID of session leader (number)
7723 ttname -- Controlling tty name (string)
7724 tpgid -- ID of foreground process group on the process's tty (number)
7725 minflt -- number of minor page faults (number)
7726 majflt -- number of major page faults (number)
7727 cminflt -- cumulative number of minor page faults (number)
7728 cmajflt -- cumulative number of major page faults (number)
7729 utime -- user time used by the process, in (current-time) format,
7730 which is a list of integers (HIGH LOW USEC PSEC)
7731 stime -- system time used by the process (current-time)
7732 time -- sum of utime and stime (current-time)
7733 cutime -- user time used by the process and its children (current-time)
7734 cstime -- system time used by the process and its children (current-time)
7735 ctime -- sum of cutime and cstime (current-time)
7736 pri -- priority of the process (number)
7737 nice -- nice value of the process (number)
7738 thcount -- process thread count (number)
7739 start -- time the process started (current-time)
7740 vsize -- virtual memory size of the process in KB's (number)
7741 rss -- resident set size of the process in KB's (number)
7742 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7743 pcpu -- percents of CPU time used by the process (floating-point number)
7744 pmem -- percents of total physical memory used by process's resident set
7745 (floating-point number)
7746 args -- command line which invoked the process (string). */)
7749 return system_process_attributes (pid
);
7753 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7754 Invoke this after init_process_emacs, and after glib and/or GNUstep
7755 futz with the SIGCHLD handler, but before Emacs forks any children.
7756 This function's caller should block SIGCHLD. */
7759 catch_child_signal (void)
7761 struct sigaction action
, old_action
;
7763 emacs_sigaction_init (&action
, deliver_child_signal
);
7764 block_child_signal (&oldset
);
7765 sigaction (SIGCHLD
, &action
, &old_action
);
7766 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7767 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7769 if (old_action
.sa_handler
!= deliver_child_signal
)
7771 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7773 : old_action
.sa_handler
);
7774 unblock_child_signal (&oldset
);
7776 #endif /* subprocesses */
7778 /* Limit the number of open files to the value it had at startup. */
7781 restore_nofile_limit (void)
7783 #ifdef HAVE_SETRLIMIT
7784 if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
7785 setrlimit (RLIMIT_NOFILE
, &nofile_limit
);
7790 /* This is not called "init_process" because that is the name of a
7791 Mach system call, so it would cause problems on Darwin systems. */
7793 init_process_emacs (int sockfd
)
7798 inhibit_sentinels
= 0;
7801 if (! noninteractive
|| initialized
)
7804 #if defined HAVE_GLIB && !defined WINDOWSNT
7805 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7806 this should always fail, but is enough to initialize glib's
7807 private SIGCHLD handler, allowing catch_child_signal to copy
7808 it into lib_child_handler. */
7809 g_source_unref (g_child_watch_source_new (getpid ()));
7811 catch_child_signal ();
7814 #ifdef HAVE_SETRLIMIT
7815 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
7816 if (getrlimit (RLIMIT_NOFILE
, &nofile_limit
) != 0)
7817 nofile_limit
.rlim_cur
= 0;
7818 else if (FD_SETSIZE
< nofile_limit
.rlim_cur
)
7820 struct rlimit rlim
= nofile_limit
;
7821 rlim
.rlim_cur
= FD_SETSIZE
;
7822 if (setrlimit (RLIMIT_NOFILE
, &rlim
) != 0)
7823 nofile_limit
.rlim_cur
= 0;
7827 FD_ZERO (&input_wait_mask
);
7828 FD_ZERO (&non_keyboard_wait_mask
);
7829 FD_ZERO (&non_process_wait_mask
);
7830 FD_ZERO (&write_mask
);
7831 max_process_desc
= max_input_desc
= -1;
7832 external_sock_fd
= sockfd
;
7833 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7835 FD_ZERO (&connect_wait_mask
);
7836 num_pending_connects
= 0;
7838 process_output_delay_count
= 0;
7839 process_output_skip
= 0;
7841 /* Don't do this, it caused infinite select loops. The display
7842 method should call add_keyboard_wait_descriptor on stdin if it
7845 FD_SET (0, &input_wait_mask
);
7848 Vprocess_alist
= Qnil
;
7849 deleted_pid_list
= Qnil
;
7850 for (i
= 0; i
< FD_SETSIZE
; i
++)
7852 chan_process
[i
] = Qnil
;
7853 proc_buffered_char
[i
] = -1;
7855 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7856 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7857 #ifdef DATAGRAM_SOCKETS
7858 memset (datagram_address
, 0, sizeof datagram_address
);
7861 #if defined (DARWIN_OS)
7862 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7863 processes. As such, we only change the default value. */
7866 char const *release
= (STRINGP (Voperating_system_release
)
7867 ? SSDATA (Voperating_system_release
)
7869 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7870 Vprocess_connection_type
= Qnil
;
7874 #endif /* subprocesses */
7879 syms_of_process (void)
7883 DEFSYM (Qprocessp
, "processp");
7884 DEFSYM (Qrun
, "run");
7885 DEFSYM (Qstop
, "stop");
7886 DEFSYM (Qsignal
, "signal");
7888 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7891 DEFSYM (Qopen
, "open");
7892 DEFSYM (Qclosed
, "closed");
7893 DEFSYM (Qconnect
, "connect");
7894 DEFSYM (Qfailed
, "failed");
7895 DEFSYM (Qlisten
, "listen");
7896 DEFSYM (Qlocal
, "local");
7897 DEFSYM (Qipv4
, "ipv4");
7899 DEFSYM (Qipv6
, "ipv6");
7901 DEFSYM (Qdatagram
, "datagram");
7902 DEFSYM (Qseqpacket
, "seqpacket");
7904 DEFSYM (QCport
, ":port");
7905 DEFSYM (QCspeed
, ":speed");
7906 DEFSYM (QCprocess
, ":process");
7908 DEFSYM (QCbytesize
, ":bytesize");
7909 DEFSYM (QCstopbits
, ":stopbits");
7910 DEFSYM (QCparity
, ":parity");
7911 DEFSYM (Qodd
, "odd");
7912 DEFSYM (Qeven
, "even");
7913 DEFSYM (QCflowcontrol
, ":flowcontrol");
7916 DEFSYM (QCsummary
, ":summary");
7918 DEFSYM (Qreal
, "real");
7919 DEFSYM (Qnetwork
, "network");
7920 DEFSYM (Qserial
, "serial");
7921 DEFSYM (Qpipe
, "pipe");
7922 DEFSYM (QCbuffer
, ":buffer");
7923 DEFSYM (QChost
, ":host");
7924 DEFSYM (QCservice
, ":service");
7925 DEFSYM (QClocal
, ":local");
7926 DEFSYM (QCremote
, ":remote");
7927 DEFSYM (QCcoding
, ":coding");
7928 DEFSYM (QCserver
, ":server");
7929 DEFSYM (QCnowait
, ":nowait");
7930 DEFSYM (QCsentinel
, ":sentinel");
7931 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7932 DEFSYM (QCtls_parameters
, ":tls-parameters");
7933 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7934 DEFSYM (QClog
, ":log");
7935 DEFSYM (QCnoquery
, ":noquery");
7936 DEFSYM (QCstop
, ":stop");
7937 DEFSYM (QCplist
, ":plist");
7938 DEFSYM (QCcommand
, ":command");
7939 DEFSYM (QCconnection_type
, ":connection-type");
7940 DEFSYM (QCstderr
, ":stderr");
7941 DEFSYM (Qpty
, "pty");
7942 DEFSYM (Qpipe
, "pipe");
7944 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7946 staticpro (&Vprocess_alist
);
7947 staticpro (&deleted_pid_list
);
7949 #endif /* subprocesses */
7951 DEFSYM (QCname
, ":name");
7952 DEFSYM (QCtype
, ":type");
7954 DEFSYM (Qeuid
, "euid");
7955 DEFSYM (Qegid
, "egid");
7956 DEFSYM (Quser
, "user");
7957 DEFSYM (Qgroup
, "group");
7958 DEFSYM (Qcomm
, "comm");
7959 DEFSYM (Qstate
, "state");
7960 DEFSYM (Qppid
, "ppid");
7961 DEFSYM (Qpgrp
, "pgrp");
7962 DEFSYM (Qsess
, "sess");
7963 DEFSYM (Qttname
, "ttname");
7964 DEFSYM (Qtpgid
, "tpgid");
7965 DEFSYM (Qminflt
, "minflt");
7966 DEFSYM (Qmajflt
, "majflt");
7967 DEFSYM (Qcminflt
, "cminflt");
7968 DEFSYM (Qcmajflt
, "cmajflt");
7969 DEFSYM (Qutime
, "utime");
7970 DEFSYM (Qstime
, "stime");
7971 DEFSYM (Qtime
, "time");
7972 DEFSYM (Qcutime
, "cutime");
7973 DEFSYM (Qcstime
, "cstime");
7974 DEFSYM (Qctime
, "ctime");
7976 DEFSYM (Qinternal_default_process_sentinel
,
7977 "internal-default-process-sentinel");
7978 DEFSYM (Qinternal_default_process_filter
,
7979 "internal-default-process-filter");
7981 DEFSYM (Qpri
, "pri");
7982 DEFSYM (Qnice
, "nice");
7983 DEFSYM (Qthcount
, "thcount");
7984 DEFSYM (Qstart
, "start");
7985 DEFSYM (Qvsize
, "vsize");
7986 DEFSYM (Qrss
, "rss");
7987 DEFSYM (Qetime
, "etime");
7988 DEFSYM (Qpcpu
, "pcpu");
7989 DEFSYM (Qpmem
, "pmem");
7990 DEFSYM (Qargs
, "args");
7992 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7993 doc
: /* Non-nil means delete processes immediately when they exit.
7994 A value of nil means don't delete them until `list-processes' is run. */);
7996 delete_exited_processes
= 1;
7999 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
8000 doc
: /* Control type of device used to communicate with subprocesses.
8001 Values are nil to use a pipe, or t or `pty' to use a pty.
8002 The value has no effect if the system has no ptys or if all ptys are busy:
8003 then a pipe is used in any case.
8004 The value takes effect when `start-process' is called. */);
8005 Vprocess_connection_type
= Qt
;
8007 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
8008 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
8009 On some systems, when Emacs reads the output from a subprocess, the output data
8010 is read in very small blocks, potentially resulting in very poor performance.
8011 This behavior can be remedied to some extent by setting this variable to a
8012 non-nil value, as it will automatically delay reading from such processes, to
8013 allow them to produce more output before Emacs tries to read it.
8014 If the value is t, the delay is reset after each write to the process; any other
8015 non-nil value means that the delay is not reset on write.
8016 The variable takes effect when `start-process' is called. */);
8017 Vprocess_adaptive_read_buffering
= Qt
;
8019 defsubr (&Sprocessp
);
8020 defsubr (&Sget_process
);
8021 defsubr (&Sdelete_process
);
8022 defsubr (&Sprocess_status
);
8023 defsubr (&Sprocess_exit_status
);
8024 defsubr (&Sprocess_id
);
8025 defsubr (&Sprocess_name
);
8026 defsubr (&Sprocess_tty_name
);
8027 defsubr (&Sprocess_command
);
8028 defsubr (&Sset_process_buffer
);
8029 defsubr (&Sprocess_buffer
);
8030 defsubr (&Sprocess_mark
);
8031 defsubr (&Sset_process_filter
);
8032 defsubr (&Sprocess_filter
);
8033 defsubr (&Sset_process_sentinel
);
8034 defsubr (&Sprocess_sentinel
);
8035 defsubr (&Sset_process_window_size
);
8036 defsubr (&Sset_process_inherit_coding_system_flag
);
8037 defsubr (&Sset_process_query_on_exit_flag
);
8038 defsubr (&Sprocess_query_on_exit_flag
);
8039 defsubr (&Sprocess_contact
);
8040 defsubr (&Sprocess_plist
);
8041 defsubr (&Sset_process_plist
);
8042 defsubr (&Sprocess_list
);
8043 defsubr (&Smake_process
);
8044 defsubr (&Smake_pipe_process
);
8045 defsubr (&Sserial_process_configure
);
8046 defsubr (&Smake_serial_process
);
8047 defsubr (&Sset_network_process_option
);
8048 defsubr (&Smake_network_process
);
8049 defsubr (&Sformat_network_address
);
8050 defsubr (&Snetwork_interface_list
);
8051 defsubr (&Snetwork_interface_info
);
8052 #ifdef DATAGRAM_SOCKETS
8053 defsubr (&Sprocess_datagram_address
);
8054 defsubr (&Sset_process_datagram_address
);
8056 defsubr (&Saccept_process_output
);
8057 defsubr (&Sprocess_send_region
);
8058 defsubr (&Sprocess_send_string
);
8059 defsubr (&Sinterrupt_process
);
8060 defsubr (&Skill_process
);
8061 defsubr (&Squit_process
);
8062 defsubr (&Sstop_process
);
8063 defsubr (&Scontinue_process
);
8064 defsubr (&Sprocess_running_child_p
);
8065 defsubr (&Sprocess_send_eof
);
8066 defsubr (&Ssignal_process
);
8067 defsubr (&Swaiting_for_user_input_p
);
8068 defsubr (&Sprocess_type
);
8069 defsubr (&Sinternal_default_process_sentinel
);
8070 defsubr (&Sinternal_default_process_filter
);
8071 defsubr (&Sset_process_coding_system
);
8072 defsubr (&Sprocess_coding_system
);
8073 defsubr (&Sset_process_filter_multibyte
);
8074 defsubr (&Sprocess_filter_multibyte_p
);
8077 Lisp_Object subfeatures
= Qnil
;
8078 const struct socket_options
*sopt
;
8080 #define ADD_SUBFEATURE(key, val) \
8081 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8083 ADD_SUBFEATURE (QCnowait
, Qt
);
8084 #ifdef DATAGRAM_SOCKETS
8085 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8087 #ifdef HAVE_SEQPACKET
8088 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8090 #ifdef HAVE_LOCAL_SOCKETS
8091 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8093 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8095 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8097 #ifdef HAVE_GETSOCKNAME
8098 ADD_SUBFEATURE (QCservice
, Qt
);
8100 ADD_SUBFEATURE (QCserver
, Qt
);
8102 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8103 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8105 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8108 #endif /* subprocesses */
8110 defsubr (&Sget_buffer_process
);
8111 defsubr (&Sprocess_inherit_coding_system_flag
);
8112 defsubr (&Slist_system_processes
);
8113 defsubr (&Sprocess_attributes
);