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_CHAN_P(chan) (0)
320 #define DATAGRAM_CONN_P(proc) (0)
323 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
324 a `for' loop which iterates over processes from Vprocess_alist. */
326 #define FOR_EACH_PROCESS(list_var, proc_var) \
327 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
329 /* These setters are used only in this file, so they can be private. */
331 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
336 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
341 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
343 p
->decode_coding_system
= val
;
346 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
348 p
->decoding_buf
= val
;
351 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
353 p
->encode_coding_system
= val
;
356 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
358 p
->encoding_buf
= val
;
361 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
363 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
366 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
371 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
376 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
381 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
386 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
388 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
391 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
396 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
401 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
403 p
->write_queue
= val
;
406 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
413 make_lisp_proc (struct Lisp_Process
*p
)
415 return make_lisp_ptr (p
, Lisp_Vectorlike
);
418 static struct fd_callback_data
424 int condition
; /* Mask of the defines above. */
425 } fd_callback_info
[FD_SETSIZE
];
428 /* Add a file descriptor FD to be monitored for when read is possible.
429 When read is possible, call FUNC with argument DATA. */
432 add_read_fd (int fd
, fd_callback func
, void *data
)
434 add_keyboard_wait_descriptor (fd
);
436 fd_callback_info
[fd
].func
= func
;
437 fd_callback_info
[fd
].data
= data
;
438 fd_callback_info
[fd
].condition
|= FOR_READ
;
441 /* Stop monitoring file descriptor FD for when read is possible. */
444 delete_read_fd (int fd
)
446 delete_keyboard_wait_descriptor (fd
);
448 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
449 if (fd_callback_info
[fd
].condition
== 0)
451 fd_callback_info
[fd
].func
= 0;
452 fd_callback_info
[fd
].data
= 0;
456 /* Add a file descriptor FD to be monitored for when write is possible.
457 When write is possible, call FUNC with argument DATA. */
460 add_write_fd (int fd
, fd_callback func
, void *data
)
462 FD_SET (fd
, &write_mask
);
463 if (fd
> max_input_desc
)
466 fd_callback_info
[fd
].func
= func
;
467 fd_callback_info
[fd
].data
= data
;
468 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
471 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
474 delete_input_desc (int fd
)
476 if (fd
== max_input_desc
)
480 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
481 || FD_ISSET (fd
, &write_mask
)));
487 /* Stop monitoring file descriptor FD for when write is possible. */
490 delete_write_fd (int fd
)
492 FD_CLR (fd
, &write_mask
);
493 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
494 if (fd_callback_info
[fd
].condition
== 0)
496 fd_callback_info
[fd
].func
= 0;
497 fd_callback_info
[fd
].data
= 0;
498 delete_input_desc (fd
);
503 /* Compute the Lisp form of the process status, p->status, from
504 the numeric status that was returned by `wait'. */
506 static Lisp_Object
status_convert (int);
509 update_status (struct Lisp_Process
*p
)
511 eassert (p
->raw_status_new
);
512 pset_status (p
, status_convert (p
->raw_status
));
513 p
->raw_status_new
= 0;
516 /* Convert a process status word in Unix format to
517 the list that we use internally. */
520 status_convert (int w
)
523 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
524 else if (WIFEXITED (w
))
525 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
526 WCOREDUMP (w
) ? Qt
: Qnil
));
527 else if (WIFSIGNALED (w
))
528 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
529 WCOREDUMP (w
) ? Qt
: Qnil
));
534 /* Given a status-list, extract the three pieces of information
535 and store them individually through the three pointers. */
538 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
552 *code
= XFASTINT (XCAR (tem
));
554 *coredump
= !NILP (tem
);
558 /* Return a string describing a process status list. */
561 status_message (struct Lisp_Process
*p
)
563 Lisp_Object status
= p
->status
;
569 decode_status (status
, &symbol
, &code
, &coredump
);
571 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
574 synchronize_system_messages_locale ();
575 signame
= strsignal (code
);
577 string
= build_string ("unknown");
582 string
= build_unibyte_string (signame
);
583 if (! NILP (Vlocale_coding_system
))
584 string
= (code_convert_string_norecord
585 (string
, Vlocale_coding_system
, 0));
586 c1
= STRING_CHAR (SDATA (string
));
589 Faset (string
, make_number (0), make_number (c2
));
591 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
592 return concat2 (string
, suffix
);
594 else if (EQ (symbol
, Qexit
))
597 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
599 return build_string ("finished\n");
600 AUTO_STRING (prefix
, "exited abnormally with code ");
601 string
= Fnumber_to_string (make_number (code
));
602 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
603 return concat3 (prefix
, string
, suffix
);
605 else if (EQ (symbol
, Qfailed
))
607 AUTO_STRING (prefix
, "failed with code ");
608 string
= Fnumber_to_string (make_number (code
));
609 AUTO_STRING (suffix
, "\n");
610 return concat3 (prefix
, string
, suffix
);
613 return Fcopy_sequence (Fsymbol_name (symbol
));
616 enum { PTY_NAME_SIZE
= 24 };
618 /* Open an available pty, returning a file descriptor.
619 Store into PTY_NAME the file name of the terminal corresponding to the pty.
620 Return -1 on failure. */
623 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
632 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
633 for (i
= 0; i
< 16; i
++)
636 #ifdef PTY_NAME_SPRINTF
639 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
640 #endif /* no PTY_NAME_SPRINTF */
644 #else /* no PTY_OPEN */
645 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
646 #endif /* no PTY_OPEN */
650 #ifdef PTY_TTY_NAME_SPRINTF
653 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
654 #endif /* no PTY_TTY_NAME_SPRINTF */
656 /* Set FD's close-on-exec flag. This is needed even if
657 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
658 doesn't require support for that combination.
659 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
660 doesn't work if the close-on-exec flag is set (Bug#20555).
661 Multithreaded platforms where posix_openpt ignores
662 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
663 have a race condition between the PTY_OPEN and here. */
664 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
666 /* Check to make certain that both sides are available.
667 This avoids a nasty yet stupid bug in rlogins. */
668 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
681 #endif /* HAVE_PTYS */
685 /* Allocate basically initialized process. */
687 static struct Lisp_Process
*
688 allocate_process (void)
690 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
694 make_process (Lisp_Object name
)
696 struct Lisp_Process
*p
= allocate_process ();
697 /* Initialize Lisp data. Note that allocate_process initializes all
698 Lisp data to nil, so do it only for slots which should not be nil. */
699 pset_status (p
, Qrun
);
700 pset_mark (p
, Fmake_marker ());
702 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
703 non-Lisp data, so do it only for slots which should not be zero. */
706 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
710 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
711 p
->gnutls_boot_parameters
= Qnil
;
714 /* If name is already in use, modify it until it is unused. */
716 Lisp_Object name1
= name
;
717 for (printmax_t i
= 1; ; i
++)
719 Lisp_Object tem
= Fget_process (name1
);
722 char const suffix_fmt
[] = "<%"pMd
">";
723 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
724 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
725 name1
= concat2 (name
, lsuffix
);
729 pset_sentinel (p
, Qinternal_default_process_sentinel
);
730 pset_filter (p
, Qinternal_default_process_filter
);
732 XSETPROCESS (val
, p
);
733 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
738 remove_process (register Lisp_Object proc
)
740 register Lisp_Object pair
;
742 pair
= Frassq (proc
, Vprocess_alist
);
743 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
745 deactivate_process (proc
);
748 #ifdef HAVE_GETADDRINFO_A
750 free_dns_request (Lisp_Object proc
)
752 struct Lisp_Process
*p
= XPROCESS (proc
);
754 if (p
->dns_request
->ar_result
)
755 freeaddrinfo (p
->dns_request
->ar_result
);
756 xfree (p
->dns_request
);
757 p
->dns_request
= NULL
;
762 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
763 doc
: /* Return t if OBJECT is a process. */)
766 return PROCESSP (object
) ? Qt
: Qnil
;
769 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
770 doc
: /* Return the process named NAME, or nil if there is none. */)
771 (register Lisp_Object name
)
776 return Fcdr (Fassoc (name
, Vprocess_alist
));
779 /* This is how commands for the user decode process arguments. It
780 accepts a process, a process name, a buffer, a buffer name, or nil.
781 Buffers denote the first process in the buffer, and nil denotes the
785 get_process (register Lisp_Object name
)
787 register Lisp_Object proc
, obj
;
790 obj
= Fget_process (name
);
792 obj
= Fget_buffer (name
);
794 error ("Process %s does not exist", SDATA (name
));
796 else if (NILP (name
))
797 obj
= Fcurrent_buffer ();
801 /* Now obj should be either a buffer object or a process object. */
804 if (NILP (BVAR (XBUFFER (obj
), name
)))
805 error ("Attempt to get process for a dead buffer");
806 proc
= Fget_buffer_process (obj
);
808 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
819 /* Fdelete_process promises to immediately forget about the process, but in
820 reality, Emacs needs to remember those processes until they have been
821 treated by the SIGCHLD handler and waitpid has been invoked on them;
822 otherwise they might fill up the kernel's process table.
824 Some processes created by call-process are also put onto this list.
826 Members of this list are (process-ID . filename) pairs. The
827 process-ID is a number; the filename, if a string, is a file that
828 needs to be removed after the process exits. */
829 static Lisp_Object deleted_pid_list
;
832 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
834 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
835 /* GC treated elements set to nil. */
836 Fdelq (Qnil
, deleted_pid_list
));
840 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
841 doc
: /* Delete PROCESS: kill it and forget about it immediately.
842 PROCESS may be a process, a buffer, the name of a process or buffer, or
843 nil, indicating the current buffer's process. */)
844 (register Lisp_Object process
)
846 register struct Lisp_Process
*p
;
848 process
= get_process (process
);
849 p
= XPROCESS (process
);
851 #ifdef HAVE_GETADDRINFO_A
854 /* Cancel the request. Unless shutting down, wait until
855 completion. Free the request if completely canceled. */
857 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
858 if (!canceled
&& !inhibit_sentinels
)
860 struct gaicb
const *req
= p
->dns_request
;
861 while (gai_suspend (&req
, 1, NULL
) != 0)
866 free_dns_request (process
);
870 p
->raw_status_new
= 0;
871 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
873 pset_status (p
, list2 (Qexit
, make_number (0)));
874 p
->tick
= ++process_tick
;
875 status_notify (p
, NULL
);
876 redisplay_preserve_echo_area (13);
881 record_kill_process (p
, Qnil
);
885 /* Update P's status, since record_kill_process will make the
886 SIGCHLD handler update deleted_pid_list, not *P. */
888 if (p
->raw_status_new
)
890 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
891 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
892 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
894 p
->tick
= ++process_tick
;
895 status_notify (p
, NULL
);
896 redisplay_preserve_echo_area (13);
899 remove_process (process
);
903 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
904 doc
: /* Return the status of PROCESS.
905 The returned value is one of the following symbols:
906 run -- for a process that is running.
907 stop -- for a process stopped but continuable.
908 exit -- for a process that has exited.
909 signal -- for a process that has got a fatal signal.
910 open -- for a network stream connection that is open.
911 listen -- for a network stream server that is listening.
912 closed -- for a network stream connection that is closed.
913 connect -- when waiting for a non-blocking connection to complete.
914 failed -- when a non-blocking connection has failed.
915 nil -- if arg is a process name and no such process exists.
916 PROCESS may be a process, a buffer, the name of a process, or
917 nil, indicating the current buffer's process. */)
918 (register Lisp_Object process
)
920 register struct Lisp_Process
*p
;
921 register Lisp_Object status
;
923 if (STRINGP (process
))
924 process
= Fget_process (process
);
926 process
= get_process (process
);
931 p
= XPROCESS (process
);
932 if (p
->raw_status_new
)
936 status
= XCAR (status
);
937 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
939 if (EQ (status
, Qexit
))
941 else if (EQ (p
->command
, Qt
))
943 else if (EQ (status
, Qrun
))
949 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
951 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
952 If PROCESS has not yet exited or died, return 0. */)
953 (register Lisp_Object process
)
955 CHECK_PROCESS (process
);
956 if (XPROCESS (process
)->raw_status_new
)
957 update_status (XPROCESS (process
));
958 if (CONSP (XPROCESS (process
)->status
))
959 return XCAR (XCDR (XPROCESS (process
)->status
));
960 return make_number (0);
963 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
964 doc
: /* Return the process id of PROCESS.
965 This is the pid of the external process which PROCESS uses or talks to.
966 For a network connection, this value is nil. */)
967 (register Lisp_Object process
)
971 CHECK_PROCESS (process
);
972 pid
= XPROCESS (process
)->pid
;
973 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
976 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
977 doc
: /* Return the name of PROCESS, as a string.
978 This is the name of the program invoked in PROCESS,
979 possibly modified to make it unique among process names. */)
980 (register Lisp_Object process
)
982 CHECK_PROCESS (process
);
983 return XPROCESS (process
)->name
;
986 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
987 doc
: /* Return the command that was executed to start PROCESS.
988 This is a list of strings, the first string being the program executed
989 and the rest of the strings being the arguments given to it.
990 For a network or serial process, this is nil (process is running) or t
991 \(process is stopped). */)
992 (register Lisp_Object process
)
994 CHECK_PROCESS (process
);
995 return XPROCESS (process
)->command
;
998 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
999 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1000 This is the terminal that the process itself reads and writes on,
1001 not the name of the pty that Emacs uses to talk with that terminal. */)
1002 (register Lisp_Object process
)
1004 CHECK_PROCESS (process
);
1005 return XPROCESS (process
)->tty_name
;
1008 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1010 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1012 (register Lisp_Object process
, Lisp_Object buffer
)
1014 struct Lisp_Process
*p
;
1016 CHECK_PROCESS (process
);
1018 CHECK_BUFFER (buffer
);
1019 p
= XPROCESS (process
);
1020 pset_buffer (p
, buffer
);
1021 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1022 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1023 setup_process_coding_systems (process
);
1027 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1029 doc
: /* Return the buffer PROCESS is associated with.
1030 The default process filter inserts output from PROCESS into this buffer. */)
1031 (register Lisp_Object process
)
1033 CHECK_PROCESS (process
);
1034 return XPROCESS (process
)->buffer
;
1037 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1039 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1040 (register Lisp_Object process
)
1042 CHECK_PROCESS (process
);
1043 return XPROCESS (process
)->mark
;
1047 set_process_filter_masks (struct Lisp_Process
*p
)
1049 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1051 FD_CLR (p
->infd
, &input_wait_mask
);
1052 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1054 else if (EQ (p
->filter
, Qt
)
1055 /* Network or serial process not stopped: */
1056 && !EQ (p
->command
, Qt
))
1058 FD_SET (p
->infd
, &input_wait_mask
);
1059 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1063 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1065 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1066 A value of t means stop accepting output from the process.
1068 When a process has a non-default filter, its buffer is not used for output.
1069 Instead, each time it does output, the entire string of output is
1070 passed to the filter.
1072 The filter gets two arguments: the process and the string of output.
1073 The string argument is normally a multibyte string, except:
1074 - if the process's input coding system is no-conversion or raw-text,
1075 it is a unibyte string (the non-converted input), or else
1076 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1077 string (the result of converting the decoded input multibyte
1078 string to unibyte with `string-make-unibyte'). */)
1079 (Lisp_Object process
, Lisp_Object filter
)
1081 CHECK_PROCESS (process
);
1082 struct Lisp_Process
*p
= XPROCESS (process
);
1084 /* Don't signal an error if the process's input file descriptor
1085 is closed. This could make debugging Lisp more difficult,
1086 for example when doing something like
1088 (setq process (start-process ...))
1090 (set-process-filter process ...) */
1093 filter
= Qinternal_default_process_filter
;
1095 pset_filter (p
, filter
);
1098 set_process_filter_masks (p
);
1100 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1101 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1102 setup_process_coding_systems (process
);
1106 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1108 doc
: /* Return the filter function of PROCESS.
1109 See `set-process-filter' for more info on filter functions. */)
1110 (register Lisp_Object process
)
1112 CHECK_PROCESS (process
);
1113 return XPROCESS (process
)->filter
;
1116 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1118 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1119 The sentinel is called as a function when the process changes state.
1120 It gets two arguments: the process, and a string describing the change. */)
1121 (register Lisp_Object process
, Lisp_Object sentinel
)
1123 struct Lisp_Process
*p
;
1125 CHECK_PROCESS (process
);
1126 p
= XPROCESS (process
);
1128 if (NILP (sentinel
))
1129 sentinel
= Qinternal_default_process_sentinel
;
1131 pset_sentinel (p
, sentinel
);
1132 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1133 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1137 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1139 doc
: /* Return the sentinel of PROCESS.
1140 See `set-process-sentinel' for more info on sentinels. */)
1141 (register Lisp_Object process
)
1143 CHECK_PROCESS (process
);
1144 return XPROCESS (process
)->sentinel
;
1147 DEFUN ("set-process-window-size", Fset_process_window_size
,
1148 Sset_process_window_size
, 3, 3, 0,
1149 doc
: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1150 Value is t if PROCESS was successfully told about the window size,
1152 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1154 CHECK_PROCESS (process
);
1156 /* All known platforms store window sizes as 'unsigned short'. */
1157 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1158 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1160 if (NETCONN_P (process
)
1161 || XPROCESS (process
)->infd
< 0
1162 || (set_window_size (XPROCESS (process
)->infd
,
1163 XINT (height
), XINT (width
))
1170 DEFUN ("set-process-inherit-coding-system-flag",
1171 Fset_process_inherit_coding_system_flag
,
1172 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1173 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1174 If the second argument FLAG is non-nil, then the variable
1175 `buffer-file-coding-system' of the buffer associated with PROCESS
1176 will be bound to the value of the coding system used to decode
1179 This is useful when the coding system specified for the process buffer
1180 leaves either the character code conversion or the end-of-line conversion
1181 unspecified, or if the coding system used to decode the process output
1182 is more appropriate for saving the process buffer.
1184 Binding the variable `inherit-process-coding-system' to non-nil before
1185 starting the process is an alternative way of setting the inherit flag
1186 for the process which will run.
1188 This function returns FLAG. */)
1189 (register Lisp_Object process
, Lisp_Object flag
)
1191 CHECK_PROCESS (process
);
1192 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1196 DEFUN ("set-process-query-on-exit-flag",
1197 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1199 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1200 If the second argument FLAG is non-nil, Emacs will query the user before
1201 exiting or killing a buffer if PROCESS is running. This function
1203 (register Lisp_Object process
, Lisp_Object flag
)
1205 CHECK_PROCESS (process
);
1206 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1210 DEFUN ("process-query-on-exit-flag",
1211 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1213 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1214 (register Lisp_Object process
)
1216 CHECK_PROCESS (process
);
1217 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1220 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1222 doc
: /* Return the contact info of PROCESS; t for a real child.
1223 For a network or serial connection, the value depends on the optional
1224 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1225 SERVICE) for a network connection or (PORT SPEED) for a serial
1226 connection. If KEY is t, the complete contact information for the
1227 connection is returned, else the specific value for the keyword KEY is
1228 returned. See `make-network-process' or `make-serial-process' for a
1230 If PROCESS is a non-blocking network process that hasn't been fully
1231 set up yet, this function will block until socket setup has completed. */)
1232 (Lisp_Object process
, Lisp_Object key
)
1234 Lisp_Object contact
;
1236 CHECK_PROCESS (process
);
1237 contact
= XPROCESS (process
)->childp
;
1239 #ifdef DATAGRAM_SOCKETS
1241 if (NETCONN_P (process
))
1242 wait_for_socket_fds (process
, "process-contact");
1244 if (DATAGRAM_CONN_P (process
)
1245 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1246 contact
= Fplist_put (contact
, QCremote
,
1247 Fprocess_datagram_address (process
));
1250 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1253 if (NILP (key
) && NETCONN_P (process
))
1254 return list2 (Fplist_get (contact
, QChost
),
1255 Fplist_get (contact
, QCservice
));
1256 if (NILP (key
) && SERIALCONN_P (process
))
1257 return list2 (Fplist_get (contact
, QCport
),
1258 Fplist_get (contact
, QCspeed
));
1259 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1260 if the pipe process is useful for purposes other than receiving
1262 if (NILP (key
) && PIPECONN_P (process
))
1264 return Fplist_get (contact
, key
);
1267 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1269 doc
: /* Return the plist of PROCESS. */)
1270 (register Lisp_Object process
)
1272 CHECK_PROCESS (process
);
1273 return XPROCESS (process
)->plist
;
1276 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1278 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1279 (Lisp_Object process
, Lisp_Object plist
)
1281 CHECK_PROCESS (process
);
1284 pset_plist (XPROCESS (process
), plist
);
1288 #if 0 /* Turned off because we don't currently record this info
1289 in the process. Perhaps add it. */
1290 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1291 doc
: /* Return the connection type of PROCESS.
1292 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1293 a socket connection. */)
1294 (Lisp_Object process
)
1296 return XPROCESS (process
)->type
;
1300 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1301 doc
: /* Return the connection type of PROCESS.
1302 The value is either the symbol `real', `network', or `serial'.
1303 PROCESS may be a process, a buffer, the name of a process or buffer, or
1304 nil, indicating the current buffer's process. */)
1305 (Lisp_Object process
)
1308 proc
= get_process (process
);
1309 return XPROCESS (proc
)->type
;
1312 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1314 doc
: /* Convert network ADDRESS from internal format to a string.
1315 A 4 or 5 element vector represents an IPv4 address (with port number).
1316 An 8 or 9 element vector represents an IPv6 address (with port number).
1317 If optional second argument OMIT-PORT is non-nil, don't include a port
1318 number in the string, even when present in ADDRESS.
1319 Return nil if format of ADDRESS is invalid. */)
1320 (Lisp_Object address
, Lisp_Object omit_port
)
1325 if (STRINGP (address
)) /* AF_LOCAL */
1328 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1330 register struct Lisp_Vector
*p
= XVECTOR (address
);
1331 ptrdiff_t size
= p
->header
.size
;
1332 Lisp_Object args
[10];
1336 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1338 format
= "%d.%d.%d.%d";
1343 format
= "%d.%d.%d.%d:%d";
1346 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1348 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1353 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1359 AUTO_STRING (format_obj
, format
);
1360 args
[0] = format_obj
;
1362 for (i
= 0; i
< nargs
; i
++)
1364 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1367 if (nargs
<= 5 /* IPv4 */
1368 && i
< 4 /* host, not port */
1369 && XINT (p
->contents
[i
]) > 255)
1372 args
[i
+ 1] = p
->contents
[i
];
1375 return Fformat (nargs
+ 1, args
);
1378 if (CONSP (address
))
1380 AUTO_STRING (format
, "<Family %d>");
1381 return CALLN (Fformat
, format
, Fcar (address
));
1387 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1388 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1391 return Fmapcar (Qcdr
, Vprocess_alist
);
1394 /* Starting asynchronous inferior processes. */
1396 static void start_process_unwind (Lisp_Object proc
);
1398 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1399 doc
: /* Start a program in a subprocess. Return the process object for it.
1401 This is similar to `start-process', but arguments are specified as
1402 keyword/argument pairs. The following arguments are defined:
1404 :name NAME -- NAME is name for process. It is modified if necessary
1407 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1408 with the process. Process output goes at end of that buffer, unless
1409 you specify an output stream or filter function to handle the output.
1410 BUFFER may be also nil, meaning that this process is not associated
1413 :command COMMAND -- COMMAND is a list starting with the program file
1414 name, followed by strings to give to the program as arguments.
1416 :coding CODING -- If CODING is a symbol, it specifies the coding
1417 system used for both reading and writing for this process. If CODING
1418 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1419 ENCODING is used for writing.
1421 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1422 the process is running. If BOOL is not given, query before exiting.
1424 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1425 In the stopped state, a process does not accept incoming data, but you
1426 can send outgoing data. The stopped state is cleared by
1427 `continue-process' and set by `stop-process'.
1429 :connection-type TYPE -- TYPE is control type of device used to
1430 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1431 to use a pty, or nil to use the default specified through
1432 `process-connection-type'.
1434 :filter FILTER -- Install FILTER as the process filter.
1436 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1438 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1439 to the standard error of subprocess. Specifying this implies
1440 `:connection-type' is set to `pipe'.
1442 usage: (make-process &rest ARGS) */)
1443 (ptrdiff_t nargs
, Lisp_Object
*args
)
1445 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1446 Lisp_Object xstderr
, stderrproc
;
1447 ptrdiff_t count
= SPECPDL_INDEX ();
1453 /* Save arguments for process-contact and clone-process. */
1454 contact
= Flist (nargs
, args
);
1456 buffer
= Fplist_get (contact
, QCbuffer
);
1458 buffer
= Fget_buffer_create (buffer
);
1460 /* Make sure that the child will be able to chdir to the current
1461 buffer's current directory, or its unhandled equivalent. We
1462 can't just have the child check for an error when it does the
1463 chdir, since it's in a vfork. */
1464 current_dir
= encode_current_directory ();
1466 name
= Fplist_get (contact
, QCname
);
1467 CHECK_STRING (name
);
1469 command
= Fplist_get (contact
, QCcommand
);
1470 if (CONSP (command
))
1471 program
= XCAR (command
);
1475 if (!NILP (program
))
1476 CHECK_STRING (program
);
1479 xstderr
= Fplist_get (contact
, QCstderr
);
1480 if (PROCESSP (xstderr
))
1482 if (!PIPECONN_P (xstderr
))
1483 error ("Process is not a pipe process");
1484 stderrproc
= xstderr
;
1486 else if (!NILP (xstderr
))
1488 CHECK_STRING (program
);
1489 stderrproc
= CALLN (Fmake_pipe_process
,
1491 concat2 (name
, build_string (" stderr")),
1493 Fget_buffer_create (xstderr
));
1496 proc
= make_process (name
);
1497 /* If an error occurs and we can't start the process, we want to
1498 remove it from the process list. This means that each error
1499 check in create_process doesn't need to call remove_process
1500 itself; it's all taken care of here. */
1501 record_unwind_protect (start_process_unwind
, proc
);
1503 pset_childp (XPROCESS (proc
), Qt
);
1504 pset_plist (XPROCESS (proc
), Qnil
);
1505 pset_type (XPROCESS (proc
), Qreal
);
1506 pset_buffer (XPROCESS (proc
), buffer
);
1507 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1508 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1509 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1511 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1512 XPROCESS (proc
)->kill_without_query
= 1;
1513 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1514 pset_command (XPROCESS (proc
), Qt
);
1516 tem
= Fplist_get (contact
, QCconnection_type
);
1518 XPROCESS (proc
)->pty_flag
= true;
1519 else if (EQ (tem
, Qpipe
))
1520 XPROCESS (proc
)->pty_flag
= false;
1521 else if (NILP (tem
))
1522 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1524 report_file_error ("Unknown connection type", tem
);
1526 if (!NILP (stderrproc
))
1528 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1530 XPROCESS (proc
)->pty_flag
= false;
1534 /* AKA GNUTLS_INITSTAGE(proc). */
1535 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1536 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1539 XPROCESS (proc
)->adaptive_read_buffering
1540 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1541 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1543 /* Make the process marker point into the process buffer (if any). */
1544 if (BUFFERP (buffer
))
1545 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1546 BUF_ZV (XBUFFER (buffer
)),
1547 BUF_ZV_BYTE (XBUFFER (buffer
)));
1550 /* Decide coding systems for communicating with the process. Here
1551 we don't setup the structure coding_system nor pay attention to
1552 unibyte mode. They are done in create_process. */
1554 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1555 Lisp_Object coding_systems
= Qt
;
1556 Lisp_Object val
, *args2
;
1558 tem
= Fplist_get (contact
, QCcoding
);
1566 val
= Vcoding_system_for_read
;
1569 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1571 SAFE_ALLOCA_LISP (args2
, nargs2
);
1573 args2
[i
++] = Qstart_process
;
1575 args2
[i
++] = buffer
;
1576 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1577 args2
[i
++] = XCAR (tem2
);
1578 if (!NILP (program
))
1579 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1580 if (CONSP (coding_systems
))
1581 val
= XCAR (coding_systems
);
1582 else if (CONSP (Vdefault_process_coding_system
))
1583 val
= XCAR (Vdefault_process_coding_system
);
1585 pset_decode_coding_system (XPROCESS (proc
), val
);
1594 val
= Vcoding_system_for_write
;
1597 if (EQ (coding_systems
, Qt
))
1599 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1601 SAFE_ALLOCA_LISP (args2
, nargs2
);
1603 args2
[i
++] = Qstart_process
;
1605 args2
[i
++] = buffer
;
1606 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1607 args2
[i
++] = XCAR (tem2
);
1608 if (!NILP (program
))
1609 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1611 if (CONSP (coding_systems
))
1612 val
= XCDR (coding_systems
);
1613 else if (CONSP (Vdefault_process_coding_system
))
1614 val
= XCDR (Vdefault_process_coding_system
);
1616 pset_encode_coding_system (XPROCESS (proc
), val
);
1617 /* Note: At this moment, the above coding system may leave
1618 text-conversion or eol-conversion unspecified. They will be
1619 decided after we read output from the process and decode it by
1620 some coding system, or just before we actually send a text to
1625 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1626 XPROCESS (proc
)->decoding_carryover
= 0;
1627 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1629 XPROCESS (proc
)->inherit_coding_system_flag
1630 = !(NILP (buffer
) || !inherit_process_coding_system
);
1632 if (!NILP (program
))
1634 Lisp_Object program_args
= XCDR (command
);
1636 /* If program file name is not absolute, search our path for it.
1637 Put the name we will really use in TEM. */
1638 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1639 && !(SCHARS (program
) > 1
1640 && IS_DEVICE_SEP (SREF (program
, 1))))
1643 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1644 make_number (X_OK
), false);
1646 report_file_error ("Searching for program", program
);
1647 tem
= Fexpand_file_name (tem
, Qnil
);
1651 if (!NILP (Ffile_directory_p (program
)))
1652 error ("Specified program for new process is a directory");
1656 /* Remove "/:" from TEM. */
1657 tem
= remove_slash_colon (tem
);
1659 Lisp_Object arg_encoding
= Qnil
;
1661 /* Encode the file name and put it in NEW_ARGV.
1662 That's where the child will use it to execute the program. */
1663 tem
= list1 (ENCODE_FILE (tem
));
1664 ptrdiff_t new_argc
= 1;
1666 /* Here we encode arguments by the coding system used for sending
1667 data to the process. We don't support using different coding
1668 systems for encoding arguments and for encoding data sent to the
1671 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1673 Lisp_Object arg
= XCAR (tem2
);
1675 if (STRING_MULTIBYTE (arg
))
1677 if (NILP (arg_encoding
))
1678 arg_encoding
= (complement_process_encoding_system
1679 (XPROCESS (proc
)->encode_coding_system
));
1680 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1682 tem
= Fcons (arg
, tem
);
1686 /* Now that everything is encoded we can collect the strings into
1689 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1690 new_argv
[new_argc
] = 0;
1692 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1694 new_argv
[i
] = SSDATA (XCAR (tem
));
1698 create_process (proc
, new_argv
, current_dir
);
1704 return unbind_to (count
, proc
);
1707 /* This function is the unwind_protect form for Fstart_process. If
1708 PROC doesn't have its pid set, then we know someone has signaled
1709 an error and the process wasn't started successfully, so we should
1710 remove it from the process list. */
1712 start_process_unwind (Lisp_Object proc
)
1714 if (!PROCESSP (proc
))
1717 /* Was PROC started successfully?
1718 -2 is used for a pty with no process, eg for gdb. */
1719 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1720 remove_process (proc
);
1723 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1726 close_process_fd (int *fd_addr
)
1736 /* Indexes of file descriptors in open_fds. */
1739 /* The pipe from Emacs to its subprocess. */
1741 WRITE_TO_SUBPROCESS
,
1743 /* The main pipe from the subprocess to Emacs. */
1744 READ_FROM_SUBPROCESS
,
1747 /* The pipe from the subprocess to Emacs that is closed when the
1748 subprocess execs. */
1749 READ_FROM_EXEC_MONITOR
,
1753 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1756 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1758 struct Lisp_Process
*p
= XPROCESS (process
);
1759 int inchannel
, outchannel
;
1762 int forkin
, forkout
, forkerr
= -1;
1764 char pty_name
[PTY_NAME_SIZE
];
1765 Lisp_Object lisp_pty_name
= Qnil
;
1768 inchannel
= outchannel
= -1;
1771 outchannel
= inchannel
= allocate_pty (pty_name
);
1775 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1776 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1777 /* On most USG systems it does not work to open the pty's tty here,
1778 then close it and reopen it in the child. */
1779 /* Don't let this terminal become our controlling terminal
1780 (in case we don't have one). */
1781 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1783 report_file_error ("Opening pty", Qnil
);
1784 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1786 forkin
= forkout
= -1;
1787 #endif /* not USG, or USG_SUBTTY_WORKS */
1789 lisp_pty_name
= build_string (pty_name
);
1793 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1794 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1795 report_file_error ("Creating pipe", Qnil
);
1796 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1797 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1798 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1799 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1801 if (!NILP (p
->stderrproc
))
1803 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1805 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1807 /* Close unnecessary file descriptors. */
1808 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1809 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1814 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1815 report_file_error ("Creating pipe", Qnil
);
1818 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1819 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1821 /* Record this as an active process, with its channels. */
1822 chan_process
[inchannel
] = process
;
1823 p
->infd
= inchannel
;
1824 p
->outfd
= outchannel
;
1826 /* Previously we recorded the tty descriptor used in the subprocess.
1827 It was only used for getting the foreground tty process, so now
1828 we just reopen the device (see emacs_get_tty_pgrp) as this is
1829 more portable (see USG_SUBTTY_WORKS above). */
1831 p
->pty_flag
= pty_flag
;
1832 pset_status (p
, Qrun
);
1834 if (!EQ (p
->command
, Qt
))
1836 FD_SET (inchannel
, &input_wait_mask
);
1837 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1840 if (inchannel
> max_process_desc
)
1841 max_process_desc
= inchannel
;
1843 /* This may signal an error. */
1844 setup_process_coding_systems (process
);
1847 block_child_signal (&oldset
);
1850 /* vfork, and prevent local vars from being clobbered by the vfork. */
1851 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1852 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1853 char **volatile new_argv_volatile
= new_argv
;
1854 int volatile forkin_volatile
= forkin
;
1855 int volatile forkout_volatile
= forkout
;
1856 int volatile forkerr_volatile
= forkerr
;
1857 struct Lisp_Process
*p_volatile
= p
;
1861 current_dir
= current_dir_volatile
;
1862 lisp_pty_name
= lisp_pty_name_volatile
;
1863 new_argv
= new_argv_volatile
;
1864 forkin
= forkin_volatile
;
1865 forkout
= forkout_volatile
;
1866 forkerr
= forkerr_volatile
;
1869 pty_flag
= p
->pty_flag
;
1872 #endif /* not WINDOWSNT */
1874 /* Make the pty be the controlling terminal of the process. */
1876 /* First, disconnect its current controlling terminal. */
1877 /* We tried doing setsid only if pty_flag, but it caused
1878 process_set_signal to fail on SGI when using a pipe. */
1880 /* Make the pty's terminal the controlling terminal. */
1881 if (pty_flag
&& forkin
>= 0)
1884 /* We ignore the return value
1885 because faith@cs.unc.edu says that is necessary on Linux. */
1886 ioctl (forkin
, TIOCSCTTY
, 0);
1889 #if defined (LDISC1)
1890 if (pty_flag
&& forkin
>= 0)
1893 tcgetattr (forkin
, &t
);
1895 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1896 emacs_perror ("create_process/tcsetattr LDISC1");
1899 #if defined (NTTYDISC) && defined (TIOCSETD)
1900 if (pty_flag
&& forkin
>= 0)
1902 /* Use new line discipline. */
1903 int ldisc
= NTTYDISC
;
1904 ioctl (forkin
, TIOCSETD
, &ldisc
);
1909 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1910 can do TIOCSPGRP only to the process's controlling tty. */
1913 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1914 I can't test it since I don't have 4.3. */
1915 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1918 ioctl (j
, TIOCNOTTY
, 0);
1922 #endif /* TIOCNOTTY */
1924 #if !defined (DONT_REOPEN_PTY)
1925 /*** There is a suggestion that this ought to be a
1926 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1927 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1928 that system does seem to need this code, even though
1929 both TIOCSCTTY is defined. */
1930 /* Now close the pty (if we had it open) and reopen it.
1931 This makes the pty the controlling terminal of the subprocess. */
1935 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1938 emacs_close (forkin
);
1939 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1943 emacs_perror (SSDATA (lisp_pty_name
));
1944 _exit (EXIT_CANCELED
);
1948 #endif /* not DONT_REOPEN_PTY */
1950 #ifdef SETUP_SLAVE_PTY
1955 #endif /* SETUP_SLAVE_PTY */
1956 #endif /* HAVE_PTYS */
1958 signal (SIGINT
, SIG_DFL
);
1959 signal (SIGQUIT
, SIG_DFL
);
1961 signal (SIGPROF
, SIG_DFL
);
1964 /* Emacs ignores SIGPIPE, but the child should not. */
1965 signal (SIGPIPE
, SIG_DFL
);
1967 /* Stop blocking SIGCHLD in the child. */
1968 unblock_child_signal (&oldset
);
1971 child_setup_tty (forkout
);
1976 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1977 #else /* not WINDOWSNT */
1978 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1979 #endif /* not WINDOWSNT */
1982 /* Back in the parent process. */
1984 vfork_errno
= errno
;
1989 /* Stop blocking in the parent. */
1990 unblock_child_signal (&oldset
);
1994 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1997 /* vfork succeeded. */
1999 /* Close the pipe ends that the child uses, or the child's pty. */
2000 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2001 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2004 register_child (pid
, inchannel
);
2005 #endif /* WINDOWSNT */
2007 pset_tty_name (p
, lisp_pty_name
);
2010 /* Wait for child_setup to complete in case that vfork is
2011 actually defined as fork. The descriptor
2012 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2013 of a pipe is closed at the child side either by close-on-exec
2014 on successful execve or the _exit call in child_setup. */
2018 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2019 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2020 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2023 if (!NILP (p
->stderrproc
))
2025 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2026 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2032 create_pty (Lisp_Object process
)
2034 struct Lisp_Process
*p
= XPROCESS (process
);
2035 char pty_name
[PTY_NAME_SIZE
];
2036 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2040 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2041 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2042 /* On most USG systems it does not work to open the pty's tty here,
2043 then close it and reopen it in the child. */
2044 /* Don't let this terminal become our controlling terminal
2045 (in case we don't have one). */
2046 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2048 report_file_error ("Opening pty", Qnil
);
2049 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2050 #if defined (DONT_REOPEN_PTY)
2051 /* In the case that vfork is defined as fork, the parent process
2052 (Emacs) may send some data before the child process completes
2053 tty options setup. So we setup tty before forking. */
2054 child_setup_tty (forkout
);
2055 #endif /* DONT_REOPEN_PTY */
2056 #endif /* not USG, or USG_SUBTTY_WORKS */
2058 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2060 /* Record this as an active process, with its channels.
2061 As a result, child_setup will close Emacs's side of the pipes. */
2062 chan_process
[pty_fd
] = process
;
2066 /* Previously we recorded the tty descriptor used in the subprocess.
2067 It was only used for getting the foreground tty process, so now
2068 we just reopen the device (see emacs_get_tty_pgrp) as this is
2069 more portable (see USG_SUBTTY_WORKS above). */
2072 pset_status (p
, Qrun
);
2073 setup_process_coding_systems (process
);
2075 FD_SET (pty_fd
, &input_wait_mask
);
2076 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2077 if (pty_fd
> max_process_desc
)
2078 max_process_desc
= pty_fd
;
2080 pset_tty_name (p
, build_string (pty_name
));
2086 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2088 doc
: /* Create and return a bidirectional pipe process.
2090 In Emacs, pipes are represented by process objects, so input and
2091 output work as for subprocesses, and `delete-process' closes a pipe.
2092 However, a pipe process has no process id, it cannot be signaled,
2093 and the status codes are different from normal processes.
2095 Arguments are specified as keyword/argument pairs. The following
2096 arguments are defined:
2098 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2100 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2101 with the process. Process output goes at the end of that buffer,
2102 unless you specify an output stream or filter function to handle the
2103 output. If BUFFER is not given, the value of NAME is used.
2105 :coding CODING -- If CODING is a symbol, it specifies the coding
2106 system used for both reading and writing for this process. If CODING
2107 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2108 ENCODING is used for writing.
2110 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2111 the process is running. If BOOL is not given, query before exiting.
2113 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2114 In the stopped state, a pipe process does not accept incoming data,
2115 but you can send outgoing data. The stopped state is cleared by
2116 `continue-process' and set by `stop-process'.
2118 :filter FILTER -- Install FILTER as the process filter.
2120 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2122 usage: (make-pipe-process &rest ARGS) */)
2123 (ptrdiff_t nargs
, Lisp_Object
*args
)
2125 Lisp_Object proc
, contact
;
2126 struct Lisp_Process
*p
;
2127 Lisp_Object name
, buffer
;
2129 ptrdiff_t specpdl_count
;
2130 int inchannel
, outchannel
;
2135 contact
= Flist (nargs
, args
);
2137 name
= Fplist_get (contact
, QCname
);
2138 CHECK_STRING (name
);
2139 proc
= make_process (name
);
2140 specpdl_count
= SPECPDL_INDEX ();
2141 record_unwind_protect (remove_process
, proc
);
2142 p
= XPROCESS (proc
);
2144 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2145 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2146 report_file_error ("Creating pipe", Qnil
);
2147 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2148 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2150 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2151 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2154 register_aux_fd (inchannel
);
2157 /* Record this as an active process, with its channels. */
2158 chan_process
[inchannel
] = proc
;
2159 p
->infd
= inchannel
;
2160 p
->outfd
= outchannel
;
2162 if (inchannel
> max_process_desc
)
2163 max_process_desc
= inchannel
;
2165 buffer
= Fplist_get (contact
, QCbuffer
);
2168 buffer
= Fget_buffer_create (buffer
);
2169 pset_buffer (p
, buffer
);
2171 pset_childp (p
, contact
);
2172 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2173 pset_type (p
, Qpipe
);
2174 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2175 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2177 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2178 p
->kill_without_query
= 1;
2179 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2180 pset_command (p
, Qt
);
2181 eassert (! p
->pty_flag
);
2183 if (!EQ (p
->command
, Qt
))
2185 FD_SET (inchannel
, &input_wait_mask
);
2186 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2188 p
->adaptive_read_buffering
2189 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2190 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2192 /* Make the process marker point into the process buffer (if any). */
2193 if (BUFFERP (buffer
))
2194 set_marker_both (p
->mark
, buffer
,
2195 BUF_ZV (XBUFFER (buffer
)),
2196 BUF_ZV_BYTE (XBUFFER (buffer
)));
2199 /* Setup coding systems for communicating with the network stream. */
2201 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2202 Lisp_Object coding_systems
= Qt
;
2205 tem
= Fplist_get (contact
, QCcoding
);
2213 else if (!NILP (Vcoding_system_for_read
))
2214 val
= Vcoding_system_for_read
;
2215 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2216 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2217 /* We dare not decode end-of-line format by setting VAL to
2218 Qraw_text, because the existing Emacs Lisp libraries
2219 assume that they receive bare code including a sequence of
2224 if (CONSP (coding_systems
))
2225 val
= XCAR (coding_systems
);
2226 else if (CONSP (Vdefault_process_coding_system
))
2227 val
= XCAR (Vdefault_process_coding_system
);
2231 pset_decode_coding_system (p
, val
);
2239 else if (!NILP (Vcoding_system_for_write
))
2240 val
= Vcoding_system_for_write
;
2241 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2245 if (CONSP (coding_systems
))
2246 val
= XCDR (coding_systems
);
2247 else if (CONSP (Vdefault_process_coding_system
))
2248 val
= XCDR (Vdefault_process_coding_system
);
2252 pset_encode_coding_system (p
, val
);
2254 /* This may signal an error. */
2255 setup_process_coding_systems (proc
);
2257 specpdl_ptr
= specpdl
+ specpdl_count
;
2263 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2264 The address family of sa is not included in the result. */
2267 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2269 Lisp_Object address
;
2272 struct Lisp_Vector
*p
;
2274 /* Workaround for a bug in getsockname on BSD: Names bound to
2275 sockets in the UNIX domain are inaccessible; getsockname returns
2276 a zero length name. */
2277 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2278 return empty_unibyte_string
;
2280 switch (sa
->sa_family
)
2284 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2285 len
= sizeof (sin
->sin_addr
) + 1;
2286 address
= Fmake_vector (make_number (len
), Qnil
);
2287 p
= XVECTOR (address
);
2288 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2289 cp
= (unsigned char *) &sin
->sin_addr
;
2295 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2296 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2297 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2298 address
= Fmake_vector (make_number (len
), Qnil
);
2299 p
= XVECTOR (address
);
2300 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2301 for (i
= 0; i
< len
; i
++)
2302 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2306 #ifdef HAVE_LOCAL_SOCKETS
2309 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2310 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2311 /* If the first byte is NUL, the name is a Linux abstract
2312 socket name, and the name can contain embedded NULs. If
2313 it's not, we have a NUL-terminated string. Be careful not
2314 to walk past the end of the object looking for the name
2315 terminator, however. */
2316 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2318 const char *terminator
2319 = memchr (sockun
->sun_path
, '\0', name_length
);
2322 name_length
= terminator
- (const char *) sockun
->sun_path
;
2325 return make_unibyte_string (sockun
->sun_path
, name_length
);
2329 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2330 address
= Fcons (make_number (sa
->sa_family
),
2331 Fmake_vector (make_number (len
), Qnil
));
2332 p
= XVECTOR (XCDR (address
));
2333 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2339 p
->contents
[i
++] = make_number (*cp
++);
2345 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2348 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2350 struct Lisp_Vector
*p
;
2352 if (VECTORP (address
))
2354 p
= XVECTOR (address
);
2355 if (p
->header
.size
== 5)
2358 return sizeof (struct sockaddr_in
);
2361 else if (p
->header
.size
== 9)
2363 *familyp
= AF_INET6
;
2364 return sizeof (struct sockaddr_in6
);
2368 #ifdef HAVE_LOCAL_SOCKETS
2369 else if (STRINGP (address
))
2371 *familyp
= AF_LOCAL
;
2372 return sizeof (struct sockaddr_un
);
2375 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2376 && VECTORP (XCDR (address
)))
2378 struct sockaddr
*sa
;
2379 p
= XVECTOR (XCDR (address
));
2380 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2382 *familyp
= XINT (XCAR (address
));
2383 return p
->header
.size
+ sizeof (sa
->sa_family
);
2388 /* Convert an address object (vector or string) to an internal sockaddr.
2390 The address format has been basically validated by
2391 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2392 it could have come from user data. So if FAMILY is not valid,
2393 we return after zeroing *SA. */
2396 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2398 register struct Lisp_Vector
*p
;
2399 register unsigned char *cp
= NULL
;
2403 memset (sa
, 0, len
);
2405 if (VECTORP (address
))
2407 p
= XVECTOR (address
);
2408 if (family
== AF_INET
)
2410 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2411 len
= sizeof (sin
->sin_addr
) + 1;
2412 hostport
= XINT (p
->contents
[--len
]);
2413 sin
->sin_port
= htons (hostport
);
2414 cp
= (unsigned char *)&sin
->sin_addr
;
2415 sa
->sa_family
= family
;
2418 else if (family
== AF_INET6
)
2420 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2421 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2422 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2423 hostport
= XINT (p
->contents
[--len
]);
2424 sin6
->sin6_port
= htons (hostport
);
2425 for (i
= 0; i
< len
; i
++)
2426 if (INTEGERP (p
->contents
[i
]))
2428 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2431 sa
->sa_family
= family
;
2438 else if (STRINGP (address
))
2440 #ifdef HAVE_LOCAL_SOCKETS
2441 if (family
== AF_LOCAL
)
2443 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2444 cp
= SDATA (address
);
2445 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2446 sockun
->sun_path
[i
] = *cp
++;
2447 sa
->sa_family
= family
;
2454 p
= XVECTOR (XCDR (address
));
2455 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2458 for (i
= 0; i
< len
; i
++)
2459 if (INTEGERP (p
->contents
[i
]))
2460 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2463 #ifdef DATAGRAM_SOCKETS
2464 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2466 doc
: /* Get the current datagram address associated with PROCESS.
2467 If PROCESS is a non-blocking network process that hasn't been fully
2468 set up yet, this function will block until socket setup has completed. */)
2469 (Lisp_Object process
)
2473 CHECK_PROCESS (process
);
2475 if (NETCONN_P (process
))
2476 wait_for_socket_fds (process
, "process-datagram-address");
2478 if (!DATAGRAM_CONN_P (process
))
2481 channel
= XPROCESS (process
)->infd
;
2482 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2483 datagram_address
[channel
].len
);
2486 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2488 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2489 Return nil upon error setting address, ADDRESS otherwise.
2491 If PROCESS is a non-blocking network process that hasn't been fully
2492 set up yet, this function will block until socket setup has completed. */)
2493 (Lisp_Object process
, Lisp_Object address
)
2499 CHECK_PROCESS (process
);
2501 if (NETCONN_P (process
))
2502 wait_for_socket_fds (process
, "set-process-datagram-address");
2504 if (!DATAGRAM_CONN_P (process
))
2507 channel
= XPROCESS (process
)->infd
;
2509 len
= get_lisp_to_sockaddr_size (address
, &family
);
2510 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2512 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2518 static const struct socket_options
{
2519 /* The name of this option. Should be lowercase version of option
2520 name without SO_ prefix. */
2522 /* Option level SOL_... */
2524 /* Option number SO_... */
2526 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2527 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2528 } socket_options
[] =
2530 #ifdef SO_BINDTODEVICE
2531 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2534 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2537 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2540 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2543 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2546 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2549 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2552 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2554 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2557 /* Set option OPT to value VAL on socket S.
2559 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2560 Signals an error if setting a known option fails.
2564 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2567 const struct socket_options
*sopt
;
2572 name
= SSDATA (SYMBOL_NAME (opt
));
2573 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2574 if (strcmp (name
, sopt
->name
) == 0)
2577 switch (sopt
->opttype
)
2582 optval
= NILP (val
) ? 0 : 1;
2583 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2584 &optval
, sizeof (optval
));
2591 if (TYPE_RANGED_INTEGERP (int, val
))
2592 optval
= XINT (val
);
2594 error ("Bad option value for %s", name
);
2595 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2596 &optval
, sizeof (optval
));
2600 #ifdef SO_BINDTODEVICE
2603 char devname
[IFNAMSIZ
+ 1];
2605 /* This is broken, at least in the Linux 2.4 kernel.
2606 To unbind, the arg must be a zero integer, not the empty string.
2607 This should work on all systems. KFS. 2003-09-23. */
2608 memset (devname
, 0, sizeof devname
);
2611 char *arg
= SSDATA (val
);
2612 int len
= min (strlen (arg
), IFNAMSIZ
);
2613 memcpy (devname
, arg
, len
);
2615 else if (!NILP (val
))
2616 error ("Bad option value for %s", name
);
2617 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2626 struct linger linger
;
2629 linger
.l_linger
= 0;
2630 if (TYPE_RANGED_INTEGERP (int, val
))
2631 linger
.l_linger
= XINT (val
);
2633 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2634 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2635 &linger
, sizeof (linger
));
2646 int setsockopt_errno
= errno
;
2647 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2651 return (1 << sopt
->optbit
);
2655 DEFUN ("set-network-process-option",
2656 Fset_network_process_option
, Sset_network_process_option
,
2658 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2659 See `make-network-process' for a list of options and values.
2660 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2661 OPTION is not a supported option, return nil instead; otherwise return t.
2663 If PROCESS is a non-blocking network process that hasn't been fully
2664 set up yet, this function will block until socket setup has completed. */)
2665 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2668 struct Lisp_Process
*p
;
2670 CHECK_PROCESS (process
);
2671 p
= XPROCESS (process
);
2672 if (!NETCONN1_P (p
))
2673 error ("Process is not a network process");
2675 wait_for_socket_fds (process
, "set-network-process-option");
2679 error ("Process is not running");
2681 if (set_socket_option (s
, option
, value
))
2683 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2687 if (NILP (no_error
))
2688 error ("Unknown or unsupported option");
2694 DEFUN ("serial-process-configure",
2695 Fserial_process_configure
,
2696 Sserial_process_configure
,
2698 doc
: /* Configure speed, bytesize, etc. of a serial process.
2700 Arguments are specified as keyword/argument pairs. Attributes that
2701 are not given are re-initialized from the process's current
2702 configuration (available via the function `process-contact') or set to
2703 reasonable default values. The following arguments are defined:
2709 -- Any of these arguments can be given to identify the process that is
2710 to be configured. If none of these arguments is given, the current
2711 buffer's process is used.
2713 :speed SPEED -- SPEED is the speed of the serial port in bits per
2714 second, also called baud rate. Any value can be given for SPEED, but
2715 most serial ports work only at a few defined values between 1200 and
2716 115200, with 9600 being the most common value. If SPEED is nil, the
2717 serial port is not configured any further, i.e., all other arguments
2718 are ignored. This may be useful for special serial ports such as
2719 Bluetooth-to-serial converters which can only be configured through AT
2720 commands. A value of nil for SPEED can be used only when passed
2721 through `make-serial-process' or `serial-term'.
2723 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2724 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2726 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2727 `odd' (use odd parity), or the symbol `even' (use even parity). If
2728 PARITY is not given, no parity is used.
2730 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2731 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2732 is not given or nil, 1 stopbit is used.
2734 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2735 flowcontrol to be used, which is either nil (don't use flowcontrol),
2736 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2737 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2738 flowcontrol is used.
2740 `serial-process-configure' is called by `make-serial-process' for the
2741 initial configuration of the serial port.
2745 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2747 \(serial-process-configure
2748 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2750 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2752 usage: (serial-process-configure &rest ARGS) */)
2753 (ptrdiff_t nargs
, Lisp_Object
*args
)
2755 struct Lisp_Process
*p
;
2756 Lisp_Object contact
= Qnil
;
2757 Lisp_Object proc
= Qnil
;
2759 contact
= Flist (nargs
, args
);
2761 proc
= Fplist_get (contact
, QCprocess
);
2763 proc
= Fplist_get (contact
, QCname
);
2765 proc
= Fplist_get (contact
, QCbuffer
);
2767 proc
= Fplist_get (contact
, QCport
);
2768 proc
= get_process (proc
);
2769 p
= XPROCESS (proc
);
2770 if (!EQ (p
->type
, Qserial
))
2771 error ("Not a serial process");
2773 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2776 serial_configure (p
, contact
);
2780 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2782 doc
: /* Create and return a serial port process.
2784 In Emacs, serial port connections are represented by process objects,
2785 so input and output work as for subprocesses, and `delete-process'
2786 closes a serial port connection. However, a serial process has no
2787 process id, it cannot be signaled, and the status codes are different
2788 from normal processes.
2790 `make-serial-process' creates a process and a buffer, on which you
2791 probably want to use `process-send-string'. Try \\[serial-term] for
2792 an interactive terminal. See below for examples.
2794 Arguments are specified as keyword/argument pairs. The following
2795 arguments are defined:
2797 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2798 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2799 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2800 the backslashes in strings).
2802 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2803 which this function calls.
2805 :name NAME -- NAME is the name of the process. If NAME is not given,
2806 the value of PORT is used.
2808 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2809 with the process. Process output goes at the end of that buffer,
2810 unless you specify an output stream or filter function to handle the
2811 output. If BUFFER is not given, the value of NAME is used.
2813 :coding CODING -- If CODING is a symbol, it specifies the coding
2814 system used for both reading and writing for this process. If CODING
2815 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2816 ENCODING is used for writing.
2818 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2819 the process is running. If BOOL is not given, query before exiting.
2821 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2822 In the stopped state, a serial process does not accept incoming data,
2823 but you can send outgoing data. The stopped state is cleared by
2824 `continue-process' and set by `stop-process'.
2826 :filter FILTER -- Install FILTER as the process filter.
2828 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2830 :plist PLIST -- Install PLIST as the initial plist of the process.
2836 -- This function calls `serial-process-configure' to handle these
2839 The original argument list, possibly modified by later configuration,
2840 is available via the function `process-contact'.
2844 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2846 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2848 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2850 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2852 usage: (make-serial-process &rest ARGS) */)
2853 (ptrdiff_t nargs
, Lisp_Object
*args
)
2856 Lisp_Object proc
, contact
, port
;
2857 struct Lisp_Process
*p
;
2858 Lisp_Object name
, buffer
;
2859 Lisp_Object tem
, val
;
2860 ptrdiff_t specpdl_count
;
2865 contact
= Flist (nargs
, args
);
2867 port
= Fplist_get (contact
, QCport
);
2869 error ("No port specified");
2870 CHECK_STRING (port
);
2872 if (NILP (Fplist_member (contact
, QCspeed
)))
2873 error (":speed not specified");
2874 if (!NILP (Fplist_get (contact
, QCspeed
)))
2875 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2877 name
= Fplist_get (contact
, QCname
);
2880 CHECK_STRING (name
);
2881 proc
= make_process (name
);
2882 specpdl_count
= SPECPDL_INDEX ();
2883 record_unwind_protect (remove_process
, proc
);
2884 p
= XPROCESS (proc
);
2886 fd
= serial_open (port
);
2887 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2890 if (fd
> max_process_desc
)
2891 max_process_desc
= fd
;
2892 chan_process
[fd
] = proc
;
2894 buffer
= Fplist_get (contact
, QCbuffer
);
2897 buffer
= Fget_buffer_create (buffer
);
2898 pset_buffer (p
, buffer
);
2900 pset_childp (p
, contact
);
2901 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2902 pset_type (p
, Qserial
);
2903 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2904 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2906 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2907 p
->kill_without_query
= 1;
2908 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2909 pset_command (p
, Qt
);
2910 eassert (! p
->pty_flag
);
2912 if (!EQ (p
->command
, Qt
))
2914 FD_SET (fd
, &input_wait_mask
);
2915 FD_SET (fd
, &non_keyboard_wait_mask
);
2918 if (BUFFERP (buffer
))
2920 set_marker_both (p
->mark
, buffer
,
2921 BUF_ZV (XBUFFER (buffer
)),
2922 BUF_ZV_BYTE (XBUFFER (buffer
)));
2925 tem
= Fplist_member (contact
, QCcoding
);
2926 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2932 val
= XCAR (XCDR (tem
));
2936 else if (!NILP (Vcoding_system_for_read
))
2937 val
= Vcoding_system_for_read
;
2938 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2939 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2941 pset_decode_coding_system (p
, val
);
2946 val
= XCAR (XCDR (tem
));
2950 else if (!NILP (Vcoding_system_for_write
))
2951 val
= Vcoding_system_for_write
;
2952 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2953 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2955 pset_encode_coding_system (p
, val
);
2957 setup_process_coding_systems (proc
);
2958 pset_decoding_buf (p
, empty_unibyte_string
);
2959 p
->decoding_carryover
= 0;
2960 pset_encoding_buf (p
, empty_unibyte_string
);
2961 p
->inherit_coding_system_flag
2962 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2964 Fserial_process_configure (nargs
, args
);
2966 specpdl_ptr
= specpdl
+ specpdl_count
;
2972 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2973 Lisp_Object service
, Lisp_Object name
)
2976 struct Lisp_Process
*p
= XPROCESS (proc
);
2977 Lisp_Object contact
= p
->childp
;
2978 Lisp_Object coding_systems
= Qt
;
2981 tem
= Fplist_member (contact
, QCcoding
);
2982 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2983 tem
= Qnil
; /* No error message (too late!). */
2985 /* Setup coding systems for communicating with the network stream. */
2986 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2990 val
= XCAR (XCDR (tem
));
2994 else if (!NILP (Vcoding_system_for_read
))
2995 val
= Vcoding_system_for_read
;
2996 else if ((!NILP (p
->buffer
)
2997 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2998 || (NILP (p
->buffer
)
2999 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3000 /* We dare not decode end-of-line format by setting VAL to
3001 Qraw_text, because the existing Emacs Lisp libraries
3002 assume that they receive bare code including a sequence of
3007 if (NILP (host
) || NILP (service
))
3008 coding_systems
= Qnil
;
3010 coding_systems
= CALLN (Ffind_operation_coding_system
,
3011 Qopen_network_stream
, name
, p
->buffer
,
3013 if (CONSP (coding_systems
))
3014 val
= XCAR (coding_systems
);
3015 else if (CONSP (Vdefault_process_coding_system
))
3016 val
= XCAR (Vdefault_process_coding_system
);
3020 pset_decode_coding_system (p
, val
);
3024 val
= XCAR (XCDR (tem
));
3028 else if (!NILP (Vcoding_system_for_write
))
3029 val
= Vcoding_system_for_write
;
3030 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3034 if (EQ (coding_systems
, Qt
))
3036 if (NILP (host
) || NILP (service
))
3037 coding_systems
= Qnil
;
3039 coding_systems
= CALLN (Ffind_operation_coding_system
,
3040 Qopen_network_stream
, name
, p
->buffer
,
3043 if (CONSP (coding_systems
))
3044 val
= XCDR (coding_systems
);
3045 else if (CONSP (Vdefault_process_coding_system
))
3046 val
= XCDR (Vdefault_process_coding_system
);
3050 pset_encode_coding_system (p
, val
);
3052 pset_decoding_buf (p
, empty_unibyte_string
);
3053 p
->decoding_carryover
= 0;
3054 pset_encoding_buf (p
, empty_unibyte_string
);
3056 p
->inherit_coding_system_flag
3057 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3062 finish_after_tls_connection (Lisp_Object proc
)
3064 struct Lisp_Process
*p
= XPROCESS (proc
);
3065 Lisp_Object contact
= p
->childp
;
3066 Lisp_Object result
= Qt
;
3068 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3069 result
= call3 (Qnsm_verify_connection
,
3071 Fplist_get (contact
, QChost
),
3072 Fplist_get (contact
, QCservice
));
3076 pset_status (p
, list2 (Qfailed
,
3077 build_string ("The Network Security Manager stopped the connections")));
3078 deactivate_process (proc
);
3082 /* If we cleared the connection wait mask before we did
3083 the TLS setup, then we have to say that the process
3084 is finally "open" here. */
3085 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3087 pset_status (p
, Qrun
);
3088 /* Execute the sentinel here. If we had relied on
3089 status_notify to do it later, it will read input
3090 from the process before calling the sentinel. */
3091 exec_sentinel (proc
, build_string ("open\n"));
3098 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
,
3099 Lisp_Object use_external_socket_p
)
3101 ptrdiff_t count
= SPECPDL_INDEX ();
3103 int s
= -1, outch
, inch
;
3105 Lisp_Object ip_address
;
3107 struct sockaddr
*sa
= NULL
;
3110 struct Lisp_Process
*p
= XPROCESS (proc
);
3111 Lisp_Object contact
= p
->childp
;
3113 int socket_to_use
= -1;
3115 if (!NILP (use_external_socket_p
))
3117 socket_to_use
= external_sock_fd
;
3119 /* Ensure we don't consume the external socket twice. */
3120 external_sock_fd
= -1;
3123 /* Do this in case we never enter the while-loop below. */
3124 count1
= SPECPDL_INDEX ();
3127 while (!NILP (ip_addresses
))
3129 ip_address
= XCAR (ip_addresses
);
3130 ip_addresses
= XCDR (ip_addresses
);
3136 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3139 sa
= xmalloc (addrlen
);
3140 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3145 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3153 #ifdef DATAGRAM_SOCKETS
3154 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3156 #endif /* DATAGRAM_SOCKETS */
3158 if (p
->is_non_blocking_client
)
3160 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3170 /* Make us close S if quit. */
3171 record_unwind_protect_int (close_file_unwind
, s
);
3173 /* Parse network options in the arg list. We simply ignore anything
3174 which isn't a known option (including other keywords). An error
3175 is signaled if setting a known option fails. */
3177 Lisp_Object params
= contact
, key
, val
;
3179 while (!NILP (params
))
3181 key
= XCAR (params
);
3182 params
= XCDR (params
);
3183 val
= XCAR (params
);
3184 params
= XCDR (params
);
3185 optbits
|= set_socket_option (s
, key
, val
);
3191 /* Configure as a server socket. */
3193 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3194 explicit :reuseaddr key to override this. */
3195 #ifdef HAVE_LOCAL_SOCKETS
3196 if (family
!= AF_LOCAL
)
3198 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3201 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3202 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3205 /* If passed a socket descriptor, it should be already bound. */
3206 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3207 report_file_error ("Cannot bind server socket", Qnil
);
3209 #ifdef HAVE_GETSOCKNAME
3212 struct sockaddr_in sa1
;
3213 socklen_t len1
= sizeof (sa1
);
3214 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3216 Lisp_Object service
;
3217 service
= make_number (ntohs (sa1
.sin_port
));
3218 contact
= Fplist_put (contact
, QCservice
, service
);
3219 /* Save the port number so that we can stash it in
3220 the process object later. */
3221 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3226 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3227 report_file_error ("Cannot listen on server socket", Qnil
);
3235 ret
= connect (s
, sa
, addrlen
);
3238 if (ret
== 0 || xerrno
== EISCONN
)
3240 /* The unwind-protect will be discarded afterwards.
3241 Likewise for immediate_quit. */
3245 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3249 if (xerrno
== EINTR
)
3251 /* Unlike most other syscalls connect() cannot be called
3252 again. (That would return EALREADY.) The proper way to
3253 wait for completion is pselect(). */
3261 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3267 report_file_error ("Failed select", Qnil
);
3271 len
= sizeof xerrno
;
3272 eassert (FD_ISSET (s
, &fdset
));
3273 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3274 report_file_error ("Failed getsockopt", Qnil
);
3276 report_file_errno ("Failed connect", Qnil
, xerrno
);
3279 #endif /* !WINDOWSNT */
3283 /* Discard the unwind protect closing S. */
3284 specpdl_ptr
= specpdl
+ count1
;
3289 if (xerrno
== EINTR
)
3296 #ifdef DATAGRAM_SOCKETS
3297 if (p
->socktype
== SOCK_DGRAM
)
3299 if (datagram_address
[s
].sa
)
3302 datagram_address
[s
].sa
= xmalloc (addrlen
);
3303 datagram_address
[s
].len
= addrlen
;
3307 memset (datagram_address
[s
].sa
, 0, addrlen
);
3308 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3311 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3312 if (rlen
!= 0 && rfamily
== family
3314 conv_lisp_to_sockaddr (rfamily
, remote
,
3315 datagram_address
[s
].sa
, rlen
);
3319 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3323 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3324 conv_sockaddr_to_lisp (sa
, addrlen
));
3325 #ifdef HAVE_GETSOCKNAME
3328 struct sockaddr_in sa1
;
3329 socklen_t len1
= sizeof (sa1
);
3330 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3331 contact
= Fplist_put (contact
, QClocal
,
3332 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3341 /* If non-blocking got this far - and failed - assume non-blocking is
3342 not supported after all. This is probably a wrong assumption, but
3343 the normal blocking calls to open-network-stream handles this error
3345 if (p
->is_non_blocking_client
)
3348 report_file_errno ((p
->is_server
3349 ? "make server process failed"
3350 : "make client process failed"),
3357 chan_process
[inch
] = proc
;
3359 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3361 p
= XPROCESS (proc
);
3362 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3366 /* Discard the unwind protect for closing S, if any. */
3367 specpdl_ptr
= specpdl
+ count1
;
3369 /* Unwind bind_polling_period and request_sigio. */
3370 unbind_to (count
, Qnil
);
3372 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3373 pset_status (p
, Qlisten
);
3375 /* Make the process marker point into the process buffer (if any). */
3376 if (BUFFERP (p
->buffer
))
3377 set_marker_both (p
->mark
, p
->buffer
,
3378 BUF_ZV (XBUFFER (p
->buffer
)),
3379 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3381 if (p
->is_non_blocking_client
)
3383 /* We may get here if connect did succeed immediately. However,
3384 in that case, we still need to signal this like a non-blocking
3386 pset_status (p
, Qconnect
);
3387 if (!FD_ISSET (inch
, &connect_wait_mask
))
3389 FD_SET (inch
, &connect_wait_mask
);
3390 FD_SET (inch
, &write_mask
);
3391 num_pending_connects
++;
3395 /* A server may have a client filter setting of Qt, but it must
3396 still listen for incoming connects unless it is stopped. */
3397 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3398 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3400 FD_SET (inch
, &input_wait_mask
);
3401 FD_SET (inch
, &non_keyboard_wait_mask
);
3404 if (inch
> max_process_desc
)
3405 max_process_desc
= inch
;
3407 /* Set up the masks based on the process filter. */
3408 set_process_filter_masks (p
);
3410 setup_process_coding_systems (proc
);
3413 /* Continue the asynchronous connection. */
3414 if (!NILP (p
->gnutls_boot_parameters
))
3416 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3418 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3419 p
->gnutls_boot_parameters
= Qnil
;
3421 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3422 /* Run sentinels, etc. */
3423 finish_after_tls_connection (proc
);
3424 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3426 deactivate_process (proc
);
3428 pset_status (p
, list2 (Qfailed
,
3429 build_string ("TLS negotiation failed")));
3431 pset_status (p
, list2 (Qfailed
, boot
));
3438 /* Create a network stream/datagram client/server process. Treated
3439 exactly like a normal process when reading and writing. Primary
3440 differences are in status display and process deletion. A network
3441 connection has no PID; you cannot signal it. All you can do is
3442 stop/continue it and deactivate/close it via delete-process. */
3444 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3446 doc
: /* Create and return a network server or client process.
3448 In Emacs, network connections are represented by process objects, so
3449 input and output work as for subprocesses and `delete-process' closes
3450 a network connection. However, a network process has no process id,
3451 it cannot be signaled, and the status codes are different from normal
3454 Arguments are specified as keyword/argument pairs. The following
3455 arguments are defined:
3457 :name NAME -- NAME is name for process. It is modified if necessary
3460 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3461 with the process. Process output goes at end of that buffer, unless
3462 you specify an output stream or filter function to handle the output.
3463 BUFFER may be also nil, meaning that this process is not associated
3466 :host HOST -- HOST is name of the host to connect to, or its IP
3467 address. The symbol `local' specifies the local host. If specified
3468 for a server process, it must be a valid name or address for the local
3469 host, and only clients connecting to that address will be accepted.
3471 :service SERVICE -- SERVICE is name of the service desired, or an
3472 integer specifying a port number to connect to. If SERVICE is t,
3473 a random port number is selected for the server. A port number can
3474 be specified as an integer string, e.g., "80", as well as an integer.
3476 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3477 stream type connection, `datagram' creates a datagram type connection,
3478 `seqpacket' creates a reliable datagram connection.
3480 :family FAMILY -- FAMILY is the address (and protocol) family for the
3481 service specified by HOST and SERVICE. The default (nil) is to use
3482 whatever address family (IPv4 or IPv6) that is defined for the host
3483 and port number specified by HOST and SERVICE. Other address families
3485 local -- for a local (i.e. UNIX) address specified by SERVICE.
3486 ipv4 -- use IPv4 address family only.
3487 ipv6 -- use IPv6 address family only.
3489 :local ADDRESS -- ADDRESS is the local address used for the connection.
3490 This parameter is ignored when opening a client process. When specified
3491 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3493 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3494 connection. This parameter is ignored when opening a stream server
3495 process. For a datagram server process, it specifies the initial
3496 setting of the remote datagram address. When specified for a client
3497 process, the FAMILY, HOST, and SERVICE args are ignored.
3499 The format of ADDRESS depends on the address family:
3500 - An IPv4 address is represented as an vector of integers [A B C D P]
3501 corresponding to numeric IP address A.B.C.D and port number P.
3502 - A local address is represented as a string with the address in the
3503 local address space.
3504 - An "unsupported family" address is represented by a cons (F . AV)
3505 where F is the family number and AV is a vector containing the socket
3506 address data with one element per address data byte. Do not rely on
3507 this format in portable code, as it may depend on implementation
3508 defined constants, data sizes, and data structure alignment.
3510 :coding CODING -- If CODING is a symbol, it specifies the coding
3511 system used for both reading and writing for this process. If CODING
3512 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3513 ENCODING is used for writing.
3515 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3516 process, return without waiting for the connection to complete;
3517 instead, the sentinel function will be called with second arg matching
3518 "open" (if successful) or "failed" when the connect completes.
3519 Default is to use a blocking connect (i.e. wait) for stream type
3522 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3523 running when Emacs is exited.
3525 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3526 In the stopped state, a server process does not accept new
3527 connections, and a client process does not handle incoming traffic.
3528 The stopped state is cleared by `continue-process' and set by
3531 :filter FILTER -- Install FILTER as the process filter.
3533 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3534 process filter are multibyte, otherwise they are unibyte.
3535 If this keyword is not specified, the strings are multibyte if
3536 the default value of `enable-multibyte-characters' is non-nil.
3538 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3540 :log LOG -- Install LOG as the server process log function. This
3541 function is called when the server accepts a network connection from a
3542 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3543 is the server process, CLIENT is the new process for the connection,
3544 and MESSAGE is a string.
3546 :plist PLIST -- Install PLIST as the new process's initial plist.
3548 :tls-parameters LIST -- is a list that should be supplied if you're
3549 opening a TLS connection. The first element is the TLS type (either
3550 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3551 be a keyword list accepted by gnutls-boot (as returned by
3552 `gnutls-boot-parameters').
3554 :server QLEN -- if QLEN is non-nil, create a server process for the
3555 specified FAMILY, SERVICE, and connection type (stream or datagram).
3556 If QLEN is an integer, it is used as the max. length of the server's
3557 pending connection queue (also known as the backlog); the default
3558 queue length is 5. Default is to create a client process.
3560 The following network options can be specified for this connection:
3562 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3563 :dontroute BOOL -- Only send to directly connected hosts.
3564 :keepalive BOOL -- Send keep-alive messages on network stream.
3565 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3566 :oobinline BOOL -- Place out-of-band data in receive data stream.
3567 :priority INT -- Set protocol defined priority for sent packets.
3568 :reuseaddr BOOL -- Allow reusing a recently used local address
3569 (this is allowed by default for a server process).
3570 :bindtodevice NAME -- bind to interface NAME. Using this may require
3571 special privileges on some systems.
3572 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3573 been passed to Emacs. If Emacs wasn't
3574 passed a socket, this option is silently
3578 Consult the relevant system programmer's manual pages for more
3579 information on using these options.
3582 A server process will listen for and accept connections from clients.
3583 When a client connection is accepted, a new network process is created
3584 for the connection with the following parameters:
3586 - The client's process name is constructed by concatenating the server
3587 process's NAME and a client identification string.
3588 - If the FILTER argument is non-nil, the client process will not get a
3589 separate process buffer; otherwise, the client's process buffer is a newly
3590 created buffer named after the server process's BUFFER name or process
3591 NAME concatenated with the client identification string.
3592 - The connection type and the process filter and sentinel parameters are
3593 inherited from the server process's TYPE, FILTER and SENTINEL.
3594 - The client process's contact info is set according to the client's
3595 addressing information (typically an IP address and a port number).
3596 - The client process's plist is initialized from the server's plist.
3598 Notice that the FILTER and SENTINEL args are never used directly by
3599 the server process. Also, the BUFFER argument is not used directly by
3600 the server process, but via the optional :log function, accepted (and
3601 failed) connections may be logged in the server process's buffer.
3603 The original argument list, modified with the actual connection
3604 information, is available via the `process-contact' function.
3606 usage: (make-network-process &rest ARGS) */)
3607 (ptrdiff_t nargs
, Lisp_Object
*args
)
3610 Lisp_Object contact
;
3611 struct Lisp_Process
*p
;
3612 const char *portstring
;
3613 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3614 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3615 #ifdef HAVE_LOCAL_SOCKETS
3616 struct sockaddr_un address_un
;
3620 Lisp_Object name
, buffer
, host
, service
, address
;
3621 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3622 Lisp_Object ip_addresses
= Qnil
;
3625 int ai_protocol
= 0;
3626 #ifdef HAVE_GETADDRINFO_A
3627 struct gaicb
*dns_request
= NULL
;
3629 ptrdiff_t count
= SPECPDL_INDEX ();
3634 /* Save arguments for process-contact and clone-process. */
3635 contact
= Flist (nargs
, args
);
3638 /* Ensure socket support is loaded if available. */
3639 init_winsock (TRUE
);
3642 /* :type TYPE (nil: stream, datagram */
3643 tem
= Fplist_get (contact
, QCtype
);
3645 socktype
= SOCK_STREAM
;
3646 #ifdef DATAGRAM_SOCKETS
3647 else if (EQ (tem
, Qdatagram
))
3648 socktype
= SOCK_DGRAM
;
3650 #ifdef HAVE_SEQPACKET
3651 else if (EQ (tem
, Qseqpacket
))
3652 socktype
= SOCK_SEQPACKET
;
3655 error ("Unsupported connection type");
3657 name
= Fplist_get (contact
, QCname
);
3658 buffer
= Fplist_get (contact
, QCbuffer
);
3659 filter
= Fplist_get (contact
, QCfilter
);
3660 sentinel
= Fplist_get (contact
, QCsentinel
);
3661 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3663 CHECK_STRING (name
);
3665 /* :local ADDRESS or :remote ADDRESS */
3666 tem
= Fplist_get (contact
, QCserver
);
3668 address
= Fplist_get (contact
, QCremote
);
3670 address
= Fplist_get (contact
, QClocal
);
3671 if (!NILP (address
))
3673 host
= service
= Qnil
;
3675 if (!get_lisp_to_sockaddr_size (address
, &family
))
3676 error ("Malformed :address");
3678 ip_addresses
= list1 (address
);
3682 /* :family FAMILY -- nil (for Inet), local, or integer. */
3683 tem
= Fplist_get (contact
, QCfamily
);
3692 #ifdef HAVE_LOCAL_SOCKETS
3693 else if (EQ (tem
, Qlocal
))
3697 else if (EQ (tem
, Qipv6
))
3700 else if (EQ (tem
, Qipv4
))
3702 else if (TYPE_RANGED_INTEGERP (int, tem
))
3703 family
= XINT (tem
);
3705 error ("Unknown address family");
3707 /* :service SERVICE -- string, integer (port number), or t (random port). */
3708 service
= Fplist_get (contact
, QCservice
);
3710 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3711 host
= Fplist_get (contact
, QChost
);
3714 /* The "connection" function gets it bind info from the address we're
3715 given, so use this dummy address if nothing is specified. */
3716 #ifdef HAVE_LOCAL_SOCKETS
3717 if (family
!= AF_LOCAL
)
3719 host
= build_string ("127.0.0.1");
3723 if (EQ (host
, Qlocal
))
3724 /* Depending on setup, "localhost" may map to different IPv4 and/or
3725 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3726 host
= build_string ("127.0.0.1");
3727 CHECK_STRING (host
);
3730 #ifdef HAVE_LOCAL_SOCKETS
3731 if (family
== AF_LOCAL
)
3735 message (":family local ignores the :host property");
3736 contact
= Fplist_put (contact
, QChost
, Qnil
);
3739 CHECK_STRING (service
);
3740 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3741 error ("Service name too long");
3742 ip_addresses
= list1 (service
);
3747 /* Slow down polling to every ten seconds.
3748 Some kernels have a bug which causes retrying connect to fail
3749 after a connect. Polling can interfere with gethostbyname too. */
3750 #ifdef POLL_FOR_INPUT
3751 if (socktype
!= SOCK_DGRAM
)
3753 record_unwind_protect_void (run_all_atimers
);
3754 bind_polling_period (10);
3760 /* SERVICE can either be a string or int.
3761 Convert to a C string for later use by getaddrinfo. */
3762 if (EQ (service
, Qt
))
3767 else if (INTEGERP (service
))
3769 portstring
= portbuf
;
3770 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3774 CHECK_STRING (service
);
3775 portstring
= SSDATA (service
);
3776 portstringlen
= SBYTES (service
);
3780 #ifdef HAVE_GETADDRINFO_A
3781 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3783 ptrdiff_t hostlen
= SBYTES (host
);
3787 struct addrinfo hints
;
3788 char str
[FLEXIBLE_ARRAY_MEMBER
];
3789 } *req
= xmalloc (offsetof (struct req
, str
)
3790 + hostlen
+ 1 + portstringlen
+ 1);
3791 dns_request
= &req
->gaicb
;
3792 dns_request
->ar_name
= req
->str
;
3793 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3794 dns_request
->ar_request
= &req
->hints
;
3795 dns_request
->ar_result
= NULL
;
3796 memset (&req
->hints
, 0, sizeof req
->hints
);
3797 req
->hints
.ai_family
= family
;
3798 req
->hints
.ai_socktype
= socktype
;
3799 strcpy (req
->str
, SSDATA (host
));
3800 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3802 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3804 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3808 #endif /* HAVE_GETADDRINFO_A */
3810 /* If we have a host, use getaddrinfo to resolve both host and service.
3811 Otherwise, use getservbyname to lookup the service. */
3815 struct addrinfo
*res
, *lres
;
3821 struct addrinfo hints
;
3822 memset (&hints
, 0, sizeof hints
);
3823 hints
.ai_family
= family
;
3824 hints
.ai_socktype
= socktype
;
3826 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3828 #ifdef HAVE_GAI_STRERROR
3830 synchronize_system_messages_locale ();
3831 char const *str
= gai_strerror (ret
);
3832 if (! NILP (Vlocale_coding_system
))
3833 str
= SSDATA (code_convert_string_norecord
3834 (build_string (str
), Vlocale_coding_system
, 0));
3835 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3838 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3842 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3844 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3845 (lres
->ai_addr
, lres
->ai_addrlen
),
3847 ai_protocol
= lres
->ai_protocol
;
3850 ip_addresses
= Fnreverse (ip_addresses
);
3857 /* No hostname has been specified (e.g., a local server process). */
3859 if (EQ (service
, Qt
))
3861 else if (INTEGERP (service
))
3862 port
= XINT (service
);
3865 CHECK_STRING (service
);
3868 if (SBYTES (service
) != 0)
3870 /* Allow the service to be a string containing the port number,
3871 because that's allowed if you have getaddrbyname. */
3873 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3874 if (service_end
== SSDATA (service
) + SBYTES (service
))
3878 struct servent
*svc_info
3879 = getservbyname (SSDATA (service
),
3880 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3882 port
= ntohs (svc_info
->s_port
);
3887 if (! (0 <= port
&& port
< 1 << 16))
3889 AUTO_STRING (unknown_service
, "Unknown service: %s");
3890 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3896 buffer
= Fget_buffer_create (buffer
);
3897 proc
= make_process (name
);
3898 p
= XPROCESS (proc
);
3899 pset_childp (p
, contact
);
3900 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3901 pset_type (p
, Qnetwork
);
3903 pset_buffer (p
, buffer
);
3904 pset_sentinel (p
, sentinel
);
3905 pset_filter (p
, filter
);
3906 pset_log (p
, Fplist_get (contact
, QClog
));
3907 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3908 p
->kill_without_query
= 1;
3909 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3910 pset_command (p
, Qt
);
3913 p
->is_non_blocking_client
= false;
3914 p
->is_server
= false;
3916 p
->socktype
= socktype
;
3917 p
->ai_protocol
= ai_protocol
;
3918 #ifdef HAVE_GETADDRINFO_A
3919 p
->dns_request
= NULL
;
3922 tem
= Fplist_get (contact
, QCtls_parameters
);
3924 p
->gnutls_boot_parameters
= tem
;
3927 set_network_socket_coding_system (proc
, host
, service
, name
);
3929 unbind_to (count
, Qnil
);
3932 tem
= Fplist_get (contact
, QCserver
);
3935 /* Don't support network sockets when non-blocking mode is
3936 not available, since a blocked Emacs is not useful. */
3937 p
->is_server
= true;
3938 if (TYPE_RANGED_INTEGERP (int, tem
))
3939 p
->backlog
= XINT (tem
);
3943 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3944 && !NILP (Fplist_get (contact
, QCnowait
)))
3945 p
->is_non_blocking_client
= true;
3947 #ifdef HAVE_GETADDRINFO_A
3948 /* With async address resolution, the list of addresses is empty, so
3949 postpone connecting to the server. */
3950 if (!p
->is_server
&& NILP (ip_addresses
))
3952 p
->dns_request
= dns_request
;
3953 p
->status
= Qconnect
;
3958 connect_network_socket (proc
, ip_addresses
, use_external_socket_p
);
3963 #ifdef HAVE_NET_IF_H
3967 network_interface_list (void)
3969 struct ifconf ifconf
;
3970 struct ifreq
*ifreq
;
3972 ptrdiff_t buf_size
= 512;
3977 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3980 count
= SPECPDL_INDEX ();
3981 record_unwind_protect_int (close_file_unwind
, s
);
3985 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3986 ifconf
.ifc_buf
= buf
;
3987 ifconf
.ifc_len
= buf_size
;
3988 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3995 while (ifconf
.ifc_len
== buf_size
);
3997 res
= unbind_to (count
, Qnil
);
3998 ifreq
= ifconf
.ifc_req
;
3999 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4001 struct ifreq
*ifq
= ifreq
;
4002 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4003 #define SIZEOF_IFREQ(sif) \
4004 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4005 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4007 int len
= SIZEOF_IFREQ (ifq
);
4009 int len
= sizeof (*ifreq
);
4011 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4012 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4014 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4017 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4018 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4019 res
= Fcons (Fcons (build_string (namebuf
),
4020 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4021 sizeof (struct sockaddr
))),
4028 #endif /* SIOCGIFCONF */
4030 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4034 const char *flag_sym
;
4037 static const struct ifflag_def ifflag_table
[] = {
4041 #ifdef IFF_BROADCAST
4042 { IFF_BROADCAST
, "broadcast" },
4045 { IFF_DEBUG
, "debug" },
4048 { IFF_LOOPBACK
, "loopback" },
4050 #ifdef IFF_POINTOPOINT
4051 { IFF_POINTOPOINT
, "pointopoint" },
4054 { IFF_RUNNING
, "running" },
4057 { IFF_NOARP
, "noarp" },
4060 { IFF_PROMISC
, "promisc" },
4062 #ifdef IFF_NOTRAILERS
4063 #ifdef NS_IMPL_COCOA
4064 /* Really means smart, notrailers is obsolete. */
4065 { IFF_NOTRAILERS
, "smart" },
4067 { IFF_NOTRAILERS
, "notrailers" },
4071 { IFF_ALLMULTI
, "allmulti" },
4074 { IFF_MASTER
, "master" },
4077 { IFF_SLAVE
, "slave" },
4079 #ifdef IFF_MULTICAST
4080 { IFF_MULTICAST
, "multicast" },
4083 { IFF_PORTSEL
, "portsel" },
4085 #ifdef IFF_AUTOMEDIA
4086 { IFF_AUTOMEDIA
, "automedia" },
4089 { IFF_DYNAMIC
, "dynamic" },
4092 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4095 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4098 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4101 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4104 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4110 network_interface_info (Lisp_Object ifname
)
4113 Lisp_Object res
= Qnil
;
4118 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4119 && defined HAVE_GETIFADDRS && defined LLADDR)
4120 struct ifaddrs
*ifap
;
4123 CHECK_STRING (ifname
);
4125 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4126 error ("interface name too long");
4127 lispstpcpy (rq
.ifr_name
, ifname
);
4129 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4132 count
= SPECPDL_INDEX ();
4133 record_unwind_protect_int (close_file_unwind
, s
);
4136 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4137 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4139 int flags
= rq
.ifr_flags
;
4140 const struct ifflag_def
*fp
;
4143 /* If flags is smaller than int (i.e. short) it may have the high bit set
4144 due to IFF_MULTICAST. In that case, sign extending it into
4146 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4147 flags
= (unsigned short) rq
.ifr_flags
;
4150 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4152 if (flags
& fp
->flag_bit
)
4154 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4155 flags
-= fp
->flag_bit
;
4158 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4162 elt
= Fcons (make_number (fnum
), elt
);
4167 res
= Fcons (elt
, res
);
4170 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4171 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4173 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4174 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4178 for (n
= 0; n
< 6; n
++)
4179 p
->contents
[n
] = make_number (((unsigned char *)
4180 &rq
.ifr_hwaddr
.sa_data
[0])
4182 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4184 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4185 if (getifaddrs (&ifap
) != -1)
4187 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4188 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4191 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4193 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4194 unsigned char linkaddr
[6];
4197 if (it
->ifa_addr
->sa_family
!= AF_LINK
4198 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4199 || sdl
->sdl_alen
!= 6)
4202 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4203 for (n
= 0; n
< 6; n
++)
4204 p
->contents
[n
] = make_number (linkaddr
[n
]);
4206 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4210 #ifdef HAVE_FREEIFADDRS
4214 #endif /* HAVE_GETIFADDRS && LLADDR */
4216 res
= Fcons (elt
, res
);
4219 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4220 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4223 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4224 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4226 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4230 res
= Fcons (elt
, res
);
4233 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4234 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4237 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4240 res
= Fcons (elt
, res
);
4243 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4244 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4247 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4250 res
= Fcons (elt
, res
);
4252 return unbind_to (count
, any
? res
: Qnil
);
4254 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4255 #endif /* defined (HAVE_NET_IF_H) */
4257 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4258 Snetwork_interface_list
, 0, 0, 0,
4259 doc
: /* Return an alist of all network interfaces and their network address.
4260 Each element is a cons, the car of which is a string containing the
4261 interface name, and the cdr is the network address in internal
4262 format; see the description of ADDRESS in `make-network-process'.
4264 If the information is not available, return nil. */)
4267 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4268 return network_interface_list ();
4274 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4275 Snetwork_interface_info
, 1, 1, 0,
4276 doc
: /* Return information about network interface named IFNAME.
4277 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4278 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4279 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4280 FLAGS is the current flags of the interface.
4282 Data that is unavailable is returned as nil. */)
4283 (Lisp_Object ifname
)
4285 #if ((defined HAVE_NET_IF_H \
4286 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4287 || defined SIOCGIFFLAGS)) \
4288 || defined WINDOWSNT)
4289 return network_interface_info (ifname
);
4295 /* Turn off input and output for process PROC. */
4298 deactivate_process (Lisp_Object proc
)
4301 struct Lisp_Process
*p
= XPROCESS (proc
);
4305 /* Delete GnuTLS structures in PROC, if any. */
4306 emacs_gnutls_deinit (proc
);
4307 #endif /* HAVE_GNUTLS */
4309 if (p
->read_output_delay
> 0)
4311 if (--process_output_delay_count
< 0)
4312 process_output_delay_count
= 0;
4313 p
->read_output_delay
= 0;
4314 p
->read_output_skip
= 0;
4317 /* Beware SIGCHLD hereabouts. */
4319 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4320 close_process_fd (&p
->open_fd
[i
]);
4322 inchannel
= p
->infd
;
4327 #ifdef DATAGRAM_SOCKETS
4328 if (DATAGRAM_CHAN_P (inchannel
))
4330 xfree (datagram_address
[inchannel
].sa
);
4331 datagram_address
[inchannel
].sa
= 0;
4332 datagram_address
[inchannel
].len
= 0;
4335 chan_process
[inchannel
] = Qnil
;
4336 FD_CLR (inchannel
, &input_wait_mask
);
4337 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4338 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4340 FD_CLR (inchannel
, &connect_wait_mask
);
4341 FD_CLR (inchannel
, &write_mask
);
4342 if (--num_pending_connects
< 0)
4345 if (inchannel
== max_process_desc
)
4347 /* We just closed the highest-numbered process input descriptor,
4348 so recompute the highest-numbered one now. */
4352 while (0 <= i
&& NILP (chan_process
[i
]));
4354 max_process_desc
= i
;
4360 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4362 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4363 It is given to their filter functions.
4364 Optional argument PROCESS means do not return until output has been
4365 received from PROCESS.
4367 Optional second argument SECONDS and third argument MILLISEC
4368 specify a timeout; return after that much time even if there is
4369 no subprocess output. If SECONDS is a floating point number,
4370 it specifies a fractional number of seconds to wait.
4371 The MILLISEC argument is obsolete and should be avoided.
4373 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4374 from PROCESS only, suspending reading output from other processes.
4375 If JUST-THIS-ONE is an integer, don't run any timers either.
4376 Return non-nil if we received any output from PROCESS (or, if PROCESS
4377 is nil, from any process) before the timeout expired. */)
4378 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4383 if (! NILP (process
))
4384 CHECK_PROCESS (process
);
4386 just_this_one
= Qnil
;
4388 if (!NILP (millisec
))
4389 { /* Obsolete calling convention using integers rather than floats. */
4390 CHECK_NUMBER (millisec
);
4392 seconds
= make_float (XINT (millisec
) / 1000.0);
4395 CHECK_NUMBER (seconds
);
4396 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4403 if (!NILP (seconds
))
4405 if (INTEGERP (seconds
))
4407 if (XINT (seconds
) > 0)
4409 secs
= XINT (seconds
);
4413 else if (FLOATP (seconds
))
4415 if (XFLOAT_DATA (seconds
) > 0)
4417 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4418 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4423 wrong_type_argument (Qnumberp
, seconds
);
4425 else if (! NILP (process
))
4429 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4431 !NILP (process
) ? XPROCESS (process
) : NULL
,
4432 (NILP (just_this_one
) ? 0
4433 : !INTEGERP (just_this_one
) ? 1 : -1))
4438 /* Accept a connection for server process SERVER on CHANNEL. */
4440 static EMACS_INT connect_counter
= 0;
4443 server_accept_connection (Lisp_Object server
, int channel
)
4445 Lisp_Object proc
, caller
, name
, buffer
;
4446 Lisp_Object contact
, host
, service
;
4447 struct Lisp_Process
*ps
= XPROCESS (server
);
4448 struct Lisp_Process
*p
;
4452 struct sockaddr_in in
;
4454 struct sockaddr_in6 in6
;
4456 #ifdef HAVE_LOCAL_SOCKETS
4457 struct sockaddr_un un
;
4460 socklen_t len
= sizeof saddr
;
4463 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4468 if (!would_block (code
) && !NILP (ps
->log
))
4469 call3 (ps
->log
, server
, Qnil
,
4470 concat3 (build_string ("accept failed with code"),
4471 Fnumber_to_string (make_number (code
)),
4472 build_string ("\n")));
4476 count
= SPECPDL_INDEX ();
4477 record_unwind_protect_int (close_file_unwind
, s
);
4481 /* Setup a new process to handle the connection. */
4483 /* Generate a unique identification of the caller, and build contact
4484 information for this process. */
4487 switch (saddr
.sa
.sa_family
)
4491 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4493 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4494 host
= CALLN (Fformat
, ipv4_format
,
4495 make_number (ip
[0]), make_number (ip
[1]),
4496 make_number (ip
[2]), make_number (ip
[3]));
4497 service
= make_number (ntohs (saddr
.in
.sin_port
));
4498 AUTO_STRING (caller_format
, " <%s:%d>");
4499 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4506 Lisp_Object args
[9];
4507 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4510 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4511 args
[0] = ipv6_format
;
4512 for (i
= 0; i
< 8; i
++)
4513 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4514 host
= CALLMANY (Fformat
, args
);
4515 service
= make_number (ntohs (saddr
.in
.sin_port
));
4516 AUTO_STRING (caller_format
, " <[%s]:%d>");
4517 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4522 #ifdef HAVE_LOCAL_SOCKETS
4526 caller
= Fnumber_to_string (make_number (connect_counter
));
4527 AUTO_STRING (space_less_than
, " <");
4528 AUTO_STRING (greater_than
, ">");
4529 caller
= concat3 (space_less_than
, caller
, greater_than
);
4533 /* Create a new buffer name for this process if it doesn't have a
4534 filter. The new buffer name is based on the buffer name or
4535 process name of the server process concatenated with the caller
4538 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4539 || EQ (ps
->filter
, Qt
)))
4543 buffer
= ps
->buffer
;
4545 buffer
= Fbuffer_name (buffer
);
4550 buffer
= concat2 (buffer
, caller
);
4551 buffer
= Fget_buffer_create (buffer
);
4555 /* Generate a unique name for the new server process. Combine the
4556 server process name with the caller identification. */
4558 name
= concat2 (ps
->name
, caller
);
4559 proc
= make_process (name
);
4561 chan_process
[s
] = proc
;
4563 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4565 p
= XPROCESS (proc
);
4567 /* Build new contact information for this setup. */
4568 contact
= Fcopy_sequence (ps
->childp
);
4569 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4570 contact
= Fplist_put (contact
, QChost
, host
);
4571 if (!NILP (service
))
4572 contact
= Fplist_put (contact
, QCservice
, service
);
4573 contact
= Fplist_put (contact
, QCremote
,
4574 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4575 #ifdef HAVE_GETSOCKNAME
4577 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4578 contact
= Fplist_put (contact
, QClocal
,
4579 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4582 pset_childp (p
, contact
);
4583 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4584 pset_type (p
, Qnetwork
);
4586 pset_buffer (p
, buffer
);
4587 pset_sentinel (p
, ps
->sentinel
);
4588 pset_filter (p
, ps
->filter
);
4589 pset_command (p
, Qnil
);
4592 /* Discard the unwind protect for closing S. */
4593 specpdl_ptr
= specpdl
+ count
;
4595 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4598 pset_status (p
, Qrun
);
4600 /* Client processes for accepted connections are not stopped initially. */
4601 if (!EQ (p
->filter
, Qt
))
4603 FD_SET (s
, &input_wait_mask
);
4604 FD_SET (s
, &non_keyboard_wait_mask
);
4607 if (s
> max_process_desc
)
4608 max_process_desc
= s
;
4610 /* Setup coding system for new process based on server process.
4611 This seems to be the proper thing to do, as the coding system
4612 of the new process should reflect the settings at the time the
4613 server socket was opened; not the current settings. */
4615 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4616 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4617 setup_process_coding_systems (proc
);
4619 pset_decoding_buf (p
, empty_unibyte_string
);
4620 p
->decoding_carryover
= 0;
4621 pset_encoding_buf (p
, empty_unibyte_string
);
4623 p
->inherit_coding_system_flag
4624 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4626 AUTO_STRING (dash
, "-");
4627 AUTO_STRING (nl
, "\n");
4628 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4630 if (!NILP (ps
->log
))
4632 AUTO_STRING (accept_from
, "accept from ");
4633 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4636 AUTO_STRING (open_from
, "open from ");
4637 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4640 #ifdef HAVE_GETADDRINFO_A
4642 check_for_dns (Lisp_Object proc
)
4644 struct Lisp_Process
*p
= XPROCESS (proc
);
4645 Lisp_Object ip_addresses
= Qnil
;
4648 if (! p
->dns_request
)
4651 int ret
= gai_error (p
->dns_request
);
4652 if (ret
== EAI_INPROGRESS
)
4655 /* We got a response. */
4658 struct addrinfo
*res
;
4660 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4662 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4663 (res
->ai_addr
, res
->ai_addrlen
),
4667 ip_addresses
= Fnreverse (ip_addresses
);
4669 /* The DNS lookup failed. */
4670 else if (EQ (p
->status
, Qconnect
))
4672 deactivate_process (proc
);
4673 pset_status (p
, (list2
4675 concat3 (build_string ("Name lookup of "),
4676 build_string (p
->dns_request
->ar_name
),
4677 build_string (" failed")))));
4680 free_dns_request (proc
);
4682 /* This process should not already be connected (or killed). */
4683 if (!EQ (p
->status
, Qconnect
))
4686 return ip_addresses
;
4689 #endif /* HAVE_GETADDRINFO_A */
4692 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4694 while (XPROCESS (process
)->infd
< 0
4695 && EQ (XPROCESS (process
)->status
, Qconnect
))
4697 add_to_log ("Waiting for socket from %s...", build_string (name
));
4698 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4703 wait_while_connecting (Lisp_Object process
)
4705 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4707 add_to_log ("Waiting for connection...");
4708 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4713 wait_for_tls_negotiation (Lisp_Object process
)
4716 while (XPROCESS (process
)->gnutls_p
4717 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4719 add_to_log ("Waiting for TLS...");
4720 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4725 /* This variable is different from waiting_for_input in keyboard.c.
4726 It is used to communicate to a lisp process-filter/sentinel (via the
4727 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4728 for user-input when that process-filter was called.
4729 waiting_for_input cannot be used as that is by definition 0 when
4730 lisp code is being evalled.
4731 This is also used in record_asynch_buffer_change.
4732 For that purpose, this must be 0
4733 when not inside wait_reading_process_output. */
4734 static int waiting_for_user_input_p
;
4737 wait_reading_process_output_unwind (int data
)
4739 waiting_for_user_input_p
= data
;
4742 /* This is here so breakpoints can be put on it. */
4744 wait_reading_process_output_1 (void)
4748 /* Read and dispose of subprocess output while waiting for timeout to
4749 elapse and/or keyboard input to be available.
4753 If negative, gobble data immediately available but don't wait for any.
4756 an additional duration to wait, measured in nanoseconds
4757 If TIME_LIMIT is zero, then:
4758 If NSECS == 0, there is no limit.
4759 If NSECS > 0, the timeout consists of NSECS only.
4760 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4763 0 to ignore keyboard input, or
4764 1 to return when input is available, or
4765 -1 meaning caller will actually read the input, so don't throw to
4766 the quit handler, or
4768 DO_DISPLAY means redisplay should be done to show subprocess
4769 output that arrives.
4771 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4772 (and gobble terminal input into the buffer if any arrives).
4774 If WAIT_PROC is specified, wait until something arrives from that
4777 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4778 (suspending output from other processes). A negative value
4779 means don't run any timers either.
4781 Return positive if we received input from WAIT_PROC (or from any
4782 process if WAIT_PROC is null), zero if we attempted to receive
4783 input but got none, and negative if we didn't even try. */
4786 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4788 Lisp_Object wait_for_cell
,
4789 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4799 struct timespec timeout
, end_time
, timer_delay
;
4800 struct timespec got_output_end_time
= invalid_timespec ();
4801 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4802 int got_some_output
= -1;
4803 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4804 bool retry_for_async
;
4806 ptrdiff_t count
= SPECPDL_INDEX ();
4808 /* Close to the current time if known, an invalid timespec otherwise. */
4809 struct timespec now
= invalid_timespec ();
4811 FD_ZERO (&Available
);
4814 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4815 && !(CONSP (wait_proc
->status
)
4816 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4817 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4819 record_unwind_protect_int (wait_reading_process_output_unwind
,
4820 waiting_for_user_input_p
);
4821 waiting_for_user_input_p
= read_kbd
;
4823 if (TYPE_MAXIMUM (time_t) < time_limit
)
4824 time_limit
= TYPE_MAXIMUM (time_t);
4826 if (time_limit
< 0 || nsecs
< 0)
4828 else if (time_limit
> 0 || nsecs
> 0)
4831 now
= current_timespec ();
4832 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4839 bool process_skipped
= false;
4841 /* If calling from keyboard input, do not quit
4842 since we want to return C-g as an input character.
4843 Otherwise, do pending quit if requested. */
4846 else if (pending_signals
)
4847 process_pending_signals ();
4849 /* Exit now if the cell we're waiting for became non-nil. */
4850 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4853 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4855 Lisp_Object process_list_head
, aproc
;
4856 struct Lisp_Process
*p
;
4858 retry_for_async
= false;
4859 FOR_EACH_PROCESS(process_list_head
, aproc
)
4861 p
= XPROCESS (aproc
);
4863 if (! wait_proc
|| p
== wait_proc
)
4865 #ifdef HAVE_GETADDRINFO_A
4866 /* Check for pending DNS requests. */
4869 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4870 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4871 connect_network_socket (aproc
, ip_addresses
, Qnil
);
4873 retry_for_async
= true;
4877 /* Continue TLS negotiation. */
4878 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4879 && p
->is_non_blocking_client
)
4881 gnutls_try_handshake (p
);
4882 p
->gnutls_handshakes_tried
++;
4884 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4886 gnutls_verify_boot (aproc
, Qnil
);
4887 finish_after_tls_connection (aproc
);
4891 retry_for_async
= true;
4892 if (p
->gnutls_handshakes_tried
4893 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4895 deactivate_process (aproc
);
4896 pset_status (p
, list2 (Qfailed
,
4897 build_string ("TLS negotiation failed")));
4905 #endif /* GETADDRINFO_A or GNUTLS */
4907 /* Compute time from now till when time limit is up. */
4908 /* Exit if already run out. */
4909 if (wait
== TIMEOUT
)
4911 if (!timespec_valid_p (now
))
4912 now
= current_timespec ();
4913 if (timespec_cmp (end_time
, now
) <= 0)
4915 timeout
= timespec_sub (end_time
, now
);
4918 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4920 /* Normally we run timers here.
4921 But not if wait_for_cell; in those cases,
4922 the wait is supposed to be short,
4923 and those callers cannot handle running arbitrary Lisp code here. */
4924 if (NILP (wait_for_cell
)
4925 && just_wait_proc
>= 0)
4929 unsigned old_timers_run
= timers_run
;
4930 struct buffer
*old_buffer
= current_buffer
;
4931 Lisp_Object old_window
= selected_window
;
4933 timer_delay
= timer_check ();
4935 /* If a timer has run, this might have changed buffers
4936 an alike. Make read_key_sequence aware of that. */
4937 if (timers_run
!= old_timers_run
4938 && (old_buffer
!= current_buffer
4939 || !EQ (old_window
, selected_window
))
4940 && waiting_for_user_input_p
== -1)
4941 record_asynch_buffer_change ();
4943 if (timers_run
!= old_timers_run
&& do_display
)
4944 /* We must retry, since a timer may have requeued itself
4945 and that could alter the time_delay. */
4946 redisplay_preserve_echo_area (9);
4950 while (!detect_input_pending ());
4952 /* If there is unread keyboard input, also return. */
4954 && requeued_events_pending_p ())
4957 /* This is so a breakpoint can be put here. */
4958 if (!timespec_valid_p (timer_delay
))
4959 wait_reading_process_output_1 ();
4962 /* Cause C-g and alarm signals to take immediate action,
4963 and cause input available signals to zero out timeout.
4965 It is important that we do this before checking for process
4966 activity. If we get a SIGCHLD after the explicit checks for
4967 process activity, timeout is the only way we will know. */
4969 set_waiting_for_input (&timeout
);
4971 /* If status of something has changed, and no input is
4972 available, notify the user of the change right away. After
4973 this explicit check, we'll let the SIGCHLD handler zap
4974 timeout to get our attention. */
4975 if (update_tick
!= process_tick
)
4980 if (kbd_on_hold_p ())
4983 Atemp
= input_wait_mask
;
4986 timeout
= make_timespec (0, 0);
4987 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4989 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4990 NULL
, &timeout
, NULL
)
4993 /* It's okay for us to do this and then continue with
4994 the loop, since timeout has already been zeroed out. */
4995 clear_waiting_for_input ();
4996 got_some_output
= status_notify (NULL
, wait_proc
);
4997 if (do_display
) redisplay_preserve_echo_area (13);
5001 /* Don't wait for output from a non-running process. Just
5002 read whatever data has already been received. */
5003 if (wait_proc
&& wait_proc
->raw_status_new
)
5004 update_status (wait_proc
);
5006 && ! EQ (wait_proc
->status
, Qrun
)
5007 && ! EQ (wait_proc
->status
, Qconnect
))
5009 bool read_some_bytes
= false;
5011 clear_waiting_for_input ();
5013 /* If data can be read from the process, do so until exhausted. */
5014 if (wait_proc
->infd
>= 0)
5016 XSETPROCESS (proc
, wait_proc
);
5020 int nread
= read_process_output (proc
, wait_proc
->infd
);
5023 if (errno
== EIO
|| would_block (errno
))
5028 if (got_some_output
< nread
)
5029 got_some_output
= nread
;
5032 read_some_bytes
= true;
5037 if (read_some_bytes
&& do_display
)
5038 redisplay_preserve_echo_area (10);
5043 /* Wait till there is something to do. */
5045 if (wait_proc
&& just_wait_proc
)
5047 if (wait_proc
->infd
< 0) /* Terminated. */
5049 FD_SET (wait_proc
->infd
, &Available
);
5053 else if (!NILP (wait_for_cell
))
5055 Available
= non_process_wait_mask
;
5062 Available
= non_keyboard_wait_mask
;
5064 Available
= input_wait_mask
;
5065 Writeok
= write_mask
;
5066 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5070 /* If frame size has changed or the window is newly mapped,
5071 redisplay now, before we start to wait. There is a race
5072 condition here; if a SIGIO arrives between now and the select
5073 and indicates that a frame is trashed, the select may block
5074 displaying a trashed screen. */
5075 if (frame_garbaged
&& do_display
)
5077 clear_waiting_for_input ();
5078 redisplay_preserve_echo_area (11);
5080 set_waiting_for_input (&timeout
);
5083 /* Skip the `select' call if input is available and we're
5084 waiting for keyboard input or a cell change (which can be
5085 triggered by processing X events). In the latter case, set
5086 nfds to 1 to avoid breaking the loop. */
5088 if ((read_kbd
|| !NILP (wait_for_cell
))
5089 && detect_input_pending ())
5091 nfds
= read_kbd
? 0 : 1;
5093 FD_ZERO (&Available
);
5097 /* Set the timeout for adaptive read buffering if any
5098 process has non-zero read_output_skip and non-zero
5099 read_output_delay, and we are not reading output for a
5100 specific process. It is not executed if
5101 Vprocess_adaptive_read_buffering is nil. */
5102 if (process_output_skip
&& check_delay
> 0)
5104 int adaptive_nsecs
= timeout
.tv_nsec
;
5105 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5106 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5107 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5109 proc
= chan_process
[channel
];
5112 /* Find minimum non-zero read_output_delay among the
5113 processes with non-zero read_output_skip. */
5114 if (XPROCESS (proc
)->read_output_delay
> 0)
5117 if (!XPROCESS (proc
)->read_output_skip
)
5119 FD_CLR (channel
, &Available
);
5120 process_skipped
= true;
5121 XPROCESS (proc
)->read_output_skip
= 0;
5122 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5123 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5126 timeout
= make_timespec (0, adaptive_nsecs
);
5127 process_output_skip
= 0;
5130 /* If we've got some output and haven't limited our timeout
5131 with adaptive read buffering, limit it. */
5132 if (got_some_output
> 0 && !process_skipped
5134 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5135 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5138 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5139 && timespec_valid_p (timer_delay
)
5140 && timespec_cmp (timer_delay
, timeout
) < 0)
5142 if (!timespec_valid_p (now
))
5143 now
= current_timespec ();
5144 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5145 if (!timespec_valid_p (got_output_end_time
)
5146 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5147 got_output_end_time
= timeout_abs
;
5148 timeout
= timer_delay
;
5151 got_output_end_time
= invalid_timespec ();
5153 /* NOW can become inaccurate if time can pass during pselect. */
5154 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5155 now
= invalid_timespec ();
5157 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5159 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5162 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5166 #if defined (HAVE_NS)
5168 #elif defined (HAVE_GLIB)
5173 (max (max_process_desc
, max_input_desc
) + 1,
5175 (check_write
? &Writeok
: 0),
5176 NULL
, &timeout
, NULL
);
5179 /* GnuTLS buffers data internally. In lowat mode it leaves
5180 some data in the TCP buffers so that select works, but
5181 with custom pull/push functions we need to check if some
5182 data is available in the buffers manually. */
5185 fd_set tls_available
;
5188 FD_ZERO (&tls_available
);
5191 /* We're not waiting on a specific process, so loop
5192 through all the channels and check for data.
5193 This is a workaround needed for some versions of
5194 the gnutls library -- 2.12.14 has been confirmed
5196 http://comments.gmane.org/gmane.emacs.devel/145074 */
5197 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5198 if (! NILP (chan_process
[channel
]))
5200 struct Lisp_Process
*p
=
5201 XPROCESS (chan_process
[channel
]);
5202 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5203 && ((emacs_gnutls_record_check_pending
5208 eassert (p
->infd
== channel
);
5209 FD_SET (p
->infd
, &tls_available
);
5216 /* Check this specific channel. */
5217 if (wait_proc
->gnutls_p
/* Check for valid process. */
5218 && wait_proc
->gnutls_state
5219 /* Do we have pending data? */
5220 && ((emacs_gnutls_record_check_pending
5221 (wait_proc
->gnutls_state
))
5225 eassert (0 <= wait_proc
->infd
);
5226 /* Set to Available. */
5227 FD_SET (wait_proc
->infd
, &tls_available
);
5232 Available
= tls_available
;
5239 /* Make C-g and alarm signals set flags again. */
5240 clear_waiting_for_input ();
5242 /* If we woke up due to SIGWINCH, actually change size now. */
5243 do_pending_window_change (0);
5247 /* Exit the main loop if we've passed the requested timeout,
5248 or aren't skipping processes and got some output and
5249 haven't lowered our timeout due to timers or SIGIO and
5250 have waited a long amount of time due to repeated
5254 struct timespec cmp_time
5257 : (!process_skipped
&& got_some_output
> 0
5258 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5259 ? got_output_end_time
5260 : invalid_timespec ());
5261 if (timespec_valid_p (cmp_time
))
5263 now
= current_timespec ();
5264 if (timespec_cmp (cmp_time
, now
) <= 0)
5271 if (xerrno
== EINTR
)
5273 else if (xerrno
== EBADF
)
5276 report_file_errno ("Failed select", Qnil
, xerrno
);
5279 /* Check for keyboard input. */
5280 /* If there is any, return immediately
5281 to give it higher priority than subprocesses. */
5285 unsigned old_timers_run
= timers_run
;
5286 struct buffer
*old_buffer
= current_buffer
;
5287 Lisp_Object old_window
= selected_window
;
5290 if (detect_input_pending_run_timers (do_display
))
5292 swallow_events (do_display
);
5293 if (detect_input_pending_run_timers (do_display
))
5297 /* If a timer has run, this might have changed buffers
5298 an alike. Make read_key_sequence aware of that. */
5299 if (timers_run
!= old_timers_run
5300 && waiting_for_user_input_p
== -1
5301 && (old_buffer
!= current_buffer
5302 || !EQ (old_window
, selected_window
)))
5303 record_asynch_buffer_change ();
5309 /* If there is unread keyboard input, also return. */
5311 && requeued_events_pending_p ())
5314 /* If we are not checking for keyboard input now,
5315 do process events (but don't run any timers).
5316 This is so that X events will be processed.
5317 Otherwise they may have to wait until polling takes place.
5318 That would causes delays in pasting selections, for example.
5320 (We used to do this only if wait_for_cell.) */
5321 if (read_kbd
== 0 && detect_input_pending ())
5323 swallow_events (do_display
);
5324 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5325 if (detect_input_pending ())
5330 /* Exit now if the cell we're waiting for became non-nil. */
5331 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5335 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5336 go read it. This can happen with X on BSD after logging out.
5337 In that case, there really is no input and no SIGIO,
5338 but select says there is input. */
5340 if (read_kbd
&& interrupt_input
5341 && keyboard_bit_set (&Available
) && ! noninteractive
)
5342 handle_input_available_signal (SIGIO
);
5345 /* If checking input just got us a size-change event from X,
5346 obey it now if we should. */
5347 if (read_kbd
|| ! NILP (wait_for_cell
))
5348 do_pending_window_change (0);
5350 /* Check for data from a process. */
5351 if (no_avail
|| nfds
== 0)
5354 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5356 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5358 && ((d
->condition
& FOR_READ
5359 && FD_ISSET (channel
, &Available
))
5360 || (d
->condition
& FOR_WRITE
5361 && FD_ISSET (channel
, &write_mask
))))
5362 d
->func (channel
, d
->data
);
5365 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5367 if (FD_ISSET (channel
, &Available
)
5368 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5369 && !FD_ISSET (channel
, &non_process_wait_mask
))
5373 /* If waiting for this channel, arrange to return as
5374 soon as no more input to be processed. No more
5376 proc
= chan_process
[channel
];
5380 /* If this is a server stream socket, accept connection. */
5381 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5383 server_accept_connection (proc
, channel
);
5387 /* Read data from the process, starting with our
5388 buffered-ahead character if we have one. */
5390 nread
= read_process_output (proc
, channel
);
5391 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5392 && got_some_output
< nread
)
5393 got_some_output
= nread
;
5396 /* Vacuum up any leftovers without waiting. */
5397 if (wait_proc
== XPROCESS (proc
))
5399 /* Since read_process_output can run a filter,
5400 which can call accept-process-output,
5401 don't try to read from any other processes
5402 before doing the select again. */
5403 FD_ZERO (&Available
);
5406 redisplay_preserve_echo_area (12);
5408 else if (nread
== -1 && would_block (errno
))
5411 /* FIXME: Is this special case still needed? */
5412 /* Note that we cannot distinguish between no input
5413 available now and a closed pipe.
5414 With luck, a closed pipe will be accompanied by
5415 subprocess termination and SIGCHLD. */
5416 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5417 && !PIPECONN_P (proc
))
5421 /* On some OSs with ptys, when the process on one end of
5422 a pty exits, the other end gets an error reading with
5423 errno = EIO instead of getting an EOF (0 bytes read).
5424 Therefore, if we get an error reading and errno =
5425 EIO, just continue, because the child process has
5426 exited and should clean itself up soon (e.g. when we
5428 else if (nread
== -1 && errno
== EIO
)
5430 struct Lisp_Process
*p
= XPROCESS (proc
);
5432 /* Clear the descriptor now, so we only raise the
5434 FD_CLR (channel
, &input_wait_mask
);
5435 FD_CLR (channel
, &non_keyboard_wait_mask
);
5439 /* If the EIO occurs on a pty, the SIGCHLD handler's
5440 waitpid call will not find the process object to
5441 delete. Do it here. */
5442 p
->tick
= ++process_tick
;
5443 pset_status (p
, Qfailed
);
5446 #endif /* HAVE_PTYS */
5447 /* If we can detect process termination, don't consider the
5448 process gone just because its pipe is closed. */
5449 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5450 && !PIPECONN_P (proc
))
5452 else if (nread
== 0 && PIPECONN_P (proc
))
5454 /* Preserve status of processes already terminated. */
5455 XPROCESS (proc
)->tick
= ++process_tick
;
5456 deactivate_process (proc
);
5457 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5458 pset_status (XPROCESS (proc
),
5459 list2 (Qexit
, make_number (0)));
5463 /* Preserve status of processes already terminated. */
5464 XPROCESS (proc
)->tick
= ++process_tick
;
5465 deactivate_process (proc
);
5466 if (XPROCESS (proc
)->raw_status_new
)
5467 update_status (XPROCESS (proc
));
5468 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5469 pset_status (XPROCESS (proc
),
5470 list2 (Qexit
, make_number (256)));
5473 if (FD_ISSET (channel
, &Writeok
)
5474 && FD_ISSET (channel
, &connect_wait_mask
))
5476 struct Lisp_Process
*p
;
5478 FD_CLR (channel
, &connect_wait_mask
);
5479 FD_CLR (channel
, &write_mask
);
5480 if (--num_pending_connects
< 0)
5483 proc
= chan_process
[channel
];
5487 p
= XPROCESS (proc
);
5490 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5491 So only use it on systems where it is known to work. */
5493 socklen_t xlen
= sizeof (xerrno
);
5494 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5499 struct sockaddr pname
;
5500 socklen_t pnamelen
= sizeof (pname
);
5502 /* If connection failed, getpeername will fail. */
5504 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5506 /* Obtain connect failure code through error slippage. */
5509 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5516 p
->tick
= ++process_tick
;
5517 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5518 deactivate_process (proc
);
5523 /* If we have an incompletely set up TLS connection,
5524 then defer the sentinel signaling until
5526 if (NILP (p
->gnutls_boot_parameters
)
5530 pset_status (p
, Qrun
);
5531 /* Execute the sentinel here. If we had relied on
5532 status_notify to do it later, it will read input
5533 from the process before calling the sentinel. */
5534 exec_sentinel (proc
, build_string ("open\n"));
5537 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5538 && !EQ (p
->command
, Qt
))
5540 FD_SET (p
->infd
, &input_wait_mask
);
5541 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5545 } /* End for each file descriptor. */
5546 } /* End while exit conditions not met. */
5548 unbind_to (count
, Qnil
);
5550 /* If calling from keyboard input, do not quit
5551 since we want to return C-g as an input character.
5552 Otherwise, do pending quit if requested. */
5555 /* Prevent input_pending from remaining set if we quit. */
5556 clear_input_pending ();
5560 return got_some_output
;
5563 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5566 read_process_output_call (Lisp_Object fun_and_args
)
5568 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5572 read_process_output_error_handler (Lisp_Object error_val
)
5574 cmd_error_internal (error_val
, "error in process filter: ");
5576 update_echo_area ();
5577 Fsleep_for (make_number (2), Qnil
);
5582 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5584 struct coding_system
*coding
);
5586 /* Read pending output from the process channel,
5587 starting with our buffered-ahead character if we have one.
5588 Yield number of decoded characters read.
5590 This function reads at most 4096 characters.
5591 If you want to read all available subprocess output,
5592 you must call it repeatedly until it returns zero.
5594 The characters read are decoded according to PROC's coding-system
5598 read_process_output (Lisp_Object proc
, int channel
)
5601 struct Lisp_Process
*p
= XPROCESS (proc
);
5602 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5603 int carryover
= p
->decoding_carryover
;
5604 enum { readmax
= 4096 };
5605 ptrdiff_t count
= SPECPDL_INDEX ();
5606 Lisp_Object odeactivate
;
5607 char chars
[sizeof coding
->carryover
+ readmax
];
5610 /* See the comment above. */
5611 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5613 #ifdef DATAGRAM_SOCKETS
5614 /* We have a working select, so proc_buffered_char is always -1. */
5615 if (DATAGRAM_CHAN_P (channel
))
5617 socklen_t len
= datagram_address
[channel
].len
;
5618 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5619 0, datagram_address
[channel
].sa
, &len
);
5624 bool buffered
= proc_buffered_char
[channel
] >= 0;
5627 chars
[carryover
] = proc_buffered_char
[channel
];
5628 proc_buffered_char
[channel
] = -1;
5631 if (p
->gnutls_p
&& p
->gnutls_state
)
5632 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5633 readmax
- buffered
);
5636 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5637 readmax
- buffered
);
5638 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5640 int delay
= p
->read_output_delay
;
5643 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5646 process_output_delay_count
++;
5647 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5650 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5652 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5654 process_output_delay_count
--;
5656 p
->read_output_delay
= delay
;
5659 p
->read_output_skip
= 1;
5660 process_output_skip
= 1;
5664 nbytes
+= buffered
&& nbytes
<= 0;
5667 p
->decoding_carryover
= 0;
5669 /* At this point, NBYTES holds number of bytes just received
5670 (including the one in proc_buffered_char[channel]). */
5673 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5675 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5678 /* Now set NBYTES how many bytes we must decode. */
5679 nbytes
+= carryover
;
5681 odeactivate
= Vdeactivate_mark
;
5682 /* There's no good reason to let process filters change the current
5683 buffer, and many callers of accept-process-output, sit-for, and
5684 friends don't expect current-buffer to be changed from under them. */
5685 record_unwind_current_buffer ();
5687 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5689 /* Handling the process output should not deactivate the mark. */
5690 Vdeactivate_mark
= odeactivate
;
5692 unbind_to (count
, Qnil
);
5697 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5699 struct coding_system
*coding
)
5701 Lisp_Object outstream
= p
->filter
;
5703 bool outer_running_asynch_code
= running_asynch_code
;
5704 int waiting
= waiting_for_user_input_p
;
5707 Lisp_Object obuffer
, okeymap
;
5708 XSETBUFFER (obuffer
, current_buffer
);
5709 okeymap
= BVAR (current_buffer
, keymap
);
5712 /* We inhibit quit here instead of just catching it so that
5713 hitting ^G when a filter happens to be running won't screw
5715 specbind (Qinhibit_quit
, Qt
);
5716 specbind (Qlast_nonmenu_event
, Qt
);
5718 /* In case we get recursively called,
5719 and we already saved the match data nonrecursively,
5720 save the same match data in safely recursive fashion. */
5721 if (outer_running_asynch_code
)
5724 /* Don't clobber the CURRENT match data, either! */
5725 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5726 restore_search_regs ();
5727 record_unwind_save_match_data ();
5728 Fset_match_data (tem
, Qt
);
5731 /* For speed, if a search happens within this code,
5732 save the match data in a special nonrecursive fashion. */
5733 running_asynch_code
= 1;
5735 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5736 text
= coding
->dst_object
;
5737 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5738 /* A new coding system might be found. */
5739 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5741 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5743 /* Don't call setup_coding_system for
5744 proc_decode_coding_system[channel] here. It is done in
5745 detect_coding called via decode_coding above. */
5747 /* If a coding system for encoding is not yet decided, we set
5748 it as the same as coding-system for decoding.
5750 But, before doing that we must check if
5751 proc_encode_coding_system[p->outfd] surely points to a
5752 valid memory because p->outfd will be changed once EOF is
5753 sent to the process. */
5754 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5755 && proc_encode_coding_system
[p
->outfd
])
5757 pset_encode_coding_system
5758 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5759 setup_coding_system (p
->encode_coding_system
,
5760 proc_encode_coding_system
[p
->outfd
]);
5764 if (coding
->carryover_bytes
> 0)
5766 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5767 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5768 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5769 coding
->carryover_bytes
);
5770 p
->decoding_carryover
= coding
->carryover_bytes
;
5772 if (SBYTES (text
) > 0)
5773 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5774 sometimes it's simply wrong to wrap (e.g. when called from
5775 accept-process-output). */
5776 internal_condition_case_1 (read_process_output_call
,
5777 list3 (outstream
, make_lisp_proc (p
), text
),
5778 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5779 read_process_output_error_handler
);
5781 /* If we saved the match data nonrecursively, restore it now. */
5782 restore_search_regs ();
5783 running_asynch_code
= outer_running_asynch_code
;
5785 /* Restore waiting_for_user_input_p as it was
5786 when we were called, in case the filter clobbered it. */
5787 waiting_for_user_input_p
= waiting
;
5789 #if 0 /* Call record_asynch_buffer_change unconditionally,
5790 because we might have changed minor modes or other things
5791 that affect key bindings. */
5792 if (! EQ (Fcurrent_buffer (), obuffer
)
5793 || ! EQ (current_buffer
->keymap
, okeymap
))
5795 /* But do it only if the caller is actually going to read events.
5796 Otherwise there's no need to make him wake up, and it could
5797 cause trouble (for example it would make sit_for return). */
5798 if (waiting_for_user_input_p
== -1)
5799 record_asynch_buffer_change ();
5802 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5803 Sinternal_default_process_filter
, 2, 2, 0,
5804 doc
: /* Function used as default process filter.
5805 This inserts the process's output into its buffer, if there is one.
5806 Otherwise it discards the output. */)
5807 (Lisp_Object proc
, Lisp_Object text
)
5809 struct Lisp_Process
*p
;
5812 CHECK_PROCESS (proc
);
5813 p
= XPROCESS (proc
);
5814 CHECK_STRING (text
);
5816 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5818 Lisp_Object old_read_only
;
5819 ptrdiff_t old_begv
, old_zv
;
5820 ptrdiff_t old_begv_byte
, old_zv_byte
;
5821 ptrdiff_t before
, before_byte
;
5822 ptrdiff_t opoint_byte
;
5825 Fset_buffer (p
->buffer
);
5827 opoint_byte
= PT_BYTE
;
5828 old_read_only
= BVAR (current_buffer
, read_only
);
5831 old_begv_byte
= BEGV_BYTE
;
5832 old_zv_byte
= ZV_BYTE
;
5834 bset_read_only (current_buffer
, Qnil
);
5836 /* Insert new output into buffer at the current end-of-output
5837 marker, thus preserving logical ordering of input and output. */
5838 if (XMARKER (p
->mark
)->buffer
)
5839 set_point_from_marker (p
->mark
);
5841 SET_PT_BOTH (ZV
, ZV_BYTE
);
5843 before_byte
= PT_BYTE
;
5845 /* If the output marker is outside of the visible region, save
5846 the restriction and widen. */
5847 if (! (BEGV
<= PT
&& PT
<= ZV
))
5850 /* Adjust the multibyteness of TEXT to that of the buffer. */
5851 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5852 != ! STRING_MULTIBYTE (text
))
5853 text
= (STRING_MULTIBYTE (text
)
5854 ? Fstring_as_unibyte (text
)
5855 : Fstring_to_multibyte (text
));
5856 /* Insert before markers in case we are inserting where
5857 the buffer's mark is, and the user's next command is Meta-y. */
5858 insert_from_string_before_markers (text
, 0, 0,
5859 SCHARS (text
), SBYTES (text
), 0);
5861 /* Make sure the process marker's position is valid when the
5862 process buffer is changed in the signal_after_change above.
5863 W3 is known to do that. */
5864 if (BUFFERP (p
->buffer
)
5865 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5866 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5868 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5870 update_mode_lines
= 23;
5872 /* Make sure opoint and the old restrictions
5873 float ahead of any new text just as point would. */
5874 if (opoint
>= before
)
5876 opoint
+= PT
- before
;
5877 opoint_byte
+= PT_BYTE
- before_byte
;
5879 if (old_begv
> before
)
5881 old_begv
+= PT
- before
;
5882 old_begv_byte
+= PT_BYTE
- before_byte
;
5884 if (old_zv
>= before
)
5886 old_zv
+= PT
- before
;
5887 old_zv_byte
+= PT_BYTE
- before_byte
;
5890 /* If the restriction isn't what it should be, set it. */
5891 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5892 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5894 bset_read_only (current_buffer
, old_read_only
);
5895 SET_PT_BOTH (opoint
, opoint_byte
);
5900 /* Sending data to subprocess. */
5902 /* In send_process, when a write fails temporarily,
5903 wait_reading_process_output is called. It may execute user code,
5904 e.g. timers, that attempts to write new data to the same process.
5905 We must ensure that data is sent in the right order, and not
5906 interspersed half-completed with other writes (Bug#10815). This is
5907 handled by the write_queue element of struct process. It is a list
5908 with each entry having the form
5910 (string . (offset . length))
5912 where STRING is a lisp string, OFFSET is the offset into the
5913 string's byte sequence from which we should begin to send, and
5914 LENGTH is the number of bytes left to send. */
5916 /* Create a new entry in write_queue.
5917 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5918 BUF is a pointer to the string sequence of the input_obj or a C
5919 string in case of Qt or Qnil. */
5922 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5923 const char *buf
, ptrdiff_t len
, bool front
)
5926 Lisp_Object entry
, obj
;
5928 if (STRINGP (input_obj
))
5930 offset
= buf
- SSDATA (input_obj
);
5936 obj
= make_unibyte_string (buf
, len
);
5939 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5942 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5944 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5947 /* Remove the first element in the write_queue of process P, put its
5948 contents in OBJ, BUF and LEN, and return true. If the
5949 write_queue is empty, return false. */
5952 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5953 const char **buf
, ptrdiff_t *len
)
5955 Lisp_Object entry
, offset_length
;
5958 if (NILP (p
->write_queue
))
5961 entry
= XCAR (p
->write_queue
);
5962 pset_write_queue (p
, XCDR (p
->write_queue
));
5964 *obj
= XCAR (entry
);
5965 offset_length
= XCDR (entry
);
5967 *len
= XINT (XCDR (offset_length
));
5968 offset
= XINT (XCAR (offset_length
));
5969 *buf
= SSDATA (*obj
) + offset
;
5974 /* Send some data to process PROC.
5975 BUF is the beginning of the data; LEN is the number of characters.
5976 OBJECT is the Lisp object that the data comes from. If OBJECT is
5977 nil or t, it means that the data comes from C string.
5979 If OBJECT is not nil, the data is encoded by PROC's coding-system
5980 for encoding before it is sent.
5982 This function can evaluate Lisp code and can garbage collect. */
5985 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5988 struct Lisp_Process
*p
= XPROCESS (proc
);
5990 struct coding_system
*coding
;
5992 if (NETCONN_P (proc
))
5994 wait_while_connecting (proc
);
5995 wait_for_tls_negotiation (proc
);
5998 if (p
->raw_status_new
)
6000 if (! EQ (p
->status
, Qrun
))
6001 error ("Process %s not running", SDATA (p
->name
));
6003 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6005 coding
= proc_encode_coding_system
[p
->outfd
];
6006 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6008 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6009 || (BUFFERP (object
)
6010 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6013 pset_encode_coding_system
6014 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6015 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6017 /* The coding system for encoding was changed to raw-text
6018 because we sent a unibyte text previously. Now we are
6019 sending a multibyte text, thus we must encode it by the
6020 original coding system specified for the current process.
6022 Another reason we come here is that the coding system
6023 was just complemented and a new one was returned by
6024 complement_process_encoding_system. */
6025 setup_coding_system (p
->encode_coding_system
, coding
);
6026 Vlast_coding_system_used
= p
->encode_coding_system
;
6028 coding
->src_multibyte
= 1;
6032 coding
->src_multibyte
= 0;
6033 /* For sending a unibyte text, character code conversion should
6034 not take place but EOL conversion should. So, setup raw-text
6035 or one of the subsidiary if we have not yet done it. */
6036 if (CODING_REQUIRE_ENCODING (coding
))
6038 if (CODING_REQUIRE_FLUSHING (coding
))
6040 /* But, before changing the coding, we must flush out data. */
6041 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6042 send_process (proc
, "", 0, Qt
);
6043 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6045 setup_coding_system (raw_text_coding_system
6046 (Vlast_coding_system_used
),
6048 coding
->src_multibyte
= 0;
6051 coding
->dst_multibyte
= 0;
6053 if (CODING_REQUIRE_ENCODING (coding
))
6055 coding
->dst_object
= Qt
;
6056 if (BUFFERP (object
))
6058 ptrdiff_t from_byte
, from
, to
;
6059 ptrdiff_t save_pt
, save_pt_byte
;
6060 struct buffer
*cur
= current_buffer
;
6062 set_buffer_internal (XBUFFER (object
));
6063 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6065 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6066 from
= BYTE_TO_CHAR (from_byte
);
6067 to
= BYTE_TO_CHAR (from_byte
+ len
);
6068 TEMP_SET_PT_BOTH (from
, from_byte
);
6069 encode_coding_object (coding
, object
, from
, from_byte
,
6070 to
, from_byte
+ len
, Qt
);
6071 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6072 set_buffer_internal (cur
);
6074 else if (STRINGP (object
))
6076 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6077 SBYTES (object
), Qt
);
6081 coding
->dst_object
= make_unibyte_string (buf
, len
);
6082 coding
->produced
= len
;
6085 len
= coding
->produced
;
6086 object
= coding
->dst_object
;
6087 buf
= SSDATA (object
);
6090 /* If there is already data in the write_queue, put the new data
6091 in the back of queue. Otherwise, ignore it. */
6092 if (!NILP (p
->write_queue
))
6093 write_queue_push (p
, object
, buf
, len
, 0);
6095 do /* while !NILP (p->write_queue) */
6097 ptrdiff_t cur_len
= -1;
6098 const char *cur_buf
;
6099 Lisp_Object cur_object
;
6101 /* If write_queue is empty, ignore it. */
6102 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6106 cur_object
= object
;
6111 /* Send this batch, using one or more write calls. */
6112 ptrdiff_t written
= 0;
6113 int outfd
= p
->outfd
;
6114 #ifdef DATAGRAM_SOCKETS
6115 if (DATAGRAM_CHAN_P (outfd
))
6117 rv
= sendto (outfd
, cur_buf
, cur_len
,
6118 0, datagram_address
[outfd
].sa
,
6119 datagram_address
[outfd
].len
);
6122 else if (errno
== EMSGSIZE
)
6123 report_file_error ("Sending datagram", proc
);
6129 if (p
->gnutls_p
&& p
->gnutls_state
)
6130 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6133 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6134 rv
= (written
? 0 : -1);
6135 if (p
->read_output_delay
> 0
6136 && p
->adaptive_read_buffering
== 1)
6138 p
->read_output_delay
= 0;
6139 process_output_delay_count
--;
6140 p
->read_output_skip
= 0;
6146 if (would_block (errno
))
6147 /* Buffer is full. Wait, accepting input;
6148 that may allow the program
6149 to finish doing output and read more. */
6151 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6152 /* A gross hack to work around a bug in FreeBSD.
6153 In the following sequence, read(2) returns
6157 write(2) 954 bytes, get EAGAIN
6158 read(2) 1024 bytes in process_read_output
6159 read(2) 11 bytes in process_read_output
6161 That is, read(2) returns more bytes than have
6162 ever been written successfully. The 1033 bytes
6163 read are the 1022 bytes written successfully
6164 after processing (for example with CRs added if
6165 the terminal is set up that way which it is
6166 here). The same bytes will be seen again in a
6167 later read(2), without the CRs. */
6169 if (errno
== EAGAIN
)
6172 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6174 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6176 /* Put what we should have written in wait_queue. */
6177 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6178 wait_reading_process_output (0, 20 * 1000 * 1000,
6179 0, 0, Qnil
, NULL
, 0);
6180 /* Reread queue, to see what is left. */
6183 else if (errno
== EPIPE
)
6185 p
->raw_status_new
= 0;
6186 pset_status (p
, list2 (Qexit
, make_number (256)));
6187 p
->tick
= ++process_tick
;
6188 deactivate_process (proc
);
6189 error ("process %s no longer connected to pipe; closed it",
6193 /* This is a real error. */
6194 report_file_error ("Writing to process", proc
);
6200 while (!NILP (p
->write_queue
));
6203 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6205 doc
: /* Send current contents of region as input to PROCESS.
6206 PROCESS may be a process, a buffer, the name of a process or buffer, or
6207 nil, indicating the current buffer's process.
6208 Called from program, takes three arguments, PROCESS, START and END.
6209 If the region is more than 500 characters long,
6210 it is sent in several bunches. This may happen even for shorter regions.
6211 Output from processes can arrive in between bunches.
6213 If PROCESS is a non-blocking network process that hasn't been fully
6214 set up yet, this function will block until socket setup has completed. */)
6215 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6217 Lisp_Object proc
= get_process (process
);
6218 ptrdiff_t start_byte
, end_byte
;
6220 validate_region (&start
, &end
);
6222 start_byte
= CHAR_TO_BYTE (XINT (start
));
6223 end_byte
= CHAR_TO_BYTE (XINT (end
));
6225 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6226 move_gap_both (XINT (start
), start_byte
);
6228 if (NETCONN_P (proc
))
6229 wait_while_connecting (proc
);
6231 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6232 end_byte
- start_byte
, Fcurrent_buffer ());
6237 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6239 doc
: /* Send PROCESS the contents of STRING as input.
6240 PROCESS may be a process, a buffer, the name of a process or buffer, or
6241 nil, indicating the current buffer's process.
6242 If STRING is more than 500 characters long,
6243 it is sent in several bunches. This may happen even for shorter strings.
6244 Output from processes can arrive in between bunches.
6246 If PROCESS is a non-blocking network process that hasn't been fully
6247 set up yet, this function will block until socket setup has completed. */)
6248 (Lisp_Object process
, Lisp_Object string
)
6250 CHECK_STRING (string
);
6251 Lisp_Object proc
= get_process (process
);
6252 send_process (proc
, SSDATA (string
),
6253 SBYTES (string
), string
);
6257 /* Return the foreground process group for the tty/pty that
6258 the process P uses. */
6260 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6265 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6268 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6269 master side. Try the slave side. */
6270 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6274 ioctl (fd
, TIOCGPGRP
, &gid
);
6278 #endif /* defined (TIOCGPGRP ) */
6283 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6284 Sprocess_running_child_p
, 0, 1, 0,
6285 doc
: /* Return non-nil if PROCESS has given the terminal to a
6286 child. If the operating system does not make it possible to find out,
6287 return t. If we can find out, return the numeric ID of the foreground
6289 (Lisp_Object process
)
6291 /* Initialize in case ioctl doesn't exist or gives an error,
6292 in a way that will cause returning t. */
6293 Lisp_Object proc
= get_process (process
);
6294 struct Lisp_Process
*p
= XPROCESS (proc
);
6296 if (!EQ (p
->type
, Qreal
))
6297 error ("Process %s is not a subprocess",
6300 error ("Process %s is not active",
6303 pid_t gid
= emacs_get_tty_pgrp (p
);
6308 return make_number (gid
);
6312 /* Send a signal number SIGNO to PROCESS.
6313 If CURRENT_GROUP is t, that means send to the process group
6314 that currently owns the terminal being used to communicate with PROCESS.
6315 This is used for various commands in shell mode.
6316 If CURRENT_GROUP is lambda, that means send to the process group
6317 that currently owns the terminal, but only if it is NOT the shell itself.
6319 If NOMSG is false, insert signal-announcements into process's buffers
6322 If we can, we try to signal PROCESS by sending control characters
6323 down the pty. This allows us to signal inferiors who have changed
6324 their uid, for which kill would return an EPERM error. */
6327 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6331 struct Lisp_Process
*p
;
6335 proc
= get_process (process
);
6336 p
= XPROCESS (proc
);
6338 if (!EQ (p
->type
, Qreal
))
6339 error ("Process %s is not a subprocess",
6342 error ("Process %s is not active",
6346 current_group
= Qnil
;
6348 /* If we are using pgrps, get a pgrp number and make it negative. */
6349 if (NILP (current_group
))
6350 /* Send the signal to the shell's process group. */
6354 #ifdef SIGNALS_VIA_CHARACTERS
6355 /* If possible, send signals to the entire pgrp
6356 by sending an input character to it. */
6359 cc_t
*sig_char
= NULL
;
6361 tcgetattr (p
->infd
, &t
);
6366 sig_char
= &t
.c_cc
[VINTR
];
6370 sig_char
= &t
.c_cc
[VQUIT
];
6375 sig_char
= &t
.c_cc
[VSWTCH
];
6377 sig_char
= &t
.c_cc
[VSUSP
];
6382 if (sig_char
&& *sig_char
!= CDISABLE
)
6384 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6387 /* If we can't send the signal with a character,
6388 fall through and send it another way. */
6390 /* The code above may fall through if it can't
6391 handle the signal. */
6392 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6395 /* Get the current pgrp using the tty itself, if we have that.
6396 Otherwise, use the pty to get the pgrp.
6397 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6398 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6399 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6400 His patch indicates that if TIOCGPGRP returns an error, then
6401 we should just assume that p->pid is also the process group id. */
6403 gid
= emacs_get_tty_pgrp (p
);
6406 /* If we can't get the information, assume
6407 the shell owns the tty. */
6410 /* It is not clear whether anything really can set GID to -1.
6411 Perhaps on some system one of those ioctls can or could do so.
6412 Or perhaps this is vestigial. */
6415 #else /* ! defined (TIOCGPGRP) */
6416 /* Can't select pgrps on this system, so we know that
6417 the child itself heads the pgrp. */
6419 #endif /* ! defined (TIOCGPGRP) */
6421 /* If current_group is lambda, and the shell owns the terminal,
6422 don't send any signal. */
6423 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6428 if (signo
== SIGCONT
)
6430 p
->raw_status_new
= 0;
6431 pset_status (p
, Qrun
);
6432 p
->tick
= ++process_tick
;
6435 status_notify (NULL
, NULL
);
6436 redisplay_preserve_echo_area (13);
6442 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6443 We don't know whether the bug is fixed in later HP-UX versions. */
6444 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6448 /* If we don't have process groups, send the signal to the immediate
6449 subprocess. That isn't really right, but it's better than any
6450 obvious alternative. */
6451 pid_t pid
= no_pgrp
? gid
: - gid
;
6453 /* Do not kill an already-reaped process, as that could kill an
6454 innocent bystander that happens to have the same process ID. */
6456 block_child_signal (&oldset
);
6459 unblock_child_signal (&oldset
);
6462 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6463 doc
: /* Interrupt process PROCESS.
6464 PROCESS may be a process, a buffer, or the name of a process or buffer.
6465 No arg or nil means current buffer's process.
6466 Second arg CURRENT-GROUP non-nil means send signal to
6467 the current process-group of the process's controlling terminal
6468 rather than to the process's own process group.
6469 If the process is a shell, this means interrupt current subjob
6470 rather than the shell.
6472 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6473 don't send the signal. */)
6474 (Lisp_Object process
, Lisp_Object current_group
)
6476 process_send_signal (process
, SIGINT
, current_group
, 0);
6480 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6481 doc
: /* Kill process PROCESS. May be process or name of one.
6482 See function `interrupt-process' for more details on usage. */)
6483 (Lisp_Object process
, Lisp_Object current_group
)
6485 process_send_signal (process
, SIGKILL
, current_group
, 0);
6489 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6490 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6491 See function `interrupt-process' for more details on usage. */)
6492 (Lisp_Object process
, Lisp_Object current_group
)
6494 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6498 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6499 doc
: /* Stop process PROCESS. May be process or name of one.
6500 See function `interrupt-process' for more details on usage.
6501 If PROCESS is a network or serial process, inhibit handling of incoming
6503 (Lisp_Object process
, Lisp_Object current_group
)
6505 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6506 || PIPECONN_P (process
)))
6508 struct Lisp_Process
*p
;
6510 p
= XPROCESS (process
);
6511 if (NILP (p
->command
)
6514 FD_CLR (p
->infd
, &input_wait_mask
);
6515 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6517 pset_command (p
, Qt
);
6521 error ("No SIGTSTP support");
6523 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6528 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6529 doc
: /* Continue process PROCESS. May be process or name of one.
6530 See function `interrupt-process' for more details on usage.
6531 If PROCESS is a network or serial process, resume handling of incoming
6533 (Lisp_Object process
, Lisp_Object current_group
)
6535 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6536 || PIPECONN_P (process
)))
6538 struct Lisp_Process
*p
;
6540 p
= XPROCESS (process
);
6541 if (EQ (p
->command
, Qt
)
6543 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6545 FD_SET (p
->infd
, &input_wait_mask
);
6546 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6548 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6549 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6550 #else /* not WINDOWSNT */
6551 tcflush (p
->infd
, TCIFLUSH
);
6552 #endif /* not WINDOWSNT */
6554 pset_command (p
, Qnil
);
6558 process_send_signal (process
, SIGCONT
, current_group
, 0);
6560 error ("No SIGCONT support");
6565 /* Return the integer value of the signal whose abbreviation is ABBR,
6566 or a negative number if there is no such signal. */
6568 abbr_to_signal (char const *name
)
6571 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6573 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6576 for (i
= 0; i
< sizeof sigbuf
; i
++)
6578 sigbuf
[i
] = c_toupper (name
[i
]);
6580 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6586 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6587 2, 2, "sProcess (name or number): \nnSignal code: ",
6588 doc
: /* Send PROCESS the signal with code SIGCODE.
6589 PROCESS may also be a number specifying the process id of the
6590 process to signal; in this case, the process need not be a child of
6592 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6593 (Lisp_Object process
, Lisp_Object sigcode
)
6598 if (STRINGP (process
))
6600 Lisp_Object tem
= Fget_process (process
);
6603 Lisp_Object process_number
6604 = string_to_number (SSDATA (process
), 10, 1);
6605 if (NUMBERP (process_number
))
6606 tem
= process_number
;
6610 else if (!NUMBERP (process
))
6611 process
= get_process (process
);
6616 if (NUMBERP (process
))
6617 CONS_TO_INTEGER (process
, pid_t
, pid
);
6620 CHECK_PROCESS (process
);
6621 pid
= XPROCESS (process
)->pid
;
6623 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6626 if (INTEGERP (sigcode
))
6628 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6629 signo
= XINT (sigcode
);
6635 CHECK_SYMBOL (sigcode
);
6636 name
= SSDATA (SYMBOL_NAME (sigcode
));
6638 signo
= abbr_to_signal (name
);
6640 error ("Undefined signal name %s", name
);
6643 return make_number (kill (pid
, signo
));
6646 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6647 doc
: /* Make PROCESS see end-of-file in its input.
6648 EOF comes after any text already sent to it.
6649 PROCESS may be a process, a buffer, the name of a process or buffer, or
6650 nil, indicating the current buffer's process.
6651 If PROCESS is a network connection, or is a process communicating
6652 through a pipe (as opposed to a pty), then you cannot send any more
6653 text to PROCESS after you call this function.
6654 If PROCESS is a serial process, wait until all output written to the
6655 process has been transmitted to the serial port. */)
6656 (Lisp_Object process
)
6659 struct coding_system
*coding
= NULL
;
6662 proc
= get_process (process
);
6664 if (NETCONN_P (proc
))
6665 wait_while_connecting (proc
);
6667 if (DATAGRAM_CONN_P (proc
))
6671 outfd
= XPROCESS (proc
)->outfd
;
6673 coding
= proc_encode_coding_system
[outfd
];
6675 /* Make sure the process is really alive. */
6676 if (XPROCESS (proc
)->raw_status_new
)
6677 update_status (XPROCESS (proc
));
6678 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6679 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6681 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6683 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6684 send_process (proc
, "", 0, Qnil
);
6687 if (XPROCESS (proc
)->pty_flag
)
6688 send_process (proc
, "\004", 1, Qnil
);
6689 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6692 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6693 report_file_error ("Failed tcdrain", Qnil
);
6694 #endif /* not WINDOWSNT */
6695 /* Do nothing on Windows because writes are blocking. */
6699 struct Lisp_Process
*p
= XPROCESS (proc
);
6700 int old_outfd
= p
->outfd
;
6703 #ifdef HAVE_SHUTDOWN
6704 /* If this is a network connection, or socketpair is used
6705 for communication with the subprocess, call shutdown to cause EOF.
6706 (In some old system, shutdown to socketpair doesn't work.
6707 Then we just can't win.) */
6709 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6710 shutdown (old_outfd
, 1);
6712 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6713 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6715 report_file_error ("Opening null device", Qnil
);
6716 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6717 p
->outfd
= new_outfd
;
6719 if (!proc_encode_coding_system
[new_outfd
])
6720 proc_encode_coding_system
[new_outfd
]
6721 = xmalloc (sizeof (struct coding_system
));
6724 *proc_encode_coding_system
[new_outfd
]
6725 = *proc_encode_coding_system
[old_outfd
];
6726 memset (proc_encode_coding_system
[old_outfd
], 0,
6727 sizeof (struct coding_system
));
6730 setup_coding_system (p
->encode_coding_system
,
6731 proc_encode_coding_system
[new_outfd
]);
6736 /* The main Emacs thread records child processes in three places:
6738 - Vprocess_alist, for asynchronous subprocesses, which are child
6739 processes visible to Lisp.
6741 - deleted_pid_list, for child processes invisible to Lisp,
6742 typically because of delete-process. These are recorded so that
6743 the processes can be reaped when they exit, so that the operating
6744 system's process table is not cluttered by zombies.
6746 - the local variable PID in Fcall_process, call_process_cleanup and
6747 call_process_kill, for synchronous subprocesses.
6748 record_unwind_protect is used to make sure this process is not
6749 forgotten: if the user interrupts call-process and the child
6750 process refuses to exit immediately even with two C-g's,
6751 call_process_kill adds PID's contents to deleted_pid_list before
6754 The main Emacs thread invokes waitpid only on child processes that
6755 it creates and that have not been reaped. This avoid races on
6756 platforms such as GTK, where other threads create their own
6757 subprocesses which the main thread should not reap. For example,
6758 if the main thread attempted to reap an already-reaped child, it
6759 might inadvertently reap a GTK-created process that happened to
6760 have the same process ID. */
6762 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6763 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6764 keep track of its own children. GNUstep is similar. */
6766 static void dummy_handler (int sig
) {}
6767 static signal_handler_t
volatile lib_child_handler
;
6769 /* Handle a SIGCHLD signal by looking for known child processes of
6770 Emacs whose status have changed. For each one found, record its
6773 All we do is change the status; we do not run sentinels or print
6774 notifications. That is saved for the next time keyboard input is
6775 done, in order to avoid timing errors.
6777 ** WARNING: this can be called during garbage collection.
6778 Therefore, it must not be fooled by the presence of mark bits in
6781 ** USG WARNING: Although it is not obvious from the documentation
6782 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6783 signal() before executing at least one wait(), otherwise the
6784 handler will be called again, resulting in an infinite loop. The
6785 relevant portion of the documentation reads "SIGCLD signals will be
6786 queued and the signal-catching function will be continually
6787 reentered until the queue is empty". Invoking signal() causes the
6788 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6791 ** Malloc WARNING: This should never call malloc either directly or
6792 indirectly; if it does, that is a bug. */
6795 handle_child_signal (int sig
)
6797 Lisp_Object tail
, proc
;
6799 /* Find the process that signaled us, and record its status. */
6801 /* The process can have been deleted by Fdelete_process, or have
6802 been started asynchronously by Fcall_process. */
6803 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6805 bool all_pids_are_fixnums
6806 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6807 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6808 Lisp_Object head
= XCAR (tail
);
6813 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6816 if (INTEGERP (xpid
))
6817 deleted_pid
= XINT (xpid
);
6819 deleted_pid
= XFLOAT_DATA (xpid
);
6820 if (child_status_changed (deleted_pid
, 0, 0))
6822 if (STRINGP (XCDR (head
)))
6823 unlink (SSDATA (XCDR (head
)));
6824 XSETCAR (tail
, Qnil
);
6829 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6830 FOR_EACH_PROCESS (tail
, proc
)
6832 struct Lisp_Process
*p
= XPROCESS (proc
);
6836 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6838 /* Change the status of the process that was found. */
6839 p
->tick
= ++process_tick
;
6840 p
->raw_status
= status
;
6841 p
->raw_status_new
= 1;
6843 /* If process has terminated, stop waiting for its output. */
6844 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6846 bool clear_desc_flag
= 0;
6849 clear_desc_flag
= 1;
6851 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6852 if (clear_desc_flag
)
6854 FD_CLR (p
->infd
, &input_wait_mask
);
6855 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6861 lib_child_handler (sig
);
6862 #ifdef NS_IMPL_GNUSTEP
6863 /* NSTask in GNUstep sets its child handler each time it is called.
6864 So we must re-set ours. */
6865 catch_child_signal ();
6870 deliver_child_signal (int sig
)
6872 deliver_process_signal (sig
, handle_child_signal
);
6877 exec_sentinel_error_handler (Lisp_Object error_val
)
6879 cmd_error_internal (error_val
, "error in process sentinel: ");
6881 update_echo_area ();
6882 Fsleep_for (make_number (2), Qnil
);
6887 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6889 Lisp_Object sentinel
, odeactivate
;
6890 struct Lisp_Process
*p
= XPROCESS (proc
);
6891 ptrdiff_t count
= SPECPDL_INDEX ();
6892 bool outer_running_asynch_code
= running_asynch_code
;
6893 int waiting
= waiting_for_user_input_p
;
6895 if (inhibit_sentinels
)
6898 odeactivate
= Vdeactivate_mark
;
6900 Lisp_Object obuffer
, okeymap
;
6901 XSETBUFFER (obuffer
, current_buffer
);
6902 okeymap
= BVAR (current_buffer
, keymap
);
6905 /* There's no good reason to let sentinels change the current
6906 buffer, and many callers of accept-process-output, sit-for, and
6907 friends don't expect current-buffer to be changed from under them. */
6908 record_unwind_current_buffer ();
6910 sentinel
= p
->sentinel
;
6912 /* Inhibit quit so that random quits don't screw up a running filter. */
6913 specbind (Qinhibit_quit
, Qt
);
6914 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6916 /* In case we get recursively called,
6917 and we already saved the match data nonrecursively,
6918 save the same match data in safely recursive fashion. */
6919 if (outer_running_asynch_code
)
6922 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6923 restore_search_regs ();
6924 record_unwind_save_match_data ();
6925 Fset_match_data (tem
, Qt
);
6928 /* For speed, if a search happens within this code,
6929 save the match data in a special nonrecursive fashion. */
6930 running_asynch_code
= 1;
6932 internal_condition_case_1 (read_process_output_call
,
6933 list3 (sentinel
, proc
, reason
),
6934 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6935 exec_sentinel_error_handler
);
6937 /* If we saved the match data nonrecursively, restore it now. */
6938 restore_search_regs ();
6939 running_asynch_code
= outer_running_asynch_code
;
6941 Vdeactivate_mark
= odeactivate
;
6943 /* Restore waiting_for_user_input_p as it was
6944 when we were called, in case the filter clobbered it. */
6945 waiting_for_user_input_p
= waiting
;
6948 if (! EQ (Fcurrent_buffer (), obuffer
)
6949 || ! EQ (current_buffer
->keymap
, okeymap
))
6951 /* But do it only if the caller is actually going to read events.
6952 Otherwise there's no need to make him wake up, and it could
6953 cause trouble (for example it would make sit_for return). */
6954 if (waiting_for_user_input_p
== -1)
6955 record_asynch_buffer_change ();
6957 unbind_to (count
, Qnil
);
6960 /* Report all recent events of a change in process status
6961 (either run the sentinel or output a message).
6962 This is usually done while Emacs is waiting for keyboard input
6963 but can be done at other times.
6965 Return positive if any input was received from WAIT_PROC (or from
6966 any process if WAIT_PROC is null), zero if input was attempted but
6967 none received, and negative if we didn't even try. */
6970 status_notify (struct Lisp_Process
*deleting_process
,
6971 struct Lisp_Process
*wait_proc
)
6974 Lisp_Object tail
, msg
;
6975 int got_some_output
= -1;
6980 /* Set this now, so that if new processes are created by sentinels
6981 that we run, we get called again to handle their status changes. */
6982 update_tick
= process_tick
;
6984 FOR_EACH_PROCESS (tail
, proc
)
6987 register struct Lisp_Process
*p
= XPROCESS (proc
);
6989 if (p
->tick
!= p
->update_tick
)
6991 p
->update_tick
= p
->tick
;
6993 /* If process is still active, read any output that remains. */
6994 while (! EQ (p
->filter
, Qt
)
6995 && ! EQ (p
->status
, Qconnect
)
6996 && ! EQ (p
->status
, Qlisten
)
6997 /* Network or serial process not stopped: */
6998 && ! EQ (p
->command
, Qt
)
7000 && p
!= deleting_process
)
7002 int nread
= read_process_output (proc
, p
->infd
);
7003 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7004 && got_some_output
< nread
)
7005 got_some_output
= nread
;
7010 /* Get the text to use for the message. */
7011 if (p
->raw_status_new
)
7013 msg
= status_message (p
);
7015 /* If process is terminated, deactivate it or delete it. */
7017 if (CONSP (p
->status
))
7018 symbol
= XCAR (p
->status
);
7020 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7021 || EQ (symbol
, Qclosed
))
7023 if (delete_exited_processes
)
7024 remove_process (proc
);
7026 deactivate_process (proc
);
7029 /* The actions above may have further incremented p->tick.
7030 So set p->update_tick again so that an error in the sentinel will
7031 not cause this code to be run again. */
7032 p
->update_tick
= p
->tick
;
7033 /* Now output the message suitably. */
7034 exec_sentinel (proc
, msg
);
7035 if (BUFFERP (p
->buffer
))
7036 /* In case it uses %s in mode-line-format. */
7037 bset_update_mode_line (XBUFFER (p
->buffer
));
7041 return got_some_output
;
7044 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7045 Sinternal_default_process_sentinel
, 2, 2, 0,
7046 doc
: /* Function used as default sentinel for processes.
7047 This inserts a status message into the process's buffer, if there is one. */)
7048 (Lisp_Object proc
, Lisp_Object msg
)
7050 Lisp_Object buffer
, symbol
;
7051 struct Lisp_Process
*p
;
7052 CHECK_PROCESS (proc
);
7053 p
= XPROCESS (proc
);
7057 symbol
= XCAR (symbol
);
7059 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7062 struct buffer
*old
= current_buffer
;
7063 ptrdiff_t opoint
, opoint_byte
;
7064 ptrdiff_t before
, before_byte
;
7066 /* Avoid error if buffer is deleted
7067 (probably that's why the process is dead, too). */
7068 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7070 Fset_buffer (buffer
);
7072 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7073 msg
= (code_convert_string_norecord
7074 (msg
, Vlocale_coding_system
, 1));
7077 opoint_byte
= PT_BYTE
;
7078 /* Insert new output into buffer
7079 at the current end-of-output marker,
7080 thus preserving logical ordering of input and output. */
7081 if (XMARKER (p
->mark
)->buffer
)
7082 Fgoto_char (p
->mark
);
7084 SET_PT_BOTH (ZV
, ZV_BYTE
);
7087 before_byte
= PT_BYTE
;
7089 tem
= BVAR (current_buffer
, read_only
);
7090 bset_read_only (current_buffer
, Qnil
);
7091 insert_string ("\nProcess ");
7092 { /* FIXME: temporary kludge. */
7093 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7094 insert_string (" ");
7096 bset_read_only (current_buffer
, tem
);
7097 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7099 if (opoint
>= before
)
7100 SET_PT_BOTH (opoint
+ (PT
- before
),
7101 opoint_byte
+ (PT_BYTE
- before_byte
));
7103 SET_PT_BOTH (opoint
, opoint_byte
);
7105 set_buffer_internal (old
);
7111 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7112 Sset_process_coding_system
, 1, 3, 0,
7113 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7114 DECODING will be used to decode subprocess output and ENCODING to
7115 encode subprocess input. */)
7116 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7118 CHECK_PROCESS (process
);
7120 struct Lisp_Process
*p
= XPROCESS (process
);
7122 Fcheck_coding_system (decoding
);
7123 Fcheck_coding_system (encoding
);
7124 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7125 pset_decode_coding_system (p
, decoding
);
7126 pset_encode_coding_system (p
, encoding
);
7128 /* If the sockets haven't been set up yet, the final setup part of
7129 this will be called asynchronously. */
7130 if (p
->infd
< 0 || p
->outfd
< 0)
7133 setup_process_coding_systems (process
);
7138 DEFUN ("process-coding-system",
7139 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7140 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7141 (register Lisp_Object process
)
7143 CHECK_PROCESS (process
);
7144 return Fcons (XPROCESS (process
)->decode_coding_system
,
7145 XPROCESS (process
)->encode_coding_system
);
7148 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7149 Sset_process_filter_multibyte
, 2, 2, 0,
7150 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7151 If FLAG is non-nil, the filter is given multibyte strings.
7152 If FLAG is nil, the filter is given unibyte strings. In this case,
7153 all character code conversion except for end-of-line conversion is
7155 (Lisp_Object process
, Lisp_Object flag
)
7157 CHECK_PROCESS (process
);
7159 struct Lisp_Process
*p
= XPROCESS (process
);
7161 pset_decode_coding_system
7162 (p
, raw_text_coding_system (p
->decode_coding_system
));
7164 /* If the sockets haven't been set up yet, the final setup part of
7165 this will be called asynchronously. */
7166 if (p
->infd
< 0 || p
->outfd
< 0)
7169 setup_process_coding_systems (process
);
7174 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7175 Sprocess_filter_multibyte_p
, 1, 1, 0,
7176 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7177 (Lisp_Object process
)
7179 CHECK_PROCESS (process
);
7180 struct Lisp_Process
*p
= XPROCESS (process
);
7183 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7184 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7193 add_gpm_wait_descriptor (int desc
)
7195 add_keyboard_wait_descriptor (desc
);
7199 delete_gpm_wait_descriptor (int desc
)
7201 delete_keyboard_wait_descriptor (desc
);
7206 # ifdef USABLE_SIGIO
7208 /* Return true if *MASK has a bit set
7209 that corresponds to one of the keyboard input descriptors. */
7212 keyboard_bit_set (fd_set
*mask
)
7216 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7217 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7218 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7225 #else /* not subprocesses */
7227 /* Defined in msdos.c. */
7228 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7229 struct timespec
*, void *);
7231 /* Implementation of wait_reading_process_output, assuming that there
7232 are no subprocesses. Used only by the MS-DOS build.
7234 Wait for timeout to elapse and/or keyboard input to be available.
7238 If negative, gobble data immediately available but don't wait for any.
7241 an additional duration to wait, measured in nanoseconds
7242 If TIME_LIMIT is zero, then:
7243 If NSECS == 0, there is no limit.
7244 If NSECS > 0, the timeout consists of NSECS only.
7245 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7248 0 to ignore keyboard input, or
7249 1 to return when input is available, or
7250 -1 means caller will actually read the input, so don't throw to
7253 see full version for other parameters. We know that wait_proc will
7254 always be NULL, since `subprocesses' isn't defined.
7256 DO_DISPLAY means redisplay should be done to show subprocess
7257 output that arrives.
7259 Return -1 signifying we got no output and did not try. */
7262 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7264 Lisp_Object wait_for_cell
,
7265 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7268 struct timespec end_time
, timeout
;
7269 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7271 if (TYPE_MAXIMUM (time_t) < time_limit
)
7272 time_limit
= TYPE_MAXIMUM (time_t);
7274 if (time_limit
< 0 || nsecs
< 0)
7276 else if (time_limit
> 0 || nsecs
> 0)
7279 end_time
= timespec_add (current_timespec (),
7280 make_timespec (time_limit
, nsecs
));
7285 /* Turn off periodic alarms (in case they are in use)
7286 and then turn off any other atimers,
7287 because the select emulator uses alarms. */
7289 turn_on_atimers (0);
7293 bool timeout_reduced_for_timers
= false;
7294 fd_set waitchannels
;
7297 /* If calling from keyboard input, do not quit
7298 since we want to return C-g as an input character.
7299 Otherwise, do pending quit if requested. */
7303 /* Exit now if the cell we're waiting for became non-nil. */
7304 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7307 /* Compute time from now till when time limit is up. */
7308 /* Exit if already run out. */
7309 if (wait
== TIMEOUT
)
7311 struct timespec now
= current_timespec ();
7312 if (timespec_cmp (end_time
, now
) <= 0)
7314 timeout
= timespec_sub (end_time
, now
);
7317 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7319 /* If our caller will not immediately handle keyboard events,
7320 run timer events directly.
7321 (Callers that will immediately read keyboard events
7322 call timer_delay on their own.) */
7323 if (NILP (wait_for_cell
))
7325 struct timespec timer_delay
;
7329 unsigned old_timers_run
= timers_run
;
7330 timer_delay
= timer_check ();
7331 if (timers_run
!= old_timers_run
&& do_display
)
7332 /* We must retry, since a timer may have requeued itself
7333 and that could alter the time delay. */
7334 redisplay_preserve_echo_area (14);
7338 while (!detect_input_pending ());
7340 /* If there is unread keyboard input, also return. */
7342 && requeued_events_pending_p ())
7345 if (timespec_valid_p (timer_delay
))
7347 if (timespec_cmp (timer_delay
, timeout
) < 0)
7349 timeout
= timer_delay
;
7350 timeout_reduced_for_timers
= true;
7355 /* Cause C-g and alarm signals to take immediate action,
7356 and cause input available signals to zero out timeout. */
7358 set_waiting_for_input (&timeout
);
7360 /* If a frame has been newly mapped and needs updating,
7361 reprocess its display stuff. */
7362 if (frame_garbaged
&& do_display
)
7364 clear_waiting_for_input ();
7365 redisplay_preserve_echo_area (15);
7367 set_waiting_for_input (&timeout
);
7370 /* Wait till there is something to do. */
7371 FD_ZERO (&waitchannels
);
7372 if (read_kbd
&& detect_input_pending ())
7376 if (read_kbd
|| !NILP (wait_for_cell
))
7377 FD_SET (0, &waitchannels
);
7378 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7383 /* Make C-g and alarm signals set flags again. */
7384 clear_waiting_for_input ();
7386 /* If we woke up due to SIGWINCH, actually change size now. */
7387 do_pending_window_change (0);
7389 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7390 /* We waited the full specified time, so return now. */
7395 /* If the system call was interrupted, then go around the
7397 if (xerrno
== EINTR
)
7398 FD_ZERO (&waitchannels
);
7400 report_file_errno ("Failed select", Qnil
, xerrno
);
7403 /* Check for keyboard input. */
7406 && detect_input_pending_run_timers (do_display
))
7408 swallow_events (do_display
);
7409 if (detect_input_pending_run_timers (do_display
))
7413 /* If there is unread keyboard input, also return. */
7415 && requeued_events_pending_p ())
7418 /* If wait_for_cell. check for keyboard input
7419 but don't run any timers.
7420 ??? (It seems wrong to me to check for keyboard
7421 input at all when wait_for_cell, but the code
7422 has been this way since July 1994.
7423 Try changing this after version 19.31.) */
7424 if (! NILP (wait_for_cell
)
7425 && detect_input_pending ())
7427 swallow_events (do_display
);
7428 if (detect_input_pending ())
7432 /* Exit now if the cell we're waiting for became non-nil. */
7433 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7442 #endif /* not subprocesses */
7444 /* The following functions are needed even if async subprocesses are
7445 not supported. Some of them are no-op stubs in that case. */
7449 /* Add FD, which is a descriptor returned by timerfd_create,
7450 to the set of non-keyboard input descriptors. */
7453 add_timer_wait_descriptor (int fd
)
7455 FD_SET (fd
, &input_wait_mask
);
7456 FD_SET (fd
, &non_keyboard_wait_mask
);
7457 FD_SET (fd
, &non_process_wait_mask
);
7458 fd_callback_info
[fd
].func
= timerfd_callback
;
7459 fd_callback_info
[fd
].data
= NULL
;
7460 fd_callback_info
[fd
].condition
|= FOR_READ
;
7461 if (fd
> max_input_desc
)
7462 max_input_desc
= fd
;
7465 #endif /* HAVE_TIMERFD */
7467 /* If program file NAME starts with /: for quoting a magic
7468 name, remove that, preserving the multibyteness of NAME. */
7471 remove_slash_colon (Lisp_Object name
)
7474 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
7475 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
7476 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
7480 /* Add DESC to the set of keyboard input descriptors. */
7483 add_keyboard_wait_descriptor (int desc
)
7485 #ifdef subprocesses /* Actually means "not MSDOS". */
7486 FD_SET (desc
, &input_wait_mask
);
7487 FD_SET (desc
, &non_process_wait_mask
);
7488 if (desc
> max_input_desc
)
7489 max_input_desc
= desc
;
7493 /* From now on, do not expect DESC to give keyboard input. */
7496 delete_keyboard_wait_descriptor (int desc
)
7499 FD_CLR (desc
, &input_wait_mask
);
7500 FD_CLR (desc
, &non_process_wait_mask
);
7501 delete_input_desc (desc
);
7505 /* Setup coding systems of PROCESS. */
7508 setup_process_coding_systems (Lisp_Object process
)
7511 struct Lisp_Process
*p
= XPROCESS (process
);
7513 int outch
= p
->outfd
;
7514 Lisp_Object coding_system
;
7516 if (inch
< 0 || outch
< 0)
7519 if (!proc_decode_coding_system
[inch
])
7520 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7521 coding_system
= p
->decode_coding_system
;
7522 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7523 && BUFFERP (p
->buffer
))
7525 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7526 coding_system
= raw_text_coding_system (coding_system
);
7528 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7530 if (!proc_encode_coding_system
[outch
])
7531 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7532 setup_coding_system (p
->encode_coding_system
,
7533 proc_encode_coding_system
[outch
]);
7537 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7538 doc
: /* Return the (or a) live process associated with BUFFER.
7539 BUFFER may be a buffer or the name of one.
7540 Return nil if all processes associated with BUFFER have been
7541 deleted or killed. */)
7542 (register Lisp_Object buffer
)
7545 register Lisp_Object buf
, tail
, proc
;
7547 if (NILP (buffer
)) return Qnil
;
7548 buf
= Fget_buffer (buffer
);
7549 if (NILP (buf
)) return Qnil
;
7551 FOR_EACH_PROCESS (tail
, proc
)
7552 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7554 #endif /* subprocesses */
7558 DEFUN ("process-inherit-coding-system-flag",
7559 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7561 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7562 If this flag is t, `buffer-file-coding-system' of the buffer
7563 associated with PROCESS will inherit the coding system used to decode
7564 the process output. */)
7565 (register Lisp_Object process
)
7568 CHECK_PROCESS (process
);
7569 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7571 /* Ignore the argument and return the value of
7572 inherit-process-coding-system. */
7573 return inherit_process_coding_system
? Qt
: Qnil
;
7577 /* Kill all processes associated with `buffer'.
7578 If `buffer' is nil, kill all processes. */
7581 kill_buffer_processes (Lisp_Object buffer
)
7584 Lisp_Object tail
, proc
;
7586 FOR_EACH_PROCESS (tail
, proc
)
7587 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7589 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7590 Fdelete_process (proc
);
7591 else if (XPROCESS (proc
)->infd
>= 0)
7592 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7594 #else /* subprocesses */
7595 /* Since we have no subprocesses, this does nothing. */
7596 #endif /* subprocesses */
7599 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7600 Swaiting_for_user_input_p
, 0, 0, 0,
7601 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7602 This is intended for use by asynchronous process output filters and sentinels. */)
7606 return (waiting_for_user_input_p
? Qt
: Qnil
);
7612 /* Stop reading input from keyboard sources. */
7615 hold_keyboard_input (void)
7620 /* Resume reading input from keyboard sources. */
7623 unhold_keyboard_input (void)
7628 /* Return true if keyboard input is on hold, zero otherwise. */
7631 kbd_on_hold_p (void)
7633 return kbd_is_on_hold
;
7637 /* Enumeration of and access to system processes a-la ps(1). */
7639 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7641 doc
: /* Return a list of numerical process IDs of all running processes.
7642 If this functionality is unsupported, return nil.
7644 See `process-attributes' for getting attributes of a process given its ID. */)
7647 return list_system_processes ();
7650 DEFUN ("process-attributes", Fprocess_attributes
,
7651 Sprocess_attributes
, 1, 1, 0,
7652 doc
: /* Return attributes of the process given by its PID, a number.
7654 Value is an alist where each element is a cons cell of the form
7658 If this functionality is unsupported, the value is nil.
7660 See `list-system-processes' for getting a list of all process IDs.
7662 The KEYs of the attributes that this function may return are listed
7663 below, together with the type of the associated VALUE (in parentheses).
7664 Not all platforms support all of these attributes; unsupported
7665 attributes will not appear in the returned alist.
7666 Unless explicitly indicated otherwise, numbers can have either
7667 integer or floating point values.
7669 euid -- Effective user User ID of the process (number)
7670 user -- User name corresponding to euid (string)
7671 egid -- Effective user Group ID of the process (number)
7672 group -- Group name corresponding to egid (string)
7673 comm -- Command name (executable name only) (string)
7674 state -- Process state code, such as "S", "R", or "T" (string)
7675 ppid -- Parent process ID (number)
7676 pgrp -- Process group ID (number)
7677 sess -- Session ID, i.e. process ID of session leader (number)
7678 ttname -- Controlling tty name (string)
7679 tpgid -- ID of foreground process group on the process's tty (number)
7680 minflt -- number of minor page faults (number)
7681 majflt -- number of major page faults (number)
7682 cminflt -- cumulative number of minor page faults (number)
7683 cmajflt -- cumulative number of major page faults (number)
7684 utime -- user time used by the process, in (current-time) format,
7685 which is a list of integers (HIGH LOW USEC PSEC)
7686 stime -- system time used by the process (current-time)
7687 time -- sum of utime and stime (current-time)
7688 cutime -- user time used by the process and its children (current-time)
7689 cstime -- system time used by the process and its children (current-time)
7690 ctime -- sum of cutime and cstime (current-time)
7691 pri -- priority of the process (number)
7692 nice -- nice value of the process (number)
7693 thcount -- process thread count (number)
7694 start -- time the process started (current-time)
7695 vsize -- virtual memory size of the process in KB's (number)
7696 rss -- resident set size of the process in KB's (number)
7697 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7698 pcpu -- percents of CPU time used by the process (floating-point number)
7699 pmem -- percents of total physical memory used by process's resident set
7700 (floating-point number)
7701 args -- command line which invoked the process (string). */)
7704 return system_process_attributes (pid
);
7708 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7709 Invoke this after init_process_emacs, and after glib and/or GNUstep
7710 futz with the SIGCHLD handler, but before Emacs forks any children.
7711 This function's caller should block SIGCHLD. */
7714 catch_child_signal (void)
7716 struct sigaction action
, old_action
;
7718 emacs_sigaction_init (&action
, deliver_child_signal
);
7719 block_child_signal (&oldset
);
7720 sigaction (SIGCHLD
, &action
, &old_action
);
7721 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7722 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7724 if (old_action
.sa_handler
!= deliver_child_signal
)
7726 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7728 : old_action
.sa_handler
);
7729 unblock_child_signal (&oldset
);
7731 #endif /* subprocesses */
7734 /* This is not called "init_process" because that is the name of a
7735 Mach system call, so it would cause problems on Darwin systems. */
7737 init_process_emacs (int sockfd
)
7742 inhibit_sentinels
= 0;
7745 if (! noninteractive
|| initialized
)
7748 #if defined HAVE_GLIB && !defined WINDOWSNT
7749 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7750 this should always fail, but is enough to initialize glib's
7751 private SIGCHLD handler, allowing catch_child_signal to copy
7752 it into lib_child_handler. */
7753 g_source_unref (g_child_watch_source_new (getpid ()));
7755 catch_child_signal ();
7758 FD_ZERO (&input_wait_mask
);
7759 FD_ZERO (&non_keyboard_wait_mask
);
7760 FD_ZERO (&non_process_wait_mask
);
7761 FD_ZERO (&write_mask
);
7762 max_process_desc
= max_input_desc
= -1;
7763 external_sock_fd
= sockfd
;
7764 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7766 FD_ZERO (&connect_wait_mask
);
7767 num_pending_connects
= 0;
7769 process_output_delay_count
= 0;
7770 process_output_skip
= 0;
7772 /* Don't do this, it caused infinite select loops. The display
7773 method should call add_keyboard_wait_descriptor on stdin if it
7776 FD_SET (0, &input_wait_mask
);
7779 Vprocess_alist
= Qnil
;
7780 deleted_pid_list
= Qnil
;
7781 for (i
= 0; i
< FD_SETSIZE
; i
++)
7783 chan_process
[i
] = Qnil
;
7784 proc_buffered_char
[i
] = -1;
7786 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7787 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7788 #ifdef DATAGRAM_SOCKETS
7789 memset (datagram_address
, 0, sizeof datagram_address
);
7792 #if defined (DARWIN_OS)
7793 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7794 processes. As such, we only change the default value. */
7797 char const *release
= (STRINGP (Voperating_system_release
)
7798 ? SSDATA (Voperating_system_release
)
7800 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7801 Vprocess_connection_type
= Qnil
;
7805 #endif /* subprocesses */
7810 syms_of_process (void)
7814 DEFSYM (Qprocessp
, "processp");
7815 DEFSYM (Qrun
, "run");
7816 DEFSYM (Qstop
, "stop");
7817 DEFSYM (Qsignal
, "signal");
7819 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7822 DEFSYM (Qopen
, "open");
7823 DEFSYM (Qclosed
, "closed");
7824 DEFSYM (Qconnect
, "connect");
7825 DEFSYM (Qfailed
, "failed");
7826 DEFSYM (Qlisten
, "listen");
7827 DEFSYM (Qlocal
, "local");
7828 DEFSYM (Qipv4
, "ipv4");
7830 DEFSYM (Qipv6
, "ipv6");
7832 DEFSYM (Qdatagram
, "datagram");
7833 DEFSYM (Qseqpacket
, "seqpacket");
7835 DEFSYM (QCport
, ":port");
7836 DEFSYM (QCspeed
, ":speed");
7837 DEFSYM (QCprocess
, ":process");
7839 DEFSYM (QCbytesize
, ":bytesize");
7840 DEFSYM (QCstopbits
, ":stopbits");
7841 DEFSYM (QCparity
, ":parity");
7842 DEFSYM (Qodd
, "odd");
7843 DEFSYM (Qeven
, "even");
7844 DEFSYM (QCflowcontrol
, ":flowcontrol");
7847 DEFSYM (QCsummary
, ":summary");
7849 DEFSYM (Qreal
, "real");
7850 DEFSYM (Qnetwork
, "network");
7851 DEFSYM (Qserial
, "serial");
7852 DEFSYM (Qpipe
, "pipe");
7853 DEFSYM (QCbuffer
, ":buffer");
7854 DEFSYM (QChost
, ":host");
7855 DEFSYM (QCservice
, ":service");
7856 DEFSYM (QClocal
, ":local");
7857 DEFSYM (QCremote
, ":remote");
7858 DEFSYM (QCcoding
, ":coding");
7859 DEFSYM (QCserver
, ":server");
7860 DEFSYM (QCnowait
, ":nowait");
7861 DEFSYM (QCsentinel
, ":sentinel");
7862 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7863 DEFSYM (QCtls_parameters
, ":tls-parameters");
7864 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7865 DEFSYM (QClog
, ":log");
7866 DEFSYM (QCnoquery
, ":noquery");
7867 DEFSYM (QCstop
, ":stop");
7868 DEFSYM (QCplist
, ":plist");
7869 DEFSYM (QCcommand
, ":command");
7870 DEFSYM (QCconnection_type
, ":connection-type");
7871 DEFSYM (QCstderr
, ":stderr");
7872 DEFSYM (Qpty
, "pty");
7873 DEFSYM (Qpipe
, "pipe");
7875 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7877 staticpro (&Vprocess_alist
);
7878 staticpro (&deleted_pid_list
);
7880 #endif /* subprocesses */
7882 DEFSYM (QCname
, ":name");
7883 DEFSYM (QCtype
, ":type");
7885 DEFSYM (Qeuid
, "euid");
7886 DEFSYM (Qegid
, "egid");
7887 DEFSYM (Quser
, "user");
7888 DEFSYM (Qgroup
, "group");
7889 DEFSYM (Qcomm
, "comm");
7890 DEFSYM (Qstate
, "state");
7891 DEFSYM (Qppid
, "ppid");
7892 DEFSYM (Qpgrp
, "pgrp");
7893 DEFSYM (Qsess
, "sess");
7894 DEFSYM (Qttname
, "ttname");
7895 DEFSYM (Qtpgid
, "tpgid");
7896 DEFSYM (Qminflt
, "minflt");
7897 DEFSYM (Qmajflt
, "majflt");
7898 DEFSYM (Qcminflt
, "cminflt");
7899 DEFSYM (Qcmajflt
, "cmajflt");
7900 DEFSYM (Qutime
, "utime");
7901 DEFSYM (Qstime
, "stime");
7902 DEFSYM (Qtime
, "time");
7903 DEFSYM (Qcutime
, "cutime");
7904 DEFSYM (Qcstime
, "cstime");
7905 DEFSYM (Qctime
, "ctime");
7907 DEFSYM (Qinternal_default_process_sentinel
,
7908 "internal-default-process-sentinel");
7909 DEFSYM (Qinternal_default_process_filter
,
7910 "internal-default-process-filter");
7912 DEFSYM (Qpri
, "pri");
7913 DEFSYM (Qnice
, "nice");
7914 DEFSYM (Qthcount
, "thcount");
7915 DEFSYM (Qstart
, "start");
7916 DEFSYM (Qvsize
, "vsize");
7917 DEFSYM (Qrss
, "rss");
7918 DEFSYM (Qetime
, "etime");
7919 DEFSYM (Qpcpu
, "pcpu");
7920 DEFSYM (Qpmem
, "pmem");
7921 DEFSYM (Qargs
, "args");
7923 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7924 doc
: /* Non-nil means delete processes immediately when they exit.
7925 A value of nil means don't delete them until `list-processes' is run. */);
7927 delete_exited_processes
= 1;
7930 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7931 doc
: /* Control type of device used to communicate with subprocesses.
7932 Values are nil to use a pipe, or t or `pty' to use a pty.
7933 The value has no effect if the system has no ptys or if all ptys are busy:
7934 then a pipe is used in any case.
7935 The value takes effect when `start-process' is called. */);
7936 Vprocess_connection_type
= Qt
;
7938 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7939 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7940 On some systems, when Emacs reads the output from a subprocess, the output data
7941 is read in very small blocks, potentially resulting in very poor performance.
7942 This behavior can be remedied to some extent by setting this variable to a
7943 non-nil value, as it will automatically delay reading from such processes, to
7944 allow them to produce more output before Emacs tries to read it.
7945 If the value is t, the delay is reset after each write to the process; any other
7946 non-nil value means that the delay is not reset on write.
7947 The variable takes effect when `start-process' is called. */);
7948 Vprocess_adaptive_read_buffering
= Qt
;
7950 defsubr (&Sprocessp
);
7951 defsubr (&Sget_process
);
7952 defsubr (&Sdelete_process
);
7953 defsubr (&Sprocess_status
);
7954 defsubr (&Sprocess_exit_status
);
7955 defsubr (&Sprocess_id
);
7956 defsubr (&Sprocess_name
);
7957 defsubr (&Sprocess_tty_name
);
7958 defsubr (&Sprocess_command
);
7959 defsubr (&Sset_process_buffer
);
7960 defsubr (&Sprocess_buffer
);
7961 defsubr (&Sprocess_mark
);
7962 defsubr (&Sset_process_filter
);
7963 defsubr (&Sprocess_filter
);
7964 defsubr (&Sset_process_sentinel
);
7965 defsubr (&Sprocess_sentinel
);
7966 defsubr (&Sset_process_window_size
);
7967 defsubr (&Sset_process_inherit_coding_system_flag
);
7968 defsubr (&Sset_process_query_on_exit_flag
);
7969 defsubr (&Sprocess_query_on_exit_flag
);
7970 defsubr (&Sprocess_contact
);
7971 defsubr (&Sprocess_plist
);
7972 defsubr (&Sset_process_plist
);
7973 defsubr (&Sprocess_list
);
7974 defsubr (&Smake_process
);
7975 defsubr (&Smake_pipe_process
);
7976 defsubr (&Sserial_process_configure
);
7977 defsubr (&Smake_serial_process
);
7978 defsubr (&Sset_network_process_option
);
7979 defsubr (&Smake_network_process
);
7980 defsubr (&Sformat_network_address
);
7981 defsubr (&Snetwork_interface_list
);
7982 defsubr (&Snetwork_interface_info
);
7983 #ifdef DATAGRAM_SOCKETS
7984 defsubr (&Sprocess_datagram_address
);
7985 defsubr (&Sset_process_datagram_address
);
7987 defsubr (&Saccept_process_output
);
7988 defsubr (&Sprocess_send_region
);
7989 defsubr (&Sprocess_send_string
);
7990 defsubr (&Sinterrupt_process
);
7991 defsubr (&Skill_process
);
7992 defsubr (&Squit_process
);
7993 defsubr (&Sstop_process
);
7994 defsubr (&Scontinue_process
);
7995 defsubr (&Sprocess_running_child_p
);
7996 defsubr (&Sprocess_send_eof
);
7997 defsubr (&Ssignal_process
);
7998 defsubr (&Swaiting_for_user_input_p
);
7999 defsubr (&Sprocess_type
);
8000 defsubr (&Sinternal_default_process_sentinel
);
8001 defsubr (&Sinternal_default_process_filter
);
8002 defsubr (&Sset_process_coding_system
);
8003 defsubr (&Sprocess_coding_system
);
8004 defsubr (&Sset_process_filter_multibyte
);
8005 defsubr (&Sprocess_filter_multibyte_p
);
8008 Lisp_Object subfeatures
= Qnil
;
8009 const struct socket_options
*sopt
;
8011 #define ADD_SUBFEATURE(key, val) \
8012 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8014 ADD_SUBFEATURE (QCnowait
, Qt
);
8015 #ifdef DATAGRAM_SOCKETS
8016 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8018 #ifdef HAVE_SEQPACKET
8019 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8021 #ifdef HAVE_LOCAL_SOCKETS
8022 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8024 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8026 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8028 #ifdef HAVE_GETSOCKNAME
8029 ADD_SUBFEATURE (QCservice
, Qt
);
8031 ADD_SUBFEATURE (QCserver
, Qt
);
8033 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8034 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8036 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
8039 #endif /* subprocesses */
8041 defsubr (&Sget_buffer_process
);
8042 defsubr (&Sprocess_inherit_coding_system_flag
);
8043 defsubr (&Slist_system_processes
);
8044 defsubr (&Sprocess_attributes
);