1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2014
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
34 /* Only MS-DOS does not define `subprocesses'. */
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
48 #define HAVE_LOCAL_SOCKETS
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
79 #include <arpa/nameser.h>
95 #endif /* subprocesses */
101 #include "character.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
121 #ifdef HAVE_WINDOW_SYSTEM
123 #endif /* HAVE_WINDOW_SYSTEM */
126 #include "xgselect.h"
133 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
134 struct timespec
*, void *);
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
144 Lisp_Object Qeuid
, Qegid
, Qcomm
, Qstate
, Qppid
, Qpgrp
, Qsess
, Qttname
, Qtpgid
;
145 Lisp_Object Qminflt
, Qmajflt
, Qcminflt
, Qcmajflt
, Qutime
, Qstime
, Qcstime
;
146 Lisp_Object Qcutime
, Qpri
, Qnice
, Qthcount
, Qstart
, Qvsize
, Qrss
, Qargs
;
147 Lisp_Object Quser
, Qgroup
, Qetime
, Qpcpu
, Qpmem
, Qtime
, Qctime
;
148 Lisp_Object QCname
, QCtype
;
150 /* True if keyboard input is on hold, zero otherwise. */
152 static bool kbd_is_on_hold
;
154 /* Nonzero means don't run process sentinels. This is used
156 bool inhibit_sentinels
;
161 # define SOCK_CLOEXEC 0
166 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
169 close_on_exec (int fd
)
172 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
177 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
179 return close_on_exec (accept (sockfd
, addr
, addrlen
));
183 process_socket (int domain
, int type
, int protocol
)
185 return close_on_exec (socket (domain
, type
, protocol
));
188 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
191 Lisp_Object Qprocessp
;
192 static Lisp_Object Qrun
, Qstop
, Qsignal
;
193 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
195 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
196 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
198 static Lisp_Object Qipv6
;
200 static Lisp_Object QCport
, QCprocess
;
202 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
203 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
204 static Lisp_Object QCbuffer
, QChost
, QCservice
;
205 static Lisp_Object QClocal
, QCremote
, QCcoding
;
206 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
207 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
208 static Lisp_Object Qlast_nonmenu_event
;
209 static Lisp_Object Qinternal_default_process_sentinel
;
210 static Lisp_Object Qinternal_default_process_filter
;
212 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
213 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
214 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
215 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick
;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick
;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 /* Only W32 has this, it really means that select can't take write mask. */
225 #ifdef BROKEN_NON_BLOCKING_CONNECT
226 #undef NON_BLOCKING_CONNECT
227 enum { SELECT_CAN_DO_WRITE_MASK
= false };
229 enum { SELECT_CAN_DO_WRITE_MASK
= true };
230 #ifndef NON_BLOCKING_CONNECT
232 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
233 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
234 #define NON_BLOCKING_CONNECT
235 #endif /* EWOULDBLOCK || EINPROGRESS */
236 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
237 #endif /* HAVE_SELECT */
238 #endif /* NON_BLOCKING_CONNECT */
239 #endif /* BROKEN_NON_BLOCKING_CONNECT */
241 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
242 this system. We need to read full packets, so we need a
243 "non-destructive" select. So we require either native select,
244 or emulation of select using FIONREAD. */
246 #ifndef BROKEN_DATAGRAM_SOCKETS
247 # if defined HAVE_SELECT || defined USABLE_FIONREAD
248 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
249 # define DATAGRAM_SOCKETS
254 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
255 # define HAVE_SEQPACKET
258 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
259 #define ADAPTIVE_READ_BUFFERING
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count
;
272 /* True if any process has non-nil read_output_skip. */
274 static bool process_output_skip
;
277 #define process_output_delay_count 0
280 static void create_process (Lisp_Object
, char **, Lisp_Object
);
282 static bool keyboard_bit_set (fd_set
*);
284 static void deactivate_process (Lisp_Object
);
285 static int status_notify (struct Lisp_Process
*, struct Lisp_Process
*);
286 static int read_process_output (Lisp_Object
, int);
287 static void handle_child_signal (int);
288 static void create_pty (Lisp_Object
);
290 static Lisp_Object
get_process (register Lisp_Object name
);
291 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
293 /* Mask of bits indicating the descriptors that we wait for input on. */
295 static fd_set input_wait_mask
;
297 /* Mask that excludes keyboard input descriptor(s). */
299 static fd_set non_keyboard_wait_mask
;
301 /* Mask that excludes process input descriptor(s). */
303 static fd_set non_process_wait_mask
;
305 /* Mask for selecting for write. */
307 static fd_set write_mask
;
309 #ifdef NON_BLOCKING_CONNECT
310 /* Mask of bits indicating the descriptors that we wait for connect to
311 complete on. Once they complete, they are removed from this mask
312 and added to the input_wait_mask and non_keyboard_wait_mask. */
314 static fd_set connect_wait_mask
;
316 /* Number of bits set in connect_wait_mask. */
317 static int num_pending_connects
;
318 #endif /* NON_BLOCKING_CONNECT */
320 /* The largest descriptor currently in use for a process object; -1 if none. */
321 static int max_process_desc
;
323 /* The largest descriptor currently in use for input; -1 if none. */
324 static int max_input_desc
;
326 /* Indexed by descriptor, gives the process (if any) for that descriptor */
327 static Lisp_Object chan_process
[FD_SETSIZE
];
329 /* Alist of elements (NAME . PROCESS) */
330 static Lisp_Object Vprocess_alist
;
332 /* Buffered-ahead input char from process, indexed by channel.
333 -1 means empty (no char is buffered).
334 Used on sys V where the only way to tell if there is any
335 output from the process is to read at least one char.
336 Always -1 on systems that support FIONREAD. */
338 static int proc_buffered_char
[FD_SETSIZE
];
340 /* Table of `struct coding-system' for each process. */
341 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
342 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
344 #ifdef DATAGRAM_SOCKETS
345 /* Table of `partner address' for datagram sockets. */
346 static struct sockaddr_and_len
{
349 } datagram_address
[FD_SETSIZE
];
350 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
351 #define DATAGRAM_CONN_P(proc) \
352 (PROCESSP (proc) && \
353 XPROCESS (proc)->infd >= 0 && \
354 datagram_address[XPROCESS (proc)->infd].sa != 0)
356 #define DATAGRAM_CHAN_P(chan) (0)
357 #define DATAGRAM_CONN_P(proc) (0)
360 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
361 a `for' loop which iterates over processes from Vprocess_alist. */
363 #define FOR_EACH_PROCESS(list_var, proc_var) \
364 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
366 /* These setters are used only in this file, so they can be private. */
368 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
373 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
380 p
->decode_coding_system
= val
;
383 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
385 p
->decoding_buf
= val
;
388 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
390 p
->encode_coding_system
= val
;
393 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
395 p
->encoding_buf
= val
;
398 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
400 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
403 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
408 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
413 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
418 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
423 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
425 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
428 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
433 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
438 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
443 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
445 p
->write_queue
= val
;
450 static struct fd_callback_data
456 int condition
; /* mask of the defines above. */
457 } fd_callback_info
[FD_SETSIZE
];
460 /* Add a file descriptor FD to be monitored for when read is possible.
461 When read is possible, call FUNC with argument DATA. */
464 add_read_fd (int fd
, fd_callback func
, void *data
)
466 add_keyboard_wait_descriptor (fd
);
468 fd_callback_info
[fd
].func
= func
;
469 fd_callback_info
[fd
].data
= data
;
470 fd_callback_info
[fd
].condition
|= FOR_READ
;
473 /* Stop monitoring file descriptor FD for when read is possible. */
476 delete_read_fd (int fd
)
478 delete_keyboard_wait_descriptor (fd
);
480 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
481 if (fd_callback_info
[fd
].condition
== 0)
483 fd_callback_info
[fd
].func
= 0;
484 fd_callback_info
[fd
].data
= 0;
488 /* Add a file descriptor FD to be monitored for when write is possible.
489 When write is possible, call FUNC with argument DATA. */
492 add_write_fd (int fd
, fd_callback func
, void *data
)
494 FD_SET (fd
, &write_mask
);
495 if (fd
> max_input_desc
)
498 fd_callback_info
[fd
].func
= func
;
499 fd_callback_info
[fd
].data
= data
;
500 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
503 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
506 delete_input_desc (int fd
)
508 if (fd
== max_input_desc
)
512 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
513 || FD_ISSET (fd
, &write_mask
)));
519 /* Stop monitoring file descriptor FD for when write is possible. */
522 delete_write_fd (int fd
)
524 FD_CLR (fd
, &write_mask
);
525 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
526 if (fd_callback_info
[fd
].condition
== 0)
528 fd_callback_info
[fd
].func
= 0;
529 fd_callback_info
[fd
].data
= 0;
530 delete_input_desc (fd
);
535 /* Compute the Lisp form of the process status, p->status, from
536 the numeric status that was returned by `wait'. */
538 static Lisp_Object
status_convert (int);
541 update_status (struct Lisp_Process
*p
)
543 eassert (p
->raw_status_new
);
544 pset_status (p
, status_convert (p
->raw_status
));
545 p
->raw_status_new
= 0;
548 /* Convert a process status word in Unix format to
549 the list that we use internally. */
552 status_convert (int w
)
555 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
556 else if (WIFEXITED (w
))
557 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
558 WCOREDUMP (w
) ? Qt
: Qnil
));
559 else if (WIFSIGNALED (w
))
560 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
561 WCOREDUMP (w
) ? Qt
: Qnil
));
566 /* Given a status-list, extract the three pieces of information
567 and store them individually through the three pointers. */
570 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
584 *code
= XFASTINT (XCAR (tem
));
586 *coredump
= !NILP (tem
);
590 /* Return a string describing a process status list. */
593 status_message (struct Lisp_Process
*p
)
595 Lisp_Object status
= p
->status
;
599 Lisp_Object string
, string2
;
601 decode_status (status
, &symbol
, &code
, &coredump
);
603 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
606 synchronize_system_messages_locale ();
607 signame
= strsignal (code
);
609 string
= build_string ("unknown");
614 string
= build_unibyte_string (signame
);
615 if (! NILP (Vlocale_coding_system
))
616 string
= (code_convert_string_norecord
617 (string
, Vlocale_coding_system
, 0));
618 c1
= STRING_CHAR (SDATA (string
));
621 Faset (string
, make_number (0), make_number (c2
));
623 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
624 return concat2 (string
, string2
);
626 else if (EQ (symbol
, Qexit
))
629 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
631 return build_string ("finished\n");
632 string
= Fnumber_to_string (make_number (code
));
633 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
634 return concat3 (build_string ("exited abnormally with code "),
637 else if (EQ (symbol
, Qfailed
))
639 string
= Fnumber_to_string (make_number (code
));
640 string2
= build_string ("\n");
641 return concat3 (build_string ("failed with code "),
645 return Fcopy_sequence (Fsymbol_name (symbol
));
648 enum { PTY_NAME_SIZE
= 24 };
650 /* Open an available pty, returning a file descriptor.
651 Store into PTY_NAME the file name of the terminal corresponding to the pty.
652 Return -1 on failure. */
655 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
664 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
665 for (i
= 0; i
< 16; i
++)
668 #ifdef PTY_NAME_SPRINTF
671 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
672 #endif /* no PTY_NAME_SPRINTF */
676 #else /* no PTY_OPEN */
677 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
678 #endif /* no PTY_OPEN */
683 /* Set FD's close-on-exec flag. This is needed even if
684 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
685 doesn't require support for that combination.
686 Multithreaded platforms where posix_openpt ignores
687 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
688 have a race condition between the PTY_OPEN and here. */
689 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
691 /* check to make certain that both sides are available
692 this avoids a nasty yet stupid bug in rlogins */
693 #ifdef PTY_TTY_NAME_SPRINTF
696 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
697 #endif /* no PTY_TTY_NAME_SPRINTF */
698 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
711 #endif /* HAVE_PTYS */
716 make_process (Lisp_Object name
)
718 register Lisp_Object val
, tem
, name1
;
719 register struct Lisp_Process
*p
;
720 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
723 p
= allocate_process ();
724 /* Initialize Lisp data. Note that allocate_process initializes all
725 Lisp data to nil, so do it only for slots which should not be nil. */
726 pset_status (p
, Qrun
);
727 pset_mark (p
, Fmake_marker ());
729 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
730 non-Lisp data, so do it only for slots which should not be zero. */
733 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
737 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
740 /* If name is already in use, modify it until it is unused. */
745 tem
= Fget_process (name1
);
746 if (NILP (tem
)) break;
747 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
751 pset_sentinel (p
, Qinternal_default_process_sentinel
);
752 pset_filter (p
, Qinternal_default_process_filter
);
753 XSETPROCESS (val
, p
);
754 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
759 remove_process (register Lisp_Object proc
)
761 register Lisp_Object pair
;
763 pair
= Frassq (proc
, Vprocess_alist
);
764 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
766 deactivate_process (proc
);
770 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
771 doc
: /* Return t if OBJECT is a process. */)
774 return PROCESSP (object
) ? Qt
: Qnil
;
777 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
778 doc
: /* Return the process named NAME, or nil if there is none. */)
779 (register Lisp_Object name
)
784 return Fcdr (Fassoc (name
, Vprocess_alist
));
787 /* This is how commands for the user decode process arguments. It
788 accepts a process, a process name, a buffer, a buffer name, or nil.
789 Buffers denote the first process in the buffer, and nil denotes the
793 get_process (register Lisp_Object name
)
795 register Lisp_Object proc
, obj
;
798 obj
= Fget_process (name
);
800 obj
= Fget_buffer (name
);
802 error ("Process %s does not exist", SDATA (name
));
804 else if (NILP (name
))
805 obj
= Fcurrent_buffer ();
809 /* Now obj should be either a buffer object or a process object. */
812 if (NILP (BVAR (XBUFFER (obj
), name
)))
813 error ("Attempt to get process for a dead buffer");
814 proc
= Fget_buffer_process (obj
);
816 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
827 /* Fdelete_process promises to immediately forget about the process, but in
828 reality, Emacs needs to remember those processes until they have been
829 treated by the SIGCHLD handler and waitpid has been invoked on them;
830 otherwise they might fill up the kernel's process table.
832 Some processes created by call-process are also put onto this list.
834 Members of this list are (process-ID . filename) pairs. The
835 process-ID is a number; the filename, if a string, is a file that
836 needs to be removed after the process exits. */
837 static Lisp_Object deleted_pid_list
;
840 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
842 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
843 /* GC treated elements set to nil. */
844 Fdelq (Qnil
, deleted_pid_list
));
848 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
849 doc
: /* Delete PROCESS: kill it and forget about it immediately.
850 PROCESS may be a process, a buffer, the name of a process or buffer, or
851 nil, indicating the current buffer's process. */)
852 (register Lisp_Object process
)
854 register struct Lisp_Process
*p
;
856 process
= get_process (process
);
857 p
= XPROCESS (process
);
859 p
->raw_status_new
= 0;
860 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
862 pset_status (p
, list2 (Qexit
, make_number (0)));
863 p
->tick
= ++process_tick
;
864 status_notify (p
, NULL
);
865 redisplay_preserve_echo_area (13);
870 record_kill_process (p
, Qnil
);
874 /* Update P's status, since record_kill_process will make the
875 SIGCHLD handler update deleted_pid_list, not *P. */
877 if (p
->raw_status_new
)
879 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
880 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
881 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
883 p
->tick
= ++process_tick
;
884 status_notify (p
, NULL
);
885 redisplay_preserve_echo_area (13);
888 remove_process (process
);
892 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
893 doc
: /* Return the status of PROCESS.
894 The returned value is one of the following symbols:
895 run -- for a process that is running.
896 stop -- for a process stopped but continuable.
897 exit -- for a process that has exited.
898 signal -- for a process that has got a fatal signal.
899 open -- for a network stream connection that is open.
900 listen -- for a network stream server that is listening.
901 closed -- for a network stream connection that is closed.
902 connect -- when waiting for a non-blocking connection to complete.
903 failed -- when a non-blocking connection has failed.
904 nil -- if arg is a process name and no such process exists.
905 PROCESS may be a process, a buffer, the name of a process, or
906 nil, indicating the current buffer's process. */)
907 (register Lisp_Object process
)
909 register struct Lisp_Process
*p
;
910 register Lisp_Object status
;
912 if (STRINGP (process
))
913 process
= Fget_process (process
);
915 process
= get_process (process
);
920 p
= XPROCESS (process
);
921 if (p
->raw_status_new
)
925 status
= XCAR (status
);
926 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
928 if (EQ (status
, Qexit
))
930 else if (EQ (p
->command
, Qt
))
932 else if (EQ (status
, Qrun
))
938 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
940 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
941 If PROCESS has not yet exited or died, return 0. */)
942 (register Lisp_Object process
)
944 CHECK_PROCESS (process
);
945 if (XPROCESS (process
)->raw_status_new
)
946 update_status (XPROCESS (process
));
947 if (CONSP (XPROCESS (process
)->status
))
948 return XCAR (XCDR (XPROCESS (process
)->status
));
949 return make_number (0);
952 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
953 doc
: /* Return the process id of PROCESS.
954 This is the pid of the external process which PROCESS uses or talks to.
955 For a network connection, this value is nil. */)
956 (register Lisp_Object process
)
960 CHECK_PROCESS (process
);
961 pid
= XPROCESS (process
)->pid
;
962 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
965 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
966 doc
: /* Return the name of PROCESS, as a string.
967 This is the name of the program invoked in PROCESS,
968 possibly modified to make it unique among process names. */)
969 (register Lisp_Object process
)
971 CHECK_PROCESS (process
);
972 return XPROCESS (process
)->name
;
975 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
976 doc
: /* Return the command that was executed to start PROCESS.
977 This is a list of strings, the first string being the program executed
978 and the rest of the strings being the arguments given to it.
979 For a network or serial process, this is nil (process is running) or t
980 \(process is stopped). */)
981 (register Lisp_Object process
)
983 CHECK_PROCESS (process
);
984 return XPROCESS (process
)->command
;
987 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
988 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
989 This is the terminal that the process itself reads and writes on,
990 not the name of the pty that Emacs uses to talk with that terminal. */)
991 (register Lisp_Object process
)
993 CHECK_PROCESS (process
);
994 return XPROCESS (process
)->tty_name
;
997 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
999 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1001 (register Lisp_Object process
, Lisp_Object buffer
)
1003 struct Lisp_Process
*p
;
1005 CHECK_PROCESS (process
);
1007 CHECK_BUFFER (buffer
);
1008 p
= XPROCESS (process
);
1009 pset_buffer (p
, buffer
);
1010 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1011 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1012 setup_process_coding_systems (process
);
1016 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1018 doc
: /* Return the buffer PROCESS is associated with.
1019 The default process filter inserts output from PROCESS into this buffer. */)
1020 (register Lisp_Object process
)
1022 CHECK_PROCESS (process
);
1023 return XPROCESS (process
)->buffer
;
1026 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1028 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1029 (register Lisp_Object process
)
1031 CHECK_PROCESS (process
);
1032 return XPROCESS (process
)->mark
;
1035 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1037 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1038 A value of t means stop accepting output from the process.
1040 When a process has a non-default filter, its buffer is not used for output.
1041 Instead, each time it does output, the entire string of output is
1042 passed to the filter.
1044 The filter gets two arguments: the process and the string of output.
1045 The string argument is normally a multibyte string, except:
1046 - if the process's input coding system is no-conversion or raw-text,
1047 it is a unibyte string (the non-converted input), or else
1048 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1049 string (the result of converting the decoded input multibyte
1050 string to unibyte with `string-make-unibyte'). */)
1051 (register Lisp_Object process
, Lisp_Object filter
)
1053 struct Lisp_Process
*p
;
1055 CHECK_PROCESS (process
);
1056 p
= XPROCESS (process
);
1058 /* Don't signal an error if the process's input file descriptor
1059 is closed. This could make debugging Lisp more difficult,
1060 for example when doing something like
1062 (setq process (start-process ...))
1064 (set-process-filter process ...) */
1067 filter
= Qinternal_default_process_filter
;
1071 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1073 FD_CLR (p
->infd
, &input_wait_mask
);
1074 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1076 else if (EQ (p
->filter
, Qt
)
1077 /* Network or serial process not stopped: */
1078 && !EQ (p
->command
, Qt
))
1080 FD_SET (p
->infd
, &input_wait_mask
);
1081 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1085 pset_filter (p
, filter
);
1086 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1087 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1088 setup_process_coding_systems (process
);
1092 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1094 doc
: /* Return the filter function of PROCESS.
1095 See `set-process-filter' for more info on filter functions. */)
1096 (register Lisp_Object process
)
1098 CHECK_PROCESS (process
);
1099 return XPROCESS (process
)->filter
;
1102 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1104 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1105 The sentinel is called as a function when the process changes state.
1106 It gets two arguments: the process, and a string describing the change. */)
1107 (register Lisp_Object process
, Lisp_Object sentinel
)
1109 struct Lisp_Process
*p
;
1111 CHECK_PROCESS (process
);
1112 p
= XPROCESS (process
);
1114 if (NILP (sentinel
))
1115 sentinel
= Qinternal_default_process_sentinel
;
1117 pset_sentinel (p
, sentinel
);
1118 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1119 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1123 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1125 doc
: /* Return the sentinel of PROCESS.
1126 See `set-process-sentinel' for more info on sentinels. */)
1127 (register Lisp_Object process
)
1129 CHECK_PROCESS (process
);
1130 return XPROCESS (process
)->sentinel
;
1133 DEFUN ("set-process-window-size", Fset_process_window_size
,
1134 Sset_process_window_size
, 3, 3, 0,
1135 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1136 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1138 CHECK_PROCESS (process
);
1140 /* All known platforms store window sizes as 'unsigned short'. */
1141 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1142 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1144 if (XPROCESS (process
)->infd
< 0
1145 || (set_window_size (XPROCESS (process
)->infd
,
1146 XINT (height
), XINT (width
))
1153 DEFUN ("set-process-inherit-coding-system-flag",
1154 Fset_process_inherit_coding_system_flag
,
1155 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1156 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1157 If the second argument FLAG is non-nil, then the variable
1158 `buffer-file-coding-system' of the buffer associated with PROCESS
1159 will be bound to the value of the coding system used to decode
1162 This is useful when the coding system specified for the process buffer
1163 leaves either the character code conversion or the end-of-line conversion
1164 unspecified, or if the coding system used to decode the process output
1165 is more appropriate for saving the process buffer.
1167 Binding the variable `inherit-process-coding-system' to non-nil before
1168 starting the process is an alternative way of setting the inherit flag
1169 for the process which will run.
1171 This function returns FLAG. */)
1172 (register Lisp_Object process
, Lisp_Object flag
)
1174 CHECK_PROCESS (process
);
1175 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1179 DEFUN ("set-process-query-on-exit-flag",
1180 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1182 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1183 If the second argument FLAG is non-nil, Emacs will query the user before
1184 exiting or killing a buffer if PROCESS is running. This function
1186 (register Lisp_Object process
, Lisp_Object flag
)
1188 CHECK_PROCESS (process
);
1189 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1193 DEFUN ("process-query-on-exit-flag",
1194 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1196 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1197 (register Lisp_Object process
)
1199 CHECK_PROCESS (process
);
1200 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1203 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1205 doc
: /* Return the contact info of PROCESS; t for a real child.
1206 For a network or serial connection, the value depends on the optional
1207 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1208 SERVICE) for a network connection or (PORT SPEED) for a serial
1209 connection. If KEY is t, the complete contact information for the
1210 connection is returned, else the specific value for the keyword KEY is
1211 returned. See `make-network-process' or `make-serial-process' for a
1212 list of keywords. */)
1213 (register Lisp_Object process
, Lisp_Object key
)
1215 Lisp_Object contact
;
1217 CHECK_PROCESS (process
);
1218 contact
= XPROCESS (process
)->childp
;
1220 #ifdef DATAGRAM_SOCKETS
1221 if (DATAGRAM_CONN_P (process
)
1222 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1223 contact
= Fplist_put (contact
, QCremote
,
1224 Fprocess_datagram_address (process
));
1227 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1229 if (NILP (key
) && NETCONN_P (process
))
1230 return list2 (Fplist_get (contact
, QChost
),
1231 Fplist_get (contact
, QCservice
));
1232 if (NILP (key
) && SERIALCONN_P (process
))
1233 return list2 (Fplist_get (contact
, QCport
),
1234 Fplist_get (contact
, QCspeed
));
1235 return Fplist_get (contact
, key
);
1238 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1240 doc
: /* Return the plist of PROCESS. */)
1241 (register Lisp_Object process
)
1243 CHECK_PROCESS (process
);
1244 return XPROCESS (process
)->plist
;
1247 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1249 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1250 (register Lisp_Object process
, Lisp_Object plist
)
1252 CHECK_PROCESS (process
);
1255 pset_plist (XPROCESS (process
), plist
);
1259 #if 0 /* Turned off because we don't currently record this info
1260 in the process. Perhaps add it. */
1261 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1262 doc
: /* Return the connection type of PROCESS.
1263 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1264 a socket connection. */)
1265 (Lisp_Object process
)
1267 return XPROCESS (process
)->type
;
1271 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1272 doc
: /* Return the connection type of PROCESS.
1273 The value is either the symbol `real', `network', or `serial'.
1274 PROCESS may be a process, a buffer, the name of a process or buffer, or
1275 nil, indicating the current buffer's process. */)
1276 (Lisp_Object process
)
1279 proc
= get_process (process
);
1280 return XPROCESS (proc
)->type
;
1283 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1285 doc
: /* Convert network ADDRESS from internal format to a string.
1286 A 4 or 5 element vector represents an IPv4 address (with port number).
1287 An 8 or 9 element vector represents an IPv6 address (with port number).
1288 If optional second argument OMIT-PORT is non-nil, don't include a port
1289 number in the string, even when present in ADDRESS.
1290 Returns nil if format of ADDRESS is invalid. */)
1291 (Lisp_Object address
, Lisp_Object omit_port
)
1296 if (STRINGP (address
)) /* AF_LOCAL */
1299 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1301 register struct Lisp_Vector
*p
= XVECTOR (address
);
1302 ptrdiff_t size
= p
->header
.size
;
1303 Lisp_Object args
[10];
1306 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1308 args
[0] = build_string ("%d.%d.%d.%d");
1313 args
[0] = build_string ("%d.%d.%d.%d:%d");
1316 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1318 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1323 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1329 for (i
= 0; i
< nargs
; i
++)
1331 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1334 if (nargs
<= 5 /* IPv4 */
1335 && i
< 4 /* host, not port */
1336 && XINT (p
->contents
[i
]) > 255)
1339 args
[i
+1] = p
->contents
[i
];
1342 return Fformat (nargs
+1, args
);
1345 if (CONSP (address
))
1347 Lisp_Object args
[2];
1348 args
[0] = build_string ("<Family %d>");
1349 args
[1] = Fcar (address
);
1350 return Fformat (2, args
);
1356 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1357 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1360 return Fmapcar (Qcdr
, Vprocess_alist
);
1363 /* Starting asynchronous inferior processes. */
1365 static void start_process_unwind (Lisp_Object proc
);
1367 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1368 doc
: /* Start a program in a subprocess. Return the process object for it.
1369 NAME is name for process. It is modified if necessary to make it unique.
1370 BUFFER is the buffer (or buffer name) to associate with the process.
1372 Process output (both standard output and standard error streams) goes
1373 at end of BUFFER, unless you specify an output stream or filter
1374 function to handle the output. BUFFER may also be nil, meaning that
1375 this process is not associated with any buffer.
1377 PROGRAM is the program file name. It is searched for in `exec-path'
1378 (which see). If nil, just associate a pty with the buffer. Remaining
1379 arguments are strings to give program as arguments.
1381 If you want to separate standard output from standard error, invoke
1382 the command through a shell and redirect one of them using the shell
1385 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1386 (ptrdiff_t nargs
, Lisp_Object
*args
)
1388 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1389 register unsigned char **new_argv
;
1391 ptrdiff_t count
= SPECPDL_INDEX ();
1395 buffer
= Fget_buffer_create (buffer
);
1397 /* Make sure that the child will be able to chdir to the current
1398 buffer's current directory, or its unhandled equivalent. We
1399 can't just have the child check for an error when it does the
1400 chdir, since it's in a vfork.
1402 We have to GCPRO around this because Fexpand_file_name and
1403 Funhandled_file_name_directory might call a file name handling
1404 function. The argument list is protected by the caller, so all
1405 we really have to worry about is buffer. */
1407 struct gcpro gcpro1
;
1409 current_dir
= encode_current_directory ();
1414 CHECK_STRING (name
);
1418 if (!NILP (program
))
1419 CHECK_STRING (program
);
1421 proc
= make_process (name
);
1422 /* If an error occurs and we can't start the process, we want to
1423 remove it from the process list. This means that each error
1424 check in create_process doesn't need to call remove_process
1425 itself; it's all taken care of here. */
1426 record_unwind_protect (start_process_unwind
, proc
);
1428 pset_childp (XPROCESS (proc
), Qt
);
1429 pset_plist (XPROCESS (proc
), Qnil
);
1430 pset_type (XPROCESS (proc
), Qreal
);
1431 pset_buffer (XPROCESS (proc
), buffer
);
1432 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1433 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1434 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1437 /* AKA GNUTLS_INITSTAGE(proc). */
1438 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1439 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1442 #ifdef ADAPTIVE_READ_BUFFERING
1443 XPROCESS (proc
)->adaptive_read_buffering
1444 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1445 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1448 /* Make the process marker point into the process buffer (if any). */
1449 if (BUFFERP (buffer
))
1450 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1451 BUF_ZV (XBUFFER (buffer
)),
1452 BUF_ZV_BYTE (XBUFFER (buffer
)));
1455 /* Decide coding systems for communicating with the process. Here
1456 we don't setup the structure coding_system nor pay attention to
1457 unibyte mode. They are done in create_process. */
1459 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1460 Lisp_Object coding_systems
= Qt
;
1461 Lisp_Object val
, *args2
;
1462 struct gcpro gcpro1
, gcpro2
;
1464 val
= Vcoding_system_for_read
;
1467 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1468 args2
[0] = Qstart_process
;
1469 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1470 GCPRO2 (proc
, current_dir
);
1471 if (!NILP (program
))
1472 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1474 if (CONSP (coding_systems
))
1475 val
= XCAR (coding_systems
);
1476 else if (CONSP (Vdefault_process_coding_system
))
1477 val
= XCAR (Vdefault_process_coding_system
);
1479 pset_decode_coding_system (XPROCESS (proc
), val
);
1481 val
= Vcoding_system_for_write
;
1484 if (EQ (coding_systems
, Qt
))
1486 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1487 args2
[0] = Qstart_process
;
1488 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1489 GCPRO2 (proc
, current_dir
);
1490 if (!NILP (program
))
1491 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1494 if (CONSP (coding_systems
))
1495 val
= XCDR (coding_systems
);
1496 else if (CONSP (Vdefault_process_coding_system
))
1497 val
= XCDR (Vdefault_process_coding_system
);
1499 pset_encode_coding_system (XPROCESS (proc
), val
);
1500 /* Note: At this moment, the above coding system may leave
1501 text-conversion or eol-conversion unspecified. They will be
1502 decided after we read output from the process and decode it by
1503 some coding system, or just before we actually send a text to
1508 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1509 XPROCESS (proc
)->decoding_carryover
= 0;
1510 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1512 XPROCESS (proc
)->inherit_coding_system_flag
1513 = !(NILP (buffer
) || !inherit_process_coding_system
);
1515 if (!NILP (program
))
1517 /* If program file name is not absolute, search our path for it.
1518 Put the name we will really use in TEM. */
1519 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1520 && !(SCHARS (program
) > 1
1521 && IS_DEVICE_SEP (SREF (program
, 1))))
1523 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1526 GCPRO4 (name
, program
, buffer
, current_dir
);
1527 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1528 make_number (X_OK
), false);
1531 report_file_error ("Searching for program", program
);
1532 tem
= Fexpand_file_name (tem
, Qnil
);
1536 if (!NILP (Ffile_directory_p (program
)))
1537 error ("Specified program for new process is a directory");
1541 /* If program file name starts with /: for quoting a magic name,
1543 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1544 && SREF (tem
, 1) == ':')
1545 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1548 Lisp_Object arg_encoding
= Qnil
;
1549 struct gcpro gcpro1
;
1552 /* Encode the file name and put it in NEW_ARGV.
1553 That's where the child will use it to execute the program. */
1554 tem
= list1 (ENCODE_FILE (tem
));
1556 /* Here we encode arguments by the coding system used for sending
1557 data to the process. We don't support using different coding
1558 systems for encoding arguments and for encoding data sent to the
1561 for (i
= 3; i
< nargs
; i
++)
1563 tem
= Fcons (args
[i
], tem
);
1564 CHECK_STRING (XCAR (tem
));
1565 if (STRING_MULTIBYTE (XCAR (tem
)))
1567 if (NILP (arg_encoding
))
1568 arg_encoding
= (complement_process_encoding_system
1569 (XPROCESS (proc
)->encode_coding_system
));
1571 code_convert_string_norecord
1572 (XCAR (tem
), arg_encoding
, 1));
1579 /* Now that everything is encoded we can collect the strings into
1581 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1582 new_argv
[nargs
- 2] = 0;
1584 for (i
= nargs
- 2; i
-- != 0; )
1586 new_argv
[i
] = SDATA (XCAR (tem
));
1590 create_process (proc
, (char **) new_argv
, current_dir
);
1595 return unbind_to (count
, proc
);
1598 /* This function is the unwind_protect form for Fstart_process. If
1599 PROC doesn't have its pid set, then we know someone has signaled
1600 an error and the process wasn't started successfully, so we should
1601 remove it from the process list. */
1603 start_process_unwind (Lisp_Object proc
)
1605 if (!PROCESSP (proc
))
1608 /* Was PROC started successfully?
1609 -2 is used for a pty with no process, eg for gdb. */
1610 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1611 remove_process (proc
);
1614 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1617 close_process_fd (int *fd_addr
)
1627 /* Indexes of file descriptors in open_fds. */
1630 /* The pipe from Emacs to its subprocess. */
1632 WRITE_TO_SUBPROCESS
,
1634 /* The main pipe from the subprocess to Emacs. */
1635 READ_FROM_SUBPROCESS
,
1638 /* The pipe from the subprocess to Emacs that is closed when the
1639 subprocess execs. */
1640 READ_FROM_EXEC_MONITOR
,
1644 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1647 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1649 struct Lisp_Process
*p
= XPROCESS (process
);
1650 int inchannel
, outchannel
;
1653 int forkin
, forkout
;
1655 char pty_name
[PTY_NAME_SIZE
];
1656 Lisp_Object lisp_pty_name
= Qnil
;
1659 inchannel
= outchannel
= -1;
1661 if (!NILP (Vprocess_connection_type
))
1662 outchannel
= inchannel
= allocate_pty (pty_name
);
1666 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1667 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1668 /* On most USG systems it does not work to open the pty's tty here,
1669 then close it and reopen it in the child. */
1670 /* Don't let this terminal become our controlling terminal
1671 (in case we don't have one). */
1672 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1674 report_file_error ("Opening pty", Qnil
);
1675 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1677 forkin
= forkout
= -1;
1678 #endif /* not USG, or USG_SUBTTY_WORKS */
1680 lisp_pty_name
= build_string (pty_name
);
1684 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1685 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1686 report_file_error ("Creating pipe", Qnil
);
1687 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1688 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1689 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1690 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1694 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1695 report_file_error ("Creating pipe", Qnil
);
1698 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1699 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1701 /* Record this as an active process, with its channels. */
1702 chan_process
[inchannel
] = process
;
1703 p
->infd
= inchannel
;
1704 p
->outfd
= outchannel
;
1706 /* Previously we recorded the tty descriptor used in the subprocess.
1707 It was only used for getting the foreground tty process, so now
1708 we just reopen the device (see emacs_get_tty_pgrp) as this is
1709 more portable (see USG_SUBTTY_WORKS above). */
1711 p
->pty_flag
= pty_flag
;
1712 pset_status (p
, Qrun
);
1714 FD_SET (inchannel
, &input_wait_mask
);
1715 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1716 if (inchannel
> max_process_desc
)
1717 max_process_desc
= inchannel
;
1719 /* This may signal an error. */
1720 setup_process_coding_systems (process
);
1723 block_child_signal (&oldset
);
1726 /* vfork, and prevent local vars from being clobbered by the vfork. */
1728 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1729 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1730 char **volatile new_argv_volatile
= new_argv
;
1731 int volatile forkin_volatile
= forkin
;
1732 int volatile forkout_volatile
= forkout
;
1733 struct Lisp_Process
*p_volatile
= p
;
1737 current_dir
= current_dir_volatile
;
1738 lisp_pty_name
= lisp_pty_name_volatile
;
1739 new_argv
= new_argv_volatile
;
1740 forkin
= forkin_volatile
;
1741 forkout
= forkout_volatile
;
1744 pty_flag
= p
->pty_flag
;
1748 #endif /* not WINDOWSNT */
1750 int xforkin
= forkin
;
1751 int xforkout
= forkout
;
1753 /* Make the pty be the controlling terminal of the process. */
1755 /* First, disconnect its current controlling terminal. */
1756 /* We tried doing setsid only if pty_flag, but it caused
1757 process_set_signal to fail on SGI when using a pipe. */
1759 /* Make the pty's terminal the controlling terminal. */
1760 if (pty_flag
&& xforkin
>= 0)
1763 /* We ignore the return value
1764 because faith@cs.unc.edu says that is necessary on Linux. */
1765 ioctl (xforkin
, TIOCSCTTY
, 0);
1768 #if defined (LDISC1)
1769 if (pty_flag
&& xforkin
>= 0)
1772 tcgetattr (xforkin
, &t
);
1774 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1775 emacs_perror ("create_process/tcsetattr LDISC1");
1778 #if defined (NTTYDISC) && defined (TIOCSETD)
1779 if (pty_flag
&& xforkin
>= 0)
1781 /* Use new line discipline. */
1782 int ldisc
= NTTYDISC
;
1783 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1788 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1789 can do TIOCSPGRP only to the process's controlling tty. */
1792 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1793 I can't test it since I don't have 4.3. */
1794 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1797 ioctl (j
, TIOCNOTTY
, 0);
1801 #endif /* TIOCNOTTY */
1803 #if !defined (DONT_REOPEN_PTY)
1804 /*** There is a suggestion that this ought to be a
1805 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1806 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1807 that system does seem to need this code, even though
1808 both TIOCSCTTY is defined. */
1809 /* Now close the pty (if we had it open) and reopen it.
1810 This makes the pty the controlling terminal of the subprocess. */
1814 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1817 emacs_close (xforkin
);
1818 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1822 emacs_perror (SSDATA (lisp_pty_name
));
1823 _exit (EXIT_CANCELED
);
1827 #endif /* not DONT_REOPEN_PTY */
1829 #ifdef SETUP_SLAVE_PTY
1834 #endif /* SETUP_SLAVE_PTY */
1835 #endif /* HAVE_PTYS */
1837 signal (SIGINT
, SIG_DFL
);
1838 signal (SIGQUIT
, SIG_DFL
);
1840 signal (SIGPROF
, SIG_DFL
);
1843 /* Emacs ignores SIGPIPE, but the child should not. */
1844 signal (SIGPIPE
, SIG_DFL
);
1846 /* Stop blocking SIGCHLD in the child. */
1847 unblock_child_signal (&oldset
);
1850 child_setup_tty (xforkout
);
1852 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1853 #else /* not WINDOWSNT */
1854 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1855 #endif /* not WINDOWSNT */
1858 /* Back in the parent process. */
1860 vfork_errno
= errno
;
1865 /* Stop blocking in the parent. */
1866 unblock_child_signal (&oldset
);
1870 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1873 /* vfork succeeded. */
1875 /* Close the pipe ends that the child uses, or the child's pty. */
1876 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1877 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1880 register_child (pid
, inchannel
);
1881 #endif /* WINDOWSNT */
1883 pset_tty_name (p
, lisp_pty_name
);
1886 /* Wait for child_setup to complete in case that vfork is
1887 actually defined as fork. The descriptor
1888 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1889 of a pipe is closed at the child side either by close-on-exec
1890 on successful execve or the _exit call in child_setup. */
1894 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1895 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
1896 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
1903 create_pty (Lisp_Object process
)
1905 struct Lisp_Process
*p
= XPROCESS (process
);
1906 char pty_name
[PTY_NAME_SIZE
];
1907 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
1911 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
1912 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1913 /* On most USG systems it does not work to open the pty's tty here,
1914 then close it and reopen it in the child. */
1915 /* Don't let this terminal become our controlling terminal
1916 (in case we don't have one). */
1917 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1919 report_file_error ("Opening pty", Qnil
);
1920 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
1921 #if defined (DONT_REOPEN_PTY)
1922 /* In the case that vfork is defined as fork, the parent process
1923 (Emacs) may send some data before the child process completes
1924 tty options setup. So we setup tty before forking. */
1925 child_setup_tty (forkout
);
1926 #endif /* DONT_REOPEN_PTY */
1927 #endif /* not USG, or USG_SUBTTY_WORKS */
1929 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
1931 /* Record this as an active process, with its channels.
1932 As a result, child_setup will close Emacs's side of the pipes. */
1933 chan_process
[pty_fd
] = process
;
1937 /* Previously we recorded the tty descriptor used in the subprocess.
1938 It was only used for getting the foreground tty process, so now
1939 we just reopen the device (see emacs_get_tty_pgrp) as this is
1940 more portable (see USG_SUBTTY_WORKS above). */
1943 pset_status (p
, Qrun
);
1944 setup_process_coding_systems (process
);
1946 FD_SET (pty_fd
, &input_wait_mask
);
1947 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
1948 if (pty_fd
> max_process_desc
)
1949 max_process_desc
= pty_fd
;
1951 pset_tty_name (p
, build_string (pty_name
));
1958 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1959 The address family of sa is not included in the result. */
1962 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
1964 Lisp_Object address
;
1967 register struct Lisp_Vector
*p
;
1969 /* Workaround for a bug in getsockname on BSD: Names bound to
1970 sockets in the UNIX domain are inaccessible; getsockname returns
1971 a zero length name. */
1972 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
1973 return empty_unibyte_string
;
1975 switch (sa
->sa_family
)
1979 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
1980 len
= sizeof (sin
->sin_addr
) + 1;
1981 address
= Fmake_vector (make_number (len
), Qnil
);
1982 p
= XVECTOR (address
);
1983 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
1984 cp
= (unsigned char *) &sin
->sin_addr
;
1990 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
1991 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
1992 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
1993 address
= Fmake_vector (make_number (len
), Qnil
);
1994 p
= XVECTOR (address
);
1995 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
1996 for (i
= 0; i
< len
; i
++)
1997 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2001 #ifdef HAVE_LOCAL_SOCKETS
2004 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2005 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2006 /* If the first byte is NUL, the name is a Linux abstract
2007 socket name, and the name can contain embedded NULs. If
2008 it's not, we have a NUL-terminated string. Be careful not
2009 to walk past the end of the object looking for the name
2010 terminator, however. */
2011 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2013 const char *terminator
2014 = memchr (sockun
->sun_path
, '\0', name_length
);
2017 name_length
= terminator
- (const char *) sockun
->sun_path
;
2020 return make_unibyte_string (sockun
->sun_path
, name_length
);
2024 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2025 address
= Fcons (make_number (sa
->sa_family
),
2026 Fmake_vector (make_number (len
), Qnil
));
2027 p
= XVECTOR (XCDR (address
));
2028 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2034 p
->contents
[i
++] = make_number (*cp
++);
2040 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2043 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2045 register struct Lisp_Vector
*p
;
2047 if (VECTORP (address
))
2049 p
= XVECTOR (address
);
2050 if (p
->header
.size
== 5)
2053 return sizeof (struct sockaddr_in
);
2056 else if (p
->header
.size
== 9)
2058 *familyp
= AF_INET6
;
2059 return sizeof (struct sockaddr_in6
);
2063 #ifdef HAVE_LOCAL_SOCKETS
2064 else if (STRINGP (address
))
2066 *familyp
= AF_LOCAL
;
2067 return sizeof (struct sockaddr_un
);
2070 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2071 && VECTORP (XCDR (address
)))
2073 struct sockaddr
*sa
;
2074 *familyp
= XINT (XCAR (address
));
2075 p
= XVECTOR (XCDR (address
));
2076 return p
->header
.size
+ sizeof (sa
->sa_family
);
2081 /* Convert an address object (vector or string) to an internal sockaddr.
2083 The address format has been basically validated by
2084 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2085 it could have come from user data. So if FAMILY is not valid,
2086 we return after zeroing *SA. */
2089 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2091 register struct Lisp_Vector
*p
;
2092 register unsigned char *cp
= NULL
;
2096 memset (sa
, 0, len
);
2098 if (VECTORP (address
))
2100 p
= XVECTOR (address
);
2101 if (family
== AF_INET
)
2103 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2104 len
= sizeof (sin
->sin_addr
) + 1;
2105 hostport
= XINT (p
->contents
[--len
]);
2106 sin
->sin_port
= htons (hostport
);
2107 cp
= (unsigned char *)&sin
->sin_addr
;
2108 sa
->sa_family
= family
;
2111 else if (family
== AF_INET6
)
2113 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2114 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2115 len
= sizeof (sin6
->sin6_addr
) + 1;
2116 hostport
= XINT (p
->contents
[--len
]);
2117 sin6
->sin6_port
= htons (hostport
);
2118 for (i
= 0; i
< len
; i
++)
2119 if (INTEGERP (p
->contents
[i
]))
2121 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2124 sa
->sa_family
= family
;
2131 else if (STRINGP (address
))
2133 #ifdef HAVE_LOCAL_SOCKETS
2134 if (family
== AF_LOCAL
)
2136 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2137 cp
= SDATA (address
);
2138 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2139 sockun
->sun_path
[i
] = *cp
++;
2140 sa
->sa_family
= family
;
2147 p
= XVECTOR (XCDR (address
));
2148 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2151 for (i
= 0; i
< len
; i
++)
2152 if (INTEGERP (p
->contents
[i
]))
2153 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2156 #ifdef DATAGRAM_SOCKETS
2157 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2159 doc
: /* Get the current datagram address associated with PROCESS. */)
2160 (Lisp_Object process
)
2164 CHECK_PROCESS (process
);
2166 if (!DATAGRAM_CONN_P (process
))
2169 channel
= XPROCESS (process
)->infd
;
2170 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2171 datagram_address
[channel
].len
);
2174 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2176 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2177 Returns nil upon error setting address, ADDRESS otherwise. */)
2178 (Lisp_Object process
, Lisp_Object address
)
2183 CHECK_PROCESS (process
);
2185 if (!DATAGRAM_CONN_P (process
))
2188 channel
= XPROCESS (process
)->infd
;
2190 len
= get_lisp_to_sockaddr_size (address
, &family
);
2191 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2193 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2199 static const struct socket_options
{
2200 /* The name of this option. Should be lowercase version of option
2201 name without SO_ prefix. */
2203 /* Option level SOL_... */
2205 /* Option number SO_... */
2207 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2208 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2209 } socket_options
[] =
2211 #ifdef SO_BINDTODEVICE
2212 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2215 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2218 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2221 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2224 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2227 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2230 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2233 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2235 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2238 /* Set option OPT to value VAL on socket S.
2240 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2241 Signals an error if setting a known option fails.
2245 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2248 const struct socket_options
*sopt
;
2253 name
= SSDATA (SYMBOL_NAME (opt
));
2254 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2255 if (strcmp (name
, sopt
->name
) == 0)
2258 switch (sopt
->opttype
)
2263 optval
= NILP (val
) ? 0 : 1;
2264 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2265 &optval
, sizeof (optval
));
2272 if (TYPE_RANGED_INTEGERP (int, val
))
2273 optval
= XINT (val
);
2275 error ("Bad option value for %s", name
);
2276 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2277 &optval
, sizeof (optval
));
2281 #ifdef SO_BINDTODEVICE
2284 char devname
[IFNAMSIZ
+1];
2286 /* This is broken, at least in the Linux 2.4 kernel.
2287 To unbind, the arg must be a zero integer, not the empty string.
2288 This should work on all systems. KFS. 2003-09-23. */
2289 memset (devname
, 0, sizeof devname
);
2292 char *arg
= SSDATA (val
);
2293 int len
= min (strlen (arg
), IFNAMSIZ
);
2294 memcpy (devname
, arg
, len
);
2296 else if (!NILP (val
))
2297 error ("Bad option value for %s", name
);
2298 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2307 struct linger linger
;
2310 linger
.l_linger
= 0;
2311 if (TYPE_RANGED_INTEGERP (int, val
))
2312 linger
.l_linger
= XINT (val
);
2314 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2315 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2316 &linger
, sizeof (linger
));
2327 int setsockopt_errno
= errno
;
2328 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2332 return (1 << sopt
->optbit
);
2336 DEFUN ("set-network-process-option",
2337 Fset_network_process_option
, Sset_network_process_option
,
2339 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2340 See `make-network-process' for a list of options and values.
2341 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2342 OPTION is not a supported option, return nil instead; otherwise return t. */)
2343 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2346 struct Lisp_Process
*p
;
2348 CHECK_PROCESS (process
);
2349 p
= XPROCESS (process
);
2350 if (!NETCONN1_P (p
))
2351 error ("Process is not a network process");
2355 error ("Process is not running");
2357 if (set_socket_option (s
, option
, value
))
2359 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2363 if (NILP (no_error
))
2364 error ("Unknown or unsupported option");
2370 DEFUN ("serial-process-configure",
2371 Fserial_process_configure
,
2372 Sserial_process_configure
,
2374 doc
: /* Configure speed, bytesize, etc. of a serial process.
2376 Arguments are specified as keyword/argument pairs. Attributes that
2377 are not given are re-initialized from the process's current
2378 configuration (available via the function `process-contact') or set to
2379 reasonable default values. The following arguments are defined:
2385 -- Any of these arguments can be given to identify the process that is
2386 to be configured. If none of these arguments is given, the current
2387 buffer's process is used.
2389 :speed SPEED -- SPEED is the speed of the serial port in bits per
2390 second, also called baud rate. Any value can be given for SPEED, but
2391 most serial ports work only at a few defined values between 1200 and
2392 115200, with 9600 being the most common value. If SPEED is nil, the
2393 serial port is not configured any further, i.e., all other arguments
2394 are ignored. This may be useful for special serial ports such as
2395 Bluetooth-to-serial converters which can only be configured through AT
2396 commands. A value of nil for SPEED can be used only when passed
2397 through `make-serial-process' or `serial-term'.
2399 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2400 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2402 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2403 `odd' (use odd parity), or the symbol `even' (use even parity). If
2404 PARITY is not given, no parity is used.
2406 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2407 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2408 is not given or nil, 1 stopbit is used.
2410 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2411 flowcontrol to be used, which is either nil (don't use flowcontrol),
2412 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2413 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2414 flowcontrol is used.
2416 `serial-process-configure' is called by `make-serial-process' for the
2417 initial configuration of the serial port.
2421 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2423 \(serial-process-configure
2424 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2426 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2428 usage: (serial-process-configure &rest ARGS) */)
2429 (ptrdiff_t nargs
, Lisp_Object
*args
)
2431 struct Lisp_Process
*p
;
2432 Lisp_Object contact
= Qnil
;
2433 Lisp_Object proc
= Qnil
;
2434 struct gcpro gcpro1
;
2436 contact
= Flist (nargs
, args
);
2439 proc
= Fplist_get (contact
, QCprocess
);
2441 proc
= Fplist_get (contact
, QCname
);
2443 proc
= Fplist_get (contact
, QCbuffer
);
2445 proc
= Fplist_get (contact
, QCport
);
2446 proc
= get_process (proc
);
2447 p
= XPROCESS (proc
);
2448 if (!EQ (p
->type
, Qserial
))
2449 error ("Not a serial process");
2451 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2457 serial_configure (p
, contact
);
2463 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2465 doc
: /* Create and return a serial port process.
2467 In Emacs, serial port connections are represented by process objects,
2468 so input and output work as for subprocesses, and `delete-process'
2469 closes a serial port connection. However, a serial process has no
2470 process id, it cannot be signaled, and the status codes are different
2471 from normal processes.
2473 `make-serial-process' creates a process and a buffer, on which you
2474 probably want to use `process-send-string'. Try \\[serial-term] for
2475 an interactive terminal. See below for examples.
2477 Arguments are specified as keyword/argument pairs. The following
2478 arguments are defined:
2480 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2481 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2482 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2483 the backslashes in strings).
2485 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2486 which this function calls.
2488 :name NAME -- NAME is the name of the process. If NAME is not given,
2489 the value of PORT is used.
2491 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2492 with the process. Process output goes at the end of that buffer,
2493 unless you specify an output stream or filter function to handle the
2494 output. If BUFFER is not given, the value of NAME is used.
2496 :coding CODING -- If CODING is a symbol, it specifies the coding
2497 system used for both reading and writing for this process. If CODING
2498 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2499 ENCODING is used for writing.
2501 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2502 the process is running. If BOOL is not given, query before exiting.
2504 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2505 In the stopped state, a serial process does not accept incoming data,
2506 but you can send outgoing data. The stopped state is cleared by
2507 `continue-process' and set by `stop-process'.
2509 :filter FILTER -- Install FILTER as the process filter.
2511 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2513 :plist PLIST -- Install PLIST as the initial plist of the process.
2519 -- This function calls `serial-process-configure' to handle these
2522 The original argument list, possibly modified by later configuration,
2523 is available via the function `process-contact'.
2527 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2529 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2531 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2533 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2535 usage: (make-serial-process &rest ARGS) */)
2536 (ptrdiff_t nargs
, Lisp_Object
*args
)
2539 Lisp_Object proc
, contact
, port
;
2540 struct Lisp_Process
*p
;
2541 struct gcpro gcpro1
;
2542 Lisp_Object name
, buffer
;
2543 Lisp_Object tem
, val
;
2544 ptrdiff_t specpdl_count
;
2549 contact
= Flist (nargs
, args
);
2552 port
= Fplist_get (contact
, QCport
);
2554 error ("No port specified");
2555 CHECK_STRING (port
);
2557 if (NILP (Fplist_member (contact
, QCspeed
)))
2558 error (":speed not specified");
2559 if (!NILP (Fplist_get (contact
, QCspeed
)))
2560 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2562 name
= Fplist_get (contact
, QCname
);
2565 CHECK_STRING (name
);
2566 proc
= make_process (name
);
2567 specpdl_count
= SPECPDL_INDEX ();
2568 record_unwind_protect_1 (remove_process
, proc
, false);
2569 p
= XPROCESS (proc
);
2571 fd
= serial_open (port
);
2572 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2575 if (fd
> max_process_desc
)
2576 max_process_desc
= fd
;
2577 chan_process
[fd
] = proc
;
2579 buffer
= Fplist_get (contact
, QCbuffer
);
2582 buffer
= Fget_buffer_create (buffer
);
2583 pset_buffer (p
, buffer
);
2585 pset_childp (p
, contact
);
2586 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2587 pset_type (p
, Qserial
);
2588 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2589 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2591 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2592 p
->kill_without_query
= 1;
2593 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2594 pset_command (p
, Qt
);
2595 eassert (! p
->pty_flag
);
2597 if (!EQ (p
->command
, Qt
))
2599 FD_SET (fd
, &input_wait_mask
);
2600 FD_SET (fd
, &non_keyboard_wait_mask
);
2603 if (BUFFERP (buffer
))
2605 set_marker_both (p
->mark
, buffer
,
2606 BUF_ZV (XBUFFER (buffer
)),
2607 BUF_ZV_BYTE (XBUFFER (buffer
)));
2610 tem
= Fplist_member (contact
, QCcoding
);
2611 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2617 val
= XCAR (XCDR (tem
));
2621 else if (!NILP (Vcoding_system_for_read
))
2622 val
= Vcoding_system_for_read
;
2623 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2624 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2626 pset_decode_coding_system (p
, val
);
2631 val
= XCAR (XCDR (tem
));
2635 else if (!NILP (Vcoding_system_for_write
))
2636 val
= Vcoding_system_for_write
;
2637 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2638 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2640 pset_encode_coding_system (p
, val
);
2642 setup_process_coding_systems (proc
);
2643 pset_decoding_buf (p
, empty_unibyte_string
);
2644 p
->decoding_carryover
= 0;
2645 pset_encoding_buf (p
, empty_unibyte_string
);
2646 p
->inherit_coding_system_flag
2647 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2649 Fserial_process_configure (nargs
, args
);
2651 unbind_to (specpdl_count
, Qnil
);
2657 /* Create a network stream/datagram client/server process. Treated
2658 exactly like a normal process when reading and writing. Primary
2659 differences are in status display and process deletion. A network
2660 connection has no PID; you cannot signal it. All you can do is
2661 stop/continue it and deactivate/close it via delete-process */
2663 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2665 doc
: /* Create and return a network server or client process.
2667 In Emacs, network connections are represented by process objects, so
2668 input and output work as for subprocesses and `delete-process' closes
2669 a network connection. However, a network process has no process id,
2670 it cannot be signaled, and the status codes are different from normal
2673 Arguments are specified as keyword/argument pairs. The following
2674 arguments are defined:
2676 :name NAME -- NAME is name for process. It is modified if necessary
2679 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2680 with the process. Process output goes at end of that buffer, unless
2681 you specify an output stream or filter function to handle the output.
2682 BUFFER may be also nil, meaning that this process is not associated
2685 :host HOST -- HOST is name of the host to connect to, or its IP
2686 address. The symbol `local' specifies the local host. If specified
2687 for a server process, it must be a valid name or address for the local
2688 host, and only clients connecting to that address will be accepted.
2690 :service SERVICE -- SERVICE is name of the service desired, or an
2691 integer specifying a port number to connect to. If SERVICE is t,
2692 a random port number is selected for the server. (If Emacs was
2693 compiled with getaddrinfo, a port number can also be specified as a
2694 string, e.g. "80", as well as an integer. This is not portable.)
2696 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2697 stream type connection, `datagram' creates a datagram type connection,
2698 `seqpacket' creates a reliable datagram connection.
2700 :family FAMILY -- FAMILY is the address (and protocol) family for the
2701 service specified by HOST and SERVICE. The default (nil) is to use
2702 whatever address family (IPv4 or IPv6) that is defined for the host
2703 and port number specified by HOST and SERVICE. Other address families
2705 local -- for a local (i.e. UNIX) address specified by SERVICE.
2706 ipv4 -- use IPv4 address family only.
2707 ipv6 -- use IPv6 address family only.
2709 :local ADDRESS -- ADDRESS is the local address used for the connection.
2710 This parameter is ignored when opening a client process. When specified
2711 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2713 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2714 connection. This parameter is ignored when opening a stream server
2715 process. For a datagram server process, it specifies the initial
2716 setting of the remote datagram address. When specified for a client
2717 process, the FAMILY, HOST, and SERVICE args are ignored.
2719 The format of ADDRESS depends on the address family:
2720 - An IPv4 address is represented as an vector of integers [A B C D P]
2721 corresponding to numeric IP address A.B.C.D and port number P.
2722 - A local address is represented as a string with the address in the
2723 local address space.
2724 - An "unsupported family" address is represented by a cons (F . AV)
2725 where F is the family number and AV is a vector containing the socket
2726 address data with one element per address data byte. Do not rely on
2727 this format in portable code, as it may depend on implementation
2728 defined constants, data sizes, and data structure alignment.
2730 :coding CODING -- If CODING is a symbol, it specifies the coding
2731 system used for both reading and writing for this process. If CODING
2732 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2733 ENCODING is used for writing.
2735 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2736 return without waiting for the connection to complete; instead, the
2737 sentinel function will be called with second arg matching "open" (if
2738 successful) or "failed" when the connect completes. Default is to use
2739 a blocking connect (i.e. wait) for stream type connections.
2741 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2742 running when Emacs is exited.
2744 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2745 In the stopped state, a server process does not accept new
2746 connections, and a client process does not handle incoming traffic.
2747 The stopped state is cleared by `continue-process' and set by
2750 :filter FILTER -- Install FILTER as the process filter.
2752 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2753 process filter are multibyte, otherwise they are unibyte.
2754 If this keyword is not specified, the strings are multibyte if
2755 the default value of `enable-multibyte-characters' is non-nil.
2757 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2759 :log LOG -- Install LOG as the server process log function. This
2760 function is called when the server accepts a network connection from a
2761 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2762 is the server process, CLIENT is the new process for the connection,
2763 and MESSAGE is a string.
2765 :plist PLIST -- Install PLIST as the new process's initial plist.
2767 :server QLEN -- if QLEN is non-nil, create a server process for the
2768 specified FAMILY, SERVICE, and connection type (stream or datagram).
2769 If QLEN is an integer, it is used as the max. length of the server's
2770 pending connection queue (also known as the backlog); the default
2771 queue length is 5. Default is to create a client process.
2773 The following network options can be specified for this connection:
2775 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2776 :dontroute BOOL -- Only send to directly connected hosts.
2777 :keepalive BOOL -- Send keep-alive messages on network stream.
2778 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2779 :oobinline BOOL -- Place out-of-band data in receive data stream.
2780 :priority INT -- Set protocol defined priority for sent packets.
2781 :reuseaddr BOOL -- Allow reusing a recently used local address
2782 (this is allowed by default for a server process).
2783 :bindtodevice NAME -- bind to interface NAME. Using this may require
2784 special privileges on some systems.
2786 Consult the relevant system programmer's manual pages for more
2787 information on using these options.
2790 A server process will listen for and accept connections from clients.
2791 When a client connection is accepted, a new network process is created
2792 for the connection with the following parameters:
2794 - The client's process name is constructed by concatenating the server
2795 process's NAME and a client identification string.
2796 - If the FILTER argument is non-nil, the client process will not get a
2797 separate process buffer; otherwise, the client's process buffer is a newly
2798 created buffer named after the server process's BUFFER name or process
2799 NAME concatenated with the client identification string.
2800 - The connection type and the process filter and sentinel parameters are
2801 inherited from the server process's TYPE, FILTER and SENTINEL.
2802 - The client process's contact info is set according to the client's
2803 addressing information (typically an IP address and a port number).
2804 - The client process's plist is initialized from the server's plist.
2806 Notice that the FILTER and SENTINEL args are never used directly by
2807 the server process. Also, the BUFFER argument is not used directly by
2808 the server process, but via the optional :log function, accepted (and
2809 failed) connections may be logged in the server process's buffer.
2811 The original argument list, modified with the actual connection
2812 information, is available via the `process-contact' function.
2814 usage: (make-network-process &rest ARGS) */)
2815 (ptrdiff_t nargs
, Lisp_Object
*args
)
2818 Lisp_Object contact
;
2819 struct Lisp_Process
*p
;
2820 #ifdef HAVE_GETADDRINFO
2821 struct addrinfo ai
, *res
, *lres
;
2822 struct addrinfo hints
;
2823 const char *portstring
;
2825 #else /* HAVE_GETADDRINFO */
2826 struct _emacs_addrinfo
2832 struct sockaddr
*ai_addr
;
2833 struct _emacs_addrinfo
*ai_next
;
2835 #endif /* HAVE_GETADDRINFO */
2836 struct sockaddr_in address_in
;
2837 #ifdef HAVE_LOCAL_SOCKETS
2838 struct sockaddr_un address_un
;
2843 int s
= -1, outch
, inch
;
2844 struct gcpro gcpro1
;
2845 ptrdiff_t count
= SPECPDL_INDEX ();
2847 Lisp_Object colon_address
; /* Either QClocal or QCremote. */
2849 Lisp_Object name
, buffer
, host
, service
, address
;
2850 Lisp_Object filter
, sentinel
;
2851 bool is_non_blocking_client
= 0;
2860 /* Save arguments for process-contact and clone-process. */
2861 contact
= Flist (nargs
, args
);
2865 /* Ensure socket support is loaded if available. */
2866 init_winsock (TRUE
);
2869 /* :type TYPE (nil: stream, datagram */
2870 tem
= Fplist_get (contact
, QCtype
);
2872 socktype
= SOCK_STREAM
;
2873 #ifdef DATAGRAM_SOCKETS
2874 else if (EQ (tem
, Qdatagram
))
2875 socktype
= SOCK_DGRAM
;
2877 #ifdef HAVE_SEQPACKET
2878 else if (EQ (tem
, Qseqpacket
))
2879 socktype
= SOCK_SEQPACKET
;
2882 error ("Unsupported connection type");
2885 tem
= Fplist_get (contact
, QCserver
);
2888 /* Don't support network sockets when non-blocking mode is
2889 not available, since a blocked Emacs is not useful. */
2891 if (TYPE_RANGED_INTEGERP (int, tem
))
2892 backlog
= XINT (tem
);
2895 /* Make colon_address an alias for :local (server) or :remote (client). */
2896 colon_address
= is_server
? QClocal
: QCremote
;
2899 if (!is_server
&& socktype
!= SOCK_DGRAM
2900 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2902 #ifndef NON_BLOCKING_CONNECT
2903 error ("Non-blocking connect not supported");
2905 is_non_blocking_client
= 1;
2909 name
= Fplist_get (contact
, QCname
);
2910 buffer
= Fplist_get (contact
, QCbuffer
);
2911 filter
= Fplist_get (contact
, QCfilter
);
2912 sentinel
= Fplist_get (contact
, QCsentinel
);
2914 CHECK_STRING (name
);
2916 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2917 ai
.ai_socktype
= socktype
;
2922 /* :local ADDRESS or :remote ADDRESS */
2923 address
= Fplist_get (contact
, colon_address
);
2924 if (!NILP (address
))
2926 host
= service
= Qnil
;
2928 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2929 error ("Malformed :address");
2930 ai
.ai_family
= family
;
2931 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2932 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
2936 /* :family FAMILY -- nil (for Inet), local, or integer. */
2937 tem
= Fplist_get (contact
, QCfamily
);
2940 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2946 #ifdef HAVE_LOCAL_SOCKETS
2947 else if (EQ (tem
, Qlocal
))
2951 else if (EQ (tem
, Qipv6
))
2954 else if (EQ (tem
, Qipv4
))
2956 else if (TYPE_RANGED_INTEGERP (int, tem
))
2957 family
= XINT (tem
);
2959 error ("Unknown address family");
2961 ai
.ai_family
= family
;
2963 /* :service SERVICE -- string, integer (port number), or t (random port). */
2964 service
= Fplist_get (contact
, QCservice
);
2966 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2967 host
= Fplist_get (contact
, QChost
);
2970 if (EQ (host
, Qlocal
))
2971 /* Depending on setup, "localhost" may map to different IPv4 and/or
2972 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2973 host
= build_string ("127.0.0.1");
2974 CHECK_STRING (host
);
2977 #ifdef HAVE_LOCAL_SOCKETS
2978 if (family
== AF_LOCAL
)
2982 message (":family local ignores the :host \"%s\" property",
2984 contact
= Fplist_put (contact
, QChost
, Qnil
);
2987 CHECK_STRING (service
);
2988 memset (&address_un
, 0, sizeof address_un
);
2989 address_un
.sun_family
= AF_LOCAL
;
2990 if (sizeof address_un
.sun_path
<= SBYTES (service
))
2991 error ("Service name too long");
2992 strcpy (address_un
.sun_path
, SSDATA (service
));
2993 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
2994 ai
.ai_addrlen
= sizeof address_un
;
2999 /* Slow down polling to every ten seconds.
3000 Some kernels have a bug which causes retrying connect to fail
3001 after a connect. Polling can interfere with gethostbyname too. */
3002 #ifdef POLL_FOR_INPUT
3003 if (socktype
!= SOCK_DGRAM
)
3005 record_unwind_protect_void (run_all_atimers
);
3006 bind_polling_period (10);
3010 #ifdef HAVE_GETADDRINFO
3011 /* If we have a host, use getaddrinfo to resolve both host and service.
3012 Otherwise, use getservbyname to lookup the service. */
3016 /* SERVICE can either be a string or int.
3017 Convert to a C string for later use by getaddrinfo. */
3018 if (EQ (service
, Qt
))
3020 else if (INTEGERP (service
))
3022 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3023 portstring
= portbuf
;
3027 CHECK_STRING (service
);
3028 portstring
= SSDATA (service
);
3033 memset (&hints
, 0, sizeof (hints
));
3035 hints
.ai_family
= family
;
3036 hints
.ai_socktype
= socktype
;
3037 hints
.ai_protocol
= 0;
3039 #ifdef HAVE_RES_INIT
3043 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3045 #ifdef HAVE_GAI_STRERROR
3046 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3048 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3054 #endif /* HAVE_GETADDRINFO */
3056 /* We end up here if getaddrinfo is not defined, or in case no hostname
3057 has been specified (e.g. for a local server process). */
3059 if (EQ (service
, Qt
))
3061 else if (INTEGERP (service
))
3062 port
= htons ((unsigned short) XINT (service
));
3065 struct servent
*svc_info
;
3066 CHECK_STRING (service
);
3067 svc_info
= getservbyname (SSDATA (service
),
3068 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3070 error ("Unknown service: %s", SDATA (service
));
3071 port
= svc_info
->s_port
;
3074 memset (&address_in
, 0, sizeof address_in
);
3075 address_in
.sin_family
= family
;
3076 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3077 address_in
.sin_port
= port
;
3079 #ifndef HAVE_GETADDRINFO
3082 struct hostent
*host_info_ptr
;
3084 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3085 as it may `hang' Emacs for a very long time. */
3089 #ifdef HAVE_RES_INIT
3093 host_info_ptr
= gethostbyname (SDATA (host
));
3098 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3099 host_info_ptr
->h_length
);
3100 family
= host_info_ptr
->h_addrtype
;
3101 address_in
.sin_family
= family
;
3104 /* Attempt to interpret host as numeric inet address */
3106 unsigned long numeric_addr
;
3107 numeric_addr
= inet_addr (SSDATA (host
));
3108 if (numeric_addr
== -1)
3109 error ("Unknown host \"%s\"", SDATA (host
));
3111 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3112 sizeof (address_in
.sin_addr
));
3116 #endif /* not HAVE_GETADDRINFO */
3118 ai
.ai_family
= family
;
3119 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3120 ai
.ai_addrlen
= sizeof address_in
;
3124 /* Do this in case we never enter the for-loop below. */
3125 count1
= SPECPDL_INDEX ();
3128 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3137 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3145 #ifdef DATAGRAM_SOCKETS
3146 if (!is_server
&& socktype
== SOCK_DGRAM
)
3148 #endif /* DATAGRAM_SOCKETS */
3150 #ifdef NON_BLOCKING_CONNECT
3151 if (is_non_blocking_client
)
3153 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3164 /* Make us close S if quit. */
3165 record_unwind_protect_int_1 (close_file_unwind
, s
, false);
3167 /* Parse network options in the arg list.
3168 We simply ignore anything which isn't a known option (including other keywords).
3169 An error is signaled if setting a known option fails. */
3170 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3171 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3175 /* Configure as a server socket. */
3177 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3178 explicit :reuseaddr key to override this. */
3179 #ifdef HAVE_LOCAL_SOCKETS
3180 if (family
!= AF_LOCAL
)
3182 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3185 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3186 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3189 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3190 report_file_error ("Cannot bind server socket", Qnil
);
3192 #ifdef HAVE_GETSOCKNAME
3193 if (EQ (service
, Qt
))
3195 struct sockaddr_in sa1
;
3196 socklen_t len1
= sizeof (sa1
);
3197 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3199 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3200 service
= make_number (ntohs (sa1
.sin_port
));
3201 contact
= Fplist_put (contact
, QCservice
, service
);
3206 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3207 report_file_error ("Cannot listen on server socket", Qnil
);
3215 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3218 if (ret
== 0 || xerrno
== EISCONN
)
3220 /* The unwind-protect will be discarded afterwards.
3221 Likewise for immediate_quit. */
3225 #ifdef NON_BLOCKING_CONNECT
3227 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3231 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3238 if (xerrno
== EINTR
)
3240 /* Unlike most other syscalls connect() cannot be called
3241 again. (That would return EALREADY.) The proper way to
3242 wait for completion is pselect(). */
3250 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3256 report_file_error ("Failed select", Qnil
);
3260 len
= sizeof xerrno
;
3261 eassert (FD_ISSET (s
, &fdset
));
3262 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3263 report_file_error ("Failed getsockopt", Qnil
);
3265 report_file_errno ("Failed connect", Qnil
, xerrno
);
3268 #endif /* !WINDOWSNT */
3272 unbind_to (count1
, Qnil
);
3277 if (xerrno
== EINTR
)
3284 #ifdef DATAGRAM_SOCKETS
3285 if (socktype
== SOCK_DGRAM
)
3287 if (datagram_address
[s
].sa
)
3289 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3290 datagram_address
[s
].len
= lres
->ai_addrlen
;
3294 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3295 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3298 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3299 if (rlen
!= 0 && rfamily
== lres
->ai_family
3300 && rlen
== lres
->ai_addrlen
)
3301 conv_lisp_to_sockaddr (rfamily
, remote
,
3302 datagram_address
[s
].sa
, rlen
);
3306 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3309 contact
= Fplist_put (contact
, colon_address
,
3310 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3311 #ifdef HAVE_GETSOCKNAME
3314 struct sockaddr_in sa1
;
3315 socklen_t len1
= sizeof (sa1
);
3316 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3317 contact
= Fplist_put (contact
, QClocal
,
3318 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3325 #ifdef HAVE_GETADDRINFO
3336 /* If non-blocking got this far - and failed - assume non-blocking is
3337 not supported after all. This is probably a wrong assumption, but
3338 the normal blocking calls to open-network-stream handles this error
3340 if (is_non_blocking_client
)
3343 report_file_errno ((is_server
3344 ? "make server process failed"
3345 : "make client process failed"),
3353 buffer
= Fget_buffer_create (buffer
);
3354 proc
= make_process (name
);
3356 chan_process
[inch
] = proc
;
3358 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3360 p
= XPROCESS (proc
);
3362 pset_childp (p
, contact
);
3363 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3364 pset_type (p
, Qnetwork
);
3366 pset_buffer (p
, buffer
);
3367 pset_sentinel (p
, sentinel
);
3368 pset_filter (p
, filter
);
3369 pset_log (p
, Fplist_get (contact
, QClog
));
3370 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3371 p
->kill_without_query
= 1;
3372 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3373 pset_command (p
, Qt
);
3376 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3380 unbind_to (count1
, Qnil
);
3382 /* Unwind bind_polling_period and request_sigio. */
3383 unbind_to (count
, Qnil
);
3385 if (is_server
&& socktype
!= SOCK_DGRAM
)
3386 pset_status (p
, Qlisten
);
3388 /* Make the process marker point into the process buffer (if any). */
3389 if (BUFFERP (buffer
))
3390 set_marker_both (p
->mark
, buffer
,
3391 BUF_ZV (XBUFFER (buffer
)),
3392 BUF_ZV_BYTE (XBUFFER (buffer
)));
3394 #ifdef NON_BLOCKING_CONNECT
3395 if (is_non_blocking_client
)
3397 /* We may get here if connect did succeed immediately. However,
3398 in that case, we still need to signal this like a non-blocking
3400 pset_status (p
, Qconnect
);
3401 if (!FD_ISSET (inch
, &connect_wait_mask
))
3403 FD_SET (inch
, &connect_wait_mask
);
3404 FD_SET (inch
, &write_mask
);
3405 num_pending_connects
++;
3410 /* A server may have a client filter setting of Qt, but it must
3411 still listen for incoming connects unless it is stopped. */
3412 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3413 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3415 FD_SET (inch
, &input_wait_mask
);
3416 FD_SET (inch
, &non_keyboard_wait_mask
);
3419 if (inch
> max_process_desc
)
3420 max_process_desc
= inch
;
3422 tem
= Fplist_member (contact
, QCcoding
);
3423 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3424 tem
= Qnil
; /* No error message (too late!). */
3427 /* Setup coding systems for communicating with the network stream. */
3428 struct gcpro gcpro1
;
3429 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3430 Lisp_Object coding_systems
= Qt
;
3431 Lisp_Object fargs
[5], val
;
3435 val
= XCAR (XCDR (tem
));
3439 else if (!NILP (Vcoding_system_for_read
))
3440 val
= Vcoding_system_for_read
;
3441 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3442 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3443 /* We dare not decode end-of-line format by setting VAL to
3444 Qraw_text, because the existing Emacs Lisp libraries
3445 assume that they receive bare code including a sequence of
3450 if (NILP (host
) || NILP (service
))
3451 coding_systems
= Qnil
;
3454 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3455 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3457 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3460 if (CONSP (coding_systems
))
3461 val
= XCAR (coding_systems
);
3462 else if (CONSP (Vdefault_process_coding_system
))
3463 val
= XCAR (Vdefault_process_coding_system
);
3467 pset_decode_coding_system (p
, val
);
3471 val
= XCAR (XCDR (tem
));
3475 else if (!NILP (Vcoding_system_for_write
))
3476 val
= Vcoding_system_for_write
;
3477 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3481 if (EQ (coding_systems
, Qt
))
3483 if (NILP (host
) || NILP (service
))
3484 coding_systems
= Qnil
;
3487 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3488 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3490 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3494 if (CONSP (coding_systems
))
3495 val
= XCDR (coding_systems
);
3496 else if (CONSP (Vdefault_process_coding_system
))
3497 val
= XCDR (Vdefault_process_coding_system
);
3501 pset_encode_coding_system (p
, val
);
3503 setup_process_coding_systems (proc
);
3505 pset_decoding_buf (p
, empty_unibyte_string
);
3506 p
->decoding_carryover
= 0;
3507 pset_encoding_buf (p
, empty_unibyte_string
);
3509 p
->inherit_coding_system_flag
3510 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3517 #ifdef HAVE_NET_IF_H
3521 network_interface_list (void)
3523 struct ifconf ifconf
;
3524 struct ifreq
*ifreq
;
3526 ptrdiff_t buf_size
= 512;
3528 Lisp_Object res
= Qnil
;
3531 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3534 count
= SPECPDL_INDEX ();
3535 record_unwind_protect_int (close_file_unwind
, s
);
3539 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3540 ifconf
.ifc_buf
= buf
;
3541 ifconf
.ifc_len
= buf_size
;
3542 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3549 while (ifconf
.ifc_len
== buf_size
);
3551 unbind_to (count
, Qnil
);
3552 ifreq
= ifconf
.ifc_req
;
3553 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3555 struct ifreq
*ifq
= ifreq
;
3556 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3557 #define SIZEOF_IFREQ(sif) \
3558 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3559 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3561 int len
= SIZEOF_IFREQ (ifq
);
3563 int len
= sizeof (*ifreq
);
3565 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3566 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3568 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3571 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3572 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3573 res
= Fcons (Fcons (build_string (namebuf
),
3574 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3575 sizeof (struct sockaddr
))),
3582 #endif /* SIOCGIFCONF */
3584 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3588 const char *flag_sym
;
3591 static const struct ifflag_def ifflag_table
[] = {
3595 #ifdef IFF_BROADCAST
3596 { IFF_BROADCAST
, "broadcast" },
3599 { IFF_DEBUG
, "debug" },
3602 { IFF_LOOPBACK
, "loopback" },
3604 #ifdef IFF_POINTOPOINT
3605 { IFF_POINTOPOINT
, "pointopoint" },
3608 { IFF_RUNNING
, "running" },
3611 { IFF_NOARP
, "noarp" },
3614 { IFF_PROMISC
, "promisc" },
3616 #ifdef IFF_NOTRAILERS
3617 #ifdef NS_IMPL_COCOA
3618 /* Really means smart, notrailers is obsolete */
3619 { IFF_NOTRAILERS
, "smart" },
3621 { IFF_NOTRAILERS
, "notrailers" },
3625 { IFF_ALLMULTI
, "allmulti" },
3628 { IFF_MASTER
, "master" },
3631 { IFF_SLAVE
, "slave" },
3633 #ifdef IFF_MULTICAST
3634 { IFF_MULTICAST
, "multicast" },
3637 { IFF_PORTSEL
, "portsel" },
3639 #ifdef IFF_AUTOMEDIA
3640 { IFF_AUTOMEDIA
, "automedia" },
3643 { IFF_DYNAMIC
, "dynamic" },
3646 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3649 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3652 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3655 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3658 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3664 network_interface_info (Lisp_Object ifname
)
3667 Lisp_Object res
= Qnil
;
3672 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3673 && defined HAVE_GETIFADDRS && defined LLADDR)
3674 struct ifaddrs
*ifap
;
3677 CHECK_STRING (ifname
);
3679 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3680 error ("interface name too long");
3681 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3683 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3686 count
= SPECPDL_INDEX ();
3687 record_unwind_protect_int (close_file_unwind
, s
);
3690 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3691 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3693 int flags
= rq
.ifr_flags
;
3694 const struct ifflag_def
*fp
;
3697 /* If flags is smaller than int (i.e. short) it may have the high bit set
3698 due to IFF_MULTICAST. In that case, sign extending it into
3700 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3701 flags
= (unsigned short) rq
.ifr_flags
;
3704 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3706 if (flags
& fp
->flag_bit
)
3708 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3709 flags
-= fp
->flag_bit
;
3712 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3716 elt
= Fcons (make_number (fnum
), elt
);
3721 res
= Fcons (elt
, res
);
3724 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3725 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3727 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3728 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3732 for (n
= 0; n
< 6; n
++)
3733 p
->contents
[n
] = make_number (((unsigned char *)
3734 &rq
.ifr_hwaddr
.sa_data
[0])
3736 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3738 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3739 if (getifaddrs (&ifap
) != -1)
3741 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3742 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3745 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3747 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3748 unsigned char linkaddr
[6];
3751 if (it
->ifa_addr
->sa_family
!= AF_LINK
3752 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3753 || sdl
->sdl_alen
!= 6)
3756 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3757 for (n
= 0; n
< 6; n
++)
3758 p
->contents
[n
] = make_number (linkaddr
[n
]);
3760 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3764 #ifdef HAVE_FREEIFADDRS
3768 #endif /* HAVE_GETIFADDRS && LLADDR */
3770 res
= Fcons (elt
, res
);
3773 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3774 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3777 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3778 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3780 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3784 res
= Fcons (elt
, res
);
3787 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3788 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3791 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3794 res
= Fcons (elt
, res
);
3797 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3798 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3801 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3804 res
= Fcons (elt
, res
);
3806 return unbind_to (count
, any
? res
: Qnil
);
3808 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3809 #endif /* defined (HAVE_NET_IF_H) */
3811 DEFUN ("network-interface-list", Fnetwork_interface_list
,
3812 Snetwork_interface_list
, 0, 0, 0,
3813 doc
: /* Return an alist of all network interfaces and their network address.
3814 Each element is a cons, the car of which is a string containing the
3815 interface name, and the cdr is the network address in internal
3816 format; see the description of ADDRESS in `make-network-process'.
3818 If the information is not available, return nil. */)
3821 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3822 return network_interface_list ();
3828 DEFUN ("network-interface-info", Fnetwork_interface_info
,
3829 Snetwork_interface_info
, 1, 1, 0,
3830 doc
: /* Return information about network interface named IFNAME.
3831 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3832 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3833 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3834 FLAGS is the current flags of the interface.
3836 Data that is unavailable is returned as nil. */)
3837 (Lisp_Object ifname
)
3839 #if ((defined HAVE_NET_IF_H \
3840 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3841 || defined SIOCGIFFLAGS)) \
3842 || defined WINDOWSNT)
3843 return network_interface_info (ifname
);
3850 /* Turn off input and output for process PROC. */
3853 deactivate_process (Lisp_Object proc
)
3856 struct Lisp_Process
*p
= XPROCESS (proc
);
3860 /* Delete GnuTLS structures in PROC, if any. */
3861 emacs_gnutls_deinit (proc
);
3862 #endif /* HAVE_GNUTLS */
3864 #ifdef ADAPTIVE_READ_BUFFERING
3865 if (p
->read_output_delay
> 0)
3867 if (--process_output_delay_count
< 0)
3868 process_output_delay_count
= 0;
3869 p
->read_output_delay
= 0;
3870 p
->read_output_skip
= 0;
3874 /* Beware SIGCHLD hereabouts. */
3876 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
3877 close_process_fd (&p
->open_fd
[i
]);
3879 inchannel
= p
->infd
;
3884 #ifdef DATAGRAM_SOCKETS
3885 if (DATAGRAM_CHAN_P (inchannel
))
3887 xfree (datagram_address
[inchannel
].sa
);
3888 datagram_address
[inchannel
].sa
= 0;
3889 datagram_address
[inchannel
].len
= 0;
3892 chan_process
[inchannel
] = Qnil
;
3893 FD_CLR (inchannel
, &input_wait_mask
);
3894 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3895 #ifdef NON_BLOCKING_CONNECT
3896 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3898 FD_CLR (inchannel
, &connect_wait_mask
);
3899 FD_CLR (inchannel
, &write_mask
);
3900 if (--num_pending_connects
< 0)
3904 if (inchannel
== max_process_desc
)
3906 /* We just closed the highest-numbered process input descriptor,
3907 so recompute the highest-numbered one now. */
3911 while (0 <= i
&& NILP (chan_process
[i
]));
3913 max_process_desc
= i
;
3919 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3921 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3922 It is given to their filter functions.
3923 Optional argument PROCESS means do not return until output has been
3924 received from PROCESS.
3926 Optional second argument SECONDS and third argument MILLISEC
3927 specify a timeout; return after that much time even if there is
3928 no subprocess output. If SECONDS is a floating point number,
3929 it specifies a fractional number of seconds to wait.
3930 The MILLISEC argument is obsolete and should be avoided.
3932 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
3933 from PROCESS only, suspending reading output from other processes.
3934 If JUST-THIS-ONE is an integer, don't run any timers either.
3935 Return non-nil if we received any output from PROCESS (or, if PROCESS
3936 is nil, from any process) before the timeout expired. */)
3937 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
3942 if (! NILP (process
))
3943 CHECK_PROCESS (process
);
3945 just_this_one
= Qnil
;
3947 if (!NILP (millisec
))
3948 { /* Obsolete calling convention using integers rather than floats. */
3949 CHECK_NUMBER (millisec
);
3951 seconds
= make_float (XINT (millisec
) / 1000.0);
3954 CHECK_NUMBER (seconds
);
3955 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
3962 if (!NILP (seconds
))
3964 if (INTEGERP (seconds
))
3966 if (XINT (seconds
) > 0)
3968 secs
= XINT (seconds
);
3972 else if (FLOATP (seconds
))
3974 if (XFLOAT_DATA (seconds
) > 0)
3976 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
3977 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
3982 wrong_type_argument (Qnumberp
, seconds
);
3984 else if (! NILP (process
))
3988 ((wait_reading_process_output (secs
, nsecs
, 0, 0,
3990 !NILP (process
) ? XPROCESS (process
) : NULL
,
3991 NILP (just_this_one
) ? 0 :
3992 !INTEGERP (just_this_one
) ? 1 : -1)
3997 /* Accept a connection for server process SERVER on CHANNEL. */
3999 static EMACS_INT connect_counter
= 0;
4002 server_accept_connection (Lisp_Object server
, int channel
)
4004 Lisp_Object proc
, caller
, name
, buffer
;
4005 Lisp_Object contact
, host
, service
;
4006 struct Lisp_Process
*ps
= XPROCESS (server
);
4007 struct Lisp_Process
*p
;
4011 struct sockaddr_in in
;
4013 struct sockaddr_in6 in6
;
4015 #ifdef HAVE_LOCAL_SOCKETS
4016 struct sockaddr_un un
;
4019 socklen_t len
= sizeof saddr
;
4022 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4031 if (code
== EWOULDBLOCK
)
4035 if (!NILP (ps
->log
))
4036 call3 (ps
->log
, server
, Qnil
,
4037 concat3 (build_string ("accept failed with code"),
4038 Fnumber_to_string (make_number (code
)),
4039 build_string ("\n")));
4043 count
= SPECPDL_INDEX ();
4044 record_unwind_protect_int_1 (close_file_unwind
, s
, false);
4048 /* Setup a new process to handle the connection. */
4050 /* Generate a unique identification of the caller, and build contact
4051 information for this process. */
4054 switch (saddr
.sa
.sa_family
)
4058 Lisp_Object args
[5];
4059 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4060 args
[0] = build_string ("%d.%d.%d.%d");
4061 args
[1] = make_number (*ip
++);
4062 args
[2] = make_number (*ip
++);
4063 args
[3] = make_number (*ip
++);
4064 args
[4] = make_number (*ip
++);
4065 host
= Fformat (5, args
);
4066 service
= make_number (ntohs (saddr
.in
.sin_port
));
4068 args
[0] = build_string (" <%s:%d>");
4071 caller
= Fformat (3, args
);
4078 Lisp_Object args
[9];
4079 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4081 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4082 for (i
= 0; i
< 8; i
++)
4083 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4084 host
= Fformat (9, args
);
4085 service
= make_number (ntohs (saddr
.in
.sin_port
));
4087 args
[0] = build_string (" <[%s]:%d>");
4090 caller
= Fformat (3, args
);
4095 #ifdef HAVE_LOCAL_SOCKETS
4099 caller
= Fnumber_to_string (make_number (connect_counter
));
4100 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4104 /* Create a new buffer name for this process if it doesn't have a
4105 filter. The new buffer name is based on the buffer name or
4106 process name of the server process concatenated with the caller
4109 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4110 || EQ (ps
->filter
, Qt
)))
4114 buffer
= ps
->buffer
;
4116 buffer
= Fbuffer_name (buffer
);
4121 buffer
= concat2 (buffer
, caller
);
4122 buffer
= Fget_buffer_create (buffer
);
4126 /* Generate a unique name for the new server process. Combine the
4127 server process name with the caller identification. */
4129 name
= concat2 (ps
->name
, caller
);
4130 proc
= make_process (name
);
4132 chan_process
[s
] = proc
;
4134 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4136 p
= XPROCESS (proc
);
4138 /* Build new contact information for this setup. */
4139 contact
= Fcopy_sequence (ps
->childp
);
4140 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4141 contact
= Fplist_put (contact
, QChost
, host
);
4142 if (!NILP (service
))
4143 contact
= Fplist_put (contact
, QCservice
, service
);
4144 contact
= Fplist_put (contact
, QCremote
,
4145 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4146 #ifdef HAVE_GETSOCKNAME
4148 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4149 contact
= Fplist_put (contact
, QClocal
,
4150 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4153 pset_childp (p
, contact
);
4154 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4155 pset_type (p
, Qnetwork
);
4157 pset_buffer (p
, buffer
);
4158 pset_sentinel (p
, ps
->sentinel
);
4159 pset_filter (p
, ps
->filter
);
4160 pset_command (p
, Qnil
);
4163 unbind_to (count
, Qnil
);
4165 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4168 pset_status (p
, Qrun
);
4170 /* Client processes for accepted connections are not stopped initially. */
4171 if (!EQ (p
->filter
, Qt
))
4173 FD_SET (s
, &input_wait_mask
);
4174 FD_SET (s
, &non_keyboard_wait_mask
);
4177 if (s
> max_process_desc
)
4178 max_process_desc
= s
;
4180 /* Setup coding system for new process based on server process.
4181 This seems to be the proper thing to do, as the coding system
4182 of the new process should reflect the settings at the time the
4183 server socket was opened; not the current settings. */
4185 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4186 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4187 setup_process_coding_systems (proc
);
4189 pset_decoding_buf (p
, empty_unibyte_string
);
4190 p
->decoding_carryover
= 0;
4191 pset_encoding_buf (p
, empty_unibyte_string
);
4193 p
->inherit_coding_system_flag
4194 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4196 if (!NILP (ps
->log
))
4197 call3 (ps
->log
, server
, proc
,
4198 concat3 (build_string ("accept from "),
4199 (STRINGP (host
) ? host
: build_string ("-")),
4200 build_string ("\n")));
4202 exec_sentinel (proc
,
4203 concat3 (build_string ("open from "),
4204 (STRINGP (host
) ? host
: build_string ("-")),
4205 build_string ("\n")));
4208 /* This variable is different from waiting_for_input in keyboard.c.
4209 It is used to communicate to a lisp process-filter/sentinel (via the
4210 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4211 for user-input when that process-filter was called.
4212 waiting_for_input cannot be used as that is by definition 0 when
4213 lisp code is being evalled.
4214 This is also used in record_asynch_buffer_change.
4215 For that purpose, this must be 0
4216 when not inside wait_reading_process_output. */
4217 static int waiting_for_user_input_p
;
4220 wait_reading_process_output_unwind (int data
)
4222 waiting_for_user_input_p
= data
;
4225 /* This is here so breakpoints can be put on it. */
4227 wait_reading_process_output_1 (void)
4231 /* Read and dispose of subprocess output while waiting for timeout to
4232 elapse and/or keyboard input to be available.
4236 If negative, gobble data immediately available but don't wait for any.
4239 an additional duration to wait, measured in nanoseconds
4240 If TIME_LIMIT is zero, then:
4241 If NSECS == 0, there is no limit.
4242 If NSECS > 0, the timeout consists of NSECS only.
4243 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4246 0 to ignore keyboard input, or
4247 1 to return when input is available, or
4248 -1 meaning caller will actually read the input, so don't throw to
4249 the quit handler, or
4251 DO_DISPLAY means redisplay should be done to show subprocess
4252 output that arrives.
4254 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4255 (and gobble terminal input into the buffer if any arrives).
4257 If WAIT_PROC is specified, wait until something arrives from that
4260 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4261 (suspending output from other processes). A negative value
4262 means don't run any timers either.
4264 Return positive if we received input from WAIT_PROC (or from any
4265 process if WAIT_PROC is null), zero if we attempted to receive
4266 input but got none, and negative if we didn't even try. */
4269 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4271 Lisp_Object wait_for_cell
,
4272 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4282 struct timespec timeout
, end_time
;
4283 int got_some_input
= -1;
4284 ptrdiff_t count
= SPECPDL_INDEX ();
4286 FD_ZERO (&Available
);
4289 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4290 && !(CONSP (wait_proc
->status
)
4291 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4292 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4294 record_unwind_protect_int (wait_reading_process_output_unwind
,
4295 waiting_for_user_input_p
);
4296 waiting_for_user_input_p
= read_kbd
;
4303 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4304 time_limit
= TYPE_MAXIMUM (time_t);
4306 /* Since we may need to wait several times,
4307 compute the absolute time to return at. */
4308 if (time_limit
|| nsecs
> 0)
4310 timeout
= make_timespec (time_limit
, nsecs
);
4311 end_time
= timespec_add (current_timespec (), timeout
);
4316 bool timeout_reduced_for_timers
= 0;
4318 /* If calling from keyboard input, do not quit
4319 since we want to return C-g as an input character.
4320 Otherwise, do pending quit if requested. */
4323 else if (pending_signals
)
4324 process_pending_signals ();
4326 /* Exit now if the cell we're waiting for became non-nil. */
4327 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4330 /* After reading input, vacuum up any leftovers without waiting. */
4331 if (0 <= got_some_input
)
4334 /* Compute time from now till when time limit is up. */
4335 /* Exit if already run out. */
4338 /* A negative timeout means
4339 gobble output available now
4340 but don't wait at all. */
4342 timeout
= make_timespec (0, 0);
4344 else if (time_limit
|| nsecs
> 0)
4346 struct timespec now
= current_timespec ();
4347 if (timespec_cmp (end_time
, now
) <= 0)
4349 timeout
= timespec_sub (end_time
, now
);
4353 timeout
= make_timespec (100000, 0);
4356 /* Normally we run timers here.
4357 But not if wait_for_cell; in those cases,
4358 the wait is supposed to be short,
4359 and those callers cannot handle running arbitrary Lisp code here. */
4360 if (NILP (wait_for_cell
)
4361 && just_wait_proc
>= 0)
4363 struct timespec timer_delay
;
4367 unsigned old_timers_run
= timers_run
;
4368 struct buffer
*old_buffer
= current_buffer
;
4369 Lisp_Object old_window
= selected_window
;
4371 timer_delay
= timer_check ();
4373 /* If a timer has run, this might have changed buffers
4374 an alike. Make read_key_sequence aware of that. */
4375 if (timers_run
!= old_timers_run
4376 && (old_buffer
!= current_buffer
4377 || !EQ (old_window
, selected_window
))
4378 && waiting_for_user_input_p
== -1)
4379 record_asynch_buffer_change ();
4381 if (timers_run
!= old_timers_run
&& do_display
)
4382 /* We must retry, since a timer may have requeued itself
4383 and that could alter the time_delay. */
4384 redisplay_preserve_echo_area (9);
4388 while (!detect_input_pending ());
4390 /* If there is unread keyboard input, also return. */
4392 && requeued_events_pending_p ())
4395 /* A negative timeout means do not wait at all. */
4398 if (timespec_valid_p (timer_delay
))
4400 if (timespec_cmp (timer_delay
, timeout
) < 0)
4402 timeout
= timer_delay
;
4403 timeout_reduced_for_timers
= 1;
4408 /* This is so a breakpoint can be put here. */
4409 wait_reading_process_output_1 ();
4414 /* Cause C-g and alarm signals to take immediate action,
4415 and cause input available signals to zero out timeout.
4417 It is important that we do this before checking for process
4418 activity. If we get a SIGCHLD after the explicit checks for
4419 process activity, timeout is the only way we will know. */
4421 set_waiting_for_input (&timeout
);
4423 /* If status of something has changed, and no input is
4424 available, notify the user of the change right away. After
4425 this explicit check, we'll let the SIGCHLD handler zap
4426 timeout to get our attention. */
4427 if (update_tick
!= process_tick
)
4432 if (kbd_on_hold_p ())
4435 Atemp
= input_wait_mask
;
4438 timeout
= make_timespec (0, 0);
4439 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4441 #ifdef NON_BLOCKING_CONNECT
4442 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4446 NULL
, &timeout
, NULL
)
4449 /* It's okay for us to do this and then continue with
4450 the loop, since timeout has already been zeroed out. */
4451 clear_waiting_for_input ();
4452 got_some_input
= status_notify (NULL
, wait_proc
);
4453 if (do_display
) redisplay_preserve_echo_area (13);
4457 /* Don't wait for output from a non-running process. Just
4458 read whatever data has already been received. */
4459 if (wait_proc
&& wait_proc
->raw_status_new
)
4460 update_status (wait_proc
);
4462 && ! EQ (wait_proc
->status
, Qrun
)
4463 && ! EQ (wait_proc
->status
, Qconnect
))
4465 bool read_some_bytes
= 0;
4467 clear_waiting_for_input ();
4468 XSETPROCESS (proc
, wait_proc
);
4470 /* Read data from the process, until we exhaust it. */
4471 while (wait_proc
->infd
>= 0)
4473 int nread
= read_process_output (proc
, wait_proc
->infd
);
4476 if (errno
== EIO
|| errno
== EAGAIN
)
4479 if (errno
== EWOULDBLOCK
)
4485 if (got_some_input
< nread
)
4486 got_some_input
= nread
;
4489 read_some_bytes
= true;
4492 if (read_some_bytes
&& do_display
)
4493 redisplay_preserve_echo_area (10);
4498 /* Wait till there is something to do */
4500 if (wait_proc
&& just_wait_proc
)
4502 if (wait_proc
->infd
< 0) /* Terminated */
4504 FD_SET (wait_proc
->infd
, &Available
);
4508 else if (!NILP (wait_for_cell
))
4510 Available
= non_process_wait_mask
;
4517 Available
= non_keyboard_wait_mask
;
4519 Available
= input_wait_mask
;
4520 Writeok
= write_mask
;
4521 check_delay
= wait_proc
? 0 : process_output_delay_count
;
4522 check_write
= SELECT_CAN_DO_WRITE_MASK
;
4525 /* If frame size has changed or the window is newly mapped,
4526 redisplay now, before we start to wait. There is a race
4527 condition here; if a SIGIO arrives between now and the select
4528 and indicates that a frame is trashed, the select may block
4529 displaying a trashed screen. */
4530 if (frame_garbaged
&& do_display
)
4532 clear_waiting_for_input ();
4533 redisplay_preserve_echo_area (11);
4535 set_waiting_for_input (&timeout
);
4538 /* Skip the `select' call if input is available and we're
4539 waiting for keyboard input or a cell change (which can be
4540 triggered by processing X events). In the latter case, set
4541 nfds to 1 to avoid breaking the loop. */
4543 if ((read_kbd
|| !NILP (wait_for_cell
))
4544 && detect_input_pending ())
4546 nfds
= read_kbd
? 0 : 1;
4548 FD_ZERO (&Available
);
4554 #ifdef ADAPTIVE_READ_BUFFERING
4555 /* Set the timeout for adaptive read buffering if any
4556 process has non-zero read_output_skip and non-zero
4557 read_output_delay, and we are not reading output for a
4558 specific process. It is not executed if
4559 Vprocess_adaptive_read_buffering is nil. */
4560 if (process_output_skip
&& check_delay
> 0)
4562 int nsecs
= timeout
.tv_nsec
;
4563 if (timeout
.tv_sec
> 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4564 nsecs
= READ_OUTPUT_DELAY_MAX
;
4565 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4567 proc
= chan_process
[channel
];
4570 /* Find minimum non-zero read_output_delay among the
4571 processes with non-zero read_output_skip. */
4572 if (XPROCESS (proc
)->read_output_delay
> 0)
4575 if (!XPROCESS (proc
)->read_output_skip
)
4577 FD_CLR (channel
, &Available
);
4578 XPROCESS (proc
)->read_output_skip
= 0;
4579 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4580 nsecs
= XPROCESS (proc
)->read_output_delay
;
4583 timeout
= make_timespec (0, nsecs
);
4584 process_output_skip
= 0;
4588 #if defined (HAVE_NS)
4590 #elif defined (HAVE_GLIB)
4595 (max (max_process_desc
, max_input_desc
) + 1,
4597 (check_write
? &Writeok
: 0),
4598 NULL
, &timeout
, NULL
);
4601 /* GnuTLS buffers data internally. In lowat mode it leaves
4602 some data in the TCP buffers so that select works, but
4603 with custom pull/push functions we need to check if some
4604 data is available in the buffers manually. */
4609 /* We're not waiting on a specific process, so loop
4610 through all the channels and check for data.
4611 This is a workaround needed for some versions of
4612 the gnutls library -- 2.12.14 has been confirmed
4614 http://comments.gmane.org/gmane.emacs.devel/145074 */
4615 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
4616 if (! NILP (chan_process
[channel
]))
4618 struct Lisp_Process
*p
=
4619 XPROCESS (chan_process
[channel
]);
4620 if (p
&& p
->gnutls_p
&& p
->gnutls_state
4621 && ((emacs_gnutls_record_check_pending
4626 eassert (p
->infd
== channel
);
4627 FD_SET (p
->infd
, &Available
);
4633 /* Check this specific channel. */
4634 if (wait_proc
->gnutls_p
/* Check for valid process. */
4635 && wait_proc
->gnutls_state
4636 /* Do we have pending data? */
4637 && ((emacs_gnutls_record_check_pending
4638 (wait_proc
->gnutls_state
))
4642 /* Set to Available. */
4643 FD_SET (wait_proc
->infd
, &Available
);
4652 /* Make C-g and alarm signals set flags again */
4653 clear_waiting_for_input ();
4655 /* If we woke up due to SIGWINCH, actually change size now. */
4656 do_pending_window_change (0);
4658 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4659 /* We waited the full specified time, so return now. */
4663 if (xerrno
== EINTR
)
4665 else if (xerrno
== EBADF
)
4668 report_file_errno ("Failed select", Qnil
, xerrno
);
4671 /* Check for keyboard input */
4672 /* If there is any, return immediately
4673 to give it higher priority than subprocesses */
4677 unsigned old_timers_run
= timers_run
;
4678 struct buffer
*old_buffer
= current_buffer
;
4679 Lisp_Object old_window
= selected_window
;
4682 if (detect_input_pending_run_timers (do_display
))
4684 swallow_events (do_display
);
4685 if (detect_input_pending_run_timers (do_display
))
4689 /* If a timer has run, this might have changed buffers
4690 an alike. Make read_key_sequence aware of that. */
4691 if (timers_run
!= old_timers_run
4692 && waiting_for_user_input_p
== -1
4693 && (old_buffer
!= current_buffer
4694 || !EQ (old_window
, selected_window
)))
4695 record_asynch_buffer_change ();
4701 /* If there is unread keyboard input, also return. */
4703 && requeued_events_pending_p ())
4706 /* If we are not checking for keyboard input now,
4707 do process events (but don't run any timers).
4708 This is so that X events will be processed.
4709 Otherwise they may have to wait until polling takes place.
4710 That would causes delays in pasting selections, for example.
4712 (We used to do this only if wait_for_cell.) */
4713 if (read_kbd
== 0 && detect_input_pending ())
4715 swallow_events (do_display
);
4716 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4717 if (detect_input_pending ())
4722 /* Exit now if the cell we're waiting for became non-nil. */
4723 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4727 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4728 go read it. This can happen with X on BSD after logging out.
4729 In that case, there really is no input and no SIGIO,
4730 but select says there is input. */
4732 if (read_kbd
&& interrupt_input
4733 && keyboard_bit_set (&Available
) && ! noninteractive
)
4734 handle_input_available_signal (SIGIO
);
4737 /* If checking input just got us a size-change event from X,
4738 obey it now if we should. */
4739 if (read_kbd
|| ! NILP (wait_for_cell
))
4740 do_pending_window_change (0);
4742 /* Check for data from a process. */
4743 if (no_avail
|| nfds
== 0)
4746 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4748 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4750 && ((d
->condition
& FOR_READ
4751 && FD_ISSET (channel
, &Available
))
4752 || (d
->condition
& FOR_WRITE
4753 && FD_ISSET (channel
, &write_mask
))))
4754 d
->func (channel
, d
->data
);
4757 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4759 if (FD_ISSET (channel
, &Available
)
4760 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4761 && !FD_ISSET (channel
, &non_process_wait_mask
))
4765 /* If waiting for this channel, arrange to return as
4766 soon as no more input to be processed. No more
4768 proc
= chan_process
[channel
];
4772 /* If this is a server stream socket, accept connection. */
4773 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4775 server_accept_connection (proc
, channel
);
4779 /* Read data from the process, starting with our
4780 buffered-ahead character if we have one. */
4782 nread
= read_process_output (proc
, channel
);
4783 if ((!wait_proc
|| wait_proc
== XPROCESS (proc
)) && got_some_input
< nread
)
4784 got_some_input
= nread
;
4787 /* Since read_process_output can run a filter,
4788 which can call accept-process-output,
4789 don't try to read from any other processes
4790 before doing the select again. */
4791 FD_ZERO (&Available
);
4794 redisplay_preserve_echo_area (12);
4797 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4800 else if (nread
== -1 && errno
== EAGAIN
)
4803 /* FIXME: Is this special case still needed? */
4804 /* Note that we cannot distinguish between no input
4805 available now and a closed pipe.
4806 With luck, a closed pipe will be accompanied by
4807 subprocess termination and SIGCHLD. */
4808 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4812 /* On some OSs with ptys, when the process on one end of
4813 a pty exits, the other end gets an error reading with
4814 errno = EIO instead of getting an EOF (0 bytes read).
4815 Therefore, if we get an error reading and errno =
4816 EIO, just continue, because the child process has
4817 exited and should clean itself up soon (e.g. when we
4819 else if (nread
== -1 && errno
== EIO
)
4821 struct Lisp_Process
*p
= XPROCESS (proc
);
4823 /* Clear the descriptor now, so we only raise the
4825 FD_CLR (channel
, &input_wait_mask
);
4826 FD_CLR (channel
, &non_keyboard_wait_mask
);
4830 /* If the EIO occurs on a pty, the SIGCHLD handler's
4831 waitpid call will not find the process object to
4832 delete. Do it here. */
4833 p
->tick
= ++process_tick
;
4834 pset_status (p
, Qfailed
);
4837 #endif /* HAVE_PTYS */
4838 /* If we can detect process termination, don't consider the
4839 process gone just because its pipe is closed. */
4840 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4844 /* Preserve status of processes already terminated. */
4845 XPROCESS (proc
)->tick
= ++process_tick
;
4846 deactivate_process (proc
);
4847 if (XPROCESS (proc
)->raw_status_new
)
4848 update_status (XPROCESS (proc
));
4849 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4850 pset_status (XPROCESS (proc
),
4851 list2 (Qexit
, make_number (256)));
4854 #ifdef NON_BLOCKING_CONNECT
4855 if (FD_ISSET (channel
, &Writeok
)
4856 && FD_ISSET (channel
, &connect_wait_mask
))
4858 struct Lisp_Process
*p
;
4860 FD_CLR (channel
, &connect_wait_mask
);
4861 FD_CLR (channel
, &write_mask
);
4862 if (--num_pending_connects
< 0)
4865 proc
= chan_process
[channel
];
4869 p
= XPROCESS (proc
);
4872 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4873 So only use it on systems where it is known to work. */
4875 socklen_t xlen
= sizeof (xerrno
);
4876 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4881 struct sockaddr pname
;
4882 socklen_t pnamelen
= sizeof (pname
);
4884 /* If connection failed, getpeername will fail. */
4886 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4888 /* Obtain connect failure code through error slippage. */
4891 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4898 p
->tick
= ++process_tick
;
4899 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
4900 deactivate_process (proc
);
4904 pset_status (p
, Qrun
);
4905 /* Execute the sentinel here. If we had relied on
4906 status_notify to do it later, it will read input
4907 from the process before calling the sentinel. */
4908 exec_sentinel (proc
, build_string ("open\n"));
4909 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
4911 FD_SET (p
->infd
, &input_wait_mask
);
4912 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4916 #endif /* NON_BLOCKING_CONNECT */
4917 } /* End for each file descriptor. */
4918 } /* End while exit conditions not met. */
4920 unbind_to (count
, Qnil
);
4922 /* If calling from keyboard input, do not quit
4923 since we want to return C-g as an input character.
4924 Otherwise, do pending quit if requested. */
4927 /* Prevent input_pending from remaining set if we quit. */
4928 clear_input_pending ();
4932 return got_some_input
;
4935 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4938 read_process_output_call (Lisp_Object fun_and_args
)
4940 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
4944 read_process_output_error_handler (Lisp_Object error_val
)
4946 cmd_error_internal (error_val
, "error in process filter: ");
4948 update_echo_area ();
4949 Fsleep_for (make_number (2), Qnil
);
4954 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
4956 struct coding_system
*coding
);
4958 /* Read pending output from the process channel,
4959 starting with our buffered-ahead character if we have one.
4960 Yield number of decoded characters read.
4962 This function reads at most 4096 characters.
4963 If you want to read all available subprocess output,
4964 you must call it repeatedly until it returns zero.
4966 The characters read are decoded according to PROC's coding-system
4970 read_process_output (Lisp_Object proc
, register int channel
)
4972 register ssize_t nbytes
;
4974 register struct Lisp_Process
*p
= XPROCESS (proc
);
4975 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
4976 int carryover
= p
->decoding_carryover
;
4978 ptrdiff_t count
= SPECPDL_INDEX ();
4979 Lisp_Object odeactivate
;
4981 chars
= alloca (carryover
+ readmax
);
4983 /* See the comment above. */
4984 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
4986 #ifdef DATAGRAM_SOCKETS
4987 /* We have a working select, so proc_buffered_char is always -1. */
4988 if (DATAGRAM_CHAN_P (channel
))
4990 socklen_t len
= datagram_address
[channel
].len
;
4991 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
4992 0, datagram_address
[channel
].sa
, &len
);
4997 bool buffered
= proc_buffered_char
[channel
] >= 0;
5000 chars
[carryover
] = proc_buffered_char
[channel
];
5001 proc_buffered_char
[channel
] = -1;
5004 if (p
->gnutls_p
&& p
->gnutls_state
)
5005 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5006 readmax
- buffered
);
5009 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5010 readmax
- buffered
);
5011 #ifdef ADAPTIVE_READ_BUFFERING
5012 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5014 int delay
= p
->read_output_delay
;
5017 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5020 process_output_delay_count
++;
5021 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5024 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5026 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5028 process_output_delay_count
--;
5030 p
->read_output_delay
= delay
;
5033 p
->read_output_skip
= 1;
5034 process_output_skip
= 1;
5039 nbytes
+= buffered
&& nbytes
<= 0;
5042 p
->decoding_carryover
= 0;
5044 /* At this point, NBYTES holds number of bytes just received
5045 (including the one in proc_buffered_char[channel]). */
5048 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5050 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5053 /* Now set NBYTES how many bytes we must decode. */
5054 nbytes
+= carryover
;
5056 odeactivate
= Vdeactivate_mark
;
5057 /* There's no good reason to let process filters change the current
5058 buffer, and many callers of accept-process-output, sit-for, and
5059 friends don't expect current-buffer to be changed from under them. */
5060 record_unwind_current_buffer ();
5062 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5064 /* Handling the process output should not deactivate the mark. */
5065 Vdeactivate_mark
= odeactivate
;
5067 unbind_to (count
, Qnil
);
5072 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5074 struct coding_system
*coding
)
5076 Lisp_Object outstream
= p
->filter
;
5078 bool outer_running_asynch_code
= running_asynch_code
;
5079 int waiting
= waiting_for_user_input_p
;
5081 /* No need to gcpro these, because all we do with them later
5082 is test them for EQness, and none of them should be a string. */
5084 Lisp_Object obuffer
, okeymap
;
5085 XSETBUFFER (obuffer
, current_buffer
);
5086 okeymap
= BVAR (current_buffer
, keymap
);
5089 /* We inhibit quit here instead of just catching it so that
5090 hitting ^G when a filter happens to be running won't screw
5092 specbind (Qinhibit_quit
, Qt
);
5093 specbind (Qlast_nonmenu_event
, Qt
);
5095 /* In case we get recursively called,
5096 and we already saved the match data nonrecursively,
5097 save the same match data in safely recursive fashion. */
5098 if (outer_running_asynch_code
)
5101 /* Don't clobber the CURRENT match data, either! */
5102 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5103 restore_search_regs ();
5104 record_unwind_save_match_data ();
5105 Fset_match_data (tem
, Qt
);
5108 /* For speed, if a search happens within this code,
5109 save the match data in a special nonrecursive fashion. */
5110 running_asynch_code
= 1;
5112 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5113 text
= coding
->dst_object
;
5114 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5115 /* A new coding system might be found. */
5116 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5118 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5120 /* Don't call setup_coding_system for
5121 proc_decode_coding_system[channel] here. It is done in
5122 detect_coding called via decode_coding above. */
5124 /* If a coding system for encoding is not yet decided, we set
5125 it as the same as coding-system for decoding.
5127 But, before doing that we must check if
5128 proc_encode_coding_system[p->outfd] surely points to a
5129 valid memory because p->outfd will be changed once EOF is
5130 sent to the process. */
5131 if (NILP (p
->encode_coding_system
)
5132 && proc_encode_coding_system
[p
->outfd
])
5134 pset_encode_coding_system
5135 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5136 setup_coding_system (p
->encode_coding_system
,
5137 proc_encode_coding_system
[p
->outfd
]);
5141 if (coding
->carryover_bytes
> 0)
5143 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5144 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5145 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5146 coding
->carryover_bytes
);
5147 p
->decoding_carryover
= coding
->carryover_bytes
;
5149 if (SBYTES (text
) > 0)
5150 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5151 sometimes it's simply wrong to wrap (e.g. when called from
5152 accept-process-output). */
5153 internal_condition_case_1 (read_process_output_call
,
5154 list3 (outstream
, make_lisp_proc (p
), text
),
5155 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5156 read_process_output_error_handler
);
5158 /* If we saved the match data nonrecursively, restore it now. */
5159 restore_search_regs ();
5160 running_asynch_code
= outer_running_asynch_code
;
5162 /* Restore waiting_for_user_input_p as it was
5163 when we were called, in case the filter clobbered it. */
5164 waiting_for_user_input_p
= waiting
;
5166 #if 0 /* Call record_asynch_buffer_change unconditionally,
5167 because we might have changed minor modes or other things
5168 that affect key bindings. */
5169 if (! EQ (Fcurrent_buffer (), obuffer
)
5170 || ! EQ (current_buffer
->keymap
, okeymap
))
5172 /* But do it only if the caller is actually going to read events.
5173 Otherwise there's no need to make him wake up, and it could
5174 cause trouble (for example it would make sit_for return). */
5175 if (waiting_for_user_input_p
== -1)
5176 record_asynch_buffer_change ();
5179 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5180 Sinternal_default_process_filter
, 2, 2, 0,
5181 doc
: /* Function used as default process filter.
5182 This inserts the process's output into its buffer, if there is one.
5183 Otherwise it discards the output. */)
5184 (Lisp_Object proc
, Lisp_Object text
)
5186 struct Lisp_Process
*p
;
5189 CHECK_PROCESS (proc
);
5190 p
= XPROCESS (proc
);
5191 CHECK_STRING (text
);
5193 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5195 Lisp_Object old_read_only
;
5196 ptrdiff_t old_begv
, old_zv
;
5197 ptrdiff_t old_begv_byte
, old_zv_byte
;
5198 ptrdiff_t before
, before_byte
;
5199 ptrdiff_t opoint_byte
;
5202 Fset_buffer (p
->buffer
);
5204 opoint_byte
= PT_BYTE
;
5205 old_read_only
= BVAR (current_buffer
, read_only
);
5208 old_begv_byte
= BEGV_BYTE
;
5209 old_zv_byte
= ZV_BYTE
;
5211 bset_read_only (current_buffer
, Qnil
);
5213 /* Insert new output into buffer at the current end-of-output
5214 marker, thus preserving logical ordering of input and output. */
5215 if (XMARKER (p
->mark
)->buffer
)
5216 set_point_from_marker (p
->mark
);
5218 SET_PT_BOTH (ZV
, ZV_BYTE
);
5220 before_byte
= PT_BYTE
;
5222 /* If the output marker is outside of the visible region, save
5223 the restriction and widen. */
5224 if (! (BEGV
<= PT
&& PT
<= ZV
))
5227 /* Adjust the multibyteness of TEXT to that of the buffer. */
5228 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5229 != ! STRING_MULTIBYTE (text
))
5230 text
= (STRING_MULTIBYTE (text
)
5231 ? Fstring_as_unibyte (text
)
5232 : Fstring_to_multibyte (text
));
5233 /* Insert before markers in case we are inserting where
5234 the buffer's mark is, and the user's next command is Meta-y. */
5235 insert_from_string_before_markers (text
, 0, 0,
5236 SCHARS (text
), SBYTES (text
), 0);
5238 /* Make sure the process marker's position is valid when the
5239 process buffer is changed in the signal_after_change above.
5240 W3 is known to do that. */
5241 if (BUFFERP (p
->buffer
)
5242 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5243 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5245 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5247 update_mode_lines
= 23;
5249 /* Make sure opoint and the old restrictions
5250 float ahead of any new text just as point would. */
5251 if (opoint
>= before
)
5253 opoint
+= PT
- before
;
5254 opoint_byte
+= PT_BYTE
- before_byte
;
5256 if (old_begv
> before
)
5258 old_begv
+= PT
- before
;
5259 old_begv_byte
+= PT_BYTE
- before_byte
;
5261 if (old_zv
>= before
)
5263 old_zv
+= PT
- before
;
5264 old_zv_byte
+= PT_BYTE
- before_byte
;
5267 /* If the restriction isn't what it should be, set it. */
5268 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5269 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5271 bset_read_only (current_buffer
, old_read_only
);
5272 SET_PT_BOTH (opoint
, opoint_byte
);
5277 /* Sending data to subprocess. */
5279 /* In send_process, when a write fails temporarily,
5280 wait_reading_process_output is called. It may execute user code,
5281 e.g. timers, that attempts to write new data to the same process.
5282 We must ensure that data is sent in the right order, and not
5283 interspersed half-completed with other writes (Bug#10815). This is
5284 handled by the write_queue element of struct process. It is a list
5285 with each entry having the form
5287 (string . (offset . length))
5289 where STRING is a lisp string, OFFSET is the offset into the
5290 string's byte sequence from which we should begin to send, and
5291 LENGTH is the number of bytes left to send. */
5293 /* Create a new entry in write_queue.
5294 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5295 BUF is a pointer to the string sequence of the input_obj or a C
5296 string in case of Qt or Qnil. */
5299 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5300 const char *buf
, ptrdiff_t len
, bool front
)
5303 Lisp_Object entry
, obj
;
5305 if (STRINGP (input_obj
))
5307 offset
= buf
- SSDATA (input_obj
);
5313 obj
= make_unibyte_string (buf
, len
);
5316 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5319 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5321 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5324 /* Remove the first element in the write_queue of process P, put its
5325 contents in OBJ, BUF and LEN, and return true. If the
5326 write_queue is empty, return false. */
5329 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5330 const char **buf
, ptrdiff_t *len
)
5332 Lisp_Object entry
, offset_length
;
5335 if (NILP (p
->write_queue
))
5338 entry
= XCAR (p
->write_queue
);
5339 pset_write_queue (p
, XCDR (p
->write_queue
));
5341 *obj
= XCAR (entry
);
5342 offset_length
= XCDR (entry
);
5344 *len
= XINT (XCDR (offset_length
));
5345 offset
= XINT (XCAR (offset_length
));
5346 *buf
= SSDATA (*obj
) + offset
;
5351 /* Send some data to process PROC.
5352 BUF is the beginning of the data; LEN is the number of characters.
5353 OBJECT is the Lisp object that the data comes from. If OBJECT is
5354 nil or t, it means that the data comes from C string.
5356 If OBJECT is not nil, the data is encoded by PROC's coding-system
5357 for encoding before it is sent.
5359 This function can evaluate Lisp code and can garbage collect. */
5362 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5365 struct Lisp_Process
*p
= XPROCESS (proc
);
5367 struct coding_system
*coding
;
5369 if (p
->raw_status_new
)
5371 if (! EQ (p
->status
, Qrun
))
5372 error ("Process %s not running", SDATA (p
->name
));
5374 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5376 coding
= proc_encode_coding_system
[p
->outfd
];
5377 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5379 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5380 || (BUFFERP (object
)
5381 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5384 pset_encode_coding_system
5385 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5386 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5388 /* The coding system for encoding was changed to raw-text
5389 because we sent a unibyte text previously. Now we are
5390 sending a multibyte text, thus we must encode it by the
5391 original coding system specified for the current process.
5393 Another reason we come here is that the coding system
5394 was just complemented and a new one was returned by
5395 complement_process_encoding_system. */
5396 setup_coding_system (p
->encode_coding_system
, coding
);
5397 Vlast_coding_system_used
= p
->encode_coding_system
;
5399 coding
->src_multibyte
= 1;
5403 coding
->src_multibyte
= 0;
5404 /* For sending a unibyte text, character code conversion should
5405 not take place but EOL conversion should. So, setup raw-text
5406 or one of the subsidiary if we have not yet done it. */
5407 if (CODING_REQUIRE_ENCODING (coding
))
5409 if (CODING_REQUIRE_FLUSHING (coding
))
5411 /* But, before changing the coding, we must flush out data. */
5412 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5413 send_process (proc
, "", 0, Qt
);
5414 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5416 setup_coding_system (raw_text_coding_system
5417 (Vlast_coding_system_used
),
5419 coding
->src_multibyte
= 0;
5422 coding
->dst_multibyte
= 0;
5424 if (CODING_REQUIRE_ENCODING (coding
))
5426 coding
->dst_object
= Qt
;
5427 if (BUFFERP (object
))
5429 ptrdiff_t from_byte
, from
, to
;
5430 ptrdiff_t save_pt
, save_pt_byte
;
5431 struct buffer
*cur
= current_buffer
;
5433 set_buffer_internal (XBUFFER (object
));
5434 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5436 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5437 from
= BYTE_TO_CHAR (from_byte
);
5438 to
= BYTE_TO_CHAR (from_byte
+ len
);
5439 TEMP_SET_PT_BOTH (from
, from_byte
);
5440 encode_coding_object (coding
, object
, from
, from_byte
,
5441 to
, from_byte
+ len
, Qt
);
5442 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5443 set_buffer_internal (cur
);
5445 else if (STRINGP (object
))
5447 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5448 SBYTES (object
), Qt
);
5452 coding
->dst_object
= make_unibyte_string (buf
, len
);
5453 coding
->produced
= len
;
5456 len
= coding
->produced
;
5457 object
= coding
->dst_object
;
5458 buf
= SSDATA (object
);
5461 /* If there is already data in the write_queue, put the new data
5462 in the back of queue. Otherwise, ignore it. */
5463 if (!NILP (p
->write_queue
))
5464 write_queue_push (p
, object
, buf
, len
, 0);
5466 do /* while !NILP (p->write_queue) */
5468 ptrdiff_t cur_len
= -1;
5469 const char *cur_buf
;
5470 Lisp_Object cur_object
;
5472 /* If write_queue is empty, ignore it. */
5473 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5477 cur_object
= object
;
5482 /* Send this batch, using one or more write calls. */
5483 ptrdiff_t written
= 0;
5484 int outfd
= p
->outfd
;
5485 #ifdef DATAGRAM_SOCKETS
5486 if (DATAGRAM_CHAN_P (outfd
))
5488 rv
= sendto (outfd
, cur_buf
, cur_len
,
5489 0, datagram_address
[outfd
].sa
,
5490 datagram_address
[outfd
].len
);
5493 else if (errno
== EMSGSIZE
)
5494 report_file_error ("Sending datagram", proc
);
5500 if (p
->gnutls_p
&& p
->gnutls_state
)
5501 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5504 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5505 rv
= (written
? 0 : -1);
5506 #ifdef ADAPTIVE_READ_BUFFERING
5507 if (p
->read_output_delay
> 0
5508 && p
->adaptive_read_buffering
== 1)
5510 p
->read_output_delay
= 0;
5511 process_output_delay_count
--;
5512 p
->read_output_skip
= 0;
5521 || errno
== EWOULDBLOCK
5524 /* Buffer is full. Wait, accepting input;
5525 that may allow the program
5526 to finish doing output and read more. */
5528 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5529 /* A gross hack to work around a bug in FreeBSD.
5530 In the following sequence, read(2) returns
5534 write(2) 954 bytes, get EAGAIN
5535 read(2) 1024 bytes in process_read_output
5536 read(2) 11 bytes in process_read_output
5538 That is, read(2) returns more bytes than have
5539 ever been written successfully. The 1033 bytes
5540 read are the 1022 bytes written successfully
5541 after processing (for example with CRs added if
5542 the terminal is set up that way which it is
5543 here). The same bytes will be seen again in a
5544 later read(2), without the CRs. */
5546 if (errno
== EAGAIN
)
5549 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5551 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5553 /* Put what we should have written in wait_queue. */
5554 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5555 wait_reading_process_output (0, 20 * 1000 * 1000,
5556 0, 0, Qnil
, NULL
, 0);
5557 /* Reread queue, to see what is left. */
5560 else if (errno
== EPIPE
)
5562 p
->raw_status_new
= 0;
5563 pset_status (p
, list2 (Qexit
, make_number (256)));
5564 p
->tick
= ++process_tick
;
5565 deactivate_process (proc
);
5566 error ("process %s no longer connected to pipe; closed it",
5570 /* This is a real error. */
5571 report_file_error ("Writing to process", proc
);
5577 while (!NILP (p
->write_queue
));
5580 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5582 doc
: /* Send current contents of region as input to PROCESS.
5583 PROCESS may be a process, a buffer, the name of a process or buffer, or
5584 nil, indicating the current buffer's process.
5585 Called from program, takes three arguments, PROCESS, START and END.
5586 If the region is more than 500 characters long,
5587 it is sent in several bunches. This may happen even for shorter regions.
5588 Output from processes can arrive in between bunches. */)
5589 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5591 Lisp_Object proc
= get_process (process
);
5592 ptrdiff_t start_byte
, end_byte
;
5594 validate_region (&start
, &end
);
5596 start_byte
= CHAR_TO_BYTE (XINT (start
));
5597 end_byte
= CHAR_TO_BYTE (XINT (end
));
5599 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5600 move_gap_both (XINT (start
), start_byte
);
5602 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5603 end_byte
- start_byte
, Fcurrent_buffer ());
5608 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5610 doc
: /* Send PROCESS the contents of STRING as input.
5611 PROCESS may be a process, a buffer, the name of a process or buffer, or
5612 nil, indicating the current buffer's process.
5613 If STRING is more than 500 characters long,
5614 it is sent in several bunches. This may happen even for shorter strings.
5615 Output from processes can arrive in between bunches. */)
5616 (Lisp_Object process
, Lisp_Object string
)
5619 CHECK_STRING (string
);
5620 proc
= get_process (process
);
5621 send_process (proc
, SSDATA (string
),
5622 SBYTES (string
), string
);
5626 /* Return the foreground process group for the tty/pty that
5627 the process P uses. */
5629 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5634 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5637 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5638 master side. Try the slave side. */
5639 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5643 ioctl (fd
, TIOCGPGRP
, &gid
);
5647 #endif /* defined (TIOCGPGRP ) */
5652 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5653 Sprocess_running_child_p
, 0, 1, 0,
5654 doc
: /* Return t if PROCESS has given the terminal to a child.
5655 If the operating system does not make it possible to find out,
5656 return t unconditionally. */)
5657 (Lisp_Object process
)
5659 /* Initialize in case ioctl doesn't exist or gives an error,
5660 in a way that will cause returning t. */
5663 struct Lisp_Process
*p
;
5665 proc
= get_process (process
);
5666 p
= XPROCESS (proc
);
5668 if (!EQ (p
->type
, Qreal
))
5669 error ("Process %s is not a subprocess",
5672 error ("Process %s is not active",
5675 gid
= emacs_get_tty_pgrp (p
);
5682 /* send a signal number SIGNO to PROCESS.
5683 If CURRENT_GROUP is t, that means send to the process group
5684 that currently owns the terminal being used to communicate with PROCESS.
5685 This is used for various commands in shell mode.
5686 If CURRENT_GROUP is lambda, that means send to the process group
5687 that currently owns the terminal, but only if it is NOT the shell itself.
5689 If NOMSG is false, insert signal-announcements into process's buffers
5692 If we can, we try to signal PROCESS by sending control characters
5693 down the pty. This allows us to signal inferiors who have changed
5694 their uid, for which kill would return an EPERM error. */
5697 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5701 struct Lisp_Process
*p
;
5705 proc
= get_process (process
);
5706 p
= XPROCESS (proc
);
5708 if (!EQ (p
->type
, Qreal
))
5709 error ("Process %s is not a subprocess",
5712 error ("Process %s is not active",
5716 current_group
= Qnil
;
5718 /* If we are using pgrps, get a pgrp number and make it negative. */
5719 if (NILP (current_group
))
5720 /* Send the signal to the shell's process group. */
5724 #ifdef SIGNALS_VIA_CHARACTERS
5725 /* If possible, send signals to the entire pgrp
5726 by sending an input character to it. */
5729 cc_t
*sig_char
= NULL
;
5731 tcgetattr (p
->infd
, &t
);
5736 sig_char
= &t
.c_cc
[VINTR
];
5740 sig_char
= &t
.c_cc
[VQUIT
];
5744 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5745 sig_char
= &t
.c_cc
[VSWTCH
];
5747 sig_char
= &t
.c_cc
[VSUSP
];
5752 if (sig_char
&& *sig_char
!= CDISABLE
)
5754 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5757 /* If we can't send the signal with a character,
5758 fall through and send it another way. */
5760 /* The code above may fall through if it can't
5761 handle the signal. */
5762 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5765 /* Get the current pgrp using the tty itself, if we have that.
5766 Otherwise, use the pty to get the pgrp.
5767 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5768 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5769 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5770 His patch indicates that if TIOCGPGRP returns an error, then
5771 we should just assume that p->pid is also the process group id. */
5773 gid
= emacs_get_tty_pgrp (p
);
5776 /* If we can't get the information, assume
5777 the shell owns the tty. */
5780 /* It is not clear whether anything really can set GID to -1.
5781 Perhaps on some system one of those ioctls can or could do so.
5782 Or perhaps this is vestigial. */
5785 #else /* ! defined (TIOCGPGRP ) */
5786 /* Can't select pgrps on this system, so we know that
5787 the child itself heads the pgrp. */
5789 #endif /* ! defined (TIOCGPGRP ) */
5791 /* If current_group is lambda, and the shell owns the terminal,
5792 don't send any signal. */
5793 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5798 if (signo
== SIGCONT
)
5800 p
->raw_status_new
= 0;
5801 pset_status (p
, Qrun
);
5802 p
->tick
= ++process_tick
;
5805 status_notify (NULL
, NULL
);
5806 redisplay_preserve_echo_area (13);
5812 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5813 We don't know whether the bug is fixed in later HP-UX versions. */
5814 if (! NILP (current_group
) && ioctl (p
->infd
, TIOCSIGSEND
, signo
) != -1)
5818 /* If we don't have process groups, send the signal to the immediate
5819 subprocess. That isn't really right, but it's better than any
5820 obvious alternative. */
5821 pid_t pid
= no_pgrp
? gid
: - gid
;
5823 /* Do not kill an already-reaped process, as that could kill an
5824 innocent bystander that happens to have the same process ID. */
5826 block_child_signal (&oldset
);
5829 unblock_child_signal (&oldset
);
5832 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5833 doc
: /* Interrupt process PROCESS.
5834 PROCESS may be a process, a buffer, or the name of a process or buffer.
5835 No arg or nil means current buffer's process.
5836 Second arg CURRENT-GROUP non-nil means send signal to
5837 the current process-group of the process's controlling terminal
5838 rather than to the process's own process group.
5839 If the process is a shell, this means interrupt current subjob
5840 rather than the shell.
5842 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5843 don't send the signal. */)
5844 (Lisp_Object process
, Lisp_Object current_group
)
5846 process_send_signal (process
, SIGINT
, current_group
, 0);
5850 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5851 doc
: /* Kill process PROCESS. May be process or name of one.
5852 See function `interrupt-process' for more details on usage. */)
5853 (Lisp_Object process
, Lisp_Object current_group
)
5855 process_send_signal (process
, SIGKILL
, current_group
, 0);
5859 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5860 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5861 See function `interrupt-process' for more details on usage. */)
5862 (Lisp_Object process
, Lisp_Object current_group
)
5864 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5868 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5869 doc
: /* Stop process PROCESS. May be process or name of one.
5870 See function `interrupt-process' for more details on usage.
5871 If PROCESS is a network or serial process, inhibit handling of incoming
5873 (Lisp_Object process
, Lisp_Object current_group
)
5875 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5877 struct Lisp_Process
*p
;
5879 p
= XPROCESS (process
);
5880 if (NILP (p
->command
)
5883 FD_CLR (p
->infd
, &input_wait_mask
);
5884 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
5886 pset_command (p
, Qt
);
5890 error ("No SIGTSTP support");
5892 process_send_signal (process
, SIGTSTP
, current_group
, 0);
5897 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
5898 doc
: /* Continue process PROCESS. May be process or name of one.
5899 See function `interrupt-process' for more details on usage.
5900 If PROCESS is a network or serial process, resume handling of incoming
5902 (Lisp_Object process
, Lisp_Object current_group
)
5904 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5906 struct Lisp_Process
*p
;
5908 p
= XPROCESS (process
);
5909 if (EQ (p
->command
, Qt
)
5911 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
5913 FD_SET (p
->infd
, &input_wait_mask
);
5914 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5916 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
5917 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
5918 #else /* not WINDOWSNT */
5919 tcflush (p
->infd
, TCIFLUSH
);
5920 #endif /* not WINDOWSNT */
5922 pset_command (p
, Qnil
);
5926 process_send_signal (process
, SIGCONT
, current_group
, 0);
5928 error ("No SIGCONT support");
5933 /* Return the integer value of the signal whose abbreviation is ABBR,
5934 or a negative number if there is no such signal. */
5936 abbr_to_signal (char const *name
)
5939 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
5941 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
5944 for (i
= 0; i
< sizeof sigbuf
; i
++)
5946 sigbuf
[i
] = c_toupper (name
[i
]);
5948 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
5954 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
5955 2, 2, "sProcess (name or number): \nnSignal code: ",
5956 doc
: /* Send PROCESS the signal with code SIGCODE.
5957 PROCESS may also be a number specifying the process id of the
5958 process to signal; in this case, the process need not be a child of
5960 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5961 (Lisp_Object process
, Lisp_Object sigcode
)
5966 if (STRINGP (process
))
5968 Lisp_Object tem
= Fget_process (process
);
5971 Lisp_Object process_number
=
5972 string_to_number (SSDATA (process
), 10, 1);
5973 if (INTEGERP (process_number
) || FLOATP (process_number
))
5974 tem
= process_number
;
5978 else if (!NUMBERP (process
))
5979 process
= get_process (process
);
5984 if (NUMBERP (process
))
5985 CONS_TO_INTEGER (process
, pid_t
, pid
);
5988 CHECK_PROCESS (process
);
5989 pid
= XPROCESS (process
)->pid
;
5991 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
5994 if (INTEGERP (sigcode
))
5996 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
5997 signo
= XINT (sigcode
);
6003 CHECK_SYMBOL (sigcode
);
6004 name
= SSDATA (SYMBOL_NAME (sigcode
));
6006 signo
= abbr_to_signal (name
);
6008 error ("Undefined signal name %s", name
);
6011 return make_number (kill (pid
, signo
));
6014 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6015 doc
: /* Make PROCESS see end-of-file in its input.
6016 EOF comes after any text already sent to it.
6017 PROCESS may be a process, a buffer, the name of a process or buffer, or
6018 nil, indicating the current buffer's process.
6019 If PROCESS is a network connection, or is a process communicating
6020 through a pipe (as opposed to a pty), then you cannot send any more
6021 text to PROCESS after you call this function.
6022 If PROCESS is a serial process, wait until all output written to the
6023 process has been transmitted to the serial port. */)
6024 (Lisp_Object process
)
6027 struct coding_system
*coding
= NULL
;
6030 if (DATAGRAM_CONN_P (process
))
6033 proc
= get_process (process
);
6034 outfd
= XPROCESS (proc
)->outfd
;
6036 coding
= proc_encode_coding_system
[outfd
];
6038 /* Make sure the process is really alive. */
6039 if (XPROCESS (proc
)->raw_status_new
)
6040 update_status (XPROCESS (proc
));
6041 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6042 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6044 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6046 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6047 send_process (proc
, "", 0, Qnil
);
6050 if (XPROCESS (proc
)->pty_flag
)
6051 send_process (proc
, "\004", 1, Qnil
);
6052 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6055 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6056 report_file_error ("Failed tcdrain", Qnil
);
6057 #endif /* not WINDOWSNT */
6058 /* Do nothing on Windows because writes are blocking. */
6062 struct Lisp_Process
*p
= XPROCESS (proc
);
6063 int old_outfd
= p
->outfd
;
6066 #ifdef HAVE_SHUTDOWN
6067 /* If this is a network connection, or socketpair is used
6068 for communication with the subprocess, call shutdown to cause EOF.
6069 (In some old system, shutdown to socketpair doesn't work.
6070 Then we just can't win.) */
6071 if (EQ (p
->type
, Qnetwork
)
6072 || p
->infd
== old_outfd
)
6073 shutdown (old_outfd
, 1);
6075 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6076 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6078 report_file_error ("Opening null device", Qnil
);
6079 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6080 p
->outfd
= new_outfd
;
6082 if (!proc_encode_coding_system
[new_outfd
])
6083 proc_encode_coding_system
[new_outfd
]
6084 = xmalloc (sizeof (struct coding_system
));
6087 *proc_encode_coding_system
[new_outfd
]
6088 = *proc_encode_coding_system
[old_outfd
];
6089 memset (proc_encode_coding_system
[old_outfd
], 0,
6090 sizeof (struct coding_system
));
6093 setup_coding_system (p
->encode_coding_system
,
6094 proc_encode_coding_system
[new_outfd
]);
6099 /* The main Emacs thread records child processes in three places:
6101 - Vprocess_alist, for asynchronous subprocesses, which are child
6102 processes visible to Lisp.
6104 - deleted_pid_list, for child processes invisible to Lisp,
6105 typically because of delete-process. These are recorded so that
6106 the processes can be reaped when they exit, so that the operating
6107 system's process table is not cluttered by zombies.
6109 - the local variable PID in Fcall_process, call_process_cleanup and
6110 call_process_kill, for synchronous subprocesses.
6111 record_unwind_protect is used to make sure this process is not
6112 forgotten: if the user interrupts call-process and the child
6113 process refuses to exit immediately even with two C-g's,
6114 call_process_kill adds PID's contents to deleted_pid_list before
6117 The main Emacs thread invokes waitpid only on child processes that
6118 it creates and that have not been reaped. This avoid races on
6119 platforms such as GTK, where other threads create their own
6120 subprocesses which the main thread should not reap. For example,
6121 if the main thread attempted to reap an already-reaped child, it
6122 might inadvertently reap a GTK-created process that happened to
6123 have the same process ID. */
6125 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6126 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6127 keep track of its own children. GNUstep is similar. */
6129 static void dummy_handler (int sig
) {}
6130 static signal_handler_t
volatile lib_child_handler
;
6132 /* Handle a SIGCHLD signal by looking for known child processes of
6133 Emacs whose status have changed. For each one found, record its
6136 All we do is change the status; we do not run sentinels or print
6137 notifications. That is saved for the next time keyboard input is
6138 done, in order to avoid timing errors.
6140 ** WARNING: this can be called during garbage collection.
6141 Therefore, it must not be fooled by the presence of mark bits in
6144 ** USG WARNING: Although it is not obvious from the documentation
6145 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6146 signal() before executing at least one wait(), otherwise the
6147 handler will be called again, resulting in an infinite loop. The
6148 relevant portion of the documentation reads "SIGCLD signals will be
6149 queued and the signal-catching function will be continually
6150 reentered until the queue is empty". Invoking signal() causes the
6151 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6154 ** Malloc WARNING: This should never call malloc either directly or
6155 indirectly; if it does, that is a bug */
6158 handle_child_signal (int sig
)
6160 Lisp_Object tail
, proc
;
6162 /* Find the process that signaled us, and record its status. */
6164 /* The process can have been deleted by Fdelete_process, or have
6165 been started asynchronously by Fcall_process. */
6166 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6168 bool all_pids_are_fixnums
6169 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6170 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6171 Lisp_Object head
= XCAR (tail
);
6176 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6179 if (INTEGERP (xpid
))
6180 deleted_pid
= XINT (xpid
);
6182 deleted_pid
= XFLOAT_DATA (xpid
);
6183 if (child_status_changed (deleted_pid
, 0, 0))
6185 if (STRINGP (XCDR (head
)))
6186 unlink (SSDATA (XCDR (head
)));
6187 XSETCAR (tail
, Qnil
);
6192 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6193 FOR_EACH_PROCESS (tail
, proc
)
6195 struct Lisp_Process
*p
= XPROCESS (proc
);
6199 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6201 /* Change the status of the process that was found. */
6202 p
->tick
= ++process_tick
;
6203 p
->raw_status
= status
;
6204 p
->raw_status_new
= 1;
6206 /* If process has terminated, stop waiting for its output. */
6207 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6209 bool clear_desc_flag
= 0;
6212 clear_desc_flag
= 1;
6214 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6215 if (clear_desc_flag
)
6217 FD_CLR (p
->infd
, &input_wait_mask
);
6218 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6224 lib_child_handler (sig
);
6225 #ifdef NS_IMPL_GNUSTEP
6226 /* NSTask in GNUstep sets its child handler each time it is called.
6227 So we must re-set ours. */
6228 catch_child_signal();
6233 deliver_child_signal (int sig
)
6235 deliver_process_signal (sig
, handle_child_signal
);
6240 exec_sentinel_error_handler (Lisp_Object error_val
)
6242 cmd_error_internal (error_val
, "error in process sentinel: ");
6244 update_echo_area ();
6245 Fsleep_for (make_number (2), Qnil
);
6250 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6252 Lisp_Object sentinel
, odeactivate
;
6253 struct Lisp_Process
*p
= XPROCESS (proc
);
6254 ptrdiff_t count
= SPECPDL_INDEX ();
6255 bool outer_running_asynch_code
= running_asynch_code
;
6256 int waiting
= waiting_for_user_input_p
;
6258 if (inhibit_sentinels
)
6261 /* No need to gcpro these, because all we do with them later
6262 is test them for EQness, and none of them should be a string. */
6263 odeactivate
= Vdeactivate_mark
;
6265 Lisp_Object obuffer
, okeymap
;
6266 XSETBUFFER (obuffer
, current_buffer
);
6267 okeymap
= BVAR (current_buffer
, keymap
);
6270 /* There's no good reason to let sentinels change the current
6271 buffer, and many callers of accept-process-output, sit-for, and
6272 friends don't expect current-buffer to be changed from under them. */
6273 record_unwind_current_buffer ();
6275 sentinel
= p
->sentinel
;
6277 /* Inhibit quit so that random quits don't screw up a running filter. */
6278 specbind (Qinhibit_quit
, Qt
);
6279 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6281 /* In case we get recursively called,
6282 and we already saved the match data nonrecursively,
6283 save the same match data in safely recursive fashion. */
6284 if (outer_running_asynch_code
)
6287 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6288 restore_search_regs ();
6289 record_unwind_save_match_data ();
6290 Fset_match_data (tem
, Qt
);
6293 /* For speed, if a search happens within this code,
6294 save the match data in a special nonrecursive fashion. */
6295 running_asynch_code
= 1;
6297 internal_condition_case_1 (read_process_output_call
,
6298 list3 (sentinel
, proc
, reason
),
6299 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6300 exec_sentinel_error_handler
);
6302 /* If we saved the match data nonrecursively, restore it now. */
6303 restore_search_regs ();
6304 running_asynch_code
= outer_running_asynch_code
;
6306 Vdeactivate_mark
= odeactivate
;
6308 /* Restore waiting_for_user_input_p as it was
6309 when we were called, in case the filter clobbered it. */
6310 waiting_for_user_input_p
= waiting
;
6313 if (! EQ (Fcurrent_buffer (), obuffer
)
6314 || ! EQ (current_buffer
->keymap
, okeymap
))
6316 /* But do it only if the caller is actually going to read events.
6317 Otherwise there's no need to make him wake up, and it could
6318 cause trouble (for example it would make sit_for return). */
6319 if (waiting_for_user_input_p
== -1)
6320 record_asynch_buffer_change ();
6322 unbind_to (count
, Qnil
);
6325 /* Report all recent events of a change in process status
6326 (either run the sentinel or output a message).
6327 This is usually done while Emacs is waiting for keyboard input
6328 but can be done at other times.
6330 Return positive if any input was received from WAIT_PROC (or from
6331 any process if WAIT_PROC is null), zero if input was attempted but
6332 none received, and negative if we didn't even try. */
6335 status_notify (struct Lisp_Process
*deleting_process
,
6336 struct Lisp_Process
*wait_proc
)
6339 Lisp_Object tail
, msg
;
6340 struct gcpro gcpro1
, gcpro2
;
6341 int got_some_input
= -1;
6345 /* We need to gcpro tail; if read_process_output calls a filter
6346 which deletes a process and removes the cons to which tail points
6347 from Vprocess_alist, and then causes a GC, tail is an unprotected
6351 /* Set this now, so that if new processes are created by sentinels
6352 that we run, we get called again to handle their status changes. */
6353 update_tick
= process_tick
;
6355 FOR_EACH_PROCESS (tail
, proc
)
6358 register struct Lisp_Process
*p
= XPROCESS (proc
);
6360 if (p
->tick
!= p
->update_tick
)
6362 p
->update_tick
= p
->tick
;
6364 /* If process is still active, read any output that remains. */
6365 while (! EQ (p
->filter
, Qt
)
6366 && ! EQ (p
->status
, Qconnect
)
6367 && ! EQ (p
->status
, Qlisten
)
6368 /* Network or serial process not stopped: */
6369 && ! EQ (p
->command
, Qt
)
6371 && p
!= deleting_process
)
6373 int nread
= read_process_output (proc
, p
->infd
);
6374 if (got_some_input
< nread
)
6375 got_some_input
= nread
;
6380 /* Get the text to use for the message. */
6381 if (p
->raw_status_new
)
6383 msg
= status_message (p
);
6385 /* If process is terminated, deactivate it or delete it. */
6387 if (CONSP (p
->status
))
6388 symbol
= XCAR (p
->status
);
6390 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6391 || EQ (symbol
, Qclosed
))
6393 if (delete_exited_processes
)
6394 remove_process (proc
);
6396 deactivate_process (proc
);
6399 /* The actions above may have further incremented p->tick.
6400 So set p->update_tick again so that an error in the sentinel will
6401 not cause this code to be run again. */
6402 p
->update_tick
= p
->tick
;
6403 /* Now output the message suitably. */
6404 exec_sentinel (proc
, msg
);
6408 update_mode_lines
= 24; /* In case buffers use %s in mode-line-format. */
6410 return got_some_input
;
6413 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6414 Sinternal_default_process_sentinel
, 2, 2, 0,
6415 doc
: /* Function used as default sentinel for processes.
6416 This inserts a status message into the process's buffer, if there is one. */)
6417 (Lisp_Object proc
, Lisp_Object msg
)
6419 Lisp_Object buffer
, symbol
;
6420 struct Lisp_Process
*p
;
6421 CHECK_PROCESS (proc
);
6422 p
= XPROCESS (proc
);
6426 symbol
= XCAR (symbol
);
6428 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6431 struct buffer
*old
= current_buffer
;
6432 ptrdiff_t opoint
, opoint_byte
;
6433 ptrdiff_t before
, before_byte
;
6435 /* Avoid error if buffer is deleted
6436 (probably that's why the process is dead, too). */
6437 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6439 Fset_buffer (buffer
);
6441 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6442 msg
= (code_convert_string_norecord
6443 (msg
, Vlocale_coding_system
, 1));
6446 opoint_byte
= PT_BYTE
;
6447 /* Insert new output into buffer
6448 at the current end-of-output marker,
6449 thus preserving logical ordering of input and output. */
6450 if (XMARKER (p
->mark
)->buffer
)
6451 Fgoto_char (p
->mark
);
6453 SET_PT_BOTH (ZV
, ZV_BYTE
);
6456 before_byte
= PT_BYTE
;
6458 tem
= BVAR (current_buffer
, read_only
);
6459 bset_read_only (current_buffer
, Qnil
);
6460 insert_string ("\nProcess ");
6461 { /* FIXME: temporary kludge. */
6462 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6463 insert_string (" ");
6465 bset_read_only (current_buffer
, tem
);
6466 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6468 if (opoint
>= before
)
6469 SET_PT_BOTH (opoint
+ (PT
- before
),
6470 opoint_byte
+ (PT_BYTE
- before_byte
));
6472 SET_PT_BOTH (opoint
, opoint_byte
);
6474 set_buffer_internal (old
);
6480 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6481 Sset_process_coding_system
, 1, 3, 0,
6482 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6483 DECODING will be used to decode subprocess output and ENCODING to
6484 encode subprocess input. */)
6485 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6487 register struct Lisp_Process
*p
;
6489 CHECK_PROCESS (process
);
6490 p
= XPROCESS (process
);
6492 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6494 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6495 Fcheck_coding_system (decoding
);
6496 Fcheck_coding_system (encoding
);
6497 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6498 pset_decode_coding_system (p
, decoding
);
6499 pset_encode_coding_system (p
, encoding
);
6500 setup_process_coding_systems (process
);
6505 DEFUN ("process-coding-system",
6506 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6507 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6508 (register Lisp_Object process
)
6510 CHECK_PROCESS (process
);
6511 return Fcons (XPROCESS (process
)->decode_coding_system
,
6512 XPROCESS (process
)->encode_coding_system
);
6515 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6516 Sset_process_filter_multibyte
, 2, 2, 0,
6517 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6518 If FLAG is non-nil, the filter is given multibyte strings.
6519 If FLAG is nil, the filter is given unibyte strings. In this case,
6520 all character code conversion except for end-of-line conversion is
6522 (Lisp_Object process
, Lisp_Object flag
)
6524 register struct Lisp_Process
*p
;
6526 CHECK_PROCESS (process
);
6527 p
= XPROCESS (process
);
6529 pset_decode_coding_system
6530 (p
, raw_text_coding_system (p
->decode_coding_system
));
6531 setup_process_coding_systems (process
);
6536 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6537 Sprocess_filter_multibyte_p
, 1, 1, 0,
6538 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6539 (Lisp_Object process
)
6541 register struct Lisp_Process
*p
;
6542 struct coding_system
*coding
;
6544 CHECK_PROCESS (process
);
6545 p
= XPROCESS (process
);
6546 coding
= proc_decode_coding_system
[p
->infd
];
6547 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6556 add_gpm_wait_descriptor (int desc
)
6558 add_keyboard_wait_descriptor (desc
);
6562 delete_gpm_wait_descriptor (int desc
)
6564 delete_keyboard_wait_descriptor (desc
);
6569 # ifdef USABLE_SIGIO
6571 /* Return true if *MASK has a bit set
6572 that corresponds to one of the keyboard input descriptors. */
6575 keyboard_bit_set (fd_set
*mask
)
6579 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6580 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6581 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6588 #else /* not subprocesses */
6590 /* Defined on msdos.c. */
6591 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
6592 struct timespec
*, void *);
6594 /* Implementation of wait_reading_process_output, assuming that there
6595 are no subprocesses. Used only by the MS-DOS build.
6597 Wait for timeout to elapse and/or keyboard input to be available.
6601 If negative, gobble data immediately available but don't wait for any.
6604 an additional duration to wait, measured in nanoseconds
6605 If TIME_LIMIT is zero, then:
6606 If NSECS == 0, there is no limit.
6607 If NSECS > 0, the timeout consists of NSECS only.
6608 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6611 0 to ignore keyboard input, or
6612 1 to return when input is available, or
6613 -1 means caller will actually read the input, so don't throw to
6616 see full version for other parameters. We know that wait_proc will
6617 always be NULL, since `subprocesses' isn't defined.
6619 DO_DISPLAY means redisplay should be done to show subprocess
6620 output that arrives.
6622 Return positive if we received input from WAIT_PROC (or from any
6623 process if WAIT_PROC is null), zero if we attempted to receive
6624 input but got none, and negative if we didn't even try. */
6627 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6629 Lisp_Object wait_for_cell
,
6630 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6633 struct timespec end_time
, timeout
;
6640 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6641 time_limit
= TYPE_MAXIMUM (time_t);
6643 /* What does time_limit really mean? */
6644 if (time_limit
|| nsecs
> 0)
6646 timeout
= make_timespec (time_limit
, nsecs
);
6647 end_time
= timespec_add (current_timespec (), timeout
);
6650 /* Turn off periodic alarms (in case they are in use)
6651 and then turn off any other atimers,
6652 because the select emulator uses alarms. */
6654 turn_on_atimers (0);
6658 bool timeout_reduced_for_timers
= 0;
6659 fd_set waitchannels
;
6662 /* If calling from keyboard input, do not quit
6663 since we want to return C-g as an input character.
6664 Otherwise, do pending quit if requested. */
6668 /* Exit now if the cell we're waiting for became non-nil. */
6669 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6672 /* Compute time from now till when time limit is up. */
6673 /* Exit if already run out. */
6676 /* A negative timeout means
6677 gobble output available now
6678 but don't wait at all. */
6680 timeout
= make_timespec (0, 0);
6682 else if (time_limit
|| nsecs
> 0)
6684 struct timespec now
= current_timespec ();
6685 if (timespec_cmp (end_time
, now
) <= 0)
6687 timeout
= timespec_sub (end_time
, now
);
6691 timeout
= make_timespec (100000, 0);
6694 /* If our caller will not immediately handle keyboard events,
6695 run timer events directly.
6696 (Callers that will immediately read keyboard events
6697 call timer_delay on their own.) */
6698 if (NILP (wait_for_cell
))
6700 struct timespec timer_delay
;
6704 unsigned old_timers_run
= timers_run
;
6705 timer_delay
= timer_check ();
6706 if (timers_run
!= old_timers_run
&& do_display
)
6707 /* We must retry, since a timer may have requeued itself
6708 and that could alter the time delay. */
6709 redisplay_preserve_echo_area (14);
6713 while (!detect_input_pending ());
6715 /* If there is unread keyboard input, also return. */
6717 && requeued_events_pending_p ())
6720 if (timespec_valid_p (timer_delay
) && nsecs
>= 0)
6722 if (timespec_cmp (timer_delay
, timeout
) < 0)
6724 timeout
= timer_delay
;
6725 timeout_reduced_for_timers
= 1;
6730 /* Cause C-g and alarm signals to take immediate action,
6731 and cause input available signals to zero out timeout. */
6733 set_waiting_for_input (&timeout
);
6735 /* If a frame has been newly mapped and needs updating,
6736 reprocess its display stuff. */
6737 if (frame_garbaged
&& do_display
)
6739 clear_waiting_for_input ();
6740 redisplay_preserve_echo_area (15);
6742 set_waiting_for_input (&timeout
);
6745 /* Wait till there is something to do. */
6746 FD_ZERO (&waitchannels
);
6747 if (read_kbd
&& detect_input_pending ())
6751 if (read_kbd
|| !NILP (wait_for_cell
))
6752 FD_SET (0, &waitchannels
);
6753 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6758 /* Make C-g and alarm signals set flags again */
6759 clear_waiting_for_input ();
6761 /* If we woke up due to SIGWINCH, actually change size now. */
6762 do_pending_window_change (0);
6764 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6765 /* We waited the full specified time, so return now. */
6770 /* If the system call was interrupted, then go around the
6772 if (xerrno
== EINTR
)
6773 FD_ZERO (&waitchannels
);
6775 report_file_errno ("Failed select", Qnil
, xerrno
);
6778 /* Check for keyboard input */
6781 && detect_input_pending_run_timers (do_display
))
6783 swallow_events (do_display
);
6784 if (detect_input_pending_run_timers (do_display
))
6788 /* If there is unread keyboard input, also return. */
6790 && requeued_events_pending_p ())
6793 /* If wait_for_cell. check for keyboard input
6794 but don't run any timers.
6795 ??? (It seems wrong to me to check for keyboard
6796 input at all when wait_for_cell, but the code
6797 has been this way since July 1994.
6798 Try changing this after version 19.31.) */
6799 if (! NILP (wait_for_cell
)
6800 && detect_input_pending ())
6802 swallow_events (do_display
);
6803 if (detect_input_pending ())
6807 /* Exit now if the cell we're waiting for became non-nil. */
6808 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6817 #endif /* not subprocesses */
6819 /* The following functions are needed even if async subprocesses are
6820 not supported. Some of them are no-op stubs in that case. */
6822 /* Add DESC to the set of keyboard input descriptors. */
6825 add_keyboard_wait_descriptor (int desc
)
6827 #ifdef subprocesses /* actually means "not MSDOS" */
6828 FD_SET (desc
, &input_wait_mask
);
6829 FD_SET (desc
, &non_process_wait_mask
);
6830 if (desc
> max_input_desc
)
6831 max_input_desc
= desc
;
6835 /* From now on, do not expect DESC to give keyboard input. */
6838 delete_keyboard_wait_descriptor (int desc
)
6841 FD_CLR (desc
, &input_wait_mask
);
6842 FD_CLR (desc
, &non_process_wait_mask
);
6843 delete_input_desc (desc
);
6847 /* Setup coding systems of PROCESS. */
6850 setup_process_coding_systems (Lisp_Object process
)
6853 struct Lisp_Process
*p
= XPROCESS (process
);
6855 int outch
= p
->outfd
;
6856 Lisp_Object coding_system
;
6858 if (inch
< 0 || outch
< 0)
6861 if (!proc_decode_coding_system
[inch
])
6862 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6863 coding_system
= p
->decode_coding_system
;
6864 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6865 && BUFFERP (p
->buffer
))
6867 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6868 coding_system
= raw_text_coding_system (coding_system
);
6870 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6872 if (!proc_encode_coding_system
[outch
])
6873 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6874 setup_coding_system (p
->encode_coding_system
,
6875 proc_encode_coding_system
[outch
]);
6879 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6880 doc
: /* Return the (or a) process associated with BUFFER.
6881 BUFFER may be a buffer or the name of one. */)
6882 (register Lisp_Object buffer
)
6885 register Lisp_Object buf
, tail
, proc
;
6887 if (NILP (buffer
)) return Qnil
;
6888 buf
= Fget_buffer (buffer
);
6889 if (NILP (buf
)) return Qnil
;
6891 FOR_EACH_PROCESS (tail
, proc
)
6892 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6894 #endif /* subprocesses */
6898 DEFUN ("process-inherit-coding-system-flag",
6899 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
6901 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
6902 If this flag is t, `buffer-file-coding-system' of the buffer
6903 associated with PROCESS will inherit the coding system used to decode
6904 the process output. */)
6905 (register Lisp_Object process
)
6908 CHECK_PROCESS (process
);
6909 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
6911 /* Ignore the argument and return the value of
6912 inherit-process-coding-system. */
6913 return inherit_process_coding_system
? Qt
: Qnil
;
6917 /* Kill all processes associated with `buffer'.
6918 If `buffer' is nil, kill all processes */
6921 kill_buffer_processes (Lisp_Object buffer
)
6924 Lisp_Object tail
, proc
;
6926 FOR_EACH_PROCESS (tail
, proc
)
6927 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
6929 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
6930 Fdelete_process (proc
);
6931 else if (XPROCESS (proc
)->infd
>= 0)
6932 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
6934 #else /* subprocesses */
6935 /* Since we have no subprocesses, this does nothing. */
6936 #endif /* subprocesses */
6939 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
6940 Swaiting_for_user_input_p
, 0, 0, 0,
6941 doc
: /* Return non-nil if Emacs is waiting for input from the user.
6942 This is intended for use by asynchronous process output filters and sentinels. */)
6946 return (waiting_for_user_input_p
? Qt
: Qnil
);
6952 /* Stop reading input from keyboard sources. */
6955 hold_keyboard_input (void)
6960 /* Resume reading input from keyboard sources. */
6963 unhold_keyboard_input (void)
6968 /* Return true if keyboard input is on hold, zero otherwise. */
6971 kbd_on_hold_p (void)
6973 return kbd_is_on_hold
;
6977 /* Enumeration of and access to system processes a-la ps(1). */
6979 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
6981 doc
: /* Return a list of numerical process IDs of all running processes.
6982 If this functionality is unsupported, return nil.
6984 See `process-attributes' for getting attributes of a process given its ID. */)
6987 return list_system_processes ();
6990 DEFUN ("process-attributes", Fprocess_attributes
,
6991 Sprocess_attributes
, 1, 1, 0,
6992 doc
: /* Return attributes of the process given by its PID, a number.
6994 Value is an alist where each element is a cons cell of the form
6998 If this functionality is unsupported, the value is nil.
7000 See `list-system-processes' for getting a list of all process IDs.
7002 The KEYs of the attributes that this function may return are listed
7003 below, together with the type of the associated VALUE (in parentheses).
7004 Not all platforms support all of these attributes; unsupported
7005 attributes will not appear in the returned alist.
7006 Unless explicitly indicated otherwise, numbers can have either
7007 integer or floating point values.
7009 euid -- Effective user User ID of the process (number)
7010 user -- User name corresponding to euid (string)
7011 egid -- Effective user Group ID of the process (number)
7012 group -- Group name corresponding to egid (string)
7013 comm -- Command name (executable name only) (string)
7014 state -- Process state code, such as "S", "R", or "T" (string)
7015 ppid -- Parent process ID (number)
7016 pgrp -- Process group ID (number)
7017 sess -- Session ID, i.e. process ID of session leader (number)
7018 ttname -- Controlling tty name (string)
7019 tpgid -- ID of foreground process group on the process's tty (number)
7020 minflt -- number of minor page faults (number)
7021 majflt -- number of major page faults (number)
7022 cminflt -- cumulative number of minor page faults (number)
7023 cmajflt -- cumulative number of major page faults (number)
7024 utime -- user time used by the process, in (current-time) format,
7025 which is a list of integers (HIGH LOW USEC PSEC)
7026 stime -- system time used by the process (current-time)
7027 time -- sum of utime and stime (current-time)
7028 cutime -- user time used by the process and its children (current-time)
7029 cstime -- system time used by the process and its children (current-time)
7030 ctime -- sum of cutime and cstime (current-time)
7031 pri -- priority of the process (number)
7032 nice -- nice value of the process (number)
7033 thcount -- process thread count (number)
7034 start -- time the process started (current-time)
7035 vsize -- virtual memory size of the process in KB's (number)
7036 rss -- resident set size of the process in KB's (number)
7037 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7038 pcpu -- percents of CPU time used by the process (floating-point number)
7039 pmem -- percents of total physical memory used by process's resident set
7040 (floating-point number)
7041 args -- command line which invoked the process (string). */)
7044 return system_process_attributes (pid
);
7048 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7049 Invoke this after init_process_emacs, and after glib and/or GNUstep
7050 futz with the SIGCHLD handler, but before Emacs forks any children.
7051 This function's caller should block SIGCHLD. */
7054 catch_child_signal (void)
7056 struct sigaction action
, old_action
;
7058 emacs_sigaction_init (&action
, deliver_child_signal
);
7059 block_child_signal (&oldset
);
7060 sigaction (SIGCHLD
, &action
, &old_action
);
7061 eassert (! (old_action
.sa_flags
& SA_SIGINFO
));
7063 if (old_action
.sa_handler
!= deliver_child_signal
)
7065 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7067 : old_action
.sa_handler
);
7068 unblock_child_signal (&oldset
);
7070 #endif /* subprocesses */
7073 /* This is not called "init_process" because that is the name of a
7074 Mach system call, so it would cause problems on Darwin systems. */
7076 init_process_emacs (void)
7081 inhibit_sentinels
= 0;
7084 if (! noninteractive
|| initialized
)
7087 #if defined HAVE_GLIB && !defined WINDOWSNT
7088 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7089 this should always fail, but is enough to initialize glib's
7090 private SIGCHLD handler, allowing catch_child_signal to copy
7091 it into lib_child_handler. */
7092 g_source_unref (g_child_watch_source_new (getpid ()));
7094 catch_child_signal ();
7097 FD_ZERO (&input_wait_mask
);
7098 FD_ZERO (&non_keyboard_wait_mask
);
7099 FD_ZERO (&non_process_wait_mask
);
7100 FD_ZERO (&write_mask
);
7101 max_process_desc
= max_input_desc
= -1;
7102 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7104 #ifdef NON_BLOCKING_CONNECT
7105 FD_ZERO (&connect_wait_mask
);
7106 num_pending_connects
= 0;
7109 #ifdef ADAPTIVE_READ_BUFFERING
7110 process_output_delay_count
= 0;
7111 process_output_skip
= 0;
7114 /* Don't do this, it caused infinite select loops. The display
7115 method should call add_keyboard_wait_descriptor on stdin if it
7118 FD_SET (0, &input_wait_mask
);
7121 Vprocess_alist
= Qnil
;
7122 deleted_pid_list
= Qnil
;
7123 for (i
= 0; i
< FD_SETSIZE
; i
++)
7125 chan_process
[i
] = Qnil
;
7126 proc_buffered_char
[i
] = -1;
7128 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7129 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7130 #ifdef DATAGRAM_SOCKETS
7131 memset (datagram_address
, 0, sizeof datagram_address
);
7135 Lisp_Object subfeatures
= Qnil
;
7136 const struct socket_options
*sopt
;
7138 #define ADD_SUBFEATURE(key, val) \
7139 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7141 #ifdef NON_BLOCKING_CONNECT
7142 ADD_SUBFEATURE (QCnowait
, Qt
);
7144 #ifdef DATAGRAM_SOCKETS
7145 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7147 #ifdef HAVE_SEQPACKET
7148 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7150 #ifdef HAVE_LOCAL_SOCKETS
7151 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7153 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7155 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7157 #ifdef HAVE_GETSOCKNAME
7158 ADD_SUBFEATURE (QCservice
, Qt
);
7160 ADD_SUBFEATURE (QCserver
, Qt
);
7162 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7163 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7165 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7168 #if defined (DARWIN_OS)
7169 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7170 processes. As such, we only change the default value. */
7173 char const *release
= (STRINGP (Voperating_system_release
)
7174 ? SSDATA (Voperating_system_release
)
7176 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7177 Vprocess_connection_type
= Qnil
;
7181 #endif /* subprocesses */
7186 syms_of_process (void)
7188 #include "process.x"
7192 DEFSYM (Qprocessp
, "processp");
7193 DEFSYM (Qrun
, "run");
7194 DEFSYM (Qstop
, "stop");
7195 DEFSYM (Qsignal
, "signal");
7197 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7200 Qexit = intern_c_string ("exit");
7201 staticpro (&Qexit); */
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
;
7324 #endif /* subprocesses */