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. */
200 /* Only W32 has this, it really means that select can't take write mask. */
201 #ifdef BROKEN_NON_BLOCKING_CONNECT
202 #undef NON_BLOCKING_CONNECT
203 enum { SELECT_CAN_DO_WRITE_MASK
= false };
205 enum { SELECT_CAN_DO_WRITE_MASK
= true };
206 #ifndef NON_BLOCKING_CONNECT
208 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
209 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
210 #define NON_BLOCKING_CONNECT
211 #endif /* EWOULDBLOCK || EINPROGRESS */
212 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
213 #endif /* HAVE_SELECT */
214 #endif /* NON_BLOCKING_CONNECT */
215 #endif /* BROKEN_NON_BLOCKING_CONNECT */
217 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
222 #ifndef BROKEN_DATAGRAM_SOCKETS
223 # if defined HAVE_SELECT || defined USABLE_FIONREAD
224 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
225 # define DATAGRAM_SOCKETS
230 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
231 # define HAVE_SEQPACKET
234 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
235 #define ADAPTIVE_READ_BUFFERING
238 #ifdef ADAPTIVE_READ_BUFFERING
239 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
240 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
241 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
243 /* Number of processes which have a non-zero read_output_delay,
244 and therefore might be delayed for adaptive read buffering. */
246 static int process_output_delay_count
;
248 /* True if any process has non-nil read_output_skip. */
250 static bool process_output_skip
;
253 #define process_output_delay_count 0
256 static void create_process (Lisp_Object
, char **, Lisp_Object
);
258 static bool keyboard_bit_set (fd_set
*);
260 static void deactivate_process (Lisp_Object
);
261 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
262 static int read_process_output (Lisp_Object
, int);
263 static void handle_child_signal (int);
264 static void create_pty (Lisp_Object
);
266 static Lisp_Object
get_process (register Lisp_Object name
);
267 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
269 /* Mask of bits indicating the descriptors that we wait for input on. */
271 static fd_set input_wait_mask
;
273 /* Mask that excludes keyboard input descriptor(s). */
275 static fd_set non_keyboard_wait_mask
;
277 /* Mask that excludes process input descriptor(s). */
279 static fd_set non_process_wait_mask
;
281 /* Mask for selecting for write. */
283 static fd_set write_mask
;
285 #ifdef NON_BLOCKING_CONNECT
286 /* Mask of bits indicating the descriptors that we wait for connect to
287 complete on. Once they complete, they are removed from this mask
288 and added to the input_wait_mask and non_keyboard_wait_mask. */
290 static fd_set connect_wait_mask
;
292 /* Number of bits set in connect_wait_mask. */
293 static int num_pending_connects
;
294 #endif /* NON_BLOCKING_CONNECT */
296 /* The largest descriptor currently in use for a process object; -1 if none. */
297 static int max_process_desc
;
299 /* The largest descriptor currently in use for input; -1 if none. */
300 static int max_input_desc
;
302 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
303 static Lisp_Object chan_process
[FD_SETSIZE
];
305 /* Alist of elements (NAME . PROCESS). */
306 static Lisp_Object Vprocess_alist
;
308 /* Buffered-ahead input char from process, indexed by channel.
309 -1 means empty (no char is buffered).
310 Used on sys V where the only way to tell if there is any
311 output from the process is to read at least one char.
312 Always -1 on systems that support FIONREAD. */
314 static int proc_buffered_char
[FD_SETSIZE
];
316 /* Table of `struct coding-system' for each process. */
317 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
318 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
320 #ifdef DATAGRAM_SOCKETS
321 /* Table of `partner address' for datagram sockets. */
322 static struct sockaddr_and_len
{
325 } datagram_address
[FD_SETSIZE
];
326 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
327 #define DATAGRAM_CONN_P(proc) \
328 (PROCESSP (proc) && \
329 XPROCESS (proc)->infd >= 0 && \
330 datagram_address[XPROCESS (proc)->infd].sa != 0)
332 #define DATAGRAM_CHAN_P(chan) (0)
333 #define DATAGRAM_CONN_P(proc) (0)
336 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
337 a `for' loop which iterates over processes from Vprocess_alist. */
339 #define FOR_EACH_PROCESS(list_var, proc_var) \
340 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
342 /* These setters are used only in this file, so they can be private. */
344 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
349 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
354 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
356 p
->decode_coding_system
= val
;
359 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
361 p
->decoding_buf
= val
;
364 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
366 p
->encode_coding_system
= val
;
369 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
371 p
->encoding_buf
= val
;
374 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
376 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
379 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
384 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
389 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
394 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
399 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
401 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
404 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
409 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
414 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
419 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
421 p
->write_queue
= val
;
426 static struct fd_callback_data
432 int condition
; /* Mask of the defines above. */
433 } fd_callback_info
[FD_SETSIZE
];
436 /* Add a file descriptor FD to be monitored for when read is possible.
437 When read is possible, call FUNC with argument DATA. */
440 add_read_fd (int fd
, fd_callback func
, void *data
)
442 add_keyboard_wait_descriptor (fd
);
444 fd_callback_info
[fd
].func
= func
;
445 fd_callback_info
[fd
].data
= data
;
446 fd_callback_info
[fd
].condition
|= FOR_READ
;
449 /* Stop monitoring file descriptor FD for when read is possible. */
452 delete_read_fd (int fd
)
454 delete_keyboard_wait_descriptor (fd
);
456 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
457 if (fd_callback_info
[fd
].condition
== 0)
459 fd_callback_info
[fd
].func
= 0;
460 fd_callback_info
[fd
].data
= 0;
464 /* Add a file descriptor FD to be monitored for when write is possible.
465 When write is possible, call FUNC with argument DATA. */
468 add_write_fd (int fd
, fd_callback func
, void *data
)
470 FD_SET (fd
, &write_mask
);
471 if (fd
> max_input_desc
)
474 fd_callback_info
[fd
].func
= func
;
475 fd_callback_info
[fd
].data
= data
;
476 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
479 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
482 delete_input_desc (int fd
)
484 if (fd
== max_input_desc
)
488 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
489 || FD_ISSET (fd
, &write_mask
)));
495 /* Stop monitoring file descriptor FD for when write is possible. */
498 delete_write_fd (int fd
)
500 FD_CLR (fd
, &write_mask
);
501 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
502 if (fd_callback_info
[fd
].condition
== 0)
504 fd_callback_info
[fd
].func
= 0;
505 fd_callback_info
[fd
].data
= 0;
506 delete_input_desc (fd
);
511 /* Compute the Lisp form of the process status, p->status, from
512 the numeric status that was returned by `wait'. */
514 static Lisp_Object
status_convert (int);
517 update_status (struct Lisp_Process
*p
)
519 eassert (p
->raw_status_new
);
520 pset_status (p
, status_convert (p
->raw_status
));
521 p
->raw_status_new
= 0;
524 /* Convert a process status word in Unix format to
525 the list that we use internally. */
528 status_convert (int w
)
531 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
532 else if (WIFEXITED (w
))
533 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
534 WCOREDUMP (w
) ? Qt
: Qnil
));
535 else if (WIFSIGNALED (w
))
536 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
537 WCOREDUMP (w
) ? Qt
: Qnil
));
542 /* Given a status-list, extract the three pieces of information
543 and store them individually through the three pointers. */
546 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
560 *code
= XFASTINT (XCAR (tem
));
562 *coredump
= !NILP (tem
);
566 /* Return a string describing a process status list. */
569 status_message (struct Lisp_Process
*p
)
571 Lisp_Object status
= p
->status
;
577 decode_status (status
, &symbol
, &code
, &coredump
);
579 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
582 synchronize_system_messages_locale ();
583 signame
= strsignal (code
);
585 string
= build_string ("unknown");
590 string
= build_unibyte_string (signame
);
591 if (! NILP (Vlocale_coding_system
))
592 string
= (code_convert_string_norecord
593 (string
, Vlocale_coding_system
, 0));
594 c1
= STRING_CHAR (SDATA (string
));
597 Faset (string
, make_number (0), make_number (c2
));
599 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
600 return concat2 (string
, suffix
);
602 else if (EQ (symbol
, Qexit
))
605 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
607 return build_string ("finished\n");
608 AUTO_STRING (prefix
, "exited abnormally with code ");
609 string
= Fnumber_to_string (make_number (code
));
610 AUTO_STRING (suffix
, coredump
? " (core dumped)\n" : "\n");
611 return concat3 (prefix
, string
, suffix
);
613 else if (EQ (symbol
, Qfailed
))
615 AUTO_STRING (prefix
, "failed with code ");
616 string
= Fnumber_to_string (make_number (code
));
617 AUTO_STRING (suffix
, "\n");
618 return concat3 (prefix
, string
, suffix
);
621 return Fcopy_sequence (Fsymbol_name (symbol
));
624 enum { PTY_NAME_SIZE
= 24 };
626 /* Open an available pty, returning a file descriptor.
627 Store into PTY_NAME the file name of the terminal corresponding to the pty.
628 Return -1 on failure. */
631 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
640 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
641 for (i
= 0; i
< 16; i
++)
644 #ifdef PTY_NAME_SPRINTF
647 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
648 #endif /* no PTY_NAME_SPRINTF */
652 #else /* no PTY_OPEN */
653 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
654 #endif /* no PTY_OPEN */
659 /* Set FD's close-on-exec flag. This is needed even if
660 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
661 doesn't require support for that combination.
662 Multithreaded platforms where posix_openpt ignores
663 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
664 have a race condition between the PTY_OPEN and here. */
665 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
667 /* Check to make certain that both sides are available
668 this avoids a nasty yet stupid bug in rlogins. */
669 #ifdef PTY_TTY_NAME_SPRINTF
672 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
673 #endif /* no PTY_TTY_NAME_SPRINTF */
674 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
687 #endif /* HAVE_PTYS */
692 make_process (Lisp_Object name
)
694 register Lisp_Object val
, tem
, name1
;
695 register struct Lisp_Process
*p
;
696 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
699 p
= allocate_process ();
700 /* Initialize Lisp data. Note that allocate_process initializes all
701 Lisp data to nil, so do it only for slots which should not be nil. */
702 pset_status (p
, Qrun
);
703 pset_mark (p
, Fmake_marker ());
705 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
706 non-Lisp data, so do it only for slots which should not be zero. */
709 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
713 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
716 /* If name is already in use, modify it until it is unused. */
721 tem
= Fget_process (name1
);
722 if (NILP (tem
)) break;
723 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
727 pset_sentinel (p
, Qinternal_default_process_sentinel
);
728 pset_filter (p
, Qinternal_default_process_filter
);
729 XSETPROCESS (val
, p
);
730 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
735 remove_process (register Lisp_Object proc
)
737 register Lisp_Object pair
;
739 pair
= Frassq (proc
, Vprocess_alist
);
740 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
742 deactivate_process (proc
);
746 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
747 doc
: /* Return t if OBJECT is a process. */)
750 return PROCESSP (object
) ? Qt
: Qnil
;
753 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
754 doc
: /* Return the process named NAME, or nil if there is none. */)
755 (register Lisp_Object name
)
760 return Fcdr (Fassoc (name
, Vprocess_alist
));
763 /* This is how commands for the user decode process arguments. It
764 accepts a process, a process name, a buffer, a buffer name, or nil.
765 Buffers denote the first process in the buffer, and nil denotes the
769 get_process (register Lisp_Object name
)
771 register Lisp_Object proc
, obj
;
774 obj
= Fget_process (name
);
776 obj
= Fget_buffer (name
);
778 error ("Process %s does not exist", SDATA (name
));
780 else if (NILP (name
))
781 obj
= Fcurrent_buffer ();
785 /* Now obj should be either a buffer object or a process object. */
788 if (NILP (BVAR (XBUFFER (obj
), name
)))
789 error ("Attempt to get process for a dead buffer");
790 proc
= Fget_buffer_process (obj
);
792 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
803 /* Fdelete_process promises to immediately forget about the process, but in
804 reality, Emacs needs to remember those processes until they have been
805 treated by the SIGCHLD handler and waitpid has been invoked on them;
806 otherwise they might fill up the kernel's process table.
808 Some processes created by call-process are also put onto this list.
810 Members of this list are (process-ID . filename) pairs. The
811 process-ID is a number; the filename, if a string, is a file that
812 needs to be removed after the process exits. */
813 static Lisp_Object deleted_pid_list
;
816 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
818 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
819 /* GC treated elements set to nil. */
820 Fdelq (Qnil
, deleted_pid_list
));
824 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
825 doc
: /* Delete PROCESS: kill it and forget about it immediately.
826 PROCESS may be a process, a buffer, the name of a process or buffer, or
827 nil, indicating the current buffer's process. */)
828 (register Lisp_Object process
)
830 register struct Lisp_Process
*p
;
832 process
= get_process (process
);
833 p
= XPROCESS (process
);
835 p
->raw_status_new
= 0;
836 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
838 pset_status (p
, list2 (Qexit
, make_number (0)));
839 p
->tick
= ++process_tick
;
840 status_notify (p
, NULL
);
841 redisplay_preserve_echo_area (13);
846 record_kill_process (p
, Qnil
);
850 /* Update P's status, since record_kill_process will make the
851 SIGCHLD handler update deleted_pid_list, not *P. */
853 if (p
->raw_status_new
)
855 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
856 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
857 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
859 p
->tick
= ++process_tick
;
860 status_notify (p
, NULL
);
861 redisplay_preserve_echo_area (13);
864 remove_process (process
);
868 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
869 doc
: /* Return the status of PROCESS.
870 The returned value is one of the following symbols:
871 run -- for a process that is running.
872 stop -- for a process stopped but continuable.
873 exit -- for a process that has exited.
874 signal -- for a process that has got a fatal signal.
875 open -- for a network stream connection that is open.
876 listen -- for a network stream server that is listening.
877 closed -- for a network stream connection that is closed.
878 connect -- when waiting for a non-blocking connection to complete.
879 failed -- when a non-blocking connection has failed.
880 nil -- if arg is a process name and no such process exists.
881 PROCESS may be a process, a buffer, the name of a process, or
882 nil, indicating the current buffer's process. */)
883 (register Lisp_Object process
)
885 register struct Lisp_Process
*p
;
886 register Lisp_Object status
;
888 if (STRINGP (process
))
889 process
= Fget_process (process
);
891 process
= get_process (process
);
896 p
= XPROCESS (process
);
897 if (p
->raw_status_new
)
901 status
= XCAR (status
);
902 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
904 if (EQ (status
, Qexit
))
906 else if (EQ (p
->command
, Qt
))
908 else if (EQ (status
, Qrun
))
914 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
916 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
917 If PROCESS has not yet exited or died, return 0. */)
918 (register Lisp_Object process
)
920 CHECK_PROCESS (process
);
921 if (XPROCESS (process
)->raw_status_new
)
922 update_status (XPROCESS (process
));
923 if (CONSP (XPROCESS (process
)->status
))
924 return XCAR (XCDR (XPROCESS (process
)->status
));
925 return make_number (0);
928 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
929 doc
: /* Return the process id of PROCESS.
930 This is the pid of the external process which PROCESS uses or talks to.
931 For a network connection, this value is nil. */)
932 (register Lisp_Object process
)
936 CHECK_PROCESS (process
);
937 pid
= XPROCESS (process
)->pid
;
938 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
941 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
942 doc
: /* Return the name of PROCESS, as a string.
943 This is the name of the program invoked in PROCESS,
944 possibly modified to make it unique among process names. */)
945 (register Lisp_Object process
)
947 CHECK_PROCESS (process
);
948 return XPROCESS (process
)->name
;
951 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
952 doc
: /* Return the command that was executed to start PROCESS.
953 This is a list of strings, the first string being the program executed
954 and the rest of the strings being the arguments given to it.
955 For a network or serial process, this is nil (process is running) or t
956 \(process is stopped). */)
957 (register Lisp_Object process
)
959 CHECK_PROCESS (process
);
960 return XPROCESS (process
)->command
;
963 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
964 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
965 This is the terminal that the process itself reads and writes on,
966 not the name of the pty that Emacs uses to talk with that terminal. */)
967 (register Lisp_Object process
)
969 CHECK_PROCESS (process
);
970 return XPROCESS (process
)->tty_name
;
973 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
975 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
977 (register Lisp_Object process
, Lisp_Object buffer
)
979 struct Lisp_Process
*p
;
981 CHECK_PROCESS (process
);
983 CHECK_BUFFER (buffer
);
984 p
= XPROCESS (process
);
985 pset_buffer (p
, buffer
);
986 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
987 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
988 setup_process_coding_systems (process
);
992 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
994 doc
: /* Return the buffer PROCESS is associated with.
995 The default process filter inserts output from PROCESS into this buffer. */)
996 (register Lisp_Object process
)
998 CHECK_PROCESS (process
);
999 return XPROCESS (process
)->buffer
;
1002 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1004 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1005 (register Lisp_Object process
)
1007 CHECK_PROCESS (process
);
1008 return XPROCESS (process
)->mark
;
1011 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1013 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1014 A value of t means stop accepting output from the process.
1016 When a process has a non-default filter, its buffer is not used for output.
1017 Instead, each time it does output, the entire string of output is
1018 passed to the filter.
1020 The filter gets two arguments: the process and the string of output.
1021 The string argument is normally a multibyte string, except:
1022 - if the process's input coding system is no-conversion or raw-text,
1023 it is a unibyte string (the non-converted input), or else
1024 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1025 string (the result of converting the decoded input multibyte
1026 string to unibyte with `string-make-unibyte'). */)
1027 (register Lisp_Object process
, Lisp_Object filter
)
1029 struct Lisp_Process
*p
;
1031 CHECK_PROCESS (process
);
1032 p
= XPROCESS (process
);
1034 /* Don't signal an error if the process's input file descriptor
1035 is closed. This could make debugging Lisp more difficult,
1036 for example when doing something like
1038 (setq process (start-process ...))
1040 (set-process-filter process ...) */
1043 filter
= Qinternal_default_process_filter
;
1047 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1049 FD_CLR (p
->infd
, &input_wait_mask
);
1050 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1052 else if (EQ (p
->filter
, Qt
)
1053 /* Network or serial process not stopped: */
1054 && !EQ (p
->command
, Qt
))
1056 FD_SET (p
->infd
, &input_wait_mask
);
1057 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1061 pset_filter (p
, filter
);
1062 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1063 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1064 setup_process_coding_systems (process
);
1068 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1070 doc
: /* Return the filter function of PROCESS.
1071 See `set-process-filter' for more info on filter functions. */)
1072 (register Lisp_Object process
)
1074 CHECK_PROCESS (process
);
1075 return XPROCESS (process
)->filter
;
1078 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1080 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1081 The sentinel is called as a function when the process changes state.
1082 It gets two arguments: the process, and a string describing the change. */)
1083 (register Lisp_Object process
, Lisp_Object sentinel
)
1085 struct Lisp_Process
*p
;
1087 CHECK_PROCESS (process
);
1088 p
= XPROCESS (process
);
1090 if (NILP (sentinel
))
1091 sentinel
= Qinternal_default_process_sentinel
;
1093 pset_sentinel (p
, sentinel
);
1094 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1095 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1099 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1101 doc
: /* Return the sentinel of PROCESS.
1102 See `set-process-sentinel' for more info on sentinels. */)
1103 (register Lisp_Object process
)
1105 CHECK_PROCESS (process
);
1106 return XPROCESS (process
)->sentinel
;
1109 DEFUN ("set-process-window-size", Fset_process_window_size
,
1110 Sset_process_window_size
, 3, 3, 0,
1111 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1112 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1114 CHECK_PROCESS (process
);
1116 /* All known platforms store window sizes as 'unsigned short'. */
1117 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1118 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1120 if (XPROCESS (process
)->infd
< 0
1121 || (set_window_size (XPROCESS (process
)->infd
,
1122 XINT (height
), XINT (width
))
1129 DEFUN ("set-process-inherit-coding-system-flag",
1130 Fset_process_inherit_coding_system_flag
,
1131 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1132 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1133 If the second argument FLAG is non-nil, then the variable
1134 `buffer-file-coding-system' of the buffer associated with PROCESS
1135 will be bound to the value of the coding system used to decode
1138 This is useful when the coding system specified for the process buffer
1139 leaves either the character code conversion or the end-of-line conversion
1140 unspecified, or if the coding system used to decode the process output
1141 is more appropriate for saving the process buffer.
1143 Binding the variable `inherit-process-coding-system' to non-nil before
1144 starting the process is an alternative way of setting the inherit flag
1145 for the process which will run.
1147 This function returns FLAG. */)
1148 (register Lisp_Object process
, Lisp_Object flag
)
1150 CHECK_PROCESS (process
);
1151 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1155 DEFUN ("set-process-query-on-exit-flag",
1156 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1158 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1159 If the second argument FLAG is non-nil, Emacs will query the user before
1160 exiting or killing a buffer if PROCESS is running. This function
1162 (register Lisp_Object process
, Lisp_Object flag
)
1164 CHECK_PROCESS (process
);
1165 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1169 DEFUN ("process-query-on-exit-flag",
1170 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1172 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1173 (register Lisp_Object process
)
1175 CHECK_PROCESS (process
);
1176 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1179 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1181 doc
: /* Return the contact info of PROCESS; t for a real child.
1182 For a network or serial connection, the value depends on the optional
1183 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1184 SERVICE) for a network connection or (PORT SPEED) for a serial
1185 connection. If KEY is t, the complete contact information for the
1186 connection is returned, else the specific value for the keyword KEY is
1187 returned. See `make-network-process' or `make-serial-process' for a
1188 list of keywords. */)
1189 (register Lisp_Object process
, Lisp_Object key
)
1191 Lisp_Object contact
;
1193 CHECK_PROCESS (process
);
1194 contact
= XPROCESS (process
)->childp
;
1196 #ifdef DATAGRAM_SOCKETS
1197 if (DATAGRAM_CONN_P (process
)
1198 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1199 contact
= Fplist_put (contact
, QCremote
,
1200 Fprocess_datagram_address (process
));
1203 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1205 if (NILP (key
) && NETCONN_P (process
))
1206 return list2 (Fplist_get (contact
, QChost
),
1207 Fplist_get (contact
, QCservice
));
1208 if (NILP (key
) && SERIALCONN_P (process
))
1209 return list2 (Fplist_get (contact
, QCport
),
1210 Fplist_get (contact
, QCspeed
));
1211 return Fplist_get (contact
, key
);
1214 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1216 doc
: /* Return the plist of PROCESS. */)
1217 (register Lisp_Object process
)
1219 CHECK_PROCESS (process
);
1220 return XPROCESS (process
)->plist
;
1223 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1225 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1226 (register Lisp_Object process
, Lisp_Object plist
)
1228 CHECK_PROCESS (process
);
1231 pset_plist (XPROCESS (process
), plist
);
1235 #if 0 /* Turned off because we don't currently record this info
1236 in the process. Perhaps add it. */
1237 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1238 doc
: /* Return the connection type of PROCESS.
1239 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1240 a socket connection. */)
1241 (Lisp_Object process
)
1243 return XPROCESS (process
)->type
;
1247 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1248 doc
: /* Return the connection type of PROCESS.
1249 The value is either the symbol `real', `network', or `serial'.
1250 PROCESS may be a process, a buffer, the name of a process or buffer, or
1251 nil, indicating the current buffer's process. */)
1252 (Lisp_Object process
)
1255 proc
= get_process (process
);
1256 return XPROCESS (proc
)->type
;
1259 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1261 doc
: /* Convert network ADDRESS from internal format to a string.
1262 A 4 or 5 element vector represents an IPv4 address (with port number).
1263 An 8 or 9 element vector represents an IPv6 address (with port number).
1264 If optional second argument OMIT-PORT is non-nil, don't include a port
1265 number in the string, even when present in ADDRESS.
1266 Returns nil if format of ADDRESS is invalid. */)
1267 (Lisp_Object address
, Lisp_Object omit_port
)
1272 if (STRINGP (address
)) /* AF_LOCAL */
1275 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1277 register struct Lisp_Vector
*p
= XVECTOR (address
);
1278 ptrdiff_t size
= p
->header
.size
;
1279 Lisp_Object args
[10];
1283 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1285 format
= "%d.%d.%d.%d";
1290 format
= "%d.%d.%d.%d:%d";
1293 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1295 format
= "%x:%x:%x:%x:%x:%x:%x:%x";
1300 format
= "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1306 AUTO_STRING (format_obj
, format
);
1307 args
[0] = format_obj
;
1309 for (i
= 0; i
< nargs
; i
++)
1311 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1314 if (nargs
<= 5 /* IPv4 */
1315 && i
< 4 /* host, not port */
1316 && XINT (p
->contents
[i
]) > 255)
1319 args
[i
+ 1] = p
->contents
[i
];
1322 return Fformat (nargs
+ 1, args
);
1325 if (CONSP (address
))
1327 AUTO_STRING (format
, "<Family %d>");
1328 return Fformat (2, (Lisp_Object
[]) {format
, Fcar (address
)});
1334 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1335 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1338 return Fmapcar (Qcdr
, Vprocess_alist
);
1341 /* Starting asynchronous inferior processes. */
1343 static void start_process_unwind (Lisp_Object proc
);
1345 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1346 doc
: /* Start a program in a subprocess. Return the process object for it.
1347 NAME is name for process. It is modified if necessary to make it unique.
1348 BUFFER is the buffer (or buffer name) to associate with the process.
1350 Process output (both standard output and standard error streams) goes
1351 at end of BUFFER, unless you specify an output stream or filter
1352 function to handle the output. BUFFER may also be nil, meaning that
1353 this process is not associated with any buffer.
1355 PROGRAM is the program file name. It is searched for in `exec-path'
1356 (which see). If nil, just associate a pty with the buffer. Remaining
1357 arguments are strings to give program as arguments.
1359 If you want to separate standard output from standard error, invoke
1360 the command through a shell and redirect one of them using the shell
1363 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1364 (ptrdiff_t nargs
, Lisp_Object
*args
)
1366 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1367 unsigned char **new_argv
;
1369 ptrdiff_t count
= SPECPDL_INDEX ();
1374 buffer
= Fget_buffer_create (buffer
);
1376 /* Make sure that the child will be able to chdir to the current
1377 buffer's current directory, or its unhandled equivalent. We
1378 can't just have the child check for an error when it does the
1379 chdir, since it's in a vfork.
1381 We have to GCPRO around this because Fexpand_file_name and
1382 Funhandled_file_name_directory might call a file name handling
1383 function. The argument list is protected by the caller, so all
1384 we really have to worry about is buffer. */
1386 struct gcpro gcpro1
;
1388 current_dir
= encode_current_directory ();
1393 CHECK_STRING (name
);
1397 if (!NILP (program
))
1398 CHECK_STRING (program
);
1400 proc
= make_process (name
);
1401 /* If an error occurs and we can't start the process, we want to
1402 remove it from the process list. This means that each error
1403 check in create_process doesn't need to call remove_process
1404 itself; it's all taken care of here. */
1405 record_unwind_protect (start_process_unwind
, proc
);
1407 pset_childp (XPROCESS (proc
), Qt
);
1408 pset_plist (XPROCESS (proc
), Qnil
);
1409 pset_type (XPROCESS (proc
), Qreal
);
1410 pset_buffer (XPROCESS (proc
), buffer
);
1411 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1412 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1413 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1416 /* AKA GNUTLS_INITSTAGE(proc). */
1417 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1418 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1421 #ifdef ADAPTIVE_READ_BUFFERING
1422 XPROCESS (proc
)->adaptive_read_buffering
1423 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1424 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1427 /* Make the process marker point into the process buffer (if any). */
1428 if (BUFFERP (buffer
))
1429 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1430 BUF_ZV (XBUFFER (buffer
)),
1431 BUF_ZV_BYTE (XBUFFER (buffer
)));
1434 /* Decide coding systems for communicating with the process. Here
1435 we don't setup the structure coding_system nor pay attention to
1436 unibyte mode. They are done in create_process. */
1438 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1439 Lisp_Object coding_systems
= Qt
;
1440 Lisp_Object val
, *args2
;
1441 struct gcpro gcpro1
, gcpro2
;
1443 val
= Vcoding_system_for_read
;
1446 SAFE_ALLOCA_LISP (args2
, nargs
+ 1);
1447 args2
[0] = Qstart_process
;
1448 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1449 GCPRO2 (proc
, current_dir
);
1450 if (!NILP (program
))
1451 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1453 if (CONSP (coding_systems
))
1454 val
= XCAR (coding_systems
);
1455 else if (CONSP (Vdefault_process_coding_system
))
1456 val
= XCAR (Vdefault_process_coding_system
);
1458 pset_decode_coding_system (XPROCESS (proc
), val
);
1460 val
= Vcoding_system_for_write
;
1463 if (EQ (coding_systems
, Qt
))
1465 SAFE_ALLOCA_LISP (args2
, nargs
+ 1);
1466 args2
[0] = Qstart_process
;
1467 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1468 GCPRO2 (proc
, current_dir
);
1469 if (!NILP (program
))
1470 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1473 if (CONSP (coding_systems
))
1474 val
= XCDR (coding_systems
);
1475 else if (CONSP (Vdefault_process_coding_system
))
1476 val
= XCDR (Vdefault_process_coding_system
);
1478 pset_encode_coding_system (XPROCESS (proc
), val
);
1479 /* Note: At this moment, the above coding system may leave
1480 text-conversion or eol-conversion unspecified. They will be
1481 decided after we read output from the process and decode it by
1482 some coding system, or just before we actually send a text to
1487 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1488 XPROCESS (proc
)->decoding_carryover
= 0;
1489 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1491 XPROCESS (proc
)->inherit_coding_system_flag
1492 = !(NILP (buffer
) || !inherit_process_coding_system
);
1494 if (!NILP (program
))
1496 /* If program file name is not absolute, search our path for it.
1497 Put the name we will really use in TEM. */
1498 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1499 && !(SCHARS (program
) > 1
1500 && IS_DEVICE_SEP (SREF (program
, 1))))
1502 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1505 GCPRO4 (name
, program
, buffer
, current_dir
);
1506 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1507 make_number (X_OK
), false);
1510 report_file_error ("Searching for program", program
);
1511 tem
= Fexpand_file_name (tem
, Qnil
);
1515 if (!NILP (Ffile_directory_p (program
)))
1516 error ("Specified program for new process is a directory");
1520 /* Remove "/:" from TEM. */
1521 tem
= remove_slash_colon (tem
);
1524 Lisp_Object arg_encoding
= Qnil
;
1525 struct gcpro gcpro1
;
1528 /* Encode the file name and put it in NEW_ARGV.
1529 That's where the child will use it to execute the program. */
1530 tem
= list1 (ENCODE_FILE (tem
));
1532 /* Here we encode arguments by the coding system used for sending
1533 data to the process. We don't support using different coding
1534 systems for encoding arguments and for encoding data sent to the
1537 for (i
= 3; i
< nargs
; i
++)
1539 tem
= Fcons (args
[i
], tem
);
1540 CHECK_STRING (XCAR (tem
));
1541 if (STRING_MULTIBYTE (XCAR (tem
)))
1543 if (NILP (arg_encoding
))
1544 arg_encoding
= (complement_process_encoding_system
1545 (XPROCESS (proc
)->encode_coding_system
));
1547 code_convert_string_norecord
1548 (XCAR (tem
), arg_encoding
, 1));
1555 /* Now that everything is encoded we can collect the strings into
1557 SAFE_NALLOCA (new_argv
, 1, nargs
- 1);
1558 new_argv
[nargs
- 2] = 0;
1560 for (i
= nargs
- 2; i
-- != 0; )
1562 new_argv
[i
] = SDATA (XCAR (tem
));
1566 create_process (proc
, (char **) new_argv
, current_dir
);
1572 return unbind_to (count
, proc
);
1575 /* This function is the unwind_protect form for Fstart_process. If
1576 PROC doesn't have its pid set, then we know someone has signaled
1577 an error and the process wasn't started successfully, so we should
1578 remove it from the process list. */
1580 start_process_unwind (Lisp_Object proc
)
1582 if (!PROCESSP (proc
))
1585 /* Was PROC started successfully?
1586 -2 is used for a pty with no process, eg for gdb. */
1587 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1588 remove_process (proc
);
1591 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1594 close_process_fd (int *fd_addr
)
1604 /* Indexes of file descriptors in open_fds. */
1607 /* The pipe from Emacs to its subprocess. */
1609 WRITE_TO_SUBPROCESS
,
1611 /* The main pipe from the subprocess to Emacs. */
1612 READ_FROM_SUBPROCESS
,
1615 /* The pipe from the subprocess to Emacs that is closed when the
1616 subprocess execs. */
1617 READ_FROM_EXEC_MONITOR
,
1621 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1624 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1626 struct Lisp_Process
*p
= XPROCESS (process
);
1627 int inchannel
, outchannel
;
1630 int forkin
, forkout
;
1632 char pty_name
[PTY_NAME_SIZE
];
1633 Lisp_Object lisp_pty_name
= Qnil
;
1636 inchannel
= outchannel
= -1;
1638 if (!NILP (Vprocess_connection_type
))
1639 outchannel
= inchannel
= allocate_pty (pty_name
);
1643 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1644 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1645 /* On most USG systems it does not work to open the pty's tty here,
1646 then close it and reopen it in the child. */
1647 /* Don't let this terminal become our controlling terminal
1648 (in case we don't have one). */
1649 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1651 report_file_error ("Opening pty", Qnil
);
1652 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1654 forkin
= forkout
= -1;
1655 #endif /* not USG, or USG_SUBTTY_WORKS */
1657 lisp_pty_name
= build_string (pty_name
);
1661 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1662 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1663 report_file_error ("Creating pipe", Qnil
);
1664 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1665 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1666 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1667 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1671 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1672 report_file_error ("Creating pipe", Qnil
);
1675 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1676 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1678 /* Record this as an active process, with its channels. */
1679 chan_process
[inchannel
] = process
;
1680 p
->infd
= inchannel
;
1681 p
->outfd
= outchannel
;
1683 /* Previously we recorded the tty descriptor used in the subprocess.
1684 It was only used for getting the foreground tty process, so now
1685 we just reopen the device (see emacs_get_tty_pgrp) as this is
1686 more portable (see USG_SUBTTY_WORKS above). */
1688 p
->pty_flag
= pty_flag
;
1689 pset_status (p
, Qrun
);
1691 FD_SET (inchannel
, &input_wait_mask
);
1692 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1693 if (inchannel
> max_process_desc
)
1694 max_process_desc
= inchannel
;
1696 /* This may signal an error. */
1697 setup_process_coding_systems (process
);
1700 block_child_signal (&oldset
);
1703 /* vfork, and prevent local vars from being clobbered by the vfork. */
1705 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1706 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1707 char **volatile new_argv_volatile
= new_argv
;
1708 int volatile forkin_volatile
= forkin
;
1709 int volatile forkout_volatile
= forkout
;
1710 struct Lisp_Process
*p_volatile
= p
;
1714 current_dir
= current_dir_volatile
;
1715 lisp_pty_name
= lisp_pty_name_volatile
;
1716 new_argv
= new_argv_volatile
;
1717 forkin
= forkin_volatile
;
1718 forkout
= forkout_volatile
;
1721 pty_flag
= p
->pty_flag
;
1725 #endif /* not WINDOWSNT */
1727 int xforkin
= forkin
;
1728 int xforkout
= forkout
;
1730 /* Make the pty be the controlling terminal of the process. */
1732 /* First, disconnect its current controlling terminal. */
1733 /* We tried doing setsid only if pty_flag, but it caused
1734 process_set_signal to fail on SGI when using a pipe. */
1736 /* Make the pty's terminal the controlling terminal. */
1737 if (pty_flag
&& xforkin
>= 0)
1740 /* We ignore the return value
1741 because faith@cs.unc.edu says that is necessary on Linux. */
1742 ioctl (xforkin
, TIOCSCTTY
, 0);
1745 #if defined (LDISC1)
1746 if (pty_flag
&& xforkin
>= 0)
1749 tcgetattr (xforkin
, &t
);
1751 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1752 emacs_perror ("create_process/tcsetattr LDISC1");
1755 #if defined (NTTYDISC) && defined (TIOCSETD)
1756 if (pty_flag
&& xforkin
>= 0)
1758 /* Use new line discipline. */
1759 int ldisc
= NTTYDISC
;
1760 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1765 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1766 can do TIOCSPGRP only to the process's controlling tty. */
1769 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1770 I can't test it since I don't have 4.3. */
1771 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1774 ioctl (j
, TIOCNOTTY
, 0);
1778 #endif /* TIOCNOTTY */
1780 #if !defined (DONT_REOPEN_PTY)
1781 /*** There is a suggestion that this ought to be a
1782 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1783 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1784 that system does seem to need this code, even though
1785 both TIOCSCTTY is defined. */
1786 /* Now close the pty (if we had it open) and reopen it.
1787 This makes the pty the controlling terminal of the subprocess. */
1791 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1794 emacs_close (xforkin
);
1795 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1799 emacs_perror (SSDATA (lisp_pty_name
));
1800 _exit (EXIT_CANCELED
);
1804 #endif /* not DONT_REOPEN_PTY */
1806 #ifdef SETUP_SLAVE_PTY
1811 #endif /* SETUP_SLAVE_PTY */
1812 #endif /* HAVE_PTYS */
1814 signal (SIGINT
, SIG_DFL
);
1815 signal (SIGQUIT
, SIG_DFL
);
1817 signal (SIGPROF
, SIG_DFL
);
1820 /* Emacs ignores SIGPIPE, but the child should not. */
1821 signal (SIGPIPE
, SIG_DFL
);
1823 /* Stop blocking SIGCHLD in the child. */
1824 unblock_child_signal (&oldset
);
1827 child_setup_tty (xforkout
);
1829 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1830 #else /* not WINDOWSNT */
1831 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1832 #endif /* not WINDOWSNT */
1835 /* Back in the parent process. */
1837 vfork_errno
= errno
;
1842 /* Stop blocking in the parent. */
1843 unblock_child_signal (&oldset
);
1847 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1850 /* vfork succeeded. */
1852 /* Close the pipe ends that the child uses, or the child's pty. */
1853 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1854 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1857 register_child (pid
, inchannel
);
1858 #endif /* WINDOWSNT */
1860 pset_tty_name (p
, lisp_pty_name
);
1863 /* Wait for child_setup to complete in case that vfork is
1864 actually defined as fork. The descriptor
1865 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1866 of a pipe is closed at the child side either by close-on-exec
1867 on successful execve or the _exit call in child_setup. */
1871 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1872 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
1873 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
1880 create_pty (Lisp_Object process
)
1882 struct Lisp_Process
*p
= XPROCESS (process
);
1883 char pty_name
[PTY_NAME_SIZE
];
1884 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
1888 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
1889 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1890 /* On most USG systems it does not work to open the pty's tty here,
1891 then close it and reopen it in the child. */
1892 /* Don't let this terminal become our controlling terminal
1893 (in case we don't have one). */
1894 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1896 report_file_error ("Opening pty", Qnil
);
1897 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
1898 #if defined (DONT_REOPEN_PTY)
1899 /* In the case that vfork is defined as fork, the parent process
1900 (Emacs) may send some data before the child process completes
1901 tty options setup. So we setup tty before forking. */
1902 child_setup_tty (forkout
);
1903 #endif /* DONT_REOPEN_PTY */
1904 #endif /* not USG, or USG_SUBTTY_WORKS */
1906 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
1908 /* Record this as an active process, with its channels.
1909 As a result, child_setup will close Emacs's side of the pipes. */
1910 chan_process
[pty_fd
] = process
;
1914 /* Previously we recorded the tty descriptor used in the subprocess.
1915 It was only used for getting the foreground tty process, so now
1916 we just reopen the device (see emacs_get_tty_pgrp) as this is
1917 more portable (see USG_SUBTTY_WORKS above). */
1920 pset_status (p
, Qrun
);
1921 setup_process_coding_systems (process
);
1923 FD_SET (pty_fd
, &input_wait_mask
);
1924 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
1925 if (pty_fd
> max_process_desc
)
1926 max_process_desc
= pty_fd
;
1928 pset_tty_name (p
, build_string (pty_name
));
1935 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1936 The address family of sa is not included in the result. */
1939 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
1941 Lisp_Object address
;
1944 register struct Lisp_Vector
*p
;
1946 /* Workaround for a bug in getsockname on BSD: Names bound to
1947 sockets in the UNIX domain are inaccessible; getsockname returns
1948 a zero length name. */
1949 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
1950 return empty_unibyte_string
;
1952 switch (sa
->sa_family
)
1956 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
1957 len
= sizeof (sin
->sin_addr
) + 1;
1958 address
= Fmake_vector (make_number (len
), Qnil
);
1959 p
= XVECTOR (address
);
1960 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
1961 cp
= (unsigned char *) &sin
->sin_addr
;
1967 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
1968 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
1969 len
= sizeof (sin6
->sin6_addr
) / 2 + 1;
1970 address
= Fmake_vector (make_number (len
), Qnil
);
1971 p
= XVECTOR (address
);
1972 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
1973 for (i
= 0; i
< len
; i
++)
1974 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
1978 #ifdef HAVE_LOCAL_SOCKETS
1981 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
1982 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
1983 /* If the first byte is NUL, the name is a Linux abstract
1984 socket name, and the name can contain embedded NULs. If
1985 it's not, we have a NUL-terminated string. Be careful not
1986 to walk past the end of the object looking for the name
1987 terminator, however. */
1988 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
1990 const char *terminator
1991 = memchr (sockun
->sun_path
, '\0', name_length
);
1994 name_length
= terminator
- (const char *) sockun
->sun_path
;
1997 return make_unibyte_string (sockun
->sun_path
, name_length
);
2001 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2002 address
= Fcons (make_number (sa
->sa_family
),
2003 Fmake_vector (make_number (len
), Qnil
));
2004 p
= XVECTOR (XCDR (address
));
2005 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2011 p
->contents
[i
++] = make_number (*cp
++);
2017 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2020 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2022 register struct Lisp_Vector
*p
;
2024 if (VECTORP (address
))
2026 p
= XVECTOR (address
);
2027 if (p
->header
.size
== 5)
2030 return sizeof (struct sockaddr_in
);
2033 else if (p
->header
.size
== 9)
2035 *familyp
= AF_INET6
;
2036 return sizeof (struct sockaddr_in6
);
2040 #ifdef HAVE_LOCAL_SOCKETS
2041 else if (STRINGP (address
))
2043 *familyp
= AF_LOCAL
;
2044 return sizeof (struct sockaddr_un
);
2047 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2048 && VECTORP (XCDR (address
)))
2050 struct sockaddr
*sa
;
2051 p
= XVECTOR (XCDR (address
));
2052 if (MAX_ALLOCA
- sizeof sa
->sa_family
< p
->header
.size
)
2054 *familyp
= XINT (XCAR (address
));
2055 return p
->header
.size
+ sizeof (sa
->sa_family
);
2060 /* Convert an address object (vector or string) to an internal sockaddr.
2062 The address format has been basically validated by
2063 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2064 it could have come from user data. So if FAMILY is not valid,
2065 we return after zeroing *SA. */
2068 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2070 register struct Lisp_Vector
*p
;
2071 register unsigned char *cp
= NULL
;
2075 memset (sa
, 0, len
);
2077 if (VECTORP (address
))
2079 p
= XVECTOR (address
);
2080 if (family
== AF_INET
)
2082 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2083 len
= sizeof (sin
->sin_addr
) + 1;
2084 hostport
= XINT (p
->contents
[--len
]);
2085 sin
->sin_port
= htons (hostport
);
2086 cp
= (unsigned char *)&sin
->sin_addr
;
2087 sa
->sa_family
= family
;
2090 else if (family
== AF_INET6
)
2092 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2093 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2094 len
= sizeof (sin6
->sin6_addr
) + 1;
2095 hostport
= XINT (p
->contents
[--len
]);
2096 sin6
->sin6_port
= htons (hostport
);
2097 for (i
= 0; i
< len
; i
++)
2098 if (INTEGERP (p
->contents
[i
]))
2100 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2103 sa
->sa_family
= family
;
2110 else if (STRINGP (address
))
2112 #ifdef HAVE_LOCAL_SOCKETS
2113 if (family
== AF_LOCAL
)
2115 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2116 cp
= SDATA (address
);
2117 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2118 sockun
->sun_path
[i
] = *cp
++;
2119 sa
->sa_family
= family
;
2126 p
= XVECTOR (XCDR (address
));
2127 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2130 for (i
= 0; i
< len
; i
++)
2131 if (INTEGERP (p
->contents
[i
]))
2132 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2135 #ifdef DATAGRAM_SOCKETS
2136 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2138 doc
: /* Get the current datagram address associated with PROCESS. */)
2139 (Lisp_Object process
)
2143 CHECK_PROCESS (process
);
2145 if (!DATAGRAM_CONN_P (process
))
2148 channel
= XPROCESS (process
)->infd
;
2149 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2150 datagram_address
[channel
].len
);
2153 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2155 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2156 Returns nil upon error setting address, ADDRESS otherwise. */)
2157 (Lisp_Object process
, Lisp_Object address
)
2162 CHECK_PROCESS (process
);
2164 if (!DATAGRAM_CONN_P (process
))
2167 channel
= XPROCESS (process
)->infd
;
2169 len
= get_lisp_to_sockaddr_size (address
, &family
);
2170 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2172 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2178 static const struct socket_options
{
2179 /* The name of this option. Should be lowercase version of option
2180 name without SO_ prefix. */
2182 /* Option level SOL_... */
2184 /* Option number SO_... */
2186 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2187 enum { OPIX_NONE
= 0, OPIX_MISC
= 1, OPIX_REUSEADDR
= 2 } optbit
;
2188 } socket_options
[] =
2190 #ifdef SO_BINDTODEVICE
2191 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2194 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2197 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2200 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2203 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2206 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2209 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2212 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2214 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2217 /* Set option OPT to value VAL on socket S.
2219 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2220 Signals an error if setting a known option fails.
2224 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2227 const struct socket_options
*sopt
;
2232 name
= SSDATA (SYMBOL_NAME (opt
));
2233 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2234 if (strcmp (name
, sopt
->name
) == 0)
2237 switch (sopt
->opttype
)
2242 optval
= NILP (val
) ? 0 : 1;
2243 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2244 &optval
, sizeof (optval
));
2251 if (TYPE_RANGED_INTEGERP (int, val
))
2252 optval
= XINT (val
);
2254 error ("Bad option value for %s", name
);
2255 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2256 &optval
, sizeof (optval
));
2260 #ifdef SO_BINDTODEVICE
2263 char devname
[IFNAMSIZ
+ 1];
2265 /* This is broken, at least in the Linux 2.4 kernel.
2266 To unbind, the arg must be a zero integer, not the empty string.
2267 This should work on all systems. KFS. 2003-09-23. */
2268 memset (devname
, 0, sizeof devname
);
2271 char *arg
= SSDATA (val
);
2272 int len
= min (strlen (arg
), IFNAMSIZ
);
2273 memcpy (devname
, arg
, len
);
2275 else if (!NILP (val
))
2276 error ("Bad option value for %s", name
);
2277 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2286 struct linger linger
;
2289 linger
.l_linger
= 0;
2290 if (TYPE_RANGED_INTEGERP (int, val
))
2291 linger
.l_linger
= XINT (val
);
2293 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2294 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2295 &linger
, sizeof (linger
));
2306 int setsockopt_errno
= errno
;
2307 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2311 return (1 << sopt
->optbit
);
2315 DEFUN ("set-network-process-option",
2316 Fset_network_process_option
, Sset_network_process_option
,
2318 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2319 See `make-network-process' for a list of options and values.
2320 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2321 OPTION is not a supported option, return nil instead; otherwise return t. */)
2322 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2325 struct Lisp_Process
*p
;
2327 CHECK_PROCESS (process
);
2328 p
= XPROCESS (process
);
2329 if (!NETCONN1_P (p
))
2330 error ("Process is not a network process");
2334 error ("Process is not running");
2336 if (set_socket_option (s
, option
, value
))
2338 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2342 if (NILP (no_error
))
2343 error ("Unknown or unsupported option");
2349 DEFUN ("serial-process-configure",
2350 Fserial_process_configure
,
2351 Sserial_process_configure
,
2353 doc
: /* Configure speed, bytesize, etc. of a serial process.
2355 Arguments are specified as keyword/argument pairs. Attributes that
2356 are not given are re-initialized from the process's current
2357 configuration (available via the function `process-contact') or set to
2358 reasonable default values. The following arguments are defined:
2364 -- Any of these arguments can be given to identify the process that is
2365 to be configured. If none of these arguments is given, the current
2366 buffer's process is used.
2368 :speed SPEED -- SPEED is the speed of the serial port in bits per
2369 second, also called baud rate. Any value can be given for SPEED, but
2370 most serial ports work only at a few defined values between 1200 and
2371 115200, with 9600 being the most common value. If SPEED is nil, the
2372 serial port is not configured any further, i.e., all other arguments
2373 are ignored. This may be useful for special serial ports such as
2374 Bluetooth-to-serial converters which can only be configured through AT
2375 commands. A value of nil for SPEED can be used only when passed
2376 through `make-serial-process' or `serial-term'.
2378 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2379 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2381 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2382 `odd' (use odd parity), or the symbol `even' (use even parity). If
2383 PARITY is not given, no parity is used.
2385 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2386 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2387 is not given or nil, 1 stopbit is used.
2389 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2390 flowcontrol to be used, which is either nil (don't use flowcontrol),
2391 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2392 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2393 flowcontrol is used.
2395 `serial-process-configure' is called by `make-serial-process' for the
2396 initial configuration of the serial port.
2400 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2402 \(serial-process-configure
2403 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2405 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2407 usage: (serial-process-configure &rest ARGS) */)
2408 (ptrdiff_t nargs
, Lisp_Object
*args
)
2410 struct Lisp_Process
*p
;
2411 Lisp_Object contact
= Qnil
;
2412 Lisp_Object proc
= Qnil
;
2413 struct gcpro gcpro1
;
2415 contact
= Flist (nargs
, args
);
2418 proc
= Fplist_get (contact
, QCprocess
);
2420 proc
= Fplist_get (contact
, QCname
);
2422 proc
= Fplist_get (contact
, QCbuffer
);
2424 proc
= Fplist_get (contact
, QCport
);
2425 proc
= get_process (proc
);
2426 p
= XPROCESS (proc
);
2427 if (!EQ (p
->type
, Qserial
))
2428 error ("Not a serial process");
2430 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2436 serial_configure (p
, contact
);
2442 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2444 doc
: /* Create and return a serial port process.
2446 In Emacs, serial port connections are represented by process objects,
2447 so input and output work as for subprocesses, and `delete-process'
2448 closes a serial port connection. However, a serial process has no
2449 process id, it cannot be signaled, and the status codes are different
2450 from normal processes.
2452 `make-serial-process' creates a process and a buffer, on which you
2453 probably want to use `process-send-string'. Try \\[serial-term] for
2454 an interactive terminal. See below for examples.
2456 Arguments are specified as keyword/argument pairs. The following
2457 arguments are defined:
2459 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2460 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2461 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2462 the backslashes in strings).
2464 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2465 which this function calls.
2467 :name NAME -- NAME is the name of the process. If NAME is not given,
2468 the value of PORT is used.
2470 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2471 with the process. Process output goes at the end of that buffer,
2472 unless you specify an output stream or filter function to handle the
2473 output. If BUFFER is not given, the value of NAME is used.
2475 :coding CODING -- If CODING is a symbol, it specifies the coding
2476 system used for both reading and writing for this process. If CODING
2477 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2478 ENCODING is used for writing.
2480 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2481 the process is running. If BOOL is not given, query before exiting.
2483 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2484 In the stopped state, a serial process does not accept incoming data,
2485 but you can send outgoing data. The stopped state is cleared by
2486 `continue-process' and set by `stop-process'.
2488 :filter FILTER -- Install FILTER as the process filter.
2490 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2492 :plist PLIST -- Install PLIST as the initial plist of the process.
2498 -- This function calls `serial-process-configure' to handle these
2501 The original argument list, possibly modified by later configuration,
2502 is available via the function `process-contact'.
2506 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2508 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2510 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2512 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2514 usage: (make-serial-process &rest ARGS) */)
2515 (ptrdiff_t nargs
, Lisp_Object
*args
)
2518 Lisp_Object proc
, contact
, port
;
2519 struct Lisp_Process
*p
;
2520 struct gcpro gcpro1
;
2521 Lisp_Object name
, buffer
;
2522 Lisp_Object tem
, val
;
2523 ptrdiff_t specpdl_count
;
2528 contact
= Flist (nargs
, args
);
2531 port
= Fplist_get (contact
, QCport
);
2533 error ("No port specified");
2534 CHECK_STRING (port
);
2536 if (NILP (Fplist_member (contact
, QCspeed
)))
2537 error (":speed not specified");
2538 if (!NILP (Fplist_get (contact
, QCspeed
)))
2539 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2541 name
= Fplist_get (contact
, QCname
);
2544 CHECK_STRING (name
);
2545 proc
= make_process (name
);
2546 specpdl_count
= SPECPDL_INDEX ();
2547 record_unwind_protect (remove_process
, proc
);
2548 p
= XPROCESS (proc
);
2550 fd
= serial_open (port
);
2551 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2554 if (fd
> max_process_desc
)
2555 max_process_desc
= fd
;
2556 chan_process
[fd
] = proc
;
2558 buffer
= Fplist_get (contact
, QCbuffer
);
2561 buffer
= Fget_buffer_create (buffer
);
2562 pset_buffer (p
, buffer
);
2564 pset_childp (p
, contact
);
2565 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2566 pset_type (p
, Qserial
);
2567 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2568 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2570 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2571 p
->kill_without_query
= 1;
2572 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2573 pset_command (p
, Qt
);
2574 eassert (! p
->pty_flag
);
2576 if (!EQ (p
->command
, Qt
))
2578 FD_SET (fd
, &input_wait_mask
);
2579 FD_SET (fd
, &non_keyboard_wait_mask
);
2582 if (BUFFERP (buffer
))
2584 set_marker_both (p
->mark
, buffer
,
2585 BUF_ZV (XBUFFER (buffer
)),
2586 BUF_ZV_BYTE (XBUFFER (buffer
)));
2589 tem
= Fplist_member (contact
, QCcoding
);
2590 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2596 val
= XCAR (XCDR (tem
));
2600 else if (!NILP (Vcoding_system_for_read
))
2601 val
= Vcoding_system_for_read
;
2602 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2603 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2605 pset_decode_coding_system (p
, val
);
2610 val
= XCAR (XCDR (tem
));
2614 else if (!NILP (Vcoding_system_for_write
))
2615 val
= Vcoding_system_for_write
;
2616 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2617 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2619 pset_encode_coding_system (p
, val
);
2621 setup_process_coding_systems (proc
);
2622 pset_decoding_buf (p
, empty_unibyte_string
);
2623 p
->decoding_carryover
= 0;
2624 pset_encoding_buf (p
, empty_unibyte_string
);
2625 p
->inherit_coding_system_flag
2626 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2628 Fserial_process_configure (nargs
, args
);
2630 specpdl_ptr
= specpdl
+ specpdl_count
;
2636 /* Create a network stream/datagram client/server process. Treated
2637 exactly like a normal process when reading and writing. Primary
2638 differences are in status display and process deletion. A network
2639 connection has no PID; you cannot signal it. All you can do is
2640 stop/continue it and deactivate/close it via delete-process. */
2642 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2644 doc
: /* Create and return a network server or client process.
2646 In Emacs, network connections are represented by process objects, so
2647 input and output work as for subprocesses and `delete-process' closes
2648 a network connection. However, a network process has no process id,
2649 it cannot be signaled, and the status codes are different from normal
2652 Arguments are specified as keyword/argument pairs. The following
2653 arguments are defined:
2655 :name NAME -- NAME is name for process. It is modified if necessary
2658 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2659 with the process. Process output goes at end of that buffer, unless
2660 you specify an output stream or filter function to handle the output.
2661 BUFFER may be also nil, meaning that this process is not associated
2664 :host HOST -- HOST is name of the host to connect to, or its IP
2665 address. The symbol `local' specifies the local host. If specified
2666 for a server process, it must be a valid name or address for the local
2667 host, and only clients connecting to that address will be accepted.
2669 :service SERVICE -- SERVICE is name of the service desired, or an
2670 integer specifying a port number to connect to. If SERVICE is t,
2671 a random port number is selected for the server. (If Emacs was
2672 compiled with getaddrinfo, a port number can also be specified as a
2673 string, e.g. "80", as well as an integer. This is not portable.)
2675 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2676 stream type connection, `datagram' creates a datagram type connection,
2677 `seqpacket' creates a reliable datagram connection.
2679 :family FAMILY -- FAMILY is the address (and protocol) family for the
2680 service specified by HOST and SERVICE. The default (nil) is to use
2681 whatever address family (IPv4 or IPv6) that is defined for the host
2682 and port number specified by HOST and SERVICE. Other address families
2684 local -- for a local (i.e. UNIX) address specified by SERVICE.
2685 ipv4 -- use IPv4 address family only.
2686 ipv6 -- use IPv6 address family only.
2688 :local ADDRESS -- ADDRESS is the local address used for the connection.
2689 This parameter is ignored when opening a client process. When specified
2690 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2692 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2693 connection. This parameter is ignored when opening a stream server
2694 process. For a datagram server process, it specifies the initial
2695 setting of the remote datagram address. When specified for a client
2696 process, the FAMILY, HOST, and SERVICE args are ignored.
2698 The format of ADDRESS depends on the address family:
2699 - An IPv4 address is represented as an vector of integers [A B C D P]
2700 corresponding to numeric IP address A.B.C.D and port number P.
2701 - A local address is represented as a string with the address in the
2702 local address space.
2703 - An "unsupported family" address is represented by a cons (F . AV)
2704 where F is the family number and AV is a vector containing the socket
2705 address data with one element per address data byte. Do not rely on
2706 this format in portable code, as it may depend on implementation
2707 defined constants, data sizes, and data structure alignment.
2709 :coding CODING -- If CODING is a symbol, it specifies the coding
2710 system used for both reading and writing for this process. If CODING
2711 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2712 ENCODING is used for writing.
2714 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2715 return without waiting for the connection to complete; instead, the
2716 sentinel function will be called with second arg matching "open" (if
2717 successful) or "failed" when the connect completes. Default is to use
2718 a blocking connect (i.e. wait) for stream type connections.
2720 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2721 running when Emacs is exited.
2723 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2724 In the stopped state, a server process does not accept new
2725 connections, and a client process does not handle incoming traffic.
2726 The stopped state is cleared by `continue-process' and set by
2729 :filter FILTER -- Install FILTER as the process filter.
2731 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2732 process filter are multibyte, otherwise they are unibyte.
2733 If this keyword is not specified, the strings are multibyte if
2734 the default value of `enable-multibyte-characters' is non-nil.
2736 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2738 :log LOG -- Install LOG as the server process log function. This
2739 function is called when the server accepts a network connection from a
2740 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2741 is the server process, CLIENT is the new process for the connection,
2742 and MESSAGE is a string.
2744 :plist PLIST -- Install PLIST as the new process's initial plist.
2746 :server QLEN -- if QLEN is non-nil, create a server process for the
2747 specified FAMILY, SERVICE, and connection type (stream or datagram).
2748 If QLEN is an integer, it is used as the max. length of the server's
2749 pending connection queue (also known as the backlog); the default
2750 queue length is 5. Default is to create a client process.
2752 The following network options can be specified for this connection:
2754 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2755 :dontroute BOOL -- Only send to directly connected hosts.
2756 :keepalive BOOL -- Send keep-alive messages on network stream.
2757 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2758 :oobinline BOOL -- Place out-of-band data in receive data stream.
2759 :priority INT -- Set protocol defined priority for sent packets.
2760 :reuseaddr BOOL -- Allow reusing a recently used local address
2761 (this is allowed by default for a server process).
2762 :bindtodevice NAME -- bind to interface NAME. Using this may require
2763 special privileges on some systems.
2765 Consult the relevant system programmer's manual pages for more
2766 information on using these options.
2769 A server process will listen for and accept connections from clients.
2770 When a client connection is accepted, a new network process is created
2771 for the connection with the following parameters:
2773 - The client's process name is constructed by concatenating the server
2774 process's NAME and a client identification string.
2775 - If the FILTER argument is non-nil, the client process will not get a
2776 separate process buffer; otherwise, the client's process buffer is a newly
2777 created buffer named after the server process's BUFFER name or process
2778 NAME concatenated with the client identification string.
2779 - The connection type and the process filter and sentinel parameters are
2780 inherited from the server process's TYPE, FILTER and SENTINEL.
2781 - The client process's contact info is set according to the client's
2782 addressing information (typically an IP address and a port number).
2783 - The client process's plist is initialized from the server's plist.
2785 Notice that the FILTER and SENTINEL args are never used directly by
2786 the server process. Also, the BUFFER argument is not used directly by
2787 the server process, but via the optional :log function, accepted (and
2788 failed) connections may be logged in the server process's buffer.
2790 The original argument list, modified with the actual connection
2791 information, is available via the `process-contact' function.
2793 usage: (make-network-process &rest ARGS) */)
2794 (ptrdiff_t nargs
, Lisp_Object
*args
)
2797 Lisp_Object contact
;
2798 struct Lisp_Process
*p
;
2799 #ifdef HAVE_GETADDRINFO
2800 struct addrinfo ai
, *res
, *lres
;
2801 struct addrinfo hints
;
2802 const char *portstring
;
2804 #else /* HAVE_GETADDRINFO */
2805 struct _emacs_addrinfo
2811 struct sockaddr
*ai_addr
;
2812 struct _emacs_addrinfo
*ai_next
;
2814 #endif /* HAVE_GETADDRINFO */
2815 struct sockaddr_in address_in
;
2816 #ifdef HAVE_LOCAL_SOCKETS
2817 struct sockaddr_un address_un
;
2822 int s
= -1, outch
, inch
;
2823 struct gcpro gcpro1
;
2824 ptrdiff_t count
= SPECPDL_INDEX ();
2826 Lisp_Object colon_address
; /* Either QClocal or QCremote. */
2828 Lisp_Object name
, buffer
, host
, service
, address
;
2829 Lisp_Object filter
, sentinel
;
2830 bool is_non_blocking_client
= 0;
2839 /* Save arguments for process-contact and clone-process. */
2840 contact
= Flist (nargs
, args
);
2844 /* Ensure socket support is loaded if available. */
2845 init_winsock (TRUE
);
2848 /* :type TYPE (nil: stream, datagram */
2849 tem
= Fplist_get (contact
, QCtype
);
2851 socktype
= SOCK_STREAM
;
2852 #ifdef DATAGRAM_SOCKETS
2853 else if (EQ (tem
, Qdatagram
))
2854 socktype
= SOCK_DGRAM
;
2856 #ifdef HAVE_SEQPACKET
2857 else if (EQ (tem
, Qseqpacket
))
2858 socktype
= SOCK_SEQPACKET
;
2861 error ("Unsupported connection type");
2864 tem
= Fplist_get (contact
, QCserver
);
2867 /* Don't support network sockets when non-blocking mode is
2868 not available, since a blocked Emacs is not useful. */
2870 if (TYPE_RANGED_INTEGERP (int, tem
))
2871 backlog
= XINT (tem
);
2874 /* Make colon_address an alias for :local (server) or :remote (client). */
2875 colon_address
= is_server
? QClocal
: QCremote
;
2878 if (!is_server
&& socktype
!= SOCK_DGRAM
2879 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2881 #ifndef NON_BLOCKING_CONNECT
2882 error ("Non-blocking connect not supported");
2884 is_non_blocking_client
= 1;
2888 name
= Fplist_get (contact
, QCname
);
2889 buffer
= Fplist_get (contact
, QCbuffer
);
2890 filter
= Fplist_get (contact
, QCfilter
);
2891 sentinel
= Fplist_get (contact
, QCsentinel
);
2893 CHECK_STRING (name
);
2895 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2896 ai
.ai_socktype
= socktype
;
2901 /* :local ADDRESS or :remote ADDRESS */
2902 address
= Fplist_get (contact
, colon_address
);
2903 if (!NILP (address
))
2905 host
= service
= Qnil
;
2907 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2908 error ("Malformed :address");
2909 ai
.ai_family
= family
;
2910 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2911 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
2915 /* :family FAMILY -- nil (for Inet), local, or integer. */
2916 tem
= Fplist_get (contact
, QCfamily
);
2919 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2925 #ifdef HAVE_LOCAL_SOCKETS
2926 else if (EQ (tem
, Qlocal
))
2930 else if (EQ (tem
, Qipv6
))
2933 else if (EQ (tem
, Qipv4
))
2935 else if (TYPE_RANGED_INTEGERP (int, tem
))
2936 family
= XINT (tem
);
2938 error ("Unknown address family");
2940 ai
.ai_family
= family
;
2942 /* :service SERVICE -- string, integer (port number), or t (random port). */
2943 service
= Fplist_get (contact
, QCservice
);
2945 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2946 host
= Fplist_get (contact
, QChost
);
2949 if (EQ (host
, Qlocal
))
2950 /* Depending on setup, "localhost" may map to different IPv4 and/or
2951 IPv6 addresses, so it's better to be explicit (Bug#6781). */
2952 host
= build_string ("127.0.0.1");
2953 CHECK_STRING (host
);
2956 #ifdef HAVE_LOCAL_SOCKETS
2957 if (family
== AF_LOCAL
)
2961 message (":family local ignores the :host \"%s\" property",
2963 contact
= Fplist_put (contact
, QChost
, Qnil
);
2966 CHECK_STRING (service
);
2967 memset (&address_un
, 0, sizeof address_un
);
2968 address_un
.sun_family
= AF_LOCAL
;
2969 if (sizeof address_un
.sun_path
<= SBYTES (service
))
2970 error ("Service name too long");
2971 lispstpcpy (address_un
.sun_path
, service
);
2972 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
2973 ai
.ai_addrlen
= sizeof address_un
;
2978 /* Slow down polling to every ten seconds.
2979 Some kernels have a bug which causes retrying connect to fail
2980 after a connect. Polling can interfere with gethostbyname too. */
2981 #ifdef POLL_FOR_INPUT
2982 if (socktype
!= SOCK_DGRAM
)
2984 record_unwind_protect_void (run_all_atimers
);
2985 bind_polling_period (10);
2989 #ifdef HAVE_GETADDRINFO
2990 /* If we have a host, use getaddrinfo to resolve both host and service.
2991 Otherwise, use getservbyname to lookup the service. */
2995 /* SERVICE can either be a string or int.
2996 Convert to a C string for later use by getaddrinfo. */
2997 if (EQ (service
, Qt
))
2999 else if (INTEGERP (service
))
3001 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3002 portstring
= portbuf
;
3006 CHECK_STRING (service
);
3007 portstring
= SSDATA (service
);
3012 memset (&hints
, 0, sizeof (hints
));
3014 hints
.ai_family
= family
;
3015 hints
.ai_socktype
= socktype
;
3016 hints
.ai_protocol
= 0;
3018 #ifdef HAVE_RES_INIT
3022 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3024 #ifdef HAVE_GAI_STRERROR
3025 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3027 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3033 #endif /* HAVE_GETADDRINFO */
3035 /* We end up here if getaddrinfo is not defined, or in case no hostname
3036 has been specified (e.g. for a local server process). */
3038 if (EQ (service
, Qt
))
3040 else if (INTEGERP (service
))
3041 port
= htons ((unsigned short) XINT (service
));
3044 struct servent
*svc_info
;
3045 CHECK_STRING (service
);
3046 svc_info
= getservbyname (SSDATA (service
),
3047 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3049 error ("Unknown service: %s", SDATA (service
));
3050 port
= svc_info
->s_port
;
3053 memset (&address_in
, 0, sizeof address_in
);
3054 address_in
.sin_family
= family
;
3055 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3056 address_in
.sin_port
= port
;
3058 #ifndef HAVE_GETADDRINFO
3061 struct hostent
*host_info_ptr
;
3063 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3064 as it may `hang' Emacs for a very long time. */
3068 #ifdef HAVE_RES_INIT
3072 host_info_ptr
= gethostbyname (SDATA (host
));
3077 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3078 host_info_ptr
->h_length
);
3079 family
= host_info_ptr
->h_addrtype
;
3080 address_in
.sin_family
= family
;
3083 /* Attempt to interpret host as numeric inet address. */
3085 unsigned long numeric_addr
;
3086 numeric_addr
= inet_addr (SSDATA (host
));
3087 if (numeric_addr
== -1)
3088 error ("Unknown host \"%s\"", SDATA (host
));
3090 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3091 sizeof (address_in
.sin_addr
));
3095 #endif /* not HAVE_GETADDRINFO */
3097 ai
.ai_family
= family
;
3098 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3099 ai
.ai_addrlen
= sizeof address_in
;
3103 /* Do this in case we never enter the for-loop below. */
3104 count1
= SPECPDL_INDEX ();
3107 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3116 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3124 #ifdef DATAGRAM_SOCKETS
3125 if (!is_server
&& socktype
== SOCK_DGRAM
)
3127 #endif /* DATAGRAM_SOCKETS */
3129 #ifdef NON_BLOCKING_CONNECT
3130 if (is_non_blocking_client
)
3132 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3143 /* Make us close S if quit. */
3144 record_unwind_protect_int (close_file_unwind
, s
);
3146 /* Parse network options in the arg list.
3147 We simply ignore anything which isn't a known option (including other keywords).
3148 An error is signaled if setting a known option fails. */
3149 for (optn
= optbits
= 0; optn
< nargs
- 1; optn
+= 2)
3150 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+ 1]);
3154 /* Configure as a server socket. */
3156 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3157 explicit :reuseaddr key to override this. */
3158 #ifdef HAVE_LOCAL_SOCKETS
3159 if (family
!= AF_LOCAL
)
3161 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3164 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3165 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3168 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3169 report_file_error ("Cannot bind server socket", Qnil
);
3171 #ifdef HAVE_GETSOCKNAME
3172 if (EQ (service
, Qt
))
3174 struct sockaddr_in sa1
;
3175 socklen_t len1
= sizeof (sa1
);
3176 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3178 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3179 service
= make_number (ntohs (sa1
.sin_port
));
3180 contact
= Fplist_put (contact
, QCservice
, service
);
3185 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3186 report_file_error ("Cannot listen on server socket", Qnil
);
3194 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3197 if (ret
== 0 || xerrno
== EISCONN
)
3199 /* The unwind-protect will be discarded afterwards.
3200 Likewise for immediate_quit. */
3204 #ifdef NON_BLOCKING_CONNECT
3206 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3210 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3217 if (xerrno
== EINTR
)
3219 /* Unlike most other syscalls connect() cannot be called
3220 again. (That would return EALREADY.) The proper way to
3221 wait for completion is pselect(). */
3229 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3235 report_file_error ("Failed select", Qnil
);
3239 len
= sizeof xerrno
;
3240 eassert (FD_ISSET (s
, &fdset
));
3241 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3242 report_file_error ("Failed getsockopt", Qnil
);
3244 report_file_errno ("Failed connect", Qnil
, xerrno
);
3247 #endif /* !WINDOWSNT */
3251 /* Discard the unwind protect closing S. */
3252 specpdl_ptr
= specpdl
+ count1
;
3257 if (xerrno
== EINTR
)
3264 #ifdef DATAGRAM_SOCKETS
3265 if (socktype
== SOCK_DGRAM
)
3267 if (datagram_address
[s
].sa
)
3269 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3270 datagram_address
[s
].len
= lres
->ai_addrlen
;
3274 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3275 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3278 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3279 if (rlen
!= 0 && rfamily
== lres
->ai_family
3280 && rlen
== lres
->ai_addrlen
)
3281 conv_lisp_to_sockaddr (rfamily
, remote
,
3282 datagram_address
[s
].sa
, rlen
);
3286 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3289 contact
= Fplist_put (contact
, colon_address
,
3290 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3291 #ifdef HAVE_GETSOCKNAME
3294 struct sockaddr_in sa1
;
3295 socklen_t len1
= sizeof (sa1
);
3296 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3297 contact
= Fplist_put (contact
, QClocal
,
3298 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3305 #ifdef HAVE_GETADDRINFO
3316 /* If non-blocking got this far - and failed - assume non-blocking is
3317 not supported after all. This is probably a wrong assumption, but
3318 the normal blocking calls to open-network-stream handles this error
3320 if (is_non_blocking_client
)
3323 report_file_errno ((is_server
3324 ? "make server process failed"
3325 : "make client process failed"),
3333 buffer
= Fget_buffer_create (buffer
);
3334 proc
= make_process (name
);
3336 chan_process
[inch
] = proc
;
3338 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3340 p
= XPROCESS (proc
);
3342 pset_childp (p
, contact
);
3343 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3344 pset_type (p
, Qnetwork
);
3346 pset_buffer (p
, buffer
);
3347 pset_sentinel (p
, sentinel
);
3348 pset_filter (p
, filter
);
3349 pset_log (p
, Fplist_get (contact
, QClog
));
3350 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3351 p
->kill_without_query
= 1;
3352 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3353 pset_command (p
, Qt
);
3356 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3360 /* Discard the unwind protect for closing S, if any. */
3361 specpdl_ptr
= specpdl
+ count1
;
3363 /* Unwind bind_polling_period and request_sigio. */
3364 unbind_to (count
, Qnil
);
3366 if (is_server
&& socktype
!= SOCK_DGRAM
)
3367 pset_status (p
, Qlisten
);
3369 /* Make the process marker point into the process buffer (if any). */
3370 if (BUFFERP (buffer
))
3371 set_marker_both (p
->mark
, buffer
,
3372 BUF_ZV (XBUFFER (buffer
)),
3373 BUF_ZV_BYTE (XBUFFER (buffer
)));
3375 #ifdef NON_BLOCKING_CONNECT
3376 if (is_non_blocking_client
)
3378 /* We may get here if connect did succeed immediately. However,
3379 in that case, we still need to signal this like a non-blocking
3381 pset_status (p
, Qconnect
);
3382 if (!FD_ISSET (inch
, &connect_wait_mask
))
3384 FD_SET (inch
, &connect_wait_mask
);
3385 FD_SET (inch
, &write_mask
);
3386 num_pending_connects
++;
3391 /* A server may have a client filter setting of Qt, but it must
3392 still listen for incoming connects unless it is stopped. */
3393 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3394 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3396 FD_SET (inch
, &input_wait_mask
);
3397 FD_SET (inch
, &non_keyboard_wait_mask
);
3400 if (inch
> max_process_desc
)
3401 max_process_desc
= inch
;
3403 tem
= Fplist_member (contact
, QCcoding
);
3404 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3405 tem
= Qnil
; /* No error message (too late!). */
3408 /* Setup coding systems for communicating with the network stream. */
3409 struct gcpro gcpro1
;
3410 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3411 Lisp_Object coding_systems
= Qt
;
3412 Lisp_Object fargs
[5], val
;
3416 val
= XCAR (XCDR (tem
));
3420 else if (!NILP (Vcoding_system_for_read
))
3421 val
= Vcoding_system_for_read
;
3422 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3423 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3424 /* We dare not decode end-of-line format by setting VAL to
3425 Qraw_text, because the existing Emacs Lisp libraries
3426 assume that they receive bare code including a sequence of
3431 if (NILP (host
) || NILP (service
))
3432 coding_systems
= Qnil
;
3435 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3436 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3438 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3441 if (CONSP (coding_systems
))
3442 val
= XCAR (coding_systems
);
3443 else if (CONSP (Vdefault_process_coding_system
))
3444 val
= XCAR (Vdefault_process_coding_system
);
3448 pset_decode_coding_system (p
, val
);
3452 val
= XCAR (XCDR (tem
));
3456 else if (!NILP (Vcoding_system_for_write
))
3457 val
= Vcoding_system_for_write
;
3458 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3462 if (EQ (coding_systems
, Qt
))
3464 if (NILP (host
) || NILP (service
))
3465 coding_systems
= Qnil
;
3468 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3469 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3471 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3475 if (CONSP (coding_systems
))
3476 val
= XCDR (coding_systems
);
3477 else if (CONSP (Vdefault_process_coding_system
))
3478 val
= XCDR (Vdefault_process_coding_system
);
3482 pset_encode_coding_system (p
, val
);
3484 setup_process_coding_systems (proc
);
3486 pset_decoding_buf (p
, empty_unibyte_string
);
3487 p
->decoding_carryover
= 0;
3488 pset_encoding_buf (p
, empty_unibyte_string
);
3490 p
->inherit_coding_system_flag
3491 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3498 #ifdef HAVE_NET_IF_H
3502 network_interface_list (void)
3504 struct ifconf ifconf
;
3505 struct ifreq
*ifreq
;
3507 ptrdiff_t buf_size
= 512;
3512 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3515 count
= SPECPDL_INDEX ();
3516 record_unwind_protect_int (close_file_unwind
, s
);
3520 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3521 ifconf
.ifc_buf
= buf
;
3522 ifconf
.ifc_len
= buf_size
;
3523 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3530 while (ifconf
.ifc_len
== buf_size
);
3532 res
= unbind_to (count
, Qnil
);
3533 ifreq
= ifconf
.ifc_req
;
3534 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3536 struct ifreq
*ifq
= ifreq
;
3537 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3538 #define SIZEOF_IFREQ(sif) \
3539 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3540 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3542 int len
= SIZEOF_IFREQ (ifq
);
3544 int len
= sizeof (*ifreq
);
3546 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3547 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3549 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3552 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3553 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3554 res
= Fcons (Fcons (build_string (namebuf
),
3555 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3556 sizeof (struct sockaddr
))),
3563 #endif /* SIOCGIFCONF */
3565 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3569 const char *flag_sym
;
3572 static const struct ifflag_def ifflag_table
[] = {
3576 #ifdef IFF_BROADCAST
3577 { IFF_BROADCAST
, "broadcast" },
3580 { IFF_DEBUG
, "debug" },
3583 { IFF_LOOPBACK
, "loopback" },
3585 #ifdef IFF_POINTOPOINT
3586 { IFF_POINTOPOINT
, "pointopoint" },
3589 { IFF_RUNNING
, "running" },
3592 { IFF_NOARP
, "noarp" },
3595 { IFF_PROMISC
, "promisc" },
3597 #ifdef IFF_NOTRAILERS
3598 #ifdef NS_IMPL_COCOA
3599 /* Really means smart, notrailers is obsolete. */
3600 { IFF_NOTRAILERS
, "smart" },
3602 { IFF_NOTRAILERS
, "notrailers" },
3606 { IFF_ALLMULTI
, "allmulti" },
3609 { IFF_MASTER
, "master" },
3612 { IFF_SLAVE
, "slave" },
3614 #ifdef IFF_MULTICAST
3615 { IFF_MULTICAST
, "multicast" },
3618 { IFF_PORTSEL
, "portsel" },
3620 #ifdef IFF_AUTOMEDIA
3621 { IFF_AUTOMEDIA
, "automedia" },
3624 { IFF_DYNAMIC
, "dynamic" },
3627 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress. */
3630 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3633 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit. */
3636 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit. */
3639 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit. */
3645 network_interface_info (Lisp_Object ifname
)
3648 Lisp_Object res
= Qnil
;
3653 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3654 && defined HAVE_GETIFADDRS && defined LLADDR)
3655 struct ifaddrs
*ifap
;
3658 CHECK_STRING (ifname
);
3660 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3661 error ("interface name too long");
3662 lispstpcpy (rq
.ifr_name
, ifname
);
3664 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3667 count
= SPECPDL_INDEX ();
3668 record_unwind_protect_int (close_file_unwind
, s
);
3671 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3672 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3674 int flags
= rq
.ifr_flags
;
3675 const struct ifflag_def
*fp
;
3678 /* If flags is smaller than int (i.e. short) it may have the high bit set
3679 due to IFF_MULTICAST. In that case, sign extending it into
3681 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3682 flags
= (unsigned short) rq
.ifr_flags
;
3685 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3687 if (flags
& fp
->flag_bit
)
3689 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3690 flags
-= fp
->flag_bit
;
3693 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3697 elt
= Fcons (make_number (fnum
), elt
);
3702 res
= Fcons (elt
, res
);
3705 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3706 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3708 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3709 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3713 for (n
= 0; n
< 6; n
++)
3714 p
->contents
[n
] = make_number (((unsigned char *)
3715 &rq
.ifr_hwaddr
.sa_data
[0])
3717 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3719 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3720 if (getifaddrs (&ifap
) != -1)
3722 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3723 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3726 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3728 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3729 unsigned char linkaddr
[6];
3732 if (it
->ifa_addr
->sa_family
!= AF_LINK
3733 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3734 || sdl
->sdl_alen
!= 6)
3737 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3738 for (n
= 0; n
< 6; n
++)
3739 p
->contents
[n
] = make_number (linkaddr
[n
]);
3741 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3745 #ifdef HAVE_FREEIFADDRS
3749 #endif /* HAVE_GETIFADDRS && LLADDR */
3751 res
= Fcons (elt
, res
);
3754 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3755 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3758 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3759 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3761 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3765 res
= Fcons (elt
, res
);
3768 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3769 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3772 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3775 res
= Fcons (elt
, res
);
3778 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3779 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3782 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3785 res
= Fcons (elt
, res
);
3787 return unbind_to (count
, any
? res
: Qnil
);
3789 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3790 #endif /* defined (HAVE_NET_IF_H) */
3792 DEFUN ("network-interface-list", Fnetwork_interface_list
,
3793 Snetwork_interface_list
, 0, 0, 0,
3794 doc
: /* Return an alist of all network interfaces and their network address.
3795 Each element is a cons, the car of which is a string containing the
3796 interface name, and the cdr is the network address in internal
3797 format; see the description of ADDRESS in `make-network-process'.
3799 If the information is not available, return nil. */)
3802 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3803 return network_interface_list ();
3809 DEFUN ("network-interface-info", Fnetwork_interface_info
,
3810 Snetwork_interface_info
, 1, 1, 0,
3811 doc
: /* Return information about network interface named IFNAME.
3812 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3813 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3814 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3815 FLAGS is the current flags of the interface.
3817 Data that is unavailable is returned as nil. */)
3818 (Lisp_Object ifname
)
3820 #if ((defined HAVE_NET_IF_H \
3821 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3822 || defined SIOCGIFFLAGS)) \
3823 || defined WINDOWSNT)
3824 return network_interface_info (ifname
);
3831 /* Turn off input and output for process PROC. */
3834 deactivate_process (Lisp_Object proc
)
3837 struct Lisp_Process
*p
= XPROCESS (proc
);
3841 /* Delete GnuTLS structures in PROC, if any. */
3842 emacs_gnutls_deinit (proc
);
3843 #endif /* HAVE_GNUTLS */
3845 #ifdef ADAPTIVE_READ_BUFFERING
3846 if (p
->read_output_delay
> 0)
3848 if (--process_output_delay_count
< 0)
3849 process_output_delay_count
= 0;
3850 p
->read_output_delay
= 0;
3851 p
->read_output_skip
= 0;
3855 /* Beware SIGCHLD hereabouts. */
3857 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
3858 close_process_fd (&p
->open_fd
[i
]);
3860 inchannel
= p
->infd
;
3865 #ifdef DATAGRAM_SOCKETS
3866 if (DATAGRAM_CHAN_P (inchannel
))
3868 xfree (datagram_address
[inchannel
].sa
);
3869 datagram_address
[inchannel
].sa
= 0;
3870 datagram_address
[inchannel
].len
= 0;
3873 chan_process
[inchannel
] = Qnil
;
3874 FD_CLR (inchannel
, &input_wait_mask
);
3875 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3876 #ifdef NON_BLOCKING_CONNECT
3877 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3879 FD_CLR (inchannel
, &connect_wait_mask
);
3880 FD_CLR (inchannel
, &write_mask
);
3881 if (--num_pending_connects
< 0)
3885 if (inchannel
== max_process_desc
)
3887 /* We just closed the highest-numbered process input descriptor,
3888 so recompute the highest-numbered one now. */
3892 while (0 <= i
&& NILP (chan_process
[i
]));
3894 max_process_desc
= i
;
3900 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3902 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3903 It is given to their filter functions.
3904 Optional argument PROCESS means do not return until output has been
3905 received from PROCESS.
3907 Optional second argument SECONDS and third argument MILLISEC
3908 specify a timeout; return after that much time even if there is
3909 no subprocess output. If SECONDS is a floating point number,
3910 it specifies a fractional number of seconds to wait.
3911 The MILLISEC argument is obsolete and should be avoided.
3913 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
3914 from PROCESS only, suspending reading output from other processes.
3915 If JUST-THIS-ONE is an integer, don't run any timers either.
3916 Return non-nil if we received any output from PROCESS (or, if PROCESS
3917 is nil, from any process) before the timeout expired. */)
3918 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
3923 if (! NILP (process
))
3924 CHECK_PROCESS (process
);
3926 just_this_one
= Qnil
;
3928 if (!NILP (millisec
))
3929 { /* Obsolete calling convention using integers rather than floats. */
3930 CHECK_NUMBER (millisec
);
3932 seconds
= make_float (XINT (millisec
) / 1000.0);
3935 CHECK_NUMBER (seconds
);
3936 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
3943 if (!NILP (seconds
))
3945 if (INTEGERP (seconds
))
3947 if (XINT (seconds
) > 0)
3949 secs
= XINT (seconds
);
3953 else if (FLOATP (seconds
))
3955 if (XFLOAT_DATA (seconds
) > 0)
3957 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
3958 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
3963 wrong_type_argument (Qnumberp
, seconds
);
3965 else if (! NILP (process
))
3969 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
3971 !NILP (process
) ? XPROCESS (process
) : NULL
,
3972 (NILP (just_this_one
) ? 0
3973 : !INTEGERP (just_this_one
) ? 1 : -1))
3978 /* Accept a connection for server process SERVER on CHANNEL. */
3980 static EMACS_INT connect_counter
= 0;
3983 server_accept_connection (Lisp_Object server
, int channel
)
3985 Lisp_Object proc
, caller
, name
, buffer
;
3986 Lisp_Object contact
, host
, service
;
3987 struct Lisp_Process
*ps
= XPROCESS (server
);
3988 struct Lisp_Process
*p
;
3992 struct sockaddr_in in
;
3994 struct sockaddr_in6 in6
;
3996 #ifdef HAVE_LOCAL_SOCKETS
3997 struct sockaddr_un un
;
4000 socklen_t len
= sizeof saddr
;
4003 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4012 if (code
== EWOULDBLOCK
)
4016 if (!NILP (ps
->log
))
4017 call3 (ps
->log
, server
, Qnil
,
4018 concat3 (build_string ("accept failed with code"),
4019 Fnumber_to_string (make_number (code
)),
4020 build_string ("\n")));
4024 count
= SPECPDL_INDEX ();
4025 record_unwind_protect_int (close_file_unwind
, s
);
4029 /* Setup a new process to handle the connection. */
4031 /* Generate a unique identification of the caller, and build contact
4032 information for this process. */
4035 switch (saddr
.sa
.sa_family
)
4039 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4041 AUTO_STRING (ipv4_format
, "%d.%d.%d.%d");
4042 host
= Fformat (5, ((Lisp_Object
[])
4043 { ipv4_format
, make_number (ip
[0]),
4044 make_number (ip
[1]), make_number (ip
[2]), make_number (ip
[3]) }));
4045 service
= make_number (ntohs (saddr
.in
.sin_port
));
4046 AUTO_STRING (caller_format
, " <%s:%d>");
4047 caller
= Fformat (3, (Lisp_Object
[]) {caller_format
, host
, service
});
4054 Lisp_Object args
[9];
4055 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4058 AUTO_STRING (ipv6_format
, "%x:%x:%x:%x:%x:%x:%x:%x");
4059 args
[0] = ipv6_format
;
4060 for (i
= 0; i
< 8; i
++)
4061 args
[i
+ 1] = make_number (ntohs (ip6
[i
]));
4062 host
= Fformat (9, args
);
4063 service
= make_number (ntohs (saddr
.in
.sin_port
));
4064 AUTO_STRING (caller_format
, " <[%s]:%d>");
4065 caller
= Fformat (3, (Lisp_Object
[]) {caller_format
, host
, service
});
4070 #ifdef HAVE_LOCAL_SOCKETS
4074 caller
= Fnumber_to_string (make_number (connect_counter
));
4075 AUTO_STRING (space_less_than
, " <");
4076 AUTO_STRING (greater_than
, ">");
4077 caller
= concat3 (space_less_than
, caller
, greater_than
);
4081 /* Create a new buffer name for this process if it doesn't have a
4082 filter. The new buffer name is based on the buffer name or
4083 process name of the server process concatenated with the caller
4086 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4087 || EQ (ps
->filter
, Qt
)))
4091 buffer
= ps
->buffer
;
4093 buffer
= Fbuffer_name (buffer
);
4098 buffer
= concat2 (buffer
, caller
);
4099 buffer
= Fget_buffer_create (buffer
);
4103 /* Generate a unique name for the new server process. Combine the
4104 server process name with the caller identification. */
4106 name
= concat2 (ps
->name
, caller
);
4107 proc
= make_process (name
);
4109 chan_process
[s
] = proc
;
4111 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4113 p
= XPROCESS (proc
);
4115 /* Build new contact information for this setup. */
4116 contact
= Fcopy_sequence (ps
->childp
);
4117 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4118 contact
= Fplist_put (contact
, QChost
, host
);
4119 if (!NILP (service
))
4120 contact
= Fplist_put (contact
, QCservice
, service
);
4121 contact
= Fplist_put (contact
, QCremote
,
4122 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4123 #ifdef HAVE_GETSOCKNAME
4125 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4126 contact
= Fplist_put (contact
, QClocal
,
4127 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4130 pset_childp (p
, contact
);
4131 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4132 pset_type (p
, Qnetwork
);
4134 pset_buffer (p
, buffer
);
4135 pset_sentinel (p
, ps
->sentinel
);
4136 pset_filter (p
, ps
->filter
);
4137 pset_command (p
, Qnil
);
4140 /* Discard the unwind protect for closing S. */
4141 specpdl_ptr
= specpdl
+ count
;
4143 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4146 pset_status (p
, Qrun
);
4148 /* Client processes for accepted connections are not stopped initially. */
4149 if (!EQ (p
->filter
, Qt
))
4151 FD_SET (s
, &input_wait_mask
);
4152 FD_SET (s
, &non_keyboard_wait_mask
);
4155 if (s
> max_process_desc
)
4156 max_process_desc
= s
;
4158 /* Setup coding system for new process based on server process.
4159 This seems to be the proper thing to do, as the coding system
4160 of the new process should reflect the settings at the time the
4161 server socket was opened; not the current settings. */
4163 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4164 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4165 setup_process_coding_systems (proc
);
4167 pset_decoding_buf (p
, empty_unibyte_string
);
4168 p
->decoding_carryover
= 0;
4169 pset_encoding_buf (p
, empty_unibyte_string
);
4171 p
->inherit_coding_system_flag
4172 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4174 AUTO_STRING (dash
, "-");
4175 AUTO_STRING (nl
, "\n");
4176 Lisp_Object host_string
= STRINGP (host
) ? host
: dash
;
4178 if (!NILP (ps
->log
))
4180 AUTO_STRING (accept_from
, "accept from ");
4181 call3 (ps
->log
, server
, proc
, concat3 (accept_from
, host_string
, nl
));
4184 AUTO_STRING (open_from
, "open from ");
4185 exec_sentinel (proc
, concat3 (open_from
, host_string
, nl
));
4188 /* This variable is different from waiting_for_input in keyboard.c.
4189 It is used to communicate to a lisp process-filter/sentinel (via the
4190 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4191 for user-input when that process-filter was called.
4192 waiting_for_input cannot be used as that is by definition 0 when
4193 lisp code is being evalled.
4194 This is also used in record_asynch_buffer_change.
4195 For that purpose, this must be 0
4196 when not inside wait_reading_process_output. */
4197 static int waiting_for_user_input_p
;
4200 wait_reading_process_output_unwind (int data
)
4202 waiting_for_user_input_p
= data
;
4205 /* This is here so breakpoints can be put on it. */
4207 wait_reading_process_output_1 (void)
4211 /* Read and dispose of subprocess output while waiting for timeout to
4212 elapse and/or keyboard input to be available.
4216 If negative, gobble data immediately available but don't wait for any.
4219 an additional duration to wait, measured in nanoseconds
4220 If TIME_LIMIT is zero, then:
4221 If NSECS == 0, there is no limit.
4222 If NSECS > 0, the timeout consists of NSECS only.
4223 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4226 0 to ignore keyboard input, or
4227 1 to return when input is available, or
4228 -1 meaning caller will actually read the input, so don't throw to
4229 the quit handler, or
4231 DO_DISPLAY means redisplay should be done to show subprocess
4232 output that arrives.
4234 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4235 (and gobble terminal input into the buffer if any arrives).
4237 If WAIT_PROC is specified, wait until something arrives from that
4240 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4241 (suspending output from other processes). A negative value
4242 means don't run any timers either.
4244 Return positive if we received input from WAIT_PROC (or from any
4245 process if WAIT_PROC is null), zero if we attempted to receive
4246 input but got none, and negative if we didn't even try. */
4249 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4251 Lisp_Object wait_for_cell
,
4252 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4262 struct timespec timeout
, end_time
;
4263 int got_some_input
= -1;
4264 ptrdiff_t count
= SPECPDL_INDEX ();
4266 FD_ZERO (&Available
);
4269 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4270 && !(CONSP (wait_proc
->status
)
4271 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4272 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4274 record_unwind_protect_int (wait_reading_process_output_unwind
,
4275 waiting_for_user_input_p
);
4276 waiting_for_user_input_p
= read_kbd
;
4283 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4284 time_limit
= TYPE_MAXIMUM (time_t);
4286 /* Since we may need to wait several times,
4287 compute the absolute time to return at. */
4288 if (time_limit
|| nsecs
> 0)
4290 timeout
= make_timespec (time_limit
, nsecs
);
4291 end_time
= timespec_add (current_timespec (), timeout
);
4296 bool timeout_reduced_for_timers
= false;
4298 /* If calling from keyboard input, do not quit
4299 since we want to return C-g as an input character.
4300 Otherwise, do pending quit if requested. */
4303 else if (pending_signals
)
4304 process_pending_signals ();
4306 /* Exit now if the cell we're waiting for became non-nil. */
4307 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4310 /* After reading input, vacuum up any leftovers without waiting. */
4311 if (0 <= got_some_input
)
4314 /* Compute time from now till when time limit is up. */
4315 /* Exit if already run out. */
4318 /* A negative timeout means
4319 gobble output available now
4320 but don't wait at all. */
4322 timeout
= make_timespec (0, 0);
4324 else if (time_limit
|| nsecs
> 0)
4326 struct timespec now
= current_timespec ();
4327 if (timespec_cmp (end_time
, now
) <= 0)
4329 timeout
= timespec_sub (end_time
, now
);
4333 timeout
= make_timespec (100000, 0);
4336 /* Normally we run timers here.
4337 But not if wait_for_cell; in those cases,
4338 the wait is supposed to be short,
4339 and those callers cannot handle running arbitrary Lisp code here. */
4340 if (NILP (wait_for_cell
)
4341 && just_wait_proc
>= 0)
4343 struct timespec timer_delay
;
4347 unsigned old_timers_run
= timers_run
;
4348 struct buffer
*old_buffer
= current_buffer
;
4349 Lisp_Object old_window
= selected_window
;
4351 timer_delay
= timer_check ();
4353 /* If a timer has run, this might have changed buffers
4354 an alike. Make read_key_sequence aware of that. */
4355 if (timers_run
!= old_timers_run
4356 && (old_buffer
!= current_buffer
4357 || !EQ (old_window
, selected_window
))
4358 && waiting_for_user_input_p
== -1)
4359 record_asynch_buffer_change ();
4361 if (timers_run
!= old_timers_run
&& do_display
)
4362 /* We must retry, since a timer may have requeued itself
4363 and that could alter the time_delay. */
4364 redisplay_preserve_echo_area (9);
4368 while (!detect_input_pending ());
4370 /* If there is unread keyboard input, also return. */
4372 && requeued_events_pending_p ())
4375 /* A negative timeout means do not wait at all. */
4378 if (timespec_valid_p (timer_delay
))
4380 if (timespec_cmp (timer_delay
, timeout
) < 0)
4382 timeout
= timer_delay
;
4383 timeout_reduced_for_timers
= true;
4388 /* This is so a breakpoint can be put here. */
4389 wait_reading_process_output_1 ();
4394 /* Cause C-g and alarm signals to take immediate action,
4395 and cause input available signals to zero out timeout.
4397 It is important that we do this before checking for process
4398 activity. If we get a SIGCHLD after the explicit checks for
4399 process activity, timeout is the only way we will know. */
4401 set_waiting_for_input (&timeout
);
4403 /* If status of something has changed, and no input is
4404 available, notify the user of the change right away. After
4405 this explicit check, we'll let the SIGCHLD handler zap
4406 timeout to get our attention. */
4407 if (update_tick
!= process_tick
)
4412 if (kbd_on_hold_p ())
4415 Atemp
= input_wait_mask
;
4418 timeout
= make_timespec (0, 0);
4419 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4421 #ifdef NON_BLOCKING_CONNECT
4422 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4426 NULL
, &timeout
, NULL
)
4429 /* It's okay for us to do this and then continue with
4430 the loop, since timeout has already been zeroed out. */
4431 clear_waiting_for_input ();
4432 got_some_input
= status_notify (NULL
, wait_proc
);
4433 if (do_display
) redisplay_preserve_echo_area (13);
4437 /* Don't wait for output from a non-running process. Just
4438 read whatever data has already been received. */
4439 if (wait_proc
&& wait_proc
->raw_status_new
)
4440 update_status (wait_proc
);
4442 && wait_proc
->infd
>= 0
4443 && ! EQ (wait_proc
->status
, Qrun
)
4444 && ! EQ (wait_proc
->status
, Qconnect
))
4446 bool read_some_bytes
= false;
4448 clear_waiting_for_input ();
4449 XSETPROCESS (proc
, wait_proc
);
4451 /* Read data from the process, until we exhaust it. */
4454 int nread
= read_process_output (proc
, wait_proc
->infd
);
4457 if (errno
== EIO
|| errno
== EAGAIN
)
4460 if (errno
== EWOULDBLOCK
)
4466 if (got_some_input
< nread
)
4467 got_some_input
= nread
;
4470 read_some_bytes
= true;
4473 if (read_some_bytes
&& do_display
)
4474 redisplay_preserve_echo_area (10);
4479 /* Wait till there is something to do. */
4481 if (wait_proc
&& just_wait_proc
)
4483 if (wait_proc
->infd
< 0) /* Terminated. */
4485 FD_SET (wait_proc
->infd
, &Available
);
4489 else if (!NILP (wait_for_cell
))
4491 Available
= non_process_wait_mask
;
4498 Available
= non_keyboard_wait_mask
;
4500 Available
= input_wait_mask
;
4501 Writeok
= write_mask
;
4502 check_delay
= wait_proc
? 0 : process_output_delay_count
;
4503 check_write
= SELECT_CAN_DO_WRITE_MASK
;
4506 /* If frame size has changed or the window is newly mapped,
4507 redisplay now, before we start to wait. There is a race
4508 condition here; if a SIGIO arrives between now and the select
4509 and indicates that a frame is trashed, the select may block
4510 displaying a trashed screen. */
4511 if (frame_garbaged
&& do_display
)
4513 clear_waiting_for_input ();
4514 redisplay_preserve_echo_area (11);
4516 set_waiting_for_input (&timeout
);
4519 /* Skip the `select' call if input is available and we're
4520 waiting for keyboard input or a cell change (which can be
4521 triggered by processing X events). In the latter case, set
4522 nfds to 1 to avoid breaking the loop. */
4524 if ((read_kbd
|| !NILP (wait_for_cell
))
4525 && detect_input_pending ())
4527 nfds
= read_kbd
? 0 : 1;
4529 FD_ZERO (&Available
);
4535 #ifdef ADAPTIVE_READ_BUFFERING
4536 /* Set the timeout for adaptive read buffering if any
4537 process has non-zero read_output_skip and non-zero
4538 read_output_delay, and we are not reading output for a
4539 specific process. It is not executed if
4540 Vprocess_adaptive_read_buffering is nil. */
4541 if (process_output_skip
&& check_delay
> 0)
4543 int nsecs
= timeout
.tv_nsec
;
4544 if (timeout
.tv_sec
> 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4545 nsecs
= READ_OUTPUT_DELAY_MAX
;
4546 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4548 proc
= chan_process
[channel
];
4551 /* Find minimum non-zero read_output_delay among the
4552 processes with non-zero read_output_skip. */
4553 if (XPROCESS (proc
)->read_output_delay
> 0)
4556 if (!XPROCESS (proc
)->read_output_skip
)
4558 FD_CLR (channel
, &Available
);
4559 XPROCESS (proc
)->read_output_skip
= 0;
4560 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4561 nsecs
= XPROCESS (proc
)->read_output_delay
;
4564 timeout
= make_timespec (0, nsecs
);
4565 process_output_skip
= 0;
4569 #if defined (HAVE_NS)
4571 #elif defined (HAVE_GLIB)
4576 (max (max_process_desc
, max_input_desc
) + 1,
4578 (check_write
? &Writeok
: 0),
4579 NULL
, &timeout
, NULL
);
4582 /* GnuTLS buffers data internally. In lowat mode it leaves
4583 some data in the TCP buffers so that select works, but
4584 with custom pull/push functions we need to check if some
4585 data is available in the buffers manually. */
4590 /* We're not waiting on a specific process, so loop
4591 through all the channels and check for data.
4592 This is a workaround needed for some versions of
4593 the gnutls library -- 2.12.14 has been confirmed
4595 http://comments.gmane.org/gmane.emacs.devel/145074 */
4596 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
4597 if (! NILP (chan_process
[channel
]))
4599 struct Lisp_Process
*p
=
4600 XPROCESS (chan_process
[channel
]);
4601 if (p
&& p
->gnutls_p
&& p
->gnutls_state
4602 && ((emacs_gnutls_record_check_pending
4607 eassert (p
->infd
== channel
);
4608 FD_SET (p
->infd
, &Available
);
4614 /* Check this specific channel. */
4615 if (wait_proc
->gnutls_p
/* Check for valid process. */
4616 && wait_proc
->gnutls_state
4617 /* Do we have pending data? */
4618 && ((emacs_gnutls_record_check_pending
4619 (wait_proc
->gnutls_state
))
4623 eassert (0 <= wait_proc
->infd
);
4624 /* Set to Available. */
4625 FD_SET (wait_proc
->infd
, &Available
);
4634 /* Make C-g and alarm signals set flags again. */
4635 clear_waiting_for_input ();
4637 /* If we woke up due to SIGWINCH, actually change size now. */
4638 do_pending_window_change (0);
4640 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4641 /* We waited the full specified time, so return now. */
4645 if (xerrno
== EINTR
)
4647 else if (xerrno
== EBADF
)
4650 report_file_errno ("Failed select", Qnil
, xerrno
);
4653 /* Check for keyboard input. */
4654 /* If there is any, return immediately
4655 to give it higher priority than subprocesses. */
4659 unsigned old_timers_run
= timers_run
;
4660 struct buffer
*old_buffer
= current_buffer
;
4661 Lisp_Object old_window
= selected_window
;
4664 if (detect_input_pending_run_timers (do_display
))
4666 swallow_events (do_display
);
4667 if (detect_input_pending_run_timers (do_display
))
4671 /* If a timer has run, this might have changed buffers
4672 an alike. Make read_key_sequence aware of that. */
4673 if (timers_run
!= old_timers_run
4674 && waiting_for_user_input_p
== -1
4675 && (old_buffer
!= current_buffer
4676 || !EQ (old_window
, selected_window
)))
4677 record_asynch_buffer_change ();
4683 /* If there is unread keyboard input, also return. */
4685 && requeued_events_pending_p ())
4688 /* If we are not checking for keyboard input now,
4689 do process events (but don't run any timers).
4690 This is so that X events will be processed.
4691 Otherwise they may have to wait until polling takes place.
4692 That would causes delays in pasting selections, for example.
4694 (We used to do this only if wait_for_cell.) */
4695 if (read_kbd
== 0 && detect_input_pending ())
4697 swallow_events (do_display
);
4698 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4699 if (detect_input_pending ())
4704 /* Exit now if the cell we're waiting for became non-nil. */
4705 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4709 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4710 go read it. This can happen with X on BSD after logging out.
4711 In that case, there really is no input and no SIGIO,
4712 but select says there is input. */
4714 if (read_kbd
&& interrupt_input
4715 && keyboard_bit_set (&Available
) && ! noninteractive
)
4716 handle_input_available_signal (SIGIO
);
4719 /* If checking input just got us a size-change event from X,
4720 obey it now if we should. */
4721 if (read_kbd
|| ! NILP (wait_for_cell
))
4722 do_pending_window_change (0);
4724 /* Check for data from a process. */
4725 if (no_avail
|| nfds
== 0)
4728 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4730 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4732 && ((d
->condition
& FOR_READ
4733 && FD_ISSET (channel
, &Available
))
4734 || (d
->condition
& FOR_WRITE
4735 && FD_ISSET (channel
, &write_mask
))))
4736 d
->func (channel
, d
->data
);
4739 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4741 if (FD_ISSET (channel
, &Available
)
4742 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4743 && !FD_ISSET (channel
, &non_process_wait_mask
))
4747 /* If waiting for this channel, arrange to return as
4748 soon as no more input to be processed. No more
4750 proc
= chan_process
[channel
];
4754 /* If this is a server stream socket, accept connection. */
4755 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4757 server_accept_connection (proc
, channel
);
4761 /* Read data from the process, starting with our
4762 buffered-ahead character if we have one. */
4764 nread
= read_process_output (proc
, channel
);
4765 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
)) && got_some_input
< nread
)
4766 got_some_input
= nread
;
4769 /* Since read_process_output can run a filter,
4770 which can call accept-process-output,
4771 don't try to read from any other processes
4772 before doing the select again. */
4773 FD_ZERO (&Available
);
4776 redisplay_preserve_echo_area (12);
4779 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4782 else if (nread
== -1 && errno
== EAGAIN
)
4785 /* FIXME: Is this special case still needed? */
4786 /* Note that we cannot distinguish between no input
4787 available now and a closed pipe.
4788 With luck, a closed pipe will be accompanied by
4789 subprocess termination and SIGCHLD. */
4790 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4794 /* On some OSs with ptys, when the process on one end of
4795 a pty exits, the other end gets an error reading with
4796 errno = EIO instead of getting an EOF (0 bytes read).
4797 Therefore, if we get an error reading and errno =
4798 EIO, just continue, because the child process has
4799 exited and should clean itself up soon (e.g. when we
4801 else if (nread
== -1 && errno
== EIO
)
4803 struct Lisp_Process
*p
= XPROCESS (proc
);
4805 /* Clear the descriptor now, so we only raise the
4807 FD_CLR (channel
, &input_wait_mask
);
4808 FD_CLR (channel
, &non_keyboard_wait_mask
);
4812 /* If the EIO occurs on a pty, the SIGCHLD handler's
4813 waitpid call will not find the process object to
4814 delete. Do it here. */
4815 p
->tick
= ++process_tick
;
4816 pset_status (p
, Qfailed
);
4819 #endif /* HAVE_PTYS */
4820 /* If we can detect process termination, don't consider the
4821 process gone just because its pipe is closed. */
4822 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4826 /* Preserve status of processes already terminated. */
4827 XPROCESS (proc
)->tick
= ++process_tick
;
4828 deactivate_process (proc
);
4829 if (XPROCESS (proc
)->raw_status_new
)
4830 update_status (XPROCESS (proc
));
4831 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4832 pset_status (XPROCESS (proc
),
4833 list2 (Qexit
, make_number (256)));
4836 #ifdef NON_BLOCKING_CONNECT
4837 if (FD_ISSET (channel
, &Writeok
)
4838 && FD_ISSET (channel
, &connect_wait_mask
))
4840 struct Lisp_Process
*p
;
4842 FD_CLR (channel
, &connect_wait_mask
);
4843 FD_CLR (channel
, &write_mask
);
4844 if (--num_pending_connects
< 0)
4847 proc
= chan_process
[channel
];
4851 p
= XPROCESS (proc
);
4854 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4855 So only use it on systems where it is known to work. */
4857 socklen_t xlen
= sizeof (xerrno
);
4858 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4863 struct sockaddr pname
;
4864 socklen_t pnamelen
= sizeof (pname
);
4866 /* If connection failed, getpeername will fail. */
4868 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4870 /* Obtain connect failure code through error slippage. */
4873 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4880 p
->tick
= ++process_tick
;
4881 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
4882 deactivate_process (proc
);
4886 pset_status (p
, Qrun
);
4887 /* Execute the sentinel here. If we had relied on
4888 status_notify to do it later, it will read input
4889 from the process before calling the sentinel. */
4890 exec_sentinel (proc
, build_string ("open\n"));
4891 if (0 <= p
->infd
&& !EQ (p
->filter
, Qt
)
4892 && !EQ (p
->command
, Qt
))
4894 FD_SET (p
->infd
, &input_wait_mask
);
4895 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4899 #endif /* NON_BLOCKING_CONNECT */
4900 } /* End for each file descriptor. */
4901 } /* End while exit conditions not met. */
4903 unbind_to (count
, Qnil
);
4905 /* If calling from keyboard input, do not quit
4906 since we want to return C-g as an input character.
4907 Otherwise, do pending quit if requested. */
4910 /* Prevent input_pending from remaining set if we quit. */
4911 clear_input_pending ();
4915 return got_some_input
;
4918 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4921 read_process_output_call (Lisp_Object fun_and_args
)
4923 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
4927 read_process_output_error_handler (Lisp_Object error_val
)
4929 cmd_error_internal (error_val
, "error in process filter: ");
4931 update_echo_area ();
4932 Fsleep_for (make_number (2), Qnil
);
4937 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
4939 struct coding_system
*coding
);
4941 /* Read pending output from the process channel,
4942 starting with our buffered-ahead character if we have one.
4943 Yield number of decoded characters read.
4945 This function reads at most 4096 characters.
4946 If you want to read all available subprocess output,
4947 you must call it repeatedly until it returns zero.
4949 The characters read are decoded according to PROC's coding-system
4953 read_process_output (Lisp_Object proc
, int channel
)
4956 struct Lisp_Process
*p
= XPROCESS (proc
);
4957 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
4958 int carryover
= p
->decoding_carryover
;
4959 enum { readmax
= 4096 };
4960 ptrdiff_t count
= SPECPDL_INDEX ();
4961 Lisp_Object odeactivate
;
4962 char chars
[sizeof coding
->carryover
+ readmax
];
4965 /* See the comment above. */
4966 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
4968 #ifdef DATAGRAM_SOCKETS
4969 /* We have a working select, so proc_buffered_char is always -1. */
4970 if (DATAGRAM_CHAN_P (channel
))
4972 socklen_t len
= datagram_address
[channel
].len
;
4973 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
4974 0, datagram_address
[channel
].sa
, &len
);
4979 bool buffered
= proc_buffered_char
[channel
] >= 0;
4982 chars
[carryover
] = proc_buffered_char
[channel
];
4983 proc_buffered_char
[channel
] = -1;
4986 if (p
->gnutls_p
&& p
->gnutls_state
)
4987 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
4988 readmax
- buffered
);
4991 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
4992 readmax
- buffered
);
4993 #ifdef ADAPTIVE_READ_BUFFERING
4994 if (nbytes
> 0 && p
->adaptive_read_buffering
)
4996 int delay
= p
->read_output_delay
;
4999 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5002 process_output_delay_count
++;
5003 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5006 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5008 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5010 process_output_delay_count
--;
5012 p
->read_output_delay
= delay
;
5015 p
->read_output_skip
= 1;
5016 process_output_skip
= 1;
5021 nbytes
+= buffered
&& nbytes
<= 0;
5024 p
->decoding_carryover
= 0;
5026 /* At this point, NBYTES holds number of bytes just received
5027 (including the one in proc_buffered_char[channel]). */
5030 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5032 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5035 /* Now set NBYTES how many bytes we must decode. */
5036 nbytes
+= carryover
;
5038 odeactivate
= Vdeactivate_mark
;
5039 /* There's no good reason to let process filters change the current
5040 buffer, and many callers of accept-process-output, sit-for, and
5041 friends don't expect current-buffer to be changed from under them. */
5042 record_unwind_current_buffer ();
5044 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5046 /* Handling the process output should not deactivate the mark. */
5047 Vdeactivate_mark
= odeactivate
;
5049 unbind_to (count
, Qnil
);
5054 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5056 struct coding_system
*coding
)
5058 Lisp_Object outstream
= p
->filter
;
5060 bool outer_running_asynch_code
= running_asynch_code
;
5061 int waiting
= waiting_for_user_input_p
;
5063 /* No need to gcpro these, because all we do with them later
5064 is test them for EQness, and none of them should be a string. */
5066 Lisp_Object obuffer
, okeymap
;
5067 XSETBUFFER (obuffer
, current_buffer
);
5068 okeymap
= BVAR (current_buffer
, keymap
);
5071 /* We inhibit quit here instead of just catching it so that
5072 hitting ^G when a filter happens to be running won't screw
5074 specbind (Qinhibit_quit
, Qt
);
5075 specbind (Qlast_nonmenu_event
, Qt
);
5077 /* In case we get recursively called,
5078 and we already saved the match data nonrecursively,
5079 save the same match data in safely recursive fashion. */
5080 if (outer_running_asynch_code
)
5083 /* Don't clobber the CURRENT match data, either! */
5084 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5085 restore_search_regs ();
5086 record_unwind_save_match_data ();
5087 Fset_match_data (tem
, Qt
);
5090 /* For speed, if a search happens within this code,
5091 save the match data in a special nonrecursive fashion. */
5092 running_asynch_code
= 1;
5094 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5095 text
= coding
->dst_object
;
5096 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5097 /* A new coding system might be found. */
5098 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5100 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5102 /* Don't call setup_coding_system for
5103 proc_decode_coding_system[channel] here. It is done in
5104 detect_coding called via decode_coding above. */
5106 /* If a coding system for encoding is not yet decided, we set
5107 it as the same as coding-system for decoding.
5109 But, before doing that we must check if
5110 proc_encode_coding_system[p->outfd] surely points to a
5111 valid memory because p->outfd will be changed once EOF is
5112 sent to the process. */
5113 if (NILP (p
->encode_coding_system
) && p
->outfd
>= 0
5114 && proc_encode_coding_system
[p
->outfd
])
5116 pset_encode_coding_system
5117 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5118 setup_coding_system (p
->encode_coding_system
,
5119 proc_encode_coding_system
[p
->outfd
]);
5123 if (coding
->carryover_bytes
> 0)
5125 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5126 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5127 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5128 coding
->carryover_bytes
);
5129 p
->decoding_carryover
= coding
->carryover_bytes
;
5131 if (SBYTES (text
) > 0)
5132 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5133 sometimes it's simply wrong to wrap (e.g. when called from
5134 accept-process-output). */
5135 internal_condition_case_1 (read_process_output_call
,
5136 list3 (outstream
, make_lisp_proc (p
), text
),
5137 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5138 read_process_output_error_handler
);
5140 /* If we saved the match data nonrecursively, restore it now. */
5141 restore_search_regs ();
5142 running_asynch_code
= outer_running_asynch_code
;
5144 /* Restore waiting_for_user_input_p as it was
5145 when we were called, in case the filter clobbered it. */
5146 waiting_for_user_input_p
= waiting
;
5148 #if 0 /* Call record_asynch_buffer_change unconditionally,
5149 because we might have changed minor modes or other things
5150 that affect key bindings. */
5151 if (! EQ (Fcurrent_buffer (), obuffer
)
5152 || ! EQ (current_buffer
->keymap
, okeymap
))
5154 /* But do it only if the caller is actually going to read events.
5155 Otherwise there's no need to make him wake up, and it could
5156 cause trouble (for example it would make sit_for return). */
5157 if (waiting_for_user_input_p
== -1)
5158 record_asynch_buffer_change ();
5161 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5162 Sinternal_default_process_filter
, 2, 2, 0,
5163 doc
: /* Function used as default process filter.
5164 This inserts the process's output into its buffer, if there is one.
5165 Otherwise it discards the output. */)
5166 (Lisp_Object proc
, Lisp_Object text
)
5168 struct Lisp_Process
*p
;
5171 CHECK_PROCESS (proc
);
5172 p
= XPROCESS (proc
);
5173 CHECK_STRING (text
);
5175 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5177 Lisp_Object old_read_only
;
5178 ptrdiff_t old_begv
, old_zv
;
5179 ptrdiff_t old_begv_byte
, old_zv_byte
;
5180 ptrdiff_t before
, before_byte
;
5181 ptrdiff_t opoint_byte
;
5184 Fset_buffer (p
->buffer
);
5186 opoint_byte
= PT_BYTE
;
5187 old_read_only
= BVAR (current_buffer
, read_only
);
5190 old_begv_byte
= BEGV_BYTE
;
5191 old_zv_byte
= ZV_BYTE
;
5193 bset_read_only (current_buffer
, Qnil
);
5195 /* Insert new output into buffer at the current end-of-output
5196 marker, thus preserving logical ordering of input and output. */
5197 if (XMARKER (p
->mark
)->buffer
)
5198 set_point_from_marker (p
->mark
);
5200 SET_PT_BOTH (ZV
, ZV_BYTE
);
5202 before_byte
= PT_BYTE
;
5204 /* If the output marker is outside of the visible region, save
5205 the restriction and widen. */
5206 if (! (BEGV
<= PT
&& PT
<= ZV
))
5209 /* Adjust the multibyteness of TEXT to that of the buffer. */
5210 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5211 != ! STRING_MULTIBYTE (text
))
5212 text
= (STRING_MULTIBYTE (text
)
5213 ? Fstring_as_unibyte (text
)
5214 : Fstring_to_multibyte (text
));
5215 /* Insert before markers in case we are inserting where
5216 the buffer's mark is, and the user's next command is Meta-y. */
5217 insert_from_string_before_markers (text
, 0, 0,
5218 SCHARS (text
), SBYTES (text
), 0);
5220 /* Make sure the process marker's position is valid when the
5221 process buffer is changed in the signal_after_change above.
5222 W3 is known to do that. */
5223 if (BUFFERP (p
->buffer
)
5224 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5225 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5227 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5229 update_mode_lines
= 23;
5231 /* Make sure opoint and the old restrictions
5232 float ahead of any new text just as point would. */
5233 if (opoint
>= before
)
5235 opoint
+= PT
- before
;
5236 opoint_byte
+= PT_BYTE
- before_byte
;
5238 if (old_begv
> before
)
5240 old_begv
+= PT
- before
;
5241 old_begv_byte
+= PT_BYTE
- before_byte
;
5243 if (old_zv
>= before
)
5245 old_zv
+= PT
- before
;
5246 old_zv_byte
+= PT_BYTE
- before_byte
;
5249 /* If the restriction isn't what it should be, set it. */
5250 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5251 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5253 bset_read_only (current_buffer
, old_read_only
);
5254 SET_PT_BOTH (opoint
, opoint_byte
);
5259 /* Sending data to subprocess. */
5261 /* In send_process, when a write fails temporarily,
5262 wait_reading_process_output is called. It may execute user code,
5263 e.g. timers, that attempts to write new data to the same process.
5264 We must ensure that data is sent in the right order, and not
5265 interspersed half-completed with other writes (Bug#10815). This is
5266 handled by the write_queue element of struct process. It is a list
5267 with each entry having the form
5269 (string . (offset . length))
5271 where STRING is a lisp string, OFFSET is the offset into the
5272 string's byte sequence from which we should begin to send, and
5273 LENGTH is the number of bytes left to send. */
5275 /* Create a new entry in write_queue.
5276 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5277 BUF is a pointer to the string sequence of the input_obj or a C
5278 string in case of Qt or Qnil. */
5281 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5282 const char *buf
, ptrdiff_t len
, bool front
)
5285 Lisp_Object entry
, obj
;
5287 if (STRINGP (input_obj
))
5289 offset
= buf
- SSDATA (input_obj
);
5295 obj
= make_unibyte_string (buf
, len
);
5298 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5301 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5303 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5306 /* Remove the first element in the write_queue of process P, put its
5307 contents in OBJ, BUF and LEN, and return true. If the
5308 write_queue is empty, return false. */
5311 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5312 const char **buf
, ptrdiff_t *len
)
5314 Lisp_Object entry
, offset_length
;
5317 if (NILP (p
->write_queue
))
5320 entry
= XCAR (p
->write_queue
);
5321 pset_write_queue (p
, XCDR (p
->write_queue
));
5323 *obj
= XCAR (entry
);
5324 offset_length
= XCDR (entry
);
5326 *len
= XINT (XCDR (offset_length
));
5327 offset
= XINT (XCAR (offset_length
));
5328 *buf
= SSDATA (*obj
) + offset
;
5333 /* Send some data to process PROC.
5334 BUF is the beginning of the data; LEN is the number of characters.
5335 OBJECT is the Lisp object that the data comes from. If OBJECT is
5336 nil or t, it means that the data comes from C string.
5338 If OBJECT is not nil, the data is encoded by PROC's coding-system
5339 for encoding before it is sent.
5341 This function can evaluate Lisp code and can garbage collect. */
5344 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5347 struct Lisp_Process
*p
= XPROCESS (proc
);
5349 struct coding_system
*coding
;
5351 if (p
->raw_status_new
)
5353 if (! EQ (p
->status
, Qrun
))
5354 error ("Process %s not running", SDATA (p
->name
));
5356 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5358 coding
= proc_encode_coding_system
[p
->outfd
];
5359 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5361 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5362 || (BUFFERP (object
)
5363 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5366 pset_encode_coding_system
5367 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5368 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5370 /* The coding system for encoding was changed to raw-text
5371 because we sent a unibyte text previously. Now we are
5372 sending a multibyte text, thus we must encode it by the
5373 original coding system specified for the current process.
5375 Another reason we come here is that the coding system
5376 was just complemented and a new one was returned by
5377 complement_process_encoding_system. */
5378 setup_coding_system (p
->encode_coding_system
, coding
);
5379 Vlast_coding_system_used
= p
->encode_coding_system
;
5381 coding
->src_multibyte
= 1;
5385 coding
->src_multibyte
= 0;
5386 /* For sending a unibyte text, character code conversion should
5387 not take place but EOL conversion should. So, setup raw-text
5388 or one of the subsidiary if we have not yet done it. */
5389 if (CODING_REQUIRE_ENCODING (coding
))
5391 if (CODING_REQUIRE_FLUSHING (coding
))
5393 /* But, before changing the coding, we must flush out data. */
5394 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5395 send_process (proc
, "", 0, Qt
);
5396 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5398 setup_coding_system (raw_text_coding_system
5399 (Vlast_coding_system_used
),
5401 coding
->src_multibyte
= 0;
5404 coding
->dst_multibyte
= 0;
5406 if (CODING_REQUIRE_ENCODING (coding
))
5408 coding
->dst_object
= Qt
;
5409 if (BUFFERP (object
))
5411 ptrdiff_t from_byte
, from
, to
;
5412 ptrdiff_t save_pt
, save_pt_byte
;
5413 struct buffer
*cur
= current_buffer
;
5415 set_buffer_internal (XBUFFER (object
));
5416 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5418 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5419 from
= BYTE_TO_CHAR (from_byte
);
5420 to
= BYTE_TO_CHAR (from_byte
+ len
);
5421 TEMP_SET_PT_BOTH (from
, from_byte
);
5422 encode_coding_object (coding
, object
, from
, from_byte
,
5423 to
, from_byte
+ len
, Qt
);
5424 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5425 set_buffer_internal (cur
);
5427 else if (STRINGP (object
))
5429 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5430 SBYTES (object
), Qt
);
5434 coding
->dst_object
= make_unibyte_string (buf
, len
);
5435 coding
->produced
= len
;
5438 len
= coding
->produced
;
5439 object
= coding
->dst_object
;
5440 buf
= SSDATA (object
);
5443 /* If there is already data in the write_queue, put the new data
5444 in the back of queue. Otherwise, ignore it. */
5445 if (!NILP (p
->write_queue
))
5446 write_queue_push (p
, object
, buf
, len
, 0);
5448 do /* while !NILP (p->write_queue) */
5450 ptrdiff_t cur_len
= -1;
5451 const char *cur_buf
;
5452 Lisp_Object cur_object
;
5454 /* If write_queue is empty, ignore it. */
5455 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5459 cur_object
= object
;
5464 /* Send this batch, using one or more write calls. */
5465 ptrdiff_t written
= 0;
5466 int outfd
= p
->outfd
;
5467 #ifdef DATAGRAM_SOCKETS
5468 if (DATAGRAM_CHAN_P (outfd
))
5470 rv
= sendto (outfd
, cur_buf
, cur_len
,
5471 0, datagram_address
[outfd
].sa
,
5472 datagram_address
[outfd
].len
);
5475 else if (errno
== EMSGSIZE
)
5476 report_file_error ("Sending datagram", proc
);
5482 if (p
->gnutls_p
&& p
->gnutls_state
)
5483 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5486 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5487 rv
= (written
? 0 : -1);
5488 #ifdef ADAPTIVE_READ_BUFFERING
5489 if (p
->read_output_delay
> 0
5490 && p
->adaptive_read_buffering
== 1)
5492 p
->read_output_delay
= 0;
5493 process_output_delay_count
--;
5494 p
->read_output_skip
= 0;
5503 || errno
== EWOULDBLOCK
5506 /* Buffer is full. Wait, accepting input;
5507 that may allow the program
5508 to finish doing output and read more. */
5510 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5511 /* A gross hack to work around a bug in FreeBSD.
5512 In the following sequence, read(2) returns
5516 write(2) 954 bytes, get EAGAIN
5517 read(2) 1024 bytes in process_read_output
5518 read(2) 11 bytes in process_read_output
5520 That is, read(2) returns more bytes than have
5521 ever been written successfully. The 1033 bytes
5522 read are the 1022 bytes written successfully
5523 after processing (for example with CRs added if
5524 the terminal is set up that way which it is
5525 here). The same bytes will be seen again in a
5526 later read(2), without the CRs. */
5528 if (errno
== EAGAIN
)
5531 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5533 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5535 /* Put what we should have written in wait_queue. */
5536 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5537 wait_reading_process_output (0, 20 * 1000 * 1000,
5538 0, 0, Qnil
, NULL
, 0);
5539 /* Reread queue, to see what is left. */
5542 else if (errno
== EPIPE
)
5544 p
->raw_status_new
= 0;
5545 pset_status (p
, list2 (Qexit
, make_number (256)));
5546 p
->tick
= ++process_tick
;
5547 deactivate_process (proc
);
5548 error ("process %s no longer connected to pipe; closed it",
5552 /* This is a real error. */
5553 report_file_error ("Writing to process", proc
);
5559 while (!NILP (p
->write_queue
));
5562 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5564 doc
: /* Send current contents of region as input to PROCESS.
5565 PROCESS may be a process, a buffer, the name of a process or buffer, or
5566 nil, indicating the current buffer's process.
5567 Called from program, takes three arguments, PROCESS, START and END.
5568 If the region is more than 500 characters long,
5569 it is sent in several bunches. This may happen even for shorter regions.
5570 Output from processes can arrive in between bunches. */)
5571 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5573 Lisp_Object proc
= get_process (process
);
5574 ptrdiff_t start_byte
, end_byte
;
5576 validate_region (&start
, &end
);
5578 start_byte
= CHAR_TO_BYTE (XINT (start
));
5579 end_byte
= CHAR_TO_BYTE (XINT (end
));
5581 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5582 move_gap_both (XINT (start
), start_byte
);
5584 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5585 end_byte
- start_byte
, Fcurrent_buffer ());
5590 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5592 doc
: /* Send PROCESS the contents of STRING as input.
5593 PROCESS may be a process, a buffer, the name of a process or buffer, or
5594 nil, indicating the current buffer's process.
5595 If STRING is more than 500 characters long,
5596 it is sent in several bunches. This may happen even for shorter strings.
5597 Output from processes can arrive in between bunches. */)
5598 (Lisp_Object process
, Lisp_Object string
)
5601 CHECK_STRING (string
);
5602 proc
= get_process (process
);
5603 send_process (proc
, SSDATA (string
),
5604 SBYTES (string
), string
);
5608 /* Return the foreground process group for the tty/pty that
5609 the process P uses. */
5611 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5616 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5619 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5620 master side. Try the slave side. */
5621 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5625 ioctl (fd
, TIOCGPGRP
, &gid
);
5629 #endif /* defined (TIOCGPGRP ) */
5634 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5635 Sprocess_running_child_p
, 0, 1, 0,
5636 doc
: /* Return t if PROCESS has given the terminal to a child.
5637 If the operating system does not make it possible to find out,
5638 return t unconditionally. */)
5639 (Lisp_Object process
)
5641 /* Initialize in case ioctl doesn't exist or gives an error,
5642 in a way that will cause returning t. */
5645 struct Lisp_Process
*p
;
5647 proc
= get_process (process
);
5648 p
= XPROCESS (proc
);
5650 if (!EQ (p
->type
, Qreal
))
5651 error ("Process %s is not a subprocess",
5654 error ("Process %s is not active",
5657 gid
= emacs_get_tty_pgrp (p
);
5664 /* Send a signal number SIGNO to PROCESS.
5665 If CURRENT_GROUP is t, that means send to the process group
5666 that currently owns the terminal being used to communicate with PROCESS.
5667 This is used for various commands in shell mode.
5668 If CURRENT_GROUP is lambda, that means send to the process group
5669 that currently owns the terminal, but only if it is NOT the shell itself.
5671 If NOMSG is false, insert signal-announcements into process's buffers
5674 If we can, we try to signal PROCESS by sending control characters
5675 down the pty. This allows us to signal inferiors who have changed
5676 their uid, for which kill would return an EPERM error. */
5679 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5683 struct Lisp_Process
*p
;
5687 proc
= get_process (process
);
5688 p
= XPROCESS (proc
);
5690 if (!EQ (p
->type
, Qreal
))
5691 error ("Process %s is not a subprocess",
5694 error ("Process %s is not active",
5698 current_group
= Qnil
;
5700 /* If we are using pgrps, get a pgrp number and make it negative. */
5701 if (NILP (current_group
))
5702 /* Send the signal to the shell's process group. */
5706 #ifdef SIGNALS_VIA_CHARACTERS
5707 /* If possible, send signals to the entire pgrp
5708 by sending an input character to it. */
5711 cc_t
*sig_char
= NULL
;
5713 tcgetattr (p
->infd
, &t
);
5718 sig_char
= &t
.c_cc
[VINTR
];
5722 sig_char
= &t
.c_cc
[VQUIT
];
5726 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5727 sig_char
= &t
.c_cc
[VSWTCH
];
5729 sig_char
= &t
.c_cc
[VSUSP
];
5734 if (sig_char
&& *sig_char
!= CDISABLE
)
5736 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5739 /* If we can't send the signal with a character,
5740 fall through and send it another way. */
5742 /* The code above may fall through if it can't
5743 handle the signal. */
5744 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5747 /* Get the current pgrp using the tty itself, if we have that.
5748 Otherwise, use the pty to get the pgrp.
5749 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5750 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5751 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5752 His patch indicates that if TIOCGPGRP returns an error, then
5753 we should just assume that p->pid is also the process group id. */
5755 gid
= emacs_get_tty_pgrp (p
);
5758 /* If we can't get the information, assume
5759 the shell owns the tty. */
5762 /* It is not clear whether anything really can set GID to -1.
5763 Perhaps on some system one of those ioctls can or could do so.
5764 Or perhaps this is vestigial. */
5767 #else /* ! defined (TIOCGPGRP) */
5768 /* Can't select pgrps on this system, so we know that
5769 the child itself heads the pgrp. */
5771 #endif /* ! defined (TIOCGPGRP) */
5773 /* If current_group is lambda, and the shell owns the terminal,
5774 don't send any signal. */
5775 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5780 if (signo
== SIGCONT
)
5782 p
->raw_status_new
= 0;
5783 pset_status (p
, Qrun
);
5784 p
->tick
= ++process_tick
;
5787 status_notify (NULL
, NULL
);
5788 redisplay_preserve_echo_area (13);
5794 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5795 We don't know whether the bug is fixed in later HP-UX versions. */
5796 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
5800 /* If we don't have process groups, send the signal to the immediate
5801 subprocess. That isn't really right, but it's better than any
5802 obvious alternative. */
5803 pid_t pid
= no_pgrp
? gid
: - gid
;
5805 /* Do not kill an already-reaped process, as that could kill an
5806 innocent bystander that happens to have the same process ID. */
5808 block_child_signal (&oldset
);
5811 unblock_child_signal (&oldset
);
5814 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5815 doc
: /* Interrupt process PROCESS.
5816 PROCESS may be a process, a buffer, or the name of a process or buffer.
5817 No arg or nil means current buffer's process.
5818 Second arg CURRENT-GROUP non-nil means send signal to
5819 the current process-group of the process's controlling terminal
5820 rather than to the process's own process group.
5821 If the process is a shell, this means interrupt current subjob
5822 rather than the shell.
5824 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5825 don't send the signal. */)
5826 (Lisp_Object process
, Lisp_Object current_group
)
5828 process_send_signal (process
, SIGINT
, current_group
, 0);
5832 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5833 doc
: /* Kill process PROCESS. May be process or name of one.
5834 See function `interrupt-process' for more details on usage. */)
5835 (Lisp_Object process
, Lisp_Object current_group
)
5837 process_send_signal (process
, SIGKILL
, current_group
, 0);
5841 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5842 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5843 See function `interrupt-process' for more details on usage. */)
5844 (Lisp_Object process
, Lisp_Object current_group
)
5846 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5850 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5851 doc
: /* Stop process PROCESS. May be process or name of one.
5852 See function `interrupt-process' for more details on usage.
5853 If PROCESS is a network or serial process, inhibit handling of incoming
5855 (Lisp_Object process
, Lisp_Object current_group
)
5857 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5859 struct Lisp_Process
*p
;
5861 p
= XPROCESS (process
);
5862 if (NILP (p
->command
)
5865 FD_CLR (p
->infd
, &input_wait_mask
);
5866 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
5868 pset_command (p
, Qt
);
5872 error ("No SIGTSTP support");
5874 process_send_signal (process
, SIGTSTP
, current_group
, 0);
5879 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
5880 doc
: /* Continue process PROCESS. May be process or name of one.
5881 See function `interrupt-process' for more details on usage.
5882 If PROCESS is a network or serial process, resume handling of incoming
5884 (Lisp_Object process
, Lisp_Object current_group
)
5886 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5888 struct Lisp_Process
*p
;
5890 p
= XPROCESS (process
);
5891 if (EQ (p
->command
, Qt
)
5893 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
5895 FD_SET (p
->infd
, &input_wait_mask
);
5896 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5898 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
5899 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
5900 #else /* not WINDOWSNT */
5901 tcflush (p
->infd
, TCIFLUSH
);
5902 #endif /* not WINDOWSNT */
5904 pset_command (p
, Qnil
);
5908 process_send_signal (process
, SIGCONT
, current_group
, 0);
5910 error ("No SIGCONT support");
5915 /* Return the integer value of the signal whose abbreviation is ABBR,
5916 or a negative number if there is no such signal. */
5918 abbr_to_signal (char const *name
)
5921 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
5923 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
5926 for (i
= 0; i
< sizeof sigbuf
; i
++)
5928 sigbuf
[i
] = c_toupper (name
[i
]);
5930 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
5936 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
5937 2, 2, "sProcess (name or number): \nnSignal code: ",
5938 doc
: /* Send PROCESS the signal with code SIGCODE.
5939 PROCESS may also be a number specifying the process id of the
5940 process to signal; in this case, the process need not be a child of
5942 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5943 (Lisp_Object process
, Lisp_Object sigcode
)
5948 if (STRINGP (process
))
5950 Lisp_Object tem
= Fget_process (process
);
5953 Lisp_Object process_number
5954 = string_to_number (SSDATA (process
), 10, 1);
5955 if (INTEGERP (process_number
) || FLOATP (process_number
))
5956 tem
= process_number
;
5960 else if (!NUMBERP (process
))
5961 process
= get_process (process
);
5966 if (NUMBERP (process
))
5967 CONS_TO_INTEGER (process
, pid_t
, pid
);
5970 CHECK_PROCESS (process
);
5971 pid
= XPROCESS (process
)->pid
;
5973 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
5976 if (INTEGERP (sigcode
))
5978 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
5979 signo
= XINT (sigcode
);
5985 CHECK_SYMBOL (sigcode
);
5986 name
= SSDATA (SYMBOL_NAME (sigcode
));
5988 signo
= abbr_to_signal (name
);
5990 error ("Undefined signal name %s", name
);
5993 return make_number (kill (pid
, signo
));
5996 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
5997 doc
: /* Make PROCESS see end-of-file in its input.
5998 EOF comes after any text already sent to it.
5999 PROCESS may be a process, a buffer, the name of a process or buffer, or
6000 nil, indicating the current buffer's process.
6001 If PROCESS is a network connection, or is a process communicating
6002 through a pipe (as opposed to a pty), then you cannot send any more
6003 text to PROCESS after you call this function.
6004 If PROCESS is a serial process, wait until all output written to the
6005 process has been transmitted to the serial port. */)
6006 (Lisp_Object process
)
6009 struct coding_system
*coding
= NULL
;
6012 if (DATAGRAM_CONN_P (process
))
6015 proc
= get_process (process
);
6016 outfd
= XPROCESS (proc
)->outfd
;
6018 coding
= proc_encode_coding_system
[outfd
];
6020 /* Make sure the process is really alive. */
6021 if (XPROCESS (proc
)->raw_status_new
)
6022 update_status (XPROCESS (proc
));
6023 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6024 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6026 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6028 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6029 send_process (proc
, "", 0, Qnil
);
6032 if (XPROCESS (proc
)->pty_flag
)
6033 send_process (proc
, "\004", 1, Qnil
);
6034 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6037 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6038 report_file_error ("Failed tcdrain", Qnil
);
6039 #endif /* not WINDOWSNT */
6040 /* Do nothing on Windows because writes are blocking. */
6044 struct Lisp_Process
*p
= XPROCESS (proc
);
6045 int old_outfd
= p
->outfd
;
6048 #ifdef HAVE_SHUTDOWN
6049 /* If this is a network connection, or socketpair is used
6050 for communication with the subprocess, call shutdown to cause EOF.
6051 (In some old system, shutdown to socketpair doesn't work.
6052 Then we just can't win.) */
6054 && (EQ (p
->type
, Qnetwork
) || p
->infd
== old_outfd
))
6055 shutdown (old_outfd
, 1);
6057 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6058 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6060 report_file_error ("Opening null device", Qnil
);
6061 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6062 p
->outfd
= new_outfd
;
6064 if (!proc_encode_coding_system
[new_outfd
])
6065 proc_encode_coding_system
[new_outfd
]
6066 = xmalloc (sizeof (struct coding_system
));
6069 *proc_encode_coding_system
[new_outfd
]
6070 = *proc_encode_coding_system
[old_outfd
];
6071 memset (proc_encode_coding_system
[old_outfd
], 0,
6072 sizeof (struct coding_system
));
6075 setup_coding_system (p
->encode_coding_system
,
6076 proc_encode_coding_system
[new_outfd
]);
6081 /* The main Emacs thread records child processes in three places:
6083 - Vprocess_alist, for asynchronous subprocesses, which are child
6084 processes visible to Lisp.
6086 - deleted_pid_list, for child processes invisible to Lisp,
6087 typically because of delete-process. These are recorded so that
6088 the processes can be reaped when they exit, so that the operating
6089 system's process table is not cluttered by zombies.
6091 - the local variable PID in Fcall_process, call_process_cleanup and
6092 call_process_kill, for synchronous subprocesses.
6093 record_unwind_protect is used to make sure this process is not
6094 forgotten: if the user interrupts call-process and the child
6095 process refuses to exit immediately even with two C-g's,
6096 call_process_kill adds PID's contents to deleted_pid_list before
6099 The main Emacs thread invokes waitpid only on child processes that
6100 it creates and that have not been reaped. This avoid races on
6101 platforms such as GTK, where other threads create their own
6102 subprocesses which the main thread should not reap. For example,
6103 if the main thread attempted to reap an already-reaped child, it
6104 might inadvertently reap a GTK-created process that happened to
6105 have the same process ID. */
6107 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6108 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6109 keep track of its own children. GNUstep is similar. */
6111 static void dummy_handler (int sig
) {}
6112 static signal_handler_t
volatile lib_child_handler
;
6114 /* Handle a SIGCHLD signal by looking for known child processes of
6115 Emacs whose status have changed. For each one found, record its
6118 All we do is change the status; we do not run sentinels or print
6119 notifications. That is saved for the next time keyboard input is
6120 done, in order to avoid timing errors.
6122 ** WARNING: this can be called during garbage collection.
6123 Therefore, it must not be fooled by the presence of mark bits in
6126 ** USG WARNING: Although it is not obvious from the documentation
6127 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6128 signal() before executing at least one wait(), otherwise the
6129 handler will be called again, resulting in an infinite loop. The
6130 relevant portion of the documentation reads "SIGCLD signals will be
6131 queued and the signal-catching function will be continually
6132 reentered until the queue is empty". Invoking signal() causes the
6133 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6136 ** Malloc WARNING: This should never call malloc either directly or
6137 indirectly; if it does, that is a bug. */
6140 handle_child_signal (int sig
)
6142 Lisp_Object tail
, proc
;
6144 /* Find the process that signaled us, and record its status. */
6146 /* The process can have been deleted by Fdelete_process, or have
6147 been started asynchronously by Fcall_process. */
6148 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6150 bool all_pids_are_fixnums
6151 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6152 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6153 Lisp_Object head
= XCAR (tail
);
6158 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6161 if (INTEGERP (xpid
))
6162 deleted_pid
= XINT (xpid
);
6164 deleted_pid
= XFLOAT_DATA (xpid
);
6165 if (child_status_changed (deleted_pid
, 0, 0))
6167 if (STRINGP (XCDR (head
)))
6168 unlink (SSDATA (XCDR (head
)));
6169 XSETCAR (tail
, Qnil
);
6174 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6175 FOR_EACH_PROCESS (tail
, proc
)
6177 struct Lisp_Process
*p
= XPROCESS (proc
);
6181 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6183 /* Change the status of the process that was found. */
6184 p
->tick
= ++process_tick
;
6185 p
->raw_status
= status
;
6186 p
->raw_status_new
= 1;
6188 /* If process has terminated, stop waiting for its output. */
6189 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6191 bool clear_desc_flag
= 0;
6194 clear_desc_flag
= 1;
6196 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6197 if (clear_desc_flag
)
6199 FD_CLR (p
->infd
, &input_wait_mask
);
6200 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6206 lib_child_handler (sig
);
6207 #ifdef NS_IMPL_GNUSTEP
6208 /* NSTask in GNUstep sets its child handler each time it is called.
6209 So we must re-set ours. */
6210 catch_child_signal ();
6215 deliver_child_signal (int sig
)
6217 deliver_process_signal (sig
, handle_child_signal
);
6222 exec_sentinel_error_handler (Lisp_Object error_val
)
6224 cmd_error_internal (error_val
, "error in process sentinel: ");
6226 update_echo_area ();
6227 Fsleep_for (make_number (2), Qnil
);
6232 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6234 Lisp_Object sentinel
, odeactivate
;
6235 struct Lisp_Process
*p
= XPROCESS (proc
);
6236 ptrdiff_t count
= SPECPDL_INDEX ();
6237 bool outer_running_asynch_code
= running_asynch_code
;
6238 int waiting
= waiting_for_user_input_p
;
6240 if (inhibit_sentinels
)
6243 /* No need to gcpro these, because all we do with them later
6244 is test them for EQness, and none of them should be a string. */
6245 odeactivate
= Vdeactivate_mark
;
6247 Lisp_Object obuffer
, okeymap
;
6248 XSETBUFFER (obuffer
, current_buffer
);
6249 okeymap
= BVAR (current_buffer
, keymap
);
6252 /* There's no good reason to let sentinels change the current
6253 buffer, and many callers of accept-process-output, sit-for, and
6254 friends don't expect current-buffer to be changed from under them. */
6255 record_unwind_current_buffer ();
6257 sentinel
= p
->sentinel
;
6259 /* Inhibit quit so that random quits don't screw up a running filter. */
6260 specbind (Qinhibit_quit
, Qt
);
6261 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6263 /* In case we get recursively called,
6264 and we already saved the match data nonrecursively,
6265 save the same match data in safely recursive fashion. */
6266 if (outer_running_asynch_code
)
6269 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6270 restore_search_regs ();
6271 record_unwind_save_match_data ();
6272 Fset_match_data (tem
, Qt
);
6275 /* For speed, if a search happens within this code,
6276 save the match data in a special nonrecursive fashion. */
6277 running_asynch_code
= 1;
6279 internal_condition_case_1 (read_process_output_call
,
6280 list3 (sentinel
, proc
, reason
),
6281 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6282 exec_sentinel_error_handler
);
6284 /* If we saved the match data nonrecursively, restore it now. */
6285 restore_search_regs ();
6286 running_asynch_code
= outer_running_asynch_code
;
6288 Vdeactivate_mark
= odeactivate
;
6290 /* Restore waiting_for_user_input_p as it was
6291 when we were called, in case the filter clobbered it. */
6292 waiting_for_user_input_p
= waiting
;
6295 if (! EQ (Fcurrent_buffer (), obuffer
)
6296 || ! EQ (current_buffer
->keymap
, okeymap
))
6298 /* But do it only if the caller is actually going to read events.
6299 Otherwise there's no need to make him wake up, and it could
6300 cause trouble (for example it would make sit_for return). */
6301 if (waiting_for_user_input_p
== -1)
6302 record_asynch_buffer_change ();
6304 unbind_to (count
, Qnil
);
6307 /* Report all recent events of a change in process status
6308 (either run the sentinel or output a message).
6309 This is usually done while Emacs is waiting for keyboard input
6310 but can be done at other times.
6312 Return positive if any input was received from WAIT_PROC (or from
6313 any process if WAIT_PROC is null), zero if input was attempted but
6314 none received, and negative if we didn't even try. */
6317 status_notify (struct Lisp_Process
*deleting_process
,
6318 struct Lisp_Process
*wait_proc
)
6321 Lisp_Object tail
, msg
;
6322 struct gcpro gcpro1
, gcpro2
;
6323 int got_some_input
= -1;
6327 /* We need to gcpro tail; if read_process_output calls a filter
6328 which deletes a process and removes the cons to which tail points
6329 from Vprocess_alist, and then causes a GC, tail is an unprotected
6333 /* Set this now, so that if new processes are created by sentinels
6334 that we run, we get called again to handle their status changes. */
6335 update_tick
= process_tick
;
6337 FOR_EACH_PROCESS (tail
, proc
)
6340 register struct Lisp_Process
*p
= XPROCESS (proc
);
6342 if (p
->tick
!= p
->update_tick
)
6344 p
->update_tick
= p
->tick
;
6346 /* If process is still active, read any output that remains. */
6347 while (! EQ (p
->filter
, Qt
)
6348 && ! EQ (p
->status
, Qconnect
)
6349 && ! EQ (p
->status
, Qlisten
)
6350 /* Network or serial process not stopped: */
6351 && ! EQ (p
->command
, Qt
)
6353 && p
!= deleting_process
)
6355 int nread
= read_process_output (proc
, p
->infd
);
6356 if (got_some_input
< nread
)
6357 got_some_input
= nread
;
6362 /* Get the text to use for the message. */
6363 if (p
->raw_status_new
)
6365 msg
= status_message (p
);
6367 /* If process is terminated, deactivate it or delete it. */
6369 if (CONSP (p
->status
))
6370 symbol
= XCAR (p
->status
);
6372 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6373 || EQ (symbol
, Qclosed
))
6375 if (delete_exited_processes
)
6376 remove_process (proc
);
6378 deactivate_process (proc
);
6381 /* The actions above may have further incremented p->tick.
6382 So set p->update_tick again so that an error in the sentinel will
6383 not cause this code to be run again. */
6384 p
->update_tick
= p
->tick
;
6385 /* Now output the message suitably. */
6386 exec_sentinel (proc
, msg
);
6390 update_mode_lines
= 24; /* In case buffers use %s in mode-line-format. */
6392 return got_some_input
;
6395 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6396 Sinternal_default_process_sentinel
, 2, 2, 0,
6397 doc
: /* Function used as default sentinel for processes.
6398 This inserts a status message into the process's buffer, if there is one. */)
6399 (Lisp_Object proc
, Lisp_Object msg
)
6401 Lisp_Object buffer
, symbol
;
6402 struct Lisp_Process
*p
;
6403 CHECK_PROCESS (proc
);
6404 p
= XPROCESS (proc
);
6408 symbol
= XCAR (symbol
);
6410 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6413 struct buffer
*old
= current_buffer
;
6414 ptrdiff_t opoint
, opoint_byte
;
6415 ptrdiff_t before
, before_byte
;
6417 /* Avoid error if buffer is deleted
6418 (probably that's why the process is dead, too). */
6419 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6421 Fset_buffer (buffer
);
6423 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6424 msg
= (code_convert_string_norecord
6425 (msg
, Vlocale_coding_system
, 1));
6428 opoint_byte
= PT_BYTE
;
6429 /* Insert new output into buffer
6430 at the current end-of-output marker,
6431 thus preserving logical ordering of input and output. */
6432 if (XMARKER (p
->mark
)->buffer
)
6433 Fgoto_char (p
->mark
);
6435 SET_PT_BOTH (ZV
, ZV_BYTE
);
6438 before_byte
= PT_BYTE
;
6440 tem
= BVAR (current_buffer
, read_only
);
6441 bset_read_only (current_buffer
, Qnil
);
6442 insert_string ("\nProcess ");
6443 { /* FIXME: temporary kludge. */
6444 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6445 insert_string (" ");
6447 bset_read_only (current_buffer
, tem
);
6448 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6450 if (opoint
>= before
)
6451 SET_PT_BOTH (opoint
+ (PT
- before
),
6452 opoint_byte
+ (PT_BYTE
- before_byte
));
6454 SET_PT_BOTH (opoint
, opoint_byte
);
6456 set_buffer_internal (old
);
6462 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6463 Sset_process_coding_system
, 1, 3, 0,
6464 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6465 DECODING will be used to decode subprocess output and ENCODING to
6466 encode subprocess input. */)
6467 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6469 register struct Lisp_Process
*p
;
6471 CHECK_PROCESS (process
);
6472 p
= XPROCESS (process
);
6474 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6476 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6477 Fcheck_coding_system (decoding
);
6478 Fcheck_coding_system (encoding
);
6479 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6480 pset_decode_coding_system (p
, decoding
);
6481 pset_encode_coding_system (p
, encoding
);
6482 setup_process_coding_systems (process
);
6487 DEFUN ("process-coding-system",
6488 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6489 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6490 (register Lisp_Object process
)
6492 CHECK_PROCESS (process
);
6493 return Fcons (XPROCESS (process
)->decode_coding_system
,
6494 XPROCESS (process
)->encode_coding_system
);
6497 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6498 Sset_process_filter_multibyte
, 2, 2, 0,
6499 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6500 If FLAG is non-nil, the filter is given multibyte strings.
6501 If FLAG is nil, the filter is given unibyte strings. In this case,
6502 all character code conversion except for end-of-line conversion is
6504 (Lisp_Object process
, Lisp_Object flag
)
6506 register struct Lisp_Process
*p
;
6508 CHECK_PROCESS (process
);
6509 p
= XPROCESS (process
);
6511 pset_decode_coding_system
6512 (p
, raw_text_coding_system (p
->decode_coding_system
));
6513 setup_process_coding_systems (process
);
6518 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6519 Sprocess_filter_multibyte_p
, 1, 1, 0,
6520 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6521 (Lisp_Object process
)
6523 register struct Lisp_Process
*p
;
6524 struct coding_system
*coding
;
6526 CHECK_PROCESS (process
);
6527 p
= XPROCESS (process
);
6530 coding
= proc_decode_coding_system
[p
->infd
];
6531 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6540 add_gpm_wait_descriptor (int desc
)
6542 add_keyboard_wait_descriptor (desc
);
6546 delete_gpm_wait_descriptor (int desc
)
6548 delete_keyboard_wait_descriptor (desc
);
6553 # ifdef USABLE_SIGIO
6555 /* Return true if *MASK has a bit set
6556 that corresponds to one of the keyboard input descriptors. */
6559 keyboard_bit_set (fd_set
*mask
)
6563 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6564 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6565 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6572 #else /* not subprocesses */
6574 /* Defined in msdos.c. */
6575 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
6576 struct timespec
*, void *);
6578 /* Implementation of wait_reading_process_output, assuming that there
6579 are no subprocesses. Used only by the MS-DOS build.
6581 Wait for timeout to elapse and/or keyboard input to be available.
6585 If negative, gobble data immediately available but don't wait for any.
6588 an additional duration to wait, measured in nanoseconds
6589 If TIME_LIMIT is zero, then:
6590 If NSECS == 0, there is no limit.
6591 If NSECS > 0, the timeout consists of NSECS only.
6592 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6595 0 to ignore keyboard input, or
6596 1 to return when input is available, or
6597 -1 means caller will actually read the input, so don't throw to
6600 see full version for other parameters. We know that wait_proc will
6601 always be NULL, since `subprocesses' isn't defined.
6603 DO_DISPLAY means redisplay should be done to show subprocess
6604 output that arrives.
6606 Return positive if we received input from WAIT_PROC (or from any
6607 process if WAIT_PROC is null), zero if we attempted to receive
6608 input but got none, and negative if we didn't even try. */
6611 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6613 Lisp_Object wait_for_cell
,
6614 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6617 struct timespec end_time
, timeout
;
6624 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6625 time_limit
= TYPE_MAXIMUM (time_t);
6627 /* What does time_limit really mean? */
6628 if (time_limit
|| nsecs
> 0)
6630 timeout
= make_timespec (time_limit
, nsecs
);
6631 end_time
= timespec_add (current_timespec (), timeout
);
6634 /* Turn off periodic alarms (in case they are in use)
6635 and then turn off any other atimers,
6636 because the select emulator uses alarms. */
6638 turn_on_atimers (0);
6642 bool timeout_reduced_for_timers
= false;
6643 fd_set waitchannels
;
6646 /* If calling from keyboard input, do not quit
6647 since we want to return C-g as an input character.
6648 Otherwise, do pending quit if requested. */
6652 /* Exit now if the cell we're waiting for became non-nil. */
6653 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6656 /* Compute time from now till when time limit is up. */
6657 /* Exit if already run out. */
6660 /* A negative timeout means
6661 gobble output available now
6662 but don't wait at all. */
6664 timeout
= make_timespec (0, 0);
6666 else if (time_limit
|| nsecs
> 0)
6668 struct timespec now
= current_timespec ();
6669 if (timespec_cmp (end_time
, now
) <= 0)
6671 timeout
= timespec_sub (end_time
, now
);
6675 timeout
= make_timespec (100000, 0);
6678 /* If our caller will not immediately handle keyboard events,
6679 run timer events directly.
6680 (Callers that will immediately read keyboard events
6681 call timer_delay on their own.) */
6682 if (NILP (wait_for_cell
))
6684 struct timespec timer_delay
;
6688 unsigned old_timers_run
= timers_run
;
6689 timer_delay
= timer_check ();
6690 if (timers_run
!= old_timers_run
&& do_display
)
6691 /* We must retry, since a timer may have requeued itself
6692 and that could alter the time delay. */
6693 redisplay_preserve_echo_area (14);
6697 while (!detect_input_pending ());
6699 /* If there is unread keyboard input, also return. */
6701 && requeued_events_pending_p ())
6704 if (timespec_valid_p (timer_delay
) && nsecs
>= 0)
6706 if (timespec_cmp (timer_delay
, timeout
) < 0)
6708 timeout
= timer_delay
;
6709 timeout_reduced_for_timers
= true;
6714 /* Cause C-g and alarm signals to take immediate action,
6715 and cause input available signals to zero out timeout. */
6717 set_waiting_for_input (&timeout
);
6719 /* If a frame has been newly mapped and needs updating,
6720 reprocess its display stuff. */
6721 if (frame_garbaged
&& do_display
)
6723 clear_waiting_for_input ();
6724 redisplay_preserve_echo_area (15);
6726 set_waiting_for_input (&timeout
);
6729 /* Wait till there is something to do. */
6730 FD_ZERO (&waitchannels
);
6731 if (read_kbd
&& detect_input_pending ())
6735 if (read_kbd
|| !NILP (wait_for_cell
))
6736 FD_SET (0, &waitchannels
);
6737 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6742 /* Make C-g and alarm signals set flags again. */
6743 clear_waiting_for_input ();
6745 /* If we woke up due to SIGWINCH, actually change size now. */
6746 do_pending_window_change (0);
6748 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6749 /* We waited the full specified time, so return now. */
6754 /* If the system call was interrupted, then go around the
6756 if (xerrno
== EINTR
)
6757 FD_ZERO (&waitchannels
);
6759 report_file_errno ("Failed select", Qnil
, xerrno
);
6762 /* Check for keyboard input. */
6765 && detect_input_pending_run_timers (do_display
))
6767 swallow_events (do_display
);
6768 if (detect_input_pending_run_timers (do_display
))
6772 /* If there is unread keyboard input, also return. */
6774 && requeued_events_pending_p ())
6777 /* If wait_for_cell. check for keyboard input
6778 but don't run any timers.
6779 ??? (It seems wrong to me to check for keyboard
6780 input at all when wait_for_cell, but the code
6781 has been this way since July 1994.
6782 Try changing this after version 19.31.) */
6783 if (! NILP (wait_for_cell
)
6784 && detect_input_pending ())
6786 swallow_events (do_display
);
6787 if (detect_input_pending ())
6791 /* Exit now if the cell we're waiting for became non-nil. */
6792 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6801 #endif /* not subprocesses */
6803 /* The following functions are needed even if async subprocesses are
6804 not supported. Some of them are no-op stubs in that case. */
6808 /* Add FD, which is a descriptor returned by timerfd_create,
6809 to the set of non-keyboard input descriptors. */
6812 add_timer_wait_descriptor (int fd
)
6814 FD_SET (fd
, &input_wait_mask
);
6815 FD_SET (fd
, &non_keyboard_wait_mask
);
6816 FD_SET (fd
, &non_process_wait_mask
);
6817 fd_callback_info
[fd
].func
= timerfd_callback
;
6818 fd_callback_info
[fd
].data
= NULL
;
6819 fd_callback_info
[fd
].condition
|= FOR_READ
;
6820 if (fd
> max_input_desc
)
6821 max_input_desc
= fd
;
6824 #endif /* HAVE_TIMERFD */
6826 /* Add DESC to the set of keyboard input descriptors. */
6829 add_keyboard_wait_descriptor (int desc
)
6831 #ifdef subprocesses /* Actually means "not MSDOS". */
6832 FD_SET (desc
, &input_wait_mask
);
6833 FD_SET (desc
, &non_process_wait_mask
);
6834 if (desc
> max_input_desc
)
6835 max_input_desc
= desc
;
6839 /* From now on, do not expect DESC to give keyboard input. */
6842 delete_keyboard_wait_descriptor (int desc
)
6845 FD_CLR (desc
, &input_wait_mask
);
6846 FD_CLR (desc
, &non_process_wait_mask
);
6847 delete_input_desc (desc
);
6851 /* Setup coding systems of PROCESS. */
6854 setup_process_coding_systems (Lisp_Object process
)
6857 struct Lisp_Process
*p
= XPROCESS (process
);
6859 int outch
= p
->outfd
;
6860 Lisp_Object coding_system
;
6862 if (inch
< 0 || outch
< 0)
6865 if (!proc_decode_coding_system
[inch
])
6866 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6867 coding_system
= p
->decode_coding_system
;
6868 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6869 && BUFFERP (p
->buffer
))
6871 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6872 coding_system
= raw_text_coding_system (coding_system
);
6874 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6876 if (!proc_encode_coding_system
[outch
])
6877 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6878 setup_coding_system (p
->encode_coding_system
,
6879 proc_encode_coding_system
[outch
]);
6883 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6884 doc
: /* Return the (or a) process associated with BUFFER.
6885 BUFFER may be a buffer or the name of one. */)
6886 (register Lisp_Object buffer
)
6889 register Lisp_Object buf
, tail
, proc
;
6891 if (NILP (buffer
)) return Qnil
;
6892 buf
= Fget_buffer (buffer
);
6893 if (NILP (buf
)) return Qnil
;
6895 FOR_EACH_PROCESS (tail
, proc
)
6896 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6898 #endif /* subprocesses */
6902 DEFUN ("process-inherit-coding-system-flag",
6903 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
6905 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
6906 If this flag is t, `buffer-file-coding-system' of the buffer
6907 associated with PROCESS will inherit the coding system used to decode
6908 the process output. */)
6909 (register Lisp_Object process
)
6912 CHECK_PROCESS (process
);
6913 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
6915 /* Ignore the argument and return the value of
6916 inherit-process-coding-system. */
6917 return inherit_process_coding_system
? Qt
: Qnil
;
6921 /* Kill all processes associated with `buffer'.
6922 If `buffer' is nil, kill all processes. */
6925 kill_buffer_processes (Lisp_Object buffer
)
6928 Lisp_Object tail
, proc
;
6930 FOR_EACH_PROCESS (tail
, proc
)
6931 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
6933 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
6934 Fdelete_process (proc
);
6935 else if (XPROCESS (proc
)->infd
>= 0)
6936 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
6938 #else /* subprocesses */
6939 /* Since we have no subprocesses, this does nothing. */
6940 #endif /* subprocesses */
6943 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
6944 Swaiting_for_user_input_p
, 0, 0, 0,
6945 doc
: /* Return non-nil if Emacs is waiting for input from the user.
6946 This is intended for use by asynchronous process output filters and sentinels. */)
6950 return (waiting_for_user_input_p
? Qt
: Qnil
);
6956 /* Stop reading input from keyboard sources. */
6959 hold_keyboard_input (void)
6964 /* Resume reading input from keyboard sources. */
6967 unhold_keyboard_input (void)
6972 /* Return true if keyboard input is on hold, zero otherwise. */
6975 kbd_on_hold_p (void)
6977 return kbd_is_on_hold
;
6981 /* Enumeration of and access to system processes a-la ps(1). */
6983 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
6985 doc
: /* Return a list of numerical process IDs of all running processes.
6986 If this functionality is unsupported, return nil.
6988 See `process-attributes' for getting attributes of a process given its ID. */)
6991 return list_system_processes ();
6994 DEFUN ("process-attributes", Fprocess_attributes
,
6995 Sprocess_attributes
, 1, 1, 0,
6996 doc
: /* Return attributes of the process given by its PID, a number.
6998 Value is an alist where each element is a cons cell of the form
7002 If this functionality is unsupported, the value is nil.
7004 See `list-system-processes' for getting a list of all process IDs.
7006 The KEYs of the attributes that this function may return are listed
7007 below, together with the type of the associated VALUE (in parentheses).
7008 Not all platforms support all of these attributes; unsupported
7009 attributes will not appear in the returned alist.
7010 Unless explicitly indicated otherwise, numbers can have either
7011 integer or floating point values.
7013 euid -- Effective user User ID of the process (number)
7014 user -- User name corresponding to euid (string)
7015 egid -- Effective user Group ID of the process (number)
7016 group -- Group name corresponding to egid (string)
7017 comm -- Command name (executable name only) (string)
7018 state -- Process state code, such as "S", "R", or "T" (string)
7019 ppid -- Parent process ID (number)
7020 pgrp -- Process group ID (number)
7021 sess -- Session ID, i.e. process ID of session leader (number)
7022 ttname -- Controlling tty name (string)
7023 tpgid -- ID of foreground process group on the process's tty (number)
7024 minflt -- number of minor page faults (number)
7025 majflt -- number of major page faults (number)
7026 cminflt -- cumulative number of minor page faults (number)
7027 cmajflt -- cumulative number of major page faults (number)
7028 utime -- user time used by the process, in (current-time) format,
7029 which is a list of integers (HIGH LOW USEC PSEC)
7030 stime -- system time used by the process (current-time)
7031 time -- sum of utime and stime (current-time)
7032 cutime -- user time used by the process and its children (current-time)
7033 cstime -- system time used by the process and its children (current-time)
7034 ctime -- sum of cutime and cstime (current-time)
7035 pri -- priority of the process (number)
7036 nice -- nice value of the process (number)
7037 thcount -- process thread count (number)
7038 start -- time the process started (current-time)
7039 vsize -- virtual memory size of the process in KB's (number)
7040 rss -- resident set size of the process in KB's (number)
7041 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7042 pcpu -- percents of CPU time used by the process (floating-point number)
7043 pmem -- percents of total physical memory used by process's resident set
7044 (floating-point number)
7045 args -- command line which invoked the process (string). */)
7048 return system_process_attributes (pid
);
7052 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7053 Invoke this after init_process_emacs, and after glib and/or GNUstep
7054 futz with the SIGCHLD handler, but before Emacs forks any children.
7055 This function's caller should block SIGCHLD. */
7058 catch_child_signal (void)
7060 struct sigaction action
, old_action
;
7062 emacs_sigaction_init (&action
, deliver_child_signal
);
7063 block_child_signal (&oldset
);
7064 sigaction (SIGCHLD
, &action
, &old_action
);
7065 eassert (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7066 || ! (old_action
.sa_flags
& SA_SIGINFO
));
7068 if (old_action
.sa_handler
!= deliver_child_signal
)
7070 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7072 : old_action
.sa_handler
);
7073 unblock_child_signal (&oldset
);
7075 #endif /* subprocesses */
7078 /* This is not called "init_process" because that is the name of a
7079 Mach system call, so it would cause problems on Darwin systems. */
7081 init_process_emacs (void)
7086 inhibit_sentinels
= 0;
7089 if (! noninteractive
|| initialized
)
7092 #if defined HAVE_GLIB && !defined WINDOWSNT
7093 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7094 this should always fail, but is enough to initialize glib's
7095 private SIGCHLD handler, allowing catch_child_signal to copy
7096 it into lib_child_handler. */
7097 g_source_unref (g_child_watch_source_new (getpid ()));
7099 catch_child_signal ();
7102 FD_ZERO (&input_wait_mask
);
7103 FD_ZERO (&non_keyboard_wait_mask
);
7104 FD_ZERO (&non_process_wait_mask
);
7105 FD_ZERO (&write_mask
);
7106 max_process_desc
= max_input_desc
= -1;
7107 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7109 #ifdef NON_BLOCKING_CONNECT
7110 FD_ZERO (&connect_wait_mask
);
7111 num_pending_connects
= 0;
7114 #ifdef ADAPTIVE_READ_BUFFERING
7115 process_output_delay_count
= 0;
7116 process_output_skip
= 0;
7119 /* Don't do this, it caused infinite select loops. The display
7120 method should call add_keyboard_wait_descriptor on stdin if it
7123 FD_SET (0, &input_wait_mask
);
7126 Vprocess_alist
= Qnil
;
7127 deleted_pid_list
= Qnil
;
7128 for (i
= 0; i
< FD_SETSIZE
; i
++)
7130 chan_process
[i
] = Qnil
;
7131 proc_buffered_char
[i
] = -1;
7133 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7134 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7135 #ifdef DATAGRAM_SOCKETS
7136 memset (datagram_address
, 0, sizeof datagram_address
);
7140 Lisp_Object subfeatures
= Qnil
;
7141 const struct socket_options
*sopt
;
7143 #define ADD_SUBFEATURE(key, val) \
7144 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7146 #ifdef NON_BLOCKING_CONNECT
7147 ADD_SUBFEATURE (QCnowait
, Qt
);
7149 #ifdef DATAGRAM_SOCKETS
7150 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7152 #ifdef HAVE_SEQPACKET
7153 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7155 #ifdef HAVE_LOCAL_SOCKETS
7156 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7158 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7160 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7162 #ifdef HAVE_GETSOCKNAME
7163 ADD_SUBFEATURE (QCservice
, Qt
);
7165 ADD_SUBFEATURE (QCserver
, Qt
);
7167 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7168 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7170 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7173 #if defined (DARWIN_OS)
7174 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7175 processes. As such, we only change the default value. */
7178 char const *release
= (STRINGP (Voperating_system_release
)
7179 ? SSDATA (Voperating_system_release
)
7181 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7182 Vprocess_connection_type
= Qnil
;
7186 #endif /* subprocesses */
7191 syms_of_process (void)
7195 DEFSYM (Qprocessp
, "processp");
7196 DEFSYM (Qrun
, "run");
7197 DEFSYM (Qstop
, "stop");
7198 DEFSYM (Qsignal
, "signal");
7200 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7203 DEFSYM (Qopen
, "open");
7204 DEFSYM (Qclosed
, "closed");
7205 DEFSYM (Qconnect
, "connect");
7206 DEFSYM (Qfailed
, "failed");
7207 DEFSYM (Qlisten
, "listen");
7208 DEFSYM (Qlocal
, "local");
7209 DEFSYM (Qipv4
, "ipv4");
7211 DEFSYM (Qipv6
, "ipv6");
7213 DEFSYM (Qdatagram
, "datagram");
7214 DEFSYM (Qseqpacket
, "seqpacket");
7216 DEFSYM (QCport
, ":port");
7217 DEFSYM (QCspeed
, ":speed");
7218 DEFSYM (QCprocess
, ":process");
7220 DEFSYM (QCbytesize
, ":bytesize");
7221 DEFSYM (QCstopbits
, ":stopbits");
7222 DEFSYM (QCparity
, ":parity");
7223 DEFSYM (Qodd
, "odd");
7224 DEFSYM (Qeven
, "even");
7225 DEFSYM (QCflowcontrol
, ":flowcontrol");
7228 DEFSYM (QCsummary
, ":summary");
7230 DEFSYM (Qreal
, "real");
7231 DEFSYM (Qnetwork
, "network");
7232 DEFSYM (Qserial
, "serial");
7233 DEFSYM (QCbuffer
, ":buffer");
7234 DEFSYM (QChost
, ":host");
7235 DEFSYM (QCservice
, ":service");
7236 DEFSYM (QClocal
, ":local");
7237 DEFSYM (QCremote
, ":remote");
7238 DEFSYM (QCcoding
, ":coding");
7239 DEFSYM (QCserver
, ":server");
7240 DEFSYM (QCnowait
, ":nowait");
7241 DEFSYM (QCsentinel
, ":sentinel");
7242 DEFSYM (QClog
, ":log");
7243 DEFSYM (QCnoquery
, ":noquery");
7244 DEFSYM (QCstop
, ":stop");
7245 DEFSYM (QCoptions
, ":options");
7246 DEFSYM (QCplist
, ":plist");
7248 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7250 staticpro (&Vprocess_alist
);
7251 staticpro (&deleted_pid_list
);
7253 #endif /* subprocesses */
7255 DEFSYM (QCname
, ":name");
7256 DEFSYM (QCtype
, ":type");
7258 DEFSYM (Qeuid
, "euid");
7259 DEFSYM (Qegid
, "egid");
7260 DEFSYM (Quser
, "user");
7261 DEFSYM (Qgroup
, "group");
7262 DEFSYM (Qcomm
, "comm");
7263 DEFSYM (Qstate
, "state");
7264 DEFSYM (Qppid
, "ppid");
7265 DEFSYM (Qpgrp
, "pgrp");
7266 DEFSYM (Qsess
, "sess");
7267 DEFSYM (Qttname
, "ttname");
7268 DEFSYM (Qtpgid
, "tpgid");
7269 DEFSYM (Qminflt
, "minflt");
7270 DEFSYM (Qmajflt
, "majflt");
7271 DEFSYM (Qcminflt
, "cminflt");
7272 DEFSYM (Qcmajflt
, "cmajflt");
7273 DEFSYM (Qutime
, "utime");
7274 DEFSYM (Qstime
, "stime");
7275 DEFSYM (Qtime
, "time");
7276 DEFSYM (Qcutime
, "cutime");
7277 DEFSYM (Qcstime
, "cstime");
7278 DEFSYM (Qctime
, "ctime");
7280 DEFSYM (Qinternal_default_process_sentinel
,
7281 "internal-default-process-sentinel");
7282 DEFSYM (Qinternal_default_process_filter
,
7283 "internal-default-process-filter");
7285 DEFSYM (Qpri
, "pri");
7286 DEFSYM (Qnice
, "nice");
7287 DEFSYM (Qthcount
, "thcount");
7288 DEFSYM (Qstart
, "start");
7289 DEFSYM (Qvsize
, "vsize");
7290 DEFSYM (Qrss
, "rss");
7291 DEFSYM (Qetime
, "etime");
7292 DEFSYM (Qpcpu
, "pcpu");
7293 DEFSYM (Qpmem
, "pmem");
7294 DEFSYM (Qargs
, "args");
7296 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7297 doc
: /* Non-nil means delete processes immediately when they exit.
7298 A value of nil means don't delete them until `list-processes' is run. */);
7300 delete_exited_processes
= 1;
7303 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7304 doc
: /* Control type of device used to communicate with subprocesses.
7305 Values are nil to use a pipe, or t or `pty' to use a pty.
7306 The value has no effect if the system has no ptys or if all ptys are busy:
7307 then a pipe is used in any case.
7308 The value takes effect when `start-process' is called. */);
7309 Vprocess_connection_type
= Qt
;
7311 #ifdef ADAPTIVE_READ_BUFFERING
7312 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7313 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7314 On some systems, when Emacs reads the output from a subprocess, the output data
7315 is read in very small blocks, potentially resulting in very poor performance.
7316 This behavior can be remedied to some extent by setting this variable to a
7317 non-nil value, as it will automatically delay reading from such processes, to
7318 allow them to produce more output before Emacs tries to read it.
7319 If the value is t, the delay is reset after each write to the process; any other
7320 non-nil value means that the delay is not reset on write.
7321 The variable takes effect when `start-process' is called. */);
7322 Vprocess_adaptive_read_buffering
= Qt
;
7325 defsubr (&Sprocessp
);
7326 defsubr (&Sget_process
);
7327 defsubr (&Sdelete_process
);
7328 defsubr (&Sprocess_status
);
7329 defsubr (&Sprocess_exit_status
);
7330 defsubr (&Sprocess_id
);
7331 defsubr (&Sprocess_name
);
7332 defsubr (&Sprocess_tty_name
);
7333 defsubr (&Sprocess_command
);
7334 defsubr (&Sset_process_buffer
);
7335 defsubr (&Sprocess_buffer
);
7336 defsubr (&Sprocess_mark
);
7337 defsubr (&Sset_process_filter
);
7338 defsubr (&Sprocess_filter
);
7339 defsubr (&Sset_process_sentinel
);
7340 defsubr (&Sprocess_sentinel
);
7341 defsubr (&Sset_process_window_size
);
7342 defsubr (&Sset_process_inherit_coding_system_flag
);
7343 defsubr (&Sset_process_query_on_exit_flag
);
7344 defsubr (&Sprocess_query_on_exit_flag
);
7345 defsubr (&Sprocess_contact
);
7346 defsubr (&Sprocess_plist
);
7347 defsubr (&Sset_process_plist
);
7348 defsubr (&Sprocess_list
);
7349 defsubr (&Sstart_process
);
7350 defsubr (&Sserial_process_configure
);
7351 defsubr (&Smake_serial_process
);
7352 defsubr (&Sset_network_process_option
);
7353 defsubr (&Smake_network_process
);
7354 defsubr (&Sformat_network_address
);
7355 defsubr (&Snetwork_interface_list
);
7356 defsubr (&Snetwork_interface_info
);
7357 #ifdef DATAGRAM_SOCKETS
7358 defsubr (&Sprocess_datagram_address
);
7359 defsubr (&Sset_process_datagram_address
);
7361 defsubr (&Saccept_process_output
);
7362 defsubr (&Sprocess_send_region
);
7363 defsubr (&Sprocess_send_string
);
7364 defsubr (&Sinterrupt_process
);
7365 defsubr (&Skill_process
);
7366 defsubr (&Squit_process
);
7367 defsubr (&Sstop_process
);
7368 defsubr (&Scontinue_process
);
7369 defsubr (&Sprocess_running_child_p
);
7370 defsubr (&Sprocess_send_eof
);
7371 defsubr (&Ssignal_process
);
7372 defsubr (&Swaiting_for_user_input_p
);
7373 defsubr (&Sprocess_type
);
7374 defsubr (&Sinternal_default_process_sentinel
);
7375 defsubr (&Sinternal_default_process_filter
);
7376 defsubr (&Sset_process_coding_system
);
7377 defsubr (&Sprocess_coding_system
);
7378 defsubr (&Sset_process_filter_multibyte
);
7379 defsubr (&Sprocess_filter_multibyte_p
);
7381 #endif /* subprocesses */
7383 defsubr (&Sget_buffer_process
);
7384 defsubr (&Sprocess_inherit_coding_system_flag
);
7385 defsubr (&Slist_system_processes
);
7386 defsubr (&Sprocess_attributes
);