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 static void wait_for_socket_fds (Lisp_Object
, char const *);
286 /* Alist of elements (NAME . PROCESS). */
287 static Lisp_Object Vprocess_alist
;
289 /* Buffered-ahead input char from process, indexed by channel.
290 -1 means empty (no char is buffered).
291 Used on sys V where the only way to tell if there is any
292 output from the process is to read at least one char.
293 Always -1 on systems that support FIONREAD. */
295 static int proc_buffered_char
[FD_SETSIZE
];
297 /* Table of `struct coding-system' for each process. */
298 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
299 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
301 #ifdef DATAGRAM_SOCKETS
302 /* Table of `partner address' for datagram sockets. */
303 static struct sockaddr_and_len
{
306 } datagram_address
[FD_SETSIZE
];
307 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
308 #define DATAGRAM_CONN_P(proc) \
309 (PROCESSP (proc) && \
310 XPROCESS (proc)->infd >= 0 && \
311 datagram_address[XPROCESS (proc)->infd].sa != 0)
313 #define DATAGRAM_CHAN_P(chan) (0)
314 #define DATAGRAM_CONN_P(proc) (0)
317 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
318 a `for' loop which iterates over processes from Vprocess_alist. */
320 #define FOR_EACH_PROCESS(list_var, proc_var) \
321 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
323 /* These setters are used only in this file, so they can be private. */
325 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
330 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
335 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
337 p
->decode_coding_system
= val
;
340 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
342 p
->decoding_buf
= val
;
345 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
347 p
->encode_coding_system
= val
;
350 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
352 p
->encoding_buf
= val
;
355 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
357 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
360 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
365 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
370 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
375 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
380 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
382 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
385 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
390 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
395 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
397 p
->write_queue
= val
;
400 pset_stderrproc (struct Lisp_Process
*p
, Lisp_Object val
)
407 make_lisp_proc (struct Lisp_Process
*p
)
409 return make_lisp_ptr (p
, Lisp_Vectorlike
);
412 static struct fd_callback_data
418 int condition
; /* Mask of the defines above. */
419 } fd_callback_info
[FD_SETSIZE
];
422 /* Add a file descriptor FD to be monitored for when read is possible.
423 When read is possible, call FUNC with argument DATA. */
426 add_read_fd (int fd
, fd_callback func
, void *data
)
428 add_keyboard_wait_descriptor (fd
);
430 fd_callback_info
[fd
].func
= func
;
431 fd_callback_info
[fd
].data
= data
;
432 fd_callback_info
[fd
].condition
|= FOR_READ
;
435 /* Stop monitoring file descriptor FD for when read is possible. */
438 delete_read_fd (int fd
)
440 delete_keyboard_wait_descriptor (fd
);
442 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
443 if (fd_callback_info
[fd
].condition
== 0)
445 fd_callback_info
[fd
].func
= 0;
446 fd_callback_info
[fd
].data
= 0;
450 /* Add a file descriptor FD to be monitored for when write is possible.
451 When write is possible, call FUNC with argument DATA. */
454 add_write_fd (int fd
, fd_callback func
, void *data
)
456 FD_SET (fd
, &write_mask
);
457 if (fd
> max_input_desc
)
460 fd_callback_info
[fd
].func
= func
;
461 fd_callback_info
[fd
].data
= data
;
462 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
465 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
468 delete_input_desc (int fd
)
470 if (fd
== max_input_desc
)
474 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
475 || FD_ISSET (fd
, &write_mask
)));
481 /* Stop monitoring file descriptor FD for when write is possible. */
484 delete_write_fd (int fd
)
486 FD_CLR (fd
, &write_mask
);
487 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
488 if (fd_callback_info
[fd
].condition
== 0)
490 fd_callback_info
[fd
].func
= 0;
491 fd_callback_info
[fd
].data
= 0;
492 delete_input_desc (fd
);
497 /* Compute the Lisp form of the process status, p->status, from
498 the numeric status that was returned by `wait'. */
500 static Lisp_Object
status_convert (int);
503 update_status (struct Lisp_Process
*p
)
505 eassert (p
->raw_status_new
);
506 pset_status (p
, status_convert (p
->raw_status
));
507 p
->raw_status_new
= 0;
510 /* Convert a process status word in Unix format to
511 the list that we use internally. */
514 status_convert (int w
)
517 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
518 else if (WIFEXITED (w
))
519 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
520 WCOREDUMP (w
) ? Qt
: Qnil
));
521 else if (WIFSIGNALED (w
))
522 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
523 WCOREDUMP (w
) ? Qt
: Qnil
));
528 /* Given a status-list, extract the three pieces of information
529 and store them individually through the three pointers. */
532 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
546 *code
= XFASTINT (XCAR (tem
));
548 *coredump
= !NILP (tem
);
552 /* Return a string describing a process status list. */
555 status_message (struct Lisp_Process
*p
)
557 Lisp_Object status
= p
->status
;
563 decode_status (status
, &symbol
, &code
, &coredump
);
565 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
568 synchronize_system_messages_locale ();
569 signame
= strsignal (code
);
571 string
= build_string ("unknown");
576 string
= build_unibyte_string (signame
);
577 if (! NILP (Vlocale_coding_system
))
578 string
= (code_convert_string_norecord
579 (string
, Vlocale_coding_system
, 0));
580 c1
= STRING_CHAR (SDATA (string
));
583 Faset (string
, make_number (0), make_number (c2
));
585 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
586 return concat2 (string
, suffix
);
588 else if (EQ (symbol
, Qexit
))
591 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
593 return build_string ("finished\n");
594 AUTO_STRING (prefix
, "exited abnormally with code ");
595 string
= Fnumber_to_string (make_number (code
));
596 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
597 return concat3 (prefix
, string
, suffix
);
599 else if (EQ (symbol
, Qfailed
))
601 AUTO_STRING (prefix
, "failed with code ");
602 string
= Fnumber_to_string (make_number (code
));
603 AUTO_STRING (suffix
, "\n");
604 return concat3 (prefix
, string
, suffix
);
607 return Fcopy_sequence (Fsymbol_name (symbol
));
610 enum { PTY_NAME_SIZE
= 24 };
612 /* Open an available pty, returning a file descriptor.
613 Store into PTY_NAME the file name of the terminal corresponding to the pty.
614 Return -1 on failure. */
617 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
626 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
627 for (i
= 0; i
< 16; i
++)
630 #ifdef PTY_NAME_SPRINTF
633 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
634 #endif /* no PTY_NAME_SPRINTF */
638 #else /* no PTY_OPEN */
639 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
640 #endif /* no PTY_OPEN */
644 #ifdef PTY_TTY_NAME_SPRINTF
647 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
648 #endif /* no PTY_TTY_NAME_SPRINTF */
650 /* Set FD's close-on-exec flag. This is needed even if
651 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
652 doesn't require support for that combination.
653 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
654 doesn't work if the close-on-exec flag is set (Bug#20555).
655 Multithreaded platforms where posix_openpt ignores
656 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
657 have a race condition between the PTY_OPEN and here. */
658 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
660 /* Check to make certain that both sides are available.
661 This avoids a nasty yet stupid bug in rlogins. */
662 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
675 #endif /* HAVE_PTYS */
679 /* Allocate basically initialized process. */
681 static struct Lisp_Process
*
682 allocate_process (void)
684 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
688 make_process (Lisp_Object name
)
690 register Lisp_Object val
, tem
, name1
;
691 register struct Lisp_Process
*p
;
692 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
695 p
= allocate_process ();
696 /* Initialize Lisp data. Note that allocate_process initializes all
697 Lisp data to nil, so do it only for slots which should not be nil. */
698 pset_status (p
, Qrun
);
699 pset_mark (p
, Fmake_marker ());
701 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
702 non-Lisp data, so do it only for slots which should not be zero. */
705 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
709 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
710 p
->gnutls_boot_parameters
= Qnil
;
713 /* If name is already in use, modify it until it is unused. */
718 tem
= Fget_process (name1
);
719 if (NILP (tem
)) break;
720 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
724 pset_sentinel (p
, Qinternal_default_process_sentinel
);
725 pset_filter (p
, Qinternal_default_process_filter
);
726 XSETPROCESS (val
, p
);
727 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
732 remove_process (register Lisp_Object proc
)
734 register Lisp_Object pair
;
736 pair
= Frassq (proc
, Vprocess_alist
);
737 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
739 deactivate_process (proc
);
742 #ifdef HAVE_GETADDRINFO_A
744 free_dns_request (Lisp_Object proc
)
746 struct Lisp_Process
*p
= XPROCESS (proc
);
748 if (p
->dns_request
->ar_result
)
749 freeaddrinfo (p
->dns_request
->ar_result
);
750 xfree (p
->dns_request
);
751 p
->dns_request
= NULL
;
756 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
757 doc
: /* Return t if OBJECT is a process. */)
760 return PROCESSP (object
) ? Qt
: Qnil
;
763 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
764 doc
: /* Return the process named NAME, or nil if there is none. */)
765 (register Lisp_Object name
)
770 return Fcdr (Fassoc (name
, Vprocess_alist
));
773 /* This is how commands for the user decode process arguments. It
774 accepts a process, a process name, a buffer, a buffer name, or nil.
775 Buffers denote the first process in the buffer, and nil denotes the
779 get_process (register Lisp_Object name
)
781 register Lisp_Object proc
, obj
;
784 obj
= Fget_process (name
);
786 obj
= Fget_buffer (name
);
788 error ("Process %s does not exist", SDATA (name
));
790 else if (NILP (name
))
791 obj
= Fcurrent_buffer ();
795 /* Now obj should be either a buffer object or a process object. */
798 if (NILP (BVAR (XBUFFER (obj
), name
)))
799 error ("Attempt to get process for a dead buffer");
800 proc
= Fget_buffer_process (obj
);
802 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
813 /* Fdelete_process promises to immediately forget about the process, but in
814 reality, Emacs needs to remember those processes until they have been
815 treated by the SIGCHLD handler and waitpid has been invoked on them;
816 otherwise they might fill up the kernel's process table.
818 Some processes created by call-process are also put onto this list.
820 Members of this list are (process-ID . filename) pairs. The
821 process-ID is a number; the filename, if a string, is a file that
822 needs to be removed after the process exits. */
823 static Lisp_Object deleted_pid_list
;
826 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
828 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
829 /* GC treated elements set to nil. */
830 Fdelq (Qnil
, deleted_pid_list
));
834 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
835 doc
: /* Delete PROCESS: kill it and forget about it immediately.
836 PROCESS may be a process, a buffer, the name of a process or buffer, or
837 nil, indicating the current buffer's process. */)
838 (register Lisp_Object process
)
840 register struct Lisp_Process
*p
;
842 process
= get_process (process
);
843 p
= XPROCESS (process
);
845 #ifdef HAVE_GETADDRINFO_A
848 gai_cancel (p
->dns_request
);
849 free_dns_request (process
);
853 p
->raw_status_new
= 0;
854 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
856 pset_status (p
, list2 (Qexit
, make_number (0)));
857 p
->tick
= ++process_tick
;
858 status_notify (p
, NULL
);
859 redisplay_preserve_echo_area (13);
864 record_kill_process (p
, Qnil
);
868 /* Update P's status, since record_kill_process will make the
869 SIGCHLD handler update deleted_pid_list, not *P. */
871 if (p
->raw_status_new
)
873 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
874 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
875 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
877 p
->tick
= ++process_tick
;
878 status_notify (p
, NULL
);
879 redisplay_preserve_echo_area (13);
882 remove_process (process
);
886 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
887 doc
: /* Return the status of PROCESS.
888 The returned value is one of the following symbols:
889 run -- for a process that is running.
890 stop -- for a process stopped but continuable.
891 exit -- for a process that has exited.
892 signal -- for a process that has got a fatal signal.
893 open -- for a network stream connection that is open.
894 listen -- for a network stream server that is listening.
895 closed -- for a network stream connection that is closed.
896 connect -- when waiting for a non-blocking connection to complete.
897 failed -- when a non-blocking connection has failed.
898 nil -- if arg is a process name and no such process exists.
899 PROCESS may be a process, a buffer, the name of a process, or
900 nil, indicating the current buffer's process. */)
901 (register Lisp_Object process
)
903 register struct Lisp_Process
*p
;
904 register Lisp_Object status
;
906 if (STRINGP (process
))
907 process
= Fget_process (process
);
909 process
= get_process (process
);
914 p
= XPROCESS (process
);
915 if (p
->raw_status_new
)
919 status
= XCAR (status
);
920 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
922 if (EQ (status
, Qexit
))
924 else if (EQ (p
->command
, Qt
))
926 else if (EQ (status
, Qrun
))
932 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
934 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
935 If PROCESS has not yet exited or died, return 0. */)
936 (register Lisp_Object process
)
938 CHECK_PROCESS (process
);
939 if (XPROCESS (process
)->raw_status_new
)
940 update_status (XPROCESS (process
));
941 if (CONSP (XPROCESS (process
)->status
))
942 return XCAR (XCDR (XPROCESS (process
)->status
));
943 return make_number (0);
946 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
947 doc
: /* Return the process id of PROCESS.
948 This is the pid of the external process which PROCESS uses or talks to.
949 For a network connection, this value is nil. */)
950 (register Lisp_Object process
)
954 CHECK_PROCESS (process
);
955 pid
= XPROCESS (process
)->pid
;
956 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
959 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
960 doc
: /* Return the name of PROCESS, as a string.
961 This is the name of the program invoked in PROCESS,
962 possibly modified to make it unique among process names. */)
963 (register Lisp_Object process
)
965 CHECK_PROCESS (process
);
966 return XPROCESS (process
)->name
;
969 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
970 doc
: /* Return the command that was executed to start PROCESS.
971 This is a list of strings, the first string being the program executed
972 and the rest of the strings being the arguments given to it.
973 For a network or serial process, this is nil (process is running) or t
974 (process is stopped). */)
975 (register Lisp_Object process
)
977 CHECK_PROCESS (process
);
978 return XPROCESS (process
)->command
;
981 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
982 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
983 This is the terminal that the process itself reads and writes on,
984 not the name of the pty that Emacs uses to talk with that terminal. */)
985 (register Lisp_Object process
)
987 CHECK_PROCESS (process
);
988 return XPROCESS (process
)->tty_name
;
991 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
993 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
995 (register Lisp_Object process
, Lisp_Object buffer
)
997 struct Lisp_Process
*p
;
999 CHECK_PROCESS (process
);
1001 CHECK_BUFFER (buffer
);
1002 p
= XPROCESS (process
);
1003 pset_buffer (p
, buffer
);
1004 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1005 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1006 setup_process_coding_systems (process
);
1010 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1012 doc
: /* Return the buffer PROCESS is associated with.
1013 The default process filter inserts output from PROCESS into this buffer. */)
1014 (register Lisp_Object process
)
1016 CHECK_PROCESS (process
);
1017 return XPROCESS (process
)->buffer
;
1020 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1022 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1023 (register Lisp_Object process
)
1025 CHECK_PROCESS (process
);
1026 return XPROCESS (process
)->mark
;
1030 set_process_filter_masks (struct Lisp_Process
*p
)
1032 if (EQ (p
->filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1034 FD_CLR (p
->infd
, &input_wait_mask
);
1035 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1037 else if (EQ (p
->filter
, Qt
)
1038 /* Network or serial process not stopped: */
1039 && !EQ (p
->command
, Qt
))
1041 FD_SET (p
->infd
, &input_wait_mask
);
1042 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1046 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1048 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1049 A value of t means stop accepting output from the process.
1051 When a process has a non-default filter, its buffer is not used for output.
1052 Instead, each time it does output, the entire string of output is
1053 passed to the filter.
1055 The filter gets two arguments: the process and the string of output.
1056 The string argument is normally a multibyte string, except:
1057 - if the process's input coding system is no-conversion or raw-text,
1058 it is a unibyte string (the non-converted input), or else
1059 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1060 string (the result of converting the decoded input multibyte
1061 string to unibyte with `string-make-unibyte'). */)
1062 (Lisp_Object process
, Lisp_Object filter
)
1064 CHECK_PROCESS (process
);
1065 struct Lisp_Process
*p
= XPROCESS (process
);
1067 /* Don't signal an error if the process's input file descriptor
1068 is closed. This could make debugging Lisp more difficult,
1069 for example when doing something like
1071 (setq process (start-process ...))
1073 (set-process-filter process ...) */
1076 filter
= Qinternal_default_process_filter
;
1078 pset_filter (p
, filter
);
1081 set_process_filter_masks (p
);
1083 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1084 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1085 setup_process_coding_systems (process
);
1089 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1091 doc
: /* Return the filter function of PROCESS.
1092 See `set-process-filter' for more info on filter functions. */)
1093 (register Lisp_Object process
)
1095 CHECK_PROCESS (process
);
1096 return XPROCESS (process
)->filter
;
1099 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1101 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1102 The sentinel is called as a function when the process changes state.
1103 It gets two arguments: the process, and a string describing the change. */)
1104 (register Lisp_Object process
, Lisp_Object sentinel
)
1106 struct Lisp_Process
*p
;
1108 CHECK_PROCESS (process
);
1109 p
= XPROCESS (process
);
1111 if (NILP (sentinel
))
1112 sentinel
= Qinternal_default_process_sentinel
;
1114 pset_sentinel (p
, sentinel
);
1115 if (NETCONN1_P (p
) || SERIALCONN1_P (p
) || PIPECONN1_P (p
))
1116 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1120 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1122 doc
: /* Return the sentinel of PROCESS.
1123 See `set-process-sentinel' for more info on sentinels. */)
1124 (register Lisp_Object process
)
1126 CHECK_PROCESS (process
);
1127 return XPROCESS (process
)->sentinel
;
1130 DEFUN ("set-process-window-size", Fset_process_window_size
,
1131 Sset_process_window_size
, 3, 3, 0,
1132 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1133 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1135 CHECK_PROCESS (process
);
1137 /* All known platforms store window sizes as 'unsigned short'. */
1138 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1139 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1141 if (NETCONN_P (process
)
1142 || XPROCESS (process
)->infd
< 0
1143 || (set_window_size (XPROCESS (process
)->infd
,
1144 XINT (height
), XINT (width
))
1151 DEFUN ("set-process-inherit-coding-system-flag",
1152 Fset_process_inherit_coding_system_flag
,
1153 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1154 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1155 If the second argument FLAG is non-nil, then the variable
1156 `buffer-file-coding-system' of the buffer associated with PROCESS
1157 will be bound to the value of the coding system used to decode
1160 This is useful when the coding system specified for the process buffer
1161 leaves either the character code conversion or the end-of-line conversion
1162 unspecified, or if the coding system used to decode the process output
1163 is more appropriate for saving the process buffer.
1165 Binding the variable `inherit-process-coding-system' to non-nil before
1166 starting the process is an alternative way of setting the inherit flag
1167 for the process which will run.
1169 This function returns FLAG. */)
1170 (register Lisp_Object process
, Lisp_Object flag
)
1172 CHECK_PROCESS (process
);
1173 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1177 DEFUN ("set-process-query-on-exit-flag",
1178 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1180 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1181 If the second argument FLAG is non-nil, Emacs will query the user before
1182 exiting or killing a buffer if PROCESS is running. This function
1184 (register Lisp_Object process
, Lisp_Object flag
)
1186 CHECK_PROCESS (process
);
1187 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1191 DEFUN ("process-query-on-exit-flag",
1192 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1194 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1195 (register Lisp_Object process
)
1197 CHECK_PROCESS (process
);
1198 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1201 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1203 doc
: /* Return the contact info of PROCESS; t for a real child.
1204 For a network or serial connection, the value depends on the optional
1205 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1206 SERVICE) for a network connection or (PORT SPEED) for a serial
1207 connection. If KEY is t, the complete contact information for the
1208 connection is returned, else the specific value for the keyword KEY is
1209 returned. See `make-network-process' or `make-serial-process' for a
1211 If PROCESS is a non-blocking network process that hasn't been fully
1212 set up yet, this function will block until socket setup has completed. */)
1213 (Lisp_Object process
, Lisp_Object key
)
1215 Lisp_Object contact
;
1217 CHECK_PROCESS (process
);
1218 contact
= XPROCESS (process
)->childp
;
1220 #ifdef DATAGRAM_SOCKETS
1222 if (NETCONN_P (process
))
1223 wait_for_socket_fds (process
, "process-contact");
1225 if (DATAGRAM_CONN_P (process
)
1226 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1227 contact
= Fplist_put (contact
, QCremote
,
1228 Fprocess_datagram_address (process
));
1231 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
) && !PIPECONN_P (process
))
1234 if (NILP (key
) && NETCONN_P (process
))
1235 return list2 (Fplist_get (contact
, QChost
),
1236 Fplist_get (contact
, QCservice
));
1237 if (NILP (key
) && SERIALCONN_P (process
))
1238 return list2 (Fplist_get (contact
, QCport
),
1239 Fplist_get (contact
, QCspeed
));
1240 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1241 if the pipe process is useful for purposes other than receiving
1243 if (NILP (key
) && PIPECONN_P (process
))
1245 return Fplist_get (contact
, key
);
1248 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1250 doc
: /* Return the plist of PROCESS. */)
1251 (register Lisp_Object process
)
1253 CHECK_PROCESS (process
);
1254 return XPROCESS (process
)->plist
;
1257 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1259 doc
: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1260 (Lisp_Object process
, Lisp_Object plist
)
1262 CHECK_PROCESS (process
);
1265 pset_plist (XPROCESS (process
), plist
);
1269 #if 0 /* Turned off because we don't currently record this info
1270 in the process. Perhaps add it. */
1271 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1272 doc
: /* Return the connection type of PROCESS.
1273 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1274 a socket connection. */)
1275 (Lisp_Object process
)
1277 return XPROCESS (process
)->type
;
1281 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1282 doc
: /* Return the connection type of PROCESS.
1283 The value is either the symbol `real', `network', or `serial'.
1284 PROCESS may be a process, a buffer, the name of a process or buffer, or
1285 nil, indicating the current buffer's process. */)
1286 (Lisp_Object process
)
1289 proc
= get_process (process
);
1290 return XPROCESS (proc
)->type
;
1293 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1295 doc
: /* Convert network ADDRESS from internal format to a string.
1296 A 4 or 5 element vector represents an IPv4 address (with port number).
1297 An 8 or 9 element vector represents an IPv6 address (with port number).
1298 If optional second argument OMIT-PORT is non-nil, don't include a port
1299 number in the string, even when present in ADDRESS.
1300 Return nil if format of ADDRESS is invalid. */)
1301 (Lisp_Object address
, Lisp_Object omit_port
)
1306 if (STRINGP (address
)) /* AF_LOCAL */
1309 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1311 register struct Lisp_Vector
*p
= XVECTOR (address
);
1312 ptrdiff_t size
= p
->header
.size
;
1313 Lisp_Object args
[10];
1317 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1319 format
= "%d.%d.%d.%d";
1324 format
= "%d.%d.%d.%d:%d";
1327 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1329 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1334 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1340 AUTO_STRING (format_obj
, format
);
1341 args
[0] = format_obj
;
1343 for (i
= 0; i
< nargs
; i
++)
1345 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1348 if (nargs
<= 5 /* IPv4 */
1349 && i
< 4 /* host, not port */
1350 && XINT (p
->contents
[i
]) > 255)
1353 args
[i
+ 1] = p
->contents
[i
];
1356 return Fformat (nargs
+ 1, args
);
1359 if (CONSP (address
))
1361 AUTO_STRING (format
, "<Family %d>");
1362 return CALLN (Fformat
, format
, Fcar (address
));
1368 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1369 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1372 return Fmapcar (Qcdr
, Vprocess_alist
);
1375 /* Starting asynchronous inferior processes. */
1377 static void start_process_unwind (Lisp_Object proc
);
1379 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1380 doc
: /* Start a program in a subprocess. Return the process object for it.
1382 This is similar to `start-process', but arguments are specified as
1383 keyword/argument pairs. The following arguments are defined:
1385 :name NAME -- NAME is name for process. It is modified if necessary
1388 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1389 with the process. Process output goes at end of that buffer, unless
1390 you specify an output stream or filter function to handle the output.
1391 BUFFER may be also nil, meaning that this process is not associated
1394 :command COMMAND -- COMMAND is a list starting with the program file
1395 name, followed by strings to give to the program as arguments.
1397 :coding CODING -- If CODING is a symbol, it specifies the coding
1398 system used for both reading and writing for this process. If CODING
1399 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1400 ENCODING is used for writing.
1402 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1403 the process is running. If BOOL is not given, query before exiting.
1405 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1406 In the stopped state, a process does not accept incoming data, but you
1407 can send outgoing data. The stopped state is cleared by
1408 `continue-process' and set by `stop-process'.
1410 :connection-type TYPE -- TYPE is control type of device used to
1411 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1412 to use a pty, or nil to use the default specified through
1413 `process-connection-type'.
1415 :filter FILTER -- Install FILTER as the process filter.
1417 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1419 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1420 to the standard error of subprocess. Specifying this implies
1421 `:connection-type' is set to `pipe'.
1423 usage: (make-process &rest ARGS) */)
1424 (ptrdiff_t nargs
, Lisp_Object
*args
)
1426 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1427 Lisp_Object xstderr
, stderrproc
;
1428 ptrdiff_t count
= SPECPDL_INDEX ();
1434 /* Save arguments for process-contact and clone-process. */
1435 contact
= Flist (nargs
, args
);
1437 buffer
= Fplist_get (contact
, QCbuffer
);
1439 buffer
= Fget_buffer_create (buffer
);
1441 /* Make sure that the child will be able to chdir to the current
1442 buffer's current directory, or its unhandled equivalent. We
1443 can't just have the child check for an error when it does the
1444 chdir, since it's in a vfork. */
1445 current_dir
= encode_current_directory ();
1447 name
= Fplist_get (contact
, QCname
);
1448 CHECK_STRING (name
);
1450 command
= Fplist_get (contact
, QCcommand
);
1451 if (CONSP (command
))
1452 program
= XCAR (command
);
1456 if (!NILP (program
))
1457 CHECK_STRING (program
);
1460 xstderr
= Fplist_get (contact
, QCstderr
);
1461 if (PROCESSP (xstderr
))
1463 if (!PIPECONN_P (xstderr
))
1464 error ("Process is not a pipe process");
1465 stderrproc
= xstderr
;
1467 else if (!NILP (xstderr
))
1469 CHECK_STRING (program
);
1470 stderrproc
= CALLN (Fmake_pipe_process
,
1472 concat2 (name
, build_string (" stderr")),
1474 Fget_buffer_create (xstderr
));
1477 proc
= make_process (name
);
1478 /* If an error occurs and we can't start the process, we want to
1479 remove it from the process list. This means that each error
1480 check in create_process doesn't need to call remove_process
1481 itself; it's all taken care of here. */
1482 record_unwind_protect (start_process_unwind
, proc
);
1484 pset_childp (XPROCESS (proc
), Qt
);
1485 pset_plist (XPROCESS (proc
), Qnil
);
1486 pset_type (XPROCESS (proc
), Qreal
);
1487 pset_buffer (XPROCESS (proc
), buffer
);
1488 pset_sentinel (XPROCESS (proc
), Fplist_get (contact
, QCsentinel
));
1489 pset_filter (XPROCESS (proc
), Fplist_get (contact
, QCfilter
));
1490 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1492 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1493 XPROCESS (proc
)->kill_without_query
= 1;
1494 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1495 pset_command (XPROCESS (proc
), Qt
);
1497 tem
= Fplist_get (contact
, QCconnection_type
);
1499 XPROCESS (proc
)->pty_flag
= true;
1500 else if (EQ (tem
, Qpipe
))
1501 XPROCESS (proc
)->pty_flag
= false;
1502 else if (NILP (tem
))
1503 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1505 report_file_error ("Unknown connection type", tem
);
1507 if (!NILP (stderrproc
))
1509 pset_stderrproc (XPROCESS (proc
), stderrproc
);
1511 XPROCESS (proc
)->pty_flag
= false;
1515 /* AKA GNUTLS_INITSTAGE(proc). */
1516 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1517 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1520 XPROCESS (proc
)->adaptive_read_buffering
1521 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1522 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1524 /* Make the process marker point into the process buffer (if any). */
1525 if (BUFFERP (buffer
))
1526 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1527 BUF_ZV (XBUFFER (buffer
)),
1528 BUF_ZV_BYTE (XBUFFER (buffer
)));
1531 /* Decide coding systems for communicating with the process. Here
1532 we don't setup the structure coding_system nor pay attention to
1533 unibyte mode. They are done in create_process. */
1535 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1536 Lisp_Object coding_systems
= Qt
;
1537 Lisp_Object val
, *args2
;
1539 tem
= Fplist_get (contact
, QCcoding
);
1547 val
= Vcoding_system_for_read
;
1550 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1552 SAFE_ALLOCA_LISP (args2
, nargs2
);
1554 args2
[i
++] = Qstart_process
;
1556 args2
[i
++] = buffer
;
1557 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1558 args2
[i
++] = XCAR (tem2
);
1559 if (!NILP (program
))
1560 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1561 if (CONSP (coding_systems
))
1562 val
= XCAR (coding_systems
);
1563 else if (CONSP (Vdefault_process_coding_system
))
1564 val
= XCAR (Vdefault_process_coding_system
);
1566 pset_decode_coding_system (XPROCESS (proc
), val
);
1575 val
= Vcoding_system_for_write
;
1578 if (EQ (coding_systems
, Qt
))
1580 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1582 SAFE_ALLOCA_LISP (args2
, nargs2
);
1584 args2
[i
++] = Qstart_process
;
1586 args2
[i
++] = buffer
;
1587 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1588 args2
[i
++] = XCAR (tem2
);
1589 if (!NILP (program
))
1590 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1592 if (CONSP (coding_systems
))
1593 val
= XCDR (coding_systems
);
1594 else if (CONSP (Vdefault_process_coding_system
))
1595 val
= XCDR (Vdefault_process_coding_system
);
1597 pset_encode_coding_system (XPROCESS (proc
), val
);
1598 /* Note: At this moment, the above coding system may leave
1599 text-conversion or eol-conversion unspecified. They will be
1600 decided after we read output from the process and decode it by
1601 some coding system, or just before we actually send a text to
1606 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1607 XPROCESS (proc
)->decoding_carryover
= 0;
1608 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1610 XPROCESS (proc
)->inherit_coding_system_flag
1611 = !(NILP (buffer
) || !inherit_process_coding_system
);
1613 if (!NILP (program
))
1615 Lisp_Object program_args
= XCDR (command
);
1617 /* If program file name is not absolute, search our path for it.
1618 Put the name we will really use in TEM. */
1619 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1620 && !(SCHARS (program
) > 1
1621 && IS_DEVICE_SEP (SREF (program
, 1))))
1624 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1625 make_number (X_OK
), false);
1627 report_file_error ("Searching for program", program
);
1628 tem
= Fexpand_file_name (tem
, Qnil
);
1632 if (!NILP (Ffile_directory_p (program
)))
1633 error ("Specified program for new process is a directory");
1637 /* Remove "/:" from TEM. */
1638 tem
= remove_slash_colon (tem
);
1640 Lisp_Object arg_encoding
= Qnil
;
1642 /* Encode the file name and put it in NEW_ARGV.
1643 That's where the child will use it to execute the program. */
1644 tem
= list1 (ENCODE_FILE (tem
));
1645 ptrdiff_t new_argc
= 1;
1647 /* Here we encode arguments by the coding system used for sending
1648 data to the process. We don't support using different coding
1649 systems for encoding arguments and for encoding data sent to the
1652 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1654 Lisp_Object arg
= XCAR (tem2
);
1656 if (STRING_MULTIBYTE (arg
))
1658 if (NILP (arg_encoding
))
1659 arg_encoding
= (complement_process_encoding_system
1660 (XPROCESS (proc
)->encode_coding_system
));
1661 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1663 tem
= Fcons (arg
, tem
);
1667 /* Now that everything is encoded we can collect the strings into
1670 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1671 new_argv
[new_argc
] = 0;
1673 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1675 new_argv
[i
] = SSDATA (XCAR (tem
));
1679 create_process (proc
, new_argv
, current_dir
);
1685 return unbind_to (count
, proc
);
1688 /* This function is the unwind_protect form for Fstart_process. If
1689 PROC doesn't have its pid set, then we know someone has signaled
1690 an error and the process wasn't started successfully, so we should
1691 remove it from the process list. */
1693 start_process_unwind (Lisp_Object proc
)
1695 if (!PROCESSP (proc
))
1698 /* Was PROC started successfully?
1699 -2 is used for a pty with no process, eg for gdb. */
1700 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1701 remove_process (proc
);
1704 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1707 close_process_fd (int *fd_addr
)
1717 /* Indexes of file descriptors in open_fds. */
1720 /* The pipe from Emacs to its subprocess. */
1722 WRITE_TO_SUBPROCESS
,
1724 /* The main pipe from the subprocess to Emacs. */
1725 READ_FROM_SUBPROCESS
,
1728 /* The pipe from the subprocess to Emacs that is closed when the
1729 subprocess execs. */
1730 READ_FROM_EXEC_MONITOR
,
1734 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1737 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1739 struct Lisp_Process
*p
= XPROCESS (process
);
1740 int inchannel
, outchannel
;
1743 int forkin
, forkout
, forkerr
= -1;
1745 char pty_name
[PTY_NAME_SIZE
];
1746 Lisp_Object lisp_pty_name
= Qnil
;
1749 inchannel
= outchannel
= -1;
1752 outchannel
= inchannel
= allocate_pty (pty_name
);
1756 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1757 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1758 /* On most USG systems it does not work to open the pty's tty here,
1759 then close it and reopen it in the child. */
1760 /* Don't let this terminal become our controlling terminal
1761 (in case we don't have one). */
1762 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1764 report_file_error ("Opening pty", Qnil
);
1765 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1767 forkin
= forkout
= -1;
1768 #endif /* not USG, or USG_SUBTTY_WORKS */
1770 lisp_pty_name
= build_string (pty_name
);
1774 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1775 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1776 report_file_error ("Creating pipe", Qnil
);
1777 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1778 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1779 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1780 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1782 if (!NILP (p
->stderrproc
))
1784 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
1786 forkerr
= pp
->open_fd
[SUBPROCESS_STDOUT
];
1788 /* Close unnecessary file descriptors. */
1789 close_process_fd (&pp
->open_fd
[WRITE_TO_SUBPROCESS
]);
1790 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDIN
]);
1795 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1796 report_file_error ("Creating pipe", Qnil
);
1799 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1800 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1802 /* Record this as an active process, with its channels. */
1803 chan_process
[inchannel
] = process
;
1804 p
->infd
= inchannel
;
1805 p
->outfd
= outchannel
;
1807 /* Previously we recorded the tty descriptor used in the subprocess.
1808 It was only used for getting the foreground tty process, so now
1809 we just reopen the device (see emacs_get_tty_pgrp) as this is
1810 more portable (see USG_SUBTTY_WORKS above). */
1812 p
->pty_flag
= pty_flag
;
1813 pset_status (p
, Qrun
);
1815 if (!EQ (p
->command
, Qt
))
1817 FD_SET (inchannel
, &input_wait_mask
);
1818 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1821 if (inchannel
> max_process_desc
)
1822 max_process_desc
= inchannel
;
1824 /* This may signal an error. */
1825 setup_process_coding_systems (process
);
1828 block_child_signal (&oldset
);
1831 /* vfork, and prevent local vars from being clobbered by the vfork. */
1832 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1833 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1834 char **volatile new_argv_volatile
= new_argv
;
1835 int volatile forkin_volatile
= forkin
;
1836 int volatile forkout_volatile
= forkout
;
1837 int volatile forkerr_volatile
= forkerr
;
1838 struct Lisp_Process
*p_volatile
= p
;
1842 current_dir
= current_dir_volatile
;
1843 lisp_pty_name
= lisp_pty_name_volatile
;
1844 new_argv
= new_argv_volatile
;
1845 forkin
= forkin_volatile
;
1846 forkout
= forkout_volatile
;
1847 forkerr
= forkerr_volatile
;
1850 pty_flag
= p
->pty_flag
;
1853 #endif /* not WINDOWSNT */
1855 /* Make the pty be the controlling terminal of the process. */
1857 /* First, disconnect its current controlling terminal. */
1858 /* We tried doing setsid only if pty_flag, but it caused
1859 process_set_signal to fail on SGI when using a pipe. */
1861 /* Make the pty's terminal the controlling terminal. */
1862 if (pty_flag
&& forkin
>= 0)
1865 /* We ignore the return value
1866 because faith@cs.unc.edu says that is necessary on Linux. */
1867 ioctl (forkin
, TIOCSCTTY
, 0);
1870 #if defined (LDISC1)
1871 if (pty_flag
&& forkin
>= 0)
1874 tcgetattr (forkin
, &t
);
1876 if (tcsetattr (forkin
, TCSANOW
, &t
) < 0)
1877 emacs_perror ("create_process/tcsetattr LDISC1");
1880 #if defined (NTTYDISC) && defined (TIOCSETD)
1881 if (pty_flag
&& forkin
>= 0)
1883 /* Use new line discipline. */
1884 int ldisc
= NTTYDISC
;
1885 ioctl (forkin
, TIOCSETD
, &ldisc
);
1890 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1891 can do TIOCSPGRP only to the process's controlling tty. */
1894 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1895 I can't test it since I don't have 4.3. */
1896 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1899 ioctl (j
, TIOCNOTTY
, 0);
1903 #endif /* TIOCNOTTY */
1905 #if !defined (DONT_REOPEN_PTY)
1906 /*** There is a suggestion that this ought to be a
1907 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1908 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1909 that system does seem to need this code, even though
1910 both TIOCSCTTY is defined. */
1911 /* Now close the pty (if we had it open) and reopen it.
1912 This makes the pty the controlling terminal of the subprocess. */
1916 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1919 emacs_close (forkin
);
1920 forkout
= forkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1924 emacs_perror (SSDATA (lisp_pty_name
));
1925 _exit (EXIT_CANCELED
);
1929 #endif /* not DONT_REOPEN_PTY */
1931 #ifdef SETUP_SLAVE_PTY
1936 #endif /* SETUP_SLAVE_PTY */
1937 #endif /* HAVE_PTYS */
1939 signal (SIGINT
, SIG_DFL
);
1940 signal (SIGQUIT
, SIG_DFL
);
1942 signal (SIGPROF
, SIG_DFL
);
1945 /* Emacs ignores SIGPIPE, but the child should not. */
1946 signal (SIGPIPE
, SIG_DFL
);
1948 /* Stop blocking SIGCHLD in the child. */
1949 unblock_child_signal (&oldset
);
1952 child_setup_tty (forkout
);
1957 pid
= child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1958 #else /* not WINDOWSNT */
1959 child_setup (forkin
, forkout
, forkerr
, new_argv
, 1, current_dir
);
1960 #endif /* not WINDOWSNT */
1963 /* Back in the parent process. */
1965 vfork_errno
= errno
;
1970 /* Stop blocking in the parent. */
1971 unblock_child_signal (&oldset
);
1975 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1978 /* vfork succeeded. */
1980 /* Close the pipe ends that the child uses, or the child's pty. */
1981 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1982 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1985 register_child (pid
, inchannel
);
1986 #endif /* WINDOWSNT */
1988 pset_tty_name (p
, lisp_pty_name
);
1991 /* Wait for child_setup to complete in case that vfork is
1992 actually defined as fork. The descriptor
1993 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1994 of a pipe is closed at the child side either by close-on-exec
1995 on successful execve or the _exit call in child_setup. */
1999 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2000 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2001 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2004 if (!NILP (p
->stderrproc
))
2006 struct Lisp_Process
*pp
= XPROCESS (p
->stderrproc
);
2007 close_process_fd (&pp
->open_fd
[SUBPROCESS_STDOUT
]);
2013 create_pty (Lisp_Object process
)
2015 struct Lisp_Process
*p
= XPROCESS (process
);
2016 char pty_name
[PTY_NAME_SIZE
];
2017 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
2021 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2022 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2023 /* On most USG systems it does not work to open the pty's tty here,
2024 then close it and reopen it in the child. */
2025 /* Don't let this terminal become our controlling terminal
2026 (in case we don't have one). */
2027 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2029 report_file_error ("Opening pty", Qnil
);
2030 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2031 #if defined (DONT_REOPEN_PTY)
2032 /* In the case that vfork is defined as fork, the parent process
2033 (Emacs) may send some data before the child process completes
2034 tty options setup. So we setup tty before forking. */
2035 child_setup_tty (forkout
);
2036 #endif /* DONT_REOPEN_PTY */
2037 #endif /* not USG, or USG_SUBTTY_WORKS */
2039 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2041 /* Record this as an active process, with its channels.
2042 As a result, child_setup will close Emacs's side of the pipes. */
2043 chan_process
[pty_fd
] = process
;
2047 /* Previously we recorded the tty descriptor used in the subprocess.
2048 It was only used for getting the foreground tty process, so now
2049 we just reopen the device (see emacs_get_tty_pgrp) as this is
2050 more portable (see USG_SUBTTY_WORKS above). */
2053 pset_status (p
, Qrun
);
2054 setup_process_coding_systems (process
);
2056 FD_SET (pty_fd
, &input_wait_mask
);
2057 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2058 if (pty_fd
> max_process_desc
)
2059 max_process_desc
= pty_fd
;
2061 pset_tty_name (p
, build_string (pty_name
));
2067 DEFUN ("make-pipe-process", Fmake_pipe_process
, Smake_pipe_process
,
2069 doc
: /* Create and return a bidirectional pipe process.
2071 In Emacs, pipes are represented by process objects, so input and
2072 output work as for subprocesses, and `delete-process' closes a pipe.
2073 However, a pipe process has no process id, it cannot be signaled,
2074 and the status codes are different from normal processes.
2076 Arguments are specified as keyword/argument pairs. The following
2077 arguments are defined:
2079 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2081 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2082 with the process. Process output goes at the end of that buffer,
2083 unless you specify an output stream or filter function to handle the
2084 output. If BUFFER is not given, the value of NAME is used.
2086 :coding CODING -- If CODING is a symbol, it specifies the coding
2087 system used for both reading and writing for this process. If CODING
2088 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2089 ENCODING is used for writing.
2091 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2092 the process is running. If BOOL is not given, query before exiting.
2094 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2095 In the stopped state, a pipe process does not accept incoming data,
2096 but you can send outgoing data. The stopped state is cleared by
2097 `continue-process' and set by `stop-process'.
2099 :filter FILTER -- Install FILTER as the process filter.
2101 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2103 usage: (make-pipe-process &rest ARGS) */)
2104 (ptrdiff_t nargs
, Lisp_Object
*args
)
2106 Lisp_Object proc
, contact
;
2107 struct Lisp_Process
*p
;
2108 Lisp_Object name
, buffer
;
2110 ptrdiff_t specpdl_count
;
2111 int inchannel
, outchannel
;
2116 contact
= Flist (nargs
, args
);
2118 name
= Fplist_get (contact
, QCname
);
2119 CHECK_STRING (name
);
2120 proc
= make_process (name
);
2121 specpdl_count
= SPECPDL_INDEX ();
2122 record_unwind_protect (remove_process
, proc
);
2123 p
= XPROCESS (proc
);
2125 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
2126 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
2127 report_file_error ("Creating pipe", Qnil
);
2128 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
2129 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
2131 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2132 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2135 register_aux_fd (inchannel
);
2138 /* Record this as an active process, with its channels. */
2139 chan_process
[inchannel
] = proc
;
2140 p
->infd
= inchannel
;
2141 p
->outfd
= outchannel
;
2143 if (inchannel
> max_process_desc
)
2144 max_process_desc
= inchannel
;
2146 buffer
= Fplist_get (contact
, QCbuffer
);
2149 buffer
= Fget_buffer_create (buffer
);
2150 pset_buffer (p
, buffer
);
2152 pset_childp (p
, contact
);
2153 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2154 pset_type (p
, Qpipe
);
2155 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2156 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2158 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2159 p
->kill_without_query
= 1;
2160 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2161 pset_command (p
, Qt
);
2162 eassert (! p
->pty_flag
);
2164 if (!EQ (p
->command
, Qt
))
2166 FD_SET (inchannel
, &input_wait_mask
);
2167 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2169 p
->adaptive_read_buffering
2170 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
2171 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
2173 /* Make the process marker point into the process buffer (if any). */
2174 if (BUFFERP (buffer
))
2175 set_marker_both (p
->mark
, buffer
,
2176 BUF_ZV (XBUFFER (buffer
)),
2177 BUF_ZV_BYTE (XBUFFER (buffer
)));
2180 /* Setup coding systems for communicating with the network stream. */
2182 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2183 Lisp_Object coding_systems
= Qt
;
2186 tem
= Fplist_get (contact
, QCcoding
);
2194 else if (!NILP (Vcoding_system_for_read
))
2195 val
= Vcoding_system_for_read
;
2196 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2197 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2198 /* We dare not decode end-of-line format by setting VAL to
2199 Qraw_text, because the existing Emacs Lisp libraries
2200 assume that they receive bare code including a sequence of
2205 if (CONSP (coding_systems
))
2206 val
= XCAR (coding_systems
);
2207 else if (CONSP (Vdefault_process_coding_system
))
2208 val
= XCAR (Vdefault_process_coding_system
);
2212 pset_decode_coding_system (p
, val
);
2220 else if (!NILP (Vcoding_system_for_write
))
2221 val
= Vcoding_system_for_write
;
2222 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2226 if (CONSP (coding_systems
))
2227 val
= XCDR (coding_systems
);
2228 else if (CONSP (Vdefault_process_coding_system
))
2229 val
= XCDR (Vdefault_process_coding_system
);
2233 pset_encode_coding_system (p
, val
);
2235 /* This may signal an error. */
2236 setup_process_coding_systems (proc
);
2238 specpdl_ptr
= specpdl
+ specpdl_count
;
2244 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2245 The address family of sa is not included in the result. */
2248 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2250 Lisp_Object address
;
2253 register struct Lisp_Vector
*p
;
2255 /* Workaround for a bug in getsockname on BSD: Names bound to
2256 sockets in the UNIX domain are inaccessible; getsockname returns
2257 a zero length name. */
2258 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2259 return empty_unibyte_string
;
2261 switch (sa
->sa_family
)
2265 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2266 len
= sizeof (sin
->sin_addr
) + 1;
2267 address
= Fmake_vector (make_number (len
), Qnil
);
2268 p
= XVECTOR (address
);
2269 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2270 cp
= (unsigned char *) &sin
->sin_addr
;
2276 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2277 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2278 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2279 address
= Fmake_vector (make_number (len
), Qnil
);
2280 p
= XVECTOR (address
);
2281 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2282 for (i
= 0; i
< len
; i
++)
2283 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2287 #ifdef HAVE_LOCAL_SOCKETS
2290 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2291 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2292 /* If the first byte is NUL, the name is a Linux abstract
2293 socket name, and the name can contain embedded NULs. If
2294 it's not, we have a NUL-terminated string. Be careful not
2295 to walk past the end of the object looking for the name
2296 terminator, however. */
2297 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2299 const char *terminator
2300 = memchr (sockun
->sun_path
, '\0', name_length
);
2303 name_length
= terminator
- (const char *) sockun
->sun_path
;
2306 return make_unibyte_string (sockun
->sun_path
, name_length
);
2310 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2311 address
= Fcons (make_number (sa
->sa_family
),
2312 Fmake_vector (make_number (len
), Qnil
));
2313 p
= XVECTOR (XCDR (address
));
2314 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2320 p
->contents
[i
++] = make_number (*cp
++);
2326 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2329 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2331 register struct Lisp_Vector
*p
;
2333 if (VECTORP (address
))
2335 p
= XVECTOR (address
);
2336 if (p
->header
.size
== 5)
2339 return sizeof (struct sockaddr_in
);
2342 else if (p
->header
.size
== 9)
2344 *familyp
= AF_INET6
;
2345 return sizeof (struct sockaddr_in6
);
2349 #ifdef HAVE_LOCAL_SOCKETS
2350 else if (STRINGP (address
))
2352 *familyp
= AF_LOCAL
;
2353 return sizeof (struct sockaddr_un
);
2356 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2357 && VECTORP (XCDR (address
)))
2359 struct sockaddr
*sa
;
2360 p
= XVECTOR (XCDR (address
));
2361 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2363 *familyp
= XINT (XCAR (address
));
2364 return p
->header
.size
+ sizeof (sa
->sa_family
);
2369 /* Convert an address object (vector or string) to an internal sockaddr.
2371 The address format has been basically validated by
2372 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2373 it could have come from user data. So if FAMILY is not valid,
2374 we return after zeroing *SA. */
2377 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2379 register struct Lisp_Vector
*p
;
2380 register unsigned char *cp
= NULL
;
2384 memset (sa
, 0, len
);
2386 if (VECTORP (address
))
2388 p
= XVECTOR (address
);
2389 if (family
== AF_INET
)
2391 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2392 len
= sizeof (sin
->sin_addr
) + 1;
2393 hostport
= XINT (p
->contents
[--len
]);
2394 sin
->sin_port
= htons (hostport
);
2395 cp
= (unsigned char *)&sin
->sin_addr
;
2396 sa
->sa_family
= family
;
2399 else if (family
== AF_INET6
)
2401 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2402 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2403 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2404 hostport
= XINT (p
->contents
[--len
]);
2405 sin6
->sin6_port
= htons (hostport
);
2406 for (i
= 0; i
< len
; i
++)
2407 if (INTEGERP (p
->contents
[i
]))
2409 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2412 sa
->sa_family
= family
;
2419 else if (STRINGP (address
))
2421 #ifdef HAVE_LOCAL_SOCKETS
2422 if (family
== AF_LOCAL
)
2424 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2425 cp
= SDATA (address
);
2426 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2427 sockun
->sun_path
[i
] = *cp
++;
2428 sa
->sa_family
= family
;
2435 p
= XVECTOR (XCDR (address
));
2436 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2439 for (i
= 0; i
< len
; i
++)
2440 if (INTEGERP (p
->contents
[i
]))
2441 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2444 #ifdef DATAGRAM_SOCKETS
2445 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2447 doc
: /* Get the current datagram address associated with PROCESS.
2448 If PROCESS is a non-blocking network process that hasn't been fully
2449 set up yet, this function will block until socket setup has completed. */)
2450 (Lisp_Object process
)
2454 CHECK_PROCESS (process
);
2456 if (NETCONN_P (process
))
2457 wait_for_socket_fds (process
, "process-datagram-address");
2459 if (!DATAGRAM_CONN_P (process
))
2462 channel
= XPROCESS (process
)->infd
;
2463 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2464 datagram_address
[channel
].len
);
2467 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2469 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2470 Return nil upon error setting address, ADDRESS otherwise.
2472 If PROCESS is a non-blocking network process that hasn't been fully
2473 set up yet, this function will block until socket setup has completed. */)
2474 (Lisp_Object process
, Lisp_Object address
)
2479 CHECK_PROCESS (process
);
2481 if (NETCONN_P (process
))
2482 wait_for_socket_fds (process
, "set-process-datagram-address");
2484 if (!DATAGRAM_CONN_P (process
))
2487 channel
= XPROCESS (process
)->infd
;
2489 len
= get_lisp_to_sockaddr_size (address
, &family
);
2490 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2492 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2498 static const struct socket_options
{
2499 /* The name of this option. Should be lowercase version of option
2500 name without SO_ prefix. */
2502 /* Option level SOL_... */
2504 /* Option number SO_... */
2506 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2507 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2508 } socket_options
[] =
2510 #ifdef SO_BINDTODEVICE
2511 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2514 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2517 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2520 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2523 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2526 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2529 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2532 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2534 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2537 /* Set option OPT to value VAL on socket S.
2539 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2540 Signals an error if setting a known option fails.
2544 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2547 const struct socket_options
*sopt
;
2552 name
= SSDATA (SYMBOL_NAME (opt
));
2553 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2554 if (strcmp (name
, sopt
->name
) == 0)
2557 switch (sopt
->opttype
)
2562 optval
= NILP (val
) ? 0 : 1;
2563 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2564 &optval
, sizeof (optval
));
2571 if (TYPE_RANGED_INTEGERP (int, val
))
2572 optval
= XINT (val
);
2574 error ("Bad option value for %s", name
);
2575 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2576 &optval
, sizeof (optval
));
2580 #ifdef SO_BINDTODEVICE
2583 char devname
[IFNAMSIZ
+ 1];
2585 /* This is broken, at least in the Linux 2.4 kernel.
2586 To unbind, the arg must be a zero integer, not the empty string.
2587 This should work on all systems. KFS. 2003-09-23. */
2588 memset (devname
, 0, sizeof devname
);
2591 char *arg
= SSDATA (val
);
2592 int len
= min (strlen (arg
), IFNAMSIZ
);
2593 memcpy (devname
, arg
, len
);
2595 else if (!NILP (val
))
2596 error ("Bad option value for %s", name
);
2597 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2606 struct linger linger
;
2609 linger
.l_linger
= 0;
2610 if (TYPE_RANGED_INTEGERP (int, val
))
2611 linger
.l_linger
= XINT (val
);
2613 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2614 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2615 &linger
, sizeof (linger
));
2626 int setsockopt_errno
= errno
;
2627 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2631 return (1 << sopt
->optbit
);
2635 DEFUN ("set-network-process-option",
2636 Fset_network_process_option
, Sset_network_process_option
,
2638 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2639 See `make-network-process' for a list of options and values.
2640 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2641 OPTION is not a supported option, return nil instead; otherwise return t.
2643 If PROCESS is a non-blocking network process that hasn't been fully
2644 set up yet, this function will block until socket setup has completed. */)
2645 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2648 struct Lisp_Process
*p
;
2650 CHECK_PROCESS (process
);
2651 p
= XPROCESS (process
);
2652 if (!NETCONN1_P (p
))
2653 error ("Process is not a network process");
2655 wait_for_socket_fds (process
, "set-network-process-option");
2659 error ("Process is not running");
2661 if (set_socket_option (s
, option
, value
))
2663 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2667 if (NILP (no_error
))
2668 error ("Unknown or unsupported option");
2674 DEFUN ("serial-process-configure",
2675 Fserial_process_configure
,
2676 Sserial_process_configure
,
2678 doc
: /* Configure speed, bytesize, etc. of a serial process.
2680 Arguments are specified as keyword/argument pairs. Attributes that
2681 are not given are re-initialized from the process's current
2682 configuration (available via the function `process-contact') or set to
2683 reasonable default values. The following arguments are defined:
2689 -- Any of these arguments can be given to identify the process that is
2690 to be configured. If none of these arguments is given, the current
2691 buffer's process is used.
2693 :speed SPEED -- SPEED is the speed of the serial port in bits per
2694 second, also called baud rate. Any value can be given for SPEED, but
2695 most serial ports work only at a few defined values between 1200 and
2696 115200, with 9600 being the most common value. If SPEED is nil, the
2697 serial port is not configured any further, i.e., all other arguments
2698 are ignored. This may be useful for special serial ports such as
2699 Bluetooth-to-serial converters which can only be configured through AT
2700 commands. A value of nil for SPEED can be used only when passed
2701 through `make-serial-process' or `serial-term'.
2703 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2704 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2706 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2707 `odd' (use odd parity), or the symbol `even' (use even parity). If
2708 PARITY is not given, no parity is used.
2710 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2711 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2712 is not given or nil, 1 stopbit is used.
2714 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2715 flowcontrol to be used, which is either nil (don't use flowcontrol),
2716 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2717 (use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2718 flowcontrol is used.
2720 `serial-process-configure' is called by `make-serial-process' for the
2721 initial configuration of the serial port.
2725 (serial-process-configure :process "/dev/ttyS0" :speed 1200)
2727 (serial-process-configure
2728 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2730 (serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2732 usage: (serial-process-configure &rest ARGS) */)
2733 (ptrdiff_t nargs
, Lisp_Object
*args
)
2735 struct Lisp_Process
*p
;
2736 Lisp_Object contact
= Qnil
;
2737 Lisp_Object proc
= Qnil
;
2739 contact
= Flist (nargs
, args
);
2741 proc
= Fplist_get (contact
, QCprocess
);
2743 proc
= Fplist_get (contact
, QCname
);
2745 proc
= Fplist_get (contact
, QCbuffer
);
2747 proc
= Fplist_get (contact
, QCport
);
2748 proc
= get_process (proc
);
2749 p
= XPROCESS (proc
);
2750 if (!EQ (p
->type
, Qserial
))
2751 error ("Not a serial process");
2753 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2756 serial_configure (p
, contact
);
2760 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2762 doc
: /* Create and return a serial port process.
2764 In Emacs, serial port connections are represented by process objects,
2765 so input and output work as for subprocesses, and `delete-process'
2766 closes a serial port connection. However, a serial process has no
2767 process id, it cannot be signaled, and the status codes are different
2768 from normal processes.
2770 `make-serial-process' creates a process and a buffer, on which you
2771 probably want to use `process-send-string'. Try \\[serial-term] for
2772 an interactive terminal. See below for examples.
2774 Arguments are specified as keyword/argument pairs. The following
2775 arguments are defined:
2777 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2778 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2779 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2780 the backslashes in strings).
2782 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2783 which this function calls.
2785 :name NAME -- NAME is the name of the process. If NAME is not given,
2786 the value of PORT is used.
2788 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2789 with the process. Process output goes at the end of that buffer,
2790 unless you specify an output stream or filter function to handle the
2791 output. If BUFFER is not given, the value of NAME is used.
2793 :coding CODING -- If CODING is a symbol, it specifies the coding
2794 system used for both reading and writing for this process. If CODING
2795 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2796 ENCODING is used for writing.
2798 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2799 the process is running. If BOOL is not given, query before exiting.
2801 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2802 In the stopped state, a serial process does not accept incoming data,
2803 but you can send outgoing data. The stopped state is cleared by
2804 `continue-process' and set by `stop-process'.
2806 :filter FILTER -- Install FILTER as the process filter.
2808 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2810 :plist PLIST -- Install PLIST as the initial plist of the process.
2816 -- This function calls `serial-process-configure' to handle these
2819 The original argument list, possibly modified by later configuration,
2820 is available via the function `process-contact'.
2824 (make-serial-process :port "/dev/ttyS0" :speed 9600)
2826 (make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2828 (make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2830 (make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2832 usage: (make-serial-process &rest ARGS) */)
2833 (ptrdiff_t nargs
, Lisp_Object
*args
)
2836 Lisp_Object proc
, contact
, port
;
2837 struct Lisp_Process
*p
;
2838 Lisp_Object name
, buffer
;
2839 Lisp_Object tem
, val
;
2840 ptrdiff_t specpdl_count
;
2845 contact
= Flist (nargs
, args
);
2847 port
= Fplist_get (contact
, QCport
);
2849 error ("No port specified");
2850 CHECK_STRING (port
);
2852 if (NILP (Fplist_member (contact
, QCspeed
)))
2853 error (":speed not specified");
2854 if (!NILP (Fplist_get (contact
, QCspeed
)))
2855 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2857 name
= Fplist_get (contact
, QCname
);
2860 CHECK_STRING (name
);
2861 proc
= make_process (name
);
2862 specpdl_count
= SPECPDL_INDEX ();
2863 record_unwind_protect (remove_process
, proc
);
2864 p
= XPROCESS (proc
);
2866 fd
= serial_open (port
);
2867 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2870 if (fd
> max_process_desc
)
2871 max_process_desc
= fd
;
2872 chan_process
[fd
] = proc
;
2874 buffer
= Fplist_get (contact
, QCbuffer
);
2877 buffer
= Fget_buffer_create (buffer
);
2878 pset_buffer (p
, buffer
);
2880 pset_childp (p
, contact
);
2881 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2882 pset_type (p
, Qserial
);
2883 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2884 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2886 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2887 p
->kill_without_query
= 1;
2888 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2889 pset_command (p
, Qt
);
2890 eassert (! p
->pty_flag
);
2892 if (!EQ (p
->command
, Qt
))
2894 FD_SET (fd
, &input_wait_mask
);
2895 FD_SET (fd
, &non_keyboard_wait_mask
);
2898 if (BUFFERP (buffer
))
2900 set_marker_both (p
->mark
, buffer
,
2901 BUF_ZV (XBUFFER (buffer
)),
2902 BUF_ZV_BYTE (XBUFFER (buffer
)));
2905 tem
= Fplist_member (contact
, QCcoding
);
2906 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2912 val
= XCAR (XCDR (tem
));
2916 else if (!NILP (Vcoding_system_for_read
))
2917 val
= Vcoding_system_for_read
;
2918 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2919 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2921 pset_decode_coding_system (p
, val
);
2926 val
= XCAR (XCDR (tem
));
2930 else if (!NILP (Vcoding_system_for_write
))
2931 val
= Vcoding_system_for_write
;
2932 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2933 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2935 pset_encode_coding_system (p
, val
);
2937 setup_process_coding_systems (proc
);
2938 pset_decoding_buf (p
, empty_unibyte_string
);
2939 p
->decoding_carryover
= 0;
2940 pset_encoding_buf (p
, empty_unibyte_string
);
2941 p
->inherit_coding_system_flag
2942 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2944 Fserial_process_configure (nargs
, args
);
2946 specpdl_ptr
= specpdl
+ specpdl_count
;
2952 set_network_socket_coding_system (Lisp_Object proc
, Lisp_Object host
,
2953 Lisp_Object service
, Lisp_Object name
)
2956 struct Lisp_Process
*p
= XPROCESS (proc
);
2957 Lisp_Object contact
= p
->childp
;
2958 Lisp_Object coding_systems
= Qt
;
2961 tem
= Fplist_member (contact
, QCcoding
);
2962 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2963 tem
= Qnil
; /* No error message (too late!). */
2965 /* Setup coding systems for communicating with the network stream. */
2966 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2970 val
= XCAR (XCDR (tem
));
2974 else if (!NILP (Vcoding_system_for_read
))
2975 val
= Vcoding_system_for_read
;
2976 else if ((!NILP (p
->buffer
)
2977 && NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
2978 || (NILP (p
->buffer
)
2979 && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2980 /* We dare not decode end-of-line format by setting VAL to
2981 Qraw_text, because the existing Emacs Lisp libraries
2982 assume that they receive bare code including a sequence of
2987 if (NILP (host
) || NILP (service
))
2988 coding_systems
= Qnil
;
2990 coding_systems
= CALLN (Ffind_operation_coding_system
,
2991 Qopen_network_stream
, name
, p
->buffer
,
2993 if (CONSP (coding_systems
))
2994 val
= XCAR (coding_systems
);
2995 else if (CONSP (Vdefault_process_coding_system
))
2996 val
= XCAR (Vdefault_process_coding_system
);
3000 pset_decode_coding_system (p
, val
);
3004 val
= XCAR (XCDR (tem
));
3008 else if (!NILP (Vcoding_system_for_write
))
3009 val
= Vcoding_system_for_write
;
3010 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3014 if (EQ (coding_systems
, Qt
))
3016 if (NILP (host
) || NILP (service
))
3017 coding_systems
= Qnil
;
3019 coding_systems
= CALLN (Ffind_operation_coding_system
,
3020 Qopen_network_stream
, name
, p
->buffer
,
3023 if (CONSP (coding_systems
))
3024 val
= XCDR (coding_systems
);
3025 else if (CONSP (Vdefault_process_coding_system
))
3026 val
= XCDR (Vdefault_process_coding_system
);
3030 pset_encode_coding_system (p
, val
);
3032 pset_decoding_buf (p
, empty_unibyte_string
);
3033 p
->decoding_carryover
= 0;
3034 pset_encoding_buf (p
, empty_unibyte_string
);
3036 p
->inherit_coding_system_flag
3037 = !(!NILP (tem
) || NILP (p
->buffer
) || !inherit_process_coding_system
);
3042 finish_after_tls_connection (Lisp_Object proc
)
3044 struct Lisp_Process
*p
= XPROCESS (proc
);
3045 Lisp_Object contact
= p
->childp
;
3046 Lisp_Object result
= Qt
;
3048 if (!NILP (Ffboundp (Qnsm_verify_connection
)))
3049 result
= call3 (Qnsm_verify_connection
,
3051 Fplist_get (contact
, QChost
),
3052 Fplist_get (contact
, QCservice
));
3056 pset_status (p
, list2 (Qfailed
,
3057 build_string ("The Network Security Manager stopped the connections")));
3058 deactivate_process (proc
);
3062 /* If we cleared the connection wait mask before we did
3063 the TLS setup, then we have to say that the process
3064 is finally "open" here. */
3065 if (! FD_ISSET (p
->outfd
, &connect_wait_mask
))
3067 pset_status (p
, Qrun
);
3068 /* Execute the sentinel here. If we had relied on
3069 status_notify to do it later, it will read input
3070 from the process before calling the sentinel. */
3071 exec_sentinel (proc
, build_string ("open\n"));
3078 connect_network_socket (Lisp_Object proc
, Lisp_Object ip_addresses
)
3080 ptrdiff_t count
= SPECPDL_INDEX ();
3082 int s
= -1, outch
, inch
;
3084 Lisp_Object ip_address
;
3086 struct sockaddr
*sa
= NULL
;
3089 struct Lisp_Process
*p
= XPROCESS (proc
);
3090 Lisp_Object contact
= p
->childp
;
3093 /* Do this in case we never enter the while-loop below. */
3094 count1
= SPECPDL_INDEX ();
3097 while (!NILP (ip_addresses
))
3099 ip_address
= XCAR (ip_addresses
);
3100 ip_addresses
= XCDR (ip_addresses
);
3106 addrlen
= get_lisp_to_sockaddr_size (ip_address
, &family
);
3109 sa
= xmalloc (addrlen
);
3110 conv_lisp_to_sockaddr (family
, ip_address
, sa
, addrlen
);
3112 s
= socket (family
, p
->socktype
| SOCK_CLOEXEC
, p
->ai_protocol
);
3119 #ifdef DATAGRAM_SOCKETS
3120 if (!p
->is_server
&& p
->socktype
== SOCK_DGRAM
)
3122 #endif /* DATAGRAM_SOCKETS */
3124 #ifdef NON_BLOCKING_CONNECT
3125 if (p
->is_non_blocking_client
)
3127 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3138 /* Make us close S if quit. */
3139 record_unwind_protect_int (close_file_unwind
, s
);
3141 /* Parse network options in the arg list. We simply ignore anything
3142 which isn't a known option (including other keywords). An error
3143 is signaled if setting a known option fails. */
3145 Lisp_Object params
= contact
, key
, val
;
3147 while (!NILP (params
))
3149 key
= XCAR (params
);
3150 params
= XCDR (params
);
3151 val
= XCAR (params
);
3152 params
= XCDR (params
);
3153 optbits
|= set_socket_option (s
, key
, val
);
3159 /* Configure as a server socket. */
3161 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3162 explicit :reuseaddr key to override this. */
3163 #ifdef HAVE_LOCAL_SOCKETS
3164 if (family
!= AF_LOCAL
)
3166 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3169 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3170 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3173 if (bind (s
, sa
, addrlen
))
3174 report_file_error ("Cannot bind server socket", Qnil
);
3176 #ifdef HAVE_GETSOCKNAME
3179 struct sockaddr_in sa1
;
3180 socklen_t len1
= sizeof (sa1
);
3181 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3183 Lisp_Object service
;
3184 service
= make_number (ntohs (sa1
.sin_port
));
3185 contact
= Fplist_put (contact
, QCservice
, service
);
3186 /* Save the port number so that we can stash it in
3187 the process object later. */
3188 ((struct sockaddr_in
*)sa
)->sin_port
= sa1
.sin_port
;
3193 if (p
->socktype
!= SOCK_DGRAM
&& listen (s
, p
->backlog
))
3194 report_file_error ("Cannot listen on server socket", Qnil
);
3202 ret
= connect (s
, sa
, addrlen
);
3205 if (ret
== 0 || xerrno
== EISCONN
)
3207 /* The unwind-protect will be discarded afterwards.
3208 Likewise for immediate_quit. */
3212 #ifdef NON_BLOCKING_CONNECT
3214 if (p
->is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3218 if (p
->is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3225 if (xerrno
== EINTR
)
3227 /* Unlike most other syscalls connect() cannot be called
3228 again. (That would return EALREADY.) The proper way to
3229 wait for completion is pselect(). */
3237 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3243 report_file_error ("Failed select", Qnil
);
3247 len
= sizeof xerrno
;
3248 eassert (FD_ISSET (s
, &fdset
));
3249 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3250 report_file_error ("Failed getsockopt", Qnil
);
3252 report_file_errno ("Failed connect", Qnil
, xerrno
);
3255 #endif /* !WINDOWSNT */
3259 /* Discard the unwind protect closing S. */
3260 specpdl_ptr
= specpdl
+ count1
;
3265 if (xerrno
== EINTR
)
3272 #ifdef DATAGRAM_SOCKETS
3273 if (p
->socktype
== SOCK_DGRAM
)
3275 if (datagram_address
[s
].sa
)
3278 datagram_address
[s
].sa
= xmalloc (addrlen
);
3279 datagram_address
[s
].len
= addrlen
;
3283 memset (datagram_address
[s
].sa
, 0, addrlen
);
3284 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3287 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3288 if (rlen
!= 0 && rfamily
== family
3290 conv_lisp_to_sockaddr (rfamily
, remote
,
3291 datagram_address
[s
].sa
, rlen
);
3295 memcpy (datagram_address
[s
].sa
, sa
, addrlen
);
3299 contact
= Fplist_put (contact
, p
->is_server
? QClocal
: QCremote
,
3300 conv_sockaddr_to_lisp (sa
, addrlen
));
3301 #ifdef HAVE_GETSOCKNAME
3304 struct sockaddr_in sa1
;
3305 socklen_t len1
= sizeof (sa1
);
3306 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3307 contact
= Fplist_put (contact
, QClocal
,
3308 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3317 /* If non-blocking got this far - and failed - assume non-blocking is
3318 not supported after all. This is probably a wrong assumption, but
3319 the normal blocking calls to open-network-stream handles this error
3321 if (p
->is_non_blocking_client
)
3324 report_file_errno ((p
->is_server
3325 ? "make server process failed"
3326 : "make client process failed"),
3333 chan_process
[inch
] = proc
;
3335 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3337 p
= XPROCESS (proc
);
3338 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3342 /* Discard the unwind protect for closing S, if any. */
3343 specpdl_ptr
= specpdl
+ count1
;
3345 /* Unwind bind_polling_period and request_sigio. */
3346 unbind_to (count
, Qnil
);
3348 if (p
->is_server
&& p
->socktype
!= SOCK_DGRAM
)
3349 pset_status (p
, Qlisten
);
3351 /* Make the process marker point into the process buffer (if any). */
3352 if (BUFFERP (p
->buffer
))
3353 set_marker_both (p
->mark
, p
->buffer
,
3354 BUF_ZV (XBUFFER (p
->buffer
)),
3355 BUF_ZV_BYTE (XBUFFER (p
->buffer
)));
3357 #ifdef NON_BLOCKING_CONNECT
3358 if (p
->is_non_blocking_client
)
3360 /* We may get here if connect did succeed immediately. However,
3361 in that case, we still need to signal this like a non-blocking
3363 pset_status (p
, Qconnect
);
3364 if (!FD_ISSET (inch
, &connect_wait_mask
))
3366 FD_SET (inch
, &connect_wait_mask
);
3367 FD_SET (inch
, &write_mask
);
3368 num_pending_connects
++;
3373 /* A server may have a client filter setting of Qt, but it must
3374 still listen for incoming connects unless it is stopped. */
3375 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3376 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3378 FD_SET (inch
, &input_wait_mask
);
3379 FD_SET (inch
, &non_keyboard_wait_mask
);
3382 if (inch
> max_process_desc
)
3383 max_process_desc
= inch
;
3385 /* Set up the masks based on the process filter. */
3386 set_process_filter_masks (p
);
3388 setup_process_coding_systems (proc
);
3391 /* Continue the asynchronous connection. */
3392 if (!NILP (p
->gnutls_boot_parameters
))
3394 Lisp_Object boot
, params
= p
->gnutls_boot_parameters
;
3396 boot
= Fgnutls_boot (proc
, XCAR (params
), XCDR (params
));
3397 p
->gnutls_boot_parameters
= Qnil
;
3399 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
3400 /* Run sentinels, etc. */
3401 finish_after_tls_connection (proc
);
3402 else if (p
->gnutls_initstage
!= GNUTLS_STAGE_HANDSHAKE_TRIED
)
3404 deactivate_process (proc
);
3406 pset_status (p
, list2 (Qfailed
,
3407 build_string ("TLS negotiation failed")));
3409 pset_status (p
, list2 (Qfailed
, boot
));
3416 #ifndef HAVE_GETADDRINFO
3418 conv_numerical_to_lisp (unsigned char *number
, int length
, int port
)
3420 Lisp_Object address
= Fmake_vector (make_number (length
+ 1), Qnil
);
3421 struct Lisp_Vector
*p
= XVECTOR (address
);
3423 p
->contents
[length
] = make_number (port
);
3424 for (int i
= 0; i
< length
; i
++)
3425 p
->contents
[i
] = make_number (number
[i
]);
3431 /* Return true if STRING consists only of numerical characters. */
3433 string_integer_p (Lisp_Object string
)
3435 char *s
= SSDATA (string
), c
;
3437 if (c
< '0' || c
> '9')
3442 /* Create a network stream/datagram client/server process. Treated
3443 exactly like a normal process when reading and writing. Primary
3444 differences are in status display and process deletion. A network
3445 connection has no PID; you cannot signal it. All you can do is
3446 stop/continue it and deactivate/close it via delete-process. */
3448 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
3450 doc
: /* Create and return a network server or client process.
3452 In Emacs, network connections are represented by process objects, so
3453 input and output work as for subprocesses and `delete-process' closes
3454 a network connection. However, a network process has no process id,
3455 it cannot be signaled, and the status codes are different from normal
3458 Arguments are specified as keyword/argument pairs. The following
3459 arguments are defined:
3461 :name NAME -- NAME is name for process. It is modified if necessary
3464 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3465 with the process. Process output goes at end of that buffer, unless
3466 you specify an output stream or filter function to handle the output.
3467 BUFFER may be also nil, meaning that this process is not associated
3470 :host HOST -- HOST is name of the host to connect to, or its IP
3471 address. The symbol `local' specifies the local host. If specified
3472 for a server process, it must be a valid name or address for the local
3473 host, and only clients connecting to that address will be accepted.
3475 :service SERVICE -- SERVICE is name of the service desired, or an
3476 integer specifying a port number to connect to. If SERVICE is t,
3477 a random port number is selected for the server. (If Emacs was
3478 compiled with getaddrinfo, a port number can also be specified as a
3479 string, e.g. "80", as well as an integer. This is not portable.)
3481 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3482 stream type connection, `datagram' creates a datagram type connection,
3483 `seqpacket' creates a reliable datagram connection.
3485 :family FAMILY -- FAMILY is the address (and protocol) family for the
3486 service specified by HOST and SERVICE. The default (nil) is to use
3487 whatever address family (IPv4 or IPv6) that is defined for the host
3488 and port number specified by HOST and SERVICE. Other address families
3490 local -- for a local (i.e. UNIX) address specified by SERVICE.
3491 ipv4 -- use IPv4 address family only.
3492 ipv6 -- use IPv6 address family only.
3494 :local ADDRESS -- ADDRESS is the local address used for the connection.
3495 This parameter is ignored when opening a client process. When specified
3496 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3498 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3499 connection. This parameter is ignored when opening a stream server
3500 process. For a datagram server process, it specifies the initial
3501 setting of the remote datagram address. When specified for a client
3502 process, the FAMILY, HOST, and SERVICE args are ignored.
3504 The format of ADDRESS depends on the address family:
3505 - An IPv4 address is represented as an vector of integers [A B C D P]
3506 corresponding to numeric IP address A.B.C.D and port number P.
3507 - A local address is represented as a string with the address in the
3508 local address space.
3509 - An "unsupported family" address is represented by a cons (F . AV)
3510 where F is the family number and AV is a vector containing the socket
3511 address data with one element per address data byte. Do not rely on
3512 this format in portable code, as it may depend on implementation
3513 defined constants, data sizes, and data structure alignment.
3515 :coding CODING -- If CODING is a symbol, it specifies the coding
3516 system used for both reading and writing for this process. If CODING
3517 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3518 ENCODING is used for writing.
3520 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3521 process, return without waiting for the connection to complete;
3522 instead, the sentinel function will be called with second arg matching
3523 "open" (if successful) or "failed" when the connect completes.
3524 Default is to use a blocking connect (i.e. wait) for stream type
3527 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3528 running when Emacs is exited.
3530 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3531 In the stopped state, a server process does not accept new
3532 connections, and a client process does not handle incoming traffic.
3533 The stopped state is cleared by `continue-process' and set by
3536 :filter FILTER -- Install FILTER as the process filter.
3538 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3539 process filter are multibyte, otherwise they are unibyte.
3540 If this keyword is not specified, the strings are multibyte if
3541 the default value of `enable-multibyte-characters' is non-nil.
3543 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3545 :log LOG -- Install LOG as the server process log function. This
3546 function is called when the server accepts a network connection from a
3547 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3548 is the server process, CLIENT is the new process for the connection,
3549 and MESSAGE is a string.
3551 :plist PLIST -- Install PLIST as the new process's initial plist.
3553 :tls-parameters LIST -- is a list that should be supplied if you're
3554 opening a TLS connection. The first element is the TLS type (either
3555 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3556 be a keyword list accepted by gnutls-boot (as returned by
3557 `gnutls-boot-parameters').
3559 :server QLEN -- if QLEN is non-nil, create a server process for the
3560 specified FAMILY, SERVICE, and connection type (stream or datagram).
3561 If QLEN is an integer, it is used as the max. length of the server's
3562 pending connection queue (also known as the backlog); the default
3563 queue length is 5. Default is to create a client process.
3565 The following network options can be specified for this connection:
3567 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3568 :dontroute BOOL -- Only send to directly connected hosts.
3569 :keepalive BOOL -- Send keep-alive messages on network stream.
3570 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3571 :oobinline BOOL -- Place out-of-band data in receive data stream.
3572 :priority INT -- Set protocol defined priority for sent packets.
3573 :reuseaddr BOOL -- Allow reusing a recently used local address
3574 (this is allowed by default for a server process).
3575 :bindtodevice NAME -- bind to interface NAME. Using this may require
3576 special privileges on some systems.
3578 Consult the relevant system programmer's manual pages for more
3579 information on using these options.
3582 A server process will listen for and accept connections from clients.
3583 When a client connection is accepted, a new network process is created
3584 for the connection with the following parameters:
3586 - The client's process name is constructed by concatenating the server
3587 process's NAME and a client identification string.
3588 - If the FILTER argument is non-nil, the client process will not get a
3589 separate process buffer; otherwise, the client's process buffer is a newly
3590 created buffer named after the server process's BUFFER name or process
3591 NAME concatenated with the client identification string.
3592 - The connection type and the process filter and sentinel parameters are
3593 inherited from the server process's TYPE, FILTER and SENTINEL.
3594 - The client process's contact info is set according to the client's
3595 addressing information (typically an IP address and a port number).
3596 - The client process's plist is initialized from the server's plist.
3598 Notice that the FILTER and SENTINEL args are never used directly by
3599 the server process. Also, the BUFFER argument is not used directly by
3600 the server process, but via the optional :log function, accepted (and
3601 failed) connections may be logged in the server process's buffer.
3603 The original argument list, modified with the actual connection
3604 information, is available via the `process-contact' function.
3606 usage: (make-network-process &rest ARGS) */)
3607 (ptrdiff_t nargs
, Lisp_Object
*args
)
3610 Lisp_Object contact
;
3611 struct Lisp_Process
*p
;
3612 #if defined HAVE_GETADDRINFO || defined HAVE_GETADDRINFO_A
3613 const char *portstring
;
3614 ptrdiff_t portstringlen ATTRIBUTE_UNUSED
;
3615 char portbuf
[INT_BUFSIZE_BOUND (EMACS_INT
)];
3617 #ifdef HAVE_LOCAL_SOCKETS
3618 struct sockaddr_un address_un
;
3622 Lisp_Object name
, buffer
, host
, service
, address
;
3623 Lisp_Object filter
, sentinel
;
3624 Lisp_Object ip_addresses
= Qnil
;
3627 int ai_protocol
= 0;
3628 #ifdef HAVE_GETADDRINFO_A
3629 struct gaicb
*dns_request
= NULL
;
3631 ptrdiff_t count
= SPECPDL_INDEX ();
3636 /* Save arguments for process-contact and clone-process. */
3637 contact
= Flist (nargs
, args
);
3640 /* Ensure socket support is loaded if available. */
3641 init_winsock (TRUE
);
3644 /* :type TYPE (nil: stream, datagram */
3645 tem
= Fplist_get (contact
, QCtype
);
3647 socktype
= SOCK_STREAM
;
3648 #ifdef DATAGRAM_SOCKETS
3649 else if (EQ (tem
, Qdatagram
))
3650 socktype
= SOCK_DGRAM
;
3652 #ifdef HAVE_SEQPACKET
3653 else if (EQ (tem
, Qseqpacket
))
3654 socktype
= SOCK_SEQPACKET
;
3657 error ("Unsupported connection type");
3659 name
= Fplist_get (contact
, QCname
);
3660 buffer
= Fplist_get (contact
, QCbuffer
);
3661 filter
= Fplist_get (contact
, QCfilter
);
3662 sentinel
= Fplist_get (contact
, QCsentinel
);
3664 CHECK_STRING (name
);
3666 /* :local ADDRESS or :remote ADDRESS */
3667 tem
= Fplist_get (contact
, QCserver
);
3669 address
= Fplist_get (contact
, QCremote
);
3671 address
= Fplist_get (contact
, QClocal
);
3672 if (!NILP (address
))
3674 host
= service
= Qnil
;
3676 if (!get_lisp_to_sockaddr_size (address
, &family
))
3677 error ("Malformed :address");
3679 ip_addresses
= list1 (address
);
3683 /* :family FAMILY -- nil (for Inet), local, or integer. */
3684 tem
= Fplist_get (contact
, QCfamily
);
3687 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3693 #ifdef HAVE_LOCAL_SOCKETS
3694 else if (EQ (tem
, Qlocal
))
3698 else if (EQ (tem
, Qipv6
))
3701 else if (EQ (tem
, Qipv4
))
3703 else if (TYPE_RANGED_INTEGERP (int, tem
))
3704 family
= XINT (tem
);
3706 error ("Unknown address family");
3708 /* :service SERVICE -- string, integer (port number), or t (random port). */
3709 service
= Fplist_get (contact
, QCservice
);
3711 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3712 host
= Fplist_get (contact
, QChost
);
3715 /* The "connection" function gets it bind info from the address we're
3716 given, so use this dummy address if nothing is specified. */
3717 #ifdef HAVE_LOCAL_SOCKETS
3718 if (family
!= AF_LOCAL
)
3720 host
= build_string ("127.0.0.1");
3724 if (EQ (host
, Qlocal
))
3725 /* Depending on setup, "localhost" may map to different IPv4 and/or
3726 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3727 host
= build_string ("127.0.0.1");
3728 CHECK_STRING (host
);
3731 #ifdef HAVE_LOCAL_SOCKETS
3732 if (family
== AF_LOCAL
)
3736 message (":family local ignores the :host property");
3737 contact
= Fplist_put (contact
, QChost
, Qnil
);
3740 CHECK_STRING (service
);
3741 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3742 error ("Service name too long");
3743 ip_addresses
= list1 (service
);
3748 /* Slow down polling to every ten seconds.
3749 Some kernels have a bug which causes retrying connect to fail
3750 after a connect. Polling can interfere with gethostbyname too. */
3751 #ifdef POLL_FOR_INPUT
3752 if (socktype
!= SOCK_DGRAM
)
3754 record_unwind_protect_void (run_all_atimers
);
3755 bind_polling_period (10);
3759 #if defined HAVE_GETADDRINFO || defined HAVE_GETADDRINFO_A
3762 /* SERVICE can either be a string or int.
3763 Convert to a C string for later use by getaddrinfo. */
3764 if (EQ (service
, Qt
))
3769 else if (INTEGERP (service
))
3771 portstring
= portbuf
;
3772 portstringlen
= sprintf (portbuf
, "%"pI
"d", XINT (service
));
3776 CHECK_STRING (service
);
3777 portstring
= SSDATA (service
);
3778 portstringlen
= SBYTES (service
);
3783 #ifdef HAVE_GETADDRINFO_A
3784 if (!NILP (host
) && !NILP (Fplist_get (contact
, QCnowait
)))
3786 ptrdiff_t hostlen
= SBYTES (host
);
3790 struct addrinfo hints
;
3791 char str
[FLEXIBLE_ARRAY_MEMBER
];
3792 } *req
= xmalloc (offsetof (struct req
, str
)
3793 + hostlen
+ 1 + portstringlen
+ 1);
3794 dns_request
= &req
->gaicb
;
3795 dns_request
->ar_name
= req
->str
;
3796 dns_request
->ar_service
= req
->str
+ hostlen
+ 1;
3797 dns_request
->ar_request
= &req
->hints
;
3798 dns_request
->ar_result
= NULL
;
3799 memset (&req
->hints
, 0, sizeof req
->hints
);
3800 req
->hints
.ai_family
= family
;
3801 req
->hints
.ai_socktype
= socktype
;
3802 strcpy (req
->str
, SSDATA (host
));
3803 strcpy (req
->str
+ hostlen
+ 1, portstring
);
3805 int ret
= getaddrinfo_a (GAI_NOWAIT
, &dns_request
, 1, NULL
);
3807 error ("%s/%s getaddrinfo_a error %d", SSDATA (host
), portstring
, ret
);
3811 #endif /* HAVE_GETADDRINFO_A */
3813 #ifdef HAVE_GETADDRINFO
3814 /* If we have a host, use getaddrinfo to resolve both host and service.
3815 Otherwise, use getservbyname to lookup the service. */
3819 struct addrinfo
*res
, *lres
;
3825 #ifdef HAVE_RES_INIT
3829 struct addrinfo hints
;
3830 memset (&hints
, 0, sizeof hints
);
3831 hints
.ai_family
= family
;
3832 hints
.ai_socktype
= socktype
;
3834 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3836 #ifdef HAVE_GAI_STRERROR
3837 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3839 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3843 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3845 ip_addresses
= Fcons (conv_sockaddr_to_lisp
3846 (lres
->ai_addr
, lres
->ai_addrlen
),
3848 ai_protocol
= lres
->ai_protocol
;
3851 ip_addresses
= Fnreverse (ip_addresses
);
3857 #endif /* HAVE_GETADDRINFO */
3859 /* We end up here if getaddrinfo is not defined, or in case no hostname
3860 has been specified (e.g. for a local server process). */
3862 if (EQ (service
, Qt
))
3864 else if (INTEGERP (service
))
3865 port
= (unsigned short) XINT (service
);
3866 /* Allow the service to be a string containing the port number,
3867 because that's allowed if you have getaddrbyname. */
3868 else if (string_integer_p (service
))
3869 port
= strtol (SSDATA (service
), NULL
, 10);
3872 struct servent
*svc_info
;
3873 CHECK_STRING (service
);
3874 svc_info
= getservbyname (SSDATA (service
),
3875 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3877 error ("Unknown service: %s", SDATA (service
));
3878 port
= ntohs (svc_info
->s_port
);
3881 #ifndef HAVE_GETADDRINFO
3884 struct hostent
*host_info_ptr
;
3885 unsigned char *addr
;
3888 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3889 as it may `hang' Emacs for a very long time. */
3893 #ifdef HAVE_RES_INIT
3897 host_info_ptr
= gethostbyname ((const char *) SDATA (host
));
3902 addr
= (unsigned char *) host_info_ptr
->h_addr
;
3903 addrlen
= host_info_ptr
->h_length
;
3906 /* Attempt to interpret host as numeric inet address. This
3907 only works for IPv4 addresses. */
3909 unsigned long numeric_addr
= inet_addr (SSDATA (host
));
3911 if (numeric_addr
== -1)
3912 error ("Unknown host \"%s\"", SDATA (host
));
3914 addr
= (unsigned char *) &numeric_addr
;
3918 ip_addresses
= list1 (conv_numerical_to_lisp (addr
, addrlen
, port
));
3920 #endif /* not HAVE_GETADDRINFO */
3925 buffer
= Fget_buffer_create (buffer
);
3926 proc
= make_process (name
);
3927 p
= XPROCESS (proc
);
3928 pset_childp (p
, contact
);
3929 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3930 pset_type (p
, Qnetwork
);
3932 pset_buffer (p
, buffer
);
3933 pset_sentinel (p
, sentinel
);
3934 pset_filter (p
, filter
);
3935 pset_log (p
, Fplist_get (contact
, QClog
));
3936 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3937 p
->kill_without_query
= 1;
3938 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3939 pset_command (p
, Qt
);
3942 p
->is_non_blocking_client
= 0;
3945 p
->socktype
= socktype
;
3946 p
->ai_protocol
= ai_protocol
;
3947 #ifdef HAVE_GETADDRINFO_A
3948 p
->dns_request
= NULL
;
3951 tem
= Fplist_get (contact
, QCtls_parameters
);
3953 p
->gnutls_boot_parameters
= tem
;
3956 set_network_socket_coding_system (proc
, service
, host
, name
);
3958 unbind_to (count
, Qnil
);
3961 tem
= Fplist_get (contact
, QCserver
);
3964 /* Don't support network sockets when non-blocking mode is
3965 not available, since a blocked Emacs is not useful. */
3967 if (TYPE_RANGED_INTEGERP (int, tem
))
3968 p
->backlog
= XINT (tem
);
3972 if (!p
->is_server
&& socktype
!= SOCK_DGRAM
3973 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
3975 #ifndef NON_BLOCKING_CONNECT
3976 error ("Non-blocking connect not supported");
3978 p
->is_non_blocking_client
= 1;
3982 #ifdef HAVE_GETADDRINFO_A
3983 /* If we're doing async address resolution, the list of addresses
3984 here will be nil, so we postpone connecting to the server. */
3985 if (!p
->is_server
&& NILP (ip_addresses
))
3987 p
->dns_request
= dns_request
;
3988 p
->status
= Qconnect
;
3992 connect_network_socket (proc
, ip_addresses
);
3994 #else /* HAVE_GETADDRINFO_A */
3995 connect_network_socket (proc
, ip_addresses
);
4002 #ifdef HAVE_NET_IF_H
4006 network_interface_list (void)
4008 struct ifconf ifconf
;
4009 struct ifreq
*ifreq
;
4011 ptrdiff_t buf_size
= 512;
4016 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4019 count
= SPECPDL_INDEX ();
4020 record_unwind_protect_int (close_file_unwind
, s
);
4024 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
4025 ifconf
.ifc_buf
= buf
;
4026 ifconf
.ifc_len
= buf_size
;
4027 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
4034 while (ifconf
.ifc_len
== buf_size
);
4036 res
= unbind_to (count
, Qnil
);
4037 ifreq
= ifconf
.ifc_req
;
4038 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
4040 struct ifreq
*ifq
= ifreq
;
4041 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4042 #define SIZEOF_IFREQ(sif) \
4043 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4044 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4046 int len
= SIZEOF_IFREQ (ifq
);
4048 int len
= sizeof (*ifreq
);
4050 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
4051 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
4053 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
4056 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
4057 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
4058 res
= Fcons (Fcons (build_string (namebuf
),
4059 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
4060 sizeof (struct sockaddr
))),
4067 #endif /* SIOCGIFCONF */
4069 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4073 const char *flag_sym
;
4076 static const struct ifflag_def ifflag_table
[] = {
4080 #ifdef IFF_BROADCAST
4081 { IFF_BROADCAST
, "broadcast" },
4084 { IFF_DEBUG
, "debug" },
4087 { IFF_LOOPBACK
, "loopback" },
4089 #ifdef IFF_POINTOPOINT
4090 { IFF_POINTOPOINT
, "pointopoint" },
4093 { IFF_RUNNING
, "running" },
4096 { IFF_NOARP
, "noarp" },
4099 { IFF_PROMISC
, "promisc" },
4101 #ifdef IFF_NOTRAILERS
4102 #ifdef NS_IMPL_COCOA
4103 /* Really means smart, notrailers is obsolete. */
4104 { IFF_NOTRAILERS
, "smart" },
4106 { IFF_NOTRAILERS
, "notrailers" },
4110 { IFF_ALLMULTI
, "allmulti" },
4113 { IFF_MASTER
, "master" },
4116 { IFF_SLAVE
, "slave" },
4118 #ifdef IFF_MULTICAST
4119 { IFF_MULTICAST
, "multicast" },
4122 { IFF_PORTSEL
, "portsel" },
4124 #ifdef IFF_AUTOMEDIA
4125 { IFF_AUTOMEDIA
, "automedia" },
4128 { IFF_DYNAMIC
, "dynamic" },
4131 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
4134 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4137 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
4140 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
4143 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
4149 network_interface_info (Lisp_Object ifname
)
4152 Lisp_Object res
= Qnil
;
4157 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4158 && defined HAVE_GETIFADDRS && defined LLADDR)
4159 struct ifaddrs
*ifap
;
4162 CHECK_STRING (ifname
);
4164 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
4165 error ("interface name too long");
4166 lispstpcpy (rq
.ifr_name
, ifname
);
4168 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
4171 count
= SPECPDL_INDEX ();
4172 record_unwind_protect_int (close_file_unwind
, s
);
4175 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4176 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
4178 int flags
= rq
.ifr_flags
;
4179 const struct ifflag_def
*fp
;
4182 /* If flags is smaller than int (i.e. short) it may have the high bit set
4183 due to IFF_MULTICAST. In that case, sign extending it into
4185 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
4186 flags
= (unsigned short) rq
.ifr_flags
;
4189 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
4191 if (flags
& fp
->flag_bit
)
4193 elt
= Fcons (intern (fp
->flag_sym
), elt
);
4194 flags
-= fp
->flag_bit
;
4197 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
4201 elt
= Fcons (make_number (fnum
), elt
);
4206 res
= Fcons (elt
, res
);
4209 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4210 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
4212 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4213 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4217 for (n
= 0; n
< 6; n
++)
4218 p
->contents
[n
] = make_number (((unsigned char *)
4219 &rq
.ifr_hwaddr
.sa_data
[0])
4221 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
4223 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4224 if (getifaddrs (&ifap
) != -1)
4226 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
4227 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
4230 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
4232 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
4233 unsigned char linkaddr
[6];
4236 if (it
->ifa_addr
->sa_family
!= AF_LINK
4237 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
4238 || sdl
->sdl_alen
!= 6)
4241 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
4242 for (n
= 0; n
< 6; n
++)
4243 p
->contents
[n
] = make_number (linkaddr
[n
]);
4245 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
4249 #ifdef HAVE_FREEIFADDRS
4253 #endif /* HAVE_GETIFADDRS && LLADDR */
4255 res
= Fcons (elt
, res
);
4258 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4259 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
4262 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4263 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
4265 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4269 res
= Fcons (elt
, res
);
4272 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4273 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
4276 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
4279 res
= Fcons (elt
, res
);
4282 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4283 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
4286 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
4289 res
= Fcons (elt
, res
);
4291 return unbind_to (count
, any
? res
: Qnil
);
4293 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4294 #endif /* defined (HAVE_NET_IF_H) */
4296 DEFUN ("network-interface-list", Fnetwork_interface_list
,
4297 Snetwork_interface_list
, 0, 0, 0,
4298 doc
: /* Return an alist of all network interfaces and their network address.
4299 Each element is a cons, the car of which is a string containing the
4300 interface name, and the cdr is the network address in internal
4301 format; see the description of ADDRESS in `make-network-process'.
4303 If the information is not available, return nil. */)
4306 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4307 return network_interface_list ();
4313 DEFUN ("network-interface-info", Fnetwork_interface_info
,
4314 Snetwork_interface_info
, 1, 1, 0,
4315 doc
: /* Return information about network interface named IFNAME.
4316 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4317 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4318 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4319 FLAGS is the current flags of the interface.
4321 Data that is unavailable is returned as nil. */)
4322 (Lisp_Object ifname
)
4324 #if ((defined HAVE_NET_IF_H \
4325 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4326 || defined SIOCGIFFLAGS)) \
4327 || defined WINDOWSNT)
4328 return network_interface_info (ifname
);
4334 /* If program file NAME starts with /: for quoting a magic
4335 name, remove that, preserving the multibyteness of NAME. */
4338 remove_slash_colon (Lisp_Object name
)
4341 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
4342 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
4343 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
4347 /* Turn off input and output for process PROC. */
4350 deactivate_process (Lisp_Object proc
)
4353 struct Lisp_Process
*p
= XPROCESS (proc
);
4357 /* Delete GnuTLS structures in PROC, if any. */
4358 emacs_gnutls_deinit (proc
);
4359 #endif /* HAVE_GNUTLS */
4361 if (p
->read_output_delay
> 0)
4363 if (--process_output_delay_count
< 0)
4364 process_output_delay_count
= 0;
4365 p
->read_output_delay
= 0;
4366 p
->read_output_skip
= 0;
4369 /* Beware SIGCHLD hereabouts. */
4371 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4372 close_process_fd (&p
->open_fd
[i
]);
4374 inchannel
= p
->infd
;
4379 #ifdef DATAGRAM_SOCKETS
4380 if (DATAGRAM_CHAN_P (inchannel
))
4382 xfree (datagram_address
[inchannel
].sa
);
4383 datagram_address
[inchannel
].sa
= 0;
4384 datagram_address
[inchannel
].len
= 0;
4387 chan_process
[inchannel
] = Qnil
;
4388 FD_CLR (inchannel
, &input_wait_mask
);
4389 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
4390 #ifdef NON_BLOCKING_CONNECT
4391 if (FD_ISSET (inchannel
, &connect_wait_mask
))
4393 FD_CLR (inchannel
, &connect_wait_mask
);
4394 FD_CLR (inchannel
, &write_mask
);
4395 if (--num_pending_connects
< 0)
4399 if (inchannel
== max_process_desc
)
4401 /* We just closed the highest-numbered process input descriptor,
4402 so recompute the highest-numbered one now. */
4406 while (0 <= i
&& NILP (chan_process
[i
]));
4408 max_process_desc
= i
;
4414 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4416 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4417 It is given to their filter functions.
4418 Optional argument PROCESS means do not return until output has been
4419 received from PROCESS.
4421 Optional second argument SECONDS and third argument MILLISEC
4422 specify a timeout; return after that much time even if there is
4423 no subprocess output. If SECONDS is a floating point number,
4424 it specifies a fractional number of seconds to wait.
4425 The MILLISEC argument is obsolete and should be avoided.
4427 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4428 from PROCESS only, suspending reading output from other processes.
4429 If JUST-THIS-ONE is an integer, don't run any timers either.
4430 Return non-nil if we received any output from PROCESS (or, if PROCESS
4431 is nil, from any process) before the timeout expired. */)
4432 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4437 if (! NILP (process
))
4438 CHECK_PROCESS (process
);
4440 just_this_one
= Qnil
;
4442 if (!NILP (millisec
))
4443 { /* Obsolete calling convention using integers rather than floats. */
4444 CHECK_NUMBER (millisec
);
4446 seconds
= make_float (XINT (millisec
) / 1000.0);
4449 CHECK_NUMBER (seconds
);
4450 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4457 if (!NILP (seconds
))
4459 if (INTEGERP (seconds
))
4461 if (XINT (seconds
) > 0)
4463 secs
= XINT (seconds
);
4467 else if (FLOATP (seconds
))
4469 if (XFLOAT_DATA (seconds
) > 0)
4471 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4472 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4477 wrong_type_argument (Qnumberp
, seconds
);
4479 else if (! NILP (process
))
4483 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4485 !NILP (process
) ? XPROCESS (process
) : NULL
,
4486 (NILP (just_this_one
) ? 0
4487 : !INTEGERP (just_this_one
) ? 1 : -1))
4492 /* Accept a connection for server process SERVER on CHANNEL. */
4494 static EMACS_INT connect_counter
= 0;
4497 server_accept_connection (Lisp_Object server
, int channel
)
4499 Lisp_Object proc
, caller
, name
, buffer
;
4500 Lisp_Object contact
, host
, service
;
4501 struct Lisp_Process
*ps
= XPROCESS (server
);
4502 struct Lisp_Process
*p
;
4506 struct sockaddr_in in
;
4508 struct sockaddr_in6 in6
;
4510 #ifdef HAVE_LOCAL_SOCKETS
4511 struct sockaddr_un un
;
4514 socklen_t len
= sizeof saddr
;
4517 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4526 if (code
== EWOULDBLOCK
)
4530 if (!NILP (ps
->log
))
4531 call3 (ps
->log
, server
, Qnil
,
4532 concat3 (build_string ("accept failed with code"),
4533 Fnumber_to_string (make_number (code
)),
4534 build_string ("\n")));
4538 count
= SPECPDL_INDEX ();
4539 record_unwind_protect_int (close_file_unwind
, s
);
4543 /* Setup a new process to handle the connection. */
4545 /* Generate a unique identification of the caller, and build contact
4546 information for this process. */
4549 switch (saddr
.sa
.sa_family
)
4553 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4555 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4556 host
= CALLN (Fformat
, ipv4_format
,
4557 make_number (ip
[0]), make_number (ip
[1]),
4558 make_number (ip
[2]), make_number (ip
[3]));
4559 service
= make_number (ntohs (saddr
.in
.sin_port
));
4560 AUTO_STRING (caller_format
, " <%s:%d>");
4561 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4568 Lisp_Object args
[9];
4569 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4572 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4573 args
[0] = ipv6_format
;
4574 for (i
= 0; i
< 8; i
++)
4575 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4576 host
= CALLMANY (Fformat
, args
);
4577 service
= make_number (ntohs (saddr
.in
.sin_port
));
4578 AUTO_STRING (caller_format
, " <[%s]:%d>");
4579 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4584 #ifdef HAVE_LOCAL_SOCKETS
4588 caller
= Fnumber_to_string (make_number (connect_counter
));
4589 AUTO_STRING (space_less_than
, " <");
4590 AUTO_STRING (greater_than
, ">");
4591 caller
= concat3 (space_less_than
, caller
, greater_than
);
4595 /* Create a new buffer name for this process if it doesn't have a
4596 filter. The new buffer name is based on the buffer name or
4597 process name of the server process concatenated with the caller
4600 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4601 || EQ (ps
->filter
, Qt
)))
4605 buffer
= ps
->buffer
;
4607 buffer
= Fbuffer_name (buffer
);
4612 buffer
= concat2 (buffer
, caller
);
4613 buffer
= Fget_buffer_create (buffer
);
4617 /* Generate a unique name for the new server process. Combine the
4618 server process name with the caller identification. */
4620 name
= concat2 (ps
->name
, caller
);
4621 proc
= make_process (name
);
4623 chan_process
[s
] = proc
;
4625 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4627 p
= XPROCESS (proc
);
4629 /* Build new contact information for this setup. */
4630 contact
= Fcopy_sequence (ps
->childp
);
4631 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4632 contact
= Fplist_put (contact
, QChost
, host
);
4633 if (!NILP (service
))
4634 contact
= Fplist_put (contact
, QCservice
, service
);
4635 contact
= Fplist_put (contact
, QCremote
,
4636 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4637 #ifdef HAVE_GETSOCKNAME
4639 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4640 contact
= Fplist_put (contact
, QClocal
,
4641 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4644 pset_childp (p
, contact
);
4645 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4646 pset_type (p
, Qnetwork
);
4648 pset_buffer (p
, buffer
);
4649 pset_sentinel (p
, ps
->sentinel
);
4650 pset_filter (p
, ps
->filter
);
4651 pset_command (p
, Qnil
);
4654 /* Discard the unwind protect for closing S. */
4655 specpdl_ptr
= specpdl
+ count
;
4657 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4660 pset_status (p
, Qrun
);
4662 /* Client processes for accepted connections are not stopped initially. */
4663 if (!EQ (p
->filter
, Qt
))
4665 FD_SET (s
, &input_wait_mask
);
4666 FD_SET (s
, &non_keyboard_wait_mask
);
4669 if (s
> max_process_desc
)
4670 max_process_desc
= s
;
4672 /* Setup coding system for new process based on server process.
4673 This seems to be the proper thing to do, as the coding system
4674 of the new process should reflect the settings at the time the
4675 server socket was opened; not the current settings. */
4677 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4678 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4679 setup_process_coding_systems (proc
);
4681 pset_decoding_buf (p
, empty_unibyte_string
);
4682 p
->decoding_carryover
= 0;
4683 pset_encoding_buf (p
, empty_unibyte_string
);
4685 p
->inherit_coding_system_flag
4686 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4688 AUTO_STRING (dash
, "-");
4689 AUTO_STRING (nl
, "\n");
4690 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4692 if (!NILP (ps
->log
))
4694 AUTO_STRING (accept_from
, "accept from ");
4695 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4698 AUTO_STRING (open_from
, "open from ");
4699 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4702 #ifdef HAVE_GETADDRINFO_A
4704 check_for_dns (Lisp_Object proc
)
4706 struct Lisp_Process
*p
= XPROCESS (proc
);
4707 Lisp_Object ip_addresses
= Qnil
;
4711 if (! p
->dns_request
)
4714 ret
= gai_error (p
->dns_request
);
4715 if (ret
== EAI_INPROGRESS
)
4718 /* We got a response. */
4721 struct addrinfo
*res
;
4723 for (res
= p
->dns_request
->ar_result
; res
; res
= res
->ai_next
)
4725 ip_addresses
= Fcons (conv_sockaddr_to_lisp
4726 (res
->ai_addr
, res
->ai_addrlen
),
4730 ip_addresses
= Fnreverse (ip_addresses
);
4732 /* The DNS lookup failed. */
4733 else if (EQ (p
->status
, Qconnect
))
4735 deactivate_process (proc
);
4736 pset_status (p
, (list2
4738 concat3 (build_string ("Name lookup of "),
4739 build_string (p
->dns_request
->ar_name
),
4740 build_string (" failed")))));
4743 free_dns_request (proc
);
4745 /* This process should not already be connected (or killed). */
4746 if (!EQ (p
->status
, Qconnect
))
4749 return ip_addresses
;
4752 #endif /* HAVE_GETADDRINFO_A */
4755 wait_for_socket_fds (Lisp_Object process
, char const *name
)
4757 while (XPROCESS (process
)->infd
< 0
4758 && EQ (XPROCESS (process
)->status
, Qconnect
))
4760 add_to_log ("Waiting for socket from %s...", build_string (name
));
4761 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4766 wait_while_connecting (Lisp_Object process
)
4768 while (EQ (XPROCESS (process
)->status
, Qconnect
))
4770 add_to_log ("Waiting for connection...");
4771 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4776 wait_for_tls_negotiation (Lisp_Object process
)
4779 while (XPROCESS (process
)->gnutls_p
4780 && XPROCESS (process
)->gnutls_initstage
!= GNUTLS_STAGE_READY
)
4782 add_to_log ("Waiting for TLS...");
4783 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil
, NULL
, 0);
4788 /* This variable is different from waiting_for_input in keyboard.c.
4789 It is used to communicate to a lisp process-filter/sentinel (via the
4790 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4791 for user-input when that process-filter was called.
4792 waiting_for_input cannot be used as that is by definition 0 when
4793 lisp code is being evalled.
4794 This is also used in record_asynch_buffer_change.
4795 For that purpose, this must be 0
4796 when not inside wait_reading_process_output. */
4797 static int waiting_for_user_input_p
;
4800 wait_reading_process_output_unwind (int data
)
4802 waiting_for_user_input_p
= data
;
4805 /* This is here so breakpoints can be put on it. */
4807 wait_reading_process_output_1 (void)
4811 /* Read and dispose of subprocess output while waiting for timeout to
4812 elapse and/or keyboard input to be available.
4816 If negative, gobble data immediately available but don't wait for any.
4819 an additional duration to wait, measured in nanoseconds
4820 If TIME_LIMIT is zero, then:
4821 If NSECS == 0, there is no limit.
4822 If NSECS > 0, the timeout consists of NSECS only.
4823 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4826 0 to ignore keyboard input, or
4827 1 to return when input is available, or
4828 -1 meaning caller will actually read the input, so don't throw to
4829 the quit handler, or
4831 DO_DISPLAY means redisplay should be done to show subprocess
4832 output that arrives.
4834 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4835 (and gobble terminal input into the buffer if any arrives).
4837 If WAIT_PROC is specified, wait until something arrives from that
4840 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4841 (suspending output from other processes). A negative value
4842 means don't run any timers either.
4844 Return positive if we received input from WAIT_PROC (or from any
4845 process if WAIT_PROC is null), zero if we attempted to receive
4846 input but got none, and negative if we didn't even try. */
4849 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4851 Lisp_Object wait_for_cell
,
4852 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4862 struct timespec timeout
, end_time
, timer_delay
;
4863 struct timespec got_output_end_time
= invalid_timespec ();
4864 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
4865 int got_some_output
= -1;
4866 ptrdiff_t count
= SPECPDL_INDEX ();
4868 /* Close to the current time if known, an invalid timespec otherwise. */
4869 struct timespec now
= invalid_timespec ();
4871 FD_ZERO (&Available
);
4874 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4875 && !(CONSP (wait_proc
->status
)
4876 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4877 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4879 record_unwind_protect_int (wait_reading_process_output_unwind
,
4880 waiting_for_user_input_p
);
4881 waiting_for_user_input_p
= read_kbd
;
4883 if (TYPE_MAXIMUM (time_t) < time_limit
)
4884 time_limit
= TYPE_MAXIMUM (time_t);
4886 if (time_limit
< 0 || nsecs
< 0)
4888 else if (time_limit
> 0 || nsecs
> 0)
4891 now
= current_timespec ();
4892 end_time
= timespec_add (now
, make_timespec (time_limit
, nsecs
));
4899 bool process_skipped
= false;
4901 /* If calling from keyboard input, do not quit
4902 since we want to return C-g as an input character.
4903 Otherwise, do pending quit if requested. */
4906 else if (pending_signals
)
4907 process_pending_signals ();
4909 /* Exit now if the cell we're waiting for became non-nil. */
4910 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4913 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4915 Lisp_Object process_list_head
, aproc
;
4916 struct Lisp_Process
*p
;
4918 FOR_EACH_PROCESS(process_list_head
, aproc
)
4920 p
= XPROCESS (aproc
);
4922 if (! wait_proc
|| p
== wait_proc
)
4924 #ifdef HAVE_GETADDRINFO_A
4925 /* Check for pending DNS requests. */
4928 Lisp_Object ip_addresses
= check_for_dns (aproc
);
4929 if (!NILP (ip_addresses
) && !EQ (ip_addresses
, Qt
))
4930 connect_network_socket (aproc
, ip_addresses
);
4934 /* Continue TLS negotiation. */
4935 if (p
->gnutls_initstage
== GNUTLS_STAGE_HANDSHAKE_TRIED
4936 && p
->is_non_blocking_client
)
4938 gnutls_try_handshake (p
);
4939 p
->gnutls_handshakes_tried
++;
4941 if (p
->gnutls_initstage
== GNUTLS_STAGE_READY
)
4943 gnutls_verify_boot (aproc
, Qnil
);
4944 finish_after_tls_connection (aproc
);
4946 else if (p
->gnutls_handshakes_tried
4947 > GNUTLS_EMACS_HANDSHAKES_LIMIT
)
4949 deactivate_process (aproc
);
4950 pset_status (p
, list2 (Qfailed
,
4951 build_string ("TLS negotiation failed")));
4958 #endif /* GETADDRINFO_A or GNUTLS */
4960 /* Compute time from now till when time limit is up. */
4961 /* Exit if already run out. */
4962 if (wait
== TIMEOUT
)
4964 if (!timespec_valid_p (now
))
4965 now
= current_timespec ();
4966 if (timespec_cmp (end_time
, now
) <= 0)
4968 timeout
= timespec_sub (end_time
, now
);
4971 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
4973 /* Normally we run timers here.
4974 But not if wait_for_cell; in those cases,
4975 the wait is supposed to be short,
4976 and those callers cannot handle running arbitrary Lisp code here. */
4977 if (NILP (wait_for_cell
)
4978 && just_wait_proc
>= 0)
4982 unsigned old_timers_run
= timers_run
;
4983 struct buffer
*old_buffer
= current_buffer
;
4984 Lisp_Object old_window
= selected_window
;
4986 timer_delay
= timer_check ();
4988 /* If a timer has run, this might have changed buffers
4989 an alike. Make read_key_sequence aware of that. */
4990 if (timers_run
!= old_timers_run
4991 && (old_buffer
!= current_buffer
4992 || !EQ (old_window
, selected_window
))
4993 && waiting_for_user_input_p
== -1)
4994 record_asynch_buffer_change ();
4996 if (timers_run
!= old_timers_run
&& do_display
)
4997 /* We must retry, since a timer may have requeued itself
4998 and that could alter the time_delay. */
4999 redisplay_preserve_echo_area (9);
5003 while (!detect_input_pending ());
5005 /* If there is unread keyboard input, also return. */
5007 && requeued_events_pending_p ())
5010 /* This is so a breakpoint can be put here. */
5011 if (!timespec_valid_p (timer_delay
))
5012 wait_reading_process_output_1 ();
5015 /* Cause C-g and alarm signals to take immediate action,
5016 and cause input available signals to zero out timeout.
5018 It is important that we do this before checking for process
5019 activity. If we get a SIGCHLD after the explicit checks for
5020 process activity, timeout is the only way we will know. */
5022 set_waiting_for_input (&timeout
);
5024 /* If status of something has changed, and no input is
5025 available, notify the user of the change right away. After
5026 this explicit check, we'll let the SIGCHLD handler zap
5027 timeout to get our attention. */
5028 if (update_tick
!= process_tick
)
5033 if (kbd_on_hold_p ())
5036 Atemp
= input_wait_mask
;
5039 timeout
= make_timespec (0, 0);
5040 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
5042 #ifdef NON_BLOCKING_CONNECT
5043 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
5047 NULL
, &timeout
, NULL
)
5050 /* It's okay for us to do this and then continue with
5051 the loop, since timeout has already been zeroed out. */
5052 clear_waiting_for_input ();
5053 got_some_output
= status_notify (NULL
, wait_proc
);
5054 if (do_display
) redisplay_preserve_echo_area (13);
5058 /* Don't wait for output from a non-running process. Just
5059 read whatever data has already been received. */
5060 if (wait_proc
&& wait_proc
->raw_status_new
)
5061 update_status (wait_proc
);
5063 && ! EQ (wait_proc
->status
, Qrun
)
5064 && ! EQ (wait_proc
->status
, Qconnect
))
5066 bool read_some_bytes
= false;
5068 clear_waiting_for_input ();
5070 /* If data can be read from the process, do so until exhausted. */
5071 if (wait_proc
->infd
>= 0)
5073 XSETPROCESS (proc
, wait_proc
);
5077 int nread
= read_process_output (proc
, wait_proc
->infd
);
5080 if (errno
== EIO
|| errno
== EAGAIN
)
5083 if (errno
== EWOULDBLOCK
)
5089 if (got_some_output
< nread
)
5090 got_some_output
= nread
;
5093 read_some_bytes
= true;
5098 if (read_some_bytes
&& do_display
)
5099 redisplay_preserve_echo_area (10);
5104 /* Wait till there is something to do. */
5106 if (wait_proc
&& just_wait_proc
)
5108 if (wait_proc
->infd
< 0) /* Terminated. */
5110 FD_SET (wait_proc
->infd
, &Available
);
5114 else if (!NILP (wait_for_cell
))
5116 Available
= non_process_wait_mask
;
5123 Available
= non_keyboard_wait_mask
;
5125 Available
= input_wait_mask
;
5126 Writeok
= write_mask
;
5127 check_delay
= wait_proc
? 0 : process_output_delay_count
;
5131 /* If frame size has changed or the window is newly mapped,
5132 redisplay now, before we start to wait. There is a race
5133 condition here; if a SIGIO arrives between now and the select
5134 and indicates that a frame is trashed, the select may block
5135 displaying a trashed screen. */
5136 if (frame_garbaged
&& do_display
)
5138 clear_waiting_for_input ();
5139 redisplay_preserve_echo_area (11);
5141 set_waiting_for_input (&timeout
);
5144 /* Skip the `select' call if input is available and we're
5145 waiting for keyboard input or a cell change (which can be
5146 triggered by processing X events). In the latter case, set
5147 nfds to 1 to avoid breaking the loop. */
5149 if ((read_kbd
|| !NILP (wait_for_cell
))
5150 && detect_input_pending ())
5152 nfds
= read_kbd
? 0 : 1;
5154 FD_ZERO (&Available
);
5158 /* Set the timeout for adaptive read buffering if any
5159 process has non-zero read_output_skip and non-zero
5160 read_output_delay, and we are not reading output for a
5161 specific process. It is not executed if
5162 Vprocess_adaptive_read_buffering is nil. */
5163 if (process_output_skip
&& check_delay
> 0)
5165 int adaptive_nsecs
= timeout
.tv_nsec
;
5166 if (timeout
.tv_sec
> 0 || adaptive_nsecs
> READ_OUTPUT_DELAY_MAX
)
5167 adaptive_nsecs
= READ_OUTPUT_DELAY_MAX
;
5168 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
5170 proc
= chan_process
[channel
];
5173 /* Find minimum non-zero read_output_delay among the
5174 processes with non-zero read_output_skip. */
5175 if (XPROCESS (proc
)->read_output_delay
> 0)
5178 if (!XPROCESS (proc
)->read_output_skip
)
5180 FD_CLR (channel
, &Available
);
5181 process_skipped
= true;
5182 XPROCESS (proc
)->read_output_skip
= 0;
5183 if (XPROCESS (proc
)->read_output_delay
< adaptive_nsecs
)
5184 adaptive_nsecs
= XPROCESS (proc
)->read_output_delay
;
5187 timeout
= make_timespec (0, adaptive_nsecs
);
5188 process_output_skip
= 0;
5191 /* If we've got some output and haven't limited our timeout
5192 with adaptive read buffering, limit it. */
5193 if (got_some_output
> 0 && !process_skipped
5195 || timeout
.tv_nsec
> READ_OUTPUT_DELAY_INCREMENT
))
5196 timeout
= make_timespec (0, READ_OUTPUT_DELAY_INCREMENT
);
5199 if (NILP (wait_for_cell
) && just_wait_proc
>= 0
5200 && timespec_valid_p (timer_delay
)
5201 && timespec_cmp (timer_delay
, timeout
) < 0)
5203 if (!timespec_valid_p (now
))
5204 now
= current_timespec ();
5205 struct timespec timeout_abs
= timespec_add (now
, timeout
);
5206 if (!timespec_valid_p (got_output_end_time
)
5207 || timespec_cmp (timeout_abs
, got_output_end_time
) < 0)
5208 got_output_end_time
= timeout_abs
;
5209 timeout
= timer_delay
;
5212 got_output_end_time
= invalid_timespec ();
5214 /* NOW can become inaccurate if time can pass during pselect. */
5215 if (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0)
5216 now
= invalid_timespec ();
5218 #if defined (HAVE_NS)
5220 #elif defined (HAVE_GLIB)
5225 (max (max_process_desc
, max_input_desc
) + 1,
5227 (check_write
? &Writeok
: 0),
5228 NULL
, &timeout
, NULL
);
5231 /* GnuTLS buffers data internally. In lowat mode it leaves
5232 some data in the TCP buffers so that select works, but
5233 with custom pull/push functions we need to check if some
5234 data is available in the buffers manually. */
5237 fd_set tls_available
;
5240 FD_ZERO (&tls_available
);
5243 /* We're not waiting on a specific process, so loop
5244 through all the channels and check for data.
5245 This is a workaround needed for some versions of
5246 the gnutls library -- 2.12.14 has been confirmed
5248 http://comments.gmane.org/gmane.emacs.devel/145074 */
5249 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
5250 if (! NILP (chan_process
[channel
]))
5252 struct Lisp_Process
*p
=
5253 XPROCESS (chan_process
[channel
]);
5254 if (p
&& p
->gnutls_p
&& p
->gnutls_state
5255 && ((emacs_gnutls_record_check_pending
5260 eassert (p
->infd
== channel
);
5261 FD_SET (p
->infd
, &tls_available
);
5268 /* Check this specific channel. */
5269 if (wait_proc
->gnutls_p
/* Check for valid process. */
5270 && wait_proc
->gnutls_state
5271 /* Do we have pending data? */
5272 && ((emacs_gnutls_record_check_pending
5273 (wait_proc
->gnutls_state
))
5277 eassert (0 <= wait_proc
->infd
);
5278 /* Set to Available. */
5279 FD_SET (wait_proc
->infd
, &tls_available
);
5284 Available
= tls_available
;
5291 /* Make C-g and alarm signals set flags again. */
5292 clear_waiting_for_input ();
5294 /* If we woke up due to SIGWINCH, actually change size now. */
5295 do_pending_window_change (0);
5299 /* Exit the main loop if we've passed the requested timeout,
5300 or aren't skipping processes and got some output and
5301 haven't lowered our timeout due to timers or SIGIO and
5302 have waited a long amount of time due to repeated
5306 struct timespec cmp_time
5309 : (!process_skipped
&& got_some_output
> 0
5310 && (timeout
.tv_sec
> 0 || timeout
.tv_nsec
> 0))
5311 ? got_output_end_time
5312 : invalid_timespec ());
5313 if (timespec_valid_p (cmp_time
))
5315 now
= current_timespec ();
5316 if (timespec_cmp (cmp_time
, now
) <= 0)
5323 if (xerrno
== EINTR
)
5325 else if (xerrno
== EBADF
)
5328 report_file_errno ("Failed select", Qnil
, xerrno
);
5331 /* Check for keyboard input. */
5332 /* If there is any, return immediately
5333 to give it higher priority than subprocesses. */
5337 unsigned old_timers_run
= timers_run
;
5338 struct buffer
*old_buffer
= current_buffer
;
5339 Lisp_Object old_window
= selected_window
;
5342 if (detect_input_pending_run_timers (do_display
))
5344 swallow_events (do_display
);
5345 if (detect_input_pending_run_timers (do_display
))
5349 /* If a timer has run, this might have changed buffers
5350 an alike. Make read_key_sequence aware of that. */
5351 if (timers_run
!= old_timers_run
5352 && waiting_for_user_input_p
== -1
5353 && (old_buffer
!= current_buffer
5354 || !EQ (old_window
, selected_window
)))
5355 record_asynch_buffer_change ();
5361 /* If there is unread keyboard input, also return. */
5363 && requeued_events_pending_p ())
5366 /* If we are not checking for keyboard input now,
5367 do process events (but don't run any timers).
5368 This is so that X events will be processed.
5369 Otherwise they may have to wait until polling takes place.
5370 That would causes delays in pasting selections, for example.
5372 (We used to do this only if wait_for_cell.) */
5373 if (read_kbd
== 0 && detect_input_pending ())
5375 swallow_events (do_display
);
5376 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5377 if (detect_input_pending ())
5382 /* Exit now if the cell we're waiting for became non-nil. */
5383 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
5387 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5388 go read it. This can happen with X on BSD after logging out.
5389 In that case, there really is no input and no SIGIO,
5390 but select says there is input. */
5392 if (read_kbd
&& interrupt_input
5393 && keyboard_bit_set (&Available
) && ! noninteractive
)
5394 handle_input_available_signal (SIGIO
);
5397 /* If checking input just got us a size-change event from X,
5398 obey it now if we should. */
5399 if (read_kbd
|| ! NILP (wait_for_cell
))
5400 do_pending_window_change (0);
5402 /* Check for data from a process. */
5403 if (no_avail
|| nfds
== 0)
5406 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
5408 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
5410 && ((d
->condition
& FOR_READ
5411 && FD_ISSET (channel
, &Available
))
5412 || (d
->condition
& FOR_WRITE
5413 && FD_ISSET (channel
, &write_mask
))))
5414 d
->func (channel
, d
->data
);
5417 for (channel
= 0; channel
<= max_process_desc
; channel
++)
5419 if (FD_ISSET (channel
, &Available
)
5420 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
5421 && !FD_ISSET (channel
, &non_process_wait_mask
))
5425 /* If waiting for this channel, arrange to return as
5426 soon as no more input to be processed. No more
5428 proc
= chan_process
[channel
];
5432 /* If this is a server stream socket, accept connection. */
5433 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
5435 server_accept_connection (proc
, channel
);
5439 /* Read data from the process, starting with our
5440 buffered-ahead character if we have one. */
5442 nread
= read_process_output (proc
, channel
);
5443 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
5444 && got_some_output
< nread
)
5445 got_some_output
= nread
;
5448 /* Vacuum up any leftovers without waiting. */
5449 if (wait_proc
== XPROCESS (proc
))
5451 /* Since read_process_output can run a filter,
5452 which can call accept-process-output,
5453 don't try to read from any other processes
5454 before doing the select again. */
5455 FD_ZERO (&Available
);
5458 redisplay_preserve_echo_area (12);
5461 else if (nread
== -1 && errno
== EWOULDBLOCK
)
5464 else if (nread
== -1 && errno
== EAGAIN
)
5467 /* FIXME: Is this special case still needed? */
5468 /* Note that we cannot distinguish between no input
5469 available now and a closed pipe.
5470 With luck, a closed pipe will be accompanied by
5471 subprocess termination and SIGCHLD. */
5472 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5473 && !PIPECONN_P (proc
))
5477 /* On some OSs with ptys, when the process on one end of
5478 a pty exits, the other end gets an error reading with
5479 errno = EIO instead of getting an EOF (0 bytes read).
5480 Therefore, if we get an error reading and errno =
5481 EIO, just continue, because the child process has
5482 exited and should clean itself up soon (e.g. when we
5484 else if (nread
== -1 && errno
== EIO
)
5486 struct Lisp_Process
*p
= XPROCESS (proc
);
5488 /* Clear the descriptor now, so we only raise the
5490 FD_CLR (channel
, &input_wait_mask
);
5491 FD_CLR (channel
, &non_keyboard_wait_mask
);
5495 /* If the EIO occurs on a pty, the SIGCHLD handler's
5496 waitpid call will not find the process object to
5497 delete. Do it here. */
5498 p
->tick
= ++process_tick
;
5499 pset_status (p
, Qfailed
);
5502 #endif /* HAVE_PTYS */
5503 /* If we can detect process termination, don't consider the
5504 process gone just because its pipe is closed. */
5505 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
)
5506 && !PIPECONN_P (proc
))
5508 else if (nread
== 0 && PIPECONN_P (proc
))
5510 /* Preserve status of processes already terminated. */
5511 XPROCESS (proc
)->tick
= ++process_tick
;
5512 deactivate_process (proc
);
5513 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5514 pset_status (XPROCESS (proc
),
5515 list2 (Qexit
, make_number (0)));
5519 /* Preserve status of processes already terminated. */
5520 XPROCESS (proc
)->tick
= ++process_tick
;
5521 deactivate_process (proc
);
5522 if (XPROCESS (proc
)->raw_status_new
)
5523 update_status (XPROCESS (proc
));
5524 if (EQ (XPROCESS (proc
)->status
, Qrun
))
5525 pset_status (XPROCESS (proc
),
5526 list2 (Qexit
, make_number (256)));
5529 #ifdef NON_BLOCKING_CONNECT
5530 if (FD_ISSET (channel
, &Writeok
)
5531 && FD_ISSET (channel
, &connect_wait_mask
))
5533 struct Lisp_Process
*p
;
5535 FD_CLR (channel
, &connect_wait_mask
);
5536 FD_CLR (channel
, &write_mask
);
5537 if (--num_pending_connects
< 0)
5540 proc
= chan_process
[channel
];
5544 p
= XPROCESS (proc
);
5547 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5548 So only use it on systems where it is known to work. */
5550 socklen_t xlen
= sizeof (xerrno
);
5551 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5556 struct sockaddr pname
;
5557 socklen_t pnamelen
= sizeof (pname
);
5559 /* If connection failed, getpeername will fail. */
5561 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5563 /* Obtain connect failure code through error slippage. */
5566 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5573 p
->tick
= ++process_tick
;
5574 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5575 deactivate_process (proc
);
5580 /* If we have an incompletely set up TLS connection,
5581 then defer the sentinel signalling until
5583 if (NILP (p
->gnutls_boot_parameters
)
5587 pset_status (p
, Qrun
);
5588 /* Execute the sentinel here. If we had relied on
5589 status_notify to do it later, it will read input
5590 from the process before calling the sentinel. */
5591 exec_sentinel (proc
, build_string ("open\n"));
5594 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
5595 && !EQ (p
->command
, Qt
))
5597 FD_SET (p
->infd
, &input_wait_mask
);
5598 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5602 #endif /* NON_BLOCKING_CONNECT */
5603 } /* End for each file descriptor. */
5604 } /* End while exit conditions not met. */
5606 unbind_to (count
, Qnil
);
5608 /* If calling from keyboard input, do not quit
5609 since we want to return C-g as an input character.
5610 Otherwise, do pending quit if requested. */
5613 /* Prevent input_pending from remaining set if we quit. */
5614 clear_input_pending ();
5618 return got_some_output
;
5621 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5624 read_process_output_call (Lisp_Object fun_and_args
)
5626 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5630 read_process_output_error_handler (Lisp_Object error_val
)
5632 cmd_error_internal (error_val
, "error in process filter: ");
5634 update_echo_area ();
5635 Fsleep_for (make_number (2), Qnil
);
5640 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5642 struct coding_system
*coding
);
5644 /* Read pending output from the process channel,
5645 starting with our buffered-ahead character if we have one.
5646 Yield number of decoded characters read.
5648 This function reads at most 4096 characters.
5649 If you want to read all available subprocess output,
5650 you must call it repeatedly until it returns zero.
5652 The characters read are decoded according to PROC's coding-system
5656 read_process_output (Lisp_Object proc
, int channel
)
5659 struct Lisp_Process
*p
= XPROCESS (proc
);
5660 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5661 int carryover
= p
->decoding_carryover
;
5662 enum { readmax
= 4096 };
5663 ptrdiff_t count
= SPECPDL_INDEX ();
5664 Lisp_Object odeactivate
;
5665 char chars
[sizeof coding
->carryover
+ readmax
];
5668 /* See the comment above. */
5669 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5671 #ifdef DATAGRAM_SOCKETS
5672 /* We have a working select, so proc_buffered_char is always -1. */
5673 if (DATAGRAM_CHAN_P (channel
))
5675 socklen_t len
= datagram_address
[channel
].len
;
5676 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5677 0, datagram_address
[channel
].sa
, &len
);
5682 bool buffered
= proc_buffered_char
[channel
] >= 0;
5685 chars
[carryover
] = proc_buffered_char
[channel
];
5686 proc_buffered_char
[channel
] = -1;
5689 if (p
->gnutls_p
&& p
->gnutls_state
)
5690 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5691 readmax
- buffered
);
5694 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5695 readmax
- buffered
);
5696 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5698 int delay
= p
->read_output_delay
;
5701 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5704 process_output_delay_count
++;
5705 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5708 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5710 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5712 process_output_delay_count
--;
5714 p
->read_output_delay
= delay
;
5717 p
->read_output_skip
= 1;
5718 process_output_skip
= 1;
5722 nbytes
+= buffered
&& nbytes
<= 0;
5725 p
->decoding_carryover
= 0;
5727 /* At this point, NBYTES holds number of bytes just received
5728 (including the one in proc_buffered_char[channel]). */
5731 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5733 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5736 /* Now set NBYTES how many bytes we must decode. */
5737 nbytes
+= carryover
;
5739 odeactivate
= Vdeactivate_mark
;
5740 /* There's no good reason to let process filters change the current
5741 buffer, and many callers of accept-process-output, sit-for, and
5742 friends don't expect current-buffer to be changed from under them. */
5743 record_unwind_current_buffer ();
5745 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5747 /* Handling the process output should not deactivate the mark. */
5748 Vdeactivate_mark
= odeactivate
;
5750 unbind_to (count
, Qnil
);
5755 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5757 struct coding_system
*coding
)
5759 Lisp_Object outstream
= p
->filter
;
5761 bool outer_running_asynch_code
= running_asynch_code
;
5762 int waiting
= waiting_for_user_input_p
;
5765 Lisp_Object obuffer
, okeymap
;
5766 XSETBUFFER (obuffer
, current_buffer
);
5767 okeymap
= BVAR (current_buffer
, keymap
);
5770 /* We inhibit quit here instead of just catching it so that
5771 hitting ^G when a filter happens to be running won't screw
5773 specbind (Qinhibit_quit
, Qt
);
5774 specbind (Qlast_nonmenu_event
, Qt
);
5776 /* In case we get recursively called,
5777 and we already saved the match data nonrecursively,
5778 save the same match data in safely recursive fashion. */
5779 if (outer_running_asynch_code
)
5782 /* Don't clobber the CURRENT match data, either! */
5783 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5784 restore_search_regs ();
5785 record_unwind_save_match_data ();
5786 Fset_match_data (tem
, Qt
);
5789 /* For speed, if a search happens within this code,
5790 save the match data in a special nonrecursive fashion. */
5791 running_asynch_code
= 1;
5793 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5794 text
= coding
->dst_object
;
5795 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5796 /* A new coding system might be found. */
5797 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5799 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5801 /* Don't call setup_coding_system for
5802 proc_decode_coding_system[channel] here. It is done in
5803 detect_coding called via decode_coding above. */
5805 /* If a coding system for encoding is not yet decided, we set
5806 it as the same as coding-system for decoding.
5808 But, before doing that we must check if
5809 proc_encode_coding_system[p->outfd] surely points to a
5810 valid memory because p->outfd will be changed once EOF is
5811 sent to the process. */
5812 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5813 && proc_encode_coding_system
[p
->outfd
])
5815 pset_encode_coding_system
5816 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5817 setup_coding_system (p
->encode_coding_system
,
5818 proc_encode_coding_system
[p
->outfd
]);
5822 if (coding
->carryover_bytes
> 0)
5824 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5825 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5826 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5827 coding
->carryover_bytes
);
5828 p
->decoding_carryover
= coding
->carryover_bytes
;
5830 if (SBYTES (text
) > 0)
5831 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5832 sometimes it's simply wrong to wrap (e.g. when called from
5833 accept-process-output). */
5834 internal_condition_case_1 (read_process_output_call
,
5835 list3 (outstream
, make_lisp_proc (p
), text
),
5836 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5837 read_process_output_error_handler
);
5839 /* If we saved the match data nonrecursively, restore it now. */
5840 restore_search_regs ();
5841 running_asynch_code
= outer_running_asynch_code
;
5843 /* Restore waiting_for_user_input_p as it was
5844 when we were called, in case the filter clobbered it. */
5845 waiting_for_user_input_p
= waiting
;
5847 #if 0 /* Call record_asynch_buffer_change unconditionally,
5848 because we might have changed minor modes or other things
5849 that affect key bindings. */
5850 if (! EQ (Fcurrent_buffer (), obuffer
)
5851 || ! EQ (current_buffer
->keymap
, okeymap
))
5853 /* But do it only if the caller is actually going to read events.
5854 Otherwise there's no need to make him wake up, and it could
5855 cause trouble (for example it would make sit_for return). */
5856 if (waiting_for_user_input_p
== -1)
5857 record_asynch_buffer_change ();
5860 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5861 Sinternal_default_process_filter
, 2, 2, 0,
5862 doc
: /* Function used as default process filter.
5863 This inserts the process's output into its buffer, if there is one.
5864 Otherwise it discards the output. */)
5865 (Lisp_Object proc
, Lisp_Object text
)
5867 struct Lisp_Process
*p
;
5870 CHECK_PROCESS (proc
);
5871 p
= XPROCESS (proc
);
5872 CHECK_STRING (text
);
5874 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5876 Lisp_Object old_read_only
;
5877 ptrdiff_t old_begv
, old_zv
;
5878 ptrdiff_t old_begv_byte
, old_zv_byte
;
5879 ptrdiff_t before
, before_byte
;
5880 ptrdiff_t opoint_byte
;
5883 Fset_buffer (p
->buffer
);
5885 opoint_byte
= PT_BYTE
;
5886 old_read_only
= BVAR (current_buffer
, read_only
);
5889 old_begv_byte
= BEGV_BYTE
;
5890 old_zv_byte
= ZV_BYTE
;
5892 bset_read_only (current_buffer
, Qnil
);
5894 /* Insert new output into buffer at the current end-of-output
5895 marker, thus preserving logical ordering of input and output. */
5896 if (XMARKER (p
->mark
)->buffer
)
5897 set_point_from_marker (p
->mark
);
5899 SET_PT_BOTH (ZV
, ZV_BYTE
);
5901 before_byte
= PT_BYTE
;
5903 /* If the output marker is outside of the visible region, save
5904 the restriction and widen. */
5905 if (! (BEGV
<= PT
&& PT
<= ZV
))
5908 /* Adjust the multibyteness of TEXT to that of the buffer. */
5909 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5910 != ! STRING_MULTIBYTE (text
))
5911 text
= (STRING_MULTIBYTE (text
)
5912 ? Fstring_as_unibyte (text
)
5913 : Fstring_to_multibyte (text
));
5914 /* Insert before markers in case we are inserting where
5915 the buffer's mark is, and the user's next command is Meta-y. */
5916 insert_from_string_before_markers (text
, 0, 0,
5917 SCHARS (text
), SBYTES (text
), 0);
5919 /* Make sure the process marker's position is valid when the
5920 process buffer is changed in the signal_after_change above.
5921 W3 is known to do that. */
5922 if (BUFFERP (p
->buffer
)
5923 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5924 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5926 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5928 update_mode_lines
= 23;
5930 /* Make sure opoint and the old restrictions
5931 float ahead of any new text just as point would. */
5932 if (opoint
>= before
)
5934 opoint
+= PT
- before
;
5935 opoint_byte
+= PT_BYTE
- before_byte
;
5937 if (old_begv
> before
)
5939 old_begv
+= PT
- before
;
5940 old_begv_byte
+= PT_BYTE
- before_byte
;
5942 if (old_zv
>= before
)
5944 old_zv
+= PT
- before
;
5945 old_zv_byte
+= PT_BYTE
- before_byte
;
5948 /* If the restriction isn't what it should be, set it. */
5949 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5950 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5952 bset_read_only (current_buffer
, old_read_only
);
5953 SET_PT_BOTH (opoint
, opoint_byte
);
5958 /* Sending data to subprocess. */
5960 /* In send_process, when a write fails temporarily,
5961 wait_reading_process_output is called. It may execute user code,
5962 e.g. timers, that attempts to write new data to the same process.
5963 We must ensure that data is sent in the right order, and not
5964 interspersed half-completed with other writes (Bug#10815). This is
5965 handled by the write_queue element of struct process. It is a list
5966 with each entry having the form
5968 (string . (offset . length))
5970 where STRING is a lisp string, OFFSET is the offset into the
5971 string's byte sequence from which we should begin to send, and
5972 LENGTH is the number of bytes left to send. */
5974 /* Create a new entry in write_queue.
5975 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5976 BUF is a pointer to the string sequence of the input_obj or a C
5977 string in case of Qt or Qnil. */
5980 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5981 const char *buf
, ptrdiff_t len
, bool front
)
5984 Lisp_Object entry
, obj
;
5986 if (STRINGP (input_obj
))
5988 offset
= buf
- SSDATA (input_obj
);
5994 obj
= make_unibyte_string (buf
, len
);
5997 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
6000 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
6002 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
6005 /* Remove the first element in the write_queue of process P, put its
6006 contents in OBJ, BUF and LEN, and return true. If the
6007 write_queue is empty, return false. */
6010 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
6011 const char **buf
, ptrdiff_t *len
)
6013 Lisp_Object entry
, offset_length
;
6016 if (NILP (p
->write_queue
))
6019 entry
= XCAR (p
->write_queue
);
6020 pset_write_queue (p
, XCDR (p
->write_queue
));
6022 *obj
= XCAR (entry
);
6023 offset_length
= XCDR (entry
);
6025 *len
= XINT (XCDR (offset_length
));
6026 offset
= XINT (XCAR (offset_length
));
6027 *buf
= SSDATA (*obj
) + offset
;
6032 /* Send some data to process PROC.
6033 BUF is the beginning of the data; LEN is the number of characters.
6034 OBJECT is the Lisp object that the data comes from. If OBJECT is
6035 nil or t, it means that the data comes from C string.
6037 If OBJECT is not nil, the data is encoded by PROC's coding-system
6038 for encoding before it is sent.
6040 This function can evaluate Lisp code and can garbage collect. */
6043 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
6046 struct Lisp_Process
*p
= XPROCESS (proc
);
6048 struct coding_system
*coding
;
6050 if (NETCONN_P (proc
))
6052 wait_while_connecting (proc
);
6053 wait_for_tls_negotiation (proc
);
6056 if (p
->raw_status_new
)
6058 if (! EQ (p
->status
, Qrun
))
6059 error ("Process %s not running", SDATA (p
->name
));
6061 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
6063 coding
= proc_encode_coding_system
[p
->outfd
];
6064 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
6066 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
6067 || (BUFFERP (object
)
6068 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
6071 pset_encode_coding_system
6072 (p
, complement_process_encoding_system (p
->encode_coding_system
));
6073 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
6075 /* The coding system for encoding was changed to raw-text
6076 because we sent a unibyte text previously. Now we are
6077 sending a multibyte text, thus we must encode it by the
6078 original coding system specified for the current process.
6080 Another reason we come here is that the coding system
6081 was just complemented and a new one was returned by
6082 complement_process_encoding_system. */
6083 setup_coding_system (p
->encode_coding_system
, coding
);
6084 Vlast_coding_system_used
= p
->encode_coding_system
;
6086 coding
->src_multibyte
= 1;
6090 coding
->src_multibyte
= 0;
6091 /* For sending a unibyte text, character code conversion should
6092 not take place but EOL conversion should. So, setup raw-text
6093 or one of the subsidiary if we have not yet done it. */
6094 if (CODING_REQUIRE_ENCODING (coding
))
6096 if (CODING_REQUIRE_FLUSHING (coding
))
6098 /* But, before changing the coding, we must flush out data. */
6099 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6100 send_process (proc
, "", 0, Qt
);
6101 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
6103 setup_coding_system (raw_text_coding_system
6104 (Vlast_coding_system_used
),
6106 coding
->src_multibyte
= 0;
6109 coding
->dst_multibyte
= 0;
6111 if (CODING_REQUIRE_ENCODING (coding
))
6113 coding
->dst_object
= Qt
;
6114 if (BUFFERP (object
))
6116 ptrdiff_t from_byte
, from
, to
;
6117 ptrdiff_t save_pt
, save_pt_byte
;
6118 struct buffer
*cur
= current_buffer
;
6120 set_buffer_internal (XBUFFER (object
));
6121 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
6123 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
6124 from
= BYTE_TO_CHAR (from_byte
);
6125 to
= BYTE_TO_CHAR (from_byte
+ len
);
6126 TEMP_SET_PT_BOTH (from
, from_byte
);
6127 encode_coding_object (coding
, object
, from
, from_byte
,
6128 to
, from_byte
+ len
, Qt
);
6129 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
6130 set_buffer_internal (cur
);
6132 else if (STRINGP (object
))
6134 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
6135 SBYTES (object
), Qt
);
6139 coding
->dst_object
= make_unibyte_string (buf
, len
);
6140 coding
->produced
= len
;
6143 len
= coding
->produced
;
6144 object
= coding
->dst_object
;
6145 buf
= SSDATA (object
);
6148 /* If there is already data in the write_queue, put the new data
6149 in the back of queue. Otherwise, ignore it. */
6150 if (!NILP (p
->write_queue
))
6151 write_queue_push (p
, object
, buf
, len
, 0);
6153 do /* while !NILP (p->write_queue) */
6155 ptrdiff_t cur_len
= -1;
6156 const char *cur_buf
;
6157 Lisp_Object cur_object
;
6159 /* If write_queue is empty, ignore it. */
6160 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
6164 cur_object
= object
;
6169 /* Send this batch, using one or more write calls. */
6170 ptrdiff_t written
= 0;
6171 int outfd
= p
->outfd
;
6172 #ifdef DATAGRAM_SOCKETS
6173 if (DATAGRAM_CHAN_P (outfd
))
6175 rv
= sendto (outfd
, cur_buf
, cur_len
,
6176 0, datagram_address
[outfd
].sa
,
6177 datagram_address
[outfd
].len
);
6180 else if (errno
== EMSGSIZE
)
6181 report_file_error ("Sending datagram", proc
);
6187 if (p
->gnutls_p
&& p
->gnutls_state
)
6188 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
6191 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
6192 rv
= (written
? 0 : -1);
6193 if (p
->read_output_delay
> 0
6194 && p
->adaptive_read_buffering
== 1)
6196 p
->read_output_delay
= 0;
6197 process_output_delay_count
--;
6198 p
->read_output_skip
= 0;
6206 || errno
== EWOULDBLOCK
6209 /* Buffer is full. Wait, accepting input;
6210 that may allow the program
6211 to finish doing output and read more. */
6213 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6214 /* A gross hack to work around a bug in FreeBSD.
6215 In the following sequence, read(2) returns
6219 write(2) 954 bytes, get EAGAIN
6220 read(2) 1024 bytes in process_read_output
6221 read(2) 11 bytes in process_read_output
6223 That is, read(2) returns more bytes than have
6224 ever been written successfully. The 1033 bytes
6225 read are the 1022 bytes written successfully
6226 after processing (for example with CRs added if
6227 the terminal is set up that way which it is
6228 here). The same bytes will be seen again in a
6229 later read(2), without the CRs. */
6231 if (errno
== EAGAIN
)
6234 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
6236 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6238 /* Put what we should have written in wait_queue. */
6239 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
6240 wait_reading_process_output (0, 20 * 1000 * 1000,
6241 0, 0, Qnil
, NULL
, 0);
6242 /* Reread queue, to see what is left. */
6245 else if (errno
== EPIPE
)
6247 p
->raw_status_new
= 0;
6248 pset_status (p
, list2 (Qexit
, make_number (256)));
6249 p
->tick
= ++process_tick
;
6250 deactivate_process (proc
);
6251 error ("process %s no longer connected to pipe; closed it",
6255 /* This is a real error. */
6256 report_file_error ("Writing to process", proc
);
6262 while (!NILP (p
->write_queue
));
6265 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
6267 doc
: /* Send current contents of region as input to PROCESS.
6268 PROCESS may be a process, a buffer, the name of a process or buffer, or
6269 nil, indicating the current buffer's process.
6270 Called from program, takes three arguments, PROCESS, START and END.
6271 If the region is more than 500 characters long,
6272 it is sent in several bunches. This may happen even for shorter regions.
6273 Output from processes can arrive in between bunches.
6275 If PROCESS is a non-blocking network process that hasn't been fully
6276 set up yet, this function will block until socket setup has completed. */)
6277 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
6279 Lisp_Object proc
= get_process (process
);
6280 ptrdiff_t start_byte
, end_byte
;
6282 validate_region (&start
, &end
);
6284 start_byte
= CHAR_TO_BYTE (XINT (start
));
6285 end_byte
= CHAR_TO_BYTE (XINT (end
));
6287 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
6288 move_gap_both (XINT (start
), start_byte
);
6290 if (NETCONN_P (proc
))
6291 wait_while_connecting (proc
);
6293 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
6294 end_byte
- start_byte
, Fcurrent_buffer ());
6299 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
6301 doc
: /* Send PROCESS the contents of STRING as input.
6302 PROCESS may be a process, a buffer, the name of a process or buffer, or
6303 nil, indicating the current buffer's process.
6304 If STRING is more than 500 characters long,
6305 it is sent in several bunches. This may happen even for shorter strings.
6306 Output from processes can arrive in between bunches.
6308 If PROCESS is a non-blocking network process that hasn't been fully
6309 set up yet, this function will block until socket setup has completed. */)
6310 (Lisp_Object process
, Lisp_Object string
)
6312 CHECK_STRING (string
);
6313 Lisp_Object proc
= get_process (process
);
6314 send_process (proc
, SSDATA (string
),
6315 SBYTES (string
), string
);
6319 /* Return the foreground process group for the tty/pty that
6320 the process P uses. */
6322 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
6327 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
6330 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6331 master side. Try the slave side. */
6332 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
6336 ioctl (fd
, TIOCGPGRP
, &gid
);
6340 #endif /* defined (TIOCGPGRP ) */
6345 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
6346 Sprocess_running_child_p
, 0, 1, 0,
6347 doc
: /* Return non-nil if PROCESS has given the terminal to a
6348 child. If the operating system does not make it possible to find out,
6349 return t. If we can find out, return the numeric ID of the foreground
6351 (Lisp_Object process
)
6353 /* Initialize in case ioctl doesn't exist or gives an error,
6354 in a way that will cause returning t. */
6355 Lisp_Object proc
= get_process (process
);
6356 struct Lisp_Process
*p
= XPROCESS (proc
);
6358 if (!EQ (p
->type
, Qreal
))
6359 error ("Process %s is not a subprocess",
6362 error ("Process %s is not active",
6365 pid_t gid
= emacs_get_tty_pgrp (p
);
6370 return make_number (gid
);
6374 /* Send a signal number SIGNO to PROCESS.
6375 If CURRENT_GROUP is t, that means send to the process group
6376 that currently owns the terminal being used to communicate with PROCESS.
6377 This is used for various commands in shell mode.
6378 If CURRENT_GROUP is lambda, that means send to the process group
6379 that currently owns the terminal, but only if it is NOT the shell itself.
6381 If NOMSG is false, insert signal-announcements into process's buffers
6384 If we can, we try to signal PROCESS by sending control characters
6385 down the pty. This allows us to signal inferiors who have changed
6386 their uid, for which kill would return an EPERM error. */
6389 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
6393 struct Lisp_Process
*p
;
6397 proc
= get_process (process
);
6398 p
= XPROCESS (proc
);
6400 if (!EQ (p
->type
, Qreal
))
6401 error ("Process %s is not a subprocess",
6404 error ("Process %s is not active",
6408 current_group
= Qnil
;
6410 /* If we are using pgrps, get a pgrp number and make it negative. */
6411 if (NILP (current_group
))
6412 /* Send the signal to the shell's process group. */
6416 #ifdef SIGNALS_VIA_CHARACTERS
6417 /* If possible, send signals to the entire pgrp
6418 by sending an input character to it. */
6421 cc_t
*sig_char
= NULL
;
6423 tcgetattr (p
->infd
, &t
);
6428 sig_char
= &t
.c_cc
[VINTR
];
6432 sig_char
= &t
.c_cc
[VQUIT
];
6436 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6437 sig_char
= &t
.c_cc
[VSWTCH
];
6439 sig_char
= &t
.c_cc
[VSUSP
];
6444 if (sig_char
&& *sig_char
!= CDISABLE
)
6446 send_process (proc
, (char *) sig_char
, 1, Qnil
);
6449 /* If we can't send the signal with a character,
6450 fall through and send it another way. */
6452 /* The code above may fall through if it can't
6453 handle the signal. */
6454 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6457 /* Get the current pgrp using the tty itself, if we have that.
6458 Otherwise, use the pty to get the pgrp.
6459 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6460 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6461 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6462 His patch indicates that if TIOCGPGRP returns an error, then
6463 we should just assume that p->pid is also the process group id. */
6465 gid
= emacs_get_tty_pgrp (p
);
6468 /* If we can't get the information, assume
6469 the shell owns the tty. */
6472 /* It is not clear whether anything really can set GID to -1.
6473 Perhaps on some system one of those ioctls can or could do so.
6474 Or perhaps this is vestigial. */
6477 #else /* ! defined (TIOCGPGRP) */
6478 /* Can't select pgrps on this system, so we know that
6479 the child itself heads the pgrp. */
6481 #endif /* ! defined (TIOCGPGRP) */
6483 /* If current_group is lambda, and the shell owns the terminal,
6484 don't send any signal. */
6485 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
6490 if (signo
== SIGCONT
)
6492 p
->raw_status_new
= 0;
6493 pset_status (p
, Qrun
);
6494 p
->tick
= ++process_tick
;
6497 status_notify (NULL
, NULL
);
6498 redisplay_preserve_echo_area (13);
6504 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6505 We don't know whether the bug is fixed in later HP-UX versions. */
6506 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
6510 /* If we don't have process groups, send the signal to the immediate
6511 subprocess. That isn't really right, but it's better than any
6512 obvious alternative. */
6513 pid_t pid
= no_pgrp
? gid
: - gid
;
6515 /* Do not kill an already-reaped process, as that could kill an
6516 innocent bystander that happens to have the same process ID. */
6518 block_child_signal (&oldset
);
6521 unblock_child_signal (&oldset
);
6524 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6525 doc
: /* Interrupt process PROCESS.
6526 PROCESS may be a process, a buffer, or the name of a process or buffer.
6527 No arg or nil means current buffer's process.
6528 Second arg CURRENT-GROUP non-nil means send signal to
6529 the current process-group of the process's controlling terminal
6530 rather than to the process's own process group.
6531 If the process is a shell, this means interrupt current subjob
6532 rather than the shell.
6534 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6535 don't send the signal. */)
6536 (Lisp_Object process
, Lisp_Object current_group
)
6538 process_send_signal (process
, SIGINT
, current_group
, 0);
6542 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6543 doc
: /* Kill process PROCESS. May be process or name of one.
6544 See function `interrupt-process' for more details on usage. */)
6545 (Lisp_Object process
, Lisp_Object current_group
)
6547 process_send_signal (process
, SIGKILL
, current_group
, 0);
6551 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6552 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6553 See function `interrupt-process' for more details on usage. */)
6554 (Lisp_Object process
, Lisp_Object current_group
)
6556 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6560 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6561 doc
: /* Stop process PROCESS. May be process or name of one.
6562 See function `interrupt-process' for more details on usage.
6563 If PROCESS is a network or serial process, inhibit handling of incoming
6565 (Lisp_Object process
, Lisp_Object current_group
)
6567 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6568 || PIPECONN_P (process
)))
6570 struct Lisp_Process
*p
;
6572 p
= XPROCESS (process
);
6573 if (NILP (p
->command
)
6576 FD_CLR (p
->infd
, &input_wait_mask
);
6577 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6579 pset_command (p
, Qt
);
6583 error ("No SIGTSTP support");
6585 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6590 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6591 doc
: /* Continue process PROCESS. May be process or name of one.
6592 See function `interrupt-process' for more details on usage.
6593 If PROCESS is a network or serial process, resume handling of incoming
6595 (Lisp_Object process
, Lisp_Object current_group
)
6597 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)
6598 || PIPECONN_P (process
)))
6600 struct Lisp_Process
*p
;
6602 p
= XPROCESS (process
);
6603 if (EQ (p
->command
, Qt
)
6605 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6607 FD_SET (p
->infd
, &input_wait_mask
);
6608 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6610 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6611 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6612 #else /* not WINDOWSNT */
6613 tcflush (p
->infd
, TCIFLUSH
);
6614 #endif /* not WINDOWSNT */
6616 pset_command (p
, Qnil
);
6620 process_send_signal (process
, SIGCONT
, current_group
, 0);
6622 error ("No SIGCONT support");
6627 /* Return the integer value of the signal whose abbreviation is ABBR,
6628 or a negative number if there is no such signal. */
6630 abbr_to_signal (char const *name
)
6633 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6635 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6638 for (i
= 0; i
< sizeof sigbuf
; i
++)
6640 sigbuf
[i
] = c_toupper (name
[i
]);
6642 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6648 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6649 2, 2, "sProcess (name or number): \nnSignal code: ",
6650 doc
: /* Send PROCESS the signal with code SIGCODE.
6651 PROCESS may also be a number specifying the process id of the
6652 process to signal; in this case, the process need not be a child of
6654 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6655 (Lisp_Object process
, Lisp_Object sigcode
)
6660 if (STRINGP (process
))
6662 Lisp_Object tem
= Fget_process (process
);
6665 Lisp_Object process_number
6666 = string_to_number (SSDATA (process
), 10, 1);
6667 if (NUMBERP (process_number
))
6668 tem
= process_number
;
6672 else if (!NUMBERP (process
))
6673 process
= get_process (process
);
6678 if (NUMBERP (process
))
6679 CONS_TO_INTEGER (process
, pid_t
, pid
);
6682 CHECK_PROCESS (process
);
6683 pid
= XPROCESS (process
)->pid
;
6685 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6688 if (INTEGERP (sigcode
))
6690 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6691 signo
= XINT (sigcode
);
6697 CHECK_SYMBOL (sigcode
);
6698 name
= SSDATA (SYMBOL_NAME (sigcode
));
6700 signo
= abbr_to_signal (name
);
6702 error ("Undefined signal name %s", name
);
6705 return make_number (kill (pid
, signo
));
6708 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6709 doc
: /* Make PROCESS see end-of-file in its input.
6710 EOF comes after any text already sent to it.
6711 PROCESS may be a process, a buffer, the name of a process or buffer, or
6712 nil, indicating the current buffer's process.
6713 If PROCESS is a network connection, or is a process communicating
6714 through a pipe (as opposed to a pty), then you cannot send any more
6715 text to PROCESS after you call this function.
6716 If PROCESS is a serial process, wait until all output written to the
6717 process has been transmitted to the serial port. */)
6718 (Lisp_Object process
)
6721 struct coding_system
*coding
= NULL
;
6724 proc
= get_process (process
);
6726 if (NETCONN_P (proc
))
6727 wait_while_connecting (proc
);
6729 if (DATAGRAM_CONN_P (proc
))
6733 outfd
= XPROCESS (proc
)->outfd
;
6735 coding
= proc_encode_coding_system
[outfd
];
6737 /* Make sure the process is really alive. */
6738 if (XPROCESS (proc
)->raw_status_new
)
6739 update_status (XPROCESS (proc
));
6740 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6741 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6743 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6745 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6746 send_process (proc
, "", 0, Qnil
);
6749 if (XPROCESS (proc
)->pty_flag
)
6750 send_process (proc
, "\004", 1, Qnil
);
6751 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6754 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6755 report_file_error ("Failed tcdrain", Qnil
);
6756 #endif /* not WINDOWSNT */
6757 /* Do nothing on Windows because writes are blocking. */
6761 struct Lisp_Process
*p
= XPROCESS (proc
);
6762 int old_outfd
= p
->outfd
;
6765 #ifdef HAVE_SHUTDOWN
6766 /* If this is a network connection, or socketpair is used
6767 for communication with the subprocess, call shutdown to cause EOF.
6768 (In some old system, shutdown to socketpair doesn't work.
6769 Then we just can't win.) */
6771 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6772 shutdown (old_outfd
, 1);
6774 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6775 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6777 report_file_error ("Opening null device", Qnil
);
6778 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6779 p
->outfd
= new_outfd
;
6781 if (!proc_encode_coding_system
[new_outfd
])
6782 proc_encode_coding_system
[new_outfd
]
6783 = xmalloc (sizeof (struct coding_system
));
6786 *proc_encode_coding_system
[new_outfd
]
6787 = *proc_encode_coding_system
[old_outfd
];
6788 memset (proc_encode_coding_system
[old_outfd
], 0,
6789 sizeof (struct coding_system
));
6792 setup_coding_system (p
->encode_coding_system
,
6793 proc_encode_coding_system
[new_outfd
]);
6798 /* The main Emacs thread records child processes in three places:
6800 - Vprocess_alist, for asynchronous subprocesses, which are child
6801 processes visible to Lisp.
6803 - deleted_pid_list, for child processes invisible to Lisp,
6804 typically because of delete-process. These are recorded so that
6805 the processes can be reaped when they exit, so that the operating
6806 system's process table is not cluttered by zombies.
6808 - the local variable PID in Fcall_process, call_process_cleanup and
6809 call_process_kill, for synchronous subprocesses.
6810 record_unwind_protect is used to make sure this process is not
6811 forgotten: if the user interrupts call-process and the child
6812 process refuses to exit immediately even with two C-g's,
6813 call_process_kill adds PID's contents to deleted_pid_list before
6816 The main Emacs thread invokes waitpid only on child processes that
6817 it creates and that have not been reaped. This avoid races on
6818 platforms such as GTK, where other threads create their own
6819 subprocesses which the main thread should not reap. For example,
6820 if the main thread attempted to reap an already-reaped child, it
6821 might inadvertently reap a GTK-created process that happened to
6822 have the same process ID. */
6824 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6825 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6826 keep track of its own children. GNUstep is similar. */
6828 static void dummy_handler (int sig
) {}
6829 static signal_handler_t
volatile lib_child_handler
;
6831 /* Handle a SIGCHLD signal by looking for known child processes of
6832 Emacs whose status have changed. For each one found, record its
6835 All we do is change the status; we do not run sentinels or print
6836 notifications. That is saved for the next time keyboard input is
6837 done, in order to avoid timing errors.
6839 ** WARNING: this can be called during garbage collection.
6840 Therefore, it must not be fooled by the presence of mark bits in
6843 ** USG WARNING: Although it is not obvious from the documentation
6844 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6845 signal() before executing at least one wait(), otherwise the
6846 handler will be called again, resulting in an infinite loop. The
6847 relevant portion of the documentation reads "SIGCLD signals will be
6848 queued and the signal-catching function will be continually
6849 reentered until the queue is empty". Invoking signal() causes the
6850 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6853 ** Malloc WARNING: This should never call malloc either directly or
6854 indirectly; if it does, that is a bug. */
6857 handle_child_signal (int sig
)
6859 Lisp_Object tail
, proc
;
6861 /* Find the process that signaled us, and record its status. */
6863 /* The process can have been deleted by Fdelete_process, or have
6864 been started asynchronously by Fcall_process. */
6865 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6867 bool all_pids_are_fixnums
6868 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6869 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6870 Lisp_Object head
= XCAR (tail
);
6875 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6878 if (INTEGERP (xpid
))
6879 deleted_pid
= XINT (xpid
);
6881 deleted_pid
= XFLOAT_DATA (xpid
);
6882 if (child_status_changed (deleted_pid
, 0, 0))
6884 if (STRINGP (XCDR (head
)))
6885 unlink (SSDATA (XCDR (head
)));
6886 XSETCAR (tail
, Qnil
);
6891 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6892 FOR_EACH_PROCESS (tail
, proc
)
6894 struct Lisp_Process
*p
= XPROCESS (proc
);
6898 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6900 /* Change the status of the process that was found. */
6901 p
->tick
= ++process_tick
;
6902 p
->raw_status
= status
;
6903 p
->raw_status_new
= 1;
6905 /* If process has terminated, stop waiting for its output. */
6906 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6908 bool clear_desc_flag
= 0;
6911 clear_desc_flag
= 1;
6913 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6914 if (clear_desc_flag
)
6916 FD_CLR (p
->infd
, &input_wait_mask
);
6917 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6923 lib_child_handler (sig
);
6924 #ifdef NS_IMPL_GNUSTEP
6925 /* NSTask in GNUstep sets its child handler each time it is called.
6926 So we must re-set ours. */
6927 catch_child_signal ();
6932 deliver_child_signal (int sig
)
6934 deliver_process_signal (sig
, handle_child_signal
);
6939 exec_sentinel_error_handler (Lisp_Object error_val
)
6941 cmd_error_internal (error_val
, "error in process sentinel: ");
6943 update_echo_area ();
6944 Fsleep_for (make_number (2), Qnil
);
6949 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6951 Lisp_Object sentinel
, odeactivate
;
6952 struct Lisp_Process
*p
= XPROCESS (proc
);
6953 ptrdiff_t count
= SPECPDL_INDEX ();
6954 bool outer_running_asynch_code
= running_asynch_code
;
6955 int waiting
= waiting_for_user_input_p
;
6957 if (inhibit_sentinels
)
6960 odeactivate
= Vdeactivate_mark
;
6962 Lisp_Object obuffer
, okeymap
;
6963 XSETBUFFER (obuffer
, current_buffer
);
6964 okeymap
= BVAR (current_buffer
, keymap
);
6967 /* There's no good reason to let sentinels change the current
6968 buffer, and many callers of accept-process-output, sit-for, and
6969 friends don't expect current-buffer to be changed from under them. */
6970 record_unwind_current_buffer ();
6972 sentinel
= p
->sentinel
;
6974 /* Inhibit quit so that random quits don't screw up a running filter. */
6975 specbind (Qinhibit_quit
, Qt
);
6976 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6978 /* In case we get recursively called,
6979 and we already saved the match data nonrecursively,
6980 save the same match data in safely recursive fashion. */
6981 if (outer_running_asynch_code
)
6984 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6985 restore_search_regs ();
6986 record_unwind_save_match_data ();
6987 Fset_match_data (tem
, Qt
);
6990 /* For speed, if a search happens within this code,
6991 save the match data in a special nonrecursive fashion. */
6992 running_asynch_code
= 1;
6994 internal_condition_case_1 (read_process_output_call
,
6995 list3 (sentinel
, proc
, reason
),
6996 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6997 exec_sentinel_error_handler
);
6999 /* If we saved the match data nonrecursively, restore it now. */
7000 restore_search_regs ();
7001 running_asynch_code
= outer_running_asynch_code
;
7003 Vdeactivate_mark
= odeactivate
;
7005 /* Restore waiting_for_user_input_p as it was
7006 when we were called, in case the filter clobbered it. */
7007 waiting_for_user_input_p
= waiting
;
7010 if (! EQ (Fcurrent_buffer (), obuffer
)
7011 || ! EQ (current_buffer
->keymap
, okeymap
))
7013 /* But do it only if the caller is actually going to read events.
7014 Otherwise there's no need to make him wake up, and it could
7015 cause trouble (for example it would make sit_for return). */
7016 if (waiting_for_user_input_p
== -1)
7017 record_asynch_buffer_change ();
7019 unbind_to (count
, Qnil
);
7022 /* Report all recent events of a change in process status
7023 (either run the sentinel or output a message).
7024 This is usually done while Emacs is waiting for keyboard input
7025 but can be done at other times.
7027 Return positive if any input was received from WAIT_PROC (or from
7028 any process if WAIT_PROC is null), zero if input was attempted but
7029 none received, and negative if we didn't even try. */
7032 status_notify (struct Lisp_Process
*deleting_process
,
7033 struct Lisp_Process
*wait_proc
)
7036 Lisp_Object tail
, msg
;
7037 int got_some_output
= -1;
7042 /* Set this now, so that if new processes are created by sentinels
7043 that we run, we get called again to handle their status changes. */
7044 update_tick
= process_tick
;
7046 FOR_EACH_PROCESS (tail
, proc
)
7049 register struct Lisp_Process
*p
= XPROCESS (proc
);
7051 if (p
->tick
!= p
->update_tick
)
7053 p
->update_tick
= p
->tick
;
7055 /* If process is still active, read any output that remains. */
7056 while (! EQ (p
->filter
, Qt
)
7057 && ! EQ (p
->status
, Qconnect
)
7058 && ! EQ (p
->status
, Qlisten
)
7059 /* Network or serial process not stopped: */
7060 && ! EQ (p
->command
, Qt
)
7062 && p
!= deleting_process
)
7064 int nread
= read_process_output (proc
, p
->infd
);
7065 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
))
7066 && got_some_output
< nread
)
7067 got_some_output
= nread
;
7072 /* Get the text to use for the message. */
7073 if (p
->raw_status_new
)
7075 msg
= status_message (p
);
7077 /* If process is terminated, deactivate it or delete it. */
7079 if (CONSP (p
->status
))
7080 symbol
= XCAR (p
->status
);
7082 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
7083 || EQ (symbol
, Qclosed
))
7085 if (delete_exited_processes
)
7086 remove_process (proc
);
7088 deactivate_process (proc
);
7091 /* The actions above may have further incremented p->tick.
7092 So set p->update_tick again so that an error in the sentinel will
7093 not cause this code to be run again. */
7094 p
->update_tick
= p
->tick
;
7095 /* Now output the message suitably. */
7096 exec_sentinel (proc
, msg
);
7097 if (BUFFERP (p
->buffer
))
7098 /* In case it uses %s in mode-line-format. */
7099 bset_update_mode_line (XBUFFER (p
->buffer
));
7103 return got_some_output
;
7106 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
7107 Sinternal_default_process_sentinel
, 2, 2, 0,
7108 doc
: /* Function used as default sentinel for processes.
7109 This inserts a status message into the process's buffer, if there is one. */)
7110 (Lisp_Object proc
, Lisp_Object msg
)
7112 Lisp_Object buffer
, symbol
;
7113 struct Lisp_Process
*p
;
7114 CHECK_PROCESS (proc
);
7115 p
= XPROCESS (proc
);
7119 symbol
= XCAR (symbol
);
7121 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
7124 struct buffer
*old
= current_buffer
;
7125 ptrdiff_t opoint
, opoint_byte
;
7126 ptrdiff_t before
, before_byte
;
7128 /* Avoid error if buffer is deleted
7129 (probably that's why the process is dead, too). */
7130 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
7132 Fset_buffer (buffer
);
7134 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
7135 msg
= (code_convert_string_norecord
7136 (msg
, Vlocale_coding_system
, 1));
7139 opoint_byte
= PT_BYTE
;
7140 /* Insert new output into buffer
7141 at the current end-of-output marker,
7142 thus preserving logical ordering of input and output. */
7143 if (XMARKER (p
->mark
)->buffer
)
7144 Fgoto_char (p
->mark
);
7146 SET_PT_BOTH (ZV
, ZV_BYTE
);
7149 before_byte
= PT_BYTE
;
7151 tem
= BVAR (current_buffer
, read_only
);
7152 bset_read_only (current_buffer
, Qnil
);
7153 insert_string ("\nProcess ");
7154 { /* FIXME: temporary kludge. */
7155 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
7156 insert_string (" ");
7158 bset_read_only (current_buffer
, tem
);
7159 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
7161 if (opoint
>= before
)
7162 SET_PT_BOTH (opoint
+ (PT
- before
),
7163 opoint_byte
+ (PT_BYTE
- before_byte
));
7165 SET_PT_BOTH (opoint
, opoint_byte
);
7167 set_buffer_internal (old
);
7173 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
7174 Sset_process_coding_system
, 1, 3, 0,
7175 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
7176 DECODING will be used to decode subprocess output and ENCODING to
7177 encode subprocess input. */)
7178 (Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
7180 CHECK_PROCESS (process
);
7182 struct Lisp_Process
*p
= XPROCESS (process
);
7184 Fcheck_coding_system (decoding
);
7185 Fcheck_coding_system (encoding
);
7186 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
7187 pset_decode_coding_system (p
, decoding
);
7188 pset_encode_coding_system (p
, encoding
);
7190 /* If the sockets haven't been set up yet, the final setup part of
7191 this will be called asynchronously. */
7192 if (p
->infd
< 0 || p
->outfd
< 0)
7195 setup_process_coding_systems (process
);
7200 DEFUN ("process-coding-system",
7201 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
7202 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7203 (register Lisp_Object process
)
7205 CHECK_PROCESS (process
);
7206 return Fcons (XPROCESS (process
)->decode_coding_system
,
7207 XPROCESS (process
)->encode_coding_system
);
7210 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
7211 Sset_process_filter_multibyte
, 2, 2, 0,
7212 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
7213 If FLAG is non-nil, the filter is given multibyte strings.
7214 If FLAG is nil, the filter is given unibyte strings. In this case,
7215 all character code conversion except for end-of-line conversion is
7217 (Lisp_Object process
, Lisp_Object flag
)
7219 CHECK_PROCESS (process
);
7221 struct Lisp_Process
*p
= XPROCESS (process
);
7223 pset_decode_coding_system
7224 (p
, raw_text_coding_system (p
->decode_coding_system
));
7226 /* If the sockets haven't been set up yet, the final setup part of
7227 this will be called asynchronously. */
7228 if (p
->infd
< 0 || p
->outfd
< 0)
7231 setup_process_coding_systems (process
);
7236 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
7237 Sprocess_filter_multibyte_p
, 1, 1, 0,
7238 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7239 (Lisp_Object process
)
7241 CHECK_PROCESS (process
);
7242 struct Lisp_Process
*p
= XPROCESS (process
);
7245 struct coding_system
*coding
= proc_decode_coding_system
[p
->infd
];
7246 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
7255 add_gpm_wait_descriptor (int desc
)
7257 add_keyboard_wait_descriptor (desc
);
7261 delete_gpm_wait_descriptor (int desc
)
7263 delete_keyboard_wait_descriptor (desc
);
7268 # ifdef USABLE_SIGIO
7270 /* Return true if *MASK has a bit set
7271 that corresponds to one of the keyboard input descriptors. */
7274 keyboard_bit_set (fd_set
*mask
)
7278 for (fd
= 0; fd
<= max_input_desc
; fd
++)
7279 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
7280 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
7287 #else /* not subprocesses */
7289 /* Defined in msdos.c. */
7290 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
7291 struct timespec
*, void *);
7293 /* Implementation of wait_reading_process_output, assuming that there
7294 are no subprocesses. Used only by the MS-DOS build.
7296 Wait for timeout to elapse and/or keyboard input to be available.
7300 If negative, gobble data immediately available but don't wait for any.
7303 an additional duration to wait, measured in nanoseconds
7304 If TIME_LIMIT is zero, then:
7305 If NSECS == 0, there is no limit.
7306 If NSECS > 0, the timeout consists of NSECS only.
7307 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7310 0 to ignore keyboard input, or
7311 1 to return when input is available, or
7312 -1 means caller will actually read the input, so don't throw to
7315 see full version for other parameters. We know that wait_proc will
7316 always be NULL, since `subprocesses' isn't defined.
7318 DO_DISPLAY means redisplay should be done to show subprocess
7319 output that arrives.
7321 Return -1 signifying we got no output and did not try. */
7324 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
7326 Lisp_Object wait_for_cell
,
7327 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
7330 struct timespec end_time
, timeout
;
7331 enum { MINIMUM
= -1, TIMEOUT
, INFINITY
} wait
;
7333 if (TYPE_MAXIMUM (time_t) < time_limit
)
7334 time_limit
= TYPE_MAXIMUM (time_t);
7336 if (time_limit
< 0 || nsecs
< 0)
7338 else if (time_limit
> 0 || nsecs
> 0)
7341 end_time
= timespec_add (current_timespec (),
7342 make_timespec (time_limit
, nsecs
));
7347 /* Turn off periodic alarms (in case they are in use)
7348 and then turn off any other atimers,
7349 because the select emulator uses alarms. */
7351 turn_on_atimers (0);
7355 bool timeout_reduced_for_timers
= false;
7356 fd_set waitchannels
;
7359 /* If calling from keyboard input, do not quit
7360 since we want to return C-g as an input character.
7361 Otherwise, do pending quit if requested. */
7365 /* Exit now if the cell we're waiting for became non-nil. */
7366 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7369 /* Compute time from now till when time limit is up. */
7370 /* Exit if already run out. */
7371 if (wait
== TIMEOUT
)
7373 struct timespec now
= current_timespec ();
7374 if (timespec_cmp (end_time
, now
) <= 0)
7376 timeout
= timespec_sub (end_time
, now
);
7379 timeout
= make_timespec (wait
< TIMEOUT
? 0 : 100000, 0);
7381 /* If our caller will not immediately handle keyboard events,
7382 run timer events directly.
7383 (Callers that will immediately read keyboard events
7384 call timer_delay on their own.) */
7385 if (NILP (wait_for_cell
))
7387 struct timespec timer_delay
;
7391 unsigned old_timers_run
= timers_run
;
7392 timer_delay
= timer_check ();
7393 if (timers_run
!= old_timers_run
&& do_display
)
7394 /* We must retry, since a timer may have requeued itself
7395 and that could alter the time delay. */
7396 redisplay_preserve_echo_area (14);
7400 while (!detect_input_pending ());
7402 /* If there is unread keyboard input, also return. */
7404 && requeued_events_pending_p ())
7407 if (timespec_valid_p (timer_delay
))
7409 if (timespec_cmp (timer_delay
, timeout
) < 0)
7411 timeout
= timer_delay
;
7412 timeout_reduced_for_timers
= true;
7417 /* Cause C-g and alarm signals to take immediate action,
7418 and cause input available signals to zero out timeout. */
7420 set_waiting_for_input (&timeout
);
7422 /* If a frame has been newly mapped and needs updating,
7423 reprocess its display stuff. */
7424 if (frame_garbaged
&& do_display
)
7426 clear_waiting_for_input ();
7427 redisplay_preserve_echo_area (15);
7429 set_waiting_for_input (&timeout
);
7432 /* Wait till there is something to do. */
7433 FD_ZERO (&waitchannels
);
7434 if (read_kbd
&& detect_input_pending ())
7438 if (read_kbd
|| !NILP (wait_for_cell
))
7439 FD_SET (0, &waitchannels
);
7440 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7445 /* Make C-g and alarm signals set flags again. */
7446 clear_waiting_for_input ();
7448 /* If we woke up due to SIGWINCH, actually change size now. */
7449 do_pending_window_change (0);
7451 if (wait
< INFINITY
&& nfds
== 0 && ! timeout_reduced_for_timers
)
7452 /* We waited the full specified time, so return now. */
7457 /* If the system call was interrupted, then go around the
7459 if (xerrno
== EINTR
)
7460 FD_ZERO (&waitchannels
);
7462 report_file_errno ("Failed select", Qnil
, xerrno
);
7465 /* Check for keyboard input. */
7468 && detect_input_pending_run_timers (do_display
))
7470 swallow_events (do_display
);
7471 if (detect_input_pending_run_timers (do_display
))
7475 /* If there is unread keyboard input, also return. */
7477 && requeued_events_pending_p ())
7480 /* If wait_for_cell. check for keyboard input
7481 but don't run any timers.
7482 ??? (It seems wrong to me to check for keyboard
7483 input at all when wait_for_cell, but the code
7484 has been this way since July 1994.
7485 Try changing this after version 19.31.) */
7486 if (! NILP (wait_for_cell
)
7487 && detect_input_pending ())
7489 swallow_events (do_display
);
7490 if (detect_input_pending ())
7494 /* Exit now if the cell we're waiting for became non-nil. */
7495 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7504 #endif /* not subprocesses */
7506 /* The following functions are needed even if async subprocesses are
7507 not supported. Some of them are no-op stubs in that case. */
7511 /* Add FD, which is a descriptor returned by timerfd_create,
7512 to the set of non-keyboard input descriptors. */
7515 add_timer_wait_descriptor (int fd
)
7517 FD_SET (fd
, &input_wait_mask
);
7518 FD_SET (fd
, &non_keyboard_wait_mask
);
7519 FD_SET (fd
, &non_process_wait_mask
);
7520 fd_callback_info
[fd
].func
= timerfd_callback
;
7521 fd_callback_info
[fd
].data
= NULL
;
7522 fd_callback_info
[fd
].condition
|= FOR_READ
;
7523 if (fd
> max_input_desc
)
7524 max_input_desc
= fd
;
7527 #endif /* HAVE_TIMERFD */
7529 /* Add DESC to the set of keyboard input descriptors. */
7532 add_keyboard_wait_descriptor (int desc
)
7534 #ifdef subprocesses /* Actually means "not MSDOS". */
7535 FD_SET (desc
, &input_wait_mask
);
7536 FD_SET (desc
, &non_process_wait_mask
);
7537 if (desc
> max_input_desc
)
7538 max_input_desc
= desc
;
7542 /* From now on, do not expect DESC to give keyboard input. */
7545 delete_keyboard_wait_descriptor (int desc
)
7548 FD_CLR (desc
, &input_wait_mask
);
7549 FD_CLR (desc
, &non_process_wait_mask
);
7550 delete_input_desc (desc
);
7554 /* Setup coding systems of PROCESS. */
7557 setup_process_coding_systems (Lisp_Object process
)
7560 struct Lisp_Process
*p
= XPROCESS (process
);
7562 int outch
= p
->outfd
;
7563 Lisp_Object coding_system
;
7565 if (inch
< 0 || outch
< 0)
7568 if (!proc_decode_coding_system
[inch
])
7569 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7570 coding_system
= p
->decode_coding_system
;
7571 if (EQ (p
->filter
, Qinternal_default_process_filter
)
7572 && BUFFERP (p
->buffer
))
7574 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7575 coding_system
= raw_text_coding_system (coding_system
);
7577 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7579 if (!proc_encode_coding_system
[outch
])
7580 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7581 setup_coding_system (p
->encode_coding_system
,
7582 proc_encode_coding_system
[outch
]);
7586 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7587 doc
: /* Return the (or a) live process associated with BUFFER.
7588 BUFFER may be a buffer or the name of one.
7589 Return nil if all processes associated with BUFFER have been
7590 deleted or killed. */)
7591 (register Lisp_Object buffer
)
7594 register Lisp_Object buf
, tail
, proc
;
7596 if (NILP (buffer
)) return Qnil
;
7597 buf
= Fget_buffer (buffer
);
7598 if (NILP (buf
)) return Qnil
;
7600 FOR_EACH_PROCESS (tail
, proc
)
7601 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7603 #endif /* subprocesses */
7607 DEFUN ("process-inherit-coding-system-flag",
7608 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7610 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7611 If this flag is t, `buffer-file-coding-system' of the buffer
7612 associated with PROCESS will inherit the coding system used to decode
7613 the process output. */)
7614 (register Lisp_Object process
)
7617 CHECK_PROCESS (process
);
7618 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7620 /* Ignore the argument and return the value of
7621 inherit-process-coding-system. */
7622 return inherit_process_coding_system
? Qt
: Qnil
;
7626 /* Kill all processes associated with `buffer'.
7627 If `buffer' is nil, kill all processes. */
7630 kill_buffer_processes (Lisp_Object buffer
)
7633 Lisp_Object tail
, proc
;
7635 FOR_EACH_PROCESS (tail
, proc
)
7636 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7638 if (NETCONN_P (proc
) || SERIALCONN_P (proc
) || PIPECONN_P (proc
))
7639 Fdelete_process (proc
);
7640 else if (XPROCESS (proc
)->infd
>= 0)
7641 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7643 #else /* subprocesses */
7644 /* Since we have no subprocesses, this does nothing. */
7645 #endif /* subprocesses */
7648 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7649 Swaiting_for_user_input_p
, 0, 0, 0,
7650 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7651 This is intended for use by asynchronous process output filters and sentinels. */)
7655 return (waiting_for_user_input_p
? Qt
: Qnil
);
7661 /* Stop reading input from keyboard sources. */
7664 hold_keyboard_input (void)
7669 /* Resume reading input from keyboard sources. */
7672 unhold_keyboard_input (void)
7677 /* Return true if keyboard input is on hold, zero otherwise. */
7680 kbd_on_hold_p (void)
7682 return kbd_is_on_hold
;
7686 /* Enumeration of and access to system processes a-la ps(1). */
7688 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7690 doc
: /* Return a list of numerical process IDs of all running processes.
7691 If this functionality is unsupported, return nil.
7693 See `process-attributes' for getting attributes of a process given its ID. */)
7696 return list_system_processes ();
7699 DEFUN ("process-attributes", Fprocess_attributes
,
7700 Sprocess_attributes
, 1, 1, 0,
7701 doc
: /* Return attributes of the process given by its PID, a number.
7703 Value is an alist where each element is a cons cell of the form
7707 If this functionality is unsupported, the value is nil.
7709 See `list-system-processes' for getting a list of all process IDs.
7711 The KEYs of the attributes that this function may return are listed
7712 below, together with the type of the associated VALUE (in parentheses).
7713 Not all platforms support all of these attributes; unsupported
7714 attributes will not appear in the returned alist.
7715 Unless explicitly indicated otherwise, numbers can have either
7716 integer or floating point values.
7718 euid -- Effective user User ID of the process (number)
7719 user -- User name corresponding to euid (string)
7720 egid -- Effective user Group ID of the process (number)
7721 group -- Group name corresponding to egid (string)
7722 comm -- Command name (executable name only) (string)
7723 state -- Process state code, such as "S", "R", or "T" (string)
7724 ppid -- Parent process ID (number)
7725 pgrp -- Process group ID (number)
7726 sess -- Session ID, i.e. process ID of session leader (number)
7727 ttname -- Controlling tty name (string)
7728 tpgid -- ID of foreground process group on the process's tty (number)
7729 minflt -- number of minor page faults (number)
7730 majflt -- number of major page faults (number)
7731 cminflt -- cumulative number of minor page faults (number)
7732 cmajflt -- cumulative number of major page faults (number)
7733 utime -- user time used by the process, in (current-time) format,
7734 which is a list of integers (HIGH LOW USEC PSEC)
7735 stime -- system time used by the process (current-time)
7736 time -- sum of utime and stime (current-time)
7737 cutime -- user time used by the process and its children (current-time)
7738 cstime -- system time used by the process and its children (current-time)
7739 ctime -- sum of cutime and cstime (current-time)
7740 pri -- priority of the process (number)
7741 nice -- nice value of the process (number)
7742 thcount -- process thread count (number)
7743 start -- time the process started (current-time)
7744 vsize -- virtual memory size of the process in KB's (number)
7745 rss -- resident set size of the process in KB's (number)
7746 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7747 pcpu -- percents of CPU time used by the process (floating-point number)
7748 pmem -- percents of total physical memory used by process's resident set
7749 (floating-point number)
7750 args -- command line which invoked the process (string). */)
7753 return system_process_attributes (pid
);
7757 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7758 Invoke this after init_process_emacs, and after glib and/or GNUstep
7759 futz with the SIGCHLD handler, but before Emacs forks any children.
7760 This function's caller should block SIGCHLD. */
7763 catch_child_signal (void)
7765 struct sigaction action
, old_action
;
7767 emacs_sigaction_init (&action
, deliver_child_signal
);
7768 block_child_signal (&oldset
);
7769 sigaction (SIGCHLD
, &action
, &old_action
);
7770 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7771 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7773 if (old_action
.sa_handler
!= deliver_child_signal
)
7775 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7777 : old_action
.sa_handler
);
7778 unblock_child_signal (&oldset
);
7780 #endif /* subprocesses */
7783 /* This is not called "init_process" because that is the name of a
7784 Mach system call, so it would cause problems on Darwin systems. */
7786 init_process_emacs (void)
7791 inhibit_sentinels
= 0;
7794 if (! noninteractive
|| initialized
)
7797 #if defined HAVE_GLIB && !defined WINDOWSNT
7798 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7799 this should always fail, but is enough to initialize glib's
7800 private SIGCHLD handler, allowing catch_child_signal to copy
7801 it into lib_child_handler. */
7802 g_source_unref (g_child_watch_source_new (getpid ()));
7804 catch_child_signal ();
7807 FD_ZERO (&input_wait_mask
);
7808 FD_ZERO (&non_keyboard_wait_mask
);
7809 FD_ZERO (&non_process_wait_mask
);
7810 FD_ZERO (&write_mask
);
7811 max_process_desc
= max_input_desc
= -1;
7812 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7814 #ifdef NON_BLOCKING_CONNECT
7815 FD_ZERO (&connect_wait_mask
);
7816 num_pending_connects
= 0;
7819 process_output_delay_count
= 0;
7820 process_output_skip
= 0;
7822 /* Don't do this, it caused infinite select loops. The display
7823 method should call add_keyboard_wait_descriptor on stdin if it
7826 FD_SET (0, &input_wait_mask
);
7829 Vprocess_alist
= Qnil
;
7830 deleted_pid_list
= Qnil
;
7831 for (i
= 0; i
< FD_SETSIZE
; i
++)
7833 chan_process
[i
] = Qnil
;
7834 proc_buffered_char
[i
] = -1;
7836 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7837 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7838 #ifdef DATAGRAM_SOCKETS
7839 memset (datagram_address
, 0, sizeof datagram_address
);
7842 #if defined (DARWIN_OS)
7843 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7844 processes. As such, we only change the default value. */
7847 char const *release
= (STRINGP (Voperating_system_release
)
7848 ? SSDATA (Voperating_system_release
)
7850 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7851 Vprocess_connection_type
= Qnil
;
7855 #endif /* subprocesses */
7860 syms_of_process (void)
7864 DEFSYM (Qprocessp
, "processp");
7865 DEFSYM (Qrun
, "run");
7866 DEFSYM (Qstop
, "stop");
7867 DEFSYM (Qsignal
, "signal");
7869 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7872 DEFSYM (Qopen
, "open");
7873 DEFSYM (Qclosed
, "closed");
7874 DEFSYM (Qconnect
, "connect");
7875 DEFSYM (Qfailed
, "failed");
7876 DEFSYM (Qlisten
, "listen");
7877 DEFSYM (Qlocal
, "local");
7878 DEFSYM (Qipv4
, "ipv4");
7880 DEFSYM (Qipv6
, "ipv6");
7882 DEFSYM (Qdatagram
, "datagram");
7883 DEFSYM (Qseqpacket
, "seqpacket");
7885 DEFSYM (QCport
, ":port");
7886 DEFSYM (QCspeed
, ":speed");
7887 DEFSYM (QCprocess
, ":process");
7889 DEFSYM (QCbytesize
, ":bytesize");
7890 DEFSYM (QCstopbits
, ":stopbits");
7891 DEFSYM (QCparity
, ":parity");
7892 DEFSYM (Qodd
, "odd");
7893 DEFSYM (Qeven
, "even");
7894 DEFSYM (QCflowcontrol
, ":flowcontrol");
7897 DEFSYM (QCsummary
, ":summary");
7899 DEFSYM (Qreal
, "real");
7900 DEFSYM (Qnetwork
, "network");
7901 DEFSYM (Qserial
, "serial");
7902 DEFSYM (Qpipe
, "pipe");
7903 DEFSYM (QCbuffer
, ":buffer");
7904 DEFSYM (QChost
, ":host");
7905 DEFSYM (QCservice
, ":service");
7906 DEFSYM (QClocal
, ":local");
7907 DEFSYM (QCremote
, ":remote");
7908 DEFSYM (QCcoding
, ":coding");
7909 DEFSYM (QCserver
, ":server");
7910 DEFSYM (QCnowait
, ":nowait");
7911 DEFSYM (QCsentinel
, ":sentinel");
7912 DEFSYM (QCtls_parameters
, ":tls-parameters");
7913 DEFSYM (Qnsm_verify_connection
, "nsm-verify-connection");
7914 DEFSYM (QClog
, ":log");
7915 DEFSYM (QCnoquery
, ":noquery");
7916 DEFSYM (QCstop
, ":stop");
7917 DEFSYM (QCplist
, ":plist");
7918 DEFSYM (QCcommand
, ":command");
7919 DEFSYM (QCconnection_type
, ":connection-type");
7920 DEFSYM (QCstderr
, ":stderr");
7921 DEFSYM (Qpty
, "pty");
7922 DEFSYM (Qpipe
, "pipe");
7924 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7926 staticpro (&Vprocess_alist
);
7927 staticpro (&deleted_pid_list
);
7929 #endif /* subprocesses */
7931 DEFSYM (QCname
, ":name");
7932 DEFSYM (QCtype
, ":type");
7934 DEFSYM (Qeuid
, "euid");
7935 DEFSYM (Qegid
, "egid");
7936 DEFSYM (Quser
, "user");
7937 DEFSYM (Qgroup
, "group");
7938 DEFSYM (Qcomm
, "comm");
7939 DEFSYM (Qstate
, "state");
7940 DEFSYM (Qppid
, "ppid");
7941 DEFSYM (Qpgrp
, "pgrp");
7942 DEFSYM (Qsess
, "sess");
7943 DEFSYM (Qttname
, "ttname");
7944 DEFSYM (Qtpgid
, "tpgid");
7945 DEFSYM (Qminflt
, "minflt");
7946 DEFSYM (Qmajflt
, "majflt");
7947 DEFSYM (Qcminflt
, "cminflt");
7948 DEFSYM (Qcmajflt
, "cmajflt");
7949 DEFSYM (Qutime
, "utime");
7950 DEFSYM (Qstime
, "stime");
7951 DEFSYM (Qtime
, "time");
7952 DEFSYM (Qcutime
, "cutime");
7953 DEFSYM (Qcstime
, "cstime");
7954 DEFSYM (Qctime
, "ctime");
7956 DEFSYM (Qinternal_default_process_sentinel
,
7957 "internal-default-process-sentinel");
7958 DEFSYM (Qinternal_default_process_filter
,
7959 "internal-default-process-filter");
7961 DEFSYM (Qpri
, "pri");
7962 DEFSYM (Qnice
, "nice");
7963 DEFSYM (Qthcount
, "thcount");
7964 DEFSYM (Qstart
, "start");
7965 DEFSYM (Qvsize
, "vsize");
7966 DEFSYM (Qrss
, "rss");
7967 DEFSYM (Qetime
, "etime");
7968 DEFSYM (Qpcpu
, "pcpu");
7969 DEFSYM (Qpmem
, "pmem");
7970 DEFSYM (Qargs
, "args");
7972 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7973 doc
: /* Non-nil means delete processes immediately when they exit.
7974 A value of nil means don't delete them until `list-processes' is run. */);
7976 delete_exited_processes
= 1;
7979 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7980 doc
: /* Control type of device used to communicate with subprocesses.
7981 Values are nil to use a pipe, or t or `pty' to use a pty.
7982 The value has no effect if the system has no ptys or if all ptys are busy:
7983 then a pipe is used in any case.
7984 The value takes effect when `start-process' is called. */);
7985 Vprocess_connection_type
= Qt
;
7987 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7988 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7989 On some systems, when Emacs reads the output from a subprocess, the output data
7990 is read in very small blocks, potentially resulting in very poor performance.
7991 This behavior can be remedied to some extent by setting this variable to a
7992 non-nil value, as it will automatically delay reading from such processes, to
7993 allow them to produce more output before Emacs tries to read it.
7994 If the value is t, the delay is reset after each write to the process; any other
7995 non-nil value means that the delay is not reset on write.
7996 The variable takes effect when `start-process' is called. */);
7997 Vprocess_adaptive_read_buffering
= Qt
;
7999 defsubr (&Sprocessp
);
8000 defsubr (&Sget_process
);
8001 defsubr (&Sdelete_process
);
8002 defsubr (&Sprocess_status
);
8003 defsubr (&Sprocess_exit_status
);
8004 defsubr (&Sprocess_id
);
8005 defsubr (&Sprocess_name
);
8006 defsubr (&Sprocess_tty_name
);
8007 defsubr (&Sprocess_command
);
8008 defsubr (&Sset_process_buffer
);
8009 defsubr (&Sprocess_buffer
);
8010 defsubr (&Sprocess_mark
);
8011 defsubr (&Sset_process_filter
);
8012 defsubr (&Sprocess_filter
);
8013 defsubr (&Sset_process_sentinel
);
8014 defsubr (&Sprocess_sentinel
);
8015 defsubr (&Sset_process_window_size
);
8016 defsubr (&Sset_process_inherit_coding_system_flag
);
8017 defsubr (&Sset_process_query_on_exit_flag
);
8018 defsubr (&Sprocess_query_on_exit_flag
);
8019 defsubr (&Sprocess_contact
);
8020 defsubr (&Sprocess_plist
);
8021 defsubr (&Sset_process_plist
);
8022 defsubr (&Sprocess_list
);
8023 defsubr (&Smake_process
);
8024 defsubr (&Smake_pipe_process
);
8025 defsubr (&Sserial_process_configure
);
8026 defsubr (&Smake_serial_process
);
8027 defsubr (&Sset_network_process_option
);
8028 defsubr (&Smake_network_process
);
8029 defsubr (&Sformat_network_address
);
8030 defsubr (&Snetwork_interface_list
);
8031 defsubr (&Snetwork_interface_info
);
8032 #ifdef DATAGRAM_SOCKETS
8033 defsubr (&Sprocess_datagram_address
);
8034 defsubr (&Sset_process_datagram_address
);
8036 defsubr (&Saccept_process_output
);
8037 defsubr (&Sprocess_send_region
);
8038 defsubr (&Sprocess_send_string
);
8039 defsubr (&Sinterrupt_process
);
8040 defsubr (&Skill_process
);
8041 defsubr (&Squit_process
);
8042 defsubr (&Sstop_process
);
8043 defsubr (&Scontinue_process
);
8044 defsubr (&Sprocess_running_child_p
);
8045 defsubr (&Sprocess_send_eof
);
8046 defsubr (&Ssignal_process
);
8047 defsubr (&Swaiting_for_user_input_p
);
8048 defsubr (&Sprocess_type
);
8049 defsubr (&Sinternal_default_process_sentinel
);
8050 defsubr (&Sinternal_default_process_filter
);
8051 defsubr (&Sset_process_coding_system
);
8052 defsubr (&Sprocess_coding_system
);
8053 defsubr (&Sset_process_filter_multibyte
);
8054 defsubr (&Sprocess_filter_multibyte_p
);
8056 #endif /* subprocesses */
8058 defsubr (&Sget_buffer_process
);
8059 defsubr (&Sprocess_inherit_coding_system_flag
);
8060 defsubr (&Slist_system_processes
);
8061 defsubr (&Sprocess_attributes
);
8064 Lisp_Object subfeatures
= Qnil
;
8065 const struct socket_options
*sopt
;
8067 #define ADD_SUBFEATURE(key, val) \
8068 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8070 #ifdef NON_BLOCKING_CONNECT
8071 ADD_SUBFEATURE (QCnowait
, Qt
);
8073 #ifdef DATAGRAM_SOCKETS
8074 ADD_SUBFEATURE (QCtype
, Qdatagram
);
8076 #ifdef HAVE_SEQPACKET
8077 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
8079 #ifdef HAVE_LOCAL_SOCKETS
8080 ADD_SUBFEATURE (QCfamily
, Qlocal
);
8082 ADD_SUBFEATURE (QCfamily
, Qipv4
);
8084 ADD_SUBFEATURE (QCfamily
, Qipv6
);
8086 #ifdef HAVE_GETSOCKNAME
8087 ADD_SUBFEATURE (QCservice
, Qt
);
8089 ADD_SUBFEATURE (QCserver
, Qt
);
8091 for (sopt
= socket_options
; sopt
->name
; sopt
++)
8092 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
8094 Fprovide (intern_c_string ("make-network-process"), subfeatures
);