1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
34 /* Only MS-DOS does not define `subprocesses'. */
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
48 #define HAVE_LOCAL_SOCKETS
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
90 #endif /* subprocesses */
96 #include "character.h"
101 #include "termopts.h"
102 #include "keyboard.h"
103 #include "blockinput.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
112 #ifdef HAVE_WINDOW_SYSTEM
114 #endif /* HAVE_WINDOW_SYSTEM */
117 #include "xgselect.h"
123 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
124 /* This is 0.1s in nanoseconds. */
125 #define ASYNC_RETRY_NSEC 100000000
129 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
130 struct timespec
*, void *);
133 /* Work around GCC 4.7.0 bug with strict overflow checking; see
134 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
135 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
136 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
137 # pragma GCC diagnostic ignored "-Wstrict-overflow"
140 /* True if keyboard input is on hold, zero otherwise. */
142 static bool kbd_is_on_hold
;
144 /* Nonzero means don't run process sentinels. This is used
146 bool inhibit_sentinels
;
151 # define SOCK_CLOEXEC 0
154 /* True if ERRNUM represents an error where the system call would
155 block if a blocking variant were used. */
157 would_block (int errnum
)
160 if (EWOULDBLOCK
!= EAGAIN
&& errnum
== EWOULDBLOCK
)
163 return errnum
== EAGAIN
;
168 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
171 close_on_exec (int fd
)
174 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
179 # define accept4(sockfd, addr, addrlen, flags) \
180 process_accept4 (sockfd, addr, addrlen, flags)
182 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
184 return close_on_exec (accept (sockfd
, addr
, addrlen
));
188 process_socket (int domain
, int type
, int protocol
)
190 return close_on_exec (socket (domain
, type
, protocol
));
193 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
196 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
197 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
198 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
199 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
200 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
201 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
203 /* Number of events of change of status of a process. */
204 static EMACS_INT process_tick
;
205 /* Number of events for which the user or sentinel has been notified. */
206 static EMACS_INT update_tick
;
208 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
209 this system. We need to read full packets, so we need a
210 "non-destructive" select. So we require either native select,
211 or emulation of select using FIONREAD. */
213 #ifndef BROKEN_DATAGRAM_SOCKETS
214 # if defined HAVE_SELECT || defined USABLE_FIONREAD
215 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
216 # define DATAGRAM_SOCKETS
221 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
222 # define HAVE_SEQPACKET
225 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
226 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
227 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
229 /* Number of processes which have a non-zero read_output_delay,
230 and therefore might be delayed for adaptive read buffering. */
232 static int process_output_delay_count
;
234 /* True if any process has non-nil read_output_skip. */
236 static bool process_output_skip
;
238 static void create_process (Lisp_Object
, char **, Lisp_Object
);
240 static bool keyboard_bit_set (fd_set
*);
242 static void deactivate_process (Lisp_Object
);
243 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
244 static int read_process_output (Lisp_Object
, int);
245 static void handle_child_signal (int);
246 static void create_pty (Lisp_Object
);
248 static Lisp_Object
get_process (register Lisp_Object name
);
249 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
251 /* Mask of bits indicating the descriptors that we wait for input on. */
253 static fd_set input_wait_mask
;
255 /* Mask that excludes keyboard input descriptor(s). */
257 static fd_set non_keyboard_wait_mask
;
259 /* Mask that excludes process input descriptor(s). */
261 static fd_set non_process_wait_mask
;
263 /* Mask for selecting for write. */
265 static fd_set write_mask
;
267 /* Mask of bits indicating the descriptors that we wait for connect to
268 complete on. Once they complete, they are removed from this mask
269 and added to the input_wait_mask and non_keyboard_wait_mask. */
271 static fd_set connect_wait_mask
;
273 /* Number of bits set in connect_wait_mask. */
274 static int num_pending_connects
;
276 /* The largest descriptor currently in use for a process object; -1 if none. */
277 static int max_process_desc
;
279 /* The largest descriptor currently in use for input; -1 if none. */
280 static int max_input_desc
;
282 /* Set the external socket descriptor for Emacs to use when
283 `make-network-process' is called with a non-nil
284 `:use-external-socket' option. The value should be either -1, or
285 the file descriptor of a socket that is already bound. */
286 static int external_sock_fd
;
288 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
289 static Lisp_Object chan_process
[FD_SETSIZE
];
290 static void wait_for_socket_fds (Lisp_Object
, char const *);
292 /* Alist of elements (NAME . PROCESS). */
293 static Lisp_Object Vprocess_alist
;
295 /* Buffered-ahead input char from process, indexed by channel.
296 -1 means empty (no char is buffered).
297 Used on sys V where the only way to tell if there is any
298 output from the process is to read at least one char.
299 Always -1 on systems that support FIONREAD. */
301 static int proc_buffered_char
[FD_SETSIZE
];
303 /* Table of `struct coding-system' for each process. */
304 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
305 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
307 #ifdef DATAGRAM_SOCKETS
308 /* Table of `partner address' for datagram sockets. */
309 static struct sockaddr_and_len
{
312 } datagram_address
[FD_SETSIZE
];
313 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
314 #define DATAGRAM_CONN_P(proc) \
315 (PROCESSP (proc) && \
316 XPROCESS (proc)->infd >= 0 && \
317 datagram_address[XPROCESS (proc)->infd].sa != 0)
319 #define DATAGRAM_CONN_P(proc) (0)
322 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
323 a `for' loop which iterates over processes from Vprocess_alist. */
325 #define FOR_EACH_PROCESS(list_var, proc_var) \
326 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
328 /* These setters are used only in this file, so they can be private. */
330 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
335 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
340 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
342 p
->decode_coding_system
= val
;
345 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
347 p
->decoding_buf
= val
;
350 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
352 p
->encode_coding_system
= val
;
355 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
357 p
->encoding_buf
= val
;
360 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
362 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
365 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
370 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
375 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
380 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
385 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
387 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
390 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
395 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
400 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
402 p
->write_queue
= val
;
405 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
412 make_lisp_proc (struct Lisp_Process
*p
)
414 return make_lisp_ptr (p
, Lisp_Vectorlike
);
417 static struct fd_callback_data
423 int condition
; /* Mask of the defines above. */
424 } fd_callback_info
[FD_SETSIZE
];
427 /* Add a file descriptor FD to be monitored for when read is possible.
428 When read is possible, call FUNC with argument DATA. */
431 add_read_fd (int fd
, fd_callback func
, void *data
)
433 add_keyboard_wait_descriptor (fd
);
435 fd_callback_info
[fd
].func
= func
;
436 fd_callback_info
[fd
].data
= data
;
437 fd_callback_info
[fd
].condition
|= FOR_READ
;
440 /* Stop monitoring file descriptor FD for when read is possible. */
443 delete_read_fd (int fd
)
445 delete_keyboard_wait_descriptor (fd
);
447 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
448 if (fd_callback_info
[fd
].condition
== 0)
450 fd_callback_info
[fd
].func
= 0;
451 fd_callback_info
[fd
].data
= 0;
455 /* Add a file descriptor FD to be monitored for when write is possible.
456 When write is possible, call FUNC with argument DATA. */
459 add_write_fd (int fd
, fd_callback func
, void *data
)
461 FD_SET (fd
, &write_mask
);
462 if (fd
> max_input_desc
)
465 fd_callback_info
[fd
].func
= func
;
466 fd_callback_info
[fd
].data
= data
;
467 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
470 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
473 delete_input_desc (int fd
)
475 if (fd
== max_input_desc
)
479 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
480 || FD_ISSET (fd
, &write_mask
)));
486 /* Stop monitoring file descriptor FD for when write is possible. */
489 delete_write_fd (int fd
)
491 FD_CLR (fd
, &write_mask
);
492 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
493 if (fd_callback_info
[fd
].condition
== 0)
495 fd_callback_info
[fd
].func
= 0;
496 fd_callback_info
[fd
].data
= 0;
497 delete_input_desc (fd
);
502 /* Compute the Lisp form of the process status, p->status, from
503 the numeric status that was returned by `wait'. */
505 static Lisp_Object
status_convert (int);
508 update_status (struct Lisp_Process
*p
)
510 eassert (p
->raw_status_new
);
511 pset_status (p
, status_convert (p
->raw_status
));
512 p
->raw_status_new
= 0;
515 /* Convert a process status word in Unix format to
516 the list that we use internally. */
519 status_convert (int w
)
522 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
523 else if (WIFEXITED (w
))
524 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
525 WCOREDUMP (w
) ? Qt
: Qnil
));
526 else if (WIFSIGNALED (w
))
527 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
528 WCOREDUMP (w
) ? Qt
: Qnil
));
533 /* Given a status-list, extract the three pieces of information
534 and store them individually through the three pointers. */
537 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
551 *code
= XFASTINT (XCAR (tem
));
553 *coredump
= !NILP (tem
);
557 /* Return a string describing a process status list. */
560 status_message (struct Lisp_Process
*p
)
562 Lisp_Object status
= p
->status
;
568 decode_status (status
, &symbol
, &code
, &coredump
);
570 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
573 synchronize_system_messages_locale ();
574 signame
= strsignal (code
);
576 string
= build_string ("unknown");
581 string
= build_unibyte_string (signame
);
582 if (! NILP (Vlocale_coding_system
))
583 string
= (code_convert_string_norecord
584 (string
, Vlocale_coding_system
, 0));
585 c1
= STRING_CHAR (SDATA (string
));
588 Faset (string
, make_number (0), make_number (c2
));
590 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
591 return concat2 (string
, suffix
);
593 else if (EQ (symbol
, Qexit
))
596 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
598 return build_string ("finished\n");
599 AUTO_STRING (prefix
, "exited abnormally with code ");
600 string
= Fnumber_to_string (make_number (code
));
601 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
602 return concat3 (prefix
, string
, suffix
);
604 else if (EQ (symbol
, Qfailed
))
606 AUTO_STRING (prefix
, "failed with code ");
607 string
= Fnumber_to_string (make_number (code
));
608 AUTO_STRING (suffix
, "\n");
609 return concat3 (prefix
, string
, suffix
);
612 return Fcopy_sequence (Fsymbol_name (symbol
));
615 enum { PTY_NAME_SIZE
= 24 };
617 /* Open an available pty, returning a file descriptor.
618 Store into PTY_NAME the file name of the terminal corresponding to the pty.
619 Return -1 on failure. */
622 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
631 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
632 for (i
= 0; i
< 16; i
++)
635 #ifdef PTY_NAME_SPRINTF
638 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
639 #endif /* no PTY_NAME_SPRINTF */
643 #else /* no PTY_OPEN */
644 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
645 #endif /* no PTY_OPEN */
649 #ifdef PTY_TTY_NAME_SPRINTF
652 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
653 #endif /* no PTY_TTY_NAME_SPRINTF */
655 /* Set FD's close-on-exec flag. This is needed even if
656 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
657 doesn't require support for that combination.
658 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
659 doesn't work if the close-on-exec flag is set (Bug#20555).
660 Multithreaded platforms where posix_openpt ignores
661 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
662 have a race condition between the PTY_OPEN and here. */
663 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
665 /* Check to make certain that both sides are available.
666 This avoids a nasty yet stupid bug in rlogins. */
667 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
680 #endif /* HAVE_PTYS */
684 /* Allocate basically initialized process. */
686 static struct Lisp_Process
*
687 allocate_process (void)
689 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
693 make_process (Lisp_Object name
)
695 struct Lisp_Process
*p
= allocate_process ();
696 /* Initialize Lisp data. Note that allocate_process initializes all
697 Lisp data to nil, so do it only for slots which should not be nil. */
698 pset_status (p
, Qrun
);
699 pset_mark (p
, Fmake_marker ());
701 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
702 non-Lisp data, so do it only for slots which should not be zero. */
705 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
709 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
710 p
->gnutls_boot_parameters
= Qnil
;
713 /* If name is already in use, modify it until it is unused. */
715 Lisp_Object name1
= name
;
716 for (printmax_t i
= 1; ; i
++)
718 Lisp_Object tem
= Fget_process (name1
);
721 char const suffix_fmt
[] = "<%"pMd
">";
722 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
723 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
724 name1
= concat2 (name
, lsuffix
);
728 pset_sentinel (p
, Qinternal_default_process_sentinel
);
729 pset_filter (p
, Qinternal_default_process_filter
);
731 XSETPROCESS (val
, p
);
732 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
737 remove_process (register Lisp_Object proc
)
739 register Lisp_Object pair
;
741 pair
= Frassq (proc
, Vprocess_alist
);
742 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
744 deactivate_process (proc
);
747 #ifdef HAVE_GETADDRINFO_A
749 free_dns_request (Lisp_Object proc
)
751 struct Lisp_Process
*p
= XPROCESS (proc
);
753 if (p
->dns_request
->ar_result
)
754 freeaddrinfo (p
->dns_request
->ar_result
);
755 xfree (p
->dns_request
);
756 p
->dns_request
= NULL
;
761 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
762 doc
: /* Return t if OBJECT is a process. */)
765 return PROCESSP (object
) ? Qt
: Qnil
;
768 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
769 doc
: /* Return the process named NAME, or nil if there is none. */)
770 (register Lisp_Object name
)
775 return Fcdr (Fassoc (name
, Vprocess_alist
));
778 /* This is how commands for the user decode process arguments. It
779 accepts a process, a process name, a buffer, a buffer name, or nil.
780 Buffers denote the first process in the buffer, and nil denotes the
784 get_process (register Lisp_Object name
)
786 register Lisp_Object proc
, obj
;
789 obj
= Fget_process (name
);
791 obj
= Fget_buffer (name
);
793 error ("Process %s does not exist", SDATA (name
));
795 else if (NILP (name
))
796 obj
= Fcurrent_buffer ();
800 /* Now obj should be either a buffer object or a process object. */
803 if (NILP (BVAR (XBUFFER (obj
), name
)))
804 error ("Attempt to get process for a dead buffer");
805 proc
= Fget_buffer_process (obj
);
807 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
818 /* Fdelete_process promises to immediately forget about the process, but in
819 reality, Emacs needs to remember those processes until they have been
820 treated by the SIGCHLD handler and waitpid has been invoked on them;
821 otherwise they might fill up the kernel's process table.
823 Some processes created by call-process are also put onto this list.
825 Members of this list are (process-ID . filename) pairs. The
826 process-ID is a number; the filename, if a string, is a file that
827 needs to be removed after the process exits. */
828 static Lisp_Object deleted_pid_list
;
831 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
833 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
834 /* GC treated elements set to nil. */
835 Fdelq (Qnil
, deleted_pid_list
));
839 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
840 doc
: /* Delete PROCESS: kill it and forget about it immediately.
841 PROCESS may be a process, a buffer, the name of a process or buffer, or
842 nil, indicating the current buffer's process. */)
843 (register Lisp_Object process
)
845 register struct Lisp_Process
*p
;
847 process
= get_process (process
);
848 p
= XPROCESS (process
);
850 #ifdef HAVE_GETADDRINFO_A
853 /* Cancel the request. Unless shutting down, wait until
854 completion. Free the request if completely canceled. */
856 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
857 if (!canceled
&& !inhibit_sentinels
)
859 struct gaicb
const *req
= p
->dns_request
;
860 while (gai_suspend (&req
, 1, NULL
) != 0)
865 free_dns_request (process
);
869 p
->raw_status_new
= 0;
870 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
872 pset_status (p
, list2 (Qexit
, make_number (0)));
873 p
->tick
= ++process_tick
;
874 status_notify (p
, NULL
);
875 redisplay_preserve_echo_area (13);
880 record_kill_process (p
, Qnil
);
884 /* Update P's status, since record_kill_process will make the
885 SIGCHLD handler update deleted_pid_list, not *P. */
887 if (p
->raw_status_new
)
889 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
890 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
891 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
893 p
->tick
= ++process_tick
;
894 status_notify (p
, NULL
);
895 redisplay_preserve_echo_area (13);
898 remove_process (process
);
902 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
903 doc
: /* Return the status of PROCESS.
904 The returned value is one of the following symbols:
905 run -- for a process that is running.
906 stop -- for a process stopped but continuable.
907 exit -- for a process that has exited.
908 signal -- for a process that has got a fatal signal.
909 open -- for a network stream connection that is open.
910 listen -- for a network stream server that is listening.
911 closed -- for a network stream connection that is closed.
912 connect -- when waiting for a non-blocking connection to complete.
913 failed -- when a non-blocking connection has failed.
914 nil -- if arg is a process name and no such process exists.
915 PROCESS may be a process, a buffer, the name of a process, or
916 nil, indicating the current buffer's process. */)
917 (register Lisp_Object process
)
919 register struct Lisp_Process
*p
;
920 register Lisp_Object status
;
922 if (STRINGP (process
))
923 process
= Fget_process (process
);
925 process
= get_process (process
);
930 p
= XPROCESS (process
);
931 if (p
->raw_status_new
)
935 status
= XCAR (status
);
936 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
938 if (EQ (status
, Qexit
))
940 else if (EQ (p
->command
, Qt
))
942 else if (EQ (status
, Qrun
))
948 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
950 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
951 If PROCESS has not yet exited or died, return 0. */)
952 (register Lisp_Object process
)
954 CHECK_PROCESS (process
);
955 if (XPROCESS (process
)->raw_status_new
)
956 update_status (XPROCESS (process
));
957 if (CONSP (XPROCESS (process
)->status
))
958 return XCAR (XCDR (XPROCESS (process
)->status
));
959 return make_number (0);
962 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
963 doc
: /* Return the process id of PROCESS.
964 This is the pid of the external process which PROCESS uses or talks to.
965 For a network connection, this value is nil. */)
966 (register Lisp_Object process
)
970 CHECK_PROCESS (process
);
971 pid
= XPROCESS (process
)->pid
;
972 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
975 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
976 doc
: /* Return the name of PROCESS, as a string.
977 This is the name of the program invoked in PROCESS,
978 possibly modified to make it unique among process names. */)
979 (register Lisp_Object process
)
981 CHECK_PROCESS (process
);
982 return XPROCESS (process
)->name
;
985 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
986 doc
: /* Return the command that was executed to start PROCESS.
987 This is a list of strings, the first string being the program executed
988 and the rest of the strings being the arguments given to it.
989 For a network or serial process, this is nil (process is running) or t
990 \(process is stopped). */)
991 (register Lisp_Object process
)
993 CHECK_PROCESS (process
);
994 return XPROCESS (process
)->command
;
997 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
998 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
999 This is the terminal that the process itself reads and writes on,
1000 not the name of the pty that Emacs uses to talk with that terminal. */)
1001 (register Lisp_Object process
)
1003 CHECK_PROCESS (process
);
1004 return XPROCESS (process
)->tty_name
;
1007 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1009 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1011 (register Lisp_Object process
, Lisp_Object buffer
)
1013 struct Lisp_Process
*p
;
1015 CHECK_PROCESS (process
);
1017 CHECK_BUFFER (buffer
);
1018 p
= XPROCESS (process
);
1019 pset_buffer (p
, buffer
);
1020 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1021 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1022 setup_process_coding_systems (process
);
1026 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1028 doc
: /* Return the buffer PROCESS is associated with.
1029 The default process filter inserts output from PROCESS into this buffer. */)
1030 (register Lisp_Object process
)
1032 CHECK_PROCESS (process
);
1033 return XPROCESS (process
)->buffer
;
1036 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1038 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1039 (register Lisp_Object process
)
1041 CHECK_PROCESS (process
);
1042 return XPROCESS (process
)->mark
;
1046 set_process_filter_masks (struct Lisp_Process
*p
)
1048 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1050 FD_CLR (p
->infd
, &input_wait_mask
);
1051 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1053 else if (EQ (p
->filter
, Qt
)
1054 /* Network or serial process not stopped: */
1055 && !EQ (p
->command
, Qt
))
1057 FD_SET (p
->infd
, &input_wait_mask
);
1058 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1062 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1064 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1065 A value of t means stop accepting output from the process.
1067 When a process has a non-default filter, its buffer is not used for output.
1068 Instead, each time it does output, the entire string of output is
1069 passed to the filter.
1071 The filter gets two arguments: the process and the string of output.
1072 The string argument is normally a multibyte string, except:
1073 - if the process's input coding system is no-conversion or raw-text,
1074 it is a unibyte string (the non-converted input), or else
1075 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1076 string (the result of converting the decoded input multibyte
1077 string to unibyte with `string-make-unibyte'). */)
1078 (Lisp_Object process
, Lisp_Object filter
)
1080 CHECK_PROCESS (process
);
1081 struct Lisp_Process
*p
= XPROCESS (process
);
1083 /* Don't signal an error if the process's input file descriptor
1084 is closed. This could make debugging Lisp more difficult,
1085 for example when doing something like
1087 (setq process (start-process ...))
1089 (set-process-filter process ...) */
1092 filter
= Qinternal_default_process_filter
;
1094 pset_filter (p
, filter
);
1097 set_process_filter_masks (p
);
1099 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1100 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1101 setup_process_coding_systems (process
);
1105 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1107 doc
: /* Return the filter function of PROCESS.
1108 See `set-process-filter' for more info on filter functions. */)
1109 (register Lisp_Object process
)
1111 CHECK_PROCESS (process
);
1112 return XPROCESS (process
)->filter
;
1115 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1117 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1118 The sentinel is called as a function when the process changes state.
1119 It gets two arguments: the process, and a string describing the change. */)
1120 (register Lisp_Object process
, Lisp_Object sentinel
)
1122 struct Lisp_Process
*p
;
1124 CHECK_PROCESS (process
);
1125 p
= XPROCESS (process
);
1127 if (NILP (sentinel
))
1128 sentinel
= Qinternal_default_process_sentinel
;
1130 pset_sentinel (p
, sentinel
);
1131 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1132 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1136 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1138 doc
: /* Return the sentinel of PROCESS.
1139 See `set-process-sentinel' for more info on sentinels. */)
1140 (register Lisp_Object process
)
1142 CHECK_PROCESS (process
);
1143 return XPROCESS (process
)->sentinel
;
1146 DEFUN ("set-process-window-size", Fset_process_window_size
,
1147 Sset_process_window_size
, 3, 3, 0,
1148 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1149 Value is t if PROCESS was successfully told about the window size,
1151 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1153 CHECK_PROCESS (process
);
1155 /* All known platforms store window sizes as 'unsigned short'. */
1156 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1157 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1159 if (NETCONN_P (process
)
1160 || XPROCESS (process
)->infd
< 0
1161 || (set_window_size (XPROCESS (process
)->infd
,
1162 XINT (height
), XINT (width
))
1169 DEFUN ("set-process-inherit-coding-system-flag",
1170 Fset_process_inherit_coding_system_flag
,
1171 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1172 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1173 If the second argument FLAG is non-nil, then the variable
1174 `buffer-file-coding-system' of the buffer associated with PROCESS
1175 will be bound to the value of the coding system used to decode
1178 This is useful when the coding system specified for the process buffer
1179 leaves either the character code conversion or the end-of-line conversion
1180 unspecified, or if the coding system used to decode the process output
1181 is more appropriate for saving the process buffer.
1183 Binding the variable `inherit-process-coding-system' to non-nil before
1184 starting the process is an alternative way of setting the inherit flag
1185 for the process which will run.
1187 This function returns FLAG. */)
1188 (register Lisp_Object process
, Lisp_Object flag
)
1190 CHECK_PROCESS (process
);
1191 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1195 DEFUN ("set-process-query-on-exit-flag",
1196 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1198 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1199 If the second argument FLAG is non-nil, Emacs will query the user before
1200 exiting or killing a buffer if PROCESS is running. This function
1202 (register Lisp_Object process
, Lisp_Object flag
)
1204 CHECK_PROCESS (process
);
1205 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1209 DEFUN ("process-query-on-exit-flag",
1210 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1212 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1213 (register Lisp_Object process
)
1215 CHECK_PROCESS (process
);
1216 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1219 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1221 doc
: /* Return the contact info of PROCESS; t for a real child.
1222 For a network or serial connection, the value depends on the optional
1223 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1224 SERVICE) for a network connection or (PORT SPEED) for a serial
1225 connection. If KEY is t, the complete contact information for the
1226 connection is returned, else the specific value for the keyword KEY is
1227 returned. See `make-network-process' or `make-serial-process' for a
1229 If PROCESS is a non-blocking network process that hasn't been fully
1230 set up yet, this function will block until socket setup has completed. */)
1231 (Lisp_Object process
, Lisp_Object key
)
1233 Lisp_Object contact
;
1235 CHECK_PROCESS (process
);
1236 contact
= XPROCESS (process
)->childp
;
1238 #ifdef DATAGRAM_SOCKETS
1240 if (NETCONN_P (process
))
1241 wait_for_socket_fds (process
, "process-contact");
1243 if (DATAGRAM_CONN_P (process
)
1244 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1245 contact
= Fplist_put (contact
, QCremote
,
1246 Fprocess_datagram_address (process
));
1249 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1252 if (NILP (key
) && NETCONN_P (process
))
1253 return list2 (Fplist_get (contact
, QChost
),
1254 Fplist_get (contact
, QCservice
));
1255 if (NILP (key
) && SERIALCONN_P (process
))
1256 return list2 (Fplist_get (contact
, QCport
),
1257 Fplist_get (contact
, QCspeed
));
1258 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1259 if the pipe process is useful for purposes other than receiving
1261 if (NILP (key
) && PIPECONN_P (process
))
1263 return Fplist_get (contact
, key
);
1266 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1268 doc
: /* Return the plist of PROCESS. */)
1269 (register Lisp_Object process
)
1271 CHECK_PROCESS (process
);
1272 return XPROCESS (process
)->plist
;
1275 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1277 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1278 (Lisp_Object process
, Lisp_Object plist
)
1280 CHECK_PROCESS (process
);
1283 pset_plist (XPROCESS (process
), plist
);
1287 #if 0 /* Turned off because we don't currently record this info
1288 in the process. Perhaps add it. */
1289 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1290 doc
: /* Return the connection type of PROCESS.
1291 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1292 a socket connection. */)
1293 (Lisp_Object process
)
1295 return XPROCESS (process
)->type
;
1299 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1300 doc
: /* Return the connection type of PROCESS.
1301 The value is either the symbol `real', `network', or `serial'.
1302 PROCESS may be a process, a buffer, the name of a process or buffer, or
1303 nil, indicating the current buffer's process. */)
1304 (Lisp_Object process
)
1307 proc
= get_process (process
);
1308 return XPROCESS (proc
)->type
;
1311 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1313 doc
: /* Convert network ADDRESS from internal format to a string.
1314 A 4 or 5 element vector represents an IPv4 address (with port number).
1315 An 8 or 9 element vector represents an IPv6 address (with port number).
1316 If optional second argument OMIT-PORT is non-nil, don't include a port
1317 number in the string, even when present in ADDRESS.
1318 Return nil if format of ADDRESS is invalid. */)
1319 (Lisp_Object address
, Lisp_Object omit_port
)
1324 if (STRINGP (address
)) /* AF_LOCAL */
1327 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1329 register struct Lisp_Vector
*p
= XVECTOR (address
);
1330 ptrdiff_t size
= p
->header
.size
;
1331 Lisp_Object args
[10];
1335 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1337 format
= "%d.%d.%d.%d";
1342 format
= "%d.%d.%d.%d:%d";
1345 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1347 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1352 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1358 AUTO_STRING (format_obj
, format
);
1359 args
[0] = format_obj
;
1361 for (i
= 0; i
< nargs
; i
++)
1363 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1366 if (nargs
<= 5 /* IPv4 */
1367 && i
< 4 /* host, not port */
1368 && XINT (p
->contents
[i
]) > 255)
1371 args
[i
+ 1] = p
->contents
[i
];
1374 return Fformat (nargs
+ 1, args
);
1377 if (CONSP (address
))
1379 AUTO_STRING (format
, "<Family %d>");
1380 return CALLN (Fformat
, format
, Fcar (address
));
1386 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1387 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1390 return Fmapcar (Qcdr
, Vprocess_alist
);
1393 /* Starting asynchronous inferior processes. */
1395 static void start_process_unwind (Lisp_Object proc
);
1397 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1398 doc
: /* Start a program in a subprocess. Return the process object for it.
1400 This is similar to `start-process', but arguments are specified as
1401 keyword/argument pairs. The following arguments are defined:
1403 :name NAME -- NAME is name for process. It is modified if necessary
1406 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1407 with the process. Process output goes at end of that buffer, unless
1408 you specify an output stream or filter function to handle the output.
1409 BUFFER may be also nil, meaning that this process is not associated
1412 :command COMMAND -- COMMAND is a list starting with the program file
1413 name, followed by strings to give to the program as arguments.
1415 :coding CODING -- If CODING is a symbol, it specifies the coding
1416 system used for both reading and writing for this process. If CODING
1417 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1418 ENCODING is used for writing.
1420 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1421 the process is running. If BOOL is not given, query before exiting.
1423 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1424 In the stopped state, a process does not accept incoming data, but you
1425 can send outgoing data. The stopped state is cleared by
1426 `continue-process' and set by `stop-process'.
1428 :connection-type TYPE -- TYPE is control type of device used to
1429 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1430 to use a pty, or nil to use the default specified through
1431 `process-connection-type'.
1433 :filter FILTER -- Install FILTER as the process filter.
1435 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1437 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1438 to the standard error of subprocess. Specifying this implies
1439 `:connection-type' is set to `pipe'.
1441 usage: (make-process &rest ARGS) */)
1442 (ptrdiff_t nargs
, Lisp_Object
*args
)
1444 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1445 Lisp_Object xstderr
, stderrproc
;
1446 ptrdiff_t count
= SPECPDL_INDEX ();
1452 /* Save arguments for process-contact and clone-process. */
1453 contact
= Flist (nargs
, args
);
1455 buffer
= Fplist_get (contact
, QCbuffer
);
1457 buffer
= Fget_buffer_create (buffer
);
1459 /* Make sure that the child will be able to chdir to the current
1460 buffer's current directory, or its unhandled equivalent. We
1461 can't just have the child check for an error when it does the
1462 chdir, since it's in a vfork. */
1463 current_dir
= encode_current_directory ();
1465 name
= Fplist_get (contact
, QCname
);
1466 CHECK_STRING (name
);
1468 command
= Fplist_get (contact
, QCcommand
);
1469 if (CONSP (command
))
1470 program
= XCAR (command
);
1474 if (!NILP (program
))
1475 CHECK_STRING (program
);
1478 xstderr
= Fplist_get (contact
, QCstderr
);
1479 if (PROCESSP (xstderr
))
1481 if (!PIPECONN_P (xstderr
))
1482 error ("Process is not a pipe process");
1483 stderrproc
= xstderr
;
1485 else if (!NILP (xstderr
))
1487 CHECK_STRING (program
);
1488 stderrproc
= CALLN (Fmake_pipe_process
,
1490 concat2 (name
, build_string (" stderr")),
1492 Fget_buffer_create (xstderr
));
1495 proc
= make_process (name
);
1496 /* If an error occurs and we can't start the process, we want to
1497 remove it from the process list. This means that each error
1498 check in create_process doesn't need to call remove_process
1499 itself; it's all taken care of here. */
1500 record_unwind_protect (start_process_unwind
, proc
);
1502 pset_childp (XPROCESS (proc
), Qt
);
1503 pset_plist (XPROCESS (proc
), Qnil
);
1504 pset_type (XPROCESS (proc
), Qreal
);
1505 pset_buffer (XPROCESS (proc
), buffer
);
1506 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1507 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1508 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1510 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1511 XPROCESS (proc
)->kill_without_query
= 1;
1512 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1513 pset_command (XPROCESS (proc
), Qt
);
1515 tem
= Fplist_get (contact
, QCconnection_type
);
1517 XPROCESS (proc
)->pty_flag
= true;
1518 else if (EQ (tem
, Qpipe
))
1519 XPROCESS (proc
)->pty_flag
= false;
1520 else if (NILP (tem
))
1521 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1523 report_file_error ("Unknown connection type", tem
);
1525 if (!NILP (stderrproc
))
1527 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1529 XPROCESS (proc
)->pty_flag
= false;
1533 /* AKA GNUTLS_INITSTAGE(proc). */
1534 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1535 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1538 XPROCESS (proc
)->adaptive_read_buffering
1539 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1540 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1542 /* Make the process marker point into the process buffer (if any). */
1543 if (BUFFERP (buffer
))
1544 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1545 BUF_ZV (XBUFFER (buffer
)),
1546 BUF_ZV_BYTE (XBUFFER (buffer
)));
1549 /* Decide coding systems for communicating with the process. Here
1550 we don't setup the structure coding_system nor pay attention to
1551 unibyte mode. They are done in create_process. */
1553 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1554 Lisp_Object coding_systems
= Qt
;
1555 Lisp_Object val
, *args2
;
1557 tem
= Fplist_get (contact
, QCcoding
);
1565 val
= Vcoding_system_for_read
;
1568 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1570 SAFE_ALLOCA_LISP (args2
, nargs2
);
1572 args2
[i
++] = Qstart_process
;
1574 args2
[i
++] = buffer
;
1575 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1576 args2
[i
++] = XCAR (tem2
);
1577 if (!NILP (program
))
1578 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1579 if (CONSP (coding_systems
))
1580 val
= XCAR (coding_systems
);
1581 else if (CONSP (Vdefault_process_coding_system
))
1582 val
= XCAR (Vdefault_process_coding_system
);
1584 pset_decode_coding_system (XPROCESS (proc
), val
);
1593 val
= Vcoding_system_for_write
;
1596 if (EQ (coding_systems
, Qt
))
1598 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1600 SAFE_ALLOCA_LISP (args2
, nargs2
);
1602 args2
[i
++] = Qstart_process
;
1604 args2
[i
++] = buffer
;
1605 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1606 args2
[i
++] = XCAR (tem2
);
1607 if (!NILP (program
))
1608 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1610 if (CONSP (coding_systems
))
1611 val
= XCDR (coding_systems
);
1612 else if (CONSP (Vdefault_process_coding_system
))
1613 val
= XCDR (Vdefault_process_coding_system
);
1615 pset_encode_coding_system (XPROCESS (proc
), val
);
1616 /* Note: At this moment, the above coding system may leave
1617 text-conversion or eol-conversion unspecified. They will be
1618 decided after we read output from the process and decode it by
1619 some coding system, or just before we actually send a text to
1624 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1625 XPROCESS (proc
)->decoding_carryover
= 0;
1626 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1628 XPROCESS (proc
)->inherit_coding_system_flag
1629 = !(NILP (buffer
) || !inherit_process_coding_system
);
1631 if (!NILP (program
))
1633 Lisp_Object program_args
= XCDR (command
);
1635 /* If program file name is not absolute, search our path for it.
1636 Put the name we will really use in TEM. */
1637 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1638 && !(SCHARS (program
) > 1
1639 && IS_DEVICE_SEP (SREF (program
, 1))))
1642 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1643 make_number (X_OK
), false);
1645 report_file_error ("Searching for program", program
);
1646 tem
= Fexpand_file_name (tem
, Qnil
);
1650 if (!NILP (Ffile_directory_p (program
)))
1651 error ("Specified program for new process is a directory");
1655 /* Remove "/:" from TEM. */
1656 tem
= remove_slash_colon (tem
);
1658 Lisp_Object arg_encoding
= Qnil
;
1660 /* Encode the file name and put it in NEW_ARGV.
1661 That's where the child will use it to execute the program. */
1662 tem
= list1 (ENCODE_FILE (tem
));
1663 ptrdiff_t new_argc
= 1;
1665 /* Here we encode arguments by the coding system used for sending
1666 data to the process. We don't support using different coding
1667 systems for encoding arguments and for encoding data sent to the
1670 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1672 Lisp_Object arg
= XCAR (tem2
);
1674 if (STRING_MULTIBYTE (arg
))
1676 if (NILP (arg_encoding
))
1677 arg_encoding
= (complement_process_encoding_system
1678 (XPROCESS (proc
)->encode_coding_system
));
1679 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1681 tem
= Fcons (arg
, tem
);
1685 /* Now that everything is encoded we can collect the strings into
1688 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1689 new_argv
[new_argc
] = 0;
1691 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1693 new_argv
[i
] = SSDATA (XCAR (tem
));
1697 create_process (proc
, new_argv
, current_dir
);
1703 return unbind_to (count
, proc
);
1706 /* This function is the unwind_protect form for Fstart_process. If
1707 PROC doesn't have its pid set, then we know someone has signaled
1708 an error and the process wasn't started successfully, so we should
1709 remove it from the process list. */
1711 start_process_unwind (Lisp_Object proc
)
1713 if (!PROCESSP (proc
))
1716 /* Was PROC started successfully?
1717 -2 is used for a pty with no process, eg for gdb. */
1718 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1719 remove_process (proc
);
1722 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1725 close_process_fd (int *fd_addr
)
1735 /* Indexes of file descriptors in open_fds. */
1738 /* The pipe from Emacs to its subprocess. */
1740 WRITE_TO_SUBPROCESS
,
1742 /* The main pipe from the subprocess to Emacs. */
1743 READ_FROM_SUBPROCESS
,
1746 /* The pipe from the subprocess to Emacs that is closed when the
1747 subprocess execs. */
1748 READ_FROM_EXEC_MONITOR
,
1752 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1755 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1757 struct Lisp_Process
*p
= XPROCESS (process
);
1758 int inchannel
, outchannel
;
1761 int forkin
, forkout
, forkerr
= -1;
1763 char pty_name
[PTY_NAME_SIZE
];
1764 Lisp_Object lisp_pty_name
= Qnil
;
1767 inchannel
= outchannel
= -1;
1770 outchannel
= inchannel
= allocate_pty (pty_name
);
1774 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1775 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1776 /* On most USG systems it does not work to open the pty's tty here,
1777 then close it and reopen it in the child. */
1778 /* Don't let this terminal become our controlling terminal
1779 (in case we don't have one). */
1780 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1782 report_file_error ("Opening pty", Qnil
);
1783 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1785 forkin
= forkout
= -1;
1786 #endif /* not USG, or USG_SUBTTY_WORKS */
1788 lisp_pty_name
= build_string (pty_name
);
1792 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1793 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1794 report_file_error ("Creating pipe", Qnil
);
1795 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1796 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1797 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1798 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1800 if (!NILP (p
->stderrproc
))
1802 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1804 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1806 /* Close unnecessary file descriptors. */
1807 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1808 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1813 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1814 report_file_error ("Creating pipe", Qnil
);
1817 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1818 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1820 /* Record this as an active process, with its channels. */
1821 chan_process
[inchannel
] = process
;
1822 p
->infd
= inchannel
;
1823 p
->outfd
= outchannel
;
1825 /* Previously we recorded the tty descriptor used in the subprocess.
1826 It was only used for getting the foreground tty process, so now
1827 we just reopen the device (see emacs_get_tty_pgrp) as this is
1828 more portable (see USG_SUBTTY_WORKS above). */
1830 p
->pty_flag
= pty_flag
;
1831 pset_status (p
, Qrun
);
1833 if (!EQ (p
->command
, Qt
))
1835 FD_SET (inchannel
, &input_wait_mask
);
1836 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1839 if (inchannel
> max_process_desc
)
1840 max_process_desc
= inchannel
;
1842 /* This may signal an error. */
1843 setup_process_coding_systems (process
);
1846 block_child_signal (&oldset
);
1849 /* vfork, and prevent local vars from being clobbered by the vfork. */
1850 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1851 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1852 char **volatile new_argv_volatile
= new_argv
;
1853 int volatile forkin_volatile
= forkin
;
1854 int volatile forkout_volatile
= forkout
;
1855 int volatile forkerr_volatile
= forkerr
;
1856 struct Lisp_Process
*p_volatile
= p
;
1860 current_dir
= current_dir_volatile
;
1861 lisp_pty_name
= lisp_pty_name_volatile
;
1862 new_argv
= new_argv_volatile
;
1863 forkin
= forkin_volatile
;
1864 forkout
= forkout_volatile
;
1865 forkerr
= forkerr_volatile
;
1868 pty_flag
= p
->pty_flag
;
1871 #endif /* not WINDOWSNT */
1873 /* Make the pty be the controlling terminal of the process. */
1875 /* First, disconnect its current controlling terminal. */
1876 /* We tried doing setsid only if pty_flag, but it caused
1877 process_set_signal to fail on SGI when using a pipe. */
1879 /* Make the pty's terminal the controlling terminal. */
1880 if (pty_flag
&& forkin
>= 0)
1883 /* We ignore the return value
1884 because faith@cs.unc.edu says that is necessary on Linux. */
1885 ioctl (forkin
, TIOCSCTTY
, 0);
1888 #if defined (LDISC1)
1889 if (pty_flag
&& forkin
>= 0)
1892 tcgetattr (forkin
, &t
);
1894 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1895 emacs_perror ("create_process/tcsetattr LDISC1");
1898 #if defined (NTTYDISC) && defined (TIOCSETD)
1899 if (pty_flag
&& forkin
>= 0)
1901 /* Use new line discipline. */
1902 int ldisc
= NTTYDISC
;
1903 ioctl (forkin
, TIOCSETD
, &ldisc
);
1908 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1909 can do TIOCSPGRP only to the process's controlling tty. */
1912 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1913 I can't test it since I don't have 4.3. */
1914 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1917 ioctl (j
, TIOCNOTTY
, 0);
1921 #endif /* TIOCNOTTY */
1923 #if !defined (DONT_REOPEN_PTY)
1924 /*** There is a suggestion that this ought to be a
1925 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1926 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1927 that system does seem to need this code, even though
1928 both TIOCSCTTY is defined. */
1929 /* Now close the pty (if we had it open) and reopen it.
1930 This makes the pty the controlling terminal of the subprocess. */
1934 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1937 emacs_close (forkin
);
1938 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1942 emacs_perror (SSDATA (lisp_pty_name
));
1943 _exit (EXIT_CANCELED
);
1947 #endif /* not DONT_REOPEN_PTY */
1949 #ifdef SETUP_SLAVE_PTY
1954 #endif /* SETUP_SLAVE_PTY */
1955 #endif /* HAVE_PTYS */
1957 signal (SIGINT
, SIG_DFL
);
1958 signal (SIGQUIT
, SIG_DFL
);
1960 signal (SIGPROF
, SIG_DFL
);
1963 /* Emacs ignores SIGPIPE, but the child should not. */
1964 signal (SIGPIPE
, SIG_DFL
);
1966 /* Stop blocking SIGCHLD in the child. */
1967 unblock_child_signal (&oldset
);
1970 child_setup_tty (forkout
);
1975 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1976 #else /* not WINDOWSNT */
1977 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1978 #endif /* not WINDOWSNT */
1981 /* Back in the parent process. */
1983 vfork_errno
= errno
;
1988 /* Stop blocking in the parent. */
1989 unblock_child_signal (&oldset
);
1993 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1996 /* vfork succeeded. */
1998 /* Close the pipe ends that the child uses, or the child's pty. */
1999 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2000 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2003 register_child (pid
, inchannel
);
2004 #endif /* WINDOWSNT */
2006 pset_tty_name (p
, lisp_pty_name
);
2009 /* Wait for child_setup to complete in case that vfork is
2010 actually defined as fork. The descriptor
2011 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2012 of a pipe is closed at the child side either by close-on-exec
2013 on successful execve or the _exit call in child_setup. */
2017 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2018 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2019 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2022 if (!NILP (p
->stderrproc
))
2024 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2025 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2031 create_pty (Lisp_Object process
)
2033 struct Lisp_Process
*p
= XPROCESS (process
);
2034 char pty_name
[PTY_NAME_SIZE
];
2035 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2039 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2040 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2041 /* On most USG systems it does not work to open the pty's tty here,
2042 then close it and reopen it in the child. */
2043 /* Don't let this terminal become our controlling terminal
2044 (in case we don't have one). */
2045 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2047 report_file_error ("Opening pty", Qnil
);
2048 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2049 #if defined (DONT_REOPEN_PTY)
2050 /* In the case that vfork is defined as fork, the parent process
2051 (Emacs) may send some data before the child process completes
2052 tty options setup. So we setup tty before forking. */
2053 child_setup_tty (forkout
);
2054 #endif /* DONT_REOPEN_PTY */
2055 #endif /* not USG, or USG_SUBTTY_WORKS */
2057 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2059 /* Record this as an active process, with its channels.
2060 As a result, child_setup will close Emacs's side of the pipes. */
2061 chan_process
[pty_fd
] = process
;
2065 /* Previously we recorded the tty descriptor used in the subprocess.
2066 It was only used for getting the foreground tty process, so now
2067 we just reopen the device (see emacs_get_tty_pgrp) as this is
2068 more portable (see USG_SUBTTY_WORKS above). */
2071 pset_status (p
, Qrun
);
2072 setup_process_coding_systems (process
);
2074 FD_SET (pty_fd
, &input_wait_mask
);
2075 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2076 if (pty_fd
> max_process_desc
)
2077 max_process_desc
= pty_fd
;
2079 pset_tty_name (p
, build_string (pty_name
));
2085 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2087 doc
: /* Create and return a bidirectional pipe process.
2089 In Emacs, pipes are represented by process objects, so input and
2090 output work as for subprocesses, and `delete-process' closes a pipe.
2091 However, a pipe process has no process id, it cannot be signaled,
2092 and the status codes are different from normal processes.
2094 Arguments are specified as keyword/argument pairs. The following
2095 arguments are defined:
2097 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2099 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2100 with the process. Process output goes at the end of that buffer,
2101 unless you specify an output stream or filter function to handle the
2102 output. If BUFFER is not given, the value of NAME is used.
2104 :coding CODING -- If CODING is a symbol, it specifies the coding
2105 system used for both reading and writing for this process. If CODING
2106 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2107 ENCODING is used for writing.
2109 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2110 the process is running. If BOOL is not given, query before exiting.
2112 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2113 In the stopped state, a pipe process does not accept incoming data,
2114 but you can send outgoing data. The stopped state is cleared by
2115 `continue-process' and set by `stop-process'.
2117 :filter FILTER -- Install FILTER as the process filter.
2119 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2121 usage: (make-pipe-process &rest ARGS) */)
2122 (ptrdiff_t nargs
, Lisp_Object
*args
)
2124 Lisp_Object proc
, contact
;
2125 struct Lisp_Process
*p
;
2126 Lisp_Object name
, buffer
;
2128 ptrdiff_t specpdl_count
;
2129 int inchannel
, outchannel
;
2134 contact
= Flist (nargs
, args
);
2136 name
= Fplist_get (contact
, QCname
);
2137 CHECK_STRING (name
);
2138 proc
= make_process (name
);
2139 specpdl_count
= SPECPDL_INDEX ();
2140 record_unwind_protect (remove_process
, proc
);
2141 p
= XPROCESS (proc
);
2143 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2144 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2145 report_file_error ("Creating pipe", Qnil
);
2146 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2147 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2149 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2150 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2153 register_aux_fd (inchannel
);
2156 /* Record this as an active process, with its channels. */
2157 chan_process
[inchannel
] = proc
;
2158 p
->infd
= inchannel
;
2159 p
->outfd
= outchannel
;
2161 if (inchannel
> max_process_desc
)
2162 max_process_desc
= inchannel
;
2164 buffer
= Fplist_get (contact
, QCbuffer
);
2167 buffer
= Fget_buffer_create (buffer
);
2168 pset_buffer (p
, buffer
);
2170 pset_childp (p
, contact
);
2171 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2172 pset_type (p
, Qpipe
);
2173 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2174 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2176 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2177 p
->kill_without_query
= 1;
2178 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2179 pset_command (p
, Qt
);
2180 eassert (! p
->pty_flag
);
2182 if (!EQ (p
->command
, Qt
))
2184 FD_SET (inchannel
, &input_wait_mask
);
2185 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2187 p
->adaptive_read_buffering
2188 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2189 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2191 /* Make the process marker point into the process buffer (if any). */
2192 if (BUFFERP (buffer
))
2193 set_marker_both (p
->mark
, buffer
,
2194 BUF_ZV (XBUFFER (buffer
)),
2195 BUF_ZV_BYTE (XBUFFER (buffer
)));
2198 /* Setup coding systems for communicating with the network stream. */
2200 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2201 Lisp_Object coding_systems
= Qt
;
2204 tem
= Fplist_get (contact
, QCcoding
);
2212 else if (!NILP (Vcoding_system_for_read
))
2213 val
= Vcoding_system_for_read
;
2214 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2215 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2216 /* We dare not decode end-of-line format by setting VAL to
2217 Qraw_text, because the existing Emacs Lisp libraries
2218 assume that they receive bare code including a sequence of
2223 if (CONSP (coding_systems
))
2224 val
= XCAR (coding_systems
);
2225 else if (CONSP (Vdefault_process_coding_system
))
2226 val
= XCAR (Vdefault_process_coding_system
);
2230 pset_decode_coding_system (p
, val
);
2238 else if (!NILP (Vcoding_system_for_write
))
2239 val
= Vcoding_system_for_write
;
2240 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2244 if (CONSP (coding_systems
))
2245 val
= XCDR (coding_systems
);
2246 else if (CONSP (Vdefault_process_coding_system
))
2247 val
= XCDR (Vdefault_process_coding_system
);
2251 pset_encode_coding_system (p
, val
);
2253 /* This may signal an error. */
2254 setup_process_coding_systems (proc
);
2256 specpdl_ptr
= specpdl
+ specpdl_count
;
2262 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2263 The address family of sa is not included in the result. */
2266 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2268 Lisp_Object address
;
2271 struct Lisp_Vector
*p
;
2273 /* Workaround for a bug in getsockname on BSD: Names bound to
2274 sockets in the UNIX domain are inaccessible; getsockname returns
2275 a zero length name. */
2276 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2277 return empty_unibyte_string
;
2279 switch (sa
->sa_family
)
2283 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2284 len
= sizeof (sin
->sin_addr
) + 1;
2285 address
= Fmake_vector (make_number (len
), Qnil
);
2286 p
= XVECTOR (address
);
2287 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2288 cp
= (unsigned char *) &sin
->sin_addr
;
2294 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2295 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2296 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2297 address
= Fmake_vector (make_number (len
), Qnil
);
2298 p
= XVECTOR (address
);
2299 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2300 for (i
= 0; i
< len
; i
++)
2301 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2305 #ifdef HAVE_LOCAL_SOCKETS
2308 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2309 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2310 /* If the first byte is NUL, the name is a Linux abstract
2311 socket name, and the name can contain embedded NULs. If
2312 it's not, we have a NUL-terminated string. Be careful not
2313 to walk past the end of the object looking for the name
2314 terminator, however. */
2315 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2317 const char *terminator
2318 = memchr (sockun
->sun_path
, '\0', name_length
);
2321 name_length
= terminator
- (const char *) sockun
->sun_path
;
2324 return make_unibyte_string (sockun
->sun_path
, name_length
);
2328 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2329 address
= Fcons (make_number (sa
->sa_family
),
2330 Fmake_vector (make_number (len
), Qnil
));
2331 p
= XVECTOR (XCDR (address
));
2332 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2338 p
->contents
[i
++] = make_number (*cp
++);
2344 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2347 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2349 struct Lisp_Vector
*p
;
2351 if (VECTORP (address
))
2353 p
= XVECTOR (address
);
2354 if (p
->header
.size
== 5)
2357 return sizeof (struct sockaddr_in
);
2360 else if (p
->header
.size
== 9)
2362 *familyp
= AF_INET6
;
2363 return sizeof (struct sockaddr_in6
);
2367 #ifdef HAVE_LOCAL_SOCKETS
2368 else if (STRINGP (address
))
2370 *familyp
= AF_LOCAL
;
2371 return sizeof (struct sockaddr_un
);
2374 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2375 && VECTORP (XCDR (address
)))
2377 struct sockaddr
*sa
;
2378 p
= XVECTOR (XCDR (address
));
2379 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2381 *familyp
= XINT (XCAR (address
));
2382 return p
->header
.size
+ sizeof (sa
->sa_family
);
2387 /* Convert an address object (vector or string) to an internal sockaddr.
2389 The address format has been basically validated by
2390 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2391 it could have come from user data. So if FAMILY is not valid,
2392 we return after zeroing *SA. */
2395 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2397 register struct Lisp_Vector
*p
;
2398 register unsigned char *cp
= NULL
;
2402 memset (sa
, 0, len
);
2404 if (VECTORP (address
))
2406 p
= XVECTOR (address
);
2407 if (family
== AF_INET
)
2409 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2410 len
= sizeof (sin
->sin_addr
) + 1;
2411 hostport
= XINT (p
->contents
[--len
]);
2412 sin
->sin_port
= htons (hostport
);
2413 cp
= (unsigned char *)&sin
->sin_addr
;
2414 sa
->sa_family
= family
;
2417 else if (family
== AF_INET6
)
2419 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2420 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2421 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2422 hostport
= XINT (p
->contents
[--len
]);
2423 sin6
->sin6_port
= htons (hostport
);
2424 for (i
= 0; i
< len
; i
++)
2425 if (INTEGERP (p
->contents
[i
]))
2427 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2430 sa
->sa_family
= family
;
2437 else if (STRINGP (address
))
2439 #ifdef HAVE_LOCAL_SOCKETS
2440 if (family
== AF_LOCAL
)
2442 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2443 cp
= SDATA (address
);
2444 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2445 sockun
->sun_path
[i
] = *cp
++;
2446 sa
->sa_family
= family
;
2453 p
= XVECTOR (XCDR (address
));
2454 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2457 for (i
= 0; i
< len
; i
++)
2458 if (INTEGERP (p
->contents
[i
]))
2459 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2462 #ifdef DATAGRAM_SOCKETS
2463 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2465 doc
: /* Get the current datagram address associated with PROCESS.
2466 If PROCESS is a non-blocking network process that hasn't been fully
2467 set up yet, this function will block until socket setup has completed. */)
2468 (Lisp_Object process
)
2472 CHECK_PROCESS (process
);
2474 if (NETCONN_P (process
))
2475 wait_for_socket_fds (process
, "process-datagram-address");
2477 if (!DATAGRAM_CONN_P (process
))
2480 channel
= XPROCESS (process
)->infd
;
2481 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2482 datagram_address
[channel
].len
);
2485 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2487 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2488 Return nil upon error setting address, ADDRESS otherwise.
2490 If PROCESS is a non-blocking network process that hasn't been fully
2491 set up yet, this function will block until socket setup has completed. */)
2492 (Lisp_Object process
, Lisp_Object address
)
2498 CHECK_PROCESS (process
);
2500 if (NETCONN_P (process
))
2501 wait_for_socket_fds (process
, "set-process-datagram-address");
2503 if (!DATAGRAM_CONN_P (process
))
2506 channel
= XPROCESS (process
)->infd
;
2508 len
= get_lisp_to_sockaddr_size (address
, &family
);
2509 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2511 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2517 static const struct socket_options
{
2518 /* The name of this option. Should be lowercase version of option
2519 name without SO_ prefix. */
2521 /* Option level SOL_... */
2523 /* Option number SO_... */
2525 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2526 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2527 } socket_options
[] =
2529 #ifdef SO_BINDTODEVICE
2530 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2533 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2536 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2539 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2542 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2545 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2548 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2551 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2553 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2556 /* Set option OPT to value VAL on socket S.
2558 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2559 Signals an error if setting a known option fails.
2563 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2566 const struct socket_options
*sopt
;
2571 name
= SSDATA (SYMBOL_NAME (opt
));
2572 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2573 if (strcmp (name
, sopt
->name
) == 0)
2576 switch (sopt
->opttype
)
2581 optval
= NILP (val
) ? 0 : 1;
2582 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2583 &optval
, sizeof (optval
));
2590 if (TYPE_RANGED_INTEGERP (int, val
))
2591 optval
= XINT (val
);
2593 error ("Bad option value for %s", name
);
2594 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2595 &optval
, sizeof (optval
));
2599 #ifdef SO_BINDTODEVICE
2602 char devname
[IFNAMSIZ
+ 1];
2604 /* This is broken, at least in the Linux 2.4 kernel.
2605 To unbind, the arg must be a zero integer, not the empty string.
2606 This should work on all systems. KFS. 2003-09-23. */
2607 memset (devname
, 0, sizeof devname
);
2610 char *arg
= SSDATA (val
);
2611 int len
= min (strlen (arg
), IFNAMSIZ
);
2612 memcpy (devname
, arg
, len
);
2614 else if (!NILP (val
))
2615 error ("Bad option value for %s", name
);
2616 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2625 struct linger linger
;
2628 linger
.l_linger
= 0;
2629 if (TYPE_RANGED_INTEGERP (int, val
))
2630 linger
.l_linger
= XINT (val
);
2632 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2633 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2634 &linger
, sizeof (linger
));
2645 int setsockopt_errno
= errno
;
2646 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2650 return (1 << sopt
->optbit
);
2654 DEFUN ("set-network-process-option",
2655 Fset_network_process_option
, Sset_network_process_option
,
2657 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2658 See `make-network-process' for a list of options and values.
2659 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2660 OPTION is not a supported option, return nil instead; otherwise return t.
2662 If PROCESS is a non-blocking network process that hasn't been fully
2663 set up yet, this function will block until socket setup has completed. */)
2664 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2667 struct Lisp_Process
*p
;
2669 CHECK_PROCESS (process
);
2670 p
= XPROCESS (process
);
2671 if (!NETCONN1_P (p
))
2672 error ("Process is not a network process");
2674 wait_for_socket_fds (process
, "set-network-process-option");
2678 error ("Process is not running");
2680 if (set_socket_option (s
, option
, value
))
2682 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2686 if (NILP (no_error
))
2687 error ("Unknown or unsupported option");
2693 DEFUN ("serial-process-configure",
2694 Fserial_process_configure
,
2695 Sserial_process_configure
,
2697 doc
: /* Configure speed, bytesize, etc. of a serial process.
2699 Arguments are specified as keyword/argument pairs. Attributes that
2700 are not given are re-initialized from the process's current
2701 configuration (available via the function `process-contact') or set to
2702 reasonable default values. The following arguments are defined:
2708 -- Any of these arguments can be given to identify the process that is
2709 to be configured. If none of these arguments is given, the current
2710 buffer's process is used.
2712 :speed SPEED -- SPEED is the speed of the serial port in bits per
2713 second, also called baud rate. Any value can be given for SPEED, but
2714 most serial ports work only at a few defined values between 1200 and
2715 115200, with 9600 being the most common value. If SPEED is nil, the
2716 serial port is not configured any further, i.e., all other arguments
2717 are ignored. This may be useful for special serial ports such as
2718 Bluetooth-to-serial converters which can only be configured through AT
2719 commands. A value of nil for SPEED can be used only when passed
2720 through `make-serial-process' or `serial-term'.
2722 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2723 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2725 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2726 `odd' (use odd parity), or the symbol `even' (use even parity). If
2727 PARITY is not given, no parity is used.
2729 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2730 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2731 is not given or nil, 1 stopbit is used.
2733 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2734 flowcontrol to be used, which is either nil (don't use flowcontrol),
2735 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2736 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2737 flowcontrol is used.
2739 `serial-process-configure' is called by `make-serial-process' for the
2740 initial configuration of the serial port.
2744 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2746 \(serial-process-configure
2747 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2749 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2751 usage: (serial-process-configure &rest ARGS) */)
2752 (ptrdiff_t nargs
, Lisp_Object
*args
)
2754 struct Lisp_Process
*p
;
2755 Lisp_Object contact
= Qnil
;
2756 Lisp_Object proc
= Qnil
;
2758 contact
= Flist (nargs
, args
);
2760 proc
= Fplist_get (contact
, QCprocess
);
2762 proc
= Fplist_get (contact
, QCname
);
2764 proc
= Fplist_get (contact
, QCbuffer
);
2766 proc
= Fplist_get (contact
, QCport
);
2767 proc
= get_process (proc
);
2768 p
= XPROCESS (proc
);
2769 if (!EQ (p
->type
, Qserial
))
2770 error ("Not a serial process");
2772 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2775 serial_configure (p
, contact
);
2779 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2781 doc
: /* Create and return a serial port process.
2783 In Emacs, serial port connections are represented by process objects,
2784 so input and output work as for subprocesses, and `delete-process'
2785 closes a serial port connection. However, a serial process has no
2786 process id, it cannot be signaled, and the status codes are different
2787 from normal processes.
2789 `make-serial-process' creates a process and a buffer, on which you
2790 probably want to use `process-send-string'. Try \\[serial-term] for
2791 an interactive terminal. See below for examples.
2793 Arguments are specified as keyword/argument pairs. The following
2794 arguments are defined:
2796 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2797 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2798 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2799 the backslashes in strings).
2801 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2802 which this function calls.
2804 :name NAME -- NAME is the name of the process. If NAME is not given,
2805 the value of PORT is used.
2807 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2808 with the process. Process output goes at the end of that buffer,
2809 unless you specify an output stream or filter function to handle the
2810 output. If BUFFER is not given, the value of NAME is used.
2812 :coding CODING -- If CODING is a symbol, it specifies the coding
2813 system used for both reading and writing for this process. If CODING
2814 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2815 ENCODING is used for writing.
2817 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2818 the process is running. If BOOL is not given, query before exiting.
2820 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2821 In the stopped state, a serial process does not accept incoming data,
2822 but you can send outgoing data. The stopped state is cleared by
2823 `continue-process' and set by `stop-process'.
2825 :filter FILTER -- Install FILTER as the process filter.
2827 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2829 :plist PLIST -- Install PLIST as the initial plist of the process.
2835 -- This function calls `serial-process-configure' to handle these
2838 The original argument list, possibly modified by later configuration,
2839 is available via the function `process-contact'.
2843 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2845 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2847 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2849 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2851 usage: (make-serial-process &rest ARGS) */)
2852 (ptrdiff_t nargs
, Lisp_Object
*args
)
2855 Lisp_Object proc
, contact
, port
;
2856 struct Lisp_Process
*p
;
2857 Lisp_Object name
, buffer
;
2858 Lisp_Object tem
, val
;
2859 ptrdiff_t specpdl_count
;
2864 contact
= Flist (nargs
, args
);
2866 port
= Fplist_get (contact
, QCport
);
2868 error ("No port specified");
2869 CHECK_STRING (port
);
2871 if (NILP (Fplist_member (contact
, QCspeed
)))
2872 error (":speed not specified");
2873 if (!NILP (Fplist_get (contact
, QCspeed
)))
2874 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2876 name
= Fplist_get (contact
, QCname
);
2879 CHECK_STRING (name
);
2880 proc
= make_process (name
);
2881 specpdl_count
= SPECPDL_INDEX ();
2882 record_unwind_protect (remove_process
, proc
);
2883 p
= XPROCESS (proc
);
2885 fd
= serial_open (port
);
2886 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2889 if (fd
> max_process_desc
)
2890 max_process_desc
= fd
;
2891 chan_process
[fd
] = proc
;
2893 buffer
= Fplist_get (contact
, QCbuffer
);
2896 buffer
= Fget_buffer_create (buffer
);
2897 pset_buffer (p
, buffer
);
2899 pset_childp (p
, contact
);
2900 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2901 pset_type (p
, Qserial
);
2902 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2903 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2905 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2906 p
->kill_without_query
= 1;
2907 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2908 pset_command (p
, Qt
);
2909 eassert (! p
->pty_flag
);
2911 if (!EQ (p
->command
, Qt
))
2913 FD_SET (fd
, &input_wait_mask
);
2914 FD_SET (fd
, &non_keyboard_wait_mask
);
2917 if (BUFFERP (buffer
))
2919 set_marker_both (p
->mark
, buffer
,
2920 BUF_ZV (XBUFFER (buffer
)),
2921 BUF_ZV_BYTE (XBUFFER (buffer
)));
2924 tem
= Fplist_member (contact
, QCcoding
);
2925 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2931 val
= XCAR (XCDR (tem
));
2935 else if (!NILP (Vcoding_system_for_read
))
2936 val
= Vcoding_system_for_read
;
2937 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2938 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2940 pset_decode_coding_system (p
, val
);
2945 val
= XCAR (XCDR (tem
));
2949 else if (!NILP (Vcoding_system_for_write
))
2950 val
= Vcoding_system_for_write
;
2951 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2952 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2954 pset_encode_coding_system (p
, val
);
2956 setup_process_coding_systems (proc
);
2957 pset_decoding_buf (p
, empty_unibyte_string
);
2958 p
->decoding_carryover
= 0;
2959 pset_encoding_buf (p
, empty_unibyte_string
);
2960 p
->inherit_coding_system_flag
2961 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2963 Fserial_process_configure (nargs
, args
);
2965 specpdl_ptr
= specpdl
+ specpdl_count
;
2971 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2972 Lisp_Object service
, Lisp_Object name
)
2975 struct Lisp_Process
*p
= XPROCESS (proc
);
2976 Lisp_Object contact
= p
->childp
;
2977 Lisp_Object coding_systems
= Qt
;
2980 tem
= Fplist_member (contact
, QCcoding
);
2981 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2982 tem
= Qnil
; /* No error message (too late!). */
2984 /* Setup coding systems for communicating with the network stream. */
2985 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2989 val
= XCAR (XCDR (tem
));
2993 else if (!NILP (Vcoding_system_for_read
))
2994 val
= Vcoding_system_for_read
;
2995 else if ((!NILP (p
->buffer
)
2996 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2997 || (NILP (p
->buffer
)
2998 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2999 /* We dare not decode end-of-line format by setting VAL to
3000 Qraw_text, because the existing Emacs Lisp libraries
3001 assume that they receive bare code including a sequence of
3006 if (NILP (host
) || NILP (service
))
3007 coding_systems
= Qnil
;
3009 coding_systems
= CALLN (Ffind_operation_coding_system
,
3010 Qopen_network_stream
, name
, p
->buffer
,
3012 if (CONSP (coding_systems
))
3013 val
= XCAR (coding_systems
);
3014 else if (CONSP (Vdefault_process_coding_system
))
3015 val
= XCAR (Vdefault_process_coding_system
);
3019 pset_decode_coding_system (p
, val
);
3023 val
= XCAR (XCDR (tem
));
3027 else if (!NILP (Vcoding_system_for_write
))
3028 val
= Vcoding_system_for_write
;
3029 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3033 if (EQ (coding_systems
, Qt
))
3035 if (NILP (host
) || NILP (service
))
3036 coding_systems
= Qnil
;
3038 coding_systems
= CALLN (Ffind_operation_coding_system
,
3039 Qopen_network_stream
, name
, p
->buffer
,
3042 if (CONSP (coding_systems
))
3043 val
= XCDR (coding_systems
);
3044 else if (CONSP (Vdefault_process_coding_system
))
3045 val
= XCDR (Vdefault_process_coding_system
);
3049 pset_encode_coding_system (p
, val
);
3051 pset_decoding_buf (p
, empty_unibyte_string
);
3052 p
->decoding_carryover
= 0;
3053 pset_encoding_buf (p
, empty_unibyte_string
);
3055 p
->inherit_coding_system_flag
3056 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3061 finish_after_tls_connection (Lisp_Object proc
)
3063 struct Lisp_Process
*p
= XPROCESS (proc
);
3064 Lisp_Object contact
= p
->childp
;
3065 Lisp_Object result
= Qt
;
3067 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3068 result
= call3 (Qnsm_verify_connection
,
3070 Fplist_get (contact
, QChost
),
3071 Fplist_get (contact
, QCservice
));
3075 pset_status (p
, list2 (Qfailed
,
3076 build_string ("The Network Security Manager stopped the connections")));
3077 deactivate_process (proc
);
3081 /* If we cleared the connection wait mask before we did
3082 the TLS setup, then we have to say that the process
3083 is finally "open" here. */
3084 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3086 pset_status (p
, Qrun
);
3087 /* Execute the sentinel here. If we had relied on
3088 status_notify to do it later, it will read input
3089 from the process before calling the sentinel. */
3090 exec_sentinel (proc
, build_string ("open\n"));
3097 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
,
3098 Lisp_Object use_external_socket_p
)
3100 ptrdiff_t count
= SPECPDL_INDEX ();
3102 int s
= -1, outch
, inch
;
3104 Lisp_Object ip_address
;
3106 struct sockaddr
*sa
= NULL
;
3109 struct Lisp_Process
*p
= XPROCESS (proc
);
3110 Lisp_Object contact
= p
->childp
;
3112 int socket_to_use
= -1;
3114 if (!NILP (use_external_socket_p
))
3116 socket_to_use
= external_sock_fd
;
3118 /* Ensure we don't consume the external socket twice. */
3119 external_sock_fd
= -1;
3122 /* Do this in case we never enter the while-loop below. */
3123 count1
= SPECPDL_INDEX ();
3126 while (!NILP (ip_addresses
))
3128 ip_address
= XCAR (ip_addresses
);
3129 ip_addresses
= XCDR (ip_addresses
);
3135 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3138 sa
= xmalloc (addrlen
);
3139 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3144 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3152 #ifdef DATAGRAM_SOCKETS
3153 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3155 #endif /* DATAGRAM_SOCKETS */
3157 if (p
->is_non_blocking_client
)
3159 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3169 /* Make us close S if quit. */
3170 record_unwind_protect_int (close_file_unwind
, s
);
3172 /* Parse network options in the arg list. We simply ignore anything
3173 which isn't a known option (including other keywords). An error
3174 is signaled if setting a known option fails. */
3176 Lisp_Object params
= contact
, key
, val
;
3178 while (!NILP (params
))
3180 key
= XCAR (params
);
3181 params
= XCDR (params
);
3182 val
= XCAR (params
);
3183 params
= XCDR (params
);
3184 optbits
|= set_socket_option (s
, key
, val
);
3190 /* Configure as a server socket. */
3192 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3193 explicit :reuseaddr key to override this. */
3194 #ifdef HAVE_LOCAL_SOCKETS
3195 if (family
!= AF_LOCAL
)
3197 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3200 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3201 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3204 /* If passed a socket descriptor, it should be already bound. */
3205 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3206 report_file_error ("Cannot bind server socket", Qnil
);
3208 #ifdef HAVE_GETSOCKNAME
3211 struct sockaddr_in sa1
;
3212 socklen_t len1
= sizeof (sa1
);
3213 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3215 Lisp_Object service
;
3216 service
= make_number (ntohs (sa1
.sin_port
));
3217 contact
= Fplist_put (contact
, QCservice
, service
);
3218 /* Save the port number so that we can stash it in
3219 the process object later. */
3220 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3225 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3226 report_file_error ("Cannot listen on server socket", Qnil
);
3234 ret
= connect (s
, sa
, addrlen
);
3237 if (ret
== 0 || xerrno
== EISCONN
)
3239 /* The unwind-protect will be discarded afterwards.
3240 Likewise for immediate_quit. */
3244 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3248 if (xerrno
== EINTR
)
3250 /* Unlike most other syscalls connect() cannot be called
3251 again. (That would return EALREADY.) The proper way to
3252 wait for completion is pselect(). */
3260 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3266 report_file_error ("Failed select", Qnil
);
3270 len
= sizeof xerrno
;
3271 eassert (FD_ISSET (s
, &fdset
));
3272 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3273 report_file_error ("Failed getsockopt", Qnil
);
3275 report_file_errno ("Failed connect", Qnil
, xerrno
);
3278 #endif /* !WINDOWSNT */
3282 /* Discard the unwind protect closing S. */
3283 specpdl_ptr
= specpdl
+ count1
;
3288 if (xerrno
== EINTR
)
3295 #ifdef DATAGRAM_SOCKETS
3296 if (p
->socktype
== SOCK_DGRAM
)
3298 if (datagram_address
[s
].sa
)
3301 datagram_address
[s
].sa
= xmalloc (addrlen
);
3302 datagram_address
[s
].len
= addrlen
;
3306 memset (datagram_address
[s
].sa
, 0, addrlen
);
3307 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3310 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3311 if (rlen
!= 0 && rfamily
== family
3313 conv_lisp_to_sockaddr (rfamily
, remote
,
3314 datagram_address
[s
].sa
, rlen
);
3318 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3322 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3323 conv_sockaddr_to_lisp (sa
, addrlen
));
3324 #ifdef HAVE_GETSOCKNAME
3327 struct sockaddr_in sa1
;
3328 socklen_t len1
= sizeof (sa1
);
3329 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3330 contact
= Fplist_put (contact
, QClocal
,
3331 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3340 /* If non-blocking got this far - and failed - assume non-blocking is
3341 not supported after all. This is probably a wrong assumption, but
3342 the normal blocking calls to open-network-stream handles this error
3344 if (p
->is_non_blocking_client
)
3347 report_file_errno ((p
->is_server
3348 ? "make server process failed"
3349 : "make client process failed"),
3356 chan_process
[inch
] = proc
;
3358 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3360 p
= XPROCESS (proc
);
3361 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3365 /* Discard the unwind protect for closing S, if any. */
3366 specpdl_ptr
= specpdl
+ count1
;
3368 /* Unwind bind_polling_period and request_sigio. */
3369 unbind_to (count
, Qnil
);
3371 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3372 pset_status (p
, Qlisten
);
3374 /* Make the process marker point into the process buffer (if any). */
3375 if (BUFFERP (p
->buffer
))
3376 set_marker_both (p
->mark
, p
->buffer
,
3377 BUF_ZV (XBUFFER (p
->buffer
)),
3378 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3380 if (p
->is_non_blocking_client
)
3382 /* We may get here if connect did succeed immediately. However,
3383 in that case, we still need to signal this like a non-blocking
3385 pset_status (p
, Qconnect
);
3386 if (!FD_ISSET (inch
, &connect_wait_mask
))
3388 FD_SET (inch
, &connect_wait_mask
);
3389 FD_SET (inch
, &write_mask
);
3390 num_pending_connects
++;
3394 /* A server may have a client filter setting of Qt, but it must
3395 still listen for incoming connects unless it is stopped. */
3396 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3397 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3399 FD_SET (inch
, &input_wait_mask
);
3400 FD_SET (inch
, &non_keyboard_wait_mask
);
3403 if (inch
> max_process_desc
)
3404 max_process_desc
= inch
;
3406 /* Set up the masks based on the process filter. */
3407 set_process_filter_masks (p
);
3409 setup_process_coding_systems (proc
);
3412 /* Continue the asynchronous connection. */
3413 if (!NILP (p
->gnutls_boot_parameters
))
3415 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3417 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3418 p
->gnutls_boot_parameters
= Qnil
;
3420 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3421 /* Run sentinels, etc. */
3422 finish_after_tls_connection (proc
);
3423 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3425 deactivate_process (proc
);
3427 pset_status (p
, list2 (Qfailed
,
3428 build_string ("TLS negotiation failed")));
3430 pset_status (p
, list2 (Qfailed
, boot
));
3437 /* Create a network stream/datagram client/server process. Treated
3438 exactly like a normal process when reading and writing. Primary
3439 differences are in status display and process deletion. A network
3440 connection has no PID; you cannot signal it. All you can do is
3441 stop/continue it and deactivate/close it via delete-process. */
3443 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3445 doc
: /* Create and return a network server or client process.
3447 In Emacs, network connections are represented by process objects, so
3448 input and output work as for subprocesses and `delete-process' closes
3449 a network connection. However, a network process has no process id,
3450 it cannot be signaled, and the status codes are different from normal
3453 Arguments are specified as keyword/argument pairs. The following
3454 arguments are defined:
3456 :name NAME -- NAME is name for process. It is modified if necessary
3459 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3460 with the process. Process output goes at end of that buffer, unless
3461 you specify an output stream or filter function to handle the output.
3462 BUFFER may be also nil, meaning that this process is not associated
3465 :host HOST -- HOST is name of the host to connect to, or its IP
3466 address. The symbol `local' specifies the local host. If specified
3467 for a server process, it must be a valid name or address for the local
3468 host, and only clients connecting to that address will be accepted.
3470 :service SERVICE -- SERVICE is name of the service desired, or an
3471 integer specifying a port number to connect to. If SERVICE is t,
3472 a random port number is selected for the server. A port number can
3473 be specified as an integer string, e.g., "80", as well as an integer.
3475 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3476 stream type connection, `datagram' creates a datagram type connection,
3477 `seqpacket' creates a reliable datagram connection.
3479 :family FAMILY -- FAMILY is the address (and protocol) family for the
3480 service specified by HOST and SERVICE. The default (nil) is to use
3481 whatever address family (IPv4 or IPv6) that is defined for the host
3482 and port number specified by HOST and SERVICE. Other address families
3484 local -- for a local (i.e. UNIX) address specified by SERVICE.
3485 ipv4 -- use IPv4 address family only.
3486 ipv6 -- use IPv6 address family only.
3488 :local ADDRESS -- ADDRESS is the local address used for the connection.
3489 This parameter is ignored when opening a client process. When specified
3490 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3492 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3493 connection. This parameter is ignored when opening a stream server
3494 process. For a datagram server process, it specifies the initial
3495 setting of the remote datagram address. When specified for a client
3496 process, the FAMILY, HOST, and SERVICE args are ignored.
3498 The format of ADDRESS depends on the address family:
3499 - An IPv4 address is represented as an vector of integers [A B C D P]
3500 corresponding to numeric IP address A.B.C.D and port number P.
3501 - A local address is represented as a string with the address in the
3502 local address space.
3503 - An "unsupported family" address is represented by a cons (F . AV)
3504 where F is the family number and AV is a vector containing the socket
3505 address data with one element per address data byte. Do not rely on
3506 this format in portable code, as it may depend on implementation
3507 defined constants, data sizes, and data structure alignment.
3509 :coding CODING -- If CODING is a symbol, it specifies the coding
3510 system used for both reading and writing for this process. If CODING
3511 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3512 ENCODING is used for writing.
3514 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3515 process, return without waiting for the connection to complete;
3516 instead, the sentinel function will be called with second arg matching
3517 "open" (if successful) or "failed" when the connect completes.
3518 Default is to use a blocking connect (i.e. wait) for stream type
3521 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3522 running when Emacs is exited.
3524 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3525 In the stopped state, a server process does not accept new
3526 connections, and a client process does not handle incoming traffic.
3527 The stopped state is cleared by `continue-process' and set by
3530 :filter FILTER -- Install FILTER as the process filter.
3532 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3533 process filter are multibyte, otherwise they are unibyte.
3534 If this keyword is not specified, the strings are multibyte if
3535 the default value of `enable-multibyte-characters' is non-nil.
3537 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3539 :log LOG -- Install LOG as the server process log function. This
3540 function is called when the server accepts a network connection from a
3541 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3542 is the server process, CLIENT is the new process for the connection,
3543 and MESSAGE is a string.
3545 :plist PLIST -- Install PLIST as the new process's initial plist.
3547 :tls-parameters LIST -- is a list that should be supplied if you're
3548 opening a TLS connection. The first element is the TLS type (either
3549 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3550 be a keyword list accepted by gnutls-boot (as returned by
3551 `gnutls-boot-parameters').
3553 :server QLEN -- if QLEN is non-nil, create a server process for the
3554 specified FAMILY, SERVICE, and connection type (stream or datagram).
3555 If QLEN is an integer, it is used as the max. length of the server's
3556 pending connection queue (also known as the backlog); the default
3557 queue length is 5. Default is to create a client process.
3559 The following network options can be specified for this connection:
3561 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3562 :dontroute BOOL -- Only send to directly connected hosts.
3563 :keepalive BOOL -- Send keep-alive messages on network stream.
3564 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3565 :oobinline BOOL -- Place out-of-band data in receive data stream.
3566 :priority INT -- Set protocol defined priority for sent packets.
3567 :reuseaddr BOOL -- Allow reusing a recently used local address
3568 (this is allowed by default for a server process).
3569 :bindtodevice NAME -- bind to interface NAME. Using this may require
3570 special privileges on some systems.
3571 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3572 been passed to Emacs. If Emacs wasn't
3573 passed a socket, this option is silently
3577 Consult the relevant system programmer's manual pages for more
3578 information on using these options.
3581 A server process will listen for and accept connections from clients.
3582 When a client connection is accepted, a new network process is created
3583 for the connection with the following parameters:
3585 - The client's process name is constructed by concatenating the server
3586 process's NAME and a client identification string.
3587 - If the FILTER argument is non-nil, the client process will not get a
3588 separate process buffer; otherwise, the client's process buffer is a newly
3589 created buffer named after the server process's BUFFER name or process
3590 NAME concatenated with the client identification string.
3591 - The connection type and the process filter and sentinel parameters are
3592 inherited from the server process's TYPE, FILTER and SENTINEL.
3593 - The client process's contact info is set according to the client's
3594 addressing information (typically an IP address and a port number).
3595 - The client process's plist is initialized from the server's plist.
3597 Notice that the FILTER and SENTINEL args are never used directly by
3598 the server process. Also, the BUFFER argument is not used directly by
3599 the server process, but via the optional :log function, accepted (and
3600 failed) connections may be logged in the server process's buffer.
3602 The original argument list, modified with the actual connection
3603 information, is available via the `process-contact' function.
3605 usage: (make-network-process &rest ARGS) */)
3606 (ptrdiff_t nargs
, Lisp_Object
*args
)
3609 Lisp_Object contact
;
3610 struct Lisp_Process
*p
;
3611 const char *portstring
;
3612 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3613 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3614 #ifdef HAVE_LOCAL_SOCKETS
3615 struct sockaddr_un address_un
;
3619 Lisp_Object name
, buffer
, host
, service
, address
;
3620 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3621 Lisp_Object ip_addresses
= Qnil
;
3624 int ai_protocol
= 0;
3625 #ifdef HAVE_GETADDRINFO_A
3626 struct gaicb
*dns_request
= NULL
;
3628 ptrdiff_t count
= SPECPDL_INDEX ();
3633 /* Save arguments for process-contact and clone-process. */
3634 contact
= Flist (nargs
, args
);
3637 /* Ensure socket support is loaded if available. */
3638 init_winsock (TRUE
);
3641 /* :type TYPE (nil: stream, datagram */
3642 tem
= Fplist_get (contact
, QCtype
);
3644 socktype
= SOCK_STREAM
;
3645 #ifdef DATAGRAM_SOCKETS
3646 else if (EQ (tem
, Qdatagram
))
3647 socktype
= SOCK_DGRAM
;
3649 #ifdef HAVE_SEQPACKET
3650 else if (EQ (tem
, Qseqpacket
))
3651 socktype
= SOCK_SEQPACKET
;
3654 error ("Unsupported connection type");
3656 name
= Fplist_get (contact
, QCname
);
3657 buffer
= Fplist_get (contact
, QCbuffer
);
3658 filter
= Fplist_get (contact
, QCfilter
);
3659 sentinel
= Fplist_get (contact
, QCsentinel
);
3660 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3662 CHECK_STRING (name
);
3664 /* :local ADDRESS or :remote ADDRESS */
3665 tem
= Fplist_get (contact
, QCserver
);
3667 address
= Fplist_get (contact
, QCremote
);
3669 address
= Fplist_get (contact
, QClocal
);
3670 if (!NILP (address
))
3672 host
= service
= Qnil
;
3674 if (!get_lisp_to_sockaddr_size (address
, &family
))
3675 error ("Malformed :address");
3677 ip_addresses
= list1 (address
);
3681 /* :family FAMILY -- nil (for Inet), local, or integer. */
3682 tem
= Fplist_get (contact
, QCfamily
);
3691 #ifdef HAVE_LOCAL_SOCKETS
3692 else if (EQ (tem
, Qlocal
))
3696 else if (EQ (tem
, Qipv6
))
3699 else if (EQ (tem
, Qipv4
))
3701 else if (TYPE_RANGED_INTEGERP (int, tem
))
3702 family
= XINT (tem
);
3704 error ("Unknown address family");
3706 /* :service SERVICE -- string, integer (port number), or t (random port). */
3707 service
= Fplist_get (contact
, QCservice
);
3709 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3710 host
= Fplist_get (contact
, QChost
);
3713 /* The "connection" function gets it bind info from the address we're
3714 given, so use this dummy address if nothing is specified. */
3715 #ifdef HAVE_LOCAL_SOCKETS
3716 if (family
!= AF_LOCAL
)
3718 host
= build_string ("127.0.0.1");
3722 if (EQ (host
, Qlocal
))
3723 /* Depending on setup, "localhost" may map to different IPv4 and/or
3724 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3725 host
= build_string ("127.0.0.1");
3726 CHECK_STRING (host
);
3729 #ifdef HAVE_LOCAL_SOCKETS
3730 if (family
== AF_LOCAL
)
3734 message (":family local ignores the :host property");
3735 contact
= Fplist_put (contact
, QChost
, Qnil
);
3738 CHECK_STRING (service
);
3739 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3740 error ("Service name too long");
3741 ip_addresses
= list1 (service
);
3746 /* Slow down polling to every ten seconds.
3747 Some kernels have a bug which causes retrying connect to fail
3748 after a connect. Polling can interfere with gethostbyname too. */
3749 #ifdef POLL_FOR_INPUT
3750 if (socktype
!= SOCK_DGRAM
)
3752 record_unwind_protect_void (run_all_atimers
);
3753 bind_polling_period (10);
3759 /* SERVICE can either be a string or int.
3760 Convert to a C string for later use by getaddrinfo. */
3761 if (EQ (service
, Qt
))
3766 else if (INTEGERP (service
))
3768 portstring
= portbuf
;
3769 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3773 CHECK_STRING (service
);
3774 portstring
= SSDATA (service
);
3775 portstringlen
= SBYTES (service
);
3779 #ifdef HAVE_GETADDRINFO_A
3780 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3782 ptrdiff_t hostlen
= SBYTES (host
);
3786 struct addrinfo hints
;
3787 char str
[FLEXIBLE_ARRAY_MEMBER
];
3788 } *req
= xmalloc (offsetof (struct req
, str
)
3789 + hostlen
+ 1 + portstringlen
+ 1);
3790 dns_request
= &req
->gaicb
;
3791 dns_request
->ar_name
= req
->str
;
3792 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3793 dns_request
->ar_request
= &req
->hints
;
3794 dns_request
->ar_result
= NULL
;
3795 memset (&req
->hints
, 0, sizeof req
->hints
);
3796 req
->hints
.ai_family
= family
;
3797 req
->hints
.ai_socktype
= socktype
;
3798 strcpy (req
->str
, SSDATA (host
));
3799 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3801 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3803 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3807 #endif /* HAVE_GETADDRINFO_A */
3809 /* If we have a host, use getaddrinfo to resolve both host and service.
3810 Otherwise, use getservbyname to lookup the service. */
3814 struct addrinfo
*res
, *lres
;
3820 struct addrinfo hints
;
3821 memset (&hints
, 0, sizeof hints
);
3822 hints
.ai_family
= family
;
3823 hints
.ai_socktype
= socktype
;
3825 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3827 #ifdef HAVE_GAI_STRERROR
3829 synchronize_system_messages_locale ();
3830 char const *str
= gai_strerror (ret
);
3831 if (! NILP (Vlocale_coding_system
))
3832 str
= SSDATA (code_convert_string_norecord
3833 (build_string (str
), Vlocale_coding_system
, 0));
3834 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3837 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3841 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3843 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3844 (lres
->ai_addr
, lres
->ai_addrlen
),
3846 ai_protocol
= lres
->ai_protocol
;
3849 ip_addresses
= Fnreverse (ip_addresses
);
3856 /* No hostname has been specified (e.g., a local server process). */
3858 if (EQ (service
, Qt
))
3860 else if (INTEGERP (service
))
3861 port
= XINT (service
);
3864 CHECK_STRING (service
);
3867 if (SBYTES (service
) != 0)
3869 /* Allow the service to be a string containing the port number,
3870 because that's allowed if you have getaddrbyname. */
3872 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3873 if (service_end
== SSDATA (service
) + SBYTES (service
))
3877 struct servent
*svc_info
3878 = getservbyname (SSDATA (service
),
3879 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3881 port
= ntohs (svc_info
->s_port
);
3886 if (! (0 <= port
&& port
< 1 << 16))
3888 AUTO_STRING (unknown_service
, "Unknown service: %s");
3889 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3895 buffer
= Fget_buffer_create (buffer
);
3896 proc
= make_process (name
);
3897 p
= XPROCESS (proc
);
3898 pset_childp (p
, contact
);
3899 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3900 pset_type (p
, Qnetwork
);
3902 pset_buffer (p
, buffer
);
3903 pset_sentinel (p
, sentinel
);
3904 pset_filter (p
, filter
);
3905 pset_log (p
, Fplist_get (contact
, QClog
));
3906 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3907 p
->kill_without_query
= 1;
3908 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3909 pset_command (p
, Qt
);
3912 p
->is_non_blocking_client
= false;
3913 p
->is_server
= false;
3915 p
->socktype
= socktype
;
3916 p
->ai_protocol
= ai_protocol
;
3917 #ifdef HAVE_GETADDRINFO_A
3918 p
->dns_request
= NULL
;
3921 tem
= Fplist_get (contact
, QCtls_parameters
);
3923 p
->gnutls_boot_parameters
= tem
;
3926 set_network_socket_coding_system (proc
, host
, service
, name
);
3928 unbind_to (count
, Qnil
);
3931 tem
= Fplist_get (contact
, QCserver
);
3934 /* Don't support network sockets when non-blocking mode is
3935 not available, since a blocked Emacs is not useful. */
3936 p
->is_server
= true;
3937 if (TYPE_RANGED_INTEGERP (int, tem
))
3938 p
->backlog
= XINT (tem
);
3942 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3943 && !NILP (Fplist_get (contact
, QCnowait
)))
3944 p
->is_non_blocking_client
= true;
3946 #ifdef HAVE_GETADDRINFO_A
3947 /* With async address resolution, the list of addresses is empty, so
3948 postpone connecting to the server. */
3949 if (!p
->is_server
&& NILP (ip_addresses
))
3951 p
->dns_request
= dns_request
;
3952 p
->status
= Qconnect
;
3957 connect_network_socket (proc
, ip_addresses
, use_external_socket_p
);
3962 #ifdef HAVE_NET_IF_H
3966 network_interface_list (void)
3968 struct ifconf ifconf
;
3969 struct ifreq
*ifreq
;
3971 ptrdiff_t buf_size
= 512;
3976 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3979 count
= SPECPDL_INDEX ();
3980 record_unwind_protect_int (close_file_unwind
, s
);
3984 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3985 ifconf
.ifc_buf
= buf
;
3986 ifconf
.ifc_len
= buf_size
;
3987 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3994 while (ifconf
.ifc_len
== buf_size
);
3996 res
= unbind_to (count
, Qnil
);
3997 ifreq
= ifconf
.ifc_req
;
3998 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4000 struct ifreq
*ifq
= ifreq
;
4001 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4002 #define SIZEOF_IFREQ(sif) \
4003 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4004 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4006 int len
= SIZEOF_IFREQ (ifq
);
4008 int len
= sizeof (*ifreq
);
4010 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4011 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4013 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4016 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4017 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4018 res
= Fcons (Fcons (build_string (namebuf
),
4019 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4020 sizeof (struct sockaddr
))),
4027 #endif /* SIOCGIFCONF */
4029 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4033 const char *flag_sym
;
4036 static const struct ifflag_def ifflag_table
[] = {
4040 #ifdef IFF_BROADCAST
4041 { IFF_BROADCAST
, "broadcast" },
4044 { IFF_DEBUG
, "debug" },
4047 { IFF_LOOPBACK
, "loopback" },
4049 #ifdef IFF_POINTOPOINT
4050 { IFF_POINTOPOINT
, "pointopoint" },
4053 { IFF_RUNNING
, "running" },
4056 { IFF_NOARP
, "noarp" },
4059 { IFF_PROMISC
, "promisc" },
4061 #ifdef IFF_NOTRAILERS
4062 #ifdef NS_IMPL_COCOA
4063 /* Really means smart, notrailers is obsolete. */
4064 { IFF_NOTRAILERS
, "smart" },
4066 { IFF_NOTRAILERS
, "notrailers" },
4070 { IFF_ALLMULTI
, "allmulti" },
4073 { IFF_MASTER
, "master" },
4076 { IFF_SLAVE
, "slave" },
4078 #ifdef IFF_MULTICAST
4079 { IFF_MULTICAST
, "multicast" },
4082 { IFF_PORTSEL
, "portsel" },
4084 #ifdef IFF_AUTOMEDIA
4085 { IFF_AUTOMEDIA
, "automedia" },
4088 { IFF_DYNAMIC
, "dynamic" },
4091 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4094 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4097 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4100 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4103 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4109 network_interface_info (Lisp_Object ifname
)
4112 Lisp_Object res
= Qnil
;
4117 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4118 && defined HAVE_GETIFADDRS && defined LLADDR)
4119 struct ifaddrs
*ifap
;
4122 CHECK_STRING (ifname
);
4124 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4125 error ("interface name too long");
4126 lispstpcpy (rq
.ifr_name
, ifname
);
4128 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4131 count
= SPECPDL_INDEX ();
4132 record_unwind_protect_int (close_file_unwind
, s
);
4135 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4136 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4138 int flags
= rq
.ifr_flags
;
4139 const struct ifflag_def
*fp
;
4142 /* If flags is smaller than int (i.e. short) it may have the high bit set
4143 due to IFF_MULTICAST. In that case, sign extending it into
4145 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4146 flags
= (unsigned short) rq
.ifr_flags
;
4149 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4151 if (flags
& fp
->flag_bit
)
4153 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4154 flags
-= fp
->flag_bit
;
4157 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4161 elt
= Fcons (make_number (fnum
), elt
);
4166 res
= Fcons (elt
, res
);
4169 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4170 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4172 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4173 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4177 for (n
= 0; n
< 6; n
++)
4178 p
->contents
[n
] = make_number (((unsigned char *)
4179 &rq
.ifr_hwaddr
.sa_data
[0])
4181 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4183 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4184 if (getifaddrs (&ifap
) != -1)
4186 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4187 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4190 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4192 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4193 unsigned char linkaddr
[6];
4196 if (it
->ifa_addr
->sa_family
!= AF_LINK
4197 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4198 || sdl
->sdl_alen
!= 6)
4201 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4202 for (n
= 0; n
< 6; n
++)
4203 p
->contents
[n
] = make_number (linkaddr
[n
]);
4205 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4209 #ifdef HAVE_FREEIFADDRS
4213 #endif /* HAVE_GETIFADDRS && LLADDR */
4215 res
= Fcons (elt
, res
);
4218 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4219 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4222 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4223 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4225 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4229 res
= Fcons (elt
, res
);
4232 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4233 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4236 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4239 res
= Fcons (elt
, res
);
4242 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4243 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4246 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4249 res
= Fcons (elt
, res
);
4251 return unbind_to (count
, any
? res
: Qnil
);
4253 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4254 #endif /* defined (HAVE_NET_IF_H) */
4256 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4257 Snetwork_interface_list
, 0, 0, 0,
4258 doc
: /* Return an alist of all network interfaces and their network address.
4259 Each element is a cons, the car of which is a string containing the
4260 interface name, and the cdr is the network address in internal
4261 format; see the description of ADDRESS in `make-network-process'.
4263 If the information is not available, return nil. */)
4266 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4267 return network_interface_list ();
4273 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4274 Snetwork_interface_info
, 1, 1, 0,
4275 doc
: /* Return information about network interface named IFNAME.
4276 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4277 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4278 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4279 FLAGS is the current flags of the interface.
4281 Data that is unavailable is returned as nil. */)
4282 (Lisp_Object ifname
)
4284 #if ((defined HAVE_NET_IF_H \
4285 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4286 || defined SIOCGIFFLAGS)) \
4287 || defined WINDOWSNT)
4288 return network_interface_info (ifname
);
4294 /* Turn off input and output for process PROC. */
4297 deactivate_process (Lisp_Object proc
)
4300 struct Lisp_Process
*p
= XPROCESS (proc
);
4304 /* Delete GnuTLS structures in PROC, if any. */
4305 emacs_gnutls_deinit (proc
);
4306 #endif /* HAVE_GNUTLS */
4308 if (p
->read_output_delay
> 0)
4310 if (--process_output_delay_count
< 0)
4311 process_output_delay_count
= 0;
4312 p
->read_output_delay
= 0;
4313 p
->read_output_skip
= 0;
4316 /* Beware SIGCHLD hereabouts. */
4318 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4319 close_process_fd (&p
->open_fd
[i
]);
4321 inchannel
= p
->infd
;
4326 #ifdef DATAGRAM_SOCKETS
4327 if (DATAGRAM_CHAN_P (inchannel
))
4329 xfree (datagram_address
[inchannel
].sa
);
4330 datagram_address
[inchannel
].sa
= 0;
4331 datagram_address
[inchannel
].len
= 0;
4334 chan_process
[inchannel
] = Qnil
;
4335 FD_CLR (inchannel
, &input_wait_mask
);
4336 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4337 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4339 FD_CLR (inchannel
, &connect_wait_mask
);
4340 FD_CLR (inchannel
, &write_mask
);
4341 if (--num_pending_connects
< 0)
4344 if (inchannel
== max_process_desc
)
4346 /* We just closed the highest-numbered process input descriptor,
4347 so recompute the highest-numbered one now. */
4351 while (0 <= i
&& NILP (chan_process
[i
]));
4353 max_process_desc
= i
;
4359 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4361 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4362 It is given to their filter functions.
4363 Optional argument PROCESS means do not return until output has been
4364 received from PROCESS.
4366 Optional second argument SECONDS and third argument MILLISEC
4367 specify a timeout; return after that much time even if there is
4368 no subprocess output. If SECONDS is a floating point number,
4369 it specifies a fractional number of seconds to wait.
4370 The MILLISEC argument is obsolete and should be avoided.
4372 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4373 from PROCESS only, suspending reading output from other processes.
4374 If JUST-THIS-ONE is an integer, don't run any timers either.
4375 Return non-nil if we received any output from PROCESS (or, if PROCESS
4376 is nil, from any process) before the timeout expired. */)
4377 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4382 if (! NILP (process
))
4383 CHECK_PROCESS (process
);
4385 just_this_one
= Qnil
;
4387 if (!NILP (millisec
))
4388 { /* Obsolete calling convention using integers rather than floats. */
4389 CHECK_NUMBER (millisec
);
4391 seconds
= make_float (XINT (millisec
) / 1000.0);
4394 CHECK_NUMBER (seconds
);
4395 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4402 if (!NILP (seconds
))
4404 if (INTEGERP (seconds
))
4406 if (XINT (seconds
) > 0)
4408 secs
= XINT (seconds
);
4412 else if (FLOATP (seconds
))
4414 if (XFLOAT_DATA (seconds
) > 0)
4416 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4417 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4422 wrong_type_argument (Qnumberp
, seconds
);
4424 else if (! NILP (process
))
4428 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4430 !NILP (process
) ? XPROCESS (process
) : NULL
,
4431 (NILP (just_this_one
) ? 0
4432 : !INTEGERP (just_this_one
) ? 1 : -1))
4437 /* Accept a connection for server process SERVER on CHANNEL. */
4439 static EMACS_INT connect_counter
= 0;
4442 server_accept_connection (Lisp_Object server
, int channel
)
4444 Lisp_Object proc
, caller
, name
, buffer
;
4445 Lisp_Object contact
, host
, service
;
4446 struct Lisp_Process
*ps
= XPROCESS (server
);
4447 struct Lisp_Process
*p
;
4451 struct sockaddr_in in
;
4453 struct sockaddr_in6 in6
;
4455 #ifdef HAVE_LOCAL_SOCKETS
4456 struct sockaddr_un un
;
4459 socklen_t len
= sizeof saddr
;
4462 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4467 if (!would_block (code
) && !NILP (ps
->log
))
4468 call3 (ps
->log
, server
, Qnil
,
4469 concat3 (build_string ("accept failed with code"),
4470 Fnumber_to_string (make_number (code
)),
4471 build_string ("\n")));
4475 count
= SPECPDL_INDEX ();
4476 record_unwind_protect_int (close_file_unwind
, s
);
4480 /* Setup a new process to handle the connection. */
4482 /* Generate a unique identification of the caller, and build contact
4483 information for this process. */
4486 switch (saddr
.sa
.sa_family
)
4490 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4492 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4493 host
= CALLN (Fformat
, ipv4_format
,
4494 make_number (ip
[0]), make_number (ip
[1]),
4495 make_number (ip
[2]), make_number (ip
[3]));
4496 service
= make_number (ntohs (saddr
.in
.sin_port
));
4497 AUTO_STRING (caller_format
, " <%s:%d>");
4498 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4505 Lisp_Object args
[9];
4506 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4509 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4510 args
[0] = ipv6_format
;
4511 for (i
= 0; i
< 8; i
++)
4512 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4513 host
= CALLMANY (Fformat
, args
);
4514 service
= make_number (ntohs (saddr
.in
.sin_port
));
4515 AUTO_STRING (caller_format
, " <[%s]:%d>");
4516 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4521 #ifdef HAVE_LOCAL_SOCKETS
4525 caller
= Fnumber_to_string (make_number (connect_counter
));
4526 AUTO_STRING (space_less_than
, " <");
4527 AUTO_STRING (greater_than
, ">");
4528 caller
= concat3 (space_less_than
, caller
, greater_than
);
4532 /* Create a new buffer name for this process if it doesn't have a
4533 filter. The new buffer name is based on the buffer name or
4534 process name of the server process concatenated with the caller
4537 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4538 || EQ (ps
->filter
, Qt
)))
4542 buffer
= ps
->buffer
;
4544 buffer
= Fbuffer_name (buffer
);
4549 buffer
= concat2 (buffer
, caller
);
4550 buffer
= Fget_buffer_create (buffer
);
4554 /* Generate a unique name for the new server process. Combine the
4555 server process name with the caller identification. */
4557 name
= concat2 (ps
->name
, caller
);
4558 proc
= make_process (name
);
4560 chan_process
[s
] = proc
;
4562 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4564 p
= XPROCESS (proc
);
4566 /* Build new contact information for this setup. */
4567 contact
= Fcopy_sequence (ps
->childp
);
4568 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4569 contact
= Fplist_put (contact
, QChost
, host
);
4570 if (!NILP (service
))
4571 contact
= Fplist_put (contact
, QCservice
, service
);
4572 contact
= Fplist_put (contact
, QCremote
,
4573 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4574 #ifdef HAVE_GETSOCKNAME
4576 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4577 contact
= Fplist_put (contact
, QClocal
,
4578 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4581 pset_childp (p
, contact
);
4582 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4583 pset_type (p
, Qnetwork
);
4585 pset_buffer (p
, buffer
);
4586 pset_sentinel (p
, ps
->sentinel
);
4587 pset_filter (p
, ps
->filter
);
4588 pset_command (p
, Qnil
);
4591 /* Discard the unwind protect for closing S. */
4592 specpdl_ptr
= specpdl
+ count
;
4594 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4597 pset_status (p
, Qrun
);
4599 /* Client processes for accepted connections are not stopped initially. */
4600 if (!EQ (p
->filter
, Qt
))
4602 FD_SET (s
, &input_wait_mask
);
4603 FD_SET (s
, &non_keyboard_wait_mask
);
4606 if (s
> max_process_desc
)
4607 max_process_desc
= s
;
4609 /* Setup coding system for new process based on server process.
4610 This seems to be the proper thing to do, as the coding system
4611 of the new process should reflect the settings at the time the
4612 server socket was opened; not the current settings. */
4614 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4615 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4616 setup_process_coding_systems (proc
);
4618 pset_decoding_buf (p
, empty_unibyte_string
);
4619 p
->decoding_carryover
= 0;
4620 pset_encoding_buf (p
, empty_unibyte_string
);
4622 p
->inherit_coding_system_flag
4623 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4625 AUTO_STRING (dash
, "-");
4626 AUTO_STRING (nl
, "\n");
4627 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4629 if (!NILP (ps
->log
))
4631 AUTO_STRING (accept_from
, "accept from ");
4632 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4635 AUTO_STRING (open_from
, "open from ");
4636 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4639 #ifdef HAVE_GETADDRINFO_A
4641 check_for_dns (Lisp_Object proc
)
4643 struct Lisp_Process
*p
= XPROCESS (proc
);
4644 Lisp_Object ip_addresses
= Qnil
;
4647 if (! p
->dns_request
)
4650 int ret
= gai_error (p
->dns_request
);
4651 if (ret
== EAI_INPROGRESS
)
4654 /* We got a response. */
4657 struct addrinfo
*res
;
4659 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4661 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4662 (res
->ai_addr
, res
->ai_addrlen
),
4666 ip_addresses
= Fnreverse (ip_addresses
);
4668 /* The DNS lookup failed. */
4669 else if (EQ (p
->status
, Qconnect
))
4671 deactivate_process (proc
);
4672 pset_status (p
, (list2
4674 concat3 (build_string ("Name lookup of "),
4675 build_string (p
->dns_request
->ar_name
),
4676 build_string (" failed")))));
4679 free_dns_request (proc
);
4681 /* This process should not already be connected (or killed). */
4682 if (!EQ (p
->status
, Qconnect
))
4685 return ip_addresses
;
4688 #endif /* HAVE_GETADDRINFO_A */
4691 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4693 while (XPROCESS (process
)->infd
< 0
4694 && EQ (XPROCESS (process
)->status
, Qconnect
))
4696 add_to_log ("Waiting for socket from %s...", build_string (name
));
4697 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4702 wait_while_connecting (Lisp_Object process
)
4704 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4706 add_to_log ("Waiting for connection...");
4707 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4712 wait_for_tls_negotiation (Lisp_Object process
)
4715 while (XPROCESS (process
)->gnutls_p
4716 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4718 add_to_log ("Waiting for TLS...");
4719 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4724 /* This variable is different from waiting_for_input in keyboard.c.
4725 It is used to communicate to a lisp process-filter/sentinel (via the
4726 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4727 for user-input when that process-filter was called.
4728 waiting_for_input cannot be used as that is by definition 0 when
4729 lisp code is being evalled.
4730 This is also used in record_asynch_buffer_change.
4731 For that purpose, this must be 0
4732 when not inside wait_reading_process_output. */
4733 static int waiting_for_user_input_p
;
4736 wait_reading_process_output_unwind (int data
)
4738 waiting_for_user_input_p
= data
;
4741 /* This is here so breakpoints can be put on it. */
4743 wait_reading_process_output_1 (void)
4747 /* Read and dispose of subprocess output while waiting for timeout to
4748 elapse and/or keyboard input to be available.
4752 If negative, gobble data immediately available but don't wait for any.
4755 an additional duration to wait, measured in nanoseconds
4756 If TIME_LIMIT is zero, then:
4757 If NSECS == 0, there is no limit.
4758 If NSECS > 0, the timeout consists of NSECS only.
4759 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4762 0 to ignore keyboard input, or
4763 1 to return when input is available, or
4764 -1 meaning caller will actually read the input, so don't throw to
4765 the quit handler, or
4767 DO_DISPLAY means redisplay should be done to show subprocess
4768 output that arrives.
4770 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4771 (and gobble terminal input into the buffer if any arrives).
4773 If WAIT_PROC is specified, wait until something arrives from that
4776 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4777 (suspending output from other processes). A negative value
4778 means don't run any timers either.
4780 Return positive if we received input from WAIT_PROC (or from any
4781 process if WAIT_PROC is null), zero if we attempted to receive
4782 input but got none, and negative if we didn't even try. */
4785 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4787 Lisp_Object wait_for_cell
,
4788 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4798 struct timespec timeout
, end_time
, timer_delay
;
4799 struct timespec got_output_end_time
= invalid_timespec ();
4800 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4801 int got_some_output
= -1;
4802 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4803 bool retry_for_async
;
4805 ptrdiff_t count
= SPECPDL_INDEX ();
4807 /* Close to the current time if known, an invalid timespec otherwise. */
4808 struct timespec now
= invalid_timespec ();
4810 FD_ZERO (&Available
);
4813 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4814 && !(CONSP (wait_proc
->status
)
4815 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4816 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4818 record_unwind_protect_int (wait_reading_process_output_unwind
,
4819 waiting_for_user_input_p
);
4820 waiting_for_user_input_p
= read_kbd
;
4822 if (TYPE_MAXIMUM (time_t) < time_limit
)
4823 time_limit
= TYPE_MAXIMUM (time_t);
4825 if (time_limit
< 0 || nsecs
< 0)
4827 else if (time_limit
> 0 || nsecs
> 0)
4830 now
= current_timespec ();
4831 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4838 bool process_skipped
= false;
4840 /* If calling from keyboard input, do not quit
4841 since we want to return C-g as an input character.
4842 Otherwise, do pending quit if requested. */
4845 else if (pending_signals
)
4846 process_pending_signals ();
4848 /* Exit now if the cell we're waiting for became non-nil. */
4849 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4852 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4854 Lisp_Object process_list_head
, aproc
;
4855 struct Lisp_Process
*p
;
4857 retry_for_async
= false;
4858 FOR_EACH_PROCESS(process_list_head
, aproc
)
4860 p
= XPROCESS (aproc
);
4862 if (! wait_proc
|| p
== wait_proc
)
4864 #ifdef HAVE_GETADDRINFO_A
4865 /* Check for pending DNS requests. */
4868 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4869 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4870 connect_network_socket (aproc
, ip_addresses
, Qnil
);
4872 retry_for_async
= true;
4876 /* Continue TLS negotiation. */
4877 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4878 && p
->is_non_blocking_client
)
4880 gnutls_try_handshake (p
);
4881 p
->gnutls_handshakes_tried
++;
4883 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4885 gnutls_verify_boot (aproc
, Qnil
);
4886 finish_after_tls_connection (aproc
);
4890 retry_for_async
= true;
4891 if (p
->gnutls_handshakes_tried
4892 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4894 deactivate_process (aproc
);
4895 pset_status (p
, list2 (Qfailed
,
4896 build_string ("TLS negotiation failed")));
4904 #endif /* GETADDRINFO_A or GNUTLS */
4906 /* Compute time from now till when time limit is up. */
4907 /* Exit if already run out. */
4908 if (wait
== TIMEOUT
)
4910 if (!timespec_valid_p (now
))
4911 now
= current_timespec ();
4912 if (timespec_cmp (end_time
, now
) <= 0)
4914 timeout
= timespec_sub (end_time
, now
);
4917 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4919 /* Normally we run timers here.
4920 But not if wait_for_cell; in those cases,
4921 the wait is supposed to be short,
4922 and those callers cannot handle running arbitrary Lisp code here. */
4923 if (NILP (wait_for_cell
)
4924 && just_wait_proc
>= 0)
4928 unsigned old_timers_run
= timers_run
;
4929 struct buffer
*old_buffer
= current_buffer
;
4930 Lisp_Object old_window
= selected_window
;
4932 timer_delay
= timer_check ();
4934 /* If a timer has run, this might have changed buffers
4935 an alike. Make read_key_sequence aware of that. */
4936 if (timers_run
!= old_timers_run
4937 && (old_buffer
!= current_buffer
4938 || !EQ (old_window
, selected_window
))
4939 && waiting_for_user_input_p
== -1)
4940 record_asynch_buffer_change ();
4942 if (timers_run
!= old_timers_run
&& do_display
)
4943 /* We must retry, since a timer may have requeued itself
4944 and that could alter the time_delay. */
4945 redisplay_preserve_echo_area (9);
4949 while (!detect_input_pending ());
4951 /* If there is unread keyboard input, also return. */
4953 && requeued_events_pending_p ())
4956 /* This is so a breakpoint can be put here. */
4957 if (!timespec_valid_p (timer_delay
))
4958 wait_reading_process_output_1 ();
4961 /* Cause C-g and alarm signals to take immediate action,
4962 and cause input available signals to zero out timeout.
4964 It is important that we do this before checking for process
4965 activity. If we get a SIGCHLD after the explicit checks for
4966 process activity, timeout is the only way we will know. */
4968 set_waiting_for_input (&timeout
);
4970 /* If status of something has changed, and no input is
4971 available, notify the user of the change right away. After
4972 this explicit check, we'll let the SIGCHLD handler zap
4973 timeout to get our attention. */
4974 if (update_tick
!= process_tick
)
4979 if (kbd_on_hold_p ())
4982 Atemp
= input_wait_mask
;
4985 timeout
= make_timespec (0, 0);
4986 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4988 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4989 NULL
, &timeout
, NULL
)
4992 /* It's okay for us to do this and then continue with
4993 the loop, since timeout has already been zeroed out. */
4994 clear_waiting_for_input ();
4995 got_some_output
= status_notify (NULL
, wait_proc
);
4996 if (do_display
) redisplay_preserve_echo_area (13);
5000 /* Don't wait for output from a non-running process. Just
5001 read whatever data has already been received. */
5002 if (wait_proc
&& wait_proc
->raw_status_new
)
5003 update_status (wait_proc
);
5005 && ! EQ (wait_proc
->status
, Qrun
)
5006 && ! EQ (wait_proc
->status
, Qconnect
))
5008 bool read_some_bytes
= false;
5010 clear_waiting_for_input ();
5012 /* If data can be read from the process, do so until exhausted. */
5013 if (wait_proc
->infd
>= 0)
5015 XSETPROCESS (proc
, wait_proc
);
5019 int nread
= read_process_output (proc
, wait_proc
->infd
);
5022 if (errno
== EIO
|| would_block (errno
))
5027 if (got_some_output
< nread
)
5028 got_some_output
= nread
;
5031 read_some_bytes
= true;
5036 if (read_some_bytes
&& do_display
)
5037 redisplay_preserve_echo_area (10);
5042 /* Wait till there is something to do. */
5044 if (wait_proc
&& just_wait_proc
)
5046 if (wait_proc
->infd
< 0) /* Terminated. */
5048 FD_SET (wait_proc
->infd
, &Available
);
5052 else if (!NILP (wait_for_cell
))
5054 Available
= non_process_wait_mask
;
5061 Available
= non_keyboard_wait_mask
;
5063 Available
= input_wait_mask
;
5064 Writeok
= write_mask
;
5065 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5069 /* If frame size has changed or the window is newly mapped,
5070 redisplay now, before we start to wait. There is a race
5071 condition here; if a SIGIO arrives between now and the select
5072 and indicates that a frame is trashed, the select may block
5073 displaying a trashed screen. */
5074 if (frame_garbaged
&& do_display
)
5076 clear_waiting_for_input ();
5077 redisplay_preserve_echo_area (11);
5079 set_waiting_for_input (&timeout
);
5082 /* Skip the `select' call if input is available and we're
5083 waiting for keyboard input or a cell change (which can be
5084 triggered by processing X events). In the latter case, set
5085 nfds to 1 to avoid breaking the loop. */
5087 if ((read_kbd
|| !NILP (wait_for_cell
))
5088 && detect_input_pending ())
5090 nfds
= read_kbd
? 0 : 1;
5092 FD_ZERO (&Available
);
5096 /* Set the timeout for adaptive read buffering if any
5097 process has non-zero read_output_skip and non-zero
5098 read_output_delay, and we are not reading output for a
5099 specific process. It is not executed if
5100 Vprocess_adaptive_read_buffering is nil. */
5101 if (process_output_skip
&& check_delay
> 0)
5103 int adaptive_nsecs
= timeout
.tv_nsec
;
5104 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5105 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5106 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5108 proc
= chan_process
[channel
];
5111 /* Find minimum non-zero read_output_delay among the
5112 processes with non-zero read_output_skip. */
5113 if (XPROCESS (proc
)->read_output_delay
> 0)
5116 if (!XPROCESS (proc
)->read_output_skip
)
5118 FD_CLR (channel
, &Available
);
5119 process_skipped
= true;
5120 XPROCESS (proc
)->read_output_skip
= 0;
5121 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5122 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5125 timeout
= make_timespec (0, adaptive_nsecs
);
5126 process_output_skip
= 0;
5129 /* If we've got some output and haven't limited our timeout
5130 with adaptive read buffering, limit it. */
5131 if (got_some_output
> 0 && !process_skipped
5133 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5134 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5137 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5138 && timespec_valid_p (timer_delay
)
5139 && timespec_cmp (timer_delay
, timeout
) < 0)
5141 if (!timespec_valid_p (now
))
5142 now
= current_timespec ();
5143 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5144 if (!timespec_valid_p (got_output_end_time
)
5145 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5146 got_output_end_time
= timeout_abs
;
5147 timeout
= timer_delay
;
5150 got_output_end_time
= invalid_timespec ();
5152 /* NOW can become inaccurate if time can pass during pselect. */
5153 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5154 now
= invalid_timespec ();
5156 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5158 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5161 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5165 #if defined (HAVE_NS)
5167 #elif defined (HAVE_GLIB)
5172 (max (max_process_desc
, max_input_desc
) + 1,
5174 (check_write
? &Writeok
: 0),
5175 NULL
, &timeout
, NULL
);
5178 /* GnuTLS buffers data internally. In lowat mode it leaves
5179 some data in the TCP buffers so that select works, but
5180 with custom pull/push functions we need to check if some
5181 data is available in the buffers manually. */
5184 fd_set tls_available
;
5187 FD_ZERO (&tls_available
);
5190 /* We're not waiting on a specific process, so loop
5191 through all the channels and check for data.
5192 This is a workaround needed for some versions of
5193 the gnutls library -- 2.12.14 has been confirmed
5195 http://comments.gmane.org/gmane.emacs.devel/145074 */
5196 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5197 if (! NILP (chan_process
[channel
]))
5199 struct Lisp_Process
*p
=
5200 XPROCESS (chan_process
[channel
]);
5201 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5202 && ((emacs_gnutls_record_check_pending
5207 eassert (p
->infd
== channel
);
5208 FD_SET (p
->infd
, &tls_available
);
5215 /* Check this specific channel. */
5216 if (wait_proc
->gnutls_p
/* Check for valid process. */
5217 && wait_proc
->gnutls_state
5218 /* Do we have pending data? */
5219 && ((emacs_gnutls_record_check_pending
5220 (wait_proc
->gnutls_state
))
5224 eassert (0 <= wait_proc
->infd
);
5225 /* Set to Available. */
5226 FD_SET (wait_proc
->infd
, &tls_available
);
5231 Available
= tls_available
;
5238 /* Make C-g and alarm signals set flags again. */
5239 clear_waiting_for_input ();
5241 /* If we woke up due to SIGWINCH, actually change size now. */
5242 do_pending_window_change (0);
5246 /* Exit the main loop if we've passed the requested timeout,
5247 or aren't skipping processes and got some output and
5248 haven't lowered our timeout due to timers or SIGIO and
5249 have waited a long amount of time due to repeated
5253 struct timespec cmp_time
5256 : (!process_skipped
&& got_some_output
> 0
5257 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5258 ? got_output_end_time
5259 : invalid_timespec ());
5260 if (timespec_valid_p (cmp_time
))
5262 now
= current_timespec ();
5263 if (timespec_cmp (cmp_time
, now
) <= 0)
5270 if (xerrno
== EINTR
)
5272 else if (xerrno
== EBADF
)
5275 report_file_errno ("Failed select", Qnil
, xerrno
);
5278 /* Check for keyboard input. */
5279 /* If there is any, return immediately
5280 to give it higher priority than subprocesses. */
5284 unsigned old_timers_run
= timers_run
;
5285 struct buffer
*old_buffer
= current_buffer
;
5286 Lisp_Object old_window
= selected_window
;
5289 if (detect_input_pending_run_timers (do_display
))
5291 swallow_events (do_display
);
5292 if (detect_input_pending_run_timers (do_display
))
5296 /* If a timer has run, this might have changed buffers
5297 an alike. Make read_key_sequence aware of that. */
5298 if (timers_run
!= old_timers_run
5299 && waiting_for_user_input_p
== -1
5300 && (old_buffer
!= current_buffer
5301 || !EQ (old_window
, selected_window
)))
5302 record_asynch_buffer_change ();
5308 /* If there is unread keyboard input, also return. */
5310 && requeued_events_pending_p ())
5313 /* If we are not checking for keyboard input now,
5314 do process events (but don't run any timers).
5315 This is so that X events will be processed.
5316 Otherwise they may have to wait until polling takes place.
5317 That would causes delays in pasting selections, for example.
5319 (We used to do this only if wait_for_cell.) */
5320 if (read_kbd
== 0 && detect_input_pending ())
5322 swallow_events (do_display
);
5323 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5324 if (detect_input_pending ())
5329 /* Exit now if the cell we're waiting for became non-nil. */
5330 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5334 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5335 go read it. This can happen with X on BSD after logging out.
5336 In that case, there really is no input and no SIGIO,
5337 but select says there is input. */
5339 if (read_kbd
&& interrupt_input
5340 && keyboard_bit_set (&Available
) && ! noninteractive
)
5341 handle_input_available_signal (SIGIO
);
5344 /* If checking input just got us a size-change event from X,
5345 obey it now if we should. */
5346 if (read_kbd
|| ! NILP (wait_for_cell
))
5347 do_pending_window_change (0);
5349 /* Check for data from a process. */
5350 if (no_avail
|| nfds
== 0)
5353 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5355 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5357 && ((d
->condition
& FOR_READ
5358 && FD_ISSET (channel
, &Available
))
5359 || (d
->condition
& FOR_WRITE
5360 && FD_ISSET (channel
, &write_mask
))))
5361 d
->func (channel
, d
->data
);
5364 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5366 if (FD_ISSET (channel
, &Available
)
5367 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5368 && !FD_ISSET (channel
, &non_process_wait_mask
))
5372 /* If waiting for this channel, arrange to return as
5373 soon as no more input to be processed. No more
5375 proc
= chan_process
[channel
];
5379 /* If this is a server stream socket, accept connection. */
5380 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5382 server_accept_connection (proc
, channel
);
5386 /* Read data from the process, starting with our
5387 buffered-ahead character if we have one. */
5389 nread
= read_process_output (proc
, channel
);
5390 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5391 && got_some_output
< nread
)
5392 got_some_output
= nread
;
5395 /* Vacuum up any leftovers without waiting. */
5396 if (wait_proc
== XPROCESS (proc
))
5398 /* Since read_process_output can run a filter,
5399 which can call accept-process-output,
5400 don't try to read from any other processes
5401 before doing the select again. */
5402 FD_ZERO (&Available
);
5405 redisplay_preserve_echo_area (12);
5407 else if (nread
== -1 && would_block (errno
))
5410 /* FIXME: Is this special case still needed? */
5411 /* Note that we cannot distinguish between no input
5412 available now and a closed pipe.
5413 With luck, a closed pipe will be accompanied by
5414 subprocess termination and SIGCHLD. */
5415 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5416 && !PIPECONN_P (proc
))
5420 /* On some OSs with ptys, when the process on one end of
5421 a pty exits, the other end gets an error reading with
5422 errno = EIO instead of getting an EOF (0 bytes read).
5423 Therefore, if we get an error reading and errno =
5424 EIO, just continue, because the child process has
5425 exited and should clean itself up soon (e.g. when we
5427 else if (nread
== -1 && errno
== EIO
)
5429 struct Lisp_Process
*p
= XPROCESS (proc
);
5431 /* Clear the descriptor now, so we only raise the
5433 FD_CLR (channel
, &input_wait_mask
);
5434 FD_CLR (channel
, &non_keyboard_wait_mask
);
5438 /* If the EIO occurs on a pty, the SIGCHLD handler's
5439 waitpid call will not find the process object to
5440 delete. Do it here. */
5441 p
->tick
= ++process_tick
;
5442 pset_status (p
, Qfailed
);
5445 #endif /* HAVE_PTYS */
5446 /* If we can detect process termination, don't consider the
5447 process gone just because its pipe is closed. */
5448 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5449 && !PIPECONN_P (proc
))
5451 else if (nread
== 0 && PIPECONN_P (proc
))
5453 /* Preserve status of processes already terminated. */
5454 XPROCESS (proc
)->tick
= ++process_tick
;
5455 deactivate_process (proc
);
5456 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5457 pset_status (XPROCESS (proc
),
5458 list2 (Qexit
, make_number (0)));
5462 /* Preserve status of processes already terminated. */
5463 XPROCESS (proc
)->tick
= ++process_tick
;
5464 deactivate_process (proc
);
5465 if (XPROCESS (proc
)->raw_status_new
)
5466 update_status (XPROCESS (proc
));
5467 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5468 pset_status (XPROCESS (proc
),
5469 list2 (Qexit
, make_number (256)));
5472 if (FD_ISSET (channel
, &Writeok
)
5473 && FD_ISSET (channel
, &connect_wait_mask
))
5475 struct Lisp_Process
*p
;
5477 FD_CLR (channel
, &connect_wait_mask
);
5478 FD_CLR (channel
, &write_mask
);
5479 if (--num_pending_connects
< 0)
5482 proc
= chan_process
[channel
];
5486 p
= XPROCESS (proc
);
5489 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5490 So only use it on systems where it is known to work. */
5492 socklen_t xlen
= sizeof (xerrno
);
5493 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5498 struct sockaddr pname
;
5499 socklen_t pnamelen
= sizeof (pname
);
5501 /* If connection failed, getpeername will fail. */
5503 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5505 /* Obtain connect failure code through error slippage. */
5508 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5515 p
->tick
= ++process_tick
;
5516 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5517 deactivate_process (proc
);
5522 /* If we have an incompletely set up TLS connection,
5523 then defer the sentinel signaling until
5525 if (NILP (p
->gnutls_boot_parameters
)
5529 pset_status (p
, Qrun
);
5530 /* Execute the sentinel here. If we had relied on
5531 status_notify to do it later, it will read input
5532 from the process before calling the sentinel. */
5533 exec_sentinel (proc
, build_string ("open\n"));
5536 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5537 && !EQ (p
->command
, Qt
))
5539 FD_SET (p
->infd
, &input_wait_mask
);
5540 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5544 } /* End for each file descriptor. */
5545 } /* End while exit conditions not met. */
5547 unbind_to (count
, Qnil
);
5549 /* If calling from keyboard input, do not quit
5550 since we want to return C-g as an input character.
5551 Otherwise, do pending quit if requested. */
5554 /* Prevent input_pending from remaining set if we quit. */
5555 clear_input_pending ();
5559 return got_some_output
;
5562 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5565 read_process_output_call (Lisp_Object fun_and_args
)
5567 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5571 read_process_output_error_handler (Lisp_Object error_val
)
5573 cmd_error_internal (error_val
, "error in process filter: ");
5575 update_echo_area ();
5576 Fsleep_for (make_number (2), Qnil
);
5581 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5583 struct coding_system
*coding
);
5585 /* Read pending output from the process channel,
5586 starting with our buffered-ahead character if we have one.
5587 Yield number of decoded characters read.
5589 This function reads at most 4096 characters.
5590 If you want to read all available subprocess output,
5591 you must call it repeatedly until it returns zero.
5593 The characters read are decoded according to PROC's coding-system
5597 read_process_output (Lisp_Object proc
, int channel
)
5600 struct Lisp_Process
*p
= XPROCESS (proc
);
5601 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5602 int carryover
= p
->decoding_carryover
;
5603 enum { readmax
= 4096 };
5604 ptrdiff_t count
= SPECPDL_INDEX ();
5605 Lisp_Object odeactivate
;
5606 char chars
[sizeof coding
->carryover
+ readmax
];
5609 /* See the comment above. */
5610 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5612 #ifdef DATAGRAM_SOCKETS
5613 /* We have a working select, so proc_buffered_char is always -1. */
5614 if (DATAGRAM_CHAN_P (channel
))
5616 socklen_t len
= datagram_address
[channel
].len
;
5617 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5618 0, datagram_address
[channel
].sa
, &len
);
5623 bool buffered
= proc_buffered_char
[channel
] >= 0;
5626 chars
[carryover
] = proc_buffered_char
[channel
];
5627 proc_buffered_char
[channel
] = -1;
5630 if (p
->gnutls_p
&& p
->gnutls_state
)
5631 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5632 readmax
- buffered
);
5635 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5636 readmax
- buffered
);
5637 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5639 int delay
= p
->read_output_delay
;
5642 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5645 process_output_delay_count
++;
5646 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5649 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5651 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5653 process_output_delay_count
--;
5655 p
->read_output_delay
= delay
;
5658 p
->read_output_skip
= 1;
5659 process_output_skip
= 1;
5663 nbytes
+= buffered
&& nbytes
<= 0;
5666 p
->decoding_carryover
= 0;
5668 /* At this point, NBYTES holds number of bytes just received
5669 (including the one in proc_buffered_char[channel]). */
5672 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5674 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5677 /* Now set NBYTES how many bytes we must decode. */
5678 nbytes
+= carryover
;
5680 odeactivate
= Vdeactivate_mark
;
5681 /* There's no good reason to let process filters change the current
5682 buffer, and many callers of accept-process-output, sit-for, and
5683 friends don't expect current-buffer to be changed from under them. */
5684 record_unwind_current_buffer ();
5686 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5688 /* Handling the process output should not deactivate the mark. */
5689 Vdeactivate_mark
= odeactivate
;
5691 unbind_to (count
, Qnil
);
5696 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5698 struct coding_system
*coding
)
5700 Lisp_Object outstream
= p
->filter
;
5702 bool outer_running_asynch_code
= running_asynch_code
;
5703 int waiting
= waiting_for_user_input_p
;
5706 Lisp_Object obuffer
, okeymap
;
5707 XSETBUFFER (obuffer
, current_buffer
);
5708 okeymap
= BVAR (current_buffer
, keymap
);
5711 /* We inhibit quit here instead of just catching it so that
5712 hitting ^G when a filter happens to be running won't screw
5714 specbind (Qinhibit_quit
, Qt
);
5715 specbind (Qlast_nonmenu_event
, Qt
);
5717 /* In case we get recursively called,
5718 and we already saved the match data nonrecursively,
5719 save the same match data in safely recursive fashion. */
5720 if (outer_running_asynch_code
)
5723 /* Don't clobber the CURRENT match data, either! */
5724 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5725 restore_search_regs ();
5726 record_unwind_save_match_data ();
5727 Fset_match_data (tem
, Qt
);
5730 /* For speed, if a search happens within this code,
5731 save the match data in a special nonrecursive fashion. */
5732 running_asynch_code
= 1;
5734 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5735 text
= coding
->dst_object
;
5736 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5737 /* A new coding system might be found. */
5738 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5740 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5742 /* Don't call setup_coding_system for
5743 proc_decode_coding_system[channel] here. It is done in
5744 detect_coding called via decode_coding above. */
5746 /* If a coding system for encoding is not yet decided, we set
5747 it as the same as coding-system for decoding.
5749 But, before doing that we must check if
5750 proc_encode_coding_system[p->outfd] surely points to a
5751 valid memory because p->outfd will be changed once EOF is
5752 sent to the process. */
5753 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5754 && proc_encode_coding_system
[p
->outfd
])
5756 pset_encode_coding_system
5757 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5758 setup_coding_system (p
->encode_coding_system
,
5759 proc_encode_coding_system
[p
->outfd
]);
5763 if (coding
->carryover_bytes
> 0)
5765 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5766 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5767 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5768 coding
->carryover_bytes
);
5769 p
->decoding_carryover
= coding
->carryover_bytes
;
5771 if (SBYTES (text
) > 0)
5772 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5773 sometimes it's simply wrong to wrap (e.g. when called from
5774 accept-process-output). */
5775 internal_condition_case_1 (read_process_output_call
,
5776 list3 (outstream
, make_lisp_proc (p
), text
),
5777 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5778 read_process_output_error_handler
);
5780 /* If we saved the match data nonrecursively, restore it now. */
5781 restore_search_regs ();
5782 running_asynch_code
= outer_running_asynch_code
;
5784 /* Restore waiting_for_user_input_p as it was
5785 when we were called, in case the filter clobbered it. */
5786 waiting_for_user_input_p
= waiting
;
5788 #if 0 /* Call record_asynch_buffer_change unconditionally,
5789 because we might have changed minor modes or other things
5790 that affect key bindings. */
5791 if (! EQ (Fcurrent_buffer (), obuffer
)
5792 || ! EQ (current_buffer
->keymap
, okeymap
))
5794 /* But do it only if the caller is actually going to read events.
5795 Otherwise there's no need to make him wake up, and it could
5796 cause trouble (for example it would make sit_for return). */
5797 if (waiting_for_user_input_p
== -1)
5798 record_asynch_buffer_change ();
5801 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5802 Sinternal_default_process_filter
, 2, 2, 0,
5803 doc
: /* Function used as default process filter.
5804 This inserts the process's output into its buffer, if there is one.
5805 Otherwise it discards the output. */)
5806 (Lisp_Object proc
, Lisp_Object text
)
5808 struct Lisp_Process
*p
;
5811 CHECK_PROCESS (proc
);
5812 p
= XPROCESS (proc
);
5813 CHECK_STRING (text
);
5815 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5817 Lisp_Object old_read_only
;
5818 ptrdiff_t old_begv
, old_zv
;
5819 ptrdiff_t old_begv_byte
, old_zv_byte
;
5820 ptrdiff_t before
, before_byte
;
5821 ptrdiff_t opoint_byte
;
5824 Fset_buffer (p
->buffer
);
5826 opoint_byte
= PT_BYTE
;
5827 old_read_only
= BVAR (current_buffer
, read_only
);
5830 old_begv_byte
= BEGV_BYTE
;
5831 old_zv_byte
= ZV_BYTE
;
5833 bset_read_only (current_buffer
, Qnil
);
5835 /* Insert new output into buffer at the current end-of-output
5836 marker, thus preserving logical ordering of input and output. */
5837 if (XMARKER (p
->mark
)->buffer
)
5838 set_point_from_marker (p
->mark
);
5840 SET_PT_BOTH (ZV
, ZV_BYTE
);
5842 before_byte
= PT_BYTE
;
5844 /* If the output marker is outside of the visible region, save
5845 the restriction and widen. */
5846 if (! (BEGV
<= PT
&& PT
<= ZV
))
5849 /* Adjust the multibyteness of TEXT to that of the buffer. */
5850 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5851 != ! STRING_MULTIBYTE (text
))
5852 text
= (STRING_MULTIBYTE (text
)
5853 ? Fstring_as_unibyte (text
)
5854 : Fstring_to_multibyte (text
));
5855 /* Insert before markers in case we are inserting where
5856 the buffer's mark is, and the user's next command is Meta-y. */
5857 insert_from_string_before_markers (text
, 0, 0,
5858 SCHARS (text
), SBYTES (text
), 0);
5860 /* Make sure the process marker's position is valid when the
5861 process buffer is changed in the signal_after_change above.
5862 W3 is known to do that. */
5863 if (BUFFERP (p
->buffer
)
5864 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5865 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5867 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5869 update_mode_lines
= 23;
5871 /* Make sure opoint and the old restrictions
5872 float ahead of any new text just as point would. */
5873 if (opoint
>= before
)
5875 opoint
+= PT
- before
;
5876 opoint_byte
+= PT_BYTE
- before_byte
;
5878 if (old_begv
> before
)
5880 old_begv
+= PT
- before
;
5881 old_begv_byte
+= PT_BYTE
- before_byte
;
5883 if (old_zv
>= before
)
5885 old_zv
+= PT
- before
;
5886 old_zv_byte
+= PT_BYTE
- before_byte
;
5889 /* If the restriction isn't what it should be, set it. */
5890 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5891 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5893 bset_read_only (current_buffer
, old_read_only
);
5894 SET_PT_BOTH (opoint
, opoint_byte
);
5899 /* Sending data to subprocess. */
5901 /* In send_process, when a write fails temporarily,
5902 wait_reading_process_output is called. It may execute user code,
5903 e.g. timers, that attempts to write new data to the same process.
5904 We must ensure that data is sent in the right order, and not
5905 interspersed half-completed with other writes (Bug#10815). This is
5906 handled by the write_queue element of struct process. It is a list
5907 with each entry having the form
5909 (string . (offset . length))
5911 where STRING is a lisp string, OFFSET is the offset into the
5912 string's byte sequence from which we should begin to send, and
5913 LENGTH is the number of bytes left to send. */
5915 /* Create a new entry in write_queue.
5916 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5917 BUF is a pointer to the string sequence of the input_obj or a C
5918 string in case of Qt or Qnil. */
5921 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5922 const char *buf
, ptrdiff_t len
, bool front
)
5925 Lisp_Object entry
, obj
;
5927 if (STRINGP (input_obj
))
5929 offset
= buf
- SSDATA (input_obj
);
5935 obj
= make_unibyte_string (buf
, len
);
5938 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5941 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5943 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5946 /* Remove the first element in the write_queue of process P, put its
5947 contents in OBJ, BUF and LEN, and return true. If the
5948 write_queue is empty, return false. */
5951 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5952 const char **buf
, ptrdiff_t *len
)
5954 Lisp_Object entry
, offset_length
;
5957 if (NILP (p
->write_queue
))
5960 entry
= XCAR (p
->write_queue
);
5961 pset_write_queue (p
, XCDR (p
->write_queue
));
5963 *obj
= XCAR (entry
);
5964 offset_length
= XCDR (entry
);
5966 *len
= XINT (XCDR (offset_length
));
5967 offset
= XINT (XCAR (offset_length
));
5968 *buf
= SSDATA (*obj
) + offset
;
5973 /* Send some data to process PROC.
5974 BUF is the beginning of the data; LEN is the number of characters.
5975 OBJECT is the Lisp object that the data comes from. If OBJECT is
5976 nil or t, it means that the data comes from C string.
5978 If OBJECT is not nil, the data is encoded by PROC's coding-system
5979 for encoding before it is sent.
5981 This function can evaluate Lisp code and can garbage collect. */
5984 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5987 struct Lisp_Process
*p
= XPROCESS (proc
);
5989 struct coding_system
*coding
;
5991 if (NETCONN_P (proc
))
5993 wait_while_connecting (proc
);
5994 wait_for_tls_negotiation (proc
);
5997 if (p
->raw_status_new
)
5999 if (! EQ (p
->status
, Qrun
))
6000 error ("Process %s not running", SDATA (p
->name
));
6002 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6004 coding
= proc_encode_coding_system
[p
->outfd
];
6005 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6007 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6008 || (BUFFERP (object
)
6009 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6012 pset_encode_coding_system
6013 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6014 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6016 /* The coding system for encoding was changed to raw-text
6017 because we sent a unibyte text previously. Now we are
6018 sending a multibyte text, thus we must encode it by the
6019 original coding system specified for the current process.
6021 Another reason we come here is that the coding system
6022 was just complemented and a new one was returned by
6023 complement_process_encoding_system. */
6024 setup_coding_system (p
->encode_coding_system
, coding
);
6025 Vlast_coding_system_used
= p
->encode_coding_system
;
6027 coding
->src_multibyte
= 1;
6031 coding
->src_multibyte
= 0;
6032 /* For sending a unibyte text, character code conversion should
6033 not take place but EOL conversion should. So, setup raw-text
6034 or one of the subsidiary if we have not yet done it. */
6035 if (CODING_REQUIRE_ENCODING (coding
))
6037 if (CODING_REQUIRE_FLUSHING (coding
))
6039 /* But, before changing the coding, we must flush out data. */
6040 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6041 send_process (proc
, "", 0, Qt
);
6042 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6044 setup_coding_system (raw_text_coding_system
6045 (Vlast_coding_system_used
),
6047 coding
->src_multibyte
= 0;
6050 coding
->dst_multibyte
= 0;
6052 if (CODING_REQUIRE_ENCODING (coding
))
6054 coding
->dst_object
= Qt
;
6055 if (BUFFERP (object
))
6057 ptrdiff_t from_byte
, from
, to
;
6058 ptrdiff_t save_pt
, save_pt_byte
;
6059 struct buffer
*cur
= current_buffer
;
6061 set_buffer_internal (XBUFFER (object
));
6062 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6064 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6065 from
= BYTE_TO_CHAR (from_byte
);
6066 to
= BYTE_TO_CHAR (from_byte
+ len
);
6067 TEMP_SET_PT_BOTH (from
, from_byte
);
6068 encode_coding_object (coding
, object
, from
, from_byte
,
6069 to
, from_byte
+ len
, Qt
);
6070 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6071 set_buffer_internal (cur
);
6073 else if (STRINGP (object
))
6075 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6076 SBYTES (object
), Qt
);
6080 coding
->dst_object
= make_unibyte_string (buf
, len
);
6081 coding
->produced
= len
;
6084 len
= coding
->produced
;
6085 object
= coding
->dst_object
;
6086 buf
= SSDATA (object
);
6089 /* If there is already data in the write_queue, put the new data
6090 in the back of queue. Otherwise, ignore it. */
6091 if (!NILP (p
->write_queue
))
6092 write_queue_push (p
, object
, buf
, len
, 0);
6094 do /* while !NILP (p->write_queue) */
6096 ptrdiff_t cur_len
= -1;
6097 const char *cur_buf
;
6098 Lisp_Object cur_object
;
6100 /* If write_queue is empty, ignore it. */
6101 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6105 cur_object
= object
;
6110 /* Send this batch, using one or more write calls. */
6111 ptrdiff_t written
= 0;
6112 int outfd
= p
->outfd
;
6113 #ifdef DATAGRAM_SOCKETS
6114 if (DATAGRAM_CHAN_P (outfd
))
6116 rv
= sendto (outfd
, cur_buf
, cur_len
,
6117 0, datagram_address
[outfd
].sa
,
6118 datagram_address
[outfd
].len
);
6121 else if (errno
== EMSGSIZE
)
6122 report_file_error ("Sending datagram", proc
);
6128 if (p
->gnutls_p
&& p
->gnutls_state
)
6129 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6132 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6133 rv
= (written
? 0 : -1);
6134 if (p
->read_output_delay
> 0
6135 && p
->adaptive_read_buffering
== 1)
6137 p
->read_output_delay
= 0;
6138 process_output_delay_count
--;
6139 p
->read_output_skip
= 0;
6145 if (would_block (errno
))
6146 /* Buffer is full. Wait, accepting input;
6147 that may allow the program
6148 to finish doing output and read more. */
6150 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6151 /* A gross hack to work around a bug in FreeBSD.
6152 In the following sequence, read(2) returns
6156 write(2) 954 bytes, get EAGAIN
6157 read(2) 1024 bytes in process_read_output
6158 read(2) 11 bytes in process_read_output
6160 That is, read(2) returns more bytes than have
6161 ever been written successfully. The 1033 bytes
6162 read are the 1022 bytes written successfully
6163 after processing (for example with CRs added if
6164 the terminal is set up that way which it is
6165 here). The same bytes will be seen again in a
6166 later read(2), without the CRs. */
6168 if (errno
== EAGAIN
)
6171 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6173 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6175 /* Put what we should have written in wait_queue. */
6176 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6177 wait_reading_process_output (0, 20 * 1000 * 1000,
6178 0, 0, Qnil
, NULL
, 0);
6179 /* Reread queue, to see what is left. */
6182 else if (errno
== EPIPE
)
6184 p
->raw_status_new
= 0;
6185 pset_status (p
, list2 (Qexit
, make_number (256)));
6186 p
->tick
= ++process_tick
;
6187 deactivate_process (proc
);
6188 error ("process %s no longer connected to pipe; closed it",
6192 /* This is a real error. */
6193 report_file_error ("Writing to process", proc
);
6199 while (!NILP (p
->write_queue
));
6202 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6204 doc
: /* Send current contents of region as input to PROCESS.
6205 PROCESS may be a process, a buffer, the name of a process or buffer, or
6206 nil, indicating the current buffer's process.
6207 Called from program, takes three arguments, PROCESS, START and END.
6208 If the region is more than 500 characters long,
6209 it is sent in several bunches. This may happen even for shorter regions.
6210 Output from processes can arrive in between bunches.
6212 If PROCESS is a non-blocking network process that hasn't been fully
6213 set up yet, this function will block until socket setup has completed. */)
6214 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6216 Lisp_Object proc
= get_process (process
);
6217 ptrdiff_t start_byte
, end_byte
;
6219 validate_region (&start
, &end
);
6221 start_byte
= CHAR_TO_BYTE (XINT (start
));
6222 end_byte
= CHAR_TO_BYTE (XINT (end
));
6224 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6225 move_gap_both (XINT (start
), start_byte
);
6227 if (NETCONN_P (proc
))
6228 wait_while_connecting (proc
);
6230 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6231 end_byte
- start_byte
, Fcurrent_buffer ());
6236 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6238 doc
: /* Send PROCESS the contents of STRING as input.
6239 PROCESS may be a process, a buffer, the name of a process or buffer, or
6240 nil, indicating the current buffer's process.
6241 If STRING is more than 500 characters long,
6242 it is sent in several bunches. This may happen even for shorter strings.
6243 Output from processes can arrive in between bunches.
6245 If PROCESS is a non-blocking network process that hasn't been fully
6246 set up yet, this function will block until socket setup has completed. */)
6247 (Lisp_Object process
, Lisp_Object string
)
6249 CHECK_STRING (string
);
6250 Lisp_Object proc
= get_process (process
);
6251 send_process (proc
, SSDATA (string
),
6252 SBYTES (string
), string
);
6256 /* Return the foreground process group for the tty/pty that
6257 the process P uses. */
6259 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6264 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6267 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6268 master side. Try the slave side. */
6269 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6273 ioctl (fd
, TIOCGPGRP
, &gid
);
6277 #endif /* defined (TIOCGPGRP ) */
6282 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6283 Sprocess_running_child_p
, 0, 1, 0,
6284 doc
: /* Return non-nil if PROCESS has given the terminal to a
6285 child. If the operating system does not make it possible to find out,
6286 return t. If we can find out, return the numeric ID of the foreground
6288 (Lisp_Object process
)
6290 /* Initialize in case ioctl doesn't exist or gives an error,
6291 in a way that will cause returning t. */
6292 Lisp_Object proc
= get_process (process
);
6293 struct Lisp_Process
*p
= XPROCESS (proc
);
6295 if (!EQ (p
->type
, Qreal
))
6296 error ("Process %s is not a subprocess",
6299 error ("Process %s is not active",
6302 pid_t gid
= emacs_get_tty_pgrp (p
);
6307 return make_number (gid
);
6311 /* Send a signal number SIGNO to PROCESS.
6312 If CURRENT_GROUP is t, that means send to the process group
6313 that currently owns the terminal being used to communicate with PROCESS.
6314 This is used for various commands in shell mode.
6315 If CURRENT_GROUP is lambda, that means send to the process group
6316 that currently owns the terminal, but only if it is NOT the shell itself.
6318 If NOMSG is false, insert signal-announcements into process's buffers
6321 If we can, we try to signal PROCESS by sending control characters
6322 down the pty. This allows us to signal inferiors who have changed
6323 their uid, for which kill would return an EPERM error. */
6326 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6330 struct Lisp_Process
*p
;
6334 proc
= get_process (process
);
6335 p
= XPROCESS (proc
);
6337 if (!EQ (p
->type
, Qreal
))
6338 error ("Process %s is not a subprocess",
6341 error ("Process %s is not active",
6345 current_group
= Qnil
;
6347 /* If we are using pgrps, get a pgrp number and make it negative. */
6348 if (NILP (current_group
))
6349 /* Send the signal to the shell's process group. */
6353 #ifdef SIGNALS_VIA_CHARACTERS
6354 /* If possible, send signals to the entire pgrp
6355 by sending an input character to it. */
6358 cc_t
*sig_char
= NULL
;
6360 tcgetattr (p
->infd
, &t
);
6365 sig_char
= &t
.c_cc
[VINTR
];
6369 sig_char
= &t
.c_cc
[VQUIT
];
6374 sig_char
= &t
.c_cc
[VSWTCH
];
6376 sig_char
= &t
.c_cc
[VSUSP
];
6381 if (sig_char
&& *sig_char
!= CDISABLE
)
6383 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6386 /* If we can't send the signal with a character,
6387 fall through and send it another way. */
6389 /* The code above may fall through if it can't
6390 handle the signal. */
6391 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6394 /* Get the current pgrp using the tty itself, if we have that.
6395 Otherwise, use the pty to get the pgrp.
6396 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6397 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6398 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6399 His patch indicates that if TIOCGPGRP returns an error, then
6400 we should just assume that p->pid is also the process group id. */
6402 gid
= emacs_get_tty_pgrp (p
);
6405 /* If we can't get the information, assume
6406 the shell owns the tty. */
6409 /* It is not clear whether anything really can set GID to -1.
6410 Perhaps on some system one of those ioctls can or could do so.
6411 Or perhaps this is vestigial. */
6414 #else /* ! defined (TIOCGPGRP) */
6415 /* Can't select pgrps on this system, so we know that
6416 the child itself heads the pgrp. */
6418 #endif /* ! defined (TIOCGPGRP) */
6420 /* If current_group is lambda, and the shell owns the terminal,
6421 don't send any signal. */
6422 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6427 if (signo
== SIGCONT
)
6429 p
->raw_status_new
= 0;
6430 pset_status (p
, Qrun
);
6431 p
->tick
= ++process_tick
;
6434 status_notify (NULL
, NULL
);
6435 redisplay_preserve_echo_area (13);
6441 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6442 We don't know whether the bug is fixed in later HP-UX versions. */
6443 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6447 /* If we don't have process groups, send the signal to the immediate
6448 subprocess. That isn't really right, but it's better than any
6449 obvious alternative. */
6450 pid_t pid
= no_pgrp
? gid
: - gid
;
6452 /* Do not kill an already-reaped process, as that could kill an
6453 innocent bystander that happens to have the same process ID. */
6455 block_child_signal (&oldset
);
6458 unblock_child_signal (&oldset
);
6461 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6462 doc
: /* Interrupt process PROCESS.
6463 PROCESS may be a process, a buffer, or the name of a process or buffer.
6464 No arg or nil means current buffer's process.
6465 Second arg CURRENT-GROUP non-nil means send signal to
6466 the current process-group of the process's controlling terminal
6467 rather than to the process's own process group.
6468 If the process is a shell, this means interrupt current subjob
6469 rather than the shell.
6471 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6472 don't send the signal. */)
6473 (Lisp_Object process
, Lisp_Object current_group
)
6475 process_send_signal (process
, SIGINT
, current_group
, 0);
6479 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6480 doc
: /* Kill process PROCESS. May be process or name of one.
6481 See function `interrupt-process' for more details on usage. */)
6482 (Lisp_Object process
, Lisp_Object current_group
)
6484 process_send_signal (process
, SIGKILL
, current_group
, 0);
6488 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6489 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6490 See function `interrupt-process' for more details on usage. */)
6491 (Lisp_Object process
, Lisp_Object current_group
)
6493 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6497 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6498 doc
: /* Stop process PROCESS. May be process or name of one.
6499 See function `interrupt-process' for more details on usage.
6500 If PROCESS is a network or serial process, inhibit handling of incoming
6502 (Lisp_Object process
, Lisp_Object current_group
)
6504 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6505 || PIPECONN_P (process
)))
6507 struct Lisp_Process
*p
;
6509 p
= XPROCESS (process
);
6510 if (NILP (p
->command
)
6513 FD_CLR (p
->infd
, &input_wait_mask
);
6514 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6516 pset_command (p
, Qt
);
6520 error ("No SIGTSTP support");
6522 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6527 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6528 doc
: /* Continue process PROCESS. May be process or name of one.
6529 See function `interrupt-process' for more details on usage.
6530 If PROCESS is a network or serial process, resume handling of incoming
6532 (Lisp_Object process
, Lisp_Object current_group
)
6534 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6535 || PIPECONN_P (process
)))
6537 struct Lisp_Process
*p
;
6539 p
= XPROCESS (process
);
6540 if (EQ (p
->command
, Qt
)
6542 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6544 FD_SET (p
->infd
, &input_wait_mask
);
6545 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6547 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6548 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6549 #else /* not WINDOWSNT */
6550 tcflush (p
->infd
, TCIFLUSH
);
6551 #endif /* not WINDOWSNT */
6553 pset_command (p
, Qnil
);
6557 process_send_signal (process
, SIGCONT
, current_group
, 0);
6559 error ("No SIGCONT support");
6564 /* Return the integer value of the signal whose abbreviation is ABBR,
6565 or a negative number if there is no such signal. */
6567 abbr_to_signal (char const *name
)
6570 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6572 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6575 for (i
= 0; i
< sizeof sigbuf
; i
++)
6577 sigbuf
[i
] = c_toupper (name
[i
]);
6579 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6585 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6586 2, 2, "sProcess (name or number): \nnSignal code: ",
6587 doc
: /* Send PROCESS the signal with code SIGCODE.
6588 PROCESS may also be a number specifying the process id of the
6589 process to signal; in this case, the process need not be a child of
6591 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6592 (Lisp_Object process
, Lisp_Object sigcode
)
6597 if (STRINGP (process
))
6599 Lisp_Object tem
= Fget_process (process
);
6602 Lisp_Object process_number
6603 = string_to_number (SSDATA (process
), 10, 1);
6604 if (NUMBERP (process_number
))
6605 tem
= process_number
;
6609 else if (!NUMBERP (process
))
6610 process
= get_process (process
);
6615 if (NUMBERP (process
))
6616 CONS_TO_INTEGER (process
, pid_t
, pid
);
6619 CHECK_PROCESS (process
);
6620 pid
= XPROCESS (process
)->pid
;
6622 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6625 if (INTEGERP (sigcode
))
6627 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6628 signo
= XINT (sigcode
);
6634 CHECK_SYMBOL (sigcode
);
6635 name
= SSDATA (SYMBOL_NAME (sigcode
));
6637 signo
= abbr_to_signal (name
);
6639 error ("Undefined signal name %s", name
);
6642 return make_number (kill (pid
, signo
));
6645 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6646 doc
: /* Make PROCESS see end-of-file in its input.
6647 EOF comes after any text already sent to it.
6648 PROCESS may be a process, a buffer, the name of a process or buffer, or
6649 nil, indicating the current buffer's process.
6650 If PROCESS is a network connection, or is a process communicating
6651 through a pipe (as opposed to a pty), then you cannot send any more
6652 text to PROCESS after you call this function.
6653 If PROCESS is a serial process, wait until all output written to the
6654 process has been transmitted to the serial port. */)
6655 (Lisp_Object process
)
6658 struct coding_system
*coding
= NULL
;
6661 proc
= get_process (process
);
6663 if (NETCONN_P (proc
))
6664 wait_while_connecting (proc
);
6666 if (DATAGRAM_CONN_P (proc
))
6670 outfd
= XPROCESS (proc
)->outfd
;
6672 coding
= proc_encode_coding_system
[outfd
];
6674 /* Make sure the process is really alive. */
6675 if (XPROCESS (proc
)->raw_status_new
)
6676 update_status (XPROCESS (proc
));
6677 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6678 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6680 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6682 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6683 send_process (proc
, "", 0, Qnil
);
6686 if (XPROCESS (proc
)->pty_flag
)
6687 send_process (proc
, "\004", 1, Qnil
);
6688 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6691 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6692 report_file_error ("Failed tcdrain", Qnil
);
6693 #endif /* not WINDOWSNT */
6694 /* Do nothing on Windows because writes are blocking. */
6698 struct Lisp_Process
*p
= XPROCESS (proc
);
6699 int old_outfd
= p
->outfd
;
6702 #ifdef HAVE_SHUTDOWN
6703 /* If this is a network connection, or socketpair is used
6704 for communication with the subprocess, call shutdown to cause EOF.
6705 (In some old system, shutdown to socketpair doesn't work.
6706 Then we just can't win.) */
6708 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6709 shutdown (old_outfd
, 1);
6711 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6712 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6714 report_file_error ("Opening null device", Qnil
);
6715 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6716 p
->outfd
= new_outfd
;
6718 if (!proc_encode_coding_system
[new_outfd
])
6719 proc_encode_coding_system
[new_outfd
]
6720 = xmalloc (sizeof (struct coding_system
));
6723 *proc_encode_coding_system
[new_outfd
]
6724 = *proc_encode_coding_system
[old_outfd
];
6725 memset (proc_encode_coding_system
[old_outfd
], 0,
6726 sizeof (struct coding_system
));
6729 setup_coding_system (p
->encode_coding_system
,
6730 proc_encode_coding_system
[new_outfd
]);
6735 /* The main Emacs thread records child processes in three places:
6737 - Vprocess_alist, for asynchronous subprocesses, which are child
6738 processes visible to Lisp.
6740 - deleted_pid_list, for child processes invisible to Lisp,
6741 typically because of delete-process. These are recorded so that
6742 the processes can be reaped when they exit, so that the operating
6743 system's process table is not cluttered by zombies.
6745 - the local variable PID in Fcall_process, call_process_cleanup and
6746 call_process_kill, for synchronous subprocesses.
6747 record_unwind_protect is used to make sure this process is not
6748 forgotten: if the user interrupts call-process and the child
6749 process refuses to exit immediately even with two C-g's,
6750 call_process_kill adds PID's contents to deleted_pid_list before
6753 The main Emacs thread invokes waitpid only on child processes that
6754 it creates and that have not been reaped. This avoid races on
6755 platforms such as GTK, where other threads create their own
6756 subprocesses which the main thread should not reap. For example,
6757 if the main thread attempted to reap an already-reaped child, it
6758 might inadvertently reap a GTK-created process that happened to
6759 have the same process ID. */
6761 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6762 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6763 keep track of its own children. GNUstep is similar. */
6765 static void dummy_handler (int sig
) {}
6766 static signal_handler_t
volatile lib_child_handler
;
6768 /* Handle a SIGCHLD signal by looking for known child processes of
6769 Emacs whose status have changed. For each one found, record its
6772 All we do is change the status; we do not run sentinels or print
6773 notifications. That is saved for the next time keyboard input is
6774 done, in order to avoid timing errors.
6776 ** WARNING: this can be called during garbage collection.
6777 Therefore, it must not be fooled by the presence of mark bits in
6780 ** USG WARNING: Although it is not obvious from the documentation
6781 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6782 signal() before executing at least one wait(), otherwise the
6783 handler will be called again, resulting in an infinite loop. The
6784 relevant portion of the documentation reads "SIGCLD signals will be
6785 queued and the signal-catching function will be continually
6786 reentered until the queue is empty". Invoking signal() causes the
6787 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6790 ** Malloc WARNING: This should never call malloc either directly or
6791 indirectly; if it does, that is a bug. */
6794 handle_child_signal (int sig
)
6796 Lisp_Object tail
, proc
;
6798 /* Find the process that signaled us, and record its status. */
6800 /* The process can have been deleted by Fdelete_process, or have
6801 been started asynchronously by Fcall_process. */
6802 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6804 bool all_pids_are_fixnums
6805 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6806 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6807 Lisp_Object head
= XCAR (tail
);
6812 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6815 if (INTEGERP (xpid
))
6816 deleted_pid
= XINT (xpid
);
6818 deleted_pid
= XFLOAT_DATA (xpid
);
6819 if (child_status_changed (deleted_pid
, 0, 0))
6821 if (STRINGP (XCDR (head
)))
6822 unlink (SSDATA (XCDR (head
)));
6823 XSETCAR (tail
, Qnil
);
6828 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6829 FOR_EACH_PROCESS (tail
, proc
)
6831 struct Lisp_Process
*p
= XPROCESS (proc
);
6835 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6837 /* Change the status of the process that was found. */
6838 p
->tick
= ++process_tick
;
6839 p
->raw_status
= status
;
6840 p
->raw_status_new
= 1;
6842 /* If process has terminated, stop waiting for its output. */
6843 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6845 bool clear_desc_flag
= 0;
6848 clear_desc_flag
= 1;
6850 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6851 if (clear_desc_flag
)
6853 FD_CLR (p
->infd
, &input_wait_mask
);
6854 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6860 lib_child_handler (sig
);
6861 #ifdef NS_IMPL_GNUSTEP
6862 /* NSTask in GNUstep sets its child handler each time it is called.
6863 So we must re-set ours. */
6864 catch_child_signal ();
6869 deliver_child_signal (int sig
)
6871 deliver_process_signal (sig
, handle_child_signal
);
6876 exec_sentinel_error_handler (Lisp_Object error_val
)
6878 cmd_error_internal (error_val
, "error in process sentinel: ");
6880 update_echo_area ();
6881 Fsleep_for (make_number (2), Qnil
);
6886 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6888 Lisp_Object sentinel
, odeactivate
;
6889 struct Lisp_Process
*p
= XPROCESS (proc
);
6890 ptrdiff_t count
= SPECPDL_INDEX ();
6891 bool outer_running_asynch_code
= running_asynch_code
;
6892 int waiting
= waiting_for_user_input_p
;
6894 if (inhibit_sentinels
)
6897 odeactivate
= Vdeactivate_mark
;
6899 Lisp_Object obuffer
, okeymap
;
6900 XSETBUFFER (obuffer
, current_buffer
);
6901 okeymap
= BVAR (current_buffer
, keymap
);
6904 /* There's no good reason to let sentinels change the current
6905 buffer, and many callers of accept-process-output, sit-for, and
6906 friends don't expect current-buffer to be changed from under them. */
6907 record_unwind_current_buffer ();
6909 sentinel
= p
->sentinel
;
6911 /* Inhibit quit so that random quits don't screw up a running filter. */
6912 specbind (Qinhibit_quit
, Qt
);
6913 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6915 /* In case we get recursively called,
6916 and we already saved the match data nonrecursively,
6917 save the same match data in safely recursive fashion. */
6918 if (outer_running_asynch_code
)
6921 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6922 restore_search_regs ();
6923 record_unwind_save_match_data ();
6924 Fset_match_data (tem
, Qt
);
6927 /* For speed, if a search happens within this code,
6928 save the match data in a special nonrecursive fashion. */
6929 running_asynch_code
= 1;
6931 internal_condition_case_1 (read_process_output_call
,
6932 list3 (sentinel
, proc
, reason
),
6933 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6934 exec_sentinel_error_handler
);
6936 /* If we saved the match data nonrecursively, restore it now. */
6937 restore_search_regs ();
6938 running_asynch_code
= outer_running_asynch_code
;
6940 Vdeactivate_mark
= odeactivate
;
6942 /* Restore waiting_for_user_input_p as it was
6943 when we were called, in case the filter clobbered it. */
6944 waiting_for_user_input_p
= waiting
;
6947 if (! EQ (Fcurrent_buffer (), obuffer
)
6948 || ! EQ (current_buffer
->keymap
, okeymap
))
6950 /* But do it only if the caller is actually going to read events.
6951 Otherwise there's no need to make him wake up, and it could
6952 cause trouble (for example it would make sit_for return). */
6953 if (waiting_for_user_input_p
== -1)
6954 record_asynch_buffer_change ();
6956 unbind_to (count
, Qnil
);
6959 /* Report all recent events of a change in process status
6960 (either run the sentinel or output a message).
6961 This is usually done while Emacs is waiting for keyboard input
6962 but can be done at other times.
6964 Return positive if any input was received from WAIT_PROC (or from
6965 any process if WAIT_PROC is null), zero if input was attempted but
6966 none received, and negative if we didn't even try. */
6969 status_notify (struct Lisp_Process
*deleting_process
,
6970 struct Lisp_Process
*wait_proc
)
6973 Lisp_Object tail
, msg
;
6974 int got_some_output
= -1;
6979 /* Set this now, so that if new processes are created by sentinels
6980 that we run, we get called again to handle their status changes. */
6981 update_tick
= process_tick
;
6983 FOR_EACH_PROCESS (tail
, proc
)
6986 register struct Lisp_Process
*p
= XPROCESS (proc
);
6988 if (p
->tick
!= p
->update_tick
)
6990 p
->update_tick
= p
->tick
;
6992 /* If process is still active, read any output that remains. */
6993 while (! EQ (p
->filter
, Qt
)
6994 && ! EQ (p
->status
, Qconnect
)
6995 && ! EQ (p
->status
, Qlisten
)
6996 /* Network or serial process not stopped: */
6997 && ! EQ (p
->command
, Qt
)
6999 && p
!= deleting_process
)
7001 int nread
= read_process_output (proc
, p
->infd
);
7002 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7003 && got_some_output
< nread
)
7004 got_some_output
= nread
;
7009 /* Get the text to use for the message. */
7010 if (p
->raw_status_new
)
7012 msg
= status_message (p
);
7014 /* If process is terminated, deactivate it or delete it. */
7016 if (CONSP (p
->status
))
7017 symbol
= XCAR (p
->status
);
7019 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7020 || EQ (symbol
, Qclosed
))
7022 if (delete_exited_processes
)
7023 remove_process (proc
);
7025 deactivate_process (proc
);
7028 /* The actions above may have further incremented p->tick.
7029 So set p->update_tick again so that an error in the sentinel will
7030 not cause this code to be run again. */
7031 p
->update_tick
= p
->tick
;
7032 /* Now output the message suitably. */
7033 exec_sentinel (proc
, msg
);
7034 if (BUFFERP (p
->buffer
))
7035 /* In case it uses %s in mode-line-format. */
7036 bset_update_mode_line (XBUFFER (p
->buffer
));
7040 return got_some_output
;
7043 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7044 Sinternal_default_process_sentinel
, 2, 2, 0,
7045 doc
: /* Function used as default sentinel for processes.
7046 This inserts a status message into the process's buffer, if there is one. */)
7047 (Lisp_Object proc
, Lisp_Object msg
)
7049 Lisp_Object buffer
, symbol
;
7050 struct Lisp_Process
*p
;
7051 CHECK_PROCESS (proc
);
7052 p
= XPROCESS (proc
);
7056 symbol
= XCAR (symbol
);
7058 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7061 struct buffer
*old
= current_buffer
;
7062 ptrdiff_t opoint
, opoint_byte
;
7063 ptrdiff_t before
, before_byte
;
7065 /* Avoid error if buffer is deleted
7066 (probably that's why the process is dead, too). */
7067 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7069 Fset_buffer (buffer
);
7071 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7072 msg
= (code_convert_string_norecord
7073 (msg
, Vlocale_coding_system
, 1));
7076 opoint_byte
= PT_BYTE
;
7077 /* Insert new output into buffer
7078 at the current end-of-output marker,
7079 thus preserving logical ordering of input and output. */
7080 if (XMARKER (p
->mark
)->buffer
)
7081 Fgoto_char (p
->mark
);
7083 SET_PT_BOTH (ZV
, ZV_BYTE
);
7086 before_byte
= PT_BYTE
;
7088 tem
= BVAR (current_buffer
, read_only
);
7089 bset_read_only (current_buffer
, Qnil
);
7090 insert_string ("\nProcess ");
7091 { /* FIXME: temporary kludge. */
7092 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7093 insert_string (" ");
7095 bset_read_only (current_buffer
, tem
);
7096 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7098 if (opoint
>= before
)
7099 SET_PT_BOTH (opoint
+ (PT
- before
),
7100 opoint_byte
+ (PT_BYTE
- before_byte
));
7102 SET_PT_BOTH (opoint
, opoint_byte
);
7104 set_buffer_internal (old
);
7110 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7111 Sset_process_coding_system
, 1, 3, 0,
7112 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7113 DECODING will be used to decode subprocess output and ENCODING to
7114 encode subprocess input. */)
7115 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7117 CHECK_PROCESS (process
);
7119 struct Lisp_Process
*p
= XPROCESS (process
);
7121 Fcheck_coding_system (decoding
);
7122 Fcheck_coding_system (encoding
);
7123 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7124 pset_decode_coding_system (p
, decoding
);
7125 pset_encode_coding_system (p
, encoding
);
7127 /* If the sockets haven't been set up yet, the final setup part of
7128 this will be called asynchronously. */
7129 if (p
->infd
< 0 || p
->outfd
< 0)
7132 setup_process_coding_systems (process
);
7137 DEFUN ("process-coding-system",
7138 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7139 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7140 (register Lisp_Object process
)
7142 CHECK_PROCESS (process
);
7143 return Fcons (XPROCESS (process
)->decode_coding_system
,
7144 XPROCESS (process
)->encode_coding_system
);
7147 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7148 Sset_process_filter_multibyte
, 2, 2, 0,
7149 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7150 If FLAG is non-nil, the filter is given multibyte strings.
7151 If FLAG is nil, the filter is given unibyte strings. In this case,
7152 all character code conversion except for end-of-line conversion is
7154 (Lisp_Object process
, Lisp_Object flag
)
7156 CHECK_PROCESS (process
);
7158 struct Lisp_Process
*p
= XPROCESS (process
);
7160 pset_decode_coding_system
7161 (p
, raw_text_coding_system (p
->decode_coding_system
));
7163 /* If the sockets haven't been set up yet, the final setup part of
7164 this will be called asynchronously. */
7165 if (p
->infd
< 0 || p
->outfd
< 0)
7168 setup_process_coding_systems (process
);
7173 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7174 Sprocess_filter_multibyte_p
, 1, 1, 0,
7175 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7176 (Lisp_Object process
)
7178 CHECK_PROCESS (process
);
7179 struct Lisp_Process
*p
= XPROCESS (process
);
7182 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7183 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7192 add_gpm_wait_descriptor (int desc
)
7194 add_keyboard_wait_descriptor (desc
);
7198 delete_gpm_wait_descriptor (int desc
)
7200 delete_keyboard_wait_descriptor (desc
);
7205 # ifdef USABLE_SIGIO
7207 /* Return true if *MASK has a bit set
7208 that corresponds to one of the keyboard input descriptors. */
7211 keyboard_bit_set (fd_set
*mask
)
7215 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7216 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7217 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7224 #else /* not subprocesses */
7226 /* Defined in msdos.c. */
7227 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7228 struct timespec
*, void *);
7230 /* Implementation of wait_reading_process_output, assuming that there
7231 are no subprocesses. Used only by the MS-DOS build.
7233 Wait for timeout to elapse and/or keyboard input to be available.
7237 If negative, gobble data immediately available but don't wait for any.
7240 an additional duration to wait, measured in nanoseconds
7241 If TIME_LIMIT is zero, then:
7242 If NSECS == 0, there is no limit.
7243 If NSECS > 0, the timeout consists of NSECS only.
7244 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7247 0 to ignore keyboard input, or
7248 1 to return when input is available, or
7249 -1 means caller will actually read the input, so don't throw to
7252 see full version for other parameters. We know that wait_proc will
7253 always be NULL, since `subprocesses' isn't defined.
7255 DO_DISPLAY means redisplay should be done to show subprocess
7256 output that arrives.
7258 Return -1 signifying we got no output and did not try. */
7261 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7263 Lisp_Object wait_for_cell
,
7264 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7267 struct timespec end_time
, timeout
;
7268 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7270 if (TYPE_MAXIMUM (time_t) < time_limit
)
7271 time_limit
= TYPE_MAXIMUM (time_t);
7273 if (time_limit
< 0 || nsecs
< 0)
7275 else if (time_limit
> 0 || nsecs
> 0)
7278 end_time
= timespec_add (current_timespec (),
7279 make_timespec (time_limit
, nsecs
));
7284 /* Turn off periodic alarms (in case they are in use)
7285 and then turn off any other atimers,
7286 because the select emulator uses alarms. */
7288 turn_on_atimers (0);
7292 bool timeout_reduced_for_timers
= false;
7293 fd_set waitchannels
;
7296 /* If calling from keyboard input, do not quit
7297 since we want to return C-g as an input character.
7298 Otherwise, do pending quit if requested. */
7302 /* Exit now if the cell we're waiting for became non-nil. */
7303 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7306 /* Compute time from now till when time limit is up. */
7307 /* Exit if already run out. */
7308 if (wait
== TIMEOUT
)
7310 struct timespec now
= current_timespec ();
7311 if (timespec_cmp (end_time
, now
) <= 0)
7313 timeout
= timespec_sub (end_time
, now
);
7316 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7318 /* If our caller will not immediately handle keyboard events,
7319 run timer events directly.
7320 (Callers that will immediately read keyboard events
7321 call timer_delay on their own.) */
7322 if (NILP (wait_for_cell
))
7324 struct timespec timer_delay
;
7328 unsigned old_timers_run
= timers_run
;
7329 timer_delay
= timer_check ();
7330 if (timers_run
!= old_timers_run
&& do_display
)
7331 /* We must retry, since a timer may have requeued itself
7332 and that could alter the time delay. */
7333 redisplay_preserve_echo_area (14);
7337 while (!detect_input_pending ());
7339 /* If there is unread keyboard input, also return. */
7341 && requeued_events_pending_p ())
7344 if (timespec_valid_p (timer_delay
))
7346 if (timespec_cmp (timer_delay
, timeout
) < 0)
7348 timeout
= timer_delay
;
7349 timeout_reduced_for_timers
= true;
7354 /* Cause C-g and alarm signals to take immediate action,
7355 and cause input available signals to zero out timeout. */
7357 set_waiting_for_input (&timeout
);
7359 /* If a frame has been newly mapped and needs updating,
7360 reprocess its display stuff. */
7361 if (frame_garbaged
&& do_display
)
7363 clear_waiting_for_input ();
7364 redisplay_preserve_echo_area (15);
7366 set_waiting_for_input (&timeout
);
7369 /* Wait till there is something to do. */
7370 FD_ZERO (&waitchannels
);
7371 if (read_kbd
&& detect_input_pending ())
7375 if (read_kbd
|| !NILP (wait_for_cell
))
7376 FD_SET (0, &waitchannels
);
7377 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7382 /* Make C-g and alarm signals set flags again. */
7383 clear_waiting_for_input ();
7385 /* If we woke up due to SIGWINCH, actually change size now. */
7386 do_pending_window_change (0);
7388 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7389 /* We waited the full specified time, so return now. */
7394 /* If the system call was interrupted, then go around the
7396 if (xerrno
== EINTR
)
7397 FD_ZERO (&waitchannels
);
7399 report_file_errno ("Failed select", Qnil
, xerrno
);
7402 /* Check for keyboard input. */
7405 && detect_input_pending_run_timers (do_display
))
7407 swallow_events (do_display
);
7408 if (detect_input_pending_run_timers (do_display
))
7412 /* If there is unread keyboard input, also return. */
7414 && requeued_events_pending_p ())
7417 /* If wait_for_cell. check for keyboard input
7418 but don't run any timers.
7419 ??? (It seems wrong to me to check for keyboard
7420 input at all when wait_for_cell, but the code
7421 has been this way since July 1994.
7422 Try changing this after version 19.31.) */
7423 if (! NILP (wait_for_cell
)
7424 && detect_input_pending ())
7426 swallow_events (do_display
);
7427 if (detect_input_pending ())
7431 /* Exit now if the cell we're waiting for became non-nil. */
7432 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7441 #endif /* not subprocesses */
7443 /* The following functions are needed even if async subprocesses are
7444 not supported. Some of them are no-op stubs in that case. */
7448 /* Add FD, which is a descriptor returned by timerfd_create,
7449 to the set of non-keyboard input descriptors. */
7452 add_timer_wait_descriptor (int fd
)
7454 FD_SET (fd
, &input_wait_mask
);
7455 FD_SET (fd
, &non_keyboard_wait_mask
);
7456 FD_SET (fd
, &non_process_wait_mask
);
7457 fd_callback_info
[fd
].func
= timerfd_callback
;
7458 fd_callback_info
[fd
].data
= NULL
;
7459 fd_callback_info
[fd
].condition
|= FOR_READ
;
7460 if (fd
> max_input_desc
)
7461 max_input_desc
= fd
;
7464 #endif /* HAVE_TIMERFD */
7466 /* If program file NAME starts with /: for quoting a magic
7467 name, remove that, preserving the multibyteness of NAME. */
7470 remove_slash_colon (Lisp_Object name
)
7473 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7474 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7475 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7479 /* Add DESC to the set of keyboard input descriptors. */
7482 add_keyboard_wait_descriptor (int desc
)
7484 #ifdef subprocesses /* Actually means "not MSDOS". */
7485 FD_SET (desc
, &input_wait_mask
);
7486 FD_SET (desc
, &non_process_wait_mask
);
7487 if (desc
> max_input_desc
)
7488 max_input_desc
= desc
;
7492 /* From now on, do not expect DESC to give keyboard input. */
7495 delete_keyboard_wait_descriptor (int desc
)
7498 FD_CLR (desc
, &input_wait_mask
);
7499 FD_CLR (desc
, &non_process_wait_mask
);
7500 delete_input_desc (desc
);
7504 /* Setup coding systems of PROCESS. */
7507 setup_process_coding_systems (Lisp_Object process
)
7510 struct Lisp_Process
*p
= XPROCESS (process
);
7512 int outch
= p
->outfd
;
7513 Lisp_Object coding_system
;
7515 if (inch
< 0 || outch
< 0)
7518 if (!proc_decode_coding_system
[inch
])
7519 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7520 coding_system
= p
->decode_coding_system
;
7521 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7522 && BUFFERP (p
->buffer
))
7524 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7525 coding_system
= raw_text_coding_system (coding_system
);
7527 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7529 if (!proc_encode_coding_system
[outch
])
7530 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7531 setup_coding_system (p
->encode_coding_system
,
7532 proc_encode_coding_system
[outch
]);
7536 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7537 doc
: /* Return the (or a) live process associated with BUFFER.
7538 BUFFER may be a buffer or the name of one.
7539 Return nil if all processes associated with BUFFER have been
7540 deleted or killed. */)
7541 (register Lisp_Object buffer
)
7544 register Lisp_Object buf
, tail
, proc
;
7546 if (NILP (buffer
)) return Qnil
;
7547 buf
= Fget_buffer (buffer
);
7548 if (NILP (buf
)) return Qnil
;
7550 FOR_EACH_PROCESS (tail
, proc
)
7551 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7553 #endif /* subprocesses */
7557 DEFUN ("process-inherit-coding-system-flag",
7558 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7560 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7561 If this flag is t, `buffer-file-coding-system' of the buffer
7562 associated with PROCESS will inherit the coding system used to decode
7563 the process output. */)
7564 (register Lisp_Object process
)
7567 CHECK_PROCESS (process
);
7568 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7570 /* Ignore the argument and return the value of
7571 inherit-process-coding-system. */
7572 return inherit_process_coding_system
? Qt
: Qnil
;
7576 /* Kill all processes associated with `buffer'.
7577 If `buffer' is nil, kill all processes. */
7580 kill_buffer_processes (Lisp_Object buffer
)
7583 Lisp_Object tail
, proc
;
7585 FOR_EACH_PROCESS (tail
, proc
)
7586 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7588 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7589 Fdelete_process (proc
);
7590 else if (XPROCESS (proc
)->infd
>= 0)
7591 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7593 #else /* subprocesses */
7594 /* Since we have no subprocesses, this does nothing. */
7595 #endif /* subprocesses */
7598 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7599 Swaiting_for_user_input_p
, 0, 0, 0,
7600 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7601 This is intended for use by asynchronous process output filters and sentinels. */)
7605 return (waiting_for_user_input_p
? Qt
: Qnil
);
7611 /* Stop reading input from keyboard sources. */
7614 hold_keyboard_input (void)
7619 /* Resume reading input from keyboard sources. */
7622 unhold_keyboard_input (void)
7627 /* Return true if keyboard input is on hold, zero otherwise. */
7630 kbd_on_hold_p (void)
7632 return kbd_is_on_hold
;
7636 /* Enumeration of and access to system processes a-la ps(1). */
7638 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7640 doc
: /* Return a list of numerical process IDs of all running processes.
7641 If this functionality is unsupported, return nil.
7643 See `process-attributes' for getting attributes of a process given its ID. */)
7646 return list_system_processes ();
7649 DEFUN ("process-attributes", Fprocess_attributes
,
7650 Sprocess_attributes
, 1, 1, 0,
7651 doc
: /* Return attributes of the process given by its PID, a number.
7653 Value is an alist where each element is a cons cell of the form
7657 If this functionality is unsupported, the value is nil.
7659 See `list-system-processes' for getting a list of all process IDs.
7661 The KEYs of the attributes that this function may return are listed
7662 below, together with the type of the associated VALUE (in parentheses).
7663 Not all platforms support all of these attributes; unsupported
7664 attributes will not appear in the returned alist.
7665 Unless explicitly indicated otherwise, numbers can have either
7666 integer or floating point values.
7668 euid -- Effective user User ID of the process (number)
7669 user -- User name corresponding to euid (string)
7670 egid -- Effective user Group ID of the process (number)
7671 group -- Group name corresponding to egid (string)
7672 comm -- Command name (executable name only) (string)
7673 state -- Process state code, such as "S", "R", or "T" (string)
7674 ppid -- Parent process ID (number)
7675 pgrp -- Process group ID (number)
7676 sess -- Session ID, i.e. process ID of session leader (number)
7677 ttname -- Controlling tty name (string)
7678 tpgid -- ID of foreground process group on the process's tty (number)
7679 minflt -- number of minor page faults (number)
7680 majflt -- number of major page faults (number)
7681 cminflt -- cumulative number of minor page faults (number)
7682 cmajflt -- cumulative number of major page faults (number)
7683 utime -- user time used by the process, in (current-time) format,
7684 which is a list of integers (HIGH LOW USEC PSEC)
7685 stime -- system time used by the process (current-time)
7686 time -- sum of utime and stime (current-time)
7687 cutime -- user time used by the process and its children (current-time)
7688 cstime -- system time used by the process and its children (current-time)
7689 ctime -- sum of cutime and cstime (current-time)
7690 pri -- priority of the process (number)
7691 nice -- nice value of the process (number)
7692 thcount -- process thread count (number)
7693 start -- time the process started (current-time)
7694 vsize -- virtual memory size of the process in KB's (number)
7695 rss -- resident set size of the process in KB's (number)
7696 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7697 pcpu -- percents of CPU time used by the process (floating-point number)
7698 pmem -- percents of total physical memory used by process's resident set
7699 (floating-point number)
7700 args -- command line which invoked the process (string). */)
7703 return system_process_attributes (pid
);
7707 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7708 Invoke this after init_process_emacs, and after glib and/or GNUstep
7709 futz with the SIGCHLD handler, but before Emacs forks any children.
7710 This function's caller should block SIGCHLD. */
7713 catch_child_signal (void)
7715 struct sigaction action
, old_action
;
7717 emacs_sigaction_init (&action
, deliver_child_signal
);
7718 block_child_signal (&oldset
);
7719 sigaction (SIGCHLD
, &action
, &old_action
);
7720 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7721 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7723 if (old_action
.sa_handler
!= deliver_child_signal
)
7725 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7727 : old_action
.sa_handler
);
7728 unblock_child_signal (&oldset
);
7730 #endif /* subprocesses */
7733 /* This is not called "init_process" because that is the name of a
7734 Mach system call, so it would cause problems on Darwin systems. */
7736 init_process_emacs (int sockfd
)
7741 inhibit_sentinels
= 0;
7744 if (! noninteractive
|| initialized
)
7747 #if defined HAVE_GLIB && !defined WINDOWSNT
7748 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7749 this should always fail, but is enough to initialize glib's
7750 private SIGCHLD handler, allowing catch_child_signal to copy
7751 it into lib_child_handler. */
7752 g_source_unref (g_child_watch_source_new (getpid ()));
7754 catch_child_signal ();
7757 FD_ZERO (&input_wait_mask
);
7758 FD_ZERO (&non_keyboard_wait_mask
);
7759 FD_ZERO (&non_process_wait_mask
);
7760 FD_ZERO (&write_mask
);
7761 max_process_desc
= max_input_desc
= -1;
7762 external_sock_fd
= sockfd
;
7763 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7765 FD_ZERO (&connect_wait_mask
);
7766 num_pending_connects
= 0;
7768 process_output_delay_count
= 0;
7769 process_output_skip
= 0;
7771 /* Don't do this, it caused infinite select loops. The display
7772 method should call add_keyboard_wait_descriptor on stdin if it
7775 FD_SET (0, &input_wait_mask
);
7778 Vprocess_alist
= Qnil
;
7779 deleted_pid_list
= Qnil
;
7780 for (i
= 0; i
< FD_SETSIZE
; i
++)
7782 chan_process
[i
] = Qnil
;
7783 proc_buffered_char
[i
] = -1;
7785 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7786 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7787 #ifdef DATAGRAM_SOCKETS
7788 memset (datagram_address
, 0, sizeof datagram_address
);
7791 #if defined (DARWIN_OS)
7792 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7793 processes. As such, we only change the default value. */
7796 char const *release
= (STRINGP (Voperating_system_release
)
7797 ? SSDATA (Voperating_system_release
)
7799 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7800 Vprocess_connection_type
= Qnil
;
7804 #endif /* subprocesses */
7809 syms_of_process (void)
7813 DEFSYM (Qprocessp
, "processp");
7814 DEFSYM (Qrun
, "run");
7815 DEFSYM (Qstop
, "stop");
7816 DEFSYM (Qsignal
, "signal");
7818 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7821 DEFSYM (Qopen
, "open");
7822 DEFSYM (Qclosed
, "closed");
7823 DEFSYM (Qconnect
, "connect");
7824 DEFSYM (Qfailed
, "failed");
7825 DEFSYM (Qlisten
, "listen");
7826 DEFSYM (Qlocal
, "local");
7827 DEFSYM (Qipv4
, "ipv4");
7829 DEFSYM (Qipv6
, "ipv6");
7831 DEFSYM (Qdatagram
, "datagram");
7832 DEFSYM (Qseqpacket
, "seqpacket");
7834 DEFSYM (QCport
, ":port");
7835 DEFSYM (QCspeed
, ":speed");
7836 DEFSYM (QCprocess
, ":process");
7838 DEFSYM (QCbytesize
, ":bytesize");
7839 DEFSYM (QCstopbits
, ":stopbits");
7840 DEFSYM (QCparity
, ":parity");
7841 DEFSYM (Qodd
, "odd");
7842 DEFSYM (Qeven
, "even");
7843 DEFSYM (QCflowcontrol
, ":flowcontrol");
7846 DEFSYM (QCsummary
, ":summary");
7848 DEFSYM (Qreal
, "real");
7849 DEFSYM (Qnetwork
, "network");
7850 DEFSYM (Qserial
, "serial");
7851 DEFSYM (Qpipe
, "pipe");
7852 DEFSYM (QCbuffer
, ":buffer");
7853 DEFSYM (QChost
, ":host");
7854 DEFSYM (QCservice
, ":service");
7855 DEFSYM (QClocal
, ":local");
7856 DEFSYM (QCremote
, ":remote");
7857 DEFSYM (QCcoding
, ":coding");
7858 DEFSYM (QCserver
, ":server");
7859 DEFSYM (QCnowait
, ":nowait");
7860 DEFSYM (QCsentinel
, ":sentinel");
7861 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7862 DEFSYM (QCtls_parameters
, ":tls-parameters");
7863 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7864 DEFSYM (QClog
, ":log");
7865 DEFSYM (QCnoquery
, ":noquery");
7866 DEFSYM (QCstop
, ":stop");
7867 DEFSYM (QCplist
, ":plist");
7868 DEFSYM (QCcommand
, ":command");
7869 DEFSYM (QCconnection_type
, ":connection-type");
7870 DEFSYM (QCstderr
, ":stderr");
7871 DEFSYM (Qpty
, "pty");
7872 DEFSYM (Qpipe
, "pipe");
7874 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7876 staticpro (&Vprocess_alist
);
7877 staticpro (&deleted_pid_list
);
7879 #endif /* subprocesses */
7881 DEFSYM (QCname
, ":name");
7882 DEFSYM (QCtype
, ":type");
7884 DEFSYM (Qeuid
, "euid");
7885 DEFSYM (Qegid
, "egid");
7886 DEFSYM (Quser
, "user");
7887 DEFSYM (Qgroup
, "group");
7888 DEFSYM (Qcomm
, "comm");
7889 DEFSYM (Qstate
, "state");
7890 DEFSYM (Qppid
, "ppid");
7891 DEFSYM (Qpgrp
, "pgrp");
7892 DEFSYM (Qsess
, "sess");
7893 DEFSYM (Qttname
, "ttname");
7894 DEFSYM (Qtpgid
, "tpgid");
7895 DEFSYM (Qminflt
, "minflt");
7896 DEFSYM (Qmajflt
, "majflt");
7897 DEFSYM (Qcminflt
, "cminflt");
7898 DEFSYM (Qcmajflt
, "cmajflt");
7899 DEFSYM (Qutime
, "utime");
7900 DEFSYM (Qstime
, "stime");
7901 DEFSYM (Qtime
, "time");
7902 DEFSYM (Qcutime
, "cutime");
7903 DEFSYM (Qcstime
, "cstime");
7904 DEFSYM (Qctime
, "ctime");
7906 DEFSYM (Qinternal_default_process_sentinel
,
7907 "internal-default-process-sentinel");
7908 DEFSYM (Qinternal_default_process_filter
,
7909 "internal-default-process-filter");
7911 DEFSYM (Qpri
, "pri");
7912 DEFSYM (Qnice
, "nice");
7913 DEFSYM (Qthcount
, "thcount");
7914 DEFSYM (Qstart
, "start");
7915 DEFSYM (Qvsize
, "vsize");
7916 DEFSYM (Qrss
, "rss");
7917 DEFSYM (Qetime
, "etime");
7918 DEFSYM (Qpcpu
, "pcpu");
7919 DEFSYM (Qpmem
, "pmem");
7920 DEFSYM (Qargs
, "args");
7922 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7923 doc
: /* Non-nil means delete processes immediately when they exit.
7924 A value of nil means don't delete them until `list-processes' is run. */);
7926 delete_exited_processes
= 1;
7929 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7930 doc
: /* Control type of device used to communicate with subprocesses.
7931 Values are nil to use a pipe, or t or `pty' to use a pty.
7932 The value has no effect if the system has no ptys or if all ptys are busy:
7933 then a pipe is used in any case.
7934 The value takes effect when `start-process' is called. */);
7935 Vprocess_connection_type
= Qt
;
7937 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7938 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7939 On some systems, when Emacs reads the output from a subprocess, the output data
7940 is read in very small blocks, potentially resulting in very poor performance.
7941 This behavior can be remedied to some extent by setting this variable to a
7942 non-nil value, as it will automatically delay reading from such processes, to
7943 allow them to produce more output before Emacs tries to read it.
7944 If the value is t, the delay is reset after each write to the process; any other
7945 non-nil value means that the delay is not reset on write.
7946 The variable takes effect when `start-process' is called. */);
7947 Vprocess_adaptive_read_buffering
= Qt
;
7949 defsubr (&Sprocessp
);
7950 defsubr (&Sget_process
);
7951 defsubr (&Sdelete_process
);
7952 defsubr (&Sprocess_status
);
7953 defsubr (&Sprocess_exit_status
);
7954 defsubr (&Sprocess_id
);
7955 defsubr (&Sprocess_name
);
7956 defsubr (&Sprocess_tty_name
);
7957 defsubr (&Sprocess_command
);
7958 defsubr (&Sset_process_buffer
);
7959 defsubr (&Sprocess_buffer
);
7960 defsubr (&Sprocess_mark
);
7961 defsubr (&Sset_process_filter
);
7962 defsubr (&Sprocess_filter
);
7963 defsubr (&Sset_process_sentinel
);
7964 defsubr (&Sprocess_sentinel
);
7965 defsubr (&Sset_process_window_size
);
7966 defsubr (&Sset_process_inherit_coding_system_flag
);
7967 defsubr (&Sset_process_query_on_exit_flag
);
7968 defsubr (&Sprocess_query_on_exit_flag
);
7969 defsubr (&Sprocess_contact
);
7970 defsubr (&Sprocess_plist
);
7971 defsubr (&Sset_process_plist
);
7972 defsubr (&Sprocess_list
);
7973 defsubr (&Smake_process
);
7974 defsubr (&Smake_pipe_process
);
7975 defsubr (&Sserial_process_configure
);
7976 defsubr (&Smake_serial_process
);
7977 defsubr (&Sset_network_process_option
);
7978 defsubr (&Smake_network_process
);
7979 defsubr (&Sformat_network_address
);
7980 defsubr (&Snetwork_interface_list
);
7981 defsubr (&Snetwork_interface_info
);
7982 #ifdef DATAGRAM_SOCKETS
7983 defsubr (&Sprocess_datagram_address
);
7984 defsubr (&Sset_process_datagram_address
);
7986 defsubr (&Saccept_process_output
);
7987 defsubr (&Sprocess_send_region
);
7988 defsubr (&Sprocess_send_string
);
7989 defsubr (&Sinterrupt_process
);
7990 defsubr (&Skill_process
);
7991 defsubr (&Squit_process
);
7992 defsubr (&Sstop_process
);
7993 defsubr (&Scontinue_process
);
7994 defsubr (&Sprocess_running_child_p
);
7995 defsubr (&Sprocess_send_eof
);
7996 defsubr (&Ssignal_process
);
7997 defsubr (&Swaiting_for_user_input_p
);
7998 defsubr (&Sprocess_type
);
7999 defsubr (&Sinternal_default_process_sentinel
);
8000 defsubr (&Sinternal_default_process_filter
);
8001 defsubr (&Sset_process_coding_system
);
8002 defsubr (&Sprocess_coding_system
);
8003 defsubr (&Sset_process_filter_multibyte
);
8004 defsubr (&Sprocess_filter_multibyte_p
);
8007 Lisp_Object subfeatures
= Qnil
;
8008 const struct socket_options
*sopt
;
8010 #define ADD_SUBFEATURE(key, val) \
8011 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8013 ADD_SUBFEATURE (QCnowait
, Qt
);
8014 #ifdef DATAGRAM_SOCKETS
8015 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8017 #ifdef HAVE_SEQPACKET
8018 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8020 #ifdef HAVE_LOCAL_SOCKETS
8021 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8023 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8025 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8027 #ifdef HAVE_GETSOCKNAME
8028 ADD_SUBFEATURE (QCservice
, Qt
);
8030 ADD_SUBFEATURE (QCserver
, Qt
);
8032 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8033 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8035 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8038 #endif /* subprocesses */
8040 defsubr (&Sget_buffer_process
);
8041 defsubr (&Sprocess_inherit_coding_system_flag
);
8042 defsubr (&Slist_system_processes
);
8043 defsubr (&Sprocess_attributes
);