1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
34 /* Only MS-DOS does not define `subprocesses'. */
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
48 #define HAVE_LOCAL_SOCKETS
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
79 #include <arpa/nameser.h>
95 #endif /* subprocesses */
101 #include "character.h"
106 #include "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 /* True if keyboard input is on hold, zero otherwise. */
146 static bool kbd_is_on_hold
;
148 /* Nonzero means don't run process sentinels. This is used
150 bool inhibit_sentinels
;
155 # define SOCK_CLOEXEC 0
160 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
163 close_on_exec (int fd
)
166 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
171 # define accept4(sockfd, addr, addrlen, flags) \
172 process_accept4 (sockfd, addr, addrlen, flags)
174 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
176 return close_on_exec (accept (sockfd
, addr
, addrlen
));
180 process_socket (int domain
, int type
, int protocol
)
182 return close_on_exec (socket (domain
, type
, protocol
));
185 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
188 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
189 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
190 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
191 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
193 /* Number of events of change of status of a process. */
194 static EMACS_INT process_tick
;
195 /* Number of events for which the user or sentinel has been notified. */
196 static EMACS_INT update_tick
;
198 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
199 The code can be simplified by assuming NON_BLOCKING_CONNECT once
200 Emacs starts assuming POSIX 1003.1-2001 or later. */
202 #if (defined HAVE_SELECT \
203 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
204 && (defined EWOULDBLOCK || defined EINPROGRESS))
205 # define NON_BLOCKING_CONNECT
208 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
209 this system. We need to read full packets, so we need a
210 "non-destructive" select. So we require either native select,
211 or emulation of select using FIONREAD. */
213 #ifndef BROKEN_DATAGRAM_SOCKETS
214 # if defined HAVE_SELECT || defined USABLE_FIONREAD
215 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
216 # define DATAGRAM_SOCKETS
221 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
222 # define HAVE_SEQPACKET
225 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
226 #define ADAPTIVE_READ_BUFFERING
229 #ifdef ADAPTIVE_READ_BUFFERING
230 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
231 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
232 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
234 /* Number of processes which have a non-zero read_output_delay,
235 and therefore might be delayed for adaptive read buffering. */
237 static int process_output_delay_count
;
239 /* True if any process has non-nil read_output_skip. */
241 static bool process_output_skip
;
244 #define process_output_delay_count 0
247 static void create_process (Lisp_Object
, char **, Lisp_Object
);
249 static bool keyboard_bit_set (fd_set
*);
251 static void deactivate_process (Lisp_Object
);
252 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
253 static int read_process_output (Lisp_Object
, int);
254 static void handle_child_signal (int);
255 static void create_pty (Lisp_Object
);
257 static Lisp_Object
get_process (register Lisp_Object name
);
258 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
260 /* Mask of bits indicating the descriptors that we wait for input on. */
262 static fd_set input_wait_mask
;
264 /* Mask that excludes keyboard input descriptor(s). */
266 static fd_set non_keyboard_wait_mask
;
268 /* Mask that excludes process input descriptor(s). */
270 static fd_set non_process_wait_mask
;
272 /* Mask for selecting for write. */
274 static fd_set write_mask
;
276 #ifdef NON_BLOCKING_CONNECT
277 /* Mask of bits indicating the descriptors that we wait for connect to
278 complete on. Once they complete, they are removed from this mask
279 and added to the input_wait_mask and non_keyboard_wait_mask. */
281 static fd_set connect_wait_mask
;
283 /* Number of bits set in connect_wait_mask. */
284 static int num_pending_connects
;
285 #endif /* NON_BLOCKING_CONNECT */
287 /* The largest descriptor currently in use for a process object; -1 if none. */
288 static int max_process_desc
;
290 /* The largest descriptor currently in use for input; -1 if none. */
291 static int max_input_desc
;
293 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
294 static Lisp_Object chan_process
[FD_SETSIZE
];
296 /* Alist of elements (NAME . PROCESS). */
297 static Lisp_Object Vprocess_alist
;
299 /* Buffered-ahead input char from process, indexed by channel.
300 -1 means empty (no char is buffered).
301 Used on sys V where the only way to tell if there is any
302 output from the process is to read at least one char.
303 Always -1 on systems that support FIONREAD. */
305 static int proc_buffered_char
[FD_SETSIZE
];
307 /* Table of `struct coding-system' for each process. */
308 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
309 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
311 #ifdef DATAGRAM_SOCKETS
312 /* Table of `partner address' for datagram sockets. */
313 static struct sockaddr_and_len
{
316 } datagram_address
[FD_SETSIZE
];
317 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
318 #define DATAGRAM_CONN_P(proc) \
319 (PROCESSP (proc) && \
320 XPROCESS (proc)->infd >= 0 && \
321 datagram_address[XPROCESS (proc)->infd].sa != 0)
323 #define DATAGRAM_CHAN_P(chan) (0)
324 #define DATAGRAM_CONN_P(proc) (0)
327 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
328 a `for' loop which iterates over processes from Vprocess_alist. */
330 #define FOR_EACH_PROCESS(list_var, proc_var) \
331 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
333 /* These setters are used only in this file, so they can be private. */
335 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
340 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
345 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
347 p
->decode_coding_system
= val
;
350 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
352 p
->decoding_buf
= val
;
355 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
357 p
->encode_coding_system
= val
;
360 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
362 p
->encoding_buf
= val
;
365 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
367 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
370 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
375 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
380 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
385 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
390 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
392 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
395 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
400 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
405 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
410 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
412 p
->write_queue
= val
;
417 make_lisp_proc (struct Lisp_Process
*p
)
419 return make_lisp_ptr (p
, Lisp_Vectorlike
);
422 static struct fd_callback_data
428 int condition
; /* Mask of the defines above. */
429 } fd_callback_info
[FD_SETSIZE
];
432 /* Add a file descriptor FD to be monitored for when read is possible.
433 When read is possible, call FUNC with argument DATA. */
436 add_read_fd (int fd
, fd_callback func
, void *data
)
438 add_keyboard_wait_descriptor (fd
);
440 fd_callback_info
[fd
].func
= func
;
441 fd_callback_info
[fd
].data
= data
;
442 fd_callback_info
[fd
].condition
|= FOR_READ
;
445 /* Stop monitoring file descriptor FD for when read is possible. */
448 delete_read_fd (int fd
)
450 delete_keyboard_wait_descriptor (fd
);
452 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
453 if (fd_callback_info
[fd
].condition
== 0)
455 fd_callback_info
[fd
].func
= 0;
456 fd_callback_info
[fd
].data
= 0;
460 /* Add a file descriptor FD to be monitored for when write is possible.
461 When write is possible, call FUNC with argument DATA. */
464 add_write_fd (int fd
, fd_callback func
, void *data
)
466 FD_SET (fd
, &write_mask
);
467 if (fd
> max_input_desc
)
470 fd_callback_info
[fd
].func
= func
;
471 fd_callback_info
[fd
].data
= data
;
472 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
475 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
478 delete_input_desc (int fd
)
480 if (fd
== max_input_desc
)
484 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
485 || FD_ISSET (fd
, &write_mask
)));
491 /* Stop monitoring file descriptor FD for when write is possible. */
494 delete_write_fd (int fd
)
496 FD_CLR (fd
, &write_mask
);
497 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
498 if (fd_callback_info
[fd
].condition
== 0)
500 fd_callback_info
[fd
].func
= 0;
501 fd_callback_info
[fd
].data
= 0;
502 delete_input_desc (fd
);
507 /* Compute the Lisp form of the process status, p->status, from
508 the numeric status that was returned by `wait'. */
510 static Lisp_Object
status_convert (int);
513 update_status (struct Lisp_Process
*p
)
515 eassert (p
->raw_status_new
);
516 pset_status (p
, status_convert (p
->raw_status
));
517 p
->raw_status_new
= 0;
520 /* Convert a process status word in Unix format to
521 the list that we use internally. */
524 status_convert (int w
)
527 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
528 else if (WIFEXITED (w
))
529 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
530 WCOREDUMP (w
) ? Qt
: Qnil
));
531 else if (WIFSIGNALED (w
))
532 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
533 WCOREDUMP (w
) ? Qt
: Qnil
));
538 /* Given a status-list, extract the three pieces of information
539 and store them individually through the three pointers. */
542 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
556 *code
= XFASTINT (XCAR (tem
));
558 *coredump
= !NILP (tem
);
562 /* Return a string describing a process status list. */
565 status_message (struct Lisp_Process
*p
)
567 Lisp_Object status
= p
->status
;
573 decode_status (status
, &symbol
, &code
, &coredump
);
575 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
578 synchronize_system_messages_locale ();
579 signame
= strsignal (code
);
581 string
= build_string ("unknown");
586 string
= build_unibyte_string (signame
);
587 if (! NILP (Vlocale_coding_system
))
588 string
= (code_convert_string_norecord
589 (string
, Vlocale_coding_system
, 0));
590 c1
= STRING_CHAR (SDATA (string
));
593 Faset (string
, make_number (0), make_number (c2
));
595 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
596 return concat2 (string
, suffix
);
598 else if (EQ (symbol
, Qexit
))
601 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
603 return build_string ("finished\n");
604 AUTO_STRING (prefix
, "exited abnormally with code ");
605 string
= Fnumber_to_string (make_number (code
));
606 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
607 return concat3 (prefix
, string
, suffix
);
609 else if (EQ (symbol
, Qfailed
))
611 AUTO_STRING (prefix
, "failed with code ");
612 string
= Fnumber_to_string (make_number (code
));
613 AUTO_STRING (suffix
, "\n");
614 return concat3 (prefix
, string
, suffix
);
617 return Fcopy_sequence (Fsymbol_name (symbol
));
620 enum { PTY_NAME_SIZE
= 24 };
622 /* Open an available pty, returning a file descriptor.
623 Store into PTY_NAME the file name of the terminal corresponding to the pty.
624 Return -1 on failure. */
627 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
636 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
637 for (i
= 0; i
< 16; i
++)
640 #ifdef PTY_NAME_SPRINTF
643 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
644 #endif /* no PTY_NAME_SPRINTF */
648 #else /* no PTY_OPEN */
649 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
650 #endif /* no PTY_OPEN */
655 /* Set FD's close-on-exec flag. This is needed even if
656 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
657 doesn't require support for that combination.
658 Multithreaded platforms where posix_openpt ignores
659 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
660 have a race condition between the PTY_OPEN and here. */
661 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
663 /* Check to make certain that both sides are available
664 this avoids a nasty yet stupid bug in rlogins. */
665 #ifdef PTY_TTY_NAME_SPRINTF
668 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
669 #endif /* no PTY_TTY_NAME_SPRINTF */
670 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
683 #endif /* HAVE_PTYS */
687 /* Allocate basically initialized process. */
689 static struct Lisp_Process
*
690 allocate_process (void)
692 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
696 make_process (Lisp_Object name
)
698 register Lisp_Object val
, tem
, name1
;
699 register struct Lisp_Process
*p
;
700 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
703 p
= allocate_process ();
704 /* Initialize Lisp data. Note that allocate_process initializes all
705 Lisp data to nil, so do it only for slots which should not be nil. */
706 pset_status (p
, Qrun
);
707 pset_mark (p
, Fmake_marker ());
709 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
710 non-Lisp data, so do it only for slots which should not be zero. */
713 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
717 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
720 /* If name is already in use, modify it until it is unused. */
725 tem
= Fget_process (name1
);
726 if (NILP (tem
)) break;
727 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
731 pset_sentinel (p
, Qinternal_default_process_sentinel
);
732 pset_filter (p
, Qinternal_default_process_filter
);
733 XSETPROCESS (val
, p
);
734 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
739 remove_process (register Lisp_Object proc
)
741 register Lisp_Object pair
;
743 pair
= Frassq (proc
, Vprocess_alist
);
744 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
746 deactivate_process (proc
);
750 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
751 doc
: /* Return t if OBJECT is a process. */)
754 return PROCESSP (object
) ? Qt
: Qnil
;
757 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
758 doc
: /* Return the process named NAME, or nil if there is none. */)
759 (register Lisp_Object name
)
764 return Fcdr (Fassoc (name
, Vprocess_alist
));
767 /* This is how commands for the user decode process arguments. It
768 accepts a process, a process name, a buffer, a buffer name, or nil.
769 Buffers denote the first process in the buffer, and nil denotes the
773 get_process (register Lisp_Object name
)
775 register Lisp_Object proc
, obj
;
778 obj
= Fget_process (name
);
780 obj
= Fget_buffer (name
);
782 error ("Process %s does not exist", SDATA (name
));
784 else if (NILP (name
))
785 obj
= Fcurrent_buffer ();
789 /* Now obj should be either a buffer object or a process object. */
792 if (NILP (BVAR (XBUFFER (obj
), name
)))
793 error ("Attempt to get process for a dead buffer");
794 proc
= Fget_buffer_process (obj
);
796 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
807 /* Fdelete_process promises to immediately forget about the process, but in
808 reality, Emacs needs to remember those processes until they have been
809 treated by the SIGCHLD handler and waitpid has been invoked on them;
810 otherwise they might fill up the kernel's process table.
812 Some processes created by call-process are also put onto this list.
814 Members of this list are (process-ID . filename) pairs. The
815 process-ID is a number; the filename, if a string, is a file that
816 needs to be removed after the process exits. */
817 static Lisp_Object deleted_pid_list
;
820 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
822 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
823 /* GC treated elements set to nil. */
824 Fdelq (Qnil
, deleted_pid_list
));
828 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
829 doc
: /* Delete PROCESS: kill it and forget about it immediately.
830 PROCESS may be a process, a buffer, the name of a process or buffer, or
831 nil, indicating the current buffer's process. */)
832 (register Lisp_Object process
)
834 register struct Lisp_Process
*p
;
836 process
= get_process (process
);
837 p
= XPROCESS (process
);
839 p
->raw_status_new
= 0;
840 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
842 pset_status (p
, list2 (Qexit
, make_number (0)));
843 p
->tick
= ++process_tick
;
844 status_notify (p
, NULL
);
845 redisplay_preserve_echo_area (13);
850 record_kill_process (p
, Qnil
);
854 /* Update P's status, since record_kill_process will make the
855 SIGCHLD handler update deleted_pid_list, not *P. */
857 if (p
->raw_status_new
)
859 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
860 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
861 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
863 p
->tick
= ++process_tick
;
864 status_notify (p
, NULL
);
865 redisplay_preserve_echo_area (13);
868 remove_process (process
);
872 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
873 doc
: /* Return the status of PROCESS.
874 The returned value is one of the following symbols:
875 run -- for a process that is running.
876 stop -- for a process stopped but continuable.
877 exit -- for a process that has exited.
878 signal -- for a process that has got a fatal signal.
879 open -- for a network stream connection that is open.
880 listen -- for a network stream server that is listening.
881 closed -- for a network stream connection that is closed.
882 connect -- when waiting for a non-blocking connection to complete.
883 failed -- when a non-blocking connection has failed.
884 nil -- if arg is a process name and no such process exists.
885 PROCESS may be a process, a buffer, the name of a process, or
886 nil, indicating the current buffer's process. */)
887 (register Lisp_Object process
)
889 register struct Lisp_Process
*p
;
890 register Lisp_Object status
;
892 if (STRINGP (process
))
893 process
= Fget_process (process
);
895 process
= get_process (process
);
900 p
= XPROCESS (process
);
901 if (p
->raw_status_new
)
905 status
= XCAR (status
);
906 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
908 if (EQ (status
, Qexit
))
910 else if (EQ (p
->command
, Qt
))
912 else if (EQ (status
, Qrun
))
918 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
920 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
921 If PROCESS has not yet exited or died, return 0. */)
922 (register Lisp_Object process
)
924 CHECK_PROCESS (process
);
925 if (XPROCESS (process
)->raw_status_new
)
926 update_status (XPROCESS (process
));
927 if (CONSP (XPROCESS (process
)->status
))
928 return XCAR (XCDR (XPROCESS (process
)->status
));
929 return make_number (0);
932 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
933 doc
: /* Return the process id of PROCESS.
934 This is the pid of the external process which PROCESS uses or talks to.
935 For a network connection, this value is nil. */)
936 (register Lisp_Object process
)
940 CHECK_PROCESS (process
);
941 pid
= XPROCESS (process
)->pid
;
942 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
945 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
946 doc
: /* Return the name of PROCESS, as a string.
947 This is the name of the program invoked in PROCESS,
948 possibly modified to make it unique among process names. */)
949 (register Lisp_Object process
)
951 CHECK_PROCESS (process
);
952 return XPROCESS (process
)->name
;
955 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
956 doc
: /* Return the command that was executed to start PROCESS.
957 This is a list of strings, the first string being the program executed
958 and the rest of the strings being the arguments given to it.
959 For a network or serial process, this is nil (process is running) or t
960 \(process is stopped). */)
961 (register Lisp_Object process
)
963 CHECK_PROCESS (process
);
964 return XPROCESS (process
)->command
;
967 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
968 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
969 This is the terminal that the process itself reads and writes on,
970 not the name of the pty that Emacs uses to talk with that terminal. */)
971 (register Lisp_Object process
)
973 CHECK_PROCESS (process
);
974 return XPROCESS (process
)->tty_name
;
977 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
979 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
981 (register Lisp_Object process
, Lisp_Object buffer
)
983 struct Lisp_Process
*p
;
985 CHECK_PROCESS (process
);
987 CHECK_BUFFER (buffer
);
988 p
= XPROCESS (process
);
989 pset_buffer (p
, buffer
);
990 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
991 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
992 setup_process_coding_systems (process
);
996 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
998 doc
: /* Return the buffer PROCESS is associated with.
999 The default process filter inserts output from PROCESS into this buffer. */)
1000 (register Lisp_Object process
)
1002 CHECK_PROCESS (process
);
1003 return XPROCESS (process
)->buffer
;
1006 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1008 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1009 (register Lisp_Object process
)
1011 CHECK_PROCESS (process
);
1012 return XPROCESS (process
)->mark
;
1015 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1017 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1018 A value of t means stop accepting output from the process.
1020 When a process has a non-default filter, its buffer is not used for output.
1021 Instead, each time it does output, the entire string of output is
1022 passed to the filter.
1024 The filter gets two arguments: the process and the string of output.
1025 The string argument is normally a multibyte string, except:
1026 - if the process's input coding system is no-conversion or raw-text,
1027 it is a unibyte string (the non-converted input), or else
1028 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1029 string (the result of converting the decoded input multibyte
1030 string to unibyte with `string-make-unibyte'). */)
1031 (register Lisp_Object process
, Lisp_Object filter
)
1033 struct Lisp_Process
*p
;
1035 CHECK_PROCESS (process
);
1036 p
= XPROCESS (process
);
1038 /* Don't signal an error if the process's input file descriptor
1039 is closed. This could make debugging Lisp more difficult,
1040 for example when doing something like
1042 (setq process (start-process ...))
1044 (set-process-filter process ...) */
1047 filter
= Qinternal_default_process_filter
;
1051 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1053 FD_CLR (p
->infd
, &input_wait_mask
);
1054 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1056 else if (EQ (p
->filter
, Qt
)
1057 /* Network or serial process not stopped: */
1058 && !EQ (p
->command
, Qt
))
1060 FD_SET (p
->infd
, &input_wait_mask
);
1061 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1065 pset_filter (p
, filter
);
1066 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1067 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1068 setup_process_coding_systems (process
);
1072 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1074 doc
: /* Return the filter function of PROCESS.
1075 See `set-process-filter' for more info on filter functions. */)
1076 (register Lisp_Object process
)
1078 CHECK_PROCESS (process
);
1079 return XPROCESS (process
)->filter
;
1082 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1084 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1085 The sentinel is called as a function when the process changes state.
1086 It gets two arguments: the process, and a string describing the change. */)
1087 (register Lisp_Object process
, Lisp_Object sentinel
)
1089 struct Lisp_Process
*p
;
1091 CHECK_PROCESS (process
);
1092 p
= XPROCESS (process
);
1094 if (NILP (sentinel
))
1095 sentinel
= Qinternal_default_process_sentinel
;
1097 pset_sentinel (p
, sentinel
);
1098 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1099 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1103 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1105 doc
: /* Return the sentinel of PROCESS.
1106 See `set-process-sentinel' for more info on sentinels. */)
1107 (register Lisp_Object process
)
1109 CHECK_PROCESS (process
);
1110 return XPROCESS (process
)->sentinel
;
1113 DEFUN ("set-process-window-size", Fset_process_window_size
,
1114 Sset_process_window_size
, 3, 3, 0,
1115 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1116 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1118 CHECK_PROCESS (process
);
1120 /* All known platforms store window sizes as 'unsigned short'. */
1121 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1122 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1124 if (XPROCESS (process
)->infd
< 0
1125 || (set_window_size (XPROCESS (process
)->infd
,
1126 XINT (height
), XINT (width
))
1133 DEFUN ("set-process-inherit-coding-system-flag",
1134 Fset_process_inherit_coding_system_flag
,
1135 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1136 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1137 If the second argument FLAG is non-nil, then the variable
1138 `buffer-file-coding-system' of the buffer associated with PROCESS
1139 will be bound to the value of the coding system used to decode
1142 This is useful when the coding system specified for the process buffer
1143 leaves either the character code conversion or the end-of-line conversion
1144 unspecified, or if the coding system used to decode the process output
1145 is more appropriate for saving the process buffer.
1147 Binding the variable `inherit-process-coding-system' to non-nil before
1148 starting the process is an alternative way of setting the inherit flag
1149 for the process which will run.
1151 This function returns FLAG. */)
1152 (register Lisp_Object process
, Lisp_Object flag
)
1154 CHECK_PROCESS (process
);
1155 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1159 DEFUN ("set-process-query-on-exit-flag",
1160 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1162 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1163 If the second argument FLAG is non-nil, Emacs will query the user before
1164 exiting or killing a buffer if PROCESS is running. This function
1166 (register Lisp_Object process
, Lisp_Object flag
)
1168 CHECK_PROCESS (process
);
1169 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1173 DEFUN ("process-query-on-exit-flag",
1174 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1176 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1177 (register Lisp_Object process
)
1179 CHECK_PROCESS (process
);
1180 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1183 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1185 doc
: /* Return the contact info of PROCESS; t for a real child.
1186 For a network or serial connection, the value depends on the optional
1187 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1188 SERVICE) for a network connection or (PORT SPEED) for a serial
1189 connection. If KEY is t, the complete contact information for the
1190 connection is returned, else the specific value for the keyword KEY is
1191 returned. See `make-network-process' or `make-serial-process' for a
1192 list of keywords. */)
1193 (register Lisp_Object process
, Lisp_Object key
)
1195 Lisp_Object contact
;
1197 CHECK_PROCESS (process
);
1198 contact
= XPROCESS (process
)->childp
;
1200 #ifdef DATAGRAM_SOCKETS
1201 if (DATAGRAM_CONN_P (process
)
1202 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1203 contact
= Fplist_put (contact
, QCremote
,
1204 Fprocess_datagram_address (process
));
1207 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1209 if (NILP (key
) && NETCONN_P (process
))
1210 return list2 (Fplist_get (contact
, QChost
),
1211 Fplist_get (contact
, QCservice
));
1212 if (NILP (key
) && SERIALCONN_P (process
))
1213 return list2 (Fplist_get (contact
, QCport
),
1214 Fplist_get (contact
, QCspeed
));
1215 return Fplist_get (contact
, key
);
1218 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1220 doc
: /* Return the plist of PROCESS. */)
1221 (register Lisp_Object process
)
1223 CHECK_PROCESS (process
);
1224 return XPROCESS (process
)->plist
;
1227 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1229 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1230 (register Lisp_Object process
, Lisp_Object plist
)
1232 CHECK_PROCESS (process
);
1235 pset_plist (XPROCESS (process
), plist
);
1239 #if 0 /* Turned off because we don't currently record this info
1240 in the process. Perhaps add it. */
1241 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1242 doc
: /* Return the connection type of PROCESS.
1243 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1244 a socket connection. */)
1245 (Lisp_Object process
)
1247 return XPROCESS (process
)->type
;
1251 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1252 doc
: /* Return the connection type of PROCESS.
1253 The value is either the symbol `real', `network', or `serial'.
1254 PROCESS may be a process, a buffer, the name of a process or buffer, or
1255 nil, indicating the current buffer's process. */)
1256 (Lisp_Object process
)
1259 proc
= get_process (process
);
1260 return XPROCESS (proc
)->type
;
1263 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1265 doc
: /* Convert network ADDRESS from internal format to a string.
1266 A 4 or 5 element vector represents an IPv4 address (with port number).
1267 An 8 or 9 element vector represents an IPv6 address (with port number).
1268 If optional second argument OMIT-PORT is non-nil, don't include a port
1269 number in the string, even when present in ADDRESS.
1270 Returns nil if format of ADDRESS is invalid. */)
1271 (Lisp_Object address
, Lisp_Object omit_port
)
1276 if (STRINGP (address
)) /* AF_LOCAL */
1279 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1281 register struct Lisp_Vector
*p
= XVECTOR (address
);
1282 ptrdiff_t size
= p
->header
.size
;
1283 Lisp_Object args
[10];
1287 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1289 format
= "%d.%d.%d.%d";
1294 format
= "%d.%d.%d.%d:%d";
1297 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1299 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1304 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1310 AUTO_STRING (format_obj
, format
);
1311 args
[0] = format_obj
;
1313 for (i
= 0; i
< nargs
; i
++)
1315 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1318 if (nargs
<= 5 /* IPv4 */
1319 && i
< 4 /* host, not port */
1320 && XINT (p
->contents
[i
]) > 255)
1323 args
[i
+ 1] = p
->contents
[i
];
1326 return Fformat (nargs
+ 1, args
);
1329 if (CONSP (address
))
1331 AUTO_STRING (format
, "<Family %d>");
1332 return CALLN (Fformat
, format
, Fcar (address
));
1338 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1339 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1342 return Fmapcar (Qcdr
, Vprocess_alist
);
1345 /* Starting asynchronous inferior processes. */
1347 static void start_process_unwind (Lisp_Object proc
);
1349 DEFUN ("make-process", Fmake_process
, Smake_process
, 0, MANY
, 0,
1350 doc
: /* Start a program in a subprocess. Return the process object for it.
1352 This is similar to `start-process', but arguments are specified as
1353 keyword/argument pairs. The following arguments are defined:
1355 :name NAME -- NAME is name for process. It is modified if necessary
1358 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1359 with the process. Process output goes at end of that buffer, unless
1360 you specify an output stream or filter function to handle the output.
1361 BUFFER may be also nil, meaning that this process is not associated
1364 :command COMMAND -- COMMAND is a list starting with the program file
1365 name, followed by strings to give to the program as arguments.
1367 :coding CODING -- If CODING is a symbol, it specifies the coding
1368 system used for both reading and writing for this process. If CODING
1369 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1370 ENCODING is used for writing.
1372 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1373 the process is running. If BOOL is not given, query before exiting.
1375 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1376 In the stopped state, a process does not accept incoming data, but you
1377 can send outgoing data. The stopped state is cleared by
1378 `continue-process' and set by `stop-process'.
1380 :connection-type TYPE -- TYPE is control type of device used to
1381 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1382 to use a pty, or nil to use the default specified through
1383 `process-connection-type'.
1385 :filter FILTER -- Install FILTER as the process filter.
1387 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1389 usage: (make-process &rest ARGS) */)
1390 (ptrdiff_t nargs
, Lisp_Object
*args
)
1392 Lisp_Object buffer
, name
, command
, program
, proc
, contact
, current_dir
, tem
;
1393 ptrdiff_t count
= SPECPDL_INDEX ();
1394 struct gcpro gcpro1
;
1400 /* Save arguments for process-contact and clone-process. */
1401 contact
= Flist (nargs
, args
);
1404 buffer
= Fplist_get (contact
, QCbuffer
);
1406 buffer
= Fget_buffer_create (buffer
);
1408 /* Make sure that the child will be able to chdir to the current
1409 buffer's current directory, or its unhandled equivalent. We
1410 can't just have the child check for an error when it does the
1411 chdir, since it's in a vfork.
1413 We have to GCPRO around this because Fexpand_file_name and
1414 Funhandled_file_name_directory might call a file name handling
1415 function. The argument list is protected by the caller, so all
1416 we really have to worry about is buffer. */
1418 struct gcpro gcpro1
;
1420 current_dir
= encode_current_directory ();
1424 name
= Fplist_get (contact
, QCname
);
1425 CHECK_STRING (name
);
1427 command
= Fplist_get (contact
, QCcommand
);
1428 if (CONSP (command
))
1429 program
= XCAR (command
);
1433 if (!NILP (program
))
1434 CHECK_STRING (program
);
1436 proc
= make_process (name
);
1437 /* If an error occurs and we can't start the process, we want to
1438 remove it from the process list. This means that each error
1439 check in create_process doesn't need to call remove_process
1440 itself; it's all taken care of here. */
1441 record_unwind_protect (start_process_unwind
, proc
);
1443 pset_childp (XPROCESS (proc
), Qt
);
1444 pset_plist (XPROCESS (proc
), Qnil
);
1445 pset_type (XPROCESS (proc
), Qreal
);
1446 pset_buffer (XPROCESS (proc
), buffer
);
1447 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1448 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1449 pset_command (XPROCESS (proc
), Fcopy_sequence (command
));
1451 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
1452 XPROCESS (proc
)->kill_without_query
= 1;
1453 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
1454 pset_command (XPROCESS (proc
), Qt
);
1456 tem
= Fplist_get (contact
, QCconnection_type
);
1458 XPROCESS (proc
)->pty_flag
= true;
1459 else if (EQ (tem
, Qpipe
))
1460 XPROCESS (proc
)->pty_flag
= false;
1461 else if (NILP (tem
))
1462 XPROCESS (proc
)->pty_flag
= !NILP (Vprocess_connection_type
);
1464 report_file_error ("Unknown connection type", tem
);
1467 /* AKA GNUTLS_INITSTAGE(proc). */
1468 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1469 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1472 #ifdef ADAPTIVE_READ_BUFFERING
1473 XPROCESS (proc
)->adaptive_read_buffering
1474 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1475 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1478 /* Make the process marker point into the process buffer (if any). */
1479 if (BUFFERP (buffer
))
1480 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1481 BUF_ZV (XBUFFER (buffer
)),
1482 BUF_ZV_BYTE (XBUFFER (buffer
)));
1485 /* Decide coding systems for communicating with the process. Here
1486 we don't setup the structure coding_system nor pay attention to
1487 unibyte mode. They are done in create_process. */
1489 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1490 Lisp_Object coding_systems
= Qt
;
1491 Lisp_Object val
, *args2
;
1492 struct gcpro gcpro1
, gcpro2
;
1494 tem
= Fplist_get (contact
, QCcoding
);
1502 val
= Vcoding_system_for_read
;
1505 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1507 SAFE_ALLOCA_LISP (args2
, nargs2
);
1509 args2
[i
++] = Qstart_process
;
1511 args2
[i
++] = buffer
;
1512 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1513 args2
[i
++] = XCAR (tem2
);
1514 GCPRO2 (proc
, current_dir
);
1515 if (!NILP (program
))
1516 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1518 if (CONSP (coding_systems
))
1519 val
= XCAR (coding_systems
);
1520 else if (CONSP (Vdefault_process_coding_system
))
1521 val
= XCAR (Vdefault_process_coding_system
);
1523 pset_decode_coding_system (XPROCESS (proc
), val
);
1532 val
= Vcoding_system_for_write
;
1535 if (EQ (coding_systems
, Qt
))
1537 ptrdiff_t nargs2
= 3 + XINT (Flength (command
));
1539 SAFE_ALLOCA_LISP (args2
, nargs2
);
1541 args2
[i
++] = Qstart_process
;
1543 args2
[i
++] = buffer
;
1544 for (tem2
= command
; CONSP (tem2
); tem2
= XCDR (tem2
))
1545 args2
[i
++] = XCAR (tem2
);
1546 GCPRO2 (proc
, current_dir
);
1547 if (!NILP (program
))
1548 coding_systems
= Ffind_operation_coding_system (nargs2
, args2
);
1551 if (CONSP (coding_systems
))
1552 val
= XCDR (coding_systems
);
1553 else if (CONSP (Vdefault_process_coding_system
))
1554 val
= XCDR (Vdefault_process_coding_system
);
1556 pset_encode_coding_system (XPROCESS (proc
), val
);
1557 /* Note: At this moment, the above coding system may leave
1558 text-conversion or eol-conversion unspecified. They will be
1559 decided after we read output from the process and decode it by
1560 some coding system, or just before we actually send a text to
1565 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1566 XPROCESS (proc
)->decoding_carryover
= 0;
1567 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1569 XPROCESS (proc
)->inherit_coding_system_flag
1570 = !(NILP (buffer
) || !inherit_process_coding_system
);
1572 if (!NILP (program
))
1574 Lisp_Object program_args
= XCDR (command
);
1576 /* If program file name is not absolute, search our path for it.
1577 Put the name we will really use in TEM. */
1578 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1579 && !(SCHARS (program
) > 1
1580 && IS_DEVICE_SEP (SREF (program
, 1))))
1582 struct gcpro gcpro1
, gcpro2
;
1585 GCPRO2 (buffer
, current_dir
);
1586 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1587 make_number (X_OK
), false);
1590 report_file_error ("Searching for program", program
);
1591 tem
= Fexpand_file_name (tem
, Qnil
);
1595 if (!NILP (Ffile_directory_p (program
)))
1596 error ("Specified program for new process is a directory");
1600 /* Remove "/:" from TEM. */
1601 tem
= remove_slash_colon (tem
);
1603 Lisp_Object arg_encoding
= Qnil
;
1604 struct gcpro gcpro1
;
1607 /* Encode the file name and put it in NEW_ARGV.
1608 That's where the child will use it to execute the program. */
1609 tem
= list1 (ENCODE_FILE (tem
));
1610 ptrdiff_t new_argc
= 1;
1612 /* Here we encode arguments by the coding system used for sending
1613 data to the process. We don't support using different coding
1614 systems for encoding arguments and for encoding data sent to the
1617 for (Lisp_Object tem2
= program_args
; CONSP (tem2
); tem2
= XCDR (tem2
))
1619 Lisp_Object arg
= XCAR (tem2
);
1621 if (STRING_MULTIBYTE (arg
))
1623 if (NILP (arg_encoding
))
1624 arg_encoding
= (complement_process_encoding_system
1625 (XPROCESS (proc
)->encode_coding_system
));
1626 arg
= code_convert_string_norecord (arg
, arg_encoding
, 1);
1628 tem
= Fcons (arg
, tem
);
1634 /* Now that everything is encoded we can collect the strings into
1637 SAFE_NALLOCA (new_argv
, 1, new_argc
+ 1);
1638 new_argv
[new_argc
] = 0;
1640 for (ptrdiff_t i
= new_argc
- 1; i
>= 0; i
--)
1642 new_argv
[i
] = SSDATA (XCAR (tem
));
1646 create_process (proc
, new_argv
, current_dir
);
1653 return unbind_to (count
, proc
);
1656 /* This function is the unwind_protect form for Fstart_process. If
1657 PROC doesn't have its pid set, then we know someone has signaled
1658 an error and the process wasn't started successfully, so we should
1659 remove it from the process list. */
1661 start_process_unwind (Lisp_Object proc
)
1663 if (!PROCESSP (proc
))
1666 /* Was PROC started successfully?
1667 -2 is used for a pty with no process, eg for gdb. */
1668 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1669 remove_process (proc
);
1672 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1675 close_process_fd (int *fd_addr
)
1685 /* Indexes of file descriptors in open_fds. */
1688 /* The pipe from Emacs to its subprocess. */
1690 WRITE_TO_SUBPROCESS
,
1692 /* The main pipe from the subprocess to Emacs. */
1693 READ_FROM_SUBPROCESS
,
1696 /* The pipe from the subprocess to Emacs that is closed when the
1697 subprocess execs. */
1698 READ_FROM_EXEC_MONITOR
,
1702 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1705 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1707 struct Lisp_Process
*p
= XPROCESS (process
);
1708 int inchannel
, outchannel
;
1711 int forkin
, forkout
;
1713 char pty_name
[PTY_NAME_SIZE
];
1714 Lisp_Object lisp_pty_name
= Qnil
;
1717 inchannel
= outchannel
= -1;
1720 outchannel
= inchannel
= allocate_pty (pty_name
);
1724 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1725 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1726 /* On most USG systems it does not work to open the pty's tty here,
1727 then close it and reopen it in the child. */
1728 /* Don't let this terminal become our controlling terminal
1729 (in case we don't have one). */
1730 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1732 report_file_error ("Opening pty", Qnil
);
1733 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1735 forkin
= forkout
= -1;
1736 #endif /* not USG, or USG_SUBTTY_WORKS */
1738 lisp_pty_name
= build_string (pty_name
);
1742 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1743 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1744 report_file_error ("Creating pipe", Qnil
);
1745 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1746 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1747 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1748 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1752 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1753 report_file_error ("Creating pipe", Qnil
);
1756 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1757 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1759 /* Record this as an active process, with its channels. */
1760 chan_process
[inchannel
] = process
;
1761 p
->infd
= inchannel
;
1762 p
->outfd
= outchannel
;
1764 /* Previously we recorded the tty descriptor used in the subprocess.
1765 It was only used for getting the foreground tty process, so now
1766 we just reopen the device (see emacs_get_tty_pgrp) as this is
1767 more portable (see USG_SUBTTY_WORKS above). */
1769 p
->pty_flag
= pty_flag
;
1770 pset_status (p
, Qrun
);
1772 if (!EQ (p
->command
, Qt
))
1774 FD_SET (inchannel
, &input_wait_mask
);
1775 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1778 if (inchannel
> max_process_desc
)
1779 max_process_desc
= inchannel
;
1781 /* This may signal an error. */
1782 setup_process_coding_systems (process
);
1785 block_child_signal (&oldset
);
1788 /* vfork, and prevent local vars from being clobbered by the vfork. */
1790 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1791 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1792 char **volatile new_argv_volatile
= new_argv
;
1793 int volatile forkin_volatile
= forkin
;
1794 int volatile forkout_volatile
= forkout
;
1795 struct Lisp_Process
*p_volatile
= p
;
1799 current_dir
= current_dir_volatile
;
1800 lisp_pty_name
= lisp_pty_name_volatile
;
1801 new_argv
= new_argv_volatile
;
1802 forkin
= forkin_volatile
;
1803 forkout
= forkout_volatile
;
1806 pty_flag
= p
->pty_flag
;
1810 #endif /* not WINDOWSNT */
1812 int xforkin
= forkin
;
1813 int xforkout
= forkout
;
1815 /* Make the pty be the controlling terminal of the process. */
1817 /* First, disconnect its current controlling terminal. */
1818 /* We tried doing setsid only if pty_flag, but it caused
1819 process_set_signal to fail on SGI when using a pipe. */
1821 /* Make the pty's terminal the controlling terminal. */
1822 if (pty_flag
&& xforkin
>= 0)
1825 /* We ignore the return value
1826 because faith@cs.unc.edu says that is necessary on Linux. */
1827 ioctl (xforkin
, TIOCSCTTY
, 0);
1830 #if defined (LDISC1)
1831 if (pty_flag
&& xforkin
>= 0)
1834 tcgetattr (xforkin
, &t
);
1836 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1837 emacs_perror ("create_process/tcsetattr LDISC1");
1840 #if defined (NTTYDISC) && defined (TIOCSETD)
1841 if (pty_flag
&& xforkin
>= 0)
1843 /* Use new line discipline. */
1844 int ldisc
= NTTYDISC
;
1845 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1850 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1851 can do TIOCSPGRP only to the process's controlling tty. */
1854 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1855 I can't test it since I don't have 4.3. */
1856 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1859 ioctl (j
, TIOCNOTTY
, 0);
1863 #endif /* TIOCNOTTY */
1865 #if !defined (DONT_REOPEN_PTY)
1866 /*** There is a suggestion that this ought to be a
1867 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1868 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1869 that system does seem to need this code, even though
1870 both TIOCSCTTY is defined. */
1871 /* Now close the pty (if we had it open) and reopen it.
1872 This makes the pty the controlling terminal of the subprocess. */
1876 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1879 emacs_close (xforkin
);
1880 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1884 emacs_perror (SSDATA (lisp_pty_name
));
1885 _exit (EXIT_CANCELED
);
1889 #endif /* not DONT_REOPEN_PTY */
1891 #ifdef SETUP_SLAVE_PTY
1896 #endif /* SETUP_SLAVE_PTY */
1897 #endif /* HAVE_PTYS */
1899 signal (SIGINT
, SIG_DFL
);
1900 signal (SIGQUIT
, SIG_DFL
);
1902 signal (SIGPROF
, SIG_DFL
);
1905 /* Emacs ignores SIGPIPE, but the child should not. */
1906 signal (SIGPIPE
, SIG_DFL
);
1908 /* Stop blocking SIGCHLD in the child. */
1909 unblock_child_signal (&oldset
);
1912 child_setup_tty (xforkout
);
1914 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1915 #else /* not WINDOWSNT */
1916 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1917 #endif /* not WINDOWSNT */
1920 /* Back in the parent process. */
1922 vfork_errno
= errno
;
1927 /* Stop blocking in the parent. */
1928 unblock_child_signal (&oldset
);
1932 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1935 /* vfork succeeded. */
1937 /* Close the pipe ends that the child uses, or the child's pty. */
1938 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1939 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1942 register_child (pid
, inchannel
);
1943 #endif /* WINDOWSNT */
1945 pset_tty_name (p
, lisp_pty_name
);
1948 /* Wait for child_setup to complete in case that vfork is
1949 actually defined as fork. The descriptor
1950 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1951 of a pipe is closed at the child side either by close-on-exec
1952 on successful execve or the _exit call in child_setup. */
1956 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1957 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
1958 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
1965 create_pty (Lisp_Object process
)
1967 struct Lisp_Process
*p
= XPROCESS (process
);
1968 char pty_name
[PTY_NAME_SIZE
];
1969 int pty_fd
= !p
->pty_flag
? -1 : allocate_pty (pty_name
);
1973 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
1974 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1975 /* On most USG systems it does not work to open the pty's tty here,
1976 then close it and reopen it in the child. */
1977 /* Don't let this terminal become our controlling terminal
1978 (in case we don't have one). */
1979 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1981 report_file_error ("Opening pty", Qnil
);
1982 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
1983 #if defined (DONT_REOPEN_PTY)
1984 /* In the case that vfork is defined as fork, the parent process
1985 (Emacs) may send some data before the child process completes
1986 tty options setup. So we setup tty before forking. */
1987 child_setup_tty (forkout
);
1988 #endif /* DONT_REOPEN_PTY */
1989 #endif /* not USG, or USG_SUBTTY_WORKS */
1991 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
1993 /* Record this as an active process, with its channels.
1994 As a result, child_setup will close Emacs's side of the pipes. */
1995 chan_process
[pty_fd
] = process
;
1999 /* Previously we recorded the tty descriptor used in the subprocess.
2000 It was only used for getting the foreground tty process, so now
2001 we just reopen the device (see emacs_get_tty_pgrp) as this is
2002 more portable (see USG_SUBTTY_WORKS above). */
2005 pset_status (p
, Qrun
);
2006 setup_process_coding_systems (process
);
2008 FD_SET (pty_fd
, &input_wait_mask
);
2009 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
2010 if (pty_fd
> max_process_desc
)
2011 max_process_desc
= pty_fd
;
2013 pset_tty_name (p
, build_string (pty_name
));
2020 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2021 The address family of sa is not included in the result. */
2024 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2026 Lisp_Object address
;
2029 register struct Lisp_Vector
*p
;
2031 /* Workaround for a bug in getsockname on BSD: Names bound to
2032 sockets in the UNIX domain are inaccessible; getsockname returns
2033 a zero length name. */
2034 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2035 return empty_unibyte_string
;
2037 switch (sa
->sa_family
)
2041 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2042 len
= sizeof (sin
->sin_addr
) + 1;
2043 address
= Fmake_vector (make_number (len
), Qnil
);
2044 p
= XVECTOR (address
);
2045 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2046 cp
= (unsigned char *) &sin
->sin_addr
;
2052 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2053 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2054 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
2055 address
= Fmake_vector (make_number (len
), Qnil
);
2056 p
= XVECTOR (address
);
2057 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2058 for (i
= 0; i
< len
; i
++)
2059 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2063 #ifdef HAVE_LOCAL_SOCKETS
2066 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2067 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2068 /* If the first byte is NUL, the name is a Linux abstract
2069 socket name, and the name can contain embedded NULs. If
2070 it's not, we have a NUL-terminated string. Be careful not
2071 to walk past the end of the object looking for the name
2072 terminator, however. */
2073 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2075 const char *terminator
2076 = memchr (sockun
->sun_path
, '\0', name_length
);
2079 name_length
= terminator
- (const char *) sockun
->sun_path
;
2082 return make_unibyte_string (sockun
->sun_path
, name_length
);
2086 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2087 address
= Fcons (make_number (sa
->sa_family
),
2088 Fmake_vector (make_number (len
), Qnil
));
2089 p
= XVECTOR (XCDR (address
));
2090 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2096 p
->contents
[i
++] = make_number (*cp
++);
2102 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2105 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2107 register struct Lisp_Vector
*p
;
2109 if (VECTORP (address
))
2111 p
= XVECTOR (address
);
2112 if (p
->header
.size
== 5)
2115 return sizeof (struct sockaddr_in
);
2118 else if (p
->header
.size
== 9)
2120 *familyp
= AF_INET6
;
2121 return sizeof (struct sockaddr_in6
);
2125 #ifdef HAVE_LOCAL_SOCKETS
2126 else if (STRINGP (address
))
2128 *familyp
= AF_LOCAL
;
2129 return sizeof (struct sockaddr_un
);
2132 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2133 && VECTORP (XCDR (address
)))
2135 struct sockaddr
*sa
;
2136 p
= XVECTOR (XCDR (address
));
2137 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2139 *familyp
= XINT (XCAR (address
));
2140 return p
->header
.size
+ sizeof (sa
->sa_family
);
2145 /* Convert an address object (vector or string) to an internal sockaddr.
2147 The address format has been basically validated by
2148 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2149 it could have come from user data. So if FAMILY is not valid,
2150 we return after zeroing *SA. */
2153 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2155 register struct Lisp_Vector
*p
;
2156 register unsigned char *cp
= NULL
;
2160 memset (sa
, 0, len
);
2162 if (VECTORP (address
))
2164 p
= XVECTOR (address
);
2165 if (family
== AF_INET
)
2167 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2168 len
= sizeof (sin
->sin_addr
) + 1;
2169 hostport
= XINT (p
->contents
[--len
]);
2170 sin
->sin_port
= htons (hostport
);
2171 cp
= (unsigned char *)&sin
->sin_addr
;
2172 sa
->sa_family
= family
;
2175 else if (family
== AF_INET6
)
2177 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2178 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2179 len
= sizeof (sin6
->sin6_addr
) + 1;
2180 hostport
= XINT (p
->contents
[--len
]);
2181 sin6
->sin6_port
= htons (hostport
);
2182 for (i
= 0; i
< len
; i
++)
2183 if (INTEGERP (p
->contents
[i
]))
2185 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2188 sa
->sa_family
= family
;
2195 else if (STRINGP (address
))
2197 #ifdef HAVE_LOCAL_SOCKETS
2198 if (family
== AF_LOCAL
)
2200 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2201 cp
= SDATA (address
);
2202 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2203 sockun
->sun_path
[i
] = *cp
++;
2204 sa
->sa_family
= family
;
2211 p
= XVECTOR (XCDR (address
));
2212 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2215 for (i
= 0; i
< len
; i
++)
2216 if (INTEGERP (p
->contents
[i
]))
2217 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2220 #ifdef DATAGRAM_SOCKETS
2221 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2223 doc
: /* Get the current datagram address associated with PROCESS. */)
2224 (Lisp_Object process
)
2228 CHECK_PROCESS (process
);
2230 if (!DATAGRAM_CONN_P (process
))
2233 channel
= XPROCESS (process
)->infd
;
2234 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2235 datagram_address
[channel
].len
);
2238 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2240 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2241 Returns nil upon error setting address, ADDRESS otherwise. */)
2242 (Lisp_Object process
, Lisp_Object address
)
2247 CHECK_PROCESS (process
);
2249 if (!DATAGRAM_CONN_P (process
))
2252 channel
= XPROCESS (process
)->infd
;
2254 len
= get_lisp_to_sockaddr_size (address
, &family
);
2255 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2257 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2263 static const struct socket_options
{
2264 /* The name of this option. Should be lowercase version of option
2265 name without SO_ prefix. */
2267 /* Option level SOL_... */
2269 /* Option number SO_... */
2271 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2272 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2273 } socket_options
[] =
2275 #ifdef SO_BINDTODEVICE
2276 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2279 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2282 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2285 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2288 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2291 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2294 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2297 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2299 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2302 /* Set option OPT to value VAL on socket S.
2304 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2305 Signals an error if setting a known option fails.
2309 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2312 const struct socket_options
*sopt
;
2317 name
= SSDATA (SYMBOL_NAME (opt
));
2318 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2319 if (strcmp (name
, sopt
->name
) == 0)
2322 switch (sopt
->opttype
)
2327 optval
= NILP (val
) ? 0 : 1;
2328 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2329 &optval
, sizeof (optval
));
2336 if (TYPE_RANGED_INTEGERP (int, val
))
2337 optval
= XINT (val
);
2339 error ("Bad option value for %s", name
);
2340 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2341 &optval
, sizeof (optval
));
2345 #ifdef SO_BINDTODEVICE
2348 char devname
[IFNAMSIZ
+ 1];
2350 /* This is broken, at least in the Linux 2.4 kernel.
2351 To unbind, the arg must be a zero integer, not the empty string.
2352 This should work on all systems. KFS. 2003-09-23. */
2353 memset (devname
, 0, sizeof devname
);
2356 char *arg
= SSDATA (val
);
2357 int len
= min (strlen (arg
), IFNAMSIZ
);
2358 memcpy (devname
, arg
, len
);
2360 else if (!NILP (val
))
2361 error ("Bad option value for %s", name
);
2362 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2371 struct linger linger
;
2374 linger
.l_linger
= 0;
2375 if (TYPE_RANGED_INTEGERP (int, val
))
2376 linger
.l_linger
= XINT (val
);
2378 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2379 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2380 &linger
, sizeof (linger
));
2391 int setsockopt_errno
= errno
;
2392 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2396 return (1 << sopt
->optbit
);
2400 DEFUN ("set-network-process-option",
2401 Fset_network_process_option
, Sset_network_process_option
,
2403 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2404 See `make-network-process' for a list of options and values.
2405 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2406 OPTION is not a supported option, return nil instead; otherwise return t. */)
2407 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2410 struct Lisp_Process
*p
;
2412 CHECK_PROCESS (process
);
2413 p
= XPROCESS (process
);
2414 if (!NETCONN1_P (p
))
2415 error ("Process is not a network process");
2419 error ("Process is not running");
2421 if (set_socket_option (s
, option
, value
))
2423 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2427 if (NILP (no_error
))
2428 error ("Unknown or unsupported option");
2434 DEFUN ("serial-process-configure",
2435 Fserial_process_configure
,
2436 Sserial_process_configure
,
2438 doc
: /* Configure speed, bytesize, etc. of a serial process.
2440 Arguments are specified as keyword/argument pairs. Attributes that
2441 are not given are re-initialized from the process's current
2442 configuration (available via the function `process-contact') or set to
2443 reasonable default values. The following arguments are defined:
2449 -- Any of these arguments can be given to identify the process that is
2450 to be configured. If none of these arguments is given, the current
2451 buffer's process is used.
2453 :speed SPEED -- SPEED is the speed of the serial port in bits per
2454 second, also called baud rate. Any value can be given for SPEED, but
2455 most serial ports work only at a few defined values between 1200 and
2456 115200, with 9600 being the most common value. If SPEED is nil, the
2457 serial port is not configured any further, i.e., all other arguments
2458 are ignored. This may be useful for special serial ports such as
2459 Bluetooth-to-serial converters which can only be configured through AT
2460 commands. A value of nil for SPEED can be used only when passed
2461 through `make-serial-process' or `serial-term'.
2463 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2464 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2466 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2467 `odd' (use odd parity), or the symbol `even' (use even parity). If
2468 PARITY is not given, no parity is used.
2470 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2471 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2472 is not given or nil, 1 stopbit is used.
2474 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2475 flowcontrol to be used, which is either nil (don't use flowcontrol),
2476 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2477 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2478 flowcontrol is used.
2480 `serial-process-configure' is called by `make-serial-process' for the
2481 initial configuration of the serial port.
2485 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2487 \(serial-process-configure
2488 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2490 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2492 usage: (serial-process-configure &rest ARGS) */)
2493 (ptrdiff_t nargs
, Lisp_Object
*args
)
2495 struct Lisp_Process
*p
;
2496 Lisp_Object contact
= Qnil
;
2497 Lisp_Object proc
= Qnil
;
2498 struct gcpro gcpro1
;
2500 contact
= Flist (nargs
, args
);
2503 proc
= Fplist_get (contact
, QCprocess
);
2505 proc
= Fplist_get (contact
, QCname
);
2507 proc
= Fplist_get (contact
, QCbuffer
);
2509 proc
= Fplist_get (contact
, QCport
);
2510 proc
= get_process (proc
);
2511 p
= XPROCESS (proc
);
2512 if (!EQ (p
->type
, Qserial
))
2513 error ("Not a serial process");
2515 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2521 serial_configure (p
, contact
);
2527 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2529 doc
: /* Create and return a serial port process.
2531 In Emacs, serial port connections are represented by process objects,
2532 so input and output work as for subprocesses, and `delete-process'
2533 closes a serial port connection. However, a serial process has no
2534 process id, it cannot be signaled, and the status codes are different
2535 from normal processes.
2537 `make-serial-process' creates a process and a buffer, on which you
2538 probably want to use `process-send-string'. Try \\[serial-term] for
2539 an interactive terminal. See below for examples.
2541 Arguments are specified as keyword/argument pairs. The following
2542 arguments are defined:
2544 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2545 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2546 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2547 the backslashes in strings).
2549 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2550 which this function calls.
2552 :name NAME -- NAME is the name of the process. If NAME is not given,
2553 the value of PORT is used.
2555 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2556 with the process. Process output goes at the end of that buffer,
2557 unless you specify an output stream or filter function to handle the
2558 output. If BUFFER is not given, the value of NAME is used.
2560 :coding CODING -- If CODING is a symbol, it specifies the coding
2561 system used for both reading and writing for this process. If CODING
2562 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2563 ENCODING is used for writing.
2565 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2566 the process is running. If BOOL is not given, query before exiting.
2568 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2569 In the stopped state, a serial process does not accept incoming data,
2570 but you can send outgoing data. The stopped state is cleared by
2571 `continue-process' and set by `stop-process'.
2573 :filter FILTER -- Install FILTER as the process filter.
2575 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2577 :plist PLIST -- Install PLIST as the initial plist of the process.
2583 -- This function calls `serial-process-configure' to handle these
2586 The original argument list, possibly modified by later configuration,
2587 is available via the function `process-contact'.
2591 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2593 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2595 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2597 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2599 usage: (make-serial-process &rest ARGS) */)
2600 (ptrdiff_t nargs
, Lisp_Object
*args
)
2603 Lisp_Object proc
, contact
, port
;
2604 struct Lisp_Process
*p
;
2605 struct gcpro gcpro1
;
2606 Lisp_Object name
, buffer
;
2607 Lisp_Object tem
, val
;
2608 ptrdiff_t specpdl_count
;
2613 contact
= Flist (nargs
, args
);
2616 port
= Fplist_get (contact
, QCport
);
2618 error ("No port specified");
2619 CHECK_STRING (port
);
2621 if (NILP (Fplist_member (contact
, QCspeed
)))
2622 error (":speed not specified");
2623 if (!NILP (Fplist_get (contact
, QCspeed
)))
2624 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2626 name
= Fplist_get (contact
, QCname
);
2629 CHECK_STRING (name
);
2630 proc
= make_process (name
);
2631 specpdl_count
= SPECPDL_INDEX ();
2632 record_unwind_protect (remove_process
, proc
);
2633 p
= XPROCESS (proc
);
2635 fd
= serial_open (port
);
2636 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2639 if (fd
> max_process_desc
)
2640 max_process_desc
= fd
;
2641 chan_process
[fd
] = proc
;
2643 buffer
= Fplist_get (contact
, QCbuffer
);
2646 buffer
= Fget_buffer_create (buffer
);
2647 pset_buffer (p
, buffer
);
2649 pset_childp (p
, contact
);
2650 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2651 pset_type (p
, Qserial
);
2652 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2653 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2655 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2656 p
->kill_without_query
= 1;
2657 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2658 pset_command (p
, Qt
);
2659 eassert (! p
->pty_flag
);
2661 if (!EQ (p
->command
, Qt
))
2663 FD_SET (fd
, &input_wait_mask
);
2664 FD_SET (fd
, &non_keyboard_wait_mask
);
2667 if (BUFFERP (buffer
))
2669 set_marker_both (p
->mark
, buffer
,
2670 BUF_ZV (XBUFFER (buffer
)),
2671 BUF_ZV_BYTE (XBUFFER (buffer
)));
2674 tem
= Fplist_member (contact
, QCcoding
);
2675 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2681 val
= XCAR (XCDR (tem
));
2685 else if (!NILP (Vcoding_system_for_read
))
2686 val
= Vcoding_system_for_read
;
2687 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2688 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2690 pset_decode_coding_system (p
, val
);
2695 val
= XCAR (XCDR (tem
));
2699 else if (!NILP (Vcoding_system_for_write
))
2700 val
= Vcoding_system_for_write
;
2701 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2702 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2704 pset_encode_coding_system (p
, val
);
2706 setup_process_coding_systems (proc
);
2707 pset_decoding_buf (p
, empty_unibyte_string
);
2708 p
->decoding_carryover
= 0;
2709 pset_encoding_buf (p
, empty_unibyte_string
);
2710 p
->inherit_coding_system_flag
2711 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2713 Fserial_process_configure (nargs
, args
);
2715 specpdl_ptr
= specpdl
+ specpdl_count
;
2721 /* Create a network stream/datagram client/server process. Treated
2722 exactly like a normal process when reading and writing. Primary
2723 differences are in status display and process deletion. A network
2724 connection has no PID; you cannot signal it. All you can do is
2725 stop/continue it and deactivate/close it via delete-process. */
2727 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2729 doc
: /* Create and return a network server or client process.
2731 In Emacs, network connections are represented by process objects, so
2732 input and output work as for subprocesses and `delete-process' closes
2733 a network connection. However, a network process has no process id,
2734 it cannot be signaled, and the status codes are different from normal
2737 Arguments are specified as keyword/argument pairs. The following
2738 arguments are defined:
2740 :name NAME -- NAME is name for process. It is modified if necessary
2743 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2744 with the process. Process output goes at end of that buffer, unless
2745 you specify an output stream or filter function to handle the output.
2746 BUFFER may be also nil, meaning that this process is not associated
2749 :host HOST -- HOST is name of the host to connect to, or its IP
2750 address. The symbol `local' specifies the local host. If specified
2751 for a server process, it must be a valid name or address for the local
2752 host, and only clients connecting to that address will be accepted.
2754 :service SERVICE -- SERVICE is name of the service desired, or an
2755 integer specifying a port number to connect to. If SERVICE is t,
2756 a random port number is selected for the server. (If Emacs was
2757 compiled with getaddrinfo, a port number can also be specified as a
2758 string, e.g. "80", as well as an integer. This is not portable.)
2760 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2761 stream type connection, `datagram' creates a datagram type connection,
2762 `seqpacket' creates a reliable datagram connection.
2764 :family FAMILY -- FAMILY is the address (and protocol) family for the
2765 service specified by HOST and SERVICE. The default (nil) is to use
2766 whatever address family (IPv4 or IPv6) that is defined for the host
2767 and port number specified by HOST and SERVICE. Other address families
2769 local -- for a local (i.e. UNIX) address specified by SERVICE.
2770 ipv4 -- use IPv4 address family only.
2771 ipv6 -- use IPv6 address family only.
2773 :local ADDRESS -- ADDRESS is the local address used for the connection.
2774 This parameter is ignored when opening a client process. When specified
2775 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2777 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2778 connection. This parameter is ignored when opening a stream server
2779 process. For a datagram server process, it specifies the initial
2780 setting of the remote datagram address. When specified for a client
2781 process, the FAMILY, HOST, and SERVICE args are ignored.
2783 The format of ADDRESS depends on the address family:
2784 - An IPv4 address is represented as an vector of integers [A B C D P]
2785 corresponding to numeric IP address A.B.C.D and port number P.
2786 - A local address is represented as a string with the address in the
2787 local address space.
2788 - An "unsupported family" address is represented by a cons (F . AV)
2789 where F is the family number and AV is a vector containing the socket
2790 address data with one element per address data byte. Do not rely on
2791 this format in portable code, as it may depend on implementation
2792 defined constants, data sizes, and data structure alignment.
2794 :coding CODING -- If CODING is a symbol, it specifies the coding
2795 system used for both reading and writing for this process. If CODING
2796 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2797 ENCODING is used for writing.
2799 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2800 return without waiting for the connection to complete; instead, the
2801 sentinel function will be called with second arg matching "open" (if
2802 successful) or "failed" when the connect completes. Default is to use
2803 a blocking connect (i.e. wait) for stream type connections.
2805 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2806 running when Emacs is exited.
2808 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2809 In the stopped state, a server process does not accept new
2810 connections, and a client process does not handle incoming traffic.
2811 The stopped state is cleared by `continue-process' and set by
2814 :filter FILTER -- Install FILTER as the process filter.
2816 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2817 process filter are multibyte, otherwise they are unibyte.
2818 If this keyword is not specified, the strings are multibyte if
2819 the default value of `enable-multibyte-characters' is non-nil.
2821 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2823 :log LOG -- Install LOG as the server process log function. This
2824 function is called when the server accepts a network connection from a
2825 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2826 is the server process, CLIENT is the new process for the connection,
2827 and MESSAGE is a string.
2829 :plist PLIST -- Install PLIST as the new process's initial plist.
2831 :server QLEN -- if QLEN is non-nil, create a server process for the
2832 specified FAMILY, SERVICE, and connection type (stream or datagram).
2833 If QLEN is an integer, it is used as the max. length of the server's
2834 pending connection queue (also known as the backlog); the default
2835 queue length is 5. Default is to create a client process.
2837 The following network options can be specified for this connection:
2839 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2840 :dontroute BOOL -- Only send to directly connected hosts.
2841 :keepalive BOOL -- Send keep-alive messages on network stream.
2842 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2843 :oobinline BOOL -- Place out-of-band data in receive data stream.
2844 :priority INT -- Set protocol defined priority for sent packets.
2845 :reuseaddr BOOL -- Allow reusing a recently used local address
2846 (this is allowed by default for a server process).
2847 :bindtodevice NAME -- bind to interface NAME. Using this may require
2848 special privileges on some systems.
2850 Consult the relevant system programmer's manual pages for more
2851 information on using these options.
2854 A server process will listen for and accept connections from clients.
2855 When a client connection is accepted, a new network process is created
2856 for the connection with the following parameters:
2858 - The client's process name is constructed by concatenating the server
2859 process's NAME and a client identification string.
2860 - If the FILTER argument is non-nil, the client process will not get a
2861 separate process buffer; otherwise, the client's process buffer is a newly
2862 created buffer named after the server process's BUFFER name or process
2863 NAME concatenated with the client identification string.
2864 - The connection type and the process filter and sentinel parameters are
2865 inherited from the server process's TYPE, FILTER and SENTINEL.
2866 - The client process's contact info is set according to the client's
2867 addressing information (typically an IP address and a port number).
2868 - The client process's plist is initialized from the server's plist.
2870 Notice that the FILTER and SENTINEL args are never used directly by
2871 the server process. Also, the BUFFER argument is not used directly by
2872 the server process, but via the optional :log function, accepted (and
2873 failed) connections may be logged in the server process's buffer.
2875 The original argument list, modified with the actual connection
2876 information, is available via the `process-contact' function.
2878 usage: (make-network-process &rest ARGS) */)
2879 (ptrdiff_t nargs
, Lisp_Object
*args
)
2882 Lisp_Object contact
;
2883 struct Lisp_Process
*p
;
2884 #ifdef HAVE_GETADDRINFO
2885 struct addrinfo ai
, *res
, *lres
;
2886 struct addrinfo hints
;
2887 const char *portstring
;
2889 #else /* HAVE_GETADDRINFO */
2890 struct _emacs_addrinfo
2896 struct sockaddr
*ai_addr
;
2897 struct _emacs_addrinfo
*ai_next
;
2899 #endif /* HAVE_GETADDRINFO */
2900 struct sockaddr_in address_in
;
2901 #ifdef HAVE_LOCAL_SOCKETS
2902 struct sockaddr_un address_un
;
2907 int s
= -1, outch
, inch
;
2908 struct gcpro gcpro1
;
2909 ptrdiff_t count
= SPECPDL_INDEX ();
2911 Lisp_Object colon_address
; /* Either QClocal or QCremote. */
2913 Lisp_Object name
, buffer
, host
, service
, address
;
2914 Lisp_Object filter
, sentinel
;
2915 bool is_non_blocking_client
= 0;
2924 /* Save arguments for process-contact and clone-process. */
2925 contact
= Flist (nargs
, args
);
2929 /* Ensure socket support is loaded if available. */
2930 init_winsock (TRUE
);
2933 /* :type TYPE (nil: stream, datagram */
2934 tem
= Fplist_get (contact
, QCtype
);
2936 socktype
= SOCK_STREAM
;
2937 #ifdef DATAGRAM_SOCKETS
2938 else if (EQ (tem
, Qdatagram
))
2939 socktype
= SOCK_DGRAM
;
2941 #ifdef HAVE_SEQPACKET
2942 else if (EQ (tem
, Qseqpacket
))
2943 socktype
= SOCK_SEQPACKET
;
2946 error ("Unsupported connection type");
2949 tem
= Fplist_get (contact
, QCserver
);
2952 /* Don't support network sockets when non-blocking mode is
2953 not available, since a blocked Emacs is not useful. */
2955 if (TYPE_RANGED_INTEGERP (int, tem
))
2956 backlog
= XINT (tem
);
2959 /* Make colon_address an alias for :local (server) or :remote (client). */
2960 colon_address
= is_server
? QClocal
: QCremote
;
2963 if (!is_server
&& socktype
!= SOCK_DGRAM
2964 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2966 #ifndef NON_BLOCKING_CONNECT
2967 error ("Non-blocking connect not supported");
2969 is_non_blocking_client
= 1;
2973 name
= Fplist_get (contact
, QCname
);
2974 buffer
= Fplist_get (contact
, QCbuffer
);
2975 filter
= Fplist_get (contact
, QCfilter
);
2976 sentinel
= Fplist_get (contact
, QCsentinel
);
2978 CHECK_STRING (name
);
2980 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2981 ai
.ai_socktype
= socktype
;
2986 /* :local ADDRESS or :remote ADDRESS */
2987 address
= Fplist_get (contact
, colon_address
);
2988 if (!NILP (address
))
2990 host
= service
= Qnil
;
2992 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2993 error ("Malformed :address");
2994 ai
.ai_family
= family
;
2995 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2996 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
3000 /* :family FAMILY -- nil (for Inet), local, or integer. */
3001 tem
= Fplist_get (contact
, QCfamily
);
3004 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3010 #ifdef HAVE_LOCAL_SOCKETS
3011 else if (EQ (tem
, Qlocal
))
3015 else if (EQ (tem
, Qipv6
))
3018 else if (EQ (tem
, Qipv4
))
3020 else if (TYPE_RANGED_INTEGERP (int, tem
))
3021 family
= XINT (tem
);
3023 error ("Unknown address family");
3025 ai
.ai_family
= family
;
3027 /* :service SERVICE -- string, integer (port number), or t (random port). */
3028 service
= Fplist_get (contact
, QCservice
);
3030 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3031 host
= Fplist_get (contact
, QChost
);
3034 if (EQ (host
, Qlocal
))
3035 /* Depending on setup, "localhost" may map to different IPv4 and/or
3036 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3037 host
= build_string ("127.0.0.1");
3038 CHECK_STRING (host
);
3041 #ifdef HAVE_LOCAL_SOCKETS
3042 if (family
== AF_LOCAL
)
3046 message (":family local ignores the :host \"%s\" property",
3048 contact
= Fplist_put (contact
, QChost
, Qnil
);
3051 CHECK_STRING (service
);
3052 memset (&address_un
, 0, sizeof address_un
);
3053 address_un
.sun_family
= AF_LOCAL
;
3054 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3055 error ("Service name too long");
3056 lispstpcpy (address_un
.sun_path
, service
);
3057 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3058 ai
.ai_addrlen
= sizeof address_un
;
3063 /* Slow down polling to every ten seconds.
3064 Some kernels have a bug which causes retrying connect to fail
3065 after a connect. Polling can interfere with gethostbyname too. */
3066 #ifdef POLL_FOR_INPUT
3067 if (socktype
!= SOCK_DGRAM
)
3069 record_unwind_protect_void (run_all_atimers
);
3070 bind_polling_period (10);
3074 #ifdef HAVE_GETADDRINFO
3075 /* If we have a host, use getaddrinfo to resolve both host and service.
3076 Otherwise, use getservbyname to lookup the service. */
3080 /* SERVICE can either be a string or int.
3081 Convert to a C string for later use by getaddrinfo. */
3082 if (EQ (service
, Qt
))
3084 else if (INTEGERP (service
))
3086 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3087 portstring
= portbuf
;
3091 CHECK_STRING (service
);
3092 portstring
= SSDATA (service
);
3097 memset (&hints
, 0, sizeof (hints
));
3099 hints
.ai_family
= family
;
3100 hints
.ai_socktype
= socktype
;
3101 hints
.ai_protocol
= 0;
3103 #ifdef HAVE_RES_INIT
3107 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3109 #ifdef HAVE_GAI_STRERROR
3110 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3112 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3118 #endif /* HAVE_GETADDRINFO */
3120 /* We end up here if getaddrinfo is not defined, or in case no hostname
3121 has been specified (e.g. for a local server process). */
3123 if (EQ (service
, Qt
))
3125 else if (INTEGERP (service
))
3126 port
= htons ((unsigned short) XINT (service
));
3129 struct servent
*svc_info
;
3130 CHECK_STRING (service
);
3131 svc_info
= getservbyname (SSDATA (service
),
3132 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3134 error ("Unknown service: %s", SDATA (service
));
3135 port
= svc_info
->s_port
;
3138 memset (&address_in
, 0, sizeof address_in
);
3139 address_in
.sin_family
= family
;
3140 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3141 address_in
.sin_port
= port
;
3143 #ifndef HAVE_GETADDRINFO
3146 struct hostent
*host_info_ptr
;
3148 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3149 as it may `hang' Emacs for a very long time. */
3153 #ifdef HAVE_RES_INIT
3157 host_info_ptr
= gethostbyname (SDATA (host
));
3162 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3163 host_info_ptr
->h_length
);
3164 family
= host_info_ptr
->h_addrtype
;
3165 address_in
.sin_family
= family
;
3168 /* Attempt to interpret host as numeric inet address. */
3170 unsigned long numeric_addr
;
3171 numeric_addr
= inet_addr (SSDATA (host
));
3172 if (numeric_addr
== -1)
3173 error ("Unknown host \"%s\"", SDATA (host
));
3175 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3176 sizeof (address_in
.sin_addr
));
3180 #endif /* not HAVE_GETADDRINFO */
3182 ai
.ai_family
= family
;
3183 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3184 ai
.ai_addrlen
= sizeof address_in
;
3188 /* Do this in case we never enter the for-loop below. */
3189 count1
= SPECPDL_INDEX ();
3192 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3201 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3209 #ifdef DATAGRAM_SOCKETS
3210 if (!is_server
&& socktype
== SOCK_DGRAM
)
3212 #endif /* DATAGRAM_SOCKETS */
3214 #ifdef NON_BLOCKING_CONNECT
3215 if (is_non_blocking_client
)
3217 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3228 /* Make us close S if quit. */
3229 record_unwind_protect_int (close_file_unwind
, s
);
3231 /* Parse network options in the arg list.
3232 We simply ignore anything which isn't a known option (including other keywords).
3233 An error is signaled if setting a known option fails. */
3234 for (optn
= optbits
= 0; optn
< nargs
- 1; optn
+= 2)
3235 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+ 1]);
3239 /* Configure as a server socket. */
3241 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3242 explicit :reuseaddr key to override this. */
3243 #ifdef HAVE_LOCAL_SOCKETS
3244 if (family
!= AF_LOCAL
)
3246 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3249 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3250 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3253 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3254 report_file_error ("Cannot bind server socket", Qnil
);
3256 #ifdef HAVE_GETSOCKNAME
3257 if (EQ (service
, Qt
))
3259 struct sockaddr_in sa1
;
3260 socklen_t len1
= sizeof (sa1
);
3261 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3263 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3264 service
= make_number (ntohs (sa1
.sin_port
));
3265 contact
= Fplist_put (contact
, QCservice
, service
);
3270 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3271 report_file_error ("Cannot listen on server socket", Qnil
);
3279 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3282 if (ret
== 0 || xerrno
== EISCONN
)
3284 /* The unwind-protect will be discarded afterwards.
3285 Likewise for immediate_quit. */
3289 #ifdef NON_BLOCKING_CONNECT
3291 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3295 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3302 if (xerrno
== EINTR
)
3304 /* Unlike most other syscalls connect() cannot be called
3305 again. (That would return EALREADY.) The proper way to
3306 wait for completion is pselect(). */
3314 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3320 report_file_error ("Failed select", Qnil
);
3324 len
= sizeof xerrno
;
3325 eassert (FD_ISSET (s
, &fdset
));
3326 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3327 report_file_error ("Failed getsockopt", Qnil
);
3329 report_file_errno ("Failed connect", Qnil
, xerrno
);
3332 #endif /* !WINDOWSNT */
3336 /* Discard the unwind protect closing S. */
3337 specpdl_ptr
= specpdl
+ count1
;
3342 if (xerrno
== EINTR
)
3349 #ifdef DATAGRAM_SOCKETS
3350 if (socktype
== SOCK_DGRAM
)
3352 if (datagram_address
[s
].sa
)
3354 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3355 datagram_address
[s
].len
= lres
->ai_addrlen
;
3359 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3360 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3363 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3364 if (rlen
!= 0 && rfamily
== lres
->ai_family
3365 && rlen
== lres
->ai_addrlen
)
3366 conv_lisp_to_sockaddr (rfamily
, remote
,
3367 datagram_address
[s
].sa
, rlen
);
3371 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3374 contact
= Fplist_put (contact
, colon_address
,
3375 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3376 #ifdef HAVE_GETSOCKNAME
3379 struct sockaddr_in sa1
;
3380 socklen_t len1
= sizeof (sa1
);
3381 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3382 contact
= Fplist_put (contact
, QClocal
,
3383 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3390 #ifdef HAVE_GETADDRINFO
3401 /* If non-blocking got this far - and failed - assume non-blocking is
3402 not supported after all. This is probably a wrong assumption, but
3403 the normal blocking calls to open-network-stream handles this error
3405 if (is_non_blocking_client
)
3408 report_file_errno ((is_server
3409 ? "make server process failed"
3410 : "make client process failed"),
3418 buffer
= Fget_buffer_create (buffer
);
3419 proc
= make_process (name
);
3421 chan_process
[inch
] = proc
;
3423 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3425 p
= XPROCESS (proc
);
3427 pset_childp (p
, contact
);
3428 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3429 pset_type (p
, Qnetwork
);
3431 pset_buffer (p
, buffer
);
3432 pset_sentinel (p
, sentinel
);
3433 pset_filter (p
, filter
);
3434 pset_log (p
, Fplist_get (contact
, QClog
));
3435 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3436 p
->kill_without_query
= 1;
3437 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3438 pset_command (p
, Qt
);
3441 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3445 /* Discard the unwind protect for closing S, if any. */
3446 specpdl_ptr
= specpdl
+ count1
;
3448 /* Unwind bind_polling_period and request_sigio. */
3449 unbind_to (count
, Qnil
);
3451 if (is_server
&& socktype
!= SOCK_DGRAM
)
3452 pset_status (p
, Qlisten
);
3454 /* Make the process marker point into the process buffer (if any). */
3455 if (BUFFERP (buffer
))
3456 set_marker_both (p
->mark
, buffer
,
3457 BUF_ZV (XBUFFER (buffer
)),
3458 BUF_ZV_BYTE (XBUFFER (buffer
)));
3460 #ifdef NON_BLOCKING_CONNECT
3461 if (is_non_blocking_client
)
3463 /* We may get here if connect did succeed immediately. However,
3464 in that case, we still need to signal this like a non-blocking
3466 pset_status (p
, Qconnect
);
3467 if (!FD_ISSET (inch
, &connect_wait_mask
))
3469 FD_SET (inch
, &connect_wait_mask
);
3470 FD_SET (inch
, &write_mask
);
3471 num_pending_connects
++;
3476 /* A server may have a client filter setting of Qt, but it must
3477 still listen for incoming connects unless it is stopped. */
3478 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3479 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3481 FD_SET (inch
, &input_wait_mask
);
3482 FD_SET (inch
, &non_keyboard_wait_mask
);
3485 if (inch
> max_process_desc
)
3486 max_process_desc
= inch
;
3488 tem
= Fplist_member (contact
, QCcoding
);
3489 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3490 tem
= Qnil
; /* No error message (too late!). */
3493 /* Setup coding systems for communicating with the network stream. */
3494 struct gcpro gcpro1
;
3495 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3496 Lisp_Object coding_systems
= Qt
;
3501 val
= XCAR (XCDR (tem
));
3505 else if (!NILP (Vcoding_system_for_read
))
3506 val
= Vcoding_system_for_read
;
3507 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3508 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3509 /* We dare not decode end-of-line format by setting VAL to
3510 Qraw_text, because the existing Emacs Lisp libraries
3511 assume that they receive bare code including a sequence of
3516 if (NILP (host
) || NILP (service
))
3517 coding_systems
= Qnil
;
3521 coding_systems
= CALLN (Ffind_operation_coding_system
,
3522 Qopen_network_stream
, name
, buffer
,
3526 if (CONSP (coding_systems
))
3527 val
= XCAR (coding_systems
);
3528 else if (CONSP (Vdefault_process_coding_system
))
3529 val
= XCAR (Vdefault_process_coding_system
);
3533 pset_decode_coding_system (p
, val
);
3537 val
= XCAR (XCDR (tem
));
3541 else if (!NILP (Vcoding_system_for_write
))
3542 val
= Vcoding_system_for_write
;
3543 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3547 if (EQ (coding_systems
, Qt
))
3549 if (NILP (host
) || NILP (service
))
3550 coding_systems
= Qnil
;
3554 coding_systems
= CALLN (Ffind_operation_coding_system
,
3555 Qopen_network_stream
, name
, buffer
,
3560 if (CONSP (coding_systems
))
3561 val
= XCDR (coding_systems
);
3562 else if (CONSP (Vdefault_process_coding_system
))
3563 val
= XCDR (Vdefault_process_coding_system
);
3567 pset_encode_coding_system (p
, val
);
3569 setup_process_coding_systems (proc
);
3571 pset_decoding_buf (p
, empty_unibyte_string
);
3572 p
->decoding_carryover
= 0;
3573 pset_encoding_buf (p
, empty_unibyte_string
);
3575 p
->inherit_coding_system_flag
3576 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3583 #ifdef HAVE_NET_IF_H
3587 network_interface_list (void)
3589 struct ifconf ifconf
;
3590 struct ifreq
*ifreq
;
3592 ptrdiff_t buf_size
= 512;
3597 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3600 count
= SPECPDL_INDEX ();
3601 record_unwind_protect_int (close_file_unwind
, s
);
3605 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3606 ifconf
.ifc_buf
= buf
;
3607 ifconf
.ifc_len
= buf_size
;
3608 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3615 while (ifconf
.ifc_len
== buf_size
);
3617 res
= unbind_to (count
, Qnil
);
3618 ifreq
= ifconf
.ifc_req
;
3619 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3621 struct ifreq
*ifq
= ifreq
;
3622 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3623 #define SIZEOF_IFREQ(sif) \
3624 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3625 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3627 int len
= SIZEOF_IFREQ (ifq
);
3629 int len
= sizeof (*ifreq
);
3631 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3632 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3634 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3637 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3638 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3639 res
= Fcons (Fcons (build_string (namebuf
),
3640 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3641 sizeof (struct sockaddr
))),
3648 #endif /* SIOCGIFCONF */
3650 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3654 const char *flag_sym
;
3657 static const struct ifflag_def ifflag_table
[] = {
3661 #ifdef IFF_BROADCAST
3662 { IFF_BROADCAST
, "broadcast" },
3665 { IFF_DEBUG
, "debug" },
3668 { IFF_LOOPBACK
, "loopback" },
3670 #ifdef IFF_POINTOPOINT
3671 { IFF_POINTOPOINT
, "pointopoint" },
3674 { IFF_RUNNING
, "running" },
3677 { IFF_NOARP
, "noarp" },
3680 { IFF_PROMISC
, "promisc" },
3682 #ifdef IFF_NOTRAILERS
3683 #ifdef NS_IMPL_COCOA
3684 /* Really means smart, notrailers is obsolete. */
3685 { IFF_NOTRAILERS
, "smart" },
3687 { IFF_NOTRAILERS
, "notrailers" },
3691 { IFF_ALLMULTI
, "allmulti" },
3694 { IFF_MASTER
, "master" },
3697 { IFF_SLAVE
, "slave" },
3699 #ifdef IFF_MULTICAST
3700 { IFF_MULTICAST
, "multicast" },
3703 { IFF_PORTSEL
, "portsel" },
3705 #ifdef IFF_AUTOMEDIA
3706 { IFF_AUTOMEDIA
, "automedia" },
3709 { IFF_DYNAMIC
, "dynamic" },
3712 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
3715 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3718 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
3721 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
3724 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
3730 network_interface_info (Lisp_Object ifname
)
3733 Lisp_Object res
= Qnil
;
3738 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3739 && defined HAVE_GETIFADDRS && defined LLADDR)
3740 struct ifaddrs
*ifap
;
3743 CHECK_STRING (ifname
);
3745 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3746 error ("interface name too long");
3747 lispstpcpy (rq
.ifr_name
, ifname
);
3749 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3752 count
= SPECPDL_INDEX ();
3753 record_unwind_protect_int (close_file_unwind
, s
);
3756 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3757 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3759 int flags
= rq
.ifr_flags
;
3760 const struct ifflag_def
*fp
;
3763 /* If flags is smaller than int (i.e. short) it may have the high bit set
3764 due to IFF_MULTICAST. In that case, sign extending it into
3766 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3767 flags
= (unsigned short) rq
.ifr_flags
;
3770 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3772 if (flags
& fp
->flag_bit
)
3774 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3775 flags
-= fp
->flag_bit
;
3778 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3782 elt
= Fcons (make_number (fnum
), elt
);
3787 res
= Fcons (elt
, res
);
3790 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3791 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3793 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3794 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3798 for (n
= 0; n
< 6; n
++)
3799 p
->contents
[n
] = make_number (((unsigned char *)
3800 &rq
.ifr_hwaddr
.sa_data
[0])
3802 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3804 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3805 if (getifaddrs (&ifap
) != -1)
3807 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3808 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3811 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3813 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3814 unsigned char linkaddr
[6];
3817 if (it
->ifa_addr
->sa_family
!= AF_LINK
3818 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3819 || sdl
->sdl_alen
!= 6)
3822 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3823 for (n
= 0; n
< 6; n
++)
3824 p
->contents
[n
] = make_number (linkaddr
[n
]);
3826 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3830 #ifdef HAVE_FREEIFADDRS
3834 #endif /* HAVE_GETIFADDRS && LLADDR */
3836 res
= Fcons (elt
, res
);
3839 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3840 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3843 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3844 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3846 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3850 res
= Fcons (elt
, res
);
3853 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3854 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3857 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3860 res
= Fcons (elt
, res
);
3863 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3864 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3867 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3870 res
= Fcons (elt
, res
);
3872 return unbind_to (count
, any
? res
: Qnil
);
3874 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3875 #endif /* defined (HAVE_NET_IF_H) */
3877 DEFUN ("network-interface-list", Fnetwork_interface_list
,
3878 Snetwork_interface_list
, 0, 0, 0,
3879 doc
: /* Return an alist of all network interfaces and their network address.
3880 Each element is a cons, the car of which is a string containing the
3881 interface name, and the cdr is the network address in internal
3882 format; see the description of ADDRESS in `make-network-process'.
3884 If the information is not available, return nil. */)
3887 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3888 return network_interface_list ();
3894 DEFUN ("network-interface-info", Fnetwork_interface_info
,
3895 Snetwork_interface_info
, 1, 1, 0,
3896 doc
: /* Return information about network interface named IFNAME.
3897 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3898 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3899 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3900 FLAGS is the current flags of the interface.
3902 Data that is unavailable is returned as nil. */)
3903 (Lisp_Object ifname
)
3905 #if ((defined HAVE_NET_IF_H \
3906 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3907 || defined SIOCGIFFLAGS)) \
3908 || defined WINDOWSNT)
3909 return network_interface_info (ifname
);
3915 /* If program file NAME starts with /: for quoting a magic
3916 name, remove that, preserving the multibyteness of NAME. */
3919 remove_slash_colon (Lisp_Object name
)
3922 ((SBYTES (name
) > 2 && SREF (name
, 0) == '/' && SREF (name
, 1) == ':')
3923 ? make_specified_string (SSDATA (name
) + 2, SCHARS (name
) - 2,
3924 SBYTES (name
) - 2, STRING_MULTIBYTE (name
))
3928 /* Turn off input and output for process PROC. */
3931 deactivate_process (Lisp_Object proc
)
3934 struct Lisp_Process
*p
= XPROCESS (proc
);
3938 /* Delete GnuTLS structures in PROC, if any. */
3939 emacs_gnutls_deinit (proc
);
3940 #endif /* HAVE_GNUTLS */
3942 #ifdef ADAPTIVE_READ_BUFFERING
3943 if (p
->read_output_delay
> 0)
3945 if (--process_output_delay_count
< 0)
3946 process_output_delay_count
= 0;
3947 p
->read_output_delay
= 0;
3948 p
->read_output_skip
= 0;
3952 /* Beware SIGCHLD hereabouts. */
3954 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
3955 close_process_fd (&p
->open_fd
[i
]);
3957 inchannel
= p
->infd
;
3962 #ifdef DATAGRAM_SOCKETS
3963 if (DATAGRAM_CHAN_P (inchannel
))
3965 xfree (datagram_address
[inchannel
].sa
);
3966 datagram_address
[inchannel
].sa
= 0;
3967 datagram_address
[inchannel
].len
= 0;
3970 chan_process
[inchannel
] = Qnil
;
3971 FD_CLR (inchannel
, &input_wait_mask
);
3972 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3973 #ifdef NON_BLOCKING_CONNECT
3974 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3976 FD_CLR (inchannel
, &connect_wait_mask
);
3977 FD_CLR (inchannel
, &write_mask
);
3978 if (--num_pending_connects
< 0)
3982 if (inchannel
== max_process_desc
)
3984 /* We just closed the highest-numbered process input descriptor,
3985 so recompute the highest-numbered one now. */
3989 while (0 <= i
&& NILP (chan_process
[i
]));
3991 max_process_desc
= i
;
3997 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3999 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
4000 It is given to their filter functions.
4001 Optional argument PROCESS means do not return until output has been
4002 received from PROCESS.
4004 Optional second argument SECONDS and third argument MILLISEC
4005 specify a timeout; return after that much time even if there is
4006 no subprocess output. If SECONDS is a floating point number,
4007 it specifies a fractional number of seconds to wait.
4008 The MILLISEC argument is obsolete and should be avoided.
4010 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4011 from PROCESS only, suspending reading output from other processes.
4012 If JUST-THIS-ONE is an integer, don't run any timers either.
4013 Return non-nil if we received any output from PROCESS (or, if PROCESS
4014 is nil, from any process) before the timeout expired. */)
4015 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4020 if (! NILP (process
))
4021 CHECK_PROCESS (process
);
4023 just_this_one
= Qnil
;
4025 if (!NILP (millisec
))
4026 { /* Obsolete calling convention using integers rather than floats. */
4027 CHECK_NUMBER (millisec
);
4029 seconds
= make_float (XINT (millisec
) / 1000.0);
4032 CHECK_NUMBER (seconds
);
4033 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4040 if (!NILP (seconds
))
4042 if (INTEGERP (seconds
))
4044 if (XINT (seconds
) > 0)
4046 secs
= XINT (seconds
);
4050 else if (FLOATP (seconds
))
4052 if (XFLOAT_DATA (seconds
) > 0)
4054 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
4055 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
4060 wrong_type_argument (Qnumberp
, seconds
);
4062 else if (! NILP (process
))
4066 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
4068 !NILP (process
) ? XPROCESS (process
) : NULL
,
4069 (NILP (just_this_one
) ? 0
4070 : !INTEGERP (just_this_one
) ? 1 : -1))
4075 /* Accept a connection for server process SERVER on CHANNEL. */
4077 static EMACS_INT connect_counter
= 0;
4080 server_accept_connection (Lisp_Object server
, int channel
)
4082 Lisp_Object proc
, caller
, name
, buffer
;
4083 Lisp_Object contact
, host
, service
;
4084 struct Lisp_Process
*ps
= XPROCESS (server
);
4085 struct Lisp_Process
*p
;
4089 struct sockaddr_in in
;
4091 struct sockaddr_in6 in6
;
4093 #ifdef HAVE_LOCAL_SOCKETS
4094 struct sockaddr_un un
;
4097 socklen_t len
= sizeof saddr
;
4100 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4109 if (code
== EWOULDBLOCK
)
4113 if (!NILP (ps
->log
))
4114 call3 (ps
->log
, server
, Qnil
,
4115 concat3 (build_string ("accept failed with code"),
4116 Fnumber_to_string (make_number (code
)),
4117 build_string ("\n")));
4121 count
= SPECPDL_INDEX ();
4122 record_unwind_protect_int (close_file_unwind
, s
);
4126 /* Setup a new process to handle the connection. */
4128 /* Generate a unique identification of the caller, and build contact
4129 information for this process. */
4132 switch (saddr
.sa
.sa_family
)
4136 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4138 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4139 host
= CALLN (Fformat
, ipv4_format
,
4140 make_number (ip
[0]), make_number (ip
[1]),
4141 make_number (ip
[2]), make_number (ip
[3]));
4142 service
= make_number (ntohs (saddr
.in
.sin_port
));
4143 AUTO_STRING (caller_format
, " <%s:%d>");
4144 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4151 Lisp_Object args
[9];
4152 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4155 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4156 args
[0] = ipv6_format
;
4157 for (i
= 0; i
< 8; i
++)
4158 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4159 host
= CALLMANY (Fformat
, args
);
4160 service
= make_number (ntohs (saddr
.in
.sin_port
));
4161 AUTO_STRING (caller_format
, " <[%s]:%d>");
4162 caller
= CALLN (Fformat
, caller_format
, host
, service
);
4167 #ifdef HAVE_LOCAL_SOCKETS
4171 caller
= Fnumber_to_string (make_number (connect_counter
));
4172 AUTO_STRING (space_less_than
, " <");
4173 AUTO_STRING (greater_than
, ">");
4174 caller
= concat3 (space_less_than
, caller
, greater_than
);
4178 /* Create a new buffer name for this process if it doesn't have a
4179 filter. The new buffer name is based on the buffer name or
4180 process name of the server process concatenated with the caller
4183 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4184 || EQ (ps
->filter
, Qt
)))
4188 buffer
= ps
->buffer
;
4190 buffer
= Fbuffer_name (buffer
);
4195 buffer
= concat2 (buffer
, caller
);
4196 buffer
= Fget_buffer_create (buffer
);
4200 /* Generate a unique name for the new server process. Combine the
4201 server process name with the caller identification. */
4203 name
= concat2 (ps
->name
, caller
);
4204 proc
= make_process (name
);
4206 chan_process
[s
] = proc
;
4208 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4210 p
= XPROCESS (proc
);
4212 /* Build new contact information for this setup. */
4213 contact
= Fcopy_sequence (ps
->childp
);
4214 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4215 contact
= Fplist_put (contact
, QChost
, host
);
4216 if (!NILP (service
))
4217 contact
= Fplist_put (contact
, QCservice
, service
);
4218 contact
= Fplist_put (contact
, QCremote
,
4219 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4220 #ifdef HAVE_GETSOCKNAME
4222 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4223 contact
= Fplist_put (contact
, QClocal
,
4224 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4227 pset_childp (p
, contact
);
4228 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4229 pset_type (p
, Qnetwork
);
4231 pset_buffer (p
, buffer
);
4232 pset_sentinel (p
, ps
->sentinel
);
4233 pset_filter (p
, ps
->filter
);
4234 pset_command (p
, Qnil
);
4237 /* Discard the unwind protect for closing S. */
4238 specpdl_ptr
= specpdl
+ count
;
4240 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4243 pset_status (p
, Qrun
);
4245 /* Client processes for accepted connections are not stopped initially. */
4246 if (!EQ (p
->filter
, Qt
))
4248 FD_SET (s
, &input_wait_mask
);
4249 FD_SET (s
, &non_keyboard_wait_mask
);
4252 if (s
> max_process_desc
)
4253 max_process_desc
= s
;
4255 /* Setup coding system for new process based on server process.
4256 This seems to be the proper thing to do, as the coding system
4257 of the new process should reflect the settings at the time the
4258 server socket was opened; not the current settings. */
4260 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4261 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4262 setup_process_coding_systems (proc
);
4264 pset_decoding_buf (p
, empty_unibyte_string
);
4265 p
->decoding_carryover
= 0;
4266 pset_encoding_buf (p
, empty_unibyte_string
);
4268 p
->inherit_coding_system_flag
4269 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4271 AUTO_STRING (dash
, "-");
4272 AUTO_STRING (nl
, "\n");
4273 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4275 if (!NILP (ps
->log
))
4277 AUTO_STRING (accept_from
, "accept from ");
4278 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4281 AUTO_STRING (open_from
, "open from ");
4282 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4285 /* This variable is different from waiting_for_input in keyboard.c.
4286 It is used to communicate to a lisp process-filter/sentinel (via the
4287 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4288 for user-input when that process-filter was called.
4289 waiting_for_input cannot be used as that is by definition 0 when
4290 lisp code is being evalled.
4291 This is also used in record_asynch_buffer_change.
4292 For that purpose, this must be 0
4293 when not inside wait_reading_process_output. */
4294 static int waiting_for_user_input_p
;
4297 wait_reading_process_output_unwind (int data
)
4299 waiting_for_user_input_p
= data
;
4302 /* This is here so breakpoints can be put on it. */
4304 wait_reading_process_output_1 (void)
4308 /* Read and dispose of subprocess output while waiting for timeout to
4309 elapse and/or keyboard input to be available.
4313 If negative, gobble data immediately available but don't wait for any.
4316 an additional duration to wait, measured in nanoseconds
4317 If TIME_LIMIT is zero, then:
4318 If NSECS == 0, there is no limit.
4319 If NSECS > 0, the timeout consists of NSECS only.
4320 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4323 0 to ignore keyboard input, or
4324 1 to return when input is available, or
4325 -1 meaning caller will actually read the input, so don't throw to
4326 the quit handler, or
4328 DO_DISPLAY means redisplay should be done to show subprocess
4329 output that arrives.
4331 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4332 (and gobble terminal input into the buffer if any arrives).
4334 If WAIT_PROC is specified, wait until something arrives from that
4337 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4338 (suspending output from other processes). A negative value
4339 means don't run any timers either.
4341 Return positive if we received input from WAIT_PROC (or from any
4342 process if WAIT_PROC is null), zero if we attempted to receive
4343 input but got none, and negative if we didn't even try. */
4346 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4348 Lisp_Object wait_for_cell
,
4349 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4359 struct timespec timeout
, end_time
;
4360 int got_some_input
= -1;
4361 ptrdiff_t count
= SPECPDL_INDEX ();
4363 FD_ZERO (&Available
);
4366 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4367 && !(CONSP (wait_proc
->status
)
4368 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4369 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4371 record_unwind_protect_int (wait_reading_process_output_unwind
,
4372 waiting_for_user_input_p
);
4373 waiting_for_user_input_p
= read_kbd
;
4380 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4381 time_limit
= TYPE_MAXIMUM (time_t);
4383 /* Since we may need to wait several times,
4384 compute the absolute time to return at. */
4385 if (time_limit
|| nsecs
> 0)
4387 timeout
= make_timespec (time_limit
, nsecs
);
4388 end_time
= timespec_add (current_timespec (), timeout
);
4393 bool timeout_reduced_for_timers
= false;
4395 /* If calling from keyboard input, do not quit
4396 since we want to return C-g as an input character.
4397 Otherwise, do pending quit if requested. */
4400 else if (pending_signals
)
4401 process_pending_signals ();
4403 /* Exit now if the cell we're waiting for became non-nil. */
4404 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4407 /* After reading input, vacuum up any leftovers without waiting. */
4408 if (0 <= got_some_input
)
4411 /* Compute time from now till when time limit is up. */
4412 /* Exit if already run out. */
4415 /* A negative timeout means
4416 gobble output available now
4417 but don't wait at all. */
4419 timeout
= make_timespec (0, 0);
4421 else if (time_limit
|| nsecs
> 0)
4423 struct timespec now
= current_timespec ();
4424 if (timespec_cmp (end_time
, now
) <= 0)
4426 timeout
= timespec_sub (end_time
, now
);
4430 timeout
= make_timespec (100000, 0);
4433 /* Normally we run timers here.
4434 But not if wait_for_cell; in those cases,
4435 the wait is supposed to be short,
4436 and those callers cannot handle running arbitrary Lisp code here. */
4437 if (NILP (wait_for_cell
)
4438 && just_wait_proc
>= 0)
4440 struct timespec timer_delay
;
4444 unsigned old_timers_run
= timers_run
;
4445 struct buffer
*old_buffer
= current_buffer
;
4446 Lisp_Object old_window
= selected_window
;
4448 timer_delay
= timer_check ();
4450 /* If a timer has run, this might have changed buffers
4451 an alike. Make read_key_sequence aware of that. */
4452 if (timers_run
!= old_timers_run
4453 && (old_buffer
!= current_buffer
4454 || !EQ (old_window
, selected_window
))
4455 && waiting_for_user_input_p
== -1)
4456 record_asynch_buffer_change ();
4458 if (timers_run
!= old_timers_run
&& do_display
)
4459 /* We must retry, since a timer may have requeued itself
4460 and that could alter the time_delay. */
4461 redisplay_preserve_echo_area (9);
4465 while (!detect_input_pending ());
4467 /* If there is unread keyboard input, also return. */
4469 && requeued_events_pending_p ())
4472 /* A negative timeout means do not wait at all. */
4475 if (timespec_valid_p (timer_delay
))
4477 if (timespec_cmp (timer_delay
, timeout
) < 0)
4479 timeout
= timer_delay
;
4480 timeout_reduced_for_timers
= true;
4485 /* This is so a breakpoint can be put here. */
4486 wait_reading_process_output_1 ();
4491 /* Cause C-g and alarm signals to take immediate action,
4492 and cause input available signals to zero out timeout.
4494 It is important that we do this before checking for process
4495 activity. If we get a SIGCHLD after the explicit checks for
4496 process activity, timeout is the only way we will know. */
4498 set_waiting_for_input (&timeout
);
4500 /* If status of something has changed, and no input is
4501 available, notify the user of the change right away. After
4502 this explicit check, we'll let the SIGCHLD handler zap
4503 timeout to get our attention. */
4504 if (update_tick
!= process_tick
)
4509 if (kbd_on_hold_p ())
4512 Atemp
= input_wait_mask
;
4515 timeout
= make_timespec (0, 0);
4516 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4518 #ifdef NON_BLOCKING_CONNECT
4519 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4523 NULL
, &timeout
, NULL
)
4526 /* It's okay for us to do this and then continue with
4527 the loop, since timeout has already been zeroed out. */
4528 clear_waiting_for_input ();
4529 got_some_input
= status_notify (NULL
, wait_proc
);
4530 if (do_display
) redisplay_preserve_echo_area (13);
4534 /* Don't wait for output from a non-running process. Just
4535 read whatever data has already been received. */
4536 if (wait_proc
&& wait_proc
->raw_status_new
)
4537 update_status (wait_proc
);
4539 && wait_proc
->infd
>= 0
4540 && ! EQ (wait_proc
->status
, Qrun
)
4541 && ! EQ (wait_proc
->status
, Qconnect
))
4543 bool read_some_bytes
= false;
4545 clear_waiting_for_input ();
4546 XSETPROCESS (proc
, wait_proc
);
4548 /* Read data from the process, until we exhaust it. */
4551 int nread
= read_process_output (proc
, wait_proc
->infd
);
4554 if (errno
== EIO
|| errno
== EAGAIN
)
4557 if (errno
== EWOULDBLOCK
)
4563 if (got_some_input
< nread
)
4564 got_some_input
= nread
;
4567 read_some_bytes
= true;
4570 if (read_some_bytes
&& do_display
)
4571 redisplay_preserve_echo_area (10);
4576 /* Wait till there is something to do. */
4578 if (wait_proc
&& just_wait_proc
)
4580 if (wait_proc
->infd
< 0) /* Terminated. */
4582 FD_SET (wait_proc
->infd
, &Available
);
4586 else if (!NILP (wait_for_cell
))
4588 Available
= non_process_wait_mask
;
4595 Available
= non_keyboard_wait_mask
;
4597 Available
= input_wait_mask
;
4598 Writeok
= write_mask
;
4599 check_delay
= wait_proc
? 0 : process_output_delay_count
;
4603 /* If frame size has changed or the window is newly mapped,
4604 redisplay now, before we start to wait. There is a race
4605 condition here; if a SIGIO arrives between now and the select
4606 and indicates that a frame is trashed, the select may block
4607 displaying a trashed screen. */
4608 if (frame_garbaged
&& do_display
)
4610 clear_waiting_for_input ();
4611 redisplay_preserve_echo_area (11);
4613 set_waiting_for_input (&timeout
);
4616 /* Skip the `select' call if input is available and we're
4617 waiting for keyboard input or a cell change (which can be
4618 triggered by processing X events). In the latter case, set
4619 nfds to 1 to avoid breaking the loop. */
4621 if ((read_kbd
|| !NILP (wait_for_cell
))
4622 && detect_input_pending ())
4624 nfds
= read_kbd
? 0 : 1;
4626 FD_ZERO (&Available
);
4632 #ifdef ADAPTIVE_READ_BUFFERING
4633 /* Set the timeout for adaptive read buffering if any
4634 process has non-zero read_output_skip and non-zero
4635 read_output_delay, and we are not reading output for a
4636 specific process. It is not executed if
4637 Vprocess_adaptive_read_buffering is nil. */
4638 if (process_output_skip
&& check_delay
> 0)
4640 int nsecs
= timeout
.tv_nsec
;
4641 if (timeout
.tv_sec
> 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4642 nsecs
= READ_OUTPUT_DELAY_MAX
;
4643 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4645 proc
= chan_process
[channel
];
4648 /* Find minimum non-zero read_output_delay among the
4649 processes with non-zero read_output_skip. */
4650 if (XPROCESS (proc
)->read_output_delay
> 0)
4653 if (!XPROCESS (proc
)->read_output_skip
)
4655 FD_CLR (channel
, &Available
);
4656 XPROCESS (proc
)->read_output_skip
= 0;
4657 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4658 nsecs
= XPROCESS (proc
)->read_output_delay
;
4661 timeout
= make_timespec (0, nsecs
);
4662 process_output_skip
= 0;
4666 #if defined (HAVE_NS)
4668 #elif defined (HAVE_GLIB)
4673 (max (max_process_desc
, max_input_desc
) + 1,
4675 (check_write
? &Writeok
: 0),
4676 NULL
, &timeout
, NULL
);
4679 /* GnuTLS buffers data internally. In lowat mode it leaves
4680 some data in the TCP buffers so that select works, but
4681 with custom pull/push functions we need to check if some
4682 data is available in the buffers manually. */
4687 /* We're not waiting on a specific process, so loop
4688 through all the channels and check for data.
4689 This is a workaround needed for some versions of
4690 the gnutls library -- 2.12.14 has been confirmed
4692 http://comments.gmane.org/gmane.emacs.devel/145074 */
4693 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
4694 if (! NILP (chan_process
[channel
]))
4696 struct Lisp_Process
*p
=
4697 XPROCESS (chan_process
[channel
]);
4698 if (p
&& p
->gnutls_p
&& p
->gnutls_state
4699 && ((emacs_gnutls_record_check_pending
4704 eassert (p
->infd
== channel
);
4705 FD_SET (p
->infd
, &Available
);
4711 /* Check this specific channel. */
4712 if (wait_proc
->gnutls_p
/* Check for valid process. */
4713 && wait_proc
->gnutls_state
4714 /* Do we have pending data? */
4715 && ((emacs_gnutls_record_check_pending
4716 (wait_proc
->gnutls_state
))
4720 eassert (0 <= wait_proc
->infd
);
4721 /* Set to Available. */
4722 FD_SET (wait_proc
->infd
, &Available
);
4731 /* Make C-g and alarm signals set flags again. */
4732 clear_waiting_for_input ();
4734 /* If we woke up due to SIGWINCH, actually change size now. */
4735 do_pending_window_change (0);
4737 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4738 /* We waited the full specified time, so return now. */
4742 if (xerrno
== EINTR
)
4744 else if (xerrno
== EBADF
)
4747 report_file_errno ("Failed select", Qnil
, xerrno
);
4750 /* Check for keyboard input. */
4751 /* If there is any, return immediately
4752 to give it higher priority than subprocesses. */
4756 unsigned old_timers_run
= timers_run
;
4757 struct buffer
*old_buffer
= current_buffer
;
4758 Lisp_Object old_window
= selected_window
;
4761 if (detect_input_pending_run_timers (do_display
))
4763 swallow_events (do_display
);
4764 if (detect_input_pending_run_timers (do_display
))
4768 /* If a timer has run, this might have changed buffers
4769 an alike. Make read_key_sequence aware of that. */
4770 if (timers_run
!= old_timers_run
4771 && waiting_for_user_input_p
== -1
4772 && (old_buffer
!= current_buffer
4773 || !EQ (old_window
, selected_window
)))
4774 record_asynch_buffer_change ();
4780 /* If there is unread keyboard input, also return. */
4782 && requeued_events_pending_p ())
4785 /* If we are not checking for keyboard input now,
4786 do process events (but don't run any timers).
4787 This is so that X events will be processed.
4788 Otherwise they may have to wait until polling takes place.
4789 That would causes delays in pasting selections, for example.
4791 (We used to do this only if wait_for_cell.) */
4792 if (read_kbd
== 0 && detect_input_pending ())
4794 swallow_events (do_display
);
4795 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4796 if (detect_input_pending ())
4801 /* Exit now if the cell we're waiting for became non-nil. */
4802 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4806 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4807 go read it. This can happen with X on BSD after logging out.
4808 In that case, there really is no input and no SIGIO,
4809 but select says there is input. */
4811 if (read_kbd
&& interrupt_input
4812 && keyboard_bit_set (&Available
) && ! noninteractive
)
4813 handle_input_available_signal (SIGIO
);
4816 /* If checking input just got us a size-change event from X,
4817 obey it now if we should. */
4818 if (read_kbd
|| ! NILP (wait_for_cell
))
4819 do_pending_window_change (0);
4821 /* Check for data from a process. */
4822 if (no_avail
|| nfds
== 0)
4825 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4827 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4829 && ((d
->condition
& FOR_READ
4830 && FD_ISSET (channel
, &Available
))
4831 || (d
->condition
& FOR_WRITE
4832 && FD_ISSET (channel
, &write_mask
))))
4833 d
->func (channel
, d
->data
);
4836 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4838 if (FD_ISSET (channel
, &Available
)
4839 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4840 && !FD_ISSET (channel
, &non_process_wait_mask
))
4844 /* If waiting for this channel, arrange to return as
4845 soon as no more input to be processed. No more
4847 proc
= chan_process
[channel
];
4851 /* If this is a server stream socket, accept connection. */
4852 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4854 server_accept_connection (proc
, channel
);
4858 /* Read data from the process, starting with our
4859 buffered-ahead character if we have one. */
4861 nread
= read_process_output (proc
, channel
);
4862 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
)) && got_some_input
< nread
)
4863 got_some_input
= nread
;
4866 /* Since read_process_output can run a filter,
4867 which can call accept-process-output,
4868 don't try to read from any other processes
4869 before doing the select again. */
4870 FD_ZERO (&Available
);
4873 redisplay_preserve_echo_area (12);
4876 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4879 else if (nread
== -1 && errno
== EAGAIN
)
4882 /* FIXME: Is this special case still needed? */
4883 /* Note that we cannot distinguish between no input
4884 available now and a closed pipe.
4885 With luck, a closed pipe will be accompanied by
4886 subprocess termination and SIGCHLD. */
4887 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4891 /* On some OSs with ptys, when the process on one end of
4892 a pty exits, the other end gets an error reading with
4893 errno = EIO instead of getting an EOF (0 bytes read).
4894 Therefore, if we get an error reading and errno =
4895 EIO, just continue, because the child process has
4896 exited and should clean itself up soon (e.g. when we
4898 else if (nread
== -1 && errno
== EIO
)
4900 struct Lisp_Process
*p
= XPROCESS (proc
);
4902 /* Clear the descriptor now, so we only raise the
4904 FD_CLR (channel
, &input_wait_mask
);
4905 FD_CLR (channel
, &non_keyboard_wait_mask
);
4909 /* If the EIO occurs on a pty, the SIGCHLD handler's
4910 waitpid call will not find the process object to
4911 delete. Do it here. */
4912 p
->tick
= ++process_tick
;
4913 pset_status (p
, Qfailed
);
4916 #endif /* HAVE_PTYS */
4917 /* If we can detect process termination, don't consider the
4918 process gone just because its pipe is closed. */
4919 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4923 /* Preserve status of processes already terminated. */
4924 XPROCESS (proc
)->tick
= ++process_tick
;
4925 deactivate_process (proc
);
4926 if (XPROCESS (proc
)->raw_status_new
)
4927 update_status (XPROCESS (proc
));
4928 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4929 pset_status (XPROCESS (proc
),
4930 list2 (Qexit
, make_number (256)));
4933 #ifdef NON_BLOCKING_CONNECT
4934 if (FD_ISSET (channel
, &Writeok
)
4935 && FD_ISSET (channel
, &connect_wait_mask
))
4937 struct Lisp_Process
*p
;
4939 FD_CLR (channel
, &connect_wait_mask
);
4940 FD_CLR (channel
, &write_mask
);
4941 if (--num_pending_connects
< 0)
4944 proc
= chan_process
[channel
];
4948 p
= XPROCESS (proc
);
4951 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4952 So only use it on systems where it is known to work. */
4954 socklen_t xlen
= sizeof (xerrno
);
4955 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4960 struct sockaddr pname
;
4961 socklen_t pnamelen
= sizeof (pname
);
4963 /* If connection failed, getpeername will fail. */
4965 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4967 /* Obtain connect failure code through error slippage. */
4970 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4977 p
->tick
= ++process_tick
;
4978 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
4979 deactivate_process (proc
);
4983 pset_status (p
, Qrun
);
4984 /* Execute the sentinel here. If we had relied on
4985 status_notify to do it later, it will read input
4986 from the process before calling the sentinel. */
4987 exec_sentinel (proc
, build_string ("open\n"));
4988 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
4989 && !EQ (p
->command
, Qt
))
4991 FD_SET (p
->infd
, &input_wait_mask
);
4992 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4996 #endif /* NON_BLOCKING_CONNECT */
4997 } /* End for each file descriptor. */
4998 } /* End while exit conditions not met. */
5000 unbind_to (count
, Qnil
);
5002 /* If calling from keyboard input, do not quit
5003 since we want to return C-g as an input character.
5004 Otherwise, do pending quit if requested. */
5007 /* Prevent input_pending from remaining set if we quit. */
5008 clear_input_pending ();
5012 return got_some_input
;
5015 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5018 read_process_output_call (Lisp_Object fun_and_args
)
5020 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5024 read_process_output_error_handler (Lisp_Object error_val
)
5026 cmd_error_internal (error_val
, "error in process filter: ");
5028 update_echo_area ();
5029 Fsleep_for (make_number (2), Qnil
);
5034 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5036 struct coding_system
*coding
);
5038 /* Read pending output from the process channel,
5039 starting with our buffered-ahead character if we have one.
5040 Yield number of decoded characters read.
5042 This function reads at most 4096 characters.
5043 If you want to read all available subprocess output,
5044 you must call it repeatedly until it returns zero.
5046 The characters read are decoded according to PROC's coding-system
5050 read_process_output (Lisp_Object proc
, int channel
)
5053 struct Lisp_Process
*p
= XPROCESS (proc
);
5054 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5055 int carryover
= p
->decoding_carryover
;
5056 enum { readmax
= 4096 };
5057 ptrdiff_t count
= SPECPDL_INDEX ();
5058 Lisp_Object odeactivate
;
5059 char chars
[sizeof coding
->carryover
+ readmax
];
5062 /* See the comment above. */
5063 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5065 #ifdef DATAGRAM_SOCKETS
5066 /* We have a working select, so proc_buffered_char is always -1. */
5067 if (DATAGRAM_CHAN_P (channel
))
5069 socklen_t len
= datagram_address
[channel
].len
;
5070 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5071 0, datagram_address
[channel
].sa
, &len
);
5076 bool buffered
= proc_buffered_char
[channel
] >= 0;
5079 chars
[carryover
] = proc_buffered_char
[channel
];
5080 proc_buffered_char
[channel
] = -1;
5083 if (p
->gnutls_p
&& p
->gnutls_state
)
5084 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5085 readmax
- buffered
);
5088 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5089 readmax
- buffered
);
5090 #ifdef ADAPTIVE_READ_BUFFERING
5091 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5093 int delay
= p
->read_output_delay
;
5096 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5099 process_output_delay_count
++;
5100 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5103 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5105 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5107 process_output_delay_count
--;
5109 p
->read_output_delay
= delay
;
5112 p
->read_output_skip
= 1;
5113 process_output_skip
= 1;
5118 nbytes
+= buffered
&& nbytes
<= 0;
5121 p
->decoding_carryover
= 0;
5123 /* At this point, NBYTES holds number of bytes just received
5124 (including the one in proc_buffered_char[channel]). */
5127 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5129 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5132 /* Now set NBYTES how many bytes we must decode. */
5133 nbytes
+= carryover
;
5135 odeactivate
= Vdeactivate_mark
;
5136 /* There's no good reason to let process filters change the current
5137 buffer, and many callers of accept-process-output, sit-for, and
5138 friends don't expect current-buffer to be changed from under them. */
5139 record_unwind_current_buffer ();
5141 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5143 /* Handling the process output should not deactivate the mark. */
5144 Vdeactivate_mark
= odeactivate
;
5146 unbind_to (count
, Qnil
);
5151 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5153 struct coding_system
*coding
)
5155 Lisp_Object outstream
= p
->filter
;
5157 bool outer_running_asynch_code
= running_asynch_code
;
5158 int waiting
= waiting_for_user_input_p
;
5160 /* No need to gcpro these, because all we do with them later
5161 is test them for EQness, and none of them should be a string. */
5163 Lisp_Object obuffer
, okeymap
;
5164 XSETBUFFER (obuffer
, current_buffer
);
5165 okeymap
= BVAR (current_buffer
, keymap
);
5168 /* We inhibit quit here instead of just catching it so that
5169 hitting ^G when a filter happens to be running won't screw
5171 specbind (Qinhibit_quit
, Qt
);
5172 specbind (Qlast_nonmenu_event
, Qt
);
5174 /* In case we get recursively called,
5175 and we already saved the match data nonrecursively,
5176 save the same match data in safely recursive fashion. */
5177 if (outer_running_asynch_code
)
5180 /* Don't clobber the CURRENT match data, either! */
5181 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5182 restore_search_regs ();
5183 record_unwind_save_match_data ();
5184 Fset_match_data (tem
, Qt
);
5187 /* For speed, if a search happens within this code,
5188 save the match data in a special nonrecursive fashion. */
5189 running_asynch_code
= 1;
5191 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5192 text
= coding
->dst_object
;
5193 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5194 /* A new coding system might be found. */
5195 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5197 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5199 /* Don't call setup_coding_system for
5200 proc_decode_coding_system[channel] here. It is done in
5201 detect_coding called via decode_coding above. */
5203 /* If a coding system for encoding is not yet decided, we set
5204 it as the same as coding-system for decoding.
5206 But, before doing that we must check if
5207 proc_encode_coding_system[p->outfd] surely points to a
5208 valid memory because p->outfd will be changed once EOF is
5209 sent to the process. */
5210 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5211 && proc_encode_coding_system
[p
->outfd
])
5213 pset_encode_coding_system
5214 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5215 setup_coding_system (p
->encode_coding_system
,
5216 proc_encode_coding_system
[p
->outfd
]);
5220 if (coding
->carryover_bytes
> 0)
5222 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5223 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5224 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5225 coding
->carryover_bytes
);
5226 p
->decoding_carryover
= coding
->carryover_bytes
;
5228 if (SBYTES (text
) > 0)
5229 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5230 sometimes it's simply wrong to wrap (e.g. when called from
5231 accept-process-output). */
5232 internal_condition_case_1 (read_process_output_call
,
5233 list3 (outstream
, make_lisp_proc (p
), text
),
5234 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5235 read_process_output_error_handler
);
5237 /* If we saved the match data nonrecursively, restore it now. */
5238 restore_search_regs ();
5239 running_asynch_code
= outer_running_asynch_code
;
5241 /* Restore waiting_for_user_input_p as it was
5242 when we were called, in case the filter clobbered it. */
5243 waiting_for_user_input_p
= waiting
;
5245 #if 0 /* Call record_asynch_buffer_change unconditionally,
5246 because we might have changed minor modes or other things
5247 that affect key bindings. */
5248 if (! EQ (Fcurrent_buffer (), obuffer
)
5249 || ! EQ (current_buffer
->keymap
, okeymap
))
5251 /* But do it only if the caller is actually going to read events.
5252 Otherwise there's no need to make him wake up, and it could
5253 cause trouble (for example it would make sit_for return). */
5254 if (waiting_for_user_input_p
== -1)
5255 record_asynch_buffer_change ();
5258 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5259 Sinternal_default_process_filter
, 2, 2, 0,
5260 doc
: /* Function used as default process filter.
5261 This inserts the process's output into its buffer, if there is one.
5262 Otherwise it discards the output. */)
5263 (Lisp_Object proc
, Lisp_Object text
)
5265 struct Lisp_Process
*p
;
5268 CHECK_PROCESS (proc
);
5269 p
= XPROCESS (proc
);
5270 CHECK_STRING (text
);
5272 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5274 Lisp_Object old_read_only
;
5275 ptrdiff_t old_begv
, old_zv
;
5276 ptrdiff_t old_begv_byte
, old_zv_byte
;
5277 ptrdiff_t before
, before_byte
;
5278 ptrdiff_t opoint_byte
;
5281 Fset_buffer (p
->buffer
);
5283 opoint_byte
= PT_BYTE
;
5284 old_read_only
= BVAR (current_buffer
, read_only
);
5287 old_begv_byte
= BEGV_BYTE
;
5288 old_zv_byte
= ZV_BYTE
;
5290 bset_read_only (current_buffer
, Qnil
);
5292 /* Insert new output into buffer at the current end-of-output
5293 marker, thus preserving logical ordering of input and output. */
5294 if (XMARKER (p
->mark
)->buffer
)
5295 set_point_from_marker (p
->mark
);
5297 SET_PT_BOTH (ZV
, ZV_BYTE
);
5299 before_byte
= PT_BYTE
;
5301 /* If the output marker is outside of the visible region, save
5302 the restriction and widen. */
5303 if (! (BEGV
<= PT
&& PT
<= ZV
))
5306 /* Adjust the multibyteness of TEXT to that of the buffer. */
5307 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5308 != ! STRING_MULTIBYTE (text
))
5309 text
= (STRING_MULTIBYTE (text
)
5310 ? Fstring_as_unibyte (text
)
5311 : Fstring_to_multibyte (text
));
5312 /* Insert before markers in case we are inserting where
5313 the buffer's mark is, and the user's next command is Meta-y. */
5314 insert_from_string_before_markers (text
, 0, 0,
5315 SCHARS (text
), SBYTES (text
), 0);
5317 /* Make sure the process marker's position is valid when the
5318 process buffer is changed in the signal_after_change above.
5319 W3 is known to do that. */
5320 if (BUFFERP (p
->buffer
)
5321 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5322 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5324 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5326 update_mode_lines
= 23;
5328 /* Make sure opoint and the old restrictions
5329 float ahead of any new text just as point would. */
5330 if (opoint
>= before
)
5332 opoint
+= PT
- before
;
5333 opoint_byte
+= PT_BYTE
- before_byte
;
5335 if (old_begv
> before
)
5337 old_begv
+= PT
- before
;
5338 old_begv_byte
+= PT_BYTE
- before_byte
;
5340 if (old_zv
>= before
)
5342 old_zv
+= PT
- before
;
5343 old_zv_byte
+= PT_BYTE
- before_byte
;
5346 /* If the restriction isn't what it should be, set it. */
5347 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5348 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5350 bset_read_only (current_buffer
, old_read_only
);
5351 SET_PT_BOTH (opoint
, opoint_byte
);
5356 /* Sending data to subprocess. */
5358 /* In send_process, when a write fails temporarily,
5359 wait_reading_process_output is called. It may execute user code,
5360 e.g. timers, that attempts to write new data to the same process.
5361 We must ensure that data is sent in the right order, and not
5362 interspersed half-completed with other writes (Bug#10815). This is
5363 handled by the write_queue element of struct process. It is a list
5364 with each entry having the form
5366 (string . (offset . length))
5368 where STRING is a lisp string, OFFSET is the offset into the
5369 string's byte sequence from which we should begin to send, and
5370 LENGTH is the number of bytes left to send. */
5372 /* Create a new entry in write_queue.
5373 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5374 BUF is a pointer to the string sequence of the input_obj or a C
5375 string in case of Qt or Qnil. */
5378 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5379 const char *buf
, ptrdiff_t len
, bool front
)
5382 Lisp_Object entry
, obj
;
5384 if (STRINGP (input_obj
))
5386 offset
= buf
- SSDATA (input_obj
);
5392 obj
= make_unibyte_string (buf
, len
);
5395 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5398 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5400 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5403 /* Remove the first element in the write_queue of process P, put its
5404 contents in OBJ, BUF and LEN, and return true. If the
5405 write_queue is empty, return false. */
5408 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5409 const char **buf
, ptrdiff_t *len
)
5411 Lisp_Object entry
, offset_length
;
5414 if (NILP (p
->write_queue
))
5417 entry
= XCAR (p
->write_queue
);
5418 pset_write_queue (p
, XCDR (p
->write_queue
));
5420 *obj
= XCAR (entry
);
5421 offset_length
= XCDR (entry
);
5423 *len
= XINT (XCDR (offset_length
));
5424 offset
= XINT (XCAR (offset_length
));
5425 *buf
= SSDATA (*obj
) + offset
;
5430 /* Send some data to process PROC.
5431 BUF is the beginning of the data; LEN is the number of characters.
5432 OBJECT is the Lisp object that the data comes from. If OBJECT is
5433 nil or t, it means that the data comes from C string.
5435 If OBJECT is not nil, the data is encoded by PROC's coding-system
5436 for encoding before it is sent.
5438 This function can evaluate Lisp code and can garbage collect. */
5441 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5444 struct Lisp_Process
*p
= XPROCESS (proc
);
5446 struct coding_system
*coding
;
5448 if (p
->raw_status_new
)
5450 if (! EQ (p
->status
, Qrun
))
5451 error ("Process %s not running", SDATA (p
->name
));
5453 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5455 coding
= proc_encode_coding_system
[p
->outfd
];
5456 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5458 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5459 || (BUFFERP (object
)
5460 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5463 pset_encode_coding_system
5464 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5465 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5467 /* The coding system for encoding was changed to raw-text
5468 because we sent a unibyte text previously. Now we are
5469 sending a multibyte text, thus we must encode it by the
5470 original coding system specified for the current process.
5472 Another reason we come here is that the coding system
5473 was just complemented and a new one was returned by
5474 complement_process_encoding_system. */
5475 setup_coding_system (p
->encode_coding_system
, coding
);
5476 Vlast_coding_system_used
= p
->encode_coding_system
;
5478 coding
->src_multibyte
= 1;
5482 coding
->src_multibyte
= 0;
5483 /* For sending a unibyte text, character code conversion should
5484 not take place but EOL conversion should. So, setup raw-text
5485 or one of the subsidiary if we have not yet done it. */
5486 if (CODING_REQUIRE_ENCODING (coding
))
5488 if (CODING_REQUIRE_FLUSHING (coding
))
5490 /* But, before changing the coding, we must flush out data. */
5491 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5492 send_process (proc
, "", 0, Qt
);
5493 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5495 setup_coding_system (raw_text_coding_system
5496 (Vlast_coding_system_used
),
5498 coding
->src_multibyte
= 0;
5501 coding
->dst_multibyte
= 0;
5503 if (CODING_REQUIRE_ENCODING (coding
))
5505 coding
->dst_object
= Qt
;
5506 if (BUFFERP (object
))
5508 ptrdiff_t from_byte
, from
, to
;
5509 ptrdiff_t save_pt
, save_pt_byte
;
5510 struct buffer
*cur
= current_buffer
;
5512 set_buffer_internal (XBUFFER (object
));
5513 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5515 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5516 from
= BYTE_TO_CHAR (from_byte
);
5517 to
= BYTE_TO_CHAR (from_byte
+ len
);
5518 TEMP_SET_PT_BOTH (from
, from_byte
);
5519 encode_coding_object (coding
, object
, from
, from_byte
,
5520 to
, from_byte
+ len
, Qt
);
5521 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5522 set_buffer_internal (cur
);
5524 else if (STRINGP (object
))
5526 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5527 SBYTES (object
), Qt
);
5531 coding
->dst_object
= make_unibyte_string (buf
, len
);
5532 coding
->produced
= len
;
5535 len
= coding
->produced
;
5536 object
= coding
->dst_object
;
5537 buf
= SSDATA (object
);
5540 /* If there is already data in the write_queue, put the new data
5541 in the back of queue. Otherwise, ignore it. */
5542 if (!NILP (p
->write_queue
))
5543 write_queue_push (p
, object
, buf
, len
, 0);
5545 do /* while !NILP (p->write_queue) */
5547 ptrdiff_t cur_len
= -1;
5548 const char *cur_buf
;
5549 Lisp_Object cur_object
;
5551 /* If write_queue is empty, ignore it. */
5552 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5556 cur_object
= object
;
5561 /* Send this batch, using one or more write calls. */
5562 ptrdiff_t written
= 0;
5563 int outfd
= p
->outfd
;
5564 #ifdef DATAGRAM_SOCKETS
5565 if (DATAGRAM_CHAN_P (outfd
))
5567 rv
= sendto (outfd
, cur_buf
, cur_len
,
5568 0, datagram_address
[outfd
].sa
,
5569 datagram_address
[outfd
].len
);
5572 else if (errno
== EMSGSIZE
)
5573 report_file_error ("Sending datagram", proc
);
5579 if (p
->gnutls_p
&& p
->gnutls_state
)
5580 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5583 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5584 rv
= (written
? 0 : -1);
5585 #ifdef ADAPTIVE_READ_BUFFERING
5586 if (p
->read_output_delay
> 0
5587 && p
->adaptive_read_buffering
== 1)
5589 p
->read_output_delay
= 0;
5590 process_output_delay_count
--;
5591 p
->read_output_skip
= 0;
5600 || errno
== EWOULDBLOCK
5603 /* Buffer is full. Wait, accepting input;
5604 that may allow the program
5605 to finish doing output and read more. */
5607 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5608 /* A gross hack to work around a bug in FreeBSD.
5609 In the following sequence, read(2) returns
5613 write(2) 954 bytes, get EAGAIN
5614 read(2) 1024 bytes in process_read_output
5615 read(2) 11 bytes in process_read_output
5617 That is, read(2) returns more bytes than have
5618 ever been written successfully. The 1033 bytes
5619 read are the 1022 bytes written successfully
5620 after processing (for example with CRs added if
5621 the terminal is set up that way which it is
5622 here). The same bytes will be seen again in a
5623 later read(2), without the CRs. */
5625 if (errno
== EAGAIN
)
5628 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5630 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5632 /* Put what we should have written in wait_queue. */
5633 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5634 wait_reading_process_output (0, 20 * 1000 * 1000,
5635 0, 0, Qnil
, NULL
, 0);
5636 /* Reread queue, to see what is left. */
5639 else if (errno
== EPIPE
)
5641 p
->raw_status_new
= 0;
5642 pset_status (p
, list2 (Qexit
, make_number (256)));
5643 p
->tick
= ++process_tick
;
5644 deactivate_process (proc
);
5645 error ("process %s no longer connected to pipe; closed it",
5649 /* This is a real error. */
5650 report_file_error ("Writing to process", proc
);
5656 while (!NILP (p
->write_queue
));
5659 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5661 doc
: /* Send current contents of region as input to PROCESS.
5662 PROCESS may be a process, a buffer, the name of a process or buffer, or
5663 nil, indicating the current buffer's process.
5664 Called from program, takes three arguments, PROCESS, START and END.
5665 If the region is more than 500 characters long,
5666 it is sent in several bunches. This may happen even for shorter regions.
5667 Output from processes can arrive in between bunches. */)
5668 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5670 Lisp_Object proc
= get_process (process
);
5671 ptrdiff_t start_byte
, end_byte
;
5673 validate_region (&start
, &end
);
5675 start_byte
= CHAR_TO_BYTE (XINT (start
));
5676 end_byte
= CHAR_TO_BYTE (XINT (end
));
5678 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5679 move_gap_both (XINT (start
), start_byte
);
5681 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5682 end_byte
- start_byte
, Fcurrent_buffer ());
5687 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5689 doc
: /* Send PROCESS the contents of STRING as input.
5690 PROCESS may be a process, a buffer, the name of a process or buffer, or
5691 nil, indicating the current buffer's process.
5692 If STRING is more than 500 characters long,
5693 it is sent in several bunches. This may happen even for shorter strings.
5694 Output from processes can arrive in between bunches. */)
5695 (Lisp_Object process
, Lisp_Object string
)
5698 CHECK_STRING (string
);
5699 proc
= get_process (process
);
5700 send_process (proc
, SSDATA (string
),
5701 SBYTES (string
), string
);
5705 /* Return the foreground process group for the tty/pty that
5706 the process P uses. */
5708 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5713 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5716 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5717 master side. Try the slave side. */
5718 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5722 ioctl (fd
, TIOCGPGRP
, &gid
);
5726 #endif /* defined (TIOCGPGRP ) */
5731 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5732 Sprocess_running_child_p
, 0, 1, 0,
5733 doc
: /* Return non-nil if PROCESS has given the terminal to a
5734 child. If the operating system does not make it possible to find out,
5735 return t. If we can find out, return the numeric ID of the foreground
5737 (Lisp_Object process
)
5739 /* Initialize in case ioctl doesn't exist or gives an error,
5740 in a way that will cause returning t. */
5743 struct Lisp_Process
*p
;
5745 proc
= get_process (process
);
5746 p
= XPROCESS (proc
);
5748 if (!EQ (p
->type
, Qreal
))
5749 error ("Process %s is not a subprocess",
5752 error ("Process %s is not active",
5755 gid
= emacs_get_tty_pgrp (p
);
5760 return make_number (gid
);
5764 /* Send a signal number SIGNO to PROCESS.
5765 If CURRENT_GROUP is t, that means send to the process group
5766 that currently owns the terminal being used to communicate with PROCESS.
5767 This is used for various commands in shell mode.
5768 If CURRENT_GROUP is lambda, that means send to the process group
5769 that currently owns the terminal, but only if it is NOT the shell itself.
5771 If NOMSG is false, insert signal-announcements into process's buffers
5774 If we can, we try to signal PROCESS by sending control characters
5775 down the pty. This allows us to signal inferiors who have changed
5776 their uid, for which kill would return an EPERM error. */
5779 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5783 struct Lisp_Process
*p
;
5787 proc
= get_process (process
);
5788 p
= XPROCESS (proc
);
5790 if (!EQ (p
->type
, Qreal
))
5791 error ("Process %s is not a subprocess",
5794 error ("Process %s is not active",
5798 current_group
= Qnil
;
5800 /* If we are using pgrps, get a pgrp number and make it negative. */
5801 if (NILP (current_group
))
5802 /* Send the signal to the shell's process group. */
5806 #ifdef SIGNALS_VIA_CHARACTERS
5807 /* If possible, send signals to the entire pgrp
5808 by sending an input character to it. */
5811 cc_t
*sig_char
= NULL
;
5813 tcgetattr (p
->infd
, &t
);
5818 sig_char
= &t
.c_cc
[VINTR
];
5822 sig_char
= &t
.c_cc
[VQUIT
];
5826 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5827 sig_char
= &t
.c_cc
[VSWTCH
];
5829 sig_char
= &t
.c_cc
[VSUSP
];
5834 if (sig_char
&& *sig_char
!= CDISABLE
)
5836 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5839 /* If we can't send the signal with a character,
5840 fall through and send it another way. */
5842 /* The code above may fall through if it can't
5843 handle the signal. */
5844 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5847 /* Get the current pgrp using the tty itself, if we have that.
5848 Otherwise, use the pty to get the pgrp.
5849 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5850 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5851 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5852 His patch indicates that if TIOCGPGRP returns an error, then
5853 we should just assume that p->pid is also the process group id. */
5855 gid
= emacs_get_tty_pgrp (p
);
5858 /* If we can't get the information, assume
5859 the shell owns the tty. */
5862 /* It is not clear whether anything really can set GID to -1.
5863 Perhaps on some system one of those ioctls can or could do so.
5864 Or perhaps this is vestigial. */
5867 #else /* ! defined (TIOCGPGRP) */
5868 /* Can't select pgrps on this system, so we know that
5869 the child itself heads the pgrp. */
5871 #endif /* ! defined (TIOCGPGRP) */
5873 /* If current_group is lambda, and the shell owns the terminal,
5874 don't send any signal. */
5875 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5880 if (signo
== SIGCONT
)
5882 p
->raw_status_new
= 0;
5883 pset_status (p
, Qrun
);
5884 p
->tick
= ++process_tick
;
5887 status_notify (NULL
, NULL
);
5888 redisplay_preserve_echo_area (13);
5894 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5895 We don't know whether the bug is fixed in later HP-UX versions. */
5896 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
5900 /* If we don't have process groups, send the signal to the immediate
5901 subprocess. That isn't really right, but it's better than any
5902 obvious alternative. */
5903 pid_t pid
= no_pgrp
? gid
: - gid
;
5905 /* Do not kill an already-reaped process, as that could kill an
5906 innocent bystander that happens to have the same process ID. */
5908 block_child_signal (&oldset
);
5911 unblock_child_signal (&oldset
);
5914 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5915 doc
: /* Interrupt process PROCESS.
5916 PROCESS may be a process, a buffer, or the name of a process or buffer.
5917 No arg or nil means current buffer's process.
5918 Second arg CURRENT-GROUP non-nil means send signal to
5919 the current process-group of the process's controlling terminal
5920 rather than to the process's own process group.
5921 If the process is a shell, this means interrupt current subjob
5922 rather than the shell.
5924 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5925 don't send the signal. */)
5926 (Lisp_Object process
, Lisp_Object current_group
)
5928 process_send_signal (process
, SIGINT
, current_group
, 0);
5932 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5933 doc
: /* Kill process PROCESS. May be process or name of one.
5934 See function `interrupt-process' for more details on usage. */)
5935 (Lisp_Object process
, Lisp_Object current_group
)
5937 process_send_signal (process
, SIGKILL
, current_group
, 0);
5941 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5942 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5943 See function `interrupt-process' for more details on usage. */)
5944 (Lisp_Object process
, Lisp_Object current_group
)
5946 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5950 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5951 doc
: /* Stop process PROCESS. May be process or name of one.
5952 See function `interrupt-process' for more details on usage.
5953 If PROCESS is a network or serial process, inhibit handling of incoming
5955 (Lisp_Object process
, Lisp_Object current_group
)
5957 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5959 struct Lisp_Process
*p
;
5961 p
= XPROCESS (process
);
5962 if (NILP (p
->command
)
5965 FD_CLR (p
->infd
, &input_wait_mask
);
5966 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
5968 pset_command (p
, Qt
);
5972 error ("No SIGTSTP support");
5974 process_send_signal (process
, SIGTSTP
, current_group
, 0);
5979 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
5980 doc
: /* Continue process PROCESS. May be process or name of one.
5981 See function `interrupt-process' for more details on usage.
5982 If PROCESS is a network or serial process, resume handling of incoming
5984 (Lisp_Object process
, Lisp_Object current_group
)
5986 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5988 struct Lisp_Process
*p
;
5990 p
= XPROCESS (process
);
5991 if (EQ (p
->command
, Qt
)
5993 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
5995 FD_SET (p
->infd
, &input_wait_mask
);
5996 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5998 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
5999 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6000 #else /* not WINDOWSNT */
6001 tcflush (p
->infd
, TCIFLUSH
);
6002 #endif /* not WINDOWSNT */
6004 pset_command (p
, Qnil
);
6008 process_send_signal (process
, SIGCONT
, current_group
, 0);
6010 error ("No SIGCONT support");
6015 /* Return the integer value of the signal whose abbreviation is ABBR,
6016 or a negative number if there is no such signal. */
6018 abbr_to_signal (char const *name
)
6021 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
6023 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6026 for (i
= 0; i
< sizeof sigbuf
; i
++)
6028 sigbuf
[i
] = c_toupper (name
[i
]);
6030 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
6036 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6037 2, 2, "sProcess (name or number): \nnSignal code: ",
6038 doc
: /* Send PROCESS the signal with code SIGCODE.
6039 PROCESS may also be a number specifying the process id of the
6040 process to signal; in this case, the process need not be a child of
6042 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6043 (Lisp_Object process
, Lisp_Object sigcode
)
6048 if (STRINGP (process
))
6050 Lisp_Object tem
= Fget_process (process
);
6053 Lisp_Object process_number
6054 = string_to_number (SSDATA (process
), 10, 1);
6055 if (INTEGERP (process_number
) || FLOATP (process_number
))
6056 tem
= process_number
;
6060 else if (!NUMBERP (process
))
6061 process
= get_process (process
);
6066 if (NUMBERP (process
))
6067 CONS_TO_INTEGER (process
, pid_t
, pid
);
6070 CHECK_PROCESS (process
);
6071 pid
= XPROCESS (process
)->pid
;
6073 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6076 if (INTEGERP (sigcode
))
6078 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6079 signo
= XINT (sigcode
);
6085 CHECK_SYMBOL (sigcode
);
6086 name
= SSDATA (SYMBOL_NAME (sigcode
));
6088 signo
= abbr_to_signal (name
);
6090 error ("Undefined signal name %s", name
);
6093 return make_number (kill (pid
, signo
));
6096 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6097 doc
: /* Make PROCESS see end-of-file in its input.
6098 EOF comes after any text already sent to it.
6099 PROCESS may be a process, a buffer, the name of a process or buffer, or
6100 nil, indicating the current buffer's process.
6101 If PROCESS is a network connection, or is a process communicating
6102 through a pipe (as opposed to a pty), then you cannot send any more
6103 text to PROCESS after you call this function.
6104 If PROCESS is a serial process, wait until all output written to the
6105 process has been transmitted to the serial port. */)
6106 (Lisp_Object process
)
6109 struct coding_system
*coding
= NULL
;
6112 if (DATAGRAM_CONN_P (process
))
6115 proc
= get_process (process
);
6116 outfd
= XPROCESS (proc
)->outfd
;
6118 coding
= proc_encode_coding_system
[outfd
];
6120 /* Make sure the process is really alive. */
6121 if (XPROCESS (proc
)->raw_status_new
)
6122 update_status (XPROCESS (proc
));
6123 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6124 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6126 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6128 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6129 send_process (proc
, "", 0, Qnil
);
6132 if (XPROCESS (proc
)->pty_flag
)
6133 send_process (proc
, "\004", 1, Qnil
);
6134 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6137 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6138 report_file_error ("Failed tcdrain", Qnil
);
6139 #endif /* not WINDOWSNT */
6140 /* Do nothing on Windows because writes are blocking. */
6144 struct Lisp_Process
*p
= XPROCESS (proc
);
6145 int old_outfd
= p
->outfd
;
6148 #ifdef HAVE_SHUTDOWN
6149 /* If this is a network connection, or socketpair is used
6150 for communication with the subprocess, call shutdown to cause EOF.
6151 (In some old system, shutdown to socketpair doesn't work.
6152 Then we just can't win.) */
6154 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6155 shutdown (old_outfd
, 1);
6157 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6158 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6160 report_file_error ("Opening null device", Qnil
);
6161 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6162 p
->outfd
= new_outfd
;
6164 if (!proc_encode_coding_system
[new_outfd
])
6165 proc_encode_coding_system
[new_outfd
]
6166 = xmalloc (sizeof (struct coding_system
));
6169 *proc_encode_coding_system
[new_outfd
]
6170 = *proc_encode_coding_system
[old_outfd
];
6171 memset (proc_encode_coding_system
[old_outfd
], 0,
6172 sizeof (struct coding_system
));
6175 setup_coding_system (p
->encode_coding_system
,
6176 proc_encode_coding_system
[new_outfd
]);
6181 /* The main Emacs thread records child processes in three places:
6183 - Vprocess_alist, for asynchronous subprocesses, which are child
6184 processes visible to Lisp.
6186 - deleted_pid_list, for child processes invisible to Lisp,
6187 typically because of delete-process. These are recorded so that
6188 the processes can be reaped when they exit, so that the operating
6189 system's process table is not cluttered by zombies.
6191 - the local variable PID in Fcall_process, call_process_cleanup and
6192 call_process_kill, for synchronous subprocesses.
6193 record_unwind_protect is used to make sure this process is not
6194 forgotten: if the user interrupts call-process and the child
6195 process refuses to exit immediately even with two C-g's,
6196 call_process_kill adds PID's contents to deleted_pid_list before
6199 The main Emacs thread invokes waitpid only on child processes that
6200 it creates and that have not been reaped. This avoid races on
6201 platforms such as GTK, where other threads create their own
6202 subprocesses which the main thread should not reap. For example,
6203 if the main thread attempted to reap an already-reaped child, it
6204 might inadvertently reap a GTK-created process that happened to
6205 have the same process ID. */
6207 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6208 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6209 keep track of its own children. GNUstep is similar. */
6211 static void dummy_handler (int sig
) {}
6212 static signal_handler_t
volatile lib_child_handler
;
6214 /* Handle a SIGCHLD signal by looking for known child processes of
6215 Emacs whose status have changed. For each one found, record its
6218 All we do is change the status; we do not run sentinels or print
6219 notifications. That is saved for the next time keyboard input is
6220 done, in order to avoid timing errors.
6222 ** WARNING: this can be called during garbage collection.
6223 Therefore, it must not be fooled by the presence of mark bits in
6226 ** USG WARNING: Although it is not obvious from the documentation
6227 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6228 signal() before executing at least one wait(), otherwise the
6229 handler will be called again, resulting in an infinite loop. The
6230 relevant portion of the documentation reads "SIGCLD signals will be
6231 queued and the signal-catching function will be continually
6232 reentered until the queue is empty". Invoking signal() causes the
6233 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6236 ** Malloc WARNING: This should never call malloc either directly or
6237 indirectly; if it does, that is a bug. */
6240 handle_child_signal (int sig
)
6242 Lisp_Object tail
, proc
;
6244 /* Find the process that signaled us, and record its status. */
6246 /* The process can have been deleted by Fdelete_process, or have
6247 been started asynchronously by Fcall_process. */
6248 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6250 bool all_pids_are_fixnums
6251 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6252 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6253 Lisp_Object head
= XCAR (tail
);
6258 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6261 if (INTEGERP (xpid
))
6262 deleted_pid
= XINT (xpid
);
6264 deleted_pid
= XFLOAT_DATA (xpid
);
6265 if (child_status_changed (deleted_pid
, 0, 0))
6267 if (STRINGP (XCDR (head
)))
6268 unlink (SSDATA (XCDR (head
)));
6269 XSETCAR (tail
, Qnil
);
6274 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6275 FOR_EACH_PROCESS (tail
, proc
)
6277 struct Lisp_Process
*p
= XPROCESS (proc
);
6281 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6283 /* Change the status of the process that was found. */
6284 p
->tick
= ++process_tick
;
6285 p
->raw_status
= status
;
6286 p
->raw_status_new
= 1;
6288 /* If process has terminated, stop waiting for its output. */
6289 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6291 bool clear_desc_flag
= 0;
6294 clear_desc_flag
= 1;
6296 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6297 if (clear_desc_flag
)
6299 FD_CLR (p
->infd
, &input_wait_mask
);
6300 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6306 lib_child_handler (sig
);
6307 #ifdef NS_IMPL_GNUSTEP
6308 /* NSTask in GNUstep sets its child handler each time it is called.
6309 So we must re-set ours. */
6310 catch_child_signal ();
6315 deliver_child_signal (int sig
)
6317 deliver_process_signal (sig
, handle_child_signal
);
6322 exec_sentinel_error_handler (Lisp_Object error_val
)
6324 cmd_error_internal (error_val
, "error in process sentinel: ");
6326 update_echo_area ();
6327 Fsleep_for (make_number (2), Qnil
);
6332 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6334 Lisp_Object sentinel
, odeactivate
;
6335 struct Lisp_Process
*p
= XPROCESS (proc
);
6336 ptrdiff_t count
= SPECPDL_INDEX ();
6337 bool outer_running_asynch_code
= running_asynch_code
;
6338 int waiting
= waiting_for_user_input_p
;
6340 if (inhibit_sentinels
)
6343 /* No need to gcpro these, because all we do with them later
6344 is test them for EQness, and none of them should be a string. */
6345 odeactivate
= Vdeactivate_mark
;
6347 Lisp_Object obuffer
, okeymap
;
6348 XSETBUFFER (obuffer
, current_buffer
);
6349 okeymap
= BVAR (current_buffer
, keymap
);
6352 /* There's no good reason to let sentinels change the current
6353 buffer, and many callers of accept-process-output, sit-for, and
6354 friends don't expect current-buffer to be changed from under them. */
6355 record_unwind_current_buffer ();
6357 sentinel
= p
->sentinel
;
6359 /* Inhibit quit so that random quits don't screw up a running filter. */
6360 specbind (Qinhibit_quit
, Qt
);
6361 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6363 /* In case we get recursively called,
6364 and we already saved the match data nonrecursively,
6365 save the same match data in safely recursive fashion. */
6366 if (outer_running_asynch_code
)
6369 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6370 restore_search_regs ();
6371 record_unwind_save_match_data ();
6372 Fset_match_data (tem
, Qt
);
6375 /* For speed, if a search happens within this code,
6376 save the match data in a special nonrecursive fashion. */
6377 running_asynch_code
= 1;
6379 internal_condition_case_1 (read_process_output_call
,
6380 list3 (sentinel
, proc
, reason
),
6381 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6382 exec_sentinel_error_handler
);
6384 /* If we saved the match data nonrecursively, restore it now. */
6385 restore_search_regs ();
6386 running_asynch_code
= outer_running_asynch_code
;
6388 Vdeactivate_mark
= odeactivate
;
6390 /* Restore waiting_for_user_input_p as it was
6391 when we were called, in case the filter clobbered it. */
6392 waiting_for_user_input_p
= waiting
;
6395 if (! EQ (Fcurrent_buffer (), obuffer
)
6396 || ! EQ (current_buffer
->keymap
, okeymap
))
6398 /* But do it only if the caller is actually going to read events.
6399 Otherwise there's no need to make him wake up, and it could
6400 cause trouble (for example it would make sit_for return). */
6401 if (waiting_for_user_input_p
== -1)
6402 record_asynch_buffer_change ();
6404 unbind_to (count
, Qnil
);
6407 /* Report all recent events of a change in process status
6408 (either run the sentinel or output a message).
6409 This is usually done while Emacs is waiting for keyboard input
6410 but can be done at other times.
6412 Return positive if any input was received from WAIT_PROC (or from
6413 any process if WAIT_PROC is null), zero if input was attempted but
6414 none received, and negative if we didn't even try. */
6417 status_notify (struct Lisp_Process
*deleting_process
,
6418 struct Lisp_Process
*wait_proc
)
6421 Lisp_Object tail
, msg
;
6422 struct gcpro gcpro1
, gcpro2
;
6423 int got_some_input
= -1;
6427 /* We need to gcpro tail; if read_process_output calls a filter
6428 which deletes a process and removes the cons to which tail points
6429 from Vprocess_alist, and then causes a GC, tail is an unprotected
6433 /* Set this now, so that if new processes are created by sentinels
6434 that we run, we get called again to handle their status changes. */
6435 update_tick
= process_tick
;
6437 FOR_EACH_PROCESS (tail
, proc
)
6440 register struct Lisp_Process
*p
= XPROCESS (proc
);
6442 if (p
->tick
!= p
->update_tick
)
6444 p
->update_tick
= p
->tick
;
6446 /* If process is still active, read any output that remains. */
6447 while (! EQ (p
->filter
, Qt
)
6448 && ! EQ (p
->status
, Qconnect
)
6449 && ! EQ (p
->status
, Qlisten
)
6450 /* Network or serial process not stopped: */
6451 && ! EQ (p
->command
, Qt
)
6453 && p
!= deleting_process
)
6455 int nread
= read_process_output (proc
, p
->infd
);
6456 if (got_some_input
< nread
)
6457 got_some_input
= nread
;
6462 /* Get the text to use for the message. */
6463 if (p
->raw_status_new
)
6465 msg
= status_message (p
);
6467 /* If process is terminated, deactivate it or delete it. */
6469 if (CONSP (p
->status
))
6470 symbol
= XCAR (p
->status
);
6472 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6473 || EQ (symbol
, Qclosed
))
6475 if (delete_exited_processes
)
6476 remove_process (proc
);
6478 deactivate_process (proc
);
6481 /* The actions above may have further incremented p->tick.
6482 So set p->update_tick again so that an error in the sentinel will
6483 not cause this code to be run again. */
6484 p
->update_tick
= p
->tick
;
6485 /* Now output the message suitably. */
6486 exec_sentinel (proc
, msg
);
6490 update_mode_lines
= 24; /* In case buffers use %s in mode-line-format. */
6492 return got_some_input
;
6495 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6496 Sinternal_default_process_sentinel
, 2, 2, 0,
6497 doc
: /* Function used as default sentinel for processes.
6498 This inserts a status message into the process's buffer, if there is one. */)
6499 (Lisp_Object proc
, Lisp_Object msg
)
6501 Lisp_Object buffer
, symbol
;
6502 struct Lisp_Process
*p
;
6503 CHECK_PROCESS (proc
);
6504 p
= XPROCESS (proc
);
6508 symbol
= XCAR (symbol
);
6510 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6513 struct buffer
*old
= current_buffer
;
6514 ptrdiff_t opoint
, opoint_byte
;
6515 ptrdiff_t before
, before_byte
;
6517 /* Avoid error if buffer is deleted
6518 (probably that's why the process is dead, too). */
6519 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6521 Fset_buffer (buffer
);
6523 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6524 msg
= (code_convert_string_norecord
6525 (msg
, Vlocale_coding_system
, 1));
6528 opoint_byte
= PT_BYTE
;
6529 /* Insert new output into buffer
6530 at the current end-of-output marker,
6531 thus preserving logical ordering of input and output. */
6532 if (XMARKER (p
->mark
)->buffer
)
6533 Fgoto_char (p
->mark
);
6535 SET_PT_BOTH (ZV
, ZV_BYTE
);
6538 before_byte
= PT_BYTE
;
6540 tem
= BVAR (current_buffer
, read_only
);
6541 bset_read_only (current_buffer
, Qnil
);
6542 insert_string ("\nProcess ");
6543 { /* FIXME: temporary kludge. */
6544 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6545 insert_string (" ");
6547 bset_read_only (current_buffer
, tem
);
6548 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6550 if (opoint
>= before
)
6551 SET_PT_BOTH (opoint
+ (PT
- before
),
6552 opoint_byte
+ (PT_BYTE
- before_byte
));
6554 SET_PT_BOTH (opoint
, opoint_byte
);
6556 set_buffer_internal (old
);
6562 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6563 Sset_process_coding_system
, 1, 3, 0,
6564 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6565 DECODING will be used to decode subprocess output and ENCODING to
6566 encode subprocess input. */)
6567 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6569 register struct Lisp_Process
*p
;
6571 CHECK_PROCESS (process
);
6572 p
= XPROCESS (process
);
6574 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6576 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6577 Fcheck_coding_system (decoding
);
6578 Fcheck_coding_system (encoding
);
6579 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6580 pset_decode_coding_system (p
, decoding
);
6581 pset_encode_coding_system (p
, encoding
);
6582 setup_process_coding_systems (process
);
6587 DEFUN ("process-coding-system",
6588 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6589 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6590 (register Lisp_Object process
)
6592 CHECK_PROCESS (process
);
6593 return Fcons (XPROCESS (process
)->decode_coding_system
,
6594 XPROCESS (process
)->encode_coding_system
);
6597 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6598 Sset_process_filter_multibyte
, 2, 2, 0,
6599 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6600 If FLAG is non-nil, the filter is given multibyte strings.
6601 If FLAG is nil, the filter is given unibyte strings. In this case,
6602 all character code conversion except for end-of-line conversion is
6604 (Lisp_Object process
, Lisp_Object flag
)
6606 register struct Lisp_Process
*p
;
6608 CHECK_PROCESS (process
);
6609 p
= XPROCESS (process
);
6611 pset_decode_coding_system
6612 (p
, raw_text_coding_system (p
->decode_coding_system
));
6613 setup_process_coding_systems (process
);
6618 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6619 Sprocess_filter_multibyte_p
, 1, 1, 0,
6620 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6621 (Lisp_Object process
)
6623 register struct Lisp_Process
*p
;
6624 struct coding_system
*coding
;
6626 CHECK_PROCESS (process
);
6627 p
= XPROCESS (process
);
6630 coding
= proc_decode_coding_system
[p
->infd
];
6631 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6640 add_gpm_wait_descriptor (int desc
)
6642 add_keyboard_wait_descriptor (desc
);
6646 delete_gpm_wait_descriptor (int desc
)
6648 delete_keyboard_wait_descriptor (desc
);
6653 # ifdef USABLE_SIGIO
6655 /* Return true if *MASK has a bit set
6656 that corresponds to one of the keyboard input descriptors. */
6659 keyboard_bit_set (fd_set
*mask
)
6663 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6664 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6665 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6672 #else /* not subprocesses */
6674 /* Defined in msdos.c. */
6675 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
6676 struct timespec
*, void *);
6678 /* Implementation of wait_reading_process_output, assuming that there
6679 are no subprocesses. Used only by the MS-DOS build.
6681 Wait for timeout to elapse and/or keyboard input to be available.
6685 If negative, gobble data immediately available but don't wait for any.
6688 an additional duration to wait, measured in nanoseconds
6689 If TIME_LIMIT is zero, then:
6690 If NSECS == 0, there is no limit.
6691 If NSECS > 0, the timeout consists of NSECS only.
6692 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6695 0 to ignore keyboard input, or
6696 1 to return when input is available, or
6697 -1 means caller will actually read the input, so don't throw to
6700 see full version for other parameters. We know that wait_proc will
6701 always be NULL, since `subprocesses' isn't defined.
6703 DO_DISPLAY means redisplay should be done to show subprocess
6704 output that arrives.
6706 Return positive if we received input from WAIT_PROC (or from any
6707 process if WAIT_PROC is null), zero if we attempted to receive
6708 input but got none, and negative if we didn't even try. */
6711 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6713 Lisp_Object wait_for_cell
,
6714 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6717 struct timespec end_time
, timeout
;
6724 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6725 time_limit
= TYPE_MAXIMUM (time_t);
6727 /* What does time_limit really mean? */
6728 if (time_limit
|| nsecs
> 0)
6730 timeout
= make_timespec (time_limit
, nsecs
);
6731 end_time
= timespec_add (current_timespec (), timeout
);
6734 /* Turn off periodic alarms (in case they are in use)
6735 and then turn off any other atimers,
6736 because the select emulator uses alarms. */
6738 turn_on_atimers (0);
6742 bool timeout_reduced_for_timers
= false;
6743 fd_set waitchannels
;
6746 /* If calling from keyboard input, do not quit
6747 since we want to return C-g as an input character.
6748 Otherwise, do pending quit if requested. */
6752 /* Exit now if the cell we're waiting for became non-nil. */
6753 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6756 /* Compute time from now till when time limit is up. */
6757 /* Exit if already run out. */
6760 /* A negative timeout means
6761 gobble output available now
6762 but don't wait at all. */
6764 timeout
= make_timespec (0, 0);
6766 else if (time_limit
|| nsecs
> 0)
6768 struct timespec now
= current_timespec ();
6769 if (timespec_cmp (end_time
, now
) <= 0)
6771 timeout
= timespec_sub (end_time
, now
);
6775 timeout
= make_timespec (100000, 0);
6778 /* If our caller will not immediately handle keyboard events,
6779 run timer events directly.
6780 (Callers that will immediately read keyboard events
6781 call timer_delay on their own.) */
6782 if (NILP (wait_for_cell
))
6784 struct timespec timer_delay
;
6788 unsigned old_timers_run
= timers_run
;
6789 timer_delay
= timer_check ();
6790 if (timers_run
!= old_timers_run
&& do_display
)
6791 /* We must retry, since a timer may have requeued itself
6792 and that could alter the time delay. */
6793 redisplay_preserve_echo_area (14);
6797 while (!detect_input_pending ());
6799 /* If there is unread keyboard input, also return. */
6801 && requeued_events_pending_p ())
6804 if (timespec_valid_p (timer_delay
) && nsecs
>= 0)
6806 if (timespec_cmp (timer_delay
, timeout
) < 0)
6808 timeout
= timer_delay
;
6809 timeout_reduced_for_timers
= true;
6814 /* Cause C-g and alarm signals to take immediate action,
6815 and cause input available signals to zero out timeout. */
6817 set_waiting_for_input (&timeout
);
6819 /* If a frame has been newly mapped and needs updating,
6820 reprocess its display stuff. */
6821 if (frame_garbaged
&& do_display
)
6823 clear_waiting_for_input ();
6824 redisplay_preserve_echo_area (15);
6826 set_waiting_for_input (&timeout
);
6829 /* Wait till there is something to do. */
6830 FD_ZERO (&waitchannels
);
6831 if (read_kbd
&& detect_input_pending ())
6835 if (read_kbd
|| !NILP (wait_for_cell
))
6836 FD_SET (0, &waitchannels
);
6837 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6842 /* Make C-g and alarm signals set flags again. */
6843 clear_waiting_for_input ();
6845 /* If we woke up due to SIGWINCH, actually change size now. */
6846 do_pending_window_change (0);
6848 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6849 /* We waited the full specified time, so return now. */
6854 /* If the system call was interrupted, then go around the
6856 if (xerrno
== EINTR
)
6857 FD_ZERO (&waitchannels
);
6859 report_file_errno ("Failed select", Qnil
, xerrno
);
6862 /* Check for keyboard input. */
6865 && detect_input_pending_run_timers (do_display
))
6867 swallow_events (do_display
);
6868 if (detect_input_pending_run_timers (do_display
))
6872 /* If there is unread keyboard input, also return. */
6874 && requeued_events_pending_p ())
6877 /* If wait_for_cell. check for keyboard input
6878 but don't run any timers.
6879 ??? (It seems wrong to me to check for keyboard
6880 input at all when wait_for_cell, but the code
6881 has been this way since July 1994.
6882 Try changing this after version 19.31.) */
6883 if (! NILP (wait_for_cell
)
6884 && detect_input_pending ())
6886 swallow_events (do_display
);
6887 if (detect_input_pending ())
6891 /* Exit now if the cell we're waiting for became non-nil. */
6892 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6901 #endif /* not subprocesses */
6903 /* The following functions are needed even if async subprocesses are
6904 not supported. Some of them are no-op stubs in that case. */
6908 /* Add FD, which is a descriptor returned by timerfd_create,
6909 to the set of non-keyboard input descriptors. */
6912 add_timer_wait_descriptor (int fd
)
6914 FD_SET (fd
, &input_wait_mask
);
6915 FD_SET (fd
, &non_keyboard_wait_mask
);
6916 FD_SET (fd
, &non_process_wait_mask
);
6917 fd_callback_info
[fd
].func
= timerfd_callback
;
6918 fd_callback_info
[fd
].data
= NULL
;
6919 fd_callback_info
[fd
].condition
|= FOR_READ
;
6920 if (fd
> max_input_desc
)
6921 max_input_desc
= fd
;
6924 #endif /* HAVE_TIMERFD */
6926 /* Add DESC to the set of keyboard input descriptors. */
6929 add_keyboard_wait_descriptor (int desc
)
6931 #ifdef subprocesses /* Actually means "not MSDOS". */
6932 FD_SET (desc
, &input_wait_mask
);
6933 FD_SET (desc
, &non_process_wait_mask
);
6934 if (desc
> max_input_desc
)
6935 max_input_desc
= desc
;
6939 /* From now on, do not expect DESC to give keyboard input. */
6942 delete_keyboard_wait_descriptor (int desc
)
6945 FD_CLR (desc
, &input_wait_mask
);
6946 FD_CLR (desc
, &non_process_wait_mask
);
6947 delete_input_desc (desc
);
6951 /* Setup coding systems of PROCESS. */
6954 setup_process_coding_systems (Lisp_Object process
)
6957 struct Lisp_Process
*p
= XPROCESS (process
);
6959 int outch
= p
->outfd
;
6960 Lisp_Object coding_system
;
6962 if (inch
< 0 || outch
< 0)
6965 if (!proc_decode_coding_system
[inch
])
6966 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6967 coding_system
= p
->decode_coding_system
;
6968 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6969 && BUFFERP (p
->buffer
))
6971 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6972 coding_system
= raw_text_coding_system (coding_system
);
6974 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6976 if (!proc_encode_coding_system
[outch
])
6977 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6978 setup_coding_system (p
->encode_coding_system
,
6979 proc_encode_coding_system
[outch
]);
6983 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6984 doc
: /* Return the (or a) process associated with BUFFER.
6985 BUFFER may be a buffer or the name of one. */)
6986 (register Lisp_Object buffer
)
6989 register Lisp_Object buf
, tail
, proc
;
6991 if (NILP (buffer
)) return Qnil
;
6992 buf
= Fget_buffer (buffer
);
6993 if (NILP (buf
)) return Qnil
;
6995 FOR_EACH_PROCESS (tail
, proc
)
6996 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6998 #endif /* subprocesses */
7002 DEFUN ("process-inherit-coding-system-flag",
7003 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7005 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7006 If this flag is t, `buffer-file-coding-system' of the buffer
7007 associated with PROCESS will inherit the coding system used to decode
7008 the process output. */)
7009 (register Lisp_Object process
)
7012 CHECK_PROCESS (process
);
7013 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7015 /* Ignore the argument and return the value of
7016 inherit-process-coding-system. */
7017 return inherit_process_coding_system
? Qt
: Qnil
;
7021 /* Kill all processes associated with `buffer'.
7022 If `buffer' is nil, kill all processes. */
7025 kill_buffer_processes (Lisp_Object buffer
)
7028 Lisp_Object tail
, proc
;
7030 FOR_EACH_PROCESS (tail
, proc
)
7031 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
7033 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
7034 Fdelete_process (proc
);
7035 else if (XPROCESS (proc
)->infd
>= 0)
7036 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7038 #else /* subprocesses */
7039 /* Since we have no subprocesses, this does nothing. */
7040 #endif /* subprocesses */
7043 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7044 Swaiting_for_user_input_p
, 0, 0, 0,
7045 doc
: /* Return non-nil if Emacs is waiting for input from the user.
7046 This is intended for use by asynchronous process output filters and sentinels. */)
7050 return (waiting_for_user_input_p
? Qt
: Qnil
);
7056 /* Stop reading input from keyboard sources. */
7059 hold_keyboard_input (void)
7064 /* Resume reading input from keyboard sources. */
7067 unhold_keyboard_input (void)
7072 /* Return true if keyboard input is on hold, zero otherwise. */
7075 kbd_on_hold_p (void)
7077 return kbd_is_on_hold
;
7081 /* Enumeration of and access to system processes a-la ps(1). */
7083 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7085 doc
: /* Return a list of numerical process IDs of all running processes.
7086 If this functionality is unsupported, return nil.
7088 See `process-attributes' for getting attributes of a process given its ID. */)
7091 return list_system_processes ();
7094 DEFUN ("process-attributes", Fprocess_attributes
,
7095 Sprocess_attributes
, 1, 1, 0,
7096 doc
: /* Return attributes of the process given by its PID, a number.
7098 Value is an alist where each element is a cons cell of the form
7102 If this functionality is unsupported, the value is nil.
7104 See `list-system-processes' for getting a list of all process IDs.
7106 The KEYs of the attributes that this function may return are listed
7107 below, together with the type of the associated VALUE (in parentheses).
7108 Not all platforms support all of these attributes; unsupported
7109 attributes will not appear in the returned alist.
7110 Unless explicitly indicated otherwise, numbers can have either
7111 integer or floating point values.
7113 euid -- Effective user User ID of the process (number)
7114 user -- User name corresponding to euid (string)
7115 egid -- Effective user Group ID of the process (number)
7116 group -- Group name corresponding to egid (string)
7117 comm -- Command name (executable name only) (string)
7118 state -- Process state code, such as "S", "R", or "T" (string)
7119 ppid -- Parent process ID (number)
7120 pgrp -- Process group ID (number)
7121 sess -- Session ID, i.e. process ID of session leader (number)
7122 ttname -- Controlling tty name (string)
7123 tpgid -- ID of foreground process group on the process's tty (number)
7124 minflt -- number of minor page faults (number)
7125 majflt -- number of major page faults (number)
7126 cminflt -- cumulative number of minor page faults (number)
7127 cmajflt -- cumulative number of major page faults (number)
7128 utime -- user time used by the process, in (current-time) format,
7129 which is a list of integers (HIGH LOW USEC PSEC)
7130 stime -- system time used by the process (current-time)
7131 time -- sum of utime and stime (current-time)
7132 cutime -- user time used by the process and its children (current-time)
7133 cstime -- system time used by the process and its children (current-time)
7134 ctime -- sum of cutime and cstime (current-time)
7135 pri -- priority of the process (number)
7136 nice -- nice value of the process (number)
7137 thcount -- process thread count (number)
7138 start -- time the process started (current-time)
7139 vsize -- virtual memory size of the process in KB's (number)
7140 rss -- resident set size of the process in KB's (number)
7141 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7142 pcpu -- percents of CPU time used by the process (floating-point number)
7143 pmem -- percents of total physical memory used by process's resident set
7144 (floating-point number)
7145 args -- command line which invoked the process (string). */)
7148 return system_process_attributes (pid
);
7152 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7153 Invoke this after init_process_emacs, and after glib and/or GNUstep
7154 futz with the SIGCHLD handler, but before Emacs forks any children.
7155 This function's caller should block SIGCHLD. */
7158 catch_child_signal (void)
7160 struct sigaction action
, old_action
;
7162 emacs_sigaction_init (&action
, deliver_child_signal
);
7163 block_child_signal (&oldset
);
7164 sigaction (SIGCHLD
, &action
, &old_action
);
7165 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7166 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7168 if (old_action
.sa_handler
!= deliver_child_signal
)
7170 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7172 : old_action
.sa_handler
);
7173 unblock_child_signal (&oldset
);
7175 #endif /* subprocesses */
7178 /* This is not called "init_process" because that is the name of a
7179 Mach system call, so it would cause problems on Darwin systems. */
7181 init_process_emacs (void)
7186 inhibit_sentinels
= 0;
7189 if (! noninteractive
|| initialized
)
7192 #if defined HAVE_GLIB && !defined WINDOWSNT
7193 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7194 this should always fail, but is enough to initialize glib's
7195 private SIGCHLD handler, allowing catch_child_signal to copy
7196 it into lib_child_handler. */
7197 g_source_unref (g_child_watch_source_new (getpid ()));
7199 catch_child_signal ();
7202 FD_ZERO (&input_wait_mask
);
7203 FD_ZERO (&non_keyboard_wait_mask
);
7204 FD_ZERO (&non_process_wait_mask
);
7205 FD_ZERO (&write_mask
);
7206 max_process_desc
= max_input_desc
= -1;
7207 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7209 #ifdef NON_BLOCKING_CONNECT
7210 FD_ZERO (&connect_wait_mask
);
7211 num_pending_connects
= 0;
7214 #ifdef ADAPTIVE_READ_BUFFERING
7215 process_output_delay_count
= 0;
7216 process_output_skip
= 0;
7219 /* Don't do this, it caused infinite select loops. The display
7220 method should call add_keyboard_wait_descriptor on stdin if it
7223 FD_SET (0, &input_wait_mask
);
7226 Vprocess_alist
= Qnil
;
7227 deleted_pid_list
= Qnil
;
7228 for (i
= 0; i
< FD_SETSIZE
; i
++)
7230 chan_process
[i
] = Qnil
;
7231 proc_buffered_char
[i
] = -1;
7233 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7234 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7235 #ifdef DATAGRAM_SOCKETS
7236 memset (datagram_address
, 0, sizeof datagram_address
);
7240 Lisp_Object subfeatures
= Qnil
;
7241 const struct socket_options
*sopt
;
7243 #define ADD_SUBFEATURE(key, val) \
7244 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7246 #ifdef NON_BLOCKING_CONNECT
7247 ADD_SUBFEATURE (QCnowait
, Qt
);
7249 #ifdef DATAGRAM_SOCKETS
7250 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7252 #ifdef HAVE_SEQPACKET
7253 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7255 #ifdef HAVE_LOCAL_SOCKETS
7256 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7258 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7260 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7262 #ifdef HAVE_GETSOCKNAME
7263 ADD_SUBFEATURE (QCservice
, Qt
);
7265 ADD_SUBFEATURE (QCserver
, Qt
);
7267 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7268 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7270 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7273 #if defined (DARWIN_OS)
7274 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7275 processes. As such, we only change the default value. */
7278 char const *release
= (STRINGP (Voperating_system_release
)
7279 ? SSDATA (Voperating_system_release
)
7281 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7282 Vprocess_connection_type
= Qnil
;
7286 #endif /* subprocesses */
7291 syms_of_process (void)
7295 DEFSYM (Qprocessp
, "processp");
7296 DEFSYM (Qrun
, "run");
7297 DEFSYM (Qstop
, "stop");
7298 DEFSYM (Qsignal
, "signal");
7300 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7303 DEFSYM (Qopen
, "open");
7304 DEFSYM (Qclosed
, "closed");
7305 DEFSYM (Qconnect
, "connect");
7306 DEFSYM (Qfailed
, "failed");
7307 DEFSYM (Qlisten
, "listen");
7308 DEFSYM (Qlocal
, "local");
7309 DEFSYM (Qipv4
, "ipv4");
7311 DEFSYM (Qipv6
, "ipv6");
7313 DEFSYM (Qdatagram
, "datagram");
7314 DEFSYM (Qseqpacket
, "seqpacket");
7316 DEFSYM (QCport
, ":port");
7317 DEFSYM (QCspeed
, ":speed");
7318 DEFSYM (QCprocess
, ":process");
7320 DEFSYM (QCbytesize
, ":bytesize");
7321 DEFSYM (QCstopbits
, ":stopbits");
7322 DEFSYM (QCparity
, ":parity");
7323 DEFSYM (Qodd
, "odd");
7324 DEFSYM (Qeven
, "even");
7325 DEFSYM (QCflowcontrol
, ":flowcontrol");
7328 DEFSYM (QCsummary
, ":summary");
7330 DEFSYM (Qreal
, "real");
7331 DEFSYM (Qnetwork
, "network");
7332 DEFSYM (Qserial
, "serial");
7333 DEFSYM (QCbuffer
, ":buffer");
7334 DEFSYM (QChost
, ":host");
7335 DEFSYM (QCservice
, ":service");
7336 DEFSYM (QClocal
, ":local");
7337 DEFSYM (QCremote
, ":remote");
7338 DEFSYM (QCcoding
, ":coding");
7339 DEFSYM (QCserver
, ":server");
7340 DEFSYM (QCnowait
, ":nowait");
7341 DEFSYM (QCsentinel
, ":sentinel");
7342 DEFSYM (QClog
, ":log");
7343 DEFSYM (QCnoquery
, ":noquery");
7344 DEFSYM (QCstop
, ":stop");
7345 DEFSYM (QCoptions
, ":options");
7346 DEFSYM (QCplist
, ":plist");
7347 DEFSYM (QCcommand
, ":command");
7348 DEFSYM (QCconnection_type
, ":connection-type");
7349 DEFSYM (Qpty
, "pty");
7350 DEFSYM (Qpipe
, "pipe");
7352 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7354 staticpro (&Vprocess_alist
);
7355 staticpro (&deleted_pid_list
);
7357 #endif /* subprocesses */
7359 DEFSYM (QCname
, ":name");
7360 DEFSYM (QCtype
, ":type");
7362 DEFSYM (Qeuid
, "euid");
7363 DEFSYM (Qegid
, "egid");
7364 DEFSYM (Quser
, "user");
7365 DEFSYM (Qgroup
, "group");
7366 DEFSYM (Qcomm
, "comm");
7367 DEFSYM (Qstate
, "state");
7368 DEFSYM (Qppid
, "ppid");
7369 DEFSYM (Qpgrp
, "pgrp");
7370 DEFSYM (Qsess
, "sess");
7371 DEFSYM (Qttname
, "ttname");
7372 DEFSYM (Qtpgid
, "tpgid");
7373 DEFSYM (Qminflt
, "minflt");
7374 DEFSYM (Qmajflt
, "majflt");
7375 DEFSYM (Qcminflt
, "cminflt");
7376 DEFSYM (Qcmajflt
, "cmajflt");
7377 DEFSYM (Qutime
, "utime");
7378 DEFSYM (Qstime
, "stime");
7379 DEFSYM (Qtime
, "time");
7380 DEFSYM (Qcutime
, "cutime");
7381 DEFSYM (Qcstime
, "cstime");
7382 DEFSYM (Qctime
, "ctime");
7384 DEFSYM (Qinternal_default_process_sentinel
,
7385 "internal-default-process-sentinel");
7386 DEFSYM (Qinternal_default_process_filter
,
7387 "internal-default-process-filter");
7389 DEFSYM (Qpri
, "pri");
7390 DEFSYM (Qnice
, "nice");
7391 DEFSYM (Qthcount
, "thcount");
7392 DEFSYM (Qstart
, "start");
7393 DEFSYM (Qvsize
, "vsize");
7394 DEFSYM (Qrss
, "rss");
7395 DEFSYM (Qetime
, "etime");
7396 DEFSYM (Qpcpu
, "pcpu");
7397 DEFSYM (Qpmem
, "pmem");
7398 DEFSYM (Qargs
, "args");
7400 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7401 doc
: /* Non-nil means delete processes immediately when they exit.
7402 A value of nil means don't delete them until `list-processes' is run. */);
7404 delete_exited_processes
= 1;
7407 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7408 doc
: /* Control type of device used to communicate with subprocesses.
7409 Values are nil to use a pipe, or t or `pty' to use a pty.
7410 The value has no effect if the system has no ptys or if all ptys are busy:
7411 then a pipe is used in any case.
7412 The value takes effect when `start-process' is called. */);
7413 Vprocess_connection_type
= Qt
;
7415 #ifdef ADAPTIVE_READ_BUFFERING
7416 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7417 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7418 On some systems, when Emacs reads the output from a subprocess, the output data
7419 is read in very small blocks, potentially resulting in very poor performance.
7420 This behavior can be remedied to some extent by setting this variable to a
7421 non-nil value, as it will automatically delay reading from such processes, to
7422 allow them to produce more output before Emacs tries to read it.
7423 If the value is t, the delay is reset after each write to the process; any other
7424 non-nil value means that the delay is not reset on write.
7425 The variable takes effect when `start-process' is called. */);
7426 Vprocess_adaptive_read_buffering
= Qt
;
7429 defsubr (&Sprocessp
);
7430 defsubr (&Sget_process
);
7431 defsubr (&Sdelete_process
);
7432 defsubr (&Sprocess_status
);
7433 defsubr (&Sprocess_exit_status
);
7434 defsubr (&Sprocess_id
);
7435 defsubr (&Sprocess_name
);
7436 defsubr (&Sprocess_tty_name
);
7437 defsubr (&Sprocess_command
);
7438 defsubr (&Sset_process_buffer
);
7439 defsubr (&Sprocess_buffer
);
7440 defsubr (&Sprocess_mark
);
7441 defsubr (&Sset_process_filter
);
7442 defsubr (&Sprocess_filter
);
7443 defsubr (&Sset_process_sentinel
);
7444 defsubr (&Sprocess_sentinel
);
7445 defsubr (&Sset_process_window_size
);
7446 defsubr (&Sset_process_inherit_coding_system_flag
);
7447 defsubr (&Sset_process_query_on_exit_flag
);
7448 defsubr (&Sprocess_query_on_exit_flag
);
7449 defsubr (&Sprocess_contact
);
7450 defsubr (&Sprocess_plist
);
7451 defsubr (&Sset_process_plist
);
7452 defsubr (&Sprocess_list
);
7453 defsubr (&Smake_process
);
7454 defsubr (&Sserial_process_configure
);
7455 defsubr (&Smake_serial_process
);
7456 defsubr (&Sset_network_process_option
);
7457 defsubr (&Smake_network_process
);
7458 defsubr (&Sformat_network_address
);
7459 defsubr (&Snetwork_interface_list
);
7460 defsubr (&Snetwork_interface_info
);
7461 #ifdef DATAGRAM_SOCKETS
7462 defsubr (&Sprocess_datagram_address
);
7463 defsubr (&Sset_process_datagram_address
);
7465 defsubr (&Saccept_process_output
);
7466 defsubr (&Sprocess_send_region
);
7467 defsubr (&Sprocess_send_string
);
7468 defsubr (&Sinterrupt_process
);
7469 defsubr (&Skill_process
);
7470 defsubr (&Squit_process
);
7471 defsubr (&Sstop_process
);
7472 defsubr (&Scontinue_process
);
7473 defsubr (&Sprocess_running_child_p
);
7474 defsubr (&Sprocess_send_eof
);
7475 defsubr (&Ssignal_process
);
7476 defsubr (&Swaiting_for_user_input_p
);
7477 defsubr (&Sprocess_type
);
7478 defsubr (&Sinternal_default_process_sentinel
);
7479 defsubr (&Sinternal_default_process_filter
);
7480 defsubr (&Sset_process_coding_system
);
7481 defsubr (&Sprocess_coding_system
);
7482 defsubr (&Sset_process_filter_multibyte
);
7483 defsubr (&Sprocess_filter_multibyte_p
);
7485 #endif /* subprocesses */
7487 defsubr (&Sget_buffer_process
);
7488 defsubr (&Sprocess_inherit_coding_system_flag
);
7489 defsubr (&Slist_system_processes
);
7490 defsubr (&Sprocess_attributes
);