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
156 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
159 close_on_exec (int fd
)
162 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
167 # define accept4(sockfd, addr, addrlen, flags) \
168 process_accept4 (sockfd, addr, addrlen, flags)
170 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
172 return close_on_exec (accept (sockfd
, addr
, addrlen
));
176 process_socket (int domain
, int type
, int protocol
)
178 return close_on_exec (socket (domain
, type
, protocol
));
181 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
184 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
185 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
186 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
187 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
189 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
191 /* Number of events of change of status of a process. */
192 static EMACS_INT process_tick
;
193 /* Number of events for which the user or sentinel has been notified. */
194 static EMACS_INT update_tick
;
196 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
197 this system. We need to read full packets, so we need a
198 "non-destructive" select. So we require either native select,
199 or emulation of select using FIONREAD. */
201 #ifndef BROKEN_DATAGRAM_SOCKETS
202 # if defined HAVE_SELECT || defined USABLE_FIONREAD
203 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
204 # define DATAGRAM_SOCKETS
209 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
210 # define HAVE_SEQPACKET
213 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
214 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
215 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
217 /* Number of processes which have a non-zero read_output_delay,
218 and therefore might be delayed for adaptive read buffering. */
220 static int process_output_delay_count
;
222 /* True if any process has non-nil read_output_skip. */
224 static bool process_output_skip
;
226 static void create_process (Lisp_Object
, char **, Lisp_Object
);
228 static bool keyboard_bit_set (fd_set
*);
230 static void deactivate_process (Lisp_Object
);
231 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
232 static int read_process_output (Lisp_Object
, int);
233 static void handle_child_signal (int);
234 static void create_pty (Lisp_Object
);
236 static Lisp_Object
get_process (register Lisp_Object name
);
237 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
239 /* Mask of bits indicating the descriptors that we wait for input on. */
241 static fd_set input_wait_mask
;
243 /* Mask that excludes keyboard input descriptor(s). */
245 static fd_set non_keyboard_wait_mask
;
247 /* Mask that excludes process input descriptor(s). */
249 static fd_set non_process_wait_mask
;
251 /* Mask for selecting for write. */
253 static fd_set write_mask
;
255 /* Mask of bits indicating the descriptors that we wait for connect to
256 complete on. Once they complete, they are removed from this mask
257 and added to the input_wait_mask and non_keyboard_wait_mask. */
259 static fd_set connect_wait_mask
;
261 /* Number of bits set in connect_wait_mask. */
262 static int num_pending_connects
;
264 /* The largest descriptor currently in use for a process object; -1 if none. */
265 static int max_process_desc
;
267 /* The largest descriptor currently in use for input; -1 if none. */
268 static int max_input_desc
;
270 /* The descriptor of any socket passed to Emacs; -1 if none. */
271 static int external_sock_fd
;
273 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
274 static Lisp_Object chan_process
[FD_SETSIZE
];
275 static void wait_for_socket_fds (Lisp_Object
, char const *);
277 /* Alist of elements (NAME . PROCESS). */
278 static Lisp_Object Vprocess_alist
;
280 /* Buffered-ahead input char from process, indexed by channel.
281 -1 means empty (no char is buffered).
282 Used on sys V where the only way to tell if there is any
283 output from the process is to read at least one char.
284 Always -1 on systems that support FIONREAD. */
286 static int proc_buffered_char
[FD_SETSIZE
];
288 /* Table of `struct coding-system' for each process. */
289 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
290 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
292 #ifdef DATAGRAM_SOCKETS
293 /* Table of `partner address' for datagram sockets. */
294 static struct sockaddr_and_len
{
297 } datagram_address
[FD_SETSIZE
];
298 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
299 #define DATAGRAM_CONN_P(proc) \
300 (PROCESSP (proc) && \
301 XPROCESS (proc)->infd >= 0 && \
302 datagram_address[XPROCESS (proc)->infd].sa != 0)
304 #define DATAGRAM_CHAN_P(chan) (0)
305 #define DATAGRAM_CONN_P(proc) (0)
308 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
309 a `for' loop which iterates over processes from Vprocess_alist. */
311 #define FOR_EACH_PROCESS(list_var, proc_var) \
312 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
314 /* These setters are used only in this file, so they can be private. */
316 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
321 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
326 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
328 p
->decode_coding_system
= val
;
331 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
333 p
->decoding_buf
= val
;
336 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
338 p
->encode_coding_system
= val
;
341 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
343 p
->encoding_buf
= val
;
346 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
348 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
351 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
356 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
361 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
366 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
371 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
373 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
376 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
381 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
386 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
388 p
->write_queue
= val
;
391 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
398 make_lisp_proc (struct Lisp_Process
*p
)
400 return make_lisp_ptr (p
, Lisp_Vectorlike
);
403 static struct fd_callback_data
409 int condition
; /* Mask of the defines above. */
410 } fd_callback_info
[FD_SETSIZE
];
413 /* Add a file descriptor FD to be monitored for when read is possible.
414 When read is possible, call FUNC with argument DATA. */
417 add_read_fd (int fd
, fd_callback func
, void *data
)
419 add_keyboard_wait_descriptor (fd
);
421 fd_callback_info
[fd
].func
= func
;
422 fd_callback_info
[fd
].data
= data
;
423 fd_callback_info
[fd
].condition
|= FOR_READ
;
426 /* Stop monitoring file descriptor FD for when read is possible. */
429 delete_read_fd (int fd
)
431 delete_keyboard_wait_descriptor (fd
);
433 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
434 if (fd_callback_info
[fd
].condition
== 0)
436 fd_callback_info
[fd
].func
= 0;
437 fd_callback_info
[fd
].data
= 0;
441 /* Add a file descriptor FD to be monitored for when write is possible.
442 When write is possible, call FUNC with argument DATA. */
445 add_write_fd (int fd
, fd_callback func
, void *data
)
447 FD_SET (fd
, &write_mask
);
448 if (fd
> max_input_desc
)
451 fd_callback_info
[fd
].func
= func
;
452 fd_callback_info
[fd
].data
= data
;
453 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
456 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
459 delete_input_desc (int fd
)
461 if (fd
== max_input_desc
)
465 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
466 || FD_ISSET (fd
, &write_mask
)));
472 /* Stop monitoring file descriptor FD for when write is possible. */
475 delete_write_fd (int fd
)
477 FD_CLR (fd
, &write_mask
);
478 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
479 if (fd_callback_info
[fd
].condition
== 0)
481 fd_callback_info
[fd
].func
= 0;
482 fd_callback_info
[fd
].data
= 0;
483 delete_input_desc (fd
);
488 /* Compute the Lisp form of the process status, p->status, from
489 the numeric status that was returned by `wait'. */
491 static Lisp_Object
status_convert (int);
494 update_status (struct Lisp_Process
*p
)
496 eassert (p
->raw_status_new
);
497 pset_status (p
, status_convert (p
->raw_status
));
498 p
->raw_status_new
= 0;
501 /* Convert a process status word in Unix format to
502 the list that we use internally. */
505 status_convert (int w
)
508 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
509 else if (WIFEXITED (w
))
510 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
511 WCOREDUMP (w
) ? Qt
: Qnil
));
512 else if (WIFSIGNALED (w
))
513 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
514 WCOREDUMP (w
) ? Qt
: Qnil
));
519 /* Given a status-list, extract the three pieces of information
520 and store them individually through the three pointers. */
523 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
537 *code
= XFASTINT (XCAR (tem
));
539 *coredump
= !NILP (tem
);
543 /* Return a string describing a process status list. */
546 status_message (struct Lisp_Process
*p
)
548 Lisp_Object status
= p
->status
;
554 decode_status (status
, &symbol
, &code
, &coredump
);
556 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
559 synchronize_system_messages_locale ();
560 signame
= strsignal (code
);
562 string
= build_string ("unknown");
567 string
= build_unibyte_string (signame
);
568 if (! NILP (Vlocale_coding_system
))
569 string
= (code_convert_string_norecord
570 (string
, Vlocale_coding_system
, 0));
571 c1
= STRING_CHAR (SDATA (string
));
574 Faset (string
, make_number (0), make_number (c2
));
576 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
577 return concat2 (string
, suffix
);
579 else if (EQ (symbol
, Qexit
))
582 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
584 return build_string ("finished\n");
585 AUTO_STRING (prefix
, "exited abnormally with code ");
586 string
= Fnumber_to_string (make_number (code
));
587 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
588 return concat3 (prefix
, string
, suffix
);
590 else if (EQ (symbol
, Qfailed
))
592 AUTO_STRING (prefix
, "failed with code ");
593 string
= Fnumber_to_string (make_number (code
));
594 AUTO_STRING (suffix
, "\n");
595 return concat3 (prefix
, string
, suffix
);
598 return Fcopy_sequence (Fsymbol_name (symbol
));
601 enum { PTY_NAME_SIZE
= 24 };
603 /* Open an available pty, returning a file descriptor.
604 Store into PTY_NAME the file name of the terminal corresponding to the pty.
605 Return -1 on failure. */
608 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
617 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
618 for (i
= 0; i
< 16; i
++)
621 #ifdef PTY_NAME_SPRINTF
624 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
625 #endif /* no PTY_NAME_SPRINTF */
629 #else /* no PTY_OPEN */
630 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
631 #endif /* no PTY_OPEN */
635 #ifdef PTY_TTY_NAME_SPRINTF
638 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
639 #endif /* no PTY_TTY_NAME_SPRINTF */
641 /* Set FD's close-on-exec flag. This is needed even if
642 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
643 doesn't require support for that combination.
644 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
645 doesn't work if the close-on-exec flag is set (Bug#20555).
646 Multithreaded platforms where posix_openpt ignores
647 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
648 have a race condition between the PTY_OPEN and here. */
649 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
651 /* Check to make certain that both sides are available.
652 This avoids a nasty yet stupid bug in rlogins. */
653 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
666 #endif /* HAVE_PTYS */
670 /* Allocate basically initialized process. */
672 static struct Lisp_Process
*
673 allocate_process (void)
675 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
679 make_process (Lisp_Object name
)
681 struct Lisp_Process
*p
= allocate_process ();
682 /* Initialize Lisp data. Note that allocate_process initializes all
683 Lisp data to nil, so do it only for slots which should not be nil. */
684 pset_status (p
, Qrun
);
685 pset_mark (p
, Fmake_marker ());
687 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
688 non-Lisp data, so do it only for slots which should not be zero. */
691 for (int i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
695 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
696 p
->gnutls_boot_parameters
= Qnil
;
699 /* If name is already in use, modify it until it is unused. */
701 Lisp_Object name1
= name
;
702 for (printmax_t i
= 1; ; i
++)
704 Lisp_Object tem
= Fget_process (name1
);
707 char const suffix_fmt
[] = "<%"pMd
">";
708 char suffix
[sizeof suffix_fmt
+ INT_STRLEN_BOUND (printmax_t
)];
709 AUTO_STRING_WITH_LEN (lsuffix
, suffix
, sprintf (suffix
, suffix_fmt
, i
));
710 name1
= concat2 (name
, lsuffix
);
714 pset_sentinel (p
, Qinternal_default_process_sentinel
);
715 pset_filter (p
, Qinternal_default_process_filter
);
717 XSETPROCESS (val
, p
);
718 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
723 remove_process (register Lisp_Object proc
)
725 register Lisp_Object pair
;
727 pair
= Frassq (proc
, Vprocess_alist
);
728 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
730 deactivate_process (proc
);
733 #ifdef HAVE_GETADDRINFO_A
735 free_dns_request (Lisp_Object proc
)
737 struct Lisp_Process
*p
= XPROCESS (proc
);
739 if (p
->dns_request
->ar_result
)
740 freeaddrinfo (p
->dns_request
->ar_result
);
741 xfree (p
->dns_request
);
742 p
->dns_request
= NULL
;
747 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
748 doc
: /* Return t if OBJECT is a process. */)
751 return PROCESSP (object
) ? Qt
: Qnil
;
754 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
755 doc
: /* Return the process named NAME, or nil if there is none. */)
756 (register Lisp_Object name
)
761 return Fcdr (Fassoc (name
, Vprocess_alist
));
764 /* This is how commands for the user decode process arguments. It
765 accepts a process, a process name, a buffer, a buffer name, or nil.
766 Buffers denote the first process in the buffer, and nil denotes the
770 get_process (register Lisp_Object name
)
772 register Lisp_Object proc
, obj
;
775 obj
= Fget_process (name
);
777 obj
= Fget_buffer (name
);
779 error ("Process %s does not exist", SDATA (name
));
781 else if (NILP (name
))
782 obj
= Fcurrent_buffer ();
786 /* Now obj should be either a buffer object or a process object. */
789 if (NILP (BVAR (XBUFFER (obj
), name
)))
790 error ("Attempt to get process for a dead buffer");
791 proc
= Fget_buffer_process (obj
);
793 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
804 /* Fdelete_process promises to immediately forget about the process, but in
805 reality, Emacs needs to remember those processes until they have been
806 treated by the SIGCHLD handler and waitpid has been invoked on them;
807 otherwise they might fill up the kernel's process table.
809 Some processes created by call-process are also put onto this list.
811 Members of this list are (process-ID . filename) pairs. The
812 process-ID is a number; the filename, if a string, is a file that
813 needs to be removed after the process exits. */
814 static Lisp_Object deleted_pid_list
;
817 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
819 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
820 /* GC treated elements set to nil. */
821 Fdelq (Qnil
, deleted_pid_list
));
825 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
826 doc
: /* Delete PROCESS: kill it and forget about it immediately.
827 PROCESS may be a process, a buffer, the name of a process or buffer, or
828 nil, indicating the current buffer's process. */)
829 (register Lisp_Object process
)
831 register struct Lisp_Process
*p
;
833 process
= get_process (process
);
834 p
= XPROCESS (process
);
836 #ifdef HAVE_GETADDRINFO_A
839 /* Cancel the request. Unless shutting down, wait until
840 completion. Free the request if completely canceled. */
842 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
843 if (!canceled
&& !inhibit_sentinels
)
845 struct gaicb
const *req
= p
->dns_request
;
846 while (gai_suspend (&req
, 1, NULL
) != 0)
851 free_dns_request (process
);
855 p
->raw_status_new
= 0;
856 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
858 pset_status (p
, list2 (Qexit
, make_number (0)));
859 p
->tick
= ++process_tick
;
860 status_notify (p
, NULL
);
861 redisplay_preserve_echo_area (13);
866 record_kill_process (p
, Qnil
);
870 /* Update P's status, since record_kill_process will make the
871 SIGCHLD handler update deleted_pid_list, not *P. */
873 if (p
->raw_status_new
)
875 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
876 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
877 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
879 p
->tick
= ++process_tick
;
880 status_notify (p
, NULL
);
881 redisplay_preserve_echo_area (13);
884 remove_process (process
);
888 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
889 doc
: /* Return the status of PROCESS.
890 The returned value is one of the following symbols:
891 run -- for a process that is running.
892 stop -- for a process stopped but continuable.
893 exit -- for a process that has exited.
894 signal -- for a process that has got a fatal signal.
895 open -- for a network stream connection that is open.
896 listen -- for a network stream server that is listening.
897 closed -- for a network stream connection that is closed.
898 connect -- when waiting for a non-blocking connection to complete.
899 failed -- when a non-blocking connection has failed.
900 nil -- if arg is a process name and no such process exists.
901 PROCESS may be a process, a buffer, the name of a process, or
902 nil, indicating the current buffer's process. */)
903 (register Lisp_Object process
)
905 register struct Lisp_Process
*p
;
906 register Lisp_Object status
;
908 if (STRINGP (process
))
909 process
= Fget_process (process
);
911 process
= get_process (process
);
916 p
= XPROCESS (process
);
917 if (p
->raw_status_new
)
921 status
= XCAR (status
);
922 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
924 if (EQ (status
, Qexit
))
926 else if (EQ (p
->command
, Qt
))
928 else if (EQ (status
, Qrun
))
934 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
936 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
937 If PROCESS has not yet exited or died, return 0. */)
938 (register Lisp_Object process
)
940 CHECK_PROCESS (process
);
941 if (XPROCESS (process
)->raw_status_new
)
942 update_status (XPROCESS (process
));
943 if (CONSP (XPROCESS (process
)->status
))
944 return XCAR (XCDR (XPROCESS (process
)->status
));
945 return make_number (0);
948 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
949 doc
: /* Return the process id of PROCESS.
950 This is the pid of the external process which PROCESS uses or talks to.
951 For a network connection, this value is nil. */)
952 (register Lisp_Object process
)
956 CHECK_PROCESS (process
);
957 pid
= XPROCESS (process
)->pid
;
958 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
961 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
962 doc
: /* Return the name of PROCESS, as a string.
963 This is the name of the program invoked in PROCESS,
964 possibly modified to make it unique among process names. */)
965 (register Lisp_Object process
)
967 CHECK_PROCESS (process
);
968 return XPROCESS (process
)->name
;
971 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
972 doc
: /* Return the command that was executed to start PROCESS.
973 This is a list of strings, the first string being the program executed
974 and the rest of the strings being the arguments given to it.
975 For a network or serial process, this is nil (process is running) or t
976 \(process is stopped). */)
977 (register Lisp_Object process
)
979 CHECK_PROCESS (process
);
980 return XPROCESS (process
)->command
;
983 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
984 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
985 This is the terminal that the process itself reads and writes on,
986 not the name of the pty that Emacs uses to talk with that terminal. */)
987 (register Lisp_Object process
)
989 CHECK_PROCESS (process
);
990 return XPROCESS (process
)->tty_name
;
993 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
995 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
997 (register Lisp_Object process
, Lisp_Object buffer
)
999 struct Lisp_Process
*p
;
1001 CHECK_PROCESS (process
);
1003 CHECK_BUFFER (buffer
);
1004 p
= XPROCESS (process
);
1005 pset_buffer (p
, buffer
);
1006 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1007 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1008 setup_process_coding_systems (process
);
1012 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1014 doc
: /* Return the buffer PROCESS is associated with.
1015 The default process filter inserts output from PROCESS into this buffer. */)
1016 (register Lisp_Object process
)
1018 CHECK_PROCESS (process
);
1019 return XPROCESS (process
)->buffer
;
1022 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1024 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1025 (register Lisp_Object process
)
1027 CHECK_PROCESS (process
);
1028 return XPROCESS (process
)->mark
;
1032 set_process_filter_masks (struct Lisp_Process
*p
)
1034 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1036 FD_CLR (p
->infd
, &input_wait_mask
);
1037 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1039 else if (EQ (p
->filter
, Qt
)
1040 /* Network or serial process not stopped: */
1041 && !EQ (p
->command
, Qt
))
1043 FD_SET (p
->infd
, &input_wait_mask
);
1044 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1048 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1050 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1051 A value of t means stop accepting output from the process.
1053 When a process has a non-default filter, its buffer is not used for output.
1054 Instead, each time it does output, the entire string of output is
1055 passed to the filter.
1057 The filter gets two arguments: the process and the string of output.
1058 The string argument is normally a multibyte string, except:
1059 - if the process's input coding system is no-conversion or raw-text,
1060 it is a unibyte string (the non-converted input), or else
1061 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1062 string (the result of converting the decoded input multibyte
1063 string to unibyte with `string-make-unibyte'). */)
1064 (Lisp_Object process
, Lisp_Object filter
)
1066 CHECK_PROCESS (process
);
1067 struct Lisp_Process
*p
= XPROCESS (process
);
1069 /* Don't signal an error if the process's input file descriptor
1070 is closed. This could make debugging Lisp more difficult,
1071 for example when doing something like
1073 (setq process (start-process ...))
1075 (set-process-filter process ...) */
1078 filter
= Qinternal_default_process_filter
;
1080 pset_filter (p
, filter
);
1083 set_process_filter_masks (p
);
1085 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1086 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1087 setup_process_coding_systems (process
);
1091 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1093 doc
: /* Return the filter function of PROCESS.
1094 See `set-process-filter' for more info on filter functions. */)
1095 (register Lisp_Object process
)
1097 CHECK_PROCESS (process
);
1098 return XPROCESS (process
)->filter
;
1101 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1103 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1104 The sentinel is called as a function when the process changes state.
1105 It gets two arguments: the process, and a string describing the change. */)
1106 (register Lisp_Object process
, Lisp_Object sentinel
)
1108 struct Lisp_Process
*p
;
1110 CHECK_PROCESS (process
);
1111 p
= XPROCESS (process
);
1113 if (NILP (sentinel
))
1114 sentinel
= Qinternal_default_process_sentinel
;
1116 pset_sentinel (p
, sentinel
);
1117 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1118 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1122 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1124 doc
: /* Return the sentinel of PROCESS.
1125 See `set-process-sentinel' for more info on sentinels. */)
1126 (register Lisp_Object process
)
1128 CHECK_PROCESS (process
);
1129 return XPROCESS (process
)->sentinel
;
1132 DEFUN ("set-process-window-size", Fset_process_window_size
,
1133 Sset_process_window_size
, 3, 3, 0,
1134 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1135 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1137 CHECK_PROCESS (process
);
1139 /* All known platforms store window sizes as 'unsigned short'. */
1140 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1141 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1143 if (NETCONN_P (process
)
1144 || XPROCESS (process
)->infd
< 0
1145 || (set_window_size (XPROCESS (process
)->infd
,
1146 XINT (height
), XINT (width
))
1153 DEFUN ("set-process-inherit-coding-system-flag",
1154 Fset_process_inherit_coding_system_flag
,
1155 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1156 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1157 If the second argument FLAG is non-nil, then the variable
1158 `buffer-file-coding-system' of the buffer associated with PROCESS
1159 will be bound to the value of the coding system used to decode
1162 This is useful when the coding system specified for the process buffer
1163 leaves either the character code conversion or the end-of-line conversion
1164 unspecified, or if the coding system used to decode the process output
1165 is more appropriate for saving the process buffer.
1167 Binding the variable `inherit-process-coding-system' to non-nil before
1168 starting the process is an alternative way of setting the inherit flag
1169 for the process which will run.
1171 This function returns FLAG. */)
1172 (register Lisp_Object process
, Lisp_Object flag
)
1174 CHECK_PROCESS (process
);
1175 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1179 DEFUN ("set-process-query-on-exit-flag",
1180 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1182 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1183 If the second argument FLAG is non-nil, Emacs will query the user before
1184 exiting or killing a buffer if PROCESS is running. This function
1186 (register Lisp_Object process
, Lisp_Object flag
)
1188 CHECK_PROCESS (process
);
1189 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1193 DEFUN ("process-query-on-exit-flag",
1194 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1196 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1197 (register Lisp_Object process
)
1199 CHECK_PROCESS (process
);
1200 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1203 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1205 doc
: /* Return the contact info of PROCESS; t for a real child.
1206 For a network or serial connection, the value depends on the optional
1207 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1208 SERVICE) for a network connection or (PORT SPEED) for a serial
1209 connection. If KEY is t, the complete contact information for the
1210 connection is returned, else the specific value for the keyword KEY is
1211 returned. See `make-network-process' or `make-serial-process' for a
1213 If PROCESS is a non-blocking network process that hasn't been fully
1214 set up yet, this function will block until socket setup has completed. */)
1215 (Lisp_Object process
, Lisp_Object key
)
1217 Lisp_Object contact
;
1219 CHECK_PROCESS (process
);
1220 contact
= XPROCESS (process
)->childp
;
1222 #ifdef DATAGRAM_SOCKETS
1224 if (NETCONN_P (process
))
1225 wait_for_socket_fds (process
, "process-contact");
1227 if (DATAGRAM_CONN_P (process
)
1228 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1229 contact
= Fplist_put (contact
, QCremote
,
1230 Fprocess_datagram_address (process
));
1233 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1236 if (NILP (key
) && NETCONN_P (process
))
1237 return list2 (Fplist_get (contact
, QChost
),
1238 Fplist_get (contact
, QCservice
));
1239 if (NILP (key
) && SERIALCONN_P (process
))
1240 return list2 (Fplist_get (contact
, QCport
),
1241 Fplist_get (contact
, QCspeed
));
1242 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1243 if the pipe process is useful for purposes other than receiving
1245 if (NILP (key
) && PIPECONN_P (process
))
1247 return Fplist_get (contact
, key
);
1250 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1252 doc
: /* Return the plist of PROCESS. */)
1253 (register Lisp_Object process
)
1255 CHECK_PROCESS (process
);
1256 return XPROCESS (process
)->plist
;
1259 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1261 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1262 (Lisp_Object process
, Lisp_Object plist
)
1264 CHECK_PROCESS (process
);
1267 pset_plist (XPROCESS (process
), plist
);
1271 #if 0 /* Turned off because we don't currently record this info
1272 in the process. Perhaps add it. */
1273 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1274 doc
: /* Return the connection type of PROCESS.
1275 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1276 a socket connection. */)
1277 (Lisp_Object process
)
1279 return XPROCESS (process
)->type
;
1283 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1284 doc
: /* Return the connection type of PROCESS.
1285 The value is either the symbol `real', `network', or `serial'.
1286 PROCESS may be a process, a buffer, the name of a process or buffer, or
1287 nil, indicating the current buffer's process. */)
1288 (Lisp_Object process
)
1291 proc
= get_process (process
);
1292 return XPROCESS (proc
)->type
;
1295 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1297 doc
: /* Convert network ADDRESS from internal format to a string.
1298 A 4 or 5 element vector represents an IPv4 address (with port number).
1299 An 8 or 9 element vector represents an IPv6 address (with port number).
1300 If optional second argument OMIT-PORT is non-nil, don't include a port
1301 number in the string, even when present in ADDRESS.
1302 Return nil if format of ADDRESS is invalid. */)
1303 (Lisp_Object address
, Lisp_Object omit_port
)
1308 if (STRINGP (address
)) /* AF_LOCAL */
1311 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1313 register struct Lisp_Vector
*p
= XVECTOR (address
);
1314 ptrdiff_t size
= p
->header
.size
;
1315 Lisp_Object args
[10];
1319 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1321 format
= "%d.%d.%d.%d";
1326 format
= "%d.%d.%d.%d:%d";
1329 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1331 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1336 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1342 AUTO_STRING (format_obj
, format
);
1343 args
[0] = format_obj
;
1345 for (i
= 0; i
< nargs
; i
++)
1347 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1350 if (nargs
<= 5 /* IPv4 */
1351 && i
< 4 /* host, not port */
1352 && XINT (p
->contents
[i
]) > 255)
1355 args
[i
+ 1] = p
->contents
[i
];
1358 return Fformat (nargs
+ 1, args
);
1361 if (CONSP (address
))
1363 AUTO_STRING (format
, "<Family %d>");
1364 return CALLN (Fformat
, format
, Fcar (address
));
1370 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1371 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1374 return Fmapcar (Qcdr
, Vprocess_alist
);
1377 /* Starting asynchronous inferior processes. */
1379 static void start_process_unwind (Lisp_Object proc
);
1381 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1382 doc
: /* Start a program in a subprocess. Return the process object for it.
1384 This is similar to `start-process', but arguments are specified as
1385 keyword/argument pairs. The following arguments are defined:
1387 :name NAME -- NAME is name for process. It is modified if necessary
1390 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1391 with the process. Process output goes at end of that buffer, unless
1392 you specify an output stream or filter function to handle the output.
1393 BUFFER may be also nil, meaning that this process is not associated
1396 :command COMMAND -- COMMAND is a list starting with the program file
1397 name, followed by strings to give to the program as arguments.
1399 :coding CODING -- If CODING is a symbol, it specifies the coding
1400 system used for both reading and writing for this process. If CODING
1401 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1402 ENCODING is used for writing.
1404 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1405 the process is running. If BOOL is not given, query before exiting.
1407 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1408 In the stopped state, a process does not accept incoming data, but you
1409 can send outgoing data. The stopped state is cleared by
1410 `continue-process' and set by `stop-process'.
1412 :connection-type TYPE -- TYPE is control type of device used to
1413 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1414 to use a pty, or nil to use the default specified through
1415 `process-connection-type'.
1417 :filter FILTER -- Install FILTER as the process filter.
1419 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1421 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1422 to the standard error of subprocess. Specifying this implies
1423 `:connection-type' is set to `pipe'.
1425 usage: (make-process &rest ARGS) */)
1426 (ptrdiff_t nargs
, Lisp_Object
*args
)
1428 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1429 Lisp_Object xstderr
, stderrproc
;
1430 ptrdiff_t count
= SPECPDL_INDEX ();
1436 /* Save arguments for process-contact and clone-process. */
1437 contact
= Flist (nargs
, args
);
1439 buffer
= Fplist_get (contact
, QCbuffer
);
1441 buffer
= Fget_buffer_create (buffer
);
1443 /* Make sure that the child will be able to chdir to the current
1444 buffer's current directory, or its unhandled equivalent. We
1445 can't just have the child check for an error when it does the
1446 chdir, since it's in a vfork. */
1447 current_dir
= encode_current_directory ();
1449 name
= Fplist_get (contact
, QCname
);
1450 CHECK_STRING (name
);
1452 command
= Fplist_get (contact
, QCcommand
);
1453 if (CONSP (command
))
1454 program
= XCAR (command
);
1458 if (!NILP (program
))
1459 CHECK_STRING (program
);
1462 xstderr
= Fplist_get (contact
, QCstderr
);
1463 if (PROCESSP (xstderr
))
1465 if (!PIPECONN_P (xstderr
))
1466 error ("Process is not a pipe process");
1467 stderrproc
= xstderr
;
1469 else if (!NILP (xstderr
))
1471 CHECK_STRING (program
);
1472 stderrproc
= CALLN (Fmake_pipe_process
,
1474 concat2 (name
, build_string (" stderr")),
1476 Fget_buffer_create (xstderr
));
1479 proc
= make_process (name
);
1480 /* If an error occurs and we can't start the process, we want to
1481 remove it from the process list. This means that each error
1482 check in create_process doesn't need to call remove_process
1483 itself; it's all taken care of here. */
1484 record_unwind_protect (start_process_unwind
, proc
);
1486 pset_childp (XPROCESS (proc
), Qt
);
1487 pset_plist (XPROCESS (proc
), Qnil
);
1488 pset_type (XPROCESS (proc
), Qreal
);
1489 pset_buffer (XPROCESS (proc
), buffer
);
1490 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1491 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1492 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1494 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1495 XPROCESS (proc
)->kill_without_query
= 1;
1496 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1497 pset_command (XPROCESS (proc
), Qt
);
1499 tem
= Fplist_get (contact
, QCconnection_type
);
1501 XPROCESS (proc
)->pty_flag
= true;
1502 else if (EQ (tem
, Qpipe
))
1503 XPROCESS (proc
)->pty_flag
= false;
1504 else if (NILP (tem
))
1505 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1507 report_file_error ("Unknown connection type", tem
);
1509 if (!NILP (stderrproc
))
1511 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1513 XPROCESS (proc
)->pty_flag
= false;
1517 /* AKA GNUTLS_INITSTAGE(proc). */
1518 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1519 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1522 XPROCESS (proc
)->adaptive_read_buffering
1523 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1524 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1526 /* Make the process marker point into the process buffer (if any). */
1527 if (BUFFERP (buffer
))
1528 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1529 BUF_ZV (XBUFFER (buffer
)),
1530 BUF_ZV_BYTE (XBUFFER (buffer
)));
1533 /* Decide coding systems for communicating with the process. Here
1534 we don't setup the structure coding_system nor pay attention to
1535 unibyte mode. They are done in create_process. */
1537 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1538 Lisp_Object coding_systems
= Qt
;
1539 Lisp_Object val
, *args2
;
1541 tem
= Fplist_get (contact
, QCcoding
);
1549 val
= Vcoding_system_for_read
;
1552 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1554 SAFE_ALLOCA_LISP (args2
, nargs2
);
1556 args2
[i
++] = Qstart_process
;
1558 args2
[i
++] = buffer
;
1559 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1560 args2
[i
++] = XCAR (tem2
);
1561 if (!NILP (program
))
1562 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1563 if (CONSP (coding_systems
))
1564 val
= XCAR (coding_systems
);
1565 else if (CONSP (Vdefault_process_coding_system
))
1566 val
= XCAR (Vdefault_process_coding_system
);
1568 pset_decode_coding_system (XPROCESS (proc
), val
);
1577 val
= Vcoding_system_for_write
;
1580 if (EQ (coding_systems
, Qt
))
1582 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1584 SAFE_ALLOCA_LISP (args2
, nargs2
);
1586 args2
[i
++] = Qstart_process
;
1588 args2
[i
++] = buffer
;
1589 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1590 args2
[i
++] = XCAR (tem2
);
1591 if (!NILP (program
))
1592 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1594 if (CONSP (coding_systems
))
1595 val
= XCDR (coding_systems
);
1596 else if (CONSP (Vdefault_process_coding_system
))
1597 val
= XCDR (Vdefault_process_coding_system
);
1599 pset_encode_coding_system (XPROCESS (proc
), val
);
1600 /* Note: At this moment, the above coding system may leave
1601 text-conversion or eol-conversion unspecified. They will be
1602 decided after we read output from the process and decode it by
1603 some coding system, or just before we actually send a text to
1608 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1609 XPROCESS (proc
)->decoding_carryover
= 0;
1610 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1612 XPROCESS (proc
)->inherit_coding_system_flag
1613 = !(NILP (buffer
) || !inherit_process_coding_system
);
1615 if (!NILP (program
))
1617 Lisp_Object program_args
= XCDR (command
);
1619 /* If program file name is not absolute, search our path for it.
1620 Put the name we will really use in TEM. */
1621 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1622 && !(SCHARS (program
) > 1
1623 && IS_DEVICE_SEP (SREF (program
, 1))))
1626 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1627 make_number (X_OK
), false);
1629 report_file_error ("Searching for program", program
);
1630 tem
= Fexpand_file_name (tem
, Qnil
);
1634 if (!NILP (Ffile_directory_p (program
)))
1635 error ("Specified program for new process is a directory");
1639 /* Remove "/:" from TEM. */
1640 tem
= remove_slash_colon (tem
);
1642 Lisp_Object arg_encoding
= Qnil
;
1644 /* Encode the file name and put it in NEW_ARGV.
1645 That's where the child will use it to execute the program. */
1646 tem
= list1 (ENCODE_FILE (tem
));
1647 ptrdiff_t new_argc
= 1;
1649 /* Here we encode arguments by the coding system used for sending
1650 data to the process. We don't support using different coding
1651 systems for encoding arguments and for encoding data sent to the
1654 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1656 Lisp_Object arg
= XCAR (tem2
);
1658 if (STRING_MULTIBYTE (arg
))
1660 if (NILP (arg_encoding
))
1661 arg_encoding
= (complement_process_encoding_system
1662 (XPROCESS (proc
)->encode_coding_system
));
1663 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1665 tem
= Fcons (arg
, tem
);
1669 /* Now that everything is encoded we can collect the strings into
1672 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1673 new_argv
[new_argc
] = 0;
1675 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1677 new_argv
[i
] = SSDATA (XCAR (tem
));
1681 create_process (proc
, new_argv
, current_dir
);
1687 return unbind_to (count
, proc
);
1690 /* This function is the unwind_protect form for Fstart_process. If
1691 PROC doesn't have its pid set, then we know someone has signaled
1692 an error and the process wasn't started successfully, so we should
1693 remove it from the process list. */
1695 start_process_unwind (Lisp_Object proc
)
1697 if (!PROCESSP (proc
))
1700 /* Was PROC started successfully?
1701 -2 is used for a pty with no process, eg for gdb. */
1702 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1703 remove_process (proc
);
1706 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1709 close_process_fd (int *fd_addr
)
1719 /* Indexes of file descriptors in open_fds. */
1722 /* The pipe from Emacs to its subprocess. */
1724 WRITE_TO_SUBPROCESS
,
1726 /* The main pipe from the subprocess to Emacs. */
1727 READ_FROM_SUBPROCESS
,
1730 /* The pipe from the subprocess to Emacs that is closed when the
1731 subprocess execs. */
1732 READ_FROM_EXEC_MONITOR
,
1736 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1739 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1741 struct Lisp_Process
*p
= XPROCESS (process
);
1742 int inchannel
, outchannel
;
1745 int forkin
, forkout
, forkerr
= -1;
1747 char pty_name
[PTY_NAME_SIZE
];
1748 Lisp_Object lisp_pty_name
= Qnil
;
1751 inchannel
= outchannel
= -1;
1754 outchannel
= inchannel
= allocate_pty (pty_name
);
1758 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1759 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1760 /* On most USG systems it does not work to open the pty's tty here,
1761 then close it and reopen it in the child. */
1762 /* Don't let this terminal become our controlling terminal
1763 (in case we don't have one). */
1764 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1766 report_file_error ("Opening pty", Qnil
);
1767 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1769 forkin
= forkout
= -1;
1770 #endif /* not USG, or USG_SUBTTY_WORKS */
1772 lisp_pty_name
= build_string (pty_name
);
1776 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1777 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1778 report_file_error ("Creating pipe", Qnil
);
1779 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1780 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1781 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1782 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1784 if (!NILP (p
->stderrproc
))
1786 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1788 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1790 /* Close unnecessary file descriptors. */
1791 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1792 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1797 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1798 report_file_error ("Creating pipe", Qnil
);
1801 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1802 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1804 /* Record this as an active process, with its channels. */
1805 chan_process
[inchannel
] = process
;
1806 p
->infd
= inchannel
;
1807 p
->outfd
= outchannel
;
1809 /* Previously we recorded the tty descriptor used in the subprocess.
1810 It was only used for getting the foreground tty process, so now
1811 we just reopen the device (see emacs_get_tty_pgrp) as this is
1812 more portable (see USG_SUBTTY_WORKS above). */
1814 p
->pty_flag
= pty_flag
;
1815 pset_status (p
, Qrun
);
1817 if (!EQ (p
->command
, Qt
))
1819 FD_SET (inchannel
, &input_wait_mask
);
1820 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1823 if (inchannel
> max_process_desc
)
1824 max_process_desc
= inchannel
;
1826 /* This may signal an error. */
1827 setup_process_coding_systems (process
);
1830 block_child_signal (&oldset
);
1833 /* vfork, and prevent local vars from being clobbered by the vfork. */
1834 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1835 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1836 char **volatile new_argv_volatile
= new_argv
;
1837 int volatile forkin_volatile
= forkin
;
1838 int volatile forkout_volatile
= forkout
;
1839 int volatile forkerr_volatile
= forkerr
;
1840 struct Lisp_Process
*p_volatile
= p
;
1844 current_dir
= current_dir_volatile
;
1845 lisp_pty_name
= lisp_pty_name_volatile
;
1846 new_argv
= new_argv_volatile
;
1847 forkin
= forkin_volatile
;
1848 forkout
= forkout_volatile
;
1849 forkerr
= forkerr_volatile
;
1852 pty_flag
= p
->pty_flag
;
1855 #endif /* not WINDOWSNT */
1857 /* Make the pty be the controlling terminal of the process. */
1859 /* First, disconnect its current controlling terminal. */
1860 /* We tried doing setsid only if pty_flag, but it caused
1861 process_set_signal to fail on SGI when using a pipe. */
1863 /* Make the pty's terminal the controlling terminal. */
1864 if (pty_flag
&& forkin
>= 0)
1867 /* We ignore the return value
1868 because faith@cs.unc.edu says that is necessary on Linux. */
1869 ioctl (forkin
, TIOCSCTTY
, 0);
1872 #if defined (LDISC1)
1873 if (pty_flag
&& forkin
>= 0)
1876 tcgetattr (forkin
, &t
);
1878 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1879 emacs_perror ("create_process/tcsetattr LDISC1");
1882 #if defined (NTTYDISC) && defined (TIOCSETD)
1883 if (pty_flag
&& forkin
>= 0)
1885 /* Use new line discipline. */
1886 int ldisc
= NTTYDISC
;
1887 ioctl (forkin
, TIOCSETD
, &ldisc
);
1892 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1893 can do TIOCSPGRP only to the process's controlling tty. */
1896 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1897 I can't test it since I don't have 4.3. */
1898 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1901 ioctl (j
, TIOCNOTTY
, 0);
1905 #endif /* TIOCNOTTY */
1907 #if !defined (DONT_REOPEN_PTY)
1908 /*** There is a suggestion that this ought to be a
1909 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1910 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1911 that system does seem to need this code, even though
1912 both TIOCSCTTY is defined. */
1913 /* Now close the pty (if we had it open) and reopen it.
1914 This makes the pty the controlling terminal of the subprocess. */
1918 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1921 emacs_close (forkin
);
1922 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1926 emacs_perror (SSDATA (lisp_pty_name
));
1927 _exit (EXIT_CANCELED
);
1931 #endif /* not DONT_REOPEN_PTY */
1933 #ifdef SETUP_SLAVE_PTY
1938 #endif /* SETUP_SLAVE_PTY */
1939 #endif /* HAVE_PTYS */
1941 signal (SIGINT
, SIG_DFL
);
1942 signal (SIGQUIT
, SIG_DFL
);
1944 signal (SIGPROF
, SIG_DFL
);
1947 /* Emacs ignores SIGPIPE, but the child should not. */
1948 signal (SIGPIPE
, SIG_DFL
);
1950 /* Stop blocking SIGCHLD in the child. */
1951 unblock_child_signal (&oldset
);
1954 child_setup_tty (forkout
);
1959 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1960 #else /* not WINDOWSNT */
1961 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1962 #endif /* not WINDOWSNT */
1965 /* Back in the parent process. */
1967 vfork_errno
= errno
;
1972 /* Stop blocking in the parent. */
1973 unblock_child_signal (&oldset
);
1977 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1980 /* vfork succeeded. */
1982 /* Close the pipe ends that the child uses, or the child's pty. */
1983 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1984 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1987 register_child (pid
, inchannel
);
1988 #endif /* WINDOWSNT */
1990 pset_tty_name (p
, lisp_pty_name
);
1993 /* Wait for child_setup to complete in case that vfork is
1994 actually defined as fork. The descriptor
1995 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1996 of a pipe is closed at the child side either by close-on-exec
1997 on successful execve or the _exit call in child_setup. */
2001 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2002 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2003 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2006 if (!NILP (p
->stderrproc
))
2008 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2009 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2015 create_pty (Lisp_Object process
)
2017 struct Lisp_Process
*p
= XPROCESS (process
);
2018 char pty_name
[PTY_NAME_SIZE
];
2019 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2023 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2024 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2025 /* On most USG systems it does not work to open the pty's tty here,
2026 then close it and reopen it in the child. */
2027 /* Don't let this terminal become our controlling terminal
2028 (in case we don't have one). */
2029 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2031 report_file_error ("Opening pty", Qnil
);
2032 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2033 #if defined (DONT_REOPEN_PTY)
2034 /* In the case that vfork is defined as fork, the parent process
2035 (Emacs) may send some data before the child process completes
2036 tty options setup. So we setup tty before forking. */
2037 child_setup_tty (forkout
);
2038 #endif /* DONT_REOPEN_PTY */
2039 #endif /* not USG, or USG_SUBTTY_WORKS */
2041 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2043 /* Record this as an active process, with its channels.
2044 As a result, child_setup will close Emacs's side of the pipes. */
2045 chan_process
[pty_fd
] = process
;
2049 /* Previously we recorded the tty descriptor used in the subprocess.
2050 It was only used for getting the foreground tty process, so now
2051 we just reopen the device (see emacs_get_tty_pgrp) as this is
2052 more portable (see USG_SUBTTY_WORKS above). */
2055 pset_status (p
, Qrun
);
2056 setup_process_coding_systems (process
);
2058 FD_SET (pty_fd
, &input_wait_mask
);
2059 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2060 if (pty_fd
> max_process_desc
)
2061 max_process_desc
= pty_fd
;
2063 pset_tty_name (p
, build_string (pty_name
));
2069 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2071 doc
: /* Create and return a bidirectional pipe process.
2073 In Emacs, pipes are represented by process objects, so input and
2074 output work as for subprocesses, and `delete-process' closes a pipe.
2075 However, a pipe process has no process id, it cannot be signaled,
2076 and the status codes are different from normal processes.
2078 Arguments are specified as keyword/argument pairs. The following
2079 arguments are defined:
2081 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2083 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2084 with the process. Process output goes at the end of that buffer,
2085 unless you specify an output stream or filter function to handle the
2086 output. If BUFFER is not given, the value of NAME is used.
2088 :coding CODING -- If CODING is a symbol, it specifies the coding
2089 system used for both reading and writing for this process. If CODING
2090 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2091 ENCODING is used for writing.
2093 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2094 the process is running. If BOOL is not given, query before exiting.
2096 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2097 In the stopped state, a pipe process does not accept incoming data,
2098 but you can send outgoing data. The stopped state is cleared by
2099 `continue-process' and set by `stop-process'.
2101 :filter FILTER -- Install FILTER as the process filter.
2103 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2105 usage: (make-pipe-process &rest ARGS) */)
2106 (ptrdiff_t nargs
, Lisp_Object
*args
)
2108 Lisp_Object proc
, contact
;
2109 struct Lisp_Process
*p
;
2110 Lisp_Object name
, buffer
;
2112 ptrdiff_t specpdl_count
;
2113 int inchannel
, outchannel
;
2118 contact
= Flist (nargs
, args
);
2120 name
= Fplist_get (contact
, QCname
);
2121 CHECK_STRING (name
);
2122 proc
= make_process (name
);
2123 specpdl_count
= SPECPDL_INDEX ();
2124 record_unwind_protect (remove_process
, proc
);
2125 p
= XPROCESS (proc
);
2127 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2128 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2129 report_file_error ("Creating pipe", Qnil
);
2130 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2131 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2133 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2134 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2137 register_aux_fd (inchannel
);
2140 /* Record this as an active process, with its channels. */
2141 chan_process
[inchannel
] = proc
;
2142 p
->infd
= inchannel
;
2143 p
->outfd
= outchannel
;
2145 if (inchannel
> max_process_desc
)
2146 max_process_desc
= inchannel
;
2148 buffer
= Fplist_get (contact
, QCbuffer
);
2151 buffer
= Fget_buffer_create (buffer
);
2152 pset_buffer (p
, buffer
);
2154 pset_childp (p
, contact
);
2155 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2156 pset_type (p
, Qpipe
);
2157 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2158 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2160 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2161 p
->kill_without_query
= 1;
2162 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2163 pset_command (p
, Qt
);
2164 eassert (! p
->pty_flag
);
2166 if (!EQ (p
->command
, Qt
))
2168 FD_SET (inchannel
, &input_wait_mask
);
2169 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2171 p
->adaptive_read_buffering
2172 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2173 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2175 /* Make the process marker point into the process buffer (if any). */
2176 if (BUFFERP (buffer
))
2177 set_marker_both (p
->mark
, buffer
,
2178 BUF_ZV (XBUFFER (buffer
)),
2179 BUF_ZV_BYTE (XBUFFER (buffer
)));
2182 /* Setup coding systems for communicating with the network stream. */
2184 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2185 Lisp_Object coding_systems
= Qt
;
2188 tem
= Fplist_get (contact
, QCcoding
);
2196 else if (!NILP (Vcoding_system_for_read
))
2197 val
= Vcoding_system_for_read
;
2198 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2199 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2200 /* We dare not decode end-of-line format by setting VAL to
2201 Qraw_text, because the existing Emacs Lisp libraries
2202 assume that they receive bare code including a sequence of
2207 if (CONSP (coding_systems
))
2208 val
= XCAR (coding_systems
);
2209 else if (CONSP (Vdefault_process_coding_system
))
2210 val
= XCAR (Vdefault_process_coding_system
);
2214 pset_decode_coding_system (p
, val
);
2222 else if (!NILP (Vcoding_system_for_write
))
2223 val
= Vcoding_system_for_write
;
2224 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2228 if (CONSP (coding_systems
))
2229 val
= XCDR (coding_systems
);
2230 else if (CONSP (Vdefault_process_coding_system
))
2231 val
= XCDR (Vdefault_process_coding_system
);
2235 pset_encode_coding_system (p
, val
);
2237 /* This may signal an error. */
2238 setup_process_coding_systems (proc
);
2240 specpdl_ptr
= specpdl
+ specpdl_count
;
2246 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2247 The address family of sa is not included in the result. */
2250 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2252 Lisp_Object address
;
2255 struct Lisp_Vector
*p
;
2257 /* Workaround for a bug in getsockname on BSD: Names bound to
2258 sockets in the UNIX domain are inaccessible; getsockname returns
2259 a zero length name. */
2260 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2261 return empty_unibyte_string
;
2263 switch (sa
->sa_family
)
2267 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2268 len
= sizeof (sin
->sin_addr
) + 1;
2269 address
= Fmake_vector (make_number (len
), Qnil
);
2270 p
= XVECTOR (address
);
2271 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2272 cp
= (unsigned char *) &sin
->sin_addr
;
2278 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2279 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2280 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2281 address
= Fmake_vector (make_number (len
), Qnil
);
2282 p
= XVECTOR (address
);
2283 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2284 for (i
= 0; i
< len
; i
++)
2285 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2289 #ifdef HAVE_LOCAL_SOCKETS
2292 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2293 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2294 /* If the first byte is NUL, the name is a Linux abstract
2295 socket name, and the name can contain embedded NULs. If
2296 it's not, we have a NUL-terminated string. Be careful not
2297 to walk past the end of the object looking for the name
2298 terminator, however. */
2299 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2301 const char *terminator
2302 = memchr (sockun
->sun_path
, '\0', name_length
);
2305 name_length
= terminator
- (const char *) sockun
->sun_path
;
2308 return make_unibyte_string (sockun
->sun_path
, name_length
);
2312 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2313 address
= Fcons (make_number (sa
->sa_family
),
2314 Fmake_vector (make_number (len
), Qnil
));
2315 p
= XVECTOR (XCDR (address
));
2316 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2322 p
->contents
[i
++] = make_number (*cp
++);
2328 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2331 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2333 struct Lisp_Vector
*p
;
2335 if (VECTORP (address
))
2337 p
= XVECTOR (address
);
2338 if (p
->header
.size
== 5)
2341 return sizeof (struct sockaddr_in
);
2344 else if (p
->header
.size
== 9)
2346 *familyp
= AF_INET6
;
2347 return sizeof (struct sockaddr_in6
);
2351 #ifdef HAVE_LOCAL_SOCKETS
2352 else if (STRINGP (address
))
2354 *familyp
= AF_LOCAL
;
2355 return sizeof (struct sockaddr_un
);
2358 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2359 && VECTORP (XCDR (address
)))
2361 struct sockaddr
*sa
;
2362 p
= XVECTOR (XCDR (address
));
2363 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2365 *familyp
= XINT (XCAR (address
));
2366 return p
->header
.size
+ sizeof (sa
->sa_family
);
2371 /* Convert an address object (vector or string) to an internal sockaddr.
2373 The address format has been basically validated by
2374 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2375 it could have come from user data. So if FAMILY is not valid,
2376 we return after zeroing *SA. */
2379 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2381 register struct Lisp_Vector
*p
;
2382 register unsigned char *cp
= NULL
;
2386 memset (sa
, 0, len
);
2388 if (VECTORP (address
))
2390 p
= XVECTOR (address
);
2391 if (family
== AF_INET
)
2393 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2394 len
= sizeof (sin
->sin_addr
) + 1;
2395 hostport
= XINT (p
->contents
[--len
]);
2396 sin
->sin_port
= htons (hostport
);
2397 cp
= (unsigned char *)&sin
->sin_addr
;
2398 sa
->sa_family
= family
;
2401 else if (family
== AF_INET6
)
2403 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2404 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2405 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2406 hostport
= XINT (p
->contents
[--len
]);
2407 sin6
->sin6_port
= htons (hostport
);
2408 for (i
= 0; i
< len
; i
++)
2409 if (INTEGERP (p
->contents
[i
]))
2411 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2414 sa
->sa_family
= family
;
2421 else if (STRINGP (address
))
2423 #ifdef HAVE_LOCAL_SOCKETS
2424 if (family
== AF_LOCAL
)
2426 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2427 cp
= SDATA (address
);
2428 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2429 sockun
->sun_path
[i
] = *cp
++;
2430 sa
->sa_family
= family
;
2437 p
= XVECTOR (XCDR (address
));
2438 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2441 for (i
= 0; i
< len
; i
++)
2442 if (INTEGERP (p
->contents
[i
]))
2443 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2446 #ifdef DATAGRAM_SOCKETS
2447 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2449 doc
: /* Get the current datagram address associated with PROCESS.
2450 If PROCESS is a non-blocking network process that hasn't been fully
2451 set up yet, this function will block until socket setup has completed. */)
2452 (Lisp_Object process
)
2456 CHECK_PROCESS (process
);
2458 if (NETCONN_P (process
))
2459 wait_for_socket_fds (process
, "process-datagram-address");
2461 if (!DATAGRAM_CONN_P (process
))
2464 channel
= XPROCESS (process
)->infd
;
2465 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2466 datagram_address
[channel
].len
);
2469 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2471 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2472 Return nil upon error setting address, ADDRESS otherwise.
2474 If PROCESS is a non-blocking network process that hasn't been fully
2475 set up yet, this function will block until socket setup has completed. */)
2476 (Lisp_Object process
, Lisp_Object address
)
2482 CHECK_PROCESS (process
);
2484 if (NETCONN_P (process
))
2485 wait_for_socket_fds (process
, "set-process-datagram-address");
2487 if (!DATAGRAM_CONN_P (process
))
2490 channel
= XPROCESS (process
)->infd
;
2492 len
= get_lisp_to_sockaddr_size (address
, &family
);
2493 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2495 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2501 static const struct socket_options
{
2502 /* The name of this option. Should be lowercase version of option
2503 name without SO_ prefix. */
2505 /* Option level SOL_... */
2507 /* Option number SO_... */
2509 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2510 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2511 } socket_options
[] =
2513 #ifdef SO_BINDTODEVICE
2514 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2517 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2520 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2523 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2526 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2529 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2532 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2535 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2537 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2540 /* Set option OPT to value VAL on socket S.
2542 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2543 Signals an error if setting a known option fails.
2547 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2550 const struct socket_options
*sopt
;
2555 name
= SSDATA (SYMBOL_NAME (opt
));
2556 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2557 if (strcmp (name
, sopt
->name
) == 0)
2560 switch (sopt
->opttype
)
2565 optval
= NILP (val
) ? 0 : 1;
2566 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2567 &optval
, sizeof (optval
));
2574 if (TYPE_RANGED_INTEGERP (int, val
))
2575 optval
= XINT (val
);
2577 error ("Bad option value for %s", name
);
2578 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2579 &optval
, sizeof (optval
));
2583 #ifdef SO_BINDTODEVICE
2586 char devname
[IFNAMSIZ
+ 1];
2588 /* This is broken, at least in the Linux 2.4 kernel.
2589 To unbind, the arg must be a zero integer, not the empty string.
2590 This should work on all systems. KFS. 2003-09-23. */
2591 memset (devname
, 0, sizeof devname
);
2594 char *arg
= SSDATA (val
);
2595 int len
= min (strlen (arg
), IFNAMSIZ
);
2596 memcpy (devname
, arg
, len
);
2598 else if (!NILP (val
))
2599 error ("Bad option value for %s", name
);
2600 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2609 struct linger linger
;
2612 linger
.l_linger
= 0;
2613 if (TYPE_RANGED_INTEGERP (int, val
))
2614 linger
.l_linger
= XINT (val
);
2616 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2617 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2618 &linger
, sizeof (linger
));
2629 int setsockopt_errno
= errno
;
2630 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2634 return (1 << sopt
->optbit
);
2638 DEFUN ("set-network-process-option",
2639 Fset_network_process_option
, Sset_network_process_option
,
2641 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2642 See `make-network-process' for a list of options and values.
2643 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2644 OPTION is not a supported option, return nil instead; otherwise return t.
2646 If PROCESS is a non-blocking network process that hasn't been fully
2647 set up yet, this function will block until socket setup has completed. */)
2648 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2651 struct Lisp_Process
*p
;
2653 CHECK_PROCESS (process
);
2654 p
= XPROCESS (process
);
2655 if (!NETCONN1_P (p
))
2656 error ("Process is not a network process");
2658 wait_for_socket_fds (process
, "set-network-process-option");
2662 error ("Process is not running");
2664 if (set_socket_option (s
, option
, value
))
2666 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2670 if (NILP (no_error
))
2671 error ("Unknown or unsupported option");
2677 DEFUN ("serial-process-configure",
2678 Fserial_process_configure
,
2679 Sserial_process_configure
,
2681 doc
: /* Configure speed, bytesize, etc. of a serial process.
2683 Arguments are specified as keyword/argument pairs. Attributes that
2684 are not given are re-initialized from the process's current
2685 configuration (available via the function `process-contact') or set to
2686 reasonable default values. The following arguments are defined:
2692 -- Any of these arguments can be given to identify the process that is
2693 to be configured. If none of these arguments is given, the current
2694 buffer's process is used.
2696 :speed SPEED -- SPEED is the speed of the serial port in bits per
2697 second, also called baud rate. Any value can be given for SPEED, but
2698 most serial ports work only at a few defined values between 1200 and
2699 115200, with 9600 being the most common value. If SPEED is nil, the
2700 serial port is not configured any further, i.e., all other arguments
2701 are ignored. This may be useful for special serial ports such as
2702 Bluetooth-to-serial converters which can only be configured through AT
2703 commands. A value of nil for SPEED can be used only when passed
2704 through `make-serial-process' or `serial-term'.
2706 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2707 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2709 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2710 `odd' (use odd parity), or the symbol `even' (use even parity). If
2711 PARITY is not given, no parity is used.
2713 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2714 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2715 is not given or nil, 1 stopbit is used.
2717 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2718 flowcontrol to be used, which is either nil (don't use flowcontrol),
2719 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2720 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2721 flowcontrol is used.
2723 `serial-process-configure' is called by `make-serial-process' for the
2724 initial configuration of the serial port.
2728 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2730 \(serial-process-configure
2731 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2733 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2735 usage: (serial-process-configure &rest ARGS) */)
2736 (ptrdiff_t nargs
, Lisp_Object
*args
)
2738 struct Lisp_Process
*p
;
2739 Lisp_Object contact
= Qnil
;
2740 Lisp_Object proc
= Qnil
;
2742 contact
= Flist (nargs
, args
);
2744 proc
= Fplist_get (contact
, QCprocess
);
2746 proc
= Fplist_get (contact
, QCname
);
2748 proc
= Fplist_get (contact
, QCbuffer
);
2750 proc
= Fplist_get (contact
, QCport
);
2751 proc
= get_process (proc
);
2752 p
= XPROCESS (proc
);
2753 if (!EQ (p
->type
, Qserial
))
2754 error ("Not a serial process");
2756 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2759 serial_configure (p
, contact
);
2763 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2765 doc
: /* Create and return a serial port process.
2767 In Emacs, serial port connections are represented by process objects,
2768 so input and output work as for subprocesses, and `delete-process'
2769 closes a serial port connection. However, a serial process has no
2770 process id, it cannot be signaled, and the status codes are different
2771 from normal processes.
2773 `make-serial-process' creates a process and a buffer, on which you
2774 probably want to use `process-send-string'. Try \\[serial-term] for
2775 an interactive terminal. See below for examples.
2777 Arguments are specified as keyword/argument pairs. The following
2778 arguments are defined:
2780 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2781 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2782 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2783 the backslashes in strings).
2785 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2786 which this function calls.
2788 :name NAME -- NAME is the name of the process. If NAME is not given,
2789 the value of PORT is used.
2791 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2792 with the process. Process output goes at the end of that buffer,
2793 unless you specify an output stream or filter function to handle the
2794 output. If BUFFER is not given, the value of NAME is used.
2796 :coding CODING -- If CODING is a symbol, it specifies the coding
2797 system used for both reading and writing for this process. If CODING
2798 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2799 ENCODING is used for writing.
2801 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2802 the process is running. If BOOL is not given, query before exiting.
2804 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2805 In the stopped state, a serial process does not accept incoming data,
2806 but you can send outgoing data. The stopped state is cleared by
2807 `continue-process' and set by `stop-process'.
2809 :filter FILTER -- Install FILTER as the process filter.
2811 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2813 :plist PLIST -- Install PLIST as the initial plist of the process.
2819 -- This function calls `serial-process-configure' to handle these
2822 The original argument list, possibly modified by later configuration,
2823 is available via the function `process-contact'.
2827 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2829 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2831 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2833 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2835 usage: (make-serial-process &rest ARGS) */)
2836 (ptrdiff_t nargs
, Lisp_Object
*args
)
2839 Lisp_Object proc
, contact
, port
;
2840 struct Lisp_Process
*p
;
2841 Lisp_Object name
, buffer
;
2842 Lisp_Object tem
, val
;
2843 ptrdiff_t specpdl_count
;
2848 contact
= Flist (nargs
, args
);
2850 port
= Fplist_get (contact
, QCport
);
2852 error ("No port specified");
2853 CHECK_STRING (port
);
2855 if (NILP (Fplist_member (contact
, QCspeed
)))
2856 error (":speed not specified");
2857 if (!NILP (Fplist_get (contact
, QCspeed
)))
2858 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2860 name
= Fplist_get (contact
, QCname
);
2863 CHECK_STRING (name
);
2864 proc
= make_process (name
);
2865 specpdl_count
= SPECPDL_INDEX ();
2866 record_unwind_protect (remove_process
, proc
);
2867 p
= XPROCESS (proc
);
2869 fd
= serial_open (port
);
2870 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2873 if (fd
> max_process_desc
)
2874 max_process_desc
= fd
;
2875 chan_process
[fd
] = proc
;
2877 buffer
= Fplist_get (contact
, QCbuffer
);
2880 buffer
= Fget_buffer_create (buffer
);
2881 pset_buffer (p
, buffer
);
2883 pset_childp (p
, contact
);
2884 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2885 pset_type (p
, Qserial
);
2886 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2887 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2889 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2890 p
->kill_without_query
= 1;
2891 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2892 pset_command (p
, Qt
);
2893 eassert (! p
->pty_flag
);
2895 if (!EQ (p
->command
, Qt
))
2897 FD_SET (fd
, &input_wait_mask
);
2898 FD_SET (fd
, &non_keyboard_wait_mask
);
2901 if (BUFFERP (buffer
))
2903 set_marker_both (p
->mark
, buffer
,
2904 BUF_ZV (XBUFFER (buffer
)),
2905 BUF_ZV_BYTE (XBUFFER (buffer
)));
2908 tem
= Fplist_member (contact
, QCcoding
);
2909 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2915 val
= XCAR (XCDR (tem
));
2919 else if (!NILP (Vcoding_system_for_read
))
2920 val
= Vcoding_system_for_read
;
2921 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2922 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2924 pset_decode_coding_system (p
, val
);
2929 val
= XCAR (XCDR (tem
));
2933 else if (!NILP (Vcoding_system_for_write
))
2934 val
= Vcoding_system_for_write
;
2935 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2936 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2938 pset_encode_coding_system (p
, val
);
2940 setup_process_coding_systems (proc
);
2941 pset_decoding_buf (p
, empty_unibyte_string
);
2942 p
->decoding_carryover
= 0;
2943 pset_encoding_buf (p
, empty_unibyte_string
);
2944 p
->inherit_coding_system_flag
2945 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2947 Fserial_process_configure (nargs
, args
);
2949 specpdl_ptr
= specpdl
+ specpdl_count
;
2955 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2956 Lisp_Object service
, Lisp_Object name
)
2959 struct Lisp_Process
*p
= XPROCESS (proc
);
2960 Lisp_Object contact
= p
->childp
;
2961 Lisp_Object coding_systems
= Qt
;
2964 tem
= Fplist_member (contact
, QCcoding
);
2965 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2966 tem
= Qnil
; /* No error message (too late!). */
2968 /* Setup coding systems for communicating with the network stream. */
2969 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2973 val
= XCAR (XCDR (tem
));
2977 else if (!NILP (Vcoding_system_for_read
))
2978 val
= Vcoding_system_for_read
;
2979 else if ((!NILP (p
->buffer
)
2980 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2981 || (NILP (p
->buffer
)
2982 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2983 /* We dare not decode end-of-line format by setting VAL to
2984 Qraw_text, because the existing Emacs Lisp libraries
2985 assume that they receive bare code including a sequence of
2990 if (NILP (host
) || NILP (service
))
2991 coding_systems
= Qnil
;
2993 coding_systems
= CALLN (Ffind_operation_coding_system
,
2994 Qopen_network_stream
, name
, p
->buffer
,
2996 if (CONSP (coding_systems
))
2997 val
= XCAR (coding_systems
);
2998 else if (CONSP (Vdefault_process_coding_system
))
2999 val
= XCAR (Vdefault_process_coding_system
);
3003 pset_decode_coding_system (p
, val
);
3007 val
= XCAR (XCDR (tem
));
3011 else if (!NILP (Vcoding_system_for_write
))
3012 val
= Vcoding_system_for_write
;
3013 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3017 if (EQ (coding_systems
, Qt
))
3019 if (NILP (host
) || NILP (service
))
3020 coding_systems
= Qnil
;
3022 coding_systems
= CALLN (Ffind_operation_coding_system
,
3023 Qopen_network_stream
, name
, p
->buffer
,
3026 if (CONSP (coding_systems
))
3027 val
= XCDR (coding_systems
);
3028 else if (CONSP (Vdefault_process_coding_system
))
3029 val
= XCDR (Vdefault_process_coding_system
);
3033 pset_encode_coding_system (p
, val
);
3035 pset_decoding_buf (p
, empty_unibyte_string
);
3036 p
->decoding_carryover
= 0;
3037 pset_encoding_buf (p
, empty_unibyte_string
);
3039 p
->inherit_coding_system_flag
3040 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3045 finish_after_tls_connection (Lisp_Object proc
)
3047 struct Lisp_Process
*p
= XPROCESS (proc
);
3048 Lisp_Object contact
= p
->childp
;
3049 Lisp_Object result
= Qt
;
3051 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3052 result
= call3 (Qnsm_verify_connection
,
3054 Fplist_get (contact
, QChost
),
3055 Fplist_get (contact
, QCservice
));
3059 pset_status (p
, list2 (Qfailed
,
3060 build_string ("The Network Security Manager stopped the connections")));
3061 deactivate_process (proc
);
3065 /* If we cleared the connection wait mask before we did
3066 the TLS setup, then we have to say that the process
3067 is finally "open" here. */
3068 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3070 pset_status (p
, Qrun
);
3071 /* Execute the sentinel here. If we had relied on
3072 status_notify to do it later, it will read input
3073 from the process before calling the sentinel. */
3074 exec_sentinel (proc
, build_string ("open\n"));
3081 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
,
3082 Lisp_Object use_external_socket_p
)
3084 ptrdiff_t count
= SPECPDL_INDEX ();
3086 int s
= -1, outch
, inch
;
3088 Lisp_Object ip_address
;
3090 struct sockaddr
*sa
= NULL
;
3093 struct Lisp_Process
*p
= XPROCESS (proc
);
3094 Lisp_Object contact
= p
->childp
;
3096 int socket_to_use
= -1;
3098 if (!NILP (use_external_socket_p
))
3100 socket_to_use
= external_sock_fd
;
3102 /* Ensure we don't consume the external socket twice. */
3103 external_sock_fd
= -1;
3106 /* Do this in case we never enter the while-loop below. */
3107 count1
= SPECPDL_INDEX ();
3110 while (!NILP (ip_addresses
))
3112 ip_address
= XCAR (ip_addresses
);
3113 ip_addresses
= XCDR (ip_addresses
);
3119 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3122 sa
= xmalloc (addrlen
);
3123 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3128 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3136 #ifdef DATAGRAM_SOCKETS
3137 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3139 #endif /* DATAGRAM_SOCKETS */
3141 if (p
->is_non_blocking_client
)
3143 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3153 /* Make us close S if quit. */
3154 record_unwind_protect_int (close_file_unwind
, s
);
3156 /* Parse network options in the arg list. We simply ignore anything
3157 which isn't a known option (including other keywords). An error
3158 is signaled if setting a known option fails. */
3160 Lisp_Object params
= contact
, key
, val
;
3162 while (!NILP (params
))
3164 key
= XCAR (params
);
3165 params
= XCDR (params
);
3166 val
= XCAR (params
);
3167 params
= XCDR (params
);
3168 optbits
|= set_socket_option (s
, key
, val
);
3174 /* Configure as a server socket. */
3176 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3177 explicit :reuseaddr key to override this. */
3178 #ifdef HAVE_LOCAL_SOCKETS
3179 if (family
!= AF_LOCAL
)
3181 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3184 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3185 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3188 /* If passed a socket descriptor, it should be already bound. */
3189 if (socket_to_use
< 0 && bind (s
, sa
, addrlen
) != 0)
3190 report_file_error ("Cannot bind server socket", Qnil
);
3192 #ifdef HAVE_GETSOCKNAME
3195 struct sockaddr_in sa1
;
3196 socklen_t len1
= sizeof (sa1
);
3197 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3199 Lisp_Object service
;
3200 service
= make_number (ntohs (sa1
.sin_port
));
3201 contact
= Fplist_put (contact
, QCservice
, service
);
3202 /* Save the port number so that we can stash it in
3203 the process object later. */
3204 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3209 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3210 report_file_error ("Cannot listen on server socket", Qnil
);
3218 ret
= connect (s
, sa
, addrlen
);
3221 if (ret
== 0 || xerrno
== EISCONN
)
3223 /* The unwind-protect will be discarded afterwards.
3224 Likewise for immediate_quit. */
3228 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3232 if (xerrno
== EINTR
)
3234 /* Unlike most other syscalls connect() cannot be called
3235 again. (That would return EALREADY.) The proper way to
3236 wait for completion is pselect(). */
3244 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3250 report_file_error ("Failed select", Qnil
);
3254 len
= sizeof xerrno
;
3255 eassert (FD_ISSET (s
, &fdset
));
3256 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3257 report_file_error ("Failed getsockopt", Qnil
);
3259 report_file_errno ("Failed connect", Qnil
, xerrno
);
3262 #endif /* !WINDOWSNT */
3266 /* Discard the unwind protect closing S. */
3267 specpdl_ptr
= specpdl
+ count1
;
3272 if (xerrno
== EINTR
)
3279 #ifdef DATAGRAM_SOCKETS
3280 if (p
->socktype
== SOCK_DGRAM
)
3282 if (datagram_address
[s
].sa
)
3285 datagram_address
[s
].sa
= xmalloc (addrlen
);
3286 datagram_address
[s
].len
= addrlen
;
3290 memset (datagram_address
[s
].sa
, 0, addrlen
);
3291 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3294 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3295 if (rlen
!= 0 && rfamily
== family
3297 conv_lisp_to_sockaddr (rfamily
, remote
,
3298 datagram_address
[s
].sa
, rlen
);
3302 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3306 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3307 conv_sockaddr_to_lisp (sa
, addrlen
));
3308 #ifdef HAVE_GETSOCKNAME
3311 struct sockaddr_in sa1
;
3312 socklen_t len1
= sizeof (sa1
);
3313 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3314 contact
= Fplist_put (contact
, QClocal
,
3315 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3324 /* If non-blocking got this far - and failed - assume non-blocking is
3325 not supported after all. This is probably a wrong assumption, but
3326 the normal blocking calls to open-network-stream handles this error
3328 if (p
->is_non_blocking_client
)
3331 report_file_errno ((p
->is_server
3332 ? "make server process failed"
3333 : "make client process failed"),
3340 chan_process
[inch
] = proc
;
3342 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3344 p
= XPROCESS (proc
);
3345 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3349 /* Discard the unwind protect for closing S, if any. */
3350 specpdl_ptr
= specpdl
+ count1
;
3352 /* Unwind bind_polling_period and request_sigio. */
3353 unbind_to (count
, Qnil
);
3355 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3356 pset_status (p
, Qlisten
);
3358 /* Make the process marker point into the process buffer (if any). */
3359 if (BUFFERP (p
->buffer
))
3360 set_marker_both (p
->mark
, p
->buffer
,
3361 BUF_ZV (XBUFFER (p
->buffer
)),
3362 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3364 if (p
->is_non_blocking_client
)
3366 /* We may get here if connect did succeed immediately. However,
3367 in that case, we still need to signal this like a non-blocking
3369 pset_status (p
, Qconnect
);
3370 if (!FD_ISSET (inch
, &connect_wait_mask
))
3372 FD_SET (inch
, &connect_wait_mask
);
3373 FD_SET (inch
, &write_mask
);
3374 num_pending_connects
++;
3378 /* A server may have a client filter setting of Qt, but it must
3379 still listen for incoming connects unless it is stopped. */
3380 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3381 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3383 FD_SET (inch
, &input_wait_mask
);
3384 FD_SET (inch
, &non_keyboard_wait_mask
);
3387 if (inch
> max_process_desc
)
3388 max_process_desc
= inch
;
3390 /* Set up the masks based on the process filter. */
3391 set_process_filter_masks (p
);
3393 setup_process_coding_systems (proc
);
3396 /* Continue the asynchronous connection. */
3397 if (!NILP (p
->gnutls_boot_parameters
))
3399 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3401 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3402 p
->gnutls_boot_parameters
= Qnil
;
3404 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3405 /* Run sentinels, etc. */
3406 finish_after_tls_connection (proc
);
3407 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3409 deactivate_process (proc
);
3411 pset_status (p
, list2 (Qfailed
,
3412 build_string ("TLS negotiation failed")));
3414 pset_status (p
, list2 (Qfailed
, boot
));
3421 /* Create a network stream/datagram client/server process. Treated
3422 exactly like a normal process when reading and writing. Primary
3423 differences are in status display and process deletion. A network
3424 connection has no PID; you cannot signal it. All you can do is
3425 stop/continue it and deactivate/close it via delete-process. */
3427 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3429 doc
: /* Create and return a network server or client process.
3431 In Emacs, network connections are represented by process objects, so
3432 input and output work as for subprocesses and `delete-process' closes
3433 a network connection. However, a network process has no process id,
3434 it cannot be signaled, and the status codes are different from normal
3437 Arguments are specified as keyword/argument pairs. The following
3438 arguments are defined:
3440 :name NAME -- NAME is name for process. It is modified if necessary
3443 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3444 with the process. Process output goes at end of that buffer, unless
3445 you specify an output stream or filter function to handle the output.
3446 BUFFER may be also nil, meaning that this process is not associated
3449 :host HOST -- HOST is name of the host to connect to, or its IP
3450 address. The symbol `local' specifies the local host. If specified
3451 for a server process, it must be a valid name or address for the local
3452 host, and only clients connecting to that address will be accepted.
3454 :service SERVICE -- SERVICE is name of the service desired, or an
3455 integer specifying a port number to connect to. If SERVICE is t,
3456 a random port number is selected for the server. A port number can
3457 be specified as an integer string, e.g., "80", as well as an integer.
3459 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3460 stream type connection, `datagram' creates a datagram type connection,
3461 `seqpacket' creates a reliable datagram connection.
3463 :family FAMILY -- FAMILY is the address (and protocol) family for the
3464 service specified by HOST and SERVICE. The default (nil) is to use
3465 whatever address family (IPv4 or IPv6) that is defined for the host
3466 and port number specified by HOST and SERVICE. Other address families
3468 local -- for a local (i.e. UNIX) address specified by SERVICE.
3469 ipv4 -- use IPv4 address family only.
3470 ipv6 -- use IPv6 address family only.
3472 :local ADDRESS -- ADDRESS is the local address used for the connection.
3473 This parameter is ignored when opening a client process. When specified
3474 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3476 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3477 connection. This parameter is ignored when opening a stream server
3478 process. For a datagram server process, it specifies the initial
3479 setting of the remote datagram address. When specified for a client
3480 process, the FAMILY, HOST, and SERVICE args are ignored.
3482 The format of ADDRESS depends on the address family:
3483 - An IPv4 address is represented as an vector of integers [A B C D P]
3484 corresponding to numeric IP address A.B.C.D and port number P.
3485 - A local address is represented as a string with the address in the
3486 local address space.
3487 - An "unsupported family" address is represented by a cons (F . AV)
3488 where F is the family number and AV is a vector containing the socket
3489 address data with one element per address data byte. Do not rely on
3490 this format in portable code, as it may depend on implementation
3491 defined constants, data sizes, and data structure alignment.
3493 :coding CODING -- If CODING is a symbol, it specifies the coding
3494 system used for both reading and writing for this process. If CODING
3495 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3496 ENCODING is used for writing.
3498 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3499 process, return without waiting for the connection to complete;
3500 instead, the sentinel function will be called with second arg matching
3501 "open" (if successful) or "failed" when the connect completes.
3502 Default is to use a blocking connect (i.e. wait) for stream type
3505 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3506 running when Emacs is exited.
3508 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3509 In the stopped state, a server process does not accept new
3510 connections, and a client process does not handle incoming traffic.
3511 The stopped state is cleared by `continue-process' and set by
3514 :filter FILTER -- Install FILTER as the process filter.
3516 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3517 process filter are multibyte, otherwise they are unibyte.
3518 If this keyword is not specified, the strings are multibyte if
3519 the default value of `enable-multibyte-characters' is non-nil.
3521 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3523 :log LOG -- Install LOG as the server process log function. This
3524 function is called when the server accepts a network connection from a
3525 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3526 is the server process, CLIENT is the new process for the connection,
3527 and MESSAGE is a string.
3529 :plist PLIST -- Install PLIST as the new process's initial plist.
3531 :tls-parameters LIST -- is a list that should be supplied if you're
3532 opening a TLS connection. The first element is the TLS type (either
3533 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3534 be a keyword list accepted by gnutls-boot (as returned by
3535 `gnutls-boot-parameters').
3537 :server QLEN -- if QLEN is non-nil, create a server process for the
3538 specified FAMILY, SERVICE, and connection type (stream or datagram).
3539 If QLEN is an integer, it is used as the max. length of the server's
3540 pending connection queue (also known as the backlog); the default
3541 queue length is 5. Default is to create a client process.
3543 The following network options can be specified for this connection:
3545 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3546 :dontroute BOOL -- Only send to directly connected hosts.
3547 :keepalive BOOL -- Send keep-alive messages on network stream.
3548 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3549 :oobinline BOOL -- Place out-of-band data in receive data stream.
3550 :priority INT -- Set protocol defined priority for sent packets.
3551 :reuseaddr BOOL -- Allow reusing a recently used local address
3552 (this is allowed by default for a server process).
3553 :bindtodevice NAME -- bind to interface NAME. Using this may require
3554 special privileges on some systems.
3555 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3556 been passed to Emacs. If Emacs wasn't
3557 passed a socket, this option is silently
3561 Consult the relevant system programmer's manual pages for more
3562 information on using these options.
3565 A server process will listen for and accept connections from clients.
3566 When a client connection is accepted, a new network process is created
3567 for the connection with the following parameters:
3569 - The client's process name is constructed by concatenating the server
3570 process's NAME and a client identification string.
3571 - If the FILTER argument is non-nil, the client process will not get a
3572 separate process buffer; otherwise, the client's process buffer is a newly
3573 created buffer named after the server process's BUFFER name or process
3574 NAME concatenated with the client identification string.
3575 - The connection type and the process filter and sentinel parameters are
3576 inherited from the server process's TYPE, FILTER and SENTINEL.
3577 - The client process's contact info is set according to the client's
3578 addressing information (typically an IP address and a port number).
3579 - The client process's plist is initialized from the server's plist.
3581 Notice that the FILTER and SENTINEL args are never used directly by
3582 the server process. Also, the BUFFER argument is not used directly by
3583 the server process, but via the optional :log function, accepted (and
3584 failed) connections may be logged in the server process's buffer.
3586 The original argument list, modified with the actual connection
3587 information, is available via the `process-contact' function.
3589 usage: (make-network-process &rest ARGS) */)
3590 (ptrdiff_t nargs
, Lisp_Object
*args
)
3593 Lisp_Object contact
;
3594 struct Lisp_Process
*p
;
3595 const char *portstring
;
3596 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3597 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3598 #ifdef HAVE_LOCAL_SOCKETS
3599 struct sockaddr_un address_un
;
3603 Lisp_Object name
, buffer
, host
, service
, address
;
3604 Lisp_Object filter
, sentinel
, use_external_socket_p
;
3605 Lisp_Object ip_addresses
= Qnil
;
3608 int ai_protocol
= 0;
3609 #ifdef HAVE_GETADDRINFO_A
3610 struct gaicb
*dns_request
= NULL
;
3612 ptrdiff_t count
= SPECPDL_INDEX ();
3617 /* Save arguments for process-contact and clone-process. */
3618 contact
= Flist (nargs
, args
);
3621 /* Ensure socket support is loaded if available. */
3622 init_winsock (TRUE
);
3625 /* :type TYPE (nil: stream, datagram */
3626 tem
= Fplist_get (contact
, QCtype
);
3628 socktype
= SOCK_STREAM
;
3629 #ifdef DATAGRAM_SOCKETS
3630 else if (EQ (tem
, Qdatagram
))
3631 socktype
= SOCK_DGRAM
;
3633 #ifdef HAVE_SEQPACKET
3634 else if (EQ (tem
, Qseqpacket
))
3635 socktype
= SOCK_SEQPACKET
;
3638 error ("Unsupported connection type");
3640 name
= Fplist_get (contact
, QCname
);
3641 buffer
= Fplist_get (contact
, QCbuffer
);
3642 filter
= Fplist_get (contact
, QCfilter
);
3643 sentinel
= Fplist_get (contact
, QCsentinel
);
3644 use_external_socket_p
= Fplist_get (contact
, QCuse_external_socket
);
3646 CHECK_STRING (name
);
3648 /* :local ADDRESS or :remote ADDRESS */
3649 tem
= Fplist_get (contact
, QCserver
);
3651 address
= Fplist_get (contact
, QCremote
);
3653 address
= Fplist_get (contact
, QClocal
);
3654 if (!NILP (address
))
3656 host
= service
= Qnil
;
3658 if (!get_lisp_to_sockaddr_size (address
, &family
))
3659 error ("Malformed :address");
3661 ip_addresses
= list1 (address
);
3665 /* :family FAMILY -- nil (for Inet), local, or integer. */
3666 tem
= Fplist_get (contact
, QCfamily
);
3675 #ifdef HAVE_LOCAL_SOCKETS
3676 else if (EQ (tem
, Qlocal
))
3680 else if (EQ (tem
, Qipv6
))
3683 else if (EQ (tem
, Qipv4
))
3685 else if (TYPE_RANGED_INTEGERP (int, tem
))
3686 family
= XINT (tem
);
3688 error ("Unknown address family");
3690 /* :service SERVICE -- string, integer (port number), or t (random port). */
3691 service
= Fplist_get (contact
, QCservice
);
3693 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3694 host
= Fplist_get (contact
, QChost
);
3697 /* The "connection" function gets it bind info from the address we're
3698 given, so use this dummy address if nothing is specified. */
3699 #ifdef HAVE_LOCAL_SOCKETS
3700 if (family
!= AF_LOCAL
)
3702 host
= build_string ("127.0.0.1");
3706 if (EQ (host
, Qlocal
))
3707 /* Depending on setup, "localhost" may map to different IPv4 and/or
3708 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3709 host
= build_string ("127.0.0.1");
3710 CHECK_STRING (host
);
3713 #ifdef HAVE_LOCAL_SOCKETS
3714 if (family
== AF_LOCAL
)
3718 message (":family local ignores the :host property");
3719 contact
= Fplist_put (contact
, QChost
, Qnil
);
3722 CHECK_STRING (service
);
3723 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3724 error ("Service name too long");
3725 ip_addresses
= list1 (service
);
3730 /* Slow down polling to every ten seconds.
3731 Some kernels have a bug which causes retrying connect to fail
3732 after a connect. Polling can interfere with gethostbyname too. */
3733 #ifdef POLL_FOR_INPUT
3734 if (socktype
!= SOCK_DGRAM
)
3736 record_unwind_protect_void (run_all_atimers
);
3737 bind_polling_period (10);
3743 /* SERVICE can either be a string or int.
3744 Convert to a C string for later use by getaddrinfo. */
3745 if (EQ (service
, Qt
))
3750 else if (INTEGERP (service
))
3752 portstring
= portbuf
;
3753 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3757 CHECK_STRING (service
);
3758 portstring
= SSDATA (service
);
3759 portstringlen
= SBYTES (service
);
3763 #ifdef HAVE_GETADDRINFO_A
3764 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3766 ptrdiff_t hostlen
= SBYTES (host
);
3770 struct addrinfo hints
;
3771 char str
[FLEXIBLE_ARRAY_MEMBER
];
3772 } *req
= xmalloc (offsetof (struct req
, str
)
3773 + hostlen
+ 1 + portstringlen
+ 1);
3774 dns_request
= &req
->gaicb
;
3775 dns_request
->ar_name
= req
->str
;
3776 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3777 dns_request
->ar_request
= &req
->hints
;
3778 dns_request
->ar_result
= NULL
;
3779 memset (&req
->hints
, 0, sizeof req
->hints
);
3780 req
->hints
.ai_family
= family
;
3781 req
->hints
.ai_socktype
= socktype
;
3782 strcpy (req
->str
, SSDATA (host
));
3783 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3785 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3787 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3791 #endif /* HAVE_GETADDRINFO_A */
3793 /* If we have a host, use getaddrinfo to resolve both host and service.
3794 Otherwise, use getservbyname to lookup the service. */
3798 struct addrinfo
*res
, *lres
;
3804 struct addrinfo hints
;
3805 memset (&hints
, 0, sizeof hints
);
3806 hints
.ai_family
= family
;
3807 hints
.ai_socktype
= socktype
;
3809 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3811 #ifdef HAVE_GAI_STRERROR
3813 synchronize_system_messages_locale ();
3814 char const *str
= gai_strerror (ret
);
3815 if (! NILP (Vlocale_coding_system
))
3816 str
= SSDATA (code_convert_string_norecord
3817 (build_string (str
), Vlocale_coding_system
, 0));
3818 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3821 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3825 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3827 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3828 (lres
->ai_addr
, lres
->ai_addrlen
),
3830 ai_protocol
= lres
->ai_protocol
;
3833 ip_addresses
= Fnreverse (ip_addresses
);
3840 /* No hostname has been specified (e.g., a local server process). */
3842 if (EQ (service
, Qt
))
3844 else if (INTEGERP (service
))
3845 port
= XINT (service
);
3848 CHECK_STRING (service
);
3851 if (SBYTES (service
) != 0)
3853 /* Allow the service to be a string containing the port number,
3854 because that's allowed if you have getaddrbyname. */
3856 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3857 if (service_end
== SSDATA (service
) + SBYTES (service
))
3861 struct servent
*svc_info
3862 = getservbyname (SSDATA (service
),
3863 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3865 port
= ntohs (svc_info
->s_port
);
3870 if (! (0 <= port
&& port
< 1 << 16))
3872 AUTO_STRING (unknown_service
, "Unknown service: %s");
3873 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3879 buffer
= Fget_buffer_create (buffer
);
3880 proc
= make_process (name
);
3881 p
= XPROCESS (proc
);
3882 pset_childp (p
, contact
);
3883 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3884 pset_type (p
, Qnetwork
);
3886 pset_buffer (p
, buffer
);
3887 pset_sentinel (p
, sentinel
);
3888 pset_filter (p
, filter
);
3889 pset_log (p
, Fplist_get (contact
, QClog
));
3890 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3891 p
->kill_without_query
= 1;
3892 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3893 pset_command (p
, Qt
);
3896 p
->is_non_blocking_client
= false;
3897 p
->is_server
= false;
3899 p
->socktype
= socktype
;
3900 p
->ai_protocol
= ai_protocol
;
3901 #ifdef HAVE_GETADDRINFO_A
3902 p
->dns_request
= NULL
;
3905 tem
= Fplist_get (contact
, QCtls_parameters
);
3907 p
->gnutls_boot_parameters
= tem
;
3910 set_network_socket_coding_system (proc
, service
, host
, name
);
3912 unbind_to (count
, Qnil
);
3915 tem
= Fplist_get (contact
, QCserver
);
3918 /* Don't support network sockets when non-blocking mode is
3919 not available, since a blocked Emacs is not useful. */
3920 p
->is_server
= true;
3921 if (TYPE_RANGED_INTEGERP (int, tem
))
3922 p
->backlog
= XINT (tem
);
3926 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3927 && !NILP (Fplist_get (contact
, QCnowait
)))
3928 p
->is_non_blocking_client
= true;
3930 #ifdef HAVE_GETADDRINFO_A
3931 /* With async address resolution, the list of addresses is empty, so
3932 postpone connecting to the server. */
3933 if (!p
->is_server
&& NILP (ip_addresses
))
3935 p
->dns_request
= dns_request
;
3936 p
->status
= Qconnect
;
3941 connect_network_socket (proc
, ip_addresses
, use_external_socket_p
);
3946 #ifdef HAVE_NET_IF_H
3950 network_interface_list (void)
3952 struct ifconf ifconf
;
3953 struct ifreq
*ifreq
;
3955 ptrdiff_t buf_size
= 512;
3960 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3963 count
= SPECPDL_INDEX ();
3964 record_unwind_protect_int (close_file_unwind
, s
);
3968 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3969 ifconf
.ifc_buf
= buf
;
3970 ifconf
.ifc_len
= buf_size
;
3971 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3978 while (ifconf
.ifc_len
== buf_size
);
3980 res
= unbind_to (count
, Qnil
);
3981 ifreq
= ifconf
.ifc_req
;
3982 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3984 struct ifreq
*ifq
= ifreq
;
3985 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3986 #define SIZEOF_IFREQ(sif) \
3987 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3988 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3990 int len
= SIZEOF_IFREQ (ifq
);
3992 int len
= sizeof (*ifreq
);
3994 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3995 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3997 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4000 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4001 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4002 res
= Fcons (Fcons (build_string (namebuf
),
4003 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4004 sizeof (struct sockaddr
))),
4011 #endif /* SIOCGIFCONF */
4013 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4017 const char *flag_sym
;
4020 static const struct ifflag_def ifflag_table
[] = {
4024 #ifdef IFF_BROADCAST
4025 { IFF_BROADCAST
, "broadcast" },
4028 { IFF_DEBUG
, "debug" },
4031 { IFF_LOOPBACK
, "loopback" },
4033 #ifdef IFF_POINTOPOINT
4034 { IFF_POINTOPOINT
, "pointopoint" },
4037 { IFF_RUNNING
, "running" },
4040 { IFF_NOARP
, "noarp" },
4043 { IFF_PROMISC
, "promisc" },
4045 #ifdef IFF_NOTRAILERS
4046 #ifdef NS_IMPL_COCOA
4047 /* Really means smart, notrailers is obsolete. */
4048 { IFF_NOTRAILERS
, "smart" },
4050 { IFF_NOTRAILERS
, "notrailers" },
4054 { IFF_ALLMULTI
, "allmulti" },
4057 { IFF_MASTER
, "master" },
4060 { IFF_SLAVE
, "slave" },
4062 #ifdef IFF_MULTICAST
4063 { IFF_MULTICAST
, "multicast" },
4066 { IFF_PORTSEL
, "portsel" },
4068 #ifdef IFF_AUTOMEDIA
4069 { IFF_AUTOMEDIA
, "automedia" },
4072 { IFF_DYNAMIC
, "dynamic" },
4075 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4078 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4081 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4084 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4087 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4093 network_interface_info (Lisp_Object ifname
)
4096 Lisp_Object res
= Qnil
;
4101 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4102 && defined HAVE_GETIFADDRS && defined LLADDR)
4103 struct ifaddrs
*ifap
;
4106 CHECK_STRING (ifname
);
4108 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4109 error ("interface name too long");
4110 lispstpcpy (rq
.ifr_name
, ifname
);
4112 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4115 count
= SPECPDL_INDEX ();
4116 record_unwind_protect_int (close_file_unwind
, s
);
4119 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4120 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4122 int flags
= rq
.ifr_flags
;
4123 const struct ifflag_def
*fp
;
4126 /* If flags is smaller than int (i.e. short) it may have the high bit set
4127 due to IFF_MULTICAST. In that case, sign extending it into
4129 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4130 flags
= (unsigned short) rq
.ifr_flags
;
4133 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4135 if (flags
& fp
->flag_bit
)
4137 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4138 flags
-= fp
->flag_bit
;
4141 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4145 elt
= Fcons (make_number (fnum
), elt
);
4150 res
= Fcons (elt
, res
);
4153 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4154 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4156 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4157 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4161 for (n
= 0; n
< 6; n
++)
4162 p
->contents
[n
] = make_number (((unsigned char *)
4163 &rq
.ifr_hwaddr
.sa_data
[0])
4165 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4167 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4168 if (getifaddrs (&ifap
) != -1)
4170 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4171 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4174 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4176 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4177 unsigned char linkaddr
[6];
4180 if (it
->ifa_addr
->sa_family
!= AF_LINK
4181 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4182 || sdl
->sdl_alen
!= 6)
4185 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4186 for (n
= 0; n
< 6; n
++)
4187 p
->contents
[n
] = make_number (linkaddr
[n
]);
4189 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4193 #ifdef HAVE_FREEIFADDRS
4197 #endif /* HAVE_GETIFADDRS && LLADDR */
4199 res
= Fcons (elt
, res
);
4202 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4203 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4206 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4207 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4209 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4213 res
= Fcons (elt
, res
);
4216 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4217 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4220 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4223 res
= Fcons (elt
, res
);
4226 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4227 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4230 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4233 res
= Fcons (elt
, res
);
4235 return unbind_to (count
, any
? res
: Qnil
);
4237 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4238 #endif /* defined (HAVE_NET_IF_H) */
4240 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4241 Snetwork_interface_list
, 0, 0, 0,
4242 doc
: /* Return an alist of all network interfaces and their network address.
4243 Each element is a cons, the car of which is a string containing the
4244 interface name, and the cdr is the network address in internal
4245 format; see the description of ADDRESS in `make-network-process'.
4247 If the information is not available, return nil. */)
4250 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4251 return network_interface_list ();
4257 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4258 Snetwork_interface_info
, 1, 1, 0,
4259 doc
: /* Return information about network interface named IFNAME.
4260 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4261 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4262 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4263 FLAGS is the current flags of the interface.
4265 Data that is unavailable is returned as nil. */)
4266 (Lisp_Object ifname
)
4268 #if ((defined HAVE_NET_IF_H \
4269 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4270 || defined SIOCGIFFLAGS)) \
4271 || defined WINDOWSNT)
4272 return network_interface_info (ifname
);
4278 /* If program file NAME starts with /: for quoting a magic
4279 name, remove that, preserving the multibyteness of NAME. */
4282 remove_slash_colon (Lisp_Object name
)
4285 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
4286 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
4287 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
4291 /* Turn off input and output for process PROC. */
4294 deactivate_process (Lisp_Object proc
)
4297 struct Lisp_Process
*p
= XPROCESS (proc
);
4301 /* Delete GnuTLS structures in PROC, if any. */
4302 emacs_gnutls_deinit (proc
);
4303 #endif /* HAVE_GNUTLS */
4305 if (p
->read_output_delay
> 0)
4307 if (--process_output_delay_count
< 0)
4308 process_output_delay_count
= 0;
4309 p
->read_output_delay
= 0;
4310 p
->read_output_skip
= 0;
4313 /* Beware SIGCHLD hereabouts. */
4315 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4316 close_process_fd (&p
->open_fd
[i
]);
4318 inchannel
= p
->infd
;
4323 #ifdef DATAGRAM_SOCKETS
4324 if (DATAGRAM_CHAN_P (inchannel
))
4326 xfree (datagram_address
[inchannel
].sa
);
4327 datagram_address
[inchannel
].sa
= 0;
4328 datagram_address
[inchannel
].len
= 0;
4331 chan_process
[inchannel
] = Qnil
;
4332 FD_CLR (inchannel
, &input_wait_mask
);
4333 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4334 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4336 FD_CLR (inchannel
, &connect_wait_mask
);
4337 FD_CLR (inchannel
, &write_mask
);
4338 if (--num_pending_connects
< 0)
4341 if (inchannel
== max_process_desc
)
4343 /* We just closed the highest-numbered process input descriptor,
4344 so recompute the highest-numbered one now. */
4348 while (0 <= i
&& NILP (chan_process
[i
]));
4350 max_process_desc
= i
;
4356 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4358 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4359 It is given to their filter functions.
4360 Optional argument PROCESS means do not return until output has been
4361 received from PROCESS.
4363 Optional second argument SECONDS and third argument MILLISEC
4364 specify a timeout; return after that much time even if there is
4365 no subprocess output. If SECONDS is a floating point number,
4366 it specifies a fractional number of seconds to wait.
4367 The MILLISEC argument is obsolete and should be avoided.
4369 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4370 from PROCESS only, suspending reading output from other processes.
4371 If JUST-THIS-ONE is an integer, don't run any timers either.
4372 Return non-nil if we received any output from PROCESS (or, if PROCESS
4373 is nil, from any process) before the timeout expired. */)
4374 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4379 if (! NILP (process
))
4380 CHECK_PROCESS (process
);
4382 just_this_one
= Qnil
;
4384 if (!NILP (millisec
))
4385 { /* Obsolete calling convention using integers rather than floats. */
4386 CHECK_NUMBER (millisec
);
4388 seconds
= make_float (XINT (millisec
) / 1000.0);
4391 CHECK_NUMBER (seconds
);
4392 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4399 if (!NILP (seconds
))
4401 if (INTEGERP (seconds
))
4403 if (XINT (seconds
) > 0)
4405 secs
= XINT (seconds
);
4409 else if (FLOATP (seconds
))
4411 if (XFLOAT_DATA (seconds
) > 0)
4413 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4414 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4419 wrong_type_argument (Qnumberp
, seconds
);
4421 else if (! NILP (process
))
4425 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4427 !NILP (process
) ? XPROCESS (process
) : NULL
,
4428 (NILP (just_this_one
) ? 0
4429 : !INTEGERP (just_this_one
) ? 1 : -1))
4434 /* Accept a connection for server process SERVER on CHANNEL. */
4436 static EMACS_INT connect_counter
= 0;
4439 server_accept_connection (Lisp_Object server
, int channel
)
4441 Lisp_Object proc
, caller
, name
, buffer
;
4442 Lisp_Object contact
, host
, service
;
4443 struct Lisp_Process
*ps
= XPROCESS (server
);
4444 struct Lisp_Process
*p
;
4448 struct sockaddr_in in
;
4450 struct sockaddr_in6 in6
;
4452 #ifdef HAVE_LOCAL_SOCKETS
4453 struct sockaddr_un un
;
4456 socklen_t len
= sizeof saddr
;
4459 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4468 if (code
== EWOULDBLOCK
)
4472 if (!NILP (ps
->log
))
4473 call3 (ps
->log
, server
, Qnil
,
4474 concat3 (build_string ("accept failed with code"),
4475 Fnumber_to_string (make_number (code
)),
4476 build_string ("\n")));
4480 count
= SPECPDL_INDEX ();
4481 record_unwind_protect_int (close_file_unwind
, s
);
4485 /* Setup a new process to handle the connection. */
4487 /* Generate a unique identification of the caller, and build contact
4488 information for this process. */
4491 switch (saddr
.sa
.sa_family
)
4495 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4497 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4498 host
= CALLN (Fformat
, ipv4_format
,
4499 make_number (ip
[0]), make_number (ip
[1]),
4500 make_number (ip
[2]), make_number (ip
[3]));
4501 service
= make_number (ntohs (saddr
.in
.sin_port
));
4502 AUTO_STRING (caller_format
, " <%s:%d>");
4503 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4510 Lisp_Object args
[9];
4511 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4514 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4515 args
[0] = ipv6_format
;
4516 for (i
= 0; i
< 8; i
++)
4517 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4518 host
= CALLMANY (Fformat
, args
);
4519 service
= make_number (ntohs (saddr
.in
.sin_port
));
4520 AUTO_STRING (caller_format
, " <[%s]:%d>");
4521 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4526 #ifdef HAVE_LOCAL_SOCKETS
4530 caller
= Fnumber_to_string (make_number (connect_counter
));
4531 AUTO_STRING (space_less_than
, " <");
4532 AUTO_STRING (greater_than
, ">");
4533 caller
= concat3 (space_less_than
, caller
, greater_than
);
4537 /* Create a new buffer name for this process if it doesn't have a
4538 filter. The new buffer name is based on the buffer name or
4539 process name of the server process concatenated with the caller
4542 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4543 || EQ (ps
->filter
, Qt
)))
4547 buffer
= ps
->buffer
;
4549 buffer
= Fbuffer_name (buffer
);
4554 buffer
= concat2 (buffer
, caller
);
4555 buffer
= Fget_buffer_create (buffer
);
4559 /* Generate a unique name for the new server process. Combine the
4560 server process name with the caller identification. */
4562 name
= concat2 (ps
->name
, caller
);
4563 proc
= make_process (name
);
4565 chan_process
[s
] = proc
;
4567 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4569 p
= XPROCESS (proc
);
4571 /* Build new contact information for this setup. */
4572 contact
= Fcopy_sequence (ps
->childp
);
4573 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4574 contact
= Fplist_put (contact
, QChost
, host
);
4575 if (!NILP (service
))
4576 contact
= Fplist_put (contact
, QCservice
, service
);
4577 contact
= Fplist_put (contact
, QCremote
,
4578 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4579 #ifdef HAVE_GETSOCKNAME
4581 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4582 contact
= Fplist_put (contact
, QClocal
,
4583 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4586 pset_childp (p
, contact
);
4587 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4588 pset_type (p
, Qnetwork
);
4590 pset_buffer (p
, buffer
);
4591 pset_sentinel (p
, ps
->sentinel
);
4592 pset_filter (p
, ps
->filter
);
4593 pset_command (p
, Qnil
);
4596 /* Discard the unwind protect for closing S. */
4597 specpdl_ptr
= specpdl
+ count
;
4599 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4602 pset_status (p
, Qrun
);
4604 /* Client processes for accepted connections are not stopped initially. */
4605 if (!EQ (p
->filter
, Qt
))
4607 FD_SET (s
, &input_wait_mask
);
4608 FD_SET (s
, &non_keyboard_wait_mask
);
4611 if (s
> max_process_desc
)
4612 max_process_desc
= s
;
4614 /* Setup coding system for new process based on server process.
4615 This seems to be the proper thing to do, as the coding system
4616 of the new process should reflect the settings at the time the
4617 server socket was opened; not the current settings. */
4619 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4620 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4621 setup_process_coding_systems (proc
);
4623 pset_decoding_buf (p
, empty_unibyte_string
);
4624 p
->decoding_carryover
= 0;
4625 pset_encoding_buf (p
, empty_unibyte_string
);
4627 p
->inherit_coding_system_flag
4628 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4630 AUTO_STRING (dash
, "-");
4631 AUTO_STRING (nl
, "\n");
4632 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4634 if (!NILP (ps
->log
))
4636 AUTO_STRING (accept_from
, "accept from ");
4637 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4640 AUTO_STRING (open_from
, "open from ");
4641 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4644 #ifdef HAVE_GETADDRINFO_A
4646 check_for_dns (Lisp_Object proc
)
4648 struct Lisp_Process
*p
= XPROCESS (proc
);
4649 Lisp_Object ip_addresses
= Qnil
;
4652 if (! p
->dns_request
)
4655 int ret
= gai_error (p
->dns_request
);
4656 if (ret
== EAI_INPROGRESS
)
4659 /* We got a response. */
4662 struct addrinfo
*res
;
4664 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4666 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4667 (res
->ai_addr
, res
->ai_addrlen
),
4671 ip_addresses
= Fnreverse (ip_addresses
);
4673 /* The DNS lookup failed. */
4674 else if (EQ (p
->status
, Qconnect
))
4676 deactivate_process (proc
);
4677 pset_status (p
, (list2
4679 concat3 (build_string ("Name lookup of "),
4680 build_string (p
->dns_request
->ar_name
),
4681 build_string (" failed")))));
4684 free_dns_request (proc
);
4686 /* This process should not already be connected (or killed). */
4687 if (!EQ (p
->status
, Qconnect
))
4690 return ip_addresses
;
4693 #endif /* HAVE_GETADDRINFO_A */
4696 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4698 while (XPROCESS (process
)->infd
< 0
4699 && EQ (XPROCESS (process
)->status
, Qconnect
))
4701 add_to_log ("Waiting for socket from %s...", build_string (name
));
4702 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4707 wait_while_connecting (Lisp_Object process
)
4709 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4711 add_to_log ("Waiting for connection...");
4712 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4717 wait_for_tls_negotiation (Lisp_Object process
)
4720 while (XPROCESS (process
)->gnutls_p
4721 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4723 add_to_log ("Waiting for TLS...");
4724 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4729 /* This variable is different from waiting_for_input in keyboard.c.
4730 It is used to communicate to a lisp process-filter/sentinel (via the
4731 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4732 for user-input when that process-filter was called.
4733 waiting_for_input cannot be used as that is by definition 0 when
4734 lisp code is being evalled.
4735 This is also used in record_asynch_buffer_change.
4736 For that purpose, this must be 0
4737 when not inside wait_reading_process_output. */
4738 static int waiting_for_user_input_p
;
4741 wait_reading_process_output_unwind (int data
)
4743 waiting_for_user_input_p
= data
;
4746 /* This is here so breakpoints can be put on it. */
4748 wait_reading_process_output_1 (void)
4752 /* Read and dispose of subprocess output while waiting for timeout to
4753 elapse and/or keyboard input to be available.
4757 If negative, gobble data immediately available but don't wait for any.
4760 an additional duration to wait, measured in nanoseconds
4761 If TIME_LIMIT is zero, then:
4762 If NSECS == 0, there is no limit.
4763 If NSECS > 0, the timeout consists of NSECS only.
4764 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4767 0 to ignore keyboard input, or
4768 1 to return when input is available, or
4769 -1 meaning caller will actually read the input, so don't throw to
4770 the quit handler, or
4772 DO_DISPLAY means redisplay should be done to show subprocess
4773 output that arrives.
4775 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4776 (and gobble terminal input into the buffer if any arrives).
4778 If WAIT_PROC is specified, wait until something arrives from that
4781 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4782 (suspending output from other processes). A negative value
4783 means don't run any timers either.
4785 Return positive if we received input from WAIT_PROC (or from any
4786 process if WAIT_PROC is null), zero if we attempted to receive
4787 input but got none, and negative if we didn't even try. */
4790 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4792 Lisp_Object wait_for_cell
,
4793 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4803 struct timespec timeout
, end_time
, timer_delay
;
4804 struct timespec got_output_end_time
= invalid_timespec ();
4805 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4806 int got_some_output
= -1;
4807 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4808 bool retry_for_async
;
4810 ptrdiff_t count
= SPECPDL_INDEX ();
4812 /* Close to the current time if known, an invalid timespec otherwise. */
4813 struct timespec now
= invalid_timespec ();
4815 FD_ZERO (&Available
);
4818 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4819 && !(CONSP (wait_proc
->status
)
4820 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4821 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4823 record_unwind_protect_int (wait_reading_process_output_unwind
,
4824 waiting_for_user_input_p
);
4825 waiting_for_user_input_p
= read_kbd
;
4827 if (TYPE_MAXIMUM (time_t) < time_limit
)
4828 time_limit
= TYPE_MAXIMUM (time_t);
4830 if (time_limit
< 0 || nsecs
< 0)
4832 else if (time_limit
> 0 || nsecs
> 0)
4835 now
= current_timespec ();
4836 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4843 bool process_skipped
= false;
4845 /* If calling from keyboard input, do not quit
4846 since we want to return C-g as an input character.
4847 Otherwise, do pending quit if requested. */
4850 else if (pending_signals
)
4851 process_pending_signals ();
4853 /* Exit now if the cell we're waiting for became non-nil. */
4854 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4857 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4859 Lisp_Object process_list_head
, aproc
;
4860 struct Lisp_Process
*p
;
4862 retry_for_async
= false;
4863 FOR_EACH_PROCESS(process_list_head
, aproc
)
4865 p
= XPROCESS (aproc
);
4867 if (! wait_proc
|| p
== wait_proc
)
4869 #ifdef HAVE_GETADDRINFO_A
4870 /* Check for pending DNS requests. */
4873 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4874 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4875 connect_network_socket (aproc
, ip_addresses
, Qnil
);
4877 retry_for_async
= true;
4881 /* Continue TLS negotiation. */
4882 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4883 && p
->is_non_blocking_client
)
4885 gnutls_try_handshake (p
);
4886 p
->gnutls_handshakes_tried
++;
4888 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4890 gnutls_verify_boot (aproc
, Qnil
);
4891 finish_after_tls_connection (aproc
);
4895 retry_for_async
= true;
4896 if (p
->gnutls_handshakes_tried
4897 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4899 deactivate_process (aproc
);
4900 pset_status (p
, list2 (Qfailed
,
4901 build_string ("TLS negotiation failed")));
4909 #endif /* GETADDRINFO_A or GNUTLS */
4911 /* Compute time from now till when time limit is up. */
4912 /* Exit if already run out. */
4913 if (wait
== TIMEOUT
)
4915 if (!timespec_valid_p (now
))
4916 now
= current_timespec ();
4917 if (timespec_cmp (end_time
, now
) <= 0)
4919 timeout
= timespec_sub (end_time
, now
);
4922 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4924 /* Normally we run timers here.
4925 But not if wait_for_cell; in those cases,
4926 the wait is supposed to be short,
4927 and those callers cannot handle running arbitrary Lisp code here. */
4928 if (NILP (wait_for_cell
)
4929 && just_wait_proc
>= 0)
4933 unsigned old_timers_run
= timers_run
;
4934 struct buffer
*old_buffer
= current_buffer
;
4935 Lisp_Object old_window
= selected_window
;
4937 timer_delay
= timer_check ();
4939 /* If a timer has run, this might have changed buffers
4940 an alike. Make read_key_sequence aware of that. */
4941 if (timers_run
!= old_timers_run
4942 && (old_buffer
!= current_buffer
4943 || !EQ (old_window
, selected_window
))
4944 && waiting_for_user_input_p
== -1)
4945 record_asynch_buffer_change ();
4947 if (timers_run
!= old_timers_run
&& do_display
)
4948 /* We must retry, since a timer may have requeued itself
4949 and that could alter the time_delay. */
4950 redisplay_preserve_echo_area (9);
4954 while (!detect_input_pending ());
4956 /* If there is unread keyboard input, also return. */
4958 && requeued_events_pending_p ())
4961 /* This is so a breakpoint can be put here. */
4962 if (!timespec_valid_p (timer_delay
))
4963 wait_reading_process_output_1 ();
4966 /* Cause C-g and alarm signals to take immediate action,
4967 and cause input available signals to zero out timeout.
4969 It is important that we do this before checking for process
4970 activity. If we get a SIGCHLD after the explicit checks for
4971 process activity, timeout is the only way we will know. */
4973 set_waiting_for_input (&timeout
);
4975 /* If status of something has changed, and no input is
4976 available, notify the user of the change right away. After
4977 this explicit check, we'll let the SIGCHLD handler zap
4978 timeout to get our attention. */
4979 if (update_tick
!= process_tick
)
4984 if (kbd_on_hold_p ())
4987 Atemp
= input_wait_mask
;
4990 timeout
= make_timespec (0, 0);
4991 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4993 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4994 NULL
, &timeout
, NULL
)
4997 /* It's okay for us to do this and then continue with
4998 the loop, since timeout has already been zeroed out. */
4999 clear_waiting_for_input ();
5000 got_some_output
= status_notify (NULL
, wait_proc
);
5001 if (do_display
) redisplay_preserve_echo_area (13);
5005 /* Don't wait for output from a non-running process. Just
5006 read whatever data has already been received. */
5007 if (wait_proc
&& wait_proc
->raw_status_new
)
5008 update_status (wait_proc
);
5010 && ! EQ (wait_proc
->status
, Qrun
)
5011 && ! EQ (wait_proc
->status
, Qconnect
))
5013 bool read_some_bytes
= false;
5015 clear_waiting_for_input ();
5017 /* If data can be read from the process, do so until exhausted. */
5018 if (wait_proc
->infd
>= 0)
5020 XSETPROCESS (proc
, wait_proc
);
5024 int nread
= read_process_output (proc
, wait_proc
->infd
);
5027 if (errno
== EIO
|| errno
== EAGAIN
)
5030 if (errno
== EWOULDBLOCK
)
5036 if (got_some_output
< nread
)
5037 got_some_output
= nread
;
5040 read_some_bytes
= true;
5045 if (read_some_bytes
&& do_display
)
5046 redisplay_preserve_echo_area (10);
5051 /* Wait till there is something to do. */
5053 if (wait_proc
&& just_wait_proc
)
5055 if (wait_proc
->infd
< 0) /* Terminated. */
5057 FD_SET (wait_proc
->infd
, &Available
);
5061 else if (!NILP (wait_for_cell
))
5063 Available
= non_process_wait_mask
;
5070 Available
= non_keyboard_wait_mask
;
5072 Available
= input_wait_mask
;
5073 Writeok
= write_mask
;
5074 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5078 /* If frame size has changed or the window is newly mapped,
5079 redisplay now, before we start to wait. There is a race
5080 condition here; if a SIGIO arrives between now and the select
5081 and indicates that a frame is trashed, the select may block
5082 displaying a trashed screen. */
5083 if (frame_garbaged
&& do_display
)
5085 clear_waiting_for_input ();
5086 redisplay_preserve_echo_area (11);
5088 set_waiting_for_input (&timeout
);
5091 /* Skip the `select' call if input is available and we're
5092 waiting for keyboard input or a cell change (which can be
5093 triggered by processing X events). In the latter case, set
5094 nfds to 1 to avoid breaking the loop. */
5096 if ((read_kbd
|| !NILP (wait_for_cell
))
5097 && detect_input_pending ())
5099 nfds
= read_kbd
? 0 : 1;
5101 FD_ZERO (&Available
);
5105 /* Set the timeout for adaptive read buffering if any
5106 process has non-zero read_output_skip and non-zero
5107 read_output_delay, and we are not reading output for a
5108 specific process. It is not executed if
5109 Vprocess_adaptive_read_buffering is nil. */
5110 if (process_output_skip
&& check_delay
> 0)
5112 int adaptive_nsecs
= timeout
.tv_nsec
;
5113 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5114 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5115 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5117 proc
= chan_process
[channel
];
5120 /* Find minimum non-zero read_output_delay among the
5121 processes with non-zero read_output_skip. */
5122 if (XPROCESS (proc
)->read_output_delay
> 0)
5125 if (!XPROCESS (proc
)->read_output_skip
)
5127 FD_CLR (channel
, &Available
);
5128 process_skipped
= true;
5129 XPROCESS (proc
)->read_output_skip
= 0;
5130 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5131 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5134 timeout
= make_timespec (0, adaptive_nsecs
);
5135 process_output_skip
= 0;
5138 /* If we've got some output and haven't limited our timeout
5139 with adaptive read buffering, limit it. */
5140 if (got_some_output
> 0 && !process_skipped
5142 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5143 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5146 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5147 && timespec_valid_p (timer_delay
)
5148 && timespec_cmp (timer_delay
, timeout
) < 0)
5150 if (!timespec_valid_p (now
))
5151 now
= current_timespec ();
5152 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5153 if (!timespec_valid_p (got_output_end_time
)
5154 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5155 got_output_end_time
= timeout_abs
;
5156 timeout
= timer_delay
;
5159 got_output_end_time
= invalid_timespec ();
5161 /* NOW can become inaccurate if time can pass during pselect. */
5162 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5163 now
= invalid_timespec ();
5165 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5167 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5170 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5174 #if defined (HAVE_NS)
5176 #elif defined (HAVE_GLIB)
5181 (max (max_process_desc
, max_input_desc
) + 1,
5183 (check_write
? &Writeok
: 0),
5184 NULL
, &timeout
, NULL
);
5187 /* GnuTLS buffers data internally. In lowat mode it leaves
5188 some data in the TCP buffers so that select works, but
5189 with custom pull/push functions we need to check if some
5190 data is available in the buffers manually. */
5193 fd_set tls_available
;
5196 FD_ZERO (&tls_available
);
5199 /* We're not waiting on a specific process, so loop
5200 through all the channels and check for data.
5201 This is a workaround needed for some versions of
5202 the gnutls library -- 2.12.14 has been confirmed
5204 http://comments.gmane.org/gmane.emacs.devel/145074 */
5205 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5206 if (! NILP (chan_process
[channel
]))
5208 struct Lisp_Process
*p
=
5209 XPROCESS (chan_process
[channel
]);
5210 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5211 && ((emacs_gnutls_record_check_pending
5216 eassert (p
->infd
== channel
);
5217 FD_SET (p
->infd
, &tls_available
);
5224 /* Check this specific channel. */
5225 if (wait_proc
->gnutls_p
/* Check for valid process. */
5226 && wait_proc
->gnutls_state
5227 /* Do we have pending data? */
5228 && ((emacs_gnutls_record_check_pending
5229 (wait_proc
->gnutls_state
))
5233 eassert (0 <= wait_proc
->infd
);
5234 /* Set to Available. */
5235 FD_SET (wait_proc
->infd
, &tls_available
);
5240 Available
= tls_available
;
5247 /* Make C-g and alarm signals set flags again. */
5248 clear_waiting_for_input ();
5250 /* If we woke up due to SIGWINCH, actually change size now. */
5251 do_pending_window_change (0);
5255 /* Exit the main loop if we've passed the requested timeout,
5256 or aren't skipping processes and got some output and
5257 haven't lowered our timeout due to timers or SIGIO and
5258 have waited a long amount of time due to repeated
5262 struct timespec cmp_time
5265 : (!process_skipped
&& got_some_output
> 0
5266 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5267 ? got_output_end_time
5268 : invalid_timespec ());
5269 if (timespec_valid_p (cmp_time
))
5271 now
= current_timespec ();
5272 if (timespec_cmp (cmp_time
, now
) <= 0)
5279 if (xerrno
== EINTR
)
5281 else if (xerrno
== EBADF
)
5284 report_file_errno ("Failed select", Qnil
, xerrno
);
5287 /* Check for keyboard input. */
5288 /* If there is any, return immediately
5289 to give it higher priority than subprocesses. */
5293 unsigned old_timers_run
= timers_run
;
5294 struct buffer
*old_buffer
= current_buffer
;
5295 Lisp_Object old_window
= selected_window
;
5298 if (detect_input_pending_run_timers (do_display
))
5300 swallow_events (do_display
);
5301 if (detect_input_pending_run_timers (do_display
))
5305 /* If a timer has run, this might have changed buffers
5306 an alike. Make read_key_sequence aware of that. */
5307 if (timers_run
!= old_timers_run
5308 && waiting_for_user_input_p
== -1
5309 && (old_buffer
!= current_buffer
5310 || !EQ (old_window
, selected_window
)))
5311 record_asynch_buffer_change ();
5317 /* If there is unread keyboard input, also return. */
5319 && requeued_events_pending_p ())
5322 /* If we are not checking for keyboard input now,
5323 do process events (but don't run any timers).
5324 This is so that X events will be processed.
5325 Otherwise they may have to wait until polling takes place.
5326 That would causes delays in pasting selections, for example.
5328 (We used to do this only if wait_for_cell.) */
5329 if (read_kbd
== 0 && detect_input_pending ())
5331 swallow_events (do_display
);
5332 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5333 if (detect_input_pending ())
5338 /* Exit now if the cell we're waiting for became non-nil. */
5339 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5343 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5344 go read it. This can happen with X on BSD after logging out.
5345 In that case, there really is no input and no SIGIO,
5346 but select says there is input. */
5348 if (read_kbd
&& interrupt_input
5349 && keyboard_bit_set (&Available
) && ! noninteractive
)
5350 handle_input_available_signal (SIGIO
);
5353 /* If checking input just got us a size-change event from X,
5354 obey it now if we should. */
5355 if (read_kbd
|| ! NILP (wait_for_cell
))
5356 do_pending_window_change (0);
5358 /* Check for data from a process. */
5359 if (no_avail
|| nfds
== 0)
5362 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5364 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5366 && ((d
->condition
& FOR_READ
5367 && FD_ISSET (channel
, &Available
))
5368 || (d
->condition
& FOR_WRITE
5369 && FD_ISSET (channel
, &write_mask
))))
5370 d
->func (channel
, d
->data
);
5373 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5375 if (FD_ISSET (channel
, &Available
)
5376 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5377 && !FD_ISSET (channel
, &non_process_wait_mask
))
5381 /* If waiting for this channel, arrange to return as
5382 soon as no more input to be processed. No more
5384 proc
= chan_process
[channel
];
5388 /* If this is a server stream socket, accept connection. */
5389 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5391 server_accept_connection (proc
, channel
);
5395 /* Read data from the process, starting with our
5396 buffered-ahead character if we have one. */
5398 nread
= read_process_output (proc
, channel
);
5399 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5400 && got_some_output
< nread
)
5401 got_some_output
= nread
;
5404 /* Vacuum up any leftovers without waiting. */
5405 if (wait_proc
== XPROCESS (proc
))
5407 /* Since read_process_output can run a filter,
5408 which can call accept-process-output,
5409 don't try to read from any other processes
5410 before doing the select again. */
5411 FD_ZERO (&Available
);
5414 redisplay_preserve_echo_area (12);
5417 else if (nread
== -1 && errno
== EWOULDBLOCK
)
5420 else if (nread
== -1 && errno
== EAGAIN
)
5423 /* FIXME: Is this special case still needed? */
5424 /* Note that we cannot distinguish between no input
5425 available now and a closed pipe.
5426 With luck, a closed pipe will be accompanied by
5427 subprocess termination and SIGCHLD. */
5428 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5429 && !PIPECONN_P (proc
))
5433 /* On some OSs with ptys, when the process on one end of
5434 a pty exits, the other end gets an error reading with
5435 errno = EIO instead of getting an EOF (0 bytes read).
5436 Therefore, if we get an error reading and errno =
5437 EIO, just continue, because the child process has
5438 exited and should clean itself up soon (e.g. when we
5440 else if (nread
== -1 && errno
== EIO
)
5442 struct Lisp_Process
*p
= XPROCESS (proc
);
5444 /* Clear the descriptor now, so we only raise the
5446 FD_CLR (channel
, &input_wait_mask
);
5447 FD_CLR (channel
, &non_keyboard_wait_mask
);
5451 /* If the EIO occurs on a pty, the SIGCHLD handler's
5452 waitpid call will not find the process object to
5453 delete. Do it here. */
5454 p
->tick
= ++process_tick
;
5455 pset_status (p
, Qfailed
);
5458 #endif /* HAVE_PTYS */
5459 /* If we can detect process termination, don't consider the
5460 process gone just because its pipe is closed. */
5461 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5462 && !PIPECONN_P (proc
))
5464 else if (nread
== 0 && PIPECONN_P (proc
))
5466 /* Preserve status of processes already terminated. */
5467 XPROCESS (proc
)->tick
= ++process_tick
;
5468 deactivate_process (proc
);
5469 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5470 pset_status (XPROCESS (proc
),
5471 list2 (Qexit
, make_number (0)));
5475 /* Preserve status of processes already terminated. */
5476 XPROCESS (proc
)->tick
= ++process_tick
;
5477 deactivate_process (proc
);
5478 if (XPROCESS (proc
)->raw_status_new
)
5479 update_status (XPROCESS (proc
));
5480 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5481 pset_status (XPROCESS (proc
),
5482 list2 (Qexit
, make_number (256)));
5485 if (FD_ISSET (channel
, &Writeok
)
5486 && FD_ISSET (channel
, &connect_wait_mask
))
5488 struct Lisp_Process
*p
;
5490 FD_CLR (channel
, &connect_wait_mask
);
5491 FD_CLR (channel
, &write_mask
);
5492 if (--num_pending_connects
< 0)
5495 proc
= chan_process
[channel
];
5499 p
= XPROCESS (proc
);
5502 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5503 So only use it on systems where it is known to work. */
5505 socklen_t xlen
= sizeof (xerrno
);
5506 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5511 struct sockaddr pname
;
5512 socklen_t pnamelen
= sizeof (pname
);
5514 /* If connection failed, getpeername will fail. */
5516 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5518 /* Obtain connect failure code through error slippage. */
5521 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5528 p
->tick
= ++process_tick
;
5529 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5530 deactivate_process (proc
);
5535 /* If we have an incompletely set up TLS connection,
5536 then defer the sentinel signaling until
5538 if (NILP (p
->gnutls_boot_parameters
)
5542 pset_status (p
, Qrun
);
5543 /* Execute the sentinel here. If we had relied on
5544 status_notify to do it later, it will read input
5545 from the process before calling the sentinel. */
5546 exec_sentinel (proc
, build_string ("open\n"));
5549 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5550 && !EQ (p
->command
, Qt
))
5552 FD_SET (p
->infd
, &input_wait_mask
);
5553 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5557 } /* End for each file descriptor. */
5558 } /* End while exit conditions not met. */
5560 unbind_to (count
, Qnil
);
5562 /* If calling from keyboard input, do not quit
5563 since we want to return C-g as an input character.
5564 Otherwise, do pending quit if requested. */
5567 /* Prevent input_pending from remaining set if we quit. */
5568 clear_input_pending ();
5572 return got_some_output
;
5575 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5578 read_process_output_call (Lisp_Object fun_and_args
)
5580 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5584 read_process_output_error_handler (Lisp_Object error_val
)
5586 cmd_error_internal (error_val
, "error in process filter: ");
5588 update_echo_area ();
5589 Fsleep_for (make_number (2), Qnil
);
5594 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5596 struct coding_system
*coding
);
5598 /* Read pending output from the process channel,
5599 starting with our buffered-ahead character if we have one.
5600 Yield number of decoded characters read.
5602 This function reads at most 4096 characters.
5603 If you want to read all available subprocess output,
5604 you must call it repeatedly until it returns zero.
5606 The characters read are decoded according to PROC's coding-system
5610 read_process_output (Lisp_Object proc
, int channel
)
5613 struct Lisp_Process
*p
= XPROCESS (proc
);
5614 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5615 int carryover
= p
->decoding_carryover
;
5616 enum { readmax
= 4096 };
5617 ptrdiff_t count
= SPECPDL_INDEX ();
5618 Lisp_Object odeactivate
;
5619 char chars
[sizeof coding
->carryover
+ readmax
];
5622 /* See the comment above. */
5623 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5625 #ifdef DATAGRAM_SOCKETS
5626 /* We have a working select, so proc_buffered_char is always -1. */
5627 if (DATAGRAM_CHAN_P (channel
))
5629 socklen_t len
= datagram_address
[channel
].len
;
5630 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5631 0, datagram_address
[channel
].sa
, &len
);
5636 bool buffered
= proc_buffered_char
[channel
] >= 0;
5639 chars
[carryover
] = proc_buffered_char
[channel
];
5640 proc_buffered_char
[channel
] = -1;
5643 if (p
->gnutls_p
&& p
->gnutls_state
)
5644 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5645 readmax
- buffered
);
5648 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5649 readmax
- buffered
);
5650 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5652 int delay
= p
->read_output_delay
;
5655 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5658 process_output_delay_count
++;
5659 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5662 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5664 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5666 process_output_delay_count
--;
5668 p
->read_output_delay
= delay
;
5671 p
->read_output_skip
= 1;
5672 process_output_skip
= 1;
5676 nbytes
+= buffered
&& nbytes
<= 0;
5679 p
->decoding_carryover
= 0;
5681 /* At this point, NBYTES holds number of bytes just received
5682 (including the one in proc_buffered_char[channel]). */
5685 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5687 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5690 /* Now set NBYTES how many bytes we must decode. */
5691 nbytes
+= carryover
;
5693 odeactivate
= Vdeactivate_mark
;
5694 /* There's no good reason to let process filters change the current
5695 buffer, and many callers of accept-process-output, sit-for, and
5696 friends don't expect current-buffer to be changed from under them. */
5697 record_unwind_current_buffer ();
5699 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5701 /* Handling the process output should not deactivate the mark. */
5702 Vdeactivate_mark
= odeactivate
;
5704 unbind_to (count
, Qnil
);
5709 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5711 struct coding_system
*coding
)
5713 Lisp_Object outstream
= p
->filter
;
5715 bool outer_running_asynch_code
= running_asynch_code
;
5716 int waiting
= waiting_for_user_input_p
;
5719 Lisp_Object obuffer
, okeymap
;
5720 XSETBUFFER (obuffer
, current_buffer
);
5721 okeymap
= BVAR (current_buffer
, keymap
);
5724 /* We inhibit quit here instead of just catching it so that
5725 hitting ^G when a filter happens to be running won't screw
5727 specbind (Qinhibit_quit
, Qt
);
5728 specbind (Qlast_nonmenu_event
, Qt
);
5730 /* In case we get recursively called,
5731 and we already saved the match data nonrecursively,
5732 save the same match data in safely recursive fashion. */
5733 if (outer_running_asynch_code
)
5736 /* Don't clobber the CURRENT match data, either! */
5737 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5738 restore_search_regs ();
5739 record_unwind_save_match_data ();
5740 Fset_match_data (tem
, Qt
);
5743 /* For speed, if a search happens within this code,
5744 save the match data in a special nonrecursive fashion. */
5745 running_asynch_code
= 1;
5747 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5748 text
= coding
->dst_object
;
5749 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5750 /* A new coding system might be found. */
5751 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5753 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5755 /* Don't call setup_coding_system for
5756 proc_decode_coding_system[channel] here. It is done in
5757 detect_coding called via decode_coding above. */
5759 /* If a coding system for encoding is not yet decided, we set
5760 it as the same as coding-system for decoding.
5762 But, before doing that we must check if
5763 proc_encode_coding_system[p->outfd] surely points to a
5764 valid memory because p->outfd will be changed once EOF is
5765 sent to the process. */
5766 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5767 && proc_encode_coding_system
[p
->outfd
])
5769 pset_encode_coding_system
5770 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5771 setup_coding_system (p
->encode_coding_system
,
5772 proc_encode_coding_system
[p
->outfd
]);
5776 if (coding
->carryover_bytes
> 0)
5778 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5779 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5780 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5781 coding
->carryover_bytes
);
5782 p
->decoding_carryover
= coding
->carryover_bytes
;
5784 if (SBYTES (text
) > 0)
5785 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5786 sometimes it's simply wrong to wrap (e.g. when called from
5787 accept-process-output). */
5788 internal_condition_case_1 (read_process_output_call
,
5789 list3 (outstream
, make_lisp_proc (p
), text
),
5790 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5791 read_process_output_error_handler
);
5793 /* If we saved the match data nonrecursively, restore it now. */
5794 restore_search_regs ();
5795 running_asynch_code
= outer_running_asynch_code
;
5797 /* Restore waiting_for_user_input_p as it was
5798 when we were called, in case the filter clobbered it. */
5799 waiting_for_user_input_p
= waiting
;
5801 #if 0 /* Call record_asynch_buffer_change unconditionally,
5802 because we might have changed minor modes or other things
5803 that affect key bindings. */
5804 if (! EQ (Fcurrent_buffer (), obuffer
)
5805 || ! EQ (current_buffer
->keymap
, okeymap
))
5807 /* But do it only if the caller is actually going to read events.
5808 Otherwise there's no need to make him wake up, and it could
5809 cause trouble (for example it would make sit_for return). */
5810 if (waiting_for_user_input_p
== -1)
5811 record_asynch_buffer_change ();
5814 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5815 Sinternal_default_process_filter
, 2, 2, 0,
5816 doc
: /* Function used as default process filter.
5817 This inserts the process's output into its buffer, if there is one.
5818 Otherwise it discards the output. */)
5819 (Lisp_Object proc
, Lisp_Object text
)
5821 struct Lisp_Process
*p
;
5824 CHECK_PROCESS (proc
);
5825 p
= XPROCESS (proc
);
5826 CHECK_STRING (text
);
5828 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5830 Lisp_Object old_read_only
;
5831 ptrdiff_t old_begv
, old_zv
;
5832 ptrdiff_t old_begv_byte
, old_zv_byte
;
5833 ptrdiff_t before
, before_byte
;
5834 ptrdiff_t opoint_byte
;
5837 Fset_buffer (p
->buffer
);
5839 opoint_byte
= PT_BYTE
;
5840 old_read_only
= BVAR (current_buffer
, read_only
);
5843 old_begv_byte
= BEGV_BYTE
;
5844 old_zv_byte
= ZV_BYTE
;
5846 bset_read_only (current_buffer
, Qnil
);
5848 /* Insert new output into buffer at the current end-of-output
5849 marker, thus preserving logical ordering of input and output. */
5850 if (XMARKER (p
->mark
)->buffer
)
5851 set_point_from_marker (p
->mark
);
5853 SET_PT_BOTH (ZV
, ZV_BYTE
);
5855 before_byte
= PT_BYTE
;
5857 /* If the output marker is outside of the visible region, save
5858 the restriction and widen. */
5859 if (! (BEGV
<= PT
&& PT
<= ZV
))
5862 /* Adjust the multibyteness of TEXT to that of the buffer. */
5863 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5864 != ! STRING_MULTIBYTE (text
))
5865 text
= (STRING_MULTIBYTE (text
)
5866 ? Fstring_as_unibyte (text
)
5867 : Fstring_to_multibyte (text
));
5868 /* Insert before markers in case we are inserting where
5869 the buffer's mark is, and the user's next command is Meta-y. */
5870 insert_from_string_before_markers (text
, 0, 0,
5871 SCHARS (text
), SBYTES (text
), 0);
5873 /* Make sure the process marker's position is valid when the
5874 process buffer is changed in the signal_after_change above.
5875 W3 is known to do that. */
5876 if (BUFFERP (p
->buffer
)
5877 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5878 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5880 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5882 update_mode_lines
= 23;
5884 /* Make sure opoint and the old restrictions
5885 float ahead of any new text just as point would. */
5886 if (opoint
>= before
)
5888 opoint
+= PT
- before
;
5889 opoint_byte
+= PT_BYTE
- before_byte
;
5891 if (old_begv
> before
)
5893 old_begv
+= PT
- before
;
5894 old_begv_byte
+= PT_BYTE
- before_byte
;
5896 if (old_zv
>= before
)
5898 old_zv
+= PT
- before
;
5899 old_zv_byte
+= PT_BYTE
- before_byte
;
5902 /* If the restriction isn't what it should be, set it. */
5903 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5904 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5906 bset_read_only (current_buffer
, old_read_only
);
5907 SET_PT_BOTH (opoint
, opoint_byte
);
5912 /* Sending data to subprocess. */
5914 /* In send_process, when a write fails temporarily,
5915 wait_reading_process_output is called. It may execute user code,
5916 e.g. timers, that attempts to write new data to the same process.
5917 We must ensure that data is sent in the right order, and not
5918 interspersed half-completed with other writes (Bug#10815). This is
5919 handled by the write_queue element of struct process. It is a list
5920 with each entry having the form
5922 (string . (offset . length))
5924 where STRING is a lisp string, OFFSET is the offset into the
5925 string's byte sequence from which we should begin to send, and
5926 LENGTH is the number of bytes left to send. */
5928 /* Create a new entry in write_queue.
5929 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5930 BUF is a pointer to the string sequence of the input_obj or a C
5931 string in case of Qt or Qnil. */
5934 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5935 const char *buf
, ptrdiff_t len
, bool front
)
5938 Lisp_Object entry
, obj
;
5940 if (STRINGP (input_obj
))
5942 offset
= buf
- SSDATA (input_obj
);
5948 obj
= make_unibyte_string (buf
, len
);
5951 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5954 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5956 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5959 /* Remove the first element in the write_queue of process P, put its
5960 contents in OBJ, BUF and LEN, and return true. If the
5961 write_queue is empty, return false. */
5964 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5965 const char **buf
, ptrdiff_t *len
)
5967 Lisp_Object entry
, offset_length
;
5970 if (NILP (p
->write_queue
))
5973 entry
= XCAR (p
->write_queue
);
5974 pset_write_queue (p
, XCDR (p
->write_queue
));
5976 *obj
= XCAR (entry
);
5977 offset_length
= XCDR (entry
);
5979 *len
= XINT (XCDR (offset_length
));
5980 offset
= XINT (XCAR (offset_length
));
5981 *buf
= SSDATA (*obj
) + offset
;
5986 /* Send some data to process PROC.
5987 BUF is the beginning of the data; LEN is the number of characters.
5988 OBJECT is the Lisp object that the data comes from. If OBJECT is
5989 nil or t, it means that the data comes from C string.
5991 If OBJECT is not nil, the data is encoded by PROC's coding-system
5992 for encoding before it is sent.
5994 This function can evaluate Lisp code and can garbage collect. */
5997 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6000 struct Lisp_Process
*p
= XPROCESS (proc
);
6002 struct coding_system
*coding
;
6004 if (NETCONN_P (proc
))
6006 wait_while_connecting (proc
);
6007 wait_for_tls_negotiation (proc
);
6010 if (p
->raw_status_new
)
6012 if (! EQ (p
->status
, Qrun
))
6013 error ("Process %s not running", SDATA (p
->name
));
6015 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6017 coding
= proc_encode_coding_system
[p
->outfd
];
6018 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6020 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6021 || (BUFFERP (object
)
6022 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6025 pset_encode_coding_system
6026 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6027 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6029 /* The coding system for encoding was changed to raw-text
6030 because we sent a unibyte text previously. Now we are
6031 sending a multibyte text, thus we must encode it by the
6032 original coding system specified for the current process.
6034 Another reason we come here is that the coding system
6035 was just complemented and a new one was returned by
6036 complement_process_encoding_system. */
6037 setup_coding_system (p
->encode_coding_system
, coding
);
6038 Vlast_coding_system_used
= p
->encode_coding_system
;
6040 coding
->src_multibyte
= 1;
6044 coding
->src_multibyte
= 0;
6045 /* For sending a unibyte text, character code conversion should
6046 not take place but EOL conversion should. So, setup raw-text
6047 or one of the subsidiary if we have not yet done it. */
6048 if (CODING_REQUIRE_ENCODING (coding
))
6050 if (CODING_REQUIRE_FLUSHING (coding
))
6052 /* But, before changing the coding, we must flush out data. */
6053 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6054 send_process (proc
, "", 0, Qt
);
6055 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6057 setup_coding_system (raw_text_coding_system
6058 (Vlast_coding_system_used
),
6060 coding
->src_multibyte
= 0;
6063 coding
->dst_multibyte
= 0;
6065 if (CODING_REQUIRE_ENCODING (coding
))
6067 coding
->dst_object
= Qt
;
6068 if (BUFFERP (object
))
6070 ptrdiff_t from_byte
, from
, to
;
6071 ptrdiff_t save_pt
, save_pt_byte
;
6072 struct buffer
*cur
= current_buffer
;
6074 set_buffer_internal (XBUFFER (object
));
6075 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6077 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6078 from
= BYTE_TO_CHAR (from_byte
);
6079 to
= BYTE_TO_CHAR (from_byte
+ len
);
6080 TEMP_SET_PT_BOTH (from
, from_byte
);
6081 encode_coding_object (coding
, object
, from
, from_byte
,
6082 to
, from_byte
+ len
, Qt
);
6083 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6084 set_buffer_internal (cur
);
6086 else if (STRINGP (object
))
6088 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6089 SBYTES (object
), Qt
);
6093 coding
->dst_object
= make_unibyte_string (buf
, len
);
6094 coding
->produced
= len
;
6097 len
= coding
->produced
;
6098 object
= coding
->dst_object
;
6099 buf
= SSDATA (object
);
6102 /* If there is already data in the write_queue, put the new data
6103 in the back of queue. Otherwise, ignore it. */
6104 if (!NILP (p
->write_queue
))
6105 write_queue_push (p
, object
, buf
, len
, 0);
6107 do /* while !NILP (p->write_queue) */
6109 ptrdiff_t cur_len
= -1;
6110 const char *cur_buf
;
6111 Lisp_Object cur_object
;
6113 /* If write_queue is empty, ignore it. */
6114 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6118 cur_object
= object
;
6123 /* Send this batch, using one or more write calls. */
6124 ptrdiff_t written
= 0;
6125 int outfd
= p
->outfd
;
6126 #ifdef DATAGRAM_SOCKETS
6127 if (DATAGRAM_CHAN_P (outfd
))
6129 rv
= sendto (outfd
, cur_buf
, cur_len
,
6130 0, datagram_address
[outfd
].sa
,
6131 datagram_address
[outfd
].len
);
6134 else if (errno
== EMSGSIZE
)
6135 report_file_error ("Sending datagram", proc
);
6141 if (p
->gnutls_p
&& p
->gnutls_state
)
6142 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6145 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6146 rv
= (written
? 0 : -1);
6147 if (p
->read_output_delay
> 0
6148 && p
->adaptive_read_buffering
== 1)
6150 p
->read_output_delay
= 0;
6151 process_output_delay_count
--;
6152 p
->read_output_skip
= 0;
6160 || errno
== EWOULDBLOCK
6163 /* Buffer is full. Wait, accepting input;
6164 that may allow the program
6165 to finish doing output and read more. */
6167 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6168 /* A gross hack to work around a bug in FreeBSD.
6169 In the following sequence, read(2) returns
6173 write(2) 954 bytes, get EAGAIN
6174 read(2) 1024 bytes in process_read_output
6175 read(2) 11 bytes in process_read_output
6177 That is, read(2) returns more bytes than have
6178 ever been written successfully. The 1033 bytes
6179 read are the 1022 bytes written successfully
6180 after processing (for example with CRs added if
6181 the terminal is set up that way which it is
6182 here). The same bytes will be seen again in a
6183 later read(2), without the CRs. */
6185 if (errno
== EAGAIN
)
6188 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6190 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6192 /* Put what we should have written in wait_queue. */
6193 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6194 wait_reading_process_output (0, 20 * 1000 * 1000,
6195 0, 0, Qnil
, NULL
, 0);
6196 /* Reread queue, to see what is left. */
6199 else if (errno
== EPIPE
)
6201 p
->raw_status_new
= 0;
6202 pset_status (p
, list2 (Qexit
, make_number (256)));
6203 p
->tick
= ++process_tick
;
6204 deactivate_process (proc
);
6205 error ("process %s no longer connected to pipe; closed it",
6209 /* This is a real error. */
6210 report_file_error ("Writing to process", proc
);
6216 while (!NILP (p
->write_queue
));
6219 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6221 doc
: /* Send current contents of region as input to PROCESS.
6222 PROCESS may be a process, a buffer, the name of a process or buffer, or
6223 nil, indicating the current buffer's process.
6224 Called from program, takes three arguments, PROCESS, START and END.
6225 If the region is more than 500 characters long,
6226 it is sent in several bunches. This may happen even for shorter regions.
6227 Output from processes can arrive in between bunches.
6229 If PROCESS is a non-blocking network process that hasn't been fully
6230 set up yet, this function will block until socket setup has completed. */)
6231 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6233 Lisp_Object proc
= get_process (process
);
6234 ptrdiff_t start_byte
, end_byte
;
6236 validate_region (&start
, &end
);
6238 start_byte
= CHAR_TO_BYTE (XINT (start
));
6239 end_byte
= CHAR_TO_BYTE (XINT (end
));
6241 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6242 move_gap_both (XINT (start
), start_byte
);
6244 if (NETCONN_P (proc
))
6245 wait_while_connecting (proc
);
6247 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6248 end_byte
- start_byte
, Fcurrent_buffer ());
6253 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6255 doc
: /* Send PROCESS the contents of STRING as input.
6256 PROCESS may be a process, a buffer, the name of a process or buffer, or
6257 nil, indicating the current buffer's process.
6258 If STRING is more than 500 characters long,
6259 it is sent in several bunches. This may happen even for shorter strings.
6260 Output from processes can arrive in between bunches.
6262 If PROCESS is a non-blocking network process that hasn't been fully
6263 set up yet, this function will block until socket setup has completed. */)
6264 (Lisp_Object process
, Lisp_Object string
)
6266 CHECK_STRING (string
);
6267 Lisp_Object proc
= get_process (process
);
6268 send_process (proc
, SSDATA (string
),
6269 SBYTES (string
), string
);
6273 /* Return the foreground process group for the tty/pty that
6274 the process P uses. */
6276 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6281 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6284 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6285 master side. Try the slave side. */
6286 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6290 ioctl (fd
, TIOCGPGRP
, &gid
);
6294 #endif /* defined (TIOCGPGRP ) */
6299 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6300 Sprocess_running_child_p
, 0, 1, 0,
6301 doc
: /* Return non-nil if PROCESS has given the terminal to a
6302 child. If the operating system does not make it possible to find out,
6303 return t. If we can find out, return the numeric ID of the foreground
6305 (Lisp_Object process
)
6307 /* Initialize in case ioctl doesn't exist or gives an error,
6308 in a way that will cause returning t. */
6309 Lisp_Object proc
= get_process (process
);
6310 struct Lisp_Process
*p
= XPROCESS (proc
);
6312 if (!EQ (p
->type
, Qreal
))
6313 error ("Process %s is not a subprocess",
6316 error ("Process %s is not active",
6319 pid_t gid
= emacs_get_tty_pgrp (p
);
6324 return make_number (gid
);
6328 /* Send a signal number SIGNO to PROCESS.
6329 If CURRENT_GROUP is t, that means send to the process group
6330 that currently owns the terminal being used to communicate with PROCESS.
6331 This is used for various commands in shell mode.
6332 If CURRENT_GROUP is lambda, that means send to the process group
6333 that currently owns the terminal, but only if it is NOT the shell itself.
6335 If NOMSG is false, insert signal-announcements into process's buffers
6338 If we can, we try to signal PROCESS by sending control characters
6339 down the pty. This allows us to signal inferiors who have changed
6340 their uid, for which kill would return an EPERM error. */
6343 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6347 struct Lisp_Process
*p
;
6351 proc
= get_process (process
);
6352 p
= XPROCESS (proc
);
6354 if (!EQ (p
->type
, Qreal
))
6355 error ("Process %s is not a subprocess",
6358 error ("Process %s is not active",
6362 current_group
= Qnil
;
6364 /* If we are using pgrps, get a pgrp number and make it negative. */
6365 if (NILP (current_group
))
6366 /* Send the signal to the shell's process group. */
6370 #ifdef SIGNALS_VIA_CHARACTERS
6371 /* If possible, send signals to the entire pgrp
6372 by sending an input character to it. */
6375 cc_t
*sig_char
= NULL
;
6377 tcgetattr (p
->infd
, &t
);
6382 sig_char
= &t
.c_cc
[VINTR
];
6386 sig_char
= &t
.c_cc
[VQUIT
];
6391 sig_char
= &t
.c_cc
[VSWTCH
];
6393 sig_char
= &t
.c_cc
[VSUSP
];
6398 if (sig_char
&& *sig_char
!= CDISABLE
)
6400 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6403 /* If we can't send the signal with a character,
6404 fall through and send it another way. */
6406 /* The code above may fall through if it can't
6407 handle the signal. */
6408 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6411 /* Get the current pgrp using the tty itself, if we have that.
6412 Otherwise, use the pty to get the pgrp.
6413 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6414 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6415 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6416 His patch indicates that if TIOCGPGRP returns an error, then
6417 we should just assume that p->pid is also the process group id. */
6419 gid
= emacs_get_tty_pgrp (p
);
6422 /* If we can't get the information, assume
6423 the shell owns the tty. */
6426 /* It is not clear whether anything really can set GID to -1.
6427 Perhaps on some system one of those ioctls can or could do so.
6428 Or perhaps this is vestigial. */
6431 #else /* ! defined (TIOCGPGRP) */
6432 /* Can't select pgrps on this system, so we know that
6433 the child itself heads the pgrp. */
6435 #endif /* ! defined (TIOCGPGRP) */
6437 /* If current_group is lambda, and the shell owns the terminal,
6438 don't send any signal. */
6439 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6444 if (signo
== SIGCONT
)
6446 p
->raw_status_new
= 0;
6447 pset_status (p
, Qrun
);
6448 p
->tick
= ++process_tick
;
6451 status_notify (NULL
, NULL
);
6452 redisplay_preserve_echo_area (13);
6458 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6459 We don't know whether the bug is fixed in later HP-UX versions. */
6460 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6464 /* If we don't have process groups, send the signal to the immediate
6465 subprocess. That isn't really right, but it's better than any
6466 obvious alternative. */
6467 pid_t pid
= no_pgrp
? gid
: - gid
;
6469 /* Do not kill an already-reaped process, as that could kill an
6470 innocent bystander that happens to have the same process ID. */
6472 block_child_signal (&oldset
);
6475 unblock_child_signal (&oldset
);
6478 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6479 doc
: /* Interrupt process PROCESS.
6480 PROCESS may be a process, a buffer, or the name of a process or buffer.
6481 No arg or nil means current buffer's process.
6482 Second arg CURRENT-GROUP non-nil means send signal to
6483 the current process-group of the process's controlling terminal
6484 rather than to the process's own process group.
6485 If the process is a shell, this means interrupt current subjob
6486 rather than the shell.
6488 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6489 don't send the signal. */)
6490 (Lisp_Object process
, Lisp_Object current_group
)
6492 process_send_signal (process
, SIGINT
, current_group
, 0);
6496 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6497 doc
: /* Kill process PROCESS. May be process or name of one.
6498 See function `interrupt-process' for more details on usage. */)
6499 (Lisp_Object process
, Lisp_Object current_group
)
6501 process_send_signal (process
, SIGKILL
, current_group
, 0);
6505 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6506 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6507 See function `interrupt-process' for more details on usage. */)
6508 (Lisp_Object process
, Lisp_Object current_group
)
6510 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6514 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6515 doc
: /* Stop process PROCESS. May be process or name of one.
6516 See function `interrupt-process' for more details on usage.
6517 If PROCESS is a network or serial process, inhibit handling of incoming
6519 (Lisp_Object process
, Lisp_Object current_group
)
6521 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6522 || PIPECONN_P (process
)))
6524 struct Lisp_Process
*p
;
6526 p
= XPROCESS (process
);
6527 if (NILP (p
->command
)
6530 FD_CLR (p
->infd
, &input_wait_mask
);
6531 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6533 pset_command (p
, Qt
);
6537 error ("No SIGTSTP support");
6539 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6544 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6545 doc
: /* Continue process PROCESS. May be process or name of one.
6546 See function `interrupt-process' for more details on usage.
6547 If PROCESS is a network or serial process, resume handling of incoming
6549 (Lisp_Object process
, Lisp_Object current_group
)
6551 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6552 || PIPECONN_P (process
)))
6554 struct Lisp_Process
*p
;
6556 p
= XPROCESS (process
);
6557 if (EQ (p
->command
, Qt
)
6559 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6561 FD_SET (p
->infd
, &input_wait_mask
);
6562 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6564 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6565 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6566 #else /* not WINDOWSNT */
6567 tcflush (p
->infd
, TCIFLUSH
);
6568 #endif /* not WINDOWSNT */
6570 pset_command (p
, Qnil
);
6574 process_send_signal (process
, SIGCONT
, current_group
, 0);
6576 error ("No SIGCONT support");
6581 /* Return the integer value of the signal whose abbreviation is ABBR,
6582 or a negative number if there is no such signal. */
6584 abbr_to_signal (char const *name
)
6587 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6589 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6592 for (i
= 0; i
< sizeof sigbuf
; i
++)
6594 sigbuf
[i
] = c_toupper (name
[i
]);
6596 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6602 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6603 2, 2, "sProcess (name or number): \nnSignal code: ",
6604 doc
: /* Send PROCESS the signal with code SIGCODE.
6605 PROCESS may also be a number specifying the process id of the
6606 process to signal; in this case, the process need not be a child of
6608 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6609 (Lisp_Object process
, Lisp_Object sigcode
)
6614 if (STRINGP (process
))
6616 Lisp_Object tem
= Fget_process (process
);
6619 Lisp_Object process_number
6620 = string_to_number (SSDATA (process
), 10, 1);
6621 if (NUMBERP (process_number
))
6622 tem
= process_number
;
6626 else if (!NUMBERP (process
))
6627 process
= get_process (process
);
6632 if (NUMBERP (process
))
6633 CONS_TO_INTEGER (process
, pid_t
, pid
);
6636 CHECK_PROCESS (process
);
6637 pid
= XPROCESS (process
)->pid
;
6639 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6642 if (INTEGERP (sigcode
))
6644 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6645 signo
= XINT (sigcode
);
6651 CHECK_SYMBOL (sigcode
);
6652 name
= SSDATA (SYMBOL_NAME (sigcode
));
6654 signo
= abbr_to_signal (name
);
6656 error ("Undefined signal name %s", name
);
6659 return make_number (kill (pid
, signo
));
6662 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6663 doc
: /* Make PROCESS see end-of-file in its input.
6664 EOF comes after any text already sent to it.
6665 PROCESS may be a process, a buffer, the name of a process or buffer, or
6666 nil, indicating the current buffer's process.
6667 If PROCESS is a network connection, or is a process communicating
6668 through a pipe (as opposed to a pty), then you cannot send any more
6669 text to PROCESS after you call this function.
6670 If PROCESS is a serial process, wait until all output written to the
6671 process has been transmitted to the serial port. */)
6672 (Lisp_Object process
)
6675 struct coding_system
*coding
= NULL
;
6678 proc
= get_process (process
);
6680 if (NETCONN_P (proc
))
6681 wait_while_connecting (proc
);
6683 if (DATAGRAM_CONN_P (proc
))
6687 outfd
= XPROCESS (proc
)->outfd
;
6689 coding
= proc_encode_coding_system
[outfd
];
6691 /* Make sure the process is really alive. */
6692 if (XPROCESS (proc
)->raw_status_new
)
6693 update_status (XPROCESS (proc
));
6694 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6695 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6697 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6699 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6700 send_process (proc
, "", 0, Qnil
);
6703 if (XPROCESS (proc
)->pty_flag
)
6704 send_process (proc
, "\004", 1, Qnil
);
6705 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6708 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6709 report_file_error ("Failed tcdrain", Qnil
);
6710 #endif /* not WINDOWSNT */
6711 /* Do nothing on Windows because writes are blocking. */
6715 struct Lisp_Process
*p
= XPROCESS (proc
);
6716 int old_outfd
= p
->outfd
;
6719 #ifdef HAVE_SHUTDOWN
6720 /* If this is a network connection, or socketpair is used
6721 for communication with the subprocess, call shutdown to cause EOF.
6722 (In some old system, shutdown to socketpair doesn't work.
6723 Then we just can't win.) */
6725 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6726 shutdown (old_outfd
, 1);
6728 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6729 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6731 report_file_error ("Opening null device", Qnil
);
6732 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6733 p
->outfd
= new_outfd
;
6735 if (!proc_encode_coding_system
[new_outfd
])
6736 proc_encode_coding_system
[new_outfd
]
6737 = xmalloc (sizeof (struct coding_system
));
6740 *proc_encode_coding_system
[new_outfd
]
6741 = *proc_encode_coding_system
[old_outfd
];
6742 memset (proc_encode_coding_system
[old_outfd
], 0,
6743 sizeof (struct coding_system
));
6746 setup_coding_system (p
->encode_coding_system
,
6747 proc_encode_coding_system
[new_outfd
]);
6752 /* The main Emacs thread records child processes in three places:
6754 - Vprocess_alist, for asynchronous subprocesses, which are child
6755 processes visible to Lisp.
6757 - deleted_pid_list, for child processes invisible to Lisp,
6758 typically because of delete-process. These are recorded so that
6759 the processes can be reaped when they exit, so that the operating
6760 system's process table is not cluttered by zombies.
6762 - the local variable PID in Fcall_process, call_process_cleanup and
6763 call_process_kill, for synchronous subprocesses.
6764 record_unwind_protect is used to make sure this process is not
6765 forgotten: if the user interrupts call-process and the child
6766 process refuses to exit immediately even with two C-g's,
6767 call_process_kill adds PID's contents to deleted_pid_list before
6770 The main Emacs thread invokes waitpid only on child processes that
6771 it creates and that have not been reaped. This avoid races on
6772 platforms such as GTK, where other threads create their own
6773 subprocesses which the main thread should not reap. For example,
6774 if the main thread attempted to reap an already-reaped child, it
6775 might inadvertently reap a GTK-created process that happened to
6776 have the same process ID. */
6778 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6779 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6780 keep track of its own children. GNUstep is similar. */
6782 static void dummy_handler (int sig
) {}
6783 static signal_handler_t
volatile lib_child_handler
;
6785 /* Handle a SIGCHLD signal by looking for known child processes of
6786 Emacs whose status have changed. For each one found, record its
6789 All we do is change the status; we do not run sentinels or print
6790 notifications. That is saved for the next time keyboard input is
6791 done, in order to avoid timing errors.
6793 ** WARNING: this can be called during garbage collection.
6794 Therefore, it must not be fooled by the presence of mark bits in
6797 ** USG WARNING: Although it is not obvious from the documentation
6798 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6799 signal() before executing at least one wait(), otherwise the
6800 handler will be called again, resulting in an infinite loop. The
6801 relevant portion of the documentation reads "SIGCLD signals will be
6802 queued and the signal-catching function will be continually
6803 reentered until the queue is empty". Invoking signal() causes the
6804 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6807 ** Malloc WARNING: This should never call malloc either directly or
6808 indirectly; if it does, that is a bug. */
6811 handle_child_signal (int sig
)
6813 Lisp_Object tail
, proc
;
6815 /* Find the process that signaled us, and record its status. */
6817 /* The process can have been deleted by Fdelete_process, or have
6818 been started asynchronously by Fcall_process. */
6819 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6821 bool all_pids_are_fixnums
6822 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6823 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6824 Lisp_Object head
= XCAR (tail
);
6829 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6832 if (INTEGERP (xpid
))
6833 deleted_pid
= XINT (xpid
);
6835 deleted_pid
= XFLOAT_DATA (xpid
);
6836 if (child_status_changed (deleted_pid
, 0, 0))
6838 if (STRINGP (XCDR (head
)))
6839 unlink (SSDATA (XCDR (head
)));
6840 XSETCAR (tail
, Qnil
);
6845 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6846 FOR_EACH_PROCESS (tail
, proc
)
6848 struct Lisp_Process
*p
= XPROCESS (proc
);
6852 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6854 /* Change the status of the process that was found. */
6855 p
->tick
= ++process_tick
;
6856 p
->raw_status
= status
;
6857 p
->raw_status_new
= 1;
6859 /* If process has terminated, stop waiting for its output. */
6860 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6862 bool clear_desc_flag
= 0;
6865 clear_desc_flag
= 1;
6867 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6868 if (clear_desc_flag
)
6870 FD_CLR (p
->infd
, &input_wait_mask
);
6871 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6877 lib_child_handler (sig
);
6878 #ifdef NS_IMPL_GNUSTEP
6879 /* NSTask in GNUstep sets its child handler each time it is called.
6880 So we must re-set ours. */
6881 catch_child_signal ();
6886 deliver_child_signal (int sig
)
6888 deliver_process_signal (sig
, handle_child_signal
);
6893 exec_sentinel_error_handler (Lisp_Object error_val
)
6895 cmd_error_internal (error_val
, "error in process sentinel: ");
6897 update_echo_area ();
6898 Fsleep_for (make_number (2), Qnil
);
6903 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6905 Lisp_Object sentinel
, odeactivate
;
6906 struct Lisp_Process
*p
= XPROCESS (proc
);
6907 ptrdiff_t count
= SPECPDL_INDEX ();
6908 bool outer_running_asynch_code
= running_asynch_code
;
6909 int waiting
= waiting_for_user_input_p
;
6911 if (inhibit_sentinels
)
6914 odeactivate
= Vdeactivate_mark
;
6916 Lisp_Object obuffer
, okeymap
;
6917 XSETBUFFER (obuffer
, current_buffer
);
6918 okeymap
= BVAR (current_buffer
, keymap
);
6921 /* There's no good reason to let sentinels change the current
6922 buffer, and many callers of accept-process-output, sit-for, and
6923 friends don't expect current-buffer to be changed from under them. */
6924 record_unwind_current_buffer ();
6926 sentinel
= p
->sentinel
;
6928 /* Inhibit quit so that random quits don't screw up a running filter. */
6929 specbind (Qinhibit_quit
, Qt
);
6930 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6932 /* In case we get recursively called,
6933 and we already saved the match data nonrecursively,
6934 save the same match data in safely recursive fashion. */
6935 if (outer_running_asynch_code
)
6938 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6939 restore_search_regs ();
6940 record_unwind_save_match_data ();
6941 Fset_match_data (tem
, Qt
);
6944 /* For speed, if a search happens within this code,
6945 save the match data in a special nonrecursive fashion. */
6946 running_asynch_code
= 1;
6948 internal_condition_case_1 (read_process_output_call
,
6949 list3 (sentinel
, proc
, reason
),
6950 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6951 exec_sentinel_error_handler
);
6953 /* If we saved the match data nonrecursively, restore it now. */
6954 restore_search_regs ();
6955 running_asynch_code
= outer_running_asynch_code
;
6957 Vdeactivate_mark
= odeactivate
;
6959 /* Restore waiting_for_user_input_p as it was
6960 when we were called, in case the filter clobbered it. */
6961 waiting_for_user_input_p
= waiting
;
6964 if (! EQ (Fcurrent_buffer (), obuffer
)
6965 || ! EQ (current_buffer
->keymap
, okeymap
))
6967 /* But do it only if the caller is actually going to read events.
6968 Otherwise there's no need to make him wake up, and it could
6969 cause trouble (for example it would make sit_for return). */
6970 if (waiting_for_user_input_p
== -1)
6971 record_asynch_buffer_change ();
6973 unbind_to (count
, Qnil
);
6976 /* Report all recent events of a change in process status
6977 (either run the sentinel or output a message).
6978 This is usually done while Emacs is waiting for keyboard input
6979 but can be done at other times.
6981 Return positive if any input was received from WAIT_PROC (or from
6982 any process if WAIT_PROC is null), zero if input was attempted but
6983 none received, and negative if we didn't even try. */
6986 status_notify (struct Lisp_Process
*deleting_process
,
6987 struct Lisp_Process
*wait_proc
)
6990 Lisp_Object tail
, msg
;
6991 int got_some_output
= -1;
6996 /* Set this now, so that if new processes are created by sentinels
6997 that we run, we get called again to handle their status changes. */
6998 update_tick
= process_tick
;
7000 FOR_EACH_PROCESS (tail
, proc
)
7003 register struct Lisp_Process
*p
= XPROCESS (proc
);
7005 if (p
->tick
!= p
->update_tick
)
7007 p
->update_tick
= p
->tick
;
7009 /* If process is still active, read any output that remains. */
7010 while (! EQ (p
->filter
, Qt
)
7011 && ! EQ (p
->status
, Qconnect
)
7012 && ! EQ (p
->status
, Qlisten
)
7013 /* Network or serial process not stopped: */
7014 && ! EQ (p
->command
, Qt
)
7016 && p
!= deleting_process
)
7018 int nread
= read_process_output (proc
, p
->infd
);
7019 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7020 && got_some_output
< nread
)
7021 got_some_output
= nread
;
7026 /* Get the text to use for the message. */
7027 if (p
->raw_status_new
)
7029 msg
= status_message (p
);
7031 /* If process is terminated, deactivate it or delete it. */
7033 if (CONSP (p
->status
))
7034 symbol
= XCAR (p
->status
);
7036 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7037 || EQ (symbol
, Qclosed
))
7039 if (delete_exited_processes
)
7040 remove_process (proc
);
7042 deactivate_process (proc
);
7045 /* The actions above may have further incremented p->tick.
7046 So set p->update_tick again so that an error in the sentinel will
7047 not cause this code to be run again. */
7048 p
->update_tick
= p
->tick
;
7049 /* Now output the message suitably. */
7050 exec_sentinel (proc
, msg
);
7051 if (BUFFERP (p
->buffer
))
7052 /* In case it uses %s in mode-line-format. */
7053 bset_update_mode_line (XBUFFER (p
->buffer
));
7057 return got_some_output
;
7060 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7061 Sinternal_default_process_sentinel
, 2, 2, 0,
7062 doc
: /* Function used as default sentinel for processes.
7063 This inserts a status message into the process's buffer, if there is one. */)
7064 (Lisp_Object proc
, Lisp_Object msg
)
7066 Lisp_Object buffer
, symbol
;
7067 struct Lisp_Process
*p
;
7068 CHECK_PROCESS (proc
);
7069 p
= XPROCESS (proc
);
7073 symbol
= XCAR (symbol
);
7075 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7078 struct buffer
*old
= current_buffer
;
7079 ptrdiff_t opoint
, opoint_byte
;
7080 ptrdiff_t before
, before_byte
;
7082 /* Avoid error if buffer is deleted
7083 (probably that's why the process is dead, too). */
7084 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7086 Fset_buffer (buffer
);
7088 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7089 msg
= (code_convert_string_norecord
7090 (msg
, Vlocale_coding_system
, 1));
7093 opoint_byte
= PT_BYTE
;
7094 /* Insert new output into buffer
7095 at the current end-of-output marker,
7096 thus preserving logical ordering of input and output. */
7097 if (XMARKER (p
->mark
)->buffer
)
7098 Fgoto_char (p
->mark
);
7100 SET_PT_BOTH (ZV
, ZV_BYTE
);
7103 before_byte
= PT_BYTE
;
7105 tem
= BVAR (current_buffer
, read_only
);
7106 bset_read_only (current_buffer
, Qnil
);
7107 insert_string ("\nProcess ");
7108 { /* FIXME: temporary kludge. */
7109 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7110 insert_string (" ");
7112 bset_read_only (current_buffer
, tem
);
7113 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7115 if (opoint
>= before
)
7116 SET_PT_BOTH (opoint
+ (PT
- before
),
7117 opoint_byte
+ (PT_BYTE
- before_byte
));
7119 SET_PT_BOTH (opoint
, opoint_byte
);
7121 set_buffer_internal (old
);
7127 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7128 Sset_process_coding_system
, 1, 3, 0,
7129 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7130 DECODING will be used to decode subprocess output and ENCODING to
7131 encode subprocess input. */)
7132 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7134 CHECK_PROCESS (process
);
7136 struct Lisp_Process
*p
= XPROCESS (process
);
7138 Fcheck_coding_system (decoding
);
7139 Fcheck_coding_system (encoding
);
7140 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7141 pset_decode_coding_system (p
, decoding
);
7142 pset_encode_coding_system (p
, encoding
);
7144 /* If the sockets haven't been set up yet, the final setup part of
7145 this will be called asynchronously. */
7146 if (p
->infd
< 0 || p
->outfd
< 0)
7149 setup_process_coding_systems (process
);
7154 DEFUN ("process-coding-system",
7155 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7156 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7157 (register Lisp_Object process
)
7159 CHECK_PROCESS (process
);
7160 return Fcons (XPROCESS (process
)->decode_coding_system
,
7161 XPROCESS (process
)->encode_coding_system
);
7164 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7165 Sset_process_filter_multibyte
, 2, 2, 0,
7166 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7167 If FLAG is non-nil, the filter is given multibyte strings.
7168 If FLAG is nil, the filter is given unibyte strings. In this case,
7169 all character code conversion except for end-of-line conversion is
7171 (Lisp_Object process
, Lisp_Object flag
)
7173 CHECK_PROCESS (process
);
7175 struct Lisp_Process
*p
= XPROCESS (process
);
7177 pset_decode_coding_system
7178 (p
, raw_text_coding_system (p
->decode_coding_system
));
7180 /* If the sockets haven't been set up yet, the final setup part of
7181 this will be called asynchronously. */
7182 if (p
->infd
< 0 || p
->outfd
< 0)
7185 setup_process_coding_systems (process
);
7190 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7191 Sprocess_filter_multibyte_p
, 1, 1, 0,
7192 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7193 (Lisp_Object process
)
7195 CHECK_PROCESS (process
);
7196 struct Lisp_Process
*p
= XPROCESS (process
);
7199 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7200 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7209 add_gpm_wait_descriptor (int desc
)
7211 add_keyboard_wait_descriptor (desc
);
7215 delete_gpm_wait_descriptor (int desc
)
7217 delete_keyboard_wait_descriptor (desc
);
7222 # ifdef USABLE_SIGIO
7224 /* Return true if *MASK has a bit set
7225 that corresponds to one of the keyboard input descriptors. */
7228 keyboard_bit_set (fd_set
*mask
)
7232 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7233 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7234 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7241 #else /* not subprocesses */
7243 /* Defined in msdos.c. */
7244 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7245 struct timespec
*, void *);
7247 /* Implementation of wait_reading_process_output, assuming that there
7248 are no subprocesses. Used only by the MS-DOS build.
7250 Wait for timeout to elapse and/or keyboard input to be available.
7254 If negative, gobble data immediately available but don't wait for any.
7257 an additional duration to wait, measured in nanoseconds
7258 If TIME_LIMIT is zero, then:
7259 If NSECS == 0, there is no limit.
7260 If NSECS > 0, the timeout consists of NSECS only.
7261 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7264 0 to ignore keyboard input, or
7265 1 to return when input is available, or
7266 -1 means caller will actually read the input, so don't throw to
7269 see full version for other parameters. We know that wait_proc will
7270 always be NULL, since `subprocesses' isn't defined.
7272 DO_DISPLAY means redisplay should be done to show subprocess
7273 output that arrives.
7275 Return -1 signifying we got no output and did not try. */
7278 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7280 Lisp_Object wait_for_cell
,
7281 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7284 struct timespec end_time
, timeout
;
7285 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7287 if (TYPE_MAXIMUM (time_t) < time_limit
)
7288 time_limit
= TYPE_MAXIMUM (time_t);
7290 if (time_limit
< 0 || nsecs
< 0)
7292 else if (time_limit
> 0 || nsecs
> 0)
7295 end_time
= timespec_add (current_timespec (),
7296 make_timespec (time_limit
, nsecs
));
7301 /* Turn off periodic alarms (in case they are in use)
7302 and then turn off any other atimers,
7303 because the select emulator uses alarms. */
7305 turn_on_atimers (0);
7309 bool timeout_reduced_for_timers
= false;
7310 fd_set waitchannels
;
7313 /* If calling from keyboard input, do not quit
7314 since we want to return C-g as an input character.
7315 Otherwise, do pending quit if requested. */
7319 /* Exit now if the cell we're waiting for became non-nil. */
7320 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7323 /* Compute time from now till when time limit is up. */
7324 /* Exit if already run out. */
7325 if (wait
== TIMEOUT
)
7327 struct timespec now
= current_timespec ();
7328 if (timespec_cmp (end_time
, now
) <= 0)
7330 timeout
= timespec_sub (end_time
, now
);
7333 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7335 /* If our caller will not immediately handle keyboard events,
7336 run timer events directly.
7337 (Callers that will immediately read keyboard events
7338 call timer_delay on their own.) */
7339 if (NILP (wait_for_cell
))
7341 struct timespec timer_delay
;
7345 unsigned old_timers_run
= timers_run
;
7346 timer_delay
= timer_check ();
7347 if (timers_run
!= old_timers_run
&& do_display
)
7348 /* We must retry, since a timer may have requeued itself
7349 and that could alter the time delay. */
7350 redisplay_preserve_echo_area (14);
7354 while (!detect_input_pending ());
7356 /* If there is unread keyboard input, also return. */
7358 && requeued_events_pending_p ())
7361 if (timespec_valid_p (timer_delay
))
7363 if (timespec_cmp (timer_delay
, timeout
) < 0)
7365 timeout
= timer_delay
;
7366 timeout_reduced_for_timers
= true;
7371 /* Cause C-g and alarm signals to take immediate action,
7372 and cause input available signals to zero out timeout. */
7374 set_waiting_for_input (&timeout
);
7376 /* If a frame has been newly mapped and needs updating,
7377 reprocess its display stuff. */
7378 if (frame_garbaged
&& do_display
)
7380 clear_waiting_for_input ();
7381 redisplay_preserve_echo_area (15);
7383 set_waiting_for_input (&timeout
);
7386 /* Wait till there is something to do. */
7387 FD_ZERO (&waitchannels
);
7388 if (read_kbd
&& detect_input_pending ())
7392 if (read_kbd
|| !NILP (wait_for_cell
))
7393 FD_SET (0, &waitchannels
);
7394 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7399 /* Make C-g and alarm signals set flags again. */
7400 clear_waiting_for_input ();
7402 /* If we woke up due to SIGWINCH, actually change size now. */
7403 do_pending_window_change (0);
7405 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7406 /* We waited the full specified time, so return now. */
7411 /* If the system call was interrupted, then go around the
7413 if (xerrno
== EINTR
)
7414 FD_ZERO (&waitchannels
);
7416 report_file_errno ("Failed select", Qnil
, xerrno
);
7419 /* Check for keyboard input. */
7422 && detect_input_pending_run_timers (do_display
))
7424 swallow_events (do_display
);
7425 if (detect_input_pending_run_timers (do_display
))
7429 /* If there is unread keyboard input, also return. */
7431 && requeued_events_pending_p ())
7434 /* If wait_for_cell. check for keyboard input
7435 but don't run any timers.
7436 ??? (It seems wrong to me to check for keyboard
7437 input at all when wait_for_cell, but the code
7438 has been this way since July 1994.
7439 Try changing this after version 19.31.) */
7440 if (! NILP (wait_for_cell
)
7441 && detect_input_pending ())
7443 swallow_events (do_display
);
7444 if (detect_input_pending ())
7448 /* Exit now if the cell we're waiting for became non-nil. */
7449 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7458 #endif /* not subprocesses */
7460 /* The following functions are needed even if async subprocesses are
7461 not supported. Some of them are no-op stubs in that case. */
7465 /* Add FD, which is a descriptor returned by timerfd_create,
7466 to the set of non-keyboard input descriptors. */
7469 add_timer_wait_descriptor (int fd
)
7471 FD_SET (fd
, &input_wait_mask
);
7472 FD_SET (fd
, &non_keyboard_wait_mask
);
7473 FD_SET (fd
, &non_process_wait_mask
);
7474 fd_callback_info
[fd
].func
= timerfd_callback
;
7475 fd_callback_info
[fd
].data
= NULL
;
7476 fd_callback_info
[fd
].condition
|= FOR_READ
;
7477 if (fd
> max_input_desc
)
7478 max_input_desc
= fd
;
7481 #endif /* HAVE_TIMERFD */
7483 /* Add DESC to the set of keyboard input descriptors. */
7486 add_keyboard_wait_descriptor (int desc
)
7488 #ifdef subprocesses /* Actually means "not MSDOS". */
7489 FD_SET (desc
, &input_wait_mask
);
7490 FD_SET (desc
, &non_process_wait_mask
);
7491 if (desc
> max_input_desc
)
7492 max_input_desc
= desc
;
7496 /* From now on, do not expect DESC to give keyboard input. */
7499 delete_keyboard_wait_descriptor (int desc
)
7502 FD_CLR (desc
, &input_wait_mask
);
7503 FD_CLR (desc
, &non_process_wait_mask
);
7504 delete_input_desc (desc
);
7508 /* Setup coding systems of PROCESS. */
7511 setup_process_coding_systems (Lisp_Object process
)
7514 struct Lisp_Process
*p
= XPROCESS (process
);
7516 int outch
= p
->outfd
;
7517 Lisp_Object coding_system
;
7519 if (inch
< 0 || outch
< 0)
7522 if (!proc_decode_coding_system
[inch
])
7523 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7524 coding_system
= p
->decode_coding_system
;
7525 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7526 && BUFFERP (p
->buffer
))
7528 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7529 coding_system
= raw_text_coding_system (coding_system
);
7531 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7533 if (!proc_encode_coding_system
[outch
])
7534 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7535 setup_coding_system (p
->encode_coding_system
,
7536 proc_encode_coding_system
[outch
]);
7540 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7541 doc
: /* Return the (or a) live process associated with BUFFER.
7542 BUFFER may be a buffer or the name of one.
7543 Return nil if all processes associated with BUFFER have been
7544 deleted or killed. */)
7545 (register Lisp_Object buffer
)
7548 register Lisp_Object buf
, tail
, proc
;
7550 if (NILP (buffer
)) return Qnil
;
7551 buf
= Fget_buffer (buffer
);
7552 if (NILP (buf
)) return Qnil
;
7554 FOR_EACH_PROCESS (tail
, proc
)
7555 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7557 #endif /* subprocesses */
7561 DEFUN ("process-inherit-coding-system-flag",
7562 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7564 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7565 If this flag is t, `buffer-file-coding-system' of the buffer
7566 associated with PROCESS will inherit the coding system used to decode
7567 the process output. */)
7568 (register Lisp_Object process
)
7571 CHECK_PROCESS (process
);
7572 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7574 /* Ignore the argument and return the value of
7575 inherit-process-coding-system. */
7576 return inherit_process_coding_system
? Qt
: Qnil
;
7580 /* Kill all processes associated with `buffer'.
7581 If `buffer' is nil, kill all processes. */
7584 kill_buffer_processes (Lisp_Object buffer
)
7587 Lisp_Object tail
, proc
;
7589 FOR_EACH_PROCESS (tail
, proc
)
7590 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7592 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7593 Fdelete_process (proc
);
7594 else if (XPROCESS (proc
)->infd
>= 0)
7595 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7597 #else /* subprocesses */
7598 /* Since we have no subprocesses, this does nothing. */
7599 #endif /* subprocesses */
7602 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7603 Swaiting_for_user_input_p
, 0, 0, 0,
7604 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7605 This is intended for use by asynchronous process output filters and sentinels. */)
7609 return (waiting_for_user_input_p
? Qt
: Qnil
);
7615 /* Stop reading input from keyboard sources. */
7618 hold_keyboard_input (void)
7623 /* Resume reading input from keyboard sources. */
7626 unhold_keyboard_input (void)
7631 /* Return true if keyboard input is on hold, zero otherwise. */
7634 kbd_on_hold_p (void)
7636 return kbd_is_on_hold
;
7640 /* Enumeration of and access to system processes a-la ps(1). */
7642 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7644 doc
: /* Return a list of numerical process IDs of all running processes.
7645 If this functionality is unsupported, return nil.
7647 See `process-attributes' for getting attributes of a process given its ID. */)
7650 return list_system_processes ();
7653 DEFUN ("process-attributes", Fprocess_attributes
,
7654 Sprocess_attributes
, 1, 1, 0,
7655 doc
: /* Return attributes of the process given by its PID, a number.
7657 Value is an alist where each element is a cons cell of the form
7661 If this functionality is unsupported, the value is nil.
7663 See `list-system-processes' for getting a list of all process IDs.
7665 The KEYs of the attributes that this function may return are listed
7666 below, together with the type of the associated VALUE (in parentheses).
7667 Not all platforms support all of these attributes; unsupported
7668 attributes will not appear in the returned alist.
7669 Unless explicitly indicated otherwise, numbers can have either
7670 integer or floating point values.
7672 euid -- Effective user User ID of the process (number)
7673 user -- User name corresponding to euid (string)
7674 egid -- Effective user Group ID of the process (number)
7675 group -- Group name corresponding to egid (string)
7676 comm -- Command name (executable name only) (string)
7677 state -- Process state code, such as "S", "R", or "T" (string)
7678 ppid -- Parent process ID (number)
7679 pgrp -- Process group ID (number)
7680 sess -- Session ID, i.e. process ID of session leader (number)
7681 ttname -- Controlling tty name (string)
7682 tpgid -- ID of foreground process group on the process's tty (number)
7683 minflt -- number of minor page faults (number)
7684 majflt -- number of major page faults (number)
7685 cminflt -- cumulative number of minor page faults (number)
7686 cmajflt -- cumulative number of major page faults (number)
7687 utime -- user time used by the process, in (current-time) format,
7688 which is a list of integers (HIGH LOW USEC PSEC)
7689 stime -- system time used by the process (current-time)
7690 time -- sum of utime and stime (current-time)
7691 cutime -- user time used by the process and its children (current-time)
7692 cstime -- system time used by the process and its children (current-time)
7693 ctime -- sum of cutime and cstime (current-time)
7694 pri -- priority of the process (number)
7695 nice -- nice value of the process (number)
7696 thcount -- process thread count (number)
7697 start -- time the process started (current-time)
7698 vsize -- virtual memory size of the process in KB's (number)
7699 rss -- resident set size of the process in KB's (number)
7700 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7701 pcpu -- percents of CPU time used by the process (floating-point number)
7702 pmem -- percents of total physical memory used by process's resident set
7703 (floating-point number)
7704 args -- command line which invoked the process (string). */)
7707 return system_process_attributes (pid
);
7711 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7712 Invoke this after init_process_emacs, and after glib and/or GNUstep
7713 futz with the SIGCHLD handler, but before Emacs forks any children.
7714 This function's caller should block SIGCHLD. */
7717 catch_child_signal (void)
7719 struct sigaction action
, old_action
;
7721 emacs_sigaction_init (&action
, deliver_child_signal
);
7722 block_child_signal (&oldset
);
7723 sigaction (SIGCHLD
, &action
, &old_action
);
7724 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7725 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7727 if (old_action
.sa_handler
!= deliver_child_signal
)
7729 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7731 : old_action
.sa_handler
);
7732 unblock_child_signal (&oldset
);
7734 #endif /* subprocesses */
7736 /* Set the external socket descriptor for Emacs to use when
7737 `make-network-process' is called with a non-nil
7738 `:use-external-socket' option. The fd should have been checked to
7739 ensure it is a valid socket and is already bound. */
7741 set_external_socket_descriptor (int fd
)
7743 external_sock_fd
= fd
;
7747 /* This is not called "init_process" because that is the name of a
7748 Mach system call, so it would cause problems on Darwin systems. */
7750 init_process_emacs (void)
7755 inhibit_sentinels
= 0;
7758 if (! noninteractive
|| initialized
)
7761 #if defined HAVE_GLIB && !defined WINDOWSNT
7762 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7763 this should always fail, but is enough to initialize glib's
7764 private SIGCHLD handler, allowing catch_child_signal to copy
7765 it into lib_child_handler. */
7766 g_source_unref (g_child_watch_source_new (getpid ()));
7768 catch_child_signal ();
7771 FD_ZERO (&input_wait_mask
);
7772 FD_ZERO (&non_keyboard_wait_mask
);
7773 FD_ZERO (&non_process_wait_mask
);
7774 FD_ZERO (&write_mask
);
7775 max_process_desc
= max_input_desc
= external_sock_fd
= -1;
7776 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7778 FD_ZERO (&connect_wait_mask
);
7779 num_pending_connects
= 0;
7781 process_output_delay_count
= 0;
7782 process_output_skip
= 0;
7784 /* Don't do this, it caused infinite select loops. The display
7785 method should call add_keyboard_wait_descriptor on stdin if it
7788 FD_SET (0, &input_wait_mask
);
7791 Vprocess_alist
= Qnil
;
7792 deleted_pid_list
= Qnil
;
7793 for (i
= 0; i
< FD_SETSIZE
; i
++)
7795 chan_process
[i
] = Qnil
;
7796 proc_buffered_char
[i
] = -1;
7798 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7799 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7800 #ifdef DATAGRAM_SOCKETS
7801 memset (datagram_address
, 0, sizeof datagram_address
);
7804 #if defined (DARWIN_OS)
7805 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7806 processes. As such, we only change the default value. */
7809 char const *release
= (STRINGP (Voperating_system_release
)
7810 ? SSDATA (Voperating_system_release
)
7812 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7813 Vprocess_connection_type
= Qnil
;
7817 #endif /* subprocesses */
7822 syms_of_process (void)
7826 DEFSYM (Qprocessp
, "processp");
7827 DEFSYM (Qrun
, "run");
7828 DEFSYM (Qstop
, "stop");
7829 DEFSYM (Qsignal
, "signal");
7831 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7834 DEFSYM (Qopen
, "open");
7835 DEFSYM (Qclosed
, "closed");
7836 DEFSYM (Qconnect
, "connect");
7837 DEFSYM (Qfailed
, "failed");
7838 DEFSYM (Qlisten
, "listen");
7839 DEFSYM (Qlocal
, "local");
7840 DEFSYM (Qipv4
, "ipv4");
7842 DEFSYM (Qipv6
, "ipv6");
7844 DEFSYM (Qdatagram
, "datagram");
7845 DEFSYM (Qseqpacket
, "seqpacket");
7847 DEFSYM (QCport
, ":port");
7848 DEFSYM (QCspeed
, ":speed");
7849 DEFSYM (QCprocess
, ":process");
7851 DEFSYM (QCbytesize
, ":bytesize");
7852 DEFSYM (QCstopbits
, ":stopbits");
7853 DEFSYM (QCparity
, ":parity");
7854 DEFSYM (Qodd
, "odd");
7855 DEFSYM (Qeven
, "even");
7856 DEFSYM (QCflowcontrol
, ":flowcontrol");
7859 DEFSYM (QCsummary
, ":summary");
7861 DEFSYM (Qreal
, "real");
7862 DEFSYM (Qnetwork
, "network");
7863 DEFSYM (Qserial
, "serial");
7864 DEFSYM (Qpipe
, "pipe");
7865 DEFSYM (QCbuffer
, ":buffer");
7866 DEFSYM (QChost
, ":host");
7867 DEFSYM (QCservice
, ":service");
7868 DEFSYM (QClocal
, ":local");
7869 DEFSYM (QCremote
, ":remote");
7870 DEFSYM (QCcoding
, ":coding");
7871 DEFSYM (QCserver
, ":server");
7872 DEFSYM (QCnowait
, ":nowait");
7873 DEFSYM (QCsentinel
, ":sentinel");
7874 DEFSYM (QCuse_external_socket
, ":use-external-socket");
7875 DEFSYM (QCtls_parameters
, ":tls-parameters");
7876 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7877 DEFSYM (QClog
, ":log");
7878 DEFSYM (QCnoquery
, ":noquery");
7879 DEFSYM (QCstop
, ":stop");
7880 DEFSYM (QCplist
, ":plist");
7881 DEFSYM (QCcommand
, ":command");
7882 DEFSYM (QCconnection_type
, ":connection-type");
7883 DEFSYM (QCstderr
, ":stderr");
7884 DEFSYM (Qpty
, "pty");
7885 DEFSYM (Qpipe
, "pipe");
7887 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7889 staticpro (&Vprocess_alist
);
7890 staticpro (&deleted_pid_list
);
7892 #endif /* subprocesses */
7894 DEFSYM (QCname
, ":name");
7895 DEFSYM (QCtype
, ":type");
7897 DEFSYM (Qeuid
, "euid");
7898 DEFSYM (Qegid
, "egid");
7899 DEFSYM (Quser
, "user");
7900 DEFSYM (Qgroup
, "group");
7901 DEFSYM (Qcomm
, "comm");
7902 DEFSYM (Qstate
, "state");
7903 DEFSYM (Qppid
, "ppid");
7904 DEFSYM (Qpgrp
, "pgrp");
7905 DEFSYM (Qsess
, "sess");
7906 DEFSYM (Qttname
, "ttname");
7907 DEFSYM (Qtpgid
, "tpgid");
7908 DEFSYM (Qminflt
, "minflt");
7909 DEFSYM (Qmajflt
, "majflt");
7910 DEFSYM (Qcminflt
, "cminflt");
7911 DEFSYM (Qcmajflt
, "cmajflt");
7912 DEFSYM (Qutime
, "utime");
7913 DEFSYM (Qstime
, "stime");
7914 DEFSYM (Qtime
, "time");
7915 DEFSYM (Qcutime
, "cutime");
7916 DEFSYM (Qcstime
, "cstime");
7917 DEFSYM (Qctime
, "ctime");
7919 DEFSYM (Qinternal_default_process_sentinel
,
7920 "internal-default-process-sentinel");
7921 DEFSYM (Qinternal_default_process_filter
,
7922 "internal-default-process-filter");
7924 DEFSYM (Qpri
, "pri");
7925 DEFSYM (Qnice
, "nice");
7926 DEFSYM (Qthcount
, "thcount");
7927 DEFSYM (Qstart
, "start");
7928 DEFSYM (Qvsize
, "vsize");
7929 DEFSYM (Qrss
, "rss");
7930 DEFSYM (Qetime
, "etime");
7931 DEFSYM (Qpcpu
, "pcpu");
7932 DEFSYM (Qpmem
, "pmem");
7933 DEFSYM (Qargs
, "args");
7935 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7936 doc
: /* Non-nil means delete processes immediately when they exit.
7937 A value of nil means don't delete them until `list-processes' is run. */);
7939 delete_exited_processes
= 1;
7942 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7943 doc
: /* Control type of device used to communicate with subprocesses.
7944 Values are nil to use a pipe, or t or `pty' to use a pty.
7945 The value has no effect if the system has no ptys or if all ptys are busy:
7946 then a pipe is used in any case.
7947 The value takes effect when `start-process' is called. */);
7948 Vprocess_connection_type
= Qt
;
7950 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7951 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7952 On some systems, when Emacs reads the output from a subprocess, the output data
7953 is read in very small blocks, potentially resulting in very poor performance.
7954 This behavior can be remedied to some extent by setting this variable to a
7955 non-nil value, as it will automatically delay reading from such processes, to
7956 allow them to produce more output before Emacs tries to read it.
7957 If the value is t, the delay is reset after each write to the process; any other
7958 non-nil value means that the delay is not reset on write.
7959 The variable takes effect when `start-process' is called. */);
7960 Vprocess_adaptive_read_buffering
= Qt
;
7962 defsubr (&Sprocessp
);
7963 defsubr (&Sget_process
);
7964 defsubr (&Sdelete_process
);
7965 defsubr (&Sprocess_status
);
7966 defsubr (&Sprocess_exit_status
);
7967 defsubr (&Sprocess_id
);
7968 defsubr (&Sprocess_name
);
7969 defsubr (&Sprocess_tty_name
);
7970 defsubr (&Sprocess_command
);
7971 defsubr (&Sset_process_buffer
);
7972 defsubr (&Sprocess_buffer
);
7973 defsubr (&Sprocess_mark
);
7974 defsubr (&Sset_process_filter
);
7975 defsubr (&Sprocess_filter
);
7976 defsubr (&Sset_process_sentinel
);
7977 defsubr (&Sprocess_sentinel
);
7978 defsubr (&Sset_process_window_size
);
7979 defsubr (&Sset_process_inherit_coding_system_flag
);
7980 defsubr (&Sset_process_query_on_exit_flag
);
7981 defsubr (&Sprocess_query_on_exit_flag
);
7982 defsubr (&Sprocess_contact
);
7983 defsubr (&Sprocess_plist
);
7984 defsubr (&Sset_process_plist
);
7985 defsubr (&Sprocess_list
);
7986 defsubr (&Smake_process
);
7987 defsubr (&Smake_pipe_process
);
7988 defsubr (&Sserial_process_configure
);
7989 defsubr (&Smake_serial_process
);
7990 defsubr (&Sset_network_process_option
);
7991 defsubr (&Smake_network_process
);
7992 defsubr (&Sformat_network_address
);
7993 defsubr (&Snetwork_interface_list
);
7994 defsubr (&Snetwork_interface_info
);
7995 #ifdef DATAGRAM_SOCKETS
7996 defsubr (&Sprocess_datagram_address
);
7997 defsubr (&Sset_process_datagram_address
);
7999 defsubr (&Saccept_process_output
);
8000 defsubr (&Sprocess_send_region
);
8001 defsubr (&Sprocess_send_string
);
8002 defsubr (&Sinterrupt_process
);
8003 defsubr (&Skill_process
);
8004 defsubr (&Squit_process
);
8005 defsubr (&Sstop_process
);
8006 defsubr (&Scontinue_process
);
8007 defsubr (&Sprocess_running_child_p
);
8008 defsubr (&Sprocess_send_eof
);
8009 defsubr (&Ssignal_process
);
8010 defsubr (&Swaiting_for_user_input_p
);
8011 defsubr (&Sprocess_type
);
8012 defsubr (&Sinternal_default_process_sentinel
);
8013 defsubr (&Sinternal_default_process_filter
);
8014 defsubr (&Sset_process_coding_system
);
8015 defsubr (&Sprocess_coding_system
);
8016 defsubr (&Sset_process_filter_multibyte
);
8017 defsubr (&Sprocess_filter_multibyte_p
);
8019 #endif /* subprocesses */
8021 defsubr (&Sget_buffer_process
);
8022 defsubr (&Sprocess_inherit_coding_system_flag
);
8023 defsubr (&Slist_system_processes
);
8024 defsubr (&Sprocess_attributes
);
8027 Lisp_Object subfeatures
= Qnil
;
8028 const struct socket_options
*sopt
;
8030 #define ADD_SUBFEATURE(key, val) \
8031 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8033 ADD_SUBFEATURE (QCnowait
, Qt
);
8034 #ifdef DATAGRAM_SOCKETS
8035 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8037 #ifdef HAVE_SEQPACKET
8038 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8040 #ifdef HAVE_LOCAL_SOCKETS
8041 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8043 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8045 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8047 #ifdef HAVE_GETSOCKNAME
8048 ADD_SUBFEATURE (QCservice
, Qt
);
8050 ADD_SUBFEATURE (QCserver
, Qt
);
8052 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8053 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8055 Fprovide (intern_c_string ("make-network-process"), subfeatures
);