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 */
830 /* Set FD's close-on-exec flag. This is needed even if
831 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
832 doesn't require support for that combination.
833 Multithreaded platforms where posix_openpt ignores
834 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
835 have a race condition between the PTY_OPEN and here. */
836 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
838 /* check to make certain that both sides are available
839 this avoids a nasty yet stupid bug in rlogins */
840 #ifdef PTY_TTY_NAME_SPRINTF
843 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
844 #endif /* no PTY_TTY_NAME_SPRINTF */
845 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
858 #endif /* HAVE_PTYS */
863 make_process (Lisp_Object name
)
865 register Lisp_Object val
, tem
, name1
;
866 register struct Lisp_Process
*p
;
867 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
870 p
= allocate_process ();
871 /* Initialize Lisp data. Note that allocate_process initializes all
872 Lisp data to nil, so do it only for slots which should not be nil. */
873 pset_status (p
, Qrun
);
874 pset_mark (p
, Fmake_marker ());
875 pset_thread (p
, Fcurrent_thread ());
877 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
878 non-Lisp data, so do it only for slots which should not be zero. */
881 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
885 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
888 /* If name is already in use, modify it until it is unused. */
893 tem
= Fget_process (name1
);
894 if (NILP (tem
)) break;
895 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
899 pset_sentinel (p
, Qinternal_default_process_sentinel
);
900 pset_filter (p
, Qinternal_default_process_filter
);
901 XSETPROCESS (val
, p
);
902 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
907 remove_process (register Lisp_Object proc
)
909 register Lisp_Object pair
;
911 pair
= Frassq (proc
, Vprocess_alist
);
912 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
914 deactivate_process (proc
);
918 update_processes_for_thread_death (Lisp_Object dying_thread
)
922 for (pair
= Vprocess_alist
; !NILP (pair
); pair
= XCDR (pair
))
924 Lisp_Object process
= XCDR (XCAR (pair
));
925 if (EQ (XPROCESS (process
)->thread
, dying_thread
))
927 struct Lisp_Process
*proc
= XPROCESS (process
);
931 fd_callback_info
[proc
->infd
].thread
= NULL
;
932 if (proc
->outfd
>= 0)
933 fd_callback_info
[proc
->outfd
].thread
= NULL
;
939 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
940 doc
: /* Return t if OBJECT is a process. */)
943 return PROCESSP (object
) ? Qt
: Qnil
;
946 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
947 doc
: /* Return the process named NAME, or nil if there is none. */)
948 (register Lisp_Object name
)
953 return Fcdr (Fassoc (name
, Vprocess_alist
));
956 /* This is how commands for the user decode process arguments. It
957 accepts a process, a process name, a buffer, a buffer name, or nil.
958 Buffers denote the first process in the buffer, and nil denotes the
962 get_process (register Lisp_Object name
)
964 register Lisp_Object proc
, obj
;
967 obj
= Fget_process (name
);
969 obj
= Fget_buffer (name
);
971 error ("Process %s does not exist", SDATA (name
));
973 else if (NILP (name
))
974 obj
= Fcurrent_buffer ();
978 /* Now obj should be either a buffer object or a process object.
982 proc
= Fget_buffer_process (obj
);
984 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
995 /* Fdelete_process promises to immediately forget about the process, but in
996 reality, Emacs needs to remember those processes until they have been
997 treated by the SIGCHLD handler and waitpid has been invoked on them;
998 otherwise they might fill up the kernel's process table.
1000 Some processes created by call-process are also put onto this list.
1002 Members of this list are (process-ID . filename) pairs. The
1003 process-ID is a number; the filename, if a string, is a file that
1004 needs to be removed after the process exits. */
1005 static Lisp_Object deleted_pid_list
;
1008 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
1010 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
1011 /* GC treated elements set to nil. */
1012 Fdelq (Qnil
, deleted_pid_list
));
1016 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
1017 doc
: /* Delete PROCESS: kill it and forget about it immediately.
1018 PROCESS may be a process, a buffer, the name of a process or buffer, or
1019 nil, indicating the current buffer's process. */)
1020 (register Lisp_Object process
)
1022 register struct Lisp_Process
*p
;
1024 process
= get_process (process
);
1025 p
= XPROCESS (process
);
1027 p
->raw_status_new
= 0;
1028 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1030 pset_status (p
, list2 (Qexit
, make_number (0)));
1031 p
->tick
= ++process_tick
;
1033 redisplay_preserve_echo_area (13);
1038 record_kill_process (p
, Qnil
);
1042 /* Update P's status, since record_kill_process will make the
1043 SIGCHLD handler update deleted_pid_list, not *P. */
1045 if (p
->raw_status_new
)
1047 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
1048 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
1049 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
1051 p
->tick
= ++process_tick
;
1053 redisplay_preserve_echo_area (13);
1056 remove_process (process
);
1060 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
1061 doc
: /* Return the status of PROCESS.
1062 The returned value is one of the following symbols:
1063 run -- for a process that is running.
1064 stop -- for a process stopped but continuable.
1065 exit -- for a process that has exited.
1066 signal -- for a process that has got a fatal signal.
1067 open -- for a network stream connection that is open.
1068 listen -- for a network stream server that is listening.
1069 closed -- for a network stream connection that is closed.
1070 connect -- when waiting for a non-blocking connection to complete.
1071 failed -- when a non-blocking connection has failed.
1072 nil -- if arg is a process name and no such process exists.
1073 PROCESS may be a process, a buffer, the name of a process, or
1074 nil, indicating the current buffer's process. */)
1075 (register Lisp_Object process
)
1077 register struct Lisp_Process
*p
;
1078 register Lisp_Object status
;
1080 if (STRINGP (process
))
1081 process
= Fget_process (process
);
1083 process
= get_process (process
);
1088 p
= XPROCESS (process
);
1089 if (p
->raw_status_new
)
1093 status
= XCAR (status
);
1094 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1096 if (EQ (status
, Qexit
))
1098 else if (EQ (p
->command
, Qt
))
1100 else if (EQ (status
, Qrun
))
1106 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
1108 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
1109 If PROCESS has not yet exited or died, return 0. */)
1110 (register Lisp_Object process
)
1112 CHECK_PROCESS (process
);
1113 if (XPROCESS (process
)->raw_status_new
)
1114 update_status (XPROCESS (process
));
1115 if (CONSP (XPROCESS (process
)->status
))
1116 return XCAR (XCDR (XPROCESS (process
)->status
));
1117 return make_number (0);
1120 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
1121 doc
: /* Return the process id of PROCESS.
1122 This is the pid of the external process which PROCESS uses or talks to.
1123 For a network connection, this value is nil. */)
1124 (register Lisp_Object process
)
1128 CHECK_PROCESS (process
);
1129 pid
= XPROCESS (process
)->pid
;
1130 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
1133 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
1134 doc
: /* Return the name of PROCESS, as a string.
1135 This is the name of the program invoked in PROCESS,
1136 possibly modified to make it unique among process names. */)
1137 (register Lisp_Object process
)
1139 CHECK_PROCESS (process
);
1140 return XPROCESS (process
)->name
;
1143 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
1144 doc
: /* Return the command that was executed to start PROCESS.
1145 This is a list of strings, the first string being the program executed
1146 and the rest of the strings being the arguments given to it.
1147 For a network or serial process, this is nil (process is running) or t
1148 \(process is stopped). */)
1149 (register Lisp_Object process
)
1151 CHECK_PROCESS (process
);
1152 return XPROCESS (process
)->command
;
1155 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1156 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1157 This is the terminal that the process itself reads and writes on,
1158 not the name of the pty that Emacs uses to talk with that terminal. */)
1159 (register Lisp_Object process
)
1161 CHECK_PROCESS (process
);
1162 return XPROCESS (process
)->tty_name
;
1165 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1167 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1169 (register Lisp_Object process
, Lisp_Object buffer
)
1171 struct Lisp_Process
*p
;
1173 CHECK_PROCESS (process
);
1175 CHECK_BUFFER (buffer
);
1176 p
= XPROCESS (process
);
1177 pset_buffer (p
, buffer
);
1178 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1179 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1180 setup_process_coding_systems (process
);
1184 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1186 doc
: /* Return the buffer PROCESS is associated with.
1187 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1188 (register Lisp_Object process
)
1190 CHECK_PROCESS (process
);
1191 return XPROCESS (process
)->buffer
;
1194 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1196 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1197 (register Lisp_Object process
)
1199 CHECK_PROCESS (process
);
1200 return XPROCESS (process
)->mark
;
1203 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1205 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1206 A value of t means stop accepting output from the process.
1208 When a process has a non-default filter, its buffer is not used for output.
1209 Instead, each time it does output, the entire string of output is
1210 passed to the filter.
1212 The filter gets two arguments: the process and the string of output.
1213 The string argument is normally a multibyte string, except:
1214 - if the process' input coding system is no-conversion or raw-text,
1215 it is a unibyte string (the non-converted input), or else
1216 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1217 string (the result of converting the decoded input multibyte
1218 string to unibyte with `string-make-unibyte'). */)
1219 (register Lisp_Object process
, Lisp_Object filter
)
1221 struct Lisp_Process
*p
;
1223 CHECK_PROCESS (process
);
1224 p
= XPROCESS (process
);
1226 /* Don't signal an error if the process' input file descriptor
1227 is closed. This could make debugging Lisp more difficult,
1228 for example when doing something like
1230 (setq process (start-process ...))
1232 (set-process-filter process ...) */
1235 filter
= Qinternal_default_process_filter
;
1239 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1240 delete_read_fd (p
->infd
);
1241 else if (EQ (p
->filter
, Qt
)
1242 /* Network or serial process not stopped: */
1243 && !EQ (p
->command
, Qt
))
1244 delete_read_fd (p
->infd
);
1247 pset_filter (p
, filter
);
1248 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1249 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1250 setup_process_coding_systems (process
);
1254 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1256 doc
: /* Return the filter function of PROCESS.
1257 See `set-process-filter' for more info on filter functions. */)
1258 (register Lisp_Object process
)
1260 CHECK_PROCESS (process
);
1261 return XPROCESS (process
)->filter
;
1264 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1266 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1267 The sentinel is called as a function when the process changes state.
1268 It gets two arguments: the process, and a string describing the change. */)
1269 (register Lisp_Object process
, Lisp_Object sentinel
)
1271 struct Lisp_Process
*p
;
1273 CHECK_PROCESS (process
);
1274 p
= XPROCESS (process
);
1276 if (NILP (sentinel
))
1277 sentinel
= Qinternal_default_process_sentinel
;
1279 pset_sentinel (p
, sentinel
);
1280 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1281 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1285 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1287 doc
: /* Return the sentinel of PROCESS.
1288 See `set-process-sentinel' for more info on sentinels. */)
1289 (register Lisp_Object process
)
1291 CHECK_PROCESS (process
);
1292 return XPROCESS (process
)->sentinel
;
1295 DEFUN ("set-process-thread", Fset_process_thread
, Sset_process_thread
,
1298 (Lisp_Object process
, Lisp_Object thread
)
1300 struct Lisp_Process
*proc
;
1301 struct thread_state
*tstate
;
1303 CHECK_PROCESS (process
);
1308 CHECK_THREAD (thread
);
1309 tstate
= XTHREAD (thread
);
1312 proc
= XPROCESS (process
);
1313 proc
->thread
= thread
;
1314 if (proc
->infd
>= 0)
1315 fd_callback_info
[proc
->infd
].thread
= tstate
;
1316 if (proc
->outfd
>= 0)
1317 fd_callback_info
[proc
->outfd
].thread
= tstate
;
1322 DEFUN ("process-thread", Fprocess_thread
, Sprocess_thread
,
1325 (Lisp_Object process
)
1327 CHECK_PROCESS (process
);
1328 return XPROCESS (process
)->thread
;
1331 DEFUN ("set-process-window-size", Fset_process_window_size
,
1332 Sset_process_window_size
, 3, 3, 0,
1333 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1334 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1336 CHECK_PROCESS (process
);
1338 /* All known platforms store window sizes as 'unsigned short'. */
1339 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1340 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1342 if (XPROCESS (process
)->infd
< 0
1343 || (set_window_size (XPROCESS (process
)->infd
,
1344 XINT (height
), XINT (width
))
1351 DEFUN ("set-process-inherit-coding-system-flag",
1352 Fset_process_inherit_coding_system_flag
,
1353 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1354 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1355 If the second argument FLAG is non-nil, then the variable
1356 `buffer-file-coding-system' of the buffer associated with PROCESS
1357 will be bound to the value of the coding system used to decode
1360 This is useful when the coding system specified for the process buffer
1361 leaves either the character code conversion or the end-of-line conversion
1362 unspecified, or if the coding system used to decode the process output
1363 is more appropriate for saving the process buffer.
1365 Binding the variable `inherit-process-coding-system' to non-nil before
1366 starting the process is an alternative way of setting the inherit flag
1367 for the process which will run.
1369 This function returns FLAG. */)
1370 (register Lisp_Object process
, Lisp_Object flag
)
1372 CHECK_PROCESS (process
);
1373 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1377 DEFUN ("set-process-query-on-exit-flag",
1378 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1380 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1381 If the second argument FLAG is non-nil, Emacs will query the user before
1382 exiting or killing a buffer if PROCESS is running. This function
1384 (register Lisp_Object process
, Lisp_Object flag
)
1386 CHECK_PROCESS (process
);
1387 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1391 DEFUN ("process-query-on-exit-flag",
1392 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1394 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1395 (register Lisp_Object process
)
1397 CHECK_PROCESS (process
);
1398 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1401 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1403 doc
: /* Return the contact info of PROCESS; t for a real child.
1404 For a network or serial connection, the value depends on the optional
1405 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1406 SERVICE) for a network connection or (PORT SPEED) for a serial
1407 connection. If KEY is t, the complete contact information for the
1408 connection is returned, else the specific value for the keyword KEY is
1409 returned. See `make-network-process' or `make-serial-process' for a
1410 list of keywords. */)
1411 (register Lisp_Object process
, Lisp_Object key
)
1413 Lisp_Object contact
;
1415 CHECK_PROCESS (process
);
1416 contact
= XPROCESS (process
)->childp
;
1418 #ifdef DATAGRAM_SOCKETS
1419 if (DATAGRAM_CONN_P (process
)
1420 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1421 contact
= Fplist_put (contact
, QCremote
,
1422 Fprocess_datagram_address (process
));
1425 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1427 if (NILP (key
) && NETCONN_P (process
))
1428 return list2 (Fplist_get (contact
, QChost
),
1429 Fplist_get (contact
, QCservice
));
1430 if (NILP (key
) && SERIALCONN_P (process
))
1431 return list2 (Fplist_get (contact
, QCport
),
1432 Fplist_get (contact
, QCspeed
));
1433 return Fplist_get (contact
, key
);
1436 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1438 doc
: /* Return the plist of PROCESS. */)
1439 (register Lisp_Object process
)
1441 CHECK_PROCESS (process
);
1442 return XPROCESS (process
)->plist
;
1445 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1447 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1448 (register Lisp_Object process
, Lisp_Object plist
)
1450 CHECK_PROCESS (process
);
1453 pset_plist (XPROCESS (process
), plist
);
1457 #if 0 /* Turned off because we don't currently record this info
1458 in the process. Perhaps add it. */
1459 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1460 doc
: /* Return the connection type of PROCESS.
1461 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1462 a socket connection. */)
1463 (Lisp_Object process
)
1465 return XPROCESS (process
)->type
;
1469 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1470 doc
: /* Return the connection type of PROCESS.
1471 The value is either the symbol `real', `network', or `serial'.
1472 PROCESS may be a process, a buffer, the name of a process or buffer, or
1473 nil, indicating the current buffer's process. */)
1474 (Lisp_Object process
)
1477 proc
= get_process (process
);
1478 return XPROCESS (proc
)->type
;
1481 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1483 doc
: /* Convert network ADDRESS from internal format to a string.
1484 A 4 or 5 element vector represents an IPv4 address (with port number).
1485 An 8 or 9 element vector represents an IPv6 address (with port number).
1486 If optional second argument OMIT-PORT is non-nil, don't include a port
1487 number in the string, even when present in ADDRESS.
1488 Returns nil if format of ADDRESS is invalid. */)
1489 (Lisp_Object address
, Lisp_Object omit_port
)
1494 if (STRINGP (address
)) /* AF_LOCAL */
1497 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1499 register struct Lisp_Vector
*p
= XVECTOR (address
);
1500 ptrdiff_t size
= p
->header
.size
;
1501 Lisp_Object args
[10];
1504 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1506 args
[0] = build_string ("%d.%d.%d.%d");
1511 args
[0] = build_string ("%d.%d.%d.%d:%d");
1514 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1516 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1521 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1527 for (i
= 0; i
< nargs
; i
++)
1529 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1532 if (nargs
<= 5 /* IPv4 */
1533 && i
< 4 /* host, not port */
1534 && XINT (p
->contents
[i
]) > 255)
1537 args
[i
+1] = p
->contents
[i
];
1540 return Fformat (nargs
+1, args
);
1543 if (CONSP (address
))
1545 Lisp_Object args
[2];
1546 args
[0] = build_string ("<Family %d>");
1547 args
[1] = Fcar (address
);
1548 return Fformat (2, args
);
1554 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1555 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1558 return Fmapcar (Qcdr
, Vprocess_alist
);
1561 /* Starting asynchronous inferior processes. */
1563 static void start_process_unwind (Lisp_Object proc
);
1565 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1566 doc
: /* Start a program in a subprocess. Return the process object for it.
1567 NAME is name for process. It is modified if necessary to make it unique.
1568 BUFFER is the buffer (or buffer name) to associate with the process.
1570 Process output (both standard output and standard error streams) goes
1571 at end of BUFFER, unless you specify an output stream or filter
1572 function to handle the output. BUFFER may also be nil, meaning that
1573 this process is not associated with any buffer.
1575 PROGRAM is the program file name. It is searched for in `exec-path'
1576 (which see). If nil, just associate a pty with the buffer. Remaining
1577 arguments are strings to give program as arguments.
1579 If you want to separate standard output from standard error, invoke
1580 the command through a shell and redirect one of them using the shell
1583 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1584 (ptrdiff_t nargs
, Lisp_Object
*args
)
1586 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1587 register unsigned char **new_argv
;
1589 ptrdiff_t count
= SPECPDL_INDEX ();
1593 buffer
= Fget_buffer_create (buffer
);
1595 /* Make sure that the child will be able to chdir to the current
1596 buffer's current directory, or its unhandled equivalent. We
1597 can't just have the child check for an error when it does the
1598 chdir, since it's in a vfork.
1600 We have to GCPRO around this because Fexpand_file_name and
1601 Funhandled_file_name_directory might call a file name handling
1602 function. The argument list is protected by the caller, so all
1603 we really have to worry about is buffer. */
1605 struct gcpro gcpro1
;
1607 current_dir
= encode_current_directory ();
1612 CHECK_STRING (name
);
1616 if (!NILP (program
))
1617 CHECK_STRING (program
);
1619 proc
= make_process (name
);
1620 /* If an error occurs and we can't start the process, we want to
1621 remove it from the process list. This means that each error
1622 check in create_process doesn't need to call remove_process
1623 itself; it's all taken care of here. */
1624 record_unwind_protect (start_process_unwind
, proc
);
1626 pset_childp (XPROCESS (proc
), Qt
);
1627 pset_plist (XPROCESS (proc
), Qnil
);
1628 pset_type (XPROCESS (proc
), Qreal
);
1629 pset_buffer (XPROCESS (proc
), buffer
);
1630 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1631 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1632 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1635 /* AKA GNUTLS_INITSTAGE(proc). */
1636 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1637 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1640 #ifdef ADAPTIVE_READ_BUFFERING
1641 XPROCESS (proc
)->adaptive_read_buffering
1642 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1643 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1646 /* Make the process marker point into the process buffer (if any). */
1647 if (BUFFERP (buffer
))
1648 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1649 BUF_ZV (XBUFFER (buffer
)),
1650 BUF_ZV_BYTE (XBUFFER (buffer
)));
1653 /* Decide coding systems for communicating with the process. Here
1654 we don't setup the structure coding_system nor pay attention to
1655 unibyte mode. They are done in create_process. */
1657 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1658 Lisp_Object coding_systems
= Qt
;
1659 Lisp_Object val
, *args2
;
1660 struct gcpro gcpro1
, gcpro2
;
1662 val
= Vcoding_system_for_read
;
1665 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1666 args2
[0] = Qstart_process
;
1667 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1668 GCPRO2 (proc
, current_dir
);
1669 if (!NILP (program
))
1670 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1672 if (CONSP (coding_systems
))
1673 val
= XCAR (coding_systems
);
1674 else if (CONSP (Vdefault_process_coding_system
))
1675 val
= XCAR (Vdefault_process_coding_system
);
1677 pset_decode_coding_system (XPROCESS (proc
), val
);
1679 val
= Vcoding_system_for_write
;
1682 if (EQ (coding_systems
, Qt
))
1684 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1685 args2
[0] = Qstart_process
;
1686 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1687 GCPRO2 (proc
, current_dir
);
1688 if (!NILP (program
))
1689 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1692 if (CONSP (coding_systems
))
1693 val
= XCDR (coding_systems
);
1694 else if (CONSP (Vdefault_process_coding_system
))
1695 val
= XCDR (Vdefault_process_coding_system
);
1697 pset_encode_coding_system (XPROCESS (proc
), val
);
1698 /* Note: At this moment, the above coding system may leave
1699 text-conversion or eol-conversion unspecified. They will be
1700 decided after we read output from the process and decode it by
1701 some coding system, or just before we actually send a text to
1706 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1707 XPROCESS (proc
)->decoding_carryover
= 0;
1708 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1710 XPROCESS (proc
)->inherit_coding_system_flag
1711 = !(NILP (buffer
) || !inherit_process_coding_system
);
1713 if (!NILP (program
))
1715 /* If program file name is not absolute, search our path for it.
1716 Put the name we will really use in TEM. */
1717 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1718 && !(SCHARS (program
) > 1
1719 && IS_DEVICE_SEP (SREF (program
, 1))))
1721 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1724 GCPRO4 (name
, program
, buffer
, current_dir
);
1725 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
, make_number (X_OK
));
1728 report_file_error ("Searching for program", program
);
1729 tem
= Fexpand_file_name (tem
, Qnil
);
1733 if (!NILP (Ffile_directory_p (program
)))
1734 error ("Specified program for new process is a directory");
1738 /* If program file name starts with /: for quoting a magic name,
1740 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1741 && SREF (tem
, 1) == ':')
1742 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1745 Lisp_Object arg_encoding
= Qnil
;
1746 struct gcpro gcpro1
;
1749 /* Encode the file name and put it in NEW_ARGV.
1750 That's where the child will use it to execute the program. */
1751 tem
= list1 (ENCODE_FILE (tem
));
1753 /* Here we encode arguments by the coding system used for sending
1754 data to the process. We don't support using different coding
1755 systems for encoding arguments and for encoding data sent to the
1758 for (i
= 3; i
< nargs
; i
++)
1760 tem
= Fcons (args
[i
], tem
);
1761 CHECK_STRING (XCAR (tem
));
1762 if (STRING_MULTIBYTE (XCAR (tem
)))
1764 if (NILP (arg_encoding
))
1765 arg_encoding
= (complement_process_encoding_system
1766 (XPROCESS (proc
)->encode_coding_system
));
1768 code_convert_string_norecord
1769 (XCAR (tem
), arg_encoding
, 1));
1776 /* Now that everything is encoded we can collect the strings into
1778 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1779 new_argv
[nargs
- 2] = 0;
1781 for (i
= nargs
- 2; i
-- != 0; )
1783 new_argv
[i
] = SDATA (XCAR (tem
));
1787 create_process (proc
, (char **) new_argv
, current_dir
);
1792 return unbind_to (count
, proc
);
1795 /* This function is the unwind_protect form for Fstart_process. If
1796 PROC doesn't have its pid set, then we know someone has signaled
1797 an error and the process wasn't started successfully, so we should
1798 remove it from the process list. */
1800 start_process_unwind (Lisp_Object proc
)
1802 if (!PROCESSP (proc
))
1805 /* Was PROC started successfully?
1806 -2 is used for a pty with no process, eg for gdb. */
1807 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1808 remove_process (proc
);
1811 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1814 close_process_fd (int *fd_addr
)
1824 /* Indexes of file descriptors in open_fds. */
1827 /* The pipe from Emacs to its subprocess. */
1829 WRITE_TO_SUBPROCESS
,
1831 /* The main pipe from the subprocess to Emacs. */
1832 READ_FROM_SUBPROCESS
,
1835 /* The pipe from the subprocess to Emacs that is closed when the
1836 subprocess execs. */
1837 READ_FROM_EXEC_MONITOR
,
1841 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1844 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1846 struct Lisp_Process
*p
= XPROCESS (process
);
1847 int inchannel
, outchannel
;
1850 int forkin
, forkout
;
1852 char pty_name
[PTY_NAME_SIZE
];
1853 Lisp_Object lisp_pty_name
= Qnil
;
1855 inchannel
= outchannel
= -1;
1857 if (!NILP (Vprocess_connection_type
))
1858 outchannel
= inchannel
= allocate_pty (pty_name
);
1862 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1863 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1864 /* On most USG systems it does not work to open the pty's tty here,
1865 then close it and reopen it in the child. */
1866 /* Don't let this terminal become our controlling terminal
1867 (in case we don't have one). */
1868 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1870 report_file_error ("Opening pty", Qnil
);
1871 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1873 forkin
= forkout
= -1;
1874 #endif /* not USG, or USG_SUBTTY_WORKS */
1876 lisp_pty_name
= build_string (pty_name
);
1880 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1881 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1882 report_file_error ("Creating pipe", Qnil
);
1883 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1884 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1885 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1886 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1890 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1891 report_file_error ("Creating pipe", Qnil
);
1894 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1895 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1897 /* Record this as an active process, with its channels. */
1898 chan_process
[inchannel
] = process
;
1899 p
->infd
= inchannel
;
1900 p
->outfd
= outchannel
;
1902 /* Previously we recorded the tty descriptor used in the subprocess.
1903 It was only used for getting the foreground tty process, so now
1904 we just reopen the device (see emacs_get_tty_pgrp) as this is
1905 more portable (see USG_SUBTTY_WORKS above). */
1907 p
->pty_flag
= pty_flag
;
1908 pset_status (p
, Qrun
);
1910 add_process_read_fd (inchannel
);
1912 /* This may signal an error. */
1913 setup_process_coding_systems (process
);
1916 block_child_signal ();
1919 /* vfork, and prevent local vars from being clobbered by the vfork. */
1921 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1922 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1923 char **volatile new_argv_volatile
= new_argv
;
1924 int volatile forkin_volatile
= forkin
;
1925 int volatile forkout_volatile
= forkout
;
1926 struct Lisp_Process
*p_volatile
= p
;
1930 current_dir
= current_dir_volatile
;
1931 lisp_pty_name
= lisp_pty_name_volatile
;
1932 new_argv
= new_argv_volatile
;
1933 forkin
= forkin_volatile
;
1934 forkout
= forkout_volatile
;
1937 pty_flag
= p
->pty_flag
;
1941 #endif /* not WINDOWSNT */
1943 int xforkin
= forkin
;
1944 int xforkout
= forkout
;
1946 /* Make the pty be the controlling terminal of the process. */
1948 /* First, disconnect its current controlling terminal. */
1949 /* We tried doing setsid only if pty_flag, but it caused
1950 process_set_signal to fail on SGI when using a pipe. */
1952 /* Make the pty's terminal the controlling terminal. */
1953 if (pty_flag
&& xforkin
>= 0)
1956 /* We ignore the return value
1957 because faith@cs.unc.edu says that is necessary on Linux. */
1958 ioctl (xforkin
, TIOCSCTTY
, 0);
1961 #if defined (LDISC1)
1962 if (pty_flag
&& xforkin
>= 0)
1965 tcgetattr (xforkin
, &t
);
1967 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1968 emacs_perror ("create_process/tcsetattr LDISC1");
1971 #if defined (NTTYDISC) && defined (TIOCSETD)
1972 if (pty_flag
&& xforkin
>= 0)
1974 /* Use new line discipline. */
1975 int ldisc
= NTTYDISC
;
1976 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1981 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1982 can do TIOCSPGRP only to the process's controlling tty. */
1985 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1986 I can't test it since I don't have 4.3. */
1987 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1990 ioctl (j
, TIOCNOTTY
, 0);
1994 #endif /* TIOCNOTTY */
1996 #if !defined (DONT_REOPEN_PTY)
1997 /*** There is a suggestion that this ought to be a
1998 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1999 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2000 that system does seem to need this code, even though
2001 both TIOCSCTTY is defined. */
2002 /* Now close the pty (if we had it open) and reopen it.
2003 This makes the pty the controlling terminal of the subprocess. */
2007 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
2010 emacs_close (xforkin
);
2011 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
2015 emacs_perror (SSDATA (lisp_pty_name
));
2016 _exit (EXIT_CANCELED
);
2020 #endif /* not DONT_REOPEN_PTY */
2022 #ifdef SETUP_SLAVE_PTY
2027 #endif /* SETUP_SLAVE_PTY */
2028 #endif /* HAVE_PTYS */
2030 signal (SIGINT
, SIG_DFL
);
2031 signal (SIGQUIT
, SIG_DFL
);
2033 /* Emacs ignores SIGPIPE, but the child should not. */
2034 signal (SIGPIPE
, SIG_DFL
);
2036 /* Stop blocking SIGCHLD in the child. */
2037 unblock_child_signal ();
2040 child_setup_tty (xforkout
);
2042 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
2043 #else /* not WINDOWSNT */
2044 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
2045 #endif /* not WINDOWSNT */
2048 /* Back in the parent process. */
2050 vfork_errno
= errno
;
2055 /* Stop blocking in the parent. */
2056 unblock_child_signal ();
2060 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
2063 /* vfork succeeded. */
2065 /* Close the pipe ends that the child uses, or the child's pty. */
2066 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
2067 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
2070 register_child (pid
, inchannel
);
2071 #endif /* WINDOWSNT */
2073 pset_tty_name (p
, lisp_pty_name
);
2076 /* Wait for child_setup to complete in case that vfork is
2077 actually defined as fork. The descriptor
2078 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2079 of a pipe is closed at the child side either by close-on-exec
2080 on successful execve or the _exit call in child_setup. */
2084 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
2085 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
2086 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
2093 create_pty (Lisp_Object process
)
2095 struct Lisp_Process
*p
= XPROCESS (process
);
2096 char pty_name
[PTY_NAME_SIZE
];
2097 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
2101 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
2102 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2103 /* On most USG systems it does not work to open the pty's tty here,
2104 then close it and reopen it in the child. */
2105 /* Don't let this terminal become our controlling terminal
2106 (in case we don't have one). */
2107 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2109 report_file_error ("Opening pty", Qnil
);
2110 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
2111 #if defined (DONT_REOPEN_PTY)
2112 /* In the case that vfork is defined as fork, the parent process
2113 (Emacs) may send some data before the child process completes
2114 tty options setup. So we setup tty before forking. */
2115 child_setup_tty (forkout
);
2116 #endif /* DONT_REOPEN_PTY */
2117 #endif /* not USG, or USG_SUBTTY_WORKS */
2119 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
2121 /* Record this as an active process, with its channels.
2122 As a result, child_setup will close Emacs's side of the pipes. */
2123 chan_process
[pty_fd
] = process
;
2127 /* Previously we recorded the tty descriptor used in the subprocess.
2128 It was only used for getting the foreground tty process, so now
2129 we just reopen the device (see emacs_get_tty_pgrp) as this is
2130 more portable (see USG_SUBTTY_WORKS above). */
2133 pset_status (p
, Qrun
);
2134 setup_process_coding_systems (process
);
2136 add_non_keyboard_read_fd (pty_fd
);
2138 pset_tty_name (p
, build_string (pty_name
));
2145 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2146 The address family of sa is not included in the result. */
2149 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2151 Lisp_Object address
;
2154 register struct Lisp_Vector
*p
;
2156 /* Workaround for a bug in getsockname on BSD: Names bound to
2157 sockets in the UNIX domain are inaccessible; getsockname returns
2158 a zero length name. */
2159 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2160 return empty_unibyte_string
;
2162 switch (sa
->sa_family
)
2166 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2167 len
= sizeof (sin
->sin_addr
) + 1;
2168 address
= Fmake_vector (make_number (len
), Qnil
);
2169 p
= XVECTOR (address
);
2170 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2171 cp
= (unsigned char *) &sin
->sin_addr
;
2177 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2178 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2179 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2180 address
= Fmake_vector (make_number (len
), Qnil
);
2181 p
= XVECTOR (address
);
2182 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2183 for (i
= 0; i
< len
; i
++)
2184 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2188 #ifdef HAVE_LOCAL_SOCKETS
2191 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2192 for (i
= 0; i
< sizeof (sockun
->sun_path
); i
++)
2193 if (sockun
->sun_path
[i
] == 0)
2195 return make_unibyte_string (sockun
->sun_path
, i
);
2199 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2200 address
= Fcons (make_number (sa
->sa_family
),
2201 Fmake_vector (make_number (len
), Qnil
));
2202 p
= XVECTOR (XCDR (address
));
2203 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2209 p
->contents
[i
++] = make_number (*cp
++);
2215 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2218 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2220 register struct Lisp_Vector
*p
;
2222 if (VECTORP (address
))
2224 p
= XVECTOR (address
);
2225 if (p
->header
.size
== 5)
2228 return sizeof (struct sockaddr_in
);
2231 else if (p
->header
.size
== 9)
2233 *familyp
= AF_INET6
;
2234 return sizeof (struct sockaddr_in6
);
2238 #ifdef HAVE_LOCAL_SOCKETS
2239 else if (STRINGP (address
))
2241 *familyp
= AF_LOCAL
;
2242 return sizeof (struct sockaddr_un
);
2245 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2246 && VECTORP (XCDR (address
)))
2248 struct sockaddr
*sa
;
2249 *familyp
= XINT (XCAR (address
));
2250 p
= XVECTOR (XCDR (address
));
2251 return p
->header
.size
+ sizeof (sa
->sa_family
);
2256 /* Convert an address object (vector or string) to an internal sockaddr.
2258 The address format has been basically validated by
2259 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2260 it could have come from user data. So if FAMILY is not valid,
2261 we return after zeroing *SA. */
2264 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2266 register struct Lisp_Vector
*p
;
2267 register unsigned char *cp
= NULL
;
2271 memset (sa
, 0, len
);
2273 if (VECTORP (address
))
2275 p
= XVECTOR (address
);
2276 if (family
== AF_INET
)
2278 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2279 len
= sizeof (sin
->sin_addr
) + 1;
2280 hostport
= XINT (p
->contents
[--len
]);
2281 sin
->sin_port
= htons (hostport
);
2282 cp
= (unsigned char *)&sin
->sin_addr
;
2283 sa
->sa_family
= family
;
2286 else if (family
== AF_INET6
)
2288 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2289 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2290 len
= sizeof (sin6
->sin6_addr
) + 1;
2291 hostport
= XINT (p
->contents
[--len
]);
2292 sin6
->sin6_port
= htons (hostport
);
2293 for (i
= 0; i
< len
; i
++)
2294 if (INTEGERP (p
->contents
[i
]))
2296 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2299 sa
->sa_family
= family
;
2306 else if (STRINGP (address
))
2308 #ifdef HAVE_LOCAL_SOCKETS
2309 if (family
== AF_LOCAL
)
2311 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2312 cp
= SDATA (address
);
2313 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2314 sockun
->sun_path
[i
] = *cp
++;
2315 sa
->sa_family
= family
;
2322 p
= XVECTOR (XCDR (address
));
2323 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2326 for (i
= 0; i
< len
; i
++)
2327 if (INTEGERP (p
->contents
[i
]))
2328 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2331 #ifdef DATAGRAM_SOCKETS
2332 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2334 doc
: /* Get the current datagram address associated with PROCESS. */)
2335 (Lisp_Object process
)
2339 CHECK_PROCESS (process
);
2341 if (!DATAGRAM_CONN_P (process
))
2344 channel
= XPROCESS (process
)->infd
;
2345 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2346 datagram_address
[channel
].len
);
2349 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2351 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2352 Returns nil upon error setting address, ADDRESS otherwise. */)
2353 (Lisp_Object process
, Lisp_Object address
)
2358 CHECK_PROCESS (process
);
2360 if (!DATAGRAM_CONN_P (process
))
2363 channel
= XPROCESS (process
)->infd
;
2365 len
= get_lisp_to_sockaddr_size (address
, &family
);
2366 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2368 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2374 static const struct socket_options
{
2375 /* The name of this option. Should be lowercase version of option
2376 name without SO_ prefix. */
2378 /* Option level SOL_... */
2380 /* Option number SO_... */
2382 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2383 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2384 } socket_options
[] =
2386 #ifdef SO_BINDTODEVICE
2387 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2390 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2393 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2396 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2399 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2402 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2405 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2408 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2410 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2413 /* Set option OPT to value VAL on socket S.
2415 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2416 Signals an error if setting a known option fails.
2420 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2423 const struct socket_options
*sopt
;
2428 name
= SSDATA (SYMBOL_NAME (opt
));
2429 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2430 if (strcmp (name
, sopt
->name
) == 0)
2433 switch (sopt
->opttype
)
2438 optval
= NILP (val
) ? 0 : 1;
2439 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2440 &optval
, sizeof (optval
));
2447 if (TYPE_RANGED_INTEGERP (int, val
))
2448 optval
= XINT (val
);
2450 error ("Bad option value for %s", name
);
2451 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2452 &optval
, sizeof (optval
));
2456 #ifdef SO_BINDTODEVICE
2459 char devname
[IFNAMSIZ
+1];
2461 /* This is broken, at least in the Linux 2.4 kernel.
2462 To unbind, the arg must be a zero integer, not the empty string.
2463 This should work on all systems. KFS. 2003-09-23. */
2464 memset (devname
, 0, sizeof devname
);
2467 char *arg
= SSDATA (val
);
2468 int len
= min (strlen (arg
), IFNAMSIZ
);
2469 memcpy (devname
, arg
, len
);
2471 else if (!NILP (val
))
2472 error ("Bad option value for %s", name
);
2473 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2482 struct linger linger
;
2485 linger
.l_linger
= 0;
2486 if (TYPE_RANGED_INTEGERP (int, val
))
2487 linger
.l_linger
= XINT (val
);
2489 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2490 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2491 &linger
, sizeof (linger
));
2502 int setsockopt_errno
= errno
;
2503 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2507 return (1 << sopt
->optbit
);
2511 DEFUN ("set-network-process-option",
2512 Fset_network_process_option
, Sset_network_process_option
,
2514 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2515 See `make-network-process' for a list of options and values.
2516 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2517 OPTION is not a supported option, return nil instead; otherwise return t. */)
2518 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2521 struct Lisp_Process
*p
;
2523 CHECK_PROCESS (process
);
2524 p
= XPROCESS (process
);
2525 if (!NETCONN1_P (p
))
2526 error ("Process is not a network process");
2530 error ("Process is not running");
2532 if (set_socket_option (s
, option
, value
))
2534 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2538 if (NILP (no_error
))
2539 error ("Unknown or unsupported option");
2545 DEFUN ("serial-process-configure",
2546 Fserial_process_configure
,
2547 Sserial_process_configure
,
2549 doc
: /* Configure speed, bytesize, etc. of a serial process.
2551 Arguments are specified as keyword/argument pairs. Attributes that
2552 are not given are re-initialized from the process's current
2553 configuration (available via the function `process-contact') or set to
2554 reasonable default values. The following arguments are defined:
2560 -- Any of these arguments can be given to identify the process that is
2561 to be configured. If none of these arguments is given, the current
2562 buffer's process is used.
2564 :speed SPEED -- SPEED is the speed of the serial port in bits per
2565 second, also called baud rate. Any value can be given for SPEED, but
2566 most serial ports work only at a few defined values between 1200 and
2567 115200, with 9600 being the most common value. If SPEED is nil, the
2568 serial port is not configured any further, i.e., all other arguments
2569 are ignored. This may be useful for special serial ports such as
2570 Bluetooth-to-serial converters which can only be configured through AT
2571 commands. A value of nil for SPEED can be used only when passed
2572 through `make-serial-process' or `serial-term'.
2574 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2575 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2577 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2578 `odd' (use odd parity), or the symbol `even' (use even parity). If
2579 PARITY is not given, no parity is used.
2581 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2582 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2583 is not given or nil, 1 stopbit is used.
2585 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2586 flowcontrol to be used, which is either nil (don't use flowcontrol),
2587 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2588 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2589 flowcontrol is used.
2591 `serial-process-configure' is called by `make-serial-process' for the
2592 initial configuration of the serial port.
2596 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2598 \(serial-process-configure
2599 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2601 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2603 usage: (serial-process-configure &rest ARGS) */)
2604 (ptrdiff_t nargs
, Lisp_Object
*args
)
2606 struct Lisp_Process
*p
;
2607 Lisp_Object contact
= Qnil
;
2608 Lisp_Object proc
= Qnil
;
2609 struct gcpro gcpro1
;
2611 contact
= Flist (nargs
, args
);
2614 proc
= Fplist_get (contact
, QCprocess
);
2616 proc
= Fplist_get (contact
, QCname
);
2618 proc
= Fplist_get (contact
, QCbuffer
);
2620 proc
= Fplist_get (contact
, QCport
);
2621 proc
= get_process (proc
);
2622 p
= XPROCESS (proc
);
2623 if (!EQ (p
->type
, Qserial
))
2624 error ("Not a serial process");
2626 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2632 serial_configure (p
, contact
);
2638 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2640 doc
: /* Create and return a serial port process.
2642 In Emacs, serial port connections are represented by process objects,
2643 so input and output work as for subprocesses, and `delete-process'
2644 closes a serial port connection. However, a serial process has no
2645 process id, it cannot be signaled, and the status codes are different
2646 from normal processes.
2648 `make-serial-process' creates a process and a buffer, on which you
2649 probably want to use `process-send-string'. Try \\[serial-term] for
2650 an interactive terminal. See below for examples.
2652 Arguments are specified as keyword/argument pairs. The following
2653 arguments are defined:
2655 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2656 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2657 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2658 the backslashes in strings).
2660 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2661 which this function calls.
2663 :name NAME -- NAME is the name of the process. If NAME is not given,
2664 the value of PORT is used.
2666 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2667 with the process. Process output goes at the end of that buffer,
2668 unless you specify an output stream or filter function to handle the
2669 output. If BUFFER is not given, the value of NAME is used.
2671 :coding CODING -- If CODING is a symbol, it specifies the coding
2672 system used for both reading and writing for this process. If CODING
2673 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2674 ENCODING is used for writing.
2676 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2677 the process is running. If BOOL is not given, query before exiting.
2679 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2680 In the stopped state, a serial process does not accept incoming data,
2681 but you can send outgoing data. The stopped state is cleared by
2682 `continue-process' and set by `stop-process'.
2684 :filter FILTER -- Install FILTER as the process filter.
2686 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2688 :plist PLIST -- Install PLIST as the initial plist of the process.
2694 -- This function calls `serial-process-configure' to handle these
2697 The original argument list, possibly modified by later configuration,
2698 is available via the function `process-contact'.
2702 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2704 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2706 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2708 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2710 usage: (make-serial-process &rest ARGS) */)
2711 (ptrdiff_t nargs
, Lisp_Object
*args
)
2714 Lisp_Object proc
, contact
, port
;
2715 struct Lisp_Process
*p
;
2716 struct gcpro gcpro1
;
2717 Lisp_Object name
, buffer
;
2718 Lisp_Object tem
, val
;
2719 ptrdiff_t specpdl_count
;
2724 contact
= Flist (nargs
, args
);
2727 port
= Fplist_get (contact
, QCport
);
2729 error ("No port specified");
2730 CHECK_STRING (port
);
2732 if (NILP (Fplist_member (contact
, QCspeed
)))
2733 error (":speed not specified");
2734 if (!NILP (Fplist_get (contact
, QCspeed
)))
2735 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2737 name
= Fplist_get (contact
, QCname
);
2740 CHECK_STRING (name
);
2741 proc
= make_process (name
);
2742 specpdl_count
= SPECPDL_INDEX ();
2743 record_unwind_protect (remove_process
, proc
);
2744 p
= XPROCESS (proc
);
2746 fd
= serial_open (port
);
2747 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2752 chan_process
[fd
] = proc
;
2754 buffer
= Fplist_get (contact
, QCbuffer
);
2757 buffer
= Fget_buffer_create (buffer
);
2758 pset_buffer (p
, buffer
);
2760 pset_childp (p
, contact
);
2761 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2762 pset_type (p
, Qserial
);
2763 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2764 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2766 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2767 p
->kill_without_query
= 1;
2768 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2769 pset_command (p
, Qt
);
2770 eassert (! p
->pty_flag
);
2772 if (!EQ (p
->command
, Qt
))
2773 add_non_keyboard_read_fd (fd
);
2775 if (BUFFERP (buffer
))
2777 set_marker_both (p
->mark
, buffer
,
2778 BUF_ZV (XBUFFER (buffer
)),
2779 BUF_ZV_BYTE (XBUFFER (buffer
)));
2782 tem
= Fplist_member (contact
, QCcoding
);
2783 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2789 val
= XCAR (XCDR (tem
));
2793 else if (!NILP (Vcoding_system_for_read
))
2794 val
= Vcoding_system_for_read
;
2795 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2796 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2798 pset_decode_coding_system (p
, val
);
2803 val
= XCAR (XCDR (tem
));
2807 else if (!NILP (Vcoding_system_for_write
))
2808 val
= Vcoding_system_for_write
;
2809 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2810 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2812 pset_encode_coding_system (p
, val
);
2814 setup_process_coding_systems (proc
);
2815 pset_decoding_buf (p
, empty_unibyte_string
);
2816 p
->decoding_carryover
= 0;
2817 pset_encoding_buf (p
, empty_unibyte_string
);
2818 p
->inherit_coding_system_flag
2819 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2821 Fserial_process_configure (nargs
, args
);
2823 specpdl_ptr
= specpdl
+ specpdl_count
;
2829 /* Create a network stream/datagram client/server process. Treated
2830 exactly like a normal process when reading and writing. Primary
2831 differences are in status display and process deletion. A network
2832 connection has no PID; you cannot signal it. All you can do is
2833 stop/continue it and deactivate/close it via delete-process */
2835 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2837 doc
: /* Create and return a network server or client process.
2839 In Emacs, network connections are represented by process objects, so
2840 input and output work as for subprocesses and `delete-process' closes
2841 a network connection. However, a network process has no process id,
2842 it cannot be signaled, and the status codes are different from normal
2845 Arguments are specified as keyword/argument pairs. The following
2846 arguments are defined:
2848 :name NAME -- NAME is name for process. It is modified if necessary
2851 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2852 with the process. Process output goes at end of that buffer, unless
2853 you specify an output stream or filter function to handle the output.
2854 BUFFER may be also nil, meaning that this process is not associated
2857 :host HOST -- HOST is name of the host to connect to, or its IP
2858 address. The symbol `local' specifies the local host. If specified
2859 for a server process, it must be a valid name or address for the local
2860 host, and only clients connecting to that address will be accepted.
2862 :service SERVICE -- SERVICE is name of the service desired, or an
2863 integer specifying a port number to connect to. If SERVICE is t,
2864 a random port number is selected for the server. (If Emacs was
2865 compiled with getaddrinfo, a port number can also be specified as a
2866 string, e.g. "80", as well as an integer. This is not portable.)
2868 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2869 stream type connection, `datagram' creates a datagram type connection,
2870 `seqpacket' creates a reliable datagram connection.
2872 :family FAMILY -- FAMILY is the address (and protocol) family for the
2873 service specified by HOST and SERVICE. The default (nil) is to use
2874 whatever address family (IPv4 or IPv6) that is defined for the host
2875 and port number specified by HOST and SERVICE. Other address families
2877 local -- for a local (i.e. UNIX) address specified by SERVICE.
2878 ipv4 -- use IPv4 address family only.
2879 ipv6 -- use IPv6 address family only.
2881 :local ADDRESS -- ADDRESS is the local address used for the connection.
2882 This parameter is ignored when opening a client process. When specified
2883 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2885 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2886 connection. This parameter is ignored when opening a stream server
2887 process. For a datagram server process, it specifies the initial
2888 setting of the remote datagram address. When specified for a client
2889 process, the FAMILY, HOST, and SERVICE args are ignored.
2891 The format of ADDRESS depends on the address family:
2892 - An IPv4 address is represented as an vector of integers [A B C D P]
2893 corresponding to numeric IP address A.B.C.D and port number P.
2894 - A local address is represented as a string with the address in the
2895 local address space.
2896 - An "unsupported family" address is represented by a cons (F . AV)
2897 where F is the family number and AV is a vector containing the socket
2898 address data with one element per address data byte. Do not rely on
2899 this format in portable code, as it may depend on implementation
2900 defined constants, data sizes, and data structure alignment.
2902 :coding CODING -- If CODING is a symbol, it specifies the coding
2903 system used for both reading and writing for this process. If CODING
2904 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2905 ENCODING is used for writing.
2907 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2908 return without waiting for the connection to complete; instead, the
2909 sentinel function will be called with second arg matching "open" (if
2910 successful) or "failed" when the connect completes. Default is to use
2911 a blocking connect (i.e. wait) for stream type connections.
2913 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2914 running when Emacs is exited.
2916 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2917 In the stopped state, a server process does not accept new
2918 connections, and a client process does not handle incoming traffic.
2919 The stopped state is cleared by `continue-process' and set by
2922 :filter FILTER -- Install FILTER as the process filter.
2924 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2925 process filter are multibyte, otherwise they are unibyte.
2926 If this keyword is not specified, the strings are multibyte if
2927 the default value of `enable-multibyte-characters' is non-nil.
2929 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2931 :log LOG -- Install LOG as the server process log function. This
2932 function is called when the server accepts a network connection from a
2933 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2934 is the server process, CLIENT is the new process for the connection,
2935 and MESSAGE is a string.
2937 :plist PLIST -- Install PLIST as the new process' initial plist.
2939 :server QLEN -- if QLEN is non-nil, create a server process for the
2940 specified FAMILY, SERVICE, and connection type (stream or datagram).
2941 If QLEN is an integer, it is used as the max. length of the server's
2942 pending connection queue (also known as the backlog); the default
2943 queue length is 5. Default is to create a client process.
2945 The following network options can be specified for this connection:
2947 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2948 :dontroute BOOL -- Only send to directly connected hosts.
2949 :keepalive BOOL -- Send keep-alive messages on network stream.
2950 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2951 :oobinline BOOL -- Place out-of-band data in receive data stream.
2952 :priority INT -- Set protocol defined priority for sent packets.
2953 :reuseaddr BOOL -- Allow reusing a recently used local address
2954 (this is allowed by default for a server process).
2955 :bindtodevice NAME -- bind to interface NAME. Using this may require
2956 special privileges on some systems.
2958 Consult the relevant system programmer's manual pages for more
2959 information on using these options.
2962 A server process will listen for and accept connections from clients.
2963 When a client connection is accepted, a new network process is created
2964 for the connection with the following parameters:
2966 - The client's process name is constructed by concatenating the server
2967 process' NAME and a client identification string.
2968 - If the FILTER argument is non-nil, the client process will not get a
2969 separate process buffer; otherwise, the client's process buffer is a newly
2970 created buffer named after the server process' BUFFER name or process
2971 NAME concatenated with the client identification string.
2972 - The connection type and the process filter and sentinel parameters are
2973 inherited from the server process' TYPE, FILTER and SENTINEL.
2974 - The client process' contact info is set according to the client's
2975 addressing information (typically an IP address and a port number).
2976 - The client process' plist is initialized from the server's plist.
2978 Notice that the FILTER and SENTINEL args are never used directly by
2979 the server process. Also, the BUFFER argument is not used directly by
2980 the server process, but via the optional :log function, accepted (and
2981 failed) connections may be logged in the server process' buffer.
2983 The original argument list, modified with the actual connection
2984 information, is available via the `process-contact' function.
2986 usage: (make-network-process &rest ARGS) */)
2987 (ptrdiff_t nargs
, Lisp_Object
*args
)
2990 Lisp_Object contact
;
2991 struct Lisp_Process
*p
;
2992 #ifdef HAVE_GETADDRINFO
2993 struct addrinfo ai
, *res
, *lres
;
2994 struct addrinfo hints
;
2995 const char *portstring
;
2997 #else /* HAVE_GETADDRINFO */
2998 struct _emacs_addrinfo
3004 struct sockaddr
*ai_addr
;
3005 struct _emacs_addrinfo
*ai_next
;
3007 #endif /* HAVE_GETADDRINFO */
3008 struct sockaddr_in address_in
;
3009 #ifdef HAVE_LOCAL_SOCKETS
3010 struct sockaddr_un address_un
;
3015 int s
= -1, outch
, inch
;
3016 struct gcpro gcpro1
;
3017 ptrdiff_t count
= SPECPDL_INDEX ();
3019 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
3021 Lisp_Object name
, buffer
, host
, service
, address
;
3022 Lisp_Object filter
, sentinel
;
3023 bool is_non_blocking_client
= 0;
3032 /* Save arguments for process-contact and clone-process. */
3033 contact
= Flist (nargs
, args
);
3037 /* Ensure socket support is loaded if available. */
3038 init_winsock (TRUE
);
3041 /* :type TYPE (nil: stream, datagram */
3042 tem
= Fplist_get (contact
, QCtype
);
3044 socktype
= SOCK_STREAM
;
3045 #ifdef DATAGRAM_SOCKETS
3046 else if (EQ (tem
, Qdatagram
))
3047 socktype
= SOCK_DGRAM
;
3049 #ifdef HAVE_SEQPACKET
3050 else if (EQ (tem
, Qseqpacket
))
3051 socktype
= SOCK_SEQPACKET
;
3054 error ("Unsupported connection type");
3057 tem
= Fplist_get (contact
, QCserver
);
3060 /* Don't support network sockets when non-blocking mode is
3061 not available, since a blocked Emacs is not useful. */
3063 if (TYPE_RANGED_INTEGERP (int, tem
))
3064 backlog
= XINT (tem
);
3067 /* Make QCaddress an alias for :local (server) or :remote (client). */
3068 QCaddress
= is_server
? QClocal
: QCremote
;
3071 if (!is_server
&& socktype
!= SOCK_DGRAM
3072 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
3074 #ifndef NON_BLOCKING_CONNECT
3075 error ("Non-blocking connect not supported");
3077 is_non_blocking_client
= 1;
3081 name
= Fplist_get (contact
, QCname
);
3082 buffer
= Fplist_get (contact
, QCbuffer
);
3083 filter
= Fplist_get (contact
, QCfilter
);
3084 sentinel
= Fplist_get (contact
, QCsentinel
);
3086 CHECK_STRING (name
);
3088 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3089 ai
.ai_socktype
= socktype
;
3094 /* :local ADDRESS or :remote ADDRESS */
3095 address
= Fplist_get (contact
, QCaddress
);
3096 if (!NILP (address
))
3098 host
= service
= Qnil
;
3100 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
3101 error ("Malformed :address");
3102 ai
.ai_family
= family
;
3103 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
3104 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
3108 /* :family FAMILY -- nil (for Inet), local, or integer. */
3109 tem
= Fplist_get (contact
, QCfamily
);
3112 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3118 #ifdef HAVE_LOCAL_SOCKETS
3119 else if (EQ (tem
, Qlocal
))
3123 else if (EQ (tem
, Qipv6
))
3126 else if (EQ (tem
, Qipv4
))
3128 else if (TYPE_RANGED_INTEGERP (int, tem
))
3129 family
= XINT (tem
);
3131 error ("Unknown address family");
3133 ai
.ai_family
= family
;
3135 /* :service SERVICE -- string, integer (port number), or t (random port). */
3136 service
= Fplist_get (contact
, QCservice
);
3138 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3139 host
= Fplist_get (contact
, QChost
);
3142 if (EQ (host
, Qlocal
))
3143 /* Depending on setup, "localhost" may map to different IPv4 and/or
3144 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3145 host
= build_string ("127.0.0.1");
3146 CHECK_STRING (host
);
3149 #ifdef HAVE_LOCAL_SOCKETS
3150 if (family
== AF_LOCAL
)
3154 message (":family local ignores the :host \"%s\" property",
3156 contact
= Fplist_put (contact
, QChost
, Qnil
);
3159 CHECK_STRING (service
);
3160 memset (&address_un
, 0, sizeof address_un
);
3161 address_un
.sun_family
= AF_LOCAL
;
3162 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3163 error ("Service name too long");
3164 strcpy (address_un
.sun_path
, SSDATA (service
));
3165 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3166 ai
.ai_addrlen
= sizeof address_un
;
3171 /* Slow down polling to every ten seconds.
3172 Some kernels have a bug which causes retrying connect to fail
3173 after a connect. Polling can interfere with gethostbyname too. */
3174 #ifdef POLL_FOR_INPUT
3175 if (socktype
!= SOCK_DGRAM
)
3177 record_unwind_protect_void (run_all_atimers
);
3178 bind_polling_period (10);
3182 #ifdef HAVE_GETADDRINFO
3183 /* If we have a host, use getaddrinfo to resolve both host and service.
3184 Otherwise, use getservbyname to lookup the service. */
3188 /* SERVICE can either be a string or int.
3189 Convert to a C string for later use by getaddrinfo. */
3190 if (EQ (service
, Qt
))
3192 else if (INTEGERP (service
))
3194 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3195 portstring
= portbuf
;
3199 CHECK_STRING (service
);
3200 portstring
= SSDATA (service
);
3205 memset (&hints
, 0, sizeof (hints
));
3207 hints
.ai_family
= family
;
3208 hints
.ai_socktype
= socktype
;
3209 hints
.ai_protocol
= 0;
3211 #ifdef HAVE_RES_INIT
3215 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3217 #ifdef HAVE_GAI_STRERROR
3218 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3220 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3226 #endif /* HAVE_GETADDRINFO */
3228 /* We end up here if getaddrinfo is not defined, or in case no hostname
3229 has been specified (e.g. for a local server process). */
3231 if (EQ (service
, Qt
))
3233 else if (INTEGERP (service
))
3234 port
= htons ((unsigned short) XINT (service
));
3237 struct servent
*svc_info
;
3238 CHECK_STRING (service
);
3239 svc_info
= getservbyname (SSDATA (service
),
3240 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3242 error ("Unknown service: %s", SDATA (service
));
3243 port
= svc_info
->s_port
;
3246 memset (&address_in
, 0, sizeof address_in
);
3247 address_in
.sin_family
= family
;
3248 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3249 address_in
.sin_port
= port
;
3251 #ifndef HAVE_GETADDRINFO
3254 struct hostent
*host_info_ptr
;
3256 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3257 as it may `hang' Emacs for a very long time. */
3261 #ifdef HAVE_RES_INIT
3265 host_info_ptr
= gethostbyname (SDATA (host
));
3270 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3271 host_info_ptr
->h_length
);
3272 family
= host_info_ptr
->h_addrtype
;
3273 address_in
.sin_family
= family
;
3276 /* Attempt to interpret host as numeric inet address */
3278 unsigned long numeric_addr
;
3279 numeric_addr
= inet_addr (SSDATA (host
));
3280 if (numeric_addr
== -1)
3281 error ("Unknown host \"%s\"", SDATA (host
));
3283 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3284 sizeof (address_in
.sin_addr
));
3288 #endif /* not HAVE_GETADDRINFO */
3290 ai
.ai_family
= family
;
3291 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3292 ai
.ai_addrlen
= sizeof address_in
;
3296 /* Do this in case we never enter the for-loop below. */
3297 count1
= SPECPDL_INDEX ();
3300 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3309 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3317 #ifdef DATAGRAM_SOCKETS
3318 if (!is_server
&& socktype
== SOCK_DGRAM
)
3320 #endif /* DATAGRAM_SOCKETS */
3322 #ifdef NON_BLOCKING_CONNECT
3323 if (is_non_blocking_client
)
3325 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3336 /* Make us close S if quit. */
3337 record_unwind_protect_int (close_file_unwind
, s
);
3339 /* Parse network options in the arg list.
3340 We simply ignore anything which isn't a known option (including other keywords).
3341 An error is signaled if setting a known option fails. */
3342 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3343 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3347 /* Configure as a server socket. */
3349 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3350 explicit :reuseaddr key to override this. */
3351 #ifdef HAVE_LOCAL_SOCKETS
3352 if (family
!= AF_LOCAL
)
3354 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3357 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3358 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3361 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3362 report_file_error ("Cannot bind server socket", Qnil
);
3364 #ifdef HAVE_GETSOCKNAME
3365 if (EQ (service
, Qt
))
3367 struct sockaddr_in sa1
;
3368 socklen_t len1
= sizeof (sa1
);
3369 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3371 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3372 service
= make_number (ntohs (sa1
.sin_port
));
3373 contact
= Fplist_put (contact
, QCservice
, service
);
3378 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3379 report_file_error ("Cannot listen on server socket", Qnil
);
3387 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3390 if (ret
== 0 || xerrno
== EISCONN
)
3392 /* The unwind-protect will be discarded afterwards.
3393 Likewise for immediate_quit. */
3397 #ifdef NON_BLOCKING_CONNECT
3399 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3403 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3410 if (xerrno
== EINTR
)
3412 /* Unlike most other syscalls connect() cannot be called
3413 again. (That would return EALREADY.) The proper way to
3414 wait for completion is pselect(). */
3422 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3428 report_file_error ("Failed select", Qnil
);
3432 len
= sizeof xerrno
;
3433 eassert (FD_ISSET (s
, &fdset
));
3434 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3435 report_file_error ("Failed getsockopt", Qnil
);
3437 report_file_errno ("Failed connect", Qnil
, xerrno
);
3440 #endif /* !WINDOWSNT */
3444 /* Discard the unwind protect closing S. */
3445 specpdl_ptr
= specpdl
+ count1
;
3450 if (xerrno
== EINTR
)
3457 #ifdef DATAGRAM_SOCKETS
3458 if (socktype
== SOCK_DGRAM
)
3460 if (datagram_address
[s
].sa
)
3462 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3463 datagram_address
[s
].len
= lres
->ai_addrlen
;
3467 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3468 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3471 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3472 if (rlen
!= 0 && rfamily
== lres
->ai_family
3473 && rlen
== lres
->ai_addrlen
)
3474 conv_lisp_to_sockaddr (rfamily
, remote
,
3475 datagram_address
[s
].sa
, rlen
);
3479 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3482 contact
= Fplist_put (contact
, QCaddress
,
3483 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3484 #ifdef HAVE_GETSOCKNAME
3487 struct sockaddr_in sa1
;
3488 socklen_t len1
= sizeof (sa1
);
3489 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3490 contact
= Fplist_put (contact
, QClocal
,
3491 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3498 #ifdef HAVE_GETADDRINFO
3509 /* If non-blocking got this far - and failed - assume non-blocking is
3510 not supported after all. This is probably a wrong assumption, but
3511 the normal blocking calls to open-network-stream handles this error
3513 if (is_non_blocking_client
)
3516 report_file_errno ((is_server
3517 ? "make server process failed"
3518 : "make client process failed"),
3526 buffer
= Fget_buffer_create (buffer
);
3527 proc
= make_process (name
);
3529 chan_process
[inch
] = proc
;
3531 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3533 p
= XPROCESS (proc
);
3535 pset_childp (p
, contact
);
3536 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3537 pset_type (p
, Qnetwork
);
3539 pset_buffer (p
, buffer
);
3540 pset_sentinel (p
, sentinel
);
3541 pset_filter (p
, filter
);
3542 pset_log (p
, Fplist_get (contact
, QClog
));
3543 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3544 p
->kill_without_query
= 1;
3545 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3546 pset_command (p
, Qt
);
3549 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3553 /* Discard the unwind protect for closing S, if any. */
3554 specpdl_ptr
= specpdl
+ count1
;
3556 /* Unwind bind_polling_period and request_sigio. */
3557 unbind_to (count
, Qnil
);
3559 if (is_server
&& socktype
!= SOCK_DGRAM
)
3560 pset_status (p
, Qlisten
);
3562 /* Make the process marker point into the process buffer (if any). */
3563 if (BUFFERP (buffer
))
3564 set_marker_both (p
->mark
, buffer
,
3565 BUF_ZV (XBUFFER (buffer
)),
3566 BUF_ZV_BYTE (XBUFFER (buffer
)));
3568 #ifdef NON_BLOCKING_CONNECT
3569 if (is_non_blocking_client
)
3571 /* We may get here if connect did succeed immediately. However,
3572 in that case, we still need to signal this like a non-blocking
3574 pset_status (p
, Qconnect
);
3575 if ((fd_callback_info
[inch
].flags
& NON_BLOCKING_CONNECT_FD
) == 0)
3576 add_non_blocking_write_fd (inch
);
3580 /* A server may have a client filter setting of Qt, but it must
3581 still listen for incoming connects unless it is stopped. */
3582 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3583 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3584 add_non_keyboard_read_fd (inch
);
3586 if (inch
> max_desc
)
3589 tem
= Fplist_member (contact
, QCcoding
);
3590 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3591 tem
= Qnil
; /* No error message (too late!). */
3594 /* Setup coding systems for communicating with the network stream. */
3595 struct gcpro gcpro1
;
3596 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3597 Lisp_Object coding_systems
= Qt
;
3598 Lisp_Object fargs
[5], val
;
3602 val
= XCAR (XCDR (tem
));
3606 else if (!NILP (Vcoding_system_for_read
))
3607 val
= Vcoding_system_for_read
;
3608 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3609 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3610 /* We dare not decode end-of-line format by setting VAL to
3611 Qraw_text, because the existing Emacs Lisp libraries
3612 assume that they receive bare code including a sequence of
3617 if (NILP (host
) || NILP (service
))
3618 coding_systems
= Qnil
;
3621 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3622 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3624 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3627 if (CONSP (coding_systems
))
3628 val
= XCAR (coding_systems
);
3629 else if (CONSP (Vdefault_process_coding_system
))
3630 val
= XCAR (Vdefault_process_coding_system
);
3634 pset_decode_coding_system (p
, val
);
3638 val
= XCAR (XCDR (tem
));
3642 else if (!NILP (Vcoding_system_for_write
))
3643 val
= Vcoding_system_for_write
;
3644 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3648 if (EQ (coding_systems
, Qt
))
3650 if (NILP (host
) || NILP (service
))
3651 coding_systems
= Qnil
;
3654 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3655 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3657 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3661 if (CONSP (coding_systems
))
3662 val
= XCDR (coding_systems
);
3663 else if (CONSP (Vdefault_process_coding_system
))
3664 val
= XCDR (Vdefault_process_coding_system
);
3668 pset_encode_coding_system (p
, val
);
3670 setup_process_coding_systems (proc
);
3672 pset_decoding_buf (p
, empty_unibyte_string
);
3673 p
->decoding_carryover
= 0;
3674 pset_encoding_buf (p
, empty_unibyte_string
);
3676 p
->inherit_coding_system_flag
3677 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3684 #if defined (HAVE_NET_IF_H)
3687 DEFUN ("network-interface-list", Fnetwork_interface_list
, Snetwork_interface_list
, 0, 0, 0,
3688 doc
: /* Return an alist of all network interfaces and their network address.
3689 Each element is a cons, the car of which is a string containing the
3690 interface name, and the cdr is the network address in internal
3691 format; see the description of ADDRESS in `make-network-process'. */)
3694 struct ifconf ifconf
;
3695 struct ifreq
*ifreq
;
3697 ptrdiff_t buf_size
= 512;
3702 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3705 count
= SPECPDL_INDEX ();
3706 record_unwind_protect_int (close_file_unwind
, s
);
3710 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3711 ifconf
.ifc_buf
= buf
;
3712 ifconf
.ifc_len
= buf_size
;
3713 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3720 while (ifconf
.ifc_len
== buf_size
);
3722 res
= unbind_to (count
, Qnil
);
3723 ifreq
= ifconf
.ifc_req
;
3724 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3726 struct ifreq
*ifq
= ifreq
;
3727 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3728 #define SIZEOF_IFREQ(sif) \
3729 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3730 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3732 int len
= SIZEOF_IFREQ (ifq
);
3734 int len
= sizeof (*ifreq
);
3736 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3737 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3739 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3742 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3743 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3744 res
= Fcons (Fcons (build_string (namebuf
),
3745 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3746 sizeof (struct sockaddr
))),
3753 #endif /* SIOCGIFCONF */
3755 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3759 const char *flag_sym
;
3762 static const struct ifflag_def ifflag_table
[] = {
3766 #ifdef IFF_BROADCAST
3767 { IFF_BROADCAST
, "broadcast" },
3770 { IFF_DEBUG
, "debug" },
3773 { IFF_LOOPBACK
, "loopback" },
3775 #ifdef IFF_POINTOPOINT
3776 { IFF_POINTOPOINT
, "pointopoint" },
3779 { IFF_RUNNING
, "running" },
3782 { IFF_NOARP
, "noarp" },
3785 { IFF_PROMISC
, "promisc" },
3787 #ifdef IFF_NOTRAILERS
3788 #ifdef NS_IMPL_COCOA
3789 /* Really means smart, notrailers is obsolete */
3790 { IFF_NOTRAILERS
, "smart" },
3792 { IFF_NOTRAILERS
, "notrailers" },
3796 { IFF_ALLMULTI
, "allmulti" },
3799 { IFF_MASTER
, "master" },
3802 { IFF_SLAVE
, "slave" },
3804 #ifdef IFF_MULTICAST
3805 { IFF_MULTICAST
, "multicast" },
3808 { IFF_PORTSEL
, "portsel" },
3810 #ifdef IFF_AUTOMEDIA
3811 { IFF_AUTOMEDIA
, "automedia" },
3814 { IFF_DYNAMIC
, "dynamic" },
3817 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3820 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3823 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3826 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3829 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3834 DEFUN ("network-interface-info", Fnetwork_interface_info
, Snetwork_interface_info
, 1, 1, 0,
3835 doc
: /* Return information about network interface named IFNAME.
3836 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3837 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3838 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3839 FLAGS is the current flags of the interface. */)
3840 (Lisp_Object ifname
)
3843 Lisp_Object res
= Qnil
;
3848 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3849 && defined HAVE_GETIFADDRS && defined LLADDR)
3850 struct ifaddrs
*ifap
;
3853 CHECK_STRING (ifname
);
3855 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3856 error ("interface name too long");
3857 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3859 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3862 count
= SPECPDL_INDEX ();
3863 record_unwind_protect_int (close_file_unwind
, s
);
3866 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3867 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3869 int flags
= rq
.ifr_flags
;
3870 const struct ifflag_def
*fp
;
3873 /* If flags is smaller than int (i.e. short) it may have the high bit set
3874 due to IFF_MULTICAST. In that case, sign extending it into
3876 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3877 flags
= (unsigned short) rq
.ifr_flags
;
3880 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3882 if (flags
& fp
->flag_bit
)
3884 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3885 flags
-= fp
->flag_bit
;
3888 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3892 elt
= Fcons (make_number (fnum
), elt
);
3897 res
= Fcons (elt
, res
);
3900 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3901 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3903 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3904 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3908 for (n
= 0; n
< 6; n
++)
3909 p
->contents
[n
] = make_number (((unsigned char *)&rq
.ifr_hwaddr
.sa_data
[0])[n
]);
3910 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3912 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3913 if (getifaddrs (&ifap
) != -1)
3915 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3916 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3919 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3921 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3922 unsigned char linkaddr
[6];
3925 if (it
->ifa_addr
->sa_family
!= AF_LINK
3926 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3927 || sdl
->sdl_alen
!= 6)
3930 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3931 for (n
= 0; n
< 6; n
++)
3932 p
->contents
[n
] = make_number (linkaddr
[n
]);
3934 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3938 #ifdef HAVE_FREEIFADDRS
3942 #endif /* HAVE_GETIFADDRS && LLADDR */
3944 res
= Fcons (elt
, res
);
3947 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3948 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3951 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3952 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3954 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3958 res
= Fcons (elt
, res
);
3961 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3962 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3965 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3968 res
= Fcons (elt
, res
);
3971 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3972 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3975 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3978 res
= Fcons (elt
, res
);
3980 return unbind_to (count
, any
? res
: Qnil
);
3983 #endif /* defined (HAVE_NET_IF_H) */
3985 /* Turn off input and output for process PROC. */
3988 deactivate_process (Lisp_Object proc
)
3991 struct Lisp_Process
*p
= XPROCESS (proc
);
3995 /* Delete GnuTLS structures in PROC, if any. */
3996 emacs_gnutls_deinit (proc
);
3997 #endif /* HAVE_GNUTLS */
3999 #ifdef ADAPTIVE_READ_BUFFERING
4000 if (p
->read_output_delay
> 0)
4002 if (--process_output_delay_count
< 0)
4003 process_output_delay_count
= 0;
4004 p
->read_output_delay
= 0;
4005 p
->read_output_skip
= 0;
4009 /* Beware SIGCHLD hereabouts. */
4011 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
4012 close_process_fd (&p
->open_fd
[i
]);
4014 inchannel
= p
->infd
;
4019 #ifdef DATAGRAM_SOCKETS
4020 if (DATAGRAM_CHAN_P (inchannel
))
4022 xfree (datagram_address
[inchannel
].sa
);
4023 datagram_address
[inchannel
].sa
= 0;
4024 datagram_address
[inchannel
].len
= 0;
4027 chan_process
[inchannel
] = Qnil
;
4028 delete_read_fd (inchannel
);
4029 #ifdef NON_BLOCKING_CONNECT
4030 if ((fd_callback_info
[inchannel
].flags
& NON_BLOCKING_CONNECT_FD
) != 0)
4031 delete_write_fd (inchannel
);
4033 if (inchannel
== max_desc
)
4034 recompute_max_desc ();
4039 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
4041 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4042 It is read into the process' buffers or given to their filter functions.
4043 Non-nil arg PROCESS means do not return until some output has been received
4046 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4047 and milliseconds to wait; return after that much time whether or not
4048 there is any subprocess output. If SECONDS is a floating point number,
4049 it specifies a fractional number of seconds to wait.
4050 The MILLISEC argument is obsolete and should be avoided.
4052 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4053 from PROCESS, suspending reading output from other processes.
4054 If JUST-THIS-ONE is an integer, don't run any timers either.
4055 Return non-nil if we received any output before the timeout expired. */)
4056 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4061 if (! NILP (process
))
4063 struct Lisp_Process
*procp
;
4065 CHECK_PROCESS (process
);
4066 procp
= XPROCESS (process
);
4068 /* Can't wait for a process that is dedicated to a different
4070 if (!EQ (procp
->thread
, Qnil
) && !EQ (procp
->thread
, Fcurrent_thread ()))
4074 just_this_one
= Qnil
;
4076 if (!NILP (millisec
))
4077 { /* Obsolete calling convention using integers rather than floats. */
4078 CHECK_NUMBER (millisec
);
4080 seconds
= make_float (XINT (millisec
) / 1000.0);
4083 CHECK_NUMBER (seconds
);
4084 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4091 if (!NILP (seconds
))
4093 if (INTEGERP (seconds
))
4095 if (XINT (seconds
) > 0)
4097 secs
= XINT (seconds
);
4101 else if (FLOATP (seconds
))
4103 if (XFLOAT_DATA (seconds
) > 0)
4105 EMACS_TIME t
= EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds
));
4106 secs
= min (EMACS_SECS (t
), WAIT_READING_MAX
);
4107 nsecs
= EMACS_NSECS (t
);
4111 wrong_type_argument (Qnumberp
, seconds
);
4113 else if (! NILP (process
))
4117 (wait_reading_process_output (secs
, nsecs
, 0, 0,
4119 !NILP (process
) ? XPROCESS (process
) : NULL
,
4120 NILP (just_this_one
) ? 0 :
4121 !INTEGERP (just_this_one
) ? 1 : -1)
4125 /* Accept a connection for server process SERVER on CHANNEL. */
4127 static EMACS_INT connect_counter
= 0;
4130 server_accept_connection (Lisp_Object server
, int channel
)
4132 Lisp_Object proc
, caller
, name
, buffer
;
4133 Lisp_Object contact
, host
, service
;
4134 struct Lisp_Process
*ps
= XPROCESS (server
);
4135 struct Lisp_Process
*p
;
4139 struct sockaddr_in in
;
4141 struct sockaddr_in6 in6
;
4143 #ifdef HAVE_LOCAL_SOCKETS
4144 struct sockaddr_un un
;
4147 socklen_t len
= sizeof saddr
;
4150 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4159 if (code
== EWOULDBLOCK
)
4163 if (!NILP (ps
->log
))
4164 call3 (ps
->log
, server
, Qnil
,
4165 concat3 (build_string ("accept failed with code"),
4166 Fnumber_to_string (make_number (code
)),
4167 build_string ("\n")));
4171 count
= SPECPDL_INDEX ();
4172 record_unwind_protect_int (close_file_unwind
, s
);
4176 /* Setup a new process to handle the connection. */
4178 /* Generate a unique identification of the caller, and build contact
4179 information for this process. */
4182 switch (saddr
.sa
.sa_family
)
4186 Lisp_Object args
[5];
4187 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4188 args
[0] = build_string ("%d.%d.%d.%d");
4189 args
[1] = make_number (*ip
++);
4190 args
[2] = make_number (*ip
++);
4191 args
[3] = make_number (*ip
++);
4192 args
[4] = make_number (*ip
++);
4193 host
= Fformat (5, args
);
4194 service
= make_number (ntohs (saddr
.in
.sin_port
));
4196 args
[0] = build_string (" <%s:%d>");
4199 caller
= Fformat (3, args
);
4206 Lisp_Object args
[9];
4207 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4209 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4210 for (i
= 0; i
< 8; i
++)
4211 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4212 host
= Fformat (9, args
);
4213 service
= make_number (ntohs (saddr
.in
.sin_port
));
4215 args
[0] = build_string (" <[%s]:%d>");
4218 caller
= Fformat (3, args
);
4223 #ifdef HAVE_LOCAL_SOCKETS
4227 caller
= Fnumber_to_string (make_number (connect_counter
));
4228 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4232 /* Create a new buffer name for this process if it doesn't have a
4233 filter. The new buffer name is based on the buffer name or
4234 process name of the server process concatenated with the caller
4237 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4238 || EQ (ps
->filter
, Qt
)))
4242 buffer
= ps
->buffer
;
4244 buffer
= Fbuffer_name (buffer
);
4249 buffer
= concat2 (buffer
, caller
);
4250 buffer
= Fget_buffer_create (buffer
);
4254 /* Generate a unique name for the new server process. Combine the
4255 server process name with the caller identification. */
4257 name
= concat2 (ps
->name
, caller
);
4258 proc
= make_process (name
);
4260 chan_process
[s
] = proc
;
4262 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4264 p
= XPROCESS (proc
);
4266 /* Build new contact information for this setup. */
4267 contact
= Fcopy_sequence (ps
->childp
);
4268 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4269 contact
= Fplist_put (contact
, QChost
, host
);
4270 if (!NILP (service
))
4271 contact
= Fplist_put (contact
, QCservice
, service
);
4272 contact
= Fplist_put (contact
, QCremote
,
4273 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4274 #ifdef HAVE_GETSOCKNAME
4276 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4277 contact
= Fplist_put (contact
, QClocal
,
4278 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4281 pset_childp (p
, contact
);
4282 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4283 pset_type (p
, Qnetwork
);
4285 pset_buffer (p
, buffer
);
4286 pset_sentinel (p
, ps
->sentinel
);
4287 pset_filter (p
, ps
->filter
);
4288 pset_command (p
, Qnil
);
4291 /* Discard the unwind protect for closing S. */
4292 specpdl_ptr
= specpdl
+ count
;
4294 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4297 pset_status (p
, Qrun
);
4299 /* Client processes for accepted connections are not stopped initially. */
4300 if (!EQ (p
->filter
, Qt
))
4301 add_non_keyboard_read_fd (s
);
4303 /* Setup coding system for new process based on server process.
4304 This seems to be the proper thing to do, as the coding system
4305 of the new process should reflect the settings at the time the
4306 server socket was opened; not the current settings. */
4308 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4309 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4310 setup_process_coding_systems (proc
);
4312 pset_decoding_buf (p
, empty_unibyte_string
);
4313 p
->decoding_carryover
= 0;
4314 pset_encoding_buf (p
, empty_unibyte_string
);
4316 p
->inherit_coding_system_flag
4317 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4319 if (!NILP (ps
->log
))
4320 call3 (ps
->log
, server
, proc
,
4321 concat3 (build_string ("accept from "),
4322 (STRINGP (host
) ? host
: build_string ("-")),
4323 build_string ("\n")));
4325 exec_sentinel (proc
,
4326 concat3 (build_string ("open from "),
4327 (STRINGP (host
) ? host
: build_string ("-")),
4328 build_string ("\n")));
4332 wait_reading_process_output_unwind (int data
)
4334 clear_waiting_thread_info ();
4335 waiting_for_user_input_p
= data
;
4338 /* This is here so breakpoints can be put on it. */
4340 wait_reading_process_output_1 (void)
4344 /* Read and dispose of subprocess output while waiting for timeout to
4345 elapse and/or keyboard input to be available.
4349 If negative, gobble data immediately available but don't wait for any.
4352 an additional duration to wait, measured in nanoseconds
4353 If TIME_LIMIT is zero, then:
4354 If NSECS == 0, there is no limit.
4355 If NSECS > 0, the timeout consists of NSECS only.
4356 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4359 0 to ignore keyboard input, or
4360 1 to return when input is available, or
4361 -1 meaning caller will actually read the input, so don't throw to
4362 the quit handler, or
4364 DO_DISPLAY means redisplay should be done to show subprocess
4365 output that arrives.
4367 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4368 (and gobble terminal input into the buffer if any arrives).
4370 If WAIT_PROC is specified, wait until something arrives from that
4371 process. The return value is true if we read some input from
4374 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4375 (suspending output from other processes). A negative value
4376 means don't run any timers either.
4378 If WAIT_PROC is specified, then the function returns true if we
4379 received input from that process before the timeout elapsed.
4380 Otherwise, return true if we received input from any process. */
4383 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4385 Lisp_Object wait_for_cell
,
4386 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4389 SELECT_TYPE Available
;
4390 SELECT_TYPE Writeok
;
4396 EMACS_TIME timeout
, end_time
;
4397 int wait_channel
= -1;
4398 bool got_some_input
= 0;
4399 ptrdiff_t count
= SPECPDL_INDEX ();
4401 eassert (wait_proc
== NULL
4402 || EQ (wait_proc
->thread
, Qnil
)
4403 || XTHREAD (wait_proc
->thread
) == current_thread
);
4405 FD_ZERO (&Available
);
4408 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4409 && !(CONSP (wait_proc
->status
)
4410 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4411 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4413 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4414 if (wait_proc
!= NULL
)
4415 wait_channel
= wait_proc
->infd
;
4417 record_unwind_protect_int (wait_reading_process_output_unwind
,
4418 waiting_for_user_input_p
);
4419 waiting_for_user_input_p
= read_kbd
;
4426 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4427 time_limit
= TYPE_MAXIMUM (time_t);
4429 /* Since we may need to wait several times,
4430 compute the absolute time to return at. */
4431 if (time_limit
|| nsecs
> 0)
4433 timeout
= make_emacs_time (time_limit
, nsecs
);
4434 end_time
= add_emacs_time (current_emacs_time (), timeout
);
4439 bool timeout_reduced_for_timers
= 0;
4441 /* If calling from keyboard input, do not quit
4442 since we want to return C-g as an input character.
4443 Otherwise, do pending quit if requested. */
4446 else if (pending_signals
)
4447 process_pending_signals ();
4449 /* Exit now if the cell we're waiting for became non-nil. */
4450 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4453 /* Compute time from now till when time limit is up. */
4454 /* Exit if already run out. */
4457 /* A negative timeout means
4458 gobble output available now
4459 but don't wait at all. */
4461 timeout
= make_emacs_time (0, 0);
4463 else if (time_limit
|| nsecs
> 0)
4465 EMACS_TIME now
= current_emacs_time ();
4466 if (EMACS_TIME_LE (end_time
, now
))
4468 timeout
= sub_emacs_time (end_time
, now
);
4472 timeout
= make_emacs_time (100000, 0);
4475 /* Normally we run timers here.
4476 But not if wait_for_cell; in those cases,
4477 the wait is supposed to be short,
4478 and those callers cannot handle running arbitrary Lisp code here. */
4479 if (NILP (wait_for_cell
)
4480 && just_wait_proc
>= 0)
4482 EMACS_TIME timer_delay
;
4486 unsigned old_timers_run
= timers_run
;
4487 struct buffer
*old_buffer
= current_buffer
;
4488 Lisp_Object old_window
= selected_window
;
4490 timer_delay
= timer_check ();
4492 /* If a timer has run, this might have changed buffers
4493 an alike. Make read_key_sequence aware of that. */
4494 if (timers_run
!= old_timers_run
4495 && (old_buffer
!= current_buffer
4496 || !EQ (old_window
, selected_window
))
4497 && waiting_for_user_input_p
== -1)
4498 record_asynch_buffer_change ();
4500 if (timers_run
!= old_timers_run
&& do_display
)
4501 /* We must retry, since a timer may have requeued itself
4502 and that could alter the time_delay. */
4503 redisplay_preserve_echo_area (9);
4507 while (!detect_input_pending ());
4509 /* If there is unread keyboard input, also return. */
4511 && requeued_events_pending_p ())
4514 /* A negative timeout means do not wait at all. */
4517 if (EMACS_TIME_VALID_P (timer_delay
))
4519 if (EMACS_TIME_LT (timer_delay
, timeout
))
4521 timeout
= timer_delay
;
4522 timeout_reduced_for_timers
= 1;
4527 /* This is so a breakpoint can be put here. */
4528 wait_reading_process_output_1 ();
4533 /* Cause C-g and alarm signals to take immediate action,
4534 and cause input available signals to zero out timeout.
4536 It is important that we do this before checking for process
4537 activity. If we get a SIGCHLD after the explicit checks for
4538 process activity, timeout is the only way we will know. */
4540 set_waiting_for_input (&timeout
);
4542 /* If status of something has changed, and no input is
4543 available, notify the user of the change right away. After
4544 this explicit check, we'll let the SIGCHLD handler zap
4545 timeout to get our attention. */
4546 if (update_tick
!= process_tick
)
4551 if (kbd_on_hold_p ())
4554 compute_input_wait_mask (&Atemp
);
4555 compute_write_mask (&Ctemp
);
4557 timeout
= make_emacs_time (0, 0);
4558 if ((thread_select (pselect
, max_desc
+ 1,
4560 #ifdef NON_BLOCKING_CONNECT
4561 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4565 NULL
, &timeout
, NULL
)
4568 /* It's okay for us to do this and then continue with
4569 the loop, since timeout has already been zeroed out. */
4570 clear_waiting_for_input ();
4571 status_notify (NULL
);
4572 if (do_display
) redisplay_preserve_echo_area (13);
4576 /* Don't wait for output from a non-running process. Just
4577 read whatever data has already been received. */
4578 if (wait_proc
&& wait_proc
->raw_status_new
)
4579 update_status (wait_proc
);
4581 && ! EQ (wait_proc
->status
, Qrun
)
4582 && ! EQ (wait_proc
->status
, Qconnect
))
4584 bool read_some_bytes
= 0;
4586 clear_waiting_for_input ();
4587 XSETPROCESS (proc
, wait_proc
);
4589 /* Read data from the process, until we exhaust it. */
4590 while (wait_proc
->infd
>= 0)
4592 int nread
= read_process_output (proc
, wait_proc
->infd
);
4598 got_some_input
= read_some_bytes
= 1;
4599 else if (nread
== -1 && (errno
== EIO
|| errno
== EAGAIN
))
4602 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4606 if (read_some_bytes
&& do_display
)
4607 redisplay_preserve_echo_area (10);
4612 /* Wait till there is something to do */
4614 if (wait_proc
&& just_wait_proc
)
4616 if (wait_proc
->infd
< 0) /* Terminated */
4618 FD_SET (wait_proc
->infd
, &Available
);
4622 else if (!NILP (wait_for_cell
))
4624 compute_non_process_wait_mask (&Available
);
4631 compute_non_keyboard_wait_mask (&Available
);
4633 compute_input_wait_mask (&Available
);
4634 compute_write_mask (&Writeok
);
4635 #ifdef SELECT_CANT_DO_WRITE_MASK
4640 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4643 /* If frame size has changed or the window is newly mapped,
4644 redisplay now, before we start to wait. There is a race
4645 condition here; if a SIGIO arrives between now and the select
4646 and indicates that a frame is trashed, the select may block
4647 displaying a trashed screen. */
4648 if (frame_garbaged
&& do_display
)
4650 clear_waiting_for_input ();
4651 redisplay_preserve_echo_area (11);
4653 set_waiting_for_input (&timeout
);
4656 /* Skip the `select' call if input is available and we're
4657 waiting for keyboard input or a cell change (which can be
4658 triggered by processing X events). In the latter case, set
4659 nfds to 1 to avoid breaking the loop. */
4661 if ((read_kbd
|| !NILP (wait_for_cell
))
4662 && detect_input_pending ())
4664 nfds
= read_kbd
? 0 : 1;
4671 #ifdef ADAPTIVE_READ_BUFFERING
4672 /* Set the timeout for adaptive read buffering if any
4673 process has non-zero read_output_skip and non-zero
4674 read_output_delay, and we are not reading output for a
4675 specific wait_channel. It is not executed if
4676 Vprocess_adaptive_read_buffering is nil. */
4677 if (process_output_skip
&& check_delay
> 0)
4679 int nsecs
= EMACS_NSECS (timeout
);
4680 if (EMACS_SECS (timeout
) > 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4681 nsecs
= READ_OUTPUT_DELAY_MAX
;
4682 for (channel
= 0; check_delay
> 0 && channel
<= max_desc
; channel
++)
4684 proc
= chan_process
[channel
];
4687 /* Find minimum non-zero read_output_delay among the
4688 processes with non-zero read_output_skip. */
4689 if (XPROCESS (proc
)->read_output_delay
> 0)
4692 if (!XPROCESS (proc
)->read_output_skip
)
4694 FD_CLR (channel
, &Available
);
4695 XPROCESS (proc
)->read_output_skip
= 0;
4696 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4697 nsecs
= XPROCESS (proc
)->read_output_delay
;
4700 timeout
= make_emacs_time (0, nsecs
);
4701 process_output_skip
= 0;
4704 nfds
= thread_select (
4705 #if defined (HAVE_NS)
4707 #elif defined (HAVE_GLIB)
4714 (check_write
? &Writeok
: 0),
4715 NULL
, &timeout
, NULL
);
4718 /* GnuTLS buffers data internally. In lowat mode it leaves
4719 some data in the TCP buffers so that select works, but
4720 with custom pull/push functions we need to check if some
4721 data is available in the buffers manually. */
4726 /* We're not waiting on a specific process, so loop
4727 through all the channels and check for data.
4728 This is a workaround needed for some versions of
4729 the gnutls library -- 2.12.14 has been confirmed
4731 http://comments.gmane.org/gmane.emacs.devel/145074 */
4732 for (channel
= 0; channel
< MAXDESC
; ++channel
)
4733 if (! NILP (chan_process
[channel
]))
4735 struct Lisp_Process
*p
=
4736 XPROCESS (chan_process
[channel
]);
4737 if (p
&& p
->gnutls_p
&& p
->infd
4738 && ((emacs_gnutls_record_check_pending
4743 FD_SET (p
->infd
, &Available
);
4749 /* Check this specific channel. */
4750 if (wait_proc
->gnutls_p
/* Check for valid process. */
4751 /* Do we have pending data? */
4752 && ((emacs_gnutls_record_check_pending
4753 (wait_proc
->gnutls_state
))
4757 /* Set to Available. */
4758 FD_SET (wait_proc
->infd
, &Available
);
4767 /* Make C-g and alarm signals set flags again */
4768 clear_waiting_for_input ();
4770 /* If we woke up due to SIGWINCH, actually change size now. */
4771 do_pending_window_change (0);
4773 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4774 /* We waited the full specified time, so return now. */
4778 if (xerrno
== EINTR
)
4780 else if (xerrno
== EBADF
)
4783 report_file_errno ("Failed select", Qnil
, xerrno
);
4788 FD_ZERO (&Available
);
4792 /* Check for keyboard input */
4793 /* If there is any, return immediately
4794 to give it higher priority than subprocesses */
4798 unsigned old_timers_run
= timers_run
;
4799 struct buffer
*old_buffer
= current_buffer
;
4800 Lisp_Object old_window
= selected_window
;
4803 if (detect_input_pending_run_timers (do_display
))
4805 swallow_events (do_display
);
4806 if (detect_input_pending_run_timers (do_display
))
4810 /* If a timer has run, this might have changed buffers
4811 an alike. Make read_key_sequence aware of that. */
4812 if (timers_run
!= old_timers_run
4813 && waiting_for_user_input_p
== -1
4814 && (old_buffer
!= current_buffer
4815 || !EQ (old_window
, selected_window
)))
4816 record_asynch_buffer_change ();
4822 /* If there is unread keyboard input, also return. */
4824 && requeued_events_pending_p ())
4827 /* If we are not checking for keyboard input now,
4828 do process events (but don't run any timers).
4829 This is so that X events will be processed.
4830 Otherwise they may have to wait until polling takes place.
4831 That would causes delays in pasting selections, for example.
4833 (We used to do this only if wait_for_cell.) */
4834 if (read_kbd
== 0 && detect_input_pending ())
4836 swallow_events (do_display
);
4837 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4838 if (detect_input_pending ())
4843 /* Exit now if the cell we're waiting for became non-nil. */
4844 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4848 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4849 go read it. This can happen with X on BSD after logging out.
4850 In that case, there really is no input and no SIGIO,
4851 but select says there is input. */
4853 if (read_kbd
&& interrupt_input
4854 && keyboard_bit_set (&Available
) && ! noninteractive
)
4855 handle_input_available_signal (SIGIO
);
4859 got_some_input
|= nfds
> 0;
4861 /* If checking input just got us a size-change event from X,
4862 obey it now if we should. */
4863 if (read_kbd
|| ! NILP (wait_for_cell
))
4864 do_pending_window_change (0);
4866 /* Check for data from a process. */
4867 if (no_avail
|| nfds
== 0)
4870 for (channel
= 0; channel
<= max_desc
; ++channel
)
4872 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4874 && ((d
->flags
& FOR_READ
4875 && FD_ISSET (channel
, &Available
))
4876 || (d
->flags
& FOR_WRITE
4877 && FD_ISSET (channel
, &Writeok
))))
4878 d
->func (channel
, d
->data
);
4881 for (channel
= 0; channel
<= max_desc
; channel
++)
4883 if (FD_ISSET (channel
, &Available
)
4884 && ((fd_callback_info
[channel
].flags
& (KEYBOARD_FD
| PROCESS_FD
))
4889 /* If waiting for this channel, arrange to return as
4890 soon as no more input to be processed. No more
4892 if (wait_channel
== channel
)
4898 proc
= chan_process
[channel
];
4902 /* If this is a server stream socket, accept connection. */
4903 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4905 server_accept_connection (proc
, channel
);
4909 /* Read data from the process, starting with our
4910 buffered-ahead character if we have one. */
4912 nread
= read_process_output (proc
, channel
);
4915 /* Since read_process_output can run a filter,
4916 which can call accept-process-output,
4917 don't try to read from any other processes
4918 before doing the select again. */
4919 FD_ZERO (&Available
);
4922 redisplay_preserve_echo_area (12);
4925 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4928 else if (nread
== -1 && errno
== EAGAIN
)
4931 /* FIXME: Is this special case still needed? */
4932 /* Note that we cannot distinguish between no input
4933 available now and a closed pipe.
4934 With luck, a closed pipe will be accompanied by
4935 subprocess termination and SIGCHLD. */
4936 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4940 /* On some OSs with ptys, when the process on one end of
4941 a pty exits, the other end gets an error reading with
4942 errno = EIO instead of getting an EOF (0 bytes read).
4943 Therefore, if we get an error reading and errno =
4944 EIO, just continue, because the child process has
4945 exited and should clean itself up soon (e.g. when we
4947 else if (nread
== -1 && errno
== EIO
)
4949 struct Lisp_Process
*p
= XPROCESS (proc
);
4951 /* Clear the descriptor now, so we only raise the
4953 delete_read_fd (channel
);
4957 /* If the EIO occurs on a pty, the SIGCHLD handler's
4958 waitpid call will not find the process object to
4959 delete. Do it here. */
4960 p
->tick
= ++process_tick
;
4961 pset_status (p
, Qfailed
);
4964 #endif /* HAVE_PTYS */
4965 /* If we can detect process termination, don't consider the
4966 process gone just because its pipe is closed. */
4967 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4971 /* Preserve status of processes already terminated. */
4972 XPROCESS (proc
)->tick
= ++process_tick
;
4973 deactivate_process (proc
);
4974 if (XPROCESS (proc
)->raw_status_new
)
4975 update_status (XPROCESS (proc
));
4976 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4977 pset_status (XPROCESS (proc
),
4978 list2 (Qexit
, make_number (256)));
4981 #ifdef NON_BLOCKING_CONNECT
4982 if (FD_ISSET (channel
, &Writeok
)
4983 && (fd_callback_info
[channel
].flags
4984 & NON_BLOCKING_CONNECT_FD
) != 0)
4986 struct Lisp_Process
*p
;
4988 delete_write_fd (channel
);
4990 proc
= chan_process
[channel
];
4994 p
= XPROCESS (proc
);
4997 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4998 So only use it on systems where it is known to work. */
5000 socklen_t xlen
= sizeof (xerrno
);
5001 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5006 struct sockaddr pname
;
5007 int pnamelen
= sizeof (pname
);
5009 /* If connection failed, getpeername will fail. */
5011 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5013 /* Obtain connect failure code through error slippage. */
5016 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5023 p
->tick
= ++process_tick
;
5024 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5025 deactivate_process (proc
);
5029 pset_status (p
, Qrun
);
5030 /* Execute the sentinel here. If we had relied on
5031 status_notify to do it later, it will read input
5032 from the process before calling the sentinel. */
5033 exec_sentinel (proc
, build_string ("open\n"));
5034 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
5035 delete_read_fd (p
->infd
);
5038 #endif /* NON_BLOCKING_CONNECT */
5039 } /* End for each file descriptor. */
5040 } /* End while exit conditions not met. */
5042 unbind_to (count
, Qnil
);
5044 /* If calling from keyboard input, do not quit
5045 since we want to return C-g as an input character.
5046 Otherwise, do pending quit if requested. */
5049 /* Prevent input_pending from remaining set if we quit. */
5050 clear_input_pending ();
5054 return got_some_input
;
5057 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5060 read_process_output_call (Lisp_Object fun_and_args
)
5062 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5066 read_process_output_error_handler (Lisp_Object error_val
)
5068 cmd_error_internal (error_val
, "error in process filter: ");
5070 update_echo_area ();
5071 Fsleep_for (make_number (2), Qnil
);
5076 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5078 struct coding_system
*coding
);
5080 /* Read pending output from the process channel,
5081 starting with our buffered-ahead character if we have one.
5082 Yield number of decoded characters read.
5084 This function reads at most 4096 characters.
5085 If you want to read all available subprocess output,
5086 you must call it repeatedly until it returns zero.
5088 The characters read are decoded according to PROC's coding-system
5092 read_process_output (Lisp_Object proc
, register int channel
)
5094 register ssize_t nbytes
;
5096 register struct Lisp_Process
*p
= XPROCESS (proc
);
5097 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5098 int carryover
= p
->decoding_carryover
;
5100 ptrdiff_t count
= SPECPDL_INDEX ();
5101 Lisp_Object odeactivate
;
5103 chars
= alloca (carryover
+ readmax
);
5105 /* See the comment above. */
5106 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5108 #ifdef DATAGRAM_SOCKETS
5109 /* We have a working select, so proc_buffered_char is always -1. */
5110 if (DATAGRAM_CHAN_P (channel
))
5112 socklen_t len
= datagram_address
[channel
].len
;
5113 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5114 0, datagram_address
[channel
].sa
, &len
);
5119 bool buffered
= proc_buffered_char
[channel
] >= 0;
5122 chars
[carryover
] = proc_buffered_char
[channel
];
5123 proc_buffered_char
[channel
] = -1;
5127 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5128 readmax
- buffered
);
5131 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5132 readmax
- buffered
);
5133 #ifdef ADAPTIVE_READ_BUFFERING
5134 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5136 int delay
= p
->read_output_delay
;
5139 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5142 process_output_delay_count
++;
5143 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5146 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5148 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5150 process_output_delay_count
--;
5152 p
->read_output_delay
= delay
;
5155 p
->read_output_skip
= 1;
5156 process_output_skip
= 1;
5161 nbytes
+= buffered
&& nbytes
<= 0;
5164 p
->decoding_carryover
= 0;
5166 /* At this point, NBYTES holds number of bytes just received
5167 (including the one in proc_buffered_char[channel]). */
5170 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5172 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5175 /* Now set NBYTES how many bytes we must decode. */
5176 nbytes
+= carryover
;
5178 odeactivate
= Vdeactivate_mark
;
5179 /* There's no good reason to let process filters change the current
5180 buffer, and many callers of accept-process-output, sit-for, and
5181 friends don't expect current-buffer to be changed from under them. */
5182 record_unwind_current_buffer ();
5184 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5186 /* Handling the process output should not deactivate the mark. */
5187 Vdeactivate_mark
= odeactivate
;
5189 unbind_to (count
, Qnil
);
5194 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5196 struct coding_system
*coding
)
5198 Lisp_Object outstream
= p
->filter
;
5200 bool outer_running_asynch_code
= running_asynch_code
;
5201 int waiting
= waiting_for_user_input_p
;
5203 /* No need to gcpro these, because all we do with them later
5204 is test them for EQness, and none of them should be a string. */
5206 Lisp_Object obuffer
, okeymap
;
5207 XSETBUFFER (obuffer
, current_buffer
);
5208 okeymap
= BVAR (current_buffer
, keymap
);
5211 /* We inhibit quit here instead of just catching it so that
5212 hitting ^G when a filter happens to be running won't screw
5214 specbind (Qinhibit_quit
, Qt
);
5215 specbind (Qlast_nonmenu_event
, Qt
);
5217 /* In case we get recursively called,
5218 and we already saved the match data nonrecursively,
5219 save the same match data in safely recursive fashion. */
5220 if (outer_running_asynch_code
)
5223 /* Don't clobber the CURRENT match data, either! */
5224 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5225 restore_search_regs ();
5226 record_unwind_save_match_data ();
5227 Fset_match_data (tem
, Qt
);
5230 /* For speed, if a search happens within this code,
5231 save the match data in a special nonrecursive fashion. */
5232 running_asynch_code
= 1;
5234 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5235 text
= coding
->dst_object
;
5236 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5237 /* A new coding system might be found. */
5238 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5240 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5242 /* Don't call setup_coding_system for
5243 proc_decode_coding_system[channel] here. It is done in
5244 detect_coding called via decode_coding above. */
5246 /* If a coding system for encoding is not yet decided, we set
5247 it as the same as coding-system for decoding.
5249 But, before doing that we must check if
5250 proc_encode_coding_system[p->outfd] surely points to a
5251 valid memory because p->outfd will be changed once EOF is
5252 sent to the process. */
5253 if (NILP (p
->encode_coding_system
)
5254 && proc_encode_coding_system
[p
->outfd
])
5256 pset_encode_coding_system
5257 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5258 setup_coding_system (p
->encode_coding_system
,
5259 proc_encode_coding_system
[p
->outfd
]);
5263 if (coding
->carryover_bytes
> 0)
5265 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5266 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5267 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5268 coding
->carryover_bytes
);
5269 p
->decoding_carryover
= coding
->carryover_bytes
;
5271 if (SBYTES (text
) > 0)
5272 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5273 sometimes it's simply wrong to wrap (e.g. when called from
5274 accept-process-output). */
5275 internal_condition_case_1 (read_process_output_call
,
5276 list3 (outstream
, make_lisp_proc (p
), text
),
5277 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5278 read_process_output_error_handler
);
5280 /* If we saved the match data nonrecursively, restore it now. */
5281 restore_search_regs ();
5282 running_asynch_code
= outer_running_asynch_code
;
5284 /* Restore waiting_for_user_input_p as it was
5285 when we were called, in case the filter clobbered it. */
5286 waiting_for_user_input_p
= waiting
;
5288 #if 0 /* Call record_asynch_buffer_change unconditionally,
5289 because we might have changed minor modes or other things
5290 that affect key bindings. */
5291 if (! EQ (Fcurrent_buffer (), obuffer
)
5292 || ! EQ (current_buffer
->keymap
, okeymap
))
5294 /* But do it only if the caller is actually going to read events.
5295 Otherwise there's no need to make him wake up, and it could
5296 cause trouble (for example it would make sit_for return). */
5297 if (waiting_for_user_input_p
== -1)
5298 record_asynch_buffer_change ();
5301 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5302 Sinternal_default_process_filter
, 2, 2, 0,
5303 doc
: /* Function used as default process filter. */)
5304 (Lisp_Object proc
, Lisp_Object text
)
5306 struct Lisp_Process
*p
;
5309 CHECK_PROCESS (proc
);
5310 p
= XPROCESS (proc
);
5311 CHECK_STRING (text
);
5313 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5315 Lisp_Object old_read_only
;
5316 ptrdiff_t old_begv
, old_zv
;
5317 ptrdiff_t old_begv_byte
, old_zv_byte
;
5318 ptrdiff_t before
, before_byte
;
5319 ptrdiff_t opoint_byte
;
5322 Fset_buffer (p
->buffer
);
5324 opoint_byte
= PT_BYTE
;
5325 old_read_only
= BVAR (current_buffer
, read_only
);
5328 old_begv_byte
= BEGV_BYTE
;
5329 old_zv_byte
= ZV_BYTE
;
5331 bset_read_only (current_buffer
, Qnil
);
5333 /* Insert new output into buffer
5334 at the current end-of-output marker,
5335 thus preserving logical ordering of input and output. */
5336 if (XMARKER (p
->mark
)->buffer
)
5337 SET_PT_BOTH (clip_to_bounds (BEGV
,
5338 marker_position (p
->mark
), ZV
),
5339 clip_to_bounds (BEGV_BYTE
,
5340 marker_byte_position (p
->mark
),
5343 SET_PT_BOTH (ZV
, ZV_BYTE
);
5345 before_byte
= PT_BYTE
;
5347 /* If the output marker is outside of the visible region, save
5348 the restriction and widen. */
5349 if (! (BEGV
<= PT
&& PT
<= ZV
))
5352 /* Adjust the multibyteness of TEXT to that of the buffer. */
5353 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5354 != ! STRING_MULTIBYTE (text
))
5355 text
= (STRING_MULTIBYTE (text
)
5356 ? Fstring_as_unibyte (text
)
5357 : Fstring_to_multibyte (text
));
5358 /* Insert before markers in case we are inserting where
5359 the buffer's mark is, and the user's next command is Meta-y. */
5360 insert_from_string_before_markers (text
, 0, 0,
5361 SCHARS (text
), SBYTES (text
), 0);
5363 /* Make sure the process marker's position is valid when the
5364 process buffer is changed in the signal_after_change above.
5365 W3 is known to do that. */
5366 if (BUFFERP (p
->buffer
)
5367 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5368 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5370 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5372 update_mode_lines
++;
5374 /* Make sure opoint and the old restrictions
5375 float ahead of any new text just as point would. */
5376 if (opoint
>= before
)
5378 opoint
+= PT
- before
;
5379 opoint_byte
+= PT_BYTE
- before_byte
;
5381 if (old_begv
> before
)
5383 old_begv
+= PT
- before
;
5384 old_begv_byte
+= PT_BYTE
- before_byte
;
5386 if (old_zv
>= before
)
5388 old_zv
+= PT
- before
;
5389 old_zv_byte
+= PT_BYTE
- before_byte
;
5392 /* If the restriction isn't what it should be, set it. */
5393 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5394 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5396 bset_read_only (current_buffer
, old_read_only
);
5397 SET_PT_BOTH (opoint
, opoint_byte
);
5402 /* Sending data to subprocess. */
5404 /* In send_process, when a write fails temporarily,
5405 wait_reading_process_output is called. It may execute user code,
5406 e.g. timers, that attempts to write new data to the same process.
5407 We must ensure that data is sent in the right order, and not
5408 interspersed half-completed with other writes (Bug#10815). This is
5409 handled by the write_queue element of struct process. It is a list
5410 with each entry having the form
5412 (string . (offset . length))
5414 where STRING is a lisp string, OFFSET is the offset into the
5415 string's byte sequence from which we should begin to send, and
5416 LENGTH is the number of bytes left to send. */
5418 /* Create a new entry in write_queue.
5419 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5420 BUF is a pointer to the string sequence of the input_obj or a C
5421 string in case of Qt or Qnil. */
5424 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5425 const char *buf
, ptrdiff_t len
, bool front
)
5428 Lisp_Object entry
, obj
;
5430 if (STRINGP (input_obj
))
5432 offset
= buf
- SSDATA (input_obj
);
5438 obj
= make_unibyte_string (buf
, len
);
5441 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5444 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5446 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5449 /* Remove the first element in the write_queue of process P, put its
5450 contents in OBJ, BUF and LEN, and return true. If the
5451 write_queue is empty, return false. */
5454 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5455 const char **buf
, ptrdiff_t *len
)
5457 Lisp_Object entry
, offset_length
;
5460 if (NILP (p
->write_queue
))
5463 entry
= XCAR (p
->write_queue
);
5464 pset_write_queue (p
, XCDR (p
->write_queue
));
5466 *obj
= XCAR (entry
);
5467 offset_length
= XCDR (entry
);
5469 *len
= XINT (XCDR (offset_length
));
5470 offset
= XINT (XCAR (offset_length
));
5471 *buf
= SSDATA (*obj
) + offset
;
5476 /* Send some data to process PROC.
5477 BUF is the beginning of the data; LEN is the number of characters.
5478 OBJECT is the Lisp object that the data comes from. If OBJECT is
5479 nil or t, it means that the data comes from C string.
5481 If OBJECT is not nil, the data is encoded by PROC's coding-system
5482 for encoding before it is sent.
5484 This function can evaluate Lisp code and can garbage collect. */
5487 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5490 struct Lisp_Process
*p
= XPROCESS (proc
);
5492 struct coding_system
*coding
;
5494 if (p
->raw_status_new
)
5496 if (! EQ (p
->status
, Qrun
))
5497 error ("Process %s not running", SDATA (p
->name
));
5499 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5501 coding
= proc_encode_coding_system
[p
->outfd
];
5502 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5504 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5505 || (BUFFERP (object
)
5506 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5509 pset_encode_coding_system
5510 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5511 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5513 /* The coding system for encoding was changed to raw-text
5514 because we sent a unibyte text previously. Now we are
5515 sending a multibyte text, thus we must encode it by the
5516 original coding system specified for the current process.
5518 Another reason we come here is that the coding system
5519 was just complemented and a new one was returned by
5520 complement_process_encoding_system. */
5521 setup_coding_system (p
->encode_coding_system
, coding
);
5522 Vlast_coding_system_used
= p
->encode_coding_system
;
5524 coding
->src_multibyte
= 1;
5528 coding
->src_multibyte
= 0;
5529 /* For sending a unibyte text, character code conversion should
5530 not take place but EOL conversion should. So, setup raw-text
5531 or one of the subsidiary if we have not yet done it. */
5532 if (CODING_REQUIRE_ENCODING (coding
))
5534 if (CODING_REQUIRE_FLUSHING (coding
))
5536 /* But, before changing the coding, we must flush out data. */
5537 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5538 send_process (proc
, "", 0, Qt
);
5539 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5541 setup_coding_system (raw_text_coding_system
5542 (Vlast_coding_system_used
),
5544 coding
->src_multibyte
= 0;
5547 coding
->dst_multibyte
= 0;
5549 if (CODING_REQUIRE_ENCODING (coding
))
5551 coding
->dst_object
= Qt
;
5552 if (BUFFERP (object
))
5554 ptrdiff_t from_byte
, from
, to
;
5555 ptrdiff_t save_pt
, save_pt_byte
;
5556 struct buffer
*cur
= current_buffer
;
5558 set_buffer_internal (XBUFFER (object
));
5559 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5561 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5562 from
= BYTE_TO_CHAR (from_byte
);
5563 to
= BYTE_TO_CHAR (from_byte
+ len
);
5564 TEMP_SET_PT_BOTH (from
, from_byte
);
5565 encode_coding_object (coding
, object
, from
, from_byte
,
5566 to
, from_byte
+ len
, Qt
);
5567 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5568 set_buffer_internal (cur
);
5570 else if (STRINGP (object
))
5572 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5573 SBYTES (object
), Qt
);
5577 coding
->dst_object
= make_unibyte_string (buf
, len
);
5578 coding
->produced
= len
;
5581 len
= coding
->produced
;
5582 object
= coding
->dst_object
;
5583 buf
= SSDATA (object
);
5586 /* If there is already data in the write_queue, put the new data
5587 in the back of queue. Otherwise, ignore it. */
5588 if (!NILP (p
->write_queue
))
5589 write_queue_push (p
, object
, buf
, len
, 0);
5591 do /* while !NILP (p->write_queue) */
5593 ptrdiff_t cur_len
= -1;
5594 const char *cur_buf
;
5595 Lisp_Object cur_object
;
5597 /* If write_queue is empty, ignore it. */
5598 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5602 cur_object
= object
;
5607 /* Send this batch, using one or more write calls. */
5608 ptrdiff_t written
= 0;
5609 int outfd
= p
->outfd
;
5610 #ifdef DATAGRAM_SOCKETS
5611 if (DATAGRAM_CHAN_P (outfd
))
5613 rv
= sendto (outfd
, cur_buf
, cur_len
,
5614 0, datagram_address
[outfd
].sa
,
5615 datagram_address
[outfd
].len
);
5618 else if (errno
== EMSGSIZE
)
5619 report_file_error ("Sending datagram", proc
);
5626 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5629 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5630 rv
= (written
? 0 : -1);
5631 #ifdef ADAPTIVE_READ_BUFFERING
5632 if (p
->read_output_delay
> 0
5633 && p
->adaptive_read_buffering
== 1)
5635 p
->read_output_delay
= 0;
5636 process_output_delay_count
--;
5637 p
->read_output_skip
= 0;
5646 || errno
== EWOULDBLOCK
5649 /* Buffer is full. Wait, accepting input;
5650 that may allow the program
5651 to finish doing output and read more. */
5653 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5654 /* A gross hack to work around a bug in FreeBSD.
5655 In the following sequence, read(2) returns
5659 write(2) 954 bytes, get EAGAIN
5660 read(2) 1024 bytes in process_read_output
5661 read(2) 11 bytes in process_read_output
5663 That is, read(2) returns more bytes than have
5664 ever been written successfully. The 1033 bytes
5665 read are the 1022 bytes written successfully
5666 after processing (for example with CRs added if
5667 the terminal is set up that way which it is
5668 here). The same bytes will be seen again in a
5669 later read(2), without the CRs. */
5671 if (errno
== EAGAIN
)
5674 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5676 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5678 /* Put what we should have written in wait_queue. */
5679 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5680 wait_reading_process_output (0, 20 * 1000 * 1000,
5681 0, 0, Qnil
, NULL
, 0);
5682 /* Reread queue, to see what is left. */
5685 else if (errno
== EPIPE
)
5687 p
->raw_status_new
= 0;
5688 pset_status (p
, list2 (Qexit
, make_number (256)));
5689 p
->tick
= ++process_tick
;
5690 deactivate_process (proc
);
5691 error ("process %s no longer connected to pipe; closed it",
5695 /* This is a real error. */
5696 report_file_error ("Writing to process", proc
);
5702 while (!NILP (p
->write_queue
));
5705 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5707 doc
: /* Send current contents of region as input to PROCESS.
5708 PROCESS may be a process, a buffer, the name of a process or buffer, or
5709 nil, indicating the current buffer's process.
5710 Called from program, takes three arguments, PROCESS, START and END.
5711 If the region is more than 500 characters long,
5712 it is sent in several bunches. This may happen even for shorter regions.
5713 Output from processes can arrive in between bunches. */)
5714 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5716 Lisp_Object proc
= get_process (process
);
5717 ptrdiff_t start_byte
, end_byte
;
5719 validate_region (&start
, &end
);
5721 start_byte
= CHAR_TO_BYTE (XINT (start
));
5722 end_byte
= CHAR_TO_BYTE (XINT (end
));
5724 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5725 move_gap_both (XINT (start
), start_byte
);
5727 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5728 end_byte
- start_byte
, Fcurrent_buffer ());
5733 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5735 doc
: /* Send PROCESS the contents of STRING as input.
5736 PROCESS may be a process, a buffer, the name of a process or buffer, or
5737 nil, indicating the current buffer's process.
5738 If STRING is more than 500 characters long,
5739 it is sent in several bunches. This may happen even for shorter strings.
5740 Output from processes can arrive in between bunches. */)
5741 (Lisp_Object process
, Lisp_Object string
)
5744 CHECK_STRING (string
);
5745 proc
= get_process (process
);
5746 send_process (proc
, SSDATA (string
),
5747 SBYTES (string
), string
);
5751 /* Return the foreground process group for the tty/pty that
5752 the process P uses. */
5754 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5759 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5762 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5763 master side. Try the slave side. */
5764 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5768 ioctl (fd
, TIOCGPGRP
, &gid
);
5772 #endif /* defined (TIOCGPGRP ) */
5777 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5778 Sprocess_running_child_p
, 0, 1, 0,
5779 doc
: /* Return t if PROCESS has given the terminal to a child.
5780 If the operating system does not make it possible to find out,
5781 return t unconditionally. */)
5782 (Lisp_Object process
)
5784 /* Initialize in case ioctl doesn't exist or gives an error,
5785 in a way that will cause returning t. */
5788 struct Lisp_Process
*p
;
5790 proc
= get_process (process
);
5791 p
= XPROCESS (proc
);
5793 if (!EQ (p
->type
, Qreal
))
5794 error ("Process %s is not a subprocess",
5797 error ("Process %s is not active",
5800 gid
= emacs_get_tty_pgrp (p
);
5807 /* send a signal number SIGNO to PROCESS.
5808 If CURRENT_GROUP is t, that means send to the process group
5809 that currently owns the terminal being used to communicate with PROCESS.
5810 This is used for various commands in shell mode.
5811 If CURRENT_GROUP is lambda, that means send to the process group
5812 that currently owns the terminal, but only if it is NOT the shell itself.
5814 If NOMSG is false, insert signal-announcements into process's buffers
5817 If we can, we try to signal PROCESS by sending control characters
5818 down the pty. This allows us to signal inferiors who have changed
5819 their uid, for which kill would return an EPERM error. */
5822 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5826 struct Lisp_Process
*p
;
5830 proc
= get_process (process
);
5831 p
= XPROCESS (proc
);
5833 if (!EQ (p
->type
, Qreal
))
5834 error ("Process %s is not a subprocess",
5837 error ("Process %s is not active",
5841 current_group
= Qnil
;
5843 /* If we are using pgrps, get a pgrp number and make it negative. */
5844 if (NILP (current_group
))
5845 /* Send the signal to the shell's process group. */
5849 #ifdef SIGNALS_VIA_CHARACTERS
5850 /* If possible, send signals to the entire pgrp
5851 by sending an input character to it. */
5854 cc_t
*sig_char
= NULL
;
5856 tcgetattr (p
->infd
, &t
);
5861 sig_char
= &t
.c_cc
[VINTR
];
5865 sig_char
= &t
.c_cc
[VQUIT
];
5869 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5870 sig_char
= &t
.c_cc
[VSWTCH
];
5872 sig_char
= &t
.c_cc
[VSUSP
];
5877 if (sig_char
&& *sig_char
!= CDISABLE
)
5879 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5882 /* If we can't send the signal with a character,
5883 fall through and send it another way. */
5885 /* The code above may fall through if it can't
5886 handle the signal. */
5887 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5890 /* Get the current pgrp using the tty itself, if we have that.
5891 Otherwise, use the pty to get the pgrp.
5892 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5893 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5894 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5895 His patch indicates that if TIOCGPGRP returns an error, then
5896 we should just assume that p->pid is also the process group id. */
5898 gid
= emacs_get_tty_pgrp (p
);
5901 /* If we can't get the information, assume
5902 the shell owns the tty. */
5905 /* It is not clear whether anything really can set GID to -1.
5906 Perhaps on some system one of those ioctls can or could do so.
5907 Or perhaps this is vestigial. */
5910 #else /* ! defined (TIOCGPGRP ) */
5911 /* Can't select pgrps on this system, so we know that
5912 the child itself heads the pgrp. */
5914 #endif /* ! defined (TIOCGPGRP ) */
5916 /* If current_group is lambda, and the shell owns the terminal,
5917 don't send any signal. */
5918 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5923 if (signo
== SIGCONT
)
5925 p
->raw_status_new
= 0;
5926 pset_status (p
, Qrun
);
5927 p
->tick
= ++process_tick
;
5930 status_notify (NULL
);
5931 redisplay_preserve_echo_area (13);
5936 /* If we don't have process groups, send the signal to the immediate
5937 subprocess. That isn't really right, but it's better than any
5938 obvious alternative. */
5941 kill (p
->pid
, signo
);
5945 /* gid may be a pid, or minus a pgrp's number */
5947 if (!NILP (current_group
))
5949 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
5957 #else /* ! defined (TIOCSIGSEND) */
5959 #endif /* ! defined (TIOCSIGSEND) */
5962 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5963 doc
: /* Interrupt process PROCESS.
5964 PROCESS may be a process, a buffer, or the name of a process or buffer.
5965 No arg or nil means current buffer's process.
5966 Second arg CURRENT-GROUP non-nil means send signal to
5967 the current process-group of the process's controlling terminal
5968 rather than to the process's own process group.
5969 If the process is a shell, this means interrupt current subjob
5970 rather than the shell.
5972 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5973 don't send the signal. */)
5974 (Lisp_Object process
, Lisp_Object current_group
)
5976 process_send_signal (process
, SIGINT
, current_group
, 0);
5980 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5981 doc
: /* Kill process PROCESS. May be process or name of one.
5982 See function `interrupt-process' for more details on usage. */)
5983 (Lisp_Object process
, Lisp_Object current_group
)
5985 process_send_signal (process
, SIGKILL
, current_group
, 0);
5989 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5990 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5991 See function `interrupt-process' for more details on usage. */)
5992 (Lisp_Object process
, Lisp_Object current_group
)
5994 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5998 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5999 doc
: /* Stop process PROCESS. May be process or name of one.
6000 See function `interrupt-process' for more details on usage.
6001 If PROCESS is a network or serial process, inhibit handling of incoming
6003 (Lisp_Object process
, Lisp_Object current_group
)
6005 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6007 struct Lisp_Process
*p
;
6009 p
= XPROCESS (process
);
6010 if (NILP (p
->command
)
6012 delete_read_fd (p
->infd
);
6013 pset_command (p
, Qt
);
6017 error ("No SIGTSTP support");
6019 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6024 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6025 doc
: /* Continue process PROCESS. May be process or name of one.
6026 See function `interrupt-process' for more details on usage.
6027 If PROCESS is a network or serial process, resume handling of incoming
6029 (Lisp_Object process
, Lisp_Object current_group
)
6031 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6033 struct Lisp_Process
*p
;
6035 p
= XPROCESS (process
);
6036 if (EQ (p
->command
, Qt
)
6038 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6040 add_non_keyboard_read_fd (p
->infd
);
6042 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6043 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6044 #else /* not WINDOWSNT */
6045 tcflush (p
->infd
, TCIFLUSH
);
6046 #endif /* not WINDOWSNT */
6048 pset_command (p
, Qnil
);
6052 process_send_signal (process
, SIGCONT
, current_group
, 0);
6054 error ("No SIGCONT support");
6059 /* Return the integer value of the signal whose abbreviation is ABBR,
6060 or a negative number if there is no such signal. */
6062 abbr_to_signal (char const *name
)
6065 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6067 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6070 for (i
= 0; i
< sizeof sigbuf
; i
++)
6072 sigbuf
[i
] = c_toupper (name
[i
]);
6074 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6080 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6081 2, 2, "sProcess (name or number): \nnSignal code: ",
6082 doc
: /* Send PROCESS the signal with code SIGCODE.
6083 PROCESS may also be a number specifying the process id of the
6084 process to signal; in this case, the process need not be a child of
6086 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6087 (Lisp_Object process
, Lisp_Object sigcode
)
6092 if (STRINGP (process
))
6094 Lisp_Object tem
= Fget_process (process
);
6097 Lisp_Object process_number
=
6098 string_to_number (SSDATA (process
), 10, 1);
6099 if (INTEGERP (process_number
) || FLOATP (process_number
))
6100 tem
= process_number
;
6104 else if (!NUMBERP (process
))
6105 process
= get_process (process
);
6110 if (NUMBERP (process
))
6111 CONS_TO_INTEGER (process
, pid_t
, pid
);
6114 CHECK_PROCESS (process
);
6115 pid
= XPROCESS (process
)->pid
;
6117 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6120 if (INTEGERP (sigcode
))
6122 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6123 signo
= XINT (sigcode
);
6129 CHECK_SYMBOL (sigcode
);
6130 name
= SSDATA (SYMBOL_NAME (sigcode
));
6132 signo
= abbr_to_signal (name
);
6134 error ("Undefined signal name %s", name
);
6137 return make_number (kill (pid
, signo
));
6140 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6141 doc
: /* Make PROCESS see end-of-file in its input.
6142 EOF comes after any text already sent to it.
6143 PROCESS may be a process, a buffer, the name of a process or buffer, or
6144 nil, indicating the current buffer's process.
6145 If PROCESS is a network connection, or is a process communicating
6146 through a pipe (as opposed to a pty), then you cannot send any more
6147 text to PROCESS after you call this function.
6148 If PROCESS is a serial process, wait until all output written to the
6149 process has been transmitted to the serial port. */)
6150 (Lisp_Object process
)
6153 struct coding_system
*coding
;
6155 if (DATAGRAM_CONN_P (process
))
6158 proc
= get_process (process
);
6159 coding
= proc_encode_coding_system
[XPROCESS (proc
)->outfd
];
6161 /* Make sure the process is really alive. */
6162 if (XPROCESS (proc
)->raw_status_new
)
6163 update_status (XPROCESS (proc
));
6164 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6165 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6167 if (CODING_REQUIRE_FLUSHING (coding
))
6169 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6170 send_process (proc
, "", 0, Qnil
);
6173 if (XPROCESS (proc
)->pty_flag
)
6174 send_process (proc
, "\004", 1, Qnil
);
6175 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6178 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6179 report_file_error ("Failed tcdrain", Qnil
);
6180 #endif /* not WINDOWSNT */
6181 /* Do nothing on Windows because writes are blocking. */
6185 int old_outfd
= XPROCESS (proc
)->outfd
;
6188 #ifdef HAVE_SHUTDOWN
6189 /* If this is a network connection, or socketpair is used
6190 for communication with the subprocess, call shutdown to cause EOF.
6191 (In some old system, shutdown to socketpair doesn't work.
6192 Then we just can't win.) */
6193 if (EQ (XPROCESS (proc
)->type
, Qnetwork
)
6194 || XPROCESS (proc
)->infd
== old_outfd
)
6195 shutdown (old_outfd
, 1);
6197 close_process_fd (&XPROCESS (proc
)->open_fd
[WRITE_TO_SUBPROCESS
]);
6198 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6200 report_file_error ("Opening null device", Qnil
);
6201 XPROCESS (proc
)->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6202 XPROCESS (proc
)->outfd
= new_outfd
;
6204 if (!proc_encode_coding_system
[new_outfd
])
6205 proc_encode_coding_system
[new_outfd
]
6206 = xmalloc (sizeof (struct coding_system
));
6207 *proc_encode_coding_system
[new_outfd
]
6208 = *proc_encode_coding_system
[old_outfd
];
6209 memset (proc_encode_coding_system
[old_outfd
], 0,
6210 sizeof (struct coding_system
));
6215 /* The main Emacs thread records child processes in three places:
6217 - Vprocess_alist, for asynchronous subprocesses, which are child
6218 processes visible to Lisp.
6220 - deleted_pid_list, for child processes invisible to Lisp,
6221 typically because of delete-process. These are recorded so that
6222 the processes can be reaped when they exit, so that the operating
6223 system's process table is not cluttered by zombies.
6225 - the local variable PID in Fcall_process, call_process_cleanup and
6226 call_process_kill, for synchronous subprocesses.
6227 record_unwind_protect is used to make sure this process is not
6228 forgotten: if the user interrupts call-process and the child
6229 process refuses to exit immediately even with two C-g's,
6230 call_process_kill adds PID's contents to deleted_pid_list before
6233 The main Emacs thread invokes waitpid only on child processes that
6234 it creates and that have not been reaped. This avoid races on
6235 platforms such as GTK, where other threads create their own
6236 subprocesses which the main thread should not reap. For example,
6237 if the main thread attempted to reap an already-reaped child, it
6238 might inadvertently reap a GTK-created process that happened to
6239 have the same process ID. */
6241 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6242 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6243 keep track of its own children. GNUstep is similar. */
6245 static void dummy_handler (int sig
) {}
6246 static signal_handler_t
volatile lib_child_handler
;
6248 /* Handle a SIGCHLD signal by looking for known child processes of
6249 Emacs whose status have changed. For each one found, record its
6252 All we do is change the status; we do not run sentinels or print
6253 notifications. That is saved for the next time keyboard input is
6254 done, in order to avoid timing errors.
6256 ** WARNING: this can be called during garbage collection.
6257 Therefore, it must not be fooled by the presence of mark bits in
6260 ** USG WARNING: Although it is not obvious from the documentation
6261 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6262 signal() before executing at least one wait(), otherwise the
6263 handler will be called again, resulting in an infinite loop. The
6264 relevant portion of the documentation reads "SIGCLD signals will be
6265 queued and the signal-catching function will be continually
6266 reentered until the queue is empty". Invoking signal() causes the
6267 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6270 ** Malloc WARNING: This should never call malloc either directly or
6271 indirectly; if it does, that is a bug */
6274 handle_child_signal (int sig
)
6276 Lisp_Object tail
, proc
;
6278 /* Find the process that signaled us, and record its status. */
6280 /* The process can have been deleted by Fdelete_process, or have
6281 been started asynchronously by Fcall_process. */
6282 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6284 bool all_pids_are_fixnums
6285 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6286 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6287 Lisp_Object head
= XCAR (tail
);
6292 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6295 if (INTEGERP (xpid
))
6296 deleted_pid
= XINT (xpid
);
6298 deleted_pid
= XFLOAT_DATA (xpid
);
6299 if (child_status_changed (deleted_pid
, 0, 0))
6301 if (STRINGP (XCDR (head
)))
6302 unlink (SSDATA (XCDR (head
)));
6303 XSETCAR (tail
, Qnil
);
6308 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6309 FOR_EACH_PROCESS (tail
, proc
)
6311 struct Lisp_Process
*p
= XPROCESS (proc
);
6315 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6317 /* Change the status of the process that was found. */
6318 p
->tick
= ++process_tick
;
6319 p
->raw_status
= status
;
6320 p
->raw_status_new
= 1;
6322 /* If process has terminated, stop waiting for its output. */
6323 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6325 bool clear_desc_flag
= 0;
6328 clear_desc_flag
= 1;
6330 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6331 if (clear_desc_flag
)
6332 delete_read_fd (p
->infd
);
6337 lib_child_handler (sig
);
6338 #ifdef NS_IMPL_GNUSTEP
6339 /* NSTask in GNUStep sets its child handler each time it is called.
6340 So we must re-set ours. */
6341 catch_child_signal();
6346 deliver_child_signal (int sig
)
6348 deliver_process_signal (sig
, handle_child_signal
);
6353 exec_sentinel_error_handler (Lisp_Object error_val
)
6355 cmd_error_internal (error_val
, "error in process sentinel: ");
6357 update_echo_area ();
6358 Fsleep_for (make_number (2), Qnil
);
6363 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6365 Lisp_Object sentinel
, odeactivate
;
6366 struct Lisp_Process
*p
= XPROCESS (proc
);
6367 ptrdiff_t count
= SPECPDL_INDEX ();
6368 bool outer_running_asynch_code
= running_asynch_code
;
6369 int waiting
= waiting_for_user_input_p
;
6371 if (inhibit_sentinels
)
6374 /* No need to gcpro these, because all we do with them later
6375 is test them for EQness, and none of them should be a string. */
6376 odeactivate
= Vdeactivate_mark
;
6378 Lisp_Object obuffer
, okeymap
;
6379 XSETBUFFER (obuffer
, current_buffer
);
6380 okeymap
= BVAR (current_buffer
, keymap
);
6383 /* There's no good reason to let sentinels change the current
6384 buffer, and many callers of accept-process-output, sit-for, and
6385 friends don't expect current-buffer to be changed from under them. */
6386 record_unwind_current_buffer ();
6388 sentinel
= p
->sentinel
;
6390 /* Inhibit quit so that random quits don't screw up a running filter. */
6391 specbind (Qinhibit_quit
, Qt
);
6392 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6394 /* In case we get recursively called,
6395 and we already saved the match data nonrecursively,
6396 save the same match data in safely recursive fashion. */
6397 if (outer_running_asynch_code
)
6400 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6401 restore_search_regs ();
6402 record_unwind_save_match_data ();
6403 Fset_match_data (tem
, Qt
);
6406 /* For speed, if a search happens within this code,
6407 save the match data in a special nonrecursive fashion. */
6408 running_asynch_code
= 1;
6410 internal_condition_case_1 (read_process_output_call
,
6411 list3 (sentinel
, proc
, reason
),
6412 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6413 exec_sentinel_error_handler
);
6415 /* If we saved the match data nonrecursively, restore it now. */
6416 restore_search_regs ();
6417 running_asynch_code
= outer_running_asynch_code
;
6419 Vdeactivate_mark
= odeactivate
;
6421 /* Restore waiting_for_user_input_p as it was
6422 when we were called, in case the filter clobbered it. */
6423 waiting_for_user_input_p
= waiting
;
6426 if (! EQ (Fcurrent_buffer (), obuffer
)
6427 || ! EQ (current_buffer
->keymap
, okeymap
))
6429 /* But do it only if the caller is actually going to read events.
6430 Otherwise there's no need to make him wake up, and it could
6431 cause trouble (for example it would make sit_for return). */
6432 if (waiting_for_user_input_p
== -1)
6433 record_asynch_buffer_change ();
6435 unbind_to (count
, Qnil
);
6438 /* Report all recent events of a change in process status
6439 (either run the sentinel or output a message).
6440 This is usually done while Emacs is waiting for keyboard input
6441 but can be done at other times. */
6444 status_notify (struct Lisp_Process
*deleting_process
)
6446 register Lisp_Object proc
;
6447 Lisp_Object tail
, msg
;
6448 struct gcpro gcpro1
, gcpro2
;
6452 /* We need to gcpro tail; if read_process_output calls a filter
6453 which deletes a process and removes the cons to which tail points
6454 from Vprocess_alist, and then causes a GC, tail is an unprotected
6458 /* Set this now, so that if new processes are created by sentinels
6459 that we run, we get called again to handle their status changes. */
6460 update_tick
= process_tick
;
6462 FOR_EACH_PROCESS (tail
, proc
)
6465 register struct Lisp_Process
*p
= XPROCESS (proc
);
6467 if (p
->tick
!= p
->update_tick
)
6469 p
->update_tick
= p
->tick
;
6471 /* If process is still active, read any output that remains. */
6472 while (! EQ (p
->filter
, Qt
)
6473 && ! EQ (p
->status
, Qconnect
)
6474 && ! EQ (p
->status
, Qlisten
)
6475 /* Network or serial process not stopped: */
6476 && ! EQ (p
->command
, Qt
)
6478 && p
!= deleting_process
6479 && read_process_output (proc
, p
->infd
) > 0);
6481 /* Get the text to use for the message. */
6482 if (p
->raw_status_new
)
6484 msg
= status_message (p
);
6486 /* If process is terminated, deactivate it or delete it. */
6488 if (CONSP (p
->status
))
6489 symbol
= XCAR (p
->status
);
6491 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6492 || EQ (symbol
, Qclosed
))
6494 if (delete_exited_processes
)
6495 remove_process (proc
);
6497 deactivate_process (proc
);
6500 /* The actions above may have further incremented p->tick.
6501 So set p->update_tick again so that an error in the sentinel will
6502 not cause this code to be run again. */
6503 p
->update_tick
= p
->tick
;
6504 /* Now output the message suitably. */
6505 exec_sentinel (proc
, msg
);
6509 update_mode_lines
++; /* In case buffers use %s in mode-line-format. */
6513 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6514 Sinternal_default_process_sentinel
, 2, 2, 0,
6515 doc
: /* Function used as default sentinel for processes. */)
6516 (Lisp_Object proc
, Lisp_Object msg
)
6518 Lisp_Object buffer
, symbol
;
6519 struct Lisp_Process
*p
;
6520 CHECK_PROCESS (proc
);
6521 p
= XPROCESS (proc
);
6525 symbol
= XCAR (symbol
);
6527 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6530 struct buffer
*old
= current_buffer
;
6531 ptrdiff_t opoint
, opoint_byte
;
6532 ptrdiff_t before
, before_byte
;
6534 /* Avoid error if buffer is deleted
6535 (probably that's why the process is dead, too). */
6536 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6538 Fset_buffer (buffer
);
6540 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6541 msg
= (code_convert_string_norecord
6542 (msg
, Vlocale_coding_system
, 1));
6545 opoint_byte
= PT_BYTE
;
6546 /* Insert new output into buffer
6547 at the current end-of-output marker,
6548 thus preserving logical ordering of input and output. */
6549 if (XMARKER (p
->mark
)->buffer
)
6550 Fgoto_char (p
->mark
);
6552 SET_PT_BOTH (ZV
, ZV_BYTE
);
6555 before_byte
= PT_BYTE
;
6557 tem
= BVAR (current_buffer
, read_only
);
6558 bset_read_only (current_buffer
, Qnil
);
6559 insert_string ("\nProcess ");
6560 { /* FIXME: temporary kludge. */
6561 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6562 insert_string (" ");
6564 bset_read_only (current_buffer
, tem
);
6565 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6567 if (opoint
>= before
)
6568 SET_PT_BOTH (opoint
+ (PT
- before
),
6569 opoint_byte
+ (PT_BYTE
- before_byte
));
6571 SET_PT_BOTH (opoint
, opoint_byte
);
6573 set_buffer_internal (old
);
6579 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6580 Sset_process_coding_system
, 1, 3, 0,
6581 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6582 DECODING will be used to decode subprocess output and ENCODING to
6583 encode subprocess input. */)
6584 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6586 register struct Lisp_Process
*p
;
6588 CHECK_PROCESS (process
);
6589 p
= XPROCESS (process
);
6591 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6593 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6594 Fcheck_coding_system (decoding
);
6595 Fcheck_coding_system (encoding
);
6596 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6597 pset_decode_coding_system (p
, decoding
);
6598 pset_encode_coding_system (p
, encoding
);
6599 setup_process_coding_systems (process
);
6604 DEFUN ("process-coding-system",
6605 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6606 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6607 (register Lisp_Object process
)
6609 CHECK_PROCESS (process
);
6610 return Fcons (XPROCESS (process
)->decode_coding_system
,
6611 XPROCESS (process
)->encode_coding_system
);
6614 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6615 Sset_process_filter_multibyte
, 2, 2, 0,
6616 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6617 If FLAG is non-nil, the filter is given multibyte strings.
6618 If FLAG is nil, the filter is given unibyte strings. In this case,
6619 all character code conversion except for end-of-line conversion is
6621 (Lisp_Object process
, Lisp_Object flag
)
6623 register struct Lisp_Process
*p
;
6625 CHECK_PROCESS (process
);
6626 p
= XPROCESS (process
);
6628 pset_decode_coding_system
6629 (p
, raw_text_coding_system (p
->decode_coding_system
));
6630 setup_process_coding_systems (process
);
6635 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6636 Sprocess_filter_multibyte_p
, 1, 1, 0,
6637 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6638 (Lisp_Object process
)
6640 register struct Lisp_Process
*p
;
6641 struct coding_system
*coding
;
6643 CHECK_PROCESS (process
);
6644 p
= XPROCESS (process
);
6645 coding
= proc_decode_coding_system
[p
->infd
];
6646 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6655 add_gpm_wait_descriptor (int desc
)
6657 add_keyboard_wait_descriptor (desc
);
6661 delete_gpm_wait_descriptor (int desc
)
6663 delete_keyboard_wait_descriptor (desc
);
6668 # ifdef USABLE_SIGIO
6670 /* Return true if *MASK has a bit set
6671 that corresponds to one of the keyboard input descriptors. */
6674 keyboard_bit_set (fd_set
*mask
)
6678 for (fd
= 0; fd
<= max_desc
; fd
++)
6679 if (FD_ISSET (fd
, mask
)
6680 && ((fd_callback_info
[fd
].flags
& KEYBOARD_FD
) != 0))
6687 #else /* not subprocesses */
6689 /* Defined on msdos.c. */
6690 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
6691 EMACS_TIME
*, void *);
6693 /* Implementation of wait_reading_process_output, assuming that there
6694 are no subprocesses. Used only by the MS-DOS build.
6696 Wait for timeout to elapse and/or keyboard input to be available.
6700 If negative, gobble data immediately available but don't wait for any.
6703 an additional duration to wait, measured in nanoseconds
6704 If TIME_LIMIT is zero, then:
6705 If NSECS == 0, there is no limit.
6706 If NSECS > 0, the timeout consists of NSECS only.
6707 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6710 0 to ignore keyboard input, or
6711 1 to return when input is available, or
6712 -1 means caller will actually read the input, so don't throw to
6715 see full version for other parameters. We know that wait_proc will
6716 always be NULL, since `subprocesses' isn't defined.
6718 DO_DISPLAY means redisplay should be done to show subprocess
6719 output that arrives.
6721 Return true if we received input from any process. */
6724 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6726 Lisp_Object wait_for_cell
,
6727 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6730 EMACS_TIME end_time
, timeout
;
6737 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6738 time_limit
= TYPE_MAXIMUM (time_t);
6740 /* What does time_limit really mean? */
6741 if (time_limit
|| nsecs
> 0)
6743 timeout
= make_emacs_time (time_limit
, nsecs
);
6744 end_time
= add_emacs_time (current_emacs_time (), timeout
);
6747 /* Turn off periodic alarms (in case they are in use)
6748 and then turn off any other atimers,
6749 because the select emulator uses alarms. */
6751 turn_on_atimers (0);
6755 bool timeout_reduced_for_timers
= 0;
6756 SELECT_TYPE waitchannels
;
6759 /* If calling from keyboard input, do not quit
6760 since we want to return C-g as an input character.
6761 Otherwise, do pending quit if requested. */
6765 /* Exit now if the cell we're waiting for became non-nil. */
6766 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6769 /* Compute time from now till when time limit is up. */
6770 /* Exit if already run out. */
6773 /* A negative timeout means
6774 gobble output available now
6775 but don't wait at all. */
6777 timeout
= make_emacs_time (0, 0);
6779 else if (time_limit
|| nsecs
> 0)
6781 EMACS_TIME now
= current_emacs_time ();
6782 if (EMACS_TIME_LE (end_time
, now
))
6784 timeout
= sub_emacs_time (end_time
, now
);
6788 timeout
= make_emacs_time (100000, 0);
6791 /* If our caller will not immediately handle keyboard events,
6792 run timer events directly.
6793 (Callers that will immediately read keyboard events
6794 call timer_delay on their own.) */
6795 if (NILP (wait_for_cell
))
6797 EMACS_TIME timer_delay
;
6801 unsigned old_timers_run
= timers_run
;
6802 timer_delay
= timer_check ();
6803 if (timers_run
!= old_timers_run
&& do_display
)
6804 /* We must retry, since a timer may have requeued itself
6805 and that could alter the time delay. */
6806 redisplay_preserve_echo_area (14);
6810 while (!detect_input_pending ());
6812 /* If there is unread keyboard input, also return. */
6814 && requeued_events_pending_p ())
6817 if (EMACS_TIME_VALID_P (timer_delay
) && nsecs
>= 0)
6819 if (EMACS_TIME_LT (timer_delay
, timeout
))
6821 timeout
= timer_delay
;
6822 timeout_reduced_for_timers
= 1;
6827 /* Cause C-g and alarm signals to take immediate action,
6828 and cause input available signals to zero out timeout. */
6830 set_waiting_for_input (&timeout
);
6832 /* If a frame has been newly mapped and needs updating,
6833 reprocess its display stuff. */
6834 if (frame_garbaged
&& do_display
)
6836 clear_waiting_for_input ();
6837 redisplay_preserve_echo_area (15);
6839 set_waiting_for_input (&timeout
);
6842 /* Wait till there is something to do. */
6843 FD_ZERO (&waitchannels
);
6844 if (read_kbd
&& detect_input_pending ())
6848 if (read_kbd
|| !NILP (wait_for_cell
))
6849 FD_SET (0, &waitchannels
);
6850 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6855 /* Make C-g and alarm signals set flags again */
6856 clear_waiting_for_input ();
6858 /* If we woke up due to SIGWINCH, actually change size now. */
6859 do_pending_window_change (0);
6861 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6862 /* We waited the full specified time, so return now. */
6867 /* If the system call was interrupted, then go around the
6869 if (xerrno
== EINTR
)
6870 FD_ZERO (&waitchannels
);
6872 report_file_errno ("Failed select", Qnil
, xerrno
);
6875 /* Check for keyboard input */
6878 && detect_input_pending_run_timers (do_display
))
6880 swallow_events (do_display
);
6881 if (detect_input_pending_run_timers (do_display
))
6885 /* If there is unread keyboard input, also return. */
6887 && requeued_events_pending_p ())
6890 /* If wait_for_cell. check for keyboard input
6891 but don't run any timers.
6892 ??? (It seems wrong to me to check for keyboard
6893 input at all when wait_for_cell, but the code
6894 has been this way since July 1994.
6895 Try changing this after version 19.31.) */
6896 if (! NILP (wait_for_cell
)
6897 && detect_input_pending ())
6899 swallow_events (do_display
);
6900 if (detect_input_pending ())
6904 /* Exit now if the cell we're waiting for became non-nil. */
6905 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6914 #endif /* not subprocesses */
6916 /* The following functions are needed even if async subprocesses are
6917 not supported. Some of them are no-op stubs in that case. */
6919 /* Add DESC to the set of keyboard input descriptors. */
6922 add_keyboard_wait_descriptor (int desc
)
6924 #ifdef subprocesses /* actually means "not MSDOS" */
6925 eassert (desc
>= 0 && desc
< MAXDESC
);
6926 fd_callback_info
[desc
].flags
|= FOR_READ
| KEYBOARD_FD
;
6927 if (desc
> max_desc
)
6932 /* From now on, do not expect DESC to give keyboard input. */
6935 delete_keyboard_wait_descriptor (int desc
)
6941 eassert (desc
>= 0 && desc
< MAXDESC
);
6942 eassert (desc
<= max_desc
);
6944 fd_callback_info
[desc
].flags
&= ~(FOR_READ
| KEYBOARD_FD
| PROCESS_FD
);
6946 if (desc
== max_desc
)
6947 recompute_max_desc ();
6951 /* Setup coding systems of PROCESS. */
6954 setup_process_coding_systems (Lisp_Object process
)
6957 struct Lisp_Process
*p
= XPROCESS (process
);
6959 int outch
= p
->outfd
;
6960 Lisp_Object coding_system
;
6962 if (inch
< 0 || outch
< 0)
6965 if (!proc_decode_coding_system
[inch
])
6966 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6967 coding_system
= p
->decode_coding_system
;
6968 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6969 && BUFFERP (p
->buffer
))
6971 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6972 coding_system
= raw_text_coding_system (coding_system
);
6974 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6976 if (!proc_encode_coding_system
[outch
])
6977 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6978 setup_coding_system (p
->encode_coding_system
,
6979 proc_encode_coding_system
[outch
]);
6983 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6984 doc
: /* Return the (or a) process associated with BUFFER.
6985 BUFFER may be a buffer or the name of one. */)
6986 (register Lisp_Object buffer
)
6989 register Lisp_Object buf
, tail
, proc
;
6991 if (NILP (buffer
)) return Qnil
;
6992 buf
= Fget_buffer (buffer
);
6993 if (NILP (buf
)) return Qnil
;
6995 FOR_EACH_PROCESS (tail
, proc
)
6996 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6998 #endif /* subprocesses */
7002 DEFUN ("process-inherit-coding-system-flag",
7003 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7005 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7006 If this flag is t, `buffer-file-coding-system' of the buffer
7007 associated with PROCESS will inherit the coding system used to decode
7008 the process output. */)
7009 (register Lisp_Object process
)
7012 CHECK_PROCESS (process
);
7013 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7015 /* Ignore the argument and return the value of
7016 inherit-process-coding-system. */
7017 return inherit_process_coding_system
? Qt
: Qnil
;
7021 /* Kill all processes associated with `buffer'.
7022 If `buffer' is nil, kill all processes */
7025 kill_buffer_processes (Lisp_Object buffer
)
7028 Lisp_Object tail
, proc
;
7030 FOR_EACH_PROCESS (tail
, proc
)
7031 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7033 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
7034 Fdelete_process (proc
);
7035 else if (XPROCESS (proc
)->infd
>= 0)
7036 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7038 #else /* subprocesses */
7039 /* Since we have no subprocesses, this does nothing. */
7040 #endif /* subprocesses */
7043 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7044 Swaiting_for_user_input_p
, 0, 0, 0,
7045 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7046 This is intended for use by asynchronous process output filters and sentinels. */)
7050 return (waiting_for_user_input_p
? Qt
: Qnil
);
7056 /* Stop reading input from keyboard sources. */
7059 hold_keyboard_input (void)
7064 /* Resume reading input from keyboard sources. */
7067 unhold_keyboard_input (void)
7072 /* Return true if keyboard input is on hold, zero otherwise. */
7075 kbd_on_hold_p (void)
7077 return kbd_is_on_hold
;
7081 /* Enumeration of and access to system processes a-la ps(1). */
7083 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7085 doc
: /* Return a list of numerical process IDs of all running processes.
7086 If this functionality is unsupported, return nil.
7088 See `process-attributes' for getting attributes of a process given its ID. */)
7091 return list_system_processes ();
7094 DEFUN ("process-attributes", Fprocess_attributes
,
7095 Sprocess_attributes
, 1, 1, 0,
7096 doc
: /* Return attributes of the process given by its PID, a number.
7098 Value is an alist where each element is a cons cell of the form
7102 If this functionality is unsupported, the value is nil.
7104 See `list-system-processes' for getting a list of all process IDs.
7106 The KEYs of the attributes that this function may return are listed
7107 below, together with the type of the associated VALUE (in parentheses).
7108 Not all platforms support all of these attributes; unsupported
7109 attributes will not appear in the returned alist.
7110 Unless explicitly indicated otherwise, numbers can have either
7111 integer or floating point values.
7113 euid -- Effective user User ID of the process (number)
7114 user -- User name corresponding to euid (string)
7115 egid -- Effective user Group ID of the process (number)
7116 group -- Group name corresponding to egid (string)
7117 comm -- Command name (executable name only) (string)
7118 state -- Process state code, such as "S", "R", or "T" (string)
7119 ppid -- Parent process ID (number)
7120 pgrp -- Process group ID (number)
7121 sess -- Session ID, i.e. process ID of session leader (number)
7122 ttname -- Controlling tty name (string)
7123 tpgid -- ID of foreground process group on the process's tty (number)
7124 minflt -- number of minor page faults (number)
7125 majflt -- number of major page faults (number)
7126 cminflt -- cumulative number of minor page faults (number)
7127 cmajflt -- cumulative number of major page faults (number)
7128 utime -- user time used by the process, in (current-time) format,
7129 which is a list of integers (HIGH LOW USEC PSEC)
7130 stime -- system time used by the process (current-time)
7131 time -- sum of utime and stime (current-time)
7132 cutime -- user time used by the process and its children (current-time)
7133 cstime -- system time used by the process and its children (current-time)
7134 ctime -- sum of cutime and cstime (current-time)
7135 pri -- priority of the process (number)
7136 nice -- nice value of the process (number)
7137 thcount -- process thread count (number)
7138 start -- time the process started (current-time)
7139 vsize -- virtual memory size of the process in KB's (number)
7140 rss -- resident set size of the process in KB's (number)
7141 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7142 pcpu -- percents of CPU time used by the process (floating-point number)
7143 pmem -- percents of total physical memory used by process's resident set
7144 (floating-point number)
7145 args -- command line which invoked the process (string). */)
7148 return system_process_attributes (pid
);
7151 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7152 Invoke this after init_process_emacs, and after glib and/or GNUstep
7153 futz with the SIGCHLD handler, but before Emacs forks any children.
7154 This function's caller should block SIGCHLD. */
7156 #ifndef NS_IMPL_GNUSTEP
7160 catch_child_signal (void)
7162 struct sigaction action
, old_action
;
7163 emacs_sigaction_init (&action
, deliver_child_signal
);
7164 block_child_signal ();
7165 sigaction (SIGCHLD
, &action
, &old_action
);
7166 eassert (! (old_action
.sa_flags
& SA_SIGINFO
));
7168 if (old_action
.sa_handler
!= deliver_child_signal
)
7170 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7172 : old_action
.sa_handler
);
7173 unblock_child_signal ();
7177 /* This is not called "init_process" because that is the name of a
7178 Mach system call, so it would cause problems on Darwin systems. */
7180 init_process_emacs (void)
7185 inhibit_sentinels
= 0;
7188 if (! noninteractive
|| initialized
)
7191 #if defined HAVE_GLIB && !defined WINDOWSNT
7192 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7193 this should always fail, but is enough to initialize glib's
7194 private SIGCHLD handler, allowing catch_child_signal to copy
7195 it into lib_child_handler. */
7196 g_source_unref (g_child_watch_source_new (getpid ()));
7198 catch_child_signal ();
7202 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7204 #ifdef NON_BLOCKING_CONNECT
7205 num_pending_connects
= 0;
7208 #ifdef ADAPTIVE_READ_BUFFERING
7209 process_output_delay_count
= 0;
7210 process_output_skip
= 0;
7213 /* Don't do this, it caused infinite select loops. The display
7214 method should call add_keyboard_wait_descriptor on stdin if it
7217 FD_SET (0, &input_wait_mask
);
7220 Vprocess_alist
= Qnil
;
7221 deleted_pid_list
= Qnil
;
7222 for (i
= 0; i
< MAXDESC
; i
++)
7224 chan_process
[i
] = Qnil
;
7225 proc_buffered_char
[i
] = -1;
7227 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7228 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7229 #ifdef DATAGRAM_SOCKETS
7230 memset (datagram_address
, 0, sizeof datagram_address
);
7234 Lisp_Object subfeatures
= Qnil
;
7235 const struct socket_options
*sopt
;
7237 #define ADD_SUBFEATURE(key, val) \
7238 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7240 #ifdef NON_BLOCKING_CONNECT
7241 ADD_SUBFEATURE (QCnowait
, Qt
);
7243 #ifdef DATAGRAM_SOCKETS
7244 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7246 #ifdef HAVE_SEQPACKET
7247 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7249 #ifdef HAVE_LOCAL_SOCKETS
7250 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7252 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7254 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7256 #ifdef HAVE_GETSOCKNAME
7257 ADD_SUBFEATURE (QCservice
, Qt
);
7259 ADD_SUBFEATURE (QCserver
, Qt
);
7261 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7262 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7264 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7267 #if defined (DARWIN_OS)
7268 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7269 processes. As such, we only change the default value. */
7272 char const *release
= (STRINGP (Voperating_system_release
)
7273 ? SSDATA (Voperating_system_release
)
7275 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7276 Vprocess_connection_type
= Qnil
;
7280 #endif /* subprocesses */
7285 syms_of_process (void)
7289 DEFSYM (Qprocessp
, "processp");
7290 DEFSYM (Qrun
, "run");
7291 DEFSYM (Qstop
, "stop");
7292 DEFSYM (Qsignal
, "signal");
7294 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7297 Qexit = intern_c_string ("exit");
7298 staticpro (&Qexit); */
7300 DEFSYM (Qopen
, "open");
7301 DEFSYM (Qclosed
, "closed");
7302 DEFSYM (Qconnect
, "connect");
7303 DEFSYM (Qfailed
, "failed");
7304 DEFSYM (Qlisten
, "listen");
7305 DEFSYM (Qlocal
, "local");
7306 DEFSYM (Qipv4
, "ipv4");
7308 DEFSYM (Qipv6
, "ipv6");
7310 DEFSYM (Qdatagram
, "datagram");
7311 DEFSYM (Qseqpacket
, "seqpacket");
7313 DEFSYM (QCport
, ":port");
7314 DEFSYM (QCspeed
, ":speed");
7315 DEFSYM (QCprocess
, ":process");
7317 DEFSYM (QCbytesize
, ":bytesize");
7318 DEFSYM (QCstopbits
, ":stopbits");
7319 DEFSYM (QCparity
, ":parity");
7320 DEFSYM (Qodd
, "odd");
7321 DEFSYM (Qeven
, "even");
7322 DEFSYM (QCflowcontrol
, ":flowcontrol");
7325 DEFSYM (QCsummary
, ":summary");
7327 DEFSYM (Qreal
, "real");
7328 DEFSYM (Qnetwork
, "network");
7329 DEFSYM (Qserial
, "serial");
7330 DEFSYM (QCbuffer
, ":buffer");
7331 DEFSYM (QChost
, ":host");
7332 DEFSYM (QCservice
, ":service");
7333 DEFSYM (QClocal
, ":local");
7334 DEFSYM (QCremote
, ":remote");
7335 DEFSYM (QCcoding
, ":coding");
7336 DEFSYM (QCserver
, ":server");
7337 DEFSYM (QCnowait
, ":nowait");
7338 DEFSYM (QCsentinel
, ":sentinel");
7339 DEFSYM (QClog
, ":log");
7340 DEFSYM (QCnoquery
, ":noquery");
7341 DEFSYM (QCstop
, ":stop");
7342 DEFSYM (QCoptions
, ":options");
7343 DEFSYM (QCplist
, ":plist");
7345 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7347 staticpro (&Vprocess_alist
);
7348 staticpro (&deleted_pid_list
);
7350 #endif /* subprocesses */
7352 DEFSYM (QCname
, ":name");
7353 DEFSYM (QCtype
, ":type");
7355 DEFSYM (Qeuid
, "euid");
7356 DEFSYM (Qegid
, "egid");
7357 DEFSYM (Quser
, "user");
7358 DEFSYM (Qgroup
, "group");
7359 DEFSYM (Qcomm
, "comm");
7360 DEFSYM (Qstate
, "state");
7361 DEFSYM (Qppid
, "ppid");
7362 DEFSYM (Qpgrp
, "pgrp");
7363 DEFSYM (Qsess
, "sess");
7364 DEFSYM (Qttname
, "ttname");
7365 DEFSYM (Qtpgid
, "tpgid");
7366 DEFSYM (Qminflt
, "minflt");
7367 DEFSYM (Qmajflt
, "majflt");
7368 DEFSYM (Qcminflt
, "cminflt");
7369 DEFSYM (Qcmajflt
, "cmajflt");
7370 DEFSYM (Qutime
, "utime");
7371 DEFSYM (Qstime
, "stime");
7372 DEFSYM (Qtime
, "time");
7373 DEFSYM (Qcutime
, "cutime");
7374 DEFSYM (Qcstime
, "cstime");
7375 DEFSYM (Qctime
, "ctime");
7376 DEFSYM (Qinternal_default_process_sentinel
,
7377 "internal-default-process-sentinel");
7378 DEFSYM (Qinternal_default_process_filter
,
7379 "internal-default-process-filter");
7380 DEFSYM (Qpri
, "pri");
7381 DEFSYM (Qnice
, "nice");
7382 DEFSYM (Qthcount
, "thcount");
7383 DEFSYM (Qstart
, "start");
7384 DEFSYM (Qvsize
, "vsize");
7385 DEFSYM (Qrss
, "rss");
7386 DEFSYM (Qetime
, "etime");
7387 DEFSYM (Qpcpu
, "pcpu");
7388 DEFSYM (Qpmem
, "pmem");
7389 DEFSYM (Qargs
, "args");
7391 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7392 doc
: /* Non-nil means delete processes immediately when they exit.
7393 A value of nil means don't delete them until `list-processes' is run. */);
7395 delete_exited_processes
= 1;
7398 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7399 doc
: /* Control type of device used to communicate with subprocesses.
7400 Values are nil to use a pipe, or t or `pty' to use a pty.
7401 The value has no effect if the system has no ptys or if all ptys are busy:
7402 then a pipe is used in any case.
7403 The value takes effect when `start-process' is called. */);
7404 Vprocess_connection_type
= Qt
;
7406 #ifdef ADAPTIVE_READ_BUFFERING
7407 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7408 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7409 On some systems, when Emacs reads the output from a subprocess, the output data
7410 is read in very small blocks, potentially resulting in very poor performance.
7411 This behavior can be remedied to some extent by setting this variable to a
7412 non-nil value, as it will automatically delay reading from such processes, to
7413 allow them to produce more output before Emacs tries to read it.
7414 If the value is t, the delay is reset after each write to the process; any other
7415 non-nil value means that the delay is not reset on write.
7416 The variable takes effect when `start-process' is called. */);
7417 Vprocess_adaptive_read_buffering
= Qt
;
7420 defsubr (&Sprocessp
);
7421 defsubr (&Sget_process
);
7422 defsubr (&Sdelete_process
);
7423 defsubr (&Sprocess_status
);
7424 defsubr (&Sprocess_exit_status
);
7425 defsubr (&Sprocess_id
);
7426 defsubr (&Sprocess_name
);
7427 defsubr (&Sprocess_tty_name
);
7428 defsubr (&Sprocess_command
);
7429 defsubr (&Sset_process_buffer
);
7430 defsubr (&Sprocess_buffer
);
7431 defsubr (&Sprocess_mark
);
7432 defsubr (&Sset_process_filter
);
7433 defsubr (&Sprocess_filter
);
7434 defsubr (&Sset_process_sentinel
);
7435 defsubr (&Sprocess_sentinel
);
7436 defsubr (&Sset_process_thread
);
7437 defsubr (&Sprocess_thread
);
7438 defsubr (&Sset_process_window_size
);
7439 defsubr (&Sset_process_inherit_coding_system_flag
);
7440 defsubr (&Sset_process_query_on_exit_flag
);
7441 defsubr (&Sprocess_query_on_exit_flag
);
7442 defsubr (&Sprocess_contact
);
7443 defsubr (&Sprocess_plist
);
7444 defsubr (&Sset_process_plist
);
7445 defsubr (&Sprocess_list
);
7446 defsubr (&Sstart_process
);
7447 defsubr (&Sserial_process_configure
);
7448 defsubr (&Smake_serial_process
);
7449 defsubr (&Sset_network_process_option
);
7450 defsubr (&Smake_network_process
);
7451 defsubr (&Sformat_network_address
);
7452 #if defined (HAVE_NET_IF_H)
7454 defsubr (&Snetwork_interface_list
);
7456 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7457 defsubr (&Snetwork_interface_info
);
7459 #endif /* defined (HAVE_NET_IF_H) */
7460 #ifdef DATAGRAM_SOCKETS
7461 defsubr (&Sprocess_datagram_address
);
7462 defsubr (&Sset_process_datagram_address
);
7464 defsubr (&Saccept_process_output
);
7465 defsubr (&Sprocess_send_region
);
7466 defsubr (&Sprocess_send_string
);
7467 defsubr (&Sinterrupt_process
);
7468 defsubr (&Skill_process
);
7469 defsubr (&Squit_process
);
7470 defsubr (&Sstop_process
);
7471 defsubr (&Scontinue_process
);
7472 defsubr (&Sprocess_running_child_p
);
7473 defsubr (&Sprocess_send_eof
);
7474 defsubr (&Ssignal_process
);
7475 defsubr (&Swaiting_for_user_input_p
);
7476 defsubr (&Sprocess_type
);
7477 defsubr (&Sinternal_default_process_sentinel
);
7478 defsubr (&Sinternal_default_process_filter
);
7479 defsubr (&Sset_process_coding_system
);
7480 defsubr (&Sprocess_coding_system
);
7481 defsubr (&Sset_process_filter_multibyte
);
7482 defsubr (&Sprocess_filter_multibyte_p
);
7484 #endif /* subprocesses */
7486 defsubr (&Sget_buffer_process
);
7487 defsubr (&Sprocess_inherit_coding_system_flag
);
7488 defsubr (&Slist_system_processes
);
7489 defsubr (&Sprocess_attributes
);