1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2014
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
34 /* Only MS-DOS does not define `subprocesses'. */
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
48 #define HAVE_LOCAL_SOCKETS
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
79 #include <arpa/nameser.h>
95 #endif /* subprocesses */
101 #include "character.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
121 #ifdef HAVE_WINDOW_SYSTEM
123 #endif /* HAVE_WINDOW_SYSTEM */
126 #include "xgselect.h"
133 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
134 struct timespec
*, void *);
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
144 Lisp_Object Qeuid
, Qegid
, Qcomm
, Qstate
, Qppid
, Qpgrp
, Qsess
, Qttname
, Qtpgid
;
145 Lisp_Object Qminflt
, Qmajflt
, Qcminflt
, Qcmajflt
, Qutime
, Qstime
, Qcstime
;
146 Lisp_Object Qcutime
, Qpri
, Qnice
, Qthcount
, Qstart
, Qvsize
, Qrss
, Qargs
;
147 Lisp_Object Quser
, Qgroup
, Qetime
, Qpcpu
, Qpmem
, Qtime
, Qctime
;
148 Lisp_Object QCname
, QCtype
;
150 /* True if keyboard input is on hold, zero otherwise. */
152 static bool kbd_is_on_hold
;
154 /* Nonzero means don't run process sentinels. This is used
156 bool inhibit_sentinels
;
161 # define SOCK_CLOEXEC 0
166 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
169 close_on_exec (int fd
)
172 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
177 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
179 return close_on_exec (accept (sockfd
, addr
, addrlen
));
183 process_socket (int domain
, int type
, int protocol
)
185 return close_on_exec (socket (domain
, type
, protocol
));
188 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
191 Lisp_Object Qprocessp
;
192 static Lisp_Object Qrun
, Qstop
, Qsignal
;
193 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
195 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
196 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
198 static Lisp_Object Qipv6
;
200 static Lisp_Object QCport
, QCprocess
;
202 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
203 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
204 static Lisp_Object QCbuffer
, QChost
, QCservice
;
205 static Lisp_Object QClocal
, QCremote
, QCcoding
;
206 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
207 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
208 static Lisp_Object Qlast_nonmenu_event
;
209 static Lisp_Object Qinternal_default_process_sentinel
;
210 static Lisp_Object Qinternal_default_process_filter
;
212 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
213 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
214 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
215 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick
;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick
;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 /* Only W32 has this, it really means that select can't take write mask. */
225 #ifdef BROKEN_NON_BLOCKING_CONNECT
226 #undef NON_BLOCKING_CONNECT
227 #define SELECT_CANT_DO_WRITE_MASK
229 #ifndef NON_BLOCKING_CONNECT
231 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
232 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
233 #define NON_BLOCKING_CONNECT
234 #endif /* EWOULDBLOCK || EINPROGRESS */
235 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
236 #endif /* HAVE_SELECT */
237 #endif /* NON_BLOCKING_CONNECT */
238 #endif /* BROKEN_NON_BLOCKING_CONNECT */
240 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
241 this system. We need to read full packets, so we need a
242 "non-destructive" select. So we require either native select,
243 or emulation of select using FIONREAD. */
245 #ifndef BROKEN_DATAGRAM_SOCKETS
246 # if defined HAVE_SELECT || defined USABLE_FIONREAD
247 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
248 # define DATAGRAM_SOCKETS
253 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
254 # define HAVE_SEQPACKET
257 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
258 #define ADAPTIVE_READ_BUFFERING
261 #ifdef ADAPTIVE_READ_BUFFERING
262 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
263 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
264 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
266 /* Number of processes which have a non-zero read_output_delay,
267 and therefore might be delayed for adaptive read buffering. */
269 static int process_output_delay_count
;
271 /* True if any process has non-nil read_output_skip. */
273 static bool process_output_skip
;
276 #define process_output_delay_count 0
279 static void create_process (Lisp_Object
, char **, Lisp_Object
);
281 static bool keyboard_bit_set (fd_set
*);
283 static void deactivate_process (Lisp_Object
);
284 static void status_notify (struct Lisp_Process
*);
285 static int read_process_output (Lisp_Object
, int);
286 static void handle_child_signal (int);
287 static void create_pty (Lisp_Object
);
289 /* If we support a window system, turn on the code to poll periodically
290 to detect C-g. It isn't actually used when doing interrupt input. */
291 #ifdef HAVE_WINDOW_SYSTEM
292 #define POLL_FOR_INPUT
295 static Lisp_Object
get_process (register Lisp_Object name
);
296 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
298 /* Mask of bits indicating the descriptors that we wait for input on. */
300 static fd_set input_wait_mask
;
302 /* Mask that excludes keyboard input descriptor(s). */
304 static fd_set non_keyboard_wait_mask
;
306 /* Mask that excludes process input descriptor(s). */
308 static fd_set non_process_wait_mask
;
310 /* Mask for selecting for write. */
312 static fd_set write_mask
;
314 #ifdef NON_BLOCKING_CONNECT
315 /* Mask of bits indicating the descriptors that we wait for connect to
316 complete on. Once they complete, they are removed from this mask
317 and added to the input_wait_mask and non_keyboard_wait_mask. */
319 static fd_set connect_wait_mask
;
321 /* Number of bits set in connect_wait_mask. */
322 static int num_pending_connects
;
323 #endif /* NON_BLOCKING_CONNECT */
325 /* The largest descriptor currently in use for a process object; -1 if none. */
326 static int max_process_desc
;
328 /* The largest descriptor currently in use for input; -1 if none. */
329 static int max_input_desc
;
331 /* Indexed by descriptor, gives the process (if any) for that descriptor */
332 static Lisp_Object chan_process
[FD_SETSIZE
];
334 /* Alist of elements (NAME . PROCESS) */
335 static Lisp_Object Vprocess_alist
;
337 /* Buffered-ahead input char from process, indexed by channel.
338 -1 means empty (no char is buffered).
339 Used on sys V where the only way to tell if there is any
340 output from the process is to read at least one char.
341 Always -1 on systems that support FIONREAD. */
343 static int proc_buffered_char
[FD_SETSIZE
];
345 /* Table of `struct coding-system' for each process. */
346 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
347 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
349 #ifdef DATAGRAM_SOCKETS
350 /* Table of `partner address' for datagram sockets. */
351 static struct sockaddr_and_len
{
354 } datagram_address
[FD_SETSIZE
];
355 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
356 #define DATAGRAM_CONN_P(proc) \
357 (PROCESSP (proc) && \
358 XPROCESS (proc)->infd >= 0 && \
359 datagram_address[XPROCESS (proc)->infd].sa != 0)
361 #define DATAGRAM_CHAN_P(chan) (0)
362 #define DATAGRAM_CONN_P(proc) (0)
365 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
366 a `for' loop which iterates over processes from Vprocess_alist. */
368 #define FOR_EACH_PROCESS(list_var, proc_var) \
369 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
371 /* These setters are used only in this file, so they can be private. */
373 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
383 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
385 p
->decode_coding_system
= val
;
388 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
390 p
->decoding_buf
= val
;
393 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
395 p
->encode_coding_system
= val
;
398 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
400 p
->encoding_buf
= val
;
403 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
405 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
408 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
413 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
418 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
423 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
428 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
430 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
433 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
438 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
443 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
448 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
450 p
->write_queue
= val
;
455 static struct fd_callback_data
461 int condition
; /* mask of the defines above. */
462 } fd_callback_info
[FD_SETSIZE
];
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
< FD_SETSIZE
);
472 add_keyboard_wait_descriptor (fd
);
474 fd_callback_info
[fd
].func
= func
;
475 fd_callback_info
[fd
].data
= data
;
476 fd_callback_info
[fd
].condition
|= FOR_READ
;
479 /* Stop monitoring file descriptor FD for when read is possible. */
482 delete_read_fd (int fd
)
484 eassert (fd
< FD_SETSIZE
);
485 delete_keyboard_wait_descriptor (fd
);
487 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
488 if (fd_callback_info
[fd
].condition
== 0)
490 fd_callback_info
[fd
].func
= 0;
491 fd_callback_info
[fd
].data
= 0;
495 /* Add a file descriptor FD to be monitored for when write is possible.
496 When write is possible, call FUNC with argument DATA. */
499 add_write_fd (int fd
, fd_callback func
, void *data
)
501 eassert (fd
< FD_SETSIZE
);
502 FD_SET (fd
, &write_mask
);
503 if (fd
> max_input_desc
)
506 fd_callback_info
[fd
].func
= func
;
507 fd_callback_info
[fd
].data
= data
;
508 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
511 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
514 delete_input_desc (int fd
)
516 if (fd
== max_input_desc
)
520 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
521 || FD_ISSET (fd
, &write_mask
)));
527 /* Stop monitoring file descriptor FD for when write is possible. */
530 delete_write_fd (int fd
)
532 eassert (fd
< FD_SETSIZE
);
533 FD_CLR (fd
, &write_mask
);
534 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
535 if (fd_callback_info
[fd
].condition
== 0)
537 fd_callback_info
[fd
].func
= 0;
538 fd_callback_info
[fd
].data
= 0;
539 delete_input_desc (fd
);
544 /* Compute the Lisp form of the process status, p->status, from
545 the numeric status that was returned by `wait'. */
547 static Lisp_Object
status_convert (int);
550 update_status (struct Lisp_Process
*p
)
552 eassert (p
->raw_status_new
);
553 pset_status (p
, status_convert (p
->raw_status
));
554 p
->raw_status_new
= 0;
557 /* Convert a process status word in Unix format to
558 the list that we use internally. */
561 status_convert (int w
)
564 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
565 else if (WIFEXITED (w
))
566 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
567 WCOREDUMP (w
) ? Qt
: Qnil
));
568 else if (WIFSIGNALED (w
))
569 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
570 WCOREDUMP (w
) ? Qt
: Qnil
));
575 /* Given a status-list, extract the three pieces of information
576 and store them individually through the three pointers. */
579 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
593 *code
= XFASTINT (XCAR (tem
));
595 *coredump
= !NILP (tem
);
599 /* Return a string describing a process status list. */
602 status_message (struct Lisp_Process
*p
)
604 Lisp_Object status
= p
->status
;
608 Lisp_Object string
, string2
;
610 decode_status (status
, &symbol
, &code
, &coredump
);
612 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
615 synchronize_system_messages_locale ();
616 signame
= strsignal (code
);
618 string
= build_string ("unknown");
623 string
= build_unibyte_string (signame
);
624 if (! NILP (Vlocale_coding_system
))
625 string
= (code_convert_string_norecord
626 (string
, Vlocale_coding_system
, 0));
627 c1
= STRING_CHAR (SDATA (string
));
630 Faset (string
, make_number (0), make_number (c2
));
632 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
633 return concat2 (string
, string2
);
635 else if (EQ (symbol
, Qexit
))
638 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
640 return build_string ("finished\n");
641 string
= Fnumber_to_string (make_number (code
));
642 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
643 return concat3 (build_string ("exited abnormally with code "),
646 else if (EQ (symbol
, Qfailed
))
648 string
= Fnumber_to_string (make_number (code
));
649 string2
= build_string ("\n");
650 return concat3 (build_string ("failed with code "),
654 return Fcopy_sequence (Fsymbol_name (symbol
));
657 enum { PTY_NAME_SIZE
= 24 };
659 /* Open an available pty, returning a file descriptor.
660 Store into PTY_NAME the file name of the terminal corresponding to the pty.
661 Return -1 on failure. */
664 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
673 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
674 for (i
= 0; i
< 16; i
++)
677 #ifdef PTY_NAME_SPRINTF
680 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
681 #endif /* no PTY_NAME_SPRINTF */
685 #else /* no PTY_OPEN */
686 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
687 #endif /* no PTY_OPEN */
692 /* Set FD's close-on-exec flag. This is needed even if
693 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
694 doesn't require support for that combination.
695 Multithreaded platforms where posix_openpt ignores
696 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
697 have a race condition between the PTY_OPEN and here. */
698 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
700 /* check to make certain that both sides are available
701 this avoids a nasty yet stupid bug in rlogins */
702 #ifdef PTY_TTY_NAME_SPRINTF
705 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
706 #endif /* no PTY_TTY_NAME_SPRINTF */
707 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
720 #endif /* HAVE_PTYS */
725 make_process (Lisp_Object name
)
727 register Lisp_Object val
, tem
, name1
;
728 register struct Lisp_Process
*p
;
729 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
732 p
= allocate_process ();
733 /* Initialize Lisp data. Note that allocate_process initializes all
734 Lisp data to nil, so do it only for slots which should not be nil. */
735 pset_status (p
, Qrun
);
736 pset_mark (p
, Fmake_marker ());
738 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
739 non-Lisp data, so do it only for slots which should not be zero. */
742 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
746 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
749 /* If name is already in use, modify it until it is unused. */
754 tem
= Fget_process (name1
);
755 if (NILP (tem
)) break;
756 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
760 pset_sentinel (p
, Qinternal_default_process_sentinel
);
761 pset_filter (p
, Qinternal_default_process_filter
);
762 XSETPROCESS (val
, p
);
763 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
768 remove_process (register Lisp_Object proc
)
770 register Lisp_Object pair
;
772 pair
= Frassq (proc
, Vprocess_alist
);
773 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
775 deactivate_process (proc
);
779 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
780 doc
: /* Return t if OBJECT is a process. */)
783 return PROCESSP (object
) ? Qt
: Qnil
;
786 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
787 doc
: /* Return the process named NAME, or nil if there is none. */)
788 (register Lisp_Object name
)
793 return Fcdr (Fassoc (name
, Vprocess_alist
));
796 /* This is how commands for the user decode process arguments. It
797 accepts a process, a process name, a buffer, a buffer name, or nil.
798 Buffers denote the first process in the buffer, and nil denotes the
802 get_process (register Lisp_Object name
)
804 register Lisp_Object proc
, obj
;
807 obj
= Fget_process (name
);
809 obj
= Fget_buffer (name
);
811 error ("Process %s does not exist", SDATA (name
));
813 else if (NILP (name
))
814 obj
= Fcurrent_buffer ();
818 /* Now obj should be either a buffer object or a process object. */
821 if (NILP (BVAR (XBUFFER (obj
), name
)))
822 error ("Attempt to get process for a dead buffer");
823 proc
= Fget_buffer_process (obj
);
825 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
836 /* Fdelete_process promises to immediately forget about the process, but in
837 reality, Emacs needs to remember those processes until they have been
838 treated by the SIGCHLD handler and waitpid has been invoked on them;
839 otherwise they might fill up the kernel's process table.
841 Some processes created by call-process are also put onto this list.
843 Members of this list are (process-ID . filename) pairs. The
844 process-ID is a number; the filename, if a string, is a file that
845 needs to be removed after the process exits. */
846 static Lisp_Object deleted_pid_list
;
849 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
851 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
852 /* GC treated elements set to nil. */
853 Fdelq (Qnil
, deleted_pid_list
));
857 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
858 doc
: /* Delete PROCESS: kill it and forget about it immediately.
859 PROCESS may be a process, a buffer, the name of a process or buffer, or
860 nil, indicating the current buffer's process. */)
861 (register Lisp_Object process
)
863 register struct Lisp_Process
*p
;
865 process
= get_process (process
);
866 p
= XPROCESS (process
);
868 p
->raw_status_new
= 0;
869 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
871 pset_status (p
, list2 (Qexit
, make_number (0)));
872 p
->tick
= ++process_tick
;
874 redisplay_preserve_echo_area (13);
879 record_kill_process (p
, Qnil
);
883 /* Update P's status, since record_kill_process will make the
884 SIGCHLD handler update deleted_pid_list, not *P. */
886 if (p
->raw_status_new
)
888 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
889 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
890 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
892 p
->tick
= ++process_tick
;
894 redisplay_preserve_echo_area (13);
897 remove_process (process
);
901 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
902 doc
: /* Return the status of PROCESS.
903 The returned value is one of the following symbols:
904 run -- for a process that is running.
905 stop -- for a process stopped but continuable.
906 exit -- for a process that has exited.
907 signal -- for a process that has got a fatal signal.
908 open -- for a network stream connection that is open.
909 listen -- for a network stream server that is listening.
910 closed -- for a network stream connection that is closed.
911 connect -- when waiting for a non-blocking connection to complete.
912 failed -- when a non-blocking connection has failed.
913 nil -- if arg is a process name and no such process exists.
914 PROCESS may be a process, a buffer, the name of a process, or
915 nil, indicating the current buffer's process. */)
916 (register Lisp_Object process
)
918 register struct Lisp_Process
*p
;
919 register Lisp_Object status
;
921 if (STRINGP (process
))
922 process
= Fget_process (process
);
924 process
= get_process (process
);
929 p
= XPROCESS (process
);
930 if (p
->raw_status_new
)
934 status
= XCAR (status
);
935 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
937 if (EQ (status
, Qexit
))
939 else if (EQ (p
->command
, Qt
))
941 else if (EQ (status
, Qrun
))
947 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
949 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
950 If PROCESS has not yet exited or died, return 0. */)
951 (register Lisp_Object process
)
953 CHECK_PROCESS (process
);
954 if (XPROCESS (process
)->raw_status_new
)
955 update_status (XPROCESS (process
));
956 if (CONSP (XPROCESS (process
)->status
))
957 return XCAR (XCDR (XPROCESS (process
)->status
));
958 return make_number (0);
961 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
962 doc
: /* Return the process id of PROCESS.
963 This is the pid of the external process which PROCESS uses or talks to.
964 For a network connection, this value is nil. */)
965 (register Lisp_Object process
)
969 CHECK_PROCESS (process
);
970 pid
= XPROCESS (process
)->pid
;
971 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
974 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
975 doc
: /* Return the name of PROCESS, as a string.
976 This is the name of the program invoked in PROCESS,
977 possibly modified to make it unique among process names. */)
978 (register Lisp_Object process
)
980 CHECK_PROCESS (process
);
981 return XPROCESS (process
)->name
;
984 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
985 doc
: /* Return the command that was executed to start PROCESS.
986 This is a list of strings, the first string being the program executed
987 and the rest of the strings being the arguments given to it.
988 For a network or serial process, this is nil (process is running) or t
989 \(process is stopped). */)
990 (register Lisp_Object process
)
992 CHECK_PROCESS (process
);
993 return XPROCESS (process
)->command
;
996 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
997 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
998 This is the terminal that the process itself reads and writes on,
999 not the name of the pty that Emacs uses to talk with that terminal. */)
1000 (register Lisp_Object process
)
1002 CHECK_PROCESS (process
);
1003 return XPROCESS (process
)->tty_name
;
1006 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1008 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1010 (register Lisp_Object process
, Lisp_Object buffer
)
1012 struct Lisp_Process
*p
;
1014 CHECK_PROCESS (process
);
1016 CHECK_BUFFER (buffer
);
1017 p
= XPROCESS (process
);
1018 pset_buffer (p
, buffer
);
1019 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1020 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1021 setup_process_coding_systems (process
);
1025 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1027 doc
: /* Return the buffer PROCESS is associated with.
1028 The default process filter inserts output from PROCESS into this buffer. */)
1029 (register Lisp_Object process
)
1031 CHECK_PROCESS (process
);
1032 return XPROCESS (process
)->buffer
;
1035 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1037 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1038 (register Lisp_Object process
)
1040 CHECK_PROCESS (process
);
1041 return XPROCESS (process
)->mark
;
1044 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1046 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1047 A value of t means stop accepting output from the process.
1049 When a process has a non-default filter, its buffer is not used for output.
1050 Instead, each time it does output, the entire string of output is
1051 passed to the filter.
1053 The filter gets two arguments: the process and the string of output.
1054 The string argument is normally a multibyte string, except:
1055 - if the process's input coding system is no-conversion or raw-text,
1056 it is a unibyte string (the non-converted input), or else
1057 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1058 string (the result of converting the decoded input multibyte
1059 string to unibyte with `string-make-unibyte'). */)
1060 (register Lisp_Object process
, Lisp_Object filter
)
1062 struct Lisp_Process
*p
;
1064 CHECK_PROCESS (process
);
1065 p
= XPROCESS (process
);
1067 /* Don't signal an error if the process's input file descriptor
1068 is closed. This could make debugging Lisp more difficult,
1069 for example when doing something like
1071 (setq process (start-process ...))
1073 (set-process-filter process ...) */
1076 filter
= Qinternal_default_process_filter
;
1080 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1082 FD_CLR (p
->infd
, &input_wait_mask
);
1083 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1085 else if (EQ (p
->filter
, Qt
)
1086 /* Network or serial process not stopped: */
1087 && !EQ (p
->command
, Qt
))
1089 FD_SET (p
->infd
, &input_wait_mask
);
1090 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1094 pset_filter (p
, filter
);
1095 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1096 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1097 setup_process_coding_systems (process
);
1101 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1103 doc
: /* Return the filter function of PROCESS.
1104 See `set-process-filter' for more info on filter functions. */)
1105 (register Lisp_Object process
)
1107 CHECK_PROCESS (process
);
1108 return XPROCESS (process
)->filter
;
1111 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1113 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1114 The sentinel is called as a function when the process changes state.
1115 It gets two arguments: the process, and a string describing the change. */)
1116 (register Lisp_Object process
, Lisp_Object sentinel
)
1118 struct Lisp_Process
*p
;
1120 CHECK_PROCESS (process
);
1121 p
= XPROCESS (process
);
1123 if (NILP (sentinel
))
1124 sentinel
= Qinternal_default_process_sentinel
;
1126 pset_sentinel (p
, sentinel
);
1127 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1128 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1132 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1134 doc
: /* Return the sentinel of PROCESS.
1135 See `set-process-sentinel' for more info on sentinels. */)
1136 (register Lisp_Object process
)
1138 CHECK_PROCESS (process
);
1139 return XPROCESS (process
)->sentinel
;
1142 DEFUN ("set-process-window-size", Fset_process_window_size
,
1143 Sset_process_window_size
, 3, 3, 0,
1144 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1145 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1147 CHECK_PROCESS (process
);
1149 /* All known platforms store window sizes as 'unsigned short'. */
1150 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1151 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1153 if (XPROCESS (process
)->infd
< 0
1154 || (set_window_size (XPROCESS (process
)->infd
,
1155 XINT (height
), XINT (width
))
1162 DEFUN ("set-process-inherit-coding-system-flag",
1163 Fset_process_inherit_coding_system_flag
,
1164 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1165 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1166 If the second argument FLAG is non-nil, then the variable
1167 `buffer-file-coding-system' of the buffer associated with PROCESS
1168 will be bound to the value of the coding system used to decode
1171 This is useful when the coding system specified for the process buffer
1172 leaves either the character code conversion or the end-of-line conversion
1173 unspecified, or if the coding system used to decode the process output
1174 is more appropriate for saving the process buffer.
1176 Binding the variable `inherit-process-coding-system' to non-nil before
1177 starting the process is an alternative way of setting the inherit flag
1178 for the process which will run.
1180 This function returns FLAG. */)
1181 (register Lisp_Object process
, Lisp_Object flag
)
1183 CHECK_PROCESS (process
);
1184 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1188 DEFUN ("set-process-query-on-exit-flag",
1189 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1191 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1192 If the second argument FLAG is non-nil, Emacs will query the user before
1193 exiting or killing a buffer if PROCESS is running. This function
1195 (register Lisp_Object process
, Lisp_Object flag
)
1197 CHECK_PROCESS (process
);
1198 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1202 DEFUN ("process-query-on-exit-flag",
1203 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1205 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1206 (register Lisp_Object process
)
1208 CHECK_PROCESS (process
);
1209 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1212 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1214 doc
: /* Return the contact info of PROCESS; t for a real child.
1215 For a network or serial connection, the value depends on the optional
1216 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1217 SERVICE) for a network connection or (PORT SPEED) for a serial
1218 connection. If KEY is t, the complete contact information for the
1219 connection is returned, else the specific value for the keyword KEY is
1220 returned. See `make-network-process' or `make-serial-process' for a
1221 list of keywords. */)
1222 (register Lisp_Object process
, Lisp_Object key
)
1224 Lisp_Object contact
;
1226 CHECK_PROCESS (process
);
1227 contact
= XPROCESS (process
)->childp
;
1229 #ifdef DATAGRAM_SOCKETS
1230 if (DATAGRAM_CONN_P (process
)
1231 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1232 contact
= Fplist_put (contact
, QCremote
,
1233 Fprocess_datagram_address (process
));
1236 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1238 if (NILP (key
) && NETCONN_P (process
))
1239 return list2 (Fplist_get (contact
, QChost
),
1240 Fplist_get (contact
, QCservice
));
1241 if (NILP (key
) && SERIALCONN_P (process
))
1242 return list2 (Fplist_get (contact
, QCport
),
1243 Fplist_get (contact
, QCspeed
));
1244 return Fplist_get (contact
, key
);
1247 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1249 doc
: /* Return the plist of PROCESS. */)
1250 (register Lisp_Object process
)
1252 CHECK_PROCESS (process
);
1253 return XPROCESS (process
)->plist
;
1256 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1258 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1259 (register Lisp_Object process
, Lisp_Object plist
)
1261 CHECK_PROCESS (process
);
1264 pset_plist (XPROCESS (process
), plist
);
1268 #if 0 /* Turned off because we don't currently record this info
1269 in the process. Perhaps add it. */
1270 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1271 doc
: /* Return the connection type of PROCESS.
1272 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1273 a socket connection. */)
1274 (Lisp_Object process
)
1276 return XPROCESS (process
)->type
;
1280 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1281 doc
: /* Return the connection type of PROCESS.
1282 The value is either the symbol `real', `network', or `serial'.
1283 PROCESS may be a process, a buffer, the name of a process or buffer, or
1284 nil, indicating the current buffer's process. */)
1285 (Lisp_Object process
)
1288 proc
= get_process (process
);
1289 return XPROCESS (proc
)->type
;
1292 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1294 doc
: /* Convert network ADDRESS from internal format to a string.
1295 A 4 or 5 element vector represents an IPv4 address (with port number).
1296 An 8 or 9 element vector represents an IPv6 address (with port number).
1297 If optional second argument OMIT-PORT is non-nil, don't include a port
1298 number in the string, even when present in ADDRESS.
1299 Returns nil if format of ADDRESS is invalid. */)
1300 (Lisp_Object address
, Lisp_Object omit_port
)
1305 if (STRINGP (address
)) /* AF_LOCAL */
1308 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1310 register struct Lisp_Vector
*p
= XVECTOR (address
);
1311 ptrdiff_t size
= p
->header
.size
;
1312 Lisp_Object args
[10];
1315 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1317 args
[0] = build_string ("%d.%d.%d.%d");
1322 args
[0] = build_string ("%d.%d.%d.%d:%d");
1325 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1327 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1332 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1338 for (i
= 0; i
< nargs
; i
++)
1340 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1343 if (nargs
<= 5 /* IPv4 */
1344 && i
< 4 /* host, not port */
1345 && XINT (p
->contents
[i
]) > 255)
1348 args
[i
+1] = p
->contents
[i
];
1351 return Fformat (nargs
+1, args
);
1354 if (CONSP (address
))
1356 Lisp_Object args
[2];
1357 args
[0] = build_string ("<Family %d>");
1358 args
[1] = Fcar (address
);
1359 return Fformat (2, args
);
1365 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1366 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1369 return Fmapcar (Qcdr
, Vprocess_alist
);
1372 /* Starting asynchronous inferior processes. */
1374 static void start_process_unwind (Lisp_Object proc
);
1376 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1377 doc
: /* Start a program in a subprocess. Return the process object for it.
1378 NAME is name for process. It is modified if necessary to make it unique.
1379 BUFFER is the buffer (or buffer name) to associate with the process.
1381 Process output (both standard output and standard error streams) goes
1382 at end of BUFFER, unless you specify an output stream or filter
1383 function to handle the output. BUFFER may also be nil, meaning that
1384 this process is not associated with any buffer.
1386 PROGRAM is the program file name. It is searched for in `exec-path'
1387 (which see). If nil, just associate a pty with the buffer. Remaining
1388 arguments are strings to give program as arguments.
1390 If you want to separate standard output from standard error, invoke
1391 the command through a shell and redirect one of them using the shell
1394 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1395 (ptrdiff_t nargs
, Lisp_Object
*args
)
1397 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1398 register unsigned char **new_argv
;
1400 ptrdiff_t count
= SPECPDL_INDEX ();
1404 buffer
= Fget_buffer_create (buffer
);
1406 /* Make sure that the child will be able to chdir to the current
1407 buffer's current directory, or its unhandled equivalent. We
1408 can't just have the child check for an error when it does the
1409 chdir, since it's in a vfork.
1411 We have to GCPRO around this because Fexpand_file_name and
1412 Funhandled_file_name_directory might call a file name handling
1413 function. The argument list is protected by the caller, so all
1414 we really have to worry about is buffer. */
1416 struct gcpro gcpro1
;
1418 current_dir
= encode_current_directory ();
1423 CHECK_STRING (name
);
1427 if (!NILP (program
))
1428 CHECK_STRING (program
);
1430 proc
= make_process (name
);
1431 /* If an error occurs and we can't start the process, we want to
1432 remove it from the process list. This means that each error
1433 check in create_process doesn't need to call remove_process
1434 itself; it's all taken care of here. */
1435 record_unwind_protect (start_process_unwind
, proc
);
1437 pset_childp (XPROCESS (proc
), Qt
);
1438 pset_plist (XPROCESS (proc
), Qnil
);
1439 pset_type (XPROCESS (proc
), Qreal
);
1440 pset_buffer (XPROCESS (proc
), buffer
);
1441 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1442 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1443 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1446 /* AKA GNUTLS_INITSTAGE(proc). */
1447 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1448 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1451 #ifdef ADAPTIVE_READ_BUFFERING
1452 XPROCESS (proc
)->adaptive_read_buffering
1453 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1454 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1457 /* Make the process marker point into the process buffer (if any). */
1458 if (BUFFERP (buffer
))
1459 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1460 BUF_ZV (XBUFFER (buffer
)),
1461 BUF_ZV_BYTE (XBUFFER (buffer
)));
1464 /* Decide coding systems for communicating with the process. Here
1465 we don't setup the structure coding_system nor pay attention to
1466 unibyte mode. They are done in create_process. */
1468 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1469 Lisp_Object coding_systems
= Qt
;
1470 Lisp_Object val
, *args2
;
1471 struct gcpro gcpro1
, gcpro2
;
1473 val
= Vcoding_system_for_read
;
1476 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1477 args2
[0] = Qstart_process
;
1478 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1479 GCPRO2 (proc
, current_dir
);
1480 if (!NILP (program
))
1481 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1483 if (CONSP (coding_systems
))
1484 val
= XCAR (coding_systems
);
1485 else if (CONSP (Vdefault_process_coding_system
))
1486 val
= XCAR (Vdefault_process_coding_system
);
1488 pset_decode_coding_system (XPROCESS (proc
), val
);
1490 val
= Vcoding_system_for_write
;
1493 if (EQ (coding_systems
, Qt
))
1495 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1496 args2
[0] = Qstart_process
;
1497 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1498 GCPRO2 (proc
, current_dir
);
1499 if (!NILP (program
))
1500 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1503 if (CONSP (coding_systems
))
1504 val
= XCDR (coding_systems
);
1505 else if (CONSP (Vdefault_process_coding_system
))
1506 val
= XCDR (Vdefault_process_coding_system
);
1508 pset_encode_coding_system (XPROCESS (proc
), val
);
1509 /* Note: At this moment, the above coding system may leave
1510 text-conversion or eol-conversion unspecified. They will be
1511 decided after we read output from the process and decode it by
1512 some coding system, or just before we actually send a text to
1517 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1518 XPROCESS (proc
)->decoding_carryover
= 0;
1519 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1521 XPROCESS (proc
)->inherit_coding_system_flag
1522 = !(NILP (buffer
) || !inherit_process_coding_system
);
1524 if (!NILP (program
))
1526 /* If program file name is not absolute, search our path for it.
1527 Put the name we will really use in TEM. */
1528 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1529 && !(SCHARS (program
) > 1
1530 && IS_DEVICE_SEP (SREF (program
, 1))))
1532 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1535 GCPRO4 (name
, program
, buffer
, current_dir
);
1536 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1537 make_number (X_OK
), false);
1540 report_file_error ("Searching for program", program
);
1541 tem
= Fexpand_file_name (tem
, Qnil
);
1545 if (!NILP (Ffile_directory_p (program
)))
1546 error ("Specified program for new process is a directory");
1550 /* If program file name starts with /: for quoting a magic name,
1552 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1553 && SREF (tem
, 1) == ':')
1554 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1557 Lisp_Object arg_encoding
= Qnil
;
1558 struct gcpro gcpro1
;
1561 /* Encode the file name and put it in NEW_ARGV.
1562 That's where the child will use it to execute the program. */
1563 tem
= list1 (ENCODE_FILE (tem
));
1565 /* Here we encode arguments by the coding system used for sending
1566 data to the process. We don't support using different coding
1567 systems for encoding arguments and for encoding data sent to the
1570 for (i
= 3; i
< nargs
; i
++)
1572 tem
= Fcons (args
[i
], tem
);
1573 CHECK_STRING (XCAR (tem
));
1574 if (STRING_MULTIBYTE (XCAR (tem
)))
1576 if (NILP (arg_encoding
))
1577 arg_encoding
= (complement_process_encoding_system
1578 (XPROCESS (proc
)->encode_coding_system
));
1580 code_convert_string_norecord
1581 (XCAR (tem
), arg_encoding
, 1));
1588 /* Now that everything is encoded we can collect the strings into
1590 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1591 new_argv
[nargs
- 2] = 0;
1593 for (i
= nargs
- 2; i
-- != 0; )
1595 new_argv
[i
] = SDATA (XCAR (tem
));
1599 create_process (proc
, (char **) new_argv
, current_dir
);
1604 return unbind_to (count
, proc
);
1607 /* This function is the unwind_protect form for Fstart_process. If
1608 PROC doesn't have its pid set, then we know someone has signaled
1609 an error and the process wasn't started successfully, so we should
1610 remove it from the process list. */
1612 start_process_unwind (Lisp_Object proc
)
1614 if (!PROCESSP (proc
))
1617 /* Was PROC started successfully?
1618 -2 is used for a pty with no process, eg for gdb. */
1619 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1620 remove_process (proc
);
1623 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1626 close_process_fd (int *fd_addr
)
1636 /* Indexes of file descriptors in open_fds. */
1639 /* The pipe from Emacs to its subprocess. */
1641 WRITE_TO_SUBPROCESS
,
1643 /* The main pipe from the subprocess to Emacs. */
1644 READ_FROM_SUBPROCESS
,
1647 /* The pipe from the subprocess to Emacs that is closed when the
1648 subprocess execs. */
1649 READ_FROM_EXEC_MONITOR
,
1653 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1656 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1658 struct Lisp_Process
*p
= XPROCESS (process
);
1659 int inchannel
, outchannel
;
1662 int forkin
, forkout
;
1664 char pty_name
[PTY_NAME_SIZE
];
1665 Lisp_Object lisp_pty_name
= Qnil
;
1667 inchannel
= outchannel
= -1;
1669 if (!NILP (Vprocess_connection_type
))
1670 outchannel
= inchannel
= allocate_pty (pty_name
);
1674 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1675 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1676 /* On most USG systems it does not work to open the pty's tty here,
1677 then close it and reopen it in the child. */
1678 /* Don't let this terminal become our controlling terminal
1679 (in case we don't have one). */
1680 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1682 report_file_error ("Opening pty", Qnil
);
1683 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1685 forkin
= forkout
= -1;
1686 #endif /* not USG, or USG_SUBTTY_WORKS */
1688 lisp_pty_name
= build_string (pty_name
);
1692 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1693 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1694 report_file_error ("Creating pipe", Qnil
);
1695 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1696 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1697 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1698 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1702 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1703 report_file_error ("Creating pipe", Qnil
);
1706 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1707 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1709 /* Record this as an active process, with its channels. */
1710 chan_process
[inchannel
] = process
;
1711 p
->infd
= inchannel
;
1712 p
->outfd
= outchannel
;
1714 /* Previously we recorded the tty descriptor used in the subprocess.
1715 It was only used for getting the foreground tty process, so now
1716 we just reopen the device (see emacs_get_tty_pgrp) as this is
1717 more portable (see USG_SUBTTY_WORKS above). */
1719 p
->pty_flag
= pty_flag
;
1720 pset_status (p
, Qrun
);
1722 FD_SET (inchannel
, &input_wait_mask
);
1723 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1724 if (inchannel
> max_process_desc
)
1725 max_process_desc
= inchannel
;
1727 /* This may signal an error. */
1728 setup_process_coding_systems (process
);
1731 block_child_signal ();
1734 /* vfork, and prevent local vars from being clobbered by the vfork. */
1736 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1737 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1738 char **volatile new_argv_volatile
= new_argv
;
1739 int volatile forkin_volatile
= forkin
;
1740 int volatile forkout_volatile
= forkout
;
1741 struct Lisp_Process
*p_volatile
= p
;
1745 current_dir
= current_dir_volatile
;
1746 lisp_pty_name
= lisp_pty_name_volatile
;
1747 new_argv
= new_argv_volatile
;
1748 forkin
= forkin_volatile
;
1749 forkout
= forkout_volatile
;
1752 pty_flag
= p
->pty_flag
;
1756 #endif /* not WINDOWSNT */
1758 int xforkin
= forkin
;
1759 int xforkout
= forkout
;
1761 /* Make the pty be the controlling terminal of the process. */
1763 /* First, disconnect its current controlling terminal. */
1764 /* We tried doing setsid only if pty_flag, but it caused
1765 process_set_signal to fail on SGI when using a pipe. */
1767 /* Make the pty's terminal the controlling terminal. */
1768 if (pty_flag
&& xforkin
>= 0)
1771 /* We ignore the return value
1772 because faith@cs.unc.edu says that is necessary on Linux. */
1773 ioctl (xforkin
, TIOCSCTTY
, 0);
1776 #if defined (LDISC1)
1777 if (pty_flag
&& xforkin
>= 0)
1780 tcgetattr (xforkin
, &t
);
1782 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1783 emacs_perror ("create_process/tcsetattr LDISC1");
1786 #if defined (NTTYDISC) && defined (TIOCSETD)
1787 if (pty_flag
&& xforkin
>= 0)
1789 /* Use new line discipline. */
1790 int ldisc
= NTTYDISC
;
1791 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1796 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1797 can do TIOCSPGRP only to the process's controlling tty. */
1800 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1801 I can't test it since I don't have 4.3. */
1802 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1805 ioctl (j
, TIOCNOTTY
, 0);
1809 #endif /* TIOCNOTTY */
1811 #if !defined (DONT_REOPEN_PTY)
1812 /*** There is a suggestion that this ought to be a
1813 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1814 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1815 that system does seem to need this code, even though
1816 both TIOCSCTTY is defined. */
1817 /* Now close the pty (if we had it open) and reopen it.
1818 This makes the pty the controlling terminal of the subprocess. */
1822 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1825 emacs_close (xforkin
);
1826 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1830 emacs_perror (SSDATA (lisp_pty_name
));
1831 _exit (EXIT_CANCELED
);
1835 #endif /* not DONT_REOPEN_PTY */
1837 #ifdef SETUP_SLAVE_PTY
1842 #endif /* SETUP_SLAVE_PTY */
1843 #endif /* HAVE_PTYS */
1845 signal (SIGINT
, SIG_DFL
);
1846 signal (SIGQUIT
, SIG_DFL
);
1848 signal (SIGPROF
, SIG_DFL
);
1851 /* Emacs ignores SIGPIPE, but the child should not. */
1852 signal (SIGPIPE
, SIG_DFL
);
1854 /* Stop blocking SIGCHLD in the child. */
1855 unblock_child_signal ();
1858 child_setup_tty (xforkout
);
1860 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1861 #else /* not WINDOWSNT */
1862 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1863 #endif /* not WINDOWSNT */
1866 /* Back in the parent process. */
1868 vfork_errno
= errno
;
1873 /* Stop blocking in the parent. */
1874 unblock_child_signal ();
1878 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1881 /* vfork succeeded. */
1883 /* Close the pipe ends that the child uses, or the child's pty. */
1884 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1885 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1888 register_child (pid
, inchannel
);
1889 #endif /* WINDOWSNT */
1891 pset_tty_name (p
, lisp_pty_name
);
1894 /* Wait for child_setup to complete in case that vfork is
1895 actually defined as fork. The descriptor
1896 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1897 of a pipe is closed at the child side either by close-on-exec
1898 on successful execve or the _exit call in child_setup. */
1902 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1903 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
1904 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
1911 create_pty (Lisp_Object process
)
1913 struct Lisp_Process
*p
= XPROCESS (process
);
1914 char pty_name
[PTY_NAME_SIZE
];
1915 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
1919 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
1920 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1921 /* On most USG systems it does not work to open the pty's tty here,
1922 then close it and reopen it in the child. */
1923 /* Don't let this terminal become our controlling terminal
1924 (in case we don't have one). */
1925 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1927 report_file_error ("Opening pty", Qnil
);
1928 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
1929 #if defined (DONT_REOPEN_PTY)
1930 /* In the case that vfork is defined as fork, the parent process
1931 (Emacs) may send some data before the child process completes
1932 tty options setup. So we setup tty before forking. */
1933 child_setup_tty (forkout
);
1934 #endif /* DONT_REOPEN_PTY */
1935 #endif /* not USG, or USG_SUBTTY_WORKS */
1937 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
1939 /* Record this as an active process, with its channels.
1940 As a result, child_setup will close Emacs's side of the pipes. */
1941 chan_process
[pty_fd
] = process
;
1945 /* Previously we recorded the tty descriptor used in the subprocess.
1946 It was only used for getting the foreground tty process, so now
1947 we just reopen the device (see emacs_get_tty_pgrp) as this is
1948 more portable (see USG_SUBTTY_WORKS above). */
1951 pset_status (p
, Qrun
);
1952 setup_process_coding_systems (process
);
1954 FD_SET (pty_fd
, &input_wait_mask
);
1955 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
1956 if (pty_fd
> max_process_desc
)
1957 max_process_desc
= pty_fd
;
1959 pset_tty_name (p
, build_string (pty_name
));
1966 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1967 The address family of sa is not included in the result. */
1973 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
1975 Lisp_Object address
;
1978 register struct Lisp_Vector
*p
;
1980 /* Workaround for a bug in getsockname on BSD: Names bound to
1981 sockets in the UNIX domain are inaccessible; getsockname returns
1982 a zero length name. */
1983 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
1984 return empty_unibyte_string
;
1986 switch (sa
->sa_family
)
1990 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
1991 len
= sizeof (sin
->sin_addr
) + 1;
1992 address
= Fmake_vector (make_number (len
), Qnil
);
1993 p
= XVECTOR (address
);
1994 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
1995 cp
= (unsigned char *) &sin
->sin_addr
;
2001 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2002 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2003 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2004 address
= Fmake_vector (make_number (len
), Qnil
);
2005 p
= XVECTOR (address
);
2006 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2007 for (i
= 0; i
< len
; i
++)
2008 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2012 #ifdef HAVE_LOCAL_SOCKETS
2015 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2016 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2017 /* If the first byte is NUL, the name is a Linux abstract
2018 socket name, and the name can contain embedded NULs. If
2019 it's not, we have a NUL-terminated string. Be careful not
2020 to walk past the end of the object looking for the name
2021 terminator, however. */
2022 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2024 const char* terminator
=
2025 memchr (sockun
->sun_path
, '\0', name_length
);
2028 name_length
= terminator
- (const char*) sockun
->sun_path
;
2031 return make_unibyte_string (sockun
->sun_path
, name_length
);
2035 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2036 address
= Fcons (make_number (sa
->sa_family
),
2037 Fmake_vector (make_number (len
), Qnil
));
2038 p
= XVECTOR (XCDR (address
));
2039 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2045 p
->contents
[i
++] = make_number (*cp
++);
2051 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2054 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2056 register struct Lisp_Vector
*p
;
2058 if (VECTORP (address
))
2060 p
= XVECTOR (address
);
2061 if (p
->header
.size
== 5)
2064 return sizeof (struct sockaddr_in
);
2067 else if (p
->header
.size
== 9)
2069 *familyp
= AF_INET6
;
2070 return sizeof (struct sockaddr_in6
);
2074 #ifdef HAVE_LOCAL_SOCKETS
2075 else if (STRINGP (address
))
2077 *familyp
= AF_LOCAL
;
2078 return sizeof (struct sockaddr_un
);
2081 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2082 && VECTORP (XCDR (address
)))
2084 struct sockaddr
*sa
;
2085 *familyp
= XINT (XCAR (address
));
2086 p
= XVECTOR (XCDR (address
));
2087 return p
->header
.size
+ sizeof (sa
->sa_family
);
2092 /* Convert an address object (vector or string) to an internal sockaddr.
2094 The address format has been basically validated by
2095 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2096 it could have come from user data. So if FAMILY is not valid,
2097 we return after zeroing *SA. */
2100 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2102 register struct Lisp_Vector
*p
;
2103 register unsigned char *cp
= NULL
;
2107 memset (sa
, 0, len
);
2109 if (VECTORP (address
))
2111 p
= XVECTOR (address
);
2112 if (family
== AF_INET
)
2114 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2115 len
= sizeof (sin
->sin_addr
) + 1;
2116 hostport
= XINT (p
->contents
[--len
]);
2117 sin
->sin_port
= htons (hostport
);
2118 cp
= (unsigned char *)&sin
->sin_addr
;
2119 sa
->sa_family
= family
;
2122 else if (family
== AF_INET6
)
2124 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2125 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2126 len
= sizeof (sin6
->sin6_addr
) + 1;
2127 hostport
= XINT (p
->contents
[--len
]);
2128 sin6
->sin6_port
= htons (hostport
);
2129 for (i
= 0; i
< len
; i
++)
2130 if (INTEGERP (p
->contents
[i
]))
2132 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2135 sa
->sa_family
= family
;
2142 else if (STRINGP (address
))
2144 #ifdef HAVE_LOCAL_SOCKETS
2145 if (family
== AF_LOCAL
)
2147 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2148 cp
= SDATA (address
);
2149 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2150 sockun
->sun_path
[i
] = *cp
++;
2151 sa
->sa_family
= family
;
2158 p
= XVECTOR (XCDR (address
));
2159 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2162 for (i
= 0; i
< len
; i
++)
2163 if (INTEGERP (p
->contents
[i
]))
2164 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2167 #ifdef DATAGRAM_SOCKETS
2168 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2170 doc
: /* Get the current datagram address associated with PROCESS. */)
2171 (Lisp_Object process
)
2175 CHECK_PROCESS (process
);
2177 if (!DATAGRAM_CONN_P (process
))
2180 channel
= XPROCESS (process
)->infd
;
2181 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2182 datagram_address
[channel
].len
);
2185 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2187 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2188 Returns nil upon error setting address, ADDRESS otherwise. */)
2189 (Lisp_Object process
, Lisp_Object address
)
2194 CHECK_PROCESS (process
);
2196 if (!DATAGRAM_CONN_P (process
))
2199 channel
= XPROCESS (process
)->infd
;
2201 len
= get_lisp_to_sockaddr_size (address
, &family
);
2202 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2204 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2210 static const struct socket_options
{
2211 /* The name of this option. Should be lowercase version of option
2212 name without SO_ prefix. */
2214 /* Option level SOL_... */
2216 /* Option number SO_... */
2218 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2219 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2220 } socket_options
[] =
2222 #ifdef SO_BINDTODEVICE
2223 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2226 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2229 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2232 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2235 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2238 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2241 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2244 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2246 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2249 /* Set option OPT to value VAL on socket S.
2251 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2252 Signals an error if setting a known option fails.
2256 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2259 const struct socket_options
*sopt
;
2264 name
= SSDATA (SYMBOL_NAME (opt
));
2265 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2266 if (strcmp (name
, sopt
->name
) == 0)
2269 switch (sopt
->opttype
)
2274 optval
= NILP (val
) ? 0 : 1;
2275 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2276 &optval
, sizeof (optval
));
2283 if (TYPE_RANGED_INTEGERP (int, val
))
2284 optval
= XINT (val
);
2286 error ("Bad option value for %s", name
);
2287 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2288 &optval
, sizeof (optval
));
2292 #ifdef SO_BINDTODEVICE
2295 char devname
[IFNAMSIZ
+1];
2297 /* This is broken, at least in the Linux 2.4 kernel.
2298 To unbind, the arg must be a zero integer, not the empty string.
2299 This should work on all systems. KFS. 2003-09-23. */
2300 memset (devname
, 0, sizeof devname
);
2303 char *arg
= SSDATA (val
);
2304 int len
= min (strlen (arg
), IFNAMSIZ
);
2305 memcpy (devname
, arg
, len
);
2307 else if (!NILP (val
))
2308 error ("Bad option value for %s", name
);
2309 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2318 struct linger linger
;
2321 linger
.l_linger
= 0;
2322 if (TYPE_RANGED_INTEGERP (int, val
))
2323 linger
.l_linger
= XINT (val
);
2325 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2326 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2327 &linger
, sizeof (linger
));
2338 int setsockopt_errno
= errno
;
2339 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2343 return (1 << sopt
->optbit
);
2347 DEFUN ("set-network-process-option",
2348 Fset_network_process_option
, Sset_network_process_option
,
2350 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2351 See `make-network-process' for a list of options and values.
2352 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2353 OPTION is not a supported option, return nil instead; otherwise return t. */)
2354 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2357 struct Lisp_Process
*p
;
2359 CHECK_PROCESS (process
);
2360 p
= XPROCESS (process
);
2361 if (!NETCONN1_P (p
))
2362 error ("Process is not a network process");
2366 error ("Process is not running");
2368 if (set_socket_option (s
, option
, value
))
2370 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2374 if (NILP (no_error
))
2375 error ("Unknown or unsupported option");
2381 DEFUN ("serial-process-configure",
2382 Fserial_process_configure
,
2383 Sserial_process_configure
,
2385 doc
: /* Configure speed, bytesize, etc. of a serial process.
2387 Arguments are specified as keyword/argument pairs. Attributes that
2388 are not given are re-initialized from the process's current
2389 configuration (available via the function `process-contact') or set to
2390 reasonable default values. The following arguments are defined:
2396 -- Any of these arguments can be given to identify the process that is
2397 to be configured. If none of these arguments is given, the current
2398 buffer's process is used.
2400 :speed SPEED -- SPEED is the speed of the serial port in bits per
2401 second, also called baud rate. Any value can be given for SPEED, but
2402 most serial ports work only at a few defined values between 1200 and
2403 115200, with 9600 being the most common value. If SPEED is nil, the
2404 serial port is not configured any further, i.e., all other arguments
2405 are ignored. This may be useful for special serial ports such as
2406 Bluetooth-to-serial converters which can only be configured through AT
2407 commands. A value of nil for SPEED can be used only when passed
2408 through `make-serial-process' or `serial-term'.
2410 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2411 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2413 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2414 `odd' (use odd parity), or the symbol `even' (use even parity). If
2415 PARITY is not given, no parity is used.
2417 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2418 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2419 is not given or nil, 1 stopbit is used.
2421 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2422 flowcontrol to be used, which is either nil (don't use flowcontrol),
2423 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2424 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2425 flowcontrol is used.
2427 `serial-process-configure' is called by `make-serial-process' for the
2428 initial configuration of the serial port.
2432 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2434 \(serial-process-configure
2435 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2437 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2439 usage: (serial-process-configure &rest ARGS) */)
2440 (ptrdiff_t nargs
, Lisp_Object
*args
)
2442 struct Lisp_Process
*p
;
2443 Lisp_Object contact
= Qnil
;
2444 Lisp_Object proc
= Qnil
;
2445 struct gcpro gcpro1
;
2447 contact
= Flist (nargs
, args
);
2450 proc
= Fplist_get (contact
, QCprocess
);
2452 proc
= Fplist_get (contact
, QCname
);
2454 proc
= Fplist_get (contact
, QCbuffer
);
2456 proc
= Fplist_get (contact
, QCport
);
2457 proc
= get_process (proc
);
2458 p
= XPROCESS (proc
);
2459 if (!EQ (p
->type
, Qserial
))
2460 error ("Not a serial process");
2462 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2468 serial_configure (p
, contact
);
2474 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2476 doc
: /* Create and return a serial port process.
2478 In Emacs, serial port connections are represented by process objects,
2479 so input and output work as for subprocesses, and `delete-process'
2480 closes a serial port connection. However, a serial process has no
2481 process id, it cannot be signaled, and the status codes are different
2482 from normal processes.
2484 `make-serial-process' creates a process and a buffer, on which you
2485 probably want to use `process-send-string'. Try \\[serial-term] for
2486 an interactive terminal. See below for examples.
2488 Arguments are specified as keyword/argument pairs. The following
2489 arguments are defined:
2491 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2492 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2493 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2494 the backslashes in strings).
2496 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2497 which this function calls.
2499 :name NAME -- NAME is the name of the process. If NAME is not given,
2500 the value of PORT is used.
2502 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2503 with the process. Process output goes at the end of that buffer,
2504 unless you specify an output stream or filter function to handle the
2505 output. If BUFFER is not given, the value of NAME is used.
2507 :coding CODING -- If CODING is a symbol, it specifies the coding
2508 system used for both reading and writing for this process. If CODING
2509 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2510 ENCODING is used for writing.
2512 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2513 the process is running. If BOOL is not given, query before exiting.
2515 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2516 In the stopped state, a serial process does not accept incoming data,
2517 but you can send outgoing data. The stopped state is cleared by
2518 `continue-process' and set by `stop-process'.
2520 :filter FILTER -- Install FILTER as the process filter.
2522 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2524 :plist PLIST -- Install PLIST as the initial plist of the process.
2530 -- This function calls `serial-process-configure' to handle these
2533 The original argument list, possibly modified by later configuration,
2534 is available via the function `process-contact'.
2538 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2540 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2542 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2544 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2546 usage: (make-serial-process &rest ARGS) */)
2547 (ptrdiff_t nargs
, Lisp_Object
*args
)
2550 Lisp_Object proc
, contact
, port
;
2551 struct Lisp_Process
*p
;
2552 struct gcpro gcpro1
;
2553 Lisp_Object name
, buffer
;
2554 Lisp_Object tem
, val
;
2555 ptrdiff_t specpdl_count
;
2560 contact
= Flist (nargs
, args
);
2563 port
= Fplist_get (contact
, QCport
);
2565 error ("No port specified");
2566 CHECK_STRING (port
);
2568 if (NILP (Fplist_member (contact
, QCspeed
)))
2569 error (":speed not specified");
2570 if (!NILP (Fplist_get (contact
, QCspeed
)))
2571 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2573 name
= Fplist_get (contact
, QCname
);
2576 CHECK_STRING (name
);
2577 proc
= make_process (name
);
2578 specpdl_count
= SPECPDL_INDEX ();
2579 record_unwind_protect (remove_process
, proc
);
2580 p
= XPROCESS (proc
);
2582 fd
= serial_open (port
);
2583 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2586 if (fd
> max_process_desc
)
2587 max_process_desc
= fd
;
2588 chan_process
[fd
] = proc
;
2590 buffer
= Fplist_get (contact
, QCbuffer
);
2593 buffer
= Fget_buffer_create (buffer
);
2594 pset_buffer (p
, buffer
);
2596 pset_childp (p
, contact
);
2597 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2598 pset_type (p
, Qserial
);
2599 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2600 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2602 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2603 p
->kill_without_query
= 1;
2604 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2605 pset_command (p
, Qt
);
2606 eassert (! p
->pty_flag
);
2608 if (!EQ (p
->command
, Qt
))
2610 FD_SET (fd
, &input_wait_mask
);
2611 FD_SET (fd
, &non_keyboard_wait_mask
);
2614 if (BUFFERP (buffer
))
2616 set_marker_both (p
->mark
, buffer
,
2617 BUF_ZV (XBUFFER (buffer
)),
2618 BUF_ZV_BYTE (XBUFFER (buffer
)));
2621 tem
= Fplist_member (contact
, QCcoding
);
2622 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2628 val
= XCAR (XCDR (tem
));
2632 else if (!NILP (Vcoding_system_for_read
))
2633 val
= Vcoding_system_for_read
;
2634 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2635 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2637 pset_decode_coding_system (p
, val
);
2642 val
= XCAR (XCDR (tem
));
2646 else if (!NILP (Vcoding_system_for_write
))
2647 val
= Vcoding_system_for_write
;
2648 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2649 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2651 pset_encode_coding_system (p
, val
);
2653 setup_process_coding_systems (proc
);
2654 pset_decoding_buf (p
, empty_unibyte_string
);
2655 p
->decoding_carryover
= 0;
2656 pset_encoding_buf (p
, empty_unibyte_string
);
2657 p
->inherit_coding_system_flag
2658 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2660 Fserial_process_configure (nargs
, args
);
2662 specpdl_ptr
= specpdl
+ specpdl_count
;
2668 /* Create a network stream/datagram client/server process. Treated
2669 exactly like a normal process when reading and writing. Primary
2670 differences are in status display and process deletion. A network
2671 connection has no PID; you cannot signal it. All you can do is
2672 stop/continue it and deactivate/close it via delete-process */
2674 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2676 doc
: /* Create and return a network server or client process.
2678 In Emacs, network connections are represented by process objects, so
2679 input and output work as for subprocesses and `delete-process' closes
2680 a network connection. However, a network process has no process id,
2681 it cannot be signaled, and the status codes are different from normal
2684 Arguments are specified as keyword/argument pairs. The following
2685 arguments are defined:
2687 :name NAME -- NAME is name for process. It is modified if necessary
2690 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2691 with the process. Process output goes at end of that buffer, unless
2692 you specify an output stream or filter function to handle the output.
2693 BUFFER may be also nil, meaning that this process is not associated
2696 :host HOST -- HOST is name of the host to connect to, or its IP
2697 address. The symbol `local' specifies the local host. If specified
2698 for a server process, it must be a valid name or address for the local
2699 host, and only clients connecting to that address will be accepted.
2701 :service SERVICE -- SERVICE is name of the service desired, or an
2702 integer specifying a port number to connect to. If SERVICE is t,
2703 a random port number is selected for the server. (If Emacs was
2704 compiled with getaddrinfo, a port number can also be specified as a
2705 string, e.g. "80", as well as an integer. This is not portable.)
2707 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2708 stream type connection, `datagram' creates a datagram type connection,
2709 `seqpacket' creates a reliable datagram connection.
2711 :family FAMILY -- FAMILY is the address (and protocol) family for the
2712 service specified by HOST and SERVICE. The default (nil) is to use
2713 whatever address family (IPv4 or IPv6) that is defined for the host
2714 and port number specified by HOST and SERVICE. Other address families
2716 local -- for a local (i.e. UNIX) address specified by SERVICE.
2717 ipv4 -- use IPv4 address family only.
2718 ipv6 -- use IPv6 address family only.
2720 :local ADDRESS -- ADDRESS is the local address used for the connection.
2721 This parameter is ignored when opening a client process. When specified
2722 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2724 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2725 connection. This parameter is ignored when opening a stream server
2726 process. For a datagram server process, it specifies the initial
2727 setting of the remote datagram address. When specified for a client
2728 process, the FAMILY, HOST, and SERVICE args are ignored.
2730 The format of ADDRESS depends on the address family:
2731 - An IPv4 address is represented as an vector of integers [A B C D P]
2732 corresponding to numeric IP address A.B.C.D and port number P.
2733 - A local address is represented as a string with the address in the
2734 local address space.
2735 - An "unsupported family" address is represented by a cons (F . AV)
2736 where F is the family number and AV is a vector containing the socket
2737 address data with one element per address data byte. Do not rely on
2738 this format in portable code, as it may depend on implementation
2739 defined constants, data sizes, and data structure alignment.
2741 :coding CODING -- If CODING is a symbol, it specifies the coding
2742 system used for both reading and writing for this process. If CODING
2743 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2744 ENCODING is used for writing.
2746 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2747 return without waiting for the connection to complete; instead, the
2748 sentinel function will be called with second arg matching "open" (if
2749 successful) or "failed" when the connect completes. Default is to use
2750 a blocking connect (i.e. wait) for stream type connections.
2752 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2753 running when Emacs is exited.
2755 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2756 In the stopped state, a server process does not accept new
2757 connections, and a client process does not handle incoming traffic.
2758 The stopped state is cleared by `continue-process' and set by
2761 :filter FILTER -- Install FILTER as the process filter.
2763 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2764 process filter are multibyte, otherwise they are unibyte.
2765 If this keyword is not specified, the strings are multibyte if
2766 the default value of `enable-multibyte-characters' is non-nil.
2768 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2770 :log LOG -- Install LOG as the server process log function. This
2771 function is called when the server accepts a network connection from a
2772 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2773 is the server process, CLIENT is the new process for the connection,
2774 and MESSAGE is a string.
2776 :plist PLIST -- Install PLIST as the new process's initial plist.
2778 :server QLEN -- if QLEN is non-nil, create a server process for the
2779 specified FAMILY, SERVICE, and connection type (stream or datagram).
2780 If QLEN is an integer, it is used as the max. length of the server's
2781 pending connection queue (also known as the backlog); the default
2782 queue length is 5. Default is to create a client process.
2784 The following network options can be specified for this connection:
2786 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2787 :dontroute BOOL -- Only send to directly connected hosts.
2788 :keepalive BOOL -- Send keep-alive messages on network stream.
2789 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2790 :oobinline BOOL -- Place out-of-band data in receive data stream.
2791 :priority INT -- Set protocol defined priority for sent packets.
2792 :reuseaddr BOOL -- Allow reusing a recently used local address
2793 (this is allowed by default for a server process).
2794 :bindtodevice NAME -- bind to interface NAME. Using this may require
2795 special privileges on some systems.
2797 Consult the relevant system programmer's manual pages for more
2798 information on using these options.
2801 A server process will listen for and accept connections from clients.
2802 When a client connection is accepted, a new network process is created
2803 for the connection with the following parameters:
2805 - The client's process name is constructed by concatenating the server
2806 process's NAME and a client identification string.
2807 - If the FILTER argument is non-nil, the client process will not get a
2808 separate process buffer; otherwise, the client's process buffer is a newly
2809 created buffer named after the server process's BUFFER name or process
2810 NAME concatenated with the client identification string.
2811 - The connection type and the process filter and sentinel parameters are
2812 inherited from the server process's TYPE, FILTER and SENTINEL.
2813 - The client process's contact info is set according to the client's
2814 addressing information (typically an IP address and a port number).
2815 - The client process's plist is initialized from the server's plist.
2817 Notice that the FILTER and SENTINEL args are never used directly by
2818 the server process. Also, the BUFFER argument is not used directly by
2819 the server process, but via the optional :log function, accepted (and
2820 failed) connections may be logged in the server process's buffer.
2822 The original argument list, modified with the actual connection
2823 information, is available via the `process-contact' function.
2825 usage: (make-network-process &rest ARGS) */)
2826 (ptrdiff_t nargs
, Lisp_Object
*args
)
2829 Lisp_Object contact
;
2830 struct Lisp_Process
*p
;
2831 #ifdef HAVE_GETADDRINFO
2832 struct addrinfo ai
, *res
, *lres
;
2833 struct addrinfo hints
;
2834 const char *portstring
;
2836 #else /* HAVE_GETADDRINFO */
2837 struct _emacs_addrinfo
2843 struct sockaddr
*ai_addr
;
2844 struct _emacs_addrinfo
*ai_next
;
2846 #endif /* HAVE_GETADDRINFO */
2847 struct sockaddr_in address_in
;
2848 #ifdef HAVE_LOCAL_SOCKETS
2849 struct sockaddr_un address_un
;
2854 int s
= -1, outch
, inch
;
2855 struct gcpro gcpro1
;
2856 ptrdiff_t count
= SPECPDL_INDEX ();
2858 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
2860 Lisp_Object name
, buffer
, host
, service
, address
;
2861 Lisp_Object filter
, sentinel
;
2862 bool is_non_blocking_client
= 0;
2871 /* Save arguments for process-contact and clone-process. */
2872 contact
= Flist (nargs
, args
);
2876 /* Ensure socket support is loaded if available. */
2877 init_winsock (TRUE
);
2880 /* :type TYPE (nil: stream, datagram */
2881 tem
= Fplist_get (contact
, QCtype
);
2883 socktype
= SOCK_STREAM
;
2884 #ifdef DATAGRAM_SOCKETS
2885 else if (EQ (tem
, Qdatagram
))
2886 socktype
= SOCK_DGRAM
;
2888 #ifdef HAVE_SEQPACKET
2889 else if (EQ (tem
, Qseqpacket
))
2890 socktype
= SOCK_SEQPACKET
;
2893 error ("Unsupported connection type");
2896 tem
= Fplist_get (contact
, QCserver
);
2899 /* Don't support network sockets when non-blocking mode is
2900 not available, since a blocked Emacs is not useful. */
2902 if (TYPE_RANGED_INTEGERP (int, tem
))
2903 backlog
= XINT (tem
);
2906 /* Make QCaddress an alias for :local (server) or :remote (client). */
2907 QCaddress
= is_server
? QClocal
: QCremote
;
2910 if (!is_server
&& socktype
!= SOCK_DGRAM
2911 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2913 #ifndef NON_BLOCKING_CONNECT
2914 error ("Non-blocking connect not supported");
2916 is_non_blocking_client
= 1;
2920 name
= Fplist_get (contact
, QCname
);
2921 buffer
= Fplist_get (contact
, QCbuffer
);
2922 filter
= Fplist_get (contact
, QCfilter
);
2923 sentinel
= Fplist_get (contact
, QCsentinel
);
2925 CHECK_STRING (name
);
2927 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2928 ai
.ai_socktype
= socktype
;
2933 /* :local ADDRESS or :remote ADDRESS */
2934 address
= Fplist_get (contact
, QCaddress
);
2935 if (!NILP (address
))
2937 host
= service
= Qnil
;
2939 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2940 error ("Malformed :address");
2941 ai
.ai_family
= family
;
2942 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2943 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
2947 /* :family FAMILY -- nil (for Inet), local, or integer. */
2948 tem
= Fplist_get (contact
, QCfamily
);
2951 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2957 #ifdef HAVE_LOCAL_SOCKETS
2958 else if (EQ (tem
, Qlocal
))
2962 else if (EQ (tem
, Qipv6
))
2965 else if (EQ (tem
, Qipv4
))
2967 else if (TYPE_RANGED_INTEGERP (int, tem
))
2968 family
= XINT (tem
);
2970 error ("Unknown address family");
2972 ai
.ai_family
= family
;
2974 /* :service SERVICE -- string, integer (port number), or t (random port). */
2975 service
= Fplist_get (contact
, QCservice
);
2977 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2978 host
= Fplist_get (contact
, QChost
);
2981 if (EQ (host
, Qlocal
))
2982 /* Depending on setup, "localhost" may map to different IPv4 and/or
2983 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2984 host
= build_string ("127.0.0.1");
2985 CHECK_STRING (host
);
2988 #ifdef HAVE_LOCAL_SOCKETS
2989 if (family
== AF_LOCAL
)
2993 message (":family local ignores the :host \"%s\" property",
2995 contact
= Fplist_put (contact
, QChost
, Qnil
);
2998 CHECK_STRING (service
);
2999 memset (&address_un
, 0, sizeof address_un
);
3000 address_un
.sun_family
= AF_LOCAL
;
3001 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3002 error ("Service name too long");
3003 strcpy (address_un
.sun_path
, SSDATA (service
));
3004 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3005 ai
.ai_addrlen
= sizeof address_un
;
3010 /* Slow down polling to every ten seconds.
3011 Some kernels have a bug which causes retrying connect to fail
3012 after a connect. Polling can interfere with gethostbyname too. */
3013 #ifdef POLL_FOR_INPUT
3014 if (socktype
!= SOCK_DGRAM
)
3016 record_unwind_protect_void (run_all_atimers
);
3017 bind_polling_period (10);
3021 #ifdef HAVE_GETADDRINFO
3022 /* If we have a host, use getaddrinfo to resolve both host and service.
3023 Otherwise, use getservbyname to lookup the service. */
3027 /* SERVICE can either be a string or int.
3028 Convert to a C string for later use by getaddrinfo. */
3029 if (EQ (service
, Qt
))
3031 else if (INTEGERP (service
))
3033 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3034 portstring
= portbuf
;
3038 CHECK_STRING (service
);
3039 portstring
= SSDATA (service
);
3044 memset (&hints
, 0, sizeof (hints
));
3046 hints
.ai_family
= family
;
3047 hints
.ai_socktype
= socktype
;
3048 hints
.ai_protocol
= 0;
3050 #ifdef HAVE_RES_INIT
3054 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3056 #ifdef HAVE_GAI_STRERROR
3057 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3059 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3065 #endif /* HAVE_GETADDRINFO */
3067 /* We end up here if getaddrinfo is not defined, or in case no hostname
3068 has been specified (e.g. for a local server process). */
3070 if (EQ (service
, Qt
))
3072 else if (INTEGERP (service
))
3073 port
= htons ((unsigned short) XINT (service
));
3076 struct servent
*svc_info
;
3077 CHECK_STRING (service
);
3078 svc_info
= getservbyname (SSDATA (service
),
3079 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3081 error ("Unknown service: %s", SDATA (service
));
3082 port
= svc_info
->s_port
;
3085 memset (&address_in
, 0, sizeof address_in
);
3086 address_in
.sin_family
= family
;
3087 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3088 address_in
.sin_port
= port
;
3090 #ifndef HAVE_GETADDRINFO
3093 struct hostent
*host_info_ptr
;
3095 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3096 as it may `hang' Emacs for a very long time. */
3100 #ifdef HAVE_RES_INIT
3104 host_info_ptr
= gethostbyname (SDATA (host
));
3109 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3110 host_info_ptr
->h_length
);
3111 family
= host_info_ptr
->h_addrtype
;
3112 address_in
.sin_family
= family
;
3115 /* Attempt to interpret host as numeric inet address */
3117 unsigned long numeric_addr
;
3118 numeric_addr
= inet_addr (SSDATA (host
));
3119 if (numeric_addr
== -1)
3120 error ("Unknown host \"%s\"", SDATA (host
));
3122 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3123 sizeof (address_in
.sin_addr
));
3127 #endif /* not HAVE_GETADDRINFO */
3129 ai
.ai_family
= family
;
3130 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3131 ai
.ai_addrlen
= sizeof address_in
;
3135 /* Do this in case we never enter the for-loop below. */
3136 count1
= SPECPDL_INDEX ();
3139 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3148 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3156 #ifdef DATAGRAM_SOCKETS
3157 if (!is_server
&& socktype
== SOCK_DGRAM
)
3159 #endif /* DATAGRAM_SOCKETS */
3161 #ifdef NON_BLOCKING_CONNECT
3162 if (is_non_blocking_client
)
3164 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3175 /* Make us close S if quit. */
3176 record_unwind_protect_int (close_file_unwind
, s
);
3178 /* Parse network options in the arg list.
3179 We simply ignore anything which isn't a known option (including other keywords).
3180 An error is signaled if setting a known option fails. */
3181 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3182 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3186 /* Configure as a server socket. */
3188 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3189 explicit :reuseaddr key to override this. */
3190 #ifdef HAVE_LOCAL_SOCKETS
3191 if (family
!= AF_LOCAL
)
3193 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3196 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3197 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3200 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3201 report_file_error ("Cannot bind server socket", Qnil
);
3203 #ifdef HAVE_GETSOCKNAME
3204 if (EQ (service
, Qt
))
3206 struct sockaddr_in sa1
;
3207 socklen_t len1
= sizeof (sa1
);
3208 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3210 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3211 service
= make_number (ntohs (sa1
.sin_port
));
3212 contact
= Fplist_put (contact
, QCservice
, service
);
3217 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3218 report_file_error ("Cannot listen on server socket", Qnil
);
3226 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3229 if (ret
== 0 || xerrno
== EISCONN
)
3231 /* The unwind-protect will be discarded afterwards.
3232 Likewise for immediate_quit. */
3236 #ifdef NON_BLOCKING_CONNECT
3238 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3242 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3249 if (xerrno
== EINTR
)
3251 /* Unlike most other syscalls connect() cannot be called
3252 again. (That would return EALREADY.) The proper way to
3253 wait for completion is pselect(). */
3261 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3267 report_file_error ("Failed select", Qnil
);
3271 len
= sizeof xerrno
;
3272 eassert (FD_ISSET (s
, &fdset
));
3273 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3274 report_file_error ("Failed getsockopt", Qnil
);
3276 report_file_errno ("Failed connect", Qnil
, xerrno
);
3279 #endif /* !WINDOWSNT */
3283 /* Discard the unwind protect closing S. */
3284 specpdl_ptr
= specpdl
+ count1
;
3289 if (xerrno
== EINTR
)
3296 #ifdef DATAGRAM_SOCKETS
3297 if (socktype
== SOCK_DGRAM
)
3299 if (datagram_address
[s
].sa
)
3301 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3302 datagram_address
[s
].len
= lres
->ai_addrlen
;
3306 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3307 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3310 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3311 if (rlen
!= 0 && rfamily
== lres
->ai_family
3312 && rlen
== lres
->ai_addrlen
)
3313 conv_lisp_to_sockaddr (rfamily
, remote
,
3314 datagram_address
[s
].sa
, rlen
);
3318 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3321 contact
= Fplist_put (contact
, QCaddress
,
3322 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3323 #ifdef HAVE_GETSOCKNAME
3326 struct sockaddr_in sa1
;
3327 socklen_t len1
= sizeof (sa1
);
3328 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3329 contact
= Fplist_put (contact
, QClocal
,
3330 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3337 #ifdef HAVE_GETADDRINFO
3348 /* If non-blocking got this far - and failed - assume non-blocking is
3349 not supported after all. This is probably a wrong assumption, but
3350 the normal blocking calls to open-network-stream handles this error
3352 if (is_non_blocking_client
)
3355 report_file_errno ((is_server
3356 ? "make server process failed"
3357 : "make client process failed"),
3365 buffer
= Fget_buffer_create (buffer
);
3366 proc
= make_process (name
);
3368 chan_process
[inch
] = proc
;
3370 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3372 p
= XPROCESS (proc
);
3374 pset_childp (p
, contact
);
3375 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3376 pset_type (p
, Qnetwork
);
3378 pset_buffer (p
, buffer
);
3379 pset_sentinel (p
, sentinel
);
3380 pset_filter (p
, filter
);
3381 pset_log (p
, Fplist_get (contact
, QClog
));
3382 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3383 p
->kill_without_query
= 1;
3384 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3385 pset_command (p
, Qt
);
3388 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3392 /* Discard the unwind protect for closing S, if any. */
3393 specpdl_ptr
= specpdl
+ count1
;
3395 /* Unwind bind_polling_period and request_sigio. */
3396 unbind_to (count
, Qnil
);
3398 if (is_server
&& socktype
!= SOCK_DGRAM
)
3399 pset_status (p
, Qlisten
);
3401 /* Make the process marker point into the process buffer (if any). */
3402 if (BUFFERP (buffer
))
3403 set_marker_both (p
->mark
, buffer
,
3404 BUF_ZV (XBUFFER (buffer
)),
3405 BUF_ZV_BYTE (XBUFFER (buffer
)));
3407 #ifdef NON_BLOCKING_CONNECT
3408 if (is_non_blocking_client
)
3410 /* We may get here if connect did succeed immediately. However,
3411 in that case, we still need to signal this like a non-blocking
3413 pset_status (p
, Qconnect
);
3414 if (!FD_ISSET (inch
, &connect_wait_mask
))
3416 FD_SET (inch
, &connect_wait_mask
);
3417 FD_SET (inch
, &write_mask
);
3418 num_pending_connects
++;
3423 /* A server may have a client filter setting of Qt, but it must
3424 still listen for incoming connects unless it is stopped. */
3425 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3426 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3428 FD_SET (inch
, &input_wait_mask
);
3429 FD_SET (inch
, &non_keyboard_wait_mask
);
3432 if (inch
> max_process_desc
)
3433 max_process_desc
= inch
;
3435 tem
= Fplist_member (contact
, QCcoding
);
3436 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3437 tem
= Qnil
; /* No error message (too late!). */
3440 /* Setup coding systems for communicating with the network stream. */
3441 struct gcpro gcpro1
;
3442 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3443 Lisp_Object coding_systems
= Qt
;
3444 Lisp_Object fargs
[5], val
;
3448 val
= XCAR (XCDR (tem
));
3452 else if (!NILP (Vcoding_system_for_read
))
3453 val
= Vcoding_system_for_read
;
3454 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3455 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3456 /* We dare not decode end-of-line format by setting VAL to
3457 Qraw_text, because the existing Emacs Lisp libraries
3458 assume that they receive bare code including a sequence of
3463 if (NILP (host
) || NILP (service
))
3464 coding_systems
= Qnil
;
3467 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3468 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3470 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3473 if (CONSP (coding_systems
))
3474 val
= XCAR (coding_systems
);
3475 else if (CONSP (Vdefault_process_coding_system
))
3476 val
= XCAR (Vdefault_process_coding_system
);
3480 pset_decode_coding_system (p
, val
);
3484 val
= XCAR (XCDR (tem
));
3488 else if (!NILP (Vcoding_system_for_write
))
3489 val
= Vcoding_system_for_write
;
3490 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3494 if (EQ (coding_systems
, Qt
))
3496 if (NILP (host
) || NILP (service
))
3497 coding_systems
= Qnil
;
3500 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3501 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3503 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3507 if (CONSP (coding_systems
))
3508 val
= XCDR (coding_systems
);
3509 else if (CONSP (Vdefault_process_coding_system
))
3510 val
= XCDR (Vdefault_process_coding_system
);
3514 pset_encode_coding_system (p
, val
);
3516 setup_process_coding_systems (proc
);
3518 pset_decoding_buf (p
, empty_unibyte_string
);
3519 p
->decoding_carryover
= 0;
3520 pset_encoding_buf (p
, empty_unibyte_string
);
3522 p
->inherit_coding_system_flag
3523 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3530 #ifdef HAVE_NET_IF_H
3534 network_interface_list (void)
3536 struct ifconf ifconf
;
3537 struct ifreq
*ifreq
;
3539 ptrdiff_t buf_size
= 512;
3544 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3547 count
= SPECPDL_INDEX ();
3548 record_unwind_protect_int (close_file_unwind
, s
);
3552 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3553 ifconf
.ifc_buf
= buf
;
3554 ifconf
.ifc_len
= buf_size
;
3555 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3562 while (ifconf
.ifc_len
== buf_size
);
3564 res
= unbind_to (count
, Qnil
);
3565 ifreq
= ifconf
.ifc_req
;
3566 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3568 struct ifreq
*ifq
= ifreq
;
3569 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3570 #define SIZEOF_IFREQ(sif) \
3571 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3572 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3574 int len
= SIZEOF_IFREQ (ifq
);
3576 int len
= sizeof (*ifreq
);
3578 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3579 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3581 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3584 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3585 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3586 res
= Fcons (Fcons (build_string (namebuf
),
3587 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3588 sizeof (struct sockaddr
))),
3595 #endif /* SIOCGIFCONF */
3597 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3601 const char *flag_sym
;
3604 static const struct ifflag_def ifflag_table
[] = {
3608 #ifdef IFF_BROADCAST
3609 { IFF_BROADCAST
, "broadcast" },
3612 { IFF_DEBUG
, "debug" },
3615 { IFF_LOOPBACK
, "loopback" },
3617 #ifdef IFF_POINTOPOINT
3618 { IFF_POINTOPOINT
, "pointopoint" },
3621 { IFF_RUNNING
, "running" },
3624 { IFF_NOARP
, "noarp" },
3627 { IFF_PROMISC
, "promisc" },
3629 #ifdef IFF_NOTRAILERS
3630 #ifdef NS_IMPL_COCOA
3631 /* Really means smart, notrailers is obsolete */
3632 { IFF_NOTRAILERS
, "smart" },
3634 { IFF_NOTRAILERS
, "notrailers" },
3638 { IFF_ALLMULTI
, "allmulti" },
3641 { IFF_MASTER
, "master" },
3644 { IFF_SLAVE
, "slave" },
3646 #ifdef IFF_MULTICAST
3647 { IFF_MULTICAST
, "multicast" },
3650 { IFF_PORTSEL
, "portsel" },
3652 #ifdef IFF_AUTOMEDIA
3653 { IFF_AUTOMEDIA
, "automedia" },
3656 { IFF_DYNAMIC
, "dynamic" },
3659 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3662 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3665 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3668 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3671 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3677 network_interface_info (Lisp_Object ifname
)
3680 Lisp_Object res
= Qnil
;
3685 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3686 && defined HAVE_GETIFADDRS && defined LLADDR)
3687 struct ifaddrs
*ifap
;
3690 CHECK_STRING (ifname
);
3692 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3693 error ("interface name too long");
3694 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3696 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3699 count
= SPECPDL_INDEX ();
3700 record_unwind_protect_int (close_file_unwind
, s
);
3703 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3704 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3706 int flags
= rq
.ifr_flags
;
3707 const struct ifflag_def
*fp
;
3710 /* If flags is smaller than int (i.e. short) it may have the high bit set
3711 due to IFF_MULTICAST. In that case, sign extending it into
3713 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3714 flags
= (unsigned short) rq
.ifr_flags
;
3717 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3719 if (flags
& fp
->flag_bit
)
3721 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3722 flags
-= fp
->flag_bit
;
3725 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3729 elt
= Fcons (make_number (fnum
), elt
);
3734 res
= Fcons (elt
, res
);
3737 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3738 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3740 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3741 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3745 for (n
= 0; n
< 6; n
++)
3746 p
->contents
[n
] = make_number (((unsigned char *)
3747 &rq
.ifr_hwaddr
.sa_data
[0])
3749 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3751 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3752 if (getifaddrs (&ifap
) != -1)
3754 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3755 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3758 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3760 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3761 unsigned char linkaddr
[6];
3764 if (it
->ifa_addr
->sa_family
!= AF_LINK
3765 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3766 || sdl
->sdl_alen
!= 6)
3769 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3770 for (n
= 0; n
< 6; n
++)
3771 p
->contents
[n
] = make_number (linkaddr
[n
]);
3773 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3777 #ifdef HAVE_FREEIFADDRS
3781 #endif /* HAVE_GETIFADDRS && LLADDR */
3783 res
= Fcons (elt
, res
);
3786 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3787 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3790 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3791 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3793 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3797 res
= Fcons (elt
, res
);
3800 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3801 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3804 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3807 res
= Fcons (elt
, res
);
3810 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3811 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3814 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3817 res
= Fcons (elt
, res
);
3819 return unbind_to (count
, any
? res
: Qnil
);
3821 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3822 #endif /* defined (HAVE_NET_IF_H) */
3824 DEFUN ("network-interface-list", Fnetwork_interface_list
,
3825 Snetwork_interface_list
, 0, 0, 0,
3826 doc
: /* Return an alist of all network interfaces and their network address.
3827 Each element is a cons, the car of which is a string containing the
3828 interface name, and the cdr is the network address in internal
3829 format; see the description of ADDRESS in `make-network-process'.
3831 If the information is not available, return nil. */)
3834 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3835 return network_interface_list ();
3841 DEFUN ("network-interface-info", Fnetwork_interface_info
,
3842 Snetwork_interface_info
, 1, 1, 0,
3843 doc
: /* Return information about network interface named IFNAME.
3844 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3845 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3846 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3847 FLAGS is the current flags of the interface.
3849 Data that is unavailable is returned as nil. */)
3850 (Lisp_Object ifname
)
3852 #if ((defined HAVE_NET_IF_H \
3853 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3854 || defined SIOCGIFFLAGS)) \
3855 || defined WINDOWSNT)
3856 return network_interface_info (ifname
);
3863 /* Turn off input and output for process PROC. */
3866 deactivate_process (Lisp_Object proc
)
3869 struct Lisp_Process
*p
= XPROCESS (proc
);
3873 /* Delete GnuTLS structures in PROC, if any. */
3874 emacs_gnutls_deinit (proc
);
3875 #endif /* HAVE_GNUTLS */
3877 #ifdef ADAPTIVE_READ_BUFFERING
3878 if (p
->read_output_delay
> 0)
3880 if (--process_output_delay_count
< 0)
3881 process_output_delay_count
= 0;
3882 p
->read_output_delay
= 0;
3883 p
->read_output_skip
= 0;
3887 /* Beware SIGCHLD hereabouts. */
3889 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
3890 close_process_fd (&p
->open_fd
[i
]);
3892 inchannel
= p
->infd
;
3897 #ifdef DATAGRAM_SOCKETS
3898 if (DATAGRAM_CHAN_P (inchannel
))
3900 xfree (datagram_address
[inchannel
].sa
);
3901 datagram_address
[inchannel
].sa
= 0;
3902 datagram_address
[inchannel
].len
= 0;
3905 chan_process
[inchannel
] = Qnil
;
3906 FD_CLR (inchannel
, &input_wait_mask
);
3907 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3908 #ifdef NON_BLOCKING_CONNECT
3909 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3911 FD_CLR (inchannel
, &connect_wait_mask
);
3912 FD_CLR (inchannel
, &write_mask
);
3913 if (--num_pending_connects
< 0)
3917 if (inchannel
== max_process_desc
)
3919 /* We just closed the highest-numbered process input descriptor,
3920 so recompute the highest-numbered one now. */
3924 while (0 <= i
&& NILP (chan_process
[i
]));
3926 max_process_desc
= i
;
3932 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3934 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3935 It is given to their filter functions.
3936 Non-nil arg PROCESS means do not return until some output has been received
3939 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3940 and milliseconds to wait; return after that much time whether or not
3941 there is any subprocess output. If SECONDS is a floating point number,
3942 it specifies a fractional number of seconds to wait.
3943 The MILLISEC argument is obsolete and should be avoided.
3945 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3946 from PROCESS, suspending reading output from other processes.
3947 If JUST-THIS-ONE is an integer, don't run any timers either.
3948 Return non-nil if we received any output before the timeout expired. */)
3949 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
3954 if (! NILP (process
))
3955 CHECK_PROCESS (process
);
3957 just_this_one
= Qnil
;
3959 if (!NILP (millisec
))
3960 { /* Obsolete calling convention using integers rather than floats. */
3961 CHECK_NUMBER (millisec
);
3963 seconds
= make_float (XINT (millisec
) / 1000.0);
3966 CHECK_NUMBER (seconds
);
3967 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
3974 if (!NILP (seconds
))
3976 if (INTEGERP (seconds
))
3978 if (XINT (seconds
) > 0)
3980 secs
= XINT (seconds
);
3984 else if (FLOATP (seconds
))
3986 if (XFLOAT_DATA (seconds
) > 0)
3988 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
3989 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
3994 wrong_type_argument (Qnumberp
, seconds
);
3996 else if (! NILP (process
))
4000 (wait_reading_process_output (secs
, nsecs
, 0, 0,
4002 !NILP (process
) ? XPROCESS (process
) : NULL
,
4003 NILP (just_this_one
) ? 0 :
4004 !INTEGERP (just_this_one
) ? 1 : -1)
4008 /* Accept a connection for server process SERVER on CHANNEL. */
4010 static EMACS_INT connect_counter
= 0;
4013 server_accept_connection (Lisp_Object server
, int channel
)
4015 Lisp_Object proc
, caller
, name
, buffer
;
4016 Lisp_Object contact
, host
, service
;
4017 struct Lisp_Process
*ps
= XPROCESS (server
);
4018 struct Lisp_Process
*p
;
4022 struct sockaddr_in in
;
4024 struct sockaddr_in6 in6
;
4026 #ifdef HAVE_LOCAL_SOCKETS
4027 struct sockaddr_un un
;
4030 socklen_t len
= sizeof saddr
;
4033 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4042 if (code
== EWOULDBLOCK
)
4046 if (!NILP (ps
->log
))
4047 call3 (ps
->log
, server
, Qnil
,
4048 concat3 (build_string ("accept failed with code"),
4049 Fnumber_to_string (make_number (code
)),
4050 build_string ("\n")));
4054 count
= SPECPDL_INDEX ();
4055 record_unwind_protect_int (close_file_unwind
, s
);
4059 /* Setup a new process to handle the connection. */
4061 /* Generate a unique identification of the caller, and build contact
4062 information for this process. */
4065 switch (saddr
.sa
.sa_family
)
4069 Lisp_Object args
[5];
4070 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4071 args
[0] = build_string ("%d.%d.%d.%d");
4072 args
[1] = make_number (*ip
++);
4073 args
[2] = make_number (*ip
++);
4074 args
[3] = make_number (*ip
++);
4075 args
[4] = make_number (*ip
++);
4076 host
= Fformat (5, args
);
4077 service
= make_number (ntohs (saddr
.in
.sin_port
));
4079 args
[0] = build_string (" <%s:%d>");
4082 caller
= Fformat (3, args
);
4089 Lisp_Object args
[9];
4090 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4092 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4093 for (i
= 0; i
< 8; i
++)
4094 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4095 host
= Fformat (9, args
);
4096 service
= make_number (ntohs (saddr
.in
.sin_port
));
4098 args
[0] = build_string (" <[%s]:%d>");
4101 caller
= Fformat (3, args
);
4106 #ifdef HAVE_LOCAL_SOCKETS
4110 caller
= Fnumber_to_string (make_number (connect_counter
));
4111 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4115 /* Create a new buffer name for this process if it doesn't have a
4116 filter. The new buffer name is based on the buffer name or
4117 process name of the server process concatenated with the caller
4120 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4121 || EQ (ps
->filter
, Qt
)))
4125 buffer
= ps
->buffer
;
4127 buffer
= Fbuffer_name (buffer
);
4132 buffer
= concat2 (buffer
, caller
);
4133 buffer
= Fget_buffer_create (buffer
);
4137 /* Generate a unique name for the new server process. Combine the
4138 server process name with the caller identification. */
4140 name
= concat2 (ps
->name
, caller
);
4141 proc
= make_process (name
);
4143 chan_process
[s
] = proc
;
4145 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4147 p
= XPROCESS (proc
);
4149 /* Build new contact information for this setup. */
4150 contact
= Fcopy_sequence (ps
->childp
);
4151 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4152 contact
= Fplist_put (contact
, QChost
, host
);
4153 if (!NILP (service
))
4154 contact
= Fplist_put (contact
, QCservice
, service
);
4155 contact
= Fplist_put (contact
, QCremote
,
4156 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4157 #ifdef HAVE_GETSOCKNAME
4159 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4160 contact
= Fplist_put (contact
, QClocal
,
4161 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4164 pset_childp (p
, contact
);
4165 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4166 pset_type (p
, Qnetwork
);
4168 pset_buffer (p
, buffer
);
4169 pset_sentinel (p
, ps
->sentinel
);
4170 pset_filter (p
, ps
->filter
);
4171 pset_command (p
, Qnil
);
4174 /* Discard the unwind protect for closing S. */
4175 specpdl_ptr
= specpdl
+ count
;
4177 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4180 pset_status (p
, Qrun
);
4182 /* Client processes for accepted connections are not stopped initially. */
4183 if (!EQ (p
->filter
, Qt
))
4185 FD_SET (s
, &input_wait_mask
);
4186 FD_SET (s
, &non_keyboard_wait_mask
);
4189 if (s
> max_process_desc
)
4190 max_process_desc
= s
;
4192 /* Setup coding system for new process based on server process.
4193 This seems to be the proper thing to do, as the coding system
4194 of the new process should reflect the settings at the time the
4195 server socket was opened; not the current settings. */
4197 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4198 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4199 setup_process_coding_systems (proc
);
4201 pset_decoding_buf (p
, empty_unibyte_string
);
4202 p
->decoding_carryover
= 0;
4203 pset_encoding_buf (p
, empty_unibyte_string
);
4205 p
->inherit_coding_system_flag
4206 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4208 if (!NILP (ps
->log
))
4209 call3 (ps
->log
, server
, proc
,
4210 concat3 (build_string ("accept from "),
4211 (STRINGP (host
) ? host
: build_string ("-")),
4212 build_string ("\n")));
4214 exec_sentinel (proc
,
4215 concat3 (build_string ("open from "),
4216 (STRINGP (host
) ? host
: build_string ("-")),
4217 build_string ("\n")));
4220 /* This variable is different from waiting_for_input in keyboard.c.
4221 It is used to communicate to a lisp process-filter/sentinel (via the
4222 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4223 for user-input when that process-filter was called.
4224 waiting_for_input cannot be used as that is by definition 0 when
4225 lisp code is being evalled.
4226 This is also used in record_asynch_buffer_change.
4227 For that purpose, this must be 0
4228 when not inside wait_reading_process_output. */
4229 static int waiting_for_user_input_p
;
4232 wait_reading_process_output_unwind (int data
)
4234 waiting_for_user_input_p
= data
;
4237 /* This is here so breakpoints can be put on it. */
4239 wait_reading_process_output_1 (void)
4243 /* Read and dispose of subprocess output while waiting for timeout to
4244 elapse and/or keyboard input to be available.
4248 If negative, gobble data immediately available but don't wait for any.
4251 an additional duration to wait, measured in nanoseconds
4252 If TIME_LIMIT is zero, then:
4253 If NSECS == 0, there is no limit.
4254 If NSECS > 0, the timeout consists of NSECS only.
4255 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4258 0 to ignore keyboard input, or
4259 1 to return when input is available, or
4260 -1 meaning caller will actually read the input, so don't throw to
4261 the quit handler, or
4263 DO_DISPLAY means redisplay should be done to show subprocess
4264 output that arrives.
4266 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4267 (and gobble terminal input into the buffer if any arrives).
4269 If WAIT_PROC is specified, wait until something arrives from that
4270 process. The return value is true if we read some input from
4273 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4274 (suspending output from other processes). A negative value
4275 means don't run any timers either.
4277 If WAIT_PROC is specified, then the function returns true if we
4278 received input from that process before the timeout elapsed.
4279 Otherwise, return true if we received input from any process. */
4282 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4284 Lisp_Object wait_for_cell
,
4285 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4295 struct timespec timeout
, end_time
;
4296 int wait_channel
= -1;
4297 bool got_some_input
= 0;
4298 ptrdiff_t count
= SPECPDL_INDEX ();
4300 FD_ZERO (&Available
);
4303 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4304 && !(CONSP (wait_proc
->status
)
4305 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4306 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4308 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4309 if (wait_proc
!= NULL
)
4310 wait_channel
= wait_proc
->infd
;
4312 record_unwind_protect_int (wait_reading_process_output_unwind
,
4313 waiting_for_user_input_p
);
4314 waiting_for_user_input_p
= read_kbd
;
4321 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4322 time_limit
= TYPE_MAXIMUM (time_t);
4324 /* Since we may need to wait several times,
4325 compute the absolute time to return at. */
4326 if (time_limit
|| nsecs
> 0)
4328 timeout
= make_timespec (time_limit
, nsecs
);
4329 end_time
= timespec_add (current_timespec (), timeout
);
4334 bool timeout_reduced_for_timers
= 0;
4336 /* If calling from keyboard input, do not quit
4337 since we want to return C-g as an input character.
4338 Otherwise, do pending quit if requested. */
4341 else if (pending_signals
)
4342 process_pending_signals ();
4344 /* Exit now if the cell we're waiting for became non-nil. */
4345 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4348 /* Compute time from now till when time limit is up. */
4349 /* Exit if already run out. */
4352 /* A negative timeout means
4353 gobble output available now
4354 but don't wait at all. */
4356 timeout
= make_timespec (0, 0);
4358 else if (time_limit
|| nsecs
> 0)
4360 struct timespec now
= current_timespec ();
4361 if (timespec_cmp (end_time
, now
) <= 0)
4363 timeout
= timespec_sub (end_time
, now
);
4367 timeout
= make_timespec (100000, 0);
4370 /* Normally we run timers here.
4371 But not if wait_for_cell; in those cases,
4372 the wait is supposed to be short,
4373 and those callers cannot handle running arbitrary Lisp code here. */
4374 if (NILP (wait_for_cell
)
4375 && just_wait_proc
>= 0)
4377 struct timespec timer_delay
;
4381 unsigned old_timers_run
= timers_run
;
4382 struct buffer
*old_buffer
= current_buffer
;
4383 Lisp_Object old_window
= selected_window
;
4385 timer_delay
= timer_check ();
4387 /* If a timer has run, this might have changed buffers
4388 an alike. Make read_key_sequence aware of that. */
4389 if (timers_run
!= old_timers_run
4390 && (old_buffer
!= current_buffer
4391 || !EQ (old_window
, selected_window
))
4392 && waiting_for_user_input_p
== -1)
4393 record_asynch_buffer_change ();
4395 if (timers_run
!= old_timers_run
&& do_display
)
4396 /* We must retry, since a timer may have requeued itself
4397 and that could alter the time_delay. */
4398 redisplay_preserve_echo_area (9);
4402 while (!detect_input_pending ());
4404 /* If there is unread keyboard input, also return. */
4406 && requeued_events_pending_p ())
4409 /* A negative timeout means do not wait at all. */
4412 if (timespec_valid_p (timer_delay
))
4414 if (timespec_cmp (timer_delay
, timeout
) < 0)
4416 timeout
= timer_delay
;
4417 timeout_reduced_for_timers
= 1;
4422 /* This is so a breakpoint can be put here. */
4423 wait_reading_process_output_1 ();
4428 /* Cause C-g and alarm signals to take immediate action,
4429 and cause input available signals to zero out timeout.
4431 It is important that we do this before checking for process
4432 activity. If we get a SIGCHLD after the explicit checks for
4433 process activity, timeout is the only way we will know. */
4435 set_waiting_for_input (&timeout
);
4437 /* If status of something has changed, and no input is
4438 available, notify the user of the change right away. After
4439 this explicit check, we'll let the SIGCHLD handler zap
4440 timeout to get our attention. */
4441 if (update_tick
!= process_tick
)
4446 if (kbd_on_hold_p ())
4449 Atemp
= input_wait_mask
;
4452 timeout
= make_timespec (0, 0);
4453 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4455 #ifdef NON_BLOCKING_CONNECT
4456 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4460 NULL
, &timeout
, NULL
)
4463 /* It's okay for us to do this and then continue with
4464 the loop, since timeout has already been zeroed out. */
4465 clear_waiting_for_input ();
4466 status_notify (NULL
);
4467 if (do_display
) redisplay_preserve_echo_area (13);
4471 /* Don't wait for output from a non-running process. Just
4472 read whatever data has already been received. */
4473 if (wait_proc
&& wait_proc
->raw_status_new
)
4474 update_status (wait_proc
);
4476 && ! EQ (wait_proc
->status
, Qrun
)
4477 && ! EQ (wait_proc
->status
, Qconnect
))
4479 bool read_some_bytes
= 0;
4481 clear_waiting_for_input ();
4482 XSETPROCESS (proc
, wait_proc
);
4484 /* Read data from the process, until we exhaust it. */
4485 while (wait_proc
->infd
>= 0)
4487 int nread
= read_process_output (proc
, wait_proc
->infd
);
4493 got_some_input
= read_some_bytes
= 1;
4494 else if (nread
== -1 && (errno
== EIO
|| errno
== EAGAIN
))
4497 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4501 if (read_some_bytes
&& do_display
)
4502 redisplay_preserve_echo_area (10);
4507 /* Wait till there is something to do */
4509 if (wait_proc
&& just_wait_proc
)
4511 if (wait_proc
->infd
< 0) /* Terminated */
4513 FD_SET (wait_proc
->infd
, &Available
);
4517 else if (!NILP (wait_for_cell
))
4519 Available
= non_process_wait_mask
;
4526 Available
= non_keyboard_wait_mask
;
4528 Available
= input_wait_mask
;
4529 Writeok
= write_mask
;
4530 #ifdef SELECT_CANT_DO_WRITE_MASK
4535 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4538 /* If frame size has changed or the window is newly mapped,
4539 redisplay now, before we start to wait. There is a race
4540 condition here; if a SIGIO arrives between now and the select
4541 and indicates that a frame is trashed, the select may block
4542 displaying a trashed screen. */
4543 if (frame_garbaged
&& do_display
)
4545 clear_waiting_for_input ();
4546 redisplay_preserve_echo_area (11);
4548 set_waiting_for_input (&timeout
);
4551 /* Skip the `select' call if input is available and we're
4552 waiting for keyboard input or a cell change (which can be
4553 triggered by processing X events). In the latter case, set
4554 nfds to 1 to avoid breaking the loop. */
4556 if ((read_kbd
|| !NILP (wait_for_cell
))
4557 && detect_input_pending ())
4559 nfds
= read_kbd
? 0 : 1;
4566 #ifdef ADAPTIVE_READ_BUFFERING
4567 /* Set the timeout for adaptive read buffering if any
4568 process has non-zero read_output_skip and non-zero
4569 read_output_delay, and we are not reading output for a
4570 specific wait_channel. It is not executed if
4571 Vprocess_adaptive_read_buffering is nil. */
4572 if (process_output_skip
&& check_delay
> 0)
4574 int nsecs
= timeout
.tv_nsec
;
4575 if (timeout
.tv_sec
> 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4576 nsecs
= READ_OUTPUT_DELAY_MAX
;
4577 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4579 proc
= chan_process
[channel
];
4582 /* Find minimum non-zero read_output_delay among the
4583 processes with non-zero read_output_skip. */
4584 if (XPROCESS (proc
)->read_output_delay
> 0)
4587 if (!XPROCESS (proc
)->read_output_skip
)
4589 FD_CLR (channel
, &Available
);
4590 XPROCESS (proc
)->read_output_skip
= 0;
4591 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4592 nsecs
= XPROCESS (proc
)->read_output_delay
;
4595 timeout
= make_timespec (0, nsecs
);
4596 process_output_skip
= 0;
4600 #if defined (HAVE_NS)
4602 #elif defined (HAVE_GLIB)
4607 (max (max_process_desc
, max_input_desc
) + 1,
4609 (check_write
? &Writeok
: 0),
4610 NULL
, &timeout
, NULL
);
4613 /* GnuTLS buffers data internally. In lowat mode it leaves
4614 some data in the TCP buffers so that select works, but
4615 with custom pull/push functions we need to check if some
4616 data is available in the buffers manually. */
4621 /* We're not waiting on a specific process, so loop
4622 through all the channels and check for data.
4623 This is a workaround needed for some versions of
4624 the gnutls library -- 2.12.14 has been confirmed
4626 http://comments.gmane.org/gmane.emacs.devel/145074 */
4627 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
4628 if (! NILP (chan_process
[channel
]))
4630 struct Lisp_Process
*p
=
4631 XPROCESS (chan_process
[channel
]);
4632 if (p
&& p
->gnutls_p
&& p
->gnutls_state
&& p
->infd
4633 && ((emacs_gnutls_record_check_pending
4638 FD_SET (p
->infd
, &Available
);
4644 /* Check this specific channel. */
4645 if (wait_proc
->gnutls_p
/* Check for valid process. */
4646 && wait_proc
->gnutls_state
4647 /* Do we have pending data? */
4648 && ((emacs_gnutls_record_check_pending
4649 (wait_proc
->gnutls_state
))
4653 /* Set to Available. */
4654 FD_SET (wait_proc
->infd
, &Available
);
4663 /* Make C-g and alarm signals set flags again */
4664 clear_waiting_for_input ();
4666 /* If we woke up due to SIGWINCH, actually change size now. */
4667 do_pending_window_change (0);
4669 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4670 /* We waited the full specified time, so return now. */
4674 if (xerrno
== EINTR
)
4676 else if (xerrno
== EBADF
)
4679 report_file_errno ("Failed select", Qnil
, xerrno
);
4684 FD_ZERO (&Available
);
4688 /* Check for keyboard input */
4689 /* If there is any, return immediately
4690 to give it higher priority than subprocesses */
4694 unsigned old_timers_run
= timers_run
;
4695 struct buffer
*old_buffer
= current_buffer
;
4696 Lisp_Object old_window
= selected_window
;
4699 if (detect_input_pending_run_timers (do_display
))
4701 swallow_events (do_display
);
4702 if (detect_input_pending_run_timers (do_display
))
4706 /* If a timer has run, this might have changed buffers
4707 an alike. Make read_key_sequence aware of that. */
4708 if (timers_run
!= old_timers_run
4709 && waiting_for_user_input_p
== -1
4710 && (old_buffer
!= current_buffer
4711 || !EQ (old_window
, selected_window
)))
4712 record_asynch_buffer_change ();
4718 /* If there is unread keyboard input, also return. */
4720 && requeued_events_pending_p ())
4723 /* If we are not checking for keyboard input now,
4724 do process events (but don't run any timers).
4725 This is so that X events will be processed.
4726 Otherwise they may have to wait until polling takes place.
4727 That would causes delays in pasting selections, for example.
4729 (We used to do this only if wait_for_cell.) */
4730 if (read_kbd
== 0 && detect_input_pending ())
4732 swallow_events (do_display
);
4733 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4734 if (detect_input_pending ())
4739 /* Exit now if the cell we're waiting for became non-nil. */
4740 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4744 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4745 go read it. This can happen with X on BSD after logging out.
4746 In that case, there really is no input and no SIGIO,
4747 but select says there is input. */
4749 if (read_kbd
&& interrupt_input
4750 && keyboard_bit_set (&Available
) && ! noninteractive
)
4751 handle_input_available_signal (SIGIO
);
4755 got_some_input
|= nfds
> 0;
4757 /* If checking input just got us a size-change event from X,
4758 obey it now if we should. */
4759 if (read_kbd
|| ! NILP (wait_for_cell
))
4760 do_pending_window_change (0);
4762 /* Check for data from a process. */
4763 if (no_avail
|| nfds
== 0)
4766 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4768 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4770 && ((d
->condition
& FOR_READ
4771 && FD_ISSET (channel
, &Available
))
4772 || (d
->condition
& FOR_WRITE
4773 && FD_ISSET (channel
, &write_mask
))))
4774 d
->func (channel
, d
->data
);
4777 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4779 if (FD_ISSET (channel
, &Available
)
4780 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4781 && !FD_ISSET (channel
, &non_process_wait_mask
))
4785 /* If waiting for this channel, arrange to return as
4786 soon as no more input to be processed. No more
4788 if (wait_channel
== channel
)
4794 proc
= chan_process
[channel
];
4798 /* If this is a server stream socket, accept connection. */
4799 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4801 server_accept_connection (proc
, channel
);
4805 /* Read data from the process, starting with our
4806 buffered-ahead character if we have one. */
4808 nread
= read_process_output (proc
, channel
);
4811 /* Since read_process_output can run a filter,
4812 which can call accept-process-output,
4813 don't try to read from any other processes
4814 before doing the select again. */
4815 FD_ZERO (&Available
);
4818 redisplay_preserve_echo_area (12);
4821 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4824 else if (nread
== -1 && errno
== EAGAIN
)
4827 /* FIXME: Is this special case still needed? */
4828 /* Note that we cannot distinguish between no input
4829 available now and a closed pipe.
4830 With luck, a closed pipe will be accompanied by
4831 subprocess termination and SIGCHLD. */
4832 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4836 /* On some OSs with ptys, when the process on one end of
4837 a pty exits, the other end gets an error reading with
4838 errno = EIO instead of getting an EOF (0 bytes read).
4839 Therefore, if we get an error reading and errno =
4840 EIO, just continue, because the child process has
4841 exited and should clean itself up soon (e.g. when we
4843 else if (nread
== -1 && errno
== EIO
)
4845 struct Lisp_Process
*p
= XPROCESS (proc
);
4847 /* Clear the descriptor now, so we only raise the
4849 FD_CLR (channel
, &input_wait_mask
);
4850 FD_CLR (channel
, &non_keyboard_wait_mask
);
4854 /* If the EIO occurs on a pty, the SIGCHLD handler's
4855 waitpid call will not find the process object to
4856 delete. Do it here. */
4857 p
->tick
= ++process_tick
;
4858 pset_status (p
, Qfailed
);
4861 #endif /* HAVE_PTYS */
4862 /* If we can detect process termination, don't consider the
4863 process gone just because its pipe is closed. */
4864 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4868 /* Preserve status of processes already terminated. */
4869 XPROCESS (proc
)->tick
= ++process_tick
;
4870 deactivate_process (proc
);
4871 if (XPROCESS (proc
)->raw_status_new
)
4872 update_status (XPROCESS (proc
));
4873 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4874 pset_status (XPROCESS (proc
),
4875 list2 (Qexit
, make_number (256)));
4878 #ifdef NON_BLOCKING_CONNECT
4879 if (FD_ISSET (channel
, &Writeok
)
4880 && FD_ISSET (channel
, &connect_wait_mask
))
4882 struct Lisp_Process
*p
;
4884 FD_CLR (channel
, &connect_wait_mask
);
4885 FD_CLR (channel
, &write_mask
);
4886 if (--num_pending_connects
< 0)
4889 proc
= chan_process
[channel
];
4893 p
= XPROCESS (proc
);
4896 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4897 So only use it on systems where it is known to work. */
4899 socklen_t xlen
= sizeof (xerrno
);
4900 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4905 struct sockaddr pname
;
4906 socklen_t pnamelen
= sizeof (pname
);
4908 /* If connection failed, getpeername will fail. */
4910 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4912 /* Obtain connect failure code through error slippage. */
4915 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4922 p
->tick
= ++process_tick
;
4923 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
4924 deactivate_process (proc
);
4928 pset_status (p
, Qrun
);
4929 /* Execute the sentinel here. If we had relied on
4930 status_notify to do it later, it will read input
4931 from the process before calling the sentinel. */
4932 exec_sentinel (proc
, build_string ("open\n"));
4933 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
4935 FD_SET (p
->infd
, &input_wait_mask
);
4936 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4940 #endif /* NON_BLOCKING_CONNECT */
4941 } /* End for each file descriptor. */
4942 } /* End while exit conditions not met. */
4944 unbind_to (count
, Qnil
);
4946 /* If calling from keyboard input, do not quit
4947 since we want to return C-g as an input character.
4948 Otherwise, do pending quit if requested. */
4951 /* Prevent input_pending from remaining set if we quit. */
4952 clear_input_pending ();
4956 return got_some_input
;
4959 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4962 read_process_output_call (Lisp_Object fun_and_args
)
4964 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
4968 read_process_output_error_handler (Lisp_Object error_val
)
4970 cmd_error_internal (error_val
, "error in process filter: ");
4972 update_echo_area ();
4973 Fsleep_for (make_number (2), Qnil
);
4978 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
4980 struct coding_system
*coding
);
4982 /* Read pending output from the process channel,
4983 starting with our buffered-ahead character if we have one.
4984 Yield number of decoded characters read.
4986 This function reads at most 4096 characters.
4987 If you want to read all available subprocess output,
4988 you must call it repeatedly until it returns zero.
4990 The characters read are decoded according to PROC's coding-system
4994 read_process_output (Lisp_Object proc
, register int channel
)
4996 register ssize_t nbytes
;
4998 register struct Lisp_Process
*p
= XPROCESS (proc
);
4999 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5000 int carryover
= p
->decoding_carryover
;
5002 ptrdiff_t count
= SPECPDL_INDEX ();
5003 Lisp_Object odeactivate
;
5005 chars
= alloca (carryover
+ readmax
);
5007 /* See the comment above. */
5008 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5010 #ifdef DATAGRAM_SOCKETS
5011 /* We have a working select, so proc_buffered_char is always -1. */
5012 if (DATAGRAM_CHAN_P (channel
))
5014 socklen_t len
= datagram_address
[channel
].len
;
5015 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5016 0, datagram_address
[channel
].sa
, &len
);
5021 bool buffered
= proc_buffered_char
[channel
] >= 0;
5024 chars
[carryover
] = proc_buffered_char
[channel
];
5025 proc_buffered_char
[channel
] = -1;
5028 if (p
->gnutls_p
&& p
->gnutls_state
)
5029 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5030 readmax
- buffered
);
5033 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5034 readmax
- buffered
);
5035 #ifdef ADAPTIVE_READ_BUFFERING
5036 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5038 int delay
= p
->read_output_delay
;
5041 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5044 process_output_delay_count
++;
5045 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5048 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5050 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5052 process_output_delay_count
--;
5054 p
->read_output_delay
= delay
;
5057 p
->read_output_skip
= 1;
5058 process_output_skip
= 1;
5063 nbytes
+= buffered
&& nbytes
<= 0;
5066 p
->decoding_carryover
= 0;
5068 /* At this point, NBYTES holds number of bytes just received
5069 (including the one in proc_buffered_char[channel]). */
5072 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5074 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5077 /* Now set NBYTES how many bytes we must decode. */
5078 nbytes
+= carryover
;
5080 odeactivate
= Vdeactivate_mark
;
5081 /* There's no good reason to let process filters change the current
5082 buffer, and many callers of accept-process-output, sit-for, and
5083 friends don't expect current-buffer to be changed from under them. */
5084 record_unwind_current_buffer ();
5086 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5088 /* Handling the process output should not deactivate the mark. */
5089 Vdeactivate_mark
= odeactivate
;
5091 unbind_to (count
, Qnil
);
5096 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5098 struct coding_system
*coding
)
5100 Lisp_Object outstream
= p
->filter
;
5102 bool outer_running_asynch_code
= running_asynch_code
;
5103 int waiting
= waiting_for_user_input_p
;
5105 /* No need to gcpro these, because all we do with them later
5106 is test them for EQness, and none of them should be a string. */
5108 Lisp_Object obuffer
, okeymap
;
5109 XSETBUFFER (obuffer
, current_buffer
);
5110 okeymap
= BVAR (current_buffer
, keymap
);
5113 /* We inhibit quit here instead of just catching it so that
5114 hitting ^G when a filter happens to be running won't screw
5116 specbind (Qinhibit_quit
, Qt
);
5117 specbind (Qlast_nonmenu_event
, Qt
);
5119 /* In case we get recursively called,
5120 and we already saved the match data nonrecursively,
5121 save the same match data in safely recursive fashion. */
5122 if (outer_running_asynch_code
)
5125 /* Don't clobber the CURRENT match data, either! */
5126 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5127 restore_search_regs ();
5128 record_unwind_save_match_data ();
5129 Fset_match_data (tem
, Qt
);
5132 /* For speed, if a search happens within this code,
5133 save the match data in a special nonrecursive fashion. */
5134 running_asynch_code
= 1;
5136 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5137 text
= coding
->dst_object
;
5138 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5139 /* A new coding system might be found. */
5140 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5142 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5144 /* Don't call setup_coding_system for
5145 proc_decode_coding_system[channel] here. It is done in
5146 detect_coding called via decode_coding above. */
5148 /* If a coding system for encoding is not yet decided, we set
5149 it as the same as coding-system for decoding.
5151 But, before doing that we must check if
5152 proc_encode_coding_system[p->outfd] surely points to a
5153 valid memory because p->outfd will be changed once EOF is
5154 sent to the process. */
5155 if (NILP (p
->encode_coding_system
)
5156 && proc_encode_coding_system
[p
->outfd
])
5158 pset_encode_coding_system
5159 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5160 setup_coding_system (p
->encode_coding_system
,
5161 proc_encode_coding_system
[p
->outfd
]);
5165 if (coding
->carryover_bytes
> 0)
5167 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5168 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5169 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5170 coding
->carryover_bytes
);
5171 p
->decoding_carryover
= coding
->carryover_bytes
;
5173 if (SBYTES (text
) > 0)
5174 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5175 sometimes it's simply wrong to wrap (e.g. when called from
5176 accept-process-output). */
5177 internal_condition_case_1 (read_process_output_call
,
5178 list3 (outstream
, make_lisp_proc (p
), text
),
5179 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5180 read_process_output_error_handler
);
5182 /* If we saved the match data nonrecursively, restore it now. */
5183 restore_search_regs ();
5184 running_asynch_code
= outer_running_asynch_code
;
5186 /* Restore waiting_for_user_input_p as it was
5187 when we were called, in case the filter clobbered it. */
5188 waiting_for_user_input_p
= waiting
;
5190 #if 0 /* Call record_asynch_buffer_change unconditionally,
5191 because we might have changed minor modes or other things
5192 that affect key bindings. */
5193 if (! EQ (Fcurrent_buffer (), obuffer
)
5194 || ! EQ (current_buffer
->keymap
, okeymap
))
5196 /* But do it only if the caller is actually going to read events.
5197 Otherwise there's no need to make him wake up, and it could
5198 cause trouble (for example it would make sit_for return). */
5199 if (waiting_for_user_input_p
== -1)
5200 record_asynch_buffer_change ();
5203 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5204 Sinternal_default_process_filter
, 2, 2, 0,
5205 doc
: /* Function used as default process filter.
5206 This inserts the process's output into its buffer, if there is one.
5207 Otherwise it discards the output. */)
5208 (Lisp_Object proc
, Lisp_Object text
)
5210 struct Lisp_Process
*p
;
5213 CHECK_PROCESS (proc
);
5214 p
= XPROCESS (proc
);
5215 CHECK_STRING (text
);
5217 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5219 Lisp_Object old_read_only
;
5220 ptrdiff_t old_begv
, old_zv
;
5221 ptrdiff_t old_begv_byte
, old_zv_byte
;
5222 ptrdiff_t before
, before_byte
;
5223 ptrdiff_t opoint_byte
;
5226 Fset_buffer (p
->buffer
);
5228 opoint_byte
= PT_BYTE
;
5229 old_read_only
= BVAR (current_buffer
, read_only
);
5232 old_begv_byte
= BEGV_BYTE
;
5233 old_zv_byte
= ZV_BYTE
;
5235 bset_read_only (current_buffer
, Qnil
);
5237 /* Insert new output into buffer at the current end-of-output
5238 marker, thus preserving logical ordering of input and output. */
5239 if (XMARKER (p
->mark
)->buffer
)
5240 set_point_from_marker (p
->mark
);
5242 SET_PT_BOTH (ZV
, ZV_BYTE
);
5244 before_byte
= PT_BYTE
;
5246 /* If the output marker is outside of the visible region, save
5247 the restriction and widen. */
5248 if (! (BEGV
<= PT
&& PT
<= ZV
))
5251 /* Adjust the multibyteness of TEXT to that of the buffer. */
5252 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5253 != ! STRING_MULTIBYTE (text
))
5254 text
= (STRING_MULTIBYTE (text
)
5255 ? Fstring_as_unibyte (text
)
5256 : Fstring_to_multibyte (text
));
5257 /* Insert before markers in case we are inserting where
5258 the buffer's mark is, and the user's next command is Meta-y. */
5259 insert_from_string_before_markers (text
, 0, 0,
5260 SCHARS (text
), SBYTES (text
), 0);
5262 /* Make sure the process marker's position is valid when the
5263 process buffer is changed in the signal_after_change above.
5264 W3 is known to do that. */
5265 if (BUFFERP (p
->buffer
)
5266 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5267 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5269 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5271 update_mode_lines
= 23;
5273 /* Make sure opoint and the old restrictions
5274 float ahead of any new text just as point would. */
5275 if (opoint
>= before
)
5277 opoint
+= PT
- before
;
5278 opoint_byte
+= PT_BYTE
- before_byte
;
5280 if (old_begv
> before
)
5282 old_begv
+= PT
- before
;
5283 old_begv_byte
+= PT_BYTE
- before_byte
;
5285 if (old_zv
>= before
)
5287 old_zv
+= PT
- before
;
5288 old_zv_byte
+= PT_BYTE
- before_byte
;
5291 /* If the restriction isn't what it should be, set it. */
5292 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5293 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5295 bset_read_only (current_buffer
, old_read_only
);
5296 SET_PT_BOTH (opoint
, opoint_byte
);
5301 /* Sending data to subprocess. */
5303 /* In send_process, when a write fails temporarily,
5304 wait_reading_process_output is called. It may execute user code,
5305 e.g. timers, that attempts to write new data to the same process.
5306 We must ensure that data is sent in the right order, and not
5307 interspersed half-completed with other writes (Bug#10815). This is
5308 handled by the write_queue element of struct process. It is a list
5309 with each entry having the form
5311 (string . (offset . length))
5313 where STRING is a lisp string, OFFSET is the offset into the
5314 string's byte sequence from which we should begin to send, and
5315 LENGTH is the number of bytes left to send. */
5317 /* Create a new entry in write_queue.
5318 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5319 BUF is a pointer to the string sequence of the input_obj or a C
5320 string in case of Qt or Qnil. */
5323 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5324 const char *buf
, ptrdiff_t len
, bool front
)
5327 Lisp_Object entry
, obj
;
5329 if (STRINGP (input_obj
))
5331 offset
= buf
- SSDATA (input_obj
);
5337 obj
= make_unibyte_string (buf
, len
);
5340 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5343 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5345 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5348 /* Remove the first element in the write_queue of process P, put its
5349 contents in OBJ, BUF and LEN, and return true. If the
5350 write_queue is empty, return false. */
5353 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5354 const char **buf
, ptrdiff_t *len
)
5356 Lisp_Object entry
, offset_length
;
5359 if (NILP (p
->write_queue
))
5362 entry
= XCAR (p
->write_queue
);
5363 pset_write_queue (p
, XCDR (p
->write_queue
));
5365 *obj
= XCAR (entry
);
5366 offset_length
= XCDR (entry
);
5368 *len
= XINT (XCDR (offset_length
));
5369 offset
= XINT (XCAR (offset_length
));
5370 *buf
= SSDATA (*obj
) + offset
;
5375 /* Send some data to process PROC.
5376 BUF is the beginning of the data; LEN is the number of characters.
5377 OBJECT is the Lisp object that the data comes from. If OBJECT is
5378 nil or t, it means that the data comes from C string.
5380 If OBJECT is not nil, the data is encoded by PROC's coding-system
5381 for encoding before it is sent.
5383 This function can evaluate Lisp code and can garbage collect. */
5386 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5389 struct Lisp_Process
*p
= XPROCESS (proc
);
5391 struct coding_system
*coding
;
5393 if (p
->raw_status_new
)
5395 if (! EQ (p
->status
, Qrun
))
5396 error ("Process %s not running", SDATA (p
->name
));
5398 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5400 coding
= proc_encode_coding_system
[p
->outfd
];
5401 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5403 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5404 || (BUFFERP (object
)
5405 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5408 pset_encode_coding_system
5409 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5410 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5412 /* The coding system for encoding was changed to raw-text
5413 because we sent a unibyte text previously. Now we are
5414 sending a multibyte text, thus we must encode it by the
5415 original coding system specified for the current process.
5417 Another reason we come here is that the coding system
5418 was just complemented and a new one was returned by
5419 complement_process_encoding_system. */
5420 setup_coding_system (p
->encode_coding_system
, coding
);
5421 Vlast_coding_system_used
= p
->encode_coding_system
;
5423 coding
->src_multibyte
= 1;
5427 coding
->src_multibyte
= 0;
5428 /* For sending a unibyte text, character code conversion should
5429 not take place but EOL conversion should. So, setup raw-text
5430 or one of the subsidiary if we have not yet done it. */
5431 if (CODING_REQUIRE_ENCODING (coding
))
5433 if (CODING_REQUIRE_FLUSHING (coding
))
5435 /* But, before changing the coding, we must flush out data. */
5436 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5437 send_process (proc
, "", 0, Qt
);
5438 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5440 setup_coding_system (raw_text_coding_system
5441 (Vlast_coding_system_used
),
5443 coding
->src_multibyte
= 0;
5446 coding
->dst_multibyte
= 0;
5448 if (CODING_REQUIRE_ENCODING (coding
))
5450 coding
->dst_object
= Qt
;
5451 if (BUFFERP (object
))
5453 ptrdiff_t from_byte
, from
, to
;
5454 ptrdiff_t save_pt
, save_pt_byte
;
5455 struct buffer
*cur
= current_buffer
;
5457 set_buffer_internal (XBUFFER (object
));
5458 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5460 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5461 from
= BYTE_TO_CHAR (from_byte
);
5462 to
= BYTE_TO_CHAR (from_byte
+ len
);
5463 TEMP_SET_PT_BOTH (from
, from_byte
);
5464 encode_coding_object (coding
, object
, from
, from_byte
,
5465 to
, from_byte
+ len
, Qt
);
5466 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5467 set_buffer_internal (cur
);
5469 else if (STRINGP (object
))
5471 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5472 SBYTES (object
), Qt
);
5476 coding
->dst_object
= make_unibyte_string (buf
, len
);
5477 coding
->produced
= len
;
5480 len
= coding
->produced
;
5481 object
= coding
->dst_object
;
5482 buf
= SSDATA (object
);
5485 /* If there is already data in the write_queue, put the new data
5486 in the back of queue. Otherwise, ignore it. */
5487 if (!NILP (p
->write_queue
))
5488 write_queue_push (p
, object
, buf
, len
, 0);
5490 do /* while !NILP (p->write_queue) */
5492 ptrdiff_t cur_len
= -1;
5493 const char *cur_buf
;
5494 Lisp_Object cur_object
;
5496 /* If write_queue is empty, ignore it. */
5497 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5501 cur_object
= object
;
5506 /* Send this batch, using one or more write calls. */
5507 ptrdiff_t written
= 0;
5508 int outfd
= p
->outfd
;
5509 #ifdef DATAGRAM_SOCKETS
5510 if (DATAGRAM_CHAN_P (outfd
))
5512 rv
= sendto (outfd
, cur_buf
, cur_len
,
5513 0, datagram_address
[outfd
].sa
,
5514 datagram_address
[outfd
].len
);
5517 else if (errno
== EMSGSIZE
)
5518 report_file_error ("Sending datagram", proc
);
5524 if (p
->gnutls_p
&& p
->gnutls_state
)
5525 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5528 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5529 rv
= (written
? 0 : -1);
5530 #ifdef ADAPTIVE_READ_BUFFERING
5531 if (p
->read_output_delay
> 0
5532 && p
->adaptive_read_buffering
== 1)
5534 p
->read_output_delay
= 0;
5535 process_output_delay_count
--;
5536 p
->read_output_skip
= 0;
5545 || errno
== EWOULDBLOCK
5548 /* Buffer is full. Wait, accepting input;
5549 that may allow the program
5550 to finish doing output and read more. */
5552 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5553 /* A gross hack to work around a bug in FreeBSD.
5554 In the following sequence, read(2) returns
5558 write(2) 954 bytes, get EAGAIN
5559 read(2) 1024 bytes in process_read_output
5560 read(2) 11 bytes in process_read_output
5562 That is, read(2) returns more bytes than have
5563 ever been written successfully. The 1033 bytes
5564 read are the 1022 bytes written successfully
5565 after processing (for example with CRs added if
5566 the terminal is set up that way which it is
5567 here). The same bytes will be seen again in a
5568 later read(2), without the CRs. */
5570 if (errno
== EAGAIN
)
5573 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5575 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5577 /* Put what we should have written in wait_queue. */
5578 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5579 wait_reading_process_output (0, 20 * 1000 * 1000,
5580 0, 0, Qnil
, NULL
, 0);
5581 /* Reread queue, to see what is left. */
5584 else if (errno
== EPIPE
)
5586 p
->raw_status_new
= 0;
5587 pset_status (p
, list2 (Qexit
, make_number (256)));
5588 p
->tick
= ++process_tick
;
5589 deactivate_process (proc
);
5590 error ("process %s no longer connected to pipe; closed it",
5594 /* This is a real error. */
5595 report_file_error ("Writing to process", proc
);
5601 while (!NILP (p
->write_queue
));
5604 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5606 doc
: /* Send current contents of region as input to PROCESS.
5607 PROCESS may be a process, a buffer, the name of a process or buffer, or
5608 nil, indicating the current buffer's process.
5609 Called from program, takes three arguments, PROCESS, START and END.
5610 If the region is more than 500 characters long,
5611 it is sent in several bunches. This may happen even for shorter regions.
5612 Output from processes can arrive in between bunches. */)
5613 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5615 Lisp_Object proc
= get_process (process
);
5616 ptrdiff_t start_byte
, end_byte
;
5618 validate_region (&start
, &end
);
5620 start_byte
= CHAR_TO_BYTE (XINT (start
));
5621 end_byte
= CHAR_TO_BYTE (XINT (end
));
5623 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5624 move_gap_both (XINT (start
), start_byte
);
5626 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5627 end_byte
- start_byte
, Fcurrent_buffer ());
5632 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5634 doc
: /* Send PROCESS the contents of STRING as input.
5635 PROCESS may be a process, a buffer, the name of a process or buffer, or
5636 nil, indicating the current buffer's process.
5637 If STRING is more than 500 characters long,
5638 it is sent in several bunches. This may happen even for shorter strings.
5639 Output from processes can arrive in between bunches. */)
5640 (Lisp_Object process
, Lisp_Object string
)
5643 CHECK_STRING (string
);
5644 proc
= get_process (process
);
5645 send_process (proc
, SSDATA (string
),
5646 SBYTES (string
), string
);
5650 /* Return the foreground process group for the tty/pty that
5651 the process P uses. */
5653 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5658 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5661 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5662 master side. Try the slave side. */
5663 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5667 ioctl (fd
, TIOCGPGRP
, &gid
);
5671 #endif /* defined (TIOCGPGRP ) */
5676 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5677 Sprocess_running_child_p
, 0, 1, 0,
5678 doc
: /* Return t if PROCESS has given the terminal to a child.
5679 If the operating system does not make it possible to find out,
5680 return t unconditionally. */)
5681 (Lisp_Object process
)
5683 /* Initialize in case ioctl doesn't exist or gives an error,
5684 in a way that will cause returning t. */
5687 struct Lisp_Process
*p
;
5689 proc
= get_process (process
);
5690 p
= XPROCESS (proc
);
5692 if (!EQ (p
->type
, Qreal
))
5693 error ("Process %s is not a subprocess",
5696 error ("Process %s is not active",
5699 gid
= emacs_get_tty_pgrp (p
);
5706 /* send a signal number SIGNO to PROCESS.
5707 If CURRENT_GROUP is t, that means send to the process group
5708 that currently owns the terminal being used to communicate with PROCESS.
5709 This is used for various commands in shell mode.
5710 If CURRENT_GROUP is lambda, that means send to the process group
5711 that currently owns the terminal, but only if it is NOT the shell itself.
5713 If NOMSG is false, insert signal-announcements into process's buffers
5716 If we can, we try to signal PROCESS by sending control characters
5717 down the pty. This allows us to signal inferiors who have changed
5718 their uid, for which kill would return an EPERM error. */
5721 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5725 struct Lisp_Process
*p
;
5729 proc
= get_process (process
);
5730 p
= XPROCESS (proc
);
5732 if (!EQ (p
->type
, Qreal
))
5733 error ("Process %s is not a subprocess",
5736 error ("Process %s is not active",
5740 current_group
= Qnil
;
5742 /* If we are using pgrps, get a pgrp number and make it negative. */
5743 if (NILP (current_group
))
5744 /* Send the signal to the shell's process group. */
5748 #ifdef SIGNALS_VIA_CHARACTERS
5749 /* If possible, send signals to the entire pgrp
5750 by sending an input character to it. */
5753 cc_t
*sig_char
= NULL
;
5755 tcgetattr (p
->infd
, &t
);
5760 sig_char
= &t
.c_cc
[VINTR
];
5764 sig_char
= &t
.c_cc
[VQUIT
];
5768 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5769 sig_char
= &t
.c_cc
[VSWTCH
];
5771 sig_char
= &t
.c_cc
[VSUSP
];
5776 if (sig_char
&& *sig_char
!= CDISABLE
)
5778 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5781 /* If we can't send the signal with a character,
5782 fall through and send it another way. */
5784 /* The code above may fall through if it can't
5785 handle the signal. */
5786 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5789 /* Get the current pgrp using the tty itself, if we have that.
5790 Otherwise, use the pty to get the pgrp.
5791 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5792 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5793 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5794 His patch indicates that if TIOCGPGRP returns an error, then
5795 we should just assume that p->pid is also the process group id. */
5797 gid
= emacs_get_tty_pgrp (p
);
5800 /* If we can't get the information, assume
5801 the shell owns the tty. */
5804 /* It is not clear whether anything really can set GID to -1.
5805 Perhaps on some system one of those ioctls can or could do so.
5806 Or perhaps this is vestigial. */
5809 #else /* ! defined (TIOCGPGRP ) */
5810 /* Can't select pgrps on this system, so we know that
5811 the child itself heads the pgrp. */
5813 #endif /* ! defined (TIOCGPGRP ) */
5815 /* If current_group is lambda, and the shell owns the terminal,
5816 don't send any signal. */
5817 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5822 if (signo
== SIGCONT
)
5824 p
->raw_status_new
= 0;
5825 pset_status (p
, Qrun
);
5826 p
->tick
= ++process_tick
;
5829 status_notify (NULL
);
5830 redisplay_preserve_echo_area (13);
5835 /* If we don't have process groups, send the signal to the immediate
5836 subprocess. That isn't really right, but it's better than any
5837 obvious alternative. */
5840 kill (p
->pid
, signo
);
5844 /* gid may be a pid, or minus a pgrp's number */
5846 if (!NILP (current_group
))
5848 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
5856 #else /* ! defined (TIOCSIGSEND) */
5858 #endif /* ! defined (TIOCSIGSEND) */
5861 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5862 doc
: /* Interrupt process PROCESS.
5863 PROCESS may be a process, a buffer, or the name of a process or buffer.
5864 No arg or nil means current buffer's process.
5865 Second arg CURRENT-GROUP non-nil means send signal to
5866 the current process-group of the process's controlling terminal
5867 rather than to the process's own process group.
5868 If the process is a shell, this means interrupt current subjob
5869 rather than the shell.
5871 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5872 don't send the signal. */)
5873 (Lisp_Object process
, Lisp_Object current_group
)
5875 process_send_signal (process
, SIGINT
, current_group
, 0);
5879 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5880 doc
: /* Kill process PROCESS. May be process or name of one.
5881 See function `interrupt-process' for more details on usage. */)
5882 (Lisp_Object process
, Lisp_Object current_group
)
5884 process_send_signal (process
, SIGKILL
, current_group
, 0);
5888 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5889 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5890 See function `interrupt-process' for more details on usage. */)
5891 (Lisp_Object process
, Lisp_Object current_group
)
5893 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5897 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5898 doc
: /* Stop process PROCESS. May be process or name of one.
5899 See function `interrupt-process' for more details on usage.
5900 If PROCESS is a network or serial process, inhibit handling of incoming
5902 (Lisp_Object process
, Lisp_Object current_group
)
5904 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5906 struct Lisp_Process
*p
;
5908 p
= XPROCESS (process
);
5909 if (NILP (p
->command
)
5912 FD_CLR (p
->infd
, &input_wait_mask
);
5913 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
5915 pset_command (p
, Qt
);
5919 error ("No SIGTSTP support");
5921 process_send_signal (process
, SIGTSTP
, current_group
, 0);
5926 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
5927 doc
: /* Continue process PROCESS. May be process or name of one.
5928 See function `interrupt-process' for more details on usage.
5929 If PROCESS is a network or serial process, resume handling of incoming
5931 (Lisp_Object process
, Lisp_Object current_group
)
5933 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5935 struct Lisp_Process
*p
;
5937 p
= XPROCESS (process
);
5938 if (EQ (p
->command
, Qt
)
5940 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
5942 FD_SET (p
->infd
, &input_wait_mask
);
5943 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5945 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
5946 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
5947 #else /* not WINDOWSNT */
5948 tcflush (p
->infd
, TCIFLUSH
);
5949 #endif /* not WINDOWSNT */
5951 pset_command (p
, Qnil
);
5955 process_send_signal (process
, SIGCONT
, current_group
, 0);
5957 error ("No SIGCONT support");
5962 /* Return the integer value of the signal whose abbreviation is ABBR,
5963 or a negative number if there is no such signal. */
5965 abbr_to_signal (char const *name
)
5968 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
5970 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
5973 for (i
= 0; i
< sizeof sigbuf
; i
++)
5975 sigbuf
[i
] = c_toupper (name
[i
]);
5977 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
5983 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
5984 2, 2, "sProcess (name or number): \nnSignal code: ",
5985 doc
: /* Send PROCESS the signal with code SIGCODE.
5986 PROCESS may also be a number specifying the process id of the
5987 process to signal; in this case, the process need not be a child of
5989 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5990 (Lisp_Object process
, Lisp_Object sigcode
)
5995 if (STRINGP (process
))
5997 Lisp_Object tem
= Fget_process (process
);
6000 Lisp_Object process_number
=
6001 string_to_number (SSDATA (process
), 10, 1);
6002 if (INTEGERP (process_number
) || FLOATP (process_number
))
6003 tem
= process_number
;
6007 else if (!NUMBERP (process
))
6008 process
= get_process (process
);
6013 if (NUMBERP (process
))
6014 CONS_TO_INTEGER (process
, pid_t
, pid
);
6017 CHECK_PROCESS (process
);
6018 pid
= XPROCESS (process
)->pid
;
6020 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6023 if (INTEGERP (sigcode
))
6025 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6026 signo
= XINT (sigcode
);
6032 CHECK_SYMBOL (sigcode
);
6033 name
= SSDATA (SYMBOL_NAME (sigcode
));
6035 signo
= abbr_to_signal (name
);
6037 error ("Undefined signal name %s", name
);
6040 return make_number (kill (pid
, signo
));
6043 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6044 doc
: /* Make PROCESS see end-of-file in its input.
6045 EOF comes after any text already sent to it.
6046 PROCESS may be a process, a buffer, the name of a process or buffer, or
6047 nil, indicating the current buffer's process.
6048 If PROCESS is a network connection, or is a process communicating
6049 through a pipe (as opposed to a pty), then you cannot send any more
6050 text to PROCESS after you call this function.
6051 If PROCESS is a serial process, wait until all output written to the
6052 process has been transmitted to the serial port. */)
6053 (Lisp_Object process
)
6056 struct coding_system
*coding
= NULL
;
6059 if (DATAGRAM_CONN_P (process
))
6062 proc
= get_process (process
);
6063 outfd
= XPROCESS (proc
)->outfd
;
6065 coding
= proc_encode_coding_system
[outfd
];
6067 /* Make sure the process is really alive. */
6068 if (XPROCESS (proc
)->raw_status_new
)
6069 update_status (XPROCESS (proc
));
6070 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6071 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6073 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6075 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6076 send_process (proc
, "", 0, Qnil
);
6079 if (XPROCESS (proc
)->pty_flag
)
6080 send_process (proc
, "\004", 1, Qnil
);
6081 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6084 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6085 report_file_error ("Failed tcdrain", Qnil
);
6086 #endif /* not WINDOWSNT */
6087 /* Do nothing on Windows because writes are blocking. */
6091 struct Lisp_Process
*p
= XPROCESS (proc
);
6092 int old_outfd
= p
->outfd
;
6095 #ifdef HAVE_SHUTDOWN
6096 /* If this is a network connection, or socketpair is used
6097 for communication with the subprocess, call shutdown to cause EOF.
6098 (In some old system, shutdown to socketpair doesn't work.
6099 Then we just can't win.) */
6100 if (EQ (p
->type
, Qnetwork
)
6101 || p
->infd
== old_outfd
)
6102 shutdown (old_outfd
, 1);
6104 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6105 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6107 report_file_error ("Opening null device", Qnil
);
6108 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6109 p
->outfd
= new_outfd
;
6111 if (!proc_encode_coding_system
[new_outfd
])
6112 proc_encode_coding_system
[new_outfd
]
6113 = xmalloc (sizeof (struct coding_system
));
6116 *proc_encode_coding_system
[new_outfd
]
6117 = *proc_encode_coding_system
[old_outfd
];
6118 memset (proc_encode_coding_system
[old_outfd
], 0,
6119 sizeof (struct coding_system
));
6122 setup_coding_system (p
->encode_coding_system
,
6123 proc_encode_coding_system
[new_outfd
]);
6128 /* The main Emacs thread records child processes in three places:
6130 - Vprocess_alist, for asynchronous subprocesses, which are child
6131 processes visible to Lisp.
6133 - deleted_pid_list, for child processes invisible to Lisp,
6134 typically because of delete-process. These are recorded so that
6135 the processes can be reaped when they exit, so that the operating
6136 system's process table is not cluttered by zombies.
6138 - the local variable PID in Fcall_process, call_process_cleanup and
6139 call_process_kill, for synchronous subprocesses.
6140 record_unwind_protect is used to make sure this process is not
6141 forgotten: if the user interrupts call-process and the child
6142 process refuses to exit immediately even with two C-g's,
6143 call_process_kill adds PID's contents to deleted_pid_list before
6146 The main Emacs thread invokes waitpid only on child processes that
6147 it creates and that have not been reaped. This avoid races on
6148 platforms such as GTK, where other threads create their own
6149 subprocesses which the main thread should not reap. For example,
6150 if the main thread attempted to reap an already-reaped child, it
6151 might inadvertently reap a GTK-created process that happened to
6152 have the same process ID. */
6154 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6155 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6156 keep track of its own children. GNUstep is similar. */
6158 static void dummy_handler (int sig
) {}
6159 static signal_handler_t
volatile lib_child_handler
;
6161 /* Handle a SIGCHLD signal by looking for known child processes of
6162 Emacs whose status have changed. For each one found, record its
6165 All we do is change the status; we do not run sentinels or print
6166 notifications. That is saved for the next time keyboard input is
6167 done, in order to avoid timing errors.
6169 ** WARNING: this can be called during garbage collection.
6170 Therefore, it must not be fooled by the presence of mark bits in
6173 ** USG WARNING: Although it is not obvious from the documentation
6174 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6175 signal() before executing at least one wait(), otherwise the
6176 handler will be called again, resulting in an infinite loop. The
6177 relevant portion of the documentation reads "SIGCLD signals will be
6178 queued and the signal-catching function will be continually
6179 reentered until the queue is empty". Invoking signal() causes the
6180 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6183 ** Malloc WARNING: This should never call malloc either directly or
6184 indirectly; if it does, that is a bug */
6187 handle_child_signal (int sig
)
6189 Lisp_Object tail
, proc
;
6191 /* Find the process that signaled us, and record its status. */
6193 /* The process can have been deleted by Fdelete_process, or have
6194 been started asynchronously by Fcall_process. */
6195 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6197 bool all_pids_are_fixnums
6198 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6199 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6200 Lisp_Object head
= XCAR (tail
);
6205 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6208 if (INTEGERP (xpid
))
6209 deleted_pid
= XINT (xpid
);
6211 deleted_pid
= XFLOAT_DATA (xpid
);
6212 if (child_status_changed (deleted_pid
, 0, 0))
6214 if (STRINGP (XCDR (head
)))
6215 unlink (SSDATA (XCDR (head
)));
6216 XSETCAR (tail
, Qnil
);
6221 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6222 FOR_EACH_PROCESS (tail
, proc
)
6224 struct Lisp_Process
*p
= XPROCESS (proc
);
6228 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6230 /* Change the status of the process that was found. */
6231 p
->tick
= ++process_tick
;
6232 p
->raw_status
= status
;
6233 p
->raw_status_new
= 1;
6235 /* If process has terminated, stop waiting for its output. */
6236 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6238 bool clear_desc_flag
= 0;
6241 clear_desc_flag
= 1;
6243 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6244 if (clear_desc_flag
)
6246 FD_CLR (p
->infd
, &input_wait_mask
);
6247 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6253 lib_child_handler (sig
);
6254 #ifdef NS_IMPL_GNUSTEP
6255 /* NSTask in GNUstep sets its child handler each time it is called.
6256 So we must re-set ours. */
6257 catch_child_signal();
6262 deliver_child_signal (int sig
)
6264 deliver_process_signal (sig
, handle_child_signal
);
6269 exec_sentinel_error_handler (Lisp_Object error_val
)
6271 cmd_error_internal (error_val
, "error in process sentinel: ");
6273 update_echo_area ();
6274 Fsleep_for (make_number (2), Qnil
);
6279 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6281 Lisp_Object sentinel
, odeactivate
;
6282 struct Lisp_Process
*p
= XPROCESS (proc
);
6283 ptrdiff_t count
= SPECPDL_INDEX ();
6284 bool outer_running_asynch_code
= running_asynch_code
;
6285 int waiting
= waiting_for_user_input_p
;
6287 if (inhibit_sentinels
)
6290 /* No need to gcpro these, because all we do with them later
6291 is test them for EQness, and none of them should be a string. */
6292 odeactivate
= Vdeactivate_mark
;
6294 Lisp_Object obuffer
, okeymap
;
6295 XSETBUFFER (obuffer
, current_buffer
);
6296 okeymap
= BVAR (current_buffer
, keymap
);
6299 /* There's no good reason to let sentinels change the current
6300 buffer, and many callers of accept-process-output, sit-for, and
6301 friends don't expect current-buffer to be changed from under them. */
6302 record_unwind_current_buffer ();
6304 sentinel
= p
->sentinel
;
6306 /* Inhibit quit so that random quits don't screw up a running filter. */
6307 specbind (Qinhibit_quit
, Qt
);
6308 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6310 /* In case we get recursively called,
6311 and we already saved the match data nonrecursively,
6312 save the same match data in safely recursive fashion. */
6313 if (outer_running_asynch_code
)
6316 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6317 restore_search_regs ();
6318 record_unwind_save_match_data ();
6319 Fset_match_data (tem
, Qt
);
6322 /* For speed, if a search happens within this code,
6323 save the match data in a special nonrecursive fashion. */
6324 running_asynch_code
= 1;
6326 internal_condition_case_1 (read_process_output_call
,
6327 list3 (sentinel
, proc
, reason
),
6328 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6329 exec_sentinel_error_handler
);
6331 /* If we saved the match data nonrecursively, restore it now. */
6332 restore_search_regs ();
6333 running_asynch_code
= outer_running_asynch_code
;
6335 Vdeactivate_mark
= odeactivate
;
6337 /* Restore waiting_for_user_input_p as it was
6338 when we were called, in case the filter clobbered it. */
6339 waiting_for_user_input_p
= waiting
;
6342 if (! EQ (Fcurrent_buffer (), obuffer
)
6343 || ! EQ (current_buffer
->keymap
, okeymap
))
6345 /* But do it only if the caller is actually going to read events.
6346 Otherwise there's no need to make him wake up, and it could
6347 cause trouble (for example it would make sit_for return). */
6348 if (waiting_for_user_input_p
== -1)
6349 record_asynch_buffer_change ();
6351 unbind_to (count
, Qnil
);
6354 /* Report all recent events of a change in process status
6355 (either run the sentinel or output a message).
6356 This is usually done while Emacs is waiting for keyboard input
6357 but can be done at other times. */
6360 status_notify (struct Lisp_Process
*deleting_process
)
6362 register Lisp_Object proc
;
6363 Lisp_Object tail
, msg
;
6364 struct gcpro gcpro1
, gcpro2
;
6368 /* We need to gcpro tail; if read_process_output calls a filter
6369 which deletes a process and removes the cons to which tail points
6370 from Vprocess_alist, and then causes a GC, tail is an unprotected
6374 /* Set this now, so that if new processes are created by sentinels
6375 that we run, we get called again to handle their status changes. */
6376 update_tick
= process_tick
;
6378 FOR_EACH_PROCESS (tail
, proc
)
6381 register struct Lisp_Process
*p
= XPROCESS (proc
);
6383 if (p
->tick
!= p
->update_tick
)
6385 p
->update_tick
= p
->tick
;
6387 /* If process is still active, read any output that remains. */
6388 while (! EQ (p
->filter
, Qt
)
6389 && ! EQ (p
->status
, Qconnect
)
6390 && ! EQ (p
->status
, Qlisten
)
6391 /* Network or serial process not stopped: */
6392 && ! EQ (p
->command
, Qt
)
6394 && p
!= deleting_process
6395 && read_process_output (proc
, p
->infd
) > 0);
6397 /* Get the text to use for the message. */
6398 if (p
->raw_status_new
)
6400 msg
= status_message (p
);
6402 /* If process is terminated, deactivate it or delete it. */
6404 if (CONSP (p
->status
))
6405 symbol
= XCAR (p
->status
);
6407 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6408 || EQ (symbol
, Qclosed
))
6410 if (delete_exited_processes
)
6411 remove_process (proc
);
6413 deactivate_process (proc
);
6416 /* The actions above may have further incremented p->tick.
6417 So set p->update_tick again so that an error in the sentinel will
6418 not cause this code to be run again. */
6419 p
->update_tick
= p
->tick
;
6420 /* Now output the message suitably. */
6421 exec_sentinel (proc
, msg
);
6425 update_mode_lines
= 24; /* In case buffers use %s in mode-line-format. */
6429 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6430 Sinternal_default_process_sentinel
, 2, 2, 0,
6431 doc
: /* Function used as default sentinel for processes.
6432 This inserts a status message into the process's buffer, if there is one. */)
6433 (Lisp_Object proc
, Lisp_Object msg
)
6435 Lisp_Object buffer
, symbol
;
6436 struct Lisp_Process
*p
;
6437 CHECK_PROCESS (proc
);
6438 p
= XPROCESS (proc
);
6442 symbol
= XCAR (symbol
);
6444 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6447 struct buffer
*old
= current_buffer
;
6448 ptrdiff_t opoint
, opoint_byte
;
6449 ptrdiff_t before
, before_byte
;
6451 /* Avoid error if buffer is deleted
6452 (probably that's why the process is dead, too). */
6453 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6455 Fset_buffer (buffer
);
6457 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6458 msg
= (code_convert_string_norecord
6459 (msg
, Vlocale_coding_system
, 1));
6462 opoint_byte
= PT_BYTE
;
6463 /* Insert new output into buffer
6464 at the current end-of-output marker,
6465 thus preserving logical ordering of input and output. */
6466 if (XMARKER (p
->mark
)->buffer
)
6467 Fgoto_char (p
->mark
);
6469 SET_PT_BOTH (ZV
, ZV_BYTE
);
6472 before_byte
= PT_BYTE
;
6474 tem
= BVAR (current_buffer
, read_only
);
6475 bset_read_only (current_buffer
, Qnil
);
6476 insert_string ("\nProcess ");
6477 { /* FIXME: temporary kludge. */
6478 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6479 insert_string (" ");
6481 bset_read_only (current_buffer
, tem
);
6482 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6484 if (opoint
>= before
)
6485 SET_PT_BOTH (opoint
+ (PT
- before
),
6486 opoint_byte
+ (PT_BYTE
- before_byte
));
6488 SET_PT_BOTH (opoint
, opoint_byte
);
6490 set_buffer_internal (old
);
6496 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6497 Sset_process_coding_system
, 1, 3, 0,
6498 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6499 DECODING will be used to decode subprocess output and ENCODING to
6500 encode subprocess input. */)
6501 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6503 register struct Lisp_Process
*p
;
6505 CHECK_PROCESS (process
);
6506 p
= XPROCESS (process
);
6508 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6510 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6511 Fcheck_coding_system (decoding
);
6512 Fcheck_coding_system (encoding
);
6513 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6514 pset_decode_coding_system (p
, decoding
);
6515 pset_encode_coding_system (p
, encoding
);
6516 setup_process_coding_systems (process
);
6521 DEFUN ("process-coding-system",
6522 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6523 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6524 (register Lisp_Object process
)
6526 CHECK_PROCESS (process
);
6527 return Fcons (XPROCESS (process
)->decode_coding_system
,
6528 XPROCESS (process
)->encode_coding_system
);
6531 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6532 Sset_process_filter_multibyte
, 2, 2, 0,
6533 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6534 If FLAG is non-nil, the filter is given multibyte strings.
6535 If FLAG is nil, the filter is given unibyte strings. In this case,
6536 all character code conversion except for end-of-line conversion is
6538 (Lisp_Object process
, Lisp_Object flag
)
6540 register struct Lisp_Process
*p
;
6542 CHECK_PROCESS (process
);
6543 p
= XPROCESS (process
);
6545 pset_decode_coding_system
6546 (p
, raw_text_coding_system (p
->decode_coding_system
));
6547 setup_process_coding_systems (process
);
6552 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6553 Sprocess_filter_multibyte_p
, 1, 1, 0,
6554 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6555 (Lisp_Object process
)
6557 register struct Lisp_Process
*p
;
6558 struct coding_system
*coding
;
6560 CHECK_PROCESS (process
);
6561 p
= XPROCESS (process
);
6562 coding
= proc_decode_coding_system
[p
->infd
];
6563 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6572 add_gpm_wait_descriptor (int desc
)
6574 add_keyboard_wait_descriptor (desc
);
6578 delete_gpm_wait_descriptor (int desc
)
6580 delete_keyboard_wait_descriptor (desc
);
6585 # ifdef USABLE_SIGIO
6587 /* Return true if *MASK has a bit set
6588 that corresponds to one of the keyboard input descriptors. */
6591 keyboard_bit_set (fd_set
*mask
)
6595 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6596 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6597 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6604 #else /* not subprocesses */
6606 /* Defined on msdos.c. */
6607 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
6608 struct timespec
*, void *);
6610 /* Implementation of wait_reading_process_output, assuming that there
6611 are no subprocesses. Used only by the MS-DOS build.
6613 Wait for timeout to elapse and/or keyboard input to be available.
6617 If negative, gobble data immediately available but don't wait for any.
6620 an additional duration to wait, measured in nanoseconds
6621 If TIME_LIMIT is zero, then:
6622 If NSECS == 0, there is no limit.
6623 If NSECS > 0, the timeout consists of NSECS only.
6624 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6627 0 to ignore keyboard input, or
6628 1 to return when input is available, or
6629 -1 means caller will actually read the input, so don't throw to
6632 see full version for other parameters. We know that wait_proc will
6633 always be NULL, since `subprocesses' isn't defined.
6635 DO_DISPLAY means redisplay should be done to show subprocess
6636 output that arrives.
6638 Return true if we received input from any process. */
6641 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6643 Lisp_Object wait_for_cell
,
6644 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6647 struct timespec end_time
, timeout
;
6654 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6655 time_limit
= TYPE_MAXIMUM (time_t);
6657 /* What does time_limit really mean? */
6658 if (time_limit
|| nsecs
> 0)
6660 timeout
= make_timespec (time_limit
, nsecs
);
6661 end_time
= timespec_add (current_timespec (), timeout
);
6664 /* Turn off periodic alarms (in case they are in use)
6665 and then turn off any other atimers,
6666 because the select emulator uses alarms. */
6668 turn_on_atimers (0);
6672 bool timeout_reduced_for_timers
= 0;
6673 fd_set waitchannels
;
6676 /* If calling from keyboard input, do not quit
6677 since we want to return C-g as an input character.
6678 Otherwise, do pending quit if requested. */
6682 /* Exit now if the cell we're waiting for became non-nil. */
6683 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6686 /* Compute time from now till when time limit is up. */
6687 /* Exit if already run out. */
6690 /* A negative timeout means
6691 gobble output available now
6692 but don't wait at all. */
6694 timeout
= make_timespec (0, 0);
6696 else if (time_limit
|| nsecs
> 0)
6698 struct timespec now
= current_timespec ();
6699 if (timespec_cmp (end_time
, now
) <= 0)
6701 timeout
= timespec_sub (end_time
, now
);
6705 timeout
= make_timespec (100000, 0);
6708 /* If our caller will not immediately handle keyboard events,
6709 run timer events directly.
6710 (Callers that will immediately read keyboard events
6711 call timer_delay on their own.) */
6712 if (NILP (wait_for_cell
))
6714 struct timespec timer_delay
;
6718 unsigned old_timers_run
= timers_run
;
6719 timer_delay
= timer_check ();
6720 if (timers_run
!= old_timers_run
&& do_display
)
6721 /* We must retry, since a timer may have requeued itself
6722 and that could alter the time delay. */
6723 redisplay_preserve_echo_area (14);
6727 while (!detect_input_pending ());
6729 /* If there is unread keyboard input, also return. */
6731 && requeued_events_pending_p ())
6734 if (timespec_valid_p (timer_delay
) && nsecs
>= 0)
6736 if (timespec_cmp (timer_delay
, timeout
) < 0)
6738 timeout
= timer_delay
;
6739 timeout_reduced_for_timers
= 1;
6744 /* Cause C-g and alarm signals to take immediate action,
6745 and cause input available signals to zero out timeout. */
6747 set_waiting_for_input (&timeout
);
6749 /* If a frame has been newly mapped and needs updating,
6750 reprocess its display stuff. */
6751 if (frame_garbaged
&& do_display
)
6753 clear_waiting_for_input ();
6754 redisplay_preserve_echo_area (15);
6756 set_waiting_for_input (&timeout
);
6759 /* Wait till there is something to do. */
6760 FD_ZERO (&waitchannels
);
6761 if (read_kbd
&& detect_input_pending ())
6765 if (read_kbd
|| !NILP (wait_for_cell
))
6766 FD_SET (0, &waitchannels
);
6767 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6772 /* Make C-g and alarm signals set flags again */
6773 clear_waiting_for_input ();
6775 /* If we woke up due to SIGWINCH, actually change size now. */
6776 do_pending_window_change (0);
6778 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6779 /* We waited the full specified time, so return now. */
6784 /* If the system call was interrupted, then go around the
6786 if (xerrno
== EINTR
)
6787 FD_ZERO (&waitchannels
);
6789 report_file_errno ("Failed select", Qnil
, xerrno
);
6792 /* Check for keyboard input */
6795 && detect_input_pending_run_timers (do_display
))
6797 swallow_events (do_display
);
6798 if (detect_input_pending_run_timers (do_display
))
6802 /* If there is unread keyboard input, also return. */
6804 && requeued_events_pending_p ())
6807 /* If wait_for_cell. check for keyboard input
6808 but don't run any timers.
6809 ??? (It seems wrong to me to check for keyboard
6810 input at all when wait_for_cell, but the code
6811 has been this way since July 1994.
6812 Try changing this after version 19.31.) */
6813 if (! NILP (wait_for_cell
)
6814 && detect_input_pending ())
6816 swallow_events (do_display
);
6817 if (detect_input_pending ())
6821 /* Exit now if the cell we're waiting for became non-nil. */
6822 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6831 #endif /* not subprocesses */
6833 /* The following functions are needed even if async subprocesses are
6834 not supported. Some of them are no-op stubs in that case. */
6836 /* Add DESC to the set of keyboard input descriptors. */
6839 add_keyboard_wait_descriptor (int desc
)
6841 #ifdef subprocesses /* actually means "not MSDOS" */
6842 FD_SET (desc
, &input_wait_mask
);
6843 FD_SET (desc
, &non_process_wait_mask
);
6844 if (desc
> max_input_desc
)
6845 max_input_desc
= desc
;
6849 /* From now on, do not expect DESC to give keyboard input. */
6852 delete_keyboard_wait_descriptor (int desc
)
6855 FD_CLR (desc
, &input_wait_mask
);
6856 FD_CLR (desc
, &non_process_wait_mask
);
6857 delete_input_desc (desc
);
6861 /* Setup coding systems of PROCESS. */
6864 setup_process_coding_systems (Lisp_Object process
)
6867 struct Lisp_Process
*p
= XPROCESS (process
);
6869 int outch
= p
->outfd
;
6870 Lisp_Object coding_system
;
6872 if (inch
< 0 || outch
< 0)
6875 if (!proc_decode_coding_system
[inch
])
6876 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6877 coding_system
= p
->decode_coding_system
;
6878 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6879 && BUFFERP (p
->buffer
))
6881 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6882 coding_system
= raw_text_coding_system (coding_system
);
6884 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6886 if (!proc_encode_coding_system
[outch
])
6887 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6888 setup_coding_system (p
->encode_coding_system
,
6889 proc_encode_coding_system
[outch
]);
6893 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6894 doc
: /* Return the (or a) process associated with BUFFER.
6895 BUFFER may be a buffer or the name of one. */)
6896 (register Lisp_Object buffer
)
6899 register Lisp_Object buf
, tail
, proc
;
6901 if (NILP (buffer
)) return Qnil
;
6902 buf
= Fget_buffer (buffer
);
6903 if (NILP (buf
)) return Qnil
;
6905 FOR_EACH_PROCESS (tail
, proc
)
6906 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6908 #endif /* subprocesses */
6912 DEFUN ("process-inherit-coding-system-flag",
6913 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
6915 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
6916 If this flag is t, `buffer-file-coding-system' of the buffer
6917 associated with PROCESS will inherit the coding system used to decode
6918 the process output. */)
6919 (register Lisp_Object process
)
6922 CHECK_PROCESS (process
);
6923 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
6925 /* Ignore the argument and return the value of
6926 inherit-process-coding-system. */
6927 return inherit_process_coding_system
? Qt
: Qnil
;
6931 /* Kill all processes associated with `buffer'.
6932 If `buffer' is nil, kill all processes */
6935 kill_buffer_processes (Lisp_Object buffer
)
6938 Lisp_Object tail
, proc
;
6940 FOR_EACH_PROCESS (tail
, proc
)
6941 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
6943 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
6944 Fdelete_process (proc
);
6945 else if (XPROCESS (proc
)->infd
>= 0)
6946 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
6948 #else /* subprocesses */
6949 /* Since we have no subprocesses, this does nothing. */
6950 #endif /* subprocesses */
6953 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
6954 Swaiting_for_user_input_p
, 0, 0, 0,
6955 doc
: /* Return non-nil if Emacs is waiting for input from the user.
6956 This is intended for use by asynchronous process output filters and sentinels. */)
6960 return (waiting_for_user_input_p
? Qt
: Qnil
);
6966 /* Stop reading input from keyboard sources. */
6969 hold_keyboard_input (void)
6974 /* Resume reading input from keyboard sources. */
6977 unhold_keyboard_input (void)
6982 /* Return true if keyboard input is on hold, zero otherwise. */
6985 kbd_on_hold_p (void)
6987 return kbd_is_on_hold
;
6991 /* Enumeration of and access to system processes a-la ps(1). */
6993 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
6995 doc
: /* Return a list of numerical process IDs of all running processes.
6996 If this functionality is unsupported, return nil.
6998 See `process-attributes' for getting attributes of a process given its ID. */)
7001 return list_system_processes ();
7004 DEFUN ("process-attributes", Fprocess_attributes
,
7005 Sprocess_attributes
, 1, 1, 0,
7006 doc
: /* Return attributes of the process given by its PID, a number.
7008 Value is an alist where each element is a cons cell of the form
7012 If this functionality is unsupported, the value is nil.
7014 See `list-system-processes' for getting a list of all process IDs.
7016 The KEYs of the attributes that this function may return are listed
7017 below, together with the type of the associated VALUE (in parentheses).
7018 Not all platforms support all of these attributes; unsupported
7019 attributes will not appear in the returned alist.
7020 Unless explicitly indicated otherwise, numbers can have either
7021 integer or floating point values.
7023 euid -- Effective user User ID of the process (number)
7024 user -- User name corresponding to euid (string)
7025 egid -- Effective user Group ID of the process (number)
7026 group -- Group name corresponding to egid (string)
7027 comm -- Command name (executable name only) (string)
7028 state -- Process state code, such as "S", "R", or "T" (string)
7029 ppid -- Parent process ID (number)
7030 pgrp -- Process group ID (number)
7031 sess -- Session ID, i.e. process ID of session leader (number)
7032 ttname -- Controlling tty name (string)
7033 tpgid -- ID of foreground process group on the process's tty (number)
7034 minflt -- number of minor page faults (number)
7035 majflt -- number of major page faults (number)
7036 cminflt -- cumulative number of minor page faults (number)
7037 cmajflt -- cumulative number of major page faults (number)
7038 utime -- user time used by the process, in (current-time) format,
7039 which is a list of integers (HIGH LOW USEC PSEC)
7040 stime -- system time used by the process (current-time)
7041 time -- sum of utime and stime (current-time)
7042 cutime -- user time used by the process and its children (current-time)
7043 cstime -- system time used by the process and its children (current-time)
7044 ctime -- sum of cutime and cstime (current-time)
7045 pri -- priority of the process (number)
7046 nice -- nice value of the process (number)
7047 thcount -- process thread count (number)
7048 start -- time the process started (current-time)
7049 vsize -- virtual memory size of the process in KB's (number)
7050 rss -- resident set size of the process in KB's (number)
7051 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7052 pcpu -- percents of CPU time used by the process (floating-point number)
7053 pmem -- percents of total physical memory used by process's resident set
7054 (floating-point number)
7055 args -- command line which invoked the process (string). */)
7058 return system_process_attributes (pid
);
7062 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7063 Invoke this after init_process_emacs, and after glib and/or GNUstep
7064 futz with the SIGCHLD handler, but before Emacs forks any children.
7065 This function's caller should block SIGCHLD. */
7067 #ifndef NS_IMPL_GNUSTEP
7071 catch_child_signal (void)
7073 struct sigaction action
, old_action
;
7074 emacs_sigaction_init (&action
, deliver_child_signal
);
7075 block_child_signal ();
7076 sigaction (SIGCHLD
, &action
, &old_action
);
7077 eassert (! (old_action
.sa_flags
& SA_SIGINFO
));
7079 if (old_action
.sa_handler
!= deliver_child_signal
)
7081 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7083 : old_action
.sa_handler
);
7084 unblock_child_signal ();
7086 #endif /* subprocesses */
7089 /* This is not called "init_process" because that is the name of a
7090 Mach system call, so it would cause problems on Darwin systems. */
7092 init_process_emacs (void)
7097 inhibit_sentinels
= 0;
7100 if (! noninteractive
|| initialized
)
7103 #if defined HAVE_GLIB && !defined WINDOWSNT
7104 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7105 this should always fail, but is enough to initialize glib's
7106 private SIGCHLD handler, allowing catch_child_signal to copy
7107 it into lib_child_handler. */
7108 g_source_unref (g_child_watch_source_new (getpid ()));
7110 catch_child_signal ();
7113 FD_ZERO (&input_wait_mask
);
7114 FD_ZERO (&non_keyboard_wait_mask
);
7115 FD_ZERO (&non_process_wait_mask
);
7116 FD_ZERO (&write_mask
);
7117 max_process_desc
= max_input_desc
= -1;
7118 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7120 #ifdef NON_BLOCKING_CONNECT
7121 FD_ZERO (&connect_wait_mask
);
7122 num_pending_connects
= 0;
7125 #ifdef ADAPTIVE_READ_BUFFERING
7126 process_output_delay_count
= 0;
7127 process_output_skip
= 0;
7130 /* Don't do this, it caused infinite select loops. The display
7131 method should call add_keyboard_wait_descriptor on stdin if it
7134 FD_SET (0, &input_wait_mask
);
7137 Vprocess_alist
= Qnil
;
7138 deleted_pid_list
= Qnil
;
7139 for (i
= 0; i
< FD_SETSIZE
; i
++)
7141 chan_process
[i
] = Qnil
;
7142 proc_buffered_char
[i
] = -1;
7144 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7145 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7146 #ifdef DATAGRAM_SOCKETS
7147 memset (datagram_address
, 0, sizeof datagram_address
);
7151 Lisp_Object subfeatures
= Qnil
;
7152 const struct socket_options
*sopt
;
7154 #define ADD_SUBFEATURE(key, val) \
7155 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7157 #ifdef NON_BLOCKING_CONNECT
7158 ADD_SUBFEATURE (QCnowait
, Qt
);
7160 #ifdef DATAGRAM_SOCKETS
7161 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7163 #ifdef HAVE_SEQPACKET
7164 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7166 #ifdef HAVE_LOCAL_SOCKETS
7167 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7169 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7171 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7173 #ifdef HAVE_GETSOCKNAME
7174 ADD_SUBFEATURE (QCservice
, Qt
);
7176 ADD_SUBFEATURE (QCserver
, Qt
);
7178 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7179 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7181 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7184 #if defined (DARWIN_OS)
7185 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7186 processes. As such, we only change the default value. */
7189 char const *release
= (STRINGP (Voperating_system_release
)
7190 ? SSDATA (Voperating_system_release
)
7192 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7193 Vprocess_connection_type
= Qnil
;
7197 #endif /* subprocesses */
7202 syms_of_process (void)
7206 DEFSYM (Qprocessp
, "processp");
7207 DEFSYM (Qrun
, "run");
7208 DEFSYM (Qstop
, "stop");
7209 DEFSYM (Qsignal
, "signal");
7211 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7214 Qexit = intern_c_string ("exit");
7215 staticpro (&Qexit); */
7217 DEFSYM (Qopen
, "open");
7218 DEFSYM (Qclosed
, "closed");
7219 DEFSYM (Qconnect
, "connect");
7220 DEFSYM (Qfailed
, "failed");
7221 DEFSYM (Qlisten
, "listen");
7222 DEFSYM (Qlocal
, "local");
7223 DEFSYM (Qipv4
, "ipv4");
7225 DEFSYM (Qipv6
, "ipv6");
7227 DEFSYM (Qdatagram
, "datagram");
7228 DEFSYM (Qseqpacket
, "seqpacket");
7230 DEFSYM (QCport
, ":port");
7231 DEFSYM (QCspeed
, ":speed");
7232 DEFSYM (QCprocess
, ":process");
7234 DEFSYM (QCbytesize
, ":bytesize");
7235 DEFSYM (QCstopbits
, ":stopbits");
7236 DEFSYM (QCparity
, ":parity");
7237 DEFSYM (Qodd
, "odd");
7238 DEFSYM (Qeven
, "even");
7239 DEFSYM (QCflowcontrol
, ":flowcontrol");
7242 DEFSYM (QCsummary
, ":summary");
7244 DEFSYM (Qreal
, "real");
7245 DEFSYM (Qnetwork
, "network");
7246 DEFSYM (Qserial
, "serial");
7247 DEFSYM (QCbuffer
, ":buffer");
7248 DEFSYM (QChost
, ":host");
7249 DEFSYM (QCservice
, ":service");
7250 DEFSYM (QClocal
, ":local");
7251 DEFSYM (QCremote
, ":remote");
7252 DEFSYM (QCcoding
, ":coding");
7253 DEFSYM (QCserver
, ":server");
7254 DEFSYM (QCnowait
, ":nowait");
7255 DEFSYM (QCsentinel
, ":sentinel");
7256 DEFSYM (QClog
, ":log");
7257 DEFSYM (QCnoquery
, ":noquery");
7258 DEFSYM (QCstop
, ":stop");
7259 DEFSYM (QCoptions
, ":options");
7260 DEFSYM (QCplist
, ":plist");
7262 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7264 staticpro (&Vprocess_alist
);
7265 staticpro (&deleted_pid_list
);
7267 #endif /* subprocesses */
7269 DEFSYM (QCname
, ":name");
7270 DEFSYM (QCtype
, ":type");
7272 DEFSYM (Qeuid
, "euid");
7273 DEFSYM (Qegid
, "egid");
7274 DEFSYM (Quser
, "user");
7275 DEFSYM (Qgroup
, "group");
7276 DEFSYM (Qcomm
, "comm");
7277 DEFSYM (Qstate
, "state");
7278 DEFSYM (Qppid
, "ppid");
7279 DEFSYM (Qpgrp
, "pgrp");
7280 DEFSYM (Qsess
, "sess");
7281 DEFSYM (Qttname
, "ttname");
7282 DEFSYM (Qtpgid
, "tpgid");
7283 DEFSYM (Qminflt
, "minflt");
7284 DEFSYM (Qmajflt
, "majflt");
7285 DEFSYM (Qcminflt
, "cminflt");
7286 DEFSYM (Qcmajflt
, "cmajflt");
7287 DEFSYM (Qutime
, "utime");
7288 DEFSYM (Qstime
, "stime");
7289 DEFSYM (Qtime
, "time");
7290 DEFSYM (Qcutime
, "cutime");
7291 DEFSYM (Qcstime
, "cstime");
7292 DEFSYM (Qctime
, "ctime");
7294 DEFSYM (Qinternal_default_process_sentinel
,
7295 "internal-default-process-sentinel");
7296 DEFSYM (Qinternal_default_process_filter
,
7297 "internal-default-process-filter");
7299 DEFSYM (Qpri
, "pri");
7300 DEFSYM (Qnice
, "nice");
7301 DEFSYM (Qthcount
, "thcount");
7302 DEFSYM (Qstart
, "start");
7303 DEFSYM (Qvsize
, "vsize");
7304 DEFSYM (Qrss
, "rss");
7305 DEFSYM (Qetime
, "etime");
7306 DEFSYM (Qpcpu
, "pcpu");
7307 DEFSYM (Qpmem
, "pmem");
7308 DEFSYM (Qargs
, "args");
7310 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7311 doc
: /* Non-nil means delete processes immediately when they exit.
7312 A value of nil means don't delete them until `list-processes' is run. */);
7314 delete_exited_processes
= 1;
7317 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7318 doc
: /* Control type of device used to communicate with subprocesses.
7319 Values are nil to use a pipe, or t or `pty' to use a pty.
7320 The value has no effect if the system has no ptys or if all ptys are busy:
7321 then a pipe is used in any case.
7322 The value takes effect when `start-process' is called. */);
7323 Vprocess_connection_type
= Qt
;
7325 #ifdef ADAPTIVE_READ_BUFFERING
7326 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7327 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7328 On some systems, when Emacs reads the output from a subprocess, the output data
7329 is read in very small blocks, potentially resulting in very poor performance.
7330 This behavior can be remedied to some extent by setting this variable to a
7331 non-nil value, as it will automatically delay reading from such processes, to
7332 allow them to produce more output before Emacs tries to read it.
7333 If the value is t, the delay is reset after each write to the process; any other
7334 non-nil value means that the delay is not reset on write.
7335 The variable takes effect when `start-process' is called. */);
7336 Vprocess_adaptive_read_buffering
= Qt
;
7339 defsubr (&Sprocessp
);
7340 defsubr (&Sget_process
);
7341 defsubr (&Sdelete_process
);
7342 defsubr (&Sprocess_status
);
7343 defsubr (&Sprocess_exit_status
);
7344 defsubr (&Sprocess_id
);
7345 defsubr (&Sprocess_name
);
7346 defsubr (&Sprocess_tty_name
);
7347 defsubr (&Sprocess_command
);
7348 defsubr (&Sset_process_buffer
);
7349 defsubr (&Sprocess_buffer
);
7350 defsubr (&Sprocess_mark
);
7351 defsubr (&Sset_process_filter
);
7352 defsubr (&Sprocess_filter
);
7353 defsubr (&Sset_process_sentinel
);
7354 defsubr (&Sprocess_sentinel
);
7355 defsubr (&Sset_process_window_size
);
7356 defsubr (&Sset_process_inherit_coding_system_flag
);
7357 defsubr (&Sset_process_query_on_exit_flag
);
7358 defsubr (&Sprocess_query_on_exit_flag
);
7359 defsubr (&Sprocess_contact
);
7360 defsubr (&Sprocess_plist
);
7361 defsubr (&Sset_process_plist
);
7362 defsubr (&Sprocess_list
);
7363 defsubr (&Sstart_process
);
7364 defsubr (&Sserial_process_configure
);
7365 defsubr (&Smake_serial_process
);
7366 defsubr (&Sset_network_process_option
);
7367 defsubr (&Smake_network_process
);
7368 defsubr (&Sformat_network_address
);
7369 defsubr (&Snetwork_interface_list
);
7370 defsubr (&Snetwork_interface_info
);
7371 #ifdef DATAGRAM_SOCKETS
7372 defsubr (&Sprocess_datagram_address
);
7373 defsubr (&Sset_process_datagram_address
);
7375 defsubr (&Saccept_process_output
);
7376 defsubr (&Sprocess_send_region
);
7377 defsubr (&Sprocess_send_string
);
7378 defsubr (&Sinterrupt_process
);
7379 defsubr (&Skill_process
);
7380 defsubr (&Squit_process
);
7381 defsubr (&Sstop_process
);
7382 defsubr (&Scontinue_process
);
7383 defsubr (&Sprocess_running_child_p
);
7384 defsubr (&Sprocess_send_eof
);
7385 defsubr (&Ssignal_process
);
7386 defsubr (&Swaiting_for_user_input_p
);
7387 defsubr (&Sprocess_type
);
7388 defsubr (&Sinternal_default_process_sentinel
);
7389 defsubr (&Sinternal_default_process_filter
);
7390 defsubr (&Sset_process_coding_system
);
7391 defsubr (&Sprocess_coding_system
);
7392 defsubr (&Sset_process_filter_multibyte
);
7393 defsubr (&Sprocess_filter_multibyte_p
);
7395 #endif /* subprocesses */
7397 defsubr (&Sget_buffer_process
);
7398 defsubr (&Sprocess_inherit_coding_system_flag
);
7399 defsubr (&Slist_system_processes
);
7400 defsubr (&Sprocess_attributes
);