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 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
271 static Lisp_Object chan_process
[FD_SETSIZE
];
272 static void wait_for_socket_fds (Lisp_Object
, char const *);
274 /* Alist of elements (NAME . PROCESS). */
275 static Lisp_Object Vprocess_alist
;
277 /* Buffered-ahead input char from process, indexed by channel.
278 -1 means empty (no char is buffered).
279 Used on sys V where the only way to tell if there is any
280 output from the process is to read at least one char.
281 Always -1 on systems that support FIONREAD. */
283 static int proc_buffered_char
[FD_SETSIZE
];
285 /* Table of `struct coding-system' for each process. */
286 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
287 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
289 #ifdef DATAGRAM_SOCKETS
290 /* Table of `partner address' for datagram sockets. */
291 static struct sockaddr_and_len
{
294 } datagram_address
[FD_SETSIZE
];
295 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
296 #define DATAGRAM_CONN_P(proc) \
297 (PROCESSP (proc) && \
298 XPROCESS (proc)->infd >= 0 && \
299 datagram_address[XPROCESS (proc)->infd].sa != 0)
301 #define DATAGRAM_CHAN_P(chan) (0)
302 #define DATAGRAM_CONN_P(proc) (0)
305 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
306 a `for' loop which iterates over processes from Vprocess_alist. */
308 #define FOR_EACH_PROCESS(list_var, proc_var) \
309 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
311 /* These setters are used only in this file, so they can be private. */
313 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
318 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
323 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
325 p
->decode_coding_system
= val
;
328 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
330 p
->decoding_buf
= val
;
333 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
335 p
->encode_coding_system
= val
;
338 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
340 p
->encoding_buf
= val
;
343 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
345 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
348 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
353 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
358 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
363 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
368 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
370 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
373 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
383 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
385 p
->write_queue
= val
;
388 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
395 make_lisp_proc (struct Lisp_Process
*p
)
397 return make_lisp_ptr (p
, Lisp_Vectorlike
);
400 static struct fd_callback_data
406 int condition
; /* Mask of the defines above. */
407 } fd_callback_info
[FD_SETSIZE
];
410 /* Add a file descriptor FD to be monitored for when read is possible.
411 When read is possible, call FUNC with argument DATA. */
414 add_read_fd (int fd
, fd_callback func
, void *data
)
416 add_keyboard_wait_descriptor (fd
);
418 fd_callback_info
[fd
].func
= func
;
419 fd_callback_info
[fd
].data
= data
;
420 fd_callback_info
[fd
].condition
|= FOR_READ
;
423 /* Stop monitoring file descriptor FD for when read is possible. */
426 delete_read_fd (int fd
)
428 delete_keyboard_wait_descriptor (fd
);
430 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
431 if (fd_callback_info
[fd
].condition
== 0)
433 fd_callback_info
[fd
].func
= 0;
434 fd_callback_info
[fd
].data
= 0;
438 /* Add a file descriptor FD to be monitored for when write is possible.
439 When write is possible, call FUNC with argument DATA. */
442 add_write_fd (int fd
, fd_callback func
, void *data
)
444 FD_SET (fd
, &write_mask
);
445 if (fd
> max_input_desc
)
448 fd_callback_info
[fd
].func
= func
;
449 fd_callback_info
[fd
].data
= data
;
450 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
453 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
456 delete_input_desc (int fd
)
458 if (fd
== max_input_desc
)
462 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
463 || FD_ISSET (fd
, &write_mask
)));
469 /* Stop monitoring file descriptor FD for when write is possible. */
472 delete_write_fd (int fd
)
474 FD_CLR (fd
, &write_mask
);
475 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
476 if (fd_callback_info
[fd
].condition
== 0)
478 fd_callback_info
[fd
].func
= 0;
479 fd_callback_info
[fd
].data
= 0;
480 delete_input_desc (fd
);
485 /* Compute the Lisp form of the process status, p->status, from
486 the numeric status that was returned by `wait'. */
488 static Lisp_Object
status_convert (int);
491 update_status (struct Lisp_Process
*p
)
493 eassert (p
->raw_status_new
);
494 pset_status (p
, status_convert (p
->raw_status
));
495 p
->raw_status_new
= 0;
498 /* Convert a process status word in Unix format to
499 the list that we use internally. */
502 status_convert (int w
)
505 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
506 else if (WIFEXITED (w
))
507 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
508 WCOREDUMP (w
) ? Qt
: Qnil
));
509 else if (WIFSIGNALED (w
))
510 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
511 WCOREDUMP (w
) ? Qt
: Qnil
));
516 /* Given a status-list, extract the three pieces of information
517 and store them individually through the three pointers. */
520 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
534 *code
= XFASTINT (XCAR (tem
));
536 *coredump
= !NILP (tem
);
540 /* Return a string describing a process status list. */
543 status_message (struct Lisp_Process
*p
)
545 Lisp_Object status
= p
->status
;
551 decode_status (status
, &symbol
, &code
, &coredump
);
553 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
556 synchronize_system_messages_locale ();
557 signame
= strsignal (code
);
559 string
= build_string ("unknown");
564 string
= build_unibyte_string (signame
);
565 if (! NILP (Vlocale_coding_system
))
566 string
= (code_convert_string_norecord
567 (string
, Vlocale_coding_system
, 0));
568 c1
= STRING_CHAR (SDATA (string
));
571 Faset (string
, make_number (0), make_number (c2
));
573 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
574 return concat2 (string
, suffix
);
576 else if (EQ (symbol
, Qexit
))
579 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
581 return build_string ("finished\n");
582 AUTO_STRING (prefix
, "exited abnormally with code ");
583 string
= Fnumber_to_string (make_number (code
));
584 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
585 return concat3 (prefix
, string
, suffix
);
587 else if (EQ (symbol
, Qfailed
))
589 AUTO_STRING (prefix
, "failed with code ");
590 string
= Fnumber_to_string (make_number (code
));
591 AUTO_STRING (suffix
, "\n");
592 return concat3 (prefix
, string
, suffix
);
595 return Fcopy_sequence (Fsymbol_name (symbol
));
598 enum { PTY_NAME_SIZE
= 24 };
600 /* Open an available pty, returning a file descriptor.
601 Store into PTY_NAME the file name of the terminal corresponding to the pty.
602 Return -1 on failure. */
605 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
614 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
615 for (i
= 0; i
< 16; i
++)
618 #ifdef PTY_NAME_SPRINTF
621 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
622 #endif /* no PTY_NAME_SPRINTF */
626 #else /* no PTY_OPEN */
627 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
628 #endif /* no PTY_OPEN */
632 #ifdef PTY_TTY_NAME_SPRINTF
635 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
636 #endif /* no PTY_TTY_NAME_SPRINTF */
638 /* Set FD's close-on-exec flag. This is needed even if
639 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
640 doesn't require support for that combination.
641 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
642 doesn't work if the close-on-exec flag is set (Bug#20555).
643 Multithreaded platforms where posix_openpt ignores
644 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
645 have a race condition between the PTY_OPEN and here. */
646 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
648 /* Check to make certain that both sides are available.
649 This avoids a nasty yet stupid bug in rlogins. */
650 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
663 #endif /* HAVE_PTYS */
667 /* Allocate basically initialized process. */
669 static struct Lisp_Process
*
670 allocate_process (void)
672 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
676 make_process (Lisp_Object name
)
678 register Lisp_Object val
, tem
, name1
;
679 register struct Lisp_Process
*p
;
680 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
683 p
= allocate_process ();
684 /* Initialize Lisp data. Note that allocate_process initializes all
685 Lisp data to nil, so do it only for slots which should not be nil. */
686 pset_status (p
, Qrun
);
687 pset_mark (p
, Fmake_marker ());
689 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
690 non-Lisp data, so do it only for slots which should not be zero. */
693 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
697 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
698 p
->gnutls_boot_parameters
= Qnil
;
701 /* If name is already in use, modify it until it is unused. */
706 tem
= Fget_process (name1
);
707 if (NILP (tem
)) break;
708 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
712 pset_sentinel (p
, Qinternal_default_process_sentinel
);
713 pset_filter (p
, Qinternal_default_process_filter
);
714 XSETPROCESS (val
, p
);
715 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
720 remove_process (register Lisp_Object proc
)
722 register Lisp_Object pair
;
724 pair
= Frassq (proc
, Vprocess_alist
);
725 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
727 deactivate_process (proc
);
730 #ifdef HAVE_GETADDRINFO_A
732 free_dns_request (Lisp_Object proc
)
734 struct Lisp_Process
*p
= XPROCESS (proc
);
736 if (p
->dns_request
->ar_result
)
737 freeaddrinfo (p
->dns_request
->ar_result
);
738 xfree (p
->dns_request
);
739 p
->dns_request
= NULL
;
744 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
745 doc
: /* Return t if OBJECT is a process. */)
748 return PROCESSP (object
) ? Qt
: Qnil
;
751 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
752 doc
: /* Return the process named NAME, or nil if there is none. */)
753 (register Lisp_Object name
)
758 return Fcdr (Fassoc (name
, Vprocess_alist
));
761 /* This is how commands for the user decode process arguments. It
762 accepts a process, a process name, a buffer, a buffer name, or nil.
763 Buffers denote the first process in the buffer, and nil denotes the
767 get_process (register Lisp_Object name
)
769 register Lisp_Object proc
, obj
;
772 obj
= Fget_process (name
);
774 obj
= Fget_buffer (name
);
776 error ("Process %s does not exist", SDATA (name
));
778 else if (NILP (name
))
779 obj
= Fcurrent_buffer ();
783 /* Now obj should be either a buffer object or a process object. */
786 if (NILP (BVAR (XBUFFER (obj
), name
)))
787 error ("Attempt to get process for a dead buffer");
788 proc
= Fget_buffer_process (obj
);
790 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
801 /* Fdelete_process promises to immediately forget about the process, but in
802 reality, Emacs needs to remember those processes until they have been
803 treated by the SIGCHLD handler and waitpid has been invoked on them;
804 otherwise they might fill up the kernel's process table.
806 Some processes created by call-process are also put onto this list.
808 Members of this list are (process-ID . filename) pairs. The
809 process-ID is a number; the filename, if a string, is a file that
810 needs to be removed after the process exits. */
811 static Lisp_Object deleted_pid_list
;
814 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
816 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
817 /* GC treated elements set to nil. */
818 Fdelq (Qnil
, deleted_pid_list
));
822 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
823 doc
: /* Delete PROCESS: kill it and forget about it immediately.
824 PROCESS may be a process, a buffer, the name of a process or buffer, or
825 nil, indicating the current buffer's process. */)
826 (register Lisp_Object process
)
828 register struct Lisp_Process
*p
;
830 process
= get_process (process
);
831 p
= XPROCESS (process
);
833 #ifdef HAVE_GETADDRINFO_A
836 /* Cancel the request. Unless shutting down, wait until
837 completion. Free the request if completely canceled. */
839 bool canceled
= gai_cancel (p
->dns_request
) != EAI_NOTCANCELED
;
840 if (!canceled
&& !inhibit_sentinels
)
842 struct gaicb
const *req
= p
->dns_request
;
843 while (gai_suspend (&req
, 1, NULL
) != 0)
848 free_dns_request (process
);
852 p
->raw_status_new
= 0;
853 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
855 pset_status (p
, list2 (Qexit
, make_number (0)));
856 p
->tick
= ++process_tick
;
857 status_notify (p
, NULL
);
858 redisplay_preserve_echo_area (13);
863 record_kill_process (p
, Qnil
);
867 /* Update P's status, since record_kill_process will make the
868 SIGCHLD handler update deleted_pid_list, not *P. */
870 if (p
->raw_status_new
)
872 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
873 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
874 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
876 p
->tick
= ++process_tick
;
877 status_notify (p
, NULL
);
878 redisplay_preserve_echo_area (13);
881 remove_process (process
);
885 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
886 doc
: /* Return the status of PROCESS.
887 The returned value is one of the following symbols:
888 run -- for a process that is running.
889 stop -- for a process stopped but continuable.
890 exit -- for a process that has exited.
891 signal -- for a process that has got a fatal signal.
892 open -- for a network stream connection that is open.
893 listen -- for a network stream server that is listening.
894 closed -- for a network stream connection that is closed.
895 connect -- when waiting for a non-blocking connection to complete.
896 failed -- when a non-blocking connection has failed.
897 nil -- if arg is a process name and no such process exists.
898 PROCESS may be a process, a buffer, the name of a process, or
899 nil, indicating the current buffer's process. */)
900 (register Lisp_Object process
)
902 register struct Lisp_Process
*p
;
903 register Lisp_Object status
;
905 if (STRINGP (process
))
906 process
= Fget_process (process
);
908 process
= get_process (process
);
913 p
= XPROCESS (process
);
914 if (p
->raw_status_new
)
918 status
= XCAR (status
);
919 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
921 if (EQ (status
, Qexit
))
923 else if (EQ (p
->command
, Qt
))
925 else if (EQ (status
, Qrun
))
931 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
933 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
934 If PROCESS has not yet exited or died, return 0. */)
935 (register Lisp_Object process
)
937 CHECK_PROCESS (process
);
938 if (XPROCESS (process
)->raw_status_new
)
939 update_status (XPROCESS (process
));
940 if (CONSP (XPROCESS (process
)->status
))
941 return XCAR (XCDR (XPROCESS (process
)->status
));
942 return make_number (0);
945 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
946 doc
: /* Return the process id of PROCESS.
947 This is the pid of the external process which PROCESS uses or talks to.
948 For a network connection, this value is nil. */)
949 (register Lisp_Object process
)
953 CHECK_PROCESS (process
);
954 pid
= XPROCESS (process
)->pid
;
955 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
958 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
959 doc
: /* Return the name of PROCESS, as a string.
960 This is the name of the program invoked in PROCESS,
961 possibly modified to make it unique among process names. */)
962 (register Lisp_Object process
)
964 CHECK_PROCESS (process
);
965 return XPROCESS (process
)->name
;
968 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
969 doc
: /* Return the command that was executed to start PROCESS.
970 This is a list of strings, the first string being the program executed
971 and the rest of the strings being the arguments given to it.
972 For a network or serial process, this is nil (process is running) or t
973 \(process is stopped). */)
974 (register Lisp_Object process
)
976 CHECK_PROCESS (process
);
977 return XPROCESS (process
)->command
;
980 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
981 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
982 This is the terminal that the process itself reads and writes on,
983 not the name of the pty that Emacs uses to talk with that terminal. */)
984 (register Lisp_Object process
)
986 CHECK_PROCESS (process
);
987 return XPROCESS (process
)->tty_name
;
990 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
992 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
994 (register Lisp_Object process
, Lisp_Object buffer
)
996 struct Lisp_Process
*p
;
998 CHECK_PROCESS (process
);
1000 CHECK_BUFFER (buffer
);
1001 p
= XPROCESS (process
);
1002 pset_buffer (p
, buffer
);
1003 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1004 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1005 setup_process_coding_systems (process
);
1009 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1011 doc
: /* Return the buffer PROCESS is associated with.
1012 The default process filter inserts output from PROCESS into this buffer. */)
1013 (register Lisp_Object process
)
1015 CHECK_PROCESS (process
);
1016 return XPROCESS (process
)->buffer
;
1019 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1021 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1022 (register Lisp_Object process
)
1024 CHECK_PROCESS (process
);
1025 return XPROCESS (process
)->mark
;
1029 set_process_filter_masks (struct Lisp_Process
*p
)
1031 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1033 FD_CLR (p
->infd
, &input_wait_mask
);
1034 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1036 else if (EQ (p
->filter
, Qt
)
1037 /* Network or serial process not stopped: */
1038 && !EQ (p
->command
, Qt
))
1040 FD_SET (p
->infd
, &input_wait_mask
);
1041 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1045 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1047 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1048 A value of t means stop accepting output from the process.
1050 When a process has a non-default filter, its buffer is not used for output.
1051 Instead, each time it does output, the entire string of output is
1052 passed to the filter.
1054 The filter gets two arguments: the process and the string of output.
1055 The string argument is normally a multibyte string, except:
1056 - if the process's input coding system is no-conversion or raw-text,
1057 it is a unibyte string (the non-converted input), or else
1058 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1059 string (the result of converting the decoded input multibyte
1060 string to unibyte with `string-make-unibyte'). */)
1061 (Lisp_Object process
, Lisp_Object filter
)
1063 CHECK_PROCESS (process
);
1064 struct Lisp_Process
*p
= XPROCESS (process
);
1066 /* Don't signal an error if the process's input file descriptor
1067 is closed. This could make debugging Lisp more difficult,
1068 for example when doing something like
1070 (setq process (start-process ...))
1072 (set-process-filter process ...) */
1075 filter
= Qinternal_default_process_filter
;
1077 pset_filter (p
, filter
);
1080 set_process_filter_masks (p
);
1082 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1083 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1084 setup_process_coding_systems (process
);
1088 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1090 doc
: /* Return the filter function of PROCESS.
1091 See `set-process-filter' for more info on filter functions. */)
1092 (register Lisp_Object process
)
1094 CHECK_PROCESS (process
);
1095 return XPROCESS (process
)->filter
;
1098 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1100 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1101 The sentinel is called as a function when the process changes state.
1102 It gets two arguments: the process, and a string describing the change. */)
1103 (register Lisp_Object process
, Lisp_Object sentinel
)
1105 struct Lisp_Process
*p
;
1107 CHECK_PROCESS (process
);
1108 p
= XPROCESS (process
);
1110 if (NILP (sentinel
))
1111 sentinel
= Qinternal_default_process_sentinel
;
1113 pset_sentinel (p
, sentinel
);
1114 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1115 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1119 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1121 doc
: /* Return the sentinel of PROCESS.
1122 See `set-process-sentinel' for more info on sentinels. */)
1123 (register Lisp_Object process
)
1125 CHECK_PROCESS (process
);
1126 return XPROCESS (process
)->sentinel
;
1129 DEFUN ("set-process-window-size", Fset_process_window_size
,
1130 Sset_process_window_size
, 3, 3, 0,
1131 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1132 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1134 CHECK_PROCESS (process
);
1136 /* All known platforms store window sizes as 'unsigned short'. */
1137 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1138 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1140 if (NETCONN_P (process
)
1141 || XPROCESS (process
)->infd
< 0
1142 || (set_window_size (XPROCESS (process
)->infd
,
1143 XINT (height
), XINT (width
))
1150 DEFUN ("set-process-inherit-coding-system-flag",
1151 Fset_process_inherit_coding_system_flag
,
1152 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1153 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1154 If the second argument FLAG is non-nil, then the variable
1155 `buffer-file-coding-system' of the buffer associated with PROCESS
1156 will be bound to the value of the coding system used to decode
1159 This is useful when the coding system specified for the process buffer
1160 leaves either the character code conversion or the end-of-line conversion
1161 unspecified, or if the coding system used to decode the process output
1162 is more appropriate for saving the process buffer.
1164 Binding the variable `inherit-process-coding-system' to non-nil before
1165 starting the process is an alternative way of setting the inherit flag
1166 for the process which will run.
1168 This function returns FLAG. */)
1169 (register Lisp_Object process
, Lisp_Object flag
)
1171 CHECK_PROCESS (process
);
1172 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1176 DEFUN ("set-process-query-on-exit-flag",
1177 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1179 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1180 If the second argument FLAG is non-nil, Emacs will query the user before
1181 exiting or killing a buffer if PROCESS is running. This function
1183 (register Lisp_Object process
, Lisp_Object flag
)
1185 CHECK_PROCESS (process
);
1186 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1190 DEFUN ("process-query-on-exit-flag",
1191 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1193 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1194 (register Lisp_Object process
)
1196 CHECK_PROCESS (process
);
1197 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1200 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1202 doc
: /* Return the contact info of PROCESS; t for a real child.
1203 For a network or serial connection, the value depends on the optional
1204 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1205 SERVICE) for a network connection or (PORT SPEED) for a serial
1206 connection. If KEY is t, the complete contact information for the
1207 connection is returned, else the specific value for the keyword KEY is
1208 returned. See `make-network-process' or `make-serial-process' for a
1210 If PROCESS is a non-blocking network process that hasn't been fully
1211 set up yet, this function will block until socket setup has completed. */)
1212 (Lisp_Object process
, Lisp_Object key
)
1214 Lisp_Object contact
;
1216 CHECK_PROCESS (process
);
1217 contact
= XPROCESS (process
)->childp
;
1219 #ifdef DATAGRAM_SOCKETS
1221 if (NETCONN_P (process
))
1222 wait_for_socket_fds (process
, "process-contact");
1224 if (DATAGRAM_CONN_P (process
)
1225 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1226 contact
= Fplist_put (contact
, QCremote
,
1227 Fprocess_datagram_address (process
));
1230 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1233 if (NILP (key
) && NETCONN_P (process
))
1234 return list2 (Fplist_get (contact
, QChost
),
1235 Fplist_get (contact
, QCservice
));
1236 if (NILP (key
) && SERIALCONN_P (process
))
1237 return list2 (Fplist_get (contact
, QCport
),
1238 Fplist_get (contact
, QCspeed
));
1239 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1240 if the pipe process is useful for purposes other than receiving
1242 if (NILP (key
) && PIPECONN_P (process
))
1244 return Fplist_get (contact
, key
);
1247 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1249 doc
: /* Return the plist of PROCESS. */)
1250 (register Lisp_Object process
)
1252 CHECK_PROCESS (process
);
1253 return XPROCESS (process
)->plist
;
1256 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1258 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1259 (Lisp_Object process
, Lisp_Object plist
)
1261 CHECK_PROCESS (process
);
1264 pset_plist (XPROCESS (process
), plist
);
1268 #if 0 /* Turned off because we don't currently record this info
1269 in the process. Perhaps add it. */
1270 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1271 doc
: /* Return the connection type of PROCESS.
1272 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1273 a socket connection. */)
1274 (Lisp_Object process
)
1276 return XPROCESS (process
)->type
;
1280 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1281 doc
: /* Return the connection type of PROCESS.
1282 The value is either the symbol `real', `network', or `serial'.
1283 PROCESS may be a process, a buffer, the name of a process or buffer, or
1284 nil, indicating the current buffer's process. */)
1285 (Lisp_Object process
)
1288 proc
= get_process (process
);
1289 return XPROCESS (proc
)->type
;
1292 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1294 doc
: /* Convert network ADDRESS from internal format to a string.
1295 A 4 or 5 element vector represents an IPv4 address (with port number).
1296 An 8 or 9 element vector represents an IPv6 address (with port number).
1297 If optional second argument OMIT-PORT is non-nil, don't include a port
1298 number in the string, even when present in ADDRESS.
1299 Return nil if format of ADDRESS is invalid. */)
1300 (Lisp_Object address
, Lisp_Object omit_port
)
1305 if (STRINGP (address
)) /* AF_LOCAL */
1308 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1310 register struct Lisp_Vector
*p
= XVECTOR (address
);
1311 ptrdiff_t size
= p
->header
.size
;
1312 Lisp_Object args
[10];
1316 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1318 format
= "%d.%d.%d.%d";
1323 format
= "%d.%d.%d.%d:%d";
1326 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1328 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1333 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1339 AUTO_STRING (format_obj
, format
);
1340 args
[0] = format_obj
;
1342 for (i
= 0; i
< nargs
; i
++)
1344 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1347 if (nargs
<= 5 /* IPv4 */
1348 && i
< 4 /* host, not port */
1349 && XINT (p
->contents
[i
]) > 255)
1352 args
[i
+ 1] = p
->contents
[i
];
1355 return Fformat (nargs
+ 1, args
);
1358 if (CONSP (address
))
1360 AUTO_STRING (format
, "<Family %d>");
1361 return CALLN (Fformat
, format
, Fcar (address
));
1367 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1368 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1371 return Fmapcar (Qcdr
, Vprocess_alist
);
1374 /* Starting asynchronous inferior processes. */
1376 static void start_process_unwind (Lisp_Object proc
);
1378 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1379 doc
: /* Start a program in a subprocess. Return the process object for it.
1381 This is similar to `start-process', but arguments are specified as
1382 keyword/argument pairs. The following arguments are defined:
1384 :name NAME -- NAME is name for process. It is modified if necessary
1387 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1388 with the process. Process output goes at end of that buffer, unless
1389 you specify an output stream or filter function to handle the output.
1390 BUFFER may be also nil, meaning that this process is not associated
1393 :command COMMAND -- COMMAND is a list starting with the program file
1394 name, followed by strings to give to the program as arguments.
1396 :coding CODING -- If CODING is a symbol, it specifies the coding
1397 system used for both reading and writing for this process. If CODING
1398 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1399 ENCODING is used for writing.
1401 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1402 the process is running. If BOOL is not given, query before exiting.
1404 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1405 In the stopped state, a process does not accept incoming data, but you
1406 can send outgoing data. The stopped state is cleared by
1407 `continue-process' and set by `stop-process'.
1409 :connection-type TYPE -- TYPE is control type of device used to
1410 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1411 to use a pty, or nil to use the default specified through
1412 `process-connection-type'.
1414 :filter FILTER -- Install FILTER as the process filter.
1416 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1418 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1419 to the standard error of subprocess. Specifying this implies
1420 `:connection-type' is set to `pipe'.
1422 usage: (make-process &rest ARGS) */)
1423 (ptrdiff_t nargs
, Lisp_Object
*args
)
1425 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1426 Lisp_Object xstderr
, stderrproc
;
1427 ptrdiff_t count
= SPECPDL_INDEX ();
1433 /* Save arguments for process-contact and clone-process. */
1434 contact
= Flist (nargs
, args
);
1436 buffer
= Fplist_get (contact
, QCbuffer
);
1438 buffer
= Fget_buffer_create (buffer
);
1440 /* Make sure that the child will be able to chdir to the current
1441 buffer's current directory, or its unhandled equivalent. We
1442 can't just have the child check for an error when it does the
1443 chdir, since it's in a vfork. */
1444 current_dir
= encode_current_directory ();
1446 name
= Fplist_get (contact
, QCname
);
1447 CHECK_STRING (name
);
1449 command
= Fplist_get (contact
, QCcommand
);
1450 if (CONSP (command
))
1451 program
= XCAR (command
);
1455 if (!NILP (program
))
1456 CHECK_STRING (program
);
1459 xstderr
= Fplist_get (contact
, QCstderr
);
1460 if (PROCESSP (xstderr
))
1462 if (!PIPECONN_P (xstderr
))
1463 error ("Process is not a pipe process");
1464 stderrproc
= xstderr
;
1466 else if (!NILP (xstderr
))
1468 CHECK_STRING (program
);
1469 stderrproc
= CALLN (Fmake_pipe_process
,
1471 concat2 (name
, build_string (" stderr")),
1473 Fget_buffer_create (xstderr
));
1476 proc
= make_process (name
);
1477 /* If an error occurs and we can't start the process, we want to
1478 remove it from the process list. This means that each error
1479 check in create_process doesn't need to call remove_process
1480 itself; it's all taken care of here. */
1481 record_unwind_protect (start_process_unwind
, proc
);
1483 pset_childp (XPROCESS (proc
), Qt
);
1484 pset_plist (XPROCESS (proc
), Qnil
);
1485 pset_type (XPROCESS (proc
), Qreal
);
1486 pset_buffer (XPROCESS (proc
), buffer
);
1487 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1488 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1489 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1491 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1492 XPROCESS (proc
)->kill_without_query
= 1;
1493 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1494 pset_command (XPROCESS (proc
), Qt
);
1496 tem
= Fplist_get (contact
, QCconnection_type
);
1498 XPROCESS (proc
)->pty_flag
= true;
1499 else if (EQ (tem
, Qpipe
))
1500 XPROCESS (proc
)->pty_flag
= false;
1501 else if (NILP (tem
))
1502 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1504 report_file_error ("Unknown connection type", tem
);
1506 if (!NILP (stderrproc
))
1508 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1510 XPROCESS (proc
)->pty_flag
= false;
1514 /* AKA GNUTLS_INITSTAGE(proc). */
1515 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1516 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1519 XPROCESS (proc
)->adaptive_read_buffering
1520 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1521 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1523 /* Make the process marker point into the process buffer (if any). */
1524 if (BUFFERP (buffer
))
1525 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1526 BUF_ZV (XBUFFER (buffer
)),
1527 BUF_ZV_BYTE (XBUFFER (buffer
)));
1530 /* Decide coding systems for communicating with the process. Here
1531 we don't setup the structure coding_system nor pay attention to
1532 unibyte mode. They are done in create_process. */
1534 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1535 Lisp_Object coding_systems
= Qt
;
1536 Lisp_Object val
, *args2
;
1538 tem
= Fplist_get (contact
, QCcoding
);
1546 val
= Vcoding_system_for_read
;
1549 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1551 SAFE_ALLOCA_LISP (args2
, nargs2
);
1553 args2
[i
++] = Qstart_process
;
1555 args2
[i
++] = buffer
;
1556 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1557 args2
[i
++] = XCAR (tem2
);
1558 if (!NILP (program
))
1559 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1560 if (CONSP (coding_systems
))
1561 val
= XCAR (coding_systems
);
1562 else if (CONSP (Vdefault_process_coding_system
))
1563 val
= XCAR (Vdefault_process_coding_system
);
1565 pset_decode_coding_system (XPROCESS (proc
), val
);
1574 val
= Vcoding_system_for_write
;
1577 if (EQ (coding_systems
, Qt
))
1579 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1581 SAFE_ALLOCA_LISP (args2
, nargs2
);
1583 args2
[i
++] = Qstart_process
;
1585 args2
[i
++] = buffer
;
1586 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1587 args2
[i
++] = XCAR (tem2
);
1588 if (!NILP (program
))
1589 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1591 if (CONSP (coding_systems
))
1592 val
= XCDR (coding_systems
);
1593 else if (CONSP (Vdefault_process_coding_system
))
1594 val
= XCDR (Vdefault_process_coding_system
);
1596 pset_encode_coding_system (XPROCESS (proc
), val
);
1597 /* Note: At this moment, the above coding system may leave
1598 text-conversion or eol-conversion unspecified. They will be
1599 decided after we read output from the process and decode it by
1600 some coding system, or just before we actually send a text to
1605 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1606 XPROCESS (proc
)->decoding_carryover
= 0;
1607 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1609 XPROCESS (proc
)->inherit_coding_system_flag
1610 = !(NILP (buffer
) || !inherit_process_coding_system
);
1612 if (!NILP (program
))
1614 Lisp_Object program_args
= XCDR (command
);
1616 /* If program file name is not absolute, search our path for it.
1617 Put the name we will really use in TEM. */
1618 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1619 && !(SCHARS (program
) > 1
1620 && IS_DEVICE_SEP (SREF (program
, 1))))
1623 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1624 make_number (X_OK
), false);
1626 report_file_error ("Searching for program", program
);
1627 tem
= Fexpand_file_name (tem
, Qnil
);
1631 if (!NILP (Ffile_directory_p (program
)))
1632 error ("Specified program for new process is a directory");
1636 /* Remove "/:" from TEM. */
1637 tem
= remove_slash_colon (tem
);
1639 Lisp_Object arg_encoding
= Qnil
;
1641 /* Encode the file name and put it in NEW_ARGV.
1642 That's where the child will use it to execute the program. */
1643 tem
= list1 (ENCODE_FILE (tem
));
1644 ptrdiff_t new_argc
= 1;
1646 /* Here we encode arguments by the coding system used for sending
1647 data to the process. We don't support using different coding
1648 systems for encoding arguments and for encoding data sent to the
1651 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1653 Lisp_Object arg
= XCAR (tem2
);
1655 if (STRING_MULTIBYTE (arg
))
1657 if (NILP (arg_encoding
))
1658 arg_encoding
= (complement_process_encoding_system
1659 (XPROCESS (proc
)->encode_coding_system
));
1660 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1662 tem
= Fcons (arg
, tem
);
1666 /* Now that everything is encoded we can collect the strings into
1669 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1670 new_argv
[new_argc
] = 0;
1672 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1674 new_argv
[i
] = SSDATA (XCAR (tem
));
1678 create_process (proc
, new_argv
, current_dir
);
1684 return unbind_to (count
, proc
);
1687 /* This function is the unwind_protect form for Fstart_process. If
1688 PROC doesn't have its pid set, then we know someone has signaled
1689 an error and the process wasn't started successfully, so we should
1690 remove it from the process list. */
1692 start_process_unwind (Lisp_Object proc
)
1694 if (!PROCESSP (proc
))
1697 /* Was PROC started successfully?
1698 -2 is used for a pty with no process, eg for gdb. */
1699 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1700 remove_process (proc
);
1703 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1706 close_process_fd (int *fd_addr
)
1716 /* Indexes of file descriptors in open_fds. */
1719 /* The pipe from Emacs to its subprocess. */
1721 WRITE_TO_SUBPROCESS
,
1723 /* The main pipe from the subprocess to Emacs. */
1724 READ_FROM_SUBPROCESS
,
1727 /* The pipe from the subprocess to Emacs that is closed when the
1728 subprocess execs. */
1729 READ_FROM_EXEC_MONITOR
,
1733 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1736 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1738 struct Lisp_Process
*p
= XPROCESS (process
);
1739 int inchannel
, outchannel
;
1742 int forkin
, forkout
, forkerr
= -1;
1744 char pty_name
[PTY_NAME_SIZE
];
1745 Lisp_Object lisp_pty_name
= Qnil
;
1748 inchannel
= outchannel
= -1;
1751 outchannel
= inchannel
= allocate_pty (pty_name
);
1755 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1756 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1757 /* On most USG systems it does not work to open the pty's tty here,
1758 then close it and reopen it in the child. */
1759 /* Don't let this terminal become our controlling terminal
1760 (in case we don't have one). */
1761 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1763 report_file_error ("Opening pty", Qnil
);
1764 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1766 forkin
= forkout
= -1;
1767 #endif /* not USG, or USG_SUBTTY_WORKS */
1769 lisp_pty_name
= build_string (pty_name
);
1773 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1774 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1775 report_file_error ("Creating pipe", Qnil
);
1776 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1777 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1778 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1779 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1781 if (!NILP (p
->stderrproc
))
1783 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1785 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1787 /* Close unnecessary file descriptors. */
1788 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1789 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1794 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1795 report_file_error ("Creating pipe", Qnil
);
1798 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1799 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1801 /* Record this as an active process, with its channels. */
1802 chan_process
[inchannel
] = process
;
1803 p
->infd
= inchannel
;
1804 p
->outfd
= outchannel
;
1806 /* Previously we recorded the tty descriptor used in the subprocess.
1807 It was only used for getting the foreground tty process, so now
1808 we just reopen the device (see emacs_get_tty_pgrp) as this is
1809 more portable (see USG_SUBTTY_WORKS above). */
1811 p
->pty_flag
= pty_flag
;
1812 pset_status (p
, Qrun
);
1814 if (!EQ (p
->command
, Qt
))
1816 FD_SET (inchannel
, &input_wait_mask
);
1817 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1820 if (inchannel
> max_process_desc
)
1821 max_process_desc
= inchannel
;
1823 /* This may signal an error. */
1824 setup_process_coding_systems (process
);
1827 block_child_signal (&oldset
);
1830 /* vfork, and prevent local vars from being clobbered by the vfork. */
1831 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1832 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1833 char **volatile new_argv_volatile
= new_argv
;
1834 int volatile forkin_volatile
= forkin
;
1835 int volatile forkout_volatile
= forkout
;
1836 int volatile forkerr_volatile
= forkerr
;
1837 struct Lisp_Process
*p_volatile
= p
;
1841 current_dir
= current_dir_volatile
;
1842 lisp_pty_name
= lisp_pty_name_volatile
;
1843 new_argv
= new_argv_volatile
;
1844 forkin
= forkin_volatile
;
1845 forkout
= forkout_volatile
;
1846 forkerr
= forkerr_volatile
;
1849 pty_flag
= p
->pty_flag
;
1852 #endif /* not WINDOWSNT */
1854 /* Make the pty be the controlling terminal of the process. */
1856 /* First, disconnect its current controlling terminal. */
1857 /* We tried doing setsid only if pty_flag, but it caused
1858 process_set_signal to fail on SGI when using a pipe. */
1860 /* Make the pty's terminal the controlling terminal. */
1861 if (pty_flag
&& forkin
>= 0)
1864 /* We ignore the return value
1865 because faith@cs.unc.edu says that is necessary on Linux. */
1866 ioctl (forkin
, TIOCSCTTY
, 0);
1869 #if defined (LDISC1)
1870 if (pty_flag
&& forkin
>= 0)
1873 tcgetattr (forkin
, &t
);
1875 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1876 emacs_perror ("create_process/tcsetattr LDISC1");
1879 #if defined (NTTYDISC) && defined (TIOCSETD)
1880 if (pty_flag
&& forkin
>= 0)
1882 /* Use new line discipline. */
1883 int ldisc
= NTTYDISC
;
1884 ioctl (forkin
, TIOCSETD
, &ldisc
);
1889 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1890 can do TIOCSPGRP only to the process's controlling tty. */
1893 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1894 I can't test it since I don't have 4.3. */
1895 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1898 ioctl (j
, TIOCNOTTY
, 0);
1902 #endif /* TIOCNOTTY */
1904 #if !defined (DONT_REOPEN_PTY)
1905 /*** There is a suggestion that this ought to be a
1906 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1907 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1908 that system does seem to need this code, even though
1909 both TIOCSCTTY is defined. */
1910 /* Now close the pty (if we had it open) and reopen it.
1911 This makes the pty the controlling terminal of the subprocess. */
1915 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1918 emacs_close (forkin
);
1919 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1923 emacs_perror (SSDATA (lisp_pty_name
));
1924 _exit (EXIT_CANCELED
);
1928 #endif /* not DONT_REOPEN_PTY */
1930 #ifdef SETUP_SLAVE_PTY
1935 #endif /* SETUP_SLAVE_PTY */
1936 #endif /* HAVE_PTYS */
1938 signal (SIGINT
, SIG_DFL
);
1939 signal (SIGQUIT
, SIG_DFL
);
1941 signal (SIGPROF
, SIG_DFL
);
1944 /* Emacs ignores SIGPIPE, but the child should not. */
1945 signal (SIGPIPE
, SIG_DFL
);
1947 /* Stop blocking SIGCHLD in the child. */
1948 unblock_child_signal (&oldset
);
1951 child_setup_tty (forkout
);
1956 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1957 #else /* not WINDOWSNT */
1958 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1959 #endif /* not WINDOWSNT */
1962 /* Back in the parent process. */
1964 vfork_errno
= errno
;
1969 /* Stop blocking in the parent. */
1970 unblock_child_signal (&oldset
);
1974 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1977 /* vfork succeeded. */
1979 /* Close the pipe ends that the child uses, or the child's pty. */
1980 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1981 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1984 register_child (pid
, inchannel
);
1985 #endif /* WINDOWSNT */
1987 pset_tty_name (p
, lisp_pty_name
);
1990 /* Wait for child_setup to complete in case that vfork is
1991 actually defined as fork. The descriptor
1992 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1993 of a pipe is closed at the child side either by close-on-exec
1994 on successful execve or the _exit call in child_setup. */
1998 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1999 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2000 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2003 if (!NILP (p
->stderrproc
))
2005 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2006 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2012 create_pty (Lisp_Object process
)
2014 struct Lisp_Process
*p
= XPROCESS (process
);
2015 char pty_name
[PTY_NAME_SIZE
];
2016 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2020 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2021 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2022 /* On most USG systems it does not work to open the pty's tty here,
2023 then close it and reopen it in the child. */
2024 /* Don't let this terminal become our controlling terminal
2025 (in case we don't have one). */
2026 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2028 report_file_error ("Opening pty", Qnil
);
2029 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2030 #if defined (DONT_REOPEN_PTY)
2031 /* In the case that vfork is defined as fork, the parent process
2032 (Emacs) may send some data before the child process completes
2033 tty options setup. So we setup tty before forking. */
2034 child_setup_tty (forkout
);
2035 #endif /* DONT_REOPEN_PTY */
2036 #endif /* not USG, or USG_SUBTTY_WORKS */
2038 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2040 /* Record this as an active process, with its channels.
2041 As a result, child_setup will close Emacs's side of the pipes. */
2042 chan_process
[pty_fd
] = process
;
2046 /* Previously we recorded the tty descriptor used in the subprocess.
2047 It was only used for getting the foreground tty process, so now
2048 we just reopen the device (see emacs_get_tty_pgrp) as this is
2049 more portable (see USG_SUBTTY_WORKS above). */
2052 pset_status (p
, Qrun
);
2053 setup_process_coding_systems (process
);
2055 FD_SET (pty_fd
, &input_wait_mask
);
2056 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2057 if (pty_fd
> max_process_desc
)
2058 max_process_desc
= pty_fd
;
2060 pset_tty_name (p
, build_string (pty_name
));
2066 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2068 doc
: /* Create and return a bidirectional pipe process.
2070 In Emacs, pipes are represented by process objects, so input and
2071 output work as for subprocesses, and `delete-process' closes a pipe.
2072 However, a pipe process has no process id, it cannot be signaled,
2073 and the status codes are different from normal processes.
2075 Arguments are specified as keyword/argument pairs. The following
2076 arguments are defined:
2078 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2080 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2081 with the process. Process output goes at the end of that buffer,
2082 unless you specify an output stream or filter function to handle the
2083 output. If BUFFER is not given, the value of NAME is used.
2085 :coding CODING -- If CODING is a symbol, it specifies the coding
2086 system used for both reading and writing for this process. If CODING
2087 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2088 ENCODING is used for writing.
2090 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2091 the process is running. If BOOL is not given, query before exiting.
2093 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2094 In the stopped state, a pipe process does not accept incoming data,
2095 but you can send outgoing data. The stopped state is cleared by
2096 `continue-process' and set by `stop-process'.
2098 :filter FILTER -- Install FILTER as the process filter.
2100 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2102 usage: (make-pipe-process &rest ARGS) */)
2103 (ptrdiff_t nargs
, Lisp_Object
*args
)
2105 Lisp_Object proc
, contact
;
2106 struct Lisp_Process
*p
;
2107 Lisp_Object name
, buffer
;
2109 ptrdiff_t specpdl_count
;
2110 int inchannel
, outchannel
;
2115 contact
= Flist (nargs
, args
);
2117 name
= Fplist_get (contact
, QCname
);
2118 CHECK_STRING (name
);
2119 proc
= make_process (name
);
2120 specpdl_count
= SPECPDL_INDEX ();
2121 record_unwind_protect (remove_process
, proc
);
2122 p
= XPROCESS (proc
);
2124 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2125 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2126 report_file_error ("Creating pipe", Qnil
);
2127 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2128 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2130 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2131 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2134 register_aux_fd (inchannel
);
2137 /* Record this as an active process, with its channels. */
2138 chan_process
[inchannel
] = proc
;
2139 p
->infd
= inchannel
;
2140 p
->outfd
= outchannel
;
2142 if (inchannel
> max_process_desc
)
2143 max_process_desc
= inchannel
;
2145 buffer
= Fplist_get (contact
, QCbuffer
);
2148 buffer
= Fget_buffer_create (buffer
);
2149 pset_buffer (p
, buffer
);
2151 pset_childp (p
, contact
);
2152 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2153 pset_type (p
, Qpipe
);
2154 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2155 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2157 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2158 p
->kill_without_query
= 1;
2159 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2160 pset_command (p
, Qt
);
2161 eassert (! p
->pty_flag
);
2163 if (!EQ (p
->command
, Qt
))
2165 FD_SET (inchannel
, &input_wait_mask
);
2166 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2168 p
->adaptive_read_buffering
2169 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2170 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2172 /* Make the process marker point into the process buffer (if any). */
2173 if (BUFFERP (buffer
))
2174 set_marker_both (p
->mark
, buffer
,
2175 BUF_ZV (XBUFFER (buffer
)),
2176 BUF_ZV_BYTE (XBUFFER (buffer
)));
2179 /* Setup coding systems for communicating with the network stream. */
2181 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2182 Lisp_Object coding_systems
= Qt
;
2185 tem
= Fplist_get (contact
, QCcoding
);
2193 else if (!NILP (Vcoding_system_for_read
))
2194 val
= Vcoding_system_for_read
;
2195 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2196 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2197 /* We dare not decode end-of-line format by setting VAL to
2198 Qraw_text, because the existing Emacs Lisp libraries
2199 assume that they receive bare code including a sequence of
2204 if (CONSP (coding_systems
))
2205 val
= XCAR (coding_systems
);
2206 else if (CONSP (Vdefault_process_coding_system
))
2207 val
= XCAR (Vdefault_process_coding_system
);
2211 pset_decode_coding_system (p
, val
);
2219 else if (!NILP (Vcoding_system_for_write
))
2220 val
= Vcoding_system_for_write
;
2221 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2225 if (CONSP (coding_systems
))
2226 val
= XCDR (coding_systems
);
2227 else if (CONSP (Vdefault_process_coding_system
))
2228 val
= XCDR (Vdefault_process_coding_system
);
2232 pset_encode_coding_system (p
, val
);
2234 /* This may signal an error. */
2235 setup_process_coding_systems (proc
);
2237 specpdl_ptr
= specpdl
+ specpdl_count
;
2243 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2244 The address family of sa is not included in the result. */
2247 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2249 Lisp_Object address
;
2252 struct Lisp_Vector
*p
;
2254 /* Workaround for a bug in getsockname on BSD: Names bound to
2255 sockets in the UNIX domain are inaccessible; getsockname returns
2256 a zero length name. */
2257 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2258 return empty_unibyte_string
;
2260 switch (sa
->sa_family
)
2264 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2265 len
= sizeof (sin
->sin_addr
) + 1;
2266 address
= Fmake_vector (make_number (len
), Qnil
);
2267 p
= XVECTOR (address
);
2268 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2269 cp
= (unsigned char *) &sin
->sin_addr
;
2275 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2276 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2277 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2278 address
= Fmake_vector (make_number (len
), Qnil
);
2279 p
= XVECTOR (address
);
2280 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2281 for (i
= 0; i
< len
; i
++)
2282 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2286 #ifdef HAVE_LOCAL_SOCKETS
2289 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2290 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2291 /* If the first byte is NUL, the name is a Linux abstract
2292 socket name, and the name can contain embedded NULs. If
2293 it's not, we have a NUL-terminated string. Be careful not
2294 to walk past the end of the object looking for the name
2295 terminator, however. */
2296 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2298 const char *terminator
2299 = memchr (sockun
->sun_path
, '\0', name_length
);
2302 name_length
= terminator
- (const char *) sockun
->sun_path
;
2305 return make_unibyte_string (sockun
->sun_path
, name_length
);
2309 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2310 address
= Fcons (make_number (sa
->sa_family
),
2311 Fmake_vector (make_number (len
), Qnil
));
2312 p
= XVECTOR (XCDR (address
));
2313 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2319 p
->contents
[i
++] = make_number (*cp
++);
2325 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2328 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2330 struct Lisp_Vector
*p
;
2332 if (VECTORP (address
))
2334 p
= XVECTOR (address
);
2335 if (p
->header
.size
== 5)
2338 return sizeof (struct sockaddr_in
);
2341 else if (p
->header
.size
== 9)
2343 *familyp
= AF_INET6
;
2344 return sizeof (struct sockaddr_in6
);
2348 #ifdef HAVE_LOCAL_SOCKETS
2349 else if (STRINGP (address
))
2351 *familyp
= AF_LOCAL
;
2352 return sizeof (struct sockaddr_un
);
2355 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2356 && VECTORP (XCDR (address
)))
2358 struct sockaddr
*sa
;
2359 p
= XVECTOR (XCDR (address
));
2360 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2362 *familyp
= XINT (XCAR (address
));
2363 return p
->header
.size
+ sizeof (sa
->sa_family
);
2368 /* Convert an address object (vector or string) to an internal sockaddr.
2370 The address format has been basically validated by
2371 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2372 it could have come from user data. So if FAMILY is not valid,
2373 we return after zeroing *SA. */
2376 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2378 register struct Lisp_Vector
*p
;
2379 register unsigned char *cp
= NULL
;
2383 memset (sa
, 0, len
);
2385 if (VECTORP (address
))
2387 p
= XVECTOR (address
);
2388 if (family
== AF_INET
)
2390 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2391 len
= sizeof (sin
->sin_addr
) + 1;
2392 hostport
= XINT (p
->contents
[--len
]);
2393 sin
->sin_port
= htons (hostport
);
2394 cp
= (unsigned char *)&sin
->sin_addr
;
2395 sa
->sa_family
= family
;
2398 else if (family
== AF_INET6
)
2400 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2401 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2402 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2403 hostport
= XINT (p
->contents
[--len
]);
2404 sin6
->sin6_port
= htons (hostport
);
2405 for (i
= 0; i
< len
; i
++)
2406 if (INTEGERP (p
->contents
[i
]))
2408 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2411 sa
->sa_family
= family
;
2418 else if (STRINGP (address
))
2420 #ifdef HAVE_LOCAL_SOCKETS
2421 if (family
== AF_LOCAL
)
2423 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2424 cp
= SDATA (address
);
2425 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2426 sockun
->sun_path
[i
] = *cp
++;
2427 sa
->sa_family
= family
;
2434 p
= XVECTOR (XCDR (address
));
2435 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2438 for (i
= 0; i
< len
; i
++)
2439 if (INTEGERP (p
->contents
[i
]))
2440 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2443 #ifdef DATAGRAM_SOCKETS
2444 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2446 doc
: /* Get the current datagram address associated with PROCESS.
2447 If PROCESS is a non-blocking network process that hasn't been fully
2448 set up yet, this function will block until socket setup has completed. */)
2449 (Lisp_Object process
)
2453 CHECK_PROCESS (process
);
2455 if (NETCONN_P (process
))
2456 wait_for_socket_fds (process
, "process-datagram-address");
2458 if (!DATAGRAM_CONN_P (process
))
2461 channel
= XPROCESS (process
)->infd
;
2462 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2463 datagram_address
[channel
].len
);
2466 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2468 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2469 Return nil upon error setting address, ADDRESS otherwise.
2471 If PROCESS is a non-blocking network process that hasn't been fully
2472 set up yet, this function will block until socket setup has completed. */)
2473 (Lisp_Object process
, Lisp_Object address
)
2479 CHECK_PROCESS (process
);
2481 if (NETCONN_P (process
))
2482 wait_for_socket_fds (process
, "set-process-datagram-address");
2484 if (!DATAGRAM_CONN_P (process
))
2487 channel
= XPROCESS (process
)->infd
;
2489 len
= get_lisp_to_sockaddr_size (address
, &family
);
2490 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2492 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2498 static const struct socket_options
{
2499 /* The name of this option. Should be lowercase version of option
2500 name without SO_ prefix. */
2502 /* Option level SOL_... */
2504 /* Option number SO_... */
2506 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2507 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2508 } socket_options
[] =
2510 #ifdef SO_BINDTODEVICE
2511 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2514 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2517 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2520 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2523 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2526 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2529 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2532 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2534 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2537 /* Set option OPT to value VAL on socket S.
2539 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2540 Signals an error if setting a known option fails.
2544 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2547 const struct socket_options
*sopt
;
2552 name
= SSDATA (SYMBOL_NAME (opt
));
2553 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2554 if (strcmp (name
, sopt
->name
) == 0)
2557 switch (sopt
->opttype
)
2562 optval
= NILP (val
) ? 0 : 1;
2563 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2564 &optval
, sizeof (optval
));
2571 if (TYPE_RANGED_INTEGERP (int, val
))
2572 optval
= XINT (val
);
2574 error ("Bad option value for %s", name
);
2575 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2576 &optval
, sizeof (optval
));
2580 #ifdef SO_BINDTODEVICE
2583 char devname
[IFNAMSIZ
+ 1];
2585 /* This is broken, at least in the Linux 2.4 kernel.
2586 To unbind, the arg must be a zero integer, not the empty string.
2587 This should work on all systems. KFS. 2003-09-23. */
2588 memset (devname
, 0, sizeof devname
);
2591 char *arg
= SSDATA (val
);
2592 int len
= min (strlen (arg
), IFNAMSIZ
);
2593 memcpy (devname
, arg
, len
);
2595 else if (!NILP (val
))
2596 error ("Bad option value for %s", name
);
2597 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2606 struct linger linger
;
2609 linger
.l_linger
= 0;
2610 if (TYPE_RANGED_INTEGERP (int, val
))
2611 linger
.l_linger
= XINT (val
);
2613 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2614 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2615 &linger
, sizeof (linger
));
2626 int setsockopt_errno
= errno
;
2627 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2631 return (1 << sopt
->optbit
);
2635 DEFUN ("set-network-process-option",
2636 Fset_network_process_option
, Sset_network_process_option
,
2638 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2639 See `make-network-process' for a list of options and values.
2640 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2641 OPTION is not a supported option, return nil instead; otherwise return t.
2643 If PROCESS is a non-blocking network process that hasn't been fully
2644 set up yet, this function will block until socket setup has completed. */)
2645 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2648 struct Lisp_Process
*p
;
2650 CHECK_PROCESS (process
);
2651 p
= XPROCESS (process
);
2652 if (!NETCONN1_P (p
))
2653 error ("Process is not a network process");
2655 wait_for_socket_fds (process
, "set-network-process-option");
2659 error ("Process is not running");
2661 if (set_socket_option (s
, option
, value
))
2663 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2667 if (NILP (no_error
))
2668 error ("Unknown or unsupported option");
2674 DEFUN ("serial-process-configure",
2675 Fserial_process_configure
,
2676 Sserial_process_configure
,
2678 doc
: /* Configure speed, bytesize, etc. of a serial process.
2680 Arguments are specified as keyword/argument pairs. Attributes that
2681 are not given are re-initialized from the process's current
2682 configuration (available via the function `process-contact') or set to
2683 reasonable default values. The following arguments are defined:
2689 -- Any of these arguments can be given to identify the process that is
2690 to be configured. If none of these arguments is given, the current
2691 buffer's process is used.
2693 :speed SPEED -- SPEED is the speed of the serial port in bits per
2694 second, also called baud rate. Any value can be given for SPEED, but
2695 most serial ports work only at a few defined values between 1200 and
2696 115200, with 9600 being the most common value. If SPEED is nil, the
2697 serial port is not configured any further, i.e., all other arguments
2698 are ignored. This may be useful for special serial ports such as
2699 Bluetooth-to-serial converters which can only be configured through AT
2700 commands. A value of nil for SPEED can be used only when passed
2701 through `make-serial-process' or `serial-term'.
2703 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2704 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2706 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2707 `odd' (use odd parity), or the symbol `even' (use even parity). If
2708 PARITY is not given, no parity is used.
2710 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2711 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2712 is not given or nil, 1 stopbit is used.
2714 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2715 flowcontrol to be used, which is either nil (don't use flowcontrol),
2716 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2717 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2718 flowcontrol is used.
2720 `serial-process-configure' is called by `make-serial-process' for the
2721 initial configuration of the serial port.
2725 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2727 \(serial-process-configure
2728 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2730 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2732 usage: (serial-process-configure &rest ARGS) */)
2733 (ptrdiff_t nargs
, Lisp_Object
*args
)
2735 struct Lisp_Process
*p
;
2736 Lisp_Object contact
= Qnil
;
2737 Lisp_Object proc
= Qnil
;
2739 contact
= Flist (nargs
, args
);
2741 proc
= Fplist_get (contact
, QCprocess
);
2743 proc
= Fplist_get (contact
, QCname
);
2745 proc
= Fplist_get (contact
, QCbuffer
);
2747 proc
= Fplist_get (contact
, QCport
);
2748 proc
= get_process (proc
);
2749 p
= XPROCESS (proc
);
2750 if (!EQ (p
->type
, Qserial
))
2751 error ("Not a serial process");
2753 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2756 serial_configure (p
, contact
);
2760 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2762 doc
: /* Create and return a serial port process.
2764 In Emacs, serial port connections are represented by process objects,
2765 so input and output work as for subprocesses, and `delete-process'
2766 closes a serial port connection. However, a serial process has no
2767 process id, it cannot be signaled, and the status codes are different
2768 from normal processes.
2770 `make-serial-process' creates a process and a buffer, on which you
2771 probably want to use `process-send-string'. Try \\[serial-term] for
2772 an interactive terminal. See below for examples.
2774 Arguments are specified as keyword/argument pairs. The following
2775 arguments are defined:
2777 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2778 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2779 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2780 the backslashes in strings).
2782 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2783 which this function calls.
2785 :name NAME -- NAME is the name of the process. If NAME is not given,
2786 the value of PORT is used.
2788 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2789 with the process. Process output goes at the end of that buffer,
2790 unless you specify an output stream or filter function to handle the
2791 output. If BUFFER is not given, the value of NAME is used.
2793 :coding CODING -- If CODING is a symbol, it specifies the coding
2794 system used for both reading and writing for this process. If CODING
2795 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2796 ENCODING is used for writing.
2798 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2799 the process is running. If BOOL is not given, query before exiting.
2801 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2802 In the stopped state, a serial process does not accept incoming data,
2803 but you can send outgoing data. The stopped state is cleared by
2804 `continue-process' and set by `stop-process'.
2806 :filter FILTER -- Install FILTER as the process filter.
2808 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2810 :plist PLIST -- Install PLIST as the initial plist of the process.
2816 -- This function calls `serial-process-configure' to handle these
2819 The original argument list, possibly modified by later configuration,
2820 is available via the function `process-contact'.
2824 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2826 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2828 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2830 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2832 usage: (make-serial-process &rest ARGS) */)
2833 (ptrdiff_t nargs
, Lisp_Object
*args
)
2836 Lisp_Object proc
, contact
, port
;
2837 struct Lisp_Process
*p
;
2838 Lisp_Object name
, buffer
;
2839 Lisp_Object tem
, val
;
2840 ptrdiff_t specpdl_count
;
2845 contact
= Flist (nargs
, args
);
2847 port
= Fplist_get (contact
, QCport
);
2849 error ("No port specified");
2850 CHECK_STRING (port
);
2852 if (NILP (Fplist_member (contact
, QCspeed
)))
2853 error (":speed not specified");
2854 if (!NILP (Fplist_get (contact
, QCspeed
)))
2855 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2857 name
= Fplist_get (contact
, QCname
);
2860 CHECK_STRING (name
);
2861 proc
= make_process (name
);
2862 specpdl_count
= SPECPDL_INDEX ();
2863 record_unwind_protect (remove_process
, proc
);
2864 p
= XPROCESS (proc
);
2866 fd
= serial_open (port
);
2867 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2870 if (fd
> max_process_desc
)
2871 max_process_desc
= fd
;
2872 chan_process
[fd
] = proc
;
2874 buffer
= Fplist_get (contact
, QCbuffer
);
2877 buffer
= Fget_buffer_create (buffer
);
2878 pset_buffer (p
, buffer
);
2880 pset_childp (p
, contact
);
2881 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2882 pset_type (p
, Qserial
);
2883 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2884 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2886 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2887 p
->kill_without_query
= 1;
2888 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2889 pset_command (p
, Qt
);
2890 eassert (! p
->pty_flag
);
2892 if (!EQ (p
->command
, Qt
))
2894 FD_SET (fd
, &input_wait_mask
);
2895 FD_SET (fd
, &non_keyboard_wait_mask
);
2898 if (BUFFERP (buffer
))
2900 set_marker_both (p
->mark
, buffer
,
2901 BUF_ZV (XBUFFER (buffer
)),
2902 BUF_ZV_BYTE (XBUFFER (buffer
)));
2905 tem
= Fplist_member (contact
, QCcoding
);
2906 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2912 val
= XCAR (XCDR (tem
));
2916 else if (!NILP (Vcoding_system_for_read
))
2917 val
= Vcoding_system_for_read
;
2918 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2919 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2921 pset_decode_coding_system (p
, val
);
2926 val
= XCAR (XCDR (tem
));
2930 else if (!NILP (Vcoding_system_for_write
))
2931 val
= Vcoding_system_for_write
;
2932 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2933 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2935 pset_encode_coding_system (p
, val
);
2937 setup_process_coding_systems (proc
);
2938 pset_decoding_buf (p
, empty_unibyte_string
);
2939 p
->decoding_carryover
= 0;
2940 pset_encoding_buf (p
, empty_unibyte_string
);
2941 p
->inherit_coding_system_flag
2942 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2944 Fserial_process_configure (nargs
, args
);
2946 specpdl_ptr
= specpdl
+ specpdl_count
;
2952 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2953 Lisp_Object service
, Lisp_Object name
)
2956 struct Lisp_Process
*p
= XPROCESS (proc
);
2957 Lisp_Object contact
= p
->childp
;
2958 Lisp_Object coding_systems
= Qt
;
2961 tem
= Fplist_member (contact
, QCcoding
);
2962 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2963 tem
= Qnil
; /* No error message (too late!). */
2965 /* Setup coding systems for communicating with the network stream. */
2966 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2970 val
= XCAR (XCDR (tem
));
2974 else if (!NILP (Vcoding_system_for_read
))
2975 val
= Vcoding_system_for_read
;
2976 else if ((!NILP (p
->buffer
)
2977 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2978 || (NILP (p
->buffer
)
2979 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2980 /* We dare not decode end-of-line format by setting VAL to
2981 Qraw_text, because the existing Emacs Lisp libraries
2982 assume that they receive bare code including a sequence of
2987 if (NILP (host
) || NILP (service
))
2988 coding_systems
= Qnil
;
2990 coding_systems
= CALLN (Ffind_operation_coding_system
,
2991 Qopen_network_stream
, name
, p
->buffer
,
2993 if (CONSP (coding_systems
))
2994 val
= XCAR (coding_systems
);
2995 else if (CONSP (Vdefault_process_coding_system
))
2996 val
= XCAR (Vdefault_process_coding_system
);
3000 pset_decode_coding_system (p
, val
);
3004 val
= XCAR (XCDR (tem
));
3008 else if (!NILP (Vcoding_system_for_write
))
3009 val
= Vcoding_system_for_write
;
3010 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3014 if (EQ (coding_systems
, Qt
))
3016 if (NILP (host
) || NILP (service
))
3017 coding_systems
= Qnil
;
3019 coding_systems
= CALLN (Ffind_operation_coding_system
,
3020 Qopen_network_stream
, name
, p
->buffer
,
3023 if (CONSP (coding_systems
))
3024 val
= XCDR (coding_systems
);
3025 else if (CONSP (Vdefault_process_coding_system
))
3026 val
= XCDR (Vdefault_process_coding_system
);
3030 pset_encode_coding_system (p
, val
);
3032 pset_decoding_buf (p
, empty_unibyte_string
);
3033 p
->decoding_carryover
= 0;
3034 pset_encoding_buf (p
, empty_unibyte_string
);
3036 p
->inherit_coding_system_flag
3037 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3042 finish_after_tls_connection (Lisp_Object proc
)
3044 struct Lisp_Process
*p
= XPROCESS (proc
);
3045 Lisp_Object contact
= p
->childp
;
3046 Lisp_Object result
= Qt
;
3048 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3049 result
= call3 (Qnsm_verify_connection
,
3051 Fplist_get (contact
, QChost
),
3052 Fplist_get (contact
, QCservice
));
3056 pset_status (p
, list2 (Qfailed
,
3057 build_string ("The Network Security Manager stopped the connections")));
3058 deactivate_process (proc
);
3062 /* If we cleared the connection wait mask before we did
3063 the TLS setup, then we have to say that the process
3064 is finally "open" here. */
3065 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3067 pset_status (p
, Qrun
);
3068 /* Execute the sentinel here. If we had relied on
3069 status_notify to do it later, it will read input
3070 from the process before calling the sentinel. */
3071 exec_sentinel (proc
, build_string ("open\n"));
3078 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
)
3080 ptrdiff_t count
= SPECPDL_INDEX ();
3082 int s
= -1, outch
, inch
;
3084 Lisp_Object ip_address
;
3086 struct sockaddr
*sa
= NULL
;
3089 struct Lisp_Process
*p
= XPROCESS (proc
);
3090 Lisp_Object contact
= p
->childp
;
3093 /* Do this in case we never enter the while-loop below. */
3094 count1
= SPECPDL_INDEX ();
3097 while (!NILP (ip_addresses
))
3099 ip_address
= XCAR (ip_addresses
);
3100 ip_addresses
= XCDR (ip_addresses
);
3106 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3109 sa
= xmalloc (addrlen
);
3110 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3112 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3119 #ifdef DATAGRAM_SOCKETS
3120 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3122 #endif /* DATAGRAM_SOCKETS */
3124 if (p
->is_non_blocking_client
)
3126 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3136 /* Make us close S if quit. */
3137 record_unwind_protect_int (close_file_unwind
, s
);
3139 /* Parse network options in the arg list. We simply ignore anything
3140 which isn't a known option (including other keywords). An error
3141 is signaled if setting a known option fails. */
3143 Lisp_Object params
= contact
, key
, val
;
3145 while (!NILP (params
))
3147 key
= XCAR (params
);
3148 params
= XCDR (params
);
3149 val
= XCAR (params
);
3150 params
= XCDR (params
);
3151 optbits
|= set_socket_option (s
, key
, val
);
3157 /* Configure as a server socket. */
3159 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3160 explicit :reuseaddr key to override this. */
3161 #ifdef HAVE_LOCAL_SOCKETS
3162 if (family
!= AF_LOCAL
)
3164 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3167 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3168 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3171 if (bind (s
, sa
, addrlen
))
3172 report_file_error ("Cannot bind server socket", Qnil
);
3174 #ifdef HAVE_GETSOCKNAME
3177 struct sockaddr_in sa1
;
3178 socklen_t len1
= sizeof (sa1
);
3179 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3181 Lisp_Object service
;
3182 service
= make_number (ntohs (sa1
.sin_port
));
3183 contact
= Fplist_put (contact
, QCservice
, service
);
3184 /* Save the port number so that we can stash it in
3185 the process object later. */
3186 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3191 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3192 report_file_error ("Cannot listen on server socket", Qnil
);
3200 ret
= connect (s
, sa
, addrlen
);
3203 if (ret
== 0 || xerrno
== EISCONN
)
3205 /* The unwind-protect will be discarded afterwards.
3206 Likewise for immediate_quit. */
3210 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3214 if (xerrno
== EINTR
)
3216 /* Unlike most other syscalls connect() cannot be called
3217 again. (That would return EALREADY.) The proper way to
3218 wait for completion is pselect(). */
3226 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3232 report_file_error ("Failed select", Qnil
);
3236 len
= sizeof xerrno
;
3237 eassert (FD_ISSET (s
, &fdset
));
3238 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3239 report_file_error ("Failed getsockopt", Qnil
);
3241 report_file_errno ("Failed connect", Qnil
, xerrno
);
3244 #endif /* !WINDOWSNT */
3248 /* Discard the unwind protect closing S. */
3249 specpdl_ptr
= specpdl
+ count1
;
3254 if (xerrno
== EINTR
)
3261 #ifdef DATAGRAM_SOCKETS
3262 if (p
->socktype
== SOCK_DGRAM
)
3264 if (datagram_address
[s
].sa
)
3267 datagram_address
[s
].sa
= xmalloc (addrlen
);
3268 datagram_address
[s
].len
= addrlen
;
3272 memset (datagram_address
[s
].sa
, 0, addrlen
);
3273 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3276 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3277 if (rlen
!= 0 && rfamily
== family
3279 conv_lisp_to_sockaddr (rfamily
, remote
,
3280 datagram_address
[s
].sa
, rlen
);
3284 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3288 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3289 conv_sockaddr_to_lisp (sa
, addrlen
));
3290 #ifdef HAVE_GETSOCKNAME
3293 struct sockaddr_in sa1
;
3294 socklen_t len1
= sizeof (sa1
);
3295 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3296 contact
= Fplist_put (contact
, QClocal
,
3297 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3306 /* If non-blocking got this far - and failed - assume non-blocking is
3307 not supported after all. This is probably a wrong assumption, but
3308 the normal blocking calls to open-network-stream handles this error
3310 if (p
->is_non_blocking_client
)
3313 report_file_errno ((p
->is_server
3314 ? "make server process failed"
3315 : "make client process failed"),
3322 chan_process
[inch
] = proc
;
3324 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3326 p
= XPROCESS (proc
);
3327 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3331 /* Discard the unwind protect for closing S, if any. */
3332 specpdl_ptr
= specpdl
+ count1
;
3334 /* Unwind bind_polling_period and request_sigio. */
3335 unbind_to (count
, Qnil
);
3337 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3338 pset_status (p
, Qlisten
);
3340 /* Make the process marker point into the process buffer (if any). */
3341 if (BUFFERP (p
->buffer
))
3342 set_marker_both (p
->mark
, p
->buffer
,
3343 BUF_ZV (XBUFFER (p
->buffer
)),
3344 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3346 if (p
->is_non_blocking_client
)
3348 /* We may get here if connect did succeed immediately. However,
3349 in that case, we still need to signal this like a non-blocking
3351 pset_status (p
, Qconnect
);
3352 if (!FD_ISSET (inch
, &connect_wait_mask
))
3354 FD_SET (inch
, &connect_wait_mask
);
3355 FD_SET (inch
, &write_mask
);
3356 num_pending_connects
++;
3360 /* A server may have a client filter setting of Qt, but it must
3361 still listen for incoming connects unless it is stopped. */
3362 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3363 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3365 FD_SET (inch
, &input_wait_mask
);
3366 FD_SET (inch
, &non_keyboard_wait_mask
);
3369 if (inch
> max_process_desc
)
3370 max_process_desc
= inch
;
3372 /* Set up the masks based on the process filter. */
3373 set_process_filter_masks (p
);
3375 setup_process_coding_systems (proc
);
3378 /* Continue the asynchronous connection. */
3379 if (!NILP (p
->gnutls_boot_parameters
))
3381 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3383 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3384 p
->gnutls_boot_parameters
= Qnil
;
3386 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3387 /* Run sentinels, etc. */
3388 finish_after_tls_connection (proc
);
3389 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3391 deactivate_process (proc
);
3393 pset_status (p
, list2 (Qfailed
,
3394 build_string ("TLS negotiation failed")));
3396 pset_status (p
, list2 (Qfailed
, boot
));
3403 /* Create a network stream/datagram client/server process. Treated
3404 exactly like a normal process when reading and writing. Primary
3405 differences are in status display and process deletion. A network
3406 connection has no PID; you cannot signal it. All you can do is
3407 stop/continue it and deactivate/close it via delete-process. */
3409 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3411 doc
: /* Create and return a network server or client process.
3413 In Emacs, network connections are represented by process objects, so
3414 input and output work as for subprocesses and `delete-process' closes
3415 a network connection. However, a network process has no process id,
3416 it cannot be signaled, and the status codes are different from normal
3419 Arguments are specified as keyword/argument pairs. The following
3420 arguments are defined:
3422 :name NAME -- NAME is name for process. It is modified if necessary
3425 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3426 with the process. Process output goes at end of that buffer, unless
3427 you specify an output stream or filter function to handle the output.
3428 BUFFER may be also nil, meaning that this process is not associated
3431 :host HOST -- HOST is name of the host to connect to, or its IP
3432 address. The symbol `local' specifies the local host. If specified
3433 for a server process, it must be a valid name or address for the local
3434 host, and only clients connecting to that address will be accepted.
3436 :service SERVICE -- SERVICE is name of the service desired, or an
3437 integer specifying a port number to connect to. If SERVICE is t,
3438 a random port number is selected for the server. A port number can
3439 be specified as an integer string, e.g., "80", as well as an integer.
3441 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3442 stream type connection, `datagram' creates a datagram type connection,
3443 `seqpacket' creates a reliable datagram connection.
3445 :family FAMILY -- FAMILY is the address (and protocol) family for the
3446 service specified by HOST and SERVICE. The default (nil) is to use
3447 whatever address family (IPv4 or IPv6) that is defined for the host
3448 and port number specified by HOST and SERVICE. Other address families
3450 local -- for a local (i.e. UNIX) address specified by SERVICE.
3451 ipv4 -- use IPv4 address family only.
3452 ipv6 -- use IPv6 address family only.
3454 :local ADDRESS -- ADDRESS is the local address used for the connection.
3455 This parameter is ignored when opening a client process. When specified
3456 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3458 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3459 connection. This parameter is ignored when opening a stream server
3460 process. For a datagram server process, it specifies the initial
3461 setting of the remote datagram address. When specified for a client
3462 process, the FAMILY, HOST, and SERVICE args are ignored.
3464 The format of ADDRESS depends on the address family:
3465 - An IPv4 address is represented as an vector of integers [A B C D P]
3466 corresponding to numeric IP address A.B.C.D and port number P.
3467 - A local address is represented as a string with the address in the
3468 local address space.
3469 - An "unsupported family" address is represented by a cons (F . AV)
3470 where F is the family number and AV is a vector containing the socket
3471 address data with one element per address data byte. Do not rely on
3472 this format in portable code, as it may depend on implementation
3473 defined constants, data sizes, and data structure alignment.
3475 :coding CODING -- If CODING is a symbol, it specifies the coding
3476 system used for both reading and writing for this process. If CODING
3477 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3478 ENCODING is used for writing.
3480 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3481 process, return without waiting for the connection to complete;
3482 instead, the sentinel function will be called with second arg matching
3483 "open" (if successful) or "failed" when the connect completes.
3484 Default is to use a blocking connect (i.e. wait) for stream type
3487 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3488 running when Emacs is exited.
3490 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3491 In the stopped state, a server process does not accept new
3492 connections, and a client process does not handle incoming traffic.
3493 The stopped state is cleared by `continue-process' and set by
3496 :filter FILTER -- Install FILTER as the process filter.
3498 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3499 process filter are multibyte, otherwise they are unibyte.
3500 If this keyword is not specified, the strings are multibyte if
3501 the default value of `enable-multibyte-characters' is non-nil.
3503 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3505 :log LOG -- Install LOG as the server process log function. This
3506 function is called when the server accepts a network connection from a
3507 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3508 is the server process, CLIENT is the new process for the connection,
3509 and MESSAGE is a string.
3511 :plist PLIST -- Install PLIST as the new process's initial plist.
3513 :tls-parameters LIST -- is a list that should be supplied if you're
3514 opening a TLS connection. The first element is the TLS type (either
3515 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3516 be a keyword list accepted by gnutls-boot (as returned by
3517 `gnutls-boot-parameters').
3519 :server QLEN -- if QLEN is non-nil, create a server process for the
3520 specified FAMILY, SERVICE, and connection type (stream or datagram).
3521 If QLEN is an integer, it is used as the max. length of the server's
3522 pending connection queue (also known as the backlog); the default
3523 queue length is 5. Default is to create a client process.
3525 The following network options can be specified for this connection:
3527 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3528 :dontroute BOOL -- Only send to directly connected hosts.
3529 :keepalive BOOL -- Send keep-alive messages on network stream.
3530 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3531 :oobinline BOOL -- Place out-of-band data in receive data stream.
3532 :priority INT -- Set protocol defined priority for sent packets.
3533 :reuseaddr BOOL -- Allow reusing a recently used local address
3534 (this is allowed by default for a server process).
3535 :bindtodevice NAME -- bind to interface NAME. Using this may require
3536 special privileges on some systems.
3538 Consult the relevant system programmer's manual pages for more
3539 information on using these options.
3542 A server process will listen for and accept connections from clients.
3543 When a client connection is accepted, a new network process is created
3544 for the connection with the following parameters:
3546 - The client's process name is constructed by concatenating the server
3547 process's NAME and a client identification string.
3548 - If the FILTER argument is non-nil, the client process will not get a
3549 separate process buffer; otherwise, the client's process buffer is a newly
3550 created buffer named after the server process's BUFFER name or process
3551 NAME concatenated with the client identification string.
3552 - The connection type and the process filter and sentinel parameters are
3553 inherited from the server process's TYPE, FILTER and SENTINEL.
3554 - The client process's contact info is set according to the client's
3555 addressing information (typically an IP address and a port number).
3556 - The client process's plist is initialized from the server's plist.
3558 Notice that the FILTER and SENTINEL args are never used directly by
3559 the server process. Also, the BUFFER argument is not used directly by
3560 the server process, but via the optional :log function, accepted (and
3561 failed) connections may be logged in the server process's buffer.
3563 The original argument list, modified with the actual connection
3564 information, is available via the `process-contact' function.
3566 usage: (make-network-process &rest ARGS) */)
3567 (ptrdiff_t nargs
, Lisp_Object
*args
)
3570 Lisp_Object contact
;
3571 struct Lisp_Process
*p
;
3572 const char *portstring
;
3573 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3574 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3575 #ifdef HAVE_LOCAL_SOCKETS
3576 struct sockaddr_un address_un
;
3580 Lisp_Object name
, buffer
, host
, service
, address
;
3581 Lisp_Object filter
, sentinel
;
3582 Lisp_Object ip_addresses
= Qnil
;
3585 int ai_protocol
= 0;
3586 #ifdef HAVE_GETADDRINFO_A
3587 struct gaicb
*dns_request
= NULL
;
3589 ptrdiff_t count
= SPECPDL_INDEX ();
3594 /* Save arguments for process-contact and clone-process. */
3595 contact
= Flist (nargs
, args
);
3598 /* Ensure socket support is loaded if available. */
3599 init_winsock (TRUE
);
3602 /* :type TYPE (nil: stream, datagram */
3603 tem
= Fplist_get (contact
, QCtype
);
3605 socktype
= SOCK_STREAM
;
3606 #ifdef DATAGRAM_SOCKETS
3607 else if (EQ (tem
, Qdatagram
))
3608 socktype
= SOCK_DGRAM
;
3610 #ifdef HAVE_SEQPACKET
3611 else if (EQ (tem
, Qseqpacket
))
3612 socktype
= SOCK_SEQPACKET
;
3615 error ("Unsupported connection type");
3617 name
= Fplist_get (contact
, QCname
);
3618 buffer
= Fplist_get (contact
, QCbuffer
);
3619 filter
= Fplist_get (contact
, QCfilter
);
3620 sentinel
= Fplist_get (contact
, QCsentinel
);
3622 CHECK_STRING (name
);
3624 /* :local ADDRESS or :remote ADDRESS */
3625 tem
= Fplist_get (contact
, QCserver
);
3627 address
= Fplist_get (contact
, QCremote
);
3629 address
= Fplist_get (contact
, QClocal
);
3630 if (!NILP (address
))
3632 host
= service
= Qnil
;
3634 if (!get_lisp_to_sockaddr_size (address
, &family
))
3635 error ("Malformed :address");
3637 ip_addresses
= list1 (address
);
3641 /* :family FAMILY -- nil (for Inet), local, or integer. */
3642 tem
= Fplist_get (contact
, QCfamily
);
3651 #ifdef HAVE_LOCAL_SOCKETS
3652 else if (EQ (tem
, Qlocal
))
3656 else if (EQ (tem
, Qipv6
))
3659 else if (EQ (tem
, Qipv4
))
3661 else if (TYPE_RANGED_INTEGERP (int, tem
))
3662 family
= XINT (tem
);
3664 error ("Unknown address family");
3666 /* :service SERVICE -- string, integer (port number), or t (random port). */
3667 service
= Fplist_get (contact
, QCservice
);
3669 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3670 host
= Fplist_get (contact
, QChost
);
3673 /* The "connection" function gets it bind info from the address we're
3674 given, so use this dummy address if nothing is specified. */
3675 #ifdef HAVE_LOCAL_SOCKETS
3676 if (family
!= AF_LOCAL
)
3678 host
= build_string ("127.0.0.1");
3682 if (EQ (host
, Qlocal
))
3683 /* Depending on setup, "localhost" may map to different IPv4 and/or
3684 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3685 host
= build_string ("127.0.0.1");
3686 CHECK_STRING (host
);
3689 #ifdef HAVE_LOCAL_SOCKETS
3690 if (family
== AF_LOCAL
)
3694 message (":family local ignores the :host property");
3695 contact
= Fplist_put (contact
, QChost
, Qnil
);
3698 CHECK_STRING (service
);
3699 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3700 error ("Service name too long");
3701 ip_addresses
= list1 (service
);
3706 /* Slow down polling to every ten seconds.
3707 Some kernels have a bug which causes retrying connect to fail
3708 after a connect. Polling can interfere with gethostbyname too. */
3709 #ifdef POLL_FOR_INPUT
3710 if (socktype
!= SOCK_DGRAM
)
3712 record_unwind_protect_void (run_all_atimers
);
3713 bind_polling_period (10);
3719 /* SERVICE can either be a string or int.
3720 Convert to a C string for later use by getaddrinfo. */
3721 if (EQ (service
, Qt
))
3726 else if (INTEGERP (service
))
3728 portstring
= portbuf
;
3729 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3733 CHECK_STRING (service
);
3734 portstring
= SSDATA (service
);
3735 portstringlen
= SBYTES (service
);
3739 #ifdef HAVE_GETADDRINFO_A
3740 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3742 ptrdiff_t hostlen
= SBYTES (host
);
3746 struct addrinfo hints
;
3747 char str
[FLEXIBLE_ARRAY_MEMBER
];
3748 } *req
= xmalloc (offsetof (struct req
, str
)
3749 + hostlen
+ 1 + portstringlen
+ 1);
3750 dns_request
= &req
->gaicb
;
3751 dns_request
->ar_name
= req
->str
;
3752 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3753 dns_request
->ar_request
= &req
->hints
;
3754 dns_request
->ar_result
= NULL
;
3755 memset (&req
->hints
, 0, sizeof req
->hints
);
3756 req
->hints
.ai_family
= family
;
3757 req
->hints
.ai_socktype
= socktype
;
3758 strcpy (req
->str
, SSDATA (host
));
3759 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3761 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3763 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3767 #endif /* HAVE_GETADDRINFO_A */
3769 /* If we have a host, use getaddrinfo to resolve both host and service.
3770 Otherwise, use getservbyname to lookup the service. */
3774 struct addrinfo
*res
, *lres
;
3780 struct addrinfo hints
;
3781 memset (&hints
, 0, sizeof hints
);
3782 hints
.ai_family
= family
;
3783 hints
.ai_socktype
= socktype
;
3785 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3787 #ifdef HAVE_GAI_STRERROR
3789 synchronize_system_messages_locale ();
3790 char const *str
= gai_strerror (ret
);
3791 if (! NILP (Vlocale_coding_system
))
3792 str
= SSDATA (code_convert_string_norecord
3793 (build_string (str
), Vlocale_coding_system
, 0));
3794 error ("%s/%s %s", SSDATA (host
), portstring
, str
);
3797 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3801 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3803 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3804 (lres
->ai_addr
, lres
->ai_addrlen
),
3806 ai_protocol
= lres
->ai_protocol
;
3809 ip_addresses
= Fnreverse (ip_addresses
);
3816 /* No hostname has been specified (e.g., a local server process). */
3818 if (EQ (service
, Qt
))
3820 else if (INTEGERP (service
))
3821 port
= XINT (service
);
3824 CHECK_STRING (service
);
3827 if (SBYTES (service
) != 0)
3829 /* Allow the service to be a string containing the port number,
3830 because that's allowed if you have getaddrbyname. */
3832 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3833 if (service_end
== SSDATA (service
) + SBYTES (service
))
3837 struct servent
*svc_info
3838 = getservbyname (SSDATA (service
),
3839 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3841 port
= ntohs (svc_info
->s_port
);
3846 if (! (0 <= port
&& port
< 1 << 16))
3848 AUTO_STRING (unknown_service
, "Unknown service: %s");
3849 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3855 buffer
= Fget_buffer_create (buffer
);
3856 proc
= make_process (name
);
3857 p
= XPROCESS (proc
);
3858 pset_childp (p
, contact
);
3859 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3860 pset_type (p
, Qnetwork
);
3862 pset_buffer (p
, buffer
);
3863 pset_sentinel (p
, sentinel
);
3864 pset_filter (p
, filter
);
3865 pset_log (p
, Fplist_get (contact
, QClog
));
3866 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3867 p
->kill_without_query
= 1;
3868 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3869 pset_command (p
, Qt
);
3872 p
->is_non_blocking_client
= false;
3873 p
->is_server
= false;
3875 p
->socktype
= socktype
;
3876 p
->ai_protocol
= ai_protocol
;
3877 #ifdef HAVE_GETADDRINFO_A
3878 p
->dns_request
= NULL
;
3881 tem
= Fplist_get (contact
, QCtls_parameters
);
3883 p
->gnutls_boot_parameters
= tem
;
3886 set_network_socket_coding_system (proc
, service
, host
, name
);
3888 unbind_to (count
, Qnil
);
3891 tem
= Fplist_get (contact
, QCserver
);
3894 /* Don't support network sockets when non-blocking mode is
3895 not available, since a blocked Emacs is not useful. */
3896 p
->is_server
= true;
3897 if (TYPE_RANGED_INTEGERP (int, tem
))
3898 p
->backlog
= XINT (tem
);
3902 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3903 && !NILP (Fplist_get (contact
, QCnowait
)))
3904 p
->is_non_blocking_client
= true;
3906 #ifdef HAVE_GETADDRINFO_A
3907 /* With async address resolution, the list of addresses is empty, so
3908 postpone connecting to the server. */
3909 if (!p
->is_server
&& NILP (ip_addresses
))
3911 p
->dns_request
= dns_request
;
3912 p
->status
= Qconnect
;
3917 connect_network_socket (proc
, ip_addresses
);
3922 #ifdef HAVE_NET_IF_H
3926 network_interface_list (void)
3928 struct ifconf ifconf
;
3929 struct ifreq
*ifreq
;
3931 ptrdiff_t buf_size
= 512;
3936 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3939 count
= SPECPDL_INDEX ();
3940 record_unwind_protect_int (close_file_unwind
, s
);
3944 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3945 ifconf
.ifc_buf
= buf
;
3946 ifconf
.ifc_len
= buf_size
;
3947 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3954 while (ifconf
.ifc_len
== buf_size
);
3956 res
= unbind_to (count
, Qnil
);
3957 ifreq
= ifconf
.ifc_req
;
3958 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3960 struct ifreq
*ifq
= ifreq
;
3961 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3962 #define SIZEOF_IFREQ(sif) \
3963 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3964 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3966 int len
= SIZEOF_IFREQ (ifq
);
3968 int len
= sizeof (*ifreq
);
3970 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3971 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3973 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3976 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3977 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3978 res
= Fcons (Fcons (build_string (namebuf
),
3979 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3980 sizeof (struct sockaddr
))),
3987 #endif /* SIOCGIFCONF */
3989 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3993 const char *flag_sym
;
3996 static const struct ifflag_def ifflag_table
[] = {
4000 #ifdef IFF_BROADCAST
4001 { IFF_BROADCAST
, "broadcast" },
4004 { IFF_DEBUG
, "debug" },
4007 { IFF_LOOPBACK
, "loopback" },
4009 #ifdef IFF_POINTOPOINT
4010 { IFF_POINTOPOINT
, "pointopoint" },
4013 { IFF_RUNNING
, "running" },
4016 { IFF_NOARP
, "noarp" },
4019 { IFF_PROMISC
, "promisc" },
4021 #ifdef IFF_NOTRAILERS
4022 #ifdef NS_IMPL_COCOA
4023 /* Really means smart, notrailers is obsolete. */
4024 { IFF_NOTRAILERS
, "smart" },
4026 { IFF_NOTRAILERS
, "notrailers" },
4030 { IFF_ALLMULTI
, "allmulti" },
4033 { IFF_MASTER
, "master" },
4036 { IFF_SLAVE
, "slave" },
4038 #ifdef IFF_MULTICAST
4039 { IFF_MULTICAST
, "multicast" },
4042 { IFF_PORTSEL
, "portsel" },
4044 #ifdef IFF_AUTOMEDIA
4045 { IFF_AUTOMEDIA
, "automedia" },
4048 { IFF_DYNAMIC
, "dynamic" },
4051 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4054 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4057 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4060 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4063 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4069 network_interface_info (Lisp_Object ifname
)
4072 Lisp_Object res
= Qnil
;
4077 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4078 && defined HAVE_GETIFADDRS && defined LLADDR)
4079 struct ifaddrs
*ifap
;
4082 CHECK_STRING (ifname
);
4084 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4085 error ("interface name too long");
4086 lispstpcpy (rq
.ifr_name
, ifname
);
4088 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4091 count
= SPECPDL_INDEX ();
4092 record_unwind_protect_int (close_file_unwind
, s
);
4095 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4096 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4098 int flags
= rq
.ifr_flags
;
4099 const struct ifflag_def
*fp
;
4102 /* If flags is smaller than int (i.e. short) it may have the high bit set
4103 due to IFF_MULTICAST. In that case, sign extending it into
4105 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4106 flags
= (unsigned short) rq
.ifr_flags
;
4109 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4111 if (flags
& fp
->flag_bit
)
4113 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4114 flags
-= fp
->flag_bit
;
4117 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4121 elt
= Fcons (make_number (fnum
), elt
);
4126 res
= Fcons (elt
, res
);
4129 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4130 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4132 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4133 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4137 for (n
= 0; n
< 6; n
++)
4138 p
->contents
[n
] = make_number (((unsigned char *)
4139 &rq
.ifr_hwaddr
.sa_data
[0])
4141 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4143 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4144 if (getifaddrs (&ifap
) != -1)
4146 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4147 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4150 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4152 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4153 unsigned char linkaddr
[6];
4156 if (it
->ifa_addr
->sa_family
!= AF_LINK
4157 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4158 || sdl
->sdl_alen
!= 6)
4161 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4162 for (n
= 0; n
< 6; n
++)
4163 p
->contents
[n
] = make_number (linkaddr
[n
]);
4165 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4169 #ifdef HAVE_FREEIFADDRS
4173 #endif /* HAVE_GETIFADDRS && LLADDR */
4175 res
= Fcons (elt
, res
);
4178 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4179 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4182 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4183 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4185 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4189 res
= Fcons (elt
, res
);
4192 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4193 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4196 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4199 res
= Fcons (elt
, res
);
4202 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4203 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4206 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4209 res
= Fcons (elt
, res
);
4211 return unbind_to (count
, any
? res
: Qnil
);
4213 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4214 #endif /* defined (HAVE_NET_IF_H) */
4216 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4217 Snetwork_interface_list
, 0, 0, 0,
4218 doc
: /* Return an alist of all network interfaces and their network address.
4219 Each element is a cons, the car of which is a string containing the
4220 interface name, and the cdr is the network address in internal
4221 format; see the description of ADDRESS in `make-network-process'.
4223 If the information is not available, return nil. */)
4226 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4227 return network_interface_list ();
4233 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4234 Snetwork_interface_info
, 1, 1, 0,
4235 doc
: /* Return information about network interface named IFNAME.
4236 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4237 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4238 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4239 FLAGS is the current flags of the interface.
4241 Data that is unavailable is returned as nil. */)
4242 (Lisp_Object ifname
)
4244 #if ((defined HAVE_NET_IF_H \
4245 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4246 || defined SIOCGIFFLAGS)) \
4247 || defined WINDOWSNT)
4248 return network_interface_info (ifname
);
4254 /* If program file NAME starts with /: for quoting a magic
4255 name, remove that, preserving the multibyteness of NAME. */
4258 remove_slash_colon (Lisp_Object name
)
4261 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
4262 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
4263 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
4267 /* Turn off input and output for process PROC. */
4270 deactivate_process (Lisp_Object proc
)
4273 struct Lisp_Process
*p
= XPROCESS (proc
);
4277 /* Delete GnuTLS structures in PROC, if any. */
4278 emacs_gnutls_deinit (proc
);
4279 #endif /* HAVE_GNUTLS */
4281 if (p
->read_output_delay
> 0)
4283 if (--process_output_delay_count
< 0)
4284 process_output_delay_count
= 0;
4285 p
->read_output_delay
= 0;
4286 p
->read_output_skip
= 0;
4289 /* Beware SIGCHLD hereabouts. */
4291 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4292 close_process_fd (&p
->open_fd
[i
]);
4294 inchannel
= p
->infd
;
4299 #ifdef DATAGRAM_SOCKETS
4300 if (DATAGRAM_CHAN_P (inchannel
))
4302 xfree (datagram_address
[inchannel
].sa
);
4303 datagram_address
[inchannel
].sa
= 0;
4304 datagram_address
[inchannel
].len
= 0;
4307 chan_process
[inchannel
] = Qnil
;
4308 FD_CLR (inchannel
, &input_wait_mask
);
4309 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4310 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4312 FD_CLR (inchannel
, &connect_wait_mask
);
4313 FD_CLR (inchannel
, &write_mask
);
4314 if (--num_pending_connects
< 0)
4317 if (inchannel
== max_process_desc
)
4319 /* We just closed the highest-numbered process input descriptor,
4320 so recompute the highest-numbered one now. */
4324 while (0 <= i
&& NILP (chan_process
[i
]));
4326 max_process_desc
= i
;
4332 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4334 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4335 It is given to their filter functions.
4336 Optional argument PROCESS means do not return until output has been
4337 received from PROCESS.
4339 Optional second argument SECONDS and third argument MILLISEC
4340 specify a timeout; return after that much time even if there is
4341 no subprocess output. If SECONDS is a floating point number,
4342 it specifies a fractional number of seconds to wait.
4343 The MILLISEC argument is obsolete and should be avoided.
4345 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4346 from PROCESS only, suspending reading output from other processes.
4347 If JUST-THIS-ONE is an integer, don't run any timers either.
4348 Return non-nil if we received any output from PROCESS (or, if PROCESS
4349 is nil, from any process) before the timeout expired. */)
4350 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4355 if (! NILP (process
))
4356 CHECK_PROCESS (process
);
4358 just_this_one
= Qnil
;
4360 if (!NILP (millisec
))
4361 { /* Obsolete calling convention using integers rather than floats. */
4362 CHECK_NUMBER (millisec
);
4364 seconds
= make_float (XINT (millisec
) / 1000.0);
4367 CHECK_NUMBER (seconds
);
4368 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4375 if (!NILP (seconds
))
4377 if (INTEGERP (seconds
))
4379 if (XINT (seconds
) > 0)
4381 secs
= XINT (seconds
);
4385 else if (FLOATP (seconds
))
4387 if (XFLOAT_DATA (seconds
) > 0)
4389 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4390 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4395 wrong_type_argument (Qnumberp
, seconds
);
4397 else if (! NILP (process
))
4401 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4403 !NILP (process
) ? XPROCESS (process
) : NULL
,
4404 (NILP (just_this_one
) ? 0
4405 : !INTEGERP (just_this_one
) ? 1 : -1))
4410 /* Accept a connection for server process SERVER on CHANNEL. */
4412 static EMACS_INT connect_counter
= 0;
4415 server_accept_connection (Lisp_Object server
, int channel
)
4417 Lisp_Object proc
, caller
, name
, buffer
;
4418 Lisp_Object contact
, host
, service
;
4419 struct Lisp_Process
*ps
= XPROCESS (server
);
4420 struct Lisp_Process
*p
;
4424 struct sockaddr_in in
;
4426 struct sockaddr_in6 in6
;
4428 #ifdef HAVE_LOCAL_SOCKETS
4429 struct sockaddr_un un
;
4432 socklen_t len
= sizeof saddr
;
4435 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4444 if (code
== EWOULDBLOCK
)
4448 if (!NILP (ps
->log
))
4449 call3 (ps
->log
, server
, Qnil
,
4450 concat3 (build_string ("accept failed with code"),
4451 Fnumber_to_string (make_number (code
)),
4452 build_string ("\n")));
4456 count
= SPECPDL_INDEX ();
4457 record_unwind_protect_int (close_file_unwind
, s
);
4461 /* Setup a new process to handle the connection. */
4463 /* Generate a unique identification of the caller, and build contact
4464 information for this process. */
4467 switch (saddr
.sa
.sa_family
)
4471 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4473 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4474 host
= CALLN (Fformat
, ipv4_format
,
4475 make_number (ip
[0]), make_number (ip
[1]),
4476 make_number (ip
[2]), make_number (ip
[3]));
4477 service
= make_number (ntohs (saddr
.in
.sin_port
));
4478 AUTO_STRING (caller_format
, " <%s:%d>");
4479 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4486 Lisp_Object args
[9];
4487 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4490 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4491 args
[0] = ipv6_format
;
4492 for (i
= 0; i
< 8; i
++)
4493 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4494 host
= CALLMANY (Fformat
, args
);
4495 service
= make_number (ntohs (saddr
.in
.sin_port
));
4496 AUTO_STRING (caller_format
, " <[%s]:%d>");
4497 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4502 #ifdef HAVE_LOCAL_SOCKETS
4506 caller
= Fnumber_to_string (make_number (connect_counter
));
4507 AUTO_STRING (space_less_than
, " <");
4508 AUTO_STRING (greater_than
, ">");
4509 caller
= concat3 (space_less_than
, caller
, greater_than
);
4513 /* Create a new buffer name for this process if it doesn't have a
4514 filter. The new buffer name is based on the buffer name or
4515 process name of the server process concatenated with the caller
4518 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4519 || EQ (ps
->filter
, Qt
)))
4523 buffer
= ps
->buffer
;
4525 buffer
= Fbuffer_name (buffer
);
4530 buffer
= concat2 (buffer
, caller
);
4531 buffer
= Fget_buffer_create (buffer
);
4535 /* Generate a unique name for the new server process. Combine the
4536 server process name with the caller identification. */
4538 name
= concat2 (ps
->name
, caller
);
4539 proc
= make_process (name
);
4541 chan_process
[s
] = proc
;
4543 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4545 p
= XPROCESS (proc
);
4547 /* Build new contact information for this setup. */
4548 contact
= Fcopy_sequence (ps
->childp
);
4549 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4550 contact
= Fplist_put (contact
, QChost
, host
);
4551 if (!NILP (service
))
4552 contact
= Fplist_put (contact
, QCservice
, service
);
4553 contact
= Fplist_put (contact
, QCremote
,
4554 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4555 #ifdef HAVE_GETSOCKNAME
4557 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4558 contact
= Fplist_put (contact
, QClocal
,
4559 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4562 pset_childp (p
, contact
);
4563 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4564 pset_type (p
, Qnetwork
);
4566 pset_buffer (p
, buffer
);
4567 pset_sentinel (p
, ps
->sentinel
);
4568 pset_filter (p
, ps
->filter
);
4569 pset_command (p
, Qnil
);
4572 /* Discard the unwind protect for closing S. */
4573 specpdl_ptr
= specpdl
+ count
;
4575 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4578 pset_status (p
, Qrun
);
4580 /* Client processes for accepted connections are not stopped initially. */
4581 if (!EQ (p
->filter
, Qt
))
4583 FD_SET (s
, &input_wait_mask
);
4584 FD_SET (s
, &non_keyboard_wait_mask
);
4587 if (s
> max_process_desc
)
4588 max_process_desc
= s
;
4590 /* Setup coding system for new process based on server process.
4591 This seems to be the proper thing to do, as the coding system
4592 of the new process should reflect the settings at the time the
4593 server socket was opened; not the current settings. */
4595 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4596 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4597 setup_process_coding_systems (proc
);
4599 pset_decoding_buf (p
, empty_unibyte_string
);
4600 p
->decoding_carryover
= 0;
4601 pset_encoding_buf (p
, empty_unibyte_string
);
4603 p
->inherit_coding_system_flag
4604 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4606 AUTO_STRING (dash
, "-");
4607 AUTO_STRING (nl
, "\n");
4608 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4610 if (!NILP (ps
->log
))
4612 AUTO_STRING (accept_from
, "accept from ");
4613 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4616 AUTO_STRING (open_from
, "open from ");
4617 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4620 #ifdef HAVE_GETADDRINFO_A
4622 check_for_dns (Lisp_Object proc
)
4624 struct Lisp_Process
*p
= XPROCESS (proc
);
4625 Lisp_Object ip_addresses
= Qnil
;
4628 if (! p
->dns_request
)
4631 int ret
= gai_error (p
->dns_request
);
4632 if (ret
== EAI_INPROGRESS
)
4635 /* We got a response. */
4638 struct addrinfo
*res
;
4640 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4642 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4643 (res
->ai_addr
, res
->ai_addrlen
),
4647 ip_addresses
= Fnreverse (ip_addresses
);
4649 /* The DNS lookup failed. */
4650 else if (EQ (p
->status
, Qconnect
))
4652 deactivate_process (proc
);
4653 pset_status (p
, (list2
4655 concat3 (build_string ("Name lookup of "),
4656 build_string (p
->dns_request
->ar_name
),
4657 build_string (" failed")))));
4660 free_dns_request (proc
);
4662 /* This process should not already be connected (or killed). */
4663 if (!EQ (p
->status
, Qconnect
))
4666 return ip_addresses
;
4669 #endif /* HAVE_GETADDRINFO_A */
4672 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4674 while (XPROCESS (process
)->infd
< 0
4675 && EQ (XPROCESS (process
)->status
, Qconnect
))
4677 add_to_log ("Waiting for socket from %s...", build_string (name
));
4678 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4683 wait_while_connecting (Lisp_Object process
)
4685 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4687 add_to_log ("Waiting for connection...");
4688 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4693 wait_for_tls_negotiation (Lisp_Object process
)
4696 while (XPROCESS (process
)->gnutls_p
4697 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4699 add_to_log ("Waiting for TLS...");
4700 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4705 /* This variable is different from waiting_for_input in keyboard.c.
4706 It is used to communicate to a lisp process-filter/sentinel (via the
4707 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4708 for user-input when that process-filter was called.
4709 waiting_for_input cannot be used as that is by definition 0 when
4710 lisp code is being evalled.
4711 This is also used in record_asynch_buffer_change.
4712 For that purpose, this must be 0
4713 when not inside wait_reading_process_output. */
4714 static int waiting_for_user_input_p
;
4717 wait_reading_process_output_unwind (int data
)
4719 waiting_for_user_input_p
= data
;
4722 /* This is here so breakpoints can be put on it. */
4724 wait_reading_process_output_1 (void)
4728 /* Read and dispose of subprocess output while waiting for timeout to
4729 elapse and/or keyboard input to be available.
4733 If negative, gobble data immediately available but don't wait for any.
4736 an additional duration to wait, measured in nanoseconds
4737 If TIME_LIMIT is zero, then:
4738 If NSECS == 0, there is no limit.
4739 If NSECS > 0, the timeout consists of NSECS only.
4740 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4743 0 to ignore keyboard input, or
4744 1 to return when input is available, or
4745 -1 meaning caller will actually read the input, so don't throw to
4746 the quit handler, or
4748 DO_DISPLAY means redisplay should be done to show subprocess
4749 output that arrives.
4751 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4752 (and gobble terminal input into the buffer if any arrives).
4754 If WAIT_PROC is specified, wait until something arrives from that
4757 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4758 (suspending output from other processes). A negative value
4759 means don't run any timers either.
4761 Return positive if we received input from WAIT_PROC (or from any
4762 process if WAIT_PROC is null), zero if we attempted to receive
4763 input but got none, and negative if we didn't even try. */
4766 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4768 Lisp_Object wait_for_cell
,
4769 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4779 struct timespec timeout
, end_time
, timer_delay
;
4780 struct timespec got_output_end_time
= invalid_timespec ();
4781 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4782 int got_some_output
= -1;
4783 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4784 bool retry_for_async
;
4786 ptrdiff_t count
= SPECPDL_INDEX ();
4788 /* Close to the current time if known, an invalid timespec otherwise. */
4789 struct timespec now
= invalid_timespec ();
4791 FD_ZERO (&Available
);
4794 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4795 && !(CONSP (wait_proc
->status
)
4796 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4797 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4799 record_unwind_protect_int (wait_reading_process_output_unwind
,
4800 waiting_for_user_input_p
);
4801 waiting_for_user_input_p
= read_kbd
;
4803 if (TYPE_MAXIMUM (time_t) < time_limit
)
4804 time_limit
= TYPE_MAXIMUM (time_t);
4806 if (time_limit
< 0 || nsecs
< 0)
4808 else if (time_limit
> 0 || nsecs
> 0)
4811 now
= current_timespec ();
4812 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4819 bool process_skipped
= false;
4821 /* If calling from keyboard input, do not quit
4822 since we want to return C-g as an input character.
4823 Otherwise, do pending quit if requested. */
4826 else if (pending_signals
)
4827 process_pending_signals ();
4829 /* Exit now if the cell we're waiting for became non-nil. */
4830 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4833 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4835 Lisp_Object process_list_head
, aproc
;
4836 struct Lisp_Process
*p
;
4838 retry_for_async
= false;
4839 FOR_EACH_PROCESS(process_list_head
, aproc
)
4841 p
= XPROCESS (aproc
);
4843 if (! wait_proc
|| p
== wait_proc
)
4845 #ifdef HAVE_GETADDRINFO_A
4846 /* Check for pending DNS requests. */
4849 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4850 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4851 connect_network_socket (aproc
, ip_addresses
);
4853 retry_for_async
= true;
4857 /* Continue TLS negotiation. */
4858 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4859 && p
->is_non_blocking_client
)
4861 gnutls_try_handshake (p
);
4862 p
->gnutls_handshakes_tried
++;
4864 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4866 gnutls_verify_boot (aproc
, Qnil
);
4867 finish_after_tls_connection (aproc
);
4871 retry_for_async
= true;
4872 if (p
->gnutls_handshakes_tried
4873 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4875 deactivate_process (aproc
);
4876 pset_status (p
, list2 (Qfailed
,
4877 build_string ("TLS negotiation failed")));
4885 #endif /* GETADDRINFO_A or GNUTLS */
4887 /* Compute time from now till when time limit is up. */
4888 /* Exit if already run out. */
4889 if (wait
== TIMEOUT
)
4891 if (!timespec_valid_p (now
))
4892 now
= current_timespec ();
4893 if (timespec_cmp (end_time
, now
) <= 0)
4895 timeout
= timespec_sub (end_time
, now
);
4898 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4900 /* Normally we run timers here.
4901 But not if wait_for_cell; in those cases,
4902 the wait is supposed to be short,
4903 and those callers cannot handle running arbitrary Lisp code here. */
4904 if (NILP (wait_for_cell
)
4905 && just_wait_proc
>= 0)
4909 unsigned old_timers_run
= timers_run
;
4910 struct buffer
*old_buffer
= current_buffer
;
4911 Lisp_Object old_window
= selected_window
;
4913 timer_delay
= timer_check ();
4915 /* If a timer has run, this might have changed buffers
4916 an alike. Make read_key_sequence aware of that. */
4917 if (timers_run
!= old_timers_run
4918 && (old_buffer
!= current_buffer
4919 || !EQ (old_window
, selected_window
))
4920 && waiting_for_user_input_p
== -1)
4921 record_asynch_buffer_change ();
4923 if (timers_run
!= old_timers_run
&& do_display
)
4924 /* We must retry, since a timer may have requeued itself
4925 and that could alter the time_delay. */
4926 redisplay_preserve_echo_area (9);
4930 while (!detect_input_pending ());
4932 /* If there is unread keyboard input, also return. */
4934 && requeued_events_pending_p ())
4937 /* This is so a breakpoint can be put here. */
4938 if (!timespec_valid_p (timer_delay
))
4939 wait_reading_process_output_1 ();
4942 /* Cause C-g and alarm signals to take immediate action,
4943 and cause input available signals to zero out timeout.
4945 It is important that we do this before checking for process
4946 activity. If we get a SIGCHLD after the explicit checks for
4947 process activity, timeout is the only way we will know. */
4949 set_waiting_for_input (&timeout
);
4951 /* If status of something has changed, and no input is
4952 available, notify the user of the change right away. After
4953 this explicit check, we'll let the SIGCHLD handler zap
4954 timeout to get our attention. */
4955 if (update_tick
!= process_tick
)
4960 if (kbd_on_hold_p ())
4963 Atemp
= input_wait_mask
;
4966 timeout
= make_timespec (0, 0);
4967 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4969 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4970 NULL
, &timeout
, NULL
)
4973 /* It's okay for us to do this and then continue with
4974 the loop, since timeout has already been zeroed out. */
4975 clear_waiting_for_input ();
4976 got_some_output
= status_notify (NULL
, wait_proc
);
4977 if (do_display
) redisplay_preserve_echo_area (13);
4981 /* Don't wait for output from a non-running process. Just
4982 read whatever data has already been received. */
4983 if (wait_proc
&& wait_proc
->raw_status_new
)
4984 update_status (wait_proc
);
4986 && ! EQ (wait_proc
->status
, Qrun
)
4987 && ! EQ (wait_proc
->status
, Qconnect
))
4989 bool read_some_bytes
= false;
4991 clear_waiting_for_input ();
4993 /* If data can be read from the process, do so until exhausted. */
4994 if (wait_proc
->infd
>= 0)
4996 XSETPROCESS (proc
, wait_proc
);
5000 int nread
= read_process_output (proc
, wait_proc
->infd
);
5003 if (errno
== EIO
|| errno
== EAGAIN
)
5006 if (errno
== EWOULDBLOCK
)
5012 if (got_some_output
< nread
)
5013 got_some_output
= nread
;
5016 read_some_bytes
= true;
5021 if (read_some_bytes
&& do_display
)
5022 redisplay_preserve_echo_area (10);
5027 /* Wait till there is something to do. */
5029 if (wait_proc
&& just_wait_proc
)
5031 if (wait_proc
->infd
< 0) /* Terminated. */
5033 FD_SET (wait_proc
->infd
, &Available
);
5037 else if (!NILP (wait_for_cell
))
5039 Available
= non_process_wait_mask
;
5046 Available
= non_keyboard_wait_mask
;
5048 Available
= input_wait_mask
;
5049 Writeok
= write_mask
;
5050 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5054 /* If frame size has changed or the window is newly mapped,
5055 redisplay now, before we start to wait. There is a race
5056 condition here; if a SIGIO arrives between now and the select
5057 and indicates that a frame is trashed, the select may block
5058 displaying a trashed screen. */
5059 if (frame_garbaged
&& do_display
)
5061 clear_waiting_for_input ();
5062 redisplay_preserve_echo_area (11);
5064 set_waiting_for_input (&timeout
);
5067 /* Skip the `select' call if input is available and we're
5068 waiting for keyboard input or a cell change (which can be
5069 triggered by processing X events). In the latter case, set
5070 nfds to 1 to avoid breaking the loop. */
5072 if ((read_kbd
|| !NILP (wait_for_cell
))
5073 && detect_input_pending ())
5075 nfds
= read_kbd
? 0 : 1;
5077 FD_ZERO (&Available
);
5081 /* Set the timeout for adaptive read buffering if any
5082 process has non-zero read_output_skip and non-zero
5083 read_output_delay, and we are not reading output for a
5084 specific process. It is not executed if
5085 Vprocess_adaptive_read_buffering is nil. */
5086 if (process_output_skip
&& check_delay
> 0)
5088 int adaptive_nsecs
= timeout
.tv_nsec
;
5089 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5090 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5091 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5093 proc
= chan_process
[channel
];
5096 /* Find minimum non-zero read_output_delay among the
5097 processes with non-zero read_output_skip. */
5098 if (XPROCESS (proc
)->read_output_delay
> 0)
5101 if (!XPROCESS (proc
)->read_output_skip
)
5103 FD_CLR (channel
, &Available
);
5104 process_skipped
= true;
5105 XPROCESS (proc
)->read_output_skip
= 0;
5106 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5107 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5110 timeout
= make_timespec (0, adaptive_nsecs
);
5111 process_output_skip
= 0;
5114 /* If we've got some output and haven't limited our timeout
5115 with adaptive read buffering, limit it. */
5116 if (got_some_output
> 0 && !process_skipped
5118 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5119 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5122 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5123 && timespec_valid_p (timer_delay
)
5124 && timespec_cmp (timer_delay
, timeout
) < 0)
5126 if (!timespec_valid_p (now
))
5127 now
= current_timespec ();
5128 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5129 if (!timespec_valid_p (got_output_end_time
)
5130 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5131 got_output_end_time
= timeout_abs
;
5132 timeout
= timer_delay
;
5135 got_output_end_time
= invalid_timespec ();
5137 /* NOW can become inaccurate if time can pass during pselect. */
5138 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5139 now
= invalid_timespec ();
5141 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5143 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> ASYNC_RETRY_NSEC
))
5146 timeout
.tv_nsec
= ASYNC_RETRY_NSEC
;
5150 #if defined (HAVE_NS)
5152 #elif defined (HAVE_GLIB)
5157 (max (max_process_desc
, max_input_desc
) + 1,
5159 (check_write
? &Writeok
: 0),
5160 NULL
, &timeout
, NULL
);
5163 /* GnuTLS buffers data internally. In lowat mode it leaves
5164 some data in the TCP buffers so that select works, but
5165 with custom pull/push functions we need to check if some
5166 data is available in the buffers manually. */
5169 fd_set tls_available
;
5172 FD_ZERO (&tls_available
);
5175 /* We're not waiting on a specific process, so loop
5176 through all the channels and check for data.
5177 This is a workaround needed for some versions of
5178 the gnutls library -- 2.12.14 has been confirmed
5180 http://comments.gmane.org/gmane.emacs.devel/145074 */
5181 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5182 if (! NILP (chan_process
[channel
]))
5184 struct Lisp_Process
*p
=
5185 XPROCESS (chan_process
[channel
]);
5186 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5187 && ((emacs_gnutls_record_check_pending
5192 eassert (p
->infd
== channel
);
5193 FD_SET (p
->infd
, &tls_available
);
5200 /* Check this specific channel. */
5201 if (wait_proc
->gnutls_p
/* Check for valid process. */
5202 && wait_proc
->gnutls_state
5203 /* Do we have pending data? */
5204 && ((emacs_gnutls_record_check_pending
5205 (wait_proc
->gnutls_state
))
5209 eassert (0 <= wait_proc
->infd
);
5210 /* Set to Available. */
5211 FD_SET (wait_proc
->infd
, &tls_available
);
5216 Available
= tls_available
;
5223 /* Make C-g and alarm signals set flags again. */
5224 clear_waiting_for_input ();
5226 /* If we woke up due to SIGWINCH, actually change size now. */
5227 do_pending_window_change (0);
5231 /* Exit the main loop if we've passed the requested timeout,
5232 or aren't skipping processes and got some output and
5233 haven't lowered our timeout due to timers or SIGIO and
5234 have waited a long amount of time due to repeated
5238 struct timespec cmp_time
5241 : (!process_skipped
&& got_some_output
> 0
5242 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5243 ? got_output_end_time
5244 : invalid_timespec ());
5245 if (timespec_valid_p (cmp_time
))
5247 now
= current_timespec ();
5248 if (timespec_cmp (cmp_time
, now
) <= 0)
5255 if (xerrno
== EINTR
)
5257 else if (xerrno
== EBADF
)
5260 report_file_errno ("Failed select", Qnil
, xerrno
);
5263 /* Check for keyboard input. */
5264 /* If there is any, return immediately
5265 to give it higher priority than subprocesses. */
5269 unsigned old_timers_run
= timers_run
;
5270 struct buffer
*old_buffer
= current_buffer
;
5271 Lisp_Object old_window
= selected_window
;
5274 if (detect_input_pending_run_timers (do_display
))
5276 swallow_events (do_display
);
5277 if (detect_input_pending_run_timers (do_display
))
5281 /* If a timer has run, this might have changed buffers
5282 an alike. Make read_key_sequence aware of that. */
5283 if (timers_run
!= old_timers_run
5284 && waiting_for_user_input_p
== -1
5285 && (old_buffer
!= current_buffer
5286 || !EQ (old_window
, selected_window
)))
5287 record_asynch_buffer_change ();
5293 /* If there is unread keyboard input, also return. */
5295 && requeued_events_pending_p ())
5298 /* If we are not checking for keyboard input now,
5299 do process events (but don't run any timers).
5300 This is so that X events will be processed.
5301 Otherwise they may have to wait until polling takes place.
5302 That would causes delays in pasting selections, for example.
5304 (We used to do this only if wait_for_cell.) */
5305 if (read_kbd
== 0 && detect_input_pending ())
5307 swallow_events (do_display
);
5308 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5309 if (detect_input_pending ())
5314 /* Exit now if the cell we're waiting for became non-nil. */
5315 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5319 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5320 go read it. This can happen with X on BSD after logging out.
5321 In that case, there really is no input and no SIGIO,
5322 but select says there is input. */
5324 if (read_kbd
&& interrupt_input
5325 && keyboard_bit_set (&Available
) && ! noninteractive
)
5326 handle_input_available_signal (SIGIO
);
5329 /* If checking input just got us a size-change event from X,
5330 obey it now if we should. */
5331 if (read_kbd
|| ! NILP (wait_for_cell
))
5332 do_pending_window_change (0);
5334 /* Check for data from a process. */
5335 if (no_avail
|| nfds
== 0)
5338 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5340 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5342 && ((d
->condition
& FOR_READ
5343 && FD_ISSET (channel
, &Available
))
5344 || (d
->condition
& FOR_WRITE
5345 && FD_ISSET (channel
, &write_mask
))))
5346 d
->func (channel
, d
->data
);
5349 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5351 if (FD_ISSET (channel
, &Available
)
5352 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5353 && !FD_ISSET (channel
, &non_process_wait_mask
))
5357 /* If waiting for this channel, arrange to return as
5358 soon as no more input to be processed. No more
5360 proc
= chan_process
[channel
];
5364 /* If this is a server stream socket, accept connection. */
5365 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5367 server_accept_connection (proc
, channel
);
5371 /* Read data from the process, starting with our
5372 buffered-ahead character if we have one. */
5374 nread
= read_process_output (proc
, channel
);
5375 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5376 && got_some_output
< nread
)
5377 got_some_output
= nread
;
5380 /* Vacuum up any leftovers without waiting. */
5381 if (wait_proc
== XPROCESS (proc
))
5383 /* Since read_process_output can run a filter,
5384 which can call accept-process-output,
5385 don't try to read from any other processes
5386 before doing the select again. */
5387 FD_ZERO (&Available
);
5390 redisplay_preserve_echo_area (12);
5393 else if (nread
== -1 && errno
== EWOULDBLOCK
)
5396 else if (nread
== -1 && errno
== EAGAIN
)
5399 /* FIXME: Is this special case still needed? */
5400 /* Note that we cannot distinguish between no input
5401 available now and a closed pipe.
5402 With luck, a closed pipe will be accompanied by
5403 subprocess termination and SIGCHLD. */
5404 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5405 && !PIPECONN_P (proc
))
5409 /* On some OSs with ptys, when the process on one end of
5410 a pty exits, the other end gets an error reading with
5411 errno = EIO instead of getting an EOF (0 bytes read).
5412 Therefore, if we get an error reading and errno =
5413 EIO, just continue, because the child process has
5414 exited and should clean itself up soon (e.g. when we
5416 else if (nread
== -1 && errno
== EIO
)
5418 struct Lisp_Process
*p
= XPROCESS (proc
);
5420 /* Clear the descriptor now, so we only raise the
5422 FD_CLR (channel
, &input_wait_mask
);
5423 FD_CLR (channel
, &non_keyboard_wait_mask
);
5427 /* If the EIO occurs on a pty, the SIGCHLD handler's
5428 waitpid call will not find the process object to
5429 delete. Do it here. */
5430 p
->tick
= ++process_tick
;
5431 pset_status (p
, Qfailed
);
5434 #endif /* HAVE_PTYS */
5435 /* If we can detect process termination, don't consider the
5436 process gone just because its pipe is closed. */
5437 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5438 && !PIPECONN_P (proc
))
5440 else if (nread
== 0 && PIPECONN_P (proc
))
5442 /* Preserve status of processes already terminated. */
5443 XPROCESS (proc
)->tick
= ++process_tick
;
5444 deactivate_process (proc
);
5445 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5446 pset_status (XPROCESS (proc
),
5447 list2 (Qexit
, make_number (0)));
5451 /* Preserve status of processes already terminated. */
5452 XPROCESS (proc
)->tick
= ++process_tick
;
5453 deactivate_process (proc
);
5454 if (XPROCESS (proc
)->raw_status_new
)
5455 update_status (XPROCESS (proc
));
5456 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5457 pset_status (XPROCESS (proc
),
5458 list2 (Qexit
, make_number (256)));
5461 if (FD_ISSET (channel
, &Writeok
)
5462 && FD_ISSET (channel
, &connect_wait_mask
))
5464 struct Lisp_Process
*p
;
5466 FD_CLR (channel
, &connect_wait_mask
);
5467 FD_CLR (channel
, &write_mask
);
5468 if (--num_pending_connects
< 0)
5471 proc
= chan_process
[channel
];
5475 p
= XPROCESS (proc
);
5478 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5479 So only use it on systems where it is known to work. */
5481 socklen_t xlen
= sizeof (xerrno
);
5482 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5487 struct sockaddr pname
;
5488 socklen_t pnamelen
= sizeof (pname
);
5490 /* If connection failed, getpeername will fail. */
5492 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5494 /* Obtain connect failure code through error slippage. */
5497 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5504 p
->tick
= ++process_tick
;
5505 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5506 deactivate_process (proc
);
5511 /* If we have an incompletely set up TLS connection,
5512 then defer the sentinel signaling until
5514 if (NILP (p
->gnutls_boot_parameters
)
5518 pset_status (p
, Qrun
);
5519 /* Execute the sentinel here. If we had relied on
5520 status_notify to do it later, it will read input
5521 from the process before calling the sentinel. */
5522 exec_sentinel (proc
, build_string ("open\n"));
5525 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5526 && !EQ (p
->command
, Qt
))
5528 FD_SET (p
->infd
, &input_wait_mask
);
5529 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5533 } /* End for each file descriptor. */
5534 } /* End while exit conditions not met. */
5536 unbind_to (count
, Qnil
);
5538 /* If calling from keyboard input, do not quit
5539 since we want to return C-g as an input character.
5540 Otherwise, do pending quit if requested. */
5543 /* Prevent input_pending from remaining set if we quit. */
5544 clear_input_pending ();
5548 return got_some_output
;
5551 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5554 read_process_output_call (Lisp_Object fun_and_args
)
5556 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5560 read_process_output_error_handler (Lisp_Object error_val
)
5562 cmd_error_internal (error_val
, "error in process filter: ");
5564 update_echo_area ();
5565 Fsleep_for (make_number (2), Qnil
);
5570 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5572 struct coding_system
*coding
);
5574 /* Read pending output from the process channel,
5575 starting with our buffered-ahead character if we have one.
5576 Yield number of decoded characters read.
5578 This function reads at most 4096 characters.
5579 If you want to read all available subprocess output,
5580 you must call it repeatedly until it returns zero.
5582 The characters read are decoded according to PROC's coding-system
5586 read_process_output (Lisp_Object proc
, int channel
)
5589 struct Lisp_Process
*p
= XPROCESS (proc
);
5590 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5591 int carryover
= p
->decoding_carryover
;
5592 enum { readmax
= 4096 };
5593 ptrdiff_t count
= SPECPDL_INDEX ();
5594 Lisp_Object odeactivate
;
5595 char chars
[sizeof coding
->carryover
+ readmax
];
5598 /* See the comment above. */
5599 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5601 #ifdef DATAGRAM_SOCKETS
5602 /* We have a working select, so proc_buffered_char is always -1. */
5603 if (DATAGRAM_CHAN_P (channel
))
5605 socklen_t len
= datagram_address
[channel
].len
;
5606 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5607 0, datagram_address
[channel
].sa
, &len
);
5612 bool buffered
= proc_buffered_char
[channel
] >= 0;
5615 chars
[carryover
] = proc_buffered_char
[channel
];
5616 proc_buffered_char
[channel
] = -1;
5619 if (p
->gnutls_p
&& p
->gnutls_state
)
5620 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5621 readmax
- buffered
);
5624 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5625 readmax
- buffered
);
5626 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5628 int delay
= p
->read_output_delay
;
5631 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5634 process_output_delay_count
++;
5635 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5638 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5640 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5642 process_output_delay_count
--;
5644 p
->read_output_delay
= delay
;
5647 p
->read_output_skip
= 1;
5648 process_output_skip
= 1;
5652 nbytes
+= buffered
&& nbytes
<= 0;
5655 p
->decoding_carryover
= 0;
5657 /* At this point, NBYTES holds number of bytes just received
5658 (including the one in proc_buffered_char[channel]). */
5661 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5663 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5666 /* Now set NBYTES how many bytes we must decode. */
5667 nbytes
+= carryover
;
5669 odeactivate
= Vdeactivate_mark
;
5670 /* There's no good reason to let process filters change the current
5671 buffer, and many callers of accept-process-output, sit-for, and
5672 friends don't expect current-buffer to be changed from under them. */
5673 record_unwind_current_buffer ();
5675 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5677 /* Handling the process output should not deactivate the mark. */
5678 Vdeactivate_mark
= odeactivate
;
5680 unbind_to (count
, Qnil
);
5685 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5687 struct coding_system
*coding
)
5689 Lisp_Object outstream
= p
->filter
;
5691 bool outer_running_asynch_code
= running_asynch_code
;
5692 int waiting
= waiting_for_user_input_p
;
5695 Lisp_Object obuffer
, okeymap
;
5696 XSETBUFFER (obuffer
, current_buffer
);
5697 okeymap
= BVAR (current_buffer
, keymap
);
5700 /* We inhibit quit here instead of just catching it so that
5701 hitting ^G when a filter happens to be running won't screw
5703 specbind (Qinhibit_quit
, Qt
);
5704 specbind (Qlast_nonmenu_event
, Qt
);
5706 /* In case we get recursively called,
5707 and we already saved the match data nonrecursively,
5708 save the same match data in safely recursive fashion. */
5709 if (outer_running_asynch_code
)
5712 /* Don't clobber the CURRENT match data, either! */
5713 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5714 restore_search_regs ();
5715 record_unwind_save_match_data ();
5716 Fset_match_data (tem
, Qt
);
5719 /* For speed, if a search happens within this code,
5720 save the match data in a special nonrecursive fashion. */
5721 running_asynch_code
= 1;
5723 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5724 text
= coding
->dst_object
;
5725 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5726 /* A new coding system might be found. */
5727 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5729 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5731 /* Don't call setup_coding_system for
5732 proc_decode_coding_system[channel] here. It is done in
5733 detect_coding called via decode_coding above. */
5735 /* If a coding system for encoding is not yet decided, we set
5736 it as the same as coding-system for decoding.
5738 But, before doing that we must check if
5739 proc_encode_coding_system[p->outfd] surely points to a
5740 valid memory because p->outfd will be changed once EOF is
5741 sent to the process. */
5742 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5743 && proc_encode_coding_system
[p
->outfd
])
5745 pset_encode_coding_system
5746 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5747 setup_coding_system (p
->encode_coding_system
,
5748 proc_encode_coding_system
[p
->outfd
]);
5752 if (coding
->carryover_bytes
> 0)
5754 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5755 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5756 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5757 coding
->carryover_bytes
);
5758 p
->decoding_carryover
= coding
->carryover_bytes
;
5760 if (SBYTES (text
) > 0)
5761 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5762 sometimes it's simply wrong to wrap (e.g. when called from
5763 accept-process-output). */
5764 internal_condition_case_1 (read_process_output_call
,
5765 list3 (outstream
, make_lisp_proc (p
), text
),
5766 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5767 read_process_output_error_handler
);
5769 /* If we saved the match data nonrecursively, restore it now. */
5770 restore_search_regs ();
5771 running_asynch_code
= outer_running_asynch_code
;
5773 /* Restore waiting_for_user_input_p as it was
5774 when we were called, in case the filter clobbered it. */
5775 waiting_for_user_input_p
= waiting
;
5777 #if 0 /* Call record_asynch_buffer_change unconditionally,
5778 because we might have changed minor modes or other things
5779 that affect key bindings. */
5780 if (! EQ (Fcurrent_buffer (), obuffer
)
5781 || ! EQ (current_buffer
->keymap
, okeymap
))
5783 /* But do it only if the caller is actually going to read events.
5784 Otherwise there's no need to make him wake up, and it could
5785 cause trouble (for example it would make sit_for return). */
5786 if (waiting_for_user_input_p
== -1)
5787 record_asynch_buffer_change ();
5790 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5791 Sinternal_default_process_filter
, 2, 2, 0,
5792 doc
: /* Function used as default process filter.
5793 This inserts the process's output into its buffer, if there is one.
5794 Otherwise it discards the output. */)
5795 (Lisp_Object proc
, Lisp_Object text
)
5797 struct Lisp_Process
*p
;
5800 CHECK_PROCESS (proc
);
5801 p
= XPROCESS (proc
);
5802 CHECK_STRING (text
);
5804 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5806 Lisp_Object old_read_only
;
5807 ptrdiff_t old_begv
, old_zv
;
5808 ptrdiff_t old_begv_byte
, old_zv_byte
;
5809 ptrdiff_t before
, before_byte
;
5810 ptrdiff_t opoint_byte
;
5813 Fset_buffer (p
->buffer
);
5815 opoint_byte
= PT_BYTE
;
5816 old_read_only
= BVAR (current_buffer
, read_only
);
5819 old_begv_byte
= BEGV_BYTE
;
5820 old_zv_byte
= ZV_BYTE
;
5822 bset_read_only (current_buffer
, Qnil
);
5824 /* Insert new output into buffer at the current end-of-output
5825 marker, thus preserving logical ordering of input and output. */
5826 if (XMARKER (p
->mark
)->buffer
)
5827 set_point_from_marker (p
->mark
);
5829 SET_PT_BOTH (ZV
, ZV_BYTE
);
5831 before_byte
= PT_BYTE
;
5833 /* If the output marker is outside of the visible region, save
5834 the restriction and widen. */
5835 if (! (BEGV
<= PT
&& PT
<= ZV
))
5838 /* Adjust the multibyteness of TEXT to that of the buffer. */
5839 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5840 != ! STRING_MULTIBYTE (text
))
5841 text
= (STRING_MULTIBYTE (text
)
5842 ? Fstring_as_unibyte (text
)
5843 : Fstring_to_multibyte (text
));
5844 /* Insert before markers in case we are inserting where
5845 the buffer's mark is, and the user's next command is Meta-y. */
5846 insert_from_string_before_markers (text
, 0, 0,
5847 SCHARS (text
), SBYTES (text
), 0);
5849 /* Make sure the process marker's position is valid when the
5850 process buffer is changed in the signal_after_change above.
5851 W3 is known to do that. */
5852 if (BUFFERP (p
->buffer
)
5853 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5854 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5856 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5858 update_mode_lines
= 23;
5860 /* Make sure opoint and the old restrictions
5861 float ahead of any new text just as point would. */
5862 if (opoint
>= before
)
5864 opoint
+= PT
- before
;
5865 opoint_byte
+= PT_BYTE
- before_byte
;
5867 if (old_begv
> before
)
5869 old_begv
+= PT
- before
;
5870 old_begv_byte
+= PT_BYTE
- before_byte
;
5872 if (old_zv
>= before
)
5874 old_zv
+= PT
- before
;
5875 old_zv_byte
+= PT_BYTE
- before_byte
;
5878 /* If the restriction isn't what it should be, set it. */
5879 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5880 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5882 bset_read_only (current_buffer
, old_read_only
);
5883 SET_PT_BOTH (opoint
, opoint_byte
);
5888 /* Sending data to subprocess. */
5890 /* In send_process, when a write fails temporarily,
5891 wait_reading_process_output is called. It may execute user code,
5892 e.g. timers, that attempts to write new data to the same process.
5893 We must ensure that data is sent in the right order, and not
5894 interspersed half-completed with other writes (Bug#10815). This is
5895 handled by the write_queue element of struct process. It is a list
5896 with each entry having the form
5898 (string . (offset . length))
5900 where STRING is a lisp string, OFFSET is the offset into the
5901 string's byte sequence from which we should begin to send, and
5902 LENGTH is the number of bytes left to send. */
5904 /* Create a new entry in write_queue.
5905 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5906 BUF is a pointer to the string sequence of the input_obj or a C
5907 string in case of Qt or Qnil. */
5910 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5911 const char *buf
, ptrdiff_t len
, bool front
)
5914 Lisp_Object entry
, obj
;
5916 if (STRINGP (input_obj
))
5918 offset
= buf
- SSDATA (input_obj
);
5924 obj
= make_unibyte_string (buf
, len
);
5927 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5930 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5932 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5935 /* Remove the first element in the write_queue of process P, put its
5936 contents in OBJ, BUF and LEN, and return true. If the
5937 write_queue is empty, return false. */
5940 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5941 const char **buf
, ptrdiff_t *len
)
5943 Lisp_Object entry
, offset_length
;
5946 if (NILP (p
->write_queue
))
5949 entry
= XCAR (p
->write_queue
);
5950 pset_write_queue (p
, XCDR (p
->write_queue
));
5952 *obj
= XCAR (entry
);
5953 offset_length
= XCDR (entry
);
5955 *len
= XINT (XCDR (offset_length
));
5956 offset
= XINT (XCAR (offset_length
));
5957 *buf
= SSDATA (*obj
) + offset
;
5962 /* Send some data to process PROC.
5963 BUF is the beginning of the data; LEN is the number of characters.
5964 OBJECT is the Lisp object that the data comes from. If OBJECT is
5965 nil or t, it means that the data comes from C string.
5967 If OBJECT is not nil, the data is encoded by PROC's coding-system
5968 for encoding before it is sent.
5970 This function can evaluate Lisp code and can garbage collect. */
5973 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5976 struct Lisp_Process
*p
= XPROCESS (proc
);
5978 struct coding_system
*coding
;
5980 if (NETCONN_P (proc
))
5982 wait_while_connecting (proc
);
5983 wait_for_tls_negotiation (proc
);
5986 if (p
->raw_status_new
)
5988 if (! EQ (p
->status
, Qrun
))
5989 error ("Process %s not running", SDATA (p
->name
));
5991 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5993 coding
= proc_encode_coding_system
[p
->outfd
];
5994 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5996 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5997 || (BUFFERP (object
)
5998 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6001 pset_encode_coding_system
6002 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6003 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6005 /* The coding system for encoding was changed to raw-text
6006 because we sent a unibyte text previously. Now we are
6007 sending a multibyte text, thus we must encode it by the
6008 original coding system specified for the current process.
6010 Another reason we come here is that the coding system
6011 was just complemented and a new one was returned by
6012 complement_process_encoding_system. */
6013 setup_coding_system (p
->encode_coding_system
, coding
);
6014 Vlast_coding_system_used
= p
->encode_coding_system
;
6016 coding
->src_multibyte
= 1;
6020 coding
->src_multibyte
= 0;
6021 /* For sending a unibyte text, character code conversion should
6022 not take place but EOL conversion should. So, setup raw-text
6023 or one of the subsidiary if we have not yet done it. */
6024 if (CODING_REQUIRE_ENCODING (coding
))
6026 if (CODING_REQUIRE_FLUSHING (coding
))
6028 /* But, before changing the coding, we must flush out data. */
6029 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6030 send_process (proc
, "", 0, Qt
);
6031 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6033 setup_coding_system (raw_text_coding_system
6034 (Vlast_coding_system_used
),
6036 coding
->src_multibyte
= 0;
6039 coding
->dst_multibyte
= 0;
6041 if (CODING_REQUIRE_ENCODING (coding
))
6043 coding
->dst_object
= Qt
;
6044 if (BUFFERP (object
))
6046 ptrdiff_t from_byte
, from
, to
;
6047 ptrdiff_t save_pt
, save_pt_byte
;
6048 struct buffer
*cur
= current_buffer
;
6050 set_buffer_internal (XBUFFER (object
));
6051 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6053 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6054 from
= BYTE_TO_CHAR (from_byte
);
6055 to
= BYTE_TO_CHAR (from_byte
+ len
);
6056 TEMP_SET_PT_BOTH (from
, from_byte
);
6057 encode_coding_object (coding
, object
, from
, from_byte
,
6058 to
, from_byte
+ len
, Qt
);
6059 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6060 set_buffer_internal (cur
);
6062 else if (STRINGP (object
))
6064 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6065 SBYTES (object
), Qt
);
6069 coding
->dst_object
= make_unibyte_string (buf
, len
);
6070 coding
->produced
= len
;
6073 len
= coding
->produced
;
6074 object
= coding
->dst_object
;
6075 buf
= SSDATA (object
);
6078 /* If there is already data in the write_queue, put the new data
6079 in the back of queue. Otherwise, ignore it. */
6080 if (!NILP (p
->write_queue
))
6081 write_queue_push (p
, object
, buf
, len
, 0);
6083 do /* while !NILP (p->write_queue) */
6085 ptrdiff_t cur_len
= -1;
6086 const char *cur_buf
;
6087 Lisp_Object cur_object
;
6089 /* If write_queue is empty, ignore it. */
6090 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6094 cur_object
= object
;
6099 /* Send this batch, using one or more write calls. */
6100 ptrdiff_t written
= 0;
6101 int outfd
= p
->outfd
;
6102 #ifdef DATAGRAM_SOCKETS
6103 if (DATAGRAM_CHAN_P (outfd
))
6105 rv
= sendto (outfd
, cur_buf
, cur_len
,
6106 0, datagram_address
[outfd
].sa
,
6107 datagram_address
[outfd
].len
);
6110 else if (errno
== EMSGSIZE
)
6111 report_file_error ("Sending datagram", proc
);
6117 if (p
->gnutls_p
&& p
->gnutls_state
)
6118 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6121 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6122 rv
= (written
? 0 : -1);
6123 if (p
->read_output_delay
> 0
6124 && p
->adaptive_read_buffering
== 1)
6126 p
->read_output_delay
= 0;
6127 process_output_delay_count
--;
6128 p
->read_output_skip
= 0;
6136 || errno
== EWOULDBLOCK
6139 /* Buffer is full. Wait, accepting input;
6140 that may allow the program
6141 to finish doing output and read more. */
6143 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6144 /* A gross hack to work around a bug in FreeBSD.
6145 In the following sequence, read(2) returns
6149 write(2) 954 bytes, get EAGAIN
6150 read(2) 1024 bytes in process_read_output
6151 read(2) 11 bytes in process_read_output
6153 That is, read(2) returns more bytes than have
6154 ever been written successfully. The 1033 bytes
6155 read are the 1022 bytes written successfully
6156 after processing (for example with CRs added if
6157 the terminal is set up that way which it is
6158 here). The same bytes will be seen again in a
6159 later read(2), without the CRs. */
6161 if (errno
== EAGAIN
)
6164 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6166 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6168 /* Put what we should have written in wait_queue. */
6169 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6170 wait_reading_process_output (0, 20 * 1000 * 1000,
6171 0, 0, Qnil
, NULL
, 0);
6172 /* Reread queue, to see what is left. */
6175 else if (errno
== EPIPE
)
6177 p
->raw_status_new
= 0;
6178 pset_status (p
, list2 (Qexit
, make_number (256)));
6179 p
->tick
= ++process_tick
;
6180 deactivate_process (proc
);
6181 error ("process %s no longer connected to pipe; closed it",
6185 /* This is a real error. */
6186 report_file_error ("Writing to process", proc
);
6192 while (!NILP (p
->write_queue
));
6195 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6197 doc
: /* Send current contents of region as input to PROCESS.
6198 PROCESS may be a process, a buffer, the name of a process or buffer, or
6199 nil, indicating the current buffer's process.
6200 Called from program, takes three arguments, PROCESS, START and END.
6201 If the region is more than 500 characters long,
6202 it is sent in several bunches. This may happen even for shorter regions.
6203 Output from processes can arrive in between bunches.
6205 If PROCESS is a non-blocking network process that hasn't been fully
6206 set up yet, this function will block until socket setup has completed. */)
6207 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6209 Lisp_Object proc
= get_process (process
);
6210 ptrdiff_t start_byte
, end_byte
;
6212 validate_region (&start
, &end
);
6214 start_byte
= CHAR_TO_BYTE (XINT (start
));
6215 end_byte
= CHAR_TO_BYTE (XINT (end
));
6217 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6218 move_gap_both (XINT (start
), start_byte
);
6220 if (NETCONN_P (proc
))
6221 wait_while_connecting (proc
);
6223 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6224 end_byte
- start_byte
, Fcurrent_buffer ());
6229 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6231 doc
: /* Send PROCESS the contents of STRING as input.
6232 PROCESS may be a process, a buffer, the name of a process or buffer, or
6233 nil, indicating the current buffer's process.
6234 If STRING is more than 500 characters long,
6235 it is sent in several bunches. This may happen even for shorter strings.
6236 Output from processes can arrive in between bunches.
6238 If PROCESS is a non-blocking network process that hasn't been fully
6239 set up yet, this function will block until socket setup has completed. */)
6240 (Lisp_Object process
, Lisp_Object string
)
6242 CHECK_STRING (string
);
6243 Lisp_Object proc
= get_process (process
);
6244 send_process (proc
, SSDATA (string
),
6245 SBYTES (string
), string
);
6249 /* Return the foreground process group for the tty/pty that
6250 the process P uses. */
6252 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6257 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6260 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6261 master side. Try the slave side. */
6262 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6266 ioctl (fd
, TIOCGPGRP
, &gid
);
6270 #endif /* defined (TIOCGPGRP ) */
6275 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6276 Sprocess_running_child_p
, 0, 1, 0,
6277 doc
: /* Return non-nil if PROCESS has given the terminal to a
6278 child. If the operating system does not make it possible to find out,
6279 return t. If we can find out, return the numeric ID of the foreground
6281 (Lisp_Object process
)
6283 /* Initialize in case ioctl doesn't exist or gives an error,
6284 in a way that will cause returning t. */
6285 Lisp_Object proc
= get_process (process
);
6286 struct Lisp_Process
*p
= XPROCESS (proc
);
6288 if (!EQ (p
->type
, Qreal
))
6289 error ("Process %s is not a subprocess",
6292 error ("Process %s is not active",
6295 pid_t gid
= emacs_get_tty_pgrp (p
);
6300 return make_number (gid
);
6304 /* Send a signal number SIGNO to PROCESS.
6305 If CURRENT_GROUP is t, that means send to the process group
6306 that currently owns the terminal being used to communicate with PROCESS.
6307 This is used for various commands in shell mode.
6308 If CURRENT_GROUP is lambda, that means send to the process group
6309 that currently owns the terminal, but only if it is NOT the shell itself.
6311 If NOMSG is false, insert signal-announcements into process's buffers
6314 If we can, we try to signal PROCESS by sending control characters
6315 down the pty. This allows us to signal inferiors who have changed
6316 their uid, for which kill would return an EPERM error. */
6319 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6323 struct Lisp_Process
*p
;
6327 proc
= get_process (process
);
6328 p
= XPROCESS (proc
);
6330 if (!EQ (p
->type
, Qreal
))
6331 error ("Process %s is not a subprocess",
6334 error ("Process %s is not active",
6338 current_group
= Qnil
;
6340 /* If we are using pgrps, get a pgrp number and make it negative. */
6341 if (NILP (current_group
))
6342 /* Send the signal to the shell's process group. */
6346 #ifdef SIGNALS_VIA_CHARACTERS
6347 /* If possible, send signals to the entire pgrp
6348 by sending an input character to it. */
6351 cc_t
*sig_char
= NULL
;
6353 tcgetattr (p
->infd
, &t
);
6358 sig_char
= &t
.c_cc
[VINTR
];
6362 sig_char
= &t
.c_cc
[VQUIT
];
6367 sig_char
= &t
.c_cc
[VSWTCH
];
6369 sig_char
= &t
.c_cc
[VSUSP
];
6374 if (sig_char
&& *sig_char
!= CDISABLE
)
6376 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6379 /* If we can't send the signal with a character,
6380 fall through and send it another way. */
6382 /* The code above may fall through if it can't
6383 handle the signal. */
6384 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6387 /* Get the current pgrp using the tty itself, if we have that.
6388 Otherwise, use the pty to get the pgrp.
6389 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6390 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6391 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6392 His patch indicates that if TIOCGPGRP returns an error, then
6393 we should just assume that p->pid is also the process group id. */
6395 gid
= emacs_get_tty_pgrp (p
);
6398 /* If we can't get the information, assume
6399 the shell owns the tty. */
6402 /* It is not clear whether anything really can set GID to -1.
6403 Perhaps on some system one of those ioctls can or could do so.
6404 Or perhaps this is vestigial. */
6407 #else /* ! defined (TIOCGPGRP) */
6408 /* Can't select pgrps on this system, so we know that
6409 the child itself heads the pgrp. */
6411 #endif /* ! defined (TIOCGPGRP) */
6413 /* If current_group is lambda, and the shell owns the terminal,
6414 don't send any signal. */
6415 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6420 if (signo
== SIGCONT
)
6422 p
->raw_status_new
= 0;
6423 pset_status (p
, Qrun
);
6424 p
->tick
= ++process_tick
;
6427 status_notify (NULL
, NULL
);
6428 redisplay_preserve_echo_area (13);
6434 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6435 We don't know whether the bug is fixed in later HP-UX versions. */
6436 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6440 /* If we don't have process groups, send the signal to the immediate
6441 subprocess. That isn't really right, but it's better than any
6442 obvious alternative. */
6443 pid_t pid
= no_pgrp
? gid
: - gid
;
6445 /* Do not kill an already-reaped process, as that could kill an
6446 innocent bystander that happens to have the same process ID. */
6448 block_child_signal (&oldset
);
6451 unblock_child_signal (&oldset
);
6454 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6455 doc
: /* Interrupt process PROCESS.
6456 PROCESS may be a process, a buffer, or the name of a process or buffer.
6457 No arg or nil means current buffer's process.
6458 Second arg CURRENT-GROUP non-nil means send signal to
6459 the current process-group of the process's controlling terminal
6460 rather than to the process's own process group.
6461 If the process is a shell, this means interrupt current subjob
6462 rather than the shell.
6464 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6465 don't send the signal. */)
6466 (Lisp_Object process
, Lisp_Object current_group
)
6468 process_send_signal (process
, SIGINT
, current_group
, 0);
6472 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6473 doc
: /* Kill process PROCESS. May be process or name of one.
6474 See function `interrupt-process' for more details on usage. */)
6475 (Lisp_Object process
, Lisp_Object current_group
)
6477 process_send_signal (process
, SIGKILL
, current_group
, 0);
6481 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6482 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6483 See function `interrupt-process' for more details on usage. */)
6484 (Lisp_Object process
, Lisp_Object current_group
)
6486 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6490 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6491 doc
: /* Stop process PROCESS. May be process or name of one.
6492 See function `interrupt-process' for more details on usage.
6493 If PROCESS is a network or serial process, inhibit handling of incoming
6495 (Lisp_Object process
, Lisp_Object current_group
)
6497 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6498 || PIPECONN_P (process
)))
6500 struct Lisp_Process
*p
;
6502 p
= XPROCESS (process
);
6503 if (NILP (p
->command
)
6506 FD_CLR (p
->infd
, &input_wait_mask
);
6507 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6509 pset_command (p
, Qt
);
6513 error ("No SIGTSTP support");
6515 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6520 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6521 doc
: /* Continue process PROCESS. May be process or name of one.
6522 See function `interrupt-process' for more details on usage.
6523 If PROCESS is a network or serial process, resume handling of incoming
6525 (Lisp_Object process
, Lisp_Object current_group
)
6527 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6528 || PIPECONN_P (process
)))
6530 struct Lisp_Process
*p
;
6532 p
= XPROCESS (process
);
6533 if (EQ (p
->command
, Qt
)
6535 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6537 FD_SET (p
->infd
, &input_wait_mask
);
6538 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6540 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6541 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6542 #else /* not WINDOWSNT */
6543 tcflush (p
->infd
, TCIFLUSH
);
6544 #endif /* not WINDOWSNT */
6546 pset_command (p
, Qnil
);
6550 process_send_signal (process
, SIGCONT
, current_group
, 0);
6552 error ("No SIGCONT support");
6557 /* Return the integer value of the signal whose abbreviation is ABBR,
6558 or a negative number if there is no such signal. */
6560 abbr_to_signal (char const *name
)
6563 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6565 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6568 for (i
= 0; i
< sizeof sigbuf
; i
++)
6570 sigbuf
[i
] = c_toupper (name
[i
]);
6572 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6578 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6579 2, 2, "sProcess (name or number): \nnSignal code: ",
6580 doc
: /* Send PROCESS the signal with code SIGCODE.
6581 PROCESS may also be a number specifying the process id of the
6582 process to signal; in this case, the process need not be a child of
6584 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6585 (Lisp_Object process
, Lisp_Object sigcode
)
6590 if (STRINGP (process
))
6592 Lisp_Object tem
= Fget_process (process
);
6595 Lisp_Object process_number
6596 = string_to_number (SSDATA (process
), 10, 1);
6597 if (NUMBERP (process_number
))
6598 tem
= process_number
;
6602 else if (!NUMBERP (process
))
6603 process
= get_process (process
);
6608 if (NUMBERP (process
))
6609 CONS_TO_INTEGER (process
, pid_t
, pid
);
6612 CHECK_PROCESS (process
);
6613 pid
= XPROCESS (process
)->pid
;
6615 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6618 if (INTEGERP (sigcode
))
6620 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6621 signo
= XINT (sigcode
);
6627 CHECK_SYMBOL (sigcode
);
6628 name
= SSDATA (SYMBOL_NAME (sigcode
));
6630 signo
= abbr_to_signal (name
);
6632 error ("Undefined signal name %s", name
);
6635 return make_number (kill (pid
, signo
));
6638 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6639 doc
: /* Make PROCESS see end-of-file in its input.
6640 EOF comes after any text already sent to it.
6641 PROCESS may be a process, a buffer, the name of a process or buffer, or
6642 nil, indicating the current buffer's process.
6643 If PROCESS is a network connection, or is a process communicating
6644 through a pipe (as opposed to a pty), then you cannot send any more
6645 text to PROCESS after you call this function.
6646 If PROCESS is a serial process, wait until all output written to the
6647 process has been transmitted to the serial port. */)
6648 (Lisp_Object process
)
6651 struct coding_system
*coding
= NULL
;
6654 proc
= get_process (process
);
6656 if (NETCONN_P (proc
))
6657 wait_while_connecting (proc
);
6659 if (DATAGRAM_CONN_P (proc
))
6663 outfd
= XPROCESS (proc
)->outfd
;
6665 coding
= proc_encode_coding_system
[outfd
];
6667 /* Make sure the process is really alive. */
6668 if (XPROCESS (proc
)->raw_status_new
)
6669 update_status (XPROCESS (proc
));
6670 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6671 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6673 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6675 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6676 send_process (proc
, "", 0, Qnil
);
6679 if (XPROCESS (proc
)->pty_flag
)
6680 send_process (proc
, "\004", 1, Qnil
);
6681 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6684 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6685 report_file_error ("Failed tcdrain", Qnil
);
6686 #endif /* not WINDOWSNT */
6687 /* Do nothing on Windows because writes are blocking. */
6691 struct Lisp_Process
*p
= XPROCESS (proc
);
6692 int old_outfd
= p
->outfd
;
6695 #ifdef HAVE_SHUTDOWN
6696 /* If this is a network connection, or socketpair is used
6697 for communication with the subprocess, call shutdown to cause EOF.
6698 (In some old system, shutdown to socketpair doesn't work.
6699 Then we just can't win.) */
6701 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6702 shutdown (old_outfd
, 1);
6704 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6705 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6707 report_file_error ("Opening null device", Qnil
);
6708 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6709 p
->outfd
= new_outfd
;
6711 if (!proc_encode_coding_system
[new_outfd
])
6712 proc_encode_coding_system
[new_outfd
]
6713 = xmalloc (sizeof (struct coding_system
));
6716 *proc_encode_coding_system
[new_outfd
]
6717 = *proc_encode_coding_system
[old_outfd
];
6718 memset (proc_encode_coding_system
[old_outfd
], 0,
6719 sizeof (struct coding_system
));
6722 setup_coding_system (p
->encode_coding_system
,
6723 proc_encode_coding_system
[new_outfd
]);
6728 /* The main Emacs thread records child processes in three places:
6730 - Vprocess_alist, for asynchronous subprocesses, which are child
6731 processes visible to Lisp.
6733 - deleted_pid_list, for child processes invisible to Lisp,
6734 typically because of delete-process. These are recorded so that
6735 the processes can be reaped when they exit, so that the operating
6736 system's process table is not cluttered by zombies.
6738 - the local variable PID in Fcall_process, call_process_cleanup and
6739 call_process_kill, for synchronous subprocesses.
6740 record_unwind_protect is used to make sure this process is not
6741 forgotten: if the user interrupts call-process and the child
6742 process refuses to exit immediately even with two C-g's,
6743 call_process_kill adds PID's contents to deleted_pid_list before
6746 The main Emacs thread invokes waitpid only on child processes that
6747 it creates and that have not been reaped. This avoid races on
6748 platforms such as GTK, where other threads create their own
6749 subprocesses which the main thread should not reap. For example,
6750 if the main thread attempted to reap an already-reaped child, it
6751 might inadvertently reap a GTK-created process that happened to
6752 have the same process ID. */
6754 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6755 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6756 keep track of its own children. GNUstep is similar. */
6758 static void dummy_handler (int sig
) {}
6759 static signal_handler_t
volatile lib_child_handler
;
6761 /* Handle a SIGCHLD signal by looking for known child processes of
6762 Emacs whose status have changed. For each one found, record its
6765 All we do is change the status; we do not run sentinels or print
6766 notifications. That is saved for the next time keyboard input is
6767 done, in order to avoid timing errors.
6769 ** WARNING: this can be called during garbage collection.
6770 Therefore, it must not be fooled by the presence of mark bits in
6773 ** USG WARNING: Although it is not obvious from the documentation
6774 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6775 signal() before executing at least one wait(), otherwise the
6776 handler will be called again, resulting in an infinite loop. The
6777 relevant portion of the documentation reads "SIGCLD signals will be
6778 queued and the signal-catching function will be continually
6779 reentered until the queue is empty". Invoking signal() causes the
6780 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6783 ** Malloc WARNING: This should never call malloc either directly or
6784 indirectly; if it does, that is a bug. */
6787 handle_child_signal (int sig
)
6789 Lisp_Object tail
, proc
;
6791 /* Find the process that signaled us, and record its status. */
6793 /* The process can have been deleted by Fdelete_process, or have
6794 been started asynchronously by Fcall_process. */
6795 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6797 bool all_pids_are_fixnums
6798 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6799 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6800 Lisp_Object head
= XCAR (tail
);
6805 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6808 if (INTEGERP (xpid
))
6809 deleted_pid
= XINT (xpid
);
6811 deleted_pid
= XFLOAT_DATA (xpid
);
6812 if (child_status_changed (deleted_pid
, 0, 0))
6814 if (STRINGP (XCDR (head
)))
6815 unlink (SSDATA (XCDR (head
)));
6816 XSETCAR (tail
, Qnil
);
6821 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6822 FOR_EACH_PROCESS (tail
, proc
)
6824 struct Lisp_Process
*p
= XPROCESS (proc
);
6828 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6830 /* Change the status of the process that was found. */
6831 p
->tick
= ++process_tick
;
6832 p
->raw_status
= status
;
6833 p
->raw_status_new
= 1;
6835 /* If process has terminated, stop waiting for its output. */
6836 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6838 bool clear_desc_flag
= 0;
6841 clear_desc_flag
= 1;
6843 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6844 if (clear_desc_flag
)
6846 FD_CLR (p
->infd
, &input_wait_mask
);
6847 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6853 lib_child_handler (sig
);
6854 #ifdef NS_IMPL_GNUSTEP
6855 /* NSTask in GNUstep sets its child handler each time it is called.
6856 So we must re-set ours. */
6857 catch_child_signal ();
6862 deliver_child_signal (int sig
)
6864 deliver_process_signal (sig
, handle_child_signal
);
6869 exec_sentinel_error_handler (Lisp_Object error_val
)
6871 cmd_error_internal (error_val
, "error in process sentinel: ");
6873 update_echo_area ();
6874 Fsleep_for (make_number (2), Qnil
);
6879 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6881 Lisp_Object sentinel
, odeactivate
;
6882 struct Lisp_Process
*p
= XPROCESS (proc
);
6883 ptrdiff_t count
= SPECPDL_INDEX ();
6884 bool outer_running_asynch_code
= running_asynch_code
;
6885 int waiting
= waiting_for_user_input_p
;
6887 if (inhibit_sentinels
)
6890 odeactivate
= Vdeactivate_mark
;
6892 Lisp_Object obuffer
, okeymap
;
6893 XSETBUFFER (obuffer
, current_buffer
);
6894 okeymap
= BVAR (current_buffer
, keymap
);
6897 /* There's no good reason to let sentinels change the current
6898 buffer, and many callers of accept-process-output, sit-for, and
6899 friends don't expect current-buffer to be changed from under them. */
6900 record_unwind_current_buffer ();
6902 sentinel
= p
->sentinel
;
6904 /* Inhibit quit so that random quits don't screw up a running filter. */
6905 specbind (Qinhibit_quit
, Qt
);
6906 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6908 /* In case we get recursively called,
6909 and we already saved the match data nonrecursively,
6910 save the same match data in safely recursive fashion. */
6911 if (outer_running_asynch_code
)
6914 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6915 restore_search_regs ();
6916 record_unwind_save_match_data ();
6917 Fset_match_data (tem
, Qt
);
6920 /* For speed, if a search happens within this code,
6921 save the match data in a special nonrecursive fashion. */
6922 running_asynch_code
= 1;
6924 internal_condition_case_1 (read_process_output_call
,
6925 list3 (sentinel
, proc
, reason
),
6926 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6927 exec_sentinel_error_handler
);
6929 /* If we saved the match data nonrecursively, restore it now. */
6930 restore_search_regs ();
6931 running_asynch_code
= outer_running_asynch_code
;
6933 Vdeactivate_mark
= odeactivate
;
6935 /* Restore waiting_for_user_input_p as it was
6936 when we were called, in case the filter clobbered it. */
6937 waiting_for_user_input_p
= waiting
;
6940 if (! EQ (Fcurrent_buffer (), obuffer
)
6941 || ! EQ (current_buffer
->keymap
, okeymap
))
6943 /* But do it only if the caller is actually going to read events.
6944 Otherwise there's no need to make him wake up, and it could
6945 cause trouble (for example it would make sit_for return). */
6946 if (waiting_for_user_input_p
== -1)
6947 record_asynch_buffer_change ();
6949 unbind_to (count
, Qnil
);
6952 /* Report all recent events of a change in process status
6953 (either run the sentinel or output a message).
6954 This is usually done while Emacs is waiting for keyboard input
6955 but can be done at other times.
6957 Return positive if any input was received from WAIT_PROC (or from
6958 any process if WAIT_PROC is null), zero if input was attempted but
6959 none received, and negative if we didn't even try. */
6962 status_notify (struct Lisp_Process
*deleting_process
,
6963 struct Lisp_Process
*wait_proc
)
6966 Lisp_Object tail
, msg
;
6967 int got_some_output
= -1;
6972 /* Set this now, so that if new processes are created by sentinels
6973 that we run, we get called again to handle their status changes. */
6974 update_tick
= process_tick
;
6976 FOR_EACH_PROCESS (tail
, proc
)
6979 register struct Lisp_Process
*p
= XPROCESS (proc
);
6981 if (p
->tick
!= p
->update_tick
)
6983 p
->update_tick
= p
->tick
;
6985 /* If process is still active, read any output that remains. */
6986 while (! EQ (p
->filter
, Qt
)
6987 && ! EQ (p
->status
, Qconnect
)
6988 && ! EQ (p
->status
, Qlisten
)
6989 /* Network or serial process not stopped: */
6990 && ! EQ (p
->command
, Qt
)
6992 && p
!= deleting_process
)
6994 int nread
= read_process_output (proc
, p
->infd
);
6995 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
6996 && got_some_output
< nread
)
6997 got_some_output
= nread
;
7002 /* Get the text to use for the message. */
7003 if (p
->raw_status_new
)
7005 msg
= status_message (p
);
7007 /* If process is terminated, deactivate it or delete it. */
7009 if (CONSP (p
->status
))
7010 symbol
= XCAR (p
->status
);
7012 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7013 || EQ (symbol
, Qclosed
))
7015 if (delete_exited_processes
)
7016 remove_process (proc
);
7018 deactivate_process (proc
);
7021 /* The actions above may have further incremented p->tick.
7022 So set p->update_tick again so that an error in the sentinel will
7023 not cause this code to be run again. */
7024 p
->update_tick
= p
->tick
;
7025 /* Now output the message suitably. */
7026 exec_sentinel (proc
, msg
);
7027 if (BUFFERP (p
->buffer
))
7028 /* In case it uses %s in mode-line-format. */
7029 bset_update_mode_line (XBUFFER (p
->buffer
));
7033 return got_some_output
;
7036 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7037 Sinternal_default_process_sentinel
, 2, 2, 0,
7038 doc
: /* Function used as default sentinel for processes.
7039 This inserts a status message into the process's buffer, if there is one. */)
7040 (Lisp_Object proc
, Lisp_Object msg
)
7042 Lisp_Object buffer
, symbol
;
7043 struct Lisp_Process
*p
;
7044 CHECK_PROCESS (proc
);
7045 p
= XPROCESS (proc
);
7049 symbol
= XCAR (symbol
);
7051 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7054 struct buffer
*old
= current_buffer
;
7055 ptrdiff_t opoint
, opoint_byte
;
7056 ptrdiff_t before
, before_byte
;
7058 /* Avoid error if buffer is deleted
7059 (probably that's why the process is dead, too). */
7060 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7062 Fset_buffer (buffer
);
7064 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7065 msg
= (code_convert_string_norecord
7066 (msg
, Vlocale_coding_system
, 1));
7069 opoint_byte
= PT_BYTE
;
7070 /* Insert new output into buffer
7071 at the current end-of-output marker,
7072 thus preserving logical ordering of input and output. */
7073 if (XMARKER (p
->mark
)->buffer
)
7074 Fgoto_char (p
->mark
);
7076 SET_PT_BOTH (ZV
, ZV_BYTE
);
7079 before_byte
= PT_BYTE
;
7081 tem
= BVAR (current_buffer
, read_only
);
7082 bset_read_only (current_buffer
, Qnil
);
7083 insert_string ("\nProcess ");
7084 { /* FIXME: temporary kludge. */
7085 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7086 insert_string (" ");
7088 bset_read_only (current_buffer
, tem
);
7089 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7091 if (opoint
>= before
)
7092 SET_PT_BOTH (opoint
+ (PT
- before
),
7093 opoint_byte
+ (PT_BYTE
- before_byte
));
7095 SET_PT_BOTH (opoint
, opoint_byte
);
7097 set_buffer_internal (old
);
7103 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7104 Sset_process_coding_system
, 1, 3, 0,
7105 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7106 DECODING will be used to decode subprocess output and ENCODING to
7107 encode subprocess input. */)
7108 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7110 CHECK_PROCESS (process
);
7112 struct Lisp_Process
*p
= XPROCESS (process
);
7114 Fcheck_coding_system (decoding
);
7115 Fcheck_coding_system (encoding
);
7116 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7117 pset_decode_coding_system (p
, decoding
);
7118 pset_encode_coding_system (p
, encoding
);
7120 /* If the sockets haven't been set up yet, the final setup part of
7121 this will be called asynchronously. */
7122 if (p
->infd
< 0 || p
->outfd
< 0)
7125 setup_process_coding_systems (process
);
7130 DEFUN ("process-coding-system",
7131 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7132 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7133 (register Lisp_Object process
)
7135 CHECK_PROCESS (process
);
7136 return Fcons (XPROCESS (process
)->decode_coding_system
,
7137 XPROCESS (process
)->encode_coding_system
);
7140 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7141 Sset_process_filter_multibyte
, 2, 2, 0,
7142 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7143 If FLAG is non-nil, the filter is given multibyte strings.
7144 If FLAG is nil, the filter is given unibyte strings. In this case,
7145 all character code conversion except for end-of-line conversion is
7147 (Lisp_Object process
, Lisp_Object flag
)
7149 CHECK_PROCESS (process
);
7151 struct Lisp_Process
*p
= XPROCESS (process
);
7153 pset_decode_coding_system
7154 (p
, raw_text_coding_system (p
->decode_coding_system
));
7156 /* If the sockets haven't been set up yet, the final setup part of
7157 this will be called asynchronously. */
7158 if (p
->infd
< 0 || p
->outfd
< 0)
7161 setup_process_coding_systems (process
);
7166 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7167 Sprocess_filter_multibyte_p
, 1, 1, 0,
7168 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7169 (Lisp_Object process
)
7171 CHECK_PROCESS (process
);
7172 struct Lisp_Process
*p
= XPROCESS (process
);
7175 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7176 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7185 add_gpm_wait_descriptor (int desc
)
7187 add_keyboard_wait_descriptor (desc
);
7191 delete_gpm_wait_descriptor (int desc
)
7193 delete_keyboard_wait_descriptor (desc
);
7198 # ifdef USABLE_SIGIO
7200 /* Return true if *MASK has a bit set
7201 that corresponds to one of the keyboard input descriptors. */
7204 keyboard_bit_set (fd_set
*mask
)
7208 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7209 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7210 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7217 #else /* not subprocesses */
7219 /* Defined in msdos.c. */
7220 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7221 struct timespec
*, void *);
7223 /* Implementation of wait_reading_process_output, assuming that there
7224 are no subprocesses. Used only by the MS-DOS build.
7226 Wait for timeout to elapse and/or keyboard input to be available.
7230 If negative, gobble data immediately available but don't wait for any.
7233 an additional duration to wait, measured in nanoseconds
7234 If TIME_LIMIT is zero, then:
7235 If NSECS == 0, there is no limit.
7236 If NSECS > 0, the timeout consists of NSECS only.
7237 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7240 0 to ignore keyboard input, or
7241 1 to return when input is available, or
7242 -1 means caller will actually read the input, so don't throw to
7245 see full version for other parameters. We know that wait_proc will
7246 always be NULL, since `subprocesses' isn't defined.
7248 DO_DISPLAY means redisplay should be done to show subprocess
7249 output that arrives.
7251 Return -1 signifying we got no output and did not try. */
7254 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7256 Lisp_Object wait_for_cell
,
7257 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7260 struct timespec end_time
, timeout
;
7261 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7263 if (TYPE_MAXIMUM (time_t) < time_limit
)
7264 time_limit
= TYPE_MAXIMUM (time_t);
7266 if (time_limit
< 0 || nsecs
< 0)
7268 else if (time_limit
> 0 || nsecs
> 0)
7271 end_time
= timespec_add (current_timespec (),
7272 make_timespec (time_limit
, nsecs
));
7277 /* Turn off periodic alarms (in case they are in use)
7278 and then turn off any other atimers,
7279 because the select emulator uses alarms. */
7281 turn_on_atimers (0);
7285 bool timeout_reduced_for_timers
= false;
7286 fd_set waitchannels
;
7289 /* If calling from keyboard input, do not quit
7290 since we want to return C-g as an input character.
7291 Otherwise, do pending quit if requested. */
7295 /* Exit now if the cell we're waiting for became non-nil. */
7296 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7299 /* Compute time from now till when time limit is up. */
7300 /* Exit if already run out. */
7301 if (wait
== TIMEOUT
)
7303 struct timespec now
= current_timespec ();
7304 if (timespec_cmp (end_time
, now
) <= 0)
7306 timeout
= timespec_sub (end_time
, now
);
7309 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7311 /* If our caller will not immediately handle keyboard events,
7312 run timer events directly.
7313 (Callers that will immediately read keyboard events
7314 call timer_delay on their own.) */
7315 if (NILP (wait_for_cell
))
7317 struct timespec timer_delay
;
7321 unsigned old_timers_run
= timers_run
;
7322 timer_delay
= timer_check ();
7323 if (timers_run
!= old_timers_run
&& do_display
)
7324 /* We must retry, since a timer may have requeued itself
7325 and that could alter the time delay. */
7326 redisplay_preserve_echo_area (14);
7330 while (!detect_input_pending ());
7332 /* If there is unread keyboard input, also return. */
7334 && requeued_events_pending_p ())
7337 if (timespec_valid_p (timer_delay
))
7339 if (timespec_cmp (timer_delay
, timeout
) < 0)
7341 timeout
= timer_delay
;
7342 timeout_reduced_for_timers
= true;
7347 /* Cause C-g and alarm signals to take immediate action,
7348 and cause input available signals to zero out timeout. */
7350 set_waiting_for_input (&timeout
);
7352 /* If a frame has been newly mapped and needs updating,
7353 reprocess its display stuff. */
7354 if (frame_garbaged
&& do_display
)
7356 clear_waiting_for_input ();
7357 redisplay_preserve_echo_area (15);
7359 set_waiting_for_input (&timeout
);
7362 /* Wait till there is something to do. */
7363 FD_ZERO (&waitchannels
);
7364 if (read_kbd
&& detect_input_pending ())
7368 if (read_kbd
|| !NILP (wait_for_cell
))
7369 FD_SET (0, &waitchannels
);
7370 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7375 /* Make C-g and alarm signals set flags again. */
7376 clear_waiting_for_input ();
7378 /* If we woke up due to SIGWINCH, actually change size now. */
7379 do_pending_window_change (0);
7381 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7382 /* We waited the full specified time, so return now. */
7387 /* If the system call was interrupted, then go around the
7389 if (xerrno
== EINTR
)
7390 FD_ZERO (&waitchannels
);
7392 report_file_errno ("Failed select", Qnil
, xerrno
);
7395 /* Check for keyboard input. */
7398 && detect_input_pending_run_timers (do_display
))
7400 swallow_events (do_display
);
7401 if (detect_input_pending_run_timers (do_display
))
7405 /* If there is unread keyboard input, also return. */
7407 && requeued_events_pending_p ())
7410 /* If wait_for_cell. check for keyboard input
7411 but don't run any timers.
7412 ??? (It seems wrong to me to check for keyboard
7413 input at all when wait_for_cell, but the code
7414 has been this way since July 1994.
7415 Try changing this after version 19.31.) */
7416 if (! NILP (wait_for_cell
)
7417 && detect_input_pending ())
7419 swallow_events (do_display
);
7420 if (detect_input_pending ())
7424 /* Exit now if the cell we're waiting for became non-nil. */
7425 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7434 #endif /* not subprocesses */
7436 /* The following functions are needed even if async subprocesses are
7437 not supported. Some of them are no-op stubs in that case. */
7441 /* Add FD, which is a descriptor returned by timerfd_create,
7442 to the set of non-keyboard input descriptors. */
7445 add_timer_wait_descriptor (int fd
)
7447 FD_SET (fd
, &input_wait_mask
);
7448 FD_SET (fd
, &non_keyboard_wait_mask
);
7449 FD_SET (fd
, &non_process_wait_mask
);
7450 fd_callback_info
[fd
].func
= timerfd_callback
;
7451 fd_callback_info
[fd
].data
= NULL
;
7452 fd_callback_info
[fd
].condition
|= FOR_READ
;
7453 if (fd
> max_input_desc
)
7454 max_input_desc
= fd
;
7457 #endif /* HAVE_TIMERFD */
7459 /* Add DESC to the set of keyboard input descriptors. */
7462 add_keyboard_wait_descriptor (int desc
)
7464 #ifdef subprocesses /* Actually means "not MSDOS". */
7465 FD_SET (desc
, &input_wait_mask
);
7466 FD_SET (desc
, &non_process_wait_mask
);
7467 if (desc
> max_input_desc
)
7468 max_input_desc
= desc
;
7472 /* From now on, do not expect DESC to give keyboard input. */
7475 delete_keyboard_wait_descriptor (int desc
)
7478 FD_CLR (desc
, &input_wait_mask
);
7479 FD_CLR (desc
, &non_process_wait_mask
);
7480 delete_input_desc (desc
);
7484 /* Setup coding systems of PROCESS. */
7487 setup_process_coding_systems (Lisp_Object process
)
7490 struct Lisp_Process
*p
= XPROCESS (process
);
7492 int outch
= p
->outfd
;
7493 Lisp_Object coding_system
;
7495 if (inch
< 0 || outch
< 0)
7498 if (!proc_decode_coding_system
[inch
])
7499 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7500 coding_system
= p
->decode_coding_system
;
7501 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7502 && BUFFERP (p
->buffer
))
7504 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7505 coding_system
= raw_text_coding_system (coding_system
);
7507 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7509 if (!proc_encode_coding_system
[outch
])
7510 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7511 setup_coding_system (p
->encode_coding_system
,
7512 proc_encode_coding_system
[outch
]);
7516 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7517 doc
: /* Return the (or a) live process associated with BUFFER.
7518 BUFFER may be a buffer or the name of one.
7519 Return nil if all processes associated with BUFFER have been
7520 deleted or killed. */)
7521 (register Lisp_Object buffer
)
7524 register Lisp_Object buf
, tail
, proc
;
7526 if (NILP (buffer
)) return Qnil
;
7527 buf
= Fget_buffer (buffer
);
7528 if (NILP (buf
)) return Qnil
;
7530 FOR_EACH_PROCESS (tail
, proc
)
7531 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7533 #endif /* subprocesses */
7537 DEFUN ("process-inherit-coding-system-flag",
7538 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7540 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7541 If this flag is t, `buffer-file-coding-system' of the buffer
7542 associated with PROCESS will inherit the coding system used to decode
7543 the process output. */)
7544 (register Lisp_Object process
)
7547 CHECK_PROCESS (process
);
7548 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7550 /* Ignore the argument and return the value of
7551 inherit-process-coding-system. */
7552 return inherit_process_coding_system
? Qt
: Qnil
;
7556 /* Kill all processes associated with `buffer'.
7557 If `buffer' is nil, kill all processes. */
7560 kill_buffer_processes (Lisp_Object buffer
)
7563 Lisp_Object tail
, proc
;
7565 FOR_EACH_PROCESS (tail
, proc
)
7566 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7568 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7569 Fdelete_process (proc
);
7570 else if (XPROCESS (proc
)->infd
>= 0)
7571 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7573 #else /* subprocesses */
7574 /* Since we have no subprocesses, this does nothing. */
7575 #endif /* subprocesses */
7578 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7579 Swaiting_for_user_input_p
, 0, 0, 0,
7580 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7581 This is intended for use by asynchronous process output filters and sentinels. */)
7585 return (waiting_for_user_input_p
? Qt
: Qnil
);
7591 /* Stop reading input from keyboard sources. */
7594 hold_keyboard_input (void)
7599 /* Resume reading input from keyboard sources. */
7602 unhold_keyboard_input (void)
7607 /* Return true if keyboard input is on hold, zero otherwise. */
7610 kbd_on_hold_p (void)
7612 return kbd_is_on_hold
;
7616 /* Enumeration of and access to system processes a-la ps(1). */
7618 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7620 doc
: /* Return a list of numerical process IDs of all running processes.
7621 If this functionality is unsupported, return nil.
7623 See `process-attributes' for getting attributes of a process given its ID. */)
7626 return list_system_processes ();
7629 DEFUN ("process-attributes", Fprocess_attributes
,
7630 Sprocess_attributes
, 1, 1, 0,
7631 doc
: /* Return attributes of the process given by its PID, a number.
7633 Value is an alist where each element is a cons cell of the form
7637 If this functionality is unsupported, the value is nil.
7639 See `list-system-processes' for getting a list of all process IDs.
7641 The KEYs of the attributes that this function may return are listed
7642 below, together with the type of the associated VALUE (in parentheses).
7643 Not all platforms support all of these attributes; unsupported
7644 attributes will not appear in the returned alist.
7645 Unless explicitly indicated otherwise, numbers can have either
7646 integer or floating point values.
7648 euid -- Effective user User ID of the process (number)
7649 user -- User name corresponding to euid (string)
7650 egid -- Effective user Group ID of the process (number)
7651 group -- Group name corresponding to egid (string)
7652 comm -- Command name (executable name only) (string)
7653 state -- Process state code, such as "S", "R", or "T" (string)
7654 ppid -- Parent process ID (number)
7655 pgrp -- Process group ID (number)
7656 sess -- Session ID, i.e. process ID of session leader (number)
7657 ttname -- Controlling tty name (string)
7658 tpgid -- ID of foreground process group on the process's tty (number)
7659 minflt -- number of minor page faults (number)
7660 majflt -- number of major page faults (number)
7661 cminflt -- cumulative number of minor page faults (number)
7662 cmajflt -- cumulative number of major page faults (number)
7663 utime -- user time used by the process, in (current-time) format,
7664 which is a list of integers (HIGH LOW USEC PSEC)
7665 stime -- system time used by the process (current-time)
7666 time -- sum of utime and stime (current-time)
7667 cutime -- user time used by the process and its children (current-time)
7668 cstime -- system time used by the process and its children (current-time)
7669 ctime -- sum of cutime and cstime (current-time)
7670 pri -- priority of the process (number)
7671 nice -- nice value of the process (number)
7672 thcount -- process thread count (number)
7673 start -- time the process started (current-time)
7674 vsize -- virtual memory size of the process in KB's (number)
7675 rss -- resident set size of the process in KB's (number)
7676 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7677 pcpu -- percents of CPU time used by the process (floating-point number)
7678 pmem -- percents of total physical memory used by process's resident set
7679 (floating-point number)
7680 args -- command line which invoked the process (string). */)
7683 return system_process_attributes (pid
);
7687 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7688 Invoke this after init_process_emacs, and after glib and/or GNUstep
7689 futz with the SIGCHLD handler, but before Emacs forks any children.
7690 This function's caller should block SIGCHLD. */
7693 catch_child_signal (void)
7695 struct sigaction action
, old_action
;
7697 emacs_sigaction_init (&action
, deliver_child_signal
);
7698 block_child_signal (&oldset
);
7699 sigaction (SIGCHLD
, &action
, &old_action
);
7700 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7701 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7703 if (old_action
.sa_handler
!= deliver_child_signal
)
7705 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7707 : old_action
.sa_handler
);
7708 unblock_child_signal (&oldset
);
7710 #endif /* subprocesses */
7713 /* This is not called "init_process" because that is the name of a
7714 Mach system call, so it would cause problems on Darwin systems. */
7716 init_process_emacs (void)
7721 inhibit_sentinels
= 0;
7724 if (! noninteractive
|| initialized
)
7727 #if defined HAVE_GLIB && !defined WINDOWSNT
7728 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7729 this should always fail, but is enough to initialize glib's
7730 private SIGCHLD handler, allowing catch_child_signal to copy
7731 it into lib_child_handler. */
7732 g_source_unref (g_child_watch_source_new (getpid ()));
7734 catch_child_signal ();
7737 FD_ZERO (&input_wait_mask
);
7738 FD_ZERO (&non_keyboard_wait_mask
);
7739 FD_ZERO (&non_process_wait_mask
);
7740 FD_ZERO (&write_mask
);
7741 max_process_desc
= max_input_desc
= -1;
7742 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7744 FD_ZERO (&connect_wait_mask
);
7745 num_pending_connects
= 0;
7747 process_output_delay_count
= 0;
7748 process_output_skip
= 0;
7750 /* Don't do this, it caused infinite select loops. The display
7751 method should call add_keyboard_wait_descriptor on stdin if it
7754 FD_SET (0, &input_wait_mask
);
7757 Vprocess_alist
= Qnil
;
7758 deleted_pid_list
= Qnil
;
7759 for (i
= 0; i
< FD_SETSIZE
; i
++)
7761 chan_process
[i
] = Qnil
;
7762 proc_buffered_char
[i
] = -1;
7764 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7765 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7766 #ifdef DATAGRAM_SOCKETS
7767 memset (datagram_address
, 0, sizeof datagram_address
);
7770 #if defined (DARWIN_OS)
7771 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7772 processes. As such, we only change the default value. */
7775 char const *release
= (STRINGP (Voperating_system_release
)
7776 ? SSDATA (Voperating_system_release
)
7778 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7779 Vprocess_connection_type
= Qnil
;
7783 #endif /* subprocesses */
7788 syms_of_process (void)
7792 DEFSYM (Qprocessp
, "processp");
7793 DEFSYM (Qrun
, "run");
7794 DEFSYM (Qstop
, "stop");
7795 DEFSYM (Qsignal
, "signal");
7797 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7800 DEFSYM (Qopen
, "open");
7801 DEFSYM (Qclosed
, "closed");
7802 DEFSYM (Qconnect
, "connect");
7803 DEFSYM (Qfailed
, "failed");
7804 DEFSYM (Qlisten
, "listen");
7805 DEFSYM (Qlocal
, "local");
7806 DEFSYM (Qipv4
, "ipv4");
7808 DEFSYM (Qipv6
, "ipv6");
7810 DEFSYM (Qdatagram
, "datagram");
7811 DEFSYM (Qseqpacket
, "seqpacket");
7813 DEFSYM (QCport
, ":port");
7814 DEFSYM (QCspeed
, ":speed");
7815 DEFSYM (QCprocess
, ":process");
7817 DEFSYM (QCbytesize
, ":bytesize");
7818 DEFSYM (QCstopbits
, ":stopbits");
7819 DEFSYM (QCparity
, ":parity");
7820 DEFSYM (Qodd
, "odd");
7821 DEFSYM (Qeven
, "even");
7822 DEFSYM (QCflowcontrol
, ":flowcontrol");
7825 DEFSYM (QCsummary
, ":summary");
7827 DEFSYM (Qreal
, "real");
7828 DEFSYM (Qnetwork
, "network");
7829 DEFSYM (Qserial
, "serial");
7830 DEFSYM (Qpipe
, "pipe");
7831 DEFSYM (QCbuffer
, ":buffer");
7832 DEFSYM (QChost
, ":host");
7833 DEFSYM (QCservice
, ":service");
7834 DEFSYM (QClocal
, ":local");
7835 DEFSYM (QCremote
, ":remote");
7836 DEFSYM (QCcoding
, ":coding");
7837 DEFSYM (QCserver
, ":server");
7838 DEFSYM (QCnowait
, ":nowait");
7839 DEFSYM (QCsentinel
, ":sentinel");
7840 DEFSYM (QCtls_parameters
, ":tls-parameters");
7841 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7842 DEFSYM (QClog
, ":log");
7843 DEFSYM (QCnoquery
, ":noquery");
7844 DEFSYM (QCstop
, ":stop");
7845 DEFSYM (QCplist
, ":plist");
7846 DEFSYM (QCcommand
, ":command");
7847 DEFSYM (QCconnection_type
, ":connection-type");
7848 DEFSYM (QCstderr
, ":stderr");
7849 DEFSYM (Qpty
, "pty");
7850 DEFSYM (Qpipe
, "pipe");
7852 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7854 staticpro (&Vprocess_alist
);
7855 staticpro (&deleted_pid_list
);
7857 #endif /* subprocesses */
7859 DEFSYM (QCname
, ":name");
7860 DEFSYM (QCtype
, ":type");
7862 DEFSYM (Qeuid
, "euid");
7863 DEFSYM (Qegid
, "egid");
7864 DEFSYM (Quser
, "user");
7865 DEFSYM (Qgroup
, "group");
7866 DEFSYM (Qcomm
, "comm");
7867 DEFSYM (Qstate
, "state");
7868 DEFSYM (Qppid
, "ppid");
7869 DEFSYM (Qpgrp
, "pgrp");
7870 DEFSYM (Qsess
, "sess");
7871 DEFSYM (Qttname
, "ttname");
7872 DEFSYM (Qtpgid
, "tpgid");
7873 DEFSYM (Qminflt
, "minflt");
7874 DEFSYM (Qmajflt
, "majflt");
7875 DEFSYM (Qcminflt
, "cminflt");
7876 DEFSYM (Qcmajflt
, "cmajflt");
7877 DEFSYM (Qutime
, "utime");
7878 DEFSYM (Qstime
, "stime");
7879 DEFSYM (Qtime
, "time");
7880 DEFSYM (Qcutime
, "cutime");
7881 DEFSYM (Qcstime
, "cstime");
7882 DEFSYM (Qctime
, "ctime");
7884 DEFSYM (Qinternal_default_process_sentinel
,
7885 "internal-default-process-sentinel");
7886 DEFSYM (Qinternal_default_process_filter
,
7887 "internal-default-process-filter");
7889 DEFSYM (Qpri
, "pri");
7890 DEFSYM (Qnice
, "nice");
7891 DEFSYM (Qthcount
, "thcount");
7892 DEFSYM (Qstart
, "start");
7893 DEFSYM (Qvsize
, "vsize");
7894 DEFSYM (Qrss
, "rss");
7895 DEFSYM (Qetime
, "etime");
7896 DEFSYM (Qpcpu
, "pcpu");
7897 DEFSYM (Qpmem
, "pmem");
7898 DEFSYM (Qargs
, "args");
7900 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7901 doc
: /* Non-nil means delete processes immediately when they exit.
7902 A value of nil means don't delete them until `list-processes' is run. */);
7904 delete_exited_processes
= 1;
7907 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7908 doc
: /* Control type of device used to communicate with subprocesses.
7909 Values are nil to use a pipe, or t or `pty' to use a pty.
7910 The value has no effect if the system has no ptys or if all ptys are busy:
7911 then a pipe is used in any case.
7912 The value takes effect when `start-process' is called. */);
7913 Vprocess_connection_type
= Qt
;
7915 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7916 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7917 On some systems, when Emacs reads the output from a subprocess, the output data
7918 is read in very small blocks, potentially resulting in very poor performance.
7919 This behavior can be remedied to some extent by setting this variable to a
7920 non-nil value, as it will automatically delay reading from such processes, to
7921 allow them to produce more output before Emacs tries to read it.
7922 If the value is t, the delay is reset after each write to the process; any other
7923 non-nil value means that the delay is not reset on write.
7924 The variable takes effect when `start-process' is called. */);
7925 Vprocess_adaptive_read_buffering
= Qt
;
7927 defsubr (&Sprocessp
);
7928 defsubr (&Sget_process
);
7929 defsubr (&Sdelete_process
);
7930 defsubr (&Sprocess_status
);
7931 defsubr (&Sprocess_exit_status
);
7932 defsubr (&Sprocess_id
);
7933 defsubr (&Sprocess_name
);
7934 defsubr (&Sprocess_tty_name
);
7935 defsubr (&Sprocess_command
);
7936 defsubr (&Sset_process_buffer
);
7937 defsubr (&Sprocess_buffer
);
7938 defsubr (&Sprocess_mark
);
7939 defsubr (&Sset_process_filter
);
7940 defsubr (&Sprocess_filter
);
7941 defsubr (&Sset_process_sentinel
);
7942 defsubr (&Sprocess_sentinel
);
7943 defsubr (&Sset_process_window_size
);
7944 defsubr (&Sset_process_inherit_coding_system_flag
);
7945 defsubr (&Sset_process_query_on_exit_flag
);
7946 defsubr (&Sprocess_query_on_exit_flag
);
7947 defsubr (&Sprocess_contact
);
7948 defsubr (&Sprocess_plist
);
7949 defsubr (&Sset_process_plist
);
7950 defsubr (&Sprocess_list
);
7951 defsubr (&Smake_process
);
7952 defsubr (&Smake_pipe_process
);
7953 defsubr (&Sserial_process_configure
);
7954 defsubr (&Smake_serial_process
);
7955 defsubr (&Sset_network_process_option
);
7956 defsubr (&Smake_network_process
);
7957 defsubr (&Sformat_network_address
);
7958 defsubr (&Snetwork_interface_list
);
7959 defsubr (&Snetwork_interface_info
);
7960 #ifdef DATAGRAM_SOCKETS
7961 defsubr (&Sprocess_datagram_address
);
7962 defsubr (&Sset_process_datagram_address
);
7964 defsubr (&Saccept_process_output
);
7965 defsubr (&Sprocess_send_region
);
7966 defsubr (&Sprocess_send_string
);
7967 defsubr (&Sinterrupt_process
);
7968 defsubr (&Skill_process
);
7969 defsubr (&Squit_process
);
7970 defsubr (&Sstop_process
);
7971 defsubr (&Scontinue_process
);
7972 defsubr (&Sprocess_running_child_p
);
7973 defsubr (&Sprocess_send_eof
);
7974 defsubr (&Ssignal_process
);
7975 defsubr (&Swaiting_for_user_input_p
);
7976 defsubr (&Sprocess_type
);
7977 defsubr (&Sinternal_default_process_sentinel
);
7978 defsubr (&Sinternal_default_process_filter
);
7979 defsubr (&Sset_process_coding_system
);
7980 defsubr (&Sprocess_coding_system
);
7981 defsubr (&Sset_process_filter_multibyte
);
7982 defsubr (&Sprocess_filter_multibyte_p
);
7984 #endif /* subprocesses */
7986 defsubr (&Sget_buffer_process
);
7987 defsubr (&Sprocess_inherit_coding_system_flag
);
7988 defsubr (&Slist_system_processes
);
7989 defsubr (&Sprocess_attributes
);
7992 Lisp_Object subfeatures
= Qnil
;
7993 const struct socket_options
*sopt
;
7995 #define ADD_SUBFEATURE(key, val) \
7996 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7998 ADD_SUBFEATURE (QCnowait
, Qt
);
7999 #ifdef DATAGRAM_SOCKETS
8000 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8002 #ifdef HAVE_SEQPACKET
8003 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8005 #ifdef HAVE_LOCAL_SOCKETS
8006 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8008 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8010 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8012 #ifdef HAVE_GETSOCKNAME
8013 ADD_SUBFEATURE (QCservice
, Qt
);
8015 ADD_SUBFEATURE (QCserver
, Qt
);
8017 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8018 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8020 Fprovide (intern_c_string ("make-network-process"), subfeatures
);