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>
79 #include <arpa/nameser.h>
95 #endif /* subprocesses */
101 #include "character.h"
106 #include "termopts.h"
107 #include "keyboard.h"
108 #include "blockinput.h"
110 #include "sysselect.h"
111 #include "syssignal.h"
117 #ifdef HAVE_WINDOW_SYSTEM
119 #endif /* HAVE_WINDOW_SYSTEM */
122 #include "xgselect.h"
129 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
130 struct timespec
*, void *);
133 /* Work around GCC 4.7.0 bug with strict overflow checking; see
134 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
135 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
136 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
137 # pragma GCC diagnostic ignored "-Wstrict-overflow"
140 /* True if keyboard input is on hold, zero otherwise. */
142 static bool kbd_is_on_hold
;
144 /* Nonzero means don't run process sentinels. This is used
146 bool inhibit_sentinels
;
151 # define SOCK_CLOEXEC 0
156 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
159 close_on_exec (int fd
)
162 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
167 # define accept4(sockfd, addr, addrlen, flags) \
168 process_accept4 (sockfd, addr, addrlen, flags)
170 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
172 return close_on_exec (accept (sockfd
, addr
, addrlen
));
176 process_socket (int domain
, int type
, int protocol
)
178 return close_on_exec (socket (domain
, type
, protocol
));
181 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
184 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
185 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
186 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
187 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
189 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
191 /* Number of events of change of status of a process. */
192 static EMACS_INT process_tick
;
193 /* Number of events for which the user or sentinel has been notified. */
194 static EMACS_INT update_tick
;
196 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
197 The code can be simplified by assuming NON_BLOCKING_CONNECT once
198 Emacs starts assuming POSIX 1003.1-2001 or later. */
200 #if (defined HAVE_SELECT \
201 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
202 && (defined EWOULDBLOCK || defined EINPROGRESS))
203 # define NON_BLOCKING_CONNECT
206 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
207 this system. We need to read full packets, so we need a
208 "non-destructive" select. So we require either native select,
209 or emulation of select using FIONREAD. */
211 #ifndef BROKEN_DATAGRAM_SOCKETS
212 # if defined HAVE_SELECT || defined USABLE_FIONREAD
213 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
214 # define DATAGRAM_SOCKETS
219 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
220 # define HAVE_SEQPACKET
223 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
224 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
225 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
227 /* Number of processes which have a non-zero read_output_delay,
228 and therefore might be delayed for adaptive read buffering. */
230 static int process_output_delay_count
;
232 /* True if any process has non-nil read_output_skip. */
234 static bool process_output_skip
;
236 static void create_process (Lisp_Object
, char **, Lisp_Object
);
238 static bool keyboard_bit_set (fd_set
*);
240 static void deactivate_process (Lisp_Object
);
241 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
242 static int read_process_output (Lisp_Object
, int);
243 static void handle_child_signal (int);
244 static void create_pty (Lisp_Object
);
246 static Lisp_Object
get_process (register Lisp_Object name
);
247 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
249 /* Mask of bits indicating the descriptors that we wait for input on. */
251 static fd_set input_wait_mask
;
253 /* Mask that excludes keyboard input descriptor(s). */
255 static fd_set non_keyboard_wait_mask
;
257 /* Mask that excludes process input descriptor(s). */
259 static fd_set non_process_wait_mask
;
261 /* Mask for selecting for write. */
263 static fd_set write_mask
;
265 #ifdef NON_BLOCKING_CONNECT
266 /* Mask of bits indicating the descriptors that we wait for connect to
267 complete on. Once they complete, they are removed from this mask
268 and added to the input_wait_mask and non_keyboard_wait_mask. */
270 static fd_set connect_wait_mask
;
272 /* Number of bits set in connect_wait_mask. */
273 static int num_pending_connects
;
274 #endif /* NON_BLOCKING_CONNECT */
276 /* The largest descriptor currently in use for a process object; -1 if none. */
277 static int max_process_desc
;
279 /* The largest descriptor currently in use for input; -1 if none. */
280 static int max_input_desc
;
282 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
283 static Lisp_Object chan_process
[FD_SETSIZE
];
284 #ifdef HAVE_GETADDRINFO_A
285 static void wait_for_socket_fds (Lisp_Object process
, char *name
);
288 /* Alist of elements (NAME . PROCESS). */
289 static Lisp_Object Vprocess_alist
;
291 /* Buffered-ahead input char from process, indexed by channel.
292 -1 means empty (no char is buffered).
293 Used on sys V where the only way to tell if there is any
294 output from the process is to read at least one char.
295 Always -1 on systems that support FIONREAD. */
297 static int proc_buffered_char
[FD_SETSIZE
];
299 /* Table of `struct coding-system' for each process. */
300 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
301 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
303 #ifdef DATAGRAM_SOCKETS
304 /* Table of `partner address' for datagram sockets. */
305 static struct sockaddr_and_len
{
308 } datagram_address
[FD_SETSIZE
];
309 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
310 #define DATAGRAM_CONN_P(proc) \
311 (PROCESSP (proc) && \
312 XPROCESS (proc)->infd >= 0 && \
313 datagram_address[XPROCESS (proc)->infd].sa != 0)
315 #define DATAGRAM_CHAN_P(chan) (0)
316 #define DATAGRAM_CONN_P(proc) (0)
319 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
320 a `for' loop which iterates over processes from Vprocess_alist. */
322 #define FOR_EACH_PROCESS(list_var, proc_var) \
323 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
325 /* These setters are used only in this file, so they can be private. */
327 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
332 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
337 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
339 p
->decode_coding_system
= val
;
342 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
344 p
->decoding_buf
= val
;
347 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
349 p
->encode_coding_system
= val
;
352 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
354 p
->encoding_buf
= val
;
357 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
359 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
362 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
367 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
372 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
377 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
382 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
384 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
387 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
392 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
397 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
399 p
->write_queue
= val
;
402 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
409 make_lisp_proc (struct Lisp_Process
*p
)
411 return make_lisp_ptr (p
, Lisp_Vectorlike
);
414 static struct fd_callback_data
420 int condition
; /* Mask of the defines above. */
421 } fd_callback_info
[FD_SETSIZE
];
424 /* Add a file descriptor FD to be monitored for when read is possible.
425 When read is possible, call FUNC with argument DATA. */
428 add_read_fd (int fd
, fd_callback func
, void *data
)
430 add_keyboard_wait_descriptor (fd
);
432 fd_callback_info
[fd
].func
= func
;
433 fd_callback_info
[fd
].data
= data
;
434 fd_callback_info
[fd
].condition
|= FOR_READ
;
437 /* Stop monitoring file descriptor FD for when read is possible. */
440 delete_read_fd (int fd
)
442 delete_keyboard_wait_descriptor (fd
);
444 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
445 if (fd_callback_info
[fd
].condition
== 0)
447 fd_callback_info
[fd
].func
= 0;
448 fd_callback_info
[fd
].data
= 0;
452 /* Add a file descriptor FD to be monitored for when write is possible.
453 When write is possible, call FUNC with argument DATA. */
456 add_write_fd (int fd
, fd_callback func
, void *data
)
458 FD_SET (fd
, &write_mask
);
459 if (fd
> max_input_desc
)
462 fd_callback_info
[fd
].func
= func
;
463 fd_callback_info
[fd
].data
= data
;
464 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
467 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
470 delete_input_desc (int fd
)
472 if (fd
== max_input_desc
)
476 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
477 || FD_ISSET (fd
, &write_mask
)));
483 /* Stop monitoring file descriptor FD for when write is possible. */
486 delete_write_fd (int fd
)
488 FD_CLR (fd
, &write_mask
);
489 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
490 if (fd_callback_info
[fd
].condition
== 0)
492 fd_callback_info
[fd
].func
= 0;
493 fd_callback_info
[fd
].data
= 0;
494 delete_input_desc (fd
);
499 /* Compute the Lisp form of the process status, p->status, from
500 the numeric status that was returned by `wait'. */
502 static Lisp_Object
status_convert (int);
505 update_status (struct Lisp_Process
*p
)
507 eassert (p
->raw_status_new
);
508 pset_status (p
, status_convert (p
->raw_status
));
509 p
->raw_status_new
= 0;
512 /* Convert a process status word in Unix format to
513 the list that we use internally. */
516 status_convert (int w
)
519 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
520 else if (WIFEXITED (w
))
521 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
522 WCOREDUMP (w
) ? Qt
: Qnil
));
523 else if (WIFSIGNALED (w
))
524 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
525 WCOREDUMP (w
) ? Qt
: Qnil
));
530 /* Given a status-list, extract the three pieces of information
531 and store them individually through the three pointers. */
534 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
548 *code
= XFASTINT (XCAR (tem
));
550 *coredump
= !NILP (tem
);
554 /* Return a string describing a process status list. */
557 status_message (struct Lisp_Process
*p
)
559 Lisp_Object status
= p
->status
;
565 decode_status (status
, &symbol
, &code
, &coredump
);
567 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
570 synchronize_system_messages_locale ();
571 signame
= strsignal (code
);
573 string
= build_string ("unknown");
578 string
= build_unibyte_string (signame
);
579 if (! NILP (Vlocale_coding_system
))
580 string
= (code_convert_string_norecord
581 (string
, Vlocale_coding_system
, 0));
582 c1
= STRING_CHAR (SDATA (string
));
585 Faset (string
, make_number (0), make_number (c2
));
587 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
588 return concat2 (string
, suffix
);
590 else if (EQ (symbol
, Qexit
))
593 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
595 return build_string ("finished\n");
596 AUTO_STRING (prefix
, "exited abnormally with code ");
597 string
= Fnumber_to_string (make_number (code
));
598 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
599 return concat3 (prefix
, string
, suffix
);
601 else if (EQ (symbol
, Qfailed
))
603 AUTO_STRING (prefix
, "failed with code ");
604 string
= Fnumber_to_string (make_number (code
));
605 AUTO_STRING (suffix
, "\n");
606 return concat3 (prefix
, string
, suffix
);
609 return Fcopy_sequence (Fsymbol_name (symbol
));
612 enum { PTY_NAME_SIZE
= 24 };
614 /* Open an available pty, returning a file descriptor.
615 Store into PTY_NAME the file name of the terminal corresponding to the pty.
616 Return -1 on failure. */
619 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
628 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
629 for (i
= 0; i
< 16; i
++)
632 #ifdef PTY_NAME_SPRINTF
635 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
636 #endif /* no PTY_NAME_SPRINTF */
640 #else /* no PTY_OPEN */
641 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
642 #endif /* no PTY_OPEN */
646 #ifdef PTY_TTY_NAME_SPRINTF
649 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
650 #endif /* no PTY_TTY_NAME_SPRINTF */
652 /* Set FD's close-on-exec flag. This is needed even if
653 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
654 doesn't require support for that combination.
655 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
656 doesn't work if the close-on-exec flag is set (Bug#20555).
657 Multithreaded platforms where posix_openpt ignores
658 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
659 have a race condition between the PTY_OPEN and here. */
660 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
662 /* Check to make certain that both sides are available.
663 This avoids a nasty yet stupid bug in rlogins. */
664 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
677 #endif /* HAVE_PTYS */
681 /* Allocate basically initialized process. */
683 static struct Lisp_Process
*
684 allocate_process (void)
686 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
690 make_process (Lisp_Object name
)
692 register Lisp_Object val
, tem
, name1
;
693 register struct Lisp_Process
*p
;
694 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
697 p
= allocate_process ();
698 /* Initialize Lisp data. Note that allocate_process initializes all
699 Lisp data to nil, so do it only for slots which should not be nil. */
700 pset_status (p
, Qrun
);
701 pset_mark (p
, Fmake_marker ());
703 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
704 non-Lisp data, so do it only for slots which should not be zero. */
707 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
711 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
712 p
->gnutls_boot_parameters
= Qnil
;
715 /* If name is already in use, modify it until it is unused. */
720 tem
= Fget_process (name1
);
721 if (NILP (tem
)) break;
722 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
726 pset_sentinel (p
, Qinternal_default_process_sentinel
);
727 pset_filter (p
, Qinternal_default_process_filter
);
728 XSETPROCESS (val
, p
);
729 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
734 remove_process (register Lisp_Object proc
)
736 register Lisp_Object pair
;
738 pair
= Frassq (proc
, Vprocess_alist
);
739 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
741 deactivate_process (proc
);
744 #ifdef HAVE_GETADDRINFO_A
746 free_dns_request (Lisp_Object proc
)
748 struct Lisp_Process
*p
= XPROCESS (proc
);
750 if (p
->dns_requests
[0]->ar_result
)
751 freeaddrinfo (p
->dns_requests
[0]->ar_result
);
752 xfree ((void *)p
->dns_requests
[0]->ar_request
);
753 xfree ((void *)p
->dns_requests
[0]->ar_name
);
754 xfree ((void *)p
->dns_requests
[0]->ar_service
);
755 xfree (p
->dns_requests
[0]);
756 xfree (p
->dns_requests
);
757 p
->dns_requests
= NULL
;
762 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
763 doc
: /* Return t if OBJECT is a process. */)
766 return PROCESSP (object
) ? Qt
: Qnil
;
769 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
770 doc
: /* Return the process named NAME, or nil if there is none. */)
771 (register Lisp_Object name
)
776 return Fcdr (Fassoc (name
, Vprocess_alist
));
779 /* This is how commands for the user decode process arguments. It
780 accepts a process, a process name, a buffer, a buffer name, or nil.
781 Buffers denote the first process in the buffer, and nil denotes the
785 get_process (register Lisp_Object name
)
787 register Lisp_Object proc
, obj
;
790 obj
= Fget_process (name
);
792 obj
= Fget_buffer (name
);
794 error ("Process %s does not exist", SDATA (name
));
796 else if (NILP (name
))
797 obj
= Fcurrent_buffer ();
801 /* Now obj should be either a buffer object or a process object. */
804 if (NILP (BVAR (XBUFFER (obj
), name
)))
805 error ("Attempt to get process for a dead buffer");
806 proc
= Fget_buffer_process (obj
);
808 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
819 /* Fdelete_process promises to immediately forget about the process, but in
820 reality, Emacs needs to remember those processes until they have been
821 treated by the SIGCHLD handler and waitpid has been invoked on them;
822 otherwise they might fill up the kernel's process table.
824 Some processes created by call-process are also put onto this list.
826 Members of this list are (process-ID . filename) pairs. The
827 process-ID is a number; the filename, if a string, is a file that
828 needs to be removed after the process exits. */
829 static Lisp_Object deleted_pid_list
;
832 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
834 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
835 /* GC treated elements set to nil. */
836 Fdelq (Qnil
, deleted_pid_list
));
840 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
841 doc
: /* Delete PROCESS: kill it and forget about it immediately.
842 PROCESS may be a process, a buffer, the name of a process or buffer, or
843 nil, indicating the current buffer's process. */)
844 (register Lisp_Object process
)
846 register struct Lisp_Process
*p
;
848 process
= get_process (process
);
849 p
= XPROCESS (process
);
851 #ifdef HAVE_GETADDRINFO_A
854 gai_cancel (p
->dns_requests
[0]);
855 free_dns_request (process
);
859 p
->raw_status_new
= 0;
860 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
862 pset_status (p
, list2 (Qexit
, make_number (0)));
863 p
->tick
= ++process_tick
;
864 status_notify (p
, NULL
);
865 redisplay_preserve_echo_area (13);
870 record_kill_process (p
, Qnil
);
874 /* Update P's status, since record_kill_process will make the
875 SIGCHLD handler update deleted_pid_list, not *P. */
877 if (p
->raw_status_new
)
879 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
880 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
881 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
883 p
->tick
= ++process_tick
;
884 status_notify (p
, NULL
);
885 redisplay_preserve_echo_area (13);
888 remove_process (process
);
892 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
893 doc
: /* Return the status of PROCESS.
894 The returned value is one of the following symbols:
895 run -- for a process that is running.
896 stop -- for a process stopped but continuable.
897 exit -- for a process that has exited.
898 signal -- for a process that has got a fatal signal.
899 open -- for a network stream connection that is open.
900 listen -- for a network stream server that is listening.
901 closed -- for a network stream connection that is closed.
902 connect -- when waiting for a non-blocking connection to complete.
903 failed -- when a non-blocking connection has failed.
904 nil -- if arg is a process name and no such process exists.
905 PROCESS may be a process, a buffer, the name of a process, or
906 nil, indicating the current buffer's process. */)
907 (register Lisp_Object process
)
909 register struct Lisp_Process
*p
;
910 register Lisp_Object status
;
912 if (STRINGP (process
))
913 process
= Fget_process (process
);
915 process
= get_process (process
);
920 p
= XPROCESS (process
);
921 if (p
->raw_status_new
)
925 status
= XCAR (status
);
926 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
928 if (EQ (status
, Qexit
))
930 else if (EQ (p
->command
, Qt
))
932 else if (EQ (status
, Qrun
))
938 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
940 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
941 If PROCESS has not yet exited or died, return 0. */)
942 (register Lisp_Object process
)
944 CHECK_PROCESS (process
);
945 if (XPROCESS (process
)->raw_status_new
)
946 update_status (XPROCESS (process
));
947 if (CONSP (XPROCESS (process
)->status
))
948 return XCAR (XCDR (XPROCESS (process
)->status
));
949 return make_number (0);
952 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
953 doc
: /* Return the process id of PROCESS.
954 This is the pid of the external process which PROCESS uses or talks to.
955 For a network connection, this value is nil. */)
956 (register Lisp_Object process
)
960 CHECK_PROCESS (process
);
961 pid
= XPROCESS (process
)->pid
;
962 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
965 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
966 doc
: /* Return the name of PROCESS, as a string.
967 This is the name of the program invoked in PROCESS,
968 possibly modified to make it unique among process names. */)
969 (register Lisp_Object process
)
971 CHECK_PROCESS (process
);
972 return XPROCESS (process
)->name
;
975 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
976 doc
: /* Return the command that was executed to start PROCESS.
977 This is a list of strings, the first string being the program executed
978 and the rest of the strings being the arguments given to it.
979 For a network or serial process, this is nil (process is running) or t
980 (process is stopped). */)
981 (register Lisp_Object process
)
983 CHECK_PROCESS (process
);
984 return XPROCESS (process
)->command
;
987 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
988 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
989 This is the terminal that the process itself reads and writes on,
990 not the name of the pty that Emacs uses to talk with that terminal. */)
991 (register Lisp_Object process
)
993 CHECK_PROCESS (process
);
994 return XPROCESS (process
)->tty_name
;
997 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
999 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1001 (register Lisp_Object process
, Lisp_Object buffer
)
1003 struct Lisp_Process
*p
;
1005 CHECK_PROCESS (process
);
1007 CHECK_BUFFER (buffer
);
1008 p
= XPROCESS (process
);
1009 pset_buffer (p
, buffer
);
1010 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1011 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1012 setup_process_coding_systems (process
);
1016 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1018 doc
: /* Return the buffer PROCESS is associated with.
1019 The default process filter inserts output from PROCESS into this buffer. */)
1020 (register Lisp_Object process
)
1022 CHECK_PROCESS (process
);
1023 return XPROCESS (process
)->buffer
;
1026 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1028 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1029 (register Lisp_Object process
)
1031 CHECK_PROCESS (process
);
1032 return XPROCESS (process
)->mark
;
1036 set_process_filter_masks (struct Lisp_Process
*p
)
1038 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1040 FD_CLR (p
->infd
, &input_wait_mask
);
1041 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1043 else if (EQ (p
->filter
, Qt
)
1044 /* Network or serial process not stopped: */
1045 && !EQ (p
->command
, Qt
))
1047 FD_SET (p
->infd
, &input_wait_mask
);
1048 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1052 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1054 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1055 A value of t means stop accepting output from the process.
1057 When a process has a non-default filter, its buffer is not used for output.
1058 Instead, each time it does output, the entire string of output is
1059 passed to the filter.
1061 The filter gets two arguments: the process and the string of output.
1062 The string argument is normally a multibyte string, except:
1063 - if the process's input coding system is no-conversion or raw-text,
1064 it is a unibyte string (the non-converted input), or else
1065 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1066 string (the result of converting the decoded input multibyte
1067 string to unibyte with `string-make-unibyte'). */)
1068 (register Lisp_Object process
, Lisp_Object filter
)
1070 struct Lisp_Process
*p
;
1072 CHECK_PROCESS (process
);
1074 p
= XPROCESS (process
);
1076 /* Don't signal an error if the process's input file descriptor
1077 is closed. This could make debugging Lisp more difficult,
1078 for example when doing something like
1080 (setq process (start-process ...))
1082 (set-process-filter process ...) */
1085 filter
= Qinternal_default_process_filter
;
1087 pset_filter (p
, filter
);
1090 set_process_filter_masks (p
);
1092 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1093 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1094 setup_process_coding_systems (process
);
1098 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1100 doc
: /* Return the filter function of PROCESS.
1101 See `set-process-filter' for more info on filter functions. */)
1102 (register Lisp_Object process
)
1104 CHECK_PROCESS (process
);
1105 return XPROCESS (process
)->filter
;
1108 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1110 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1111 The sentinel is called as a function when the process changes state.
1112 It gets two arguments: the process, and a string describing the change. */)
1113 (register Lisp_Object process
, Lisp_Object sentinel
)
1115 struct Lisp_Process
*p
;
1117 CHECK_PROCESS (process
);
1118 p
= XPROCESS (process
);
1120 if (NILP (sentinel
))
1121 sentinel
= Qinternal_default_process_sentinel
;
1123 pset_sentinel (p
, sentinel
);
1124 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1125 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1129 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1131 doc
: /* Return the sentinel of PROCESS.
1132 See `set-process-sentinel' for more info on sentinels. */)
1133 (register Lisp_Object process
)
1135 CHECK_PROCESS (process
);
1136 return XPROCESS (process
)->sentinel
;
1139 DEFUN ("set-process-window-size", Fset_process_window_size
,
1140 Sset_process_window_size
, 3, 3, 0,
1141 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1142 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1144 CHECK_PROCESS (process
);
1146 /* All known platforms store window sizes as 'unsigned short'. */
1147 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1148 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1150 if (NETCONN_P (process
)
1151 || XPROCESS (process
)->infd
< 0
1152 || (set_window_size (XPROCESS (process
)->infd
,
1153 XINT (height
), XINT (width
))
1160 DEFUN ("set-process-inherit-coding-system-flag",
1161 Fset_process_inherit_coding_system_flag
,
1162 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1163 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1164 If the second argument FLAG is non-nil, then the variable
1165 `buffer-file-coding-system' of the buffer associated with PROCESS
1166 will be bound to the value of the coding system used to decode
1169 This is useful when the coding system specified for the process buffer
1170 leaves either the character code conversion or the end-of-line conversion
1171 unspecified, or if the coding system used to decode the process output
1172 is more appropriate for saving the process buffer.
1174 Binding the variable `inherit-process-coding-system' to non-nil before
1175 starting the process is an alternative way of setting the inherit flag
1176 for the process which will run.
1178 This function returns FLAG. */)
1179 (register Lisp_Object process
, Lisp_Object flag
)
1181 CHECK_PROCESS (process
);
1182 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1186 DEFUN ("set-process-query-on-exit-flag",
1187 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1189 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1190 If the second argument FLAG is non-nil, Emacs will query the user before
1191 exiting or killing a buffer if PROCESS is running. This function
1193 (register Lisp_Object process
, Lisp_Object flag
)
1195 CHECK_PROCESS (process
);
1196 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1200 DEFUN ("process-query-on-exit-flag",
1201 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1203 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1204 (register Lisp_Object process
)
1206 CHECK_PROCESS (process
);
1207 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1210 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1212 doc
: /* Return the contact info of PROCESS; t for a real child.
1213 For a network or serial connection, the value depends on the optional
1214 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1215 SERVICE) for a network connection or (PORT SPEED) for a serial
1216 connection. If KEY is t, the complete contact information for the
1217 connection is returned, else the specific value for the keyword KEY is
1218 returned. See `make-network-process' or `make-serial-process' for a
1219 list of keywords. */)
1220 (register Lisp_Object process
, Lisp_Object key
)
1222 Lisp_Object contact
;
1224 CHECK_PROCESS (process
);
1225 contact
= XPROCESS (process
)->childp
;
1227 #ifdef DATAGRAM_SOCKETS
1229 if (NETCONN_P (process
))
1230 wait_for_socket_fds (process
, "process-contact");
1232 if (DATAGRAM_CONN_P (process
)
1233 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1234 contact
= Fplist_put (contact
, QCremote
,
1235 Fprocess_datagram_address (process
));
1238 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1241 if (NILP (key
) && NETCONN_P (process
))
1242 return list2 (Fplist_get (contact
, QChost
),
1243 Fplist_get (contact
, QCservice
));
1244 if (NILP (key
) && SERIALCONN_P (process
))
1245 return list2 (Fplist_get (contact
, QCport
),
1246 Fplist_get (contact
, QCspeed
));
1247 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1248 if the pipe process is useful for purposes other than receiving
1250 if (NILP (key
) && PIPECONN_P (process
))
1252 return Fplist_get (contact
, key
);
1255 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1257 doc
: /* Return the plist of PROCESS. */)
1258 (register Lisp_Object process
)
1260 CHECK_PROCESS (process
);
1261 return XPROCESS (process
)->plist
;
1264 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1266 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1267 (register Lisp_Object process
, Lisp_Object plist
)
1269 CHECK_PROCESS (process
);
1272 pset_plist (XPROCESS (process
), plist
);
1276 #if 0 /* Turned off because we don't currently record this info
1277 in the process. Perhaps add it. */
1278 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1279 doc
: /* Return the connection type of PROCESS.
1280 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1281 a socket connection. */)
1282 (Lisp_Object process
)
1284 return XPROCESS (process
)->type
;
1288 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1289 doc
: /* Return the connection type of PROCESS.
1290 The value is either the symbol `real', `network', or `serial'.
1291 PROCESS may be a process, a buffer, the name of a process or buffer, or
1292 nil, indicating the current buffer's process. */)
1293 (Lisp_Object process
)
1296 proc
= get_process (process
);
1297 return XPROCESS (proc
)->type
;
1300 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1302 doc
: /* Convert network ADDRESS from internal format to a string.
1303 A 4 or 5 element vector represents an IPv4 address (with port number).
1304 An 8 or 9 element vector represents an IPv6 address (with port number).
1305 If optional second argument OMIT-PORT is non-nil, don't include a port
1306 number in the string, even when present in ADDRESS.
1307 Returns nil if format of ADDRESS is invalid. */)
1308 (Lisp_Object address
, Lisp_Object omit_port
)
1313 if (STRINGP (address
)) /* AF_LOCAL */
1316 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1318 register struct Lisp_Vector
*p
= XVECTOR (address
);
1319 ptrdiff_t size
= p
->header
.size
;
1320 Lisp_Object args
[10];
1324 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1326 format
= "%d.%d.%d.%d";
1331 format
= "%d.%d.%d.%d:%d";
1334 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1336 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1341 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1347 AUTO_STRING (format_obj
, format
);
1348 args
[0] = format_obj
;
1350 for (i
= 0; i
< nargs
; i
++)
1352 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1355 if (nargs
<= 5 /* IPv4 */
1356 && i
< 4 /* host, not port */
1357 && XINT (p
->contents
[i
]) > 255)
1360 args
[i
+ 1] = p
->contents
[i
];
1363 return Fformat (nargs
+ 1, args
);
1366 if (CONSP (address
))
1368 AUTO_STRING (format
, "<Family %d>");
1369 return CALLN (Fformat
, format
, Fcar (address
));
1375 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1376 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1379 return Fmapcar (Qcdr
, Vprocess_alist
);
1382 /* Starting asynchronous inferior processes. */
1384 static void start_process_unwind (Lisp_Object proc
);
1386 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1387 doc
: /* Start a program in a subprocess. Return the process object for it.
1389 This is similar to `start-process', but arguments are specified as
1390 keyword/argument pairs. The following arguments are defined:
1392 :name NAME -- NAME is name for process. It is modified if necessary
1395 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1396 with the process. Process output goes at end of that buffer, unless
1397 you specify an output stream or filter function to handle the output.
1398 BUFFER may be also nil, meaning that this process is not associated
1401 :command COMMAND -- COMMAND is a list starting with the program file
1402 name, followed by strings to give to the program as arguments.
1404 :coding CODING -- If CODING is a symbol, it specifies the coding
1405 system used for both reading and writing for this process. If CODING
1406 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1407 ENCODING is used for writing.
1409 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1410 the process is running. If BOOL is not given, query before exiting.
1412 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1413 In the stopped state, a process does not accept incoming data, but you
1414 can send outgoing data. The stopped state is cleared by
1415 `continue-process' and set by `stop-process'.
1417 :connection-type TYPE -- TYPE is control type of device used to
1418 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1419 to use a pty, or nil to use the default specified through
1420 `process-connection-type'.
1422 :filter FILTER -- Install FILTER as the process filter.
1424 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1426 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1427 to the standard error of subprocess. Specifying this implies
1428 `:connection-type' is set to `pipe'.
1430 usage: (make-process &rest ARGS) */)
1431 (ptrdiff_t nargs
, Lisp_Object
*args
)
1433 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1434 Lisp_Object xstderr
, stderrproc
;
1435 ptrdiff_t count
= SPECPDL_INDEX ();
1441 /* Save arguments for process-contact and clone-process. */
1442 contact
= Flist (nargs
, args
);
1444 buffer
= Fplist_get (contact
, QCbuffer
);
1446 buffer
= Fget_buffer_create (buffer
);
1448 /* Make sure that the child will be able to chdir to the current
1449 buffer's current directory, or its unhandled equivalent. We
1450 can't just have the child check for an error when it does the
1451 chdir, since it's in a vfork. */
1452 current_dir
= encode_current_directory ();
1454 name
= Fplist_get (contact
, QCname
);
1455 CHECK_STRING (name
);
1457 command
= Fplist_get (contact
, QCcommand
);
1458 if (CONSP (command
))
1459 program
= XCAR (command
);
1463 if (!NILP (program
))
1464 CHECK_STRING (program
);
1467 xstderr
= Fplist_get (contact
, QCstderr
);
1468 if (PROCESSP (xstderr
))
1470 if (!PIPECONN_P (xstderr
))
1471 error ("Process is not a pipe process");
1472 stderrproc
= xstderr
;
1474 else if (!NILP (xstderr
))
1476 CHECK_STRING (program
);
1477 stderrproc
= CALLN (Fmake_pipe_process
,
1479 concat2 (name
, build_string (" stderr")),
1481 Fget_buffer_create (xstderr
));
1484 proc
= make_process (name
);
1485 /* If an error occurs and we can't start the process, we want to
1486 remove it from the process list. This means that each error
1487 check in create_process doesn't need to call remove_process
1488 itself; it's all taken care of here. */
1489 record_unwind_protect (start_process_unwind
, proc
);
1491 pset_childp (XPROCESS (proc
), Qt
);
1492 pset_plist (XPROCESS (proc
), Qnil
);
1493 pset_type (XPROCESS (proc
), Qreal
);
1494 pset_buffer (XPROCESS (proc
), buffer
);
1495 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1496 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1497 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1499 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1500 XPROCESS (proc
)->kill_without_query
= 1;
1501 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1502 pset_command (XPROCESS (proc
), Qt
);
1504 tem
= Fplist_get (contact
, QCconnection_type
);
1506 XPROCESS (proc
)->pty_flag
= true;
1507 else if (EQ (tem
, Qpipe
))
1508 XPROCESS (proc
)->pty_flag
= false;
1509 else if (NILP (tem
))
1510 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1512 report_file_error ("Unknown connection type", tem
);
1514 if (!NILP (stderrproc
))
1516 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1518 XPROCESS (proc
)->pty_flag
= false;
1522 /* AKA GNUTLS_INITSTAGE(proc). */
1523 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1524 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1527 XPROCESS (proc
)->adaptive_read_buffering
1528 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1529 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1531 /* Make the process marker point into the process buffer (if any). */
1532 if (BUFFERP (buffer
))
1533 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1534 BUF_ZV (XBUFFER (buffer
)),
1535 BUF_ZV_BYTE (XBUFFER (buffer
)));
1538 /* Decide coding systems for communicating with the process. Here
1539 we don't setup the structure coding_system nor pay attention to
1540 unibyte mode. They are done in create_process. */
1542 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1543 Lisp_Object coding_systems
= Qt
;
1544 Lisp_Object val
, *args2
;
1546 tem
= Fplist_get (contact
, QCcoding
);
1554 val
= Vcoding_system_for_read
;
1557 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1559 SAFE_ALLOCA_LISP (args2
, nargs2
);
1561 args2
[i
++] = Qstart_process
;
1563 args2
[i
++] = buffer
;
1564 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1565 args2
[i
++] = XCAR (tem2
);
1566 if (!NILP (program
))
1567 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1568 if (CONSP (coding_systems
))
1569 val
= XCAR (coding_systems
);
1570 else if (CONSP (Vdefault_process_coding_system
))
1571 val
= XCAR (Vdefault_process_coding_system
);
1573 pset_decode_coding_system (XPROCESS (proc
), val
);
1582 val
= Vcoding_system_for_write
;
1585 if (EQ (coding_systems
, Qt
))
1587 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1589 SAFE_ALLOCA_LISP (args2
, nargs2
);
1591 args2
[i
++] = Qstart_process
;
1593 args2
[i
++] = buffer
;
1594 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1595 args2
[i
++] = XCAR (tem2
);
1596 if (!NILP (program
))
1597 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1599 if (CONSP (coding_systems
))
1600 val
= XCDR (coding_systems
);
1601 else if (CONSP (Vdefault_process_coding_system
))
1602 val
= XCDR (Vdefault_process_coding_system
);
1604 pset_encode_coding_system (XPROCESS (proc
), val
);
1605 /* Note: At this moment, the above coding system may leave
1606 text-conversion or eol-conversion unspecified. They will be
1607 decided after we read output from the process and decode it by
1608 some coding system, or just before we actually send a text to
1613 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1614 XPROCESS (proc
)->decoding_carryover
= 0;
1615 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1617 XPROCESS (proc
)->inherit_coding_system_flag
1618 = !(NILP (buffer
) || !inherit_process_coding_system
);
1620 if (!NILP (program
))
1622 Lisp_Object program_args
= XCDR (command
);
1624 /* If program file name is not absolute, search our path for it.
1625 Put the name we will really use in TEM. */
1626 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1627 && !(SCHARS (program
) > 1
1628 && IS_DEVICE_SEP (SREF (program
, 1))))
1631 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1632 make_number (X_OK
), false);
1634 report_file_error ("Searching for program", program
);
1635 tem
= Fexpand_file_name (tem
, Qnil
);
1639 if (!NILP (Ffile_directory_p (program
)))
1640 error ("Specified program for new process is a directory");
1644 /* Remove "/:" from TEM. */
1645 tem
= remove_slash_colon (tem
);
1647 Lisp_Object arg_encoding
= Qnil
;
1649 /* Encode the file name and put it in NEW_ARGV.
1650 That's where the child will use it to execute the program. */
1651 tem
= list1 (ENCODE_FILE (tem
));
1652 ptrdiff_t new_argc
= 1;
1654 /* Here we encode arguments by the coding system used for sending
1655 data to the process. We don't support using different coding
1656 systems for encoding arguments and for encoding data sent to the
1659 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1661 Lisp_Object arg
= XCAR (tem2
);
1663 if (STRING_MULTIBYTE (arg
))
1665 if (NILP (arg_encoding
))
1666 arg_encoding
= (complement_process_encoding_system
1667 (XPROCESS (proc
)->encode_coding_system
));
1668 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1670 tem
= Fcons (arg
, tem
);
1674 /* Now that everything is encoded we can collect the strings into
1677 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1678 new_argv
[new_argc
] = 0;
1680 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1682 new_argv
[i
] = SSDATA (XCAR (tem
));
1686 create_process (proc
, new_argv
, current_dir
);
1692 return unbind_to (count
, proc
);
1695 /* This function is the unwind_protect form for Fstart_process. If
1696 PROC doesn't have its pid set, then we know someone has signaled
1697 an error and the process wasn't started successfully, so we should
1698 remove it from the process list. */
1700 start_process_unwind (Lisp_Object proc
)
1702 if (!PROCESSP (proc
))
1705 /* Was PROC started successfully?
1706 -2 is used for a pty with no process, eg for gdb. */
1707 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1708 remove_process (proc
);
1711 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1714 close_process_fd (int *fd_addr
)
1724 /* Indexes of file descriptors in open_fds. */
1727 /* The pipe from Emacs to its subprocess. */
1729 WRITE_TO_SUBPROCESS
,
1731 /* The main pipe from the subprocess to Emacs. */
1732 READ_FROM_SUBPROCESS
,
1735 /* The pipe from the subprocess to Emacs that is closed when the
1736 subprocess execs. */
1737 READ_FROM_EXEC_MONITOR
,
1741 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1744 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1746 struct Lisp_Process
*p
= XPROCESS (process
);
1747 int inchannel
, outchannel
;
1750 int forkin
, forkout
, forkerr
= -1;
1752 char pty_name
[PTY_NAME_SIZE
];
1753 Lisp_Object lisp_pty_name
= Qnil
;
1756 inchannel
= outchannel
= -1;
1759 outchannel
= inchannel
= allocate_pty (pty_name
);
1763 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1764 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1765 /* On most USG systems it does not work to open the pty's tty here,
1766 then close it and reopen it in the child. */
1767 /* Don't let this terminal become our controlling terminal
1768 (in case we don't have one). */
1769 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1771 report_file_error ("Opening pty", Qnil
);
1772 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1774 forkin
= forkout
= -1;
1775 #endif /* not USG, or USG_SUBTTY_WORKS */
1777 lisp_pty_name
= build_string (pty_name
);
1781 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1782 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1783 report_file_error ("Creating pipe", Qnil
);
1784 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1785 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1786 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1787 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1789 if (!NILP (p
->stderrproc
))
1791 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1793 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1795 /* Close unnecessary file descriptors. */
1796 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1797 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1802 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1803 report_file_error ("Creating pipe", Qnil
);
1806 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1807 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1809 /* Record this as an active process, with its channels. */
1810 chan_process
[inchannel
] = process
;
1811 p
->infd
= inchannel
;
1812 p
->outfd
= outchannel
;
1814 /* Previously we recorded the tty descriptor used in the subprocess.
1815 It was only used for getting the foreground tty process, so now
1816 we just reopen the device (see emacs_get_tty_pgrp) as this is
1817 more portable (see USG_SUBTTY_WORKS above). */
1819 p
->pty_flag
= pty_flag
;
1820 pset_status (p
, Qrun
);
1822 if (!EQ (p
->command
, Qt
))
1824 FD_SET (inchannel
, &input_wait_mask
);
1825 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1828 if (inchannel
> max_process_desc
)
1829 max_process_desc
= inchannel
;
1831 /* This may signal an error. */
1832 setup_process_coding_systems (process
);
1835 block_child_signal (&oldset
);
1838 /* vfork, and prevent local vars from being clobbered by the vfork. */
1839 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1840 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1841 char **volatile new_argv_volatile
= new_argv
;
1842 int volatile forkin_volatile
= forkin
;
1843 int volatile forkout_volatile
= forkout
;
1844 int volatile forkerr_volatile
= forkerr
;
1845 struct Lisp_Process
*p_volatile
= p
;
1849 current_dir
= current_dir_volatile
;
1850 lisp_pty_name
= lisp_pty_name_volatile
;
1851 new_argv
= new_argv_volatile
;
1852 forkin
= forkin_volatile
;
1853 forkout
= forkout_volatile
;
1854 forkerr
= forkerr_volatile
;
1857 pty_flag
= p
->pty_flag
;
1860 #endif /* not WINDOWSNT */
1862 /* Make the pty be the controlling terminal of the process. */
1864 /* First, disconnect its current controlling terminal. */
1865 /* We tried doing setsid only if pty_flag, but it caused
1866 process_set_signal to fail on SGI when using a pipe. */
1868 /* Make the pty's terminal the controlling terminal. */
1869 if (pty_flag
&& forkin
>= 0)
1872 /* We ignore the return value
1873 because faith@cs.unc.edu says that is necessary on Linux. */
1874 ioctl (forkin
, TIOCSCTTY
, 0);
1877 #if defined (LDISC1)
1878 if (pty_flag
&& forkin
>= 0)
1881 tcgetattr (forkin
, &t
);
1883 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1884 emacs_perror ("create_process/tcsetattr LDISC1");
1887 #if defined (NTTYDISC) && defined (TIOCSETD)
1888 if (pty_flag
&& forkin
>= 0)
1890 /* Use new line discipline. */
1891 int ldisc
= NTTYDISC
;
1892 ioctl (forkin
, TIOCSETD
, &ldisc
);
1897 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1898 can do TIOCSPGRP only to the process's controlling tty. */
1901 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1902 I can't test it since I don't have 4.3. */
1903 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1906 ioctl (j
, TIOCNOTTY
, 0);
1910 #endif /* TIOCNOTTY */
1912 #if !defined (DONT_REOPEN_PTY)
1913 /*** There is a suggestion that this ought to be a
1914 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1915 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1916 that system does seem to need this code, even though
1917 both TIOCSCTTY is defined. */
1918 /* Now close the pty (if we had it open) and reopen it.
1919 This makes the pty the controlling terminal of the subprocess. */
1923 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1926 emacs_close (forkin
);
1927 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1931 emacs_perror (SSDATA (lisp_pty_name
));
1932 _exit (EXIT_CANCELED
);
1936 #endif /* not DONT_REOPEN_PTY */
1938 #ifdef SETUP_SLAVE_PTY
1943 #endif /* SETUP_SLAVE_PTY */
1944 #endif /* HAVE_PTYS */
1946 signal (SIGINT
, SIG_DFL
);
1947 signal (SIGQUIT
, SIG_DFL
);
1949 signal (SIGPROF
, SIG_DFL
);
1952 /* Emacs ignores SIGPIPE, but the child should not. */
1953 signal (SIGPIPE
, SIG_DFL
);
1955 /* Stop blocking SIGCHLD in the child. */
1956 unblock_child_signal (&oldset
);
1959 child_setup_tty (forkout
);
1964 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1965 #else /* not WINDOWSNT */
1966 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1967 #endif /* not WINDOWSNT */
1970 /* Back in the parent process. */
1972 vfork_errno
= errno
;
1977 /* Stop blocking in the parent. */
1978 unblock_child_signal (&oldset
);
1982 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1985 /* vfork succeeded. */
1987 /* Close the pipe ends that the child uses, or the child's pty. */
1988 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1989 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1992 register_child (pid
, inchannel
);
1993 #endif /* WINDOWSNT */
1995 pset_tty_name (p
, lisp_pty_name
);
1998 /* Wait for child_setup to complete in case that vfork is
1999 actually defined as fork. The descriptor
2000 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2001 of a pipe is closed at the child side either by close-on-exec
2002 on successful execve or the _exit call in child_setup. */
2006 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2007 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2008 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2011 if (!NILP (p
->stderrproc
))
2013 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2014 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2020 create_pty (Lisp_Object process
)
2022 struct Lisp_Process
*p
= XPROCESS (process
);
2023 char pty_name
[PTY_NAME_SIZE
];
2024 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2028 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2029 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2030 /* On most USG systems it does not work to open the pty's tty here,
2031 then close it and reopen it in the child. */
2032 /* Don't let this terminal become our controlling terminal
2033 (in case we don't have one). */
2034 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2036 report_file_error ("Opening pty", Qnil
);
2037 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2038 #if defined (DONT_REOPEN_PTY)
2039 /* In the case that vfork is defined as fork, the parent process
2040 (Emacs) may send some data before the child process completes
2041 tty options setup. So we setup tty before forking. */
2042 child_setup_tty (forkout
);
2043 #endif /* DONT_REOPEN_PTY */
2044 #endif /* not USG, or USG_SUBTTY_WORKS */
2046 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2048 /* Record this as an active process, with its channels.
2049 As a result, child_setup will close Emacs's side of the pipes. */
2050 chan_process
[pty_fd
] = process
;
2054 /* Previously we recorded the tty descriptor used in the subprocess.
2055 It was only used for getting the foreground tty process, so now
2056 we just reopen the device (see emacs_get_tty_pgrp) as this is
2057 more portable (see USG_SUBTTY_WORKS above). */
2060 pset_status (p
, Qrun
);
2061 setup_process_coding_systems (process
);
2063 FD_SET (pty_fd
, &input_wait_mask
);
2064 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2065 if (pty_fd
> max_process_desc
)
2066 max_process_desc
= pty_fd
;
2068 pset_tty_name (p
, build_string (pty_name
));
2074 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2076 doc
: /* Create and return a bidirectional pipe process.
2078 In Emacs, pipes are represented by process objects, so input and
2079 output work as for subprocesses, and `delete-process' closes a pipe.
2080 However, a pipe process has no process id, it cannot be signaled,
2081 and the status codes are different from normal processes.
2083 Arguments are specified as keyword/argument pairs. The following
2084 arguments are defined:
2086 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2088 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2089 with the process. Process output goes at the end of that buffer,
2090 unless you specify an output stream or filter function to handle the
2091 output. If BUFFER is not given, the value of NAME is used.
2093 :coding CODING -- If CODING is a symbol, it specifies the coding
2094 system used for both reading and writing for this process. If CODING
2095 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2096 ENCODING is used for writing.
2098 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2099 the process is running. If BOOL is not given, query before exiting.
2101 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2102 In the stopped state, a pipe process does not accept incoming data,
2103 but you can send outgoing data. The stopped state is cleared by
2104 `continue-process' and set by `stop-process'.
2106 :filter FILTER -- Install FILTER as the process filter.
2108 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2110 usage: (make-pipe-process &rest ARGS) */)
2111 (ptrdiff_t nargs
, Lisp_Object
*args
)
2113 Lisp_Object proc
, contact
;
2114 struct Lisp_Process
*p
;
2115 Lisp_Object name
, buffer
;
2117 ptrdiff_t specpdl_count
;
2118 int inchannel
, outchannel
;
2123 contact
= Flist (nargs
, args
);
2125 name
= Fplist_get (contact
, QCname
);
2126 CHECK_STRING (name
);
2127 proc
= make_process (name
);
2128 specpdl_count
= SPECPDL_INDEX ();
2129 record_unwind_protect (remove_process
, proc
);
2130 p
= XPROCESS (proc
);
2132 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2133 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2134 report_file_error ("Creating pipe", Qnil
);
2135 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2136 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2138 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2139 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2142 register_aux_fd (inchannel
);
2145 /* Record this as an active process, with its channels. */
2146 chan_process
[inchannel
] = proc
;
2147 p
->infd
= inchannel
;
2148 p
->outfd
= outchannel
;
2150 if (inchannel
> max_process_desc
)
2151 max_process_desc
= inchannel
;
2153 buffer
= Fplist_get (contact
, QCbuffer
);
2156 buffer
= Fget_buffer_create (buffer
);
2157 pset_buffer (p
, buffer
);
2159 pset_childp (p
, contact
);
2160 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2161 pset_type (p
, Qpipe
);
2162 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2163 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2165 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2166 p
->kill_without_query
= 1;
2167 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2168 pset_command (p
, Qt
);
2169 eassert (! p
->pty_flag
);
2171 if (!EQ (p
->command
, Qt
))
2173 FD_SET (inchannel
, &input_wait_mask
);
2174 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2176 p
->adaptive_read_buffering
2177 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2178 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2180 /* Make the process marker point into the process buffer (if any). */
2181 if (BUFFERP (buffer
))
2182 set_marker_both (p
->mark
, buffer
,
2183 BUF_ZV (XBUFFER (buffer
)),
2184 BUF_ZV_BYTE (XBUFFER (buffer
)));
2187 /* Setup coding systems for communicating with the network stream. */
2189 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2190 Lisp_Object coding_systems
= Qt
;
2193 tem
= Fplist_get (contact
, QCcoding
);
2201 else if (!NILP (Vcoding_system_for_read
))
2202 val
= Vcoding_system_for_read
;
2203 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2204 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2205 /* We dare not decode end-of-line format by setting VAL to
2206 Qraw_text, because the existing Emacs Lisp libraries
2207 assume that they receive bare code including a sequence of
2212 if (CONSP (coding_systems
))
2213 val
= XCAR (coding_systems
);
2214 else if (CONSP (Vdefault_process_coding_system
))
2215 val
= XCAR (Vdefault_process_coding_system
);
2219 pset_decode_coding_system (p
, val
);
2227 else if (!NILP (Vcoding_system_for_write
))
2228 val
= Vcoding_system_for_write
;
2229 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2233 if (CONSP (coding_systems
))
2234 val
= XCDR (coding_systems
);
2235 else if (CONSP (Vdefault_process_coding_system
))
2236 val
= XCDR (Vdefault_process_coding_system
);
2240 pset_encode_coding_system (p
, val
);
2242 /* This may signal an error. */
2243 setup_process_coding_systems (proc
);
2245 specpdl_ptr
= specpdl
+ specpdl_count
;
2251 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2252 The address family of sa is not included in the result. */
2255 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2257 Lisp_Object address
;
2260 register struct Lisp_Vector
*p
;
2262 /* Workaround for a bug in getsockname on BSD: Names bound to
2263 sockets in the UNIX domain are inaccessible; getsockname returns
2264 a zero length name. */
2265 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2266 return empty_unibyte_string
;
2268 switch (sa
->sa_family
)
2272 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2273 len
= sizeof (sin
->sin_addr
) + 1;
2274 address
= Fmake_vector (make_number (len
), Qnil
);
2275 p
= XVECTOR (address
);
2276 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2277 cp
= (unsigned char *) &sin
->sin_addr
;
2283 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2284 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2285 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2286 address
= Fmake_vector (make_number (len
), Qnil
);
2287 p
= XVECTOR (address
);
2288 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2289 for (i
= 0; i
< len
; i
++)
2290 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2294 #ifdef HAVE_LOCAL_SOCKETS
2297 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2298 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2299 /* If the first byte is NUL, the name is a Linux abstract
2300 socket name, and the name can contain embedded NULs. If
2301 it's not, we have a NUL-terminated string. Be careful not
2302 to walk past the end of the object looking for the name
2303 terminator, however. */
2304 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2306 const char *terminator
2307 = memchr (sockun
->sun_path
, '\0', name_length
);
2310 name_length
= terminator
- (const char *) sockun
->sun_path
;
2313 return make_unibyte_string (sockun
->sun_path
, name_length
);
2317 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2318 address
= Fcons (make_number (sa
->sa_family
),
2319 Fmake_vector (make_number (len
), Qnil
));
2320 p
= XVECTOR (XCDR (address
));
2321 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2327 p
->contents
[i
++] = make_number (*cp
++);
2333 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2336 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2338 register struct Lisp_Vector
*p
;
2340 if (VECTORP (address
))
2342 p
= XVECTOR (address
);
2343 if (p
->header
.size
== 5)
2346 return sizeof (struct sockaddr_in
);
2349 else if (p
->header
.size
== 9)
2351 *familyp
= AF_INET6
;
2352 return sizeof (struct sockaddr_in6
);
2356 #ifdef HAVE_LOCAL_SOCKETS
2357 else if (STRINGP (address
))
2359 *familyp
= AF_LOCAL
;
2360 return sizeof (struct sockaddr_un
);
2363 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2364 && VECTORP (XCDR (address
)))
2366 struct sockaddr
*sa
;
2367 p
= XVECTOR (XCDR (address
));
2368 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2370 *familyp
= XINT (XCAR (address
));
2371 return p
->header
.size
+ sizeof (sa
->sa_family
);
2376 /* Convert an address object (vector or string) to an internal sockaddr.
2378 The address format has been basically validated by
2379 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2380 it could have come from user data. So if FAMILY is not valid,
2381 we return after zeroing *SA. */
2384 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2386 register struct Lisp_Vector
*p
;
2387 register unsigned char *cp
= NULL
;
2391 memset (sa
, 0, len
);
2393 if (VECTORP (address
))
2395 p
= XVECTOR (address
);
2396 if (family
== AF_INET
)
2398 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2399 len
= sizeof (sin
->sin_addr
) + 1;
2400 hostport
= XINT (p
->contents
[--len
]);
2401 sin
->sin_port
= htons (hostport
);
2402 cp
= (unsigned char *)&sin
->sin_addr
;
2403 sa
->sa_family
= family
;
2406 else if (family
== AF_INET6
)
2408 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2409 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2410 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2411 hostport
= XINT (p
->contents
[--len
]);
2412 sin6
->sin6_port
= htons (hostport
);
2413 for (i
= 0; i
< len
; i
++)
2414 if (INTEGERP (p
->contents
[i
]))
2416 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2419 sa
->sa_family
= family
;
2426 else if (STRINGP (address
))
2428 #ifdef HAVE_LOCAL_SOCKETS
2429 if (family
== AF_LOCAL
)
2431 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2432 cp
= SDATA (address
);
2433 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2434 sockun
->sun_path
[i
] = *cp
++;
2435 sa
->sa_family
= family
;
2442 p
= XVECTOR (XCDR (address
));
2443 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2446 for (i
= 0; i
< len
; i
++)
2447 if (INTEGERP (p
->contents
[i
]))
2448 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2451 #ifdef DATAGRAM_SOCKETS
2452 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2454 doc
: /* Get the current datagram address associated with PROCESS. */)
2455 (Lisp_Object process
)
2459 CHECK_PROCESS (process
);
2461 if (NETCONN_P (process
))
2462 wait_for_socket_fds (process
, "process-datagram-address");
2464 if (!DATAGRAM_CONN_P (process
))
2467 channel
= XPROCESS (process
)->infd
;
2468 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2469 datagram_address
[channel
].len
);
2472 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2474 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2475 Returns nil upon error setting address, ADDRESS otherwise. */)
2476 (Lisp_Object process
, Lisp_Object address
)
2481 CHECK_PROCESS (process
);
2483 if (NETCONN_P (process
))
2484 wait_for_socket_fds (process
, "set-process-datagram-address");
2486 if (!DATAGRAM_CONN_P (process
))
2489 channel
= XPROCESS (process
)->infd
;
2491 len
= get_lisp_to_sockaddr_size (address
, &family
);
2492 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2494 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2500 static const struct socket_options
{
2501 /* The name of this option. Should be lowercase version of option
2502 name without SO_ prefix. */
2504 /* Option level SOL_... */
2506 /* Option number SO_... */
2508 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2509 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2510 } socket_options
[] =
2512 #ifdef SO_BINDTODEVICE
2513 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2516 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2519 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2522 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2525 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2528 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2531 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2534 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2536 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2539 /* Set option OPT to value VAL on socket S.
2541 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2542 Signals an error if setting a known option fails.
2546 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2549 const struct socket_options
*sopt
;
2554 name
= SSDATA (SYMBOL_NAME (opt
));
2555 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2556 if (strcmp (name
, sopt
->name
) == 0)
2559 switch (sopt
->opttype
)
2564 optval
= NILP (val
) ? 0 : 1;
2565 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2566 &optval
, sizeof (optval
));
2573 if (TYPE_RANGED_INTEGERP (int, val
))
2574 optval
= XINT (val
);
2576 error ("Bad option value for %s", name
);
2577 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2578 &optval
, sizeof (optval
));
2582 #ifdef SO_BINDTODEVICE
2585 char devname
[IFNAMSIZ
+ 1];
2587 /* This is broken, at least in the Linux 2.4 kernel.
2588 To unbind, the arg must be a zero integer, not the empty string.
2589 This should work on all systems. KFS. 2003-09-23. */
2590 memset (devname
, 0, sizeof devname
);
2593 char *arg
= SSDATA (val
);
2594 int len
= min (strlen (arg
), IFNAMSIZ
);
2595 memcpy (devname
, arg
, len
);
2597 else if (!NILP (val
))
2598 error ("Bad option value for %s", name
);
2599 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2608 struct linger linger
;
2611 linger
.l_linger
= 0;
2612 if (TYPE_RANGED_INTEGERP (int, val
))
2613 linger
.l_linger
= XINT (val
);
2615 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2616 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2617 &linger
, sizeof (linger
));
2628 int setsockopt_errno
= errno
;
2629 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2633 return (1 << sopt
->optbit
);
2637 DEFUN ("set-network-process-option",
2638 Fset_network_process_option
, Sset_network_process_option
,
2640 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2641 See `make-network-process' for a list of options and values.
2642 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2643 OPTION is not a supported option, return nil instead; otherwise return t. */)
2644 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2647 struct Lisp_Process
*p
;
2649 CHECK_PROCESS (process
);
2650 p
= XPROCESS (process
);
2651 if (!NETCONN1_P (p
))
2652 error ("Process is not a network process");
2654 wait_for_socket_fds (process
, "set-network-process-option");
2658 error ("Process is not running");
2660 if (set_socket_option (s
, option
, value
))
2662 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2666 if (NILP (no_error
))
2667 error ("Unknown or unsupported option");
2673 DEFUN ("serial-process-configure",
2674 Fserial_process_configure
,
2675 Sserial_process_configure
,
2677 doc
: /* Configure speed, bytesize, etc. of a serial process.
2679 Arguments are specified as keyword/argument pairs. Attributes that
2680 are not given are re-initialized from the process's current
2681 configuration (available via the function `process-contact') or set to
2682 reasonable default values. The following arguments are defined:
2688 -- Any of these arguments can be given to identify the process that is
2689 to be configured. If none of these arguments is given, the current
2690 buffer's process is used.
2692 :speed SPEED -- SPEED is the speed of the serial port in bits per
2693 second, also called baud rate. Any value can be given for SPEED, but
2694 most serial ports work only at a few defined values between 1200 and
2695 115200, with 9600 being the most common value. If SPEED is nil, the
2696 serial port is not configured any further, i.e., all other arguments
2697 are ignored. This may be useful for special serial ports such as
2698 Bluetooth-to-serial converters which can only be configured through AT
2699 commands. A value of nil for SPEED can be used only when passed
2700 through `make-serial-process' or `serial-term'.
2702 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2703 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2705 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2706 `odd' (use odd parity), or the symbol `even' (use even parity). If
2707 PARITY is not given, no parity is used.
2709 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2710 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2711 is not given or nil, 1 stopbit is used.
2713 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2714 flowcontrol to be used, which is either nil (don't use flowcontrol),
2715 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2716 (use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2717 flowcontrol is used.
2719 `serial-process-configure' is called by `make-serial-process' for the
2720 initial configuration of the serial port.
2724 (serial-process-configure :process "/dev/ttyS0" :speed 1200)
2726 (serial-process-configure
2727 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2729 (serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2731 usage: (serial-process-configure &rest ARGS) */)
2732 (ptrdiff_t nargs
, Lisp_Object
*args
)
2734 struct Lisp_Process
*p
;
2735 Lisp_Object contact
= Qnil
;
2736 Lisp_Object proc
= Qnil
;
2738 contact
= Flist (nargs
, args
);
2740 proc
= Fplist_get (contact
, QCprocess
);
2742 proc
= Fplist_get (contact
, QCname
);
2744 proc
= Fplist_get (contact
, QCbuffer
);
2746 proc
= Fplist_get (contact
, QCport
);
2747 proc
= get_process (proc
);
2748 p
= XPROCESS (proc
);
2749 if (!EQ (p
->type
, Qserial
))
2750 error ("Not a serial process");
2752 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2755 serial_configure (p
, contact
);
2759 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2761 doc
: /* Create and return a serial port process.
2763 In Emacs, serial port connections are represented by process objects,
2764 so input and output work as for subprocesses, and `delete-process'
2765 closes a serial port connection. However, a serial process has no
2766 process id, it cannot be signaled, and the status codes are different
2767 from normal processes.
2769 `make-serial-process' creates a process and a buffer, on which you
2770 probably want to use `process-send-string'. Try \\[serial-term] for
2771 an interactive terminal. See below for examples.
2773 Arguments are specified as keyword/argument pairs. The following
2774 arguments are defined:
2776 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2777 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2778 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2779 the backslashes in strings).
2781 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2782 which this function calls.
2784 :name NAME -- NAME is the name of the process. If NAME is not given,
2785 the value of PORT is used.
2787 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2788 with the process. Process output goes at the end of that buffer,
2789 unless you specify an output stream or filter function to handle the
2790 output. If BUFFER is not given, the value of NAME is used.
2792 :coding CODING -- If CODING is a symbol, it specifies the coding
2793 system used for both reading and writing for this process. If CODING
2794 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2795 ENCODING is used for writing.
2797 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2798 the process is running. If BOOL is not given, query before exiting.
2800 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2801 In the stopped state, a serial process does not accept incoming data,
2802 but you can send outgoing data. The stopped state is cleared by
2803 `continue-process' and set by `stop-process'.
2805 :filter FILTER -- Install FILTER as the process filter.
2807 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2809 :plist PLIST -- Install PLIST as the initial plist of the process.
2815 -- This function calls `serial-process-configure' to handle these
2818 The original argument list, possibly modified by later configuration,
2819 is available via the function `process-contact'.
2823 (make-serial-process :port "/dev/ttyS0" :speed 9600)
2825 (make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2827 (make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2829 (make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2831 usage: (make-serial-process &rest ARGS) */)
2832 (ptrdiff_t nargs
, Lisp_Object
*args
)
2835 Lisp_Object proc
, contact
, port
;
2836 struct Lisp_Process
*p
;
2837 Lisp_Object name
, buffer
;
2838 Lisp_Object tem
, val
;
2839 ptrdiff_t specpdl_count
;
2844 contact
= Flist (nargs
, args
);
2846 port
= Fplist_get (contact
, QCport
);
2848 error ("No port specified");
2849 CHECK_STRING (port
);
2851 if (NILP (Fplist_member (contact
, QCspeed
)))
2852 error (":speed not specified");
2853 if (!NILP (Fplist_get (contact
, QCspeed
)))
2854 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2856 name
= Fplist_get (contact
, QCname
);
2859 CHECK_STRING (name
);
2860 proc
= make_process (name
);
2861 specpdl_count
= SPECPDL_INDEX ();
2862 record_unwind_protect (remove_process
, proc
);
2863 p
= XPROCESS (proc
);
2865 fd
= serial_open (port
);
2866 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2869 if (fd
> max_process_desc
)
2870 max_process_desc
= fd
;
2871 chan_process
[fd
] = proc
;
2873 buffer
= Fplist_get (contact
, QCbuffer
);
2876 buffer
= Fget_buffer_create (buffer
);
2877 pset_buffer (p
, buffer
);
2879 pset_childp (p
, contact
);
2880 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2881 pset_type (p
, Qserial
);
2882 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2883 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2885 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2886 p
->kill_without_query
= 1;
2887 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2888 pset_command (p
, Qt
);
2889 eassert (! p
->pty_flag
);
2891 if (!EQ (p
->command
, Qt
))
2893 FD_SET (fd
, &input_wait_mask
);
2894 FD_SET (fd
, &non_keyboard_wait_mask
);
2897 if (BUFFERP (buffer
))
2899 set_marker_both (p
->mark
, buffer
,
2900 BUF_ZV (XBUFFER (buffer
)),
2901 BUF_ZV_BYTE (XBUFFER (buffer
)));
2904 tem
= Fplist_member (contact
, QCcoding
);
2905 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2911 val
= XCAR (XCDR (tem
));
2915 else if (!NILP (Vcoding_system_for_read
))
2916 val
= Vcoding_system_for_read
;
2917 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2918 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2920 pset_decode_coding_system (p
, val
);
2925 val
= XCAR (XCDR (tem
));
2929 else if (!NILP (Vcoding_system_for_write
))
2930 val
= Vcoding_system_for_write
;
2931 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2932 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2934 pset_encode_coding_system (p
, val
);
2936 setup_process_coding_systems (proc
);
2937 pset_decoding_buf (p
, empty_unibyte_string
);
2938 p
->decoding_carryover
= 0;
2939 pset_encoding_buf (p
, empty_unibyte_string
);
2940 p
->inherit_coding_system_flag
2941 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2943 Fserial_process_configure (nargs
, args
);
2945 specpdl_ptr
= specpdl
+ specpdl_count
;
2950 void set_network_socket_coding_system (Lisp_Object proc
)
2953 struct Lisp_Process
*p
= XPROCESS (proc
);
2954 Lisp_Object contact
= p
->childp
;
2955 Lisp_Object service
, host
, name
;
2956 Lisp_Object coding_systems
= Qt
;
2959 service
= Fplist_get (contact
, QCservice
);
2960 host
= Fplist_get (contact
, QChost
);
2961 name
= Fplist_get (contact
, QCname
);
2963 tem
= Fplist_member (contact
, QCcoding
);
2964 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2965 tem
= Qnil
; /* No error message (too late!). */
2967 /* Setup coding systems for communicating with the network stream. */
2968 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2972 val
= XCAR (XCDR (tem
));
2976 else if (!NILP (Vcoding_system_for_read
))
2977 val
= Vcoding_system_for_read
;
2978 else if ((!NILP (p
->buffer
) &&
2979 NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2980 || (NILP (p
->buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2981 /* We dare not decode end-of-line format by setting VAL to
2982 Qraw_text, because the existing Emacs Lisp libraries
2983 assume that they receive bare code including a sequence of
2988 if (NILP (host
) || NILP (service
))
2989 coding_systems
= Qnil
;
2991 coding_systems
= CALLN (Ffind_operation_coding_system
,
2992 Qopen_network_stream
, name
, p
->buffer
,
2994 if (CONSP (coding_systems
))
2995 val
= XCAR (coding_systems
);
2996 else if (CONSP (Vdefault_process_coding_system
))
2997 val
= XCAR (Vdefault_process_coding_system
);
3001 pset_decode_coding_system (p
, val
);
3005 val
= XCAR (XCDR (tem
));
3009 else if (!NILP (Vcoding_system_for_write
))
3010 val
= Vcoding_system_for_write
;
3011 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3015 if (EQ (coding_systems
, Qt
))
3017 if (NILP (host
) || NILP (service
))
3018 coding_systems
= Qnil
;
3020 coding_systems
= CALLN (Ffind_operation_coding_system
,
3021 Qopen_network_stream
, name
, p
->buffer
,
3024 if (CONSP (coding_systems
))
3025 val
= XCDR (coding_systems
);
3026 else if (CONSP (Vdefault_process_coding_system
))
3027 val
= XCDR (Vdefault_process_coding_system
);
3031 pset_encode_coding_system (p
, val
);
3033 pset_decoding_buf (p
, empty_unibyte_string
);
3034 p
->decoding_carryover
= 0;
3035 pset_encoding_buf (p
, empty_unibyte_string
);
3037 p
->inherit_coding_system_flag
3038 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3041 void connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
)
3043 ptrdiff_t count
= SPECPDL_INDEX ();
3045 int s
= -1, outch
, inch
;
3047 Lisp_Object ip_address
;
3049 struct sockaddr
*sa
= NULL
;
3052 struct Lisp_Process
*p
= XPROCESS (proc
);
3053 Lisp_Object contact
= p
->childp
;
3056 /* Do this in case we never enter the while-loop below. */
3057 count1
= SPECPDL_INDEX ();
3060 while (!NILP (ip_addresses
))
3062 ip_address
= XCAR (ip_addresses
);
3063 ip_addresses
= XCDR (ip_addresses
);
3069 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3072 sa
= xmalloc (addrlen
);
3073 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3075 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3082 #ifdef DATAGRAM_SOCKETS
3083 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3085 #endif /* DATAGRAM_SOCKETS */
3087 #ifdef NON_BLOCKING_CONNECT
3088 if (p
->is_non_blocking_client
)
3090 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3101 /* Make us close S if quit. */
3102 record_unwind_protect_int (close_file_unwind
, s
);
3104 /* Parse network options in the arg list. We simply ignore anything
3105 which isn't a known option (including other keywords). An error
3106 is signaled if setting a known option fails. */
3108 Lisp_Object params
= contact
, key
, val
;
3110 while (!NILP (params
))
3112 key
= XCAR (params
);
3113 params
= XCDR (params
);
3114 val
= XCAR (params
);
3115 params
= XCDR (params
);
3116 optbits
|= set_socket_option (s
, key
, val
);
3122 /* Configure as a server socket. */
3124 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3125 explicit :reuseaddr key to override this. */
3126 #ifdef HAVE_LOCAL_SOCKETS
3127 if (family
!= AF_LOCAL
)
3129 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3132 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3133 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3136 if (bind (s
, sa
, addrlen
))
3137 report_file_error ("Cannot bind server socket", Qnil
);
3139 #ifdef HAVE_GETSOCKNAME
3142 struct sockaddr_in sa1
;
3143 socklen_t len1
= sizeof (sa1
);
3144 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3146 Lisp_Object service
;
3147 service
= make_number (ntohs (sa1
.sin_port
));
3148 contact
= Fplist_put (contact
, QCservice
, service
);
3149 // Save the port number so that we can stash it in
3150 // the process object later.
3151 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3156 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3157 report_file_error ("Cannot listen on server socket", Qnil
);
3165 ret
= connect (s
, sa
, addrlen
);
3168 if (ret
== 0 || xerrno
== EISCONN
)
3170 /* The unwind-protect will be discarded afterwards.
3171 Likewise for immediate_quit. */
3175 #ifdef NON_BLOCKING_CONNECT
3177 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3181 if (p
->is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3188 if (xerrno
== EINTR
)
3190 /* Unlike most other syscalls connect() cannot be called
3191 again. (That would return EALREADY.) The proper way to
3192 wait for completion is pselect(). */
3200 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3206 report_file_error ("Failed select", Qnil
);
3210 len
= sizeof xerrno
;
3211 eassert (FD_ISSET (s
, &fdset
));
3212 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3213 report_file_error ("Failed getsockopt", Qnil
);
3215 report_file_errno ("Failed connect", Qnil
, xerrno
);
3218 #endif /* !WINDOWSNT */
3222 /* Discard the unwind protect closing S. */
3223 specpdl_ptr
= specpdl
+ count1
;
3228 if (xerrno
== EINTR
)
3235 #ifdef DATAGRAM_SOCKETS
3236 if (p
->socktype
== SOCK_DGRAM
)
3238 if (datagram_address
[s
].sa
)
3241 datagram_address
[s
].sa
= xmalloc (addrlen
);
3242 datagram_address
[s
].len
= addrlen
;
3246 memset (datagram_address
[s
].sa
, 0, addrlen
);
3247 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3250 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3251 if (rlen
!= 0 && rfamily
== family
3253 conv_lisp_to_sockaddr (rfamily
, remote
,
3254 datagram_address
[s
].sa
, rlen
);
3258 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3262 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3263 conv_sockaddr_to_lisp (sa
, addrlen
));
3264 #ifdef HAVE_GETSOCKNAME
3267 struct sockaddr_in sa1
;
3268 socklen_t len1
= sizeof (sa1
);
3269 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3270 contact
= Fplist_put (contact
, QClocal
,
3271 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3280 /* If non-blocking got this far - and failed - assume non-blocking is
3281 not supported after all. This is probably a wrong assumption, but
3282 the normal blocking calls to open-network-stream handles this error
3284 if (p
->is_non_blocking_client
)
3287 report_file_errno ((p
->is_server
3288 ? "make server process failed"
3289 : "make client process failed"),
3296 chan_process
[inch
] = proc
;
3298 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3300 p
= XPROCESS (proc
);
3301 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3305 /* Discard the unwind protect for closing S, if any. */
3306 specpdl_ptr
= specpdl
+ count1
;
3308 /* Unwind bind_polling_period and request_sigio. */
3309 unbind_to (count
, Qnil
);
3311 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3312 pset_status (p
, Qlisten
);
3314 /* Make the process marker point into the process buffer (if any). */
3315 if (BUFFERP (p
->buffer
))
3316 set_marker_both (p
->mark
, p
->buffer
,
3317 BUF_ZV (XBUFFER (p
->buffer
)),
3318 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3320 #ifdef NON_BLOCKING_CONNECT
3321 if (p
->is_non_blocking_client
)
3323 /* We may get here if connect did succeed immediately. However,
3324 in that case, we still need to signal this like a non-blocking
3326 pset_status (p
, Qconnect
);
3327 if (!FD_ISSET (inch
, &connect_wait_mask
))
3329 FD_SET (inch
, &connect_wait_mask
);
3330 FD_SET (inch
, &write_mask
);
3331 num_pending_connects
++;
3336 /* A server may have a client filter setting of Qt, but it must
3337 still listen for incoming connects unless it is stopped. */
3338 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3339 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3341 FD_SET (inch
, &input_wait_mask
);
3342 FD_SET (inch
, &non_keyboard_wait_mask
);
3345 if (inch
> max_process_desc
)
3346 max_process_desc
= inch
;
3348 /* Set up the masks based on the process filter. */
3349 set_process_filter_masks (p
);
3351 setup_process_coding_systems (proc
);
3354 /* Continue the asynchronous connection. */
3355 if (!NILP (p
->gnutls_boot_parameters
))
3357 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3359 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3360 p
->gnutls_boot_parameters
= Qnil
;
3362 if (NILP (boot
) || STRINGP (boot
) ||
3363 p
->gnutls_initstage
!= GNUTLS_STAGE_READY
)
3365 deactivate_process (proc
);
3367 pset_status (p
, list2 (Qfailed
,
3368 build_string ("TLS negotiation failed")));
3370 pset_status (p
, list2 (Qfailed
, boot
));
3374 Lisp_Object result
= Qt
;
3376 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3377 result
= call3 (Qnsm_verify_connection
,
3379 Fplist_get (contact
, QChost
),
3380 Fplist_get (contact
, QCservice
));
3384 pset_status (p
, list2 (Qfailed
,
3385 build_string ("The Network Security Manager stopped the connections")));
3386 deactivate_process (proc
);
3390 /* If we cleared the connection wait mask before we did
3391 the TLS setup, then we have to say that the process
3392 is finally "open" here. */
3393 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3395 pset_status (p
, Qrun
);
3396 /* Execute the sentinel here. If we had relied on
3397 status_notify to do it later, it will read input
3398 from the process before calling the sentinel. */
3399 exec_sentinel (proc
, build_string ("open\n"));
3408 #ifndef HAVE_GETADDRINFO
3410 conv_numerical_to_lisp (unsigned char *number
, unsigned int length
, int port
)
3412 Lisp_Object address
= Fmake_vector (make_number (length
+ 1), Qnil
);
3413 register struct Lisp_Vector
*p
= XVECTOR (address
);
3416 p
->contents
[length
] = make_number (port
);
3417 for (i
= 0; i
< length
; i
++)
3418 p
->contents
[i
] = make_number (*(number
+ i
));
3424 /* Create a network stream/datagram client/server process. Treated
3425 exactly like a normal process when reading and writing. Primary
3426 differences are in status display and process deletion. A network
3427 connection has no PID; you cannot signal it. All you can do is
3428 stop/continue it and deactivate/close it via delete-process. */
3430 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3432 doc
: /* Create and return a network server or client process.
3434 In Emacs, network connections are represented by process objects, so
3435 input and output work as for subprocesses and `delete-process' closes
3436 a network connection. However, a network process has no process id,
3437 it cannot be signaled, and the status codes are different from normal
3440 Arguments are specified as keyword/argument pairs. The following
3441 arguments are defined:
3443 :name NAME -- NAME is name for process. It is modified if necessary
3446 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3447 with the process. Process output goes at end of that buffer, unless
3448 you specify an output stream or filter function to handle the output.
3449 BUFFER may be also nil, meaning that this process is not associated
3452 :host HOST -- HOST is name of the host to connect to, or its IP
3453 address. The symbol `local' specifies the local host. If specified
3454 for a server process, it must be a valid name or address for the local
3455 host, and only clients connecting to that address will be accepted.
3457 :service SERVICE -- SERVICE is name of the service desired, or an
3458 integer specifying a port number to connect to. If SERVICE is t,
3459 a random port number is selected for the server. (If Emacs was
3460 compiled with getaddrinfo, a port number can also be specified as a
3461 string, e.g. "80", as well as an integer. This is not portable.)
3463 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3464 stream type connection, `datagram' creates a datagram type connection,
3465 `seqpacket' creates a reliable datagram connection.
3467 :family FAMILY -- FAMILY is the address (and protocol) family for the
3468 service specified by HOST and SERVICE. The default (nil) is to use
3469 whatever address family (IPv4 or IPv6) that is defined for the host
3470 and port number specified by HOST and SERVICE. Other address families
3472 local -- for a local (i.e. UNIX) address specified by SERVICE.
3473 ipv4 -- use IPv4 address family only.
3474 ipv6 -- use IPv6 address family only.
3476 :local ADDRESS -- ADDRESS is the local address used for the connection.
3477 This parameter is ignored when opening a client process. When specified
3478 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3480 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3481 connection. This parameter is ignored when opening a stream server
3482 process. For a datagram server process, it specifies the initial
3483 setting of the remote datagram address. When specified for a client
3484 process, the FAMILY, HOST, and SERVICE args are ignored.
3486 The format of ADDRESS depends on the address family:
3487 - An IPv4 address is represented as an vector of integers [A B C D P]
3488 corresponding to numeric IP address A.B.C.D and port number P.
3489 - A local address is represented as a string with the address in the
3490 local address space.
3491 - An "unsupported family" address is represented by a cons (F . AV)
3492 where F is the family number and AV is a vector containing the socket
3493 address data with one element per address data byte. Do not rely on
3494 this format in portable code, as it may depend on implementation
3495 defined constants, data sizes, and data structure alignment.
3497 :coding CODING -- If CODING is a symbol, it specifies the coding
3498 system used for both reading and writing for this process. If CODING
3499 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3500 ENCODING is used for writing.
3502 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3503 process, return without waiting for the connection to complete;
3504 instead, the sentinel function will be called with second arg matching
3505 "open" (if successful) or "failed" when the connect completes.
3506 Default is to use a blocking connect (i.e. wait) for stream type
3509 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3510 running when Emacs is exited.
3512 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3513 In the stopped state, a server process does not accept new
3514 connections, and a client process does not handle incoming traffic.
3515 The stopped state is cleared by `continue-process' and set by
3518 :filter FILTER -- Install FILTER as the process filter.
3520 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3521 process filter are multibyte, otherwise they are unibyte.
3522 If this keyword is not specified, the strings are multibyte if
3523 the default value of `enable-multibyte-characters' is non-nil.
3525 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3527 :log LOG -- Install LOG as the server process log function. This
3528 function is called when the server accepts a network connection from a
3529 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3530 is the server process, CLIENT is the new process for the connection,
3531 and MESSAGE is a string.
3533 :plist PLIST -- Install PLIST as the new process's initial plist.
3535 :tls-parameters LIST -- is a list that should be supplied if you're
3536 opening a TLS connection. The first element is the TLS type (either
3537 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3538 be a keyword list accepted by gnutls-boot (as returned by
3539 `gnutls-boot-parameters').
3541 :server QLEN -- if QLEN is non-nil, create a server process for the
3542 specified FAMILY, SERVICE, and connection type (stream or datagram).
3543 If QLEN is an integer, it is used as the max. length of the server's
3544 pending connection queue (also known as the backlog); the default
3545 queue length is 5. Default is to create a client process.
3547 The following network options can be specified for this connection:
3549 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3550 :dontroute BOOL -- Only send to directly connected hosts.
3551 :keepalive BOOL -- Send keep-alive messages on network stream.
3552 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3553 :oobinline BOOL -- Place out-of-band data in receive data stream.
3554 :priority INT -- Set protocol defined priority for sent packets.
3555 :reuseaddr BOOL -- Allow reusing a recently used local address
3556 (this is allowed by default for a server process).
3557 :bindtodevice NAME -- bind to interface NAME. Using this may require
3558 special privileges on some systems.
3560 Consult the relevant system programmer's manual pages for more
3561 information on using these options.
3564 A server process will listen for and accept connections from clients.
3565 When a client connection is accepted, a new network process is created
3566 for the connection with the following parameters:
3568 - The client's process name is constructed by concatenating the server
3569 process's NAME and a client identification string.
3570 - If the FILTER argument is non-nil, the client process will not get a
3571 separate process buffer; otherwise, the client's process buffer is a newly
3572 created buffer named after the server process's BUFFER name or process
3573 NAME concatenated with the client identification string.
3574 - The connection type and the process filter and sentinel parameters are
3575 inherited from the server process's TYPE, FILTER and SENTINEL.
3576 - The client process's contact info is set according to the client's
3577 addressing information (typically an IP address and a port number).
3578 - The client process's plist is initialized from the server's plist.
3580 Notice that the FILTER and SENTINEL args are never used directly by
3581 the server process. Also, the BUFFER argument is not used directly by
3582 the server process, but via the optional :log function, accepted (and
3583 failed) connections may be logged in the server process's buffer.
3585 The original argument list, modified with the actual connection
3586 information, is available via the `process-contact' function.
3588 usage: (make-network-process &rest ARGS) */)
3589 (ptrdiff_t nargs
, Lisp_Object
*args
)
3592 Lisp_Object contact
;
3593 struct Lisp_Process
*p
;
3594 #if defined(HAVE_GETADDRINFO) || defined(HAVE_GETADDRINFO_A)
3595 struct addrinfo
*hints
;
3596 const char *portstring
;
3599 #ifdef HAVE_LOCAL_SOCKETS
3600 struct sockaddr_un address_un
;
3604 Lisp_Object name
, buffer
, host
, service
, address
;
3605 Lisp_Object filter
, sentinel
;
3606 Lisp_Object ip_addresses
= Qnil
;
3609 int ai_protocol
= 0;
3610 #ifdef HAVE_GETADDRINFO_A
3611 struct gaicb
**dns_requests
= NULL
;
3613 ptrdiff_t count
= SPECPDL_INDEX ();
3618 /* Save arguments for process-contact and clone-process. */
3619 contact
= Flist (nargs
, args
);
3622 /* Ensure socket support is loaded if available. */
3623 init_winsock (TRUE
);
3626 /* :type TYPE (nil: stream, datagram */
3627 tem
= Fplist_get (contact
, QCtype
);
3629 socktype
= SOCK_STREAM
;
3630 #ifdef DATAGRAM_SOCKETS
3631 else if (EQ (tem
, Qdatagram
))
3632 socktype
= SOCK_DGRAM
;
3634 #ifdef HAVE_SEQPACKET
3635 else if (EQ (tem
, Qseqpacket
))
3636 socktype
= SOCK_SEQPACKET
;
3639 error ("Unsupported connection type");
3641 name
= Fplist_get (contact
, QCname
);
3642 buffer
= Fplist_get (contact
, QCbuffer
);
3643 filter
= Fplist_get (contact
, QCfilter
);
3644 sentinel
= Fplist_get (contact
, QCsentinel
);
3646 CHECK_STRING (name
);
3648 /* :local ADDRESS or :remote ADDRESS */
3649 tem
= Fplist_get (contact
, QCserver
);
3651 address
= Fplist_get (contact
, QCremote
);
3653 address
= Fplist_get (contact
, QClocal
);
3654 if (!NILP (address
))
3656 host
= service
= Qnil
;
3658 if (!get_lisp_to_sockaddr_size (address
, &family
))
3659 error ("Malformed :address");
3661 ip_addresses
= Fcons (address
, Qnil
);
3665 /* :family FAMILY -- nil (for Inet), local, or integer. */
3666 tem
= Fplist_get (contact
, QCfamily
);
3669 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3675 #ifdef HAVE_LOCAL_SOCKETS
3676 else if (EQ (tem
, Qlocal
))
3680 else if (EQ (tem
, Qipv6
))
3683 else if (EQ (tem
, Qipv4
))
3685 else if (TYPE_RANGED_INTEGERP (int, tem
))
3686 family
= XINT (tem
);
3688 error ("Unknown address family");
3690 /* :service SERVICE -- string, integer (port number), or t (random port). */
3691 service
= Fplist_get (contact
, QCservice
);
3693 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3694 host
= Fplist_get (contact
, QChost
);
3697 /* The "connection" function gets it bind info from the address we're
3698 given, so use this dummy address if nothing is specified. */
3699 #ifdef HAVE_LOCAL_SOCKETS
3700 if (family
!= AF_LOCAL
)
3702 host
= build_string ("127.0.0.1");
3706 if (EQ (host
, Qlocal
))
3707 /* Depending on setup, "localhost" may map to different IPv4 and/or
3708 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3709 host
= build_string ("127.0.0.1");
3710 CHECK_STRING (host
);
3713 #ifdef HAVE_LOCAL_SOCKETS
3714 if (family
== AF_LOCAL
)
3718 message (":family local ignores the :host property");
3719 contact
= Fplist_put (contact
, QChost
, Qnil
);
3722 CHECK_STRING (service
);
3723 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3724 error ("Service name too long");
3725 ip_addresses
= Fcons (service
, Qnil
);
3730 /* Slow down polling to every ten seconds.
3731 Some kernels have a bug which causes retrying connect to fail
3732 after a connect. Polling can interfere with gethostbyname too. */
3733 #ifdef POLL_FOR_INPUT
3734 if (socktype
!= SOCK_DGRAM
)
3736 record_unwind_protect_void (run_all_atimers
);
3737 bind_polling_period (10);
3741 #if defined (HAVE_GETADDRINFO) || defined (HAVE_GETADDRINFO_A)
3745 /* SERVICE can either be a string or int.
3746 Convert to a C string for later use by getaddrinfo. */
3747 if (EQ (service
, Qt
))
3749 else if (INTEGERP (service
))
3751 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3752 portstring
= portbuf
;
3756 CHECK_STRING (service
);
3757 portstring
= SSDATA (service
);
3760 hints
= xzalloc (sizeof (struct addrinfo
));
3761 hints
->ai_flags
= 0;
3762 hints
->ai_family
= family
;
3763 hints
->ai_socktype
= socktype
;
3764 hints
->ai_protocol
= 0;
3769 #ifdef HAVE_GETADDRINFO_A
3770 if (!NILP (Fplist_get (contact
, QCnowait
)) &&
3775 printf("Async DNS for '%s'\n", SSDATA (host
));
3776 dns_requests
= xmalloc (sizeof (struct gaicb
*));
3777 dns_requests
[0] = xmalloc (sizeof (struct gaicb
));
3778 dns_requests
[0]->ar_name
= strdup (SSDATA (host
));
3779 dns_requests
[0]->ar_service
= strdup (portstring
);
3780 dns_requests
[0]->ar_request
= hints
;
3781 dns_requests
[0]->ar_result
= NULL
;
3783 ret
= getaddrinfo_a (GAI_NOWAIT
, dns_requests
, 1, NULL
);
3785 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3789 #endif /* HAVE_GETADDRINFO_A */
3791 #ifdef HAVE_GETADDRINFO
3792 /* If we have a host, use getaddrinfo to resolve both host and service.
3793 Otherwise, use getservbyname to lookup the service. */
3797 struct addrinfo
*res
, *lres
;
3803 #ifdef HAVE_RES_INIT
3807 ret
= getaddrinfo (SSDATA (host
), portstring
, hints
, &res
);
3809 #ifdef HAVE_GAI_STRERROR
3810 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3812 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3816 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3818 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3819 (lres
->ai_addr
, lres
->ai_addrlen
),
3821 ai_protocol
= lres
->ai_protocol
;
3824 ip_addresses
= Fnreverse (ip_addresses
);
3831 #endif /* HAVE_GETADDRINFO */
3833 /* We end up here if getaddrinfo is not defined, or in case no hostname
3834 has been specified (e.g. for a local server process). */
3836 if (EQ (service
, Qt
))
3838 else if (INTEGERP (service
))
3839 port
= (unsigned short) XINT (service
);
3842 struct servent
*svc_info
;
3843 CHECK_STRING (service
);
3844 svc_info
= getservbyname (SSDATA (service
),
3845 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3847 error ("Unknown service: %s", SDATA (service
));
3848 port
= ntohs (svc_info
->s_port
);
3851 #ifndef HAVE_GETADDRINFO
3854 struct hostent
*host_info_ptr
;
3856 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3857 as it may `hang' Emacs for a very long time. */
3861 #ifdef HAVE_RES_INIT
3865 host_info_ptr
= gethostbyname ((const char *) SDATA (host
));
3870 ip_addresses
= Fcons (conv_numerical_to_lisp
3871 ((unsigned char *) host_info_ptr
->h_addr
,
3872 host_info_ptr
->h_length
,
3877 /* Attempt to interpret host as numeric inet address. This
3878 only works for IPv4 addresses. */
3880 unsigned long numeric_addr
= inet_addr (SSDATA (host
));
3882 if (numeric_addr
== -1)
3883 error ("Unknown host \"%s\"", SDATA (host
));
3885 ip_addresses
= Fcons (conv_numerical_to_lisp
3886 ((unsigned char *) &numeric_addr
, 4, port
),
3891 #endif /* not HAVE_GETADDRINFO */
3896 buffer
= Fget_buffer_create (buffer
);
3897 proc
= make_process (name
);
3898 p
= XPROCESS (proc
);
3899 pset_childp (p
, contact
);
3900 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3901 pset_type (p
, Qnetwork
);
3903 pset_buffer (p
, buffer
);
3904 pset_sentinel (p
, sentinel
);
3905 pset_filter (p
, filter
);
3906 pset_log (p
, Fplist_get (contact
, QClog
));
3907 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3908 p
->kill_without_query
= 1;
3909 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3910 pset_command (p
, Qt
);
3913 p
->is_non_blocking_client
= 0;
3916 p
->socktype
= socktype
;
3917 p
->ai_protocol
= ai_protocol
;
3918 #ifdef HAVE_GETADDRINFO_A
3919 p
->dns_requests
= NULL
;
3922 tem
= Fplist_get (contact
, QCtls_parameters
);
3924 p
->gnutls_boot_parameters
= tem
;
3927 set_network_socket_coding_system (proc
);
3929 unbind_to (count
, Qnil
);
3932 tem
= Fplist_get (contact
, QCserver
);
3935 /* Don't support network sockets when non-blocking mode is
3936 not available, since a blocked Emacs is not useful. */
3938 if (TYPE_RANGED_INTEGERP (int, tem
))
3939 p
->backlog
= XINT (tem
);
3943 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3944 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
3946 #ifndef NON_BLOCKING_CONNECT
3947 error ("Non-blocking connect not supported");
3949 p
->is_non_blocking_client
= 1;
3953 #ifdef HAVE_GETADDRINFO_A
3954 /* If we're doing async address resolution, the list of addresses
3955 here will be nil, so we postpone connecting to the server. */
3956 if (!p
->is_server
&& NILP (ip_addresses
))
3958 p
->dns_requests
= dns_requests
;
3959 p
->status
= Qconnect
;
3963 connect_network_socket (proc
, ip_addresses
);
3965 #else /* HAVE_GETADDRINFO_A */
3966 connect_network_socket (proc
, ip_addresses
);
3973 #ifdef HAVE_NET_IF_H
3977 network_interface_list (void)
3979 struct ifconf ifconf
;
3980 struct ifreq
*ifreq
;
3982 ptrdiff_t buf_size
= 512;
3987 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3990 count
= SPECPDL_INDEX ();
3991 record_unwind_protect_int (close_file_unwind
, s
);
3995 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3996 ifconf
.ifc_buf
= buf
;
3997 ifconf
.ifc_len
= buf_size
;
3998 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4005 while (ifconf
.ifc_len
== buf_size
);
4007 res
= unbind_to (count
, Qnil
);
4008 ifreq
= ifconf
.ifc_req
;
4009 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4011 struct ifreq
*ifq
= ifreq
;
4012 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4013 #define SIZEOF_IFREQ(sif) \
4014 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4015 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4017 int len
= SIZEOF_IFREQ (ifq
);
4019 int len
= sizeof (*ifreq
);
4021 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4022 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4024 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4027 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4028 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4029 res
= Fcons (Fcons (build_string (namebuf
),
4030 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4031 sizeof (struct sockaddr
))),
4038 #endif /* SIOCGIFCONF */
4040 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4044 const char *flag_sym
;
4047 static const struct ifflag_def ifflag_table
[] = {
4051 #ifdef IFF_BROADCAST
4052 { IFF_BROADCAST
, "broadcast" },
4055 { IFF_DEBUG
, "debug" },
4058 { IFF_LOOPBACK
, "loopback" },
4060 #ifdef IFF_POINTOPOINT
4061 { IFF_POINTOPOINT
, "pointopoint" },
4064 { IFF_RUNNING
, "running" },
4067 { IFF_NOARP
, "noarp" },
4070 { IFF_PROMISC
, "promisc" },
4072 #ifdef IFF_NOTRAILERS
4073 #ifdef NS_IMPL_COCOA
4074 /* Really means smart, notrailers is obsolete. */
4075 { IFF_NOTRAILERS
, "smart" },
4077 { IFF_NOTRAILERS
, "notrailers" },
4081 { IFF_ALLMULTI
, "allmulti" },
4084 { IFF_MASTER
, "master" },
4087 { IFF_SLAVE
, "slave" },
4089 #ifdef IFF_MULTICAST
4090 { IFF_MULTICAST
, "multicast" },
4093 { IFF_PORTSEL
, "portsel" },
4095 #ifdef IFF_AUTOMEDIA
4096 { IFF_AUTOMEDIA
, "automedia" },
4099 { IFF_DYNAMIC
, "dynamic" },
4102 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4105 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4108 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4111 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4114 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4120 network_interface_info (Lisp_Object ifname
)
4123 Lisp_Object res
= Qnil
;
4128 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4129 && defined HAVE_GETIFADDRS && defined LLADDR)
4130 struct ifaddrs
*ifap
;
4133 CHECK_STRING (ifname
);
4135 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4136 error ("interface name too long");
4137 lispstpcpy (rq
.ifr_name
, ifname
);
4139 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4142 count
= SPECPDL_INDEX ();
4143 record_unwind_protect_int (close_file_unwind
, s
);
4146 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4147 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4149 int flags
= rq
.ifr_flags
;
4150 const struct ifflag_def
*fp
;
4153 /* If flags is smaller than int (i.e. short) it may have the high bit set
4154 due to IFF_MULTICAST. In that case, sign extending it into
4156 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4157 flags
= (unsigned short) rq
.ifr_flags
;
4160 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4162 if (flags
& fp
->flag_bit
)
4164 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4165 flags
-= fp
->flag_bit
;
4168 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4172 elt
= Fcons (make_number (fnum
), elt
);
4177 res
= Fcons (elt
, res
);
4180 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4181 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4183 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4184 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4188 for (n
= 0; n
< 6; n
++)
4189 p
->contents
[n
] = make_number (((unsigned char *)
4190 &rq
.ifr_hwaddr
.sa_data
[0])
4192 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4194 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4195 if (getifaddrs (&ifap
) != -1)
4197 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4198 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4201 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4203 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4204 unsigned char linkaddr
[6];
4207 if (it
->ifa_addr
->sa_family
!= AF_LINK
4208 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4209 || sdl
->sdl_alen
!= 6)
4212 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4213 for (n
= 0; n
< 6; n
++)
4214 p
->contents
[n
] = make_number (linkaddr
[n
]);
4216 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4220 #ifdef HAVE_FREEIFADDRS
4224 #endif /* HAVE_GETIFADDRS && LLADDR */
4226 res
= Fcons (elt
, res
);
4229 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4230 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4233 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4234 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4236 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4240 res
= Fcons (elt
, res
);
4243 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4244 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4247 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4250 res
= Fcons (elt
, res
);
4253 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4254 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4257 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4260 res
= Fcons (elt
, res
);
4262 return unbind_to (count
, any
? res
: Qnil
);
4264 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4265 #endif /* defined (HAVE_NET_IF_H) */
4267 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4268 Snetwork_interface_list
, 0, 0, 0,
4269 doc
: /* Return an alist of all network interfaces and their network address.
4270 Each element is a cons, the car of which is a string containing the
4271 interface name, and the cdr is the network address in internal
4272 format; see the description of ADDRESS in `make-network-process'.
4274 If the information is not available, return nil. */)
4277 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4278 return network_interface_list ();
4284 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4285 Snetwork_interface_info
, 1, 1, 0,
4286 doc
: /* Return information about network interface named IFNAME.
4287 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4288 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4289 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4290 FLAGS is the current flags of the interface.
4292 Data that is unavailable is returned as nil. */)
4293 (Lisp_Object ifname
)
4295 #if ((defined HAVE_NET_IF_H \
4296 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4297 || defined SIOCGIFFLAGS)) \
4298 || defined WINDOWSNT)
4299 return network_interface_info (ifname
);
4305 /* If program file NAME starts with /: for quoting a magic
4306 name, remove that, preserving the multibyteness of NAME. */
4309 remove_slash_colon (Lisp_Object name
)
4312 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
4313 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
4314 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
4318 /* Turn off input and output for process PROC. */
4321 deactivate_process (Lisp_Object proc
)
4324 struct Lisp_Process
*p
= XPROCESS (proc
);
4328 /* Delete GnuTLS structures in PROC, if any. */
4329 emacs_gnutls_deinit (proc
);
4330 #endif /* HAVE_GNUTLS */
4332 if (p
->read_output_delay
> 0)
4334 if (--process_output_delay_count
< 0)
4335 process_output_delay_count
= 0;
4336 p
->read_output_delay
= 0;
4337 p
->read_output_skip
= 0;
4340 /* Beware SIGCHLD hereabouts. */
4342 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4343 close_process_fd (&p
->open_fd
[i
]);
4345 inchannel
= p
->infd
;
4350 #ifdef DATAGRAM_SOCKETS
4351 if (DATAGRAM_CHAN_P (inchannel
))
4353 xfree (datagram_address
[inchannel
].sa
);
4354 datagram_address
[inchannel
].sa
= 0;
4355 datagram_address
[inchannel
].len
= 0;
4358 chan_process
[inchannel
] = Qnil
;
4359 FD_CLR (inchannel
, &input_wait_mask
);
4360 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4361 #ifdef NON_BLOCKING_CONNECT
4362 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4364 FD_CLR (inchannel
, &connect_wait_mask
);
4365 FD_CLR (inchannel
, &write_mask
);
4366 if (--num_pending_connects
< 0)
4370 if (inchannel
== max_process_desc
)
4372 /* We just closed the highest-numbered process input descriptor,
4373 so recompute the highest-numbered one now. */
4377 while (0 <= i
&& NILP (chan_process
[i
]));
4379 max_process_desc
= i
;
4385 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4387 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4388 It is given to their filter functions.
4389 Optional argument PROCESS means do not return until output has been
4390 received from PROCESS.
4392 Optional second argument SECONDS and third argument MILLISEC
4393 specify a timeout; return after that much time even if there is
4394 no subprocess output. If SECONDS is a floating point number,
4395 it specifies a fractional number of seconds to wait.
4396 The MILLISEC argument is obsolete and should be avoided.
4398 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4399 from PROCESS only, suspending reading output from other processes.
4400 If JUST-THIS-ONE is an integer, don't run any timers either.
4401 Return non-nil if we received any output from PROCESS (or, if PROCESS
4402 is nil, from any process) before the timeout expired. */)
4403 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4408 if (! NILP (process
))
4409 CHECK_PROCESS (process
);
4411 just_this_one
= Qnil
;
4413 if (!NILP (millisec
))
4414 { /* Obsolete calling convention using integers rather than floats. */
4415 CHECK_NUMBER (millisec
);
4417 seconds
= make_float (XINT (millisec
) / 1000.0);
4420 CHECK_NUMBER (seconds
);
4421 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4428 if (!NILP (seconds
))
4430 if (INTEGERP (seconds
))
4432 if (XINT (seconds
) > 0)
4434 secs
= XINT (seconds
);
4438 else if (FLOATP (seconds
))
4440 if (XFLOAT_DATA (seconds
) > 0)
4442 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4443 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4448 wrong_type_argument (Qnumberp
, seconds
);
4450 else if (! NILP (process
))
4454 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4456 !NILP (process
) ? XPROCESS (process
) : NULL
,
4457 (NILP (just_this_one
) ? 0
4458 : !INTEGERP (just_this_one
) ? 1 : -1))
4463 /* Accept a connection for server process SERVER on CHANNEL. */
4465 static EMACS_INT connect_counter
= 0;
4468 server_accept_connection (Lisp_Object server
, int channel
)
4470 Lisp_Object proc
, caller
, name
, buffer
;
4471 Lisp_Object contact
, host
, service
;
4472 struct Lisp_Process
*ps
= XPROCESS (server
);
4473 struct Lisp_Process
*p
;
4477 struct sockaddr_in in
;
4479 struct sockaddr_in6 in6
;
4481 #ifdef HAVE_LOCAL_SOCKETS
4482 struct sockaddr_un un
;
4485 socklen_t len
= sizeof saddr
;
4488 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4497 if (code
== EWOULDBLOCK
)
4501 if (!NILP (ps
->log
))
4502 call3 (ps
->log
, server
, Qnil
,
4503 concat3 (build_string ("accept failed with code"),
4504 Fnumber_to_string (make_number (code
)),
4505 build_string ("\n")));
4509 count
= SPECPDL_INDEX ();
4510 record_unwind_protect_int (close_file_unwind
, s
);
4514 /* Setup a new process to handle the connection. */
4516 /* Generate a unique identification of the caller, and build contact
4517 information for this process. */
4520 switch (saddr
.sa
.sa_family
)
4524 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4526 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4527 host
= CALLN (Fformat
, ipv4_format
,
4528 make_number (ip
[0]), make_number (ip
[1]),
4529 make_number (ip
[2]), make_number (ip
[3]));
4530 service
= make_number (ntohs (saddr
.in
.sin_port
));
4531 AUTO_STRING (caller_format
, " <%s:%d>");
4532 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4539 Lisp_Object args
[9];
4540 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4543 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4544 args
[0] = ipv6_format
;
4545 for (i
= 0; i
< 8; i
++)
4546 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4547 host
= CALLMANY (Fformat
, args
);
4548 service
= make_number (ntohs (saddr
.in
.sin_port
));
4549 AUTO_STRING (caller_format
, " <[%s]:%d>");
4550 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4555 #ifdef HAVE_LOCAL_SOCKETS
4559 caller
= Fnumber_to_string (make_number (connect_counter
));
4560 AUTO_STRING (space_less_than
, " <");
4561 AUTO_STRING (greater_than
, ">");
4562 caller
= concat3 (space_less_than
, caller
, greater_than
);
4566 /* Create a new buffer name for this process if it doesn't have a
4567 filter. The new buffer name is based on the buffer name or
4568 process name of the server process concatenated with the caller
4571 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4572 || EQ (ps
->filter
, Qt
)))
4576 buffer
= ps
->buffer
;
4578 buffer
= Fbuffer_name (buffer
);
4583 buffer
= concat2 (buffer
, caller
);
4584 buffer
= Fget_buffer_create (buffer
);
4588 /* Generate a unique name for the new server process. Combine the
4589 server process name with the caller identification. */
4591 name
= concat2 (ps
->name
, caller
);
4592 proc
= make_process (name
);
4594 chan_process
[s
] = proc
;
4596 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4598 p
= XPROCESS (proc
);
4600 /* Build new contact information for this setup. */
4601 contact
= Fcopy_sequence (ps
->childp
);
4602 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4603 contact
= Fplist_put (contact
, QChost
, host
);
4604 if (!NILP (service
))
4605 contact
= Fplist_put (contact
, QCservice
, service
);
4606 contact
= Fplist_put (contact
, QCremote
,
4607 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4608 #ifdef HAVE_GETSOCKNAME
4610 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4611 contact
= Fplist_put (contact
, QClocal
,
4612 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4615 pset_childp (p
, contact
);
4616 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4617 pset_type (p
, Qnetwork
);
4619 pset_buffer (p
, buffer
);
4620 pset_sentinel (p
, ps
->sentinel
);
4621 pset_filter (p
, ps
->filter
);
4622 pset_command (p
, Qnil
);
4625 /* Discard the unwind protect for closing S. */
4626 specpdl_ptr
= specpdl
+ count
;
4628 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4631 pset_status (p
, Qrun
);
4633 /* Client processes for accepted connections are not stopped initially. */
4634 if (!EQ (p
->filter
, Qt
))
4636 FD_SET (s
, &input_wait_mask
);
4637 FD_SET (s
, &non_keyboard_wait_mask
);
4640 if (s
> max_process_desc
)
4641 max_process_desc
= s
;
4643 /* Setup coding system for new process based on server process.
4644 This seems to be the proper thing to do, as the coding system
4645 of the new process should reflect the settings at the time the
4646 server socket was opened; not the current settings. */
4648 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4649 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4650 setup_process_coding_systems (proc
);
4652 pset_decoding_buf (p
, empty_unibyte_string
);
4653 p
->decoding_carryover
= 0;
4654 pset_encoding_buf (p
, empty_unibyte_string
);
4656 p
->inherit_coding_system_flag
4657 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4659 AUTO_STRING (dash
, "-");
4660 AUTO_STRING (nl
, "\n");
4661 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4663 if (!NILP (ps
->log
))
4665 AUTO_STRING (accept_from
, "accept from ");
4666 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4669 AUTO_STRING (open_from
, "open from ");
4670 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4673 #ifdef HAVE_GETADDRINFO_A
4675 check_for_dns (Lisp_Object proc
)
4677 struct Lisp_Process
*p
= XPROCESS (proc
);
4678 Lisp_Object ip_addresses
= Qnil
;
4682 if (! p
->dns_requests
)
4685 ret
= gai_error (p
->dns_requests
[0]);
4686 if (ret
== EAI_INPROGRESS
)
4689 /* We got a response. */
4692 struct addrinfo
*res
;
4694 for (res
= p
->dns_requests
[0]->ar_result
; res
; res
= res
->ai_next
)
4696 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4697 (res
->ai_addr
, res
->ai_addrlen
),
4701 ip_addresses
= Fnreverse (ip_addresses
);
4703 /* The DNS lookup failed. */
4704 else if (!EQ (p
->status
, Qconnect
))
4706 deactivate_process (proc
);
4707 pset_status (p
, (list2
4709 concat3 (build_string ("Name lookup of "),
4710 build_string (p
->dns_requests
[0]->ar_name
),
4711 build_string (" failed")))));
4714 free_dns_request (proc
);
4716 /* This process should not already be connected (or killed). */
4717 if (!EQ (p
->status
, Qconnect
))
4720 return ip_addresses
;
4723 #endif /* HAVE_GETADDRINFO_A */
4726 wait_for_socket_fds (Lisp_Object process
, char *name
)
4728 while (XPROCESS (process
)->infd
< 0 &&
4729 EQ (XPROCESS (process
)->status
, Qconnect
))
4731 printf("Waiting for socket from %s...\n", name
);
4732 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4737 wait_while_connecting (Lisp_Object process
)
4739 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4741 printf("Waiting for connection...\n");
4742 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4747 wait_for_tls_negotiation (Lisp_Object process
)
4750 while (EQ (XPROCESS (process
)->status
, Qconnect
) &&
4751 !NILP (XPROCESS (process
)->gnutls_boot_parameters
))
4753 printf("Waiting for TLS...\n");
4754 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4759 /* This variable is different from waiting_for_input in keyboard.c.
4760 It is used to communicate to a lisp process-filter/sentinel (via the
4761 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4762 for user-input when that process-filter was called.
4763 waiting_for_input cannot be used as that is by definition 0 when
4764 lisp code is being evalled.
4765 This is also used in record_asynch_buffer_change.
4766 For that purpose, this must be 0
4767 when not inside wait_reading_process_output. */
4768 static int waiting_for_user_input_p
;
4771 wait_reading_process_output_unwind (int data
)
4773 waiting_for_user_input_p
= data
;
4776 /* This is here so breakpoints can be put on it. */
4778 wait_reading_process_output_1 (void)
4782 /* Read and dispose of subprocess output while waiting for timeout to
4783 elapse and/or keyboard input to be available.
4787 If negative, gobble data immediately available but don't wait for any.
4790 an additional duration to wait, measured in nanoseconds
4791 If TIME_LIMIT is zero, then:
4792 If NSECS == 0, there is no limit.
4793 If NSECS > 0, the timeout consists of NSECS only.
4794 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4797 0 to ignore keyboard input, or
4798 1 to return when input is available, or
4799 -1 meaning caller will actually read the input, so don't throw to
4800 the quit handler, or
4802 DO_DISPLAY means redisplay should be done to show subprocess
4803 output that arrives.
4805 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4806 (and gobble terminal input into the buffer if any arrives).
4808 If WAIT_PROC is specified, wait until something arrives from that
4811 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4812 (suspending output from other processes). A negative value
4813 means don't run any timers either.
4815 Return positive if we received input from WAIT_PROC (or from any
4816 process if WAIT_PROC is null), zero if we attempted to receive
4817 input but got none, and negative if we didn't even try. */
4820 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4822 Lisp_Object wait_for_cell
,
4823 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4833 struct timespec timeout
, end_time
, timer_delay
;
4834 struct timespec got_output_end_time
= invalid_timespec ();
4835 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4836 int got_some_output
= -1;
4837 ptrdiff_t count
= SPECPDL_INDEX ();
4839 /* Close to the current time if known, an invalid timespec otherwise. */
4840 struct timespec now
= invalid_timespec ();
4842 FD_ZERO (&Available
);
4845 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4846 && !(CONSP (wait_proc
->status
)
4847 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4848 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4850 record_unwind_protect_int (wait_reading_process_output_unwind
,
4851 waiting_for_user_input_p
);
4852 waiting_for_user_input_p
= read_kbd
;
4854 if (TYPE_MAXIMUM (time_t) < time_limit
)
4855 time_limit
= TYPE_MAXIMUM (time_t);
4857 if (time_limit
< 0 || nsecs
< 0)
4859 else if (time_limit
> 0 || nsecs
> 0)
4862 now
= current_timespec ();
4863 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4870 bool process_skipped
= false;
4872 /* If calling from keyboard input, do not quit
4873 since we want to return C-g as an input character.
4874 Otherwise, do pending quit if requested. */
4877 else if (pending_signals
)
4878 process_pending_signals ();
4880 /* Exit now if the cell we're waiting for became non-nil. */
4881 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4884 #ifdef HAVE_GETADDRINFO_A
4886 Lisp_Object ip_addresses
;
4887 Lisp_Object process_list_head
, aproc
;
4888 struct Lisp_Process
*p
;
4890 FOR_EACH_PROCESS(process_list_head
, aproc
)
4892 p
= XPROCESS (aproc
);
4894 if (p
->dns_requests
&&
4895 (! wait_proc
|| p
== wait_proc
))
4897 ip_addresses
= check_for_dns (aproc
);
4898 if (!NILP (ip_addresses
) &&
4899 !EQ (ip_addresses
, Qt
))
4900 connect_network_socket (aproc
, ip_addresses
);
4904 #endif /* HAVE_GETADDRINFO_A */
4906 /* Compute time from now till when time limit is up. */
4907 /* Exit if already run out. */
4908 if (wait
== TIMEOUT
)
4910 if (!timespec_valid_p (now
))
4911 now
= current_timespec ();
4912 if (timespec_cmp (end_time
, now
) <= 0)
4914 timeout
= timespec_sub (end_time
, now
);
4917 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4919 /* Normally we run timers here.
4920 But not if wait_for_cell; in those cases,
4921 the wait is supposed to be short,
4922 and those callers cannot handle running arbitrary Lisp code here. */
4923 if (NILP (wait_for_cell
)
4924 && just_wait_proc
>= 0)
4928 unsigned old_timers_run
= timers_run
;
4929 struct buffer
*old_buffer
= current_buffer
;
4930 Lisp_Object old_window
= selected_window
;
4932 timer_delay
= timer_check ();
4934 /* If a timer has run, this might have changed buffers
4935 an alike. Make read_key_sequence aware of that. */
4936 if (timers_run
!= old_timers_run
4937 && (old_buffer
!= current_buffer
4938 || !EQ (old_window
, selected_window
))
4939 && waiting_for_user_input_p
== -1)
4940 record_asynch_buffer_change ();
4942 if (timers_run
!= old_timers_run
&& do_display
)
4943 /* We must retry, since a timer may have requeued itself
4944 and that could alter the time_delay. */
4945 redisplay_preserve_echo_area (9);
4949 while (!detect_input_pending ());
4951 /* If there is unread keyboard input, also return. */
4953 && requeued_events_pending_p ())
4956 /* This is so a breakpoint can be put here. */
4957 if (!timespec_valid_p (timer_delay
))
4958 wait_reading_process_output_1 ();
4961 /* Cause C-g and alarm signals to take immediate action,
4962 and cause input available signals to zero out timeout.
4964 It is important that we do this before checking for process
4965 activity. If we get a SIGCHLD after the explicit checks for
4966 process activity, timeout is the only way we will know. */
4968 set_waiting_for_input (&timeout
);
4970 /* If status of something has changed, and no input is
4971 available, notify the user of the change right away. After
4972 this explicit check, we'll let the SIGCHLD handler zap
4973 timeout to get our attention. */
4974 if (update_tick
!= process_tick
)
4979 if (kbd_on_hold_p ())
4982 Atemp
= input_wait_mask
;
4985 timeout
= make_timespec (0, 0);
4986 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4988 #ifdef NON_BLOCKING_CONNECT
4989 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4993 NULL
, &timeout
, NULL
)
4996 /* It's okay for us to do this and then continue with
4997 the loop, since timeout has already been zeroed out. */
4998 clear_waiting_for_input ();
4999 got_some_output
= status_notify (NULL
, wait_proc
);
5000 if (do_display
) redisplay_preserve_echo_area (13);
5004 /* Don't wait for output from a non-running process. Just
5005 read whatever data has already been received. */
5006 if (wait_proc
&& wait_proc
->raw_status_new
)
5007 update_status (wait_proc
);
5009 && ! EQ (wait_proc
->status
, Qrun
)
5010 && ! EQ (wait_proc
->status
, Qconnect
))
5012 bool read_some_bytes
= false;
5014 clear_waiting_for_input ();
5016 /* If data can be read from the process, do so until exhausted. */
5017 if (wait_proc
->infd
>= 0)
5019 XSETPROCESS (proc
, wait_proc
);
5023 int nread
= read_process_output (proc
, wait_proc
->infd
);
5026 if (errno
== EIO
|| errno
== EAGAIN
)
5029 if (errno
== EWOULDBLOCK
)
5035 if (got_some_output
< nread
)
5036 got_some_output
= nread
;
5039 read_some_bytes
= true;
5044 if (read_some_bytes
&& do_display
)
5045 redisplay_preserve_echo_area (10);
5050 /* Wait till there is something to do. */
5052 if (wait_proc
&& just_wait_proc
)
5054 if (wait_proc
->infd
< 0) /* Terminated. */
5056 FD_SET (wait_proc
->infd
, &Available
);
5060 else if (!NILP (wait_for_cell
))
5062 Available
= non_process_wait_mask
;
5069 Available
= non_keyboard_wait_mask
;
5071 Available
= input_wait_mask
;
5072 Writeok
= write_mask
;
5073 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5077 /* If frame size has changed or the window is newly mapped,
5078 redisplay now, before we start to wait. There is a race
5079 condition here; if a SIGIO arrives between now and the select
5080 and indicates that a frame is trashed, the select may block
5081 displaying a trashed screen. */
5082 if (frame_garbaged
&& do_display
)
5084 clear_waiting_for_input ();
5085 redisplay_preserve_echo_area (11);
5087 set_waiting_for_input (&timeout
);
5090 /* Skip the `select' call if input is available and we're
5091 waiting for keyboard input or a cell change (which can be
5092 triggered by processing X events). In the latter case, set
5093 nfds to 1 to avoid breaking the loop. */
5095 if ((read_kbd
|| !NILP (wait_for_cell
))
5096 && detect_input_pending ())
5098 nfds
= read_kbd
? 0 : 1;
5100 FD_ZERO (&Available
);
5104 /* Set the timeout for adaptive read buffering if any
5105 process has non-zero read_output_skip and non-zero
5106 read_output_delay, and we are not reading output for a
5107 specific process. It is not executed if
5108 Vprocess_adaptive_read_buffering is nil. */
5109 if (process_output_skip
&& check_delay
> 0)
5111 int adaptive_nsecs
= timeout
.tv_nsec
;
5112 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5113 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5114 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5116 proc
= chan_process
[channel
];
5119 /* Find minimum non-zero read_output_delay among the
5120 processes with non-zero read_output_skip. */
5121 if (XPROCESS (proc
)->read_output_delay
> 0)
5124 if (!XPROCESS (proc
)->read_output_skip
)
5126 FD_CLR (channel
, &Available
);
5127 process_skipped
= true;
5128 XPROCESS (proc
)->read_output_skip
= 0;
5129 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5130 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5133 timeout
= make_timespec (0, adaptive_nsecs
);
5134 process_output_skip
= 0;
5137 /* If we've got some output and haven't limited our timeout
5138 with adaptive read buffering, limit it. */
5139 if (got_some_output
> 0 && !process_skipped
5141 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5142 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5145 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5146 && timespec_valid_p (timer_delay
)
5147 && timespec_cmp (timer_delay
, timeout
) < 0)
5149 if (!timespec_valid_p (now
))
5150 now
= current_timespec ();
5151 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5152 if (!timespec_valid_p (got_output_end_time
)
5153 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5154 got_output_end_time
= timeout_abs
;
5155 timeout
= timer_delay
;
5158 got_output_end_time
= invalid_timespec ();
5160 /* NOW can become inaccurate if time can pass during pselect. */
5161 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5162 now
= invalid_timespec ();
5164 #if defined (HAVE_NS)
5166 #elif defined (HAVE_GLIB)
5171 (max (max_process_desc
, max_input_desc
) + 1,
5173 (check_write
? &Writeok
: 0),
5174 NULL
, &timeout
, NULL
);
5177 /* GnuTLS buffers data internally. In lowat mode it leaves
5178 some data in the TCP buffers so that select works, but
5179 with custom pull/push functions we need to check if some
5180 data is available in the buffers manually. */
5183 fd_set tls_available
;
5186 FD_ZERO (&tls_available
);
5189 /* We're not waiting on a specific process, so loop
5190 through all the channels and check for data.
5191 This is a workaround needed for some versions of
5192 the gnutls library -- 2.12.14 has been confirmed
5194 http://comments.gmane.org/gmane.emacs.devel/145074 */
5195 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5196 if (! NILP (chan_process
[channel
]))
5198 struct Lisp_Process
*p
=
5199 XPROCESS (chan_process
[channel
]);
5200 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5201 && ((emacs_gnutls_record_check_pending
5206 eassert (p
->infd
== channel
);
5207 FD_SET (p
->infd
, &tls_available
);
5214 /* Check this specific channel. */
5215 if (wait_proc
->gnutls_p
/* Check for valid process. */
5216 && wait_proc
->gnutls_state
5217 /* Do we have pending data? */
5218 && ((emacs_gnutls_record_check_pending
5219 (wait_proc
->gnutls_state
))
5223 eassert (0 <= wait_proc
->infd
);
5224 /* Set to Available. */
5225 FD_SET (wait_proc
->infd
, &tls_available
);
5230 Available
= tls_available
;
5237 /* Make C-g and alarm signals set flags again. */
5238 clear_waiting_for_input ();
5240 /* If we woke up due to SIGWINCH, actually change size now. */
5241 do_pending_window_change (0);
5245 /* Exit the main loop if we've passed the requested timeout,
5246 or aren't skipping processes and got some output and
5247 haven't lowered our timeout due to timers or SIGIO and
5248 have waited a long amount of time due to repeated
5252 struct timespec cmp_time
5255 : (!process_skipped
&& got_some_output
> 0
5256 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5257 ? got_output_end_time
5258 : invalid_timespec ());
5259 if (timespec_valid_p (cmp_time
))
5261 now
= current_timespec ();
5262 if (timespec_cmp (cmp_time
, now
) <= 0)
5269 if (xerrno
== EINTR
)
5271 else if (xerrno
== EBADF
)
5274 report_file_errno ("Failed select", Qnil
, xerrno
);
5277 /* Check for keyboard input. */
5278 /* If there is any, return immediately
5279 to give it higher priority than subprocesses. */
5283 unsigned old_timers_run
= timers_run
;
5284 struct buffer
*old_buffer
= current_buffer
;
5285 Lisp_Object old_window
= selected_window
;
5288 if (detect_input_pending_run_timers (do_display
))
5290 swallow_events (do_display
);
5291 if (detect_input_pending_run_timers (do_display
))
5295 /* If a timer has run, this might have changed buffers
5296 an alike. Make read_key_sequence aware of that. */
5297 if (timers_run
!= old_timers_run
5298 && waiting_for_user_input_p
== -1
5299 && (old_buffer
!= current_buffer
5300 || !EQ (old_window
, selected_window
)))
5301 record_asynch_buffer_change ();
5307 /* If there is unread keyboard input, also return. */
5309 && requeued_events_pending_p ())
5312 /* If we are not checking for keyboard input now,
5313 do process events (but don't run any timers).
5314 This is so that X events will be processed.
5315 Otherwise they may have to wait until polling takes place.
5316 That would causes delays in pasting selections, for example.
5318 (We used to do this only if wait_for_cell.) */
5319 if (read_kbd
== 0 && detect_input_pending ())
5321 swallow_events (do_display
);
5322 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5323 if (detect_input_pending ())
5328 /* Exit now if the cell we're waiting for became non-nil. */
5329 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5333 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5334 go read it. This can happen with X on BSD after logging out.
5335 In that case, there really is no input and no SIGIO,
5336 but select says there is input. */
5338 if (read_kbd
&& interrupt_input
5339 && keyboard_bit_set (&Available
) && ! noninteractive
)
5340 handle_input_available_signal (SIGIO
);
5343 /* If checking input just got us a size-change event from X,
5344 obey it now if we should. */
5345 if (read_kbd
|| ! NILP (wait_for_cell
))
5346 do_pending_window_change (0);
5348 /* Check for data from a process. */
5349 if (no_avail
|| nfds
== 0)
5352 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5354 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5356 && ((d
->condition
& FOR_READ
5357 && FD_ISSET (channel
, &Available
))
5358 || (d
->condition
& FOR_WRITE
5359 && FD_ISSET (channel
, &write_mask
))))
5360 d
->func (channel
, d
->data
);
5363 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5365 if (FD_ISSET (channel
, &Available
)
5366 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5367 && !FD_ISSET (channel
, &non_process_wait_mask
))
5371 /* If waiting for this channel, arrange to return as
5372 soon as no more input to be processed. No more
5374 proc
= chan_process
[channel
];
5378 /* If this is a server stream socket, accept connection. */
5379 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5381 server_accept_connection (proc
, channel
);
5385 /* Read data from the process, starting with our
5386 buffered-ahead character if we have one. */
5388 nread
= read_process_output (proc
, channel
);
5389 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5390 && got_some_output
< nread
)
5391 got_some_output
= nread
;
5394 /* Vacuum up any leftovers without waiting. */
5395 if (wait_proc
== XPROCESS (proc
))
5397 /* Since read_process_output can run a filter,
5398 which can call accept-process-output,
5399 don't try to read from any other processes
5400 before doing the select again. */
5401 FD_ZERO (&Available
);
5404 redisplay_preserve_echo_area (12);
5407 else if (nread
== -1 && errno
== EWOULDBLOCK
)
5410 else if (nread
== -1 && errno
== EAGAIN
)
5413 /* FIXME: Is this special case still needed? */
5414 /* Note that we cannot distinguish between no input
5415 available now and a closed pipe.
5416 With luck, a closed pipe will be accompanied by
5417 subprocess termination and SIGCHLD. */
5418 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5419 && !PIPECONN_P (proc
))
5423 /* On some OSs with ptys, when the process on one end of
5424 a pty exits, the other end gets an error reading with
5425 errno = EIO instead of getting an EOF (0 bytes read).
5426 Therefore, if we get an error reading and errno =
5427 EIO, just continue, because the child process has
5428 exited and should clean itself up soon (e.g. when we
5430 else if (nread
== -1 && errno
== EIO
)
5432 struct Lisp_Process
*p
= XPROCESS (proc
);
5434 /* Clear the descriptor now, so we only raise the
5436 FD_CLR (channel
, &input_wait_mask
);
5437 FD_CLR (channel
, &non_keyboard_wait_mask
);
5441 /* If the EIO occurs on a pty, the SIGCHLD handler's
5442 waitpid call will not find the process object to
5443 delete. Do it here. */
5444 p
->tick
= ++process_tick
;
5445 pset_status (p
, Qfailed
);
5448 #endif /* HAVE_PTYS */
5449 /* If we can detect process termination, don't consider the
5450 process gone just because its pipe is closed. */
5451 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5452 && !PIPECONN_P (proc
))
5454 else if (nread
== 0 && PIPECONN_P (proc
))
5456 /* Preserve status of processes already terminated. */
5457 XPROCESS (proc
)->tick
= ++process_tick
;
5458 deactivate_process (proc
);
5459 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5460 pset_status (XPROCESS (proc
),
5461 list2 (Qexit
, make_number (0)));
5465 /* Preserve status of processes already terminated. */
5466 XPROCESS (proc
)->tick
= ++process_tick
;
5467 deactivate_process (proc
);
5468 if (XPROCESS (proc
)->raw_status_new
)
5469 update_status (XPROCESS (proc
));
5470 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5471 pset_status (XPROCESS (proc
),
5472 list2 (Qexit
, make_number (256)));
5475 #ifdef NON_BLOCKING_CONNECT
5476 if (FD_ISSET (channel
, &Writeok
)
5477 && FD_ISSET (channel
, &connect_wait_mask
))
5479 struct Lisp_Process
*p
;
5481 FD_CLR (channel
, &connect_wait_mask
);
5482 FD_CLR (channel
, &write_mask
);
5483 if (--num_pending_connects
< 0)
5486 proc
= chan_process
[channel
];
5490 p
= XPROCESS (proc
);
5493 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5494 So only use it on systems where it is known to work. */
5496 socklen_t xlen
= sizeof (xerrno
);
5497 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5502 struct sockaddr pname
;
5503 socklen_t pnamelen
= sizeof (pname
);
5505 /* If connection failed, getpeername will fail. */
5507 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5509 /* Obtain connect failure code through error slippage. */
5512 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5519 p
->tick
= ++process_tick
;
5520 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5521 deactivate_process (proc
);
5525 if (NILP (p
->gnutls_boot_parameters
))
5527 pset_status (p
, Qrun
);
5528 /* Execute the sentinel here. If we had relied on
5529 status_notify to do it later, it will read input
5530 from the process before calling the sentinel. */
5531 exec_sentinel (proc
, build_string ("open\n"));
5534 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5535 && !EQ (p
->command
, Qt
))
5537 FD_SET (p
->infd
, &input_wait_mask
);
5538 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5542 #endif /* NON_BLOCKING_CONNECT */
5543 } /* End for each file descriptor. */
5544 } /* End while exit conditions not met. */
5546 unbind_to (count
, Qnil
);
5548 /* If calling from keyboard input, do not quit
5549 since we want to return C-g as an input character.
5550 Otherwise, do pending quit if requested. */
5553 /* Prevent input_pending from remaining set if we quit. */
5554 clear_input_pending ();
5558 return got_some_output
;
5561 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5564 read_process_output_call (Lisp_Object fun_and_args
)
5566 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5570 read_process_output_error_handler (Lisp_Object error_val
)
5572 cmd_error_internal (error_val
, "error in process filter: ");
5574 update_echo_area ();
5575 Fsleep_for (make_number (2), Qnil
);
5580 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5582 struct coding_system
*coding
);
5584 /* Read pending output from the process channel,
5585 starting with our buffered-ahead character if we have one.
5586 Yield number of decoded characters read.
5588 This function reads at most 4096 characters.
5589 If you want to read all available subprocess output,
5590 you must call it repeatedly until it returns zero.
5592 The characters read are decoded according to PROC's coding-system
5596 read_process_output (Lisp_Object proc
, int channel
)
5599 struct Lisp_Process
*p
= XPROCESS (proc
);
5600 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5601 int carryover
= p
->decoding_carryover
;
5602 enum { readmax
= 4096 };
5603 ptrdiff_t count
= SPECPDL_INDEX ();
5604 Lisp_Object odeactivate
;
5605 char chars
[sizeof coding
->carryover
+ readmax
];
5608 /* See the comment above. */
5609 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5611 #ifdef DATAGRAM_SOCKETS
5612 /* We have a working select, so proc_buffered_char is always -1. */
5613 if (DATAGRAM_CHAN_P (channel
))
5615 socklen_t len
= datagram_address
[channel
].len
;
5616 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5617 0, datagram_address
[channel
].sa
, &len
);
5622 bool buffered
= proc_buffered_char
[channel
] >= 0;
5625 chars
[carryover
] = proc_buffered_char
[channel
];
5626 proc_buffered_char
[channel
] = -1;
5629 if (p
->gnutls_p
&& p
->gnutls_state
)
5630 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5631 readmax
- buffered
);
5634 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5635 readmax
- buffered
);
5636 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5638 int delay
= p
->read_output_delay
;
5641 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5644 process_output_delay_count
++;
5645 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5648 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5650 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5652 process_output_delay_count
--;
5654 p
->read_output_delay
= delay
;
5657 p
->read_output_skip
= 1;
5658 process_output_skip
= 1;
5662 nbytes
+= buffered
&& nbytes
<= 0;
5665 p
->decoding_carryover
= 0;
5667 /* At this point, NBYTES holds number of bytes just received
5668 (including the one in proc_buffered_char[channel]). */
5671 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5673 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5676 /* Now set NBYTES how many bytes we must decode. */
5677 nbytes
+= carryover
;
5679 odeactivate
= Vdeactivate_mark
;
5680 /* There's no good reason to let process filters change the current
5681 buffer, and many callers of accept-process-output, sit-for, and
5682 friends don't expect current-buffer to be changed from under them. */
5683 record_unwind_current_buffer ();
5685 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5687 /* Handling the process output should not deactivate the mark. */
5688 Vdeactivate_mark
= odeactivate
;
5690 unbind_to (count
, Qnil
);
5695 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5697 struct coding_system
*coding
)
5699 Lisp_Object outstream
= p
->filter
;
5701 bool outer_running_asynch_code
= running_asynch_code
;
5702 int waiting
= waiting_for_user_input_p
;
5705 Lisp_Object obuffer
, okeymap
;
5706 XSETBUFFER (obuffer
, current_buffer
);
5707 okeymap
= BVAR (current_buffer
, keymap
);
5710 /* We inhibit quit here instead of just catching it so that
5711 hitting ^G when a filter happens to be running won't screw
5713 specbind (Qinhibit_quit
, Qt
);
5714 specbind (Qlast_nonmenu_event
, Qt
);
5716 /* In case we get recursively called,
5717 and we already saved the match data nonrecursively,
5718 save the same match data in safely recursive fashion. */
5719 if (outer_running_asynch_code
)
5722 /* Don't clobber the CURRENT match data, either! */
5723 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5724 restore_search_regs ();
5725 record_unwind_save_match_data ();
5726 Fset_match_data (tem
, Qt
);
5729 /* For speed, if a search happens within this code,
5730 save the match data in a special nonrecursive fashion. */
5731 running_asynch_code
= 1;
5733 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5734 text
= coding
->dst_object
;
5735 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5736 /* A new coding system might be found. */
5737 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5739 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5741 /* Don't call setup_coding_system for
5742 proc_decode_coding_system[channel] here. It is done in
5743 detect_coding called via decode_coding above. */
5745 /* If a coding system for encoding is not yet decided, we set
5746 it as the same as coding-system for decoding.
5748 But, before doing that we must check if
5749 proc_encode_coding_system[p->outfd] surely points to a
5750 valid memory because p->outfd will be changed once EOF is
5751 sent to the process. */
5752 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5753 && proc_encode_coding_system
[p
->outfd
])
5755 pset_encode_coding_system
5756 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5757 setup_coding_system (p
->encode_coding_system
,
5758 proc_encode_coding_system
[p
->outfd
]);
5762 if (coding
->carryover_bytes
> 0)
5764 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5765 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5766 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5767 coding
->carryover_bytes
);
5768 p
->decoding_carryover
= coding
->carryover_bytes
;
5770 if (SBYTES (text
) > 0)
5771 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5772 sometimes it's simply wrong to wrap (e.g. when called from
5773 accept-process-output). */
5774 internal_condition_case_1 (read_process_output_call
,
5775 list3 (outstream
, make_lisp_proc (p
), text
),
5776 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5777 read_process_output_error_handler
);
5779 /* If we saved the match data nonrecursively, restore it now. */
5780 restore_search_regs ();
5781 running_asynch_code
= outer_running_asynch_code
;
5783 /* Restore waiting_for_user_input_p as it was
5784 when we were called, in case the filter clobbered it. */
5785 waiting_for_user_input_p
= waiting
;
5787 #if 0 /* Call record_asynch_buffer_change unconditionally,
5788 because we might have changed minor modes or other things
5789 that affect key bindings. */
5790 if (! EQ (Fcurrent_buffer (), obuffer
)
5791 || ! EQ (current_buffer
->keymap
, okeymap
))
5793 /* But do it only if the caller is actually going to read events.
5794 Otherwise there's no need to make him wake up, and it could
5795 cause trouble (for example it would make sit_for return). */
5796 if (waiting_for_user_input_p
== -1)
5797 record_asynch_buffer_change ();
5800 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5801 Sinternal_default_process_filter
, 2, 2, 0,
5802 doc
: /* Function used as default process filter.
5803 This inserts the process's output into its buffer, if there is one.
5804 Otherwise it discards the output. */)
5805 (Lisp_Object proc
, Lisp_Object text
)
5807 struct Lisp_Process
*p
;
5810 CHECK_PROCESS (proc
);
5811 p
= XPROCESS (proc
);
5812 CHECK_STRING (text
);
5814 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5816 Lisp_Object old_read_only
;
5817 ptrdiff_t old_begv
, old_zv
;
5818 ptrdiff_t old_begv_byte
, old_zv_byte
;
5819 ptrdiff_t before
, before_byte
;
5820 ptrdiff_t opoint_byte
;
5823 Fset_buffer (p
->buffer
);
5825 opoint_byte
= PT_BYTE
;
5826 old_read_only
= BVAR (current_buffer
, read_only
);
5829 old_begv_byte
= BEGV_BYTE
;
5830 old_zv_byte
= ZV_BYTE
;
5832 bset_read_only (current_buffer
, Qnil
);
5834 /* Insert new output into buffer at the current end-of-output
5835 marker, thus preserving logical ordering of input and output. */
5836 if (XMARKER (p
->mark
)->buffer
)
5837 set_point_from_marker (p
->mark
);
5839 SET_PT_BOTH (ZV
, ZV_BYTE
);
5841 before_byte
= PT_BYTE
;
5843 /* If the output marker is outside of the visible region, save
5844 the restriction and widen. */
5845 if (! (BEGV
<= PT
&& PT
<= ZV
))
5848 /* Adjust the multibyteness of TEXT to that of the buffer. */
5849 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5850 != ! STRING_MULTIBYTE (text
))
5851 text
= (STRING_MULTIBYTE (text
)
5852 ? Fstring_as_unibyte (text
)
5853 : Fstring_to_multibyte (text
));
5854 /* Insert before markers in case we are inserting where
5855 the buffer's mark is, and the user's next command is Meta-y. */
5856 insert_from_string_before_markers (text
, 0, 0,
5857 SCHARS (text
), SBYTES (text
), 0);
5859 /* Make sure the process marker's position is valid when the
5860 process buffer is changed in the signal_after_change above.
5861 W3 is known to do that. */
5862 if (BUFFERP (p
->buffer
)
5863 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5864 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5866 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5868 update_mode_lines
= 23;
5870 /* Make sure opoint and the old restrictions
5871 float ahead of any new text just as point would. */
5872 if (opoint
>= before
)
5874 opoint
+= PT
- before
;
5875 opoint_byte
+= PT_BYTE
- before_byte
;
5877 if (old_begv
> before
)
5879 old_begv
+= PT
- before
;
5880 old_begv_byte
+= PT_BYTE
- before_byte
;
5882 if (old_zv
>= before
)
5884 old_zv
+= PT
- before
;
5885 old_zv_byte
+= PT_BYTE
- before_byte
;
5888 /* If the restriction isn't what it should be, set it. */
5889 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5890 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5892 bset_read_only (current_buffer
, old_read_only
);
5893 SET_PT_BOTH (opoint
, opoint_byte
);
5898 /* Sending data to subprocess. */
5900 /* In send_process, when a write fails temporarily,
5901 wait_reading_process_output is called. It may execute user code,
5902 e.g. timers, that attempts to write new data to the same process.
5903 We must ensure that data is sent in the right order, and not
5904 interspersed half-completed with other writes (Bug#10815). This is
5905 handled by the write_queue element of struct process. It is a list
5906 with each entry having the form
5908 (string . (offset . length))
5910 where STRING is a lisp string, OFFSET is the offset into the
5911 string's byte sequence from which we should begin to send, and
5912 LENGTH is the number of bytes left to send. */
5914 /* Create a new entry in write_queue.
5915 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5916 BUF is a pointer to the string sequence of the input_obj or a C
5917 string in case of Qt or Qnil. */
5920 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5921 const char *buf
, ptrdiff_t len
, bool front
)
5924 Lisp_Object entry
, obj
;
5926 if (STRINGP (input_obj
))
5928 offset
= buf
- SSDATA (input_obj
);
5934 obj
= make_unibyte_string (buf
, len
);
5937 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5940 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5942 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5945 /* Remove the first element in the write_queue of process P, put its
5946 contents in OBJ, BUF and LEN, and return true. If the
5947 write_queue is empty, return false. */
5950 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5951 const char **buf
, ptrdiff_t *len
)
5953 Lisp_Object entry
, offset_length
;
5956 if (NILP (p
->write_queue
))
5959 entry
= XCAR (p
->write_queue
);
5960 pset_write_queue (p
, XCDR (p
->write_queue
));
5962 *obj
= XCAR (entry
);
5963 offset_length
= XCDR (entry
);
5965 *len
= XINT (XCDR (offset_length
));
5966 offset
= XINT (XCAR (offset_length
));
5967 *buf
= SSDATA (*obj
) + offset
;
5972 /* Send some data to process PROC.
5973 BUF is the beginning of the data; LEN is the number of characters.
5974 OBJECT is the Lisp object that the data comes from. If OBJECT is
5975 nil or t, it means that the data comes from C string.
5977 If OBJECT is not nil, the data is encoded by PROC's coding-system
5978 for encoding before it is sent.
5980 This function can evaluate Lisp code and can garbage collect. */
5983 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5986 struct Lisp_Process
*p
= XPROCESS (proc
);
5988 struct coding_system
*coding
;
5990 if (NETCONN_P (proc
)) {
5991 wait_while_connecting (proc
);
5992 wait_for_tls_negotiation (proc
);
5995 if (p
->raw_status_new
)
5997 if (! EQ (p
->status
, Qrun
))
5998 error ("Process %s not running", SDATA (p
->name
));
6000 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6002 coding
= proc_encode_coding_system
[p
->outfd
];
6003 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6005 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6006 || (BUFFERP (object
)
6007 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6010 pset_encode_coding_system
6011 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6012 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6014 /* The coding system for encoding was changed to raw-text
6015 because we sent a unibyte text previously. Now we are
6016 sending a multibyte text, thus we must encode it by the
6017 original coding system specified for the current process.
6019 Another reason we come here is that the coding system
6020 was just complemented and a new one was returned by
6021 complement_process_encoding_system. */
6022 setup_coding_system (p
->encode_coding_system
, coding
);
6023 Vlast_coding_system_used
= p
->encode_coding_system
;
6025 coding
->src_multibyte
= 1;
6029 coding
->src_multibyte
= 0;
6030 /* For sending a unibyte text, character code conversion should
6031 not take place but EOL conversion should. So, setup raw-text
6032 or one of the subsidiary if we have not yet done it. */
6033 if (CODING_REQUIRE_ENCODING (coding
))
6035 if (CODING_REQUIRE_FLUSHING (coding
))
6037 /* But, before changing the coding, we must flush out data. */
6038 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6039 send_process (proc
, "", 0, Qt
);
6040 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6042 setup_coding_system (raw_text_coding_system
6043 (Vlast_coding_system_used
),
6045 coding
->src_multibyte
= 0;
6048 coding
->dst_multibyte
= 0;
6050 if (CODING_REQUIRE_ENCODING (coding
))
6052 coding
->dst_object
= Qt
;
6053 if (BUFFERP (object
))
6055 ptrdiff_t from_byte
, from
, to
;
6056 ptrdiff_t save_pt
, save_pt_byte
;
6057 struct buffer
*cur
= current_buffer
;
6059 set_buffer_internal (XBUFFER (object
));
6060 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6062 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6063 from
= BYTE_TO_CHAR (from_byte
);
6064 to
= BYTE_TO_CHAR (from_byte
+ len
);
6065 TEMP_SET_PT_BOTH (from
, from_byte
);
6066 encode_coding_object (coding
, object
, from
, from_byte
,
6067 to
, from_byte
+ len
, Qt
);
6068 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6069 set_buffer_internal (cur
);
6071 else if (STRINGP (object
))
6073 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6074 SBYTES (object
), Qt
);
6078 coding
->dst_object
= make_unibyte_string (buf
, len
);
6079 coding
->produced
= len
;
6082 len
= coding
->produced
;
6083 object
= coding
->dst_object
;
6084 buf
= SSDATA (object
);
6087 /* If there is already data in the write_queue, put the new data
6088 in the back of queue. Otherwise, ignore it. */
6089 if (!NILP (p
->write_queue
))
6090 write_queue_push (p
, object
, buf
, len
, 0);
6092 do /* while !NILP (p->write_queue) */
6094 ptrdiff_t cur_len
= -1;
6095 const char *cur_buf
;
6096 Lisp_Object cur_object
;
6098 /* If write_queue is empty, ignore it. */
6099 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6103 cur_object
= object
;
6108 /* Send this batch, using one or more write calls. */
6109 ptrdiff_t written
= 0;
6110 int outfd
= p
->outfd
;
6111 #ifdef DATAGRAM_SOCKETS
6112 if (DATAGRAM_CHAN_P (outfd
))
6114 rv
= sendto (outfd
, cur_buf
, cur_len
,
6115 0, datagram_address
[outfd
].sa
,
6116 datagram_address
[outfd
].len
);
6119 else if (errno
== EMSGSIZE
)
6120 report_file_error ("Sending datagram", proc
);
6126 if (p
->gnutls_p
&& p
->gnutls_state
)
6127 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6130 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6131 rv
= (written
? 0 : -1);
6132 if (p
->read_output_delay
> 0
6133 && p
->adaptive_read_buffering
== 1)
6135 p
->read_output_delay
= 0;
6136 process_output_delay_count
--;
6137 p
->read_output_skip
= 0;
6145 || errno
== EWOULDBLOCK
6148 /* Buffer is full. Wait, accepting input;
6149 that may allow the program
6150 to finish doing output and read more. */
6152 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6153 /* A gross hack to work around a bug in FreeBSD.
6154 In the following sequence, read(2) returns
6158 write(2) 954 bytes, get EAGAIN
6159 read(2) 1024 bytes in process_read_output
6160 read(2) 11 bytes in process_read_output
6162 That is, read(2) returns more bytes than have
6163 ever been written successfully. The 1033 bytes
6164 read are the 1022 bytes written successfully
6165 after processing (for example with CRs added if
6166 the terminal is set up that way which it is
6167 here). The same bytes will be seen again in a
6168 later read(2), without the CRs. */
6170 if (errno
== EAGAIN
)
6173 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6175 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6177 /* Put what we should have written in wait_queue. */
6178 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6179 wait_reading_process_output (0, 20 * 1000 * 1000,
6180 0, 0, Qnil
, NULL
, 0);
6181 /* Reread queue, to see what is left. */
6184 else if (errno
== EPIPE
)
6186 p
->raw_status_new
= 0;
6187 pset_status (p
, list2 (Qexit
, make_number (256)));
6188 p
->tick
= ++process_tick
;
6189 deactivate_process (proc
);
6190 error ("process %s no longer connected to pipe; closed it",
6194 /* This is a real error. */
6195 report_file_error ("Writing to process", proc
);
6201 while (!NILP (p
->write_queue
));
6204 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6206 doc
: /* Send current contents of region as input to PROCESS.
6207 PROCESS may be a process, a buffer, the name of a process or buffer, or
6208 nil, indicating the current buffer's process.
6209 Called from program, takes three arguments, PROCESS, START and END.
6210 If the region is more than 500 characters long,
6211 it is sent in several bunches. This may happen even for shorter regions.
6212 Output from processes can arrive in between bunches. */)
6213 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6215 Lisp_Object proc
= get_process (process
);
6216 ptrdiff_t start_byte
, end_byte
;
6218 validate_region (&start
, &end
);
6220 start_byte
= CHAR_TO_BYTE (XINT (start
));
6221 end_byte
= CHAR_TO_BYTE (XINT (end
));
6223 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6224 move_gap_both (XINT (start
), start_byte
);
6226 if (NETCONN_P (proc
))
6227 wait_while_connecting (proc
);
6229 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6230 end_byte
- start_byte
, Fcurrent_buffer ());
6235 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6237 doc
: /* Send PROCESS the contents of STRING as input.
6238 PROCESS may be a process, a buffer, the name of a process or buffer, or
6239 nil, indicating the current buffer's process.
6240 If STRING is more than 500 characters long,
6241 it is sent in several bunches. This may happen even for shorter strings.
6242 Output from processes can arrive in between bunches. */)
6243 (Lisp_Object process
, Lisp_Object string
)
6246 CHECK_STRING (string
);
6247 proc
= get_process (process
);
6249 send_process (proc
, SSDATA (string
),
6250 SBYTES (string
), string
);
6254 /* Return the foreground process group for the tty/pty that
6255 the process P uses. */
6257 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6262 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6265 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6266 master side. Try the slave side. */
6267 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6271 ioctl (fd
, TIOCGPGRP
, &gid
);
6275 #endif /* defined (TIOCGPGRP ) */
6280 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6281 Sprocess_running_child_p
, 0, 1, 0,
6282 doc
: /* Return non-nil if PROCESS has given the terminal to a
6283 child. If the operating system does not make it possible to find out,
6284 return t. If we can find out, return the numeric ID of the foreground
6286 (Lisp_Object process
)
6288 /* Initialize in case ioctl doesn't exist or gives an error,
6289 in a way that will cause returning t. */
6292 struct Lisp_Process
*p
;
6294 proc
= get_process (process
);
6295 p
= XPROCESS (proc
);
6297 if (!EQ (p
->type
, Qreal
))
6298 error ("Process %s is not a subprocess",
6301 error ("Process %s is not active",
6304 gid
= emacs_get_tty_pgrp (p
);
6309 return make_number (gid
);
6313 /* Send a signal number SIGNO to PROCESS.
6314 If CURRENT_GROUP is t, that means send to the process group
6315 that currently owns the terminal being used to communicate with PROCESS.
6316 This is used for various commands in shell mode.
6317 If CURRENT_GROUP is lambda, that means send to the process group
6318 that currently owns the terminal, but only if it is NOT the shell itself.
6320 If NOMSG is false, insert signal-announcements into process's buffers
6323 If we can, we try to signal PROCESS by sending control characters
6324 down the pty. This allows us to signal inferiors who have changed
6325 their uid, for which kill would return an EPERM error. */
6328 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6332 struct Lisp_Process
*p
;
6336 proc
= get_process (process
);
6337 p
= XPROCESS (proc
);
6339 if (!EQ (p
->type
, Qreal
))
6340 error ("Process %s is not a subprocess",
6343 error ("Process %s is not active",
6347 current_group
= Qnil
;
6349 /* If we are using pgrps, get a pgrp number and make it negative. */
6350 if (NILP (current_group
))
6351 /* Send the signal to the shell's process group. */
6355 #ifdef SIGNALS_VIA_CHARACTERS
6356 /* If possible, send signals to the entire pgrp
6357 by sending an input character to it. */
6360 cc_t
*sig_char
= NULL
;
6362 tcgetattr (p
->infd
, &t
);
6367 sig_char
= &t
.c_cc
[VINTR
];
6371 sig_char
= &t
.c_cc
[VQUIT
];
6375 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6376 sig_char
= &t
.c_cc
[VSWTCH
];
6378 sig_char
= &t
.c_cc
[VSUSP
];
6383 if (sig_char
&& *sig_char
!= CDISABLE
)
6385 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6388 /* If we can't send the signal with a character,
6389 fall through and send it another way. */
6391 /* The code above may fall through if it can't
6392 handle the signal. */
6393 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6396 /* Get the current pgrp using the tty itself, if we have that.
6397 Otherwise, use the pty to get the pgrp.
6398 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6399 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6400 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6401 His patch indicates that if TIOCGPGRP returns an error, then
6402 we should just assume that p->pid is also the process group id. */
6404 gid
= emacs_get_tty_pgrp (p
);
6407 /* If we can't get the information, assume
6408 the shell owns the tty. */
6411 /* It is not clear whether anything really can set GID to -1.
6412 Perhaps on some system one of those ioctls can or could do so.
6413 Or perhaps this is vestigial. */
6416 #else /* ! defined (TIOCGPGRP) */
6417 /* Can't select pgrps on this system, so we know that
6418 the child itself heads the pgrp. */
6420 #endif /* ! defined (TIOCGPGRP) */
6422 /* If current_group is lambda, and the shell owns the terminal,
6423 don't send any signal. */
6424 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6429 if (signo
== SIGCONT
)
6431 p
->raw_status_new
= 0;
6432 pset_status (p
, Qrun
);
6433 p
->tick
= ++process_tick
;
6436 status_notify (NULL
, NULL
);
6437 redisplay_preserve_echo_area (13);
6443 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6444 We don't know whether the bug is fixed in later HP-UX versions. */
6445 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6449 /* If we don't have process groups, send the signal to the immediate
6450 subprocess. That isn't really right, but it's better than any
6451 obvious alternative. */
6452 pid_t pid
= no_pgrp
? gid
: - gid
;
6454 /* Do not kill an already-reaped process, as that could kill an
6455 innocent bystander that happens to have the same process ID. */
6457 block_child_signal (&oldset
);
6460 unblock_child_signal (&oldset
);
6463 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6464 doc
: /* Interrupt process PROCESS.
6465 PROCESS may be a process, a buffer, or the name of a process or buffer.
6466 No arg or nil means current buffer's process.
6467 Second arg CURRENT-GROUP non-nil means send signal to
6468 the current process-group of the process's controlling terminal
6469 rather than to the process's own process group.
6470 If the process is a shell, this means interrupt current subjob
6471 rather than the shell.
6473 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6474 don't send the signal. */)
6475 (Lisp_Object process
, Lisp_Object current_group
)
6477 process_send_signal (process
, SIGINT
, current_group
, 0);
6481 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6482 doc
: /* Kill process PROCESS. May be process or name of one.
6483 See function `interrupt-process' for more details on usage. */)
6484 (Lisp_Object process
, Lisp_Object current_group
)
6486 process_send_signal (process
, SIGKILL
, current_group
, 0);
6490 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6491 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6492 See function `interrupt-process' for more details on usage. */)
6493 (Lisp_Object process
, Lisp_Object current_group
)
6495 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6499 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6500 doc
: /* Stop process PROCESS. May be process or name of one.
6501 See function `interrupt-process' for more details on usage.
6502 If PROCESS is a network or serial process, inhibit handling of incoming
6504 (Lisp_Object process
, Lisp_Object current_group
)
6506 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6507 || PIPECONN_P (process
)))
6509 struct Lisp_Process
*p
;
6511 p
= XPROCESS (process
);
6512 if (NILP (p
->command
)
6515 FD_CLR (p
->infd
, &input_wait_mask
);
6516 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6518 pset_command (p
, Qt
);
6522 error ("No SIGTSTP support");
6524 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6529 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6530 doc
: /* Continue process PROCESS. May be process or name of one.
6531 See function `interrupt-process' for more details on usage.
6532 If PROCESS is a network or serial process, resume handling of incoming
6534 (Lisp_Object process
, Lisp_Object current_group
)
6536 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6537 || PIPECONN_P (process
)))
6539 struct Lisp_Process
*p
;
6541 p
= XPROCESS (process
);
6542 if (EQ (p
->command
, Qt
)
6544 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6546 FD_SET (p
->infd
, &input_wait_mask
);
6547 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6549 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6550 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6551 #else /* not WINDOWSNT */
6552 tcflush (p
->infd
, TCIFLUSH
);
6553 #endif /* not WINDOWSNT */
6555 pset_command (p
, Qnil
);
6559 process_send_signal (process
, SIGCONT
, current_group
, 0);
6561 error ("No SIGCONT support");
6566 /* Return the integer value of the signal whose abbreviation is ABBR,
6567 or a negative number if there is no such signal. */
6569 abbr_to_signal (char const *name
)
6572 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6574 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6577 for (i
= 0; i
< sizeof sigbuf
; i
++)
6579 sigbuf
[i
] = c_toupper (name
[i
]);
6581 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6587 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6588 2, 2, "sProcess (name or number): \nnSignal code: ",
6589 doc
: /* Send PROCESS the signal with code SIGCODE.
6590 PROCESS may also be a number specifying the process id of the
6591 process to signal; in this case, the process need not be a child of
6593 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6594 (Lisp_Object process
, Lisp_Object sigcode
)
6599 if (STRINGP (process
))
6601 Lisp_Object tem
= Fget_process (process
);
6604 Lisp_Object process_number
6605 = string_to_number (SSDATA (process
), 10, 1);
6606 if (NUMBERP (process_number
))
6607 tem
= process_number
;
6611 else if (!NUMBERP (process
))
6612 process
= get_process (process
);
6617 if (NUMBERP (process
))
6618 CONS_TO_INTEGER (process
, pid_t
, pid
);
6621 CHECK_PROCESS (process
);
6622 pid
= XPROCESS (process
)->pid
;
6624 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6627 if (INTEGERP (sigcode
))
6629 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6630 signo
= XINT (sigcode
);
6636 CHECK_SYMBOL (sigcode
);
6637 name
= SSDATA (SYMBOL_NAME (sigcode
));
6639 signo
= abbr_to_signal (name
);
6641 error ("Undefined signal name %s", name
);
6644 return make_number (kill (pid
, signo
));
6647 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6648 doc
: /* Make PROCESS see end-of-file in its input.
6649 EOF comes after any text already sent to it.
6650 PROCESS may be a process, a buffer, the name of a process or buffer, or
6651 nil, indicating the current buffer's process.
6652 If PROCESS is a network connection, or is a process communicating
6653 through a pipe (as opposed to a pty), then you cannot send any more
6654 text to PROCESS after you call this function.
6655 If PROCESS is a serial process, wait until all output written to the
6656 process has been transmitted to the serial port. */)
6657 (Lisp_Object process
)
6660 struct coding_system
*coding
= NULL
;
6663 proc
= get_process (process
);
6665 if (NETCONN_P (proc
))
6666 wait_while_connecting (proc
);
6668 if (DATAGRAM_CONN_P (proc
))
6672 outfd
= XPROCESS (proc
)->outfd
;
6674 coding
= proc_encode_coding_system
[outfd
];
6676 /* Make sure the process is really alive. */
6677 if (XPROCESS (proc
)->raw_status_new
)
6678 update_status (XPROCESS (proc
));
6679 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6680 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6682 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6684 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6685 send_process (proc
, "", 0, Qnil
);
6688 if (XPROCESS (proc
)->pty_flag
)
6689 send_process (proc
, "\004", 1, Qnil
);
6690 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6693 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6694 report_file_error ("Failed tcdrain", Qnil
);
6695 #endif /* not WINDOWSNT */
6696 /* Do nothing on Windows because writes are blocking. */
6700 struct Lisp_Process
*p
= XPROCESS (proc
);
6701 int old_outfd
= p
->outfd
;
6704 #ifdef HAVE_SHUTDOWN
6705 /* If this is a network connection, or socketpair is used
6706 for communication with the subprocess, call shutdown to cause EOF.
6707 (In some old system, shutdown to socketpair doesn't work.
6708 Then we just can't win.) */
6710 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6711 shutdown (old_outfd
, 1);
6713 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6714 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6716 report_file_error ("Opening null device", Qnil
);
6717 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6718 p
->outfd
= new_outfd
;
6720 if (!proc_encode_coding_system
[new_outfd
])
6721 proc_encode_coding_system
[new_outfd
]
6722 = xmalloc (sizeof (struct coding_system
));
6725 *proc_encode_coding_system
[new_outfd
]
6726 = *proc_encode_coding_system
[old_outfd
];
6727 memset (proc_encode_coding_system
[old_outfd
], 0,
6728 sizeof (struct coding_system
));
6731 setup_coding_system (p
->encode_coding_system
,
6732 proc_encode_coding_system
[new_outfd
]);
6737 /* The main Emacs thread records child processes in three places:
6739 - Vprocess_alist, for asynchronous subprocesses, which are child
6740 processes visible to Lisp.
6742 - deleted_pid_list, for child processes invisible to Lisp,
6743 typically because of delete-process. These are recorded so that
6744 the processes can be reaped when they exit, so that the operating
6745 system's process table is not cluttered by zombies.
6747 - the local variable PID in Fcall_process, call_process_cleanup and
6748 call_process_kill, for synchronous subprocesses.
6749 record_unwind_protect is used to make sure this process is not
6750 forgotten: if the user interrupts call-process and the child
6751 process refuses to exit immediately even with two C-g's,
6752 call_process_kill adds PID's contents to deleted_pid_list before
6755 The main Emacs thread invokes waitpid only on child processes that
6756 it creates and that have not been reaped. This avoid races on
6757 platforms such as GTK, where other threads create their own
6758 subprocesses which the main thread should not reap. For example,
6759 if the main thread attempted to reap an already-reaped child, it
6760 might inadvertently reap a GTK-created process that happened to
6761 have the same process ID. */
6763 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6764 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6765 keep track of its own children. GNUstep is similar. */
6767 static void dummy_handler (int sig
) {}
6768 static signal_handler_t
volatile lib_child_handler
;
6770 /* Handle a SIGCHLD signal by looking for known child processes of
6771 Emacs whose status have changed. For each one found, record its
6774 All we do is change the status; we do not run sentinels or print
6775 notifications. That is saved for the next time keyboard input is
6776 done, in order to avoid timing errors.
6778 ** WARNING: this can be called during garbage collection.
6779 Therefore, it must not be fooled by the presence of mark bits in
6782 ** USG WARNING: Although it is not obvious from the documentation
6783 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6784 signal() before executing at least one wait(), otherwise the
6785 handler will be called again, resulting in an infinite loop. The
6786 relevant portion of the documentation reads "SIGCLD signals will be
6787 queued and the signal-catching function will be continually
6788 reentered until the queue is empty". Invoking signal() causes the
6789 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6792 ** Malloc WARNING: This should never call malloc either directly or
6793 indirectly; if it does, that is a bug. */
6796 handle_child_signal (int sig
)
6798 Lisp_Object tail
, proc
;
6800 /* Find the process that signaled us, and record its status. */
6802 /* The process can have been deleted by Fdelete_process, or have
6803 been started asynchronously by Fcall_process. */
6804 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6806 bool all_pids_are_fixnums
6807 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6808 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6809 Lisp_Object head
= XCAR (tail
);
6814 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6817 if (INTEGERP (xpid
))
6818 deleted_pid
= XINT (xpid
);
6820 deleted_pid
= XFLOAT_DATA (xpid
);
6821 if (child_status_changed (deleted_pid
, 0, 0))
6823 if (STRINGP (XCDR (head
)))
6824 unlink (SSDATA (XCDR (head
)));
6825 XSETCAR (tail
, Qnil
);
6830 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6831 FOR_EACH_PROCESS (tail
, proc
)
6833 struct Lisp_Process
*p
= XPROCESS (proc
);
6837 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6839 /* Change the status of the process that was found. */
6840 p
->tick
= ++process_tick
;
6841 p
->raw_status
= status
;
6842 p
->raw_status_new
= 1;
6844 /* If process has terminated, stop waiting for its output. */
6845 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6847 bool clear_desc_flag
= 0;
6850 clear_desc_flag
= 1;
6852 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6853 if (clear_desc_flag
)
6855 FD_CLR (p
->infd
, &input_wait_mask
);
6856 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6862 lib_child_handler (sig
);
6863 #ifdef NS_IMPL_GNUSTEP
6864 /* NSTask in GNUstep sets its child handler each time it is called.
6865 So we must re-set ours. */
6866 catch_child_signal ();
6871 deliver_child_signal (int sig
)
6873 deliver_process_signal (sig
, handle_child_signal
);
6878 exec_sentinel_error_handler (Lisp_Object error_val
)
6880 cmd_error_internal (error_val
, "error in process sentinel: ");
6882 update_echo_area ();
6883 Fsleep_for (make_number (2), Qnil
);
6888 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6890 Lisp_Object sentinel
, odeactivate
;
6891 struct Lisp_Process
*p
= XPROCESS (proc
);
6892 ptrdiff_t count
= SPECPDL_INDEX ();
6893 bool outer_running_asynch_code
= running_asynch_code
;
6894 int waiting
= waiting_for_user_input_p
;
6896 if (inhibit_sentinels
)
6899 odeactivate
= Vdeactivate_mark
;
6901 Lisp_Object obuffer
, okeymap
;
6902 XSETBUFFER (obuffer
, current_buffer
);
6903 okeymap
= BVAR (current_buffer
, keymap
);
6906 /* There's no good reason to let sentinels change the current
6907 buffer, and many callers of accept-process-output, sit-for, and
6908 friends don't expect current-buffer to be changed from under them. */
6909 record_unwind_current_buffer ();
6911 sentinel
= p
->sentinel
;
6913 /* Inhibit quit so that random quits don't screw up a running filter. */
6914 specbind (Qinhibit_quit
, Qt
);
6915 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6917 /* In case we get recursively called,
6918 and we already saved the match data nonrecursively,
6919 save the same match data in safely recursive fashion. */
6920 if (outer_running_asynch_code
)
6923 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6924 restore_search_regs ();
6925 record_unwind_save_match_data ();
6926 Fset_match_data (tem
, Qt
);
6929 /* For speed, if a search happens within this code,
6930 save the match data in a special nonrecursive fashion. */
6931 running_asynch_code
= 1;
6933 internal_condition_case_1 (read_process_output_call
,
6934 list3 (sentinel
, proc
, reason
),
6935 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6936 exec_sentinel_error_handler
);
6938 /* If we saved the match data nonrecursively, restore it now. */
6939 restore_search_regs ();
6940 running_asynch_code
= outer_running_asynch_code
;
6942 Vdeactivate_mark
= odeactivate
;
6944 /* Restore waiting_for_user_input_p as it was
6945 when we were called, in case the filter clobbered it. */
6946 waiting_for_user_input_p
= waiting
;
6949 if (! EQ (Fcurrent_buffer (), obuffer
)
6950 || ! EQ (current_buffer
->keymap
, okeymap
))
6952 /* But do it only if the caller is actually going to read events.
6953 Otherwise there's no need to make him wake up, and it could
6954 cause trouble (for example it would make sit_for return). */
6955 if (waiting_for_user_input_p
== -1)
6956 record_asynch_buffer_change ();
6958 unbind_to (count
, Qnil
);
6961 /* Report all recent events of a change in process status
6962 (either run the sentinel or output a message).
6963 This is usually done while Emacs is waiting for keyboard input
6964 but can be done at other times.
6966 Return positive if any input was received from WAIT_PROC (or from
6967 any process if WAIT_PROC is null), zero if input was attempted but
6968 none received, and negative if we didn't even try. */
6971 status_notify (struct Lisp_Process
*deleting_process
,
6972 struct Lisp_Process
*wait_proc
)
6975 Lisp_Object tail
, msg
;
6976 int got_some_output
= -1;
6981 /* Set this now, so that if new processes are created by sentinels
6982 that we run, we get called again to handle their status changes. */
6983 update_tick
= process_tick
;
6985 FOR_EACH_PROCESS (tail
, proc
)
6988 register struct Lisp_Process
*p
= XPROCESS (proc
);
6990 if (p
->tick
!= p
->update_tick
)
6992 p
->update_tick
= p
->tick
;
6994 /* If process is still active, read any output that remains. */
6995 while (! EQ (p
->filter
, Qt
)
6996 && ! EQ (p
->status
, Qconnect
)
6997 && ! EQ (p
->status
, Qlisten
)
6998 /* Network or serial process not stopped: */
6999 && ! EQ (p
->command
, Qt
)
7001 && p
!= deleting_process
)
7003 int nread
= read_process_output (proc
, p
->infd
);
7004 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7005 && got_some_output
< nread
)
7006 got_some_output
= nread
;
7011 /* Get the text to use for the message. */
7012 if (p
->raw_status_new
)
7014 msg
= status_message (p
);
7016 /* If process is terminated, deactivate it or delete it. */
7018 if (CONSP (p
->status
))
7019 symbol
= XCAR (p
->status
);
7021 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7022 || EQ (symbol
, Qclosed
))
7024 if (delete_exited_processes
)
7025 remove_process (proc
);
7027 deactivate_process (proc
);
7030 /* The actions above may have further incremented p->tick.
7031 So set p->update_tick again so that an error in the sentinel will
7032 not cause this code to be run again. */
7033 p
->update_tick
= p
->tick
;
7034 /* Now output the message suitably. */
7035 exec_sentinel (proc
, msg
);
7036 if (BUFFERP (p
->buffer
))
7037 /* In case it uses %s in mode-line-format. */
7038 bset_update_mode_line (XBUFFER (p
->buffer
));
7042 return got_some_output
;
7045 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7046 Sinternal_default_process_sentinel
, 2, 2, 0,
7047 doc
: /* Function used as default sentinel for processes.
7048 This inserts a status message into the process's buffer, if there is one. */)
7049 (Lisp_Object proc
, Lisp_Object msg
)
7051 Lisp_Object buffer
, symbol
;
7052 struct Lisp_Process
*p
;
7053 CHECK_PROCESS (proc
);
7054 p
= XPROCESS (proc
);
7058 symbol
= XCAR (symbol
);
7060 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7063 struct buffer
*old
= current_buffer
;
7064 ptrdiff_t opoint
, opoint_byte
;
7065 ptrdiff_t before
, before_byte
;
7067 /* Avoid error if buffer is deleted
7068 (probably that's why the process is dead, too). */
7069 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7071 Fset_buffer (buffer
);
7073 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7074 msg
= (code_convert_string_norecord
7075 (msg
, Vlocale_coding_system
, 1));
7078 opoint_byte
= PT_BYTE
;
7079 /* Insert new output into buffer
7080 at the current end-of-output marker,
7081 thus preserving logical ordering of input and output. */
7082 if (XMARKER (p
->mark
)->buffer
)
7083 Fgoto_char (p
->mark
);
7085 SET_PT_BOTH (ZV
, ZV_BYTE
);
7088 before_byte
= PT_BYTE
;
7090 tem
= BVAR (current_buffer
, read_only
);
7091 bset_read_only (current_buffer
, Qnil
);
7092 insert_string ("\nProcess ");
7093 { /* FIXME: temporary kludge. */
7094 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7095 insert_string (" ");
7097 bset_read_only (current_buffer
, tem
);
7098 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7100 if (opoint
>= before
)
7101 SET_PT_BOTH (opoint
+ (PT
- before
),
7102 opoint_byte
+ (PT_BYTE
- before_byte
));
7104 SET_PT_BOTH (opoint
, opoint_byte
);
7106 set_buffer_internal (old
);
7112 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7113 Sset_process_coding_system
, 1, 3, 0,
7114 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7115 DECODING will be used to decode subprocess output and ENCODING to
7116 encode subprocess input. */)
7117 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7119 register struct Lisp_Process
*p
;
7121 CHECK_PROCESS (process
);
7123 if (NETCONN_P (process
))
7124 wait_for_socket_fds (process
, "set-process-coding-system");
7126 p
= XPROCESS (process
);
7129 error ("Input file descriptor of %s closed", SDATA (p
->name
));
7131 error ("Output file descriptor of %s closed", SDATA (p
->name
));
7132 Fcheck_coding_system (decoding
);
7133 Fcheck_coding_system (encoding
);
7134 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7135 pset_decode_coding_system (p
, decoding
);
7136 pset_encode_coding_system (p
, encoding
);
7137 setup_process_coding_systems (process
);
7142 DEFUN ("process-coding-system",
7143 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7144 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7145 (register Lisp_Object process
)
7147 CHECK_PROCESS (process
);
7148 return Fcons (XPROCESS (process
)->decode_coding_system
,
7149 XPROCESS (process
)->encode_coding_system
);
7152 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7153 Sset_process_filter_multibyte
, 2, 2, 0,
7154 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7155 If FLAG is non-nil, the filter is given multibyte strings.
7156 If FLAG is nil, the filter is given unibyte strings. In this case,
7157 all character code conversion except for end-of-line conversion is
7159 (Lisp_Object process
, Lisp_Object flag
)
7161 register struct Lisp_Process
*p
;
7163 CHECK_PROCESS (process
);
7165 if (NETCONN_P (process
))
7166 wait_for_socket_fds (process
, "set-process-filter-multibyte");
7168 p
= XPROCESS (process
);
7170 pset_decode_coding_system
7171 (p
, raw_text_coding_system (p
->decode_coding_system
));
7172 setup_process_coding_systems (process
);
7177 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7178 Sprocess_filter_multibyte_p
, 1, 1, 0,
7179 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7180 (Lisp_Object process
)
7182 register struct Lisp_Process
*p
;
7183 struct coding_system
*coding
;
7185 CHECK_PROCESS (process
);
7186 p
= XPROCESS (process
);
7189 coding
= proc_decode_coding_system
[p
->infd
];
7190 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7199 add_gpm_wait_descriptor (int desc
)
7201 add_keyboard_wait_descriptor (desc
);
7205 delete_gpm_wait_descriptor (int desc
)
7207 delete_keyboard_wait_descriptor (desc
);
7212 # ifdef USABLE_SIGIO
7214 /* Return true if *MASK has a bit set
7215 that corresponds to one of the keyboard input descriptors. */
7218 keyboard_bit_set (fd_set
*mask
)
7222 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7223 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7224 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7231 #else /* not subprocesses */
7233 /* Defined in msdos.c. */
7234 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7235 struct timespec
*, void *);
7237 /* Implementation of wait_reading_process_output, assuming that there
7238 are no subprocesses. Used only by the MS-DOS build.
7240 Wait for timeout to elapse and/or keyboard input to be available.
7244 If negative, gobble data immediately available but don't wait for any.
7247 an additional duration to wait, measured in nanoseconds
7248 If TIME_LIMIT is zero, then:
7249 If NSECS == 0, there is no limit.
7250 If NSECS > 0, the timeout consists of NSECS only.
7251 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7254 0 to ignore keyboard input, or
7255 1 to return when input is available, or
7256 -1 means caller will actually read the input, so don't throw to
7259 see full version for other parameters. We know that wait_proc will
7260 always be NULL, since `subprocesses' isn't defined.
7262 DO_DISPLAY means redisplay should be done to show subprocess
7263 output that arrives.
7265 Return -1 signifying we got no output and did not try. */
7268 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7270 Lisp_Object wait_for_cell
,
7271 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7274 struct timespec end_time
, timeout
;
7275 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7277 if (TYPE_MAXIMUM (time_t) < time_limit
)
7278 time_limit
= TYPE_MAXIMUM (time_t);
7280 if (time_limit
< 0 || nsecs
< 0)
7282 else if (time_limit
> 0 || nsecs
> 0)
7285 end_time
= timespec_add (current_timespec (),
7286 make_timespec (time_limit
, nsecs
));
7291 /* Turn off periodic alarms (in case they are in use)
7292 and then turn off any other atimers,
7293 because the select emulator uses alarms. */
7295 turn_on_atimers (0);
7299 bool timeout_reduced_for_timers
= false;
7300 fd_set waitchannels
;
7303 /* If calling from keyboard input, do not quit
7304 since we want to return C-g as an input character.
7305 Otherwise, do pending quit if requested. */
7309 /* Exit now if the cell we're waiting for became non-nil. */
7310 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7313 /* Compute time from now till when time limit is up. */
7314 /* Exit if already run out. */
7315 if (wait
== TIMEOUT
)
7317 struct timespec now
= current_timespec ();
7318 if (timespec_cmp (end_time
, now
) <= 0)
7320 timeout
= timespec_sub (end_time
, now
);
7323 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7325 /* If our caller will not immediately handle keyboard events,
7326 run timer events directly.
7327 (Callers that will immediately read keyboard events
7328 call timer_delay on their own.) */
7329 if (NILP (wait_for_cell
))
7331 struct timespec timer_delay
;
7335 unsigned old_timers_run
= timers_run
;
7336 timer_delay
= timer_check ();
7337 if (timers_run
!= old_timers_run
&& do_display
)
7338 /* We must retry, since a timer may have requeued itself
7339 and that could alter the time delay. */
7340 redisplay_preserve_echo_area (14);
7344 while (!detect_input_pending ());
7346 /* If there is unread keyboard input, also return. */
7348 && requeued_events_pending_p ())
7351 if (timespec_valid_p (timer_delay
))
7353 if (timespec_cmp (timer_delay
, timeout
) < 0)
7355 timeout
= timer_delay
;
7356 timeout_reduced_for_timers
= true;
7361 /* Cause C-g and alarm signals to take immediate action,
7362 and cause input available signals to zero out timeout. */
7364 set_waiting_for_input (&timeout
);
7366 /* If a frame has been newly mapped and needs updating,
7367 reprocess its display stuff. */
7368 if (frame_garbaged
&& do_display
)
7370 clear_waiting_for_input ();
7371 redisplay_preserve_echo_area (15);
7373 set_waiting_for_input (&timeout
);
7376 /* Wait till there is something to do. */
7377 FD_ZERO (&waitchannels
);
7378 if (read_kbd
&& detect_input_pending ())
7382 if (read_kbd
|| !NILP (wait_for_cell
))
7383 FD_SET (0, &waitchannels
);
7384 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7389 /* Make C-g and alarm signals set flags again. */
7390 clear_waiting_for_input ();
7392 /* If we woke up due to SIGWINCH, actually change size now. */
7393 do_pending_window_change (0);
7395 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7396 /* We waited the full specified time, so return now. */
7401 /* If the system call was interrupted, then go around the
7403 if (xerrno
== EINTR
)
7404 FD_ZERO (&waitchannels
);
7406 report_file_errno ("Failed select", Qnil
, xerrno
);
7409 /* Check for keyboard input. */
7412 && detect_input_pending_run_timers (do_display
))
7414 swallow_events (do_display
);
7415 if (detect_input_pending_run_timers (do_display
))
7419 /* If there is unread keyboard input, also return. */
7421 && requeued_events_pending_p ())
7424 /* If wait_for_cell. check for keyboard input
7425 but don't run any timers.
7426 ??? (It seems wrong to me to check for keyboard
7427 input at all when wait_for_cell, but the code
7428 has been this way since July 1994.
7429 Try changing this after version 19.31.) */
7430 if (! NILP (wait_for_cell
)
7431 && detect_input_pending ())
7433 swallow_events (do_display
);
7434 if (detect_input_pending ())
7438 /* Exit now if the cell we're waiting for became non-nil. */
7439 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7448 #endif /* not subprocesses */
7450 /* The following functions are needed even if async subprocesses are
7451 not supported. Some of them are no-op stubs in that case. */
7455 /* Add FD, which is a descriptor returned by timerfd_create,
7456 to the set of non-keyboard input descriptors. */
7459 add_timer_wait_descriptor (int fd
)
7461 FD_SET (fd
, &input_wait_mask
);
7462 FD_SET (fd
, &non_keyboard_wait_mask
);
7463 FD_SET (fd
, &non_process_wait_mask
);
7464 fd_callback_info
[fd
].func
= timerfd_callback
;
7465 fd_callback_info
[fd
].data
= NULL
;
7466 fd_callback_info
[fd
].condition
|= FOR_READ
;
7467 if (fd
> max_input_desc
)
7468 max_input_desc
= fd
;
7471 #endif /* HAVE_TIMERFD */
7473 /* Add DESC to the set of keyboard input descriptors. */
7476 add_keyboard_wait_descriptor (int desc
)
7478 #ifdef subprocesses /* Actually means "not MSDOS". */
7479 FD_SET (desc
, &input_wait_mask
);
7480 FD_SET (desc
, &non_process_wait_mask
);
7481 if (desc
> max_input_desc
)
7482 max_input_desc
= desc
;
7486 /* From now on, do not expect DESC to give keyboard input. */
7489 delete_keyboard_wait_descriptor (int desc
)
7492 FD_CLR (desc
, &input_wait_mask
);
7493 FD_CLR (desc
, &non_process_wait_mask
);
7494 delete_input_desc (desc
);
7498 /* Setup coding systems of PROCESS. */
7501 setup_process_coding_systems (Lisp_Object process
)
7504 struct Lisp_Process
*p
= XPROCESS (process
);
7506 int outch
= p
->outfd
;
7507 Lisp_Object coding_system
;
7509 if (inch
< 0 || outch
< 0)
7512 if (!proc_decode_coding_system
[inch
])
7513 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7514 coding_system
= p
->decode_coding_system
;
7515 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7516 && BUFFERP (p
->buffer
))
7518 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7519 coding_system
= raw_text_coding_system (coding_system
);
7521 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7523 if (!proc_encode_coding_system
[outch
])
7524 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7525 setup_coding_system (p
->encode_coding_system
,
7526 proc_encode_coding_system
[outch
]);
7530 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7531 doc
: /* Return the (or a) live process associated with BUFFER.
7532 BUFFER may be a buffer or the name of one.
7533 Return nil if all processes associated with BUFFER have been
7534 deleted or killed. */)
7535 (register Lisp_Object buffer
)
7538 register Lisp_Object buf
, tail
, proc
;
7540 if (NILP (buffer
)) return Qnil
;
7541 buf
= Fget_buffer (buffer
);
7542 if (NILP (buf
)) return Qnil
;
7544 FOR_EACH_PROCESS (tail
, proc
)
7545 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7547 #endif /* subprocesses */
7551 DEFUN ("process-inherit-coding-system-flag",
7552 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7554 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7555 If this flag is t, `buffer-file-coding-system' of the buffer
7556 associated with PROCESS will inherit the coding system used to decode
7557 the process output. */)
7558 (register Lisp_Object process
)
7561 CHECK_PROCESS (process
);
7562 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7564 /* Ignore the argument and return the value of
7565 inherit-process-coding-system. */
7566 return inherit_process_coding_system
? Qt
: Qnil
;
7570 /* Kill all processes associated with `buffer'.
7571 If `buffer' is nil, kill all processes. */
7574 kill_buffer_processes (Lisp_Object buffer
)
7577 Lisp_Object tail
, proc
;
7579 FOR_EACH_PROCESS (tail
, proc
)
7580 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7582 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7583 Fdelete_process (proc
);
7584 else if (XPROCESS (proc
)->infd
>= 0)
7585 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7587 #else /* subprocesses */
7588 /* Since we have no subprocesses, this does nothing. */
7589 #endif /* subprocesses */
7592 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7593 Swaiting_for_user_input_p
, 0, 0, 0,
7594 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7595 This is intended for use by asynchronous process output filters and sentinels. */)
7599 return (waiting_for_user_input_p
? Qt
: Qnil
);
7605 /* Stop reading input from keyboard sources. */
7608 hold_keyboard_input (void)
7613 /* Resume reading input from keyboard sources. */
7616 unhold_keyboard_input (void)
7621 /* Return true if keyboard input is on hold, zero otherwise. */
7624 kbd_on_hold_p (void)
7626 return kbd_is_on_hold
;
7630 /* Enumeration of and access to system processes a-la ps(1). */
7632 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7634 doc
: /* Return a list of numerical process IDs of all running processes.
7635 If this functionality is unsupported, return nil.
7637 See `process-attributes' for getting attributes of a process given its ID. */)
7640 return list_system_processes ();
7643 DEFUN ("process-attributes", Fprocess_attributes
,
7644 Sprocess_attributes
, 1, 1, 0,
7645 doc
: /* Return attributes of the process given by its PID, a number.
7647 Value is an alist where each element is a cons cell of the form
7651 If this functionality is unsupported, the value is nil.
7653 See `list-system-processes' for getting a list of all process IDs.
7655 The KEYs of the attributes that this function may return are listed
7656 below, together with the type of the associated VALUE (in parentheses).
7657 Not all platforms support all of these attributes; unsupported
7658 attributes will not appear in the returned alist.
7659 Unless explicitly indicated otherwise, numbers can have either
7660 integer or floating point values.
7662 euid -- Effective user User ID of the process (number)
7663 user -- User name corresponding to euid (string)
7664 egid -- Effective user Group ID of the process (number)
7665 group -- Group name corresponding to egid (string)
7666 comm -- Command name (executable name only) (string)
7667 state -- Process state code, such as "S", "R", or "T" (string)
7668 ppid -- Parent process ID (number)
7669 pgrp -- Process group ID (number)
7670 sess -- Session ID, i.e. process ID of session leader (number)
7671 ttname -- Controlling tty name (string)
7672 tpgid -- ID of foreground process group on the process's tty (number)
7673 minflt -- number of minor page faults (number)
7674 majflt -- number of major page faults (number)
7675 cminflt -- cumulative number of minor page faults (number)
7676 cmajflt -- cumulative number of major page faults (number)
7677 utime -- user time used by the process, in (current-time) format,
7678 which is a list of integers (HIGH LOW USEC PSEC)
7679 stime -- system time used by the process (current-time)
7680 time -- sum of utime and stime (current-time)
7681 cutime -- user time used by the process and its children (current-time)
7682 cstime -- system time used by the process and its children (current-time)
7683 ctime -- sum of cutime and cstime (current-time)
7684 pri -- priority of the process (number)
7685 nice -- nice value of the process (number)
7686 thcount -- process thread count (number)
7687 start -- time the process started (current-time)
7688 vsize -- virtual memory size of the process in KB's (number)
7689 rss -- resident set size of the process in KB's (number)
7690 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7691 pcpu -- percents of CPU time used by the process (floating-point number)
7692 pmem -- percents of total physical memory used by process's resident set
7693 (floating-point number)
7694 args -- command line which invoked the process (string). */)
7697 return system_process_attributes (pid
);
7701 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7702 Invoke this after init_process_emacs, and after glib and/or GNUstep
7703 futz with the SIGCHLD handler, but before Emacs forks any children.
7704 This function's caller should block SIGCHLD. */
7707 catch_child_signal (void)
7709 struct sigaction action
, old_action
;
7711 emacs_sigaction_init (&action
, deliver_child_signal
);
7712 block_child_signal (&oldset
);
7713 sigaction (SIGCHLD
, &action
, &old_action
);
7714 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7715 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7717 if (old_action
.sa_handler
!= deliver_child_signal
)
7719 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7721 : old_action
.sa_handler
);
7722 unblock_child_signal (&oldset
);
7724 #endif /* subprocesses */
7727 /* This is not called "init_process" because that is the name of a
7728 Mach system call, so it would cause problems on Darwin systems. */
7730 init_process_emacs (void)
7735 inhibit_sentinels
= 0;
7738 if (! noninteractive
|| initialized
)
7741 #if defined HAVE_GLIB && !defined WINDOWSNT
7742 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7743 this should always fail, but is enough to initialize glib's
7744 private SIGCHLD handler, allowing catch_child_signal to copy
7745 it into lib_child_handler. */
7746 g_source_unref (g_child_watch_source_new (getpid ()));
7748 catch_child_signal ();
7751 FD_ZERO (&input_wait_mask
);
7752 FD_ZERO (&non_keyboard_wait_mask
);
7753 FD_ZERO (&non_process_wait_mask
);
7754 FD_ZERO (&write_mask
);
7755 max_process_desc
= max_input_desc
= -1;
7756 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7758 #ifdef NON_BLOCKING_CONNECT
7759 FD_ZERO (&connect_wait_mask
);
7760 num_pending_connects
= 0;
7763 process_output_delay_count
= 0;
7764 process_output_skip
= 0;
7766 /* Don't do this, it caused infinite select loops. The display
7767 method should call add_keyboard_wait_descriptor on stdin if it
7770 FD_SET (0, &input_wait_mask
);
7773 Vprocess_alist
= Qnil
;
7774 deleted_pid_list
= Qnil
;
7775 for (i
= 0; i
< FD_SETSIZE
; i
++)
7777 chan_process
[i
] = Qnil
;
7778 proc_buffered_char
[i
] = -1;
7780 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7781 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7782 #ifdef DATAGRAM_SOCKETS
7783 memset (datagram_address
, 0, sizeof datagram_address
);
7786 #if defined (DARWIN_OS)
7787 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7788 processes. As such, we only change the default value. */
7791 char const *release
= (STRINGP (Voperating_system_release
)
7792 ? SSDATA (Voperating_system_release
)
7794 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7795 Vprocess_connection_type
= Qnil
;
7799 #endif /* subprocesses */
7804 syms_of_process (void)
7808 DEFSYM (Qprocessp
, "processp");
7809 DEFSYM (Qrun
, "run");
7810 DEFSYM (Qstop
, "stop");
7811 DEFSYM (Qsignal
, "signal");
7813 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7816 DEFSYM (Qopen
, "open");
7817 DEFSYM (Qclosed
, "closed");
7818 DEFSYM (Qconnect
, "connect");
7819 DEFSYM (Qfailed
, "failed");
7820 DEFSYM (Qlisten
, "listen");
7821 DEFSYM (Qlocal
, "local");
7822 DEFSYM (Qipv4
, "ipv4");
7824 DEFSYM (Qipv6
, "ipv6");
7826 DEFSYM (Qdatagram
, "datagram");
7827 DEFSYM (Qseqpacket
, "seqpacket");
7829 DEFSYM (QCport
, ":port");
7830 DEFSYM (QCspeed
, ":speed");
7831 DEFSYM (QCprocess
, ":process");
7833 DEFSYM (QCbytesize
, ":bytesize");
7834 DEFSYM (QCstopbits
, ":stopbits");
7835 DEFSYM (QCparity
, ":parity");
7836 DEFSYM (Qodd
, "odd");
7837 DEFSYM (Qeven
, "even");
7838 DEFSYM (QCflowcontrol
, ":flowcontrol");
7841 DEFSYM (QCsummary
, ":summary");
7843 DEFSYM (Qreal
, "real");
7844 DEFSYM (Qnetwork
, "network");
7845 DEFSYM (Qserial
, "serial");
7846 DEFSYM (Qpipe
, "pipe");
7847 DEFSYM (QCbuffer
, ":buffer");
7848 DEFSYM (QChost
, ":host");
7849 DEFSYM (QCservice
, ":service");
7850 DEFSYM (QClocal
, ":local");
7851 DEFSYM (QCremote
, ":remote");
7852 DEFSYM (QCcoding
, ":coding");
7853 DEFSYM (QCserver
, ":server");
7854 DEFSYM (QCnowait
, ":nowait");
7855 DEFSYM (QCsentinel
, ":sentinel");
7856 DEFSYM (QCtls_parameters
, ":tls-parameters");
7857 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7858 DEFSYM (QClog
, ":log");
7859 DEFSYM (QCnoquery
, ":noquery");
7860 DEFSYM (QCstop
, ":stop");
7861 DEFSYM (QCplist
, ":plist");
7862 DEFSYM (QCcommand
, ":command");
7863 DEFSYM (QCconnection_type
, ":connection-type");
7864 DEFSYM (QCstderr
, ":stderr");
7865 DEFSYM (Qpty
, "pty");
7866 DEFSYM (Qpipe
, "pipe");
7868 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7870 staticpro (&Vprocess_alist
);
7871 staticpro (&deleted_pid_list
);
7873 #endif /* subprocesses */
7875 DEFSYM (QCname
, ":name");
7876 DEFSYM (QCtype
, ":type");
7878 DEFSYM (Qeuid
, "euid");
7879 DEFSYM (Qegid
, "egid");
7880 DEFSYM (Quser
, "user");
7881 DEFSYM (Qgroup
, "group");
7882 DEFSYM (Qcomm
, "comm");
7883 DEFSYM (Qstate
, "state");
7884 DEFSYM (Qppid
, "ppid");
7885 DEFSYM (Qpgrp
, "pgrp");
7886 DEFSYM (Qsess
, "sess");
7887 DEFSYM (Qttname
, "ttname");
7888 DEFSYM (Qtpgid
, "tpgid");
7889 DEFSYM (Qminflt
, "minflt");
7890 DEFSYM (Qmajflt
, "majflt");
7891 DEFSYM (Qcminflt
, "cminflt");
7892 DEFSYM (Qcmajflt
, "cmajflt");
7893 DEFSYM (Qutime
, "utime");
7894 DEFSYM (Qstime
, "stime");
7895 DEFSYM (Qtime
, "time");
7896 DEFSYM (Qcutime
, "cutime");
7897 DEFSYM (Qcstime
, "cstime");
7898 DEFSYM (Qctime
, "ctime");
7900 DEFSYM (Qinternal_default_process_sentinel
,
7901 "internal-default-process-sentinel");
7902 DEFSYM (Qinternal_default_process_filter
,
7903 "internal-default-process-filter");
7905 DEFSYM (Qpri
, "pri");
7906 DEFSYM (Qnice
, "nice");
7907 DEFSYM (Qthcount
, "thcount");
7908 DEFSYM (Qstart
, "start");
7909 DEFSYM (Qvsize
, "vsize");
7910 DEFSYM (Qrss
, "rss");
7911 DEFSYM (Qetime
, "etime");
7912 DEFSYM (Qpcpu
, "pcpu");
7913 DEFSYM (Qpmem
, "pmem");
7914 DEFSYM (Qargs
, "args");
7916 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7917 doc
: /* Non-nil means delete processes immediately when they exit.
7918 A value of nil means don't delete them until `list-processes' is run. */);
7920 delete_exited_processes
= 1;
7923 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7924 doc
: /* Control type of device used to communicate with subprocesses.
7925 Values are nil to use a pipe, or t or `pty' to use a pty.
7926 The value has no effect if the system has no ptys or if all ptys are busy:
7927 then a pipe is used in any case.
7928 The value takes effect when `start-process' is called. */);
7929 Vprocess_connection_type
= Qt
;
7931 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7932 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7933 On some systems, when Emacs reads the output from a subprocess, the output data
7934 is read in very small blocks, potentially resulting in very poor performance.
7935 This behavior can be remedied to some extent by setting this variable to a
7936 non-nil value, as it will automatically delay reading from such processes, to
7937 allow them to produce more output before Emacs tries to read it.
7938 If the value is t, the delay is reset after each write to the process; any other
7939 non-nil value means that the delay is not reset on write.
7940 The variable takes effect when `start-process' is called. */);
7941 Vprocess_adaptive_read_buffering
= Qt
;
7943 defsubr (&Sprocessp
);
7944 defsubr (&Sget_process
);
7945 defsubr (&Sdelete_process
);
7946 defsubr (&Sprocess_status
);
7947 defsubr (&Sprocess_exit_status
);
7948 defsubr (&Sprocess_id
);
7949 defsubr (&Sprocess_name
);
7950 defsubr (&Sprocess_tty_name
);
7951 defsubr (&Sprocess_command
);
7952 defsubr (&Sset_process_buffer
);
7953 defsubr (&Sprocess_buffer
);
7954 defsubr (&Sprocess_mark
);
7955 defsubr (&Sset_process_filter
);
7956 defsubr (&Sprocess_filter
);
7957 defsubr (&Sset_process_sentinel
);
7958 defsubr (&Sprocess_sentinel
);
7959 defsubr (&Sset_process_window_size
);
7960 defsubr (&Sset_process_inherit_coding_system_flag
);
7961 defsubr (&Sset_process_query_on_exit_flag
);
7962 defsubr (&Sprocess_query_on_exit_flag
);
7963 defsubr (&Sprocess_contact
);
7964 defsubr (&Sprocess_plist
);
7965 defsubr (&Sset_process_plist
);
7966 defsubr (&Sprocess_list
);
7967 defsubr (&Smake_process
);
7968 defsubr (&Smake_pipe_process
);
7969 defsubr (&Sserial_process_configure
);
7970 defsubr (&Smake_serial_process
);
7971 defsubr (&Sset_network_process_option
);
7972 defsubr (&Smake_network_process
);
7973 defsubr (&Sformat_network_address
);
7974 defsubr (&Snetwork_interface_list
);
7975 defsubr (&Snetwork_interface_info
);
7976 #ifdef DATAGRAM_SOCKETS
7977 defsubr (&Sprocess_datagram_address
);
7978 defsubr (&Sset_process_datagram_address
);
7980 defsubr (&Saccept_process_output
);
7981 defsubr (&Sprocess_send_region
);
7982 defsubr (&Sprocess_send_string
);
7983 defsubr (&Sinterrupt_process
);
7984 defsubr (&Skill_process
);
7985 defsubr (&Squit_process
);
7986 defsubr (&Sstop_process
);
7987 defsubr (&Scontinue_process
);
7988 defsubr (&Sprocess_running_child_p
);
7989 defsubr (&Sprocess_send_eof
);
7990 defsubr (&Ssignal_process
);
7991 defsubr (&Swaiting_for_user_input_p
);
7992 defsubr (&Sprocess_type
);
7993 defsubr (&Sinternal_default_process_sentinel
);
7994 defsubr (&Sinternal_default_process_filter
);
7995 defsubr (&Sset_process_coding_system
);
7996 defsubr (&Sprocess_coding_system
);
7997 defsubr (&Sset_process_filter_multibyte
);
7998 defsubr (&Sprocess_filter_multibyte_p
);
8000 #endif /* subprocesses */
8002 defsubr (&Sget_buffer_process
);
8003 defsubr (&Sprocess_inherit_coding_system_flag
);
8004 defsubr (&Slist_system_processes
);
8005 defsubr (&Sprocess_attributes
);
8008 Lisp_Object subfeatures
= Qnil
;
8009 const struct socket_options
*sopt
;
8011 #define ADD_SUBFEATURE(key, val) \
8012 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8014 #ifdef NON_BLOCKING_CONNECT
8015 ADD_SUBFEATURE (QCnowait
, Qt
);
8017 #ifdef DATAGRAM_SOCKETS
8018 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8020 #ifdef HAVE_SEQPACKET
8021 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8023 #ifdef HAVE_LOCAL_SOCKETS
8024 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8026 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8028 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8030 #ifdef HAVE_GETSOCKNAME
8031 ADD_SUBFEATURE (QCservice
, Qt
);
8033 ADD_SUBFEATURE (QCserver
, Qt
);
8035 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8036 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8038 Fprovide (intern_c_string ("make-network-process"), subfeatures
);