1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 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/>. */
24 #define PROCESS_INLINE EXTERN_INLINE
28 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
36 /* Only MS-DOS does not define `subprocesses'. */
39 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
44 /* Are local (unix) sockets supported? */
45 #if defined (HAVE_SYS_UN_H)
46 #if !defined (AF_LOCAL) && defined (AF_UNIX)
47 #define AF_LOCAL AF_UNIX
50 #define HAVE_LOCAL_SOCKETS
55 #include <sys/ioctl.h>
56 #if defined (HAVE_NET_IF_H)
58 #endif /* HAVE_NET_IF_H */
60 #if defined (HAVE_IFADDRS_H)
61 /* Must be after net/if.h */
64 /* We only use structs from this header when we use getifaddrs. */
65 #if defined (HAVE_NET_IF_DL_H)
66 #include <net/if_dl.h>
76 # include <sys/stream.h>
77 # include <sys/stropts.h>
81 #include <arpa/nameser.h>
97 #endif /* subprocesses */
103 #include "character.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
123 #ifdef HAVE_WINDOW_SYSTEM
125 #endif /* HAVE_WINDOW_SYSTEM */
128 #include "xgselect.h"
135 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
136 EMACS_TIME
*, void *);
140 # define SOCK_CLOEXEC 0
145 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
148 close_on_exec (int fd
)
151 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
156 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
158 return close_on_exec (accept (sockfd
, addr
, addrlen
));
162 process_socket (int domain
, int type
, int protocol
)
164 return close_on_exec (socket (domain
, type
, protocol
));
167 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
170 /* Work around GCC 4.7.0 bug with strict overflow checking; see
171 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
172 These lines can be removed once the GCC bug is fixed. */
173 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
174 # pragma GCC diagnostic ignored "-Wstrict-overflow"
177 Lisp_Object Qeuid
, Qegid
, Qcomm
, Qstate
, Qppid
, Qpgrp
, Qsess
, Qttname
, Qtpgid
;
178 Lisp_Object Qminflt
, Qmajflt
, Qcminflt
, Qcmajflt
, Qutime
, Qstime
, Qcstime
;
179 Lisp_Object Qcutime
, Qpri
, Qnice
, Qthcount
, Qstart
, Qvsize
, Qrss
, Qargs
;
180 Lisp_Object Quser
, Qgroup
, Qetime
, Qpcpu
, Qpmem
, Qtime
, Qctime
;
181 Lisp_Object QCname
, QCtype
;
183 /* True if keyboard input is on hold, zero otherwise. */
185 static bool kbd_is_on_hold
;
187 /* Nonzero means don't run process sentinels. This is used
189 bool inhibit_sentinels
;
193 Lisp_Object Qprocessp
;
194 static Lisp_Object Qrun
, Qstop
, Qsignal
;
195 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
197 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
198 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
200 static Lisp_Object Qipv6
;
202 static Lisp_Object QCport
, QCprocess
;
204 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
205 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
206 static Lisp_Object QCbuffer
, QChost
, QCservice
;
207 static Lisp_Object QClocal
, QCremote
, QCcoding
;
208 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
209 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
210 static Lisp_Object Qlast_nonmenu_event
;
211 static Lisp_Object Qinternal_default_process_sentinel
;
212 static Lisp_Object Qinternal_default_process_filter
;
214 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
215 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
216 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
217 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
219 /* Number of events of change of status of a process. */
220 static EMACS_INT process_tick
;
221 /* Number of events for which the user or sentinel has been notified. */
222 static EMACS_INT update_tick
;
224 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
226 /* Only W32 has this, it really means that select can't take write mask. */
227 #ifdef BROKEN_NON_BLOCKING_CONNECT
228 #undef NON_BLOCKING_CONNECT
229 #define SELECT_CANT_DO_WRITE_MASK
231 #ifndef NON_BLOCKING_CONNECT
233 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
234 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
235 #define NON_BLOCKING_CONNECT
236 #endif /* EWOULDBLOCK || EINPROGRESS */
237 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
238 #endif /* HAVE_SELECT */
239 #endif /* NON_BLOCKING_CONNECT */
240 #endif /* BROKEN_NON_BLOCKING_CONNECT */
242 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
243 this system. We need to read full packets, so we need a
244 "non-destructive" select. So we require either native select,
245 or emulation of select using FIONREAD. */
247 #ifndef BROKEN_DATAGRAM_SOCKETS
248 # if defined HAVE_SELECT || defined USABLE_FIONREAD
249 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
250 # define DATAGRAM_SOCKETS
255 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
256 # define HAVE_SEQPACKET
259 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
260 #define ADAPTIVE_READ_BUFFERING
263 #ifdef ADAPTIVE_READ_BUFFERING
264 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
265 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
266 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
268 /* Number of processes which have a non-zero read_output_delay,
269 and therefore might be delayed for adaptive read buffering. */
271 static int process_output_delay_count
;
273 /* True if any process has non-nil read_output_skip. */
275 static bool process_output_skip
;
278 #define process_output_delay_count 0
281 static void create_process (Lisp_Object
, char **, Lisp_Object
);
283 static bool keyboard_bit_set (SELECT_TYPE
*);
285 static void deactivate_process (Lisp_Object
);
286 static void status_notify (struct Lisp_Process
*);
287 static int read_process_output (Lisp_Object
, int);
288 static void handle_child_signal (int);
289 static void create_pty (Lisp_Object
);
291 /* If we support a window system, turn on the code to poll periodically
292 to detect C-g. It isn't actually used when doing interrupt input. */
293 #ifdef HAVE_WINDOW_SYSTEM
294 #define POLL_FOR_INPUT
297 static Lisp_Object
get_process (register Lisp_Object name
);
298 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
300 #ifdef NON_BLOCKING_CONNECT
301 /* Number of bits set in connect_wait_mask. */
302 static int num_pending_connects
;
303 #endif /* NON_BLOCKING_CONNECT */
305 /* The largest descriptor currently in use; -1 if none. */
308 /* Indexed by descriptor, gives the process (if any) for that descriptor */
309 static Lisp_Object chan_process
[MAXDESC
];
311 /* Alist of elements (NAME . PROCESS) */
312 static Lisp_Object Vprocess_alist
;
314 /* Buffered-ahead input char from process, indexed by channel.
315 -1 means empty (no char is buffered).
316 Used on sys V where the only way to tell if there is any
317 output from the process is to read at least one char.
318 Always -1 on systems that support FIONREAD. */
320 static int proc_buffered_char
[MAXDESC
];
322 /* Table of `struct coding-system' for each process. */
323 static struct coding_system
*proc_decode_coding_system
[MAXDESC
];
324 static struct coding_system
*proc_encode_coding_system
[MAXDESC
];
326 #ifdef DATAGRAM_SOCKETS
327 /* Table of `partner address' for datagram sockets. */
328 static struct sockaddr_and_len
{
331 } datagram_address
[MAXDESC
];
332 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
333 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
335 #define DATAGRAM_CHAN_P(chan) (0)
336 #define DATAGRAM_CONN_P(proc) (0)
339 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
340 a `for' loop which iterates over processes from Vprocess_alist. */
342 #define FOR_EACH_PROCESS(list_var, proc_var) \
343 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
345 /* These setters are used only in this file, so they can be private. */
347 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
352 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
357 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
359 p
->decode_coding_system
= val
;
362 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
364 p
->decoding_buf
= val
;
367 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
369 p
->encode_coding_system
= val
;
372 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
374 p
->encoding_buf
= val
;
377 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
379 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
382 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
387 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
392 pset_thread (struct Lisp_Process
*p
, Lisp_Object val
)
397 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
402 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
407 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
409 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
412 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
417 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
422 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
427 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
429 p
->write_queue
= val
;
436 /* Read from file descriptor. */
438 /* Write to file descriptor. */
440 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
443 /* This descriptor refers to a process. */
445 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
446 NON_BLOCKING_CONNECT_FD
= 16
449 static struct fd_callback_data
453 /* Flags from enum fd_bits. */
455 /* If this fd is locked to a certain thread, this points to it.
456 Otherwise, this is NULL. If an fd is locked to a thread, then
457 only that thread is permitted to wait on it. */
458 struct thread_state
*thread
;
459 /* If this fd is currently being selected on by a thread, this
460 points to the thread. Otherwise it is NULL. */
461 struct thread_state
*waiting_thread
;
462 } fd_callback_info
[MAXDESC
];
465 /* Add a file descriptor FD to be monitored for when read is possible.
466 When read is possible, call FUNC with argument DATA. */
469 add_read_fd (int fd
, fd_callback func
, void *data
)
471 eassert (fd
< MAXDESC
);
472 add_keyboard_wait_descriptor (fd
);
474 fd_callback_info
[fd
].func
= func
;
475 fd_callback_info
[fd
].data
= data
;
479 add_non_keyboard_read_fd (int fd
)
481 eassert (fd
>= 0 && fd
< MAXDESC
);
482 eassert (fd_callback_info
[fd
].func
== NULL
);
483 fd_callback_info
[fd
].flags
|= FOR_READ
;
489 add_process_read_fd (int fd
)
491 add_non_keyboard_read_fd (fd
);
492 fd_callback_info
[fd
].flags
|= PROCESS_FD
;
495 /* Stop monitoring file descriptor FD for when read is possible. */
498 delete_read_fd (int fd
)
500 eassert (fd
< MAXDESC
);
501 eassert (fd
<= max_desc
);
502 delete_keyboard_wait_descriptor (fd
);
504 if (fd_callback_info
[fd
].flags
== 0)
506 fd_callback_info
[fd
].func
= 0;
507 fd_callback_info
[fd
].data
= 0;
511 /* Add a file descriptor FD to be monitored for when write is possible.
512 When write is possible, call FUNC with argument DATA. */
515 add_write_fd (int fd
, fd_callback func
, void *data
)
517 eassert (fd
< MAXDESC
);
521 fd_callback_info
[fd
].func
= func
;
522 fd_callback_info
[fd
].data
= data
;
523 fd_callback_info
[fd
].flags
|= FOR_WRITE
;
527 add_non_blocking_write_fd (int fd
)
529 eassert (fd
>= 0 && fd
< MAXDESC
);
530 eassert (fd_callback_info
[fd
].func
== NULL
);
532 fd_callback_info
[fd
].flags
|= FOR_WRITE
| NON_BLOCKING_CONNECT_FD
;
535 ++num_pending_connects
;
539 recompute_max_desc (void)
543 for (fd
= max_desc
; fd
>= 0; --fd
)
545 if (fd_callback_info
[fd
].flags
!= 0)
553 /* Stop monitoring file descriptor FD for when write is possible. */
556 delete_write_fd (int fd
)
560 eassert (fd
< MAXDESC
);
561 eassert (fd
<= max_desc
);
563 if ((fd_callback_info
[fd
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
565 if (--num_pending_connects
< 0)
568 fd_callback_info
[fd
].flags
&= ~(FOR_WRITE
| NON_BLOCKING_CONNECT_FD
);
569 if (fd_callback_info
[fd
].flags
== 0)
571 fd_callback_info
[fd
].func
= 0;
572 fd_callback_info
[fd
].data
= 0;
575 recompute_max_desc ();
580 compute_input_wait_mask (SELECT_TYPE
*mask
)
585 for (fd
= 0; fd
<= max_desc
; ++fd
)
587 if (fd_callback_info
[fd
].thread
!= NULL
588 && fd_callback_info
[fd
].thread
!= current_thread
)
590 if (fd_callback_info
[fd
].waiting_thread
!= NULL
591 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
593 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0)
596 fd_callback_info
[fd
].waiting_thread
= current_thread
;
602 compute_non_process_wait_mask (SELECT_TYPE
*mask
)
607 for (fd
= 0; fd
<= max_desc
; ++fd
)
609 if (fd_callback_info
[fd
].thread
!= NULL
610 && fd_callback_info
[fd
].thread
!= current_thread
)
612 if (fd_callback_info
[fd
].waiting_thread
!= NULL
613 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
615 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
616 && (fd_callback_info
[fd
].flags
& PROCESS_FD
) == 0)
619 fd_callback_info
[fd
].waiting_thread
= current_thread
;
625 compute_non_keyboard_wait_mask (SELECT_TYPE
*mask
)
630 for (fd
= 0; fd
<= max_desc
; ++fd
)
632 if (fd_callback_info
[fd
].thread
!= NULL
633 && fd_callback_info
[fd
].thread
!= current_thread
)
635 if (fd_callback_info
[fd
].waiting_thread
!= NULL
636 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
638 if ((fd_callback_info
[fd
].flags
& FOR_READ
) != 0
639 && (fd_callback_info
[fd
].flags
& KEYBOARD_FD
) == 0)
642 fd_callback_info
[fd
].waiting_thread
= current_thread
;
648 compute_write_mask (SELECT_TYPE
*mask
)
653 for (fd
= 0; fd
<= max_desc
; ++fd
)
655 if (fd_callback_info
[fd
].thread
!= NULL
656 && fd_callback_info
[fd
].thread
!= current_thread
)
658 if (fd_callback_info
[fd
].waiting_thread
!= NULL
659 && fd_callback_info
[fd
].waiting_thread
!= current_thread
)
661 if ((fd_callback_info
[fd
].flags
& FOR_WRITE
) != 0)
664 fd_callback_info
[fd
].waiting_thread
= current_thread
;
670 clear_waiting_thread_info (void)
674 for (fd
= 0; fd
<= max_desc
; ++fd
)
676 if (fd_callback_info
[fd
].waiting_thread
== current_thread
)
677 fd_callback_info
[fd
].waiting_thread
= NULL
;
682 /* Compute the Lisp form of the process status, p->status, from
683 the numeric status that was returned by `wait'. */
685 static Lisp_Object
status_convert (int);
688 update_status (struct Lisp_Process
*p
)
690 eassert (p
->raw_status_new
);
691 pset_status (p
, status_convert (p
->raw_status
));
692 p
->raw_status_new
= 0;
695 /* Convert a process status word in Unix format to
696 the list that we use internally. */
699 status_convert (int w
)
702 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
703 else if (WIFEXITED (w
))
704 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
705 WCOREDUMP (w
) ? Qt
: Qnil
));
706 else if (WIFSIGNALED (w
))
707 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
708 WCOREDUMP (w
) ? Qt
: Qnil
));
713 /* Given a status-list, extract the three pieces of information
714 and store them individually through the three pointers. */
717 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
731 *code
= XFASTINT (XCAR (tem
));
733 *coredump
= !NILP (tem
);
737 /* Return a string describing a process status list. */
740 status_message (struct Lisp_Process
*p
)
742 Lisp_Object status
= p
->status
;
746 Lisp_Object string
, string2
;
748 decode_status (status
, &symbol
, &code
, &coredump
);
750 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
753 synchronize_system_messages_locale ();
754 signame
= strsignal (code
);
756 string
= build_string ("unknown");
761 string
= build_unibyte_string (signame
);
762 if (! NILP (Vlocale_coding_system
))
763 string
= (code_convert_string_norecord
764 (string
, Vlocale_coding_system
, 0));
765 c1
= STRING_CHAR (SDATA (string
));
768 Faset (string
, make_number (0), make_number (c2
));
770 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
771 return concat2 (string
, string2
);
773 else if (EQ (symbol
, Qexit
))
776 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
778 return build_string ("finished\n");
779 string
= Fnumber_to_string (make_number (code
));
780 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
781 return concat3 (build_string ("exited abnormally with code "),
784 else if (EQ (symbol
, Qfailed
))
786 string
= Fnumber_to_string (make_number (code
));
787 string2
= build_string ("\n");
788 return concat3 (build_string ("failed with code "),
792 return Fcopy_sequence (Fsymbol_name (symbol
));
795 enum { PTY_NAME_SIZE
= 24 };
797 /* Open an available pty, returning a file descriptor.
798 Store into PTY_NAME the file name of the terminal corresponding to the pty.
799 Return -1 on failure. */
802 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
811 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
812 for (i
= 0; i
< 16; i
++)
815 #ifdef PTY_NAME_SPRINTF
818 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
819 #endif /* no PTY_NAME_SPRINTF */
823 #else /* no PTY_OPEN */
824 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
825 #endif /* no PTY_OPEN */
829 /* check to make certain that both sides are available
830 this avoids a nasty yet stupid bug in rlogins */
831 #ifdef PTY_TTY_NAME_SPRINTF
834 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
835 #endif /* no PTY_TTY_NAME_SPRINTF */
836 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
849 #endif /* HAVE_PTYS */
854 make_process (Lisp_Object name
)
856 register Lisp_Object val
, tem
, name1
;
857 register struct Lisp_Process
*p
;
858 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
861 p
= allocate_process ();
862 /* Initialize Lisp data. Note that allocate_process initializes all
863 Lisp data to nil, so do it only for slots which should not be nil. */
864 pset_status (p
, Qrun
);
865 pset_mark (p
, Fmake_marker ());
866 pset_thread (p
, Fcurrent_thread ());
868 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
869 non-Lisp data, so do it only for slots which should not be zero. */
872 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
876 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
879 /* If name is already in use, modify it until it is unused. */
884 tem
= Fget_process (name1
);
885 if (NILP (tem
)) break;
886 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
890 pset_sentinel (p
, Qinternal_default_process_sentinel
);
891 pset_filter (p
, Qinternal_default_process_filter
);
892 XSETPROCESS (val
, p
);
893 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
898 remove_process (register Lisp_Object proc
)
900 register Lisp_Object pair
;
902 pair
= Frassq (proc
, Vprocess_alist
);
903 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
905 deactivate_process (proc
);
909 update_processes_for_thread_death (Lisp_Object dying_thread
)
913 for (pair
= Vprocess_alist
; !NILP (pair
); pair
= XCDR (pair
))
915 Lisp_Object process
= XCDR (XCAR (pair
));
916 if (EQ (XPROCESS (process
)->thread
, dying_thread
))
918 struct Lisp_Process
*proc
= XPROCESS (process
);
922 fd_callback_info
[proc
->infd
].thread
= NULL
;
923 if (proc
->outfd
>= 0)
924 fd_callback_info
[proc
->outfd
].thread
= NULL
;
930 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
931 doc
: /* Return t if OBJECT is a process. */)
934 return PROCESSP (object
) ? Qt
: Qnil
;
937 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
938 doc
: /* Return the process named NAME, or nil if there is none. */)
939 (register Lisp_Object name
)
944 return Fcdr (Fassoc (name
, Vprocess_alist
));
947 /* This is how commands for the user decode process arguments. It
948 accepts a process, a process name, a buffer, a buffer name, or nil.
949 Buffers denote the first process in the buffer, and nil denotes the
953 get_process (register Lisp_Object name
)
955 register Lisp_Object proc
, obj
;
958 obj
= Fget_process (name
);
960 obj
= Fget_buffer (name
);
962 error ("Process %s does not exist", SDATA (name
));
964 else if (NILP (name
))
965 obj
= Fcurrent_buffer ();
969 /* Now obj should be either a buffer object or a process object.
973 proc
= Fget_buffer_process (obj
);
975 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
986 /* Fdelete_process promises to immediately forget about the process, but in
987 reality, Emacs needs to remember those processes until they have been
988 treated by the SIGCHLD handler and waitpid has been invoked on them;
989 otherwise they might fill up the kernel's process table.
991 Some processes created by call-process are also put onto this list.
993 Members of this list are (process-ID . filename) pairs. The
994 process-ID is a number; the filename, if a string, is a file that
995 needs to be removed after the process exits. */
996 static Lisp_Object deleted_pid_list
;
999 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
1001 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
1002 /* GC treated elements set to nil. */
1003 Fdelq (Qnil
, deleted_pid_list
));
1007 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
1008 doc
: /* Delete PROCESS: kill it and forget about it immediately.
1009 PROCESS may be a process, a buffer, the name of a process or buffer, or
1010 nil, indicating the current buffer's process. */)
1011 (register Lisp_Object process
)
1013 register struct Lisp_Process
*p
;
1015 process
= get_process (process
);
1016 p
= XPROCESS (process
);
1018 p
->raw_status_new
= 0;
1019 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1021 pset_status (p
, list2 (Qexit
, make_number (0)));
1022 p
->tick
= ++process_tick
;
1024 redisplay_preserve_echo_area (13);
1029 record_kill_process (p
, Qnil
);
1033 /* Update P's status, since record_kill_process will make the
1034 SIGCHLD handler update deleted_pid_list, not *P. */
1036 if (p
->raw_status_new
)
1038 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
1039 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
1040 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
1042 p
->tick
= ++process_tick
;
1044 redisplay_preserve_echo_area (13);
1047 remove_process (process
);
1051 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
1052 doc
: /* Return the status of PROCESS.
1053 The returned value is one of the following symbols:
1054 run -- for a process that is running.
1055 stop -- for a process stopped but continuable.
1056 exit -- for a process that has exited.
1057 signal -- for a process that has got a fatal signal.
1058 open -- for a network stream connection that is open.
1059 listen -- for a network stream server that is listening.
1060 closed -- for a network stream connection that is closed.
1061 connect -- when waiting for a non-blocking connection to complete.
1062 failed -- when a non-blocking connection has failed.
1063 nil -- if arg is a process name and no such process exists.
1064 PROCESS may be a process, a buffer, the name of a process, or
1065 nil, indicating the current buffer's process. */)
1066 (register Lisp_Object process
)
1068 register struct Lisp_Process
*p
;
1069 register Lisp_Object status
;
1071 if (STRINGP (process
))
1072 process
= Fget_process (process
);
1074 process
= get_process (process
);
1079 p
= XPROCESS (process
);
1080 if (p
->raw_status_new
)
1084 status
= XCAR (status
);
1085 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1087 if (EQ (status
, Qexit
))
1089 else if (EQ (p
->command
, Qt
))
1091 else if (EQ (status
, Qrun
))
1097 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
1099 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
1100 If PROCESS has not yet exited or died, return 0. */)
1101 (register Lisp_Object process
)
1103 CHECK_PROCESS (process
);
1104 if (XPROCESS (process
)->raw_status_new
)
1105 update_status (XPROCESS (process
));
1106 if (CONSP (XPROCESS (process
)->status
))
1107 return XCAR (XCDR (XPROCESS (process
)->status
));
1108 return make_number (0);
1111 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
1112 doc
: /* Return the process id of PROCESS.
1113 This is the pid of the external process which PROCESS uses or talks to.
1114 For a network connection, this value is nil. */)
1115 (register Lisp_Object process
)
1119 CHECK_PROCESS (process
);
1120 pid
= XPROCESS (process
)->pid
;
1121 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
1124 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
1125 doc
: /* Return the name of PROCESS, as a string.
1126 This is the name of the program invoked in PROCESS,
1127 possibly modified to make it unique among process names. */)
1128 (register Lisp_Object process
)
1130 CHECK_PROCESS (process
);
1131 return XPROCESS (process
)->name
;
1134 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1135 doc
: /* Return the command that was executed to start PROCESS.
1136 This is a list of strings, the first string being the program executed
1137 and the rest of the strings being the arguments given to it.
1138 For a network or serial process, this is nil (process is running) or t
1139 \(process is stopped). */)
1140 (register Lisp_Object process
)
1142 CHECK_PROCESS (process
);
1143 return XPROCESS (process
)->command
;
1146 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1147 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1148 This is the terminal that the process itself reads and writes on,
1149 not the name of the pty that Emacs uses to talk with that terminal. */)
1150 (register Lisp_Object process
)
1152 CHECK_PROCESS (process
);
1153 return XPROCESS (process
)->tty_name
;
1156 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1158 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1160 (register Lisp_Object process
, Lisp_Object buffer
)
1162 struct Lisp_Process
*p
;
1164 CHECK_PROCESS (process
);
1166 CHECK_BUFFER (buffer
);
1167 p
= XPROCESS (process
);
1168 pset_buffer (p
, buffer
);
1169 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1170 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1171 setup_process_coding_systems (process
);
1175 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1177 doc
: /* Return the buffer PROCESS is associated with.
1178 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1179 (register Lisp_Object process
)
1181 CHECK_PROCESS (process
);
1182 return XPROCESS (process
)->buffer
;
1185 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1187 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1188 (register Lisp_Object process
)
1190 CHECK_PROCESS (process
);
1191 return XPROCESS (process
)->mark
;
1194 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1196 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1197 A value of t means stop accepting output from the process.
1199 When a process has a non-default filter, its buffer is not used for output.
1200 Instead, each time it does output, the entire string of output is
1201 passed to the filter.
1203 The filter gets two arguments: the process and the string of output.
1204 The string argument is normally a multibyte string, except:
1205 - if the process' input coding system is no-conversion or raw-text,
1206 it is a unibyte string (the non-converted input), or else
1207 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1208 string (the result of converting the decoded input multibyte
1209 string to unibyte with `string-make-unibyte'). */)
1210 (register Lisp_Object process
, Lisp_Object filter
)
1212 struct Lisp_Process
*p
;
1214 CHECK_PROCESS (process
);
1215 p
= XPROCESS (process
);
1217 /* Don't signal an error if the process' input file descriptor
1218 is closed. This could make debugging Lisp more difficult,
1219 for example when doing something like
1221 (setq process (start-process ...))
1223 (set-process-filter process ...) */
1226 filter
= Qinternal_default_process_filter
;
1230 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1231 delete_read_fd (p
->infd
);
1232 else if (EQ (p
->filter
, Qt
)
1233 /* Network or serial process not stopped: */
1234 && !EQ (p
->command
, Qt
))
1235 delete_read_fd (p
->infd
);
1238 pset_filter (p
, filter
);
1239 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1240 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1241 setup_process_coding_systems (process
);
1245 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1247 doc
: /* Return the filter function of PROCESS.
1248 See `set-process-filter' for more info on filter functions. */)
1249 (register Lisp_Object process
)
1251 CHECK_PROCESS (process
);
1252 return XPROCESS (process
)->filter
;
1255 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1257 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1258 The sentinel is called as a function when the process changes state.
1259 It gets two arguments: the process, and a string describing the change. */)
1260 (register Lisp_Object process
, Lisp_Object sentinel
)
1262 struct Lisp_Process
*p
;
1264 CHECK_PROCESS (process
);
1265 p
= XPROCESS (process
);
1267 if (NILP (sentinel
))
1268 sentinel
= Qinternal_default_process_sentinel
;
1270 pset_sentinel (p
, sentinel
);
1271 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1272 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1276 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1278 doc
: /* Return the sentinel of PROCESS.
1279 See `set-process-sentinel' for more info on sentinels. */)
1280 (register Lisp_Object process
)
1282 CHECK_PROCESS (process
);
1283 return XPROCESS (process
)->sentinel
;
1286 DEFUN ("set-process-thread", Fset_process_thread
, Sset_process_thread
,
1289 (Lisp_Object process
, Lisp_Object thread
)
1291 struct Lisp_Process
*proc
;
1292 struct thread_state
*tstate
;
1294 CHECK_PROCESS (process
);
1299 CHECK_THREAD (thread
);
1300 tstate
= XTHREAD (thread
);
1303 proc
= XPROCESS (process
);
1304 proc
->thread
= thread
;
1305 if (proc
->infd
>= 0)
1306 fd_callback_info
[proc
->infd
].thread
= tstate
;
1307 if (proc
->outfd
>= 0)
1308 fd_callback_info
[proc
->outfd
].thread
= tstate
;
1313 DEFUN ("process-thread", Fprocess_thread
, Sprocess_thread
,
1316 (Lisp_Object process
)
1318 CHECK_PROCESS (process
);
1319 return XPROCESS (process
)->thread
;
1322 DEFUN ("set-process-window-size", Fset_process_window_size
,
1323 Sset_process_window_size
, 3, 3, 0,
1324 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1325 (register Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1327 CHECK_PROCESS (process
);
1328 CHECK_RANGED_INTEGER (height
, 0, INT_MAX
);
1329 CHECK_RANGED_INTEGER (width
, 0, INT_MAX
);
1331 if (XPROCESS (process
)->infd
< 0
1332 || set_window_size (XPROCESS (process
)->infd
,
1333 XINT (height
), XINT (width
)) <= 0)
1339 DEFUN ("set-process-inherit-coding-system-flag",
1340 Fset_process_inherit_coding_system_flag
,
1341 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1342 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1343 If the second argument FLAG is non-nil, then the variable
1344 `buffer-file-coding-system' of the buffer associated with PROCESS
1345 will be bound to the value of the coding system used to decode
1348 This is useful when the coding system specified for the process buffer
1349 leaves either the character code conversion or the end-of-line conversion
1350 unspecified, or if the coding system used to decode the process output
1351 is more appropriate for saving the process buffer.
1353 Binding the variable `inherit-process-coding-system' to non-nil before
1354 starting the process is an alternative way of setting the inherit flag
1355 for the process which will run.
1357 This function returns FLAG. */)
1358 (register Lisp_Object process
, Lisp_Object flag
)
1360 CHECK_PROCESS (process
);
1361 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1365 DEFUN ("set-process-query-on-exit-flag",
1366 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1368 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1369 If the second argument FLAG is non-nil, Emacs will query the user before
1370 exiting or killing a buffer if PROCESS is running. This function
1372 (register Lisp_Object process
, Lisp_Object flag
)
1374 CHECK_PROCESS (process
);
1375 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1379 DEFUN ("process-query-on-exit-flag",
1380 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1382 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1383 (register Lisp_Object process
)
1385 CHECK_PROCESS (process
);
1386 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1389 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1391 doc
: /* Return the contact info of PROCESS; t for a real child.
1392 For a network or serial connection, the value depends on the optional
1393 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1394 SERVICE) for a network connection or (PORT SPEED) for a serial
1395 connection. If KEY is t, the complete contact information for the
1396 connection is returned, else the specific value for the keyword KEY is
1397 returned. See `make-network-process' or `make-serial-process' for a
1398 list of keywords. */)
1399 (register Lisp_Object process
, Lisp_Object key
)
1401 Lisp_Object contact
;
1403 CHECK_PROCESS (process
);
1404 contact
= XPROCESS (process
)->childp
;
1406 #ifdef DATAGRAM_SOCKETS
1407 if (DATAGRAM_CONN_P (process
)
1408 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1409 contact
= Fplist_put (contact
, QCremote
,
1410 Fprocess_datagram_address (process
));
1413 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1415 if (NILP (key
) && NETCONN_P (process
))
1416 return list2 (Fplist_get (contact
, QChost
),
1417 Fplist_get (contact
, QCservice
));
1418 if (NILP (key
) && SERIALCONN_P (process
))
1419 return list2 (Fplist_get (contact
, QCport
),
1420 Fplist_get (contact
, QCspeed
));
1421 return Fplist_get (contact
, key
);
1424 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1426 doc
: /* Return the plist of PROCESS. */)
1427 (register Lisp_Object process
)
1429 CHECK_PROCESS (process
);
1430 return XPROCESS (process
)->plist
;
1433 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1435 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1436 (register Lisp_Object process
, Lisp_Object plist
)
1438 CHECK_PROCESS (process
);
1441 pset_plist (XPROCESS (process
), plist
);
1445 #if 0 /* Turned off because we don't currently record this info
1446 in the process. Perhaps add it. */
1447 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1448 doc
: /* Return the connection type of PROCESS.
1449 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1450 a socket connection. */)
1451 (Lisp_Object process
)
1453 return XPROCESS (process
)->type
;
1457 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1458 doc
: /* Return the connection type of PROCESS.
1459 The value is either the symbol `real', `network', or `serial'.
1460 PROCESS may be a process, a buffer, the name of a process or buffer, or
1461 nil, indicating the current buffer's process. */)
1462 (Lisp_Object process
)
1465 proc
= get_process (process
);
1466 return XPROCESS (proc
)->type
;
1469 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1471 doc
: /* Convert network ADDRESS from internal format to a string.
1472 A 4 or 5 element vector represents an IPv4 address (with port number).
1473 An 8 or 9 element vector represents an IPv6 address (with port number).
1474 If optional second argument OMIT-PORT is non-nil, don't include a port
1475 number in the string, even when present in ADDRESS.
1476 Returns nil if format of ADDRESS is invalid. */)
1477 (Lisp_Object address
, Lisp_Object omit_port
)
1482 if (STRINGP (address
)) /* AF_LOCAL */
1485 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1487 register struct Lisp_Vector
*p
= XVECTOR (address
);
1488 ptrdiff_t size
= p
->header
.size
;
1489 Lisp_Object args
[10];
1492 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1494 args
[0] = build_string ("%d.%d.%d.%d");
1499 args
[0] = build_string ("%d.%d.%d.%d:%d");
1502 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1504 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1509 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1515 for (i
= 0; i
< nargs
; i
++)
1517 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1520 if (nargs
<= 5 /* IPv4 */
1521 && i
< 4 /* host, not port */
1522 && XINT (p
->contents
[i
]) > 255)
1525 args
[i
+1] = p
->contents
[i
];
1528 return Fformat (nargs
+1, args
);
1531 if (CONSP (address
))
1533 Lisp_Object args
[2];
1534 args
[0] = build_string ("<Family %d>");
1535 args
[1] = Fcar (address
);
1536 return Fformat (2, args
);
1542 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1543 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1546 return Fmapcar (Qcdr
, Vprocess_alist
);
1549 /* Starting asynchronous inferior processes. */
1551 static void start_process_unwind (Lisp_Object proc
);
1553 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1554 doc
: /* Start a program in a subprocess. Return the process object for it.
1555 NAME is name for process. It is modified if necessary to make it unique.
1556 BUFFER is the buffer (or buffer name) to associate with the process.
1558 Process output (both standard output and standard error streams) goes
1559 at end of BUFFER, unless you specify an output stream or filter
1560 function to handle the output. BUFFER may also be nil, meaning that
1561 this process is not associated with any buffer.
1563 PROGRAM is the program file name. It is searched for in `exec-path'
1564 (which see). If nil, just associate a pty with the buffer. Remaining
1565 arguments are strings to give program as arguments.
1567 If you want to separate standard output from standard error, invoke
1568 the command through a shell and redirect one of them using the shell
1571 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1572 (ptrdiff_t nargs
, Lisp_Object
*args
)
1574 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1575 register unsigned char **new_argv
;
1577 ptrdiff_t count
= SPECPDL_INDEX ();
1581 buffer
= Fget_buffer_create (buffer
);
1583 /* Make sure that the child will be able to chdir to the current
1584 buffer's current directory, or its unhandled equivalent. We
1585 can't just have the child check for an error when it does the
1586 chdir, since it's in a vfork.
1588 We have to GCPRO around this because Fexpand_file_name and
1589 Funhandled_file_name_directory might call a file name handling
1590 function. The argument list is protected by the caller, so all
1591 we really have to worry about is buffer. */
1593 struct gcpro gcpro1
, gcpro2
;
1595 current_dir
= BVAR (current_buffer
, directory
);
1597 GCPRO2 (buffer
, current_dir
);
1599 current_dir
= Funhandled_file_name_directory (current_dir
);
1600 if (NILP (current_dir
))
1601 /* If the file name handler says that current_dir is unreachable, use
1602 a sensible default. */
1603 current_dir
= build_string ("~/");
1604 current_dir
= expand_and_dir_to_file (current_dir
, Qnil
);
1605 if (NILP (Ffile_accessible_directory_p (current_dir
)))
1606 report_file_error ("Setting current directory",
1607 BVAR (current_buffer
, directory
));
1613 CHECK_STRING (name
);
1617 if (!NILP (program
))
1618 CHECK_STRING (program
);
1620 proc
= make_process (name
);
1621 /* If an error occurs and we can't start the process, we want to
1622 remove it from the process list. This means that each error
1623 check in create_process doesn't need to call remove_process
1624 itself; it's all taken care of here. */
1625 record_unwind_protect (start_process_unwind
, proc
);
1627 pset_childp (XPROCESS (proc
), Qt
);
1628 pset_plist (XPROCESS (proc
), Qnil
);
1629 pset_type (XPROCESS (proc
), Qreal
);
1630 pset_buffer (XPROCESS (proc
), buffer
);
1631 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1632 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1633 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1636 /* AKA GNUTLS_INITSTAGE(proc). */
1637 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1638 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1641 #ifdef ADAPTIVE_READ_BUFFERING
1642 XPROCESS (proc
)->adaptive_read_buffering
1643 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1644 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1647 /* Make the process marker point into the process buffer (if any). */
1648 if (BUFFERP (buffer
))
1649 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1650 BUF_ZV (XBUFFER (buffer
)),
1651 BUF_ZV_BYTE (XBUFFER (buffer
)));
1654 /* Decide coding systems for communicating with the process. Here
1655 we don't setup the structure coding_system nor pay attention to
1656 unibyte mode. They are done in create_process. */
1658 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1659 Lisp_Object coding_systems
= Qt
;
1660 Lisp_Object val
, *args2
;
1661 struct gcpro gcpro1
, gcpro2
;
1663 val
= Vcoding_system_for_read
;
1666 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1667 args2
[0] = Qstart_process
;
1668 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1669 GCPRO2 (proc
, current_dir
);
1670 if (!NILP (program
))
1671 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1673 if (CONSP (coding_systems
))
1674 val
= XCAR (coding_systems
);
1675 else if (CONSP (Vdefault_process_coding_system
))
1676 val
= XCAR (Vdefault_process_coding_system
);
1678 pset_decode_coding_system (XPROCESS (proc
), val
);
1680 val
= Vcoding_system_for_write
;
1683 if (EQ (coding_systems
, Qt
))
1685 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1686 args2
[0] = Qstart_process
;
1687 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1688 GCPRO2 (proc
, current_dir
);
1689 if (!NILP (program
))
1690 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1693 if (CONSP (coding_systems
))
1694 val
= XCDR (coding_systems
);
1695 else if (CONSP (Vdefault_process_coding_system
))
1696 val
= XCDR (Vdefault_process_coding_system
);
1698 pset_encode_coding_system (XPROCESS (proc
), val
);
1699 /* Note: At this moment, the above coding system may leave
1700 text-conversion or eol-conversion unspecified. They will be
1701 decided after we read output from the process and decode it by
1702 some coding system, or just before we actually send a text to
1707 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1708 XPROCESS (proc
)->decoding_carryover
= 0;
1709 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1711 XPROCESS (proc
)->inherit_coding_system_flag
1712 = !(NILP (buffer
) || !inherit_process_coding_system
);
1714 if (!NILP (program
))
1716 /* If program file name is not absolute, search our path for it.
1717 Put the name we will really use in TEM. */
1718 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1719 && !(SCHARS (program
) > 1
1720 && IS_DEVICE_SEP (SREF (program
, 1))))
1722 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1725 GCPRO4 (name
, program
, buffer
, current_dir
);
1726 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
, make_number (X_OK
));
1729 report_file_error ("Searching for program", program
);
1730 tem
= Fexpand_file_name (tem
, Qnil
);
1734 if (!NILP (Ffile_directory_p (program
)))
1735 error ("Specified program for new process is a directory");
1739 /* If program file name starts with /: for quoting a magic name,
1741 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1742 && SREF (tem
, 1) == ':')
1743 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1746 Lisp_Object arg_encoding
= Qnil
;
1747 struct gcpro gcpro1
;
1750 /* Encode the file name and put it in NEW_ARGV.
1751 That's where the child will use it to execute the program. */
1752 tem
= list1 (ENCODE_FILE (tem
));
1754 /* Here we encode arguments by the coding system used for sending
1755 data to the process. We don't support using different coding
1756 systems for encoding arguments and for encoding data sent to the
1759 for (i
= 3; i
< nargs
; i
++)
1761 tem
= Fcons (args
[i
], tem
);
1762 CHECK_STRING (XCAR (tem
));
1763 if (STRING_MULTIBYTE (XCAR (tem
)))
1765 if (NILP (arg_encoding
))
1766 arg_encoding
= (complement_process_encoding_system
1767 (XPROCESS (proc
)->encode_coding_system
));
1769 code_convert_string_norecord
1770 (XCAR (tem
), arg_encoding
, 1));
1777 /* Now that everything is encoded we can collect the strings into
1779 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1780 new_argv
[nargs
- 2] = 0;
1782 for (i
= nargs
- 2; i
-- != 0; )
1784 new_argv
[i
] = SDATA (XCAR (tem
));
1788 create_process (proc
, (char **) new_argv
, current_dir
);
1793 return unbind_to (count
, proc
);
1796 /* This function is the unwind_protect form for Fstart_process. If
1797 PROC doesn't have its pid set, then we know someone has signaled
1798 an error and the process wasn't started successfully, so we should
1799 remove it from the process list. */
1801 start_process_unwind (Lisp_Object proc
)
1803 if (!PROCESSP (proc
))
1806 /* Was PROC started successfully?
1807 -2 is used for a pty with no process, eg for gdb. */
1808 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1809 remove_process (proc
);
1812 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1815 close_process_fd (int *fd_addr
)
1825 /* Indexes of file descriptors in open_fds. */
1828 /* The pipe from Emacs to its subprocess. */
1830 WRITE_TO_SUBPROCESS
,
1832 /* The main pipe from the subprocess to Emacs. */
1833 READ_FROM_SUBPROCESS
,
1836 /* The pipe from the subprocess to Emacs that is closed when the
1837 subprocess execs. */
1838 READ_FROM_EXEC_MONITOR
,
1842 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1845 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1847 struct Lisp_Process
*p
= XPROCESS (process
);
1848 int inchannel
, outchannel
;
1851 int forkin
, forkout
;
1853 char pty_name
[PTY_NAME_SIZE
];
1854 Lisp_Object lisp_pty_name
= Qnil
;
1855 Lisp_Object encoded_current_dir
;
1857 inchannel
= outchannel
= -1;
1859 if (!NILP (Vprocess_connection_type
))
1860 outchannel
= inchannel
= allocate_pty (pty_name
);
1864 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1865 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1866 /* On most USG systems it does not work to open the pty's tty here,
1867 then close it and reopen it in the child. */
1868 /* Don't let this terminal become our controlling terminal
1869 (in case we don't have one). */
1870 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1872 report_file_error ("Opening pty", Qnil
);
1873 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1875 forkin
= forkout
= -1;
1876 #endif /* not USG, or USG_SUBTTY_WORKS */
1878 lisp_pty_name
= build_string (pty_name
);
1882 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1883 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1884 report_file_error ("Creating pipe", Qnil
);
1885 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1886 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1887 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1888 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1892 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1893 report_file_error ("Creating pipe", Qnil
);
1896 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1897 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1899 /* Record this as an active process, with its channels. */
1900 chan_process
[inchannel
] = process
;
1901 p
->infd
= inchannel
;
1902 p
->outfd
= outchannel
;
1904 /* Previously we recorded the tty descriptor used in the subprocess.
1905 It was only used for getting the foreground tty process, so now
1906 we just reopen the device (see emacs_get_tty_pgrp) as this is
1907 more portable (see USG_SUBTTY_WORKS above). */
1909 p
->pty_flag
= pty_flag
;
1910 pset_status (p
, Qrun
);
1912 add_process_read_fd (inchannel
);
1914 /* This may signal an error. */
1915 setup_process_coding_systems (process
);
1917 encoded_current_dir
= ENCODE_FILE (current_dir
);
1920 block_child_signal ();
1923 /* vfork, and prevent local vars from being clobbered by the vfork. */
1925 Lisp_Object
volatile encoded_current_dir_volatile
= encoded_current_dir
;
1926 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1927 char **volatile new_argv_volatile
= new_argv
;
1928 int volatile forkin_volatile
= forkin
;
1929 int volatile forkout_volatile
= forkout
;
1930 struct Lisp_Process
*p_volatile
= p
;
1934 encoded_current_dir
= encoded_current_dir_volatile
;
1935 lisp_pty_name
= lisp_pty_name_volatile
;
1936 new_argv
= new_argv_volatile
;
1937 forkin
= forkin_volatile
;
1938 forkout
= forkout_volatile
;
1941 pty_flag
= p
->pty_flag
;
1945 #endif /* not WINDOWSNT */
1947 int xforkin
= forkin
;
1948 int xforkout
= forkout
;
1950 /* Make the pty be the controlling terminal of the process. */
1952 /* First, disconnect its current controlling terminal. */
1953 /* We tried doing setsid only if pty_flag, but it caused
1954 process_set_signal to fail on SGI when using a pipe. */
1956 /* Make the pty's terminal the controlling terminal. */
1957 if (pty_flag
&& xforkin
>= 0)
1960 /* We ignore the return value
1961 because faith@cs.unc.edu says that is necessary on Linux. */
1962 ioctl (xforkin
, TIOCSCTTY
, 0);
1965 #if defined (LDISC1)
1966 if (pty_flag
&& xforkin
>= 0)
1969 tcgetattr (xforkin
, &t
);
1971 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1972 emacs_perror ("create_process/tcsetattr LDISC1");
1975 #if defined (NTTYDISC) && defined (TIOCSETD)
1976 if (pty_flag
&& xforkin
>= 0)
1978 /* Use new line discipline. */
1979 int ldisc
= NTTYDISC
;
1980 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1985 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1986 can do TIOCSPGRP only to the process's controlling tty. */
1989 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1990 I can't test it since I don't have 4.3. */
1991 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1994 ioctl (j
, TIOCNOTTY
, 0);
1998 #endif /* TIOCNOTTY */
2000 #if !defined (DONT_REOPEN_PTY)
2001 /*** There is a suggestion that this ought to be a
2002 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
2003 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2004 that system does seem to need this code, even though
2005 both TIOCSCTTY is defined. */
2006 /* Now close the pty (if we had it open) and reopen it.
2007 This makes the pty the controlling terminal of the subprocess. */
2011 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2014 emacs_close (xforkin
);
2015 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
2019 emacs_perror (SSDATA (lisp_pty_name
));
2020 _exit (EXIT_CANCELED
);
2024 #endif /* not DONT_REOPEN_PTY */
2026 #ifdef SETUP_SLAVE_PTY
2031 #endif /* SETUP_SLAVE_PTY */
2032 #endif /* HAVE_PTYS */
2034 signal (SIGINT
, SIG_DFL
);
2035 signal (SIGQUIT
, SIG_DFL
);
2037 /* Emacs ignores SIGPIPE, but the child should not. */
2038 signal (SIGPIPE
, SIG_DFL
);
2040 /* Stop blocking SIGCHLD in the child. */
2041 unblock_child_signal ();
2044 child_setup_tty (xforkout
);
2046 pid
= child_setup (xforkin
, xforkout
, xforkout
,
2047 new_argv
, 1, encoded_current_dir
);
2048 #else /* not WINDOWSNT */
2049 child_setup (xforkin
, xforkout
, xforkout
,
2050 new_argv
, 1, encoded_current_dir
);
2051 #endif /* not WINDOWSNT */
2054 /* Back in the parent process. */
2056 vfork_errno
= errno
;
2061 /* Stop blocking in the parent. */
2062 unblock_child_signal ();
2066 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2069 /* vfork succeeded. */
2071 /* Close the pipe ends that the child uses, or the child's pty. */
2072 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2073 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2076 register_child (pid
, inchannel
);
2077 #endif /* WINDOWSNT */
2079 pset_tty_name (p
, lisp_pty_name
);
2082 /* Wait for child_setup to complete in case that vfork is
2083 actually defined as fork. The descriptor
2084 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2085 of a pipe is closed at the child side either by close-on-exec
2086 on successful execve or the _exit call in child_setup. */
2090 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2091 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2092 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2099 create_pty (Lisp_Object process
)
2101 struct Lisp_Process
*p
= XPROCESS (process
);
2102 char pty_name
[PTY_NAME_SIZE
];
2103 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
2107 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2108 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2109 /* On most USG systems it does not work to open the pty's tty here,
2110 then close it and reopen it in the child. */
2111 /* Don't let this terminal become our controlling terminal
2112 (in case we don't have one). */
2113 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2115 report_file_error ("Opening pty", Qnil
);
2116 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2117 #if defined (DONT_REOPEN_PTY)
2118 /* In the case that vfork is defined as fork, the parent process
2119 (Emacs) may send some data before the child process completes
2120 tty options setup. So we setup tty before forking. */
2121 child_setup_tty (forkout
);
2122 #endif /* DONT_REOPEN_PTY */
2123 #endif /* not USG, or USG_SUBTTY_WORKS */
2125 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2127 /* Record this as an active process, with its channels.
2128 As a result, child_setup will close Emacs's side of the pipes. */
2129 chan_process
[pty_fd
] = process
;
2133 /* Previously we recorded the tty descriptor used in the subprocess.
2134 It was only used for getting the foreground tty process, so now
2135 we just reopen the device (see emacs_get_tty_pgrp) as this is
2136 more portable (see USG_SUBTTY_WORKS above). */
2139 pset_status (p
, Qrun
);
2140 setup_process_coding_systems (process
);
2142 add_non_keyboard_read_fd (pty_fd
);
2144 pset_tty_name (p
, build_string (pty_name
));
2151 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2152 The address family of sa is not included in the result. */
2155 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2157 Lisp_Object address
;
2160 register struct Lisp_Vector
*p
;
2162 /* Workaround for a bug in getsockname on BSD: Names bound to
2163 sockets in the UNIX domain are inaccessible; getsockname returns
2164 a zero length name. */
2165 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2166 return empty_unibyte_string
;
2168 switch (sa
->sa_family
)
2172 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2173 len
= sizeof (sin
->sin_addr
) + 1;
2174 address
= Fmake_vector (make_number (len
), Qnil
);
2175 p
= XVECTOR (address
);
2176 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2177 cp
= (unsigned char *) &sin
->sin_addr
;
2183 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2184 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2185 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2186 address
= Fmake_vector (make_number (len
), Qnil
);
2187 p
= XVECTOR (address
);
2188 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2189 for (i
= 0; i
< len
; i
++)
2190 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2194 #ifdef HAVE_LOCAL_SOCKETS
2197 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2198 for (i
= 0; i
< sizeof (sockun
->sun_path
); i
++)
2199 if (sockun
->sun_path
[i
] == 0)
2201 return make_unibyte_string (sockun
->sun_path
, i
);
2205 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2206 address
= Fcons (make_number (sa
->sa_family
),
2207 Fmake_vector (make_number (len
), Qnil
));
2208 p
= XVECTOR (XCDR (address
));
2209 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2215 p
->contents
[i
++] = make_number (*cp
++);
2221 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2224 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2226 register struct Lisp_Vector
*p
;
2228 if (VECTORP (address
))
2230 p
= XVECTOR (address
);
2231 if (p
->header
.size
== 5)
2234 return sizeof (struct sockaddr_in
);
2237 else if (p
->header
.size
== 9)
2239 *familyp
= AF_INET6
;
2240 return sizeof (struct sockaddr_in6
);
2244 #ifdef HAVE_LOCAL_SOCKETS
2245 else if (STRINGP (address
))
2247 *familyp
= AF_LOCAL
;
2248 return sizeof (struct sockaddr_un
);
2251 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2252 && VECTORP (XCDR (address
)))
2254 struct sockaddr
*sa
;
2255 *familyp
= XINT (XCAR (address
));
2256 p
= XVECTOR (XCDR (address
));
2257 return p
->header
.size
+ sizeof (sa
->sa_family
);
2262 /* Convert an address object (vector or string) to an internal sockaddr.
2264 The address format has been basically validated by
2265 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2266 it could have come from user data. So if FAMILY is not valid,
2267 we return after zeroing *SA. */
2270 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2272 register struct Lisp_Vector
*p
;
2273 register unsigned char *cp
= NULL
;
2277 memset (sa
, 0, len
);
2279 if (VECTORP (address
))
2281 p
= XVECTOR (address
);
2282 if (family
== AF_INET
)
2284 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2285 len
= sizeof (sin
->sin_addr
) + 1;
2286 hostport
= XINT (p
->contents
[--len
]);
2287 sin
->sin_port
= htons (hostport
);
2288 cp
= (unsigned char *)&sin
->sin_addr
;
2289 sa
->sa_family
= family
;
2292 else if (family
== AF_INET6
)
2294 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2295 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2296 len
= sizeof (sin6
->sin6_addr
) + 1;
2297 hostport
= XINT (p
->contents
[--len
]);
2298 sin6
->sin6_port
= htons (hostport
);
2299 for (i
= 0; i
< len
; i
++)
2300 if (INTEGERP (p
->contents
[i
]))
2302 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2305 sa
->sa_family
= family
;
2312 else if (STRINGP (address
))
2314 #ifdef HAVE_LOCAL_SOCKETS
2315 if (family
== AF_LOCAL
)
2317 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2318 cp
= SDATA (address
);
2319 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2320 sockun
->sun_path
[i
] = *cp
++;
2321 sa
->sa_family
= family
;
2328 p
= XVECTOR (XCDR (address
));
2329 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2332 for (i
= 0; i
< len
; i
++)
2333 if (INTEGERP (p
->contents
[i
]))
2334 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2337 #ifdef DATAGRAM_SOCKETS
2338 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2340 doc
: /* Get the current datagram address associated with PROCESS. */)
2341 (Lisp_Object process
)
2345 CHECK_PROCESS (process
);
2347 if (!DATAGRAM_CONN_P (process
))
2350 channel
= XPROCESS (process
)->infd
;
2351 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2352 datagram_address
[channel
].len
);
2355 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2357 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2358 Returns nil upon error setting address, ADDRESS otherwise. */)
2359 (Lisp_Object process
, Lisp_Object address
)
2364 CHECK_PROCESS (process
);
2366 if (!DATAGRAM_CONN_P (process
))
2369 channel
= XPROCESS (process
)->infd
;
2371 len
= get_lisp_to_sockaddr_size (address
, &family
);
2372 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2374 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2380 static const struct socket_options
{
2381 /* The name of this option. Should be lowercase version of option
2382 name without SO_ prefix. */
2384 /* Option level SOL_... */
2386 /* Option number SO_... */
2388 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2389 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2390 } socket_options
[] =
2392 #ifdef SO_BINDTODEVICE
2393 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2396 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2399 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2402 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2405 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2408 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2411 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2414 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2416 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2419 /* Set option OPT to value VAL on socket S.
2421 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2422 Signals an error if setting a known option fails.
2426 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2429 const struct socket_options
*sopt
;
2434 name
= SSDATA (SYMBOL_NAME (opt
));
2435 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2436 if (strcmp (name
, sopt
->name
) == 0)
2439 switch (sopt
->opttype
)
2444 optval
= NILP (val
) ? 0 : 1;
2445 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2446 &optval
, sizeof (optval
));
2453 if (TYPE_RANGED_INTEGERP (int, val
))
2454 optval
= XINT (val
);
2456 error ("Bad option value for %s", name
);
2457 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2458 &optval
, sizeof (optval
));
2462 #ifdef SO_BINDTODEVICE
2465 char devname
[IFNAMSIZ
+1];
2467 /* This is broken, at least in the Linux 2.4 kernel.
2468 To unbind, the arg must be a zero integer, not the empty string.
2469 This should work on all systems. KFS. 2003-09-23. */
2470 memset (devname
, 0, sizeof devname
);
2473 char *arg
= SSDATA (val
);
2474 int len
= min (strlen (arg
), IFNAMSIZ
);
2475 memcpy (devname
, arg
, len
);
2477 else if (!NILP (val
))
2478 error ("Bad option value for %s", name
);
2479 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2488 struct linger linger
;
2491 linger
.l_linger
= 0;
2492 if (TYPE_RANGED_INTEGERP (int, val
))
2493 linger
.l_linger
= XINT (val
);
2495 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2496 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2497 &linger
, sizeof (linger
));
2508 int setsockopt_errno
= errno
;
2509 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2513 return (1 << sopt
->optbit
);
2517 DEFUN ("set-network-process-option",
2518 Fset_network_process_option
, Sset_network_process_option
,
2520 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2521 See `make-network-process' for a list of options and values.
2522 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2523 OPTION is not a supported option, return nil instead; otherwise return t. */)
2524 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2527 struct Lisp_Process
*p
;
2529 CHECK_PROCESS (process
);
2530 p
= XPROCESS (process
);
2531 if (!NETCONN1_P (p
))
2532 error ("Process is not a network process");
2536 error ("Process is not running");
2538 if (set_socket_option (s
, option
, value
))
2540 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2544 if (NILP (no_error
))
2545 error ("Unknown or unsupported option");
2551 DEFUN ("serial-process-configure",
2552 Fserial_process_configure
,
2553 Sserial_process_configure
,
2555 doc
: /* Configure speed, bytesize, etc. of a serial process.
2557 Arguments are specified as keyword/argument pairs. Attributes that
2558 are not given are re-initialized from the process's current
2559 configuration (available via the function `process-contact') or set to
2560 reasonable default values. The following arguments are defined:
2566 -- Any of these arguments can be given to identify the process that is
2567 to be configured. If none of these arguments is given, the current
2568 buffer's process is used.
2570 :speed SPEED -- SPEED is the speed of the serial port in bits per
2571 second, also called baud rate. Any value can be given for SPEED, but
2572 most serial ports work only at a few defined values between 1200 and
2573 115200, with 9600 being the most common value. If SPEED is nil, the
2574 serial port is not configured any further, i.e., all other arguments
2575 are ignored. This may be useful for special serial ports such as
2576 Bluetooth-to-serial converters which can only be configured through AT
2577 commands. A value of nil for SPEED can be used only when passed
2578 through `make-serial-process' or `serial-term'.
2580 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2581 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2583 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2584 `odd' (use odd parity), or the symbol `even' (use even parity). If
2585 PARITY is not given, no parity is used.
2587 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2588 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2589 is not given or nil, 1 stopbit is used.
2591 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2592 flowcontrol to be used, which is either nil (don't use flowcontrol),
2593 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2594 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2595 flowcontrol is used.
2597 `serial-process-configure' is called by `make-serial-process' for the
2598 initial configuration of the serial port.
2602 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2604 \(serial-process-configure
2605 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2607 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2609 usage: (serial-process-configure &rest ARGS) */)
2610 (ptrdiff_t nargs
, Lisp_Object
*args
)
2612 struct Lisp_Process
*p
;
2613 Lisp_Object contact
= Qnil
;
2614 Lisp_Object proc
= Qnil
;
2615 struct gcpro gcpro1
;
2617 contact
= Flist (nargs
, args
);
2620 proc
= Fplist_get (contact
, QCprocess
);
2622 proc
= Fplist_get (contact
, QCname
);
2624 proc
= Fplist_get (contact
, QCbuffer
);
2626 proc
= Fplist_get (contact
, QCport
);
2627 proc
= get_process (proc
);
2628 p
= XPROCESS (proc
);
2629 if (!EQ (p
->type
, Qserial
))
2630 error ("Not a serial process");
2632 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2638 serial_configure (p
, contact
);
2644 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2646 doc
: /* Create and return a serial port process.
2648 In Emacs, serial port connections are represented by process objects,
2649 so input and output work as for subprocesses, and `delete-process'
2650 closes a serial port connection. However, a serial process has no
2651 process id, it cannot be signaled, and the status codes are different
2652 from normal processes.
2654 `make-serial-process' creates a process and a buffer, on which you
2655 probably want to use `process-send-string'. Try \\[serial-term] for
2656 an interactive terminal. See below for examples.
2658 Arguments are specified as keyword/argument pairs. The following
2659 arguments are defined:
2661 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2662 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2663 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2664 the backslashes in strings).
2666 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2667 which this function calls.
2669 :name NAME -- NAME is the name of the process. If NAME is not given,
2670 the value of PORT is used.
2672 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2673 with the process. Process output goes at the end of that buffer,
2674 unless you specify an output stream or filter function to handle the
2675 output. If BUFFER is not given, the value of NAME is used.
2677 :coding CODING -- If CODING is a symbol, it specifies the coding
2678 system used for both reading and writing for this process. If CODING
2679 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2680 ENCODING is used for writing.
2682 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2683 the process is running. If BOOL is not given, query before exiting.
2685 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2686 In the stopped state, a serial process does not accept incoming data,
2687 but you can send outgoing data. The stopped state is cleared by
2688 `continue-process' and set by `stop-process'.
2690 :filter FILTER -- Install FILTER as the process filter.
2692 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2694 :plist PLIST -- Install PLIST as the initial plist of the process.
2700 -- This function calls `serial-process-configure' to handle these
2703 The original argument list, possibly modified by later configuration,
2704 is available via the function `process-contact'.
2708 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2710 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2712 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2714 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2716 usage: (make-serial-process &rest ARGS) */)
2717 (ptrdiff_t nargs
, Lisp_Object
*args
)
2720 Lisp_Object proc
, contact
, port
;
2721 struct Lisp_Process
*p
;
2722 struct gcpro gcpro1
;
2723 Lisp_Object name
, buffer
;
2724 Lisp_Object tem
, val
;
2725 ptrdiff_t specpdl_count
;
2730 contact
= Flist (nargs
, args
);
2733 port
= Fplist_get (contact
, QCport
);
2735 error ("No port specified");
2736 CHECK_STRING (port
);
2738 if (NILP (Fplist_member (contact
, QCspeed
)))
2739 error (":speed not specified");
2740 if (!NILP (Fplist_get (contact
, QCspeed
)))
2741 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2743 name
= Fplist_get (contact
, QCname
);
2746 CHECK_STRING (name
);
2747 proc
= make_process (name
);
2748 specpdl_count
= SPECPDL_INDEX ();
2749 record_unwind_protect (remove_process
, proc
);
2750 p
= XPROCESS (proc
);
2752 fd
= serial_open (port
);
2753 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2758 chan_process
[fd
] = proc
;
2760 buffer
= Fplist_get (contact
, QCbuffer
);
2763 buffer
= Fget_buffer_create (buffer
);
2764 pset_buffer (p
, buffer
);
2766 pset_childp (p
, contact
);
2767 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2768 pset_type (p
, Qserial
);
2769 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2770 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2772 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2773 p
->kill_without_query
= 1;
2774 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2775 pset_command (p
, Qt
);
2776 eassert (! p
->pty_flag
);
2778 if (!EQ (p
->command
, Qt
))
2779 add_non_keyboard_read_fd (fd
);
2781 if (BUFFERP (buffer
))
2783 set_marker_both (p
->mark
, buffer
,
2784 BUF_ZV (XBUFFER (buffer
)),
2785 BUF_ZV_BYTE (XBUFFER (buffer
)));
2788 tem
= Fplist_member (contact
, QCcoding
);
2789 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2795 val
= XCAR (XCDR (tem
));
2799 else if (!NILP (Vcoding_system_for_read
))
2800 val
= Vcoding_system_for_read
;
2801 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2802 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2804 pset_decode_coding_system (p
, val
);
2809 val
= XCAR (XCDR (tem
));
2813 else if (!NILP (Vcoding_system_for_write
))
2814 val
= Vcoding_system_for_write
;
2815 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2816 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2818 pset_encode_coding_system (p
, val
);
2820 setup_process_coding_systems (proc
);
2821 pset_decoding_buf (p
, empty_unibyte_string
);
2822 p
->decoding_carryover
= 0;
2823 pset_encoding_buf (p
, empty_unibyte_string
);
2824 p
->inherit_coding_system_flag
2825 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2827 Fserial_process_configure (nargs
, args
);
2829 specpdl_ptr
= specpdl
+ specpdl_count
;
2835 /* Create a network stream/datagram client/server process. Treated
2836 exactly like a normal process when reading and writing. Primary
2837 differences are in status display and process deletion. A network
2838 connection has no PID; you cannot signal it. All you can do is
2839 stop/continue it and deactivate/close it via delete-process */
2841 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2843 doc
: /* Create and return a network server or client process.
2845 In Emacs, network connections are represented by process objects, so
2846 input and output work as for subprocesses and `delete-process' closes
2847 a network connection. However, a network process has no process id,
2848 it cannot be signaled, and the status codes are different from normal
2851 Arguments are specified as keyword/argument pairs. The following
2852 arguments are defined:
2854 :name NAME -- NAME is name for process. It is modified if necessary
2857 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2858 with the process. Process output goes at end of that buffer, unless
2859 you specify an output stream or filter function to handle the output.
2860 BUFFER may be also nil, meaning that this process is not associated
2863 :host HOST -- HOST is name of the host to connect to, or its IP
2864 address. The symbol `local' specifies the local host. If specified
2865 for a server process, it must be a valid name or address for the local
2866 host, and only clients connecting to that address will be accepted.
2868 :service SERVICE -- SERVICE is name of the service desired, or an
2869 integer specifying a port number to connect to. If SERVICE is t,
2870 a random port number is selected for the server. (If Emacs was
2871 compiled with getaddrinfo, a port number can also be specified as a
2872 string, e.g. "80", as well as an integer. This is not portable.)
2874 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2875 stream type connection, `datagram' creates a datagram type connection,
2876 `seqpacket' creates a reliable datagram connection.
2878 :family FAMILY -- FAMILY is the address (and protocol) family for the
2879 service specified by HOST and SERVICE. The default (nil) is to use
2880 whatever address family (IPv4 or IPv6) that is defined for the host
2881 and port number specified by HOST and SERVICE. Other address families
2883 local -- for a local (i.e. UNIX) address specified by SERVICE.
2884 ipv4 -- use IPv4 address family only.
2885 ipv6 -- use IPv6 address family only.
2887 :local ADDRESS -- ADDRESS is the local address used for the connection.
2888 This parameter is ignored when opening a client process. When specified
2889 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2891 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2892 connection. This parameter is ignored when opening a stream server
2893 process. For a datagram server process, it specifies the initial
2894 setting of the remote datagram address. When specified for a client
2895 process, the FAMILY, HOST, and SERVICE args are ignored.
2897 The format of ADDRESS depends on the address family:
2898 - An IPv4 address is represented as an vector of integers [A B C D P]
2899 corresponding to numeric IP address A.B.C.D and port number P.
2900 - A local address is represented as a string with the address in the
2901 local address space.
2902 - An "unsupported family" address is represented by a cons (F . AV)
2903 where F is the family number and AV is a vector containing the socket
2904 address data with one element per address data byte. Do not rely on
2905 this format in portable code, as it may depend on implementation
2906 defined constants, data sizes, and data structure alignment.
2908 :coding CODING -- If CODING is a symbol, it specifies the coding
2909 system used for both reading and writing for this process. If CODING
2910 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2911 ENCODING is used for writing.
2913 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2914 return without waiting for the connection to complete; instead, the
2915 sentinel function will be called with second arg matching "open" (if
2916 successful) or "failed" when the connect completes. Default is to use
2917 a blocking connect (i.e. wait) for stream type connections.
2919 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2920 running when Emacs is exited.
2922 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2923 In the stopped state, a server process does not accept new
2924 connections, and a client process does not handle incoming traffic.
2925 The stopped state is cleared by `continue-process' and set by
2928 :filter FILTER -- Install FILTER as the process filter.
2930 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2931 process filter are multibyte, otherwise they are unibyte.
2932 If this keyword is not specified, the strings are multibyte if
2933 the default value of `enable-multibyte-characters' is non-nil.
2935 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2937 :log LOG -- Install LOG as the server process log function. This
2938 function is called when the server accepts a network connection from a
2939 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2940 is the server process, CLIENT is the new process for the connection,
2941 and MESSAGE is a string.
2943 :plist PLIST -- Install PLIST as the new process' initial plist.
2945 :server QLEN -- if QLEN is non-nil, create a server process for the
2946 specified FAMILY, SERVICE, and connection type (stream or datagram).
2947 If QLEN is an integer, it is used as the max. length of the server's
2948 pending connection queue (also known as the backlog); the default
2949 queue length is 5. Default is to create a client process.
2951 The following network options can be specified for this connection:
2953 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2954 :dontroute BOOL -- Only send to directly connected hosts.
2955 :keepalive BOOL -- Send keep-alive messages on network stream.
2956 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2957 :oobinline BOOL -- Place out-of-band data in receive data stream.
2958 :priority INT -- Set protocol defined priority for sent packets.
2959 :reuseaddr BOOL -- Allow reusing a recently used local address
2960 (this is allowed by default for a server process).
2961 :bindtodevice NAME -- bind to interface NAME. Using this may require
2962 special privileges on some systems.
2964 Consult the relevant system programmer's manual pages for more
2965 information on using these options.
2968 A server process will listen for and accept connections from clients.
2969 When a client connection is accepted, a new network process is created
2970 for the connection with the following parameters:
2972 - The client's process name is constructed by concatenating the server
2973 process' NAME and a client identification string.
2974 - If the FILTER argument is non-nil, the client process will not get a
2975 separate process buffer; otherwise, the client's process buffer is a newly
2976 created buffer named after the server process' BUFFER name or process
2977 NAME concatenated with the client identification string.
2978 - The connection type and the process filter and sentinel parameters are
2979 inherited from the server process' TYPE, FILTER and SENTINEL.
2980 - The client process' contact info is set according to the client's
2981 addressing information (typically an IP address and a port number).
2982 - The client process' plist is initialized from the server's plist.
2984 Notice that the FILTER and SENTINEL args are never used directly by
2985 the server process. Also, the BUFFER argument is not used directly by
2986 the server process, but via the optional :log function, accepted (and
2987 failed) connections may be logged in the server process' buffer.
2989 The original argument list, modified with the actual connection
2990 information, is available via the `process-contact' function.
2992 usage: (make-network-process &rest ARGS) */)
2993 (ptrdiff_t nargs
, Lisp_Object
*args
)
2996 Lisp_Object contact
;
2997 struct Lisp_Process
*p
;
2998 #ifdef HAVE_GETADDRINFO
2999 struct addrinfo ai
, *res
, *lres
;
3000 struct addrinfo hints
;
3001 const char *portstring
;
3003 #else /* HAVE_GETADDRINFO */
3004 struct _emacs_addrinfo
3010 struct sockaddr
*ai_addr
;
3011 struct _emacs_addrinfo
*ai_next
;
3013 #endif /* HAVE_GETADDRINFO */
3014 struct sockaddr_in address_in
;
3015 #ifdef HAVE_LOCAL_SOCKETS
3016 struct sockaddr_un address_un
;
3021 int s
= -1, outch
, inch
;
3022 struct gcpro gcpro1
;
3023 ptrdiff_t count
= SPECPDL_INDEX ();
3025 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
3027 Lisp_Object name
, buffer
, host
, service
, address
;
3028 Lisp_Object filter
, sentinel
;
3029 bool is_non_blocking_client
= 0;
3038 /* Save arguments for process-contact and clone-process. */
3039 contact
= Flist (nargs
, args
);
3043 /* Ensure socket support is loaded if available. */
3044 init_winsock (TRUE
);
3047 /* :type TYPE (nil: stream, datagram */
3048 tem
= Fplist_get (contact
, QCtype
);
3050 socktype
= SOCK_STREAM
;
3051 #ifdef DATAGRAM_SOCKETS
3052 else if (EQ (tem
, Qdatagram
))
3053 socktype
= SOCK_DGRAM
;
3055 #ifdef HAVE_SEQPACKET
3056 else if (EQ (tem
, Qseqpacket
))
3057 socktype
= SOCK_SEQPACKET
;
3060 error ("Unsupported connection type");
3063 tem
= Fplist_get (contact
, QCserver
);
3066 /* Don't support network sockets when non-blocking mode is
3067 not available, since a blocked Emacs is not useful. */
3069 if (TYPE_RANGED_INTEGERP (int, tem
))
3070 backlog
= XINT (tem
);
3073 /* Make QCaddress an alias for :local (server) or :remote (client). */
3074 QCaddress
= is_server
? QClocal
: QCremote
;
3077 if (!is_server
&& socktype
!= SOCK_DGRAM
3078 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
3080 #ifndef NON_BLOCKING_CONNECT
3081 error ("Non-blocking connect not supported");
3083 is_non_blocking_client
= 1;
3087 name
= Fplist_get (contact
, QCname
);
3088 buffer
= Fplist_get (contact
, QCbuffer
);
3089 filter
= Fplist_get (contact
, QCfilter
);
3090 sentinel
= Fplist_get (contact
, QCsentinel
);
3092 CHECK_STRING (name
);
3094 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3095 ai
.ai_socktype
= socktype
;
3100 /* :local ADDRESS or :remote ADDRESS */
3101 address
= Fplist_get (contact
, QCaddress
);
3102 if (!NILP (address
))
3104 host
= service
= Qnil
;
3106 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
3107 error ("Malformed :address");
3108 ai
.ai_family
= family
;
3109 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
3110 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
3114 /* :family FAMILY -- nil (for Inet), local, or integer. */
3115 tem
= Fplist_get (contact
, QCfamily
);
3118 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3124 #ifdef HAVE_LOCAL_SOCKETS
3125 else if (EQ (tem
, Qlocal
))
3129 else if (EQ (tem
, Qipv6
))
3132 else if (EQ (tem
, Qipv4
))
3134 else if (TYPE_RANGED_INTEGERP (int, tem
))
3135 family
= XINT (tem
);
3137 error ("Unknown address family");
3139 ai
.ai_family
= family
;
3141 /* :service SERVICE -- string, integer (port number), or t (random port). */
3142 service
= Fplist_get (contact
, QCservice
);
3144 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3145 host
= Fplist_get (contact
, QChost
);
3148 if (EQ (host
, Qlocal
))
3149 /* Depending on setup, "localhost" may map to different IPv4 and/or
3150 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3151 host
= build_string ("127.0.0.1");
3152 CHECK_STRING (host
);
3155 #ifdef HAVE_LOCAL_SOCKETS
3156 if (family
== AF_LOCAL
)
3160 message (":family local ignores the :host \"%s\" property",
3162 contact
= Fplist_put (contact
, QChost
, Qnil
);
3165 CHECK_STRING (service
);
3166 memset (&address_un
, 0, sizeof address_un
);
3167 address_un
.sun_family
= AF_LOCAL
;
3168 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3169 error ("Service name too long");
3170 strcpy (address_un
.sun_path
, SSDATA (service
));
3171 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3172 ai
.ai_addrlen
= sizeof address_un
;
3177 /* Slow down polling to every ten seconds.
3178 Some kernels have a bug which causes retrying connect to fail
3179 after a connect. Polling can interfere with gethostbyname too. */
3180 #ifdef POLL_FOR_INPUT
3181 if (socktype
!= SOCK_DGRAM
)
3183 record_unwind_protect_void (run_all_atimers
);
3184 bind_polling_period (10);
3188 #ifdef HAVE_GETADDRINFO
3189 /* If we have a host, use getaddrinfo to resolve both host and service.
3190 Otherwise, use getservbyname to lookup the service. */
3194 /* SERVICE can either be a string or int.
3195 Convert to a C string for later use by getaddrinfo. */
3196 if (EQ (service
, Qt
))
3198 else if (INTEGERP (service
))
3200 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3201 portstring
= portbuf
;
3205 CHECK_STRING (service
);
3206 portstring
= SSDATA (service
);
3211 memset (&hints
, 0, sizeof (hints
));
3213 hints
.ai_family
= family
;
3214 hints
.ai_socktype
= socktype
;
3215 hints
.ai_protocol
= 0;
3217 #ifdef HAVE_RES_INIT
3221 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3223 #ifdef HAVE_GAI_STRERROR
3224 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3226 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3232 #endif /* HAVE_GETADDRINFO */
3234 /* We end up here if getaddrinfo is not defined, or in case no hostname
3235 has been specified (e.g. for a local server process). */
3237 if (EQ (service
, Qt
))
3239 else if (INTEGERP (service
))
3240 port
= htons ((unsigned short) XINT (service
));
3243 struct servent
*svc_info
;
3244 CHECK_STRING (service
);
3245 svc_info
= getservbyname (SSDATA (service
),
3246 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3248 error ("Unknown service: %s", SDATA (service
));
3249 port
= svc_info
->s_port
;
3252 memset (&address_in
, 0, sizeof address_in
);
3253 address_in
.sin_family
= family
;
3254 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3255 address_in
.sin_port
= port
;
3257 #ifndef HAVE_GETADDRINFO
3260 struct hostent
*host_info_ptr
;
3262 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3263 as it may `hang' Emacs for a very long time. */
3267 #ifdef HAVE_RES_INIT
3271 host_info_ptr
= gethostbyname (SDATA (host
));
3276 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3277 host_info_ptr
->h_length
);
3278 family
= host_info_ptr
->h_addrtype
;
3279 address_in
.sin_family
= family
;
3282 /* Attempt to interpret host as numeric inet address */
3284 unsigned long numeric_addr
;
3285 numeric_addr
= inet_addr (SSDATA (host
));
3286 if (numeric_addr
== -1)
3287 error ("Unknown host \"%s\"", SDATA (host
));
3289 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3290 sizeof (address_in
.sin_addr
));
3294 #endif /* not HAVE_GETADDRINFO */
3296 ai
.ai_family
= family
;
3297 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3298 ai
.ai_addrlen
= sizeof address_in
;
3302 /* Do this in case we never enter the for-loop below. */
3303 count1
= SPECPDL_INDEX ();
3306 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3315 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3323 #ifdef DATAGRAM_SOCKETS
3324 if (!is_server
&& socktype
== SOCK_DGRAM
)
3326 #endif /* DATAGRAM_SOCKETS */
3328 #ifdef NON_BLOCKING_CONNECT
3329 if (is_non_blocking_client
)
3331 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3342 /* Make us close S if quit. */
3343 record_unwind_protect_int (close_file_unwind
, s
);
3345 /* Parse network options in the arg list.
3346 We simply ignore anything which isn't a known option (including other keywords).
3347 An error is signaled if setting a known option fails. */
3348 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3349 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3353 /* Configure as a server socket. */
3355 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3356 explicit :reuseaddr key to override this. */
3357 #ifdef HAVE_LOCAL_SOCKETS
3358 if (family
!= AF_LOCAL
)
3360 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3363 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3364 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3367 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3368 report_file_error ("Cannot bind server socket", Qnil
);
3370 #ifdef HAVE_GETSOCKNAME
3371 if (EQ (service
, Qt
))
3373 struct sockaddr_in sa1
;
3374 socklen_t len1
= sizeof (sa1
);
3375 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3377 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3378 service
= make_number (ntohs (sa1
.sin_port
));
3379 contact
= Fplist_put (contact
, QCservice
, service
);
3384 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3385 report_file_error ("Cannot listen on server socket", Qnil
);
3393 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3396 if (ret
== 0 || xerrno
== EISCONN
)
3398 /* The unwind-protect will be discarded afterwards.
3399 Likewise for immediate_quit. */
3403 #ifdef NON_BLOCKING_CONNECT
3405 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3409 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3416 if (xerrno
== EINTR
)
3418 /* Unlike most other syscalls connect() cannot be called
3419 again. (That would return EALREADY.) The proper way to
3420 wait for completion is pselect(). */
3428 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3434 report_file_error ("Failed select", Qnil
);
3438 len
= sizeof xerrno
;
3439 eassert (FD_ISSET (s
, &fdset
));
3440 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3441 report_file_error ("Failed getsockopt", Qnil
);
3443 report_file_errno ("Failed connect", Qnil
, xerrno
);
3446 #endif /* !WINDOWSNT */
3450 /* Discard the unwind protect closing S. */
3451 specpdl_ptr
= specpdl
+ count1
;
3456 if (xerrno
== EINTR
)
3463 #ifdef DATAGRAM_SOCKETS
3464 if (socktype
== SOCK_DGRAM
)
3466 if (datagram_address
[s
].sa
)
3468 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3469 datagram_address
[s
].len
= lres
->ai_addrlen
;
3473 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3474 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3477 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3478 if (rlen
!= 0 && rfamily
== lres
->ai_family
3479 && rlen
== lres
->ai_addrlen
)
3480 conv_lisp_to_sockaddr (rfamily
, remote
,
3481 datagram_address
[s
].sa
, rlen
);
3485 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3488 contact
= Fplist_put (contact
, QCaddress
,
3489 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3490 #ifdef HAVE_GETSOCKNAME
3493 struct sockaddr_in sa1
;
3494 socklen_t len1
= sizeof (sa1
);
3495 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3496 contact
= Fplist_put (contact
, QClocal
,
3497 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3504 #ifdef HAVE_GETADDRINFO
3515 /* If non-blocking got this far - and failed - assume non-blocking is
3516 not supported after all. This is probably a wrong assumption, but
3517 the normal blocking calls to open-network-stream handles this error
3519 if (is_non_blocking_client
)
3522 report_file_errno ((is_server
3523 ? "make server process failed"
3524 : "make client process failed"),
3532 buffer
= Fget_buffer_create (buffer
);
3533 proc
= make_process (name
);
3535 chan_process
[inch
] = proc
;
3537 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3539 p
= XPROCESS (proc
);
3541 pset_childp (p
, contact
);
3542 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3543 pset_type (p
, Qnetwork
);
3545 pset_buffer (p
, buffer
);
3546 pset_sentinel (p
, sentinel
);
3547 pset_filter (p
, filter
);
3548 pset_log (p
, Fplist_get (contact
, QClog
));
3549 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3550 p
->kill_without_query
= 1;
3551 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3552 pset_command (p
, Qt
);
3555 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3559 /* Discard the unwind protect for closing S, if any. */
3560 specpdl_ptr
= specpdl
+ count1
;
3562 /* Unwind bind_polling_period and request_sigio. */
3563 unbind_to (count
, Qnil
);
3565 if (is_server
&& socktype
!= SOCK_DGRAM
)
3566 pset_status (p
, Qlisten
);
3568 /* Make the process marker point into the process buffer (if any). */
3569 if (BUFFERP (buffer
))
3570 set_marker_both (p
->mark
, buffer
,
3571 BUF_ZV (XBUFFER (buffer
)),
3572 BUF_ZV_BYTE (XBUFFER (buffer
)));
3574 #ifdef NON_BLOCKING_CONNECT
3575 if (is_non_blocking_client
)
3577 /* We may get here if connect did succeed immediately. However,
3578 in that case, we still need to signal this like a non-blocking
3580 pset_status (p
, Qconnect
);
3581 if ((fd_callback_info
[inch
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3582 add_non_blocking_write_fd (inch
);
3586 /* A server may have a client filter setting of Qt, but it must
3587 still listen for incoming connects unless it is stopped. */
3588 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3589 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3590 add_non_keyboard_read_fd (inch
);
3592 if (inch
> max_desc
)
3595 tem
= Fplist_member (contact
, QCcoding
);
3596 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3597 tem
= Qnil
; /* No error message (too late!). */
3600 /* Setup coding systems for communicating with the network stream. */
3601 struct gcpro gcpro1
;
3602 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3603 Lisp_Object coding_systems
= Qt
;
3604 Lisp_Object fargs
[5], val
;
3608 val
= XCAR (XCDR (tem
));
3612 else if (!NILP (Vcoding_system_for_read
))
3613 val
= Vcoding_system_for_read
;
3614 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3615 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3616 /* We dare not decode end-of-line format by setting VAL to
3617 Qraw_text, because the existing Emacs Lisp libraries
3618 assume that they receive bare code including a sequence of
3623 if (NILP (host
) || NILP (service
))
3624 coding_systems
= Qnil
;
3627 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3628 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3630 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3633 if (CONSP (coding_systems
))
3634 val
= XCAR (coding_systems
);
3635 else if (CONSP (Vdefault_process_coding_system
))
3636 val
= XCAR (Vdefault_process_coding_system
);
3640 pset_decode_coding_system (p
, val
);
3644 val
= XCAR (XCDR (tem
));
3648 else if (!NILP (Vcoding_system_for_write
))
3649 val
= Vcoding_system_for_write
;
3650 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3654 if (EQ (coding_systems
, Qt
))
3656 if (NILP (host
) || NILP (service
))
3657 coding_systems
= Qnil
;
3660 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3661 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3663 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3667 if (CONSP (coding_systems
))
3668 val
= XCDR (coding_systems
);
3669 else if (CONSP (Vdefault_process_coding_system
))
3670 val
= XCDR (Vdefault_process_coding_system
);
3674 pset_encode_coding_system (p
, val
);
3676 setup_process_coding_systems (proc
);
3678 pset_decoding_buf (p
, empty_unibyte_string
);
3679 p
->decoding_carryover
= 0;
3680 pset_encoding_buf (p
, empty_unibyte_string
);
3682 p
->inherit_coding_system_flag
3683 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3690 #if defined (HAVE_NET_IF_H)
3693 DEFUN ("network-interface-list", Fnetwork_interface_list
, Snetwork_interface_list
, 0, 0, 0,
3694 doc
: /* Return an alist of all network interfaces and their network address.
3695 Each element is a cons, the car of which is a string containing the
3696 interface name, and the cdr is the network address in internal
3697 format; see the description of ADDRESS in `make-network-process'. */)
3700 struct ifconf ifconf
;
3701 struct ifreq
*ifreq
;
3703 ptrdiff_t buf_size
= 512;
3708 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3711 count
= SPECPDL_INDEX ();
3712 record_unwind_protect_int (close_file_unwind
, s
);
3716 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3717 ifconf
.ifc_buf
= buf
;
3718 ifconf
.ifc_len
= buf_size
;
3719 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3726 while (ifconf
.ifc_len
== buf_size
);
3728 res
= unbind_to (count
, Qnil
);
3729 ifreq
= ifconf
.ifc_req
;
3730 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3732 struct ifreq
*ifq
= ifreq
;
3733 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3734 #define SIZEOF_IFREQ(sif) \
3735 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3736 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3738 int len
= SIZEOF_IFREQ (ifq
);
3740 int len
= sizeof (*ifreq
);
3742 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3743 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3745 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3748 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3749 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3750 res
= Fcons (Fcons (build_string (namebuf
),
3751 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3752 sizeof (struct sockaddr
))),
3759 #endif /* SIOCGIFCONF */
3761 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3765 const char *flag_sym
;
3768 static const struct ifflag_def ifflag_table
[] = {
3772 #ifdef IFF_BROADCAST
3773 { IFF_BROADCAST
, "broadcast" },
3776 { IFF_DEBUG
, "debug" },
3779 { IFF_LOOPBACK
, "loopback" },
3781 #ifdef IFF_POINTOPOINT
3782 { IFF_POINTOPOINT
, "pointopoint" },
3785 { IFF_RUNNING
, "running" },
3788 { IFF_NOARP
, "noarp" },
3791 { IFF_PROMISC
, "promisc" },
3793 #ifdef IFF_NOTRAILERS
3794 #ifdef NS_IMPL_COCOA
3795 /* Really means smart, notrailers is obsolete */
3796 { IFF_NOTRAILERS
, "smart" },
3798 { IFF_NOTRAILERS
, "notrailers" },
3802 { IFF_ALLMULTI
, "allmulti" },
3805 { IFF_MASTER
, "master" },
3808 { IFF_SLAVE
, "slave" },
3810 #ifdef IFF_MULTICAST
3811 { IFF_MULTICAST
, "multicast" },
3814 { IFF_PORTSEL
, "portsel" },
3816 #ifdef IFF_AUTOMEDIA
3817 { IFF_AUTOMEDIA
, "automedia" },
3820 { IFF_DYNAMIC
, "dynamic" },
3823 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3826 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3829 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3832 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3835 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3840 DEFUN ("network-interface-info", Fnetwork_interface_info
, Snetwork_interface_info
, 1, 1, 0,
3841 doc
: /* Return information about network interface named IFNAME.
3842 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3843 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3844 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3845 FLAGS is the current flags of the interface. */)
3846 (Lisp_Object ifname
)
3849 Lisp_Object res
= Qnil
;
3854 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3855 && defined HAVE_GETIFADDRS && defined LLADDR)
3856 struct ifaddrs
*ifap
;
3859 CHECK_STRING (ifname
);
3861 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3862 error ("interface name too long");
3863 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3865 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3868 count
= SPECPDL_INDEX ();
3869 record_unwind_protect_int (close_file_unwind
, s
);
3872 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3873 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3875 int flags
= rq
.ifr_flags
;
3876 const struct ifflag_def
*fp
;
3879 /* If flags is smaller than int (i.e. short) it may have the high bit set
3880 due to IFF_MULTICAST. In that case, sign extending it into
3882 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3883 flags
= (unsigned short) rq
.ifr_flags
;
3886 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3888 if (flags
& fp
->flag_bit
)
3890 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3891 flags
-= fp
->flag_bit
;
3894 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3898 elt
= Fcons (make_number (fnum
), elt
);
3903 res
= Fcons (elt
, res
);
3906 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3907 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3909 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3910 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3914 for (n
= 0; n
< 6; n
++)
3915 p
->contents
[n
] = make_number (((unsigned char *)&rq
.ifr_hwaddr
.sa_data
[0])[n
]);
3916 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3918 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3919 if (getifaddrs (&ifap
) != -1)
3921 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3922 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3925 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3927 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3928 unsigned char linkaddr
[6];
3931 if (it
->ifa_addr
->sa_family
!= AF_LINK
3932 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3933 || sdl
->sdl_alen
!= 6)
3936 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3937 for (n
= 0; n
< 6; n
++)
3938 p
->contents
[n
] = make_number (linkaddr
[n
]);
3940 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3944 #ifdef HAVE_FREEIFADDRS
3948 #endif /* HAVE_GETIFADDRS && LLADDR */
3950 res
= Fcons (elt
, res
);
3953 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3954 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3957 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3958 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3960 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3964 res
= Fcons (elt
, res
);
3967 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3968 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3971 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3974 res
= Fcons (elt
, res
);
3977 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3978 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3981 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3984 res
= Fcons (elt
, res
);
3986 return unbind_to (count
, any
? res
: Qnil
);
3989 #endif /* defined (HAVE_NET_IF_H) */
3991 /* Turn off input and output for process PROC. */
3994 deactivate_process (Lisp_Object proc
)
3997 struct Lisp_Process
*p
= XPROCESS (proc
);
4001 /* Delete GnuTLS structures in PROC, if any. */
4002 emacs_gnutls_deinit (proc
);
4003 #endif /* HAVE_GNUTLS */
4005 #ifdef ADAPTIVE_READ_BUFFERING
4006 if (p
->read_output_delay
> 0)
4008 if (--process_output_delay_count
< 0)
4009 process_output_delay_count
= 0;
4010 p
->read_output_delay
= 0;
4011 p
->read_output_skip
= 0;
4015 inchannel
= p
->infd
;
4017 /* Beware SIGCHLD hereabouts. */
4019 flush_pending_output (inchannel
);
4021 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4022 close_process_fd (&p
->open_fd
[i
]);
4028 #ifdef DATAGRAM_SOCKETS
4029 if (DATAGRAM_CHAN_P (inchannel
))
4031 xfree (datagram_address
[inchannel
].sa
);
4032 datagram_address
[inchannel
].sa
= 0;
4033 datagram_address
[inchannel
].len
= 0;
4036 chan_process
[inchannel
] = Qnil
;
4037 delete_read_fd (inchannel
);
4038 #ifdef NON_BLOCKING_CONNECT
4039 if ((fd_callback_info
[inchannel
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
4040 delete_write_fd (inchannel
);
4042 if (inchannel
== max_desc
)
4043 recompute_max_desc ();
4048 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4050 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4051 It is read into the process' buffers or given to their filter functions.
4052 Non-nil arg PROCESS means do not return until some output has been received
4055 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4056 and milliseconds to wait; return after that much time whether or not
4057 there is any subprocess output. If SECONDS is a floating point number,
4058 it specifies a fractional number of seconds to wait.
4059 The MILLISEC argument is obsolete and should be avoided.
4061 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4062 from PROCESS, suspending reading output from other processes.
4063 If JUST-THIS-ONE is an integer, don't run any timers either.
4064 Return non-nil if we received any output before the timeout expired. */)
4065 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4070 if (! NILP (process
))
4072 struct Lisp_Process
*procp
;
4074 CHECK_PROCESS (process
);
4075 procp
= XPROCESS (process
);
4077 /* Can't wait for a process that is dedicated to a different
4079 if (!EQ (procp
->thread
, Qnil
) && !EQ (procp
->thread
, Fcurrent_thread ()))
4083 just_this_one
= Qnil
;
4085 if (!NILP (millisec
))
4086 { /* Obsolete calling convention using integers rather than floats. */
4087 CHECK_NUMBER (millisec
);
4089 seconds
= make_float (XINT (millisec
) / 1000.0);
4092 CHECK_NUMBER (seconds
);
4093 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4100 if (!NILP (seconds
))
4102 if (INTEGERP (seconds
))
4104 if (XINT (seconds
) > 0)
4106 secs
= XINT (seconds
);
4110 else if (FLOATP (seconds
))
4112 if (XFLOAT_DATA (seconds
) > 0)
4114 EMACS_TIME t
= EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds
));
4115 secs
= min (EMACS_SECS (t
), WAIT_READING_MAX
);
4116 nsecs
= EMACS_NSECS (t
);
4120 wrong_type_argument (Qnumberp
, seconds
);
4122 else if (! NILP (process
))
4126 (wait_reading_process_output (secs
, nsecs
, 0, 0,
4128 !NILP (process
) ? XPROCESS (process
) : NULL
,
4129 NILP (just_this_one
) ? 0 :
4130 !INTEGERP (just_this_one
) ? 1 : -1)
4134 /* Accept a connection for server process SERVER on CHANNEL. */
4136 static EMACS_INT connect_counter
= 0;
4139 server_accept_connection (Lisp_Object server
, int channel
)
4141 Lisp_Object proc
, caller
, name
, buffer
;
4142 Lisp_Object contact
, host
, service
;
4143 struct Lisp_Process
*ps
= XPROCESS (server
);
4144 struct Lisp_Process
*p
;
4148 struct sockaddr_in in
;
4150 struct sockaddr_in6 in6
;
4152 #ifdef HAVE_LOCAL_SOCKETS
4153 struct sockaddr_un un
;
4156 socklen_t len
= sizeof saddr
;
4159 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4168 if (code
== EWOULDBLOCK
)
4172 if (!NILP (ps
->log
))
4173 call3 (ps
->log
, server
, Qnil
,
4174 concat3 (build_string ("accept failed with code"),
4175 Fnumber_to_string (make_number (code
)),
4176 build_string ("\n")));
4180 count
= SPECPDL_INDEX ();
4181 record_unwind_protect_int (close_file_unwind
, s
);
4185 /* Setup a new process to handle the connection. */
4187 /* Generate a unique identification of the caller, and build contact
4188 information for this process. */
4191 switch (saddr
.sa
.sa_family
)
4195 Lisp_Object args
[5];
4196 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4197 args
[0] = build_string ("%d.%d.%d.%d");
4198 args
[1] = make_number (*ip
++);
4199 args
[2] = make_number (*ip
++);
4200 args
[3] = make_number (*ip
++);
4201 args
[4] = make_number (*ip
++);
4202 host
= Fformat (5, args
);
4203 service
= make_number (ntohs (saddr
.in
.sin_port
));
4205 args
[0] = build_string (" <%s:%d>");
4208 caller
= Fformat (3, args
);
4215 Lisp_Object args
[9];
4216 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4218 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4219 for (i
= 0; i
< 8; i
++)
4220 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4221 host
= Fformat (9, args
);
4222 service
= make_number (ntohs (saddr
.in
.sin_port
));
4224 args
[0] = build_string (" <[%s]:%d>");
4227 caller
= Fformat (3, args
);
4232 #ifdef HAVE_LOCAL_SOCKETS
4236 caller
= Fnumber_to_string (make_number (connect_counter
));
4237 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4241 /* Create a new buffer name for this process if it doesn't have a
4242 filter. The new buffer name is based on the buffer name or
4243 process name of the server process concatenated with the caller
4246 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4247 || EQ (ps
->filter
, Qt
)))
4251 buffer
= ps
->buffer
;
4253 buffer
= Fbuffer_name (buffer
);
4258 buffer
= concat2 (buffer
, caller
);
4259 buffer
= Fget_buffer_create (buffer
);
4263 /* Generate a unique name for the new server process. Combine the
4264 server process name with the caller identification. */
4266 name
= concat2 (ps
->name
, caller
);
4267 proc
= make_process (name
);
4269 chan_process
[s
] = proc
;
4271 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4273 p
= XPROCESS (proc
);
4275 /* Build new contact information for this setup. */
4276 contact
= Fcopy_sequence (ps
->childp
);
4277 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4278 contact
= Fplist_put (contact
, QChost
, host
);
4279 if (!NILP (service
))
4280 contact
= Fplist_put (contact
, QCservice
, service
);
4281 contact
= Fplist_put (contact
, QCremote
,
4282 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4283 #ifdef HAVE_GETSOCKNAME
4285 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4286 contact
= Fplist_put (contact
, QClocal
,
4287 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4290 pset_childp (p
, contact
);
4291 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4292 pset_type (p
, Qnetwork
);
4294 pset_buffer (p
, buffer
);
4295 pset_sentinel (p
, ps
->sentinel
);
4296 pset_filter (p
, ps
->filter
);
4297 pset_command (p
, Qnil
);
4300 /* Discard the unwind protect for closing S. */
4301 specpdl_ptr
= specpdl
+ count
;
4303 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4306 pset_status (p
, Qrun
);
4308 /* Client processes for accepted connections are not stopped initially. */
4309 if (!EQ (p
->filter
, Qt
))
4310 add_non_keyboard_read_fd (s
);
4312 /* Setup coding system for new process based on server process.
4313 This seems to be the proper thing to do, as the coding system
4314 of the new process should reflect the settings at the time the
4315 server socket was opened; not the current settings. */
4317 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4318 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4319 setup_process_coding_systems (proc
);
4321 pset_decoding_buf (p
, empty_unibyte_string
);
4322 p
->decoding_carryover
= 0;
4323 pset_encoding_buf (p
, empty_unibyte_string
);
4325 p
->inherit_coding_system_flag
4326 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4328 if (!NILP (ps
->log
))
4329 call3 (ps
->log
, server
, proc
,
4330 concat3 (build_string ("accept from "),
4331 (STRINGP (host
) ? host
: build_string ("-")),
4332 build_string ("\n")));
4334 exec_sentinel (proc
,
4335 concat3 (build_string ("open from "),
4336 (STRINGP (host
) ? host
: build_string ("-")),
4337 build_string ("\n")));
4341 wait_reading_process_output_unwind (int data
)
4343 clear_waiting_thread_info ();
4344 waiting_for_user_input_p
= data
;
4347 /* This is here so breakpoints can be put on it. */
4349 wait_reading_process_output_1 (void)
4353 /* Read and dispose of subprocess output while waiting for timeout to
4354 elapse and/or keyboard input to be available.
4358 If negative, gobble data immediately available but don't wait for any.
4361 an additional duration to wait, measured in nanoseconds
4362 If TIME_LIMIT is zero, then:
4363 If NSECS == 0, there is no limit.
4364 If NSECS > 0, the timeout consists of NSECS only.
4365 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4368 0 to ignore keyboard input, or
4369 1 to return when input is available, or
4370 -1 meaning caller will actually read the input, so don't throw to
4371 the quit handler, or
4373 DO_DISPLAY means redisplay should be done to show subprocess
4374 output that arrives.
4376 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4377 (and gobble terminal input into the buffer if any arrives).
4379 If WAIT_PROC is specified, wait until something arrives from that
4380 process. The return value is true if we read some input from
4383 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4384 (suspending output from other processes). A negative value
4385 means don't run any timers either.
4387 If WAIT_PROC is specified, then the function returns true if we
4388 received input from that process before the timeout elapsed.
4389 Otherwise, return true if we received input from any process. */
4392 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4394 Lisp_Object wait_for_cell
,
4395 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4398 SELECT_TYPE Available
;
4399 SELECT_TYPE Writeok
;
4405 EMACS_TIME timeout
, end_time
;
4406 int wait_channel
= -1;
4407 bool got_some_input
= 0;
4408 ptrdiff_t count
= SPECPDL_INDEX ();
4410 eassert (wait_proc
== NULL
4411 || EQ (wait_proc
->thread
, Qnil
)
4412 || XTHREAD (wait_proc
->thread
) == current_thread
);
4414 FD_ZERO (&Available
);
4417 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4418 && !(CONSP (wait_proc
->status
)
4419 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4420 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4422 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4423 if (wait_proc
!= NULL
)
4424 wait_channel
= wait_proc
->infd
;
4426 record_unwind_protect_int (wait_reading_process_output_unwind
,
4427 waiting_for_user_input_p
);
4428 waiting_for_user_input_p
= read_kbd
;
4435 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4436 time_limit
= TYPE_MAXIMUM (time_t);
4438 /* Since we may need to wait several times,
4439 compute the absolute time to return at. */
4440 if (time_limit
|| nsecs
> 0)
4442 timeout
= make_emacs_time (time_limit
, nsecs
);
4443 end_time
= add_emacs_time (current_emacs_time (), timeout
);
4448 bool timeout_reduced_for_timers
= 0;
4450 /* If calling from keyboard input, do not quit
4451 since we want to return C-g as an input character.
4452 Otherwise, do pending quit if requested. */
4455 else if (pending_signals
)
4456 process_pending_signals ();
4458 /* Exit now if the cell we're waiting for became non-nil. */
4459 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4462 /* Compute time from now till when time limit is up. */
4463 /* Exit if already run out. */
4466 /* A negative timeout means
4467 gobble output available now
4468 but don't wait at all. */
4470 timeout
= make_emacs_time (0, 0);
4472 else if (time_limit
|| nsecs
> 0)
4474 EMACS_TIME now
= current_emacs_time ();
4475 if (EMACS_TIME_LE (end_time
, now
))
4477 timeout
= sub_emacs_time (end_time
, now
);
4481 timeout
= make_emacs_time (100000, 0);
4484 /* Normally we run timers here.
4485 But not if wait_for_cell; in those cases,
4486 the wait is supposed to be short,
4487 and those callers cannot handle running arbitrary Lisp code here. */
4488 if (NILP (wait_for_cell
)
4489 && just_wait_proc
>= 0)
4491 EMACS_TIME timer_delay
;
4495 unsigned old_timers_run
= timers_run
;
4496 struct buffer
*old_buffer
= current_buffer
;
4497 Lisp_Object old_window
= selected_window
;
4499 timer_delay
= timer_check ();
4501 /* If a timer has run, this might have changed buffers
4502 an alike. Make read_key_sequence aware of that. */
4503 if (timers_run
!= old_timers_run
4504 && (old_buffer
!= current_buffer
4505 || !EQ (old_window
, selected_window
))
4506 && waiting_for_user_input_p
== -1)
4507 record_asynch_buffer_change ();
4509 if (timers_run
!= old_timers_run
&& do_display
)
4510 /* We must retry, since a timer may have requeued itself
4511 and that could alter the time_delay. */
4512 redisplay_preserve_echo_area (9);
4516 while (!detect_input_pending ());
4518 /* If there is unread keyboard input, also return. */
4520 && requeued_events_pending_p ())
4523 /* A negative timeout means do not wait at all. */
4526 if (EMACS_TIME_VALID_P (timer_delay
))
4528 if (EMACS_TIME_LT (timer_delay
, timeout
))
4530 timeout
= timer_delay
;
4531 timeout_reduced_for_timers
= 1;
4536 /* This is so a breakpoint can be put here. */
4537 wait_reading_process_output_1 ();
4542 /* Cause C-g and alarm signals to take immediate action,
4543 and cause input available signals to zero out timeout.
4545 It is important that we do this before checking for process
4546 activity. If we get a SIGCHLD after the explicit checks for
4547 process activity, timeout is the only way we will know. */
4549 set_waiting_for_input (&timeout
);
4551 /* If status of something has changed, and no input is
4552 available, notify the user of the change right away. After
4553 this explicit check, we'll let the SIGCHLD handler zap
4554 timeout to get our attention. */
4555 if (update_tick
!= process_tick
)
4560 if (kbd_on_hold_p ())
4563 compute_input_wait_mask (&Atemp
);
4564 compute_write_mask (&Ctemp
);
4566 timeout
= make_emacs_time (0, 0);
4567 if ((thread_select (pselect
, max_desc
+ 1,
4569 #ifdef NON_BLOCKING_CONNECT
4570 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4574 NULL
, &timeout
, NULL
)
4577 /* It's okay for us to do this and then continue with
4578 the loop, since timeout has already been zeroed out. */
4579 clear_waiting_for_input ();
4580 status_notify (NULL
);
4581 if (do_display
) redisplay_preserve_echo_area (13);
4585 /* Don't wait for output from a non-running process. Just
4586 read whatever data has already been received. */
4587 if (wait_proc
&& wait_proc
->raw_status_new
)
4588 update_status (wait_proc
);
4590 && ! EQ (wait_proc
->status
, Qrun
)
4591 && ! EQ (wait_proc
->status
, Qconnect
))
4593 bool read_some_bytes
= 0;
4595 clear_waiting_for_input ();
4596 XSETPROCESS (proc
, wait_proc
);
4598 /* Read data from the process, until we exhaust it. */
4599 while (wait_proc
->infd
>= 0)
4601 int nread
= read_process_output (proc
, wait_proc
->infd
);
4607 got_some_input
= read_some_bytes
= 1;
4608 else if (nread
== -1 && (errno
== EIO
|| errno
== EAGAIN
))
4611 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4615 if (read_some_bytes
&& do_display
)
4616 redisplay_preserve_echo_area (10);
4621 /* Wait till there is something to do */
4623 if (wait_proc
&& just_wait_proc
)
4625 if (wait_proc
->infd
< 0) /* Terminated */
4627 FD_SET (wait_proc
->infd
, &Available
);
4631 else if (!NILP (wait_for_cell
))
4633 compute_non_process_wait_mask (&Available
);
4640 compute_non_keyboard_wait_mask (&Available
);
4642 compute_input_wait_mask (&Available
);
4643 compute_write_mask (&Writeok
);
4644 #ifdef SELECT_CANT_DO_WRITE_MASK
4649 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4652 /* If frame size has changed or the window is newly mapped,
4653 redisplay now, before we start to wait. There is a race
4654 condition here; if a SIGIO arrives between now and the select
4655 and indicates that a frame is trashed, the select may block
4656 displaying a trashed screen. */
4657 if (frame_garbaged
&& do_display
)
4659 clear_waiting_for_input ();
4660 redisplay_preserve_echo_area (11);
4662 set_waiting_for_input (&timeout
);
4665 /* Skip the `select' call if input is available and we're
4666 waiting for keyboard input or a cell change (which can be
4667 triggered by processing X events). In the latter case, set
4668 nfds to 1 to avoid breaking the loop. */
4670 if ((read_kbd
|| !NILP (wait_for_cell
))
4671 && detect_input_pending ())
4673 nfds
= read_kbd
? 0 : 1;
4680 #ifdef ADAPTIVE_READ_BUFFERING
4681 /* Set the timeout for adaptive read buffering if any
4682 process has non-zero read_output_skip and non-zero
4683 read_output_delay, and we are not reading output for a
4684 specific wait_channel. It is not executed if
4685 Vprocess_adaptive_read_buffering is nil. */
4686 if (process_output_skip
&& check_delay
> 0)
4688 int nsecs
= EMACS_NSECS (timeout
);
4689 if (EMACS_SECS (timeout
) > 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4690 nsecs
= READ_OUTPUT_DELAY_MAX
;
4691 for (channel
= 0; check_delay
> 0 && channel
<= max_desc
; channel
++)
4693 proc
= chan_process
[channel
];
4696 /* Find minimum non-zero read_output_delay among the
4697 processes with non-zero read_output_skip. */
4698 if (XPROCESS (proc
)->read_output_delay
> 0)
4701 if (!XPROCESS (proc
)->read_output_skip
)
4703 FD_CLR (channel
, &Available
);
4704 XPROCESS (proc
)->read_output_skip
= 0;
4705 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4706 nsecs
= XPROCESS (proc
)->read_output_delay
;
4709 timeout
= make_emacs_time (0, nsecs
);
4710 process_output_skip
= 0;
4713 nfds
= thread_select (
4714 #if defined (HAVE_NS)
4716 #elif defined (HAVE_GLIB)
4723 (check_write
? &Writeok
: 0),
4724 NULL
, &timeout
, NULL
);
4727 /* GnuTLS buffers data internally. In lowat mode it leaves
4728 some data in the TCP buffers so that select works, but
4729 with custom pull/push functions we need to check if some
4730 data is available in the buffers manually. */
4735 /* We're not waiting on a specific process, so loop
4736 through all the channels and check for data.
4737 This is a workaround needed for some versions of
4738 the gnutls library -- 2.12.14 has been confirmed
4740 http://comments.gmane.org/gmane.emacs.devel/145074 */
4741 for (channel
= 0; channel
< MAXDESC
; ++channel
)
4742 if (! NILP (chan_process
[channel
]))
4744 struct Lisp_Process
*p
=
4745 XPROCESS (chan_process
[channel
]);
4746 if (p
&& p
->gnutls_p
&& p
->infd
4747 && ((emacs_gnutls_record_check_pending
4752 FD_SET (p
->infd
, &Available
);
4758 /* Check this specific channel. */
4759 if (wait_proc
->gnutls_p
/* Check for valid process. */
4760 /* Do we have pending data? */
4761 && ((emacs_gnutls_record_check_pending
4762 (wait_proc
->gnutls_state
))
4766 /* Set to Available. */
4767 FD_SET (wait_proc
->infd
, &Available
);
4776 /* Make C-g and alarm signals set flags again */
4777 clear_waiting_for_input ();
4779 /* If we woke up due to SIGWINCH, actually change size now. */
4780 do_pending_window_change (0);
4782 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4783 /* We waited the full specified time, so return now. */
4787 if (xerrno
== EINTR
)
4789 else if (xerrno
== EBADF
)
4792 report_file_errno ("Failed select", Qnil
, xerrno
);
4797 FD_ZERO (&Available
);
4801 /* Check for keyboard input */
4802 /* If there is any, return immediately
4803 to give it higher priority than subprocesses */
4807 unsigned old_timers_run
= timers_run
;
4808 struct buffer
*old_buffer
= current_buffer
;
4809 Lisp_Object old_window
= selected_window
;
4812 if (detect_input_pending_run_timers (do_display
))
4814 swallow_events (do_display
);
4815 if (detect_input_pending_run_timers (do_display
))
4819 /* If a timer has run, this might have changed buffers
4820 an alike. Make read_key_sequence aware of that. */
4821 if (timers_run
!= old_timers_run
4822 && waiting_for_user_input_p
== -1
4823 && (old_buffer
!= current_buffer
4824 || !EQ (old_window
, selected_window
)))
4825 record_asynch_buffer_change ();
4831 /* If there is unread keyboard input, also return. */
4833 && requeued_events_pending_p ())
4836 /* If we are not checking for keyboard input now,
4837 do process events (but don't run any timers).
4838 This is so that X events will be processed.
4839 Otherwise they may have to wait until polling takes place.
4840 That would causes delays in pasting selections, for example.
4842 (We used to do this only if wait_for_cell.) */
4843 if (read_kbd
== 0 && detect_input_pending ())
4845 swallow_events (do_display
);
4846 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4847 if (detect_input_pending ())
4852 /* Exit now if the cell we're waiting for became non-nil. */
4853 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4857 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4858 go read it. This can happen with X on BSD after logging out.
4859 In that case, there really is no input and no SIGIO,
4860 but select says there is input. */
4862 if (read_kbd
&& interrupt_input
4863 && keyboard_bit_set (&Available
) && ! noninteractive
)
4864 handle_input_available_signal (SIGIO
);
4868 got_some_input
|= nfds
> 0;
4870 /* If checking input just got us a size-change event from X,
4871 obey it now if we should. */
4872 if (read_kbd
|| ! NILP (wait_for_cell
))
4873 do_pending_window_change (0);
4875 /* Check for data from a process. */
4876 if (no_avail
|| nfds
== 0)
4879 for (channel
= 0; channel
<= max_desc
; ++channel
)
4881 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4883 && ((d
->flags
& FOR_READ
4884 && FD_ISSET (channel
, &Available
))
4885 || (d
->flags
& FOR_WRITE
4886 && FD_ISSET (channel
, &Writeok
))))
4887 d
->func (channel
, d
->data
);
4890 for (channel
= 0; channel
<= max_desc
; channel
++)
4892 if (FD_ISSET (channel
, &Available
)
4893 && ((fd_callback_info
[channel
].flags
& (KEYBOARD_FD
| PROCESS_FD
))
4898 /* If waiting for this channel, arrange to return as
4899 soon as no more input to be processed. No more
4901 if (wait_channel
== channel
)
4907 proc
= chan_process
[channel
];
4911 /* If this is a server stream socket, accept connection. */
4912 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4914 server_accept_connection (proc
, channel
);
4918 /* Read data from the process, starting with our
4919 buffered-ahead character if we have one. */
4921 nread
= read_process_output (proc
, channel
);
4924 /* Since read_process_output can run a filter,
4925 which can call accept-process-output,
4926 don't try to read from any other processes
4927 before doing the select again. */
4928 FD_ZERO (&Available
);
4931 redisplay_preserve_echo_area (12);
4934 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4937 else if (nread
== -1 && errno
== EAGAIN
)
4940 /* FIXME: Is this special case still needed? */
4941 /* Note that we cannot distinguish between no input
4942 available now and a closed pipe.
4943 With luck, a closed pipe will be accompanied by
4944 subprocess termination and SIGCHLD. */
4945 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4949 /* On some OSs with ptys, when the process on one end of
4950 a pty exits, the other end gets an error reading with
4951 errno = EIO instead of getting an EOF (0 bytes read).
4952 Therefore, if we get an error reading and errno =
4953 EIO, just continue, because the child process has
4954 exited and should clean itself up soon (e.g. when we
4956 else if (nread
== -1 && errno
== EIO
)
4958 struct Lisp_Process
*p
= XPROCESS (proc
);
4960 /* Clear the descriptor now, so we only raise the
4962 delete_read_fd (channel
);
4966 /* If the EIO occurs on a pty, the SIGCHLD handler's
4967 waitpid call will not find the process object to
4968 delete. Do it here. */
4969 p
->tick
= ++process_tick
;
4970 pset_status (p
, Qfailed
);
4973 #endif /* HAVE_PTYS */
4974 /* If we can detect process termination, don't consider the
4975 process gone just because its pipe is closed. */
4976 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4980 /* Preserve status of processes already terminated. */
4981 XPROCESS (proc
)->tick
= ++process_tick
;
4982 deactivate_process (proc
);
4983 if (XPROCESS (proc
)->raw_status_new
)
4984 update_status (XPROCESS (proc
));
4985 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4986 pset_status (XPROCESS (proc
),
4987 list2 (Qexit
, make_number (256)));
4990 #ifdef NON_BLOCKING_CONNECT
4991 if (FD_ISSET (channel
, &Writeok
)
4992 && (fd_callback_info
[channel
].flags
4993 & NON_BLOCKING_CONNECT_FD
) != 0)
4995 struct Lisp_Process
*p
;
4997 delete_write_fd (channel
);
4999 proc
= chan_process
[channel
];
5003 p
= XPROCESS (proc
);
5006 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5007 So only use it on systems where it is known to work. */
5009 socklen_t xlen
= sizeof (xerrno
);
5010 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5015 struct sockaddr pname
;
5016 int pnamelen
= sizeof (pname
);
5018 /* If connection failed, getpeername will fail. */
5020 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5022 /* Obtain connect failure code through error slippage. */
5025 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5032 p
->tick
= ++process_tick
;
5033 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5034 deactivate_process (proc
);
5038 pset_status (p
, Qrun
);
5039 /* Execute the sentinel here. If we had relied on
5040 status_notify to do it later, it will read input
5041 from the process before calling the sentinel. */
5042 exec_sentinel (proc
, build_string ("open\n"));
5043 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
5044 delete_read_fd (p
->infd
);
5047 #endif /* NON_BLOCKING_CONNECT */
5048 } /* End for each file descriptor. */
5049 } /* End while exit conditions not met. */
5051 unbind_to (count
, Qnil
);
5053 /* If calling from keyboard input, do not quit
5054 since we want to return C-g as an input character.
5055 Otherwise, do pending quit if requested. */
5058 /* Prevent input_pending from remaining set if we quit. */
5059 clear_input_pending ();
5063 return got_some_input
;
5066 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5069 read_process_output_call (Lisp_Object fun_and_args
)
5071 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5075 read_process_output_error_handler (Lisp_Object error_val
)
5077 cmd_error_internal (error_val
, "error in process filter: ");
5079 update_echo_area ();
5080 Fsleep_for (make_number (2), Qnil
);
5085 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5087 struct coding_system
*coding
);
5089 /* Read pending output from the process channel,
5090 starting with our buffered-ahead character if we have one.
5091 Yield number of decoded characters read.
5093 This function reads at most 4096 characters.
5094 If you want to read all available subprocess output,
5095 you must call it repeatedly until it returns zero.
5097 The characters read are decoded according to PROC's coding-system
5101 read_process_output (Lisp_Object proc
, register int channel
)
5103 register ssize_t nbytes
;
5105 register struct Lisp_Process
*p
= XPROCESS (proc
);
5106 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5107 int carryover
= p
->decoding_carryover
;
5109 ptrdiff_t count
= SPECPDL_INDEX ();
5110 Lisp_Object odeactivate
;
5112 chars
= alloca (carryover
+ readmax
);
5114 /* See the comment above. */
5115 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5117 #ifdef DATAGRAM_SOCKETS
5118 /* We have a working select, so proc_buffered_char is always -1. */
5119 if (DATAGRAM_CHAN_P (channel
))
5121 socklen_t len
= datagram_address
[channel
].len
;
5122 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5123 0, datagram_address
[channel
].sa
, &len
);
5128 bool buffered
= proc_buffered_char
[channel
] >= 0;
5131 chars
[carryover
] = proc_buffered_char
[channel
];
5132 proc_buffered_char
[channel
] = -1;
5136 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5137 readmax
- buffered
);
5140 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5141 readmax
- buffered
);
5142 #ifdef ADAPTIVE_READ_BUFFERING
5143 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5145 int delay
= p
->read_output_delay
;
5148 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5151 process_output_delay_count
++;
5152 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5155 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5157 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5159 process_output_delay_count
--;
5161 p
->read_output_delay
= delay
;
5164 p
->read_output_skip
= 1;
5165 process_output_skip
= 1;
5170 nbytes
+= buffered
&& nbytes
<= 0;
5173 p
->decoding_carryover
= 0;
5175 /* At this point, NBYTES holds number of bytes just received
5176 (including the one in proc_buffered_char[channel]). */
5179 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5181 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5184 /* Now set NBYTES how many bytes we must decode. */
5185 nbytes
+= carryover
;
5187 odeactivate
= Vdeactivate_mark
;
5188 /* There's no good reason to let process filters change the current
5189 buffer, and many callers of accept-process-output, sit-for, and
5190 friends don't expect current-buffer to be changed from under them. */
5191 record_unwind_current_buffer ();
5193 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5195 /* Handling the process output should not deactivate the mark. */
5196 Vdeactivate_mark
= odeactivate
;
5198 unbind_to (count
, Qnil
);
5203 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5205 struct coding_system
*coding
)
5207 Lisp_Object outstream
= p
->filter
;
5209 bool outer_running_asynch_code
= running_asynch_code
;
5210 int waiting
= waiting_for_user_input_p
;
5212 /* No need to gcpro these, because all we do with them later
5213 is test them for EQness, and none of them should be a string. */
5215 Lisp_Object obuffer
, okeymap
;
5216 XSETBUFFER (obuffer
, current_buffer
);
5217 okeymap
= BVAR (current_buffer
, keymap
);
5220 /* We inhibit quit here instead of just catching it so that
5221 hitting ^G when a filter happens to be running won't screw
5223 specbind (Qinhibit_quit
, Qt
);
5224 specbind (Qlast_nonmenu_event
, Qt
);
5226 /* In case we get recursively called,
5227 and we already saved the match data nonrecursively,
5228 save the same match data in safely recursive fashion. */
5229 if (outer_running_asynch_code
)
5232 /* Don't clobber the CURRENT match data, either! */
5233 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5234 restore_search_regs ();
5235 record_unwind_save_match_data ();
5236 Fset_match_data (tem
, Qt
);
5239 /* For speed, if a search happens within this code,
5240 save the match data in a special nonrecursive fashion. */
5241 running_asynch_code
= 1;
5243 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5244 text
= coding
->dst_object
;
5245 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5246 /* A new coding system might be found. */
5247 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5249 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5251 /* Don't call setup_coding_system for
5252 proc_decode_coding_system[channel] here. It is done in
5253 detect_coding called via decode_coding above. */
5255 /* If a coding system for encoding is not yet decided, we set
5256 it as the same as coding-system for decoding.
5258 But, before doing that we must check if
5259 proc_encode_coding_system[p->outfd] surely points to a
5260 valid memory because p->outfd will be changed once EOF is
5261 sent to the process. */
5262 if (NILP (p
->encode_coding_system
)
5263 && proc_encode_coding_system
[p
->outfd
])
5265 pset_encode_coding_system
5266 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5267 setup_coding_system (p
->encode_coding_system
,
5268 proc_encode_coding_system
[p
->outfd
]);
5272 if (coding
->carryover_bytes
> 0)
5274 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5275 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5276 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5277 coding
->carryover_bytes
);
5278 p
->decoding_carryover
= coding
->carryover_bytes
;
5280 if (SBYTES (text
) > 0)
5281 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5282 sometimes it's simply wrong to wrap (e.g. when called from
5283 accept-process-output). */
5284 internal_condition_case_1 (read_process_output_call
,
5285 list3 (outstream
, make_lisp_proc (p
), text
),
5286 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5287 read_process_output_error_handler
);
5289 /* If we saved the match data nonrecursively, restore it now. */
5290 restore_search_regs ();
5291 running_asynch_code
= outer_running_asynch_code
;
5293 /* Restore waiting_for_user_input_p as it was
5294 when we were called, in case the filter clobbered it. */
5295 waiting_for_user_input_p
= waiting
;
5297 #if 0 /* Call record_asynch_buffer_change unconditionally,
5298 because we might have changed minor modes or other things
5299 that affect key bindings. */
5300 if (! EQ (Fcurrent_buffer (), obuffer
)
5301 || ! EQ (current_buffer
->keymap
, okeymap
))
5303 /* But do it only if the caller is actually going to read events.
5304 Otherwise there's no need to make him wake up, and it could
5305 cause trouble (for example it would make sit_for return). */
5306 if (waiting_for_user_input_p
== -1)
5307 record_asynch_buffer_change ();
5310 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5311 Sinternal_default_process_filter
, 2, 2, 0,
5312 doc
: /* Function used as default process filter. */)
5313 (Lisp_Object proc
, Lisp_Object text
)
5315 struct Lisp_Process
*p
;
5318 CHECK_PROCESS (proc
);
5319 p
= XPROCESS (proc
);
5320 CHECK_STRING (text
);
5322 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5324 Lisp_Object old_read_only
;
5325 ptrdiff_t old_begv
, old_zv
;
5326 ptrdiff_t old_begv_byte
, old_zv_byte
;
5327 ptrdiff_t before
, before_byte
;
5328 ptrdiff_t opoint_byte
;
5331 Fset_buffer (p
->buffer
);
5333 opoint_byte
= PT_BYTE
;
5334 old_read_only
= BVAR (current_buffer
, read_only
);
5337 old_begv_byte
= BEGV_BYTE
;
5338 old_zv_byte
= ZV_BYTE
;
5340 bset_read_only (current_buffer
, Qnil
);
5342 /* Insert new output into buffer
5343 at the current end-of-output marker,
5344 thus preserving logical ordering of input and output. */
5345 if (XMARKER (p
->mark
)->buffer
)
5346 SET_PT_BOTH (clip_to_bounds (BEGV
,
5347 marker_position (p
->mark
), ZV
),
5348 clip_to_bounds (BEGV_BYTE
,
5349 marker_byte_position (p
->mark
),
5352 SET_PT_BOTH (ZV
, ZV_BYTE
);
5354 before_byte
= PT_BYTE
;
5356 /* If the output marker is outside of the visible region, save
5357 the restriction and widen. */
5358 if (! (BEGV
<= PT
&& PT
<= ZV
))
5361 /* Adjust the multibyteness of TEXT to that of the buffer. */
5362 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5363 != ! STRING_MULTIBYTE (text
))
5364 text
= (STRING_MULTIBYTE (text
)
5365 ? Fstring_as_unibyte (text
)
5366 : Fstring_to_multibyte (text
));
5367 /* Insert before markers in case we are inserting where
5368 the buffer's mark is, and the user's next command is Meta-y. */
5369 insert_from_string_before_markers (text
, 0, 0,
5370 SCHARS (text
), SBYTES (text
), 0);
5372 /* Make sure the process marker's position is valid when the
5373 process buffer is changed in the signal_after_change above.
5374 W3 is known to do that. */
5375 if (BUFFERP (p
->buffer
)
5376 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5377 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5379 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5381 update_mode_lines
++;
5383 /* Make sure opoint and the old restrictions
5384 float ahead of any new text just as point would. */
5385 if (opoint
>= before
)
5387 opoint
+= PT
- before
;
5388 opoint_byte
+= PT_BYTE
- before_byte
;
5390 if (old_begv
> before
)
5392 old_begv
+= PT
- before
;
5393 old_begv_byte
+= PT_BYTE
- before_byte
;
5395 if (old_zv
>= before
)
5397 old_zv
+= PT
- before
;
5398 old_zv_byte
+= PT_BYTE
- before_byte
;
5401 /* If the restriction isn't what it should be, set it. */
5402 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5403 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5405 bset_read_only (current_buffer
, old_read_only
);
5406 SET_PT_BOTH (opoint
, opoint_byte
);
5411 /* Sending data to subprocess. */
5413 /* In send_process, when a write fails temporarily,
5414 wait_reading_process_output is called. It may execute user code,
5415 e.g. timers, that attempts to write new data to the same process.
5416 We must ensure that data is sent in the right order, and not
5417 interspersed half-completed with other writes (Bug#10815). This is
5418 handled by the write_queue element of struct process. It is a list
5419 with each entry having the form
5421 (string . (offset . length))
5423 where STRING is a lisp string, OFFSET is the offset into the
5424 string's byte sequence from which we should begin to send, and
5425 LENGTH is the number of bytes left to send. */
5427 /* Create a new entry in write_queue.
5428 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5429 BUF is a pointer to the string sequence of the input_obj or a C
5430 string in case of Qt or Qnil. */
5433 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5434 const char *buf
, ptrdiff_t len
, bool front
)
5437 Lisp_Object entry
, obj
;
5439 if (STRINGP (input_obj
))
5441 offset
= buf
- SSDATA (input_obj
);
5447 obj
= make_unibyte_string (buf
, len
);
5450 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5453 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5455 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5458 /* Remove the first element in the write_queue of process P, put its
5459 contents in OBJ, BUF and LEN, and return true. If the
5460 write_queue is empty, return false. */
5463 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5464 const char **buf
, ptrdiff_t *len
)
5466 Lisp_Object entry
, offset_length
;
5469 if (NILP (p
->write_queue
))
5472 entry
= XCAR (p
->write_queue
);
5473 pset_write_queue (p
, XCDR (p
->write_queue
));
5475 *obj
= XCAR (entry
);
5476 offset_length
= XCDR (entry
);
5478 *len
= XINT (XCDR (offset_length
));
5479 offset
= XINT (XCAR (offset_length
));
5480 *buf
= SSDATA (*obj
) + offset
;
5485 /* Send some data to process PROC.
5486 BUF is the beginning of the data; LEN is the number of characters.
5487 OBJECT is the Lisp object that the data comes from. If OBJECT is
5488 nil or t, it means that the data comes from C string.
5490 If OBJECT is not nil, the data is encoded by PROC's coding-system
5491 for encoding before it is sent.
5493 This function can evaluate Lisp code and can garbage collect. */
5496 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5499 struct Lisp_Process
*p
= XPROCESS (proc
);
5501 struct coding_system
*coding
;
5503 if (p
->raw_status_new
)
5505 if (! EQ (p
->status
, Qrun
))
5506 error ("Process %s not running", SDATA (p
->name
));
5508 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5510 coding
= proc_encode_coding_system
[p
->outfd
];
5511 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5513 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5514 || (BUFFERP (object
)
5515 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5518 pset_encode_coding_system
5519 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5520 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5522 /* The coding system for encoding was changed to raw-text
5523 because we sent a unibyte text previously. Now we are
5524 sending a multibyte text, thus we must encode it by the
5525 original coding system specified for the current process.
5527 Another reason we come here is that the coding system
5528 was just complemented and a new one was returned by
5529 complement_process_encoding_system. */
5530 setup_coding_system (p
->encode_coding_system
, coding
);
5531 Vlast_coding_system_used
= p
->encode_coding_system
;
5533 coding
->src_multibyte
= 1;
5537 coding
->src_multibyte
= 0;
5538 /* For sending a unibyte text, character code conversion should
5539 not take place but EOL conversion should. So, setup raw-text
5540 or one of the subsidiary if we have not yet done it. */
5541 if (CODING_REQUIRE_ENCODING (coding
))
5543 if (CODING_REQUIRE_FLUSHING (coding
))
5545 /* But, before changing the coding, we must flush out data. */
5546 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5547 send_process (proc
, "", 0, Qt
);
5548 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5550 setup_coding_system (raw_text_coding_system
5551 (Vlast_coding_system_used
),
5553 coding
->src_multibyte
= 0;
5556 coding
->dst_multibyte
= 0;
5558 if (CODING_REQUIRE_ENCODING (coding
))
5560 coding
->dst_object
= Qt
;
5561 if (BUFFERP (object
))
5563 ptrdiff_t from_byte
, from
, to
;
5564 ptrdiff_t save_pt
, save_pt_byte
;
5565 struct buffer
*cur
= current_buffer
;
5567 set_buffer_internal (XBUFFER (object
));
5568 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5570 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5571 from
= BYTE_TO_CHAR (from_byte
);
5572 to
= BYTE_TO_CHAR (from_byte
+ len
);
5573 TEMP_SET_PT_BOTH (from
, from_byte
);
5574 encode_coding_object (coding
, object
, from
, from_byte
,
5575 to
, from_byte
+ len
, Qt
);
5576 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5577 set_buffer_internal (cur
);
5579 else if (STRINGP (object
))
5581 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5582 SBYTES (object
), Qt
);
5586 coding
->dst_object
= make_unibyte_string (buf
, len
);
5587 coding
->produced
= len
;
5590 len
= coding
->produced
;
5591 object
= coding
->dst_object
;
5592 buf
= SSDATA (object
);
5595 /* If there is already data in the write_queue, put the new data
5596 in the back of queue. Otherwise, ignore it. */
5597 if (!NILP (p
->write_queue
))
5598 write_queue_push (p
, object
, buf
, len
, 0);
5600 do /* while !NILP (p->write_queue) */
5602 ptrdiff_t cur_len
= -1;
5603 const char *cur_buf
;
5604 Lisp_Object cur_object
;
5606 /* If write_queue is empty, ignore it. */
5607 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5611 cur_object
= object
;
5616 /* Send this batch, using one or more write calls. */
5617 ptrdiff_t written
= 0;
5618 int outfd
= p
->outfd
;
5619 #ifdef DATAGRAM_SOCKETS
5620 if (DATAGRAM_CHAN_P (outfd
))
5622 rv
= sendto (outfd
, cur_buf
, cur_len
,
5623 0, datagram_address
[outfd
].sa
,
5624 datagram_address
[outfd
].len
);
5627 else if (errno
== EMSGSIZE
)
5628 report_file_error ("Sending datagram", proc
);
5635 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5638 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5639 rv
= (written
? 0 : -1);
5640 #ifdef ADAPTIVE_READ_BUFFERING
5641 if (p
->read_output_delay
> 0
5642 && p
->adaptive_read_buffering
== 1)
5644 p
->read_output_delay
= 0;
5645 process_output_delay_count
--;
5646 p
->read_output_skip
= 0;
5655 || errno
== EWOULDBLOCK
5658 /* Buffer is full. Wait, accepting input;
5659 that may allow the program
5660 to finish doing output and read more. */
5662 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5663 /* A gross hack to work around a bug in FreeBSD.
5664 In the following sequence, read(2) returns
5668 write(2) 954 bytes, get EAGAIN
5669 read(2) 1024 bytes in process_read_output
5670 read(2) 11 bytes in process_read_output
5672 That is, read(2) returns more bytes than have
5673 ever been written successfully. The 1033 bytes
5674 read are the 1022 bytes written successfully
5675 after processing (for example with CRs added if
5676 the terminal is set up that way which it is
5677 here). The same bytes will be seen again in a
5678 later read(2), without the CRs. */
5680 if (errno
== EAGAIN
)
5683 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5685 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5687 /* Put what we should have written in wait_queue. */
5688 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5689 wait_reading_process_output (0, 20 * 1000 * 1000,
5690 0, 0, Qnil
, NULL
, 0);
5691 /* Reread queue, to see what is left. */
5694 else if (errno
== EPIPE
)
5696 p
->raw_status_new
= 0;
5697 pset_status (p
, list2 (Qexit
, make_number (256)));
5698 p
->tick
= ++process_tick
;
5699 deactivate_process (proc
);
5700 error ("process %s no longer connected to pipe; closed it",
5704 /* This is a real error. */
5705 report_file_error ("Writing to process", proc
);
5711 while (!NILP (p
->write_queue
));
5714 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5716 doc
: /* Send current contents of region as input to PROCESS.
5717 PROCESS may be a process, a buffer, the name of a process or buffer, or
5718 nil, indicating the current buffer's process.
5719 Called from program, takes three arguments, PROCESS, START and END.
5720 If the region is more than 500 characters long,
5721 it is sent in several bunches. This may happen even for shorter regions.
5722 Output from processes can arrive in between bunches. */)
5723 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5725 Lisp_Object proc
= get_process (process
);
5726 ptrdiff_t start_byte
, end_byte
;
5728 validate_region (&start
, &end
);
5730 start_byte
= CHAR_TO_BYTE (XINT (start
));
5731 end_byte
= CHAR_TO_BYTE (XINT (end
));
5733 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5734 move_gap_both (XINT (start
), start_byte
);
5736 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5737 end_byte
- start_byte
, Fcurrent_buffer ());
5742 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5744 doc
: /* Send PROCESS the contents of STRING as input.
5745 PROCESS may be a process, a buffer, the name of a process or buffer, or
5746 nil, indicating the current buffer's process.
5747 If STRING is more than 500 characters long,
5748 it is sent in several bunches. This may happen even for shorter strings.
5749 Output from processes can arrive in between bunches. */)
5750 (Lisp_Object process
, Lisp_Object string
)
5753 CHECK_STRING (string
);
5754 proc
= get_process (process
);
5755 send_process (proc
, SSDATA (string
),
5756 SBYTES (string
), string
);
5760 /* Return the foreground process group for the tty/pty that
5761 the process P uses. */
5763 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5768 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5771 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5772 master side. Try the slave side. */
5773 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5777 ioctl (fd
, TIOCGPGRP
, &gid
);
5781 #endif /* defined (TIOCGPGRP ) */
5786 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5787 Sprocess_running_child_p
, 0, 1, 0,
5788 doc
: /* Return t if PROCESS has given the terminal to a child.
5789 If the operating system does not make it possible to find out,
5790 return t unconditionally. */)
5791 (Lisp_Object process
)
5793 /* Initialize in case ioctl doesn't exist or gives an error,
5794 in a way that will cause returning t. */
5797 struct Lisp_Process
*p
;
5799 proc
= get_process (process
);
5800 p
= XPROCESS (proc
);
5802 if (!EQ (p
->type
, Qreal
))
5803 error ("Process %s is not a subprocess",
5806 error ("Process %s is not active",
5809 gid
= emacs_get_tty_pgrp (p
);
5816 /* send a signal number SIGNO to PROCESS.
5817 If CURRENT_GROUP is t, that means send to the process group
5818 that currently owns the terminal being used to communicate with PROCESS.
5819 This is used for various commands in shell mode.
5820 If CURRENT_GROUP is lambda, that means send to the process group
5821 that currently owns the terminal, but only if it is NOT the shell itself.
5823 If NOMSG is false, insert signal-announcements into process's buffers
5826 If we can, we try to signal PROCESS by sending control characters
5827 down the pty. This allows us to signal inferiors who have changed
5828 their uid, for which kill would return an EPERM error. */
5831 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5835 struct Lisp_Process
*p
;
5839 proc
= get_process (process
);
5840 p
= XPROCESS (proc
);
5842 if (!EQ (p
->type
, Qreal
))
5843 error ("Process %s is not a subprocess",
5846 error ("Process %s is not active",
5850 current_group
= Qnil
;
5852 /* If we are using pgrps, get a pgrp number and make it negative. */
5853 if (NILP (current_group
))
5854 /* Send the signal to the shell's process group. */
5858 #ifdef SIGNALS_VIA_CHARACTERS
5859 /* If possible, send signals to the entire pgrp
5860 by sending an input character to it. */
5863 cc_t
*sig_char
= NULL
;
5865 tcgetattr (p
->infd
, &t
);
5870 sig_char
= &t
.c_cc
[VINTR
];
5874 sig_char
= &t
.c_cc
[VQUIT
];
5878 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5879 sig_char
= &t
.c_cc
[VSWTCH
];
5881 sig_char
= &t
.c_cc
[VSUSP
];
5886 if (sig_char
&& *sig_char
!= CDISABLE
)
5888 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5891 /* If we can't send the signal with a character,
5892 fall through and send it another way. */
5894 /* The code above may fall through if it can't
5895 handle the signal. */
5896 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5899 /* Get the current pgrp using the tty itself, if we have that.
5900 Otherwise, use the pty to get the pgrp.
5901 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5902 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5903 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5904 His patch indicates that if TIOCGPGRP returns an error, then
5905 we should just assume that p->pid is also the process group id. */
5907 gid
= emacs_get_tty_pgrp (p
);
5910 /* If we can't get the information, assume
5911 the shell owns the tty. */
5914 /* It is not clear whether anything really can set GID to -1.
5915 Perhaps on some system one of those ioctls can or could do so.
5916 Or perhaps this is vestigial. */
5919 #else /* ! defined (TIOCGPGRP ) */
5920 /* Can't select pgrps on this system, so we know that
5921 the child itself heads the pgrp. */
5923 #endif /* ! defined (TIOCGPGRP ) */
5925 /* If current_group is lambda, and the shell owns the terminal,
5926 don't send any signal. */
5927 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5935 p
->raw_status_new
= 0;
5936 pset_status (p
, Qrun
);
5937 p
->tick
= ++process_tick
;
5940 status_notify (NULL
);
5941 redisplay_preserve_echo_area (13);
5944 #endif /* ! defined (SIGCONT) */
5948 flush_pending_output (p
->infd
);
5952 /* If we don't have process groups, send the signal to the immediate
5953 subprocess. That isn't really right, but it's better than any
5954 obvious alternative. */
5957 kill (p
->pid
, signo
);
5961 /* gid may be a pid, or minus a pgrp's number */
5963 if (!NILP (current_group
))
5965 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
5973 #else /* ! defined (TIOCSIGSEND) */
5975 #endif /* ! defined (TIOCSIGSEND) */
5978 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5979 doc
: /* Interrupt process PROCESS.
5980 PROCESS may be a process, a buffer, or the name of a process or buffer.
5981 No arg or nil means current buffer's process.
5982 Second arg CURRENT-GROUP non-nil means send signal to
5983 the current process-group of the process's controlling terminal
5984 rather than to the process's own process group.
5985 If the process is a shell, this means interrupt current subjob
5986 rather than the shell.
5988 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5989 don't send the signal. */)
5990 (Lisp_Object process
, Lisp_Object current_group
)
5992 process_send_signal (process
, SIGINT
, current_group
, 0);
5996 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5997 doc
: /* Kill process PROCESS. May be process or name of one.
5998 See function `interrupt-process' for more details on usage. */)
5999 (Lisp_Object process
, Lisp_Object current_group
)
6001 process_send_signal (process
, SIGKILL
, current_group
, 0);
6005 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6006 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6007 See function `interrupt-process' for more details on usage. */)
6008 (Lisp_Object process
, Lisp_Object current_group
)
6010 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6014 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6015 doc
: /* Stop process PROCESS. May be process or name of one.
6016 See function `interrupt-process' for more details on usage.
6017 If PROCESS is a network or serial process, inhibit handling of incoming
6019 (Lisp_Object process
, Lisp_Object current_group
)
6021 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6023 struct Lisp_Process
*p
;
6025 p
= XPROCESS (process
);
6026 if (NILP (p
->command
)
6028 delete_read_fd (p
->infd
);
6029 pset_command (p
, Qt
);
6033 error ("No SIGTSTP support");
6035 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6040 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6041 doc
: /* Continue process PROCESS. May be process or name of one.
6042 See function `interrupt-process' for more details on usage.
6043 If PROCESS is a network or serial process, resume handling of incoming
6045 (Lisp_Object process
, Lisp_Object current_group
)
6047 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6049 struct Lisp_Process
*p
;
6051 p
= XPROCESS (process
);
6052 if (EQ (p
->command
, Qt
)
6054 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6056 add_non_keyboard_read_fd (p
->infd
);
6058 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6059 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6060 #else /* not WINDOWSNT */
6061 tcflush (p
->infd
, TCIFLUSH
);
6062 #endif /* not WINDOWSNT */
6064 pset_command (p
, Qnil
);
6068 process_send_signal (process
, SIGCONT
, current_group
, 0);
6070 error ("No SIGCONT support");
6075 /* Return the integer value of the signal whose abbreviation is ABBR,
6076 or a negative number if there is no such signal. */
6078 abbr_to_signal (char const *name
)
6081 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6083 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6086 for (i
= 0; i
< sizeof sigbuf
; i
++)
6088 sigbuf
[i
] = c_toupper (name
[i
]);
6090 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6096 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6097 2, 2, "sProcess (name or number): \nnSignal code: ",
6098 doc
: /* Send PROCESS the signal with code SIGCODE.
6099 PROCESS may also be a number specifying the process id of the
6100 process to signal; in this case, the process need not be a child of
6102 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6103 (Lisp_Object process
, Lisp_Object sigcode
)
6108 if (STRINGP (process
))
6110 Lisp_Object tem
= Fget_process (process
);
6113 Lisp_Object process_number
=
6114 string_to_number (SSDATA (process
), 10, 1);
6115 if (INTEGERP (process_number
) || FLOATP (process_number
))
6116 tem
= process_number
;
6120 else if (!NUMBERP (process
))
6121 process
= get_process (process
);
6126 if (NUMBERP (process
))
6127 CONS_TO_INTEGER (process
, pid_t
, pid
);
6130 CHECK_PROCESS (process
);
6131 pid
= XPROCESS (process
)->pid
;
6133 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6136 if (INTEGERP (sigcode
))
6138 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6139 signo
= XINT (sigcode
);
6145 CHECK_SYMBOL (sigcode
);
6146 name
= SSDATA (SYMBOL_NAME (sigcode
));
6148 signo
= abbr_to_signal (name
);
6150 error ("Undefined signal name %s", name
);
6153 return make_number (kill (pid
, signo
));
6156 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6157 doc
: /* Make PROCESS see end-of-file in its input.
6158 EOF comes after any text already sent to it.
6159 PROCESS may be a process, a buffer, the name of a process or buffer, or
6160 nil, indicating the current buffer's process.
6161 If PROCESS is a network connection, or is a process communicating
6162 through a pipe (as opposed to a pty), then you cannot send any more
6163 text to PROCESS after you call this function.
6164 If PROCESS is a serial process, wait until all output written to the
6165 process has been transmitted to the serial port. */)
6166 (Lisp_Object process
)
6169 struct coding_system
*coding
;
6171 if (DATAGRAM_CONN_P (process
))
6174 proc
= get_process (process
);
6175 coding
= proc_encode_coding_system
[XPROCESS (proc
)->outfd
];
6177 /* Make sure the process is really alive. */
6178 if (XPROCESS (proc
)->raw_status_new
)
6179 update_status (XPROCESS (proc
));
6180 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6181 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6183 if (CODING_REQUIRE_FLUSHING (coding
))
6185 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6186 send_process (proc
, "", 0, Qnil
);
6189 if (XPROCESS (proc
)->pty_flag
)
6190 send_process (proc
, "\004", 1, Qnil
);
6191 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6194 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6195 report_file_error ("Failed tcdrain", Qnil
);
6196 #endif /* not WINDOWSNT */
6197 /* Do nothing on Windows because writes are blocking. */
6201 int old_outfd
= XPROCESS (proc
)->outfd
;
6204 #ifdef HAVE_SHUTDOWN
6205 /* If this is a network connection, or socketpair is used
6206 for communication with the subprocess, call shutdown to cause EOF.
6207 (In some old system, shutdown to socketpair doesn't work.
6208 Then we just can't win.) */
6209 if (EQ (XPROCESS (proc
)->type
, Qnetwork
)
6210 || XPROCESS (proc
)->infd
== old_outfd
)
6211 shutdown (old_outfd
, 1);
6213 close_process_fd (&XPROCESS (proc
)->open_fd
[WRITE_TO_SUBPROCESS
]);
6214 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6216 report_file_error ("Opening null device", Qnil
);
6217 XPROCESS (proc
)->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6218 XPROCESS (proc
)->outfd
= new_outfd
;
6220 if (!proc_encode_coding_system
[new_outfd
])
6221 proc_encode_coding_system
[new_outfd
]
6222 = xmalloc (sizeof (struct coding_system
));
6223 *proc_encode_coding_system
[new_outfd
]
6224 = *proc_encode_coding_system
[old_outfd
];
6225 memset (proc_encode_coding_system
[old_outfd
], 0,
6226 sizeof (struct coding_system
));
6231 /* The main Emacs thread records child processes in three places:
6233 - Vprocess_alist, for asynchronous subprocesses, which are child
6234 processes visible to Lisp.
6236 - deleted_pid_list, for child processes invisible to Lisp,
6237 typically because of delete-process. These are recorded so that
6238 the processes can be reaped when they exit, so that the operating
6239 system's process table is not cluttered by zombies.
6241 - the local variable PID in Fcall_process, call_process_cleanup and
6242 call_process_kill, for synchronous subprocesses.
6243 record_unwind_protect is used to make sure this process is not
6244 forgotten: if the user interrupts call-process and the child
6245 process refuses to exit immediately even with two C-g's,
6246 call_process_kill adds PID's contents to deleted_pid_list before
6249 The main Emacs thread invokes waitpid only on child processes that
6250 it creates and that have not been reaped. This avoid races on
6251 platforms such as GTK, where other threads create their own
6252 subprocesses which the main thread should not reap. For example,
6253 if the main thread attempted to reap an already-reaped child, it
6254 might inadvertently reap a GTK-created process that happened to
6255 have the same process ID. */
6257 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6258 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6259 keep track of its own children. GNUstep is similar. */
6261 static void dummy_handler (int sig
) {}
6262 static signal_handler_t
volatile lib_child_handler
;
6264 /* Handle a SIGCHLD signal by looking for known child processes of
6265 Emacs whose status have changed. For each one found, record its
6268 All we do is change the status; we do not run sentinels or print
6269 notifications. That is saved for the next time keyboard input is
6270 done, in order to avoid timing errors.
6272 ** WARNING: this can be called during garbage collection.
6273 Therefore, it must not be fooled by the presence of mark bits in
6276 ** USG WARNING: Although it is not obvious from the documentation
6277 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6278 signal() before executing at least one wait(), otherwise the
6279 handler will be called again, resulting in an infinite loop. The
6280 relevant portion of the documentation reads "SIGCLD signals will be
6281 queued and the signal-catching function will be continually
6282 reentered until the queue is empty". Invoking signal() causes the
6283 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6286 ** Malloc WARNING: This should never call malloc either directly or
6287 indirectly; if it does, that is a bug */
6290 handle_child_signal (int sig
)
6292 Lisp_Object tail
, proc
;
6294 /* Find the process that signaled us, and record its status. */
6296 /* The process can have been deleted by Fdelete_process, or have
6297 been started asynchronously by Fcall_process. */
6298 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6300 bool all_pids_are_fixnums
6301 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6302 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6303 Lisp_Object head
= XCAR (tail
);
6308 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6311 if (INTEGERP (xpid
))
6312 deleted_pid
= XINT (xpid
);
6314 deleted_pid
= XFLOAT_DATA (xpid
);
6315 if (child_status_changed (deleted_pid
, 0, 0))
6317 if (STRINGP (XCDR (head
)))
6318 unlink (SSDATA (XCDR (head
)));
6319 XSETCAR (tail
, Qnil
);
6324 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6325 FOR_EACH_PROCESS (tail
, proc
)
6327 struct Lisp_Process
*p
= XPROCESS (proc
);
6331 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6333 /* Change the status of the process that was found. */
6334 p
->tick
= ++process_tick
;
6335 p
->raw_status
= status
;
6336 p
->raw_status_new
= 1;
6338 /* If process has terminated, stop waiting for its output. */
6339 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6341 bool clear_desc_flag
= 0;
6344 clear_desc_flag
= 1;
6346 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6347 if (clear_desc_flag
)
6348 delete_read_fd (p
->infd
);
6353 lib_child_handler (sig
);
6354 #ifdef NS_IMPL_GNUSTEP
6355 /* NSTask in GNUStep sets its child handler each time it is called.
6356 So we must re-set ours. */
6357 catch_child_signal();
6362 deliver_child_signal (int sig
)
6364 deliver_process_signal (sig
, handle_child_signal
);
6369 exec_sentinel_error_handler (Lisp_Object error_val
)
6371 cmd_error_internal (error_val
, "error in process sentinel: ");
6373 update_echo_area ();
6374 Fsleep_for (make_number (2), Qnil
);
6379 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6381 Lisp_Object sentinel
, odeactivate
;
6382 struct Lisp_Process
*p
= XPROCESS (proc
);
6383 ptrdiff_t count
= SPECPDL_INDEX ();
6384 bool outer_running_asynch_code
= running_asynch_code
;
6385 int waiting
= waiting_for_user_input_p
;
6387 if (inhibit_sentinels
)
6390 /* No need to gcpro these, because all we do with them later
6391 is test them for EQness, and none of them should be a string. */
6392 odeactivate
= Vdeactivate_mark
;
6394 Lisp_Object obuffer
, okeymap
;
6395 XSETBUFFER (obuffer
, current_buffer
);
6396 okeymap
= BVAR (current_buffer
, keymap
);
6399 /* There's no good reason to let sentinels change the current
6400 buffer, and many callers of accept-process-output, sit-for, and
6401 friends don't expect current-buffer to be changed from under them. */
6402 record_unwind_current_buffer ();
6404 sentinel
= p
->sentinel
;
6406 /* Inhibit quit so that random quits don't screw up a running filter. */
6407 specbind (Qinhibit_quit
, Qt
);
6408 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6410 /* In case we get recursively called,
6411 and we already saved the match data nonrecursively,
6412 save the same match data in safely recursive fashion. */
6413 if (outer_running_asynch_code
)
6416 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6417 restore_search_regs ();
6418 record_unwind_save_match_data ();
6419 Fset_match_data (tem
, Qt
);
6422 /* For speed, if a search happens within this code,
6423 save the match data in a special nonrecursive fashion. */
6424 running_asynch_code
= 1;
6426 internal_condition_case_1 (read_process_output_call
,
6427 list3 (sentinel
, proc
, reason
),
6428 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6429 exec_sentinel_error_handler
);
6431 /* If we saved the match data nonrecursively, restore it now. */
6432 restore_search_regs ();
6433 running_asynch_code
= outer_running_asynch_code
;
6435 Vdeactivate_mark
= odeactivate
;
6437 /* Restore waiting_for_user_input_p as it was
6438 when we were called, in case the filter clobbered it. */
6439 waiting_for_user_input_p
= waiting
;
6442 if (! EQ (Fcurrent_buffer (), obuffer
)
6443 || ! EQ (current_buffer
->keymap
, okeymap
))
6445 /* But do it only if the caller is actually going to read events.
6446 Otherwise there's no need to make him wake up, and it could
6447 cause trouble (for example it would make sit_for return). */
6448 if (waiting_for_user_input_p
== -1)
6449 record_asynch_buffer_change ();
6451 unbind_to (count
, Qnil
);
6454 /* Report all recent events of a change in process status
6455 (either run the sentinel or output a message).
6456 This is usually done while Emacs is waiting for keyboard input
6457 but can be done at other times. */
6460 status_notify (struct Lisp_Process
*deleting_process
)
6462 register Lisp_Object proc
;
6463 Lisp_Object tail
, msg
;
6464 struct gcpro gcpro1
, gcpro2
;
6468 /* We need to gcpro tail; if read_process_output calls a filter
6469 which deletes a process and removes the cons to which tail points
6470 from Vprocess_alist, and then causes a GC, tail is an unprotected
6474 /* Set this now, so that if new processes are created by sentinels
6475 that we run, we get called again to handle their status changes. */
6476 update_tick
= process_tick
;
6478 FOR_EACH_PROCESS (tail
, proc
)
6481 register struct Lisp_Process
*p
= XPROCESS (proc
);
6483 if (p
->tick
!= p
->update_tick
)
6485 p
->update_tick
= p
->tick
;
6487 /* If process is still active, read any output that remains. */
6488 while (! EQ (p
->filter
, Qt
)
6489 && ! EQ (p
->status
, Qconnect
)
6490 && ! EQ (p
->status
, Qlisten
)
6491 /* Network or serial process not stopped: */
6492 && ! EQ (p
->command
, Qt
)
6494 && p
!= deleting_process
6495 && read_process_output (proc
, p
->infd
) > 0);
6497 /* Get the text to use for the message. */
6498 if (p
->raw_status_new
)
6500 msg
= status_message (p
);
6502 /* If process is terminated, deactivate it or delete it. */
6504 if (CONSP (p
->status
))
6505 symbol
= XCAR (p
->status
);
6507 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6508 || EQ (symbol
, Qclosed
))
6510 if (delete_exited_processes
)
6511 remove_process (proc
);
6513 deactivate_process (proc
);
6516 /* The actions above may have further incremented p->tick.
6517 So set p->update_tick again so that an error in the sentinel will
6518 not cause this code to be run again. */
6519 p
->update_tick
= p
->tick
;
6520 /* Now output the message suitably. */
6521 exec_sentinel (proc
, msg
);
6525 update_mode_lines
++; /* In case buffers use %s in mode-line-format. */
6529 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6530 Sinternal_default_process_sentinel
, 2, 2, 0,
6531 doc
: /* Function used as default sentinel for processes. */)
6532 (Lisp_Object proc
, Lisp_Object msg
)
6534 Lisp_Object buffer
, symbol
;
6535 struct Lisp_Process
*p
;
6536 CHECK_PROCESS (proc
);
6537 p
= XPROCESS (proc
);
6541 symbol
= XCAR (symbol
);
6543 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6546 struct buffer
*old
= current_buffer
;
6547 ptrdiff_t opoint
, opoint_byte
;
6548 ptrdiff_t before
, before_byte
;
6550 /* Avoid error if buffer is deleted
6551 (probably that's why the process is dead, too). */
6552 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6554 Fset_buffer (buffer
);
6556 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6557 msg
= (code_convert_string_norecord
6558 (msg
, Vlocale_coding_system
, 1));
6561 opoint_byte
= PT_BYTE
;
6562 /* Insert new output into buffer
6563 at the current end-of-output marker,
6564 thus preserving logical ordering of input and output. */
6565 if (XMARKER (p
->mark
)->buffer
)
6566 Fgoto_char (p
->mark
);
6568 SET_PT_BOTH (ZV
, ZV_BYTE
);
6571 before_byte
= PT_BYTE
;
6573 tem
= BVAR (current_buffer
, read_only
);
6574 bset_read_only (current_buffer
, Qnil
);
6575 insert_string ("\nProcess ");
6576 { /* FIXME: temporary kludge. */
6577 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6578 insert_string (" ");
6580 bset_read_only (current_buffer
, tem
);
6581 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6583 if (opoint
>= before
)
6584 SET_PT_BOTH (opoint
+ (PT
- before
),
6585 opoint_byte
+ (PT_BYTE
- before_byte
));
6587 SET_PT_BOTH (opoint
, opoint_byte
);
6589 set_buffer_internal (old
);
6595 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6596 Sset_process_coding_system
, 1, 3, 0,
6597 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6598 DECODING will be used to decode subprocess output and ENCODING to
6599 encode subprocess input. */)
6600 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6602 register struct Lisp_Process
*p
;
6604 CHECK_PROCESS (process
);
6605 p
= XPROCESS (process
);
6607 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6609 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6610 Fcheck_coding_system (decoding
);
6611 Fcheck_coding_system (encoding
);
6612 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6613 pset_decode_coding_system (p
, decoding
);
6614 pset_encode_coding_system (p
, encoding
);
6615 setup_process_coding_systems (process
);
6620 DEFUN ("process-coding-system",
6621 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6622 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6623 (register Lisp_Object process
)
6625 CHECK_PROCESS (process
);
6626 return Fcons (XPROCESS (process
)->decode_coding_system
,
6627 XPROCESS (process
)->encode_coding_system
);
6630 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6631 Sset_process_filter_multibyte
, 2, 2, 0,
6632 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6633 If FLAG is non-nil, the filter is given multibyte strings.
6634 If FLAG is nil, the filter is given unibyte strings. In this case,
6635 all character code conversion except for end-of-line conversion is
6637 (Lisp_Object process
, Lisp_Object flag
)
6639 register struct Lisp_Process
*p
;
6641 CHECK_PROCESS (process
);
6642 p
= XPROCESS (process
);
6644 pset_decode_coding_system
6645 (p
, raw_text_coding_system (p
->decode_coding_system
));
6646 setup_process_coding_systems (process
);
6651 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6652 Sprocess_filter_multibyte_p
, 1, 1, 0,
6653 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6654 (Lisp_Object process
)
6656 register struct Lisp_Process
*p
;
6657 struct coding_system
*coding
;
6659 CHECK_PROCESS (process
);
6660 p
= XPROCESS (process
);
6661 coding
= proc_decode_coding_system
[p
->infd
];
6662 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6671 add_gpm_wait_descriptor (int desc
)
6673 add_keyboard_wait_descriptor (desc
);
6677 delete_gpm_wait_descriptor (int desc
)
6679 delete_keyboard_wait_descriptor (desc
);
6684 # ifdef USABLE_SIGIO
6686 /* Return true if *MASK has a bit set
6687 that corresponds to one of the keyboard input descriptors. */
6690 keyboard_bit_set (fd_set
*mask
)
6694 for (fd
= 0; fd
<= max_desc
; fd
++)
6695 if (FD_ISSET (fd
, mask
)
6696 && ((fd_callback_info
[fd
].flags
& KEYBOARD_FD
) != 0))
6703 #else /* not subprocesses */
6705 /* Defined on msdos.c. */
6706 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
6707 EMACS_TIME
*, void *);
6709 /* Implementation of wait_reading_process_output, assuming that there
6710 are no subprocesses. Used only by the MS-DOS build.
6712 Wait for timeout to elapse and/or keyboard input to be available.
6716 If negative, gobble data immediately available but don't wait for any.
6719 an additional duration to wait, measured in nanoseconds
6720 If TIME_LIMIT is zero, then:
6721 If NSECS == 0, there is no limit.
6722 If NSECS > 0, the timeout consists of NSECS only.
6723 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6726 0 to ignore keyboard input, or
6727 1 to return when input is available, or
6728 -1 means caller will actually read the input, so don't throw to
6731 see full version for other parameters. We know that wait_proc will
6732 always be NULL, since `subprocesses' isn't defined.
6734 DO_DISPLAY means redisplay should be done to show subprocess
6735 output that arrives.
6737 Return true if we received input from any process. */
6740 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6742 Lisp_Object wait_for_cell
,
6743 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6746 EMACS_TIME end_time
, timeout
;
6753 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6754 time_limit
= TYPE_MAXIMUM (time_t);
6756 /* What does time_limit really mean? */
6757 if (time_limit
|| nsecs
> 0)
6759 timeout
= make_emacs_time (time_limit
, nsecs
);
6760 end_time
= add_emacs_time (current_emacs_time (), timeout
);
6763 /* Turn off periodic alarms (in case they are in use)
6764 and then turn off any other atimers,
6765 because the select emulator uses alarms. */
6767 turn_on_atimers (0);
6771 bool timeout_reduced_for_timers
= 0;
6772 SELECT_TYPE waitchannels
;
6775 /* If calling from keyboard input, do not quit
6776 since we want to return C-g as an input character.
6777 Otherwise, do pending quit if requested. */
6781 /* Exit now if the cell we're waiting for became non-nil. */
6782 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6785 /* Compute time from now till when time limit is up. */
6786 /* Exit if already run out. */
6789 /* A negative timeout means
6790 gobble output available now
6791 but don't wait at all. */
6793 timeout
= make_emacs_time (0, 0);
6795 else if (time_limit
|| nsecs
> 0)
6797 EMACS_TIME now
= current_emacs_time ();
6798 if (EMACS_TIME_LE (end_time
, now
))
6800 timeout
= sub_emacs_time (end_time
, now
);
6804 timeout
= make_emacs_time (100000, 0);
6807 /* If our caller will not immediately handle keyboard events,
6808 run timer events directly.
6809 (Callers that will immediately read keyboard events
6810 call timer_delay on their own.) */
6811 if (NILP (wait_for_cell
))
6813 EMACS_TIME timer_delay
;
6817 unsigned old_timers_run
= timers_run
;
6818 timer_delay
= timer_check ();
6819 if (timers_run
!= old_timers_run
&& do_display
)
6820 /* We must retry, since a timer may have requeued itself
6821 and that could alter the time delay. */
6822 redisplay_preserve_echo_area (14);
6826 while (!detect_input_pending ());
6828 /* If there is unread keyboard input, also return. */
6830 && requeued_events_pending_p ())
6833 if (EMACS_TIME_VALID_P (timer_delay
) && nsecs
>= 0)
6835 if (EMACS_TIME_LT (timer_delay
, timeout
))
6837 timeout
= timer_delay
;
6838 timeout_reduced_for_timers
= 1;
6843 /* Cause C-g and alarm signals to take immediate action,
6844 and cause input available signals to zero out timeout. */
6846 set_waiting_for_input (&timeout
);
6848 /* If a frame has been newly mapped and needs updating,
6849 reprocess its display stuff. */
6850 if (frame_garbaged
&& do_display
)
6852 clear_waiting_for_input ();
6853 redisplay_preserve_echo_area (15);
6855 set_waiting_for_input (&timeout
);
6858 /* Wait till there is something to do. */
6859 FD_ZERO (&waitchannels
);
6860 if (read_kbd
&& detect_input_pending ())
6864 if (read_kbd
|| !NILP (wait_for_cell
))
6865 FD_SET (0, &waitchannels
);
6866 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6871 /* Make C-g and alarm signals set flags again */
6872 clear_waiting_for_input ();
6874 /* If we woke up due to SIGWINCH, actually change size now. */
6875 do_pending_window_change (0);
6877 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6878 /* We waited the full specified time, so return now. */
6883 /* If the system call was interrupted, then go around the
6885 if (xerrno
== EINTR
)
6886 FD_ZERO (&waitchannels
);
6888 report_file_errno ("Failed select", Qnil
, xerrno
);
6891 /* Check for keyboard input */
6894 && detect_input_pending_run_timers (do_display
))
6896 swallow_events (do_display
);
6897 if (detect_input_pending_run_timers (do_display
))
6901 /* If there is unread keyboard input, also return. */
6903 && requeued_events_pending_p ())
6906 /* If wait_for_cell. check for keyboard input
6907 but don't run any timers.
6908 ??? (It seems wrong to me to check for keyboard
6909 input at all when wait_for_cell, but the code
6910 has been this way since July 1994.
6911 Try changing this after version 19.31.) */
6912 if (! NILP (wait_for_cell
)
6913 && detect_input_pending ())
6915 swallow_events (do_display
);
6916 if (detect_input_pending ())
6920 /* Exit now if the cell we're waiting for became non-nil. */
6921 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6930 #endif /* not subprocesses */
6932 /* The following functions are needed even if async subprocesses are
6933 not supported. Some of them are no-op stubs in that case. */
6935 /* Add DESC to the set of keyboard input descriptors. */
6938 add_keyboard_wait_descriptor (int desc
)
6940 #ifdef subprocesses /* actually means "not MSDOS" */
6941 eassert (desc
>= 0 && desc
< MAXDESC
);
6942 fd_callback_info
[desc
].flags
|= FOR_READ
| KEYBOARD_FD
;
6943 if (desc
> max_desc
)
6948 /* From now on, do not expect DESC to give keyboard input. */
6951 delete_keyboard_wait_descriptor (int desc
)
6957 eassert (desc
>= 0 && desc
< MAXDESC
);
6958 eassert (desc
<= max_desc
);
6960 fd_callback_info
[desc
].flags
&= ~(FOR_READ
| KEYBOARD_FD
| PROCESS_FD
);
6962 if (desc
== max_desc
)
6963 recompute_max_desc ();
6967 /* Setup coding systems of PROCESS. */
6970 setup_process_coding_systems (Lisp_Object process
)
6973 struct Lisp_Process
*p
= XPROCESS (process
);
6975 int outch
= p
->outfd
;
6976 Lisp_Object coding_system
;
6978 if (inch
< 0 || outch
< 0)
6981 if (!proc_decode_coding_system
[inch
])
6982 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6983 coding_system
= p
->decode_coding_system
;
6984 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6985 && BUFFERP (p
->buffer
))
6987 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6988 coding_system
= raw_text_coding_system (coding_system
);
6990 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6992 if (!proc_encode_coding_system
[outch
])
6993 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6994 setup_coding_system (p
->encode_coding_system
,
6995 proc_encode_coding_system
[outch
]);
6999 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7000 doc
: /* Return the (or a) process associated with BUFFER.
7001 BUFFER may be a buffer or the name of one. */)
7002 (register Lisp_Object buffer
)
7005 register Lisp_Object buf
, tail
, proc
;
7007 if (NILP (buffer
)) return Qnil
;
7008 buf
= Fget_buffer (buffer
);
7009 if (NILP (buf
)) return Qnil
;
7011 FOR_EACH_PROCESS (tail
, proc
)
7012 if (EQ (XPROCESS (proc
)->buffer
, buf
))
7014 #endif /* subprocesses */
7018 DEFUN ("process-inherit-coding-system-flag",
7019 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7021 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7022 If this flag is t, `buffer-file-coding-system' of the buffer
7023 associated with PROCESS will inherit the coding system used to decode
7024 the process output. */)
7025 (register Lisp_Object process
)
7028 CHECK_PROCESS (process
);
7029 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7031 /* Ignore the argument and return the value of
7032 inherit-process-coding-system. */
7033 return inherit_process_coding_system
? Qt
: Qnil
;
7037 /* Kill all processes associated with `buffer'.
7038 If `buffer' is nil, kill all processes */
7041 kill_buffer_processes (Lisp_Object buffer
)
7044 Lisp_Object tail
, proc
;
7046 FOR_EACH_PROCESS (tail
, proc
)
7047 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7049 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
7050 Fdelete_process (proc
);
7051 else if (XPROCESS (proc
)->infd
>= 0)
7052 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7054 #else /* subprocesses */
7055 /* Since we have no subprocesses, this does nothing. */
7056 #endif /* subprocesses */
7059 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7060 Swaiting_for_user_input_p
, 0, 0, 0,
7061 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7062 This is intended for use by asynchronous process output filters and sentinels. */)
7066 return (waiting_for_user_input_p
? Qt
: Qnil
);
7072 /* Stop reading input from keyboard sources. */
7075 hold_keyboard_input (void)
7080 /* Resume reading input from keyboard sources. */
7083 unhold_keyboard_input (void)
7088 /* Return true if keyboard input is on hold, zero otherwise. */
7091 kbd_on_hold_p (void)
7093 return kbd_is_on_hold
;
7097 /* Enumeration of and access to system processes a-la ps(1). */
7099 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7101 doc
: /* Return a list of numerical process IDs of all running processes.
7102 If this functionality is unsupported, return nil.
7104 See `process-attributes' for getting attributes of a process given its ID. */)
7107 return list_system_processes ();
7110 DEFUN ("process-attributes", Fprocess_attributes
,
7111 Sprocess_attributes
, 1, 1, 0,
7112 doc
: /* Return attributes of the process given by its PID, a number.
7114 Value is an alist where each element is a cons cell of the form
7118 If this functionality is unsupported, the value is nil.
7120 See `list-system-processes' for getting a list of all process IDs.
7122 The KEYs of the attributes that this function may return are listed
7123 below, together with the type of the associated VALUE (in parentheses).
7124 Not all platforms support all of these attributes; unsupported
7125 attributes will not appear in the returned alist.
7126 Unless explicitly indicated otherwise, numbers can have either
7127 integer or floating point values.
7129 euid -- Effective user User ID of the process (number)
7130 user -- User name corresponding to euid (string)
7131 egid -- Effective user Group ID of the process (number)
7132 group -- Group name corresponding to egid (string)
7133 comm -- Command name (executable name only) (string)
7134 state -- Process state code, such as "S", "R", or "T" (string)
7135 ppid -- Parent process ID (number)
7136 pgrp -- Process group ID (number)
7137 sess -- Session ID, i.e. process ID of session leader (number)
7138 ttname -- Controlling tty name (string)
7139 tpgid -- ID of foreground process group on the process's tty (number)
7140 minflt -- number of minor page faults (number)
7141 majflt -- number of major page faults (number)
7142 cminflt -- cumulative number of minor page faults (number)
7143 cmajflt -- cumulative number of major page faults (number)
7144 utime -- user time used by the process, in (current-time) format,
7145 which is a list of integers (HIGH LOW USEC PSEC)
7146 stime -- system time used by the process (current-time)
7147 time -- sum of utime and stime (current-time)
7148 cutime -- user time used by the process and its children (current-time)
7149 cstime -- system time used by the process and its children (current-time)
7150 ctime -- sum of cutime and cstime (current-time)
7151 pri -- priority of the process (number)
7152 nice -- nice value of the process (number)
7153 thcount -- process thread count (number)
7154 start -- time the process started (current-time)
7155 vsize -- virtual memory size of the process in KB's (number)
7156 rss -- resident set size of the process in KB's (number)
7157 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7158 pcpu -- percents of CPU time used by the process (floating-point number)
7159 pmem -- percents of total physical memory used by process's resident set
7160 (floating-point number)
7161 args -- command line which invoked the process (string). */)
7164 return system_process_attributes (pid
);
7167 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7168 Invoke this after init_process_emacs, and after glib and/or GNUstep
7169 futz with the SIGCHLD handler, but before Emacs forks any children.
7170 This function's caller should block SIGCHLD. */
7172 #ifndef NS_IMPL_GNUSTEP
7176 catch_child_signal (void)
7178 struct sigaction action
, old_action
;
7179 emacs_sigaction_init (&action
, deliver_child_signal
);
7180 block_child_signal ();
7181 sigaction (SIGCHLD
, &action
, &old_action
);
7182 eassert (! (old_action
.sa_flags
& SA_SIGINFO
));
7184 if (old_action
.sa_handler
!= deliver_child_signal
)
7186 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7188 : old_action
.sa_handler
);
7189 unblock_child_signal ();
7193 /* This is not called "init_process" because that is the name of a
7194 Mach system call, so it would cause problems on Darwin systems. */
7196 init_process_emacs (void)
7201 inhibit_sentinels
= 0;
7204 if (! noninteractive
|| initialized
)
7207 #if defined HAVE_GLIB && !defined WINDOWSNT
7208 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7209 this should always fail, but is enough to initialize glib's
7210 private SIGCHLD handler, allowing catch_child_signal to copy
7211 it into lib_child_handler. */
7212 g_source_unref (g_child_watch_source_new (getpid ()));
7214 catch_child_signal ();
7218 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7220 #ifdef NON_BLOCKING_CONNECT
7221 num_pending_connects
= 0;
7224 #ifdef ADAPTIVE_READ_BUFFERING
7225 process_output_delay_count
= 0;
7226 process_output_skip
= 0;
7229 /* Don't do this, it caused infinite select loops. The display
7230 method should call add_keyboard_wait_descriptor on stdin if it
7233 FD_SET (0, &input_wait_mask
);
7236 Vprocess_alist
= Qnil
;
7237 deleted_pid_list
= Qnil
;
7238 for (i
= 0; i
< MAXDESC
; i
++)
7240 chan_process
[i
] = Qnil
;
7241 proc_buffered_char
[i
] = -1;
7243 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7244 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7245 #ifdef DATAGRAM_SOCKETS
7246 memset (datagram_address
, 0, sizeof datagram_address
);
7250 Lisp_Object subfeatures
= Qnil
;
7251 const struct socket_options
*sopt
;
7253 #define ADD_SUBFEATURE(key, val) \
7254 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7256 #ifdef NON_BLOCKING_CONNECT
7257 ADD_SUBFEATURE (QCnowait
, Qt
);
7259 #ifdef DATAGRAM_SOCKETS
7260 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7262 #ifdef HAVE_SEQPACKET
7263 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7265 #ifdef HAVE_LOCAL_SOCKETS
7266 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7268 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7270 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7272 #ifdef HAVE_GETSOCKNAME
7273 ADD_SUBFEATURE (QCservice
, Qt
);
7275 ADD_SUBFEATURE (QCserver
, Qt
);
7277 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7278 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7280 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7283 #if defined (DARWIN_OS)
7284 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7285 processes. As such, we only change the default value. */
7288 char const *release
= (STRINGP (Voperating_system_release
)
7289 ? SSDATA (Voperating_system_release
)
7291 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7292 Vprocess_connection_type
= Qnil
;
7296 #endif /* subprocesses */
7301 syms_of_process (void)
7305 DEFSYM (Qprocessp
, "processp");
7306 DEFSYM (Qrun
, "run");
7307 DEFSYM (Qstop
, "stop");
7308 DEFSYM (Qsignal
, "signal");
7310 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7313 Qexit = intern_c_string ("exit");
7314 staticpro (&Qexit); */
7316 DEFSYM (Qopen
, "open");
7317 DEFSYM (Qclosed
, "closed");
7318 DEFSYM (Qconnect
, "connect");
7319 DEFSYM (Qfailed
, "failed");
7320 DEFSYM (Qlisten
, "listen");
7321 DEFSYM (Qlocal
, "local");
7322 DEFSYM (Qipv4
, "ipv4");
7324 DEFSYM (Qipv6
, "ipv6");
7326 DEFSYM (Qdatagram
, "datagram");
7327 DEFSYM (Qseqpacket
, "seqpacket");
7329 DEFSYM (QCport
, ":port");
7330 DEFSYM (QCspeed
, ":speed");
7331 DEFSYM (QCprocess
, ":process");
7333 DEFSYM (QCbytesize
, ":bytesize");
7334 DEFSYM (QCstopbits
, ":stopbits");
7335 DEFSYM (QCparity
, ":parity");
7336 DEFSYM (Qodd
, "odd");
7337 DEFSYM (Qeven
, "even");
7338 DEFSYM (QCflowcontrol
, ":flowcontrol");
7341 DEFSYM (QCsummary
, ":summary");
7343 DEFSYM (Qreal
, "real");
7344 DEFSYM (Qnetwork
, "network");
7345 DEFSYM (Qserial
, "serial");
7346 DEFSYM (QCbuffer
, ":buffer");
7347 DEFSYM (QChost
, ":host");
7348 DEFSYM (QCservice
, ":service");
7349 DEFSYM (QClocal
, ":local");
7350 DEFSYM (QCremote
, ":remote");
7351 DEFSYM (QCcoding
, ":coding");
7352 DEFSYM (QCserver
, ":server");
7353 DEFSYM (QCnowait
, ":nowait");
7354 DEFSYM (QCsentinel
, ":sentinel");
7355 DEFSYM (QClog
, ":log");
7356 DEFSYM (QCnoquery
, ":noquery");
7357 DEFSYM (QCstop
, ":stop");
7358 DEFSYM (QCoptions
, ":options");
7359 DEFSYM (QCplist
, ":plist");
7361 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7363 staticpro (&Vprocess_alist
);
7364 staticpro (&deleted_pid_list
);
7366 #endif /* subprocesses */
7368 DEFSYM (QCname
, ":name");
7369 DEFSYM (QCtype
, ":type");
7371 DEFSYM (Qeuid
, "euid");
7372 DEFSYM (Qegid
, "egid");
7373 DEFSYM (Quser
, "user");
7374 DEFSYM (Qgroup
, "group");
7375 DEFSYM (Qcomm
, "comm");
7376 DEFSYM (Qstate
, "state");
7377 DEFSYM (Qppid
, "ppid");
7378 DEFSYM (Qpgrp
, "pgrp");
7379 DEFSYM (Qsess
, "sess");
7380 DEFSYM (Qttname
, "ttname");
7381 DEFSYM (Qtpgid
, "tpgid");
7382 DEFSYM (Qminflt
, "minflt");
7383 DEFSYM (Qmajflt
, "majflt");
7384 DEFSYM (Qcminflt
, "cminflt");
7385 DEFSYM (Qcmajflt
, "cmajflt");
7386 DEFSYM (Qutime
, "utime");
7387 DEFSYM (Qstime
, "stime");
7388 DEFSYM (Qtime
, "time");
7389 DEFSYM (Qcutime
, "cutime");
7390 DEFSYM (Qcstime
, "cstime");
7391 DEFSYM (Qctime
, "ctime");
7392 DEFSYM (Qinternal_default_process_sentinel
,
7393 "internal-default-process-sentinel");
7394 DEFSYM (Qinternal_default_process_filter
,
7395 "internal-default-process-filter");
7396 DEFSYM (Qpri
, "pri");
7397 DEFSYM (Qnice
, "nice");
7398 DEFSYM (Qthcount
, "thcount");
7399 DEFSYM (Qstart
, "start");
7400 DEFSYM (Qvsize
, "vsize");
7401 DEFSYM (Qrss
, "rss");
7402 DEFSYM (Qetime
, "etime");
7403 DEFSYM (Qpcpu
, "pcpu");
7404 DEFSYM (Qpmem
, "pmem");
7405 DEFSYM (Qargs
, "args");
7407 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7408 doc
: /* Non-nil means delete processes immediately when they exit.
7409 A value of nil means don't delete them until `list-processes' is run. */);
7411 delete_exited_processes
= 1;
7414 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7415 doc
: /* Control type of device used to communicate with subprocesses.
7416 Values are nil to use a pipe, or t or `pty' to use a pty.
7417 The value has no effect if the system has no ptys or if all ptys are busy:
7418 then a pipe is used in any case.
7419 The value takes effect when `start-process' is called. */);
7420 Vprocess_connection_type
= Qt
;
7422 #ifdef ADAPTIVE_READ_BUFFERING
7423 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7424 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7425 On some systems, when Emacs reads the output from a subprocess, the output data
7426 is read in very small blocks, potentially resulting in very poor performance.
7427 This behavior can be remedied to some extent by setting this variable to a
7428 non-nil value, as it will automatically delay reading from such processes, to
7429 allow them to produce more output before Emacs tries to read it.
7430 If the value is t, the delay is reset after each write to the process; any other
7431 non-nil value means that the delay is not reset on write.
7432 The variable takes effect when `start-process' is called. */);
7433 Vprocess_adaptive_read_buffering
= Qt
;
7436 defsubr (&Sprocessp
);
7437 defsubr (&Sget_process
);
7438 defsubr (&Sdelete_process
);
7439 defsubr (&Sprocess_status
);
7440 defsubr (&Sprocess_exit_status
);
7441 defsubr (&Sprocess_id
);
7442 defsubr (&Sprocess_name
);
7443 defsubr (&Sprocess_tty_name
);
7444 defsubr (&Sprocess_command
);
7445 defsubr (&Sset_process_buffer
);
7446 defsubr (&Sprocess_buffer
);
7447 defsubr (&Sprocess_mark
);
7448 defsubr (&Sset_process_filter
);
7449 defsubr (&Sprocess_filter
);
7450 defsubr (&Sset_process_sentinel
);
7451 defsubr (&Sprocess_sentinel
);
7452 defsubr (&Sset_process_thread
);
7453 defsubr (&Sprocess_thread
);
7454 defsubr (&Sset_process_window_size
);
7455 defsubr (&Sset_process_inherit_coding_system_flag
);
7456 defsubr (&Sset_process_query_on_exit_flag
);
7457 defsubr (&Sprocess_query_on_exit_flag
);
7458 defsubr (&Sprocess_contact
);
7459 defsubr (&Sprocess_plist
);
7460 defsubr (&Sset_process_plist
);
7461 defsubr (&Sprocess_list
);
7462 defsubr (&Sstart_process
);
7463 defsubr (&Sserial_process_configure
);
7464 defsubr (&Smake_serial_process
);
7465 defsubr (&Sset_network_process_option
);
7466 defsubr (&Smake_network_process
);
7467 defsubr (&Sformat_network_address
);
7468 #if defined (HAVE_NET_IF_H)
7470 defsubr (&Snetwork_interface_list
);
7472 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7473 defsubr (&Snetwork_interface_info
);
7475 #endif /* defined (HAVE_NET_IF_H) */
7476 #ifdef DATAGRAM_SOCKETS
7477 defsubr (&Sprocess_datagram_address
);
7478 defsubr (&Sset_process_datagram_address
);
7480 defsubr (&Saccept_process_output
);
7481 defsubr (&Sprocess_send_region
);
7482 defsubr (&Sprocess_send_string
);
7483 defsubr (&Sinterrupt_process
);
7484 defsubr (&Skill_process
);
7485 defsubr (&Squit_process
);
7486 defsubr (&Sstop_process
);
7487 defsubr (&Scontinue_process
);
7488 defsubr (&Sprocess_running_child_p
);
7489 defsubr (&Sprocess_send_eof
);
7490 defsubr (&Ssignal_process
);
7491 defsubr (&Swaiting_for_user_input_p
);
7492 defsubr (&Sprocess_type
);
7493 defsubr (&Sinternal_default_process_sentinel
);
7494 defsubr (&Sinternal_default_process_filter
);
7495 defsubr (&Sset_process_coding_system
);
7496 defsubr (&Sprocess_coding_system
);
7497 defsubr (&Sset_process_filter_multibyte
);
7498 defsubr (&Sprocess_filter_multibyte_p
);
7500 #endif /* subprocesses */
7502 defsubr (&Sget_buffer_process
);
7503 defsubr (&Sprocess_inherit_coding_system_flag
);
7504 defsubr (&Slist_system_processes
);
7505 defsubr (&Sprocess_attributes
);