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
11 (at 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"
124 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
125 struct timespec
*, void *);
128 /* Work around GCC 4.7.0 bug with strict overflow checking; see
129 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
130 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
131 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
132 # pragma GCC diagnostic ignored "-Wstrict-overflow"
135 /* True if keyboard input is on hold, zero otherwise. */
137 static bool kbd_is_on_hold
;
139 /* Nonzero means don't run process sentinels. This is used
141 bool inhibit_sentinels
;
146 # define SOCK_CLOEXEC 0
151 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
154 close_on_exec (int fd
)
157 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
162 # define accept4(sockfd, addr, addrlen, flags) \
163 process_accept4 (sockfd, addr, addrlen, flags)
165 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
167 return close_on_exec (accept (sockfd
, addr
, addrlen
));
171 process_socket (int domain
, int type
, int protocol
)
173 return close_on_exec (socket (domain
, type
, protocol
));
176 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
179 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
180 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
181 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
182 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
183 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
184 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
186 /* Number of events of change of status of a process. */
187 static EMACS_INT process_tick
;
188 /* Number of events for which the user or sentinel has been notified. */
189 static EMACS_INT update_tick
;
191 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
192 The code can be simplified by assuming NON_BLOCKING_CONNECT once
193 Emacs starts assuming POSIX 1003.1-2001 or later. */
195 #if (defined HAVE_SELECT \
196 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
197 && (defined EWOULDBLOCK || defined EINPROGRESS))
198 # define NON_BLOCKING_CONNECT
201 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
202 this system. We need to read full packets, so we need a
203 "non-destructive" select. So we require either native select,
204 or emulation of select using FIONREAD. */
206 #ifndef BROKEN_DATAGRAM_SOCKETS
207 # if defined HAVE_SELECT || defined USABLE_FIONREAD
208 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
209 # define DATAGRAM_SOCKETS
214 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
215 # define HAVE_SEQPACKET
218 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
219 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
220 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
222 /* Number of processes which have a non-zero read_output_delay,
223 and therefore might be delayed for adaptive read buffering. */
225 static int process_output_delay_count
;
227 /* True if any process has non-nil read_output_skip. */
229 static bool process_output_skip
;
231 static void create_process (Lisp_Object
, char **, Lisp_Object
);
233 static bool keyboard_bit_set (fd_set
*);
235 static void deactivate_process (Lisp_Object
);
236 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
237 static int read_process_output (Lisp_Object
, int);
238 static void handle_child_signal (int);
239 static void create_pty (Lisp_Object
);
241 static Lisp_Object
get_process (register Lisp_Object name
);
242 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
244 /* Mask of bits indicating the descriptors that we wait for input on. */
246 static fd_set input_wait_mask
;
248 /* Mask that excludes keyboard input descriptor(s). */
250 static fd_set non_keyboard_wait_mask
;
252 /* Mask that excludes process input descriptor(s). */
254 static fd_set non_process_wait_mask
;
256 /* Mask for selecting for write. */
258 static fd_set write_mask
;
260 #ifdef NON_BLOCKING_CONNECT
261 /* Mask of bits indicating the descriptors that we wait for connect to
262 complete on. Once they complete, they are removed from this mask
263 and added to the input_wait_mask and non_keyboard_wait_mask. */
265 static fd_set connect_wait_mask
;
267 /* Number of bits set in connect_wait_mask. */
268 static int num_pending_connects
;
269 #endif /* NON_BLOCKING_CONNECT */
271 /* The largest descriptor currently in use for a process object; -1 if none. */
272 static int max_process_desc
;
274 /* The largest descriptor currently in use for input; -1 if none. */
275 static int max_input_desc
;
277 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
278 static Lisp_Object chan_process
[FD_SETSIZE
];
279 static void wait_for_socket_fds (Lisp_Object
, char const *);
281 /* Alist of elements (NAME . PROCESS). */
282 static Lisp_Object Vprocess_alist
;
284 /* Buffered-ahead input char from process, indexed by channel.
285 -1 means empty (no char is buffered).
286 Used on sys V where the only way to tell if there is any
287 output from the process is to read at least one char.
288 Always -1 on systems that support FIONREAD. */
290 static int proc_buffered_char
[FD_SETSIZE
];
292 /* Table of `struct coding-system' for each process. */
293 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
294 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
296 #ifdef DATAGRAM_SOCKETS
297 /* Table of `partner address' for datagram sockets. */
298 static struct sockaddr_and_len
{
301 } datagram_address
[FD_SETSIZE
];
302 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
303 #define DATAGRAM_CONN_P(proc) \
304 (PROCESSP (proc) && \
305 XPROCESS (proc)->infd >= 0 && \
306 datagram_address[XPROCESS (proc)->infd].sa != 0)
308 #define DATAGRAM_CHAN_P(chan) (0)
309 #define DATAGRAM_CONN_P(proc) (0)
312 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
313 a `for' loop which iterates over processes from Vprocess_alist. */
315 #define FOR_EACH_PROCESS(list_var, proc_var) \
316 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
318 /* These setters are used only in this file, so they can be private. */
320 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
325 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
330 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
332 p
->decode_coding_system
= val
;
335 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
337 p
->decoding_buf
= val
;
340 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
342 p
->encode_coding_system
= val
;
345 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
347 p
->encoding_buf
= val
;
350 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
352 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
355 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
360 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
365 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
370 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
375 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
377 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
380 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
385 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
390 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
392 p
->write_queue
= val
;
395 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
402 make_lisp_proc (struct Lisp_Process
*p
)
404 return make_lisp_ptr (p
, Lisp_Vectorlike
);
407 static struct fd_callback_data
413 int condition
; /* Mask of the defines above. */
414 } fd_callback_info
[FD_SETSIZE
];
417 /* Add a file descriptor FD to be monitored for when read is possible.
418 When read is possible, call FUNC with argument DATA. */
421 add_read_fd (int fd
, fd_callback func
, void *data
)
423 add_keyboard_wait_descriptor (fd
);
425 fd_callback_info
[fd
].func
= func
;
426 fd_callback_info
[fd
].data
= data
;
427 fd_callback_info
[fd
].condition
|= FOR_READ
;
430 /* Stop monitoring file descriptor FD for when read is possible. */
433 delete_read_fd (int fd
)
435 delete_keyboard_wait_descriptor (fd
);
437 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
438 if (fd_callback_info
[fd
].condition
== 0)
440 fd_callback_info
[fd
].func
= 0;
441 fd_callback_info
[fd
].data
= 0;
445 /* Add a file descriptor FD to be monitored for when write is possible.
446 When write is possible, call FUNC with argument DATA. */
449 add_write_fd (int fd
, fd_callback func
, void *data
)
451 FD_SET (fd
, &write_mask
);
452 if (fd
> max_input_desc
)
455 fd_callback_info
[fd
].func
= func
;
456 fd_callback_info
[fd
].data
= data
;
457 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
460 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
463 delete_input_desc (int fd
)
465 if (fd
== max_input_desc
)
469 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
470 || FD_ISSET (fd
, &write_mask
)));
476 /* Stop monitoring file descriptor FD for when write is possible. */
479 delete_write_fd (int fd
)
481 FD_CLR (fd
, &write_mask
);
482 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
483 if (fd_callback_info
[fd
].condition
== 0)
485 fd_callback_info
[fd
].func
= 0;
486 fd_callback_info
[fd
].data
= 0;
487 delete_input_desc (fd
);
492 /* Compute the Lisp form of the process status, p->status, from
493 the numeric status that was returned by `wait'. */
495 static Lisp_Object
status_convert (int);
498 update_status (struct Lisp_Process
*p
)
500 eassert (p
->raw_status_new
);
501 pset_status (p
, status_convert (p
->raw_status
));
502 p
->raw_status_new
= 0;
505 /* Convert a process status word in Unix format to
506 the list that we use internally. */
509 status_convert (int w
)
512 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
513 else if (WIFEXITED (w
))
514 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
515 WCOREDUMP (w
) ? Qt
: Qnil
));
516 else if (WIFSIGNALED (w
))
517 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
518 WCOREDUMP (w
) ? Qt
: Qnil
));
523 /* Given a status-list, extract the three pieces of information
524 and store them individually through the three pointers. */
527 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
541 *code
= XFASTINT (XCAR (tem
));
543 *coredump
= !NILP (tem
);
547 /* Return a string describing a process status list. */
550 status_message (struct Lisp_Process
*p
)
552 Lisp_Object status
= p
->status
;
558 decode_status (status
, &symbol
, &code
, &coredump
);
560 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
563 synchronize_system_messages_locale ();
564 signame
= strsignal (code
);
566 string
= build_string ("unknown");
571 string
= build_unibyte_string (signame
);
572 if (! NILP (Vlocale_coding_system
))
573 string
= (code_convert_string_norecord
574 (string
, Vlocale_coding_system
, 0));
575 c1
= STRING_CHAR (SDATA (string
));
578 Faset (string
, make_number (0), make_number (c2
));
580 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
581 return concat2 (string
, suffix
);
583 else if (EQ (symbol
, Qexit
))
586 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
588 return build_string ("finished\n");
589 AUTO_STRING (prefix
, "exited abnormally with code ");
590 string
= Fnumber_to_string (make_number (code
));
591 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
592 return concat3 (prefix
, string
, suffix
);
594 else if (EQ (symbol
, Qfailed
))
596 AUTO_STRING (prefix
, "failed with code ");
597 string
= Fnumber_to_string (make_number (code
));
598 AUTO_STRING (suffix
, "\n");
599 return concat3 (prefix
, string
, suffix
);
602 return Fcopy_sequence (Fsymbol_name (symbol
));
605 enum { PTY_NAME_SIZE
= 24 };
607 /* Open an available pty, returning a file descriptor.
608 Store into PTY_NAME the file name of the terminal corresponding to the pty.
609 Return -1 on failure. */
612 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
621 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
622 for (i
= 0; i
< 16; i
++)
625 #ifdef PTY_NAME_SPRINTF
628 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
629 #endif /* no PTY_NAME_SPRINTF */
633 #else /* no PTY_OPEN */
634 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
635 #endif /* no PTY_OPEN */
639 #ifdef PTY_TTY_NAME_SPRINTF
642 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
643 #endif /* no PTY_TTY_NAME_SPRINTF */
645 /* Set FD's close-on-exec flag. This is needed even if
646 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
647 doesn't require support for that combination.
648 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
649 doesn't work if the close-on-exec flag is set (Bug#20555).
650 Multithreaded platforms where posix_openpt ignores
651 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
652 have a race condition between the PTY_OPEN and here. */
653 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
655 /* Check to make certain that both sides are available.
656 This avoids a nasty yet stupid bug in rlogins. */
657 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
670 #endif /* HAVE_PTYS */
674 /* Allocate basically initialized process. */
676 static struct Lisp_Process
*
677 allocate_process (void)
679 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
683 make_process (Lisp_Object name
)
685 register Lisp_Object val
, tem
, name1
;
686 register struct Lisp_Process
*p
;
687 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
690 p
= allocate_process ();
691 /* Initialize Lisp data. Note that allocate_process initializes all
692 Lisp data to nil, so do it only for slots which should not be nil. */
693 pset_status (p
, Qrun
);
694 pset_mark (p
, Fmake_marker ());
696 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
697 non-Lisp data, so do it only for slots which should not be zero. */
700 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
704 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
705 p
->gnutls_boot_parameters
= Qnil
;
708 /* If name is already in use, modify it until it is unused. */
713 tem
= Fget_process (name1
);
714 if (NILP (tem
)) break;
715 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
719 pset_sentinel (p
, Qinternal_default_process_sentinel
);
720 pset_filter (p
, Qinternal_default_process_filter
);
721 XSETPROCESS (val
, p
);
722 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
727 remove_process (register Lisp_Object proc
)
729 register Lisp_Object pair
;
731 pair
= Frassq (proc
, Vprocess_alist
);
732 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
734 deactivate_process (proc
);
737 #ifdef HAVE_GETADDRINFO_A
739 free_dns_request (Lisp_Object proc
)
741 struct Lisp_Process
*p
= XPROCESS (proc
);
743 if (p
->dns_request
->ar_result
)
744 freeaddrinfo (p
->dns_request
->ar_result
);
745 xfree (p
->dns_request
);
746 p
->dns_request
= NULL
;
751 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
752 doc
: /* Return t if OBJECT is a process. */)
755 return PROCESSP (object
) ? Qt
: Qnil
;
758 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
759 doc
: /* Return the process named NAME, or nil if there is none. */)
760 (register Lisp_Object name
)
765 return Fcdr (Fassoc (name
, Vprocess_alist
));
768 /* This is how commands for the user decode process arguments. It
769 accepts a process, a process name, a buffer, a buffer name, or nil.
770 Buffers denote the first process in the buffer, and nil denotes the
774 get_process (register Lisp_Object name
)
776 register Lisp_Object proc
, obj
;
779 obj
= Fget_process (name
);
781 obj
= Fget_buffer (name
);
783 error ("Process %s does not exist", SDATA (name
));
785 else if (NILP (name
))
786 obj
= Fcurrent_buffer ();
790 /* Now obj should be either a buffer object or a process object. */
793 if (NILP (BVAR (XBUFFER (obj
), name
)))
794 error ("Attempt to get process for a dead buffer");
795 proc
= Fget_buffer_process (obj
);
797 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
808 /* Fdelete_process promises to immediately forget about the process, but in
809 reality, Emacs needs to remember those processes until they have been
810 treated by the SIGCHLD handler and waitpid has been invoked on them;
811 otherwise they might fill up the kernel's process table.
813 Some processes created by call-process are also put onto this list.
815 Members of this list are (process-ID . filename) pairs. The
816 process-ID is a number; the filename, if a string, is a file that
817 needs to be removed after the process exits. */
818 static Lisp_Object deleted_pid_list
;
821 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
823 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
824 /* GC treated elements set to nil. */
825 Fdelq (Qnil
, deleted_pid_list
));
829 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
830 doc
: /* Delete PROCESS: kill it and forget about it immediately.
831 PROCESS may be a process, a buffer, the name of a process or buffer, or
832 nil, indicating the current buffer's process. */)
833 (register Lisp_Object process
)
835 register struct Lisp_Process
*p
;
837 process
= get_process (process
);
838 p
= XPROCESS (process
);
840 #ifdef HAVE_GETADDRINFO_A
845 gai_cancel (p
->dns_request
);
846 ret
= gai_error (p
->dns_request
);
847 if (ret
== EAI_CANCELED
|| ret
== 0)
848 free_dns_request (process
);
851 /* If we're called during shutdown, we don't really about
852 freeing all the resources. Otherwise wait until
853 completion, and then free the request. */
854 if (! inhibit_sentinels
)
856 gai_suspend ((struct gaicb
const **) &p
->dns_request
, 1, NULL
);
857 free_dns_request (process
);
863 p
->raw_status_new
= 0;
864 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
866 pset_status (p
, list2 (Qexit
, make_number (0)));
867 p
->tick
= ++process_tick
;
868 status_notify (p
, NULL
);
869 redisplay_preserve_echo_area (13);
874 record_kill_process (p
, Qnil
);
878 /* Update P's status, since record_kill_process will make the
879 SIGCHLD handler update deleted_pid_list, not *P. */
881 if (p
->raw_status_new
)
883 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
884 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
885 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
887 p
->tick
= ++process_tick
;
888 status_notify (p
, NULL
);
889 redisplay_preserve_echo_area (13);
892 remove_process (process
);
896 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
897 doc
: /* Return the status of PROCESS.
898 The returned value is one of the following symbols:
899 run -- for a process that is running.
900 stop -- for a process stopped but continuable.
901 exit -- for a process that has exited.
902 signal -- for a process that has got a fatal signal.
903 open -- for a network stream connection that is open.
904 listen -- for a network stream server that is listening.
905 closed -- for a network stream connection that is closed.
906 connect -- when waiting for a non-blocking connection to complete.
907 failed -- when a non-blocking connection has failed.
908 nil -- if arg is a process name and no such process exists.
909 PROCESS may be a process, a buffer, the name of a process, or
910 nil, indicating the current buffer's process. */)
911 (register Lisp_Object process
)
913 register struct Lisp_Process
*p
;
914 register Lisp_Object status
;
916 if (STRINGP (process
))
917 process
= Fget_process (process
);
919 process
= get_process (process
);
924 p
= XPROCESS (process
);
925 if (p
->raw_status_new
)
929 status
= XCAR (status
);
930 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
932 if (EQ (status
, Qexit
))
934 else if (EQ (p
->command
, Qt
))
936 else if (EQ (status
, Qrun
))
942 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
944 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
945 If PROCESS has not yet exited or died, return 0. */)
946 (register Lisp_Object process
)
948 CHECK_PROCESS (process
);
949 if (XPROCESS (process
)->raw_status_new
)
950 update_status (XPROCESS (process
));
951 if (CONSP (XPROCESS (process
)->status
))
952 return XCAR (XCDR (XPROCESS (process
)->status
));
953 return make_number (0);
956 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
957 doc
: /* Return the process id of PROCESS.
958 This is the pid of the external process which PROCESS uses or talks to.
959 For a network connection, this value is nil. */)
960 (register Lisp_Object process
)
964 CHECK_PROCESS (process
);
965 pid
= XPROCESS (process
)->pid
;
966 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
969 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
970 doc
: /* Return the name of PROCESS, as a string.
971 This is the name of the program invoked in PROCESS,
972 possibly modified to make it unique among process names. */)
973 (register Lisp_Object process
)
975 CHECK_PROCESS (process
);
976 return XPROCESS (process
)->name
;
979 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
980 doc
: /* Return the command that was executed to start PROCESS.
981 This is a list of strings, the first string being the program executed
982 and the rest of the strings being the arguments given to it.
983 For a network or serial process, this is nil (process is running) or t
984 (process is stopped). */)
985 (register Lisp_Object process
)
987 CHECK_PROCESS (process
);
988 return XPROCESS (process
)->command
;
991 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
992 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
993 This is the terminal that the process itself reads and writes on,
994 not the name of the pty that Emacs uses to talk with that terminal. */)
995 (register Lisp_Object process
)
997 CHECK_PROCESS (process
);
998 return XPROCESS (process
)->tty_name
;
1001 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1003 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1005 (register Lisp_Object process
, Lisp_Object buffer
)
1007 struct Lisp_Process
*p
;
1009 CHECK_PROCESS (process
);
1011 CHECK_BUFFER (buffer
);
1012 p
= XPROCESS (process
);
1013 pset_buffer (p
, buffer
);
1014 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1015 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1016 setup_process_coding_systems (process
);
1020 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1022 doc
: /* Return the buffer PROCESS is associated with.
1023 The default process filter inserts output from PROCESS into this buffer. */)
1024 (register Lisp_Object process
)
1026 CHECK_PROCESS (process
);
1027 return XPROCESS (process
)->buffer
;
1030 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1032 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1033 (register Lisp_Object process
)
1035 CHECK_PROCESS (process
);
1036 return XPROCESS (process
)->mark
;
1040 set_process_filter_masks (struct Lisp_Process
*p
)
1042 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1044 FD_CLR (p
->infd
, &input_wait_mask
);
1045 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1047 else if (EQ (p
->filter
, Qt
)
1048 /* Network or serial process not stopped: */
1049 && !EQ (p
->command
, Qt
))
1051 FD_SET (p
->infd
, &input_wait_mask
);
1052 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1056 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1058 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1059 A value of t means stop accepting output from the process.
1061 When a process has a non-default filter, its buffer is not used for output.
1062 Instead, each time it does output, the entire string of output is
1063 passed to the filter.
1065 The filter gets two arguments: the process and the string of output.
1066 The string argument is normally a multibyte string, except:
1067 - if the process's input coding system is no-conversion or raw-text,
1068 it is a unibyte string (the non-converted input), or else
1069 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1070 string (the result of converting the decoded input multibyte
1071 string to unibyte with `string-make-unibyte'). */)
1072 (Lisp_Object process
, Lisp_Object filter
)
1074 CHECK_PROCESS (process
);
1075 struct Lisp_Process
*p
= XPROCESS (process
);
1077 /* Don't signal an error if the process's input file descriptor
1078 is closed. This could make debugging Lisp more difficult,
1079 for example when doing something like
1081 (setq process (start-process ...))
1083 (set-process-filter process ...) */
1086 filter
= Qinternal_default_process_filter
;
1088 pset_filter (p
, filter
);
1091 set_process_filter_masks (p
);
1093 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1094 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1095 setup_process_coding_systems (process
);
1099 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1101 doc
: /* Return the filter function of PROCESS.
1102 See `set-process-filter' for more info on filter functions. */)
1103 (register Lisp_Object process
)
1105 CHECK_PROCESS (process
);
1106 return XPROCESS (process
)->filter
;
1109 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1111 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1112 The sentinel is called as a function when the process changes state.
1113 It gets two arguments: the process, and a string describing the change. */)
1114 (register Lisp_Object process
, Lisp_Object sentinel
)
1116 struct Lisp_Process
*p
;
1118 CHECK_PROCESS (process
);
1119 p
= XPROCESS (process
);
1121 if (NILP (sentinel
))
1122 sentinel
= Qinternal_default_process_sentinel
;
1124 pset_sentinel (p
, sentinel
);
1125 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1126 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1130 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1132 doc
: /* Return the sentinel of PROCESS.
1133 See `set-process-sentinel' for more info on sentinels. */)
1134 (register Lisp_Object process
)
1136 CHECK_PROCESS (process
);
1137 return XPROCESS (process
)->sentinel
;
1140 DEFUN ("set-process-window-size", Fset_process_window_size
,
1141 Sset_process_window_size
, 3, 3, 0,
1142 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1143 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1145 CHECK_PROCESS (process
);
1147 /* All known platforms store window sizes as 'unsigned short'. */
1148 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1149 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1151 if (NETCONN_P (process
)
1152 || XPROCESS (process
)->infd
< 0
1153 || (set_window_size (XPROCESS (process
)->infd
,
1154 XINT (height
), XINT (width
))
1161 DEFUN ("set-process-inherit-coding-system-flag",
1162 Fset_process_inherit_coding_system_flag
,
1163 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1164 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1165 If the second argument FLAG is non-nil, then the variable
1166 `buffer-file-coding-system' of the buffer associated with PROCESS
1167 will be bound to the value of the coding system used to decode
1170 This is useful when the coding system specified for the process buffer
1171 leaves either the character code conversion or the end-of-line conversion
1172 unspecified, or if the coding system used to decode the process output
1173 is more appropriate for saving the process buffer.
1175 Binding the variable `inherit-process-coding-system' to non-nil before
1176 starting the process is an alternative way of setting the inherit flag
1177 for the process which will run.
1179 This function returns FLAG. */)
1180 (register Lisp_Object process
, Lisp_Object flag
)
1182 CHECK_PROCESS (process
);
1183 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1187 DEFUN ("set-process-query-on-exit-flag",
1188 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1190 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1191 If the second argument FLAG is non-nil, Emacs will query the user before
1192 exiting or killing a buffer if PROCESS is running. This function
1194 (register Lisp_Object process
, Lisp_Object flag
)
1196 CHECK_PROCESS (process
);
1197 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1201 DEFUN ("process-query-on-exit-flag",
1202 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1204 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1205 (register Lisp_Object process
)
1207 CHECK_PROCESS (process
);
1208 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1211 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1213 doc
: /* Return the contact info of PROCESS; t for a real child.
1214 For a network or serial connection, the value depends on the optional
1215 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1216 SERVICE) for a network connection or (PORT SPEED) for a serial
1217 connection. If KEY is t, the complete contact information for the
1218 connection is returned, else the specific value for the keyword KEY is
1219 returned. See `make-network-process' or `make-serial-process' for a
1221 If PROCESS is a non-blocking network process that hasn't been fully
1222 set up yet, this function will block until socket setup has completed. */)
1223 (Lisp_Object process
, Lisp_Object key
)
1225 Lisp_Object contact
;
1227 CHECK_PROCESS (process
);
1228 contact
= XPROCESS (process
)->childp
;
1230 #ifdef DATAGRAM_SOCKETS
1232 if (NETCONN_P (process
))
1233 wait_for_socket_fds (process
, "process-contact");
1235 if (DATAGRAM_CONN_P (process
)
1236 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1237 contact
= Fplist_put (contact
, QCremote
,
1238 Fprocess_datagram_address (process
));
1241 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1244 if (NILP (key
) && NETCONN_P (process
))
1245 return list2 (Fplist_get (contact
, QChost
),
1246 Fplist_get (contact
, QCservice
));
1247 if (NILP (key
) && SERIALCONN_P (process
))
1248 return list2 (Fplist_get (contact
, QCport
),
1249 Fplist_get (contact
, QCspeed
));
1250 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1251 if the pipe process is useful for purposes other than receiving
1253 if (NILP (key
) && PIPECONN_P (process
))
1255 return Fplist_get (contact
, key
);
1258 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1260 doc
: /* Return the plist of PROCESS. */)
1261 (register Lisp_Object process
)
1263 CHECK_PROCESS (process
);
1264 return XPROCESS (process
)->plist
;
1267 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1269 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1270 (Lisp_Object process
, Lisp_Object plist
)
1272 CHECK_PROCESS (process
);
1275 pset_plist (XPROCESS (process
), plist
);
1279 #if 0 /* Turned off because we don't currently record this info
1280 in the process. Perhaps add it. */
1281 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1282 doc
: /* Return the connection type of PROCESS.
1283 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1284 a socket connection. */)
1285 (Lisp_Object process
)
1287 return XPROCESS (process
)->type
;
1291 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1292 doc
: /* Return the connection type of PROCESS.
1293 The value is either the symbol `real', `network', or `serial'.
1294 PROCESS may be a process, a buffer, the name of a process or buffer, or
1295 nil, indicating the current buffer's process. */)
1296 (Lisp_Object process
)
1299 proc
= get_process (process
);
1300 return XPROCESS (proc
)->type
;
1303 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1305 doc
: /* Convert network ADDRESS from internal format to a string.
1306 A 4 or 5 element vector represents an IPv4 address (with port number).
1307 An 8 or 9 element vector represents an IPv6 address (with port number).
1308 If optional second argument OMIT-PORT is non-nil, don't include a port
1309 number in the string, even when present in ADDRESS.
1310 Return nil if format of ADDRESS is invalid. */)
1311 (Lisp_Object address
, Lisp_Object omit_port
)
1316 if (STRINGP (address
)) /* AF_LOCAL */
1319 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1321 register struct Lisp_Vector
*p
= XVECTOR (address
);
1322 ptrdiff_t size
= p
->header
.size
;
1323 Lisp_Object args
[10];
1327 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1329 format
= "%d.%d.%d.%d";
1334 format
= "%d.%d.%d.%d:%d";
1337 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1339 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1344 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1350 AUTO_STRING (format_obj
, format
);
1351 args
[0] = format_obj
;
1353 for (i
= 0; i
< nargs
; i
++)
1355 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1358 if (nargs
<= 5 /* IPv4 */
1359 && i
< 4 /* host, not port */
1360 && XINT (p
->contents
[i
]) > 255)
1363 args
[i
+ 1] = p
->contents
[i
];
1366 return Fformat (nargs
+ 1, args
);
1369 if (CONSP (address
))
1371 AUTO_STRING (format
, "<Family %d>");
1372 return CALLN (Fformat
, format
, Fcar (address
));
1378 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1379 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1382 return Fmapcar (Qcdr
, Vprocess_alist
);
1385 /* Starting asynchronous inferior processes. */
1387 static void start_process_unwind (Lisp_Object proc
);
1389 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1390 doc
: /* Start a program in a subprocess. Return the process object for it.
1392 This is similar to `start-process', but arguments are specified as
1393 keyword/argument pairs. The following arguments are defined:
1395 :name NAME -- NAME is name for process. It is modified if necessary
1398 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1399 with the process. Process output goes at end of that buffer, unless
1400 you specify an output stream or filter function to handle the output.
1401 BUFFER may be also nil, meaning that this process is not associated
1404 :command COMMAND -- COMMAND is a list starting with the program file
1405 name, followed by strings to give to the program as arguments.
1407 :coding CODING -- If CODING is a symbol, it specifies the coding
1408 system used for both reading and writing for this process. If CODING
1409 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1410 ENCODING is used for writing.
1412 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1413 the process is running. If BOOL is not given, query before exiting.
1415 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1416 In the stopped state, a process does not accept incoming data, but you
1417 can send outgoing data. The stopped state is cleared by
1418 `continue-process' and set by `stop-process'.
1420 :connection-type TYPE -- TYPE is control type of device used to
1421 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1422 to use a pty, or nil to use the default specified through
1423 `process-connection-type'.
1425 :filter FILTER -- Install FILTER as the process filter.
1427 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1429 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1430 to the standard error of subprocess. Specifying this implies
1431 `:connection-type' is set to `pipe'.
1433 usage: (make-process &rest ARGS) */)
1434 (ptrdiff_t nargs
, Lisp_Object
*args
)
1436 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1437 Lisp_Object xstderr
, stderrproc
;
1438 ptrdiff_t count
= SPECPDL_INDEX ();
1444 /* Save arguments for process-contact and clone-process. */
1445 contact
= Flist (nargs
, args
);
1447 buffer
= Fplist_get (contact
, QCbuffer
);
1449 buffer
= Fget_buffer_create (buffer
);
1451 /* Make sure that the child will be able to chdir to the current
1452 buffer's current directory, or its unhandled equivalent. We
1453 can't just have the child check for an error when it does the
1454 chdir, since it's in a vfork. */
1455 current_dir
= encode_current_directory ();
1457 name
= Fplist_get (contact
, QCname
);
1458 CHECK_STRING (name
);
1460 command
= Fplist_get (contact
, QCcommand
);
1461 if (CONSP (command
))
1462 program
= XCAR (command
);
1466 if (!NILP (program
))
1467 CHECK_STRING (program
);
1470 xstderr
= Fplist_get (contact
, QCstderr
);
1471 if (PROCESSP (xstderr
))
1473 if (!PIPECONN_P (xstderr
))
1474 error ("Process is not a pipe process");
1475 stderrproc
= xstderr
;
1477 else if (!NILP (xstderr
))
1479 CHECK_STRING (program
);
1480 stderrproc
= CALLN (Fmake_pipe_process
,
1482 concat2 (name
, build_string (" stderr")),
1484 Fget_buffer_create (xstderr
));
1487 proc
= make_process (name
);
1488 /* If an error occurs and we can't start the process, we want to
1489 remove it from the process list. This means that each error
1490 check in create_process doesn't need to call remove_process
1491 itself; it's all taken care of here. */
1492 record_unwind_protect (start_process_unwind
, proc
);
1494 pset_childp (XPROCESS (proc
), Qt
);
1495 pset_plist (XPROCESS (proc
), Qnil
);
1496 pset_type (XPROCESS (proc
), Qreal
);
1497 pset_buffer (XPROCESS (proc
), buffer
);
1498 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1499 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1500 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1502 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1503 XPROCESS (proc
)->kill_without_query
= 1;
1504 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1505 pset_command (XPROCESS (proc
), Qt
);
1507 tem
= Fplist_get (contact
, QCconnection_type
);
1509 XPROCESS (proc
)->pty_flag
= true;
1510 else if (EQ (tem
, Qpipe
))
1511 XPROCESS (proc
)->pty_flag
= false;
1512 else if (NILP (tem
))
1513 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1515 report_file_error ("Unknown connection type", tem
);
1517 if (!NILP (stderrproc
))
1519 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1521 XPROCESS (proc
)->pty_flag
= false;
1525 /* AKA GNUTLS_INITSTAGE(proc). */
1526 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1527 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1530 XPROCESS (proc
)->adaptive_read_buffering
1531 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1532 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1534 /* Make the process marker point into the process buffer (if any). */
1535 if (BUFFERP (buffer
))
1536 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1537 BUF_ZV (XBUFFER (buffer
)),
1538 BUF_ZV_BYTE (XBUFFER (buffer
)));
1541 /* Decide coding systems for communicating with the process. Here
1542 we don't setup the structure coding_system nor pay attention to
1543 unibyte mode. They are done in create_process. */
1545 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1546 Lisp_Object coding_systems
= Qt
;
1547 Lisp_Object val
, *args2
;
1549 tem
= Fplist_get (contact
, QCcoding
);
1557 val
= Vcoding_system_for_read
;
1560 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1562 SAFE_ALLOCA_LISP (args2
, nargs2
);
1564 args2
[i
++] = Qstart_process
;
1566 args2
[i
++] = buffer
;
1567 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1568 args2
[i
++] = XCAR (tem2
);
1569 if (!NILP (program
))
1570 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1571 if (CONSP (coding_systems
))
1572 val
= XCAR (coding_systems
);
1573 else if (CONSP (Vdefault_process_coding_system
))
1574 val
= XCAR (Vdefault_process_coding_system
);
1576 pset_decode_coding_system (XPROCESS (proc
), val
);
1585 val
= Vcoding_system_for_write
;
1588 if (EQ (coding_systems
, Qt
))
1590 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1592 SAFE_ALLOCA_LISP (args2
, nargs2
);
1594 args2
[i
++] = Qstart_process
;
1596 args2
[i
++] = buffer
;
1597 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1598 args2
[i
++] = XCAR (tem2
);
1599 if (!NILP (program
))
1600 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1602 if (CONSP (coding_systems
))
1603 val
= XCDR (coding_systems
);
1604 else if (CONSP (Vdefault_process_coding_system
))
1605 val
= XCDR (Vdefault_process_coding_system
);
1607 pset_encode_coding_system (XPROCESS (proc
), val
);
1608 /* Note: At this moment, the above coding system may leave
1609 text-conversion or eol-conversion unspecified. They will be
1610 decided after we read output from the process and decode it by
1611 some coding system, or just before we actually send a text to
1616 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1617 XPROCESS (proc
)->decoding_carryover
= 0;
1618 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1620 XPROCESS (proc
)->inherit_coding_system_flag
1621 = !(NILP (buffer
) || !inherit_process_coding_system
);
1623 if (!NILP (program
))
1625 Lisp_Object program_args
= XCDR (command
);
1627 /* If program file name is not absolute, search our path for it.
1628 Put the name we will really use in TEM. */
1629 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1630 && !(SCHARS (program
) > 1
1631 && IS_DEVICE_SEP (SREF (program
, 1))))
1634 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1635 make_number (X_OK
), false);
1637 report_file_error ("Searching for program", program
);
1638 tem
= Fexpand_file_name (tem
, Qnil
);
1642 if (!NILP (Ffile_directory_p (program
)))
1643 error ("Specified program for new process is a directory");
1647 /* Remove "/:" from TEM. */
1648 tem
= remove_slash_colon (tem
);
1650 Lisp_Object arg_encoding
= Qnil
;
1652 /* Encode the file name and put it in NEW_ARGV.
1653 That's where the child will use it to execute the program. */
1654 tem
= list1 (ENCODE_FILE (tem
));
1655 ptrdiff_t new_argc
= 1;
1657 /* Here we encode arguments by the coding system used for sending
1658 data to the process. We don't support using different coding
1659 systems for encoding arguments and for encoding data sent to the
1662 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1664 Lisp_Object arg
= XCAR (tem2
);
1666 if (STRING_MULTIBYTE (arg
))
1668 if (NILP (arg_encoding
))
1669 arg_encoding
= (complement_process_encoding_system
1670 (XPROCESS (proc
)->encode_coding_system
));
1671 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1673 tem
= Fcons (arg
, tem
);
1677 /* Now that everything is encoded we can collect the strings into
1680 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1681 new_argv
[new_argc
] = 0;
1683 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1685 new_argv
[i
] = SSDATA (XCAR (tem
));
1689 create_process (proc
, new_argv
, current_dir
);
1695 return unbind_to (count
, proc
);
1698 /* This function is the unwind_protect form for Fstart_process. If
1699 PROC doesn't have its pid set, then we know someone has signaled
1700 an error and the process wasn't started successfully, so we should
1701 remove it from the process list. */
1703 start_process_unwind (Lisp_Object proc
)
1705 if (!PROCESSP (proc
))
1708 /* Was PROC started successfully?
1709 -2 is used for a pty with no process, eg for gdb. */
1710 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1711 remove_process (proc
);
1714 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1717 close_process_fd (int *fd_addr
)
1727 /* Indexes of file descriptors in open_fds. */
1730 /* The pipe from Emacs to its subprocess. */
1732 WRITE_TO_SUBPROCESS
,
1734 /* The main pipe from the subprocess to Emacs. */
1735 READ_FROM_SUBPROCESS
,
1738 /* The pipe from the subprocess to Emacs that is closed when the
1739 subprocess execs. */
1740 READ_FROM_EXEC_MONITOR
,
1744 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1747 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1749 struct Lisp_Process
*p
= XPROCESS (process
);
1750 int inchannel
, outchannel
;
1753 int forkin
, forkout
, forkerr
= -1;
1755 char pty_name
[PTY_NAME_SIZE
];
1756 Lisp_Object lisp_pty_name
= Qnil
;
1759 inchannel
= outchannel
= -1;
1762 outchannel
= inchannel
= allocate_pty (pty_name
);
1766 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1767 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1768 /* On most USG systems it does not work to open the pty's tty here,
1769 then close it and reopen it in the child. */
1770 /* Don't let this terminal become our controlling terminal
1771 (in case we don't have one). */
1772 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1774 report_file_error ("Opening pty", Qnil
);
1775 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1777 forkin
= forkout
= -1;
1778 #endif /* not USG, or USG_SUBTTY_WORKS */
1780 lisp_pty_name
= build_string (pty_name
);
1784 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1785 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1786 report_file_error ("Creating pipe", Qnil
);
1787 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1788 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1789 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1790 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1792 if (!NILP (p
->stderrproc
))
1794 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1796 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1798 /* Close unnecessary file descriptors. */
1799 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1800 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1805 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1806 report_file_error ("Creating pipe", Qnil
);
1809 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1810 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1812 /* Record this as an active process, with its channels. */
1813 chan_process
[inchannel
] = process
;
1814 p
->infd
= inchannel
;
1815 p
->outfd
= outchannel
;
1817 /* Previously we recorded the tty descriptor used in the subprocess.
1818 It was only used for getting the foreground tty process, so now
1819 we just reopen the device (see emacs_get_tty_pgrp) as this is
1820 more portable (see USG_SUBTTY_WORKS above). */
1822 p
->pty_flag
= pty_flag
;
1823 pset_status (p
, Qrun
);
1825 if (!EQ (p
->command
, Qt
))
1827 FD_SET (inchannel
, &input_wait_mask
);
1828 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1831 if (inchannel
> max_process_desc
)
1832 max_process_desc
= inchannel
;
1834 /* This may signal an error. */
1835 setup_process_coding_systems (process
);
1838 block_child_signal (&oldset
);
1841 /* vfork, and prevent local vars from being clobbered by the vfork. */
1842 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1843 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1844 char **volatile new_argv_volatile
= new_argv
;
1845 int volatile forkin_volatile
= forkin
;
1846 int volatile forkout_volatile
= forkout
;
1847 int volatile forkerr_volatile
= forkerr
;
1848 struct Lisp_Process
*p_volatile
= p
;
1852 current_dir
= current_dir_volatile
;
1853 lisp_pty_name
= lisp_pty_name_volatile
;
1854 new_argv
= new_argv_volatile
;
1855 forkin
= forkin_volatile
;
1856 forkout
= forkout_volatile
;
1857 forkerr
= forkerr_volatile
;
1860 pty_flag
= p
->pty_flag
;
1863 #endif /* not WINDOWSNT */
1865 /* Make the pty be the controlling terminal of the process. */
1867 /* First, disconnect its current controlling terminal. */
1868 /* We tried doing setsid only if pty_flag, but it caused
1869 process_set_signal to fail on SGI when using a pipe. */
1871 /* Make the pty's terminal the controlling terminal. */
1872 if (pty_flag
&& forkin
>= 0)
1875 /* We ignore the return value
1876 because faith@cs.unc.edu says that is necessary on Linux. */
1877 ioctl (forkin
, TIOCSCTTY
, 0);
1880 #if defined (LDISC1)
1881 if (pty_flag
&& forkin
>= 0)
1884 tcgetattr (forkin
, &t
);
1886 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1887 emacs_perror ("create_process/tcsetattr LDISC1");
1890 #if defined (NTTYDISC) && defined (TIOCSETD)
1891 if (pty_flag
&& forkin
>= 0)
1893 /* Use new line discipline. */
1894 int ldisc
= NTTYDISC
;
1895 ioctl (forkin
, TIOCSETD
, &ldisc
);
1900 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1901 can do TIOCSPGRP only to the process's controlling tty. */
1904 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1905 I can't test it since I don't have 4.3. */
1906 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1909 ioctl (j
, TIOCNOTTY
, 0);
1913 #endif /* TIOCNOTTY */
1915 #if !defined (DONT_REOPEN_PTY)
1916 /*** There is a suggestion that this ought to be a
1917 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1918 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1919 that system does seem to need this code, even though
1920 both TIOCSCTTY is defined. */
1921 /* Now close the pty (if we had it open) and reopen it.
1922 This makes the pty the controlling terminal of the subprocess. */
1926 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1929 emacs_close (forkin
);
1930 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1934 emacs_perror (SSDATA (lisp_pty_name
));
1935 _exit (EXIT_CANCELED
);
1939 #endif /* not DONT_REOPEN_PTY */
1941 #ifdef SETUP_SLAVE_PTY
1946 #endif /* SETUP_SLAVE_PTY */
1947 #endif /* HAVE_PTYS */
1949 signal (SIGINT
, SIG_DFL
);
1950 signal (SIGQUIT
, SIG_DFL
);
1952 signal (SIGPROF
, SIG_DFL
);
1955 /* Emacs ignores SIGPIPE, but the child should not. */
1956 signal (SIGPIPE
, SIG_DFL
);
1958 /* Stop blocking SIGCHLD in the child. */
1959 unblock_child_signal (&oldset
);
1962 child_setup_tty (forkout
);
1967 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1968 #else /* not WINDOWSNT */
1969 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1970 #endif /* not WINDOWSNT */
1973 /* Back in the parent process. */
1975 vfork_errno
= errno
;
1980 /* Stop blocking in the parent. */
1981 unblock_child_signal (&oldset
);
1985 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1988 /* vfork succeeded. */
1990 /* Close the pipe ends that the child uses, or the child's pty. */
1991 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1992 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1995 register_child (pid
, inchannel
);
1996 #endif /* WINDOWSNT */
1998 pset_tty_name (p
, lisp_pty_name
);
2001 /* Wait for child_setup to complete in case that vfork is
2002 actually defined as fork. The descriptor
2003 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2004 of a pipe is closed at the child side either by close-on-exec
2005 on successful execve or the _exit call in child_setup. */
2009 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2010 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2011 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2014 if (!NILP (p
->stderrproc
))
2016 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2017 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2023 create_pty (Lisp_Object process
)
2025 struct Lisp_Process
*p
= XPROCESS (process
);
2026 char pty_name
[PTY_NAME_SIZE
];
2027 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2031 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2032 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2033 /* On most USG systems it does not work to open the pty's tty here,
2034 then close it and reopen it in the child. */
2035 /* Don't let this terminal become our controlling terminal
2036 (in case we don't have one). */
2037 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2039 report_file_error ("Opening pty", Qnil
);
2040 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2041 #if defined (DONT_REOPEN_PTY)
2042 /* In the case that vfork is defined as fork, the parent process
2043 (Emacs) may send some data before the child process completes
2044 tty options setup. So we setup tty before forking. */
2045 child_setup_tty (forkout
);
2046 #endif /* DONT_REOPEN_PTY */
2047 #endif /* not USG, or USG_SUBTTY_WORKS */
2049 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2051 /* Record this as an active process, with its channels.
2052 As a result, child_setup will close Emacs's side of the pipes. */
2053 chan_process
[pty_fd
] = process
;
2057 /* Previously we recorded the tty descriptor used in the subprocess.
2058 It was only used for getting the foreground tty process, so now
2059 we just reopen the device (see emacs_get_tty_pgrp) as this is
2060 more portable (see USG_SUBTTY_WORKS above). */
2063 pset_status (p
, Qrun
);
2064 setup_process_coding_systems (process
);
2066 FD_SET (pty_fd
, &input_wait_mask
);
2067 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2068 if (pty_fd
> max_process_desc
)
2069 max_process_desc
= pty_fd
;
2071 pset_tty_name (p
, build_string (pty_name
));
2077 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2079 doc
: /* Create and return a bidirectional pipe process.
2081 In Emacs, pipes are represented by process objects, so input and
2082 output work as for subprocesses, and `delete-process' closes a pipe.
2083 However, a pipe process has no process id, it cannot be signaled,
2084 and the status codes are different from normal processes.
2086 Arguments are specified as keyword/argument pairs. The following
2087 arguments are defined:
2089 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2091 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2092 with the process. Process output goes at the end of that buffer,
2093 unless you specify an output stream or filter function to handle the
2094 output. If BUFFER is not given, the value of NAME is used.
2096 :coding CODING -- If CODING is a symbol, it specifies the coding
2097 system used for both reading and writing for this process. If CODING
2098 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2099 ENCODING is used for writing.
2101 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2102 the process is running. If BOOL is not given, query before exiting.
2104 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2105 In the stopped state, a pipe process does not accept incoming data,
2106 but you can send outgoing data. The stopped state is cleared by
2107 `continue-process' and set by `stop-process'.
2109 :filter FILTER -- Install FILTER as the process filter.
2111 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2113 usage: (make-pipe-process &rest ARGS) */)
2114 (ptrdiff_t nargs
, Lisp_Object
*args
)
2116 Lisp_Object proc
, contact
;
2117 struct Lisp_Process
*p
;
2118 Lisp_Object name
, buffer
;
2120 ptrdiff_t specpdl_count
;
2121 int inchannel
, outchannel
;
2126 contact
= Flist (nargs
, args
);
2128 name
= Fplist_get (contact
, QCname
);
2129 CHECK_STRING (name
);
2130 proc
= make_process (name
);
2131 specpdl_count
= SPECPDL_INDEX ();
2132 record_unwind_protect (remove_process
, proc
);
2133 p
= XPROCESS (proc
);
2135 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2136 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2137 report_file_error ("Creating pipe", Qnil
);
2138 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2139 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2141 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2142 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2145 register_aux_fd (inchannel
);
2148 /* Record this as an active process, with its channels. */
2149 chan_process
[inchannel
] = proc
;
2150 p
->infd
= inchannel
;
2151 p
->outfd
= outchannel
;
2153 if (inchannel
> max_process_desc
)
2154 max_process_desc
= inchannel
;
2156 buffer
= Fplist_get (contact
, QCbuffer
);
2159 buffer
= Fget_buffer_create (buffer
);
2160 pset_buffer (p
, buffer
);
2162 pset_childp (p
, contact
);
2163 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2164 pset_type (p
, Qpipe
);
2165 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2166 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2168 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2169 p
->kill_without_query
= 1;
2170 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2171 pset_command (p
, Qt
);
2172 eassert (! p
->pty_flag
);
2174 if (!EQ (p
->command
, Qt
))
2176 FD_SET (inchannel
, &input_wait_mask
);
2177 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2179 p
->adaptive_read_buffering
2180 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2181 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2183 /* Make the process marker point into the process buffer (if any). */
2184 if (BUFFERP (buffer
))
2185 set_marker_both (p
->mark
, buffer
,
2186 BUF_ZV (XBUFFER (buffer
)),
2187 BUF_ZV_BYTE (XBUFFER (buffer
)));
2190 /* Setup coding systems for communicating with the network stream. */
2192 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2193 Lisp_Object coding_systems
= Qt
;
2196 tem
= Fplist_get (contact
, QCcoding
);
2204 else if (!NILP (Vcoding_system_for_read
))
2205 val
= Vcoding_system_for_read
;
2206 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2207 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2208 /* We dare not decode end-of-line format by setting VAL to
2209 Qraw_text, because the existing Emacs Lisp libraries
2210 assume that they receive bare code including a sequence of
2215 if (CONSP (coding_systems
))
2216 val
= XCAR (coding_systems
);
2217 else if (CONSP (Vdefault_process_coding_system
))
2218 val
= XCAR (Vdefault_process_coding_system
);
2222 pset_decode_coding_system (p
, val
);
2230 else if (!NILP (Vcoding_system_for_write
))
2231 val
= Vcoding_system_for_write
;
2232 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2236 if (CONSP (coding_systems
))
2237 val
= XCDR (coding_systems
);
2238 else if (CONSP (Vdefault_process_coding_system
))
2239 val
= XCDR (Vdefault_process_coding_system
);
2243 pset_encode_coding_system (p
, val
);
2245 /* This may signal an error. */
2246 setup_process_coding_systems (proc
);
2248 specpdl_ptr
= specpdl
+ specpdl_count
;
2254 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2255 The address family of sa is not included in the result. */
2258 conv_sockaddr_to_lisp (struct sockaddr
*sa
, ptrdiff_t len
)
2260 Lisp_Object address
;
2263 struct Lisp_Vector
*p
;
2265 /* Workaround for a bug in getsockname on BSD: Names bound to
2266 sockets in the UNIX domain are inaccessible; getsockname returns
2267 a zero length name. */
2268 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2269 return empty_unibyte_string
;
2271 switch (sa
->sa_family
)
2275 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2276 len
= sizeof (sin
->sin_addr
) + 1;
2277 address
= Fmake_vector (make_number (len
), Qnil
);
2278 p
= XVECTOR (address
);
2279 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2280 cp
= (unsigned char *) &sin
->sin_addr
;
2286 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2287 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2288 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2289 address
= Fmake_vector (make_number (len
), Qnil
);
2290 p
= XVECTOR (address
);
2291 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2292 for (i
= 0; i
< len
; i
++)
2293 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2297 #ifdef HAVE_LOCAL_SOCKETS
2300 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2301 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2302 /* If the first byte is NUL, the name is a Linux abstract
2303 socket name, and the name can contain embedded NULs. If
2304 it's not, we have a NUL-terminated string. Be careful not
2305 to walk past the end of the object looking for the name
2306 terminator, however. */
2307 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2309 const char *terminator
2310 = memchr (sockun
->sun_path
, '\0', name_length
);
2313 name_length
= terminator
- (const char *) sockun
->sun_path
;
2316 return make_unibyte_string (sockun
->sun_path
, name_length
);
2320 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2321 address
= Fcons (make_number (sa
->sa_family
),
2322 Fmake_vector (make_number (len
), Qnil
));
2323 p
= XVECTOR (XCDR (address
));
2324 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2330 p
->contents
[i
++] = make_number (*cp
++);
2336 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2339 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2341 struct Lisp_Vector
*p
;
2343 if (VECTORP (address
))
2345 p
= XVECTOR (address
);
2346 if (p
->header
.size
== 5)
2349 return sizeof (struct sockaddr_in
);
2352 else if (p
->header
.size
== 9)
2354 *familyp
= AF_INET6
;
2355 return sizeof (struct sockaddr_in6
);
2359 #ifdef HAVE_LOCAL_SOCKETS
2360 else if (STRINGP (address
))
2362 *familyp
= AF_LOCAL
;
2363 return sizeof (struct sockaddr_un
);
2366 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2367 && VECTORP (XCDR (address
)))
2369 struct sockaddr
*sa
;
2370 p
= XVECTOR (XCDR (address
));
2371 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2373 *familyp
= XINT (XCAR (address
));
2374 return p
->header
.size
+ sizeof (sa
->sa_family
);
2379 /* Convert an address object (vector or string) to an internal sockaddr.
2381 The address format has been basically validated by
2382 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2383 it could have come from user data. So if FAMILY is not valid,
2384 we return after zeroing *SA. */
2387 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2389 register struct Lisp_Vector
*p
;
2390 register unsigned char *cp
= NULL
;
2394 memset (sa
, 0, len
);
2396 if (VECTORP (address
))
2398 p
= XVECTOR (address
);
2399 if (family
== AF_INET
)
2401 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2402 len
= sizeof (sin
->sin_addr
) + 1;
2403 hostport
= XINT (p
->contents
[--len
]);
2404 sin
->sin_port
= htons (hostport
);
2405 cp
= (unsigned char *)&sin
->sin_addr
;
2406 sa
->sa_family
= family
;
2409 else if (family
== AF_INET6
)
2411 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2412 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2413 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2414 hostport
= XINT (p
->contents
[--len
]);
2415 sin6
->sin6_port
= htons (hostport
);
2416 for (i
= 0; i
< len
; i
++)
2417 if (INTEGERP (p
->contents
[i
]))
2419 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2422 sa
->sa_family
= family
;
2429 else if (STRINGP (address
))
2431 #ifdef HAVE_LOCAL_SOCKETS
2432 if (family
== AF_LOCAL
)
2434 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2435 cp
= SDATA (address
);
2436 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2437 sockun
->sun_path
[i
] = *cp
++;
2438 sa
->sa_family
= family
;
2445 p
= XVECTOR (XCDR (address
));
2446 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2449 for (i
= 0; i
< len
; i
++)
2450 if (INTEGERP (p
->contents
[i
]))
2451 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2454 #ifdef DATAGRAM_SOCKETS
2455 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2457 doc
: /* Get the current datagram address associated with PROCESS.
2458 If PROCESS is a non-blocking network process that hasn't been fully
2459 set up yet, this function will block until socket setup has completed. */)
2460 (Lisp_Object process
)
2464 CHECK_PROCESS (process
);
2466 if (NETCONN_P (process
))
2467 wait_for_socket_fds (process
, "process-datagram-address");
2469 if (!DATAGRAM_CONN_P (process
))
2472 channel
= XPROCESS (process
)->infd
;
2473 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2474 datagram_address
[channel
].len
);
2477 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2479 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2480 Return nil upon error setting address, ADDRESS otherwise.
2482 If PROCESS is a non-blocking network process that hasn't been fully
2483 set up yet, this function will block until socket setup has completed. */)
2484 (Lisp_Object process
, Lisp_Object address
)
2490 CHECK_PROCESS (process
);
2492 if (NETCONN_P (process
))
2493 wait_for_socket_fds (process
, "set-process-datagram-address");
2495 if (!DATAGRAM_CONN_P (process
))
2498 channel
= XPROCESS (process
)->infd
;
2500 len
= get_lisp_to_sockaddr_size (address
, &family
);
2501 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2503 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2509 static const struct socket_options
{
2510 /* The name of this option. Should be lowercase version of option
2511 name without SO_ prefix. */
2513 /* Option level SOL_... */
2515 /* Option number SO_... */
2517 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2518 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2519 } socket_options
[] =
2521 #ifdef SO_BINDTODEVICE
2522 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2525 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2528 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2531 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2534 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2537 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2540 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2543 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2545 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2548 /* Set option OPT to value VAL on socket S.
2550 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2551 Signals an error if setting a known option fails.
2555 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2558 const struct socket_options
*sopt
;
2563 name
= SSDATA (SYMBOL_NAME (opt
));
2564 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2565 if (strcmp (name
, sopt
->name
) == 0)
2568 switch (sopt
->opttype
)
2573 optval
= NILP (val
) ? 0 : 1;
2574 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2575 &optval
, sizeof (optval
));
2582 if (TYPE_RANGED_INTEGERP (int, val
))
2583 optval
= XINT (val
);
2585 error ("Bad option value for %s", name
);
2586 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2587 &optval
, sizeof (optval
));
2591 #ifdef SO_BINDTODEVICE
2594 char devname
[IFNAMSIZ
+ 1];
2596 /* This is broken, at least in the Linux 2.4 kernel.
2597 To unbind, the arg must be a zero integer, not the empty string.
2598 This should work on all systems. KFS. 2003-09-23. */
2599 memset (devname
, 0, sizeof devname
);
2602 char *arg
= SSDATA (val
);
2603 int len
= min (strlen (arg
), IFNAMSIZ
);
2604 memcpy (devname
, arg
, len
);
2606 else if (!NILP (val
))
2607 error ("Bad option value for %s", name
);
2608 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2617 struct linger linger
;
2620 linger
.l_linger
= 0;
2621 if (TYPE_RANGED_INTEGERP (int, val
))
2622 linger
.l_linger
= XINT (val
);
2624 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2625 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2626 &linger
, sizeof (linger
));
2637 int setsockopt_errno
= errno
;
2638 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2642 return (1 << sopt
->optbit
);
2646 DEFUN ("set-network-process-option",
2647 Fset_network_process_option
, Sset_network_process_option
,
2649 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2650 See `make-network-process' for a list of options and values.
2651 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2652 OPTION is not a supported option, return nil instead; otherwise return t.
2654 If PROCESS is a non-blocking network process that hasn't been fully
2655 set up yet, this function will block until socket setup has completed. */)
2656 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2659 struct Lisp_Process
*p
;
2661 CHECK_PROCESS (process
);
2662 p
= XPROCESS (process
);
2663 if (!NETCONN1_P (p
))
2664 error ("Process is not a network process");
2666 wait_for_socket_fds (process
, "set-network-process-option");
2670 error ("Process is not running");
2672 if (set_socket_option (s
, option
, value
))
2674 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2678 if (NILP (no_error
))
2679 error ("Unknown or unsupported option");
2685 DEFUN ("serial-process-configure",
2686 Fserial_process_configure
,
2687 Sserial_process_configure
,
2689 doc
: /* Configure speed, bytesize, etc. of a serial process.
2691 Arguments are specified as keyword/argument pairs. Attributes that
2692 are not given are re-initialized from the process's current
2693 configuration (available via the function `process-contact') or set to
2694 reasonable default values. The following arguments are defined:
2700 -- Any of these arguments can be given to identify the process that is
2701 to be configured. If none of these arguments is given, the current
2702 buffer's process is used.
2704 :speed SPEED -- SPEED is the speed of the serial port in bits per
2705 second, also called baud rate. Any value can be given for SPEED, but
2706 most serial ports work only at a few defined values between 1200 and
2707 115200, with 9600 being the most common value. If SPEED is nil, the
2708 serial port is not configured any further, i.e., all other arguments
2709 are ignored. This may be useful for special serial ports such as
2710 Bluetooth-to-serial converters which can only be configured through AT
2711 commands. A value of nil for SPEED can be used only when passed
2712 through `make-serial-process' or `serial-term'.
2714 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2715 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2717 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2718 `odd' (use odd parity), or the symbol `even' (use even parity). If
2719 PARITY is not given, no parity is used.
2721 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2722 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2723 is not given or nil, 1 stopbit is used.
2725 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2726 flowcontrol to be used, which is either nil (don't use flowcontrol),
2727 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2728 (use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2729 flowcontrol is used.
2731 `serial-process-configure' is called by `make-serial-process' for the
2732 initial configuration of the serial port.
2736 (serial-process-configure :process "/dev/ttyS0" :speed 1200)
2738 (serial-process-configure
2739 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2741 (serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2743 usage: (serial-process-configure &rest ARGS) */)
2744 (ptrdiff_t nargs
, Lisp_Object
*args
)
2746 struct Lisp_Process
*p
;
2747 Lisp_Object contact
= Qnil
;
2748 Lisp_Object proc
= Qnil
;
2750 contact
= Flist (nargs
, args
);
2752 proc
= Fplist_get (contact
, QCprocess
);
2754 proc
= Fplist_get (contact
, QCname
);
2756 proc
= Fplist_get (contact
, QCbuffer
);
2758 proc
= Fplist_get (contact
, QCport
);
2759 proc
= get_process (proc
);
2760 p
= XPROCESS (proc
);
2761 if (!EQ (p
->type
, Qserial
))
2762 error ("Not a serial process");
2764 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2767 serial_configure (p
, contact
);
2771 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2773 doc
: /* Create and return a serial port process.
2775 In Emacs, serial port connections are represented by process objects,
2776 so input and output work as for subprocesses, and `delete-process'
2777 closes a serial port connection. However, a serial process has no
2778 process id, it cannot be signaled, and the status codes are different
2779 from normal processes.
2781 `make-serial-process' creates a process and a buffer, on which you
2782 probably want to use `process-send-string'. Try \\[serial-term] for
2783 an interactive terminal. See below for examples.
2785 Arguments are specified as keyword/argument pairs. The following
2786 arguments are defined:
2788 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2789 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2790 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2791 the backslashes in strings).
2793 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2794 which this function calls.
2796 :name NAME -- NAME is the name of the process. If NAME is not given,
2797 the value of PORT is used.
2799 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2800 with the process. Process output goes at the end of that buffer,
2801 unless you specify an output stream or filter function to handle the
2802 output. If BUFFER is not given, the value of NAME is used.
2804 :coding CODING -- If CODING is a symbol, it specifies the coding
2805 system used for both reading and writing for this process. If CODING
2806 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2807 ENCODING is used for writing.
2809 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2810 the process is running. If BOOL is not given, query before exiting.
2812 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2813 In the stopped state, a serial process does not accept incoming data,
2814 but you can send outgoing data. The stopped state is cleared by
2815 `continue-process' and set by `stop-process'.
2817 :filter FILTER -- Install FILTER as the process filter.
2819 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2821 :plist PLIST -- Install PLIST as the initial plist of the process.
2827 -- This function calls `serial-process-configure' to handle these
2830 The original argument list, possibly modified by later configuration,
2831 is available via the function `process-contact'.
2835 (make-serial-process :port "/dev/ttyS0" :speed 9600)
2837 (make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2839 (make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2841 (make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2843 usage: (make-serial-process &rest ARGS) */)
2844 (ptrdiff_t nargs
, Lisp_Object
*args
)
2847 Lisp_Object proc
, contact
, port
;
2848 struct Lisp_Process
*p
;
2849 Lisp_Object name
, buffer
;
2850 Lisp_Object tem
, val
;
2851 ptrdiff_t specpdl_count
;
2856 contact
= Flist (nargs
, args
);
2858 port
= Fplist_get (contact
, QCport
);
2860 error ("No port specified");
2861 CHECK_STRING (port
);
2863 if (NILP (Fplist_member (contact
, QCspeed
)))
2864 error (":speed not specified");
2865 if (!NILP (Fplist_get (contact
, QCspeed
)))
2866 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2868 name
= Fplist_get (contact
, QCname
);
2871 CHECK_STRING (name
);
2872 proc
= make_process (name
);
2873 specpdl_count
= SPECPDL_INDEX ();
2874 record_unwind_protect (remove_process
, proc
);
2875 p
= XPROCESS (proc
);
2877 fd
= serial_open (port
);
2878 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2881 if (fd
> max_process_desc
)
2882 max_process_desc
= fd
;
2883 chan_process
[fd
] = proc
;
2885 buffer
= Fplist_get (contact
, QCbuffer
);
2888 buffer
= Fget_buffer_create (buffer
);
2889 pset_buffer (p
, buffer
);
2891 pset_childp (p
, contact
);
2892 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2893 pset_type (p
, Qserial
);
2894 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2895 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2897 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2898 p
->kill_without_query
= 1;
2899 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2900 pset_command (p
, Qt
);
2901 eassert (! p
->pty_flag
);
2903 if (!EQ (p
->command
, Qt
))
2905 FD_SET (fd
, &input_wait_mask
);
2906 FD_SET (fd
, &non_keyboard_wait_mask
);
2909 if (BUFFERP (buffer
))
2911 set_marker_both (p
->mark
, buffer
,
2912 BUF_ZV (XBUFFER (buffer
)),
2913 BUF_ZV_BYTE (XBUFFER (buffer
)));
2916 tem
= Fplist_member (contact
, QCcoding
);
2917 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2923 val
= XCAR (XCDR (tem
));
2927 else if (!NILP (Vcoding_system_for_read
))
2928 val
= Vcoding_system_for_read
;
2929 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2930 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2932 pset_decode_coding_system (p
, val
);
2937 val
= XCAR (XCDR (tem
));
2941 else if (!NILP (Vcoding_system_for_write
))
2942 val
= Vcoding_system_for_write
;
2943 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2944 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2946 pset_encode_coding_system (p
, val
);
2948 setup_process_coding_systems (proc
);
2949 pset_decoding_buf (p
, empty_unibyte_string
);
2950 p
->decoding_carryover
= 0;
2951 pset_encoding_buf (p
, empty_unibyte_string
);
2952 p
->inherit_coding_system_flag
2953 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2955 Fserial_process_configure (nargs
, args
);
2957 specpdl_ptr
= specpdl
+ specpdl_count
;
2963 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2964 Lisp_Object service
, Lisp_Object name
)
2967 struct Lisp_Process
*p
= XPROCESS (proc
);
2968 Lisp_Object contact
= p
->childp
;
2969 Lisp_Object coding_systems
= Qt
;
2972 tem
= Fplist_member (contact
, QCcoding
);
2973 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2974 tem
= Qnil
; /* No error message (too late!). */
2976 /* Setup coding systems for communicating with the network stream. */
2977 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2981 val
= XCAR (XCDR (tem
));
2985 else if (!NILP (Vcoding_system_for_read
))
2986 val
= Vcoding_system_for_read
;
2987 else if ((!NILP (p
->buffer
)
2988 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2989 || (NILP (p
->buffer
)
2990 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2991 /* We dare not decode end-of-line format by setting VAL to
2992 Qraw_text, because the existing Emacs Lisp libraries
2993 assume that they receive bare code including a sequence of
2998 if (NILP (host
) || NILP (service
))
2999 coding_systems
= Qnil
;
3001 coding_systems
= CALLN (Ffind_operation_coding_system
,
3002 Qopen_network_stream
, name
, p
->buffer
,
3004 if (CONSP (coding_systems
))
3005 val
= XCAR (coding_systems
);
3006 else if (CONSP (Vdefault_process_coding_system
))
3007 val
= XCAR (Vdefault_process_coding_system
);
3011 pset_decode_coding_system (p
, val
);
3015 val
= XCAR (XCDR (tem
));
3019 else if (!NILP (Vcoding_system_for_write
))
3020 val
= Vcoding_system_for_write
;
3021 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3025 if (EQ (coding_systems
, Qt
))
3027 if (NILP (host
) || NILP (service
))
3028 coding_systems
= Qnil
;
3030 coding_systems
= CALLN (Ffind_operation_coding_system
,
3031 Qopen_network_stream
, name
, p
->buffer
,
3034 if (CONSP (coding_systems
))
3035 val
= XCDR (coding_systems
);
3036 else if (CONSP (Vdefault_process_coding_system
))
3037 val
= XCDR (Vdefault_process_coding_system
);
3041 pset_encode_coding_system (p
, val
);
3043 pset_decoding_buf (p
, empty_unibyte_string
);
3044 p
->decoding_carryover
= 0;
3045 pset_encoding_buf (p
, empty_unibyte_string
);
3047 p
->inherit_coding_system_flag
3048 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3053 finish_after_tls_connection (Lisp_Object proc
)
3055 struct Lisp_Process
*p
= XPROCESS (proc
);
3056 Lisp_Object contact
= p
->childp
;
3057 Lisp_Object result
= Qt
;
3059 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3060 result
= call3 (Qnsm_verify_connection
,
3062 Fplist_get (contact
, QChost
),
3063 Fplist_get (contact
, QCservice
));
3067 pset_status (p
, list2 (Qfailed
,
3068 build_string ("The Network Security Manager stopped the connections")));
3069 deactivate_process (proc
);
3073 /* If we cleared the connection wait mask before we did
3074 the TLS setup, then we have to say that the process
3075 is finally "open" here. */
3076 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3078 pset_status (p
, Qrun
);
3079 /* Execute the sentinel here. If we had relied on
3080 status_notify to do it later, it will read input
3081 from the process before calling the sentinel. */
3082 exec_sentinel (proc
, build_string ("open\n"));
3089 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
)
3091 ptrdiff_t count
= SPECPDL_INDEX ();
3093 int s
= -1, outch
, inch
;
3095 Lisp_Object ip_address
;
3097 struct sockaddr
*sa
= NULL
;
3100 struct Lisp_Process
*p
= XPROCESS (proc
);
3101 Lisp_Object contact
= p
->childp
;
3104 /* Do this in case we never enter the while-loop below. */
3105 count1
= SPECPDL_INDEX ();
3108 while (!NILP (ip_addresses
))
3110 ip_address
= XCAR (ip_addresses
);
3111 ip_addresses
= XCDR (ip_addresses
);
3117 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3120 sa
= xmalloc (addrlen
);
3121 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3123 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3130 #ifdef DATAGRAM_SOCKETS
3131 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3133 #endif /* DATAGRAM_SOCKETS */
3135 #ifdef NON_BLOCKING_CONNECT
3136 if (p
->is_non_blocking_client
)
3138 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3149 /* Make us close S if quit. */
3150 record_unwind_protect_int (close_file_unwind
, s
);
3152 /* Parse network options in the arg list. We simply ignore anything
3153 which isn't a known option (including other keywords). An error
3154 is signaled if setting a known option fails. */
3156 Lisp_Object params
= contact
, key
, val
;
3158 while (!NILP (params
))
3160 key
= XCAR (params
);
3161 params
= XCDR (params
);
3162 val
= XCAR (params
);
3163 params
= XCDR (params
);
3164 optbits
|= set_socket_option (s
, key
, val
);
3170 /* Configure as a server socket. */
3172 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3173 explicit :reuseaddr key to override this. */
3174 #ifdef HAVE_LOCAL_SOCKETS
3175 if (family
!= AF_LOCAL
)
3177 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3180 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3181 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3184 if (bind (s
, sa
, addrlen
))
3185 report_file_error ("Cannot bind server socket", Qnil
);
3187 #ifdef HAVE_GETSOCKNAME
3190 struct sockaddr_in sa1
;
3191 socklen_t len1
= sizeof (sa1
);
3192 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3194 Lisp_Object service
;
3195 service
= make_number (ntohs (sa1
.sin_port
));
3196 contact
= Fplist_put (contact
, QCservice
, service
);
3197 /* Save the port number so that we can stash it in
3198 the process object later. */
3199 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3204 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3205 report_file_error ("Cannot listen on server socket", Qnil
);
3213 ret
= connect (s
, sa
, addrlen
);
3216 if (ret
== 0 || xerrno
== EISCONN
)
3218 /* The unwind-protect will be discarded afterwards.
3219 Likewise for immediate_quit. */
3223 #ifdef NON_BLOCKING_CONNECT
3225 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3229 if (p
->is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3236 if (xerrno
== EINTR
)
3238 /* Unlike most other syscalls connect() cannot be called
3239 again. (That would return EALREADY.) The proper way to
3240 wait for completion is pselect(). */
3248 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3254 report_file_error ("Failed select", Qnil
);
3258 len
= sizeof xerrno
;
3259 eassert (FD_ISSET (s
, &fdset
));
3260 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3261 report_file_error ("Failed getsockopt", Qnil
);
3263 report_file_errno ("Failed connect", Qnil
, xerrno
);
3266 #endif /* !WINDOWSNT */
3270 /* Discard the unwind protect closing S. */
3271 specpdl_ptr
= specpdl
+ count1
;
3276 if (xerrno
== EINTR
)
3283 #ifdef DATAGRAM_SOCKETS
3284 if (p
->socktype
== SOCK_DGRAM
)
3286 if (datagram_address
[s
].sa
)
3289 datagram_address
[s
].sa
= xmalloc (addrlen
);
3290 datagram_address
[s
].len
= addrlen
;
3294 memset (datagram_address
[s
].sa
, 0, addrlen
);
3295 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3298 ptrdiff_t rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3299 if (rlen
!= 0 && rfamily
== family
3301 conv_lisp_to_sockaddr (rfamily
, remote
,
3302 datagram_address
[s
].sa
, rlen
);
3306 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3310 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3311 conv_sockaddr_to_lisp (sa
, addrlen
));
3312 #ifdef HAVE_GETSOCKNAME
3315 struct sockaddr_in sa1
;
3316 socklen_t len1
= sizeof (sa1
);
3317 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3318 contact
= Fplist_put (contact
, QClocal
,
3319 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3328 /* If non-blocking got this far - and failed - assume non-blocking is
3329 not supported after all. This is probably a wrong assumption, but
3330 the normal blocking calls to open-network-stream handles this error
3332 if (p
->is_non_blocking_client
)
3335 report_file_errno ((p
->is_server
3336 ? "make server process failed"
3337 : "make client process failed"),
3344 chan_process
[inch
] = proc
;
3346 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3348 p
= XPROCESS (proc
);
3349 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3353 /* Discard the unwind protect for closing S, if any. */
3354 specpdl_ptr
= specpdl
+ count1
;
3356 /* Unwind bind_polling_period and request_sigio. */
3357 unbind_to (count
, Qnil
);
3359 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3360 pset_status (p
, Qlisten
);
3362 /* Make the process marker point into the process buffer (if any). */
3363 if (BUFFERP (p
->buffer
))
3364 set_marker_both (p
->mark
, p
->buffer
,
3365 BUF_ZV (XBUFFER (p
->buffer
)),
3366 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3368 #ifdef NON_BLOCKING_CONNECT
3369 if (p
->is_non_blocking_client
)
3371 /* We may get here if connect did succeed immediately. However,
3372 in that case, we still need to signal this like a non-blocking
3374 pset_status (p
, Qconnect
);
3375 if (!FD_ISSET (inch
, &connect_wait_mask
))
3377 FD_SET (inch
, &connect_wait_mask
);
3378 FD_SET (inch
, &write_mask
);
3379 num_pending_connects
++;
3384 /* A server may have a client filter setting of Qt, but it must
3385 still listen for incoming connects unless it is stopped. */
3386 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3387 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3389 FD_SET (inch
, &input_wait_mask
);
3390 FD_SET (inch
, &non_keyboard_wait_mask
);
3393 if (inch
> max_process_desc
)
3394 max_process_desc
= inch
;
3396 /* Set up the masks based on the process filter. */
3397 set_process_filter_masks (p
);
3399 setup_process_coding_systems (proc
);
3402 /* Continue the asynchronous connection. */
3403 if (!NILP (p
->gnutls_boot_parameters
))
3405 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3407 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3408 p
->gnutls_boot_parameters
= Qnil
;
3410 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3411 /* Run sentinels, etc. */
3412 finish_after_tls_connection (proc
);
3413 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3415 deactivate_process (proc
);
3417 pset_status (p
, list2 (Qfailed
,
3418 build_string ("TLS negotiation failed")));
3420 pset_status (p
, list2 (Qfailed
, boot
));
3427 #ifndef HAVE_GETADDRINFO
3429 conv_numerical_to_lisp (unsigned char *number
, int length
, int port
)
3431 Lisp_Object address
= Fmake_vector (make_number (length
+ 1), Qnil
);
3432 struct Lisp_Vector
*p
= XVECTOR (address
);
3434 p
->contents
[length
] = make_number (port
);
3435 for (int i
= 0; i
< length
; i
++)
3436 p
->contents
[i
] = make_number (number
[i
]);
3442 /* Create a network stream/datagram client/server process. Treated
3443 exactly like a normal process when reading and writing. Primary
3444 differences are in status display and process deletion. A network
3445 connection has no PID; you cannot signal it. All you can do is
3446 stop/continue it and deactivate/close it via delete-process. */
3448 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3450 doc
: /* Create and return a network server or client process.
3452 In Emacs, network connections are represented by process objects, so
3453 input and output work as for subprocesses and `delete-process' closes
3454 a network connection. However, a network process has no process id,
3455 it cannot be signaled, and the status codes are different from normal
3458 Arguments are specified as keyword/argument pairs. The following
3459 arguments are defined:
3461 :name NAME -- NAME is name for process. It is modified if necessary
3464 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3465 with the process. Process output goes at end of that buffer, unless
3466 you specify an output stream or filter function to handle the output.
3467 BUFFER may be also nil, meaning that this process is not associated
3470 :host HOST -- HOST is name of the host to connect to, or its IP
3471 address. The symbol `local' specifies the local host. If specified
3472 for a server process, it must be a valid name or address for the local
3473 host, and only clients connecting to that address will be accepted.
3475 :service SERVICE -- SERVICE is name of the service desired, or an
3476 integer specifying a port number to connect to. If SERVICE is t,
3477 a random port number is selected for the server. (If Emacs was
3478 compiled with getaddrinfo, a port number can also be specified as a
3479 string, e.g. "80", as well as an integer. This is not portable.)
3481 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3482 stream type connection, `datagram' creates a datagram type connection,
3483 `seqpacket' creates a reliable datagram connection.
3485 :family FAMILY -- FAMILY is the address (and protocol) family for the
3486 service specified by HOST and SERVICE. The default (nil) is to use
3487 whatever address family (IPv4 or IPv6) that is defined for the host
3488 and port number specified by HOST and SERVICE. Other address families
3490 local -- for a local (i.e. UNIX) address specified by SERVICE.
3491 ipv4 -- use IPv4 address family only.
3492 ipv6 -- use IPv6 address family only.
3494 :local ADDRESS -- ADDRESS is the local address used for the connection.
3495 This parameter is ignored when opening a client process. When specified
3496 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3498 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3499 connection. This parameter is ignored when opening a stream server
3500 process. For a datagram server process, it specifies the initial
3501 setting of the remote datagram address. When specified for a client
3502 process, the FAMILY, HOST, and SERVICE args are ignored.
3504 The format of ADDRESS depends on the address family:
3505 - An IPv4 address is represented as an vector of integers [A B C D P]
3506 corresponding to numeric IP address A.B.C.D and port number P.
3507 - A local address is represented as a string with the address in the
3508 local address space.
3509 - An "unsupported family" address is represented by a cons (F . AV)
3510 where F is the family number and AV is a vector containing the socket
3511 address data with one element per address data byte. Do not rely on
3512 this format in portable code, as it may depend on implementation
3513 defined constants, data sizes, and data structure alignment.
3515 :coding CODING -- If CODING is a symbol, it specifies the coding
3516 system used for both reading and writing for this process. If CODING
3517 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3518 ENCODING is used for writing.
3520 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3521 process, return without waiting for the connection to complete;
3522 instead, the sentinel function will be called with second arg matching
3523 "open" (if successful) or "failed" when the connect completes.
3524 Default is to use a blocking connect (i.e. wait) for stream type
3527 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3528 running when Emacs is exited.
3530 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3531 In the stopped state, a server process does not accept new
3532 connections, and a client process does not handle incoming traffic.
3533 The stopped state is cleared by `continue-process' and set by
3536 :filter FILTER -- Install FILTER as the process filter.
3538 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3539 process filter are multibyte, otherwise they are unibyte.
3540 If this keyword is not specified, the strings are multibyte if
3541 the default value of `enable-multibyte-characters' is non-nil.
3543 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3545 :log LOG -- Install LOG as the server process log function. This
3546 function is called when the server accepts a network connection from a
3547 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3548 is the server process, CLIENT is the new process for the connection,
3549 and MESSAGE is a string.
3551 :plist PLIST -- Install PLIST as the new process's initial plist.
3553 :tls-parameters LIST -- is a list that should be supplied if you're
3554 opening a TLS connection. The first element is the TLS type (either
3555 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3556 be a keyword list accepted by gnutls-boot (as returned by
3557 `gnutls-boot-parameters').
3559 :server QLEN -- if QLEN is non-nil, create a server process for the
3560 specified FAMILY, SERVICE, and connection type (stream or datagram).
3561 If QLEN is an integer, it is used as the max. length of the server's
3562 pending connection queue (also known as the backlog); the default
3563 queue length is 5. Default is to create a client process.
3565 The following network options can be specified for this connection:
3567 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3568 :dontroute BOOL -- Only send to directly connected hosts.
3569 :keepalive BOOL -- Send keep-alive messages on network stream.
3570 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3571 :oobinline BOOL -- Place out-of-band data in receive data stream.
3572 :priority INT -- Set protocol defined priority for sent packets.
3573 :reuseaddr BOOL -- Allow reusing a recently used local address
3574 (this is allowed by default for a server process).
3575 :bindtodevice NAME -- bind to interface NAME. Using this may require
3576 special privileges on some systems.
3578 Consult the relevant system programmer's manual pages for more
3579 information on using these options.
3582 A server process will listen for and accept connections from clients.
3583 When a client connection is accepted, a new network process is created
3584 for the connection with the following parameters:
3586 - The client's process name is constructed by concatenating the server
3587 process's NAME and a client identification string.
3588 - If the FILTER argument is non-nil, the client process will not get a
3589 separate process buffer; otherwise, the client's process buffer is a newly
3590 created buffer named after the server process's BUFFER name or process
3591 NAME concatenated with the client identification string.
3592 - The connection type and the process filter and sentinel parameters are
3593 inherited from the server process's TYPE, FILTER and SENTINEL.
3594 - The client process's contact info is set according to the client's
3595 addressing information (typically an IP address and a port number).
3596 - The client process's plist is initialized from the server's plist.
3598 Notice that the FILTER and SENTINEL args are never used directly by
3599 the server process. Also, the BUFFER argument is not used directly by
3600 the server process, but via the optional :log function, accepted (and
3601 failed) connections may be logged in the server process's buffer.
3603 The original argument list, modified with the actual connection
3604 information, is available via the `process-contact' function.
3606 usage: (make-network-process &rest ARGS) */)
3607 (ptrdiff_t nargs
, Lisp_Object
*args
)
3610 Lisp_Object contact
;
3611 struct Lisp_Process
*p
;
3612 #if defined HAVE_GETADDRINFO || defined HAVE_GETADDRINFO_A
3613 const char *portstring
;
3614 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3615 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3617 #ifdef HAVE_LOCAL_SOCKETS
3618 struct sockaddr_un address_un
;
3622 Lisp_Object name
, buffer
, host
, service
, address
;
3623 Lisp_Object filter
, sentinel
;
3624 Lisp_Object ip_addresses
= Qnil
;
3627 int ai_protocol
= 0;
3628 #ifdef HAVE_GETADDRINFO_A
3629 struct gaicb
*dns_request
= NULL
;
3631 ptrdiff_t count
= SPECPDL_INDEX ();
3636 /* Save arguments for process-contact and clone-process. */
3637 contact
= Flist (nargs
, args
);
3640 /* Ensure socket support is loaded if available. */
3641 init_winsock (TRUE
);
3644 /* :type TYPE (nil: stream, datagram */
3645 tem
= Fplist_get (contact
, QCtype
);
3647 socktype
= SOCK_STREAM
;
3648 #ifdef DATAGRAM_SOCKETS
3649 else if (EQ (tem
, Qdatagram
))
3650 socktype
= SOCK_DGRAM
;
3652 #ifdef HAVE_SEQPACKET
3653 else if (EQ (tem
, Qseqpacket
))
3654 socktype
= SOCK_SEQPACKET
;
3657 error ("Unsupported connection type");
3659 name
= Fplist_get (contact
, QCname
);
3660 buffer
= Fplist_get (contact
, QCbuffer
);
3661 filter
= Fplist_get (contact
, QCfilter
);
3662 sentinel
= Fplist_get (contact
, QCsentinel
);
3664 CHECK_STRING (name
);
3666 /* :local ADDRESS or :remote ADDRESS */
3667 tem
= Fplist_get (contact
, QCserver
);
3669 address
= Fplist_get (contact
, QCremote
);
3671 address
= Fplist_get (contact
, QClocal
);
3672 if (!NILP (address
))
3674 host
= service
= Qnil
;
3676 if (!get_lisp_to_sockaddr_size (address
, &family
))
3677 error ("Malformed :address");
3679 ip_addresses
= list1 (address
);
3683 /* :family FAMILY -- nil (for Inet), local, or integer. */
3684 tem
= Fplist_get (contact
, QCfamily
);
3687 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3693 #ifdef HAVE_LOCAL_SOCKETS
3694 else if (EQ (tem
, Qlocal
))
3698 else if (EQ (tem
, Qipv6
))
3701 else if (EQ (tem
, Qipv4
))
3703 else if (TYPE_RANGED_INTEGERP (int, tem
))
3704 family
= XINT (tem
);
3706 error ("Unknown address family");
3708 /* :service SERVICE -- string, integer (port number), or t (random port). */
3709 service
= Fplist_get (contact
, QCservice
);
3711 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3712 host
= Fplist_get (contact
, QChost
);
3715 /* The "connection" function gets it bind info from the address we're
3716 given, so use this dummy address if nothing is specified. */
3717 #ifdef HAVE_LOCAL_SOCKETS
3718 if (family
!= AF_LOCAL
)
3720 host
= build_string ("127.0.0.1");
3724 if (EQ (host
, Qlocal
))
3725 /* Depending on setup, "localhost" may map to different IPv4 and/or
3726 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3727 host
= build_string ("127.0.0.1");
3728 CHECK_STRING (host
);
3731 #ifdef HAVE_LOCAL_SOCKETS
3732 if (family
== AF_LOCAL
)
3736 message (":family local ignores the :host property");
3737 contact
= Fplist_put (contact
, QChost
, Qnil
);
3740 CHECK_STRING (service
);
3741 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3742 error ("Service name too long");
3743 ip_addresses
= list1 (service
);
3748 /* Slow down polling to every ten seconds.
3749 Some kernels have a bug which causes retrying connect to fail
3750 after a connect. Polling can interfere with gethostbyname too. */
3751 #ifdef POLL_FOR_INPUT
3752 if (socktype
!= SOCK_DGRAM
)
3754 record_unwind_protect_void (run_all_atimers
);
3755 bind_polling_period (10);
3759 #if defined HAVE_GETADDRINFO || defined HAVE_GETADDRINFO_A
3762 /* SERVICE can either be a string or int.
3763 Convert to a C string for later use by getaddrinfo. */
3764 if (EQ (service
, Qt
))
3769 else if (INTEGERP (service
))
3771 portstring
= portbuf
;
3772 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3776 CHECK_STRING (service
);
3777 portstring
= SSDATA (service
);
3778 portstringlen
= SBYTES (service
);
3783 #ifdef HAVE_GETADDRINFO_A
3784 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3786 ptrdiff_t hostlen
= SBYTES (host
);
3790 struct addrinfo hints
;
3791 char str
[FLEXIBLE_ARRAY_MEMBER
];
3792 } *req
= xmalloc (offsetof (struct req
, str
)
3793 + hostlen
+ 1 + portstringlen
+ 1);
3794 dns_request
= &req
->gaicb
;
3795 dns_request
->ar_name
= req
->str
;
3796 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3797 dns_request
->ar_request
= &req
->hints
;
3798 dns_request
->ar_result
= NULL
;
3799 memset (&req
->hints
, 0, sizeof req
->hints
);
3800 req
->hints
.ai_family
= family
;
3801 req
->hints
.ai_socktype
= socktype
;
3802 strcpy (req
->str
, SSDATA (host
));
3803 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3805 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3807 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3811 #endif /* HAVE_GETADDRINFO_A */
3813 #ifdef HAVE_GETADDRINFO
3814 /* If we have a host, use getaddrinfo to resolve both host and service.
3815 Otherwise, use getservbyname to lookup the service. */
3819 struct addrinfo
*res
, *lres
;
3825 struct addrinfo hints
;
3826 memset (&hints
, 0, sizeof hints
);
3827 hints
.ai_family
= family
;
3828 hints
.ai_socktype
= socktype
;
3830 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3832 #ifdef HAVE_GAI_STRERROR
3833 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3835 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3839 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3841 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3842 (lres
->ai_addr
, lres
->ai_addrlen
),
3844 ai_protocol
= lres
->ai_protocol
;
3847 ip_addresses
= Fnreverse (ip_addresses
);
3853 #endif /* HAVE_GETADDRINFO */
3855 /* We end up here if getaddrinfo is not defined, or in case no hostname
3856 has been specified (e.g. for a local server process). */
3858 if (EQ (service
, Qt
))
3860 else if (INTEGERP (service
))
3861 port
= XINT (service
);
3864 CHECK_STRING (service
);
3867 if (SBYTES (service
) != 0)
3869 /* Allow the service to be a string containing the port number,
3870 because that's allowed if you have getaddrbyname. */
3872 long int lport
= strtol (SSDATA (service
), &service_end
, 10);
3873 if (service_end
== SSDATA (service
) + SBYTES (service
))
3877 struct servent
*svc_info
3878 = getservbyname (SSDATA (service
),
3879 socktype
== SOCK_DGRAM
? "udp" : "tcp");
3881 port
= ntohs (svc_info
->s_port
);
3886 if (! (0 <= port
&& port
< 1 << 16))
3888 AUTO_STRING (unknown_service
, "Unknown service: %s");
3889 xsignal1 (Qerror
, CALLN (Fformat
, unknown_service
, service
));
3892 #ifndef HAVE_GETADDRINFO
3895 struct hostent
*host_info_ptr
;
3896 unsigned char *addr
;
3899 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3900 as it may `hang' Emacs for a very long time. */
3904 host_info_ptr
= gethostbyname ((const char *) SDATA (host
));
3909 addr
= (unsigned char *) host_info_ptr
->h_addr
;
3910 addrlen
= host_info_ptr
->h_length
;
3913 /* Attempt to interpret host as numeric inet address. This
3914 only works for IPv4 addresses. */
3916 unsigned long numeric_addr
= inet_addr (SSDATA (host
));
3918 if (numeric_addr
== -1)
3919 error ("Unknown host \"%s\"", SDATA (host
));
3921 addr
= (unsigned char *) &numeric_addr
;
3925 ip_addresses
= list1 (conv_numerical_to_lisp (addr
, addrlen
, port
));
3927 #endif /* not HAVE_GETADDRINFO */
3932 buffer
= Fget_buffer_create (buffer
);
3933 proc
= make_process (name
);
3934 p
= XPROCESS (proc
);
3935 pset_childp (p
, contact
);
3936 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3937 pset_type (p
, Qnetwork
);
3939 pset_buffer (p
, buffer
);
3940 pset_sentinel (p
, sentinel
);
3941 pset_filter (p
, filter
);
3942 pset_log (p
, Fplist_get (contact
, QClog
));
3943 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3944 p
->kill_without_query
= 1;
3945 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3946 pset_command (p
, Qt
);
3949 p
->is_non_blocking_client
= 0;
3952 p
->socktype
= socktype
;
3953 p
->ai_protocol
= ai_protocol
;
3954 #ifdef HAVE_GETADDRINFO_A
3955 p
->dns_request
= NULL
;
3958 tem
= Fplist_get (contact
, QCtls_parameters
);
3960 p
->gnutls_boot_parameters
= tem
;
3963 set_network_socket_coding_system (proc
, service
, host
, name
);
3965 unbind_to (count
, Qnil
);
3968 tem
= Fplist_get (contact
, QCserver
);
3971 /* Don't support network sockets when non-blocking mode is
3972 not available, since a blocked Emacs is not useful. */
3974 if (TYPE_RANGED_INTEGERP (int, tem
))
3975 p
->backlog
= XINT (tem
);
3979 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3980 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
3982 #ifndef NON_BLOCKING_CONNECT
3983 error ("Non-blocking connect not supported");
3985 p
->is_non_blocking_client
= 1;
3989 #ifdef HAVE_GETADDRINFO_A
3990 /* If we're doing async address resolution, the list of addresses
3991 here will be nil, so we postpone connecting to the server. */
3992 if (!p
->is_server
&& NILP (ip_addresses
))
3994 p
->dns_request
= dns_request
;
3995 p
->status
= Qconnect
;
3999 connect_network_socket (proc
, ip_addresses
);
4001 #else /* HAVE_GETADDRINFO_A */
4002 connect_network_socket (proc
, ip_addresses
);
4009 #ifdef HAVE_NET_IF_H
4013 network_interface_list (void)
4015 struct ifconf ifconf
;
4016 struct ifreq
*ifreq
;
4018 ptrdiff_t buf_size
= 512;
4023 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4026 count
= SPECPDL_INDEX ();
4027 record_unwind_protect_int (close_file_unwind
, s
);
4031 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4032 ifconf
.ifc_buf
= buf
;
4033 ifconf
.ifc_len
= buf_size
;
4034 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4041 while (ifconf
.ifc_len
== buf_size
);
4043 res
= unbind_to (count
, Qnil
);
4044 ifreq
= ifconf
.ifc_req
;
4045 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4047 struct ifreq
*ifq
= ifreq
;
4048 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4049 #define SIZEOF_IFREQ(sif) \
4050 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4051 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4053 int len
= SIZEOF_IFREQ (ifq
);
4055 int len
= sizeof (*ifreq
);
4057 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4058 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4060 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4063 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4064 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4065 res
= Fcons (Fcons (build_string (namebuf
),
4066 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4067 sizeof (struct sockaddr
))),
4074 #endif /* SIOCGIFCONF */
4076 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4080 const char *flag_sym
;
4083 static const struct ifflag_def ifflag_table
[] = {
4087 #ifdef IFF_BROADCAST
4088 { IFF_BROADCAST
, "broadcast" },
4091 { IFF_DEBUG
, "debug" },
4094 { IFF_LOOPBACK
, "loopback" },
4096 #ifdef IFF_POINTOPOINT
4097 { IFF_POINTOPOINT
, "pointopoint" },
4100 { IFF_RUNNING
, "running" },
4103 { IFF_NOARP
, "noarp" },
4106 { IFF_PROMISC
, "promisc" },
4108 #ifdef IFF_NOTRAILERS
4109 #ifdef NS_IMPL_COCOA
4110 /* Really means smart, notrailers is obsolete. */
4111 { IFF_NOTRAILERS
, "smart" },
4113 { IFF_NOTRAILERS
, "notrailers" },
4117 { IFF_ALLMULTI
, "allmulti" },
4120 { IFF_MASTER
, "master" },
4123 { IFF_SLAVE
, "slave" },
4125 #ifdef IFF_MULTICAST
4126 { IFF_MULTICAST
, "multicast" },
4129 { IFF_PORTSEL
, "portsel" },
4131 #ifdef IFF_AUTOMEDIA
4132 { IFF_AUTOMEDIA
, "automedia" },
4135 { IFF_DYNAMIC
, "dynamic" },
4138 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4141 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4144 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4147 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4150 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4156 network_interface_info (Lisp_Object ifname
)
4159 Lisp_Object res
= Qnil
;
4164 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4165 && defined HAVE_GETIFADDRS && defined LLADDR)
4166 struct ifaddrs
*ifap
;
4169 CHECK_STRING (ifname
);
4171 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4172 error ("interface name too long");
4173 lispstpcpy (rq
.ifr_name
, ifname
);
4175 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4178 count
= SPECPDL_INDEX ();
4179 record_unwind_protect_int (close_file_unwind
, s
);
4182 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4183 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4185 int flags
= rq
.ifr_flags
;
4186 const struct ifflag_def
*fp
;
4189 /* If flags is smaller than int (i.e. short) it may have the high bit set
4190 due to IFF_MULTICAST. In that case, sign extending it into
4192 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4193 flags
= (unsigned short) rq
.ifr_flags
;
4196 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4198 if (flags
& fp
->flag_bit
)
4200 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4201 flags
-= fp
->flag_bit
;
4204 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4208 elt
= Fcons (make_number (fnum
), elt
);
4213 res
= Fcons (elt
, res
);
4216 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4217 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4219 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4220 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4224 for (n
= 0; n
< 6; n
++)
4225 p
->contents
[n
] = make_number (((unsigned char *)
4226 &rq
.ifr_hwaddr
.sa_data
[0])
4228 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4230 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4231 if (getifaddrs (&ifap
) != -1)
4233 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4234 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4237 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4239 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4240 unsigned char linkaddr
[6];
4243 if (it
->ifa_addr
->sa_family
!= AF_LINK
4244 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4245 || sdl
->sdl_alen
!= 6)
4248 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4249 for (n
= 0; n
< 6; n
++)
4250 p
->contents
[n
] = make_number (linkaddr
[n
]);
4252 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4256 #ifdef HAVE_FREEIFADDRS
4260 #endif /* HAVE_GETIFADDRS && LLADDR */
4262 res
= Fcons (elt
, res
);
4265 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4266 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4269 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4270 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4272 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4276 res
= Fcons (elt
, res
);
4279 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4280 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4283 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4286 res
= Fcons (elt
, res
);
4289 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4290 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4293 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4296 res
= Fcons (elt
, res
);
4298 return unbind_to (count
, any
? res
: Qnil
);
4300 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4301 #endif /* defined (HAVE_NET_IF_H) */
4303 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4304 Snetwork_interface_list
, 0, 0, 0,
4305 doc
: /* Return an alist of all network interfaces and their network address.
4306 Each element is a cons, the car of which is a string containing the
4307 interface name, and the cdr is the network address in internal
4308 format; see the description of ADDRESS in `make-network-process'.
4310 If the information is not available, return nil. */)
4313 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4314 return network_interface_list ();
4320 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4321 Snetwork_interface_info
, 1, 1, 0,
4322 doc
: /* Return information about network interface named IFNAME.
4323 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4324 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4325 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4326 FLAGS is the current flags of the interface.
4328 Data that is unavailable is returned as nil. */)
4329 (Lisp_Object ifname
)
4331 #if ((defined HAVE_NET_IF_H \
4332 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4333 || defined SIOCGIFFLAGS)) \
4334 || defined WINDOWSNT)
4335 return network_interface_info (ifname
);
4341 /* If program file NAME starts with /: for quoting a magic
4342 name, remove that, preserving the multibyteness of NAME. */
4345 remove_slash_colon (Lisp_Object name
)
4348 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
4349 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
4350 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
4354 /* Turn off input and output for process PROC. */
4357 deactivate_process (Lisp_Object proc
)
4360 struct Lisp_Process
*p
= XPROCESS (proc
);
4364 /* Delete GnuTLS structures in PROC, if any. */
4365 emacs_gnutls_deinit (proc
);
4366 #endif /* HAVE_GNUTLS */
4368 if (p
->read_output_delay
> 0)
4370 if (--process_output_delay_count
< 0)
4371 process_output_delay_count
= 0;
4372 p
->read_output_delay
= 0;
4373 p
->read_output_skip
= 0;
4376 /* Beware SIGCHLD hereabouts. */
4378 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4379 close_process_fd (&p
->open_fd
[i
]);
4381 inchannel
= p
->infd
;
4386 #ifdef DATAGRAM_SOCKETS
4387 if (DATAGRAM_CHAN_P (inchannel
))
4389 xfree (datagram_address
[inchannel
].sa
);
4390 datagram_address
[inchannel
].sa
= 0;
4391 datagram_address
[inchannel
].len
= 0;
4394 chan_process
[inchannel
] = Qnil
;
4395 FD_CLR (inchannel
, &input_wait_mask
);
4396 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4397 #ifdef NON_BLOCKING_CONNECT
4398 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4400 FD_CLR (inchannel
, &connect_wait_mask
);
4401 FD_CLR (inchannel
, &write_mask
);
4402 if (--num_pending_connects
< 0)
4406 if (inchannel
== max_process_desc
)
4408 /* We just closed the highest-numbered process input descriptor,
4409 so recompute the highest-numbered one now. */
4413 while (0 <= i
&& NILP (chan_process
[i
]));
4415 max_process_desc
= i
;
4421 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4423 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4424 It is given to their filter functions.
4425 Optional argument PROCESS means do not return until output has been
4426 received from PROCESS.
4428 Optional second argument SECONDS and third argument MILLISEC
4429 specify a timeout; return after that much time even if there is
4430 no subprocess output. If SECONDS is a floating point number,
4431 it specifies a fractional number of seconds to wait.
4432 The MILLISEC argument is obsolete and should be avoided.
4434 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4435 from PROCESS only, suspending reading output from other processes.
4436 If JUST-THIS-ONE is an integer, don't run any timers either.
4437 Return non-nil if we received any output from PROCESS (or, if PROCESS
4438 is nil, from any process) before the timeout expired. */)
4439 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4444 if (! NILP (process
))
4445 CHECK_PROCESS (process
);
4447 just_this_one
= Qnil
;
4449 if (!NILP (millisec
))
4450 { /* Obsolete calling convention using integers rather than floats. */
4451 CHECK_NUMBER (millisec
);
4453 seconds
= make_float (XINT (millisec
) / 1000.0);
4456 CHECK_NUMBER (seconds
);
4457 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4464 if (!NILP (seconds
))
4466 if (INTEGERP (seconds
))
4468 if (XINT (seconds
) > 0)
4470 secs
= XINT (seconds
);
4474 else if (FLOATP (seconds
))
4476 if (XFLOAT_DATA (seconds
) > 0)
4478 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4479 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4484 wrong_type_argument (Qnumberp
, seconds
);
4486 else if (! NILP (process
))
4490 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4492 !NILP (process
) ? XPROCESS (process
) : NULL
,
4493 (NILP (just_this_one
) ? 0
4494 : !INTEGERP (just_this_one
) ? 1 : -1))
4499 /* Accept a connection for server process SERVER on CHANNEL. */
4501 static EMACS_INT connect_counter
= 0;
4504 server_accept_connection (Lisp_Object server
, int channel
)
4506 Lisp_Object proc
, caller
, name
, buffer
;
4507 Lisp_Object contact
, host
, service
;
4508 struct Lisp_Process
*ps
= XPROCESS (server
);
4509 struct Lisp_Process
*p
;
4513 struct sockaddr_in in
;
4515 struct sockaddr_in6 in6
;
4517 #ifdef HAVE_LOCAL_SOCKETS
4518 struct sockaddr_un un
;
4521 socklen_t len
= sizeof saddr
;
4524 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4533 if (code
== EWOULDBLOCK
)
4537 if (!NILP (ps
->log
))
4538 call3 (ps
->log
, server
, Qnil
,
4539 concat3 (build_string ("accept failed with code"),
4540 Fnumber_to_string (make_number (code
)),
4541 build_string ("\n")));
4545 count
= SPECPDL_INDEX ();
4546 record_unwind_protect_int (close_file_unwind
, s
);
4550 /* Setup a new process to handle the connection. */
4552 /* Generate a unique identification of the caller, and build contact
4553 information for this process. */
4556 switch (saddr
.sa
.sa_family
)
4560 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4562 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4563 host
= CALLN (Fformat
, ipv4_format
,
4564 make_number (ip
[0]), make_number (ip
[1]),
4565 make_number (ip
[2]), make_number (ip
[3]));
4566 service
= make_number (ntohs (saddr
.in
.sin_port
));
4567 AUTO_STRING (caller_format
, " <%s:%d>");
4568 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4575 Lisp_Object args
[9];
4576 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4579 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4580 args
[0] = ipv6_format
;
4581 for (i
= 0; i
< 8; i
++)
4582 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4583 host
= CALLMANY (Fformat
, args
);
4584 service
= make_number (ntohs (saddr
.in
.sin_port
));
4585 AUTO_STRING (caller_format
, " <[%s]:%d>");
4586 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4591 #ifdef HAVE_LOCAL_SOCKETS
4595 caller
= Fnumber_to_string (make_number (connect_counter
));
4596 AUTO_STRING (space_less_than
, " <");
4597 AUTO_STRING (greater_than
, ">");
4598 caller
= concat3 (space_less_than
, caller
, greater_than
);
4602 /* Create a new buffer name for this process if it doesn't have a
4603 filter. The new buffer name is based on the buffer name or
4604 process name of the server process concatenated with the caller
4607 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4608 || EQ (ps
->filter
, Qt
)))
4612 buffer
= ps
->buffer
;
4614 buffer
= Fbuffer_name (buffer
);
4619 buffer
= concat2 (buffer
, caller
);
4620 buffer
= Fget_buffer_create (buffer
);
4624 /* Generate a unique name for the new server process. Combine the
4625 server process name with the caller identification. */
4627 name
= concat2 (ps
->name
, caller
);
4628 proc
= make_process (name
);
4630 chan_process
[s
] = proc
;
4632 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4634 p
= XPROCESS (proc
);
4636 /* Build new contact information for this setup. */
4637 contact
= Fcopy_sequence (ps
->childp
);
4638 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4639 contact
= Fplist_put (contact
, QChost
, host
);
4640 if (!NILP (service
))
4641 contact
= Fplist_put (contact
, QCservice
, service
);
4642 contact
= Fplist_put (contact
, QCremote
,
4643 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4644 #ifdef HAVE_GETSOCKNAME
4646 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4647 contact
= Fplist_put (contact
, QClocal
,
4648 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4651 pset_childp (p
, contact
);
4652 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4653 pset_type (p
, Qnetwork
);
4655 pset_buffer (p
, buffer
);
4656 pset_sentinel (p
, ps
->sentinel
);
4657 pset_filter (p
, ps
->filter
);
4658 pset_command (p
, Qnil
);
4661 /* Discard the unwind protect for closing S. */
4662 specpdl_ptr
= specpdl
+ count
;
4664 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4667 pset_status (p
, Qrun
);
4669 /* Client processes for accepted connections are not stopped initially. */
4670 if (!EQ (p
->filter
, Qt
))
4672 FD_SET (s
, &input_wait_mask
);
4673 FD_SET (s
, &non_keyboard_wait_mask
);
4676 if (s
> max_process_desc
)
4677 max_process_desc
= s
;
4679 /* Setup coding system for new process based on server process.
4680 This seems to be the proper thing to do, as the coding system
4681 of the new process should reflect the settings at the time the
4682 server socket was opened; not the current settings. */
4684 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4685 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4686 setup_process_coding_systems (proc
);
4688 pset_decoding_buf (p
, empty_unibyte_string
);
4689 p
->decoding_carryover
= 0;
4690 pset_encoding_buf (p
, empty_unibyte_string
);
4692 p
->inherit_coding_system_flag
4693 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4695 AUTO_STRING (dash
, "-");
4696 AUTO_STRING (nl
, "\n");
4697 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4699 if (!NILP (ps
->log
))
4701 AUTO_STRING (accept_from
, "accept from ");
4702 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4705 AUTO_STRING (open_from
, "open from ");
4706 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4709 #ifdef HAVE_GETADDRINFO_A
4711 check_for_dns (Lisp_Object proc
)
4713 struct Lisp_Process
*p
= XPROCESS (proc
);
4714 Lisp_Object ip_addresses
= Qnil
;
4718 if (! p
->dns_request
)
4721 ret
= gai_error (p
->dns_request
);
4722 if (ret
== EAI_INPROGRESS
)
4725 /* We got a response. */
4728 struct addrinfo
*res
;
4730 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4732 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4733 (res
->ai_addr
, res
->ai_addrlen
),
4737 ip_addresses
= Fnreverse (ip_addresses
);
4739 /* The DNS lookup failed. */
4740 else if (EQ (p
->status
, Qconnect
))
4742 deactivate_process (proc
);
4743 pset_status (p
, (list2
4745 concat3 (build_string ("Name lookup of "),
4746 build_string (p
->dns_request
->ar_name
),
4747 build_string (" failed")))));
4750 free_dns_request (proc
);
4752 /* This process should not already be connected (or killed). */
4753 if (!EQ (p
->status
, Qconnect
))
4756 return ip_addresses
;
4759 #endif /* HAVE_GETADDRINFO_A */
4762 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4764 while (XPROCESS (process
)->infd
< 0
4765 && EQ (XPROCESS (process
)->status
, Qconnect
))
4767 add_to_log ("Waiting for socket from %s...", build_string (name
));
4768 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4773 wait_while_connecting (Lisp_Object process
)
4775 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4777 add_to_log ("Waiting for connection...");
4778 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4783 wait_for_tls_negotiation (Lisp_Object process
)
4786 while (XPROCESS (process
)->gnutls_p
4787 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4789 add_to_log ("Waiting for TLS...");
4790 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4795 /* This variable is different from waiting_for_input in keyboard.c.
4796 It is used to communicate to a lisp process-filter/sentinel (via the
4797 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4798 for user-input when that process-filter was called.
4799 waiting_for_input cannot be used as that is by definition 0 when
4800 lisp code is being evalled.
4801 This is also used in record_asynch_buffer_change.
4802 For that purpose, this must be 0
4803 when not inside wait_reading_process_output. */
4804 static int waiting_for_user_input_p
;
4807 wait_reading_process_output_unwind (int data
)
4809 waiting_for_user_input_p
= data
;
4812 /* This is here so breakpoints can be put on it. */
4814 wait_reading_process_output_1 (void)
4818 /* Read and dispose of subprocess output while waiting for timeout to
4819 elapse and/or keyboard input to be available.
4823 If negative, gobble data immediately available but don't wait for any.
4826 an additional duration to wait, measured in nanoseconds
4827 If TIME_LIMIT is zero, then:
4828 If NSECS == 0, there is no limit.
4829 If NSECS > 0, the timeout consists of NSECS only.
4830 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4833 0 to ignore keyboard input, or
4834 1 to return when input is available, or
4835 -1 meaning caller will actually read the input, so don't throw to
4836 the quit handler, or
4838 DO_DISPLAY means redisplay should be done to show subprocess
4839 output that arrives.
4841 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4842 (and gobble terminal input into the buffer if any arrives).
4844 If WAIT_PROC is specified, wait until something arrives from that
4847 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4848 (suspending output from other processes). A negative value
4849 means don't run any timers either.
4851 Return positive if we received input from WAIT_PROC (or from any
4852 process if WAIT_PROC is null), zero if we attempted to receive
4853 input but got none, and negative if we didn't even try. */
4856 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4858 Lisp_Object wait_for_cell
,
4859 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4869 struct timespec timeout
, end_time
, timer_delay
;
4870 struct timespec got_output_end_time
= invalid_timespec ();
4871 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4872 int got_some_output
= -1;
4873 ptrdiff_t count
= SPECPDL_INDEX ();
4875 /* Close to the current time if known, an invalid timespec otherwise. */
4876 struct timespec now
= invalid_timespec ();
4878 FD_ZERO (&Available
);
4881 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4882 && !(CONSP (wait_proc
->status
)
4883 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4884 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4886 record_unwind_protect_int (wait_reading_process_output_unwind
,
4887 waiting_for_user_input_p
);
4888 waiting_for_user_input_p
= read_kbd
;
4890 if (TYPE_MAXIMUM (time_t) < time_limit
)
4891 time_limit
= TYPE_MAXIMUM (time_t);
4893 if (time_limit
< 0 || nsecs
< 0)
4895 else if (time_limit
> 0 || nsecs
> 0)
4898 now
= current_timespec ();
4899 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4906 bool process_skipped
= false;
4908 /* If calling from keyboard input, do not quit
4909 since we want to return C-g as an input character.
4910 Otherwise, do pending quit if requested. */
4913 else if (pending_signals
)
4914 process_pending_signals ();
4916 /* Exit now if the cell we're waiting for became non-nil. */
4917 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4920 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4922 Lisp_Object process_list_head
, aproc
;
4923 struct Lisp_Process
*p
;
4925 FOR_EACH_PROCESS(process_list_head
, aproc
)
4927 p
= XPROCESS (aproc
);
4929 if (! wait_proc
|| p
== wait_proc
)
4931 #ifdef HAVE_GETADDRINFO_A
4932 /* Check for pending DNS requests. */
4935 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4936 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4937 connect_network_socket (aproc
, ip_addresses
);
4941 /* Continue TLS negotiation. */
4942 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4943 && p
->is_non_blocking_client
)
4945 gnutls_try_handshake (p
);
4946 p
->gnutls_handshakes_tried
++;
4948 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4950 gnutls_verify_boot (aproc
, Qnil
);
4951 finish_after_tls_connection (aproc
);
4953 else if (p
->gnutls_handshakes_tried
4954 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4956 deactivate_process (aproc
);
4957 pset_status (p
, list2 (Qfailed
,
4958 build_string ("TLS negotiation failed")));
4965 #endif /* GETADDRINFO_A or GNUTLS */
4967 /* Compute time from now till when time limit is up. */
4968 /* Exit if already run out. */
4969 if (wait
== TIMEOUT
)
4971 if (!timespec_valid_p (now
))
4972 now
= current_timespec ();
4973 if (timespec_cmp (end_time
, now
) <= 0)
4975 timeout
= timespec_sub (end_time
, now
);
4978 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4980 /* Normally we run timers here.
4981 But not if wait_for_cell; in those cases,
4982 the wait is supposed to be short,
4983 and those callers cannot handle running arbitrary Lisp code here. */
4984 if (NILP (wait_for_cell
)
4985 && just_wait_proc
>= 0)
4989 unsigned old_timers_run
= timers_run
;
4990 struct buffer
*old_buffer
= current_buffer
;
4991 Lisp_Object old_window
= selected_window
;
4993 timer_delay
= timer_check ();
4995 /* If a timer has run, this might have changed buffers
4996 an alike. Make read_key_sequence aware of that. */
4997 if (timers_run
!= old_timers_run
4998 && (old_buffer
!= current_buffer
4999 || !EQ (old_window
, selected_window
))
5000 && waiting_for_user_input_p
== -1)
5001 record_asynch_buffer_change ();
5003 if (timers_run
!= old_timers_run
&& do_display
)
5004 /* We must retry, since a timer may have requeued itself
5005 and that could alter the time_delay. */
5006 redisplay_preserve_echo_area (9);
5010 while (!detect_input_pending ());
5012 /* If there is unread keyboard input, also return. */
5014 && requeued_events_pending_p ())
5017 /* This is so a breakpoint can be put here. */
5018 if (!timespec_valid_p (timer_delay
))
5019 wait_reading_process_output_1 ();
5022 /* Cause C-g and alarm signals to take immediate action,
5023 and cause input available signals to zero out timeout.
5025 It is important that we do this before checking for process
5026 activity. If we get a SIGCHLD after the explicit checks for
5027 process activity, timeout is the only way we will know. */
5029 set_waiting_for_input (&timeout
);
5031 /* If status of something has changed, and no input is
5032 available, notify the user of the change right away. After
5033 this explicit check, we'll let the SIGCHLD handler zap
5034 timeout to get our attention. */
5035 if (update_tick
!= process_tick
)
5040 if (kbd_on_hold_p ())
5043 Atemp
= input_wait_mask
;
5046 timeout
= make_timespec (0, 0);
5047 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
5049 #ifdef NON_BLOCKING_CONNECT
5050 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5054 NULL
, &timeout
, NULL
)
5057 /* It's okay for us to do this and then continue with
5058 the loop, since timeout has already been zeroed out. */
5059 clear_waiting_for_input ();
5060 got_some_output
= status_notify (NULL
, wait_proc
);
5061 if (do_display
) redisplay_preserve_echo_area (13);
5065 /* Don't wait for output from a non-running process. Just
5066 read whatever data has already been received. */
5067 if (wait_proc
&& wait_proc
->raw_status_new
)
5068 update_status (wait_proc
);
5070 && ! EQ (wait_proc
->status
, Qrun
)
5071 && ! EQ (wait_proc
->status
, Qconnect
))
5073 bool read_some_bytes
= false;
5075 clear_waiting_for_input ();
5077 /* If data can be read from the process, do so until exhausted. */
5078 if (wait_proc
->infd
>= 0)
5080 XSETPROCESS (proc
, wait_proc
);
5084 int nread
= read_process_output (proc
, wait_proc
->infd
);
5087 if (errno
== EIO
|| errno
== EAGAIN
)
5090 if (errno
== EWOULDBLOCK
)
5096 if (got_some_output
< nread
)
5097 got_some_output
= nread
;
5100 read_some_bytes
= true;
5105 if (read_some_bytes
&& do_display
)
5106 redisplay_preserve_echo_area (10);
5111 /* Wait till there is something to do. */
5113 if (wait_proc
&& just_wait_proc
)
5115 if (wait_proc
->infd
< 0) /* Terminated. */
5117 FD_SET (wait_proc
->infd
, &Available
);
5121 else if (!NILP (wait_for_cell
))
5123 Available
= non_process_wait_mask
;
5130 Available
= non_keyboard_wait_mask
;
5132 Available
= input_wait_mask
;
5133 Writeok
= write_mask
;
5134 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5138 /* If frame size has changed or the window is newly mapped,
5139 redisplay now, before we start to wait. There is a race
5140 condition here; if a SIGIO arrives between now and the select
5141 and indicates that a frame is trashed, the select may block
5142 displaying a trashed screen. */
5143 if (frame_garbaged
&& do_display
)
5145 clear_waiting_for_input ();
5146 redisplay_preserve_echo_area (11);
5148 set_waiting_for_input (&timeout
);
5151 /* Skip the `select' call if input is available and we're
5152 waiting for keyboard input or a cell change (which can be
5153 triggered by processing X events). In the latter case, set
5154 nfds to 1 to avoid breaking the loop. */
5156 if ((read_kbd
|| !NILP (wait_for_cell
))
5157 && detect_input_pending ())
5159 nfds
= read_kbd
? 0 : 1;
5161 FD_ZERO (&Available
);
5165 /* Set the timeout for adaptive read buffering if any
5166 process has non-zero read_output_skip and non-zero
5167 read_output_delay, and we are not reading output for a
5168 specific process. It is not executed if
5169 Vprocess_adaptive_read_buffering is nil. */
5170 if (process_output_skip
&& check_delay
> 0)
5172 int adaptive_nsecs
= timeout
.tv_nsec
;
5173 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5174 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5175 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5177 proc
= chan_process
[channel
];
5180 /* Find minimum non-zero read_output_delay among the
5181 processes with non-zero read_output_skip. */
5182 if (XPROCESS (proc
)->read_output_delay
> 0)
5185 if (!XPROCESS (proc
)->read_output_skip
)
5187 FD_CLR (channel
, &Available
);
5188 process_skipped
= true;
5189 XPROCESS (proc
)->read_output_skip
= 0;
5190 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5191 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5194 timeout
= make_timespec (0, adaptive_nsecs
);
5195 process_output_skip
= 0;
5198 /* If we've got some output and haven't limited our timeout
5199 with adaptive read buffering, limit it. */
5200 if (got_some_output
> 0 && !process_skipped
5202 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5203 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5206 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5207 && timespec_valid_p (timer_delay
)
5208 && timespec_cmp (timer_delay
, timeout
) < 0)
5210 if (!timespec_valid_p (now
))
5211 now
= current_timespec ();
5212 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5213 if (!timespec_valid_p (got_output_end_time
)
5214 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5215 got_output_end_time
= timeout_abs
;
5216 timeout
= timer_delay
;
5219 got_output_end_time
= invalid_timespec ();
5221 /* NOW can become inaccurate if time can pass during pselect. */
5222 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5223 now
= invalid_timespec ();
5225 #if defined (HAVE_NS)
5227 #elif defined (HAVE_GLIB)
5232 (max (max_process_desc
, max_input_desc
) + 1,
5234 (check_write
? &Writeok
: 0),
5235 NULL
, &timeout
, NULL
);
5238 /* GnuTLS buffers data internally. In lowat mode it leaves
5239 some data in the TCP buffers so that select works, but
5240 with custom pull/push functions we need to check if some
5241 data is available in the buffers manually. */
5244 fd_set tls_available
;
5247 FD_ZERO (&tls_available
);
5250 /* We're not waiting on a specific process, so loop
5251 through all the channels and check for data.
5252 This is a workaround needed for some versions of
5253 the gnutls library -- 2.12.14 has been confirmed
5255 http://comments.gmane.org/gmane.emacs.devel/145074 */
5256 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5257 if (! NILP (chan_process
[channel
]))
5259 struct Lisp_Process
*p
=
5260 XPROCESS (chan_process
[channel
]);
5261 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5262 && ((emacs_gnutls_record_check_pending
5267 eassert (p
->infd
== channel
);
5268 FD_SET (p
->infd
, &tls_available
);
5275 /* Check this specific channel. */
5276 if (wait_proc
->gnutls_p
/* Check for valid process. */
5277 && wait_proc
->gnutls_state
5278 /* Do we have pending data? */
5279 && ((emacs_gnutls_record_check_pending
5280 (wait_proc
->gnutls_state
))
5284 eassert (0 <= wait_proc
->infd
);
5285 /* Set to Available. */
5286 FD_SET (wait_proc
->infd
, &tls_available
);
5291 Available
= tls_available
;
5298 /* Make C-g and alarm signals set flags again. */
5299 clear_waiting_for_input ();
5301 /* If we woke up due to SIGWINCH, actually change size now. */
5302 do_pending_window_change (0);
5306 /* Exit the main loop if we've passed the requested timeout,
5307 or aren't skipping processes and got some output and
5308 haven't lowered our timeout due to timers or SIGIO and
5309 have waited a long amount of time due to repeated
5313 struct timespec cmp_time
5316 : (!process_skipped
&& got_some_output
> 0
5317 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5318 ? got_output_end_time
5319 : invalid_timespec ());
5320 if (timespec_valid_p (cmp_time
))
5322 now
= current_timespec ();
5323 if (timespec_cmp (cmp_time
, now
) <= 0)
5330 if (xerrno
== EINTR
)
5332 else if (xerrno
== EBADF
)
5335 report_file_errno ("Failed select", Qnil
, xerrno
);
5338 /* Check for keyboard input. */
5339 /* If there is any, return immediately
5340 to give it higher priority than subprocesses. */
5344 unsigned old_timers_run
= timers_run
;
5345 struct buffer
*old_buffer
= current_buffer
;
5346 Lisp_Object old_window
= selected_window
;
5349 if (detect_input_pending_run_timers (do_display
))
5351 swallow_events (do_display
);
5352 if (detect_input_pending_run_timers (do_display
))
5356 /* If a timer has run, this might have changed buffers
5357 an alike. Make read_key_sequence aware of that. */
5358 if (timers_run
!= old_timers_run
5359 && waiting_for_user_input_p
== -1
5360 && (old_buffer
!= current_buffer
5361 || !EQ (old_window
, selected_window
)))
5362 record_asynch_buffer_change ();
5368 /* If there is unread keyboard input, also return. */
5370 && requeued_events_pending_p ())
5373 /* If we are not checking for keyboard input now,
5374 do process events (but don't run any timers).
5375 This is so that X events will be processed.
5376 Otherwise they may have to wait until polling takes place.
5377 That would causes delays in pasting selections, for example.
5379 (We used to do this only if wait_for_cell.) */
5380 if (read_kbd
== 0 && detect_input_pending ())
5382 swallow_events (do_display
);
5383 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5384 if (detect_input_pending ())
5389 /* Exit now if the cell we're waiting for became non-nil. */
5390 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5394 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5395 go read it. This can happen with X on BSD after logging out.
5396 In that case, there really is no input and no SIGIO,
5397 but select says there is input. */
5399 if (read_kbd
&& interrupt_input
5400 && keyboard_bit_set (&Available
) && ! noninteractive
)
5401 handle_input_available_signal (SIGIO
);
5404 /* If checking input just got us a size-change event from X,
5405 obey it now if we should. */
5406 if (read_kbd
|| ! NILP (wait_for_cell
))
5407 do_pending_window_change (0);
5409 /* Check for data from a process. */
5410 if (no_avail
|| nfds
== 0)
5413 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5415 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5417 && ((d
->condition
& FOR_READ
5418 && FD_ISSET (channel
, &Available
))
5419 || (d
->condition
& FOR_WRITE
5420 && FD_ISSET (channel
, &write_mask
))))
5421 d
->func (channel
, d
->data
);
5424 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5426 if (FD_ISSET (channel
, &Available
)
5427 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5428 && !FD_ISSET (channel
, &non_process_wait_mask
))
5432 /* If waiting for this channel, arrange to return as
5433 soon as no more input to be processed. No more
5435 proc
= chan_process
[channel
];
5439 /* If this is a server stream socket, accept connection. */
5440 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5442 server_accept_connection (proc
, channel
);
5446 /* Read data from the process, starting with our
5447 buffered-ahead character if we have one. */
5449 nread
= read_process_output (proc
, channel
);
5450 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5451 && got_some_output
< nread
)
5452 got_some_output
= nread
;
5455 /* Vacuum up any leftovers without waiting. */
5456 if (wait_proc
== XPROCESS (proc
))
5458 /* Since read_process_output can run a filter,
5459 which can call accept-process-output,
5460 don't try to read from any other processes
5461 before doing the select again. */
5462 FD_ZERO (&Available
);
5465 redisplay_preserve_echo_area (12);
5468 else if (nread
== -1 && errno
== EWOULDBLOCK
)
5471 else if (nread
== -1 && errno
== EAGAIN
)
5474 /* FIXME: Is this special case still needed? */
5475 /* Note that we cannot distinguish between no input
5476 available now and a closed pipe.
5477 With luck, a closed pipe will be accompanied by
5478 subprocess termination and SIGCHLD. */
5479 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5480 && !PIPECONN_P (proc
))
5484 /* On some OSs with ptys, when the process on one end of
5485 a pty exits, the other end gets an error reading with
5486 errno = EIO instead of getting an EOF (0 bytes read).
5487 Therefore, if we get an error reading and errno =
5488 EIO, just continue, because the child process has
5489 exited and should clean itself up soon (e.g. when we
5491 else if (nread
== -1 && errno
== EIO
)
5493 struct Lisp_Process
*p
= XPROCESS (proc
);
5495 /* Clear the descriptor now, so we only raise the
5497 FD_CLR (channel
, &input_wait_mask
);
5498 FD_CLR (channel
, &non_keyboard_wait_mask
);
5502 /* If the EIO occurs on a pty, the SIGCHLD handler's
5503 waitpid call will not find the process object to
5504 delete. Do it here. */
5505 p
->tick
= ++process_tick
;
5506 pset_status (p
, Qfailed
);
5509 #endif /* HAVE_PTYS */
5510 /* If we can detect process termination, don't consider the
5511 process gone just because its pipe is closed. */
5512 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5513 && !PIPECONN_P (proc
))
5515 else if (nread
== 0 && PIPECONN_P (proc
))
5517 /* Preserve status of processes already terminated. */
5518 XPROCESS (proc
)->tick
= ++process_tick
;
5519 deactivate_process (proc
);
5520 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5521 pset_status (XPROCESS (proc
),
5522 list2 (Qexit
, make_number (0)));
5526 /* Preserve status of processes already terminated. */
5527 XPROCESS (proc
)->tick
= ++process_tick
;
5528 deactivate_process (proc
);
5529 if (XPROCESS (proc
)->raw_status_new
)
5530 update_status (XPROCESS (proc
));
5531 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5532 pset_status (XPROCESS (proc
),
5533 list2 (Qexit
, make_number (256)));
5536 #ifdef NON_BLOCKING_CONNECT
5537 if (FD_ISSET (channel
, &Writeok
)
5538 && FD_ISSET (channel
, &connect_wait_mask
))
5540 struct Lisp_Process
*p
;
5542 FD_CLR (channel
, &connect_wait_mask
);
5543 FD_CLR (channel
, &write_mask
);
5544 if (--num_pending_connects
< 0)
5547 proc
= chan_process
[channel
];
5551 p
= XPROCESS (proc
);
5554 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5555 So only use it on systems where it is known to work. */
5557 socklen_t xlen
= sizeof (xerrno
);
5558 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5563 struct sockaddr pname
;
5564 socklen_t pnamelen
= sizeof (pname
);
5566 /* If connection failed, getpeername will fail. */
5568 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5570 /* Obtain connect failure code through error slippage. */
5573 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5580 p
->tick
= ++process_tick
;
5581 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5582 deactivate_process (proc
);
5587 /* If we have an incompletely set up TLS connection,
5588 then defer the sentinel signalling until
5590 if (NILP (p
->gnutls_boot_parameters
)
5594 pset_status (p
, Qrun
);
5595 /* Execute the sentinel here. If we had relied on
5596 status_notify to do it later, it will read input
5597 from the process before calling the sentinel. */
5598 exec_sentinel (proc
, build_string ("open\n"));
5601 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5602 && !EQ (p
->command
, Qt
))
5604 FD_SET (p
->infd
, &input_wait_mask
);
5605 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5609 #endif /* NON_BLOCKING_CONNECT */
5610 } /* End for each file descriptor. */
5611 } /* End while exit conditions not met. */
5613 unbind_to (count
, Qnil
);
5615 /* If calling from keyboard input, do not quit
5616 since we want to return C-g as an input character.
5617 Otherwise, do pending quit if requested. */
5620 /* Prevent input_pending from remaining set if we quit. */
5621 clear_input_pending ();
5625 return got_some_output
;
5628 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5631 read_process_output_call (Lisp_Object fun_and_args
)
5633 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5637 read_process_output_error_handler (Lisp_Object error_val
)
5639 cmd_error_internal (error_val
, "error in process filter: ");
5641 update_echo_area ();
5642 Fsleep_for (make_number (2), Qnil
);
5647 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5649 struct coding_system
*coding
);
5651 /* Read pending output from the process channel,
5652 starting with our buffered-ahead character if we have one.
5653 Yield number of decoded characters read.
5655 This function reads at most 4096 characters.
5656 If you want to read all available subprocess output,
5657 you must call it repeatedly until it returns zero.
5659 The characters read are decoded according to PROC's coding-system
5663 read_process_output (Lisp_Object proc
, int channel
)
5666 struct Lisp_Process
*p
= XPROCESS (proc
);
5667 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5668 int carryover
= p
->decoding_carryover
;
5669 enum { readmax
= 4096 };
5670 ptrdiff_t count
= SPECPDL_INDEX ();
5671 Lisp_Object odeactivate
;
5672 char chars
[sizeof coding
->carryover
+ readmax
];
5675 /* See the comment above. */
5676 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5678 #ifdef DATAGRAM_SOCKETS
5679 /* We have a working select, so proc_buffered_char is always -1. */
5680 if (DATAGRAM_CHAN_P (channel
))
5682 socklen_t len
= datagram_address
[channel
].len
;
5683 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5684 0, datagram_address
[channel
].sa
, &len
);
5689 bool buffered
= proc_buffered_char
[channel
] >= 0;
5692 chars
[carryover
] = proc_buffered_char
[channel
];
5693 proc_buffered_char
[channel
] = -1;
5696 if (p
->gnutls_p
&& p
->gnutls_state
)
5697 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5698 readmax
- buffered
);
5701 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5702 readmax
- buffered
);
5703 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5705 int delay
= p
->read_output_delay
;
5708 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5711 process_output_delay_count
++;
5712 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5715 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5717 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5719 process_output_delay_count
--;
5721 p
->read_output_delay
= delay
;
5724 p
->read_output_skip
= 1;
5725 process_output_skip
= 1;
5729 nbytes
+= buffered
&& nbytes
<= 0;
5732 p
->decoding_carryover
= 0;
5734 /* At this point, NBYTES holds number of bytes just received
5735 (including the one in proc_buffered_char[channel]). */
5738 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5740 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5743 /* Now set NBYTES how many bytes we must decode. */
5744 nbytes
+= carryover
;
5746 odeactivate
= Vdeactivate_mark
;
5747 /* There's no good reason to let process filters change the current
5748 buffer, and many callers of accept-process-output, sit-for, and
5749 friends don't expect current-buffer to be changed from under them. */
5750 record_unwind_current_buffer ();
5752 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5754 /* Handling the process output should not deactivate the mark. */
5755 Vdeactivate_mark
= odeactivate
;
5757 unbind_to (count
, Qnil
);
5762 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5764 struct coding_system
*coding
)
5766 Lisp_Object outstream
= p
->filter
;
5768 bool outer_running_asynch_code
= running_asynch_code
;
5769 int waiting
= waiting_for_user_input_p
;
5772 Lisp_Object obuffer
, okeymap
;
5773 XSETBUFFER (obuffer
, current_buffer
);
5774 okeymap
= BVAR (current_buffer
, keymap
);
5777 /* We inhibit quit here instead of just catching it so that
5778 hitting ^G when a filter happens to be running won't screw
5780 specbind (Qinhibit_quit
, Qt
);
5781 specbind (Qlast_nonmenu_event
, Qt
);
5783 /* In case we get recursively called,
5784 and we already saved the match data nonrecursively,
5785 save the same match data in safely recursive fashion. */
5786 if (outer_running_asynch_code
)
5789 /* Don't clobber the CURRENT match data, either! */
5790 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5791 restore_search_regs ();
5792 record_unwind_save_match_data ();
5793 Fset_match_data (tem
, Qt
);
5796 /* For speed, if a search happens within this code,
5797 save the match data in a special nonrecursive fashion. */
5798 running_asynch_code
= 1;
5800 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5801 text
= coding
->dst_object
;
5802 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5803 /* A new coding system might be found. */
5804 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5806 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5808 /* Don't call setup_coding_system for
5809 proc_decode_coding_system[channel] here. It is done in
5810 detect_coding called via decode_coding above. */
5812 /* If a coding system for encoding is not yet decided, we set
5813 it as the same as coding-system for decoding.
5815 But, before doing that we must check if
5816 proc_encode_coding_system[p->outfd] surely points to a
5817 valid memory because p->outfd will be changed once EOF is
5818 sent to the process. */
5819 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5820 && proc_encode_coding_system
[p
->outfd
])
5822 pset_encode_coding_system
5823 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5824 setup_coding_system (p
->encode_coding_system
,
5825 proc_encode_coding_system
[p
->outfd
]);
5829 if (coding
->carryover_bytes
> 0)
5831 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5832 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5833 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5834 coding
->carryover_bytes
);
5835 p
->decoding_carryover
= coding
->carryover_bytes
;
5837 if (SBYTES (text
) > 0)
5838 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5839 sometimes it's simply wrong to wrap (e.g. when called from
5840 accept-process-output). */
5841 internal_condition_case_1 (read_process_output_call
,
5842 list3 (outstream
, make_lisp_proc (p
), text
),
5843 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5844 read_process_output_error_handler
);
5846 /* If we saved the match data nonrecursively, restore it now. */
5847 restore_search_regs ();
5848 running_asynch_code
= outer_running_asynch_code
;
5850 /* Restore waiting_for_user_input_p as it was
5851 when we were called, in case the filter clobbered it. */
5852 waiting_for_user_input_p
= waiting
;
5854 #if 0 /* Call record_asynch_buffer_change unconditionally,
5855 because we might have changed minor modes or other things
5856 that affect key bindings. */
5857 if (! EQ (Fcurrent_buffer (), obuffer
)
5858 || ! EQ (current_buffer
->keymap
, okeymap
))
5860 /* But do it only if the caller is actually going to read events.
5861 Otherwise there's no need to make him wake up, and it could
5862 cause trouble (for example it would make sit_for return). */
5863 if (waiting_for_user_input_p
== -1)
5864 record_asynch_buffer_change ();
5867 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5868 Sinternal_default_process_filter
, 2, 2, 0,
5869 doc
: /* Function used as default process filter.
5870 This inserts the process's output into its buffer, if there is one.
5871 Otherwise it discards the output. */)
5872 (Lisp_Object proc
, Lisp_Object text
)
5874 struct Lisp_Process
*p
;
5877 CHECK_PROCESS (proc
);
5878 p
= XPROCESS (proc
);
5879 CHECK_STRING (text
);
5881 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5883 Lisp_Object old_read_only
;
5884 ptrdiff_t old_begv
, old_zv
;
5885 ptrdiff_t old_begv_byte
, old_zv_byte
;
5886 ptrdiff_t before
, before_byte
;
5887 ptrdiff_t opoint_byte
;
5890 Fset_buffer (p
->buffer
);
5892 opoint_byte
= PT_BYTE
;
5893 old_read_only
= BVAR (current_buffer
, read_only
);
5896 old_begv_byte
= BEGV_BYTE
;
5897 old_zv_byte
= ZV_BYTE
;
5899 bset_read_only (current_buffer
, Qnil
);
5901 /* Insert new output into buffer at the current end-of-output
5902 marker, thus preserving logical ordering of input and output. */
5903 if (XMARKER (p
->mark
)->buffer
)
5904 set_point_from_marker (p
->mark
);
5906 SET_PT_BOTH (ZV
, ZV_BYTE
);
5908 before_byte
= PT_BYTE
;
5910 /* If the output marker is outside of the visible region, save
5911 the restriction and widen. */
5912 if (! (BEGV
<= PT
&& PT
<= ZV
))
5915 /* Adjust the multibyteness of TEXT to that of the buffer. */
5916 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5917 != ! STRING_MULTIBYTE (text
))
5918 text
= (STRING_MULTIBYTE (text
)
5919 ? Fstring_as_unibyte (text
)
5920 : Fstring_to_multibyte (text
));
5921 /* Insert before markers in case we are inserting where
5922 the buffer's mark is, and the user's next command is Meta-y. */
5923 insert_from_string_before_markers (text
, 0, 0,
5924 SCHARS (text
), SBYTES (text
), 0);
5926 /* Make sure the process marker's position is valid when the
5927 process buffer is changed in the signal_after_change above.
5928 W3 is known to do that. */
5929 if (BUFFERP (p
->buffer
)
5930 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5931 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5933 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5935 update_mode_lines
= 23;
5937 /* Make sure opoint and the old restrictions
5938 float ahead of any new text just as point would. */
5939 if (opoint
>= before
)
5941 opoint
+= PT
- before
;
5942 opoint_byte
+= PT_BYTE
- before_byte
;
5944 if (old_begv
> before
)
5946 old_begv
+= PT
- before
;
5947 old_begv_byte
+= PT_BYTE
- before_byte
;
5949 if (old_zv
>= before
)
5951 old_zv
+= PT
- before
;
5952 old_zv_byte
+= PT_BYTE
- before_byte
;
5955 /* If the restriction isn't what it should be, set it. */
5956 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5957 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5959 bset_read_only (current_buffer
, old_read_only
);
5960 SET_PT_BOTH (opoint
, opoint_byte
);
5965 /* Sending data to subprocess. */
5967 /* In send_process, when a write fails temporarily,
5968 wait_reading_process_output is called. It may execute user code,
5969 e.g. timers, that attempts to write new data to the same process.
5970 We must ensure that data is sent in the right order, and not
5971 interspersed half-completed with other writes (Bug#10815). This is
5972 handled by the write_queue element of struct process. It is a list
5973 with each entry having the form
5975 (string . (offset . length))
5977 where STRING is a lisp string, OFFSET is the offset into the
5978 string's byte sequence from which we should begin to send, and
5979 LENGTH is the number of bytes left to send. */
5981 /* Create a new entry in write_queue.
5982 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5983 BUF is a pointer to the string sequence of the input_obj or a C
5984 string in case of Qt or Qnil. */
5987 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5988 const char *buf
, ptrdiff_t len
, bool front
)
5991 Lisp_Object entry
, obj
;
5993 if (STRINGP (input_obj
))
5995 offset
= buf
- SSDATA (input_obj
);
6001 obj
= make_unibyte_string (buf
, len
);
6004 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
6007 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
6009 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
6012 /* Remove the first element in the write_queue of process P, put its
6013 contents in OBJ, BUF and LEN, and return true. If the
6014 write_queue is empty, return false. */
6017 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
6018 const char **buf
, ptrdiff_t *len
)
6020 Lisp_Object entry
, offset_length
;
6023 if (NILP (p
->write_queue
))
6026 entry
= XCAR (p
->write_queue
);
6027 pset_write_queue (p
, XCDR (p
->write_queue
));
6029 *obj
= XCAR (entry
);
6030 offset_length
= XCDR (entry
);
6032 *len
= XINT (XCDR (offset_length
));
6033 offset
= XINT (XCAR (offset_length
));
6034 *buf
= SSDATA (*obj
) + offset
;
6039 /* Send some data to process PROC.
6040 BUF is the beginning of the data; LEN is the number of characters.
6041 OBJECT is the Lisp object that the data comes from. If OBJECT is
6042 nil or t, it means that the data comes from C string.
6044 If OBJECT is not nil, the data is encoded by PROC's coding-system
6045 for encoding before it is sent.
6047 This function can evaluate Lisp code and can garbage collect. */
6050 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6053 struct Lisp_Process
*p
= XPROCESS (proc
);
6055 struct coding_system
*coding
;
6057 if (NETCONN_P (proc
))
6059 wait_while_connecting (proc
);
6060 wait_for_tls_negotiation (proc
);
6063 if (p
->raw_status_new
)
6065 if (! EQ (p
->status
, Qrun
))
6066 error ("Process %s not running", SDATA (p
->name
));
6068 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6070 coding
= proc_encode_coding_system
[p
->outfd
];
6071 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6073 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6074 || (BUFFERP (object
)
6075 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6078 pset_encode_coding_system
6079 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6080 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6082 /* The coding system for encoding was changed to raw-text
6083 because we sent a unibyte text previously. Now we are
6084 sending a multibyte text, thus we must encode it by the
6085 original coding system specified for the current process.
6087 Another reason we come here is that the coding system
6088 was just complemented and a new one was returned by
6089 complement_process_encoding_system. */
6090 setup_coding_system (p
->encode_coding_system
, coding
);
6091 Vlast_coding_system_used
= p
->encode_coding_system
;
6093 coding
->src_multibyte
= 1;
6097 coding
->src_multibyte
= 0;
6098 /* For sending a unibyte text, character code conversion should
6099 not take place but EOL conversion should. So, setup raw-text
6100 or one of the subsidiary if we have not yet done it. */
6101 if (CODING_REQUIRE_ENCODING (coding
))
6103 if (CODING_REQUIRE_FLUSHING (coding
))
6105 /* But, before changing the coding, we must flush out data. */
6106 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6107 send_process (proc
, "", 0, Qt
);
6108 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6110 setup_coding_system (raw_text_coding_system
6111 (Vlast_coding_system_used
),
6113 coding
->src_multibyte
= 0;
6116 coding
->dst_multibyte
= 0;
6118 if (CODING_REQUIRE_ENCODING (coding
))
6120 coding
->dst_object
= Qt
;
6121 if (BUFFERP (object
))
6123 ptrdiff_t from_byte
, from
, to
;
6124 ptrdiff_t save_pt
, save_pt_byte
;
6125 struct buffer
*cur
= current_buffer
;
6127 set_buffer_internal (XBUFFER (object
));
6128 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6130 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6131 from
= BYTE_TO_CHAR (from_byte
);
6132 to
= BYTE_TO_CHAR (from_byte
+ len
);
6133 TEMP_SET_PT_BOTH (from
, from_byte
);
6134 encode_coding_object (coding
, object
, from
, from_byte
,
6135 to
, from_byte
+ len
, Qt
);
6136 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6137 set_buffer_internal (cur
);
6139 else if (STRINGP (object
))
6141 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6142 SBYTES (object
), Qt
);
6146 coding
->dst_object
= make_unibyte_string (buf
, len
);
6147 coding
->produced
= len
;
6150 len
= coding
->produced
;
6151 object
= coding
->dst_object
;
6152 buf
= SSDATA (object
);
6155 /* If there is already data in the write_queue, put the new data
6156 in the back of queue. Otherwise, ignore it. */
6157 if (!NILP (p
->write_queue
))
6158 write_queue_push (p
, object
, buf
, len
, 0);
6160 do /* while !NILP (p->write_queue) */
6162 ptrdiff_t cur_len
= -1;
6163 const char *cur_buf
;
6164 Lisp_Object cur_object
;
6166 /* If write_queue is empty, ignore it. */
6167 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6171 cur_object
= object
;
6176 /* Send this batch, using one or more write calls. */
6177 ptrdiff_t written
= 0;
6178 int outfd
= p
->outfd
;
6179 #ifdef DATAGRAM_SOCKETS
6180 if (DATAGRAM_CHAN_P (outfd
))
6182 rv
= sendto (outfd
, cur_buf
, cur_len
,
6183 0, datagram_address
[outfd
].sa
,
6184 datagram_address
[outfd
].len
);
6187 else if (errno
== EMSGSIZE
)
6188 report_file_error ("Sending datagram", proc
);
6194 if (p
->gnutls_p
&& p
->gnutls_state
)
6195 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6198 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6199 rv
= (written
? 0 : -1);
6200 if (p
->read_output_delay
> 0
6201 && p
->adaptive_read_buffering
== 1)
6203 p
->read_output_delay
= 0;
6204 process_output_delay_count
--;
6205 p
->read_output_skip
= 0;
6213 || errno
== EWOULDBLOCK
6216 /* Buffer is full. Wait, accepting input;
6217 that may allow the program
6218 to finish doing output and read more. */
6220 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6221 /* A gross hack to work around a bug in FreeBSD.
6222 In the following sequence, read(2) returns
6226 write(2) 954 bytes, get EAGAIN
6227 read(2) 1024 bytes in process_read_output
6228 read(2) 11 bytes in process_read_output
6230 That is, read(2) returns more bytes than have
6231 ever been written successfully. The 1033 bytes
6232 read are the 1022 bytes written successfully
6233 after processing (for example with CRs added if
6234 the terminal is set up that way which it is
6235 here). The same bytes will be seen again in a
6236 later read(2), without the CRs. */
6238 if (errno
== EAGAIN
)
6241 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6243 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6245 /* Put what we should have written in wait_queue. */
6246 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6247 wait_reading_process_output (0, 20 * 1000 * 1000,
6248 0, 0, Qnil
, NULL
, 0);
6249 /* Reread queue, to see what is left. */
6252 else if (errno
== EPIPE
)
6254 p
->raw_status_new
= 0;
6255 pset_status (p
, list2 (Qexit
, make_number (256)));
6256 p
->tick
= ++process_tick
;
6257 deactivate_process (proc
);
6258 error ("process %s no longer connected to pipe; closed it",
6262 /* This is a real error. */
6263 report_file_error ("Writing to process", proc
);
6269 while (!NILP (p
->write_queue
));
6272 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6274 doc
: /* Send current contents of region as input to PROCESS.
6275 PROCESS may be a process, a buffer, the name of a process or buffer, or
6276 nil, indicating the current buffer's process.
6277 Called from program, takes three arguments, PROCESS, START and END.
6278 If the region is more than 500 characters long,
6279 it is sent in several bunches. This may happen even for shorter regions.
6280 Output from processes can arrive in between bunches.
6282 If PROCESS is a non-blocking network process that hasn't been fully
6283 set up yet, this function will block until socket setup has completed. */)
6284 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6286 Lisp_Object proc
= get_process (process
);
6287 ptrdiff_t start_byte
, end_byte
;
6289 validate_region (&start
, &end
);
6291 start_byte
= CHAR_TO_BYTE (XINT (start
));
6292 end_byte
= CHAR_TO_BYTE (XINT (end
));
6294 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6295 move_gap_both (XINT (start
), start_byte
);
6297 if (NETCONN_P (proc
))
6298 wait_while_connecting (proc
);
6300 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6301 end_byte
- start_byte
, Fcurrent_buffer ());
6306 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6308 doc
: /* Send PROCESS the contents of STRING as input.
6309 PROCESS may be a process, a buffer, the name of a process or buffer, or
6310 nil, indicating the current buffer's process.
6311 If STRING is more than 500 characters long,
6312 it is sent in several bunches. This may happen even for shorter strings.
6313 Output from processes can arrive in between bunches.
6315 If PROCESS is a non-blocking network process that hasn't been fully
6316 set up yet, this function will block until socket setup has completed. */)
6317 (Lisp_Object process
, Lisp_Object string
)
6319 CHECK_STRING (string
);
6320 Lisp_Object proc
= get_process (process
);
6321 send_process (proc
, SSDATA (string
),
6322 SBYTES (string
), string
);
6326 /* Return the foreground process group for the tty/pty that
6327 the process P uses. */
6329 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6334 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6337 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6338 master side. Try the slave side. */
6339 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6343 ioctl (fd
, TIOCGPGRP
, &gid
);
6347 #endif /* defined (TIOCGPGRP ) */
6352 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6353 Sprocess_running_child_p
, 0, 1, 0,
6354 doc
: /* Return non-nil if PROCESS has given the terminal to a
6355 child. If the operating system does not make it possible to find out,
6356 return t. If we can find out, return the numeric ID of the foreground
6358 (Lisp_Object process
)
6360 /* Initialize in case ioctl doesn't exist or gives an error,
6361 in a way that will cause returning t. */
6362 Lisp_Object proc
= get_process (process
);
6363 struct Lisp_Process
*p
= XPROCESS (proc
);
6365 if (!EQ (p
->type
, Qreal
))
6366 error ("Process %s is not a subprocess",
6369 error ("Process %s is not active",
6372 pid_t gid
= emacs_get_tty_pgrp (p
);
6377 return make_number (gid
);
6381 /* Send a signal number SIGNO to PROCESS.
6382 If CURRENT_GROUP is t, that means send to the process group
6383 that currently owns the terminal being used to communicate with PROCESS.
6384 This is used for various commands in shell mode.
6385 If CURRENT_GROUP is lambda, that means send to the process group
6386 that currently owns the terminal, but only if it is NOT the shell itself.
6388 If NOMSG is false, insert signal-announcements into process's buffers
6391 If we can, we try to signal PROCESS by sending control characters
6392 down the pty. This allows us to signal inferiors who have changed
6393 their uid, for which kill would return an EPERM error. */
6396 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6400 struct Lisp_Process
*p
;
6404 proc
= get_process (process
);
6405 p
= XPROCESS (proc
);
6407 if (!EQ (p
->type
, Qreal
))
6408 error ("Process %s is not a subprocess",
6411 error ("Process %s is not active",
6415 current_group
= Qnil
;
6417 /* If we are using pgrps, get a pgrp number and make it negative. */
6418 if (NILP (current_group
))
6419 /* Send the signal to the shell's process group. */
6423 #ifdef SIGNALS_VIA_CHARACTERS
6424 /* If possible, send signals to the entire pgrp
6425 by sending an input character to it. */
6428 cc_t
*sig_char
= NULL
;
6430 tcgetattr (p
->infd
, &t
);
6435 sig_char
= &t
.c_cc
[VINTR
];
6439 sig_char
= &t
.c_cc
[VQUIT
];
6443 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6444 sig_char
= &t
.c_cc
[VSWTCH
];
6446 sig_char
= &t
.c_cc
[VSUSP
];
6451 if (sig_char
&& *sig_char
!= CDISABLE
)
6453 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6456 /* If we can't send the signal with a character,
6457 fall through and send it another way. */
6459 /* The code above may fall through if it can't
6460 handle the signal. */
6461 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6464 /* Get the current pgrp using the tty itself, if we have that.
6465 Otherwise, use the pty to get the pgrp.
6466 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6467 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6468 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6469 His patch indicates that if TIOCGPGRP returns an error, then
6470 we should just assume that p->pid is also the process group id. */
6472 gid
= emacs_get_tty_pgrp (p
);
6475 /* If we can't get the information, assume
6476 the shell owns the tty. */
6479 /* It is not clear whether anything really can set GID to -1.
6480 Perhaps on some system one of those ioctls can or could do so.
6481 Or perhaps this is vestigial. */
6484 #else /* ! defined (TIOCGPGRP) */
6485 /* Can't select pgrps on this system, so we know that
6486 the child itself heads the pgrp. */
6488 #endif /* ! defined (TIOCGPGRP) */
6490 /* If current_group is lambda, and the shell owns the terminal,
6491 don't send any signal. */
6492 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6497 if (signo
== SIGCONT
)
6499 p
->raw_status_new
= 0;
6500 pset_status (p
, Qrun
);
6501 p
->tick
= ++process_tick
;
6504 status_notify (NULL
, NULL
);
6505 redisplay_preserve_echo_area (13);
6511 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6512 We don't know whether the bug is fixed in later HP-UX versions. */
6513 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6517 /* If we don't have process groups, send the signal to the immediate
6518 subprocess. That isn't really right, but it's better than any
6519 obvious alternative. */
6520 pid_t pid
= no_pgrp
? gid
: - gid
;
6522 /* Do not kill an already-reaped process, as that could kill an
6523 innocent bystander that happens to have the same process ID. */
6525 block_child_signal (&oldset
);
6528 unblock_child_signal (&oldset
);
6531 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6532 doc
: /* Interrupt process PROCESS.
6533 PROCESS may be a process, a buffer, or the name of a process or buffer.
6534 No arg or nil means current buffer's process.
6535 Second arg CURRENT-GROUP non-nil means send signal to
6536 the current process-group of the process's controlling terminal
6537 rather than to the process's own process group.
6538 If the process is a shell, this means interrupt current subjob
6539 rather than the shell.
6541 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6542 don't send the signal. */)
6543 (Lisp_Object process
, Lisp_Object current_group
)
6545 process_send_signal (process
, SIGINT
, current_group
, 0);
6549 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6550 doc
: /* Kill process PROCESS. May be process or name of one.
6551 See function `interrupt-process' for more details on usage. */)
6552 (Lisp_Object process
, Lisp_Object current_group
)
6554 process_send_signal (process
, SIGKILL
, current_group
, 0);
6558 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6559 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6560 See function `interrupt-process' for more details on usage. */)
6561 (Lisp_Object process
, Lisp_Object current_group
)
6563 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6567 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6568 doc
: /* Stop process PROCESS. May be process or name of one.
6569 See function `interrupt-process' for more details on usage.
6570 If PROCESS is a network or serial process, inhibit handling of incoming
6572 (Lisp_Object process
, Lisp_Object current_group
)
6574 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6575 || PIPECONN_P (process
)))
6577 struct Lisp_Process
*p
;
6579 p
= XPROCESS (process
);
6580 if (NILP (p
->command
)
6583 FD_CLR (p
->infd
, &input_wait_mask
);
6584 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6586 pset_command (p
, Qt
);
6590 error ("No SIGTSTP support");
6592 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6597 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6598 doc
: /* Continue process PROCESS. May be process or name of one.
6599 See function `interrupt-process' for more details on usage.
6600 If PROCESS is a network or serial process, resume handling of incoming
6602 (Lisp_Object process
, Lisp_Object current_group
)
6604 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6605 || PIPECONN_P (process
)))
6607 struct Lisp_Process
*p
;
6609 p
= XPROCESS (process
);
6610 if (EQ (p
->command
, Qt
)
6612 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6614 FD_SET (p
->infd
, &input_wait_mask
);
6615 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6617 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6618 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6619 #else /* not WINDOWSNT */
6620 tcflush (p
->infd
, TCIFLUSH
);
6621 #endif /* not WINDOWSNT */
6623 pset_command (p
, Qnil
);
6627 process_send_signal (process
, SIGCONT
, current_group
, 0);
6629 error ("No SIGCONT support");
6634 /* Return the integer value of the signal whose abbreviation is ABBR,
6635 or a negative number if there is no such signal. */
6637 abbr_to_signal (char const *name
)
6640 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6642 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6645 for (i
= 0; i
< sizeof sigbuf
; i
++)
6647 sigbuf
[i
] = c_toupper (name
[i
]);
6649 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6655 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6656 2, 2, "sProcess (name or number): \nnSignal code: ",
6657 doc
: /* Send PROCESS the signal with code SIGCODE.
6658 PROCESS may also be a number specifying the process id of the
6659 process to signal; in this case, the process need not be a child of
6661 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6662 (Lisp_Object process
, Lisp_Object sigcode
)
6667 if (STRINGP (process
))
6669 Lisp_Object tem
= Fget_process (process
);
6672 Lisp_Object process_number
6673 = string_to_number (SSDATA (process
), 10, 1);
6674 if (NUMBERP (process_number
))
6675 tem
= process_number
;
6679 else if (!NUMBERP (process
))
6680 process
= get_process (process
);
6685 if (NUMBERP (process
))
6686 CONS_TO_INTEGER (process
, pid_t
, pid
);
6689 CHECK_PROCESS (process
);
6690 pid
= XPROCESS (process
)->pid
;
6692 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6695 if (INTEGERP (sigcode
))
6697 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6698 signo
= XINT (sigcode
);
6704 CHECK_SYMBOL (sigcode
);
6705 name
= SSDATA (SYMBOL_NAME (sigcode
));
6707 signo
= abbr_to_signal (name
);
6709 error ("Undefined signal name %s", name
);
6712 return make_number (kill (pid
, signo
));
6715 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6716 doc
: /* Make PROCESS see end-of-file in its input.
6717 EOF comes after any text already sent to it.
6718 PROCESS may be a process, a buffer, the name of a process or buffer, or
6719 nil, indicating the current buffer's process.
6720 If PROCESS is a network connection, or is a process communicating
6721 through a pipe (as opposed to a pty), then you cannot send any more
6722 text to PROCESS after you call this function.
6723 If PROCESS is a serial process, wait until all output written to the
6724 process has been transmitted to the serial port. */)
6725 (Lisp_Object process
)
6728 struct coding_system
*coding
= NULL
;
6731 proc
= get_process (process
);
6733 if (NETCONN_P (proc
))
6734 wait_while_connecting (proc
);
6736 if (DATAGRAM_CONN_P (proc
))
6740 outfd
= XPROCESS (proc
)->outfd
;
6742 coding
= proc_encode_coding_system
[outfd
];
6744 /* Make sure the process is really alive. */
6745 if (XPROCESS (proc
)->raw_status_new
)
6746 update_status (XPROCESS (proc
));
6747 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6748 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6750 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6752 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6753 send_process (proc
, "", 0, Qnil
);
6756 if (XPROCESS (proc
)->pty_flag
)
6757 send_process (proc
, "\004", 1, Qnil
);
6758 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6761 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6762 report_file_error ("Failed tcdrain", Qnil
);
6763 #endif /* not WINDOWSNT */
6764 /* Do nothing on Windows because writes are blocking. */
6768 struct Lisp_Process
*p
= XPROCESS (proc
);
6769 int old_outfd
= p
->outfd
;
6772 #ifdef HAVE_SHUTDOWN
6773 /* If this is a network connection, or socketpair is used
6774 for communication with the subprocess, call shutdown to cause EOF.
6775 (In some old system, shutdown to socketpair doesn't work.
6776 Then we just can't win.) */
6778 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6779 shutdown (old_outfd
, 1);
6781 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6782 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6784 report_file_error ("Opening null device", Qnil
);
6785 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6786 p
->outfd
= new_outfd
;
6788 if (!proc_encode_coding_system
[new_outfd
])
6789 proc_encode_coding_system
[new_outfd
]
6790 = xmalloc (sizeof (struct coding_system
));
6793 *proc_encode_coding_system
[new_outfd
]
6794 = *proc_encode_coding_system
[old_outfd
];
6795 memset (proc_encode_coding_system
[old_outfd
], 0,
6796 sizeof (struct coding_system
));
6799 setup_coding_system (p
->encode_coding_system
,
6800 proc_encode_coding_system
[new_outfd
]);
6805 /* The main Emacs thread records child processes in three places:
6807 - Vprocess_alist, for asynchronous subprocesses, which are child
6808 processes visible to Lisp.
6810 - deleted_pid_list, for child processes invisible to Lisp,
6811 typically because of delete-process. These are recorded so that
6812 the processes can be reaped when they exit, so that the operating
6813 system's process table is not cluttered by zombies.
6815 - the local variable PID in Fcall_process, call_process_cleanup and
6816 call_process_kill, for synchronous subprocesses.
6817 record_unwind_protect is used to make sure this process is not
6818 forgotten: if the user interrupts call-process and the child
6819 process refuses to exit immediately even with two C-g's,
6820 call_process_kill adds PID's contents to deleted_pid_list before
6823 The main Emacs thread invokes waitpid only on child processes that
6824 it creates and that have not been reaped. This avoid races on
6825 platforms such as GTK, where other threads create their own
6826 subprocesses which the main thread should not reap. For example,
6827 if the main thread attempted to reap an already-reaped child, it
6828 might inadvertently reap a GTK-created process that happened to
6829 have the same process ID. */
6831 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6832 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6833 keep track of its own children. GNUstep is similar. */
6835 static void dummy_handler (int sig
) {}
6836 static signal_handler_t
volatile lib_child_handler
;
6838 /* Handle a SIGCHLD signal by looking for known child processes of
6839 Emacs whose status have changed. For each one found, record its
6842 All we do is change the status; we do not run sentinels or print
6843 notifications. That is saved for the next time keyboard input is
6844 done, in order to avoid timing errors.
6846 ** WARNING: this can be called during garbage collection.
6847 Therefore, it must not be fooled by the presence of mark bits in
6850 ** USG WARNING: Although it is not obvious from the documentation
6851 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6852 signal() before executing at least one wait(), otherwise the
6853 handler will be called again, resulting in an infinite loop. The
6854 relevant portion of the documentation reads "SIGCLD signals will be
6855 queued and the signal-catching function will be continually
6856 reentered until the queue is empty". Invoking signal() causes the
6857 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6860 ** Malloc WARNING: This should never call malloc either directly or
6861 indirectly; if it does, that is a bug. */
6864 handle_child_signal (int sig
)
6866 Lisp_Object tail
, proc
;
6868 /* Find the process that signaled us, and record its status. */
6870 /* The process can have been deleted by Fdelete_process, or have
6871 been started asynchronously by Fcall_process. */
6872 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6874 bool all_pids_are_fixnums
6875 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6876 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6877 Lisp_Object head
= XCAR (tail
);
6882 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6885 if (INTEGERP (xpid
))
6886 deleted_pid
= XINT (xpid
);
6888 deleted_pid
= XFLOAT_DATA (xpid
);
6889 if (child_status_changed (deleted_pid
, 0, 0))
6891 if (STRINGP (XCDR (head
)))
6892 unlink (SSDATA (XCDR (head
)));
6893 XSETCAR (tail
, Qnil
);
6898 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6899 FOR_EACH_PROCESS (tail
, proc
)
6901 struct Lisp_Process
*p
= XPROCESS (proc
);
6905 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6907 /* Change the status of the process that was found. */
6908 p
->tick
= ++process_tick
;
6909 p
->raw_status
= status
;
6910 p
->raw_status_new
= 1;
6912 /* If process has terminated, stop waiting for its output. */
6913 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6915 bool clear_desc_flag
= 0;
6918 clear_desc_flag
= 1;
6920 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6921 if (clear_desc_flag
)
6923 FD_CLR (p
->infd
, &input_wait_mask
);
6924 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6930 lib_child_handler (sig
);
6931 #ifdef NS_IMPL_GNUSTEP
6932 /* NSTask in GNUstep sets its child handler each time it is called.
6933 So we must re-set ours. */
6934 catch_child_signal ();
6939 deliver_child_signal (int sig
)
6941 deliver_process_signal (sig
, handle_child_signal
);
6946 exec_sentinel_error_handler (Lisp_Object error_val
)
6948 cmd_error_internal (error_val
, "error in process sentinel: ");
6950 update_echo_area ();
6951 Fsleep_for (make_number (2), Qnil
);
6956 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6958 Lisp_Object sentinel
, odeactivate
;
6959 struct Lisp_Process
*p
= XPROCESS (proc
);
6960 ptrdiff_t count
= SPECPDL_INDEX ();
6961 bool outer_running_asynch_code
= running_asynch_code
;
6962 int waiting
= waiting_for_user_input_p
;
6964 if (inhibit_sentinels
)
6967 odeactivate
= Vdeactivate_mark
;
6969 Lisp_Object obuffer
, okeymap
;
6970 XSETBUFFER (obuffer
, current_buffer
);
6971 okeymap
= BVAR (current_buffer
, keymap
);
6974 /* There's no good reason to let sentinels change the current
6975 buffer, and many callers of accept-process-output, sit-for, and
6976 friends don't expect current-buffer to be changed from under them. */
6977 record_unwind_current_buffer ();
6979 sentinel
= p
->sentinel
;
6981 /* Inhibit quit so that random quits don't screw up a running filter. */
6982 specbind (Qinhibit_quit
, Qt
);
6983 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6985 /* In case we get recursively called,
6986 and we already saved the match data nonrecursively,
6987 save the same match data in safely recursive fashion. */
6988 if (outer_running_asynch_code
)
6991 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6992 restore_search_regs ();
6993 record_unwind_save_match_data ();
6994 Fset_match_data (tem
, Qt
);
6997 /* For speed, if a search happens within this code,
6998 save the match data in a special nonrecursive fashion. */
6999 running_asynch_code
= 1;
7001 internal_condition_case_1 (read_process_output_call
,
7002 list3 (sentinel
, proc
, reason
),
7003 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
7004 exec_sentinel_error_handler
);
7006 /* If we saved the match data nonrecursively, restore it now. */
7007 restore_search_regs ();
7008 running_asynch_code
= outer_running_asynch_code
;
7010 Vdeactivate_mark
= odeactivate
;
7012 /* Restore waiting_for_user_input_p as it was
7013 when we were called, in case the filter clobbered it. */
7014 waiting_for_user_input_p
= waiting
;
7017 if (! EQ (Fcurrent_buffer (), obuffer
)
7018 || ! EQ (current_buffer
->keymap
, okeymap
))
7020 /* But do it only if the caller is actually going to read events.
7021 Otherwise there's no need to make him wake up, and it could
7022 cause trouble (for example it would make sit_for return). */
7023 if (waiting_for_user_input_p
== -1)
7024 record_asynch_buffer_change ();
7026 unbind_to (count
, Qnil
);
7029 /* Report all recent events of a change in process status
7030 (either run the sentinel or output a message).
7031 This is usually done while Emacs is waiting for keyboard input
7032 but can be done at other times.
7034 Return positive if any input was received from WAIT_PROC (or from
7035 any process if WAIT_PROC is null), zero if input was attempted but
7036 none received, and negative if we didn't even try. */
7039 status_notify (struct Lisp_Process
*deleting_process
,
7040 struct Lisp_Process
*wait_proc
)
7043 Lisp_Object tail
, msg
;
7044 int got_some_output
= -1;
7049 /* Set this now, so that if new processes are created by sentinels
7050 that we run, we get called again to handle their status changes. */
7051 update_tick
= process_tick
;
7053 FOR_EACH_PROCESS (tail
, proc
)
7056 register struct Lisp_Process
*p
= XPROCESS (proc
);
7058 if (p
->tick
!= p
->update_tick
)
7060 p
->update_tick
= p
->tick
;
7062 /* If process is still active, read any output that remains. */
7063 while (! EQ (p
->filter
, Qt
)
7064 && ! EQ (p
->status
, Qconnect
)
7065 && ! EQ (p
->status
, Qlisten
)
7066 /* Network or serial process not stopped: */
7067 && ! EQ (p
->command
, Qt
)
7069 && p
!= deleting_process
)
7071 int nread
= read_process_output (proc
, p
->infd
);
7072 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7073 && got_some_output
< nread
)
7074 got_some_output
= nread
;
7079 /* Get the text to use for the message. */
7080 if (p
->raw_status_new
)
7082 msg
= status_message (p
);
7084 /* If process is terminated, deactivate it or delete it. */
7086 if (CONSP (p
->status
))
7087 symbol
= XCAR (p
->status
);
7089 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7090 || EQ (symbol
, Qclosed
))
7092 if (delete_exited_processes
)
7093 remove_process (proc
);
7095 deactivate_process (proc
);
7098 /* The actions above may have further incremented p->tick.
7099 So set p->update_tick again so that an error in the sentinel will
7100 not cause this code to be run again. */
7101 p
->update_tick
= p
->tick
;
7102 /* Now output the message suitably. */
7103 exec_sentinel (proc
, msg
);
7104 if (BUFFERP (p
->buffer
))
7105 /* In case it uses %s in mode-line-format. */
7106 bset_update_mode_line (XBUFFER (p
->buffer
));
7110 return got_some_output
;
7113 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7114 Sinternal_default_process_sentinel
, 2, 2, 0,
7115 doc
: /* Function used as default sentinel for processes.
7116 This inserts a status message into the process's buffer, if there is one. */)
7117 (Lisp_Object proc
, Lisp_Object msg
)
7119 Lisp_Object buffer
, symbol
;
7120 struct Lisp_Process
*p
;
7121 CHECK_PROCESS (proc
);
7122 p
= XPROCESS (proc
);
7126 symbol
= XCAR (symbol
);
7128 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7131 struct buffer
*old
= current_buffer
;
7132 ptrdiff_t opoint
, opoint_byte
;
7133 ptrdiff_t before
, before_byte
;
7135 /* Avoid error if buffer is deleted
7136 (probably that's why the process is dead, too). */
7137 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7139 Fset_buffer (buffer
);
7141 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7142 msg
= (code_convert_string_norecord
7143 (msg
, Vlocale_coding_system
, 1));
7146 opoint_byte
= PT_BYTE
;
7147 /* Insert new output into buffer
7148 at the current end-of-output marker,
7149 thus preserving logical ordering of input and output. */
7150 if (XMARKER (p
->mark
)->buffer
)
7151 Fgoto_char (p
->mark
);
7153 SET_PT_BOTH (ZV
, ZV_BYTE
);
7156 before_byte
= PT_BYTE
;
7158 tem
= BVAR (current_buffer
, read_only
);
7159 bset_read_only (current_buffer
, Qnil
);
7160 insert_string ("\nProcess ");
7161 { /* FIXME: temporary kludge. */
7162 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7163 insert_string (" ");
7165 bset_read_only (current_buffer
, tem
);
7166 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7168 if (opoint
>= before
)
7169 SET_PT_BOTH (opoint
+ (PT
- before
),
7170 opoint_byte
+ (PT_BYTE
- before_byte
));
7172 SET_PT_BOTH (opoint
, opoint_byte
);
7174 set_buffer_internal (old
);
7180 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7181 Sset_process_coding_system
, 1, 3, 0,
7182 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7183 DECODING will be used to decode subprocess output and ENCODING to
7184 encode subprocess input. */)
7185 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7187 CHECK_PROCESS (process
);
7189 struct Lisp_Process
*p
= XPROCESS (process
);
7191 Fcheck_coding_system (decoding
);
7192 Fcheck_coding_system (encoding
);
7193 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7194 pset_decode_coding_system (p
, decoding
);
7195 pset_encode_coding_system (p
, encoding
);
7197 /* If the sockets haven't been set up yet, the final setup part of
7198 this will be called asynchronously. */
7199 if (p
->infd
< 0 || p
->outfd
< 0)
7202 setup_process_coding_systems (process
);
7207 DEFUN ("process-coding-system",
7208 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7209 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7210 (register Lisp_Object process
)
7212 CHECK_PROCESS (process
);
7213 return Fcons (XPROCESS (process
)->decode_coding_system
,
7214 XPROCESS (process
)->encode_coding_system
);
7217 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7218 Sset_process_filter_multibyte
, 2, 2, 0,
7219 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7220 If FLAG is non-nil, the filter is given multibyte strings.
7221 If FLAG is nil, the filter is given unibyte strings. In this case,
7222 all character code conversion except for end-of-line conversion is
7224 (Lisp_Object process
, Lisp_Object flag
)
7226 CHECK_PROCESS (process
);
7228 struct Lisp_Process
*p
= XPROCESS (process
);
7230 pset_decode_coding_system
7231 (p
, raw_text_coding_system (p
->decode_coding_system
));
7233 /* If the sockets haven't been set up yet, the final setup part of
7234 this will be called asynchronously. */
7235 if (p
->infd
< 0 || p
->outfd
< 0)
7238 setup_process_coding_systems (process
);
7243 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7244 Sprocess_filter_multibyte_p
, 1, 1, 0,
7245 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7246 (Lisp_Object process
)
7248 CHECK_PROCESS (process
);
7249 struct Lisp_Process
*p
= XPROCESS (process
);
7252 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7253 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7262 add_gpm_wait_descriptor (int desc
)
7264 add_keyboard_wait_descriptor (desc
);
7268 delete_gpm_wait_descriptor (int desc
)
7270 delete_keyboard_wait_descriptor (desc
);
7275 # ifdef USABLE_SIGIO
7277 /* Return true if *MASK has a bit set
7278 that corresponds to one of the keyboard input descriptors. */
7281 keyboard_bit_set (fd_set
*mask
)
7285 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7286 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7287 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7294 #else /* not subprocesses */
7296 /* Defined in msdos.c. */
7297 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7298 struct timespec
*, void *);
7300 /* Implementation of wait_reading_process_output, assuming that there
7301 are no subprocesses. Used only by the MS-DOS build.
7303 Wait for timeout to elapse and/or keyboard input to be available.
7307 If negative, gobble data immediately available but don't wait for any.
7310 an additional duration to wait, measured in nanoseconds
7311 If TIME_LIMIT is zero, then:
7312 If NSECS == 0, there is no limit.
7313 If NSECS > 0, the timeout consists of NSECS only.
7314 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7317 0 to ignore keyboard input, or
7318 1 to return when input is available, or
7319 -1 means caller will actually read the input, so don't throw to
7322 see full version for other parameters. We know that wait_proc will
7323 always be NULL, since `subprocesses' isn't defined.
7325 DO_DISPLAY means redisplay should be done to show subprocess
7326 output that arrives.
7328 Return -1 signifying we got no output and did not try. */
7331 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7333 Lisp_Object wait_for_cell
,
7334 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7337 struct timespec end_time
, timeout
;
7338 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7340 if (TYPE_MAXIMUM (time_t) < time_limit
)
7341 time_limit
= TYPE_MAXIMUM (time_t);
7343 if (time_limit
< 0 || nsecs
< 0)
7345 else if (time_limit
> 0 || nsecs
> 0)
7348 end_time
= timespec_add (current_timespec (),
7349 make_timespec (time_limit
, nsecs
));
7354 /* Turn off periodic alarms (in case they are in use)
7355 and then turn off any other atimers,
7356 because the select emulator uses alarms. */
7358 turn_on_atimers (0);
7362 bool timeout_reduced_for_timers
= false;
7363 fd_set waitchannels
;
7366 /* If calling from keyboard input, do not quit
7367 since we want to return C-g as an input character.
7368 Otherwise, do pending quit if requested. */
7372 /* Exit now if the cell we're waiting for became non-nil. */
7373 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7376 /* Compute time from now till when time limit is up. */
7377 /* Exit if already run out. */
7378 if (wait
== TIMEOUT
)
7380 struct timespec now
= current_timespec ();
7381 if (timespec_cmp (end_time
, now
) <= 0)
7383 timeout
= timespec_sub (end_time
, now
);
7386 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7388 /* If our caller will not immediately handle keyboard events,
7389 run timer events directly.
7390 (Callers that will immediately read keyboard events
7391 call timer_delay on their own.) */
7392 if (NILP (wait_for_cell
))
7394 struct timespec timer_delay
;
7398 unsigned old_timers_run
= timers_run
;
7399 timer_delay
= timer_check ();
7400 if (timers_run
!= old_timers_run
&& do_display
)
7401 /* We must retry, since a timer may have requeued itself
7402 and that could alter the time delay. */
7403 redisplay_preserve_echo_area (14);
7407 while (!detect_input_pending ());
7409 /* If there is unread keyboard input, also return. */
7411 && requeued_events_pending_p ())
7414 if (timespec_valid_p (timer_delay
))
7416 if (timespec_cmp (timer_delay
, timeout
) < 0)
7418 timeout
= timer_delay
;
7419 timeout_reduced_for_timers
= true;
7424 /* Cause C-g and alarm signals to take immediate action,
7425 and cause input available signals to zero out timeout. */
7427 set_waiting_for_input (&timeout
);
7429 /* If a frame has been newly mapped and needs updating,
7430 reprocess its display stuff. */
7431 if (frame_garbaged
&& do_display
)
7433 clear_waiting_for_input ();
7434 redisplay_preserve_echo_area (15);
7436 set_waiting_for_input (&timeout
);
7439 /* Wait till there is something to do. */
7440 FD_ZERO (&waitchannels
);
7441 if (read_kbd
&& detect_input_pending ())
7445 if (read_kbd
|| !NILP (wait_for_cell
))
7446 FD_SET (0, &waitchannels
);
7447 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7452 /* Make C-g and alarm signals set flags again. */
7453 clear_waiting_for_input ();
7455 /* If we woke up due to SIGWINCH, actually change size now. */
7456 do_pending_window_change (0);
7458 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7459 /* We waited the full specified time, so return now. */
7464 /* If the system call was interrupted, then go around the
7466 if (xerrno
== EINTR
)
7467 FD_ZERO (&waitchannels
);
7469 report_file_errno ("Failed select", Qnil
, xerrno
);
7472 /* Check for keyboard input. */
7475 && detect_input_pending_run_timers (do_display
))
7477 swallow_events (do_display
);
7478 if (detect_input_pending_run_timers (do_display
))
7482 /* If there is unread keyboard input, also return. */
7484 && requeued_events_pending_p ())
7487 /* If wait_for_cell. check for keyboard input
7488 but don't run any timers.
7489 ??? (It seems wrong to me to check for keyboard
7490 input at all when wait_for_cell, but the code
7491 has been this way since July 1994.
7492 Try changing this after version 19.31.) */
7493 if (! NILP (wait_for_cell
)
7494 && detect_input_pending ())
7496 swallow_events (do_display
);
7497 if (detect_input_pending ())
7501 /* Exit now if the cell we're waiting for became non-nil. */
7502 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7511 #endif /* not subprocesses */
7513 /* The following functions are needed even if async subprocesses are
7514 not supported. Some of them are no-op stubs in that case. */
7518 /* Add FD, which is a descriptor returned by timerfd_create,
7519 to the set of non-keyboard input descriptors. */
7522 add_timer_wait_descriptor (int fd
)
7524 FD_SET (fd
, &input_wait_mask
);
7525 FD_SET (fd
, &non_keyboard_wait_mask
);
7526 FD_SET (fd
, &non_process_wait_mask
);
7527 fd_callback_info
[fd
].func
= timerfd_callback
;
7528 fd_callback_info
[fd
].data
= NULL
;
7529 fd_callback_info
[fd
].condition
|= FOR_READ
;
7530 if (fd
> max_input_desc
)
7531 max_input_desc
= fd
;
7534 #endif /* HAVE_TIMERFD */
7536 /* Add DESC to the set of keyboard input descriptors. */
7539 add_keyboard_wait_descriptor (int desc
)
7541 #ifdef subprocesses /* Actually means "not MSDOS". */
7542 FD_SET (desc
, &input_wait_mask
);
7543 FD_SET (desc
, &non_process_wait_mask
);
7544 if (desc
> max_input_desc
)
7545 max_input_desc
= desc
;
7549 /* From now on, do not expect DESC to give keyboard input. */
7552 delete_keyboard_wait_descriptor (int desc
)
7555 FD_CLR (desc
, &input_wait_mask
);
7556 FD_CLR (desc
, &non_process_wait_mask
);
7557 delete_input_desc (desc
);
7561 /* Setup coding systems of PROCESS. */
7564 setup_process_coding_systems (Lisp_Object process
)
7567 struct Lisp_Process
*p
= XPROCESS (process
);
7569 int outch
= p
->outfd
;
7570 Lisp_Object coding_system
;
7572 if (inch
< 0 || outch
< 0)
7575 if (!proc_decode_coding_system
[inch
])
7576 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7577 coding_system
= p
->decode_coding_system
;
7578 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7579 && BUFFERP (p
->buffer
))
7581 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7582 coding_system
= raw_text_coding_system (coding_system
);
7584 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7586 if (!proc_encode_coding_system
[outch
])
7587 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7588 setup_coding_system (p
->encode_coding_system
,
7589 proc_encode_coding_system
[outch
]);
7593 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7594 doc
: /* Return the (or a) live process associated with BUFFER.
7595 BUFFER may be a buffer or the name of one.
7596 Return nil if all processes associated with BUFFER have been
7597 deleted or killed. */)
7598 (register Lisp_Object buffer
)
7601 register Lisp_Object buf
, tail
, proc
;
7603 if (NILP (buffer
)) return Qnil
;
7604 buf
= Fget_buffer (buffer
);
7605 if (NILP (buf
)) return Qnil
;
7607 FOR_EACH_PROCESS (tail
, proc
)
7608 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7610 #endif /* subprocesses */
7614 DEFUN ("process-inherit-coding-system-flag",
7615 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7617 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7618 If this flag is t, `buffer-file-coding-system' of the buffer
7619 associated with PROCESS will inherit the coding system used to decode
7620 the process output. */)
7621 (register Lisp_Object process
)
7624 CHECK_PROCESS (process
);
7625 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7627 /* Ignore the argument and return the value of
7628 inherit-process-coding-system. */
7629 return inherit_process_coding_system
? Qt
: Qnil
;
7633 /* Kill all processes associated with `buffer'.
7634 If `buffer' is nil, kill all processes. */
7637 kill_buffer_processes (Lisp_Object buffer
)
7640 Lisp_Object tail
, proc
;
7642 FOR_EACH_PROCESS (tail
, proc
)
7643 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7645 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7646 Fdelete_process (proc
);
7647 else if (XPROCESS (proc
)->infd
>= 0)
7648 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7650 #else /* subprocesses */
7651 /* Since we have no subprocesses, this does nothing. */
7652 #endif /* subprocesses */
7655 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7656 Swaiting_for_user_input_p
, 0, 0, 0,
7657 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7658 This is intended for use by asynchronous process output filters and sentinels. */)
7662 return (waiting_for_user_input_p
? Qt
: Qnil
);
7668 /* Stop reading input from keyboard sources. */
7671 hold_keyboard_input (void)
7676 /* Resume reading input from keyboard sources. */
7679 unhold_keyboard_input (void)
7684 /* Return true if keyboard input is on hold, zero otherwise. */
7687 kbd_on_hold_p (void)
7689 return kbd_is_on_hold
;
7693 /* Enumeration of and access to system processes a-la ps(1). */
7695 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7697 doc
: /* Return a list of numerical process IDs of all running processes.
7698 If this functionality is unsupported, return nil.
7700 See `process-attributes' for getting attributes of a process given its ID. */)
7703 return list_system_processes ();
7706 DEFUN ("process-attributes", Fprocess_attributes
,
7707 Sprocess_attributes
, 1, 1, 0,
7708 doc
: /* Return attributes of the process given by its PID, a number.
7710 Value is an alist where each element is a cons cell of the form
7714 If this functionality is unsupported, the value is nil.
7716 See `list-system-processes' for getting a list of all process IDs.
7718 The KEYs of the attributes that this function may return are listed
7719 below, together with the type of the associated VALUE (in parentheses).
7720 Not all platforms support all of these attributes; unsupported
7721 attributes will not appear in the returned alist.
7722 Unless explicitly indicated otherwise, numbers can have either
7723 integer or floating point values.
7725 euid -- Effective user User ID of the process (number)
7726 user -- User name corresponding to euid (string)
7727 egid -- Effective user Group ID of the process (number)
7728 group -- Group name corresponding to egid (string)
7729 comm -- Command name (executable name only) (string)
7730 state -- Process state code, such as "S", "R", or "T" (string)
7731 ppid -- Parent process ID (number)
7732 pgrp -- Process group ID (number)
7733 sess -- Session ID, i.e. process ID of session leader (number)
7734 ttname -- Controlling tty name (string)
7735 tpgid -- ID of foreground process group on the process's tty (number)
7736 minflt -- number of minor page faults (number)
7737 majflt -- number of major page faults (number)
7738 cminflt -- cumulative number of minor page faults (number)
7739 cmajflt -- cumulative number of major page faults (number)
7740 utime -- user time used by the process, in (current-time) format,
7741 which is a list of integers (HIGH LOW USEC PSEC)
7742 stime -- system time used by the process (current-time)
7743 time -- sum of utime and stime (current-time)
7744 cutime -- user time used by the process and its children (current-time)
7745 cstime -- system time used by the process and its children (current-time)
7746 ctime -- sum of cutime and cstime (current-time)
7747 pri -- priority of the process (number)
7748 nice -- nice value of the process (number)
7749 thcount -- process thread count (number)
7750 start -- time the process started (current-time)
7751 vsize -- virtual memory size of the process in KB's (number)
7752 rss -- resident set size of the process in KB's (number)
7753 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7754 pcpu -- percents of CPU time used by the process (floating-point number)
7755 pmem -- percents of total physical memory used by process's resident set
7756 (floating-point number)
7757 args -- command line which invoked the process (string). */)
7760 return system_process_attributes (pid
);
7764 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7765 Invoke this after init_process_emacs, and after glib and/or GNUstep
7766 futz with the SIGCHLD handler, but before Emacs forks any children.
7767 This function's caller should block SIGCHLD. */
7770 catch_child_signal (void)
7772 struct sigaction action
, old_action
;
7774 emacs_sigaction_init (&action
, deliver_child_signal
);
7775 block_child_signal (&oldset
);
7776 sigaction (SIGCHLD
, &action
, &old_action
);
7777 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7778 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7780 if (old_action
.sa_handler
!= deliver_child_signal
)
7782 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7784 : old_action
.sa_handler
);
7785 unblock_child_signal (&oldset
);
7787 #endif /* subprocesses */
7790 /* This is not called "init_process" because that is the name of a
7791 Mach system call, so it would cause problems on Darwin systems. */
7793 init_process_emacs (void)
7798 inhibit_sentinels
= 0;
7801 if (! noninteractive
|| initialized
)
7804 #if defined HAVE_GLIB && !defined WINDOWSNT
7805 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7806 this should always fail, but is enough to initialize glib's
7807 private SIGCHLD handler, allowing catch_child_signal to copy
7808 it into lib_child_handler. */
7809 g_source_unref (g_child_watch_source_new (getpid ()));
7811 catch_child_signal ();
7814 FD_ZERO (&input_wait_mask
);
7815 FD_ZERO (&non_keyboard_wait_mask
);
7816 FD_ZERO (&non_process_wait_mask
);
7817 FD_ZERO (&write_mask
);
7818 max_process_desc
= max_input_desc
= -1;
7819 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7821 #ifdef NON_BLOCKING_CONNECT
7822 FD_ZERO (&connect_wait_mask
);
7823 num_pending_connects
= 0;
7826 process_output_delay_count
= 0;
7827 process_output_skip
= 0;
7829 /* Don't do this, it caused infinite select loops. The display
7830 method should call add_keyboard_wait_descriptor on stdin if it
7833 FD_SET (0, &input_wait_mask
);
7836 Vprocess_alist
= Qnil
;
7837 deleted_pid_list
= Qnil
;
7838 for (i
= 0; i
< FD_SETSIZE
; i
++)
7840 chan_process
[i
] = Qnil
;
7841 proc_buffered_char
[i
] = -1;
7843 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7844 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7845 #ifdef DATAGRAM_SOCKETS
7846 memset (datagram_address
, 0, sizeof datagram_address
);
7849 #if defined (DARWIN_OS)
7850 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7851 processes. As such, we only change the default value. */
7854 char const *release
= (STRINGP (Voperating_system_release
)
7855 ? SSDATA (Voperating_system_release
)
7857 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7858 Vprocess_connection_type
= Qnil
;
7862 #endif /* subprocesses */
7867 syms_of_process (void)
7871 DEFSYM (Qprocessp
, "processp");
7872 DEFSYM (Qrun
, "run");
7873 DEFSYM (Qstop
, "stop");
7874 DEFSYM (Qsignal
, "signal");
7876 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7879 DEFSYM (Qopen
, "open");
7880 DEFSYM (Qclosed
, "closed");
7881 DEFSYM (Qconnect
, "connect");
7882 DEFSYM (Qfailed
, "failed");
7883 DEFSYM (Qlisten
, "listen");
7884 DEFSYM (Qlocal
, "local");
7885 DEFSYM (Qipv4
, "ipv4");
7887 DEFSYM (Qipv6
, "ipv6");
7889 DEFSYM (Qdatagram
, "datagram");
7890 DEFSYM (Qseqpacket
, "seqpacket");
7892 DEFSYM (QCport
, ":port");
7893 DEFSYM (QCspeed
, ":speed");
7894 DEFSYM (QCprocess
, ":process");
7896 DEFSYM (QCbytesize
, ":bytesize");
7897 DEFSYM (QCstopbits
, ":stopbits");
7898 DEFSYM (QCparity
, ":parity");
7899 DEFSYM (Qodd
, "odd");
7900 DEFSYM (Qeven
, "even");
7901 DEFSYM (QCflowcontrol
, ":flowcontrol");
7904 DEFSYM (QCsummary
, ":summary");
7906 DEFSYM (Qreal
, "real");
7907 DEFSYM (Qnetwork
, "network");
7908 DEFSYM (Qserial
, "serial");
7909 DEFSYM (Qpipe
, "pipe");
7910 DEFSYM (QCbuffer
, ":buffer");
7911 DEFSYM (QChost
, ":host");
7912 DEFSYM (QCservice
, ":service");
7913 DEFSYM (QClocal
, ":local");
7914 DEFSYM (QCremote
, ":remote");
7915 DEFSYM (QCcoding
, ":coding");
7916 DEFSYM (QCserver
, ":server");
7917 DEFSYM (QCnowait
, ":nowait");
7918 DEFSYM (QCsentinel
, ":sentinel");
7919 DEFSYM (QCtls_parameters
, ":tls-parameters");
7920 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7921 DEFSYM (QClog
, ":log");
7922 DEFSYM (QCnoquery
, ":noquery");
7923 DEFSYM (QCstop
, ":stop");
7924 DEFSYM (QCplist
, ":plist");
7925 DEFSYM (QCcommand
, ":command");
7926 DEFSYM (QCconnection_type
, ":connection-type");
7927 DEFSYM (QCstderr
, ":stderr");
7928 DEFSYM (Qpty
, "pty");
7929 DEFSYM (Qpipe
, "pipe");
7931 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7933 staticpro (&Vprocess_alist
);
7934 staticpro (&deleted_pid_list
);
7936 #endif /* subprocesses */
7938 DEFSYM (QCname
, ":name");
7939 DEFSYM (QCtype
, ":type");
7941 DEFSYM (Qeuid
, "euid");
7942 DEFSYM (Qegid
, "egid");
7943 DEFSYM (Quser
, "user");
7944 DEFSYM (Qgroup
, "group");
7945 DEFSYM (Qcomm
, "comm");
7946 DEFSYM (Qstate
, "state");
7947 DEFSYM (Qppid
, "ppid");
7948 DEFSYM (Qpgrp
, "pgrp");
7949 DEFSYM (Qsess
, "sess");
7950 DEFSYM (Qttname
, "ttname");
7951 DEFSYM (Qtpgid
, "tpgid");
7952 DEFSYM (Qminflt
, "minflt");
7953 DEFSYM (Qmajflt
, "majflt");
7954 DEFSYM (Qcminflt
, "cminflt");
7955 DEFSYM (Qcmajflt
, "cmajflt");
7956 DEFSYM (Qutime
, "utime");
7957 DEFSYM (Qstime
, "stime");
7958 DEFSYM (Qtime
, "time");
7959 DEFSYM (Qcutime
, "cutime");
7960 DEFSYM (Qcstime
, "cstime");
7961 DEFSYM (Qctime
, "ctime");
7963 DEFSYM (Qinternal_default_process_sentinel
,
7964 "internal-default-process-sentinel");
7965 DEFSYM (Qinternal_default_process_filter
,
7966 "internal-default-process-filter");
7968 DEFSYM (Qpri
, "pri");
7969 DEFSYM (Qnice
, "nice");
7970 DEFSYM (Qthcount
, "thcount");
7971 DEFSYM (Qstart
, "start");
7972 DEFSYM (Qvsize
, "vsize");
7973 DEFSYM (Qrss
, "rss");
7974 DEFSYM (Qetime
, "etime");
7975 DEFSYM (Qpcpu
, "pcpu");
7976 DEFSYM (Qpmem
, "pmem");
7977 DEFSYM (Qargs
, "args");
7979 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7980 doc
: /* Non-nil means delete processes immediately when they exit.
7981 A value of nil means don't delete them until `list-processes' is run. */);
7983 delete_exited_processes
= 1;
7986 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7987 doc
: /* Control type of device used to communicate with subprocesses.
7988 Values are nil to use a pipe, or t or `pty' to use a pty.
7989 The value has no effect if the system has no ptys or if all ptys are busy:
7990 then a pipe is used in any case.
7991 The value takes effect when `start-process' is called. */);
7992 Vprocess_connection_type
= Qt
;
7994 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7995 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7996 On some systems, when Emacs reads the output from a subprocess, the output data
7997 is read in very small blocks, potentially resulting in very poor performance.
7998 This behavior can be remedied to some extent by setting this variable to a
7999 non-nil value, as it will automatically delay reading from such processes, to
8000 allow them to produce more output before Emacs tries to read it.
8001 If the value is t, the delay is reset after each write to the process; any other
8002 non-nil value means that the delay is not reset on write.
8003 The variable takes effect when `start-process' is called. */);
8004 Vprocess_adaptive_read_buffering
= Qt
;
8006 defsubr (&Sprocessp
);
8007 defsubr (&Sget_process
);
8008 defsubr (&Sdelete_process
);
8009 defsubr (&Sprocess_status
);
8010 defsubr (&Sprocess_exit_status
);
8011 defsubr (&Sprocess_id
);
8012 defsubr (&Sprocess_name
);
8013 defsubr (&Sprocess_tty_name
);
8014 defsubr (&Sprocess_command
);
8015 defsubr (&Sset_process_buffer
);
8016 defsubr (&Sprocess_buffer
);
8017 defsubr (&Sprocess_mark
);
8018 defsubr (&Sset_process_filter
);
8019 defsubr (&Sprocess_filter
);
8020 defsubr (&Sset_process_sentinel
);
8021 defsubr (&Sprocess_sentinel
);
8022 defsubr (&Sset_process_window_size
);
8023 defsubr (&Sset_process_inherit_coding_system_flag
);
8024 defsubr (&Sset_process_query_on_exit_flag
);
8025 defsubr (&Sprocess_query_on_exit_flag
);
8026 defsubr (&Sprocess_contact
);
8027 defsubr (&Sprocess_plist
);
8028 defsubr (&Sset_process_plist
);
8029 defsubr (&Sprocess_list
);
8030 defsubr (&Smake_process
);
8031 defsubr (&Smake_pipe_process
);
8032 defsubr (&Sserial_process_configure
);
8033 defsubr (&Smake_serial_process
);
8034 defsubr (&Sset_network_process_option
);
8035 defsubr (&Smake_network_process
);
8036 defsubr (&Sformat_network_address
);
8037 defsubr (&Snetwork_interface_list
);
8038 defsubr (&Snetwork_interface_info
);
8039 #ifdef DATAGRAM_SOCKETS
8040 defsubr (&Sprocess_datagram_address
);
8041 defsubr (&Sset_process_datagram_address
);
8043 defsubr (&Saccept_process_output
);
8044 defsubr (&Sprocess_send_region
);
8045 defsubr (&Sprocess_send_string
);
8046 defsubr (&Sinterrupt_process
);
8047 defsubr (&Skill_process
);
8048 defsubr (&Squit_process
);
8049 defsubr (&Sstop_process
);
8050 defsubr (&Scontinue_process
);
8051 defsubr (&Sprocess_running_child_p
);
8052 defsubr (&Sprocess_send_eof
);
8053 defsubr (&Ssignal_process
);
8054 defsubr (&Swaiting_for_user_input_p
);
8055 defsubr (&Sprocess_type
);
8056 defsubr (&Sinternal_default_process_sentinel
);
8057 defsubr (&Sinternal_default_process_filter
);
8058 defsubr (&Sset_process_coding_system
);
8059 defsubr (&Sprocess_coding_system
);
8060 defsubr (&Sset_process_filter_multibyte
);
8061 defsubr (&Sprocess_filter_multibyte_p
);
8063 #endif /* subprocesses */
8065 defsubr (&Sget_buffer_process
);
8066 defsubr (&Sprocess_inherit_coding_system_flag
);
8067 defsubr (&Slist_system_processes
);
8068 defsubr (&Sprocess_attributes
);
8071 Lisp_Object subfeatures
= Qnil
;
8072 const struct socket_options
*sopt
;
8074 #define ADD_SUBFEATURE(key, val) \
8075 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8077 #ifdef NON_BLOCKING_CONNECT
8078 ADD_SUBFEATURE (QCnowait
, Qt
);
8080 #ifdef DATAGRAM_SOCKETS
8081 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8083 #ifdef HAVE_SEQPACKET
8084 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8086 #ifdef HAVE_LOCAL_SOCKETS
8087 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8089 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8091 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8093 #ifdef HAVE_GETSOCKNAME
8094 ADD_SUBFEATURE (QCservice
, Qt
);
8096 ADD_SUBFEATURE (QCserver
, Qt
);
8098 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8099 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8101 Fprovide (intern_c_string ("make-network-process"), subfeatures
);