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 # define accept4(sockfd, addr, addrlen, flags) \
178 process_accept4 (sockfd, addr, addrlen, flags)
180 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
182 return close_on_exec (accept (sockfd
, addr
, addrlen
));
186 process_socket (int domain
, int type
, int protocol
)
188 return close_on_exec (socket (domain
, type
, protocol
));
191 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
194 Lisp_Object Qprocessp
;
195 static Lisp_Object Qrun
, Qstop
, Qsignal
;
196 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
198 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
199 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
201 static Lisp_Object Qipv6
;
203 static Lisp_Object QCport
, QCprocess
;
205 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
206 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
207 static Lisp_Object QCbuffer
, QChost
, QCservice
;
208 static Lisp_Object QClocal
, QCremote
, QCcoding
;
209 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
210 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
211 static Lisp_Object Qlast_nonmenu_event
;
212 static Lisp_Object Qinternal_default_process_sentinel
;
213 static Lisp_Object Qinternal_default_process_filter
;
215 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
216 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
217 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
218 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
220 /* Number of events of change of status of a process. */
221 static EMACS_INT process_tick
;
222 /* Number of events for which the user or sentinel has been notified. */
223 static EMACS_INT update_tick
;
225 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
227 /* Only W32 has this, it really means that select can't take write mask. */
228 #ifdef BROKEN_NON_BLOCKING_CONNECT
229 #undef NON_BLOCKING_CONNECT
230 #define SELECT_CANT_DO_WRITE_MASK
232 #ifndef NON_BLOCKING_CONNECT
234 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
235 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
236 #define NON_BLOCKING_CONNECT
237 #endif /* EWOULDBLOCK || EINPROGRESS */
238 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
239 #endif /* HAVE_SELECT */
240 #endif /* NON_BLOCKING_CONNECT */
241 #endif /* BROKEN_NON_BLOCKING_CONNECT */
243 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
244 this system. We need to read full packets, so we need a
245 "non-destructive" select. So we require either native select,
246 or emulation of select using FIONREAD. */
248 #ifndef BROKEN_DATAGRAM_SOCKETS
249 # if defined HAVE_SELECT || defined USABLE_FIONREAD
250 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
251 # define DATAGRAM_SOCKETS
256 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
257 # define HAVE_SEQPACKET
260 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
261 #define ADAPTIVE_READ_BUFFERING
264 #ifdef ADAPTIVE_READ_BUFFERING
265 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
266 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
267 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
269 /* Number of processes which have a non-zero read_output_delay,
270 and therefore might be delayed for adaptive read buffering. */
272 static int process_output_delay_count
;
274 /* True if any process has non-nil read_output_skip. */
276 static bool process_output_skip
;
279 #define process_output_delay_count 0
282 static void create_process (Lisp_Object
, char **, Lisp_Object
);
284 static bool keyboard_bit_set (fd_set
*);
286 static void deactivate_process (Lisp_Object
);
287 static void status_notify (struct Lisp_Process
*);
288 static int read_process_output (Lisp_Object
, int);
289 static void handle_child_signal (int);
290 static void create_pty (Lisp_Object
);
292 /* If we support a window system, turn on the code to poll periodically
293 to detect C-g. It isn't actually used when doing interrupt input. */
294 #ifdef HAVE_WINDOW_SYSTEM
295 #define POLL_FOR_INPUT
298 static Lisp_Object
get_process (register Lisp_Object name
);
299 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
301 /* Mask of bits indicating the descriptors that we wait for input on. */
303 static fd_set input_wait_mask
;
305 /* Mask that excludes keyboard input descriptor(s). */
307 static fd_set non_keyboard_wait_mask
;
309 /* Mask that excludes process input descriptor(s). */
311 static fd_set non_process_wait_mask
;
313 /* Mask for selecting for write. */
315 static fd_set write_mask
;
317 #ifdef NON_BLOCKING_CONNECT
318 /* Mask of bits indicating the descriptors that we wait for connect to
319 complete on. Once they complete, they are removed from this mask
320 and added to the input_wait_mask and non_keyboard_wait_mask. */
322 static fd_set connect_wait_mask
;
324 /* Number of bits set in connect_wait_mask. */
325 static int num_pending_connects
;
326 #endif /* NON_BLOCKING_CONNECT */
328 /* The largest descriptor currently in use for a process object; -1 if none. */
329 static int max_process_desc
;
331 /* The largest descriptor currently in use for input; -1 if none. */
332 static int max_input_desc
;
334 /* Indexed by descriptor, gives the process (if any) for that descriptor */
335 static Lisp_Object chan_process
[FD_SETSIZE
];
337 /* Alist of elements (NAME . PROCESS) */
338 static Lisp_Object Vprocess_alist
;
340 /* Buffered-ahead input char from process, indexed by channel.
341 -1 means empty (no char is buffered).
342 Used on sys V where the only way to tell if there is any
343 output from the process is to read at least one char.
344 Always -1 on systems that support FIONREAD. */
346 static int proc_buffered_char
[FD_SETSIZE
];
348 /* Table of `struct coding-system' for each process. */
349 static struct coding_system
*proc_decode_coding_system
[FD_SETSIZE
];
350 static struct coding_system
*proc_encode_coding_system
[FD_SETSIZE
];
352 #ifdef DATAGRAM_SOCKETS
353 /* Table of `partner address' for datagram sockets. */
354 static struct sockaddr_and_len
{
357 } datagram_address
[FD_SETSIZE
];
358 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
359 #define DATAGRAM_CONN_P(proc) \
360 (PROCESSP (proc) && \
361 XPROCESS (proc)->infd >= 0 && \
362 datagram_address[XPROCESS (proc)->infd].sa != 0)
364 #define DATAGRAM_CHAN_P(chan) (0)
365 #define DATAGRAM_CONN_P(proc) (0)
368 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
369 a `for' loop which iterates over processes from Vprocess_alist. */
371 #define FOR_EACH_PROCESS(list_var, proc_var) \
372 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
374 /* These setters are used only in this file, so they can be private. */
376 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
381 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
386 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
388 p
->decode_coding_system
= val
;
391 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
393 p
->decoding_buf
= val
;
396 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
398 p
->encode_coding_system
= val
;
401 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
403 p
->encoding_buf
= val
;
406 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
408 p
->filter
= NILP (val
) ? Qinternal_default_process_filter
: val
;
411 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
416 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
421 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
426 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
431 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
433 p
->sentinel
= NILP (val
) ? Qinternal_default_process_sentinel
: val
;
436 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
441 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
446 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
451 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
453 p
->write_queue
= val
;
458 static struct fd_callback_data
464 int condition
; /* mask of the defines above. */
465 } fd_callback_info
[FD_SETSIZE
];
468 /* Add a file descriptor FD to be monitored for when read is possible.
469 When read is possible, call FUNC with argument DATA. */
472 add_read_fd (int fd
, fd_callback func
, void *data
)
474 eassert (fd
< FD_SETSIZE
);
475 add_keyboard_wait_descriptor (fd
);
477 fd_callback_info
[fd
].func
= func
;
478 fd_callback_info
[fd
].data
= data
;
479 fd_callback_info
[fd
].condition
|= FOR_READ
;
482 /* Stop monitoring file descriptor FD for when read is possible. */
485 delete_read_fd (int fd
)
487 eassert (fd
< FD_SETSIZE
);
488 delete_keyboard_wait_descriptor (fd
);
490 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
491 if (fd_callback_info
[fd
].condition
== 0)
493 fd_callback_info
[fd
].func
= 0;
494 fd_callback_info
[fd
].data
= 0;
498 /* Add a file descriptor FD to be monitored for when write is possible.
499 When write is possible, call FUNC with argument DATA. */
502 add_write_fd (int fd
, fd_callback func
, void *data
)
504 eassert (fd
< FD_SETSIZE
);
505 FD_SET (fd
, &write_mask
);
506 if (fd
> max_input_desc
)
509 fd_callback_info
[fd
].func
= func
;
510 fd_callback_info
[fd
].data
= data
;
511 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
514 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
517 delete_input_desc (int fd
)
519 if (fd
== max_input_desc
)
523 while (0 <= fd
&& ! (FD_ISSET (fd
, &input_wait_mask
)
524 || FD_ISSET (fd
, &write_mask
)));
530 /* Stop monitoring file descriptor FD for when write is possible. */
533 delete_write_fd (int fd
)
535 eassert (fd
< FD_SETSIZE
);
536 FD_CLR (fd
, &write_mask
);
537 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
538 if (fd_callback_info
[fd
].condition
== 0)
540 fd_callback_info
[fd
].func
= 0;
541 fd_callback_info
[fd
].data
= 0;
542 delete_input_desc (fd
);
547 /* Compute the Lisp form of the process status, p->status, from
548 the numeric status that was returned by `wait'. */
550 static Lisp_Object
status_convert (int);
553 update_status (struct Lisp_Process
*p
)
555 eassert (p
->raw_status_new
);
556 pset_status (p
, status_convert (p
->raw_status
));
557 p
->raw_status_new
= 0;
560 /* Convert a process status word in Unix format to
561 the list that we use internally. */
564 status_convert (int w
)
567 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
568 else if (WIFEXITED (w
))
569 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
570 WCOREDUMP (w
) ? Qt
: Qnil
));
571 else if (WIFSIGNALED (w
))
572 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
573 WCOREDUMP (w
) ? Qt
: Qnil
));
578 /* Given a status-list, extract the three pieces of information
579 and store them individually through the three pointers. */
582 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, bool *coredump
)
596 *code
= XFASTINT (XCAR (tem
));
598 *coredump
= !NILP (tem
);
602 /* Return a string describing a process status list. */
605 status_message (struct Lisp_Process
*p
)
607 Lisp_Object status
= p
->status
;
611 Lisp_Object string
, string2
;
613 decode_status (status
, &symbol
, &code
, &coredump
);
615 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
618 synchronize_system_messages_locale ();
619 signame
= strsignal (code
);
621 string
= build_string ("unknown");
626 string
= build_unibyte_string (signame
);
627 if (! NILP (Vlocale_coding_system
))
628 string
= (code_convert_string_norecord
629 (string
, Vlocale_coding_system
, 0));
630 c1
= STRING_CHAR (SDATA (string
));
633 Faset (string
, make_number (0), make_number (c2
));
635 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
636 return concat2 (string
, string2
);
638 else if (EQ (symbol
, Qexit
))
641 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
643 return build_string ("finished\n");
644 string
= Fnumber_to_string (make_number (code
));
645 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
646 return concat3 (build_string ("exited abnormally with code "),
649 else if (EQ (symbol
, Qfailed
))
651 string
= Fnumber_to_string (make_number (code
));
652 string2
= build_string ("\n");
653 return concat3 (build_string ("failed with code "),
657 return Fcopy_sequence (Fsymbol_name (symbol
));
660 enum { PTY_NAME_SIZE
= 24 };
662 /* Open an available pty, returning a file descriptor.
663 Store into PTY_NAME the file name of the terminal corresponding to the pty.
664 Return -1 on failure. */
667 allocate_pty (char pty_name
[PTY_NAME_SIZE
])
676 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
677 for (i
= 0; i
< 16; i
++)
680 #ifdef PTY_NAME_SPRINTF
683 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
684 #endif /* no PTY_NAME_SPRINTF */
688 #else /* no PTY_OPEN */
689 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
690 #endif /* no PTY_OPEN */
695 /* Set FD's close-on-exec flag. This is needed even if
696 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
697 doesn't require support for that combination.
698 Multithreaded platforms where posix_openpt ignores
699 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
700 have a race condition between the PTY_OPEN and here. */
701 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
703 /* check to make certain that both sides are available
704 this avoids a nasty yet stupid bug in rlogins */
705 #ifdef PTY_TTY_NAME_SPRINTF
708 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
709 #endif /* no PTY_TTY_NAME_SPRINTF */
710 if (faccessat (AT_FDCWD
, pty_name
, R_OK
| W_OK
, AT_EACCESS
) != 0)
723 #endif /* HAVE_PTYS */
728 make_process (Lisp_Object name
)
730 register Lisp_Object val
, tem
, name1
;
731 register struct Lisp_Process
*p
;
732 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
735 p
= allocate_process ();
736 /* Initialize Lisp data. Note that allocate_process initializes all
737 Lisp data to nil, so do it only for slots which should not be nil. */
738 pset_status (p
, Qrun
);
739 pset_mark (p
, Fmake_marker ());
741 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
742 non-Lisp data, so do it only for slots which should not be zero. */
745 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
749 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
752 /* If name is already in use, modify it until it is unused. */
757 tem
= Fget_process (name1
);
758 if (NILP (tem
)) break;
759 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
763 pset_sentinel (p
, Qinternal_default_process_sentinel
);
764 pset_filter (p
, Qinternal_default_process_filter
);
765 XSETPROCESS (val
, p
);
766 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
771 remove_process (register Lisp_Object proc
)
773 register Lisp_Object pair
;
775 pair
= Frassq (proc
, Vprocess_alist
);
776 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
778 deactivate_process (proc
);
782 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
783 doc
: /* Return t if OBJECT is a process. */)
786 return PROCESSP (object
) ? Qt
: Qnil
;
789 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
790 doc
: /* Return the process named NAME, or nil if there is none. */)
791 (register Lisp_Object name
)
796 return Fcdr (Fassoc (name
, Vprocess_alist
));
799 /* This is how commands for the user decode process arguments. It
800 accepts a process, a process name, a buffer, a buffer name, or nil.
801 Buffers denote the first process in the buffer, and nil denotes the
805 get_process (register Lisp_Object name
)
807 register Lisp_Object proc
, obj
;
810 obj
= Fget_process (name
);
812 obj
= Fget_buffer (name
);
814 error ("Process %s does not exist", SDATA (name
));
816 else if (NILP (name
))
817 obj
= Fcurrent_buffer ();
821 /* Now obj should be either a buffer object or a process object. */
824 if (NILP (BVAR (XBUFFER (obj
), name
)))
825 error ("Attempt to get process for a dead buffer");
826 proc
= Fget_buffer_process (obj
);
828 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
839 /* Fdelete_process promises to immediately forget about the process, but in
840 reality, Emacs needs to remember those processes until they have been
841 treated by the SIGCHLD handler and waitpid has been invoked on them;
842 otherwise they might fill up the kernel's process table.
844 Some processes created by call-process are also put onto this list.
846 Members of this list are (process-ID . filename) pairs. The
847 process-ID is a number; the filename, if a string, is a file that
848 needs to be removed after the process exits. */
849 static Lisp_Object deleted_pid_list
;
852 record_deleted_pid (pid_t pid
, Lisp_Object filename
)
854 deleted_pid_list
= Fcons (Fcons (make_fixnum_or_float (pid
), filename
),
855 /* GC treated elements set to nil. */
856 Fdelq (Qnil
, deleted_pid_list
));
860 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
861 doc
: /* Delete PROCESS: kill it and forget about it immediately.
862 PROCESS may be a process, a buffer, the name of a process or buffer, or
863 nil, indicating the current buffer's process. */)
864 (register Lisp_Object process
)
866 register struct Lisp_Process
*p
;
868 process
= get_process (process
);
869 p
= XPROCESS (process
);
871 p
->raw_status_new
= 0;
872 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
874 pset_status (p
, list2 (Qexit
, make_number (0)));
875 p
->tick
= ++process_tick
;
877 redisplay_preserve_echo_area (13);
882 record_kill_process (p
, Qnil
);
886 /* Update P's status, since record_kill_process will make the
887 SIGCHLD handler update deleted_pid_list, not *P. */
889 if (p
->raw_status_new
)
891 symbol
= CONSP (p
->status
) ? XCAR (p
->status
) : p
->status
;
892 if (! (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)))
893 pset_status (p
, list2 (Qsignal
, make_number (SIGKILL
)));
895 p
->tick
= ++process_tick
;
897 redisplay_preserve_echo_area (13);
900 remove_process (process
);
904 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
905 doc
: /* Return the status of PROCESS.
906 The returned value is one of the following symbols:
907 run -- for a process that is running.
908 stop -- for a process stopped but continuable.
909 exit -- for a process that has exited.
910 signal -- for a process that has got a fatal signal.
911 open -- for a network stream connection that is open.
912 listen -- for a network stream server that is listening.
913 closed -- for a network stream connection that is closed.
914 connect -- when waiting for a non-blocking connection to complete.
915 failed -- when a non-blocking connection has failed.
916 nil -- if arg is a process name and no such process exists.
917 PROCESS may be a process, a buffer, the name of a process, or
918 nil, indicating the current buffer's process. */)
919 (register Lisp_Object process
)
921 register struct Lisp_Process
*p
;
922 register Lisp_Object status
;
924 if (STRINGP (process
))
925 process
= Fget_process (process
);
927 process
= get_process (process
);
932 p
= XPROCESS (process
);
933 if (p
->raw_status_new
)
937 status
= XCAR (status
);
938 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
940 if (EQ (status
, Qexit
))
942 else if (EQ (p
->command
, Qt
))
944 else if (EQ (status
, Qrun
))
950 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
952 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
953 If PROCESS has not yet exited or died, return 0. */)
954 (register Lisp_Object process
)
956 CHECK_PROCESS (process
);
957 if (XPROCESS (process
)->raw_status_new
)
958 update_status (XPROCESS (process
));
959 if (CONSP (XPROCESS (process
)->status
))
960 return XCAR (XCDR (XPROCESS (process
)->status
));
961 return make_number (0);
964 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
965 doc
: /* Return the process id of PROCESS.
966 This is the pid of the external process which PROCESS uses or talks to.
967 For a network connection, this value is nil. */)
968 (register Lisp_Object process
)
972 CHECK_PROCESS (process
);
973 pid
= XPROCESS (process
)->pid
;
974 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
977 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
978 doc
: /* Return the name of PROCESS, as a string.
979 This is the name of the program invoked in PROCESS,
980 possibly modified to make it unique among process names. */)
981 (register Lisp_Object process
)
983 CHECK_PROCESS (process
);
984 return XPROCESS (process
)->name
;
987 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
988 doc
: /* Return the command that was executed to start PROCESS.
989 This is a list of strings, the first string being the program executed
990 and the rest of the strings being the arguments given to it.
991 For a network or serial process, this is nil (process is running) or t
992 \(process is stopped). */)
993 (register Lisp_Object process
)
995 CHECK_PROCESS (process
);
996 return XPROCESS (process
)->command
;
999 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
1000 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
1001 This is the terminal that the process itself reads and writes on,
1002 not the name of the pty that Emacs uses to talk with that terminal. */)
1003 (register Lisp_Object process
)
1005 CHECK_PROCESS (process
);
1006 return XPROCESS (process
)->tty_name
;
1009 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
1011 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1013 (register Lisp_Object process
, Lisp_Object buffer
)
1015 struct Lisp_Process
*p
;
1017 CHECK_PROCESS (process
);
1019 CHECK_BUFFER (buffer
);
1020 p
= XPROCESS (process
);
1021 pset_buffer (p
, buffer
);
1022 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1023 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
1024 setup_process_coding_systems (process
);
1028 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
1030 doc
: /* Return the buffer PROCESS is associated with.
1031 The default process filter inserts output from PROCESS into this buffer. */)
1032 (register Lisp_Object process
)
1034 CHECK_PROCESS (process
);
1035 return XPROCESS (process
)->buffer
;
1038 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
1040 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1041 (register Lisp_Object process
)
1043 CHECK_PROCESS (process
);
1044 return XPROCESS (process
)->mark
;
1047 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1049 doc
: /* Give PROCESS the filter function FILTER; nil means default.
1050 A value of t means stop accepting output from the process.
1052 When a process has a non-default filter, its buffer is not used for output.
1053 Instead, each time it does output, the entire string of output is
1054 passed to the filter.
1056 The filter gets two arguments: the process and the string of output.
1057 The string argument is normally a multibyte string, except:
1058 - if the process's input coding system is no-conversion or raw-text,
1059 it is a unibyte string (the non-converted input), or else
1060 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1061 string (the result of converting the decoded input multibyte
1062 string to unibyte with `string-make-unibyte'). */)
1063 (register Lisp_Object process
, Lisp_Object filter
)
1065 struct Lisp_Process
*p
;
1067 CHECK_PROCESS (process
);
1068 p
= XPROCESS (process
);
1070 /* Don't signal an error if the process's input file descriptor
1071 is closed. This could make debugging Lisp more difficult,
1072 for example when doing something like
1074 (setq process (start-process ...))
1076 (set-process-filter process ...) */
1079 filter
= Qinternal_default_process_filter
;
1083 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1085 FD_CLR (p
->infd
, &input_wait_mask
);
1086 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1088 else if (EQ (p
->filter
, Qt
)
1089 /* Network or serial process not stopped: */
1090 && !EQ (p
->command
, Qt
))
1092 FD_SET (p
->infd
, &input_wait_mask
);
1093 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1097 pset_filter (p
, filter
);
1098 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1099 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1100 setup_process_coding_systems (process
);
1104 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1106 doc
: /* Return the filter function of PROCESS.
1107 See `set-process-filter' for more info on filter functions. */)
1108 (register Lisp_Object process
)
1110 CHECK_PROCESS (process
);
1111 return XPROCESS (process
)->filter
;
1114 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1116 doc
: /* Give PROCESS the sentinel SENTINEL; nil for default.
1117 The sentinel is called as a function when the process changes state.
1118 It gets two arguments: the process, and a string describing the change. */)
1119 (register Lisp_Object process
, Lisp_Object sentinel
)
1121 struct Lisp_Process
*p
;
1123 CHECK_PROCESS (process
);
1124 p
= XPROCESS (process
);
1126 if (NILP (sentinel
))
1127 sentinel
= Qinternal_default_process_sentinel
;
1129 pset_sentinel (p
, sentinel
);
1130 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1131 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1135 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1137 doc
: /* Return the sentinel of PROCESS.
1138 See `set-process-sentinel' for more info on sentinels. */)
1139 (register Lisp_Object process
)
1141 CHECK_PROCESS (process
);
1142 return XPROCESS (process
)->sentinel
;
1145 DEFUN ("set-process-window-size", Fset_process_window_size
,
1146 Sset_process_window_size
, 3, 3, 0,
1147 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1148 (Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1150 CHECK_PROCESS (process
);
1152 /* All known platforms store window sizes as 'unsigned short'. */
1153 CHECK_RANGED_INTEGER (height
, 0, USHRT_MAX
);
1154 CHECK_RANGED_INTEGER (width
, 0, USHRT_MAX
);
1156 if (XPROCESS (process
)->infd
< 0
1157 || (set_window_size (XPROCESS (process
)->infd
,
1158 XINT (height
), XINT (width
))
1165 DEFUN ("set-process-inherit-coding-system-flag",
1166 Fset_process_inherit_coding_system_flag
,
1167 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1168 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1169 If the second argument FLAG is non-nil, then the variable
1170 `buffer-file-coding-system' of the buffer associated with PROCESS
1171 will be bound to the value of the coding system used to decode
1174 This is useful when the coding system specified for the process buffer
1175 leaves either the character code conversion or the end-of-line conversion
1176 unspecified, or if the coding system used to decode the process output
1177 is more appropriate for saving the process buffer.
1179 Binding the variable `inherit-process-coding-system' to non-nil before
1180 starting the process is an alternative way of setting the inherit flag
1181 for the process which will run.
1183 This function returns FLAG. */)
1184 (register Lisp_Object process
, Lisp_Object flag
)
1186 CHECK_PROCESS (process
);
1187 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1191 DEFUN ("set-process-query-on-exit-flag",
1192 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1194 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1195 If the second argument FLAG is non-nil, Emacs will query the user before
1196 exiting or killing a buffer if PROCESS is running. This function
1198 (register Lisp_Object process
, Lisp_Object flag
)
1200 CHECK_PROCESS (process
);
1201 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1205 DEFUN ("process-query-on-exit-flag",
1206 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1208 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1209 (register Lisp_Object process
)
1211 CHECK_PROCESS (process
);
1212 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1215 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1217 doc
: /* Return the contact info of PROCESS; t for a real child.
1218 For a network or serial connection, the value depends on the optional
1219 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1220 SERVICE) for a network connection or (PORT SPEED) for a serial
1221 connection. If KEY is t, the complete contact information for the
1222 connection is returned, else the specific value for the keyword KEY is
1223 returned. See `make-network-process' or `make-serial-process' for a
1224 list of keywords. */)
1225 (register Lisp_Object process
, Lisp_Object key
)
1227 Lisp_Object contact
;
1229 CHECK_PROCESS (process
);
1230 contact
= XPROCESS (process
)->childp
;
1232 #ifdef DATAGRAM_SOCKETS
1233 if (DATAGRAM_CONN_P (process
)
1234 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1235 contact
= Fplist_put (contact
, QCremote
,
1236 Fprocess_datagram_address (process
));
1239 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1241 if (NILP (key
) && NETCONN_P (process
))
1242 return list2 (Fplist_get (contact
, QChost
),
1243 Fplist_get (contact
, QCservice
));
1244 if (NILP (key
) && SERIALCONN_P (process
))
1245 return list2 (Fplist_get (contact
, QCport
),
1246 Fplist_get (contact
, QCspeed
));
1247 return Fplist_get (contact
, key
);
1250 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1252 doc
: /* Return the plist of PROCESS. */)
1253 (register Lisp_Object process
)
1255 CHECK_PROCESS (process
);
1256 return XPROCESS (process
)->plist
;
1259 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1261 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1262 (register Lisp_Object process
, Lisp_Object plist
)
1264 CHECK_PROCESS (process
);
1267 pset_plist (XPROCESS (process
), plist
);
1271 #if 0 /* Turned off because we don't currently record this info
1272 in the process. Perhaps add it. */
1273 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1274 doc
: /* Return the connection type of PROCESS.
1275 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1276 a socket connection. */)
1277 (Lisp_Object process
)
1279 return XPROCESS (process
)->type
;
1283 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1284 doc
: /* Return the connection type of PROCESS.
1285 The value is either the symbol `real', `network', or `serial'.
1286 PROCESS may be a process, a buffer, the name of a process or buffer, or
1287 nil, indicating the current buffer's process. */)
1288 (Lisp_Object process
)
1291 proc
= get_process (process
);
1292 return XPROCESS (proc
)->type
;
1295 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1297 doc
: /* Convert network ADDRESS from internal format to a string.
1298 A 4 or 5 element vector represents an IPv4 address (with port number).
1299 An 8 or 9 element vector represents an IPv6 address (with port number).
1300 If optional second argument OMIT-PORT is non-nil, don't include a port
1301 number in the string, even when present in ADDRESS.
1302 Returns nil if format of ADDRESS is invalid. */)
1303 (Lisp_Object address
, Lisp_Object omit_port
)
1308 if (STRINGP (address
)) /* AF_LOCAL */
1311 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1313 register struct Lisp_Vector
*p
= XVECTOR (address
);
1314 ptrdiff_t size
= p
->header
.size
;
1315 Lisp_Object args
[10];
1318 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1320 args
[0] = build_string ("%d.%d.%d.%d");
1325 args
[0] = build_string ("%d.%d.%d.%d:%d");
1328 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1330 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1335 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1341 for (i
= 0; i
< nargs
; i
++)
1343 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1346 if (nargs
<= 5 /* IPv4 */
1347 && i
< 4 /* host, not port */
1348 && XINT (p
->contents
[i
]) > 255)
1351 args
[i
+1] = p
->contents
[i
];
1354 return Fformat (nargs
+1, args
);
1357 if (CONSP (address
))
1359 Lisp_Object args
[2];
1360 args
[0] = build_string ("<Family %d>");
1361 args
[1] = Fcar (address
);
1362 return Fformat (2, args
);
1368 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1369 doc
: /* Return a list of all processes that are Emacs sub-processes. */)
1372 return Fmapcar (Qcdr
, Vprocess_alist
);
1375 /* Starting asynchronous inferior processes. */
1377 static void start_process_unwind (Lisp_Object proc
);
1379 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1380 doc
: /* Start a program in a subprocess. Return the process object for it.
1381 NAME is name for process. It is modified if necessary to make it unique.
1382 BUFFER is the buffer (or buffer name) to associate with the process.
1384 Process output (both standard output and standard error streams) goes
1385 at end of BUFFER, unless you specify an output stream or filter
1386 function to handle the output. BUFFER may also be nil, meaning that
1387 this process is not associated with any buffer.
1389 PROGRAM is the program file name. It is searched for in `exec-path'
1390 (which see). If nil, just associate a pty with the buffer. Remaining
1391 arguments are strings to give program as arguments.
1393 If you want to separate standard output from standard error, invoke
1394 the command through a shell and redirect one of them using the shell
1397 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1398 (ptrdiff_t nargs
, Lisp_Object
*args
)
1400 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1401 register unsigned char **new_argv
;
1403 ptrdiff_t count
= SPECPDL_INDEX ();
1407 buffer
= Fget_buffer_create (buffer
);
1409 /* Make sure that the child will be able to chdir to the current
1410 buffer's current directory, or its unhandled equivalent. We
1411 can't just have the child check for an error when it does the
1412 chdir, since it's in a vfork.
1414 We have to GCPRO around this because Fexpand_file_name and
1415 Funhandled_file_name_directory might call a file name handling
1416 function. The argument list is protected by the caller, so all
1417 we really have to worry about is buffer. */
1419 struct gcpro gcpro1
;
1421 current_dir
= encode_current_directory ();
1426 CHECK_STRING (name
);
1430 if (!NILP (program
))
1431 CHECK_STRING (program
);
1433 proc
= make_process (name
);
1434 /* If an error occurs and we can't start the process, we want to
1435 remove it from the process list. This means that each error
1436 check in create_process doesn't need to call remove_process
1437 itself; it's all taken care of here. */
1438 record_unwind_protect (start_process_unwind
, proc
);
1440 pset_childp (XPROCESS (proc
), Qt
);
1441 pset_plist (XPROCESS (proc
), Qnil
);
1442 pset_type (XPROCESS (proc
), Qreal
);
1443 pset_buffer (XPROCESS (proc
), buffer
);
1444 pset_sentinel (XPROCESS (proc
), Qinternal_default_process_sentinel
);
1445 pset_filter (XPROCESS (proc
), Qinternal_default_process_filter
);
1446 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1449 /* AKA GNUTLS_INITSTAGE(proc). */
1450 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1451 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1454 #ifdef ADAPTIVE_READ_BUFFERING
1455 XPROCESS (proc
)->adaptive_read_buffering
1456 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1457 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1460 /* Make the process marker point into the process buffer (if any). */
1461 if (BUFFERP (buffer
))
1462 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1463 BUF_ZV (XBUFFER (buffer
)),
1464 BUF_ZV_BYTE (XBUFFER (buffer
)));
1467 /* Decide coding systems for communicating with the process. Here
1468 we don't setup the structure coding_system nor pay attention to
1469 unibyte mode. They are done in create_process. */
1471 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1472 Lisp_Object coding_systems
= Qt
;
1473 Lisp_Object val
, *args2
;
1474 struct gcpro gcpro1
, gcpro2
;
1476 val
= Vcoding_system_for_read
;
1479 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1480 args2
[0] = Qstart_process
;
1481 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1482 GCPRO2 (proc
, current_dir
);
1483 if (!NILP (program
))
1484 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1486 if (CONSP (coding_systems
))
1487 val
= XCAR (coding_systems
);
1488 else if (CONSP (Vdefault_process_coding_system
))
1489 val
= XCAR (Vdefault_process_coding_system
);
1491 pset_decode_coding_system (XPROCESS (proc
), val
);
1493 val
= Vcoding_system_for_write
;
1496 if (EQ (coding_systems
, Qt
))
1498 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1499 args2
[0] = Qstart_process
;
1500 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1501 GCPRO2 (proc
, current_dir
);
1502 if (!NILP (program
))
1503 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1506 if (CONSP (coding_systems
))
1507 val
= XCDR (coding_systems
);
1508 else if (CONSP (Vdefault_process_coding_system
))
1509 val
= XCDR (Vdefault_process_coding_system
);
1511 pset_encode_coding_system (XPROCESS (proc
), val
);
1512 /* Note: At this moment, the above coding system may leave
1513 text-conversion or eol-conversion unspecified. They will be
1514 decided after we read output from the process and decode it by
1515 some coding system, or just before we actually send a text to
1520 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1521 XPROCESS (proc
)->decoding_carryover
= 0;
1522 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1524 XPROCESS (proc
)->inherit_coding_system_flag
1525 = !(NILP (buffer
) || !inherit_process_coding_system
);
1527 if (!NILP (program
))
1529 /* If program file name is not absolute, search our path for it.
1530 Put the name we will really use in TEM. */
1531 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1532 && !(SCHARS (program
) > 1
1533 && IS_DEVICE_SEP (SREF (program
, 1))))
1535 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1538 GCPRO4 (name
, program
, buffer
, current_dir
);
1539 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
,
1540 make_number (X_OK
), false);
1543 report_file_error ("Searching for program", program
);
1544 tem
= Fexpand_file_name (tem
, Qnil
);
1548 if (!NILP (Ffile_directory_p (program
)))
1549 error ("Specified program for new process is a directory");
1553 /* If program file name starts with /: for quoting a magic name,
1555 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1556 && SREF (tem
, 1) == ':')
1557 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1560 Lisp_Object arg_encoding
= Qnil
;
1561 struct gcpro gcpro1
;
1564 /* Encode the file name and put it in NEW_ARGV.
1565 That's where the child will use it to execute the program. */
1566 tem
= list1 (ENCODE_FILE (tem
));
1568 /* Here we encode arguments by the coding system used for sending
1569 data to the process. We don't support using different coding
1570 systems for encoding arguments and for encoding data sent to the
1573 for (i
= 3; i
< nargs
; i
++)
1575 tem
= Fcons (args
[i
], tem
);
1576 CHECK_STRING (XCAR (tem
));
1577 if (STRING_MULTIBYTE (XCAR (tem
)))
1579 if (NILP (arg_encoding
))
1580 arg_encoding
= (complement_process_encoding_system
1581 (XPROCESS (proc
)->encode_coding_system
));
1583 code_convert_string_norecord
1584 (XCAR (tem
), arg_encoding
, 1));
1591 /* Now that everything is encoded we can collect the strings into
1593 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1594 new_argv
[nargs
- 2] = 0;
1596 for (i
= nargs
- 2; i
-- != 0; )
1598 new_argv
[i
] = SDATA (XCAR (tem
));
1602 create_process (proc
, (char **) new_argv
, current_dir
);
1607 return unbind_to (count
, proc
);
1610 /* This function is the unwind_protect form for Fstart_process. If
1611 PROC doesn't have its pid set, then we know someone has signaled
1612 an error and the process wasn't started successfully, so we should
1613 remove it from the process list. */
1615 start_process_unwind (Lisp_Object proc
)
1617 if (!PROCESSP (proc
))
1620 /* Was PROC started successfully?
1621 -2 is used for a pty with no process, eg for gdb. */
1622 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1623 remove_process (proc
);
1626 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1629 close_process_fd (int *fd_addr
)
1639 /* Indexes of file descriptors in open_fds. */
1642 /* The pipe from Emacs to its subprocess. */
1644 WRITE_TO_SUBPROCESS
,
1646 /* The main pipe from the subprocess to Emacs. */
1647 READ_FROM_SUBPROCESS
,
1650 /* The pipe from the subprocess to Emacs that is closed when the
1651 subprocess execs. */
1652 READ_FROM_EXEC_MONITOR
,
1656 verify (PROCESS_OPEN_FDS
== EXEC_MONITOR_OUTPUT
+ 1);
1659 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1661 struct Lisp_Process
*p
= XPROCESS (process
);
1662 int inchannel
, outchannel
;
1665 int forkin
, forkout
;
1667 char pty_name
[PTY_NAME_SIZE
];
1668 Lisp_Object lisp_pty_name
= Qnil
;
1670 inchannel
= outchannel
= -1;
1672 if (!NILP (Vprocess_connection_type
))
1673 outchannel
= inchannel
= allocate_pty (pty_name
);
1677 p
->open_fd
[READ_FROM_SUBPROCESS
] = inchannel
;
1678 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1679 /* On most USG systems it does not work to open the pty's tty here,
1680 then close it and reopen it in the child. */
1681 /* Don't let this terminal become our controlling terminal
1682 (in case we don't have one). */
1683 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1685 report_file_error ("Opening pty", Qnil
);
1686 p
->open_fd
[SUBPROCESS_STDIN
] = forkin
;
1688 forkin
= forkout
= -1;
1689 #endif /* not USG, or USG_SUBTTY_WORKS */
1691 lisp_pty_name
= build_string (pty_name
);
1695 if (emacs_pipe (p
->open_fd
+ SUBPROCESS_STDIN
) != 0
1696 || emacs_pipe (p
->open_fd
+ READ_FROM_SUBPROCESS
) != 0)
1697 report_file_error ("Creating pipe", Qnil
);
1698 forkin
= p
->open_fd
[SUBPROCESS_STDIN
];
1699 outchannel
= p
->open_fd
[WRITE_TO_SUBPROCESS
];
1700 inchannel
= p
->open_fd
[READ_FROM_SUBPROCESS
];
1701 forkout
= p
->open_fd
[SUBPROCESS_STDOUT
];
1705 if (emacs_pipe (p
->open_fd
+ READ_FROM_EXEC_MONITOR
) != 0)
1706 report_file_error ("Creating pipe", Qnil
);
1709 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1710 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1712 /* Record this as an active process, with its channels. */
1713 chan_process
[inchannel
] = process
;
1714 p
->infd
= inchannel
;
1715 p
->outfd
= outchannel
;
1717 /* Previously we recorded the tty descriptor used in the subprocess.
1718 It was only used for getting the foreground tty process, so now
1719 we just reopen the device (see emacs_get_tty_pgrp) as this is
1720 more portable (see USG_SUBTTY_WORKS above). */
1722 p
->pty_flag
= pty_flag
;
1723 pset_status (p
, Qrun
);
1725 FD_SET (inchannel
, &input_wait_mask
);
1726 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1727 if (inchannel
> max_process_desc
)
1728 max_process_desc
= inchannel
;
1730 /* This may signal an error. */
1731 setup_process_coding_systems (process
);
1734 block_child_signal ();
1737 /* vfork, and prevent local vars from being clobbered by the vfork. */
1739 Lisp_Object
volatile current_dir_volatile
= current_dir
;
1740 Lisp_Object
volatile lisp_pty_name_volatile
= lisp_pty_name
;
1741 char **volatile new_argv_volatile
= new_argv
;
1742 int volatile forkin_volatile
= forkin
;
1743 int volatile forkout_volatile
= forkout
;
1744 struct Lisp_Process
*p_volatile
= p
;
1748 current_dir
= current_dir_volatile
;
1749 lisp_pty_name
= lisp_pty_name_volatile
;
1750 new_argv
= new_argv_volatile
;
1751 forkin
= forkin_volatile
;
1752 forkout
= forkout_volatile
;
1755 pty_flag
= p
->pty_flag
;
1759 #endif /* not WINDOWSNT */
1761 int xforkin
= forkin
;
1762 int xforkout
= forkout
;
1764 /* Make the pty be the controlling terminal of the process. */
1766 /* First, disconnect its current controlling terminal. */
1767 /* We tried doing setsid only if pty_flag, but it caused
1768 process_set_signal to fail on SGI when using a pipe. */
1770 /* Make the pty's terminal the controlling terminal. */
1771 if (pty_flag
&& xforkin
>= 0)
1774 /* We ignore the return value
1775 because faith@cs.unc.edu says that is necessary on Linux. */
1776 ioctl (xforkin
, TIOCSCTTY
, 0);
1779 #if defined (LDISC1)
1780 if (pty_flag
&& xforkin
>= 0)
1783 tcgetattr (xforkin
, &t
);
1785 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1786 emacs_perror ("create_process/tcsetattr LDISC1");
1789 #if defined (NTTYDISC) && defined (TIOCSETD)
1790 if (pty_flag
&& xforkin
>= 0)
1792 /* Use new line discipline. */
1793 int ldisc
= NTTYDISC
;
1794 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1799 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1800 can do TIOCSPGRP only to the process's controlling tty. */
1803 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1804 I can't test it since I don't have 4.3. */
1805 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1808 ioctl (j
, TIOCNOTTY
, 0);
1812 #endif /* TIOCNOTTY */
1814 #if !defined (DONT_REOPEN_PTY)
1815 /*** There is a suggestion that this ought to be a
1816 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1817 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1818 that system does seem to need this code, even though
1819 both TIOCSCTTY is defined. */
1820 /* Now close the pty (if we had it open) and reopen it.
1821 This makes the pty the controlling terminal of the subprocess. */
1825 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1828 emacs_close (xforkin
);
1829 xforkout
= xforkin
= emacs_open (SSDATA (lisp_pty_name
), O_RDWR
, 0);
1833 emacs_perror (SSDATA (lisp_pty_name
));
1834 _exit (EXIT_CANCELED
);
1838 #endif /* not DONT_REOPEN_PTY */
1840 #ifdef SETUP_SLAVE_PTY
1845 #endif /* SETUP_SLAVE_PTY */
1846 #endif /* HAVE_PTYS */
1848 signal (SIGINT
, SIG_DFL
);
1849 signal (SIGQUIT
, SIG_DFL
);
1851 signal (SIGPROF
, SIG_DFL
);
1854 /* Emacs ignores SIGPIPE, but the child should not. */
1855 signal (SIGPIPE
, SIG_DFL
);
1857 /* Stop blocking SIGCHLD in the child. */
1858 unblock_child_signal ();
1861 child_setup_tty (xforkout
);
1863 pid
= child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1864 #else /* not WINDOWSNT */
1865 child_setup (xforkin
, xforkout
, xforkout
, new_argv
, 1, current_dir
);
1866 #endif /* not WINDOWSNT */
1869 /* Back in the parent process. */
1871 vfork_errno
= errno
;
1876 /* Stop blocking in the parent. */
1877 unblock_child_signal ();
1881 report_file_errno ("Doing vfork", Qnil
, vfork_errno
);
1884 /* vfork succeeded. */
1886 /* Close the pipe ends that the child uses, or the child's pty. */
1887 close_process_fd (&p
->open_fd
[SUBPROCESS_STDIN
]);
1888 close_process_fd (&p
->open_fd
[SUBPROCESS_STDOUT
]);
1891 register_child (pid
, inchannel
);
1892 #endif /* WINDOWSNT */
1894 pset_tty_name (p
, lisp_pty_name
);
1897 /* Wait for child_setup to complete in case that vfork is
1898 actually defined as fork. The descriptor
1899 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1900 of a pipe is closed at the child side either by close-on-exec
1901 on successful execve or the _exit call in child_setup. */
1905 close_process_fd (&p
->open_fd
[EXEC_MONITOR_OUTPUT
]);
1906 emacs_read (p
->open_fd
[READ_FROM_EXEC_MONITOR
], &dummy
, 1);
1907 close_process_fd (&p
->open_fd
[READ_FROM_EXEC_MONITOR
]);
1914 create_pty (Lisp_Object process
)
1916 struct Lisp_Process
*p
= XPROCESS (process
);
1917 char pty_name
[PTY_NAME_SIZE
];
1918 int pty_fd
= NILP (Vprocess_connection_type
) ? -1 : allocate_pty (pty_name
);
1922 p
->open_fd
[SUBPROCESS_STDIN
] = pty_fd
;
1923 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1924 /* On most USG systems it does not work to open the pty's tty here,
1925 then close it and reopen it in the child. */
1926 /* Don't let this terminal become our controlling terminal
1927 (in case we don't have one). */
1928 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1930 report_file_error ("Opening pty", Qnil
);
1931 p
->open_fd
[WRITE_TO_SUBPROCESS
] = forkout
;
1932 #if defined (DONT_REOPEN_PTY)
1933 /* In the case that vfork is defined as fork, the parent process
1934 (Emacs) may send some data before the child process completes
1935 tty options setup. So we setup tty before forking. */
1936 child_setup_tty (forkout
);
1937 #endif /* DONT_REOPEN_PTY */
1938 #endif /* not USG, or USG_SUBTTY_WORKS */
1940 fcntl (pty_fd
, F_SETFL
, O_NONBLOCK
);
1942 /* Record this as an active process, with its channels.
1943 As a result, child_setup will close Emacs's side of the pipes. */
1944 chan_process
[pty_fd
] = process
;
1948 /* Previously we recorded the tty descriptor used in the subprocess.
1949 It was only used for getting the foreground tty process, so now
1950 we just reopen the device (see emacs_get_tty_pgrp) as this is
1951 more portable (see USG_SUBTTY_WORKS above). */
1954 pset_status (p
, Qrun
);
1955 setup_process_coding_systems (process
);
1957 FD_SET (pty_fd
, &input_wait_mask
);
1958 FD_SET (pty_fd
, &non_keyboard_wait_mask
);
1959 if (pty_fd
> max_process_desc
)
1960 max_process_desc
= pty_fd
;
1962 pset_tty_name (p
, build_string (pty_name
));
1969 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1970 The address family of sa is not included in the result. */
1976 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
1978 Lisp_Object address
;
1981 register struct Lisp_Vector
*p
;
1983 /* Workaround for a bug in getsockname on BSD: Names bound to
1984 sockets in the UNIX domain are inaccessible; getsockname returns
1985 a zero length name. */
1986 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
1987 return empty_unibyte_string
;
1989 switch (sa
->sa_family
)
1993 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
1994 len
= sizeof (sin
->sin_addr
) + 1;
1995 address
= Fmake_vector (make_number (len
), Qnil
);
1996 p
= XVECTOR (address
);
1997 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
1998 cp
= (unsigned char *) &sin
->sin_addr
;
2004 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2005 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2006 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2007 address
= Fmake_vector (make_number (len
), Qnil
);
2008 p
= XVECTOR (address
);
2009 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2010 for (i
= 0; i
< len
; i
++)
2011 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2015 #ifdef HAVE_LOCAL_SOCKETS
2018 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2019 ptrdiff_t name_length
= len
- offsetof (struct sockaddr_un
, sun_path
);
2020 /* If the first byte is NUL, the name is a Linux abstract
2021 socket name, and the name can contain embedded NULs. If
2022 it's not, we have a NUL-terminated string. Be careful not
2023 to walk past the end of the object looking for the name
2024 terminator, however. */
2025 if (name_length
> 0 && sockun
->sun_path
[0] != '\0')
2027 const char* terminator
=
2028 memchr (sockun
->sun_path
, '\0', name_length
);
2031 name_length
= terminator
- (const char*) sockun
->sun_path
;
2034 return make_unibyte_string (sockun
->sun_path
, name_length
);
2038 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2039 address
= Fcons (make_number (sa
->sa_family
),
2040 Fmake_vector (make_number (len
), Qnil
));
2041 p
= XVECTOR (XCDR (address
));
2042 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2048 p
->contents
[i
++] = make_number (*cp
++);
2054 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2057 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2059 register struct Lisp_Vector
*p
;
2061 if (VECTORP (address
))
2063 p
= XVECTOR (address
);
2064 if (p
->header
.size
== 5)
2067 return sizeof (struct sockaddr_in
);
2070 else if (p
->header
.size
== 9)
2072 *familyp
= AF_INET6
;
2073 return sizeof (struct sockaddr_in6
);
2077 #ifdef HAVE_LOCAL_SOCKETS
2078 else if (STRINGP (address
))
2080 *familyp
= AF_LOCAL
;
2081 return sizeof (struct sockaddr_un
);
2084 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2085 && VECTORP (XCDR (address
)))
2087 struct sockaddr
*sa
;
2088 *familyp
= XINT (XCAR (address
));
2089 p
= XVECTOR (XCDR (address
));
2090 return p
->header
.size
+ sizeof (sa
->sa_family
);
2095 /* Convert an address object (vector or string) to an internal sockaddr.
2097 The address format has been basically validated by
2098 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2099 it could have come from user data. So if FAMILY is not valid,
2100 we return after zeroing *SA. */
2103 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2105 register struct Lisp_Vector
*p
;
2106 register unsigned char *cp
= NULL
;
2110 memset (sa
, 0, len
);
2112 if (VECTORP (address
))
2114 p
= XVECTOR (address
);
2115 if (family
== AF_INET
)
2117 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2118 len
= sizeof (sin
->sin_addr
) + 1;
2119 hostport
= XINT (p
->contents
[--len
]);
2120 sin
->sin_port
= htons (hostport
);
2121 cp
= (unsigned char *)&sin
->sin_addr
;
2122 sa
->sa_family
= family
;
2125 else if (family
== AF_INET6
)
2127 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2128 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2129 len
= sizeof (sin6
->sin6_addr
) + 1;
2130 hostport
= XINT (p
->contents
[--len
]);
2131 sin6
->sin6_port
= htons (hostport
);
2132 for (i
= 0; i
< len
; i
++)
2133 if (INTEGERP (p
->contents
[i
]))
2135 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2138 sa
->sa_family
= family
;
2145 else if (STRINGP (address
))
2147 #ifdef HAVE_LOCAL_SOCKETS
2148 if (family
== AF_LOCAL
)
2150 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2151 cp
= SDATA (address
);
2152 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2153 sockun
->sun_path
[i
] = *cp
++;
2154 sa
->sa_family
= family
;
2161 p
= XVECTOR (XCDR (address
));
2162 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2165 for (i
= 0; i
< len
; i
++)
2166 if (INTEGERP (p
->contents
[i
]))
2167 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2170 #ifdef DATAGRAM_SOCKETS
2171 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2173 doc
: /* Get the current datagram address associated with PROCESS. */)
2174 (Lisp_Object process
)
2178 CHECK_PROCESS (process
);
2180 if (!DATAGRAM_CONN_P (process
))
2183 channel
= XPROCESS (process
)->infd
;
2184 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2185 datagram_address
[channel
].len
);
2188 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2190 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2191 Returns nil upon error setting address, ADDRESS otherwise. */)
2192 (Lisp_Object process
, Lisp_Object address
)
2197 CHECK_PROCESS (process
);
2199 if (!DATAGRAM_CONN_P (process
))
2202 channel
= XPROCESS (process
)->infd
;
2204 len
= get_lisp_to_sockaddr_size (address
, &family
);
2205 if (len
== 0 || datagram_address
[channel
].len
!= len
)
2207 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2213 static const struct socket_options
{
2214 /* The name of this option. Should be lowercase version of option
2215 name without SO_ prefix. */
2217 /* Option level SOL_... */
2219 /* Option number SO_... */
2221 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2222 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2223 } socket_options
[] =
2225 #ifdef SO_BINDTODEVICE
2226 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2229 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2232 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2235 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2238 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2241 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2244 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2247 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2249 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2252 /* Set option OPT to value VAL on socket S.
2254 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2255 Signals an error if setting a known option fails.
2259 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2262 const struct socket_options
*sopt
;
2267 name
= SSDATA (SYMBOL_NAME (opt
));
2268 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2269 if (strcmp (name
, sopt
->name
) == 0)
2272 switch (sopt
->opttype
)
2277 optval
= NILP (val
) ? 0 : 1;
2278 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2279 &optval
, sizeof (optval
));
2286 if (TYPE_RANGED_INTEGERP (int, val
))
2287 optval
= XINT (val
);
2289 error ("Bad option value for %s", name
);
2290 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2291 &optval
, sizeof (optval
));
2295 #ifdef SO_BINDTODEVICE
2298 char devname
[IFNAMSIZ
+1];
2300 /* This is broken, at least in the Linux 2.4 kernel.
2301 To unbind, the arg must be a zero integer, not the empty string.
2302 This should work on all systems. KFS. 2003-09-23. */
2303 memset (devname
, 0, sizeof devname
);
2306 char *arg
= SSDATA (val
);
2307 int len
= min (strlen (arg
), IFNAMSIZ
);
2308 memcpy (devname
, arg
, len
);
2310 else if (!NILP (val
))
2311 error ("Bad option value for %s", name
);
2312 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2321 struct linger linger
;
2324 linger
.l_linger
= 0;
2325 if (TYPE_RANGED_INTEGERP (int, val
))
2326 linger
.l_linger
= XINT (val
);
2328 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2329 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2330 &linger
, sizeof (linger
));
2341 int setsockopt_errno
= errno
;
2342 report_file_errno ("Cannot set network option", list2 (opt
, val
),
2346 return (1 << sopt
->optbit
);
2350 DEFUN ("set-network-process-option",
2351 Fset_network_process_option
, Sset_network_process_option
,
2353 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2354 See `make-network-process' for a list of options and values.
2355 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2356 OPTION is not a supported option, return nil instead; otherwise return t. */)
2357 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2360 struct Lisp_Process
*p
;
2362 CHECK_PROCESS (process
);
2363 p
= XPROCESS (process
);
2364 if (!NETCONN1_P (p
))
2365 error ("Process is not a network process");
2369 error ("Process is not running");
2371 if (set_socket_option (s
, option
, value
))
2373 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2377 if (NILP (no_error
))
2378 error ("Unknown or unsupported option");
2384 DEFUN ("serial-process-configure",
2385 Fserial_process_configure
,
2386 Sserial_process_configure
,
2388 doc
: /* Configure speed, bytesize, etc. of a serial process.
2390 Arguments are specified as keyword/argument pairs. Attributes that
2391 are not given are re-initialized from the process's current
2392 configuration (available via the function `process-contact') or set to
2393 reasonable default values. The following arguments are defined:
2399 -- Any of these arguments can be given to identify the process that is
2400 to be configured. If none of these arguments is given, the current
2401 buffer's process is used.
2403 :speed SPEED -- SPEED is the speed of the serial port in bits per
2404 second, also called baud rate. Any value can be given for SPEED, but
2405 most serial ports work only at a few defined values between 1200 and
2406 115200, with 9600 being the most common value. If SPEED is nil, the
2407 serial port is not configured any further, i.e., all other arguments
2408 are ignored. This may be useful for special serial ports such as
2409 Bluetooth-to-serial converters which can only be configured through AT
2410 commands. A value of nil for SPEED can be used only when passed
2411 through `make-serial-process' or `serial-term'.
2413 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2414 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2416 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2417 `odd' (use odd parity), or the symbol `even' (use even parity). If
2418 PARITY is not given, no parity is used.
2420 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2421 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2422 is not given or nil, 1 stopbit is used.
2424 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2425 flowcontrol to be used, which is either nil (don't use flowcontrol),
2426 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2427 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2428 flowcontrol is used.
2430 `serial-process-configure' is called by `make-serial-process' for the
2431 initial configuration of the serial port.
2435 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2437 \(serial-process-configure
2438 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2440 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2442 usage: (serial-process-configure &rest ARGS) */)
2443 (ptrdiff_t nargs
, Lisp_Object
*args
)
2445 struct Lisp_Process
*p
;
2446 Lisp_Object contact
= Qnil
;
2447 Lisp_Object proc
= Qnil
;
2448 struct gcpro gcpro1
;
2450 contact
= Flist (nargs
, args
);
2453 proc
= Fplist_get (contact
, QCprocess
);
2455 proc
= Fplist_get (contact
, QCname
);
2457 proc
= Fplist_get (contact
, QCbuffer
);
2459 proc
= Fplist_get (contact
, QCport
);
2460 proc
= get_process (proc
);
2461 p
= XPROCESS (proc
);
2462 if (!EQ (p
->type
, Qserial
))
2463 error ("Not a serial process");
2465 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2471 serial_configure (p
, contact
);
2477 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2479 doc
: /* Create and return a serial port process.
2481 In Emacs, serial port connections are represented by process objects,
2482 so input and output work as for subprocesses, and `delete-process'
2483 closes a serial port connection. However, a serial process has no
2484 process id, it cannot be signaled, and the status codes are different
2485 from normal processes.
2487 `make-serial-process' creates a process and a buffer, on which you
2488 probably want to use `process-send-string'. Try \\[serial-term] for
2489 an interactive terminal. See below for examples.
2491 Arguments are specified as keyword/argument pairs. The following
2492 arguments are defined:
2494 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2495 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2496 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2497 the backslashes in strings).
2499 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2500 which this function calls.
2502 :name NAME -- NAME is the name of the process. If NAME is not given,
2503 the value of PORT is used.
2505 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2506 with the process. Process output goes at the end of that buffer,
2507 unless you specify an output stream or filter function to handle the
2508 output. If BUFFER is not given, the value of NAME is used.
2510 :coding CODING -- If CODING is a symbol, it specifies the coding
2511 system used for both reading and writing for this process. If CODING
2512 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2513 ENCODING is used for writing.
2515 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2516 the process is running. If BOOL is not given, query before exiting.
2518 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2519 In the stopped state, a serial process does not accept incoming data,
2520 but you can send outgoing data. The stopped state is cleared by
2521 `continue-process' and set by `stop-process'.
2523 :filter FILTER -- Install FILTER as the process filter.
2525 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2527 :plist PLIST -- Install PLIST as the initial plist of the process.
2533 -- This function calls `serial-process-configure' to handle these
2536 The original argument list, possibly modified by later configuration,
2537 is available via the function `process-contact'.
2541 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2543 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2545 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2547 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2549 usage: (make-serial-process &rest ARGS) */)
2550 (ptrdiff_t nargs
, Lisp_Object
*args
)
2553 Lisp_Object proc
, contact
, port
;
2554 struct Lisp_Process
*p
;
2555 struct gcpro gcpro1
;
2556 Lisp_Object name
, buffer
;
2557 Lisp_Object tem
, val
;
2558 ptrdiff_t specpdl_count
;
2563 contact
= Flist (nargs
, args
);
2566 port
= Fplist_get (contact
, QCport
);
2568 error ("No port specified");
2569 CHECK_STRING (port
);
2571 if (NILP (Fplist_member (contact
, QCspeed
)))
2572 error (":speed not specified");
2573 if (!NILP (Fplist_get (contact
, QCspeed
)))
2574 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2576 name
= Fplist_get (contact
, QCname
);
2579 CHECK_STRING (name
);
2580 proc
= make_process (name
);
2581 specpdl_count
= SPECPDL_INDEX ();
2582 record_unwind_protect (remove_process
, proc
);
2583 p
= XPROCESS (proc
);
2585 fd
= serial_open (port
);
2586 p
->open_fd
[SUBPROCESS_STDIN
] = fd
;
2589 if (fd
> max_process_desc
)
2590 max_process_desc
= fd
;
2591 chan_process
[fd
] = proc
;
2593 buffer
= Fplist_get (contact
, QCbuffer
);
2596 buffer
= Fget_buffer_create (buffer
);
2597 pset_buffer (p
, buffer
);
2599 pset_childp (p
, contact
);
2600 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2601 pset_type (p
, Qserial
);
2602 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2603 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2605 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2606 p
->kill_without_query
= 1;
2607 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2608 pset_command (p
, Qt
);
2609 eassert (! p
->pty_flag
);
2611 if (!EQ (p
->command
, Qt
))
2613 FD_SET (fd
, &input_wait_mask
);
2614 FD_SET (fd
, &non_keyboard_wait_mask
);
2617 if (BUFFERP (buffer
))
2619 set_marker_both (p
->mark
, buffer
,
2620 BUF_ZV (XBUFFER (buffer
)),
2621 BUF_ZV_BYTE (XBUFFER (buffer
)));
2624 tem
= Fplist_member (contact
, QCcoding
);
2625 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2631 val
= XCAR (XCDR (tem
));
2635 else if (!NILP (Vcoding_system_for_read
))
2636 val
= Vcoding_system_for_read
;
2637 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2638 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2640 pset_decode_coding_system (p
, val
);
2645 val
= XCAR (XCDR (tem
));
2649 else if (!NILP (Vcoding_system_for_write
))
2650 val
= Vcoding_system_for_write
;
2651 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2652 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2654 pset_encode_coding_system (p
, val
);
2656 setup_process_coding_systems (proc
);
2657 pset_decoding_buf (p
, empty_unibyte_string
);
2658 p
->decoding_carryover
= 0;
2659 pset_encoding_buf (p
, empty_unibyte_string
);
2660 p
->inherit_coding_system_flag
2661 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2663 Fserial_process_configure (nargs
, args
);
2665 specpdl_ptr
= specpdl
+ specpdl_count
;
2671 /* Create a network stream/datagram client/server process. Treated
2672 exactly like a normal process when reading and writing. Primary
2673 differences are in status display and process deletion. A network
2674 connection has no PID; you cannot signal it. All you can do is
2675 stop/continue it and deactivate/close it via delete-process */
2677 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2679 doc
: /* Create and return a network server or client process.
2681 In Emacs, network connections are represented by process objects, so
2682 input and output work as for subprocesses and `delete-process' closes
2683 a network connection. However, a network process has no process id,
2684 it cannot be signaled, and the status codes are different from normal
2687 Arguments are specified as keyword/argument pairs. The following
2688 arguments are defined:
2690 :name NAME -- NAME is name for process. It is modified if necessary
2693 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2694 with the process. Process output goes at end of that buffer, unless
2695 you specify an output stream or filter function to handle the output.
2696 BUFFER may be also nil, meaning that this process is not associated
2699 :host HOST -- HOST is name of the host to connect to, or its IP
2700 address. The symbol `local' specifies the local host. If specified
2701 for a server process, it must be a valid name or address for the local
2702 host, and only clients connecting to that address will be accepted.
2704 :service SERVICE -- SERVICE is name of the service desired, or an
2705 integer specifying a port number to connect to. If SERVICE is t,
2706 a random port number is selected for the server. (If Emacs was
2707 compiled with getaddrinfo, a port number can also be specified as a
2708 string, e.g. "80", as well as an integer. This is not portable.)
2710 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2711 stream type connection, `datagram' creates a datagram type connection,
2712 `seqpacket' creates a reliable datagram connection.
2714 :family FAMILY -- FAMILY is the address (and protocol) family for the
2715 service specified by HOST and SERVICE. The default (nil) is to use
2716 whatever address family (IPv4 or IPv6) that is defined for the host
2717 and port number specified by HOST and SERVICE. Other address families
2719 local -- for a local (i.e. UNIX) address specified by SERVICE.
2720 ipv4 -- use IPv4 address family only.
2721 ipv6 -- use IPv6 address family only.
2723 :local ADDRESS -- ADDRESS is the local address used for the connection.
2724 This parameter is ignored when opening a client process. When specified
2725 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2727 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2728 connection. This parameter is ignored when opening a stream server
2729 process. For a datagram server process, it specifies the initial
2730 setting of the remote datagram address. When specified for a client
2731 process, the FAMILY, HOST, and SERVICE args are ignored.
2733 The format of ADDRESS depends on the address family:
2734 - An IPv4 address is represented as an vector of integers [A B C D P]
2735 corresponding to numeric IP address A.B.C.D and port number P.
2736 - A local address is represented as a string with the address in the
2737 local address space.
2738 - An "unsupported family" address is represented by a cons (F . AV)
2739 where F is the family number and AV is a vector containing the socket
2740 address data with one element per address data byte. Do not rely on
2741 this format in portable code, as it may depend on implementation
2742 defined constants, data sizes, and data structure alignment.
2744 :coding CODING -- If CODING is a symbol, it specifies the coding
2745 system used for both reading and writing for this process. If CODING
2746 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2747 ENCODING is used for writing.
2749 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2750 return without waiting for the connection to complete; instead, the
2751 sentinel function will be called with second arg matching "open" (if
2752 successful) or "failed" when the connect completes. Default is to use
2753 a blocking connect (i.e. wait) for stream type connections.
2755 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2756 running when Emacs is exited.
2758 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2759 In the stopped state, a server process does not accept new
2760 connections, and a client process does not handle incoming traffic.
2761 The stopped state is cleared by `continue-process' and set by
2764 :filter FILTER -- Install FILTER as the process filter.
2766 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2767 process filter are multibyte, otherwise they are unibyte.
2768 If this keyword is not specified, the strings are multibyte if
2769 the default value of `enable-multibyte-characters' is non-nil.
2771 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2773 :log LOG -- Install LOG as the server process log function. This
2774 function is called when the server accepts a network connection from a
2775 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2776 is the server process, CLIENT is the new process for the connection,
2777 and MESSAGE is a string.
2779 :plist PLIST -- Install PLIST as the new process's initial plist.
2781 :server QLEN -- if QLEN is non-nil, create a server process for the
2782 specified FAMILY, SERVICE, and connection type (stream or datagram).
2783 If QLEN is an integer, it is used as the max. length of the server's
2784 pending connection queue (also known as the backlog); the default
2785 queue length is 5. Default is to create a client process.
2787 The following network options can be specified for this connection:
2789 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2790 :dontroute BOOL -- Only send to directly connected hosts.
2791 :keepalive BOOL -- Send keep-alive messages on network stream.
2792 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2793 :oobinline BOOL -- Place out-of-band data in receive data stream.
2794 :priority INT -- Set protocol defined priority for sent packets.
2795 :reuseaddr BOOL -- Allow reusing a recently used local address
2796 (this is allowed by default for a server process).
2797 :bindtodevice NAME -- bind to interface NAME. Using this may require
2798 special privileges on some systems.
2800 Consult the relevant system programmer's manual pages for more
2801 information on using these options.
2804 A server process will listen for and accept connections from clients.
2805 When a client connection is accepted, a new network process is created
2806 for the connection with the following parameters:
2808 - The client's process name is constructed by concatenating the server
2809 process's NAME and a client identification string.
2810 - If the FILTER argument is non-nil, the client process will not get a
2811 separate process buffer; otherwise, the client's process buffer is a newly
2812 created buffer named after the server process's BUFFER name or process
2813 NAME concatenated with the client identification string.
2814 - The connection type and the process filter and sentinel parameters are
2815 inherited from the server process's TYPE, FILTER and SENTINEL.
2816 - The client process's contact info is set according to the client's
2817 addressing information (typically an IP address and a port number).
2818 - The client process's plist is initialized from the server's plist.
2820 Notice that the FILTER and SENTINEL args are never used directly by
2821 the server process. Also, the BUFFER argument is not used directly by
2822 the server process, but via the optional :log function, accepted (and
2823 failed) connections may be logged in the server process's buffer.
2825 The original argument list, modified with the actual connection
2826 information, is available via the `process-contact' function.
2828 usage: (make-network-process &rest ARGS) */)
2829 (ptrdiff_t nargs
, Lisp_Object
*args
)
2832 Lisp_Object contact
;
2833 struct Lisp_Process
*p
;
2834 #ifdef HAVE_GETADDRINFO
2835 struct addrinfo ai
, *res
, *lres
;
2836 struct addrinfo hints
;
2837 const char *portstring
;
2839 #else /* HAVE_GETADDRINFO */
2840 struct _emacs_addrinfo
2846 struct sockaddr
*ai_addr
;
2847 struct _emacs_addrinfo
*ai_next
;
2849 #endif /* HAVE_GETADDRINFO */
2850 struct sockaddr_in address_in
;
2851 #ifdef HAVE_LOCAL_SOCKETS
2852 struct sockaddr_un address_un
;
2857 int s
= -1, outch
, inch
;
2858 struct gcpro gcpro1
;
2859 ptrdiff_t count
= SPECPDL_INDEX ();
2861 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
2863 Lisp_Object name
, buffer
, host
, service
, address
;
2864 Lisp_Object filter
, sentinel
;
2865 bool is_non_blocking_client
= 0;
2874 /* Save arguments for process-contact and clone-process. */
2875 contact
= Flist (nargs
, args
);
2879 /* Ensure socket support is loaded if available. */
2880 init_winsock (TRUE
);
2883 /* :type TYPE (nil: stream, datagram */
2884 tem
= Fplist_get (contact
, QCtype
);
2886 socktype
= SOCK_STREAM
;
2887 #ifdef DATAGRAM_SOCKETS
2888 else if (EQ (tem
, Qdatagram
))
2889 socktype
= SOCK_DGRAM
;
2891 #ifdef HAVE_SEQPACKET
2892 else if (EQ (tem
, Qseqpacket
))
2893 socktype
= SOCK_SEQPACKET
;
2896 error ("Unsupported connection type");
2899 tem
= Fplist_get (contact
, QCserver
);
2902 /* Don't support network sockets when non-blocking mode is
2903 not available, since a blocked Emacs is not useful. */
2905 if (TYPE_RANGED_INTEGERP (int, tem
))
2906 backlog
= XINT (tem
);
2909 /* Make QCaddress an alias for :local (server) or :remote (client). */
2910 QCaddress
= is_server
? QClocal
: QCremote
;
2913 if (!is_server
&& socktype
!= SOCK_DGRAM
2914 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2916 #ifndef NON_BLOCKING_CONNECT
2917 error ("Non-blocking connect not supported");
2919 is_non_blocking_client
= 1;
2923 name
= Fplist_get (contact
, QCname
);
2924 buffer
= Fplist_get (contact
, QCbuffer
);
2925 filter
= Fplist_get (contact
, QCfilter
);
2926 sentinel
= Fplist_get (contact
, QCsentinel
);
2928 CHECK_STRING (name
);
2930 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2931 ai
.ai_socktype
= socktype
;
2936 /* :local ADDRESS or :remote ADDRESS */
2937 address
= Fplist_get (contact
, QCaddress
);
2938 if (!NILP (address
))
2940 host
= service
= Qnil
;
2942 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2943 error ("Malformed :address");
2944 ai
.ai_family
= family
;
2945 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2946 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
2950 /* :family FAMILY -- nil (for Inet), local, or integer. */
2951 tem
= Fplist_get (contact
, QCfamily
);
2954 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2960 #ifdef HAVE_LOCAL_SOCKETS
2961 else if (EQ (tem
, Qlocal
))
2965 else if (EQ (tem
, Qipv6
))
2968 else if (EQ (tem
, Qipv4
))
2970 else if (TYPE_RANGED_INTEGERP (int, tem
))
2971 family
= XINT (tem
);
2973 error ("Unknown address family");
2975 ai
.ai_family
= family
;
2977 /* :service SERVICE -- string, integer (port number), or t (random port). */
2978 service
= Fplist_get (contact
, QCservice
);
2980 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2981 host
= Fplist_get (contact
, QChost
);
2984 if (EQ (host
, Qlocal
))
2985 /* Depending on setup, "localhost" may map to different IPv4 and/or
2986 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2987 host
= build_string ("127.0.0.1");
2988 CHECK_STRING (host
);
2991 #ifdef HAVE_LOCAL_SOCKETS
2992 if (family
== AF_LOCAL
)
2996 message (":family local ignores the :host \"%s\" property",
2998 contact
= Fplist_put (contact
, QChost
, Qnil
);
3001 CHECK_STRING (service
);
3002 memset (&address_un
, 0, sizeof address_un
);
3003 address_un
.sun_family
= AF_LOCAL
;
3004 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3005 error ("Service name too long");
3006 strcpy (address_un
.sun_path
, SSDATA (service
));
3007 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3008 ai
.ai_addrlen
= sizeof address_un
;
3013 /* Slow down polling to every ten seconds.
3014 Some kernels have a bug which causes retrying connect to fail
3015 after a connect. Polling can interfere with gethostbyname too. */
3016 #ifdef POLL_FOR_INPUT
3017 if (socktype
!= SOCK_DGRAM
)
3019 record_unwind_protect_void (run_all_atimers
);
3020 bind_polling_period (10);
3024 #ifdef HAVE_GETADDRINFO
3025 /* If we have a host, use getaddrinfo to resolve both host and service.
3026 Otherwise, use getservbyname to lookup the service. */
3030 /* SERVICE can either be a string or int.
3031 Convert to a C string for later use by getaddrinfo. */
3032 if (EQ (service
, Qt
))
3034 else if (INTEGERP (service
))
3036 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3037 portstring
= portbuf
;
3041 CHECK_STRING (service
);
3042 portstring
= SSDATA (service
);
3047 memset (&hints
, 0, sizeof (hints
));
3049 hints
.ai_family
= family
;
3050 hints
.ai_socktype
= socktype
;
3051 hints
.ai_protocol
= 0;
3053 #ifdef HAVE_RES_INIT
3057 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3059 #ifdef HAVE_GAI_STRERROR
3060 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3062 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3068 #endif /* HAVE_GETADDRINFO */
3070 /* We end up here if getaddrinfo is not defined, or in case no hostname
3071 has been specified (e.g. for a local server process). */
3073 if (EQ (service
, Qt
))
3075 else if (INTEGERP (service
))
3076 port
= htons ((unsigned short) XINT (service
));
3079 struct servent
*svc_info
;
3080 CHECK_STRING (service
);
3081 svc_info
= getservbyname (SSDATA (service
),
3082 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3084 error ("Unknown service: %s", SDATA (service
));
3085 port
= svc_info
->s_port
;
3088 memset (&address_in
, 0, sizeof address_in
);
3089 address_in
.sin_family
= family
;
3090 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3091 address_in
.sin_port
= port
;
3093 #ifndef HAVE_GETADDRINFO
3096 struct hostent
*host_info_ptr
;
3098 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3099 as it may `hang' Emacs for a very long time. */
3103 #ifdef HAVE_RES_INIT
3107 host_info_ptr
= gethostbyname (SDATA (host
));
3112 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3113 host_info_ptr
->h_length
);
3114 family
= host_info_ptr
->h_addrtype
;
3115 address_in
.sin_family
= family
;
3118 /* Attempt to interpret host as numeric inet address */
3120 unsigned long numeric_addr
;
3121 numeric_addr
= inet_addr (SSDATA (host
));
3122 if (numeric_addr
== -1)
3123 error ("Unknown host \"%s\"", SDATA (host
));
3125 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3126 sizeof (address_in
.sin_addr
));
3130 #endif /* not HAVE_GETADDRINFO */
3132 ai
.ai_family
= family
;
3133 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3134 ai
.ai_addrlen
= sizeof address_in
;
3138 /* Do this in case we never enter the for-loop below. */
3139 count1
= SPECPDL_INDEX ();
3142 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3151 s
= socket (lres
->ai_family
, lres
->ai_socktype
| SOCK_CLOEXEC
,
3159 #ifdef DATAGRAM_SOCKETS
3160 if (!is_server
&& socktype
== SOCK_DGRAM
)
3162 #endif /* DATAGRAM_SOCKETS */
3164 #ifdef NON_BLOCKING_CONNECT
3165 if (is_non_blocking_client
)
3167 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3178 /* Make us close S if quit. */
3179 record_unwind_protect_int (close_file_unwind
, s
);
3181 /* Parse network options in the arg list.
3182 We simply ignore anything which isn't a known option (including other keywords).
3183 An error is signaled if setting a known option fails. */
3184 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3185 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3189 /* Configure as a server socket. */
3191 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3192 explicit :reuseaddr key to override this. */
3193 #ifdef HAVE_LOCAL_SOCKETS
3194 if (family
!= AF_LOCAL
)
3196 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3199 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3200 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3203 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3204 report_file_error ("Cannot bind server socket", Qnil
);
3206 #ifdef HAVE_GETSOCKNAME
3207 if (EQ (service
, Qt
))
3209 struct sockaddr_in sa1
;
3210 socklen_t len1
= sizeof (sa1
);
3211 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3213 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3214 service
= make_number (ntohs (sa1
.sin_port
));
3215 contact
= Fplist_put (contact
, QCservice
, service
);
3220 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3221 report_file_error ("Cannot listen on server socket", Qnil
);
3229 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3232 if (ret
== 0 || xerrno
== EISCONN
)
3234 /* The unwind-protect will be discarded afterwards.
3235 Likewise for immediate_quit. */
3239 #ifdef NON_BLOCKING_CONNECT
3241 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3245 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3252 if (xerrno
== EINTR
)
3254 /* Unlike most other syscalls connect() cannot be called
3255 again. (That would return EALREADY.) The proper way to
3256 wait for completion is pselect(). */
3264 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3270 report_file_error ("Failed select", Qnil
);
3274 len
= sizeof xerrno
;
3275 eassert (FD_ISSET (s
, &fdset
));
3276 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) < 0)
3277 report_file_error ("Failed getsockopt", Qnil
);
3279 report_file_errno ("Failed connect", Qnil
, xerrno
);
3282 #endif /* !WINDOWSNT */
3286 /* Discard the unwind protect closing S. */
3287 specpdl_ptr
= specpdl
+ count1
;
3292 if (xerrno
== EINTR
)
3299 #ifdef DATAGRAM_SOCKETS
3300 if (socktype
== SOCK_DGRAM
)
3302 if (datagram_address
[s
].sa
)
3304 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3305 datagram_address
[s
].len
= lres
->ai_addrlen
;
3309 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3310 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3313 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3314 if (rlen
!= 0 && rfamily
== lres
->ai_family
3315 && rlen
== lres
->ai_addrlen
)
3316 conv_lisp_to_sockaddr (rfamily
, remote
,
3317 datagram_address
[s
].sa
, rlen
);
3321 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3324 contact
= Fplist_put (contact
, QCaddress
,
3325 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3326 #ifdef HAVE_GETSOCKNAME
3329 struct sockaddr_in sa1
;
3330 socklen_t len1
= sizeof (sa1
);
3331 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3332 contact
= Fplist_put (contact
, QClocal
,
3333 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3340 #ifdef HAVE_GETADDRINFO
3351 /* If non-blocking got this far - and failed - assume non-blocking is
3352 not supported after all. This is probably a wrong assumption, but
3353 the normal blocking calls to open-network-stream handles this error
3355 if (is_non_blocking_client
)
3358 report_file_errno ((is_server
3359 ? "make server process failed"
3360 : "make client process failed"),
3368 buffer
= Fget_buffer_create (buffer
);
3369 proc
= make_process (name
);
3371 chan_process
[inch
] = proc
;
3373 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3375 p
= XPROCESS (proc
);
3377 pset_childp (p
, contact
);
3378 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3379 pset_type (p
, Qnetwork
);
3381 pset_buffer (p
, buffer
);
3382 pset_sentinel (p
, sentinel
);
3383 pset_filter (p
, filter
);
3384 pset_log (p
, Fplist_get (contact
, QClog
));
3385 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3386 p
->kill_without_query
= 1;
3387 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3388 pset_command (p
, Qt
);
3391 p
->open_fd
[SUBPROCESS_STDIN
] = inch
;
3395 /* Discard the unwind protect for closing S, if any. */
3396 specpdl_ptr
= specpdl
+ count1
;
3398 /* Unwind bind_polling_period and request_sigio. */
3399 unbind_to (count
, Qnil
);
3401 if (is_server
&& socktype
!= SOCK_DGRAM
)
3402 pset_status (p
, Qlisten
);
3404 /* Make the process marker point into the process buffer (if any). */
3405 if (BUFFERP (buffer
))
3406 set_marker_both (p
->mark
, buffer
,
3407 BUF_ZV (XBUFFER (buffer
)),
3408 BUF_ZV_BYTE (XBUFFER (buffer
)));
3410 #ifdef NON_BLOCKING_CONNECT
3411 if (is_non_blocking_client
)
3413 /* We may get here if connect did succeed immediately. However,
3414 in that case, we still need to signal this like a non-blocking
3416 pset_status (p
, Qconnect
);
3417 if (!FD_ISSET (inch
, &connect_wait_mask
))
3419 FD_SET (inch
, &connect_wait_mask
);
3420 FD_SET (inch
, &write_mask
);
3421 num_pending_connects
++;
3426 /* A server may have a client filter setting of Qt, but it must
3427 still listen for incoming connects unless it is stopped. */
3428 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3429 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3431 FD_SET (inch
, &input_wait_mask
);
3432 FD_SET (inch
, &non_keyboard_wait_mask
);
3435 if (inch
> max_process_desc
)
3436 max_process_desc
= inch
;
3438 tem
= Fplist_member (contact
, QCcoding
);
3439 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3440 tem
= Qnil
; /* No error message (too late!). */
3443 /* Setup coding systems for communicating with the network stream. */
3444 struct gcpro gcpro1
;
3445 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3446 Lisp_Object coding_systems
= Qt
;
3447 Lisp_Object fargs
[5], val
;
3451 val
= XCAR (XCDR (tem
));
3455 else if (!NILP (Vcoding_system_for_read
))
3456 val
= Vcoding_system_for_read
;
3457 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3458 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3459 /* We dare not decode end-of-line format by setting VAL to
3460 Qraw_text, because the existing Emacs Lisp libraries
3461 assume that they receive bare code including a sequence of
3466 if (NILP (host
) || NILP (service
))
3467 coding_systems
= Qnil
;
3470 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3471 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3473 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3476 if (CONSP (coding_systems
))
3477 val
= XCAR (coding_systems
);
3478 else if (CONSP (Vdefault_process_coding_system
))
3479 val
= XCAR (Vdefault_process_coding_system
);
3483 pset_decode_coding_system (p
, val
);
3487 val
= XCAR (XCDR (tem
));
3491 else if (!NILP (Vcoding_system_for_write
))
3492 val
= Vcoding_system_for_write
;
3493 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3497 if (EQ (coding_systems
, Qt
))
3499 if (NILP (host
) || NILP (service
))
3500 coding_systems
= Qnil
;
3503 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3504 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3506 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3510 if (CONSP (coding_systems
))
3511 val
= XCDR (coding_systems
);
3512 else if (CONSP (Vdefault_process_coding_system
))
3513 val
= XCDR (Vdefault_process_coding_system
);
3517 pset_encode_coding_system (p
, val
);
3519 setup_process_coding_systems (proc
);
3521 pset_decoding_buf (p
, empty_unibyte_string
);
3522 p
->decoding_carryover
= 0;
3523 pset_encoding_buf (p
, empty_unibyte_string
);
3525 p
->inherit_coding_system_flag
3526 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3533 #ifdef HAVE_NET_IF_H
3537 network_interface_list (void)
3539 struct ifconf ifconf
;
3540 struct ifreq
*ifreq
;
3542 ptrdiff_t buf_size
= 512;
3547 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3550 count
= SPECPDL_INDEX ();
3551 record_unwind_protect_int (close_file_unwind
, s
);
3555 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3556 ifconf
.ifc_buf
= buf
;
3557 ifconf
.ifc_len
= buf_size
;
3558 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3565 while (ifconf
.ifc_len
== buf_size
);
3567 res
= unbind_to (count
, Qnil
);
3568 ifreq
= ifconf
.ifc_req
;
3569 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3571 struct ifreq
*ifq
= ifreq
;
3572 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3573 #define SIZEOF_IFREQ(sif) \
3574 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3575 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3577 int len
= SIZEOF_IFREQ (ifq
);
3579 int len
= sizeof (*ifreq
);
3581 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3582 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3584 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3587 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3588 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3589 res
= Fcons (Fcons (build_string (namebuf
),
3590 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3591 sizeof (struct sockaddr
))),
3598 #endif /* SIOCGIFCONF */
3600 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3604 const char *flag_sym
;
3607 static const struct ifflag_def ifflag_table
[] = {
3611 #ifdef IFF_BROADCAST
3612 { IFF_BROADCAST
, "broadcast" },
3615 { IFF_DEBUG
, "debug" },
3618 { IFF_LOOPBACK
, "loopback" },
3620 #ifdef IFF_POINTOPOINT
3621 { IFF_POINTOPOINT
, "pointopoint" },
3624 { IFF_RUNNING
, "running" },
3627 { IFF_NOARP
, "noarp" },
3630 { IFF_PROMISC
, "promisc" },
3632 #ifdef IFF_NOTRAILERS
3633 #ifdef NS_IMPL_COCOA
3634 /* Really means smart, notrailers is obsolete */
3635 { IFF_NOTRAILERS
, "smart" },
3637 { IFF_NOTRAILERS
, "notrailers" },
3641 { IFF_ALLMULTI
, "allmulti" },
3644 { IFF_MASTER
, "master" },
3647 { IFF_SLAVE
, "slave" },
3649 #ifdef IFF_MULTICAST
3650 { IFF_MULTICAST
, "multicast" },
3653 { IFF_PORTSEL
, "portsel" },
3655 #ifdef IFF_AUTOMEDIA
3656 { IFF_AUTOMEDIA
, "automedia" },
3659 { IFF_DYNAMIC
, "dynamic" },
3662 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3665 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3668 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3671 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3674 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3680 network_interface_info (Lisp_Object ifname
)
3683 Lisp_Object res
= Qnil
;
3688 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3689 && defined HAVE_GETIFADDRS && defined LLADDR)
3690 struct ifaddrs
*ifap
;
3693 CHECK_STRING (ifname
);
3695 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3696 error ("interface name too long");
3697 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3699 s
= socket (AF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, 0);
3702 count
= SPECPDL_INDEX ();
3703 record_unwind_protect_int (close_file_unwind
, s
);
3706 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3707 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3709 int flags
= rq
.ifr_flags
;
3710 const struct ifflag_def
*fp
;
3713 /* If flags is smaller than int (i.e. short) it may have the high bit set
3714 due to IFF_MULTICAST. In that case, sign extending it into
3716 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3717 flags
= (unsigned short) rq
.ifr_flags
;
3720 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3722 if (flags
& fp
->flag_bit
)
3724 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3725 flags
-= fp
->flag_bit
;
3728 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3732 elt
= Fcons (make_number (fnum
), elt
);
3737 res
= Fcons (elt
, res
);
3740 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3741 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3743 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3744 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3748 for (n
= 0; n
< 6; n
++)
3749 p
->contents
[n
] = make_number (((unsigned char *)
3750 &rq
.ifr_hwaddr
.sa_data
[0])
3752 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3754 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3755 if (getifaddrs (&ifap
) != -1)
3757 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3758 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3761 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3763 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3764 unsigned char linkaddr
[6];
3767 if (it
->ifa_addr
->sa_family
!= AF_LINK
3768 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3769 || sdl
->sdl_alen
!= 6)
3772 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3773 for (n
= 0; n
< 6; n
++)
3774 p
->contents
[n
] = make_number (linkaddr
[n
]);
3776 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3780 #ifdef HAVE_FREEIFADDRS
3784 #endif /* HAVE_GETIFADDRS && LLADDR */
3786 res
= Fcons (elt
, res
);
3789 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3790 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3793 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3794 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3796 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3800 res
= Fcons (elt
, res
);
3803 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3804 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3807 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3810 res
= Fcons (elt
, res
);
3813 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3814 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3817 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3820 res
= Fcons (elt
, res
);
3822 return unbind_to (count
, any
? res
: Qnil
);
3824 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3825 #endif /* defined (HAVE_NET_IF_H) */
3827 DEFUN ("network-interface-list", Fnetwork_interface_list
,
3828 Snetwork_interface_list
, 0, 0, 0,
3829 doc
: /* Return an alist of all network interfaces and their network address.
3830 Each element is a cons, the car of which is a string containing the
3831 interface name, and the cdr is the network address in internal
3832 format; see the description of ADDRESS in `make-network-process'.
3834 If the information is not available, return nil. */)
3837 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3838 return network_interface_list ();
3844 DEFUN ("network-interface-info", Fnetwork_interface_info
,
3845 Snetwork_interface_info
, 1, 1, 0,
3846 doc
: /* Return information about network interface named IFNAME.
3847 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3848 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3849 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3850 FLAGS is the current flags of the interface.
3852 Data that is unavailable is returned as nil. */)
3853 (Lisp_Object ifname
)
3855 #if ((defined HAVE_NET_IF_H \
3856 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3857 || defined SIOCGIFFLAGS)) \
3858 || defined WINDOWSNT)
3859 return network_interface_info (ifname
);
3866 /* Turn off input and output for process PROC. */
3869 deactivate_process (Lisp_Object proc
)
3872 struct Lisp_Process
*p
= XPROCESS (proc
);
3876 /* Delete GnuTLS structures in PROC, if any. */
3877 emacs_gnutls_deinit (proc
);
3878 #endif /* HAVE_GNUTLS */
3880 #ifdef ADAPTIVE_READ_BUFFERING
3881 if (p
->read_output_delay
> 0)
3883 if (--process_output_delay_count
< 0)
3884 process_output_delay_count
= 0;
3885 p
->read_output_delay
= 0;
3886 p
->read_output_skip
= 0;
3890 /* Beware SIGCHLD hereabouts. */
3892 for (i
= 0; i
< PROCESS_OPEN_FDS
; i
++)
3893 close_process_fd (&p
->open_fd
[i
]);
3895 inchannel
= p
->infd
;
3900 #ifdef DATAGRAM_SOCKETS
3901 if (DATAGRAM_CHAN_P (inchannel
))
3903 xfree (datagram_address
[inchannel
].sa
);
3904 datagram_address
[inchannel
].sa
= 0;
3905 datagram_address
[inchannel
].len
= 0;
3908 chan_process
[inchannel
] = Qnil
;
3909 FD_CLR (inchannel
, &input_wait_mask
);
3910 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3911 #ifdef NON_BLOCKING_CONNECT
3912 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3914 FD_CLR (inchannel
, &connect_wait_mask
);
3915 FD_CLR (inchannel
, &write_mask
);
3916 if (--num_pending_connects
< 0)
3920 if (inchannel
== max_process_desc
)
3922 /* We just closed the highest-numbered process input descriptor,
3923 so recompute the highest-numbered one now. */
3927 while (0 <= i
&& NILP (chan_process
[i
]));
3929 max_process_desc
= i
;
3935 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3937 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3938 It is given to their filter functions.
3939 Non-nil arg PROCESS means do not return until some output has been received
3942 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3943 and milliseconds to wait; return after that much time whether or not
3944 there is any subprocess output. If SECONDS is a floating point number,
3945 it specifies a fractional number of seconds to wait.
3946 The MILLISEC argument is obsolete and should be avoided.
3948 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3949 from PROCESS, suspending reading output from other processes.
3950 If JUST-THIS-ONE is an integer, don't run any timers either.
3951 Return non-nil if we received any output before the timeout expired. */)
3952 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
3957 if (! NILP (process
))
3958 CHECK_PROCESS (process
);
3960 just_this_one
= Qnil
;
3962 if (!NILP (millisec
))
3963 { /* Obsolete calling convention using integers rather than floats. */
3964 CHECK_NUMBER (millisec
);
3966 seconds
= make_float (XINT (millisec
) / 1000.0);
3969 CHECK_NUMBER (seconds
);
3970 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
3977 if (!NILP (seconds
))
3979 if (INTEGERP (seconds
))
3981 if (XINT (seconds
) > 0)
3983 secs
= XINT (seconds
);
3987 else if (FLOATP (seconds
))
3989 if (XFLOAT_DATA (seconds
) > 0)
3991 struct timespec t
= dtotimespec (XFLOAT_DATA (seconds
));
3992 secs
= min (t
.tv_sec
, WAIT_READING_MAX
);
3997 wrong_type_argument (Qnumberp
, seconds
);
3999 else if (! NILP (process
))
4003 (wait_reading_process_output (secs
, nsecs
, 0, 0,
4005 !NILP (process
) ? XPROCESS (process
) : NULL
,
4006 NILP (just_this_one
) ? 0 :
4007 !INTEGERP (just_this_one
) ? 1 : -1)
4011 /* Accept a connection for server process SERVER on CHANNEL. */
4013 static EMACS_INT connect_counter
= 0;
4016 server_accept_connection (Lisp_Object server
, int channel
)
4018 Lisp_Object proc
, caller
, name
, buffer
;
4019 Lisp_Object contact
, host
, service
;
4020 struct Lisp_Process
*ps
= XPROCESS (server
);
4021 struct Lisp_Process
*p
;
4025 struct sockaddr_in in
;
4027 struct sockaddr_in6 in6
;
4029 #ifdef HAVE_LOCAL_SOCKETS
4030 struct sockaddr_un un
;
4033 socklen_t len
= sizeof saddr
;
4036 s
= accept4 (channel
, &saddr
.sa
, &len
, SOCK_CLOEXEC
);
4045 if (code
== EWOULDBLOCK
)
4049 if (!NILP (ps
->log
))
4050 call3 (ps
->log
, server
, Qnil
,
4051 concat3 (build_string ("accept failed with code"),
4052 Fnumber_to_string (make_number (code
)),
4053 build_string ("\n")));
4057 count
= SPECPDL_INDEX ();
4058 record_unwind_protect_int (close_file_unwind
, s
);
4062 /* Setup a new process to handle the connection. */
4064 /* Generate a unique identification of the caller, and build contact
4065 information for this process. */
4068 switch (saddr
.sa
.sa_family
)
4072 Lisp_Object args
[5];
4073 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4074 args
[0] = build_string ("%d.%d.%d.%d");
4075 args
[1] = make_number (*ip
++);
4076 args
[2] = make_number (*ip
++);
4077 args
[3] = make_number (*ip
++);
4078 args
[4] = make_number (*ip
++);
4079 host
= Fformat (5, args
);
4080 service
= make_number (ntohs (saddr
.in
.sin_port
));
4082 args
[0] = build_string (" <%s:%d>");
4085 caller
= Fformat (3, args
);
4092 Lisp_Object args
[9];
4093 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4095 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4096 for (i
= 0; i
< 8; i
++)
4097 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4098 host
= Fformat (9, args
);
4099 service
= make_number (ntohs (saddr
.in
.sin_port
));
4101 args
[0] = build_string (" <[%s]:%d>");
4104 caller
= Fformat (3, args
);
4109 #ifdef HAVE_LOCAL_SOCKETS
4113 caller
= Fnumber_to_string (make_number (connect_counter
));
4114 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4118 /* Create a new buffer name for this process if it doesn't have a
4119 filter. The new buffer name is based on the buffer name or
4120 process name of the server process concatenated with the caller
4123 if (!(EQ (ps
->filter
, Qinternal_default_process_filter
)
4124 || EQ (ps
->filter
, Qt
)))
4128 buffer
= ps
->buffer
;
4130 buffer
= Fbuffer_name (buffer
);
4135 buffer
= concat2 (buffer
, caller
);
4136 buffer
= Fget_buffer_create (buffer
);
4140 /* Generate a unique name for the new server process. Combine the
4141 server process name with the caller identification. */
4143 name
= concat2 (ps
->name
, caller
);
4144 proc
= make_process (name
);
4146 chan_process
[s
] = proc
;
4148 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4150 p
= XPROCESS (proc
);
4152 /* Build new contact information for this setup. */
4153 contact
= Fcopy_sequence (ps
->childp
);
4154 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4155 contact
= Fplist_put (contact
, QChost
, host
);
4156 if (!NILP (service
))
4157 contact
= Fplist_put (contact
, QCservice
, service
);
4158 contact
= Fplist_put (contact
, QCremote
,
4159 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4160 #ifdef HAVE_GETSOCKNAME
4162 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4163 contact
= Fplist_put (contact
, QClocal
,
4164 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4167 pset_childp (p
, contact
);
4168 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4169 pset_type (p
, Qnetwork
);
4171 pset_buffer (p
, buffer
);
4172 pset_sentinel (p
, ps
->sentinel
);
4173 pset_filter (p
, ps
->filter
);
4174 pset_command (p
, Qnil
);
4177 /* Discard the unwind protect for closing S. */
4178 specpdl_ptr
= specpdl
+ count
;
4180 p
->open_fd
[SUBPROCESS_STDIN
] = s
;
4183 pset_status (p
, Qrun
);
4185 /* Client processes for accepted connections are not stopped initially. */
4186 if (!EQ (p
->filter
, Qt
))
4188 FD_SET (s
, &input_wait_mask
);
4189 FD_SET (s
, &non_keyboard_wait_mask
);
4192 if (s
> max_process_desc
)
4193 max_process_desc
= s
;
4195 /* Setup coding system for new process based on server process.
4196 This seems to be the proper thing to do, as the coding system
4197 of the new process should reflect the settings at the time the
4198 server socket was opened; not the current settings. */
4200 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4201 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4202 setup_process_coding_systems (proc
);
4204 pset_decoding_buf (p
, empty_unibyte_string
);
4205 p
->decoding_carryover
= 0;
4206 pset_encoding_buf (p
, empty_unibyte_string
);
4208 p
->inherit_coding_system_flag
4209 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4211 if (!NILP (ps
->log
))
4212 call3 (ps
->log
, server
, proc
,
4213 concat3 (build_string ("accept from "),
4214 (STRINGP (host
) ? host
: build_string ("-")),
4215 build_string ("\n")));
4217 exec_sentinel (proc
,
4218 concat3 (build_string ("open from "),
4219 (STRINGP (host
) ? host
: build_string ("-")),
4220 build_string ("\n")));
4223 /* This variable is different from waiting_for_input in keyboard.c.
4224 It is used to communicate to a lisp process-filter/sentinel (via the
4225 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4226 for user-input when that process-filter was called.
4227 waiting_for_input cannot be used as that is by definition 0 when
4228 lisp code is being evalled.
4229 This is also used in record_asynch_buffer_change.
4230 For that purpose, this must be 0
4231 when not inside wait_reading_process_output. */
4232 static int waiting_for_user_input_p
;
4235 wait_reading_process_output_unwind (int data
)
4237 waiting_for_user_input_p
= data
;
4240 /* This is here so breakpoints can be put on it. */
4242 wait_reading_process_output_1 (void)
4246 /* Read and dispose of subprocess output while waiting for timeout to
4247 elapse and/or keyboard input to be available.
4251 If negative, gobble data immediately available but don't wait for any.
4254 an additional duration to wait, measured in nanoseconds
4255 If TIME_LIMIT is zero, then:
4256 If NSECS == 0, there is no limit.
4257 If NSECS > 0, the timeout consists of NSECS only.
4258 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4261 0 to ignore keyboard input, or
4262 1 to return when input is available, or
4263 -1 meaning caller will actually read the input, so don't throw to
4264 the quit handler, or
4266 DO_DISPLAY means redisplay should be done to show subprocess
4267 output that arrives.
4269 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4270 (and gobble terminal input into the buffer if any arrives).
4272 If WAIT_PROC is specified, wait until something arrives from that
4273 process. The return value is true if we read some input from
4276 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4277 (suspending output from other processes). A negative value
4278 means don't run any timers either.
4280 If WAIT_PROC is specified, then the function returns true if we
4281 received input from that process before the timeout elapsed.
4282 Otherwise, return true if we received input from any process. */
4285 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4287 Lisp_Object wait_for_cell
,
4288 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4298 struct timespec timeout
, end_time
;
4299 int wait_channel
= -1;
4300 bool got_some_input
= 0;
4301 ptrdiff_t count
= SPECPDL_INDEX ();
4303 FD_ZERO (&Available
);
4306 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4307 && !(CONSP (wait_proc
->status
)
4308 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4309 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4311 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4312 if (wait_proc
!= NULL
)
4313 wait_channel
= wait_proc
->infd
;
4315 record_unwind_protect_int (wait_reading_process_output_unwind
,
4316 waiting_for_user_input_p
);
4317 waiting_for_user_input_p
= read_kbd
;
4324 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4325 time_limit
= TYPE_MAXIMUM (time_t);
4327 /* Since we may need to wait several times,
4328 compute the absolute time to return at. */
4329 if (time_limit
|| nsecs
> 0)
4331 timeout
= make_timespec (time_limit
, nsecs
);
4332 end_time
= timespec_add (current_timespec (), timeout
);
4337 bool timeout_reduced_for_timers
= 0;
4339 /* If calling from keyboard input, do not quit
4340 since we want to return C-g as an input character.
4341 Otherwise, do pending quit if requested. */
4344 else if (pending_signals
)
4345 process_pending_signals ();
4347 /* Exit now if the cell we're waiting for became non-nil. */
4348 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4351 /* Compute time from now till when time limit is up. */
4352 /* Exit if already run out. */
4355 /* A negative timeout means
4356 gobble output available now
4357 but don't wait at all. */
4359 timeout
= make_timespec (0, 0);
4361 else if (time_limit
|| nsecs
> 0)
4363 struct timespec now
= current_timespec ();
4364 if (timespec_cmp (end_time
, now
) <= 0)
4366 timeout
= timespec_sub (end_time
, now
);
4370 timeout
= make_timespec (100000, 0);
4373 /* Normally we run timers here.
4374 But not if wait_for_cell; in those cases,
4375 the wait is supposed to be short,
4376 and those callers cannot handle running arbitrary Lisp code here. */
4377 if (NILP (wait_for_cell
)
4378 && just_wait_proc
>= 0)
4380 struct timespec timer_delay
;
4384 unsigned old_timers_run
= timers_run
;
4385 struct buffer
*old_buffer
= current_buffer
;
4386 Lisp_Object old_window
= selected_window
;
4388 timer_delay
= timer_check ();
4390 /* If a timer has run, this might have changed buffers
4391 an alike. Make read_key_sequence aware of that. */
4392 if (timers_run
!= old_timers_run
4393 && (old_buffer
!= current_buffer
4394 || !EQ (old_window
, selected_window
))
4395 && waiting_for_user_input_p
== -1)
4396 record_asynch_buffer_change ();
4398 if (timers_run
!= old_timers_run
&& do_display
)
4399 /* We must retry, since a timer may have requeued itself
4400 and that could alter the time_delay. */
4401 redisplay_preserve_echo_area (9);
4405 while (!detect_input_pending ());
4407 /* If there is unread keyboard input, also return. */
4409 && requeued_events_pending_p ())
4412 /* A negative timeout means do not wait at all. */
4415 if (timespec_valid_p (timer_delay
))
4417 if (timespec_cmp (timer_delay
, timeout
) < 0)
4419 timeout
= timer_delay
;
4420 timeout_reduced_for_timers
= 1;
4425 /* This is so a breakpoint can be put here. */
4426 wait_reading_process_output_1 ();
4431 /* Cause C-g and alarm signals to take immediate action,
4432 and cause input available signals to zero out timeout.
4434 It is important that we do this before checking for process
4435 activity. If we get a SIGCHLD after the explicit checks for
4436 process activity, timeout is the only way we will know. */
4438 set_waiting_for_input (&timeout
);
4440 /* If status of something has changed, and no input is
4441 available, notify the user of the change right away. After
4442 this explicit check, we'll let the SIGCHLD handler zap
4443 timeout to get our attention. */
4444 if (update_tick
!= process_tick
)
4449 if (kbd_on_hold_p ())
4452 Atemp
= input_wait_mask
;
4455 timeout
= make_timespec (0, 0);
4456 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4458 #ifdef NON_BLOCKING_CONNECT
4459 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4463 NULL
, &timeout
, NULL
)
4466 /* It's okay for us to do this and then continue with
4467 the loop, since timeout has already been zeroed out. */
4468 clear_waiting_for_input ();
4469 status_notify (NULL
);
4470 if (do_display
) redisplay_preserve_echo_area (13);
4474 /* Don't wait for output from a non-running process. Just
4475 read whatever data has already been received. */
4476 if (wait_proc
&& wait_proc
->raw_status_new
)
4477 update_status (wait_proc
);
4479 && ! EQ (wait_proc
->status
, Qrun
)
4480 && ! EQ (wait_proc
->status
, Qconnect
))
4482 bool read_some_bytes
= 0;
4484 clear_waiting_for_input ();
4485 XSETPROCESS (proc
, wait_proc
);
4487 /* Read data from the process, until we exhaust it. */
4488 while (wait_proc
->infd
>= 0)
4490 int nread
= read_process_output (proc
, wait_proc
->infd
);
4496 got_some_input
= read_some_bytes
= 1;
4497 else if (nread
== -1 && (errno
== EIO
|| errno
== EAGAIN
))
4500 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4504 if (read_some_bytes
&& do_display
)
4505 redisplay_preserve_echo_area (10);
4510 /* Wait till there is something to do */
4512 if (wait_proc
&& just_wait_proc
)
4514 if (wait_proc
->infd
< 0) /* Terminated */
4516 FD_SET (wait_proc
->infd
, &Available
);
4520 else if (!NILP (wait_for_cell
))
4522 Available
= non_process_wait_mask
;
4529 Available
= non_keyboard_wait_mask
;
4531 Available
= input_wait_mask
;
4532 Writeok
= write_mask
;
4533 #ifdef SELECT_CANT_DO_WRITE_MASK
4538 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4541 /* If frame size has changed or the window is newly mapped,
4542 redisplay now, before we start to wait. There is a race
4543 condition here; if a SIGIO arrives between now and the select
4544 and indicates that a frame is trashed, the select may block
4545 displaying a trashed screen. */
4546 if (frame_garbaged
&& do_display
)
4548 clear_waiting_for_input ();
4549 redisplay_preserve_echo_area (11);
4551 set_waiting_for_input (&timeout
);
4554 /* Skip the `select' call if input is available and we're
4555 waiting for keyboard input or a cell change (which can be
4556 triggered by processing X events). In the latter case, set
4557 nfds to 1 to avoid breaking the loop. */
4559 if ((read_kbd
|| !NILP (wait_for_cell
))
4560 && detect_input_pending ())
4562 nfds
= read_kbd
? 0 : 1;
4569 #ifdef ADAPTIVE_READ_BUFFERING
4570 /* Set the timeout for adaptive read buffering if any
4571 process has non-zero read_output_skip and non-zero
4572 read_output_delay, and we are not reading output for a
4573 specific wait_channel. It is not executed if
4574 Vprocess_adaptive_read_buffering is nil. */
4575 if (process_output_skip
&& check_delay
> 0)
4577 int nsecs
= timeout
.tv_nsec
;
4578 if (timeout
.tv_sec
> 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4579 nsecs
= READ_OUTPUT_DELAY_MAX
;
4580 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4582 proc
= chan_process
[channel
];
4585 /* Find minimum non-zero read_output_delay among the
4586 processes with non-zero read_output_skip. */
4587 if (XPROCESS (proc
)->read_output_delay
> 0)
4590 if (!XPROCESS (proc
)->read_output_skip
)
4592 FD_CLR (channel
, &Available
);
4593 XPROCESS (proc
)->read_output_skip
= 0;
4594 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4595 nsecs
= XPROCESS (proc
)->read_output_delay
;
4598 timeout
= make_timespec (0, nsecs
);
4599 process_output_skip
= 0;
4603 #if defined (HAVE_NS)
4605 #elif defined (HAVE_GLIB)
4610 (max (max_process_desc
, max_input_desc
) + 1,
4612 (check_write
? &Writeok
: 0),
4613 NULL
, &timeout
, NULL
);
4616 /* GnuTLS buffers data internally. In lowat mode it leaves
4617 some data in the TCP buffers so that select works, but
4618 with custom pull/push functions we need to check if some
4619 data is available in the buffers manually. */
4624 /* We're not waiting on a specific process, so loop
4625 through all the channels and check for data.
4626 This is a workaround needed for some versions of
4627 the gnutls library -- 2.12.14 has been confirmed
4629 http://comments.gmane.org/gmane.emacs.devel/145074 */
4630 for (channel
= 0; channel
< FD_SETSIZE
; ++channel
)
4631 if (! NILP (chan_process
[channel
]))
4633 struct Lisp_Process
*p
=
4634 XPROCESS (chan_process
[channel
]);
4635 if (p
&& p
->gnutls_p
&& p
->gnutls_state
&& p
->infd
4636 && ((emacs_gnutls_record_check_pending
4641 FD_SET (p
->infd
, &Available
);
4647 /* Check this specific channel. */
4648 if (wait_proc
->gnutls_p
/* Check for valid process. */
4649 && wait_proc
->gnutls_state
4650 /* Do we have pending data? */
4651 && ((emacs_gnutls_record_check_pending
4652 (wait_proc
->gnutls_state
))
4656 /* Set to Available. */
4657 FD_SET (wait_proc
->infd
, &Available
);
4666 /* Make C-g and alarm signals set flags again */
4667 clear_waiting_for_input ();
4669 /* If we woke up due to SIGWINCH, actually change size now. */
4670 do_pending_window_change (0);
4672 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4673 /* We waited the full specified time, so return now. */
4677 if (xerrno
== EINTR
)
4679 else if (xerrno
== EBADF
)
4682 report_file_errno ("Failed select", Qnil
, xerrno
);
4687 FD_ZERO (&Available
);
4691 /* Check for keyboard input */
4692 /* If there is any, return immediately
4693 to give it higher priority than subprocesses */
4697 unsigned old_timers_run
= timers_run
;
4698 struct buffer
*old_buffer
= current_buffer
;
4699 Lisp_Object old_window
= selected_window
;
4702 if (detect_input_pending_run_timers (do_display
))
4704 swallow_events (do_display
);
4705 if (detect_input_pending_run_timers (do_display
))
4709 /* If a timer has run, this might have changed buffers
4710 an alike. Make read_key_sequence aware of that. */
4711 if (timers_run
!= old_timers_run
4712 && waiting_for_user_input_p
== -1
4713 && (old_buffer
!= current_buffer
4714 || !EQ (old_window
, selected_window
)))
4715 record_asynch_buffer_change ();
4721 /* If there is unread keyboard input, also return. */
4723 && requeued_events_pending_p ())
4726 /* If we are not checking for keyboard input now,
4727 do process events (but don't run any timers).
4728 This is so that X events will be processed.
4729 Otherwise they may have to wait until polling takes place.
4730 That would causes delays in pasting selections, for example.
4732 (We used to do this only if wait_for_cell.) */
4733 if (read_kbd
== 0 && detect_input_pending ())
4735 swallow_events (do_display
);
4736 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4737 if (detect_input_pending ())
4742 /* Exit now if the cell we're waiting for became non-nil. */
4743 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4747 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4748 go read it. This can happen with X on BSD after logging out.
4749 In that case, there really is no input and no SIGIO,
4750 but select says there is input. */
4752 if (read_kbd
&& interrupt_input
4753 && keyboard_bit_set (&Available
) && ! noninteractive
)
4754 handle_input_available_signal (SIGIO
);
4758 got_some_input
|= nfds
> 0;
4760 /* If checking input just got us a size-change event from X,
4761 obey it now if we should. */
4762 if (read_kbd
|| ! NILP (wait_for_cell
))
4763 do_pending_window_change (0);
4765 /* Check for data from a process. */
4766 if (no_avail
|| nfds
== 0)
4769 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4771 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4773 && ((d
->condition
& FOR_READ
4774 && FD_ISSET (channel
, &Available
))
4775 || (d
->condition
& FOR_WRITE
4776 && FD_ISSET (channel
, &write_mask
))))
4777 d
->func (channel
, d
->data
);
4780 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4782 if (FD_ISSET (channel
, &Available
)
4783 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4784 && !FD_ISSET (channel
, &non_process_wait_mask
))
4788 /* If waiting for this channel, arrange to return as
4789 soon as no more input to be processed. No more
4791 if (wait_channel
== channel
)
4797 proc
= chan_process
[channel
];
4801 /* If this is a server stream socket, accept connection. */
4802 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4804 server_accept_connection (proc
, channel
);
4808 /* Read data from the process, starting with our
4809 buffered-ahead character if we have one. */
4811 nread
= read_process_output (proc
, channel
);
4814 /* Since read_process_output can run a filter,
4815 which can call accept-process-output,
4816 don't try to read from any other processes
4817 before doing the select again. */
4818 FD_ZERO (&Available
);
4821 redisplay_preserve_echo_area (12);
4824 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4827 else if (nread
== -1 && errno
== EAGAIN
)
4830 /* FIXME: Is this special case still needed? */
4831 /* Note that we cannot distinguish between no input
4832 available now and a closed pipe.
4833 With luck, a closed pipe will be accompanied by
4834 subprocess termination and SIGCHLD. */
4835 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4839 /* On some OSs with ptys, when the process on one end of
4840 a pty exits, the other end gets an error reading with
4841 errno = EIO instead of getting an EOF (0 bytes read).
4842 Therefore, if we get an error reading and errno =
4843 EIO, just continue, because the child process has
4844 exited and should clean itself up soon (e.g. when we
4846 else if (nread
== -1 && errno
== EIO
)
4848 struct Lisp_Process
*p
= XPROCESS (proc
);
4850 /* Clear the descriptor now, so we only raise the
4852 FD_CLR (channel
, &input_wait_mask
);
4853 FD_CLR (channel
, &non_keyboard_wait_mask
);
4857 /* If the EIO occurs on a pty, the SIGCHLD handler's
4858 waitpid call will not find the process object to
4859 delete. Do it here. */
4860 p
->tick
= ++process_tick
;
4861 pset_status (p
, Qfailed
);
4864 #endif /* HAVE_PTYS */
4865 /* If we can detect process termination, don't consider the
4866 process gone just because its pipe is closed. */
4867 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4871 /* Preserve status of processes already terminated. */
4872 XPROCESS (proc
)->tick
= ++process_tick
;
4873 deactivate_process (proc
);
4874 if (XPROCESS (proc
)->raw_status_new
)
4875 update_status (XPROCESS (proc
));
4876 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4877 pset_status (XPROCESS (proc
),
4878 list2 (Qexit
, make_number (256)));
4881 #ifdef NON_BLOCKING_CONNECT
4882 if (FD_ISSET (channel
, &Writeok
)
4883 && FD_ISSET (channel
, &connect_wait_mask
))
4885 struct Lisp_Process
*p
;
4887 FD_CLR (channel
, &connect_wait_mask
);
4888 FD_CLR (channel
, &write_mask
);
4889 if (--num_pending_connects
< 0)
4892 proc
= chan_process
[channel
];
4896 p
= XPROCESS (proc
);
4899 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4900 So only use it on systems where it is known to work. */
4902 socklen_t xlen
= sizeof (xerrno
);
4903 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4908 struct sockaddr pname
;
4909 socklen_t pnamelen
= sizeof (pname
);
4911 /* If connection failed, getpeername will fail. */
4913 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4915 /* Obtain connect failure code through error slippage. */
4918 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4925 p
->tick
= ++process_tick
;
4926 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
4927 deactivate_process (proc
);
4931 pset_status (p
, Qrun
);
4932 /* Execute the sentinel here. If we had relied on
4933 status_notify to do it later, it will read input
4934 from the process before calling the sentinel. */
4935 exec_sentinel (proc
, build_string ("open\n"));
4936 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
4938 FD_SET (p
->infd
, &input_wait_mask
);
4939 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4943 #endif /* NON_BLOCKING_CONNECT */
4944 } /* End for each file descriptor. */
4945 } /* End while exit conditions not met. */
4947 unbind_to (count
, Qnil
);
4949 /* If calling from keyboard input, do not quit
4950 since we want to return C-g as an input character.
4951 Otherwise, do pending quit if requested. */
4954 /* Prevent input_pending from remaining set if we quit. */
4955 clear_input_pending ();
4959 return got_some_input
;
4962 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4965 read_process_output_call (Lisp_Object fun_and_args
)
4967 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
4971 read_process_output_error_handler (Lisp_Object error_val
)
4973 cmd_error_internal (error_val
, "error in process filter: ");
4975 update_echo_area ();
4976 Fsleep_for (make_number (2), Qnil
);
4981 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
4983 struct coding_system
*coding
);
4985 /* Read pending output from the process channel,
4986 starting with our buffered-ahead character if we have one.
4987 Yield number of decoded characters read.
4989 This function reads at most 4096 characters.
4990 If you want to read all available subprocess output,
4991 you must call it repeatedly until it returns zero.
4993 The characters read are decoded according to PROC's coding-system
4997 read_process_output (Lisp_Object proc
, register int channel
)
4999 register ssize_t nbytes
;
5001 register struct Lisp_Process
*p
= XPROCESS (proc
);
5002 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5003 int carryover
= p
->decoding_carryover
;
5005 ptrdiff_t count
= SPECPDL_INDEX ();
5006 Lisp_Object odeactivate
;
5008 chars
= alloca (carryover
+ readmax
);
5010 /* See the comment above. */
5011 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5013 #ifdef DATAGRAM_SOCKETS
5014 /* We have a working select, so proc_buffered_char is always -1. */
5015 if (DATAGRAM_CHAN_P (channel
))
5017 socklen_t len
= datagram_address
[channel
].len
;
5018 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5019 0, datagram_address
[channel
].sa
, &len
);
5024 bool buffered
= proc_buffered_char
[channel
] >= 0;
5027 chars
[carryover
] = proc_buffered_char
[channel
];
5028 proc_buffered_char
[channel
] = -1;
5031 if (p
->gnutls_p
&& p
->gnutls_state
)
5032 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5033 readmax
- buffered
);
5036 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5037 readmax
- buffered
);
5038 #ifdef ADAPTIVE_READ_BUFFERING
5039 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5041 int delay
= p
->read_output_delay
;
5044 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5047 process_output_delay_count
++;
5048 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5051 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5053 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5055 process_output_delay_count
--;
5057 p
->read_output_delay
= delay
;
5060 p
->read_output_skip
= 1;
5061 process_output_skip
= 1;
5066 nbytes
+= buffered
&& nbytes
<= 0;
5069 p
->decoding_carryover
= 0;
5071 /* At this point, NBYTES holds number of bytes just received
5072 (including the one in proc_buffered_char[channel]). */
5075 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5077 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5080 /* Now set NBYTES how many bytes we must decode. */
5081 nbytes
+= carryover
;
5083 odeactivate
= Vdeactivate_mark
;
5084 /* There's no good reason to let process filters change the current
5085 buffer, and many callers of accept-process-output, sit-for, and
5086 friends don't expect current-buffer to be changed from under them. */
5087 record_unwind_current_buffer ();
5089 read_and_dispose_of_process_output (p
, chars
, nbytes
, coding
);
5091 /* Handling the process output should not deactivate the mark. */
5092 Vdeactivate_mark
= odeactivate
;
5094 unbind_to (count
, Qnil
);
5099 read_and_dispose_of_process_output (struct Lisp_Process
*p
, char *chars
,
5101 struct coding_system
*coding
)
5103 Lisp_Object outstream
= p
->filter
;
5105 bool outer_running_asynch_code
= running_asynch_code
;
5106 int waiting
= waiting_for_user_input_p
;
5108 /* No need to gcpro these, because all we do with them later
5109 is test them for EQness, and none of them should be a string. */
5111 Lisp_Object obuffer
, okeymap
;
5112 XSETBUFFER (obuffer
, current_buffer
);
5113 okeymap
= BVAR (current_buffer
, keymap
);
5116 /* We inhibit quit here instead of just catching it so that
5117 hitting ^G when a filter happens to be running won't screw
5119 specbind (Qinhibit_quit
, Qt
);
5120 specbind (Qlast_nonmenu_event
, Qt
);
5122 /* In case we get recursively called,
5123 and we already saved the match data nonrecursively,
5124 save the same match data in safely recursive fashion. */
5125 if (outer_running_asynch_code
)
5128 /* Don't clobber the CURRENT match data, either! */
5129 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5130 restore_search_regs ();
5131 record_unwind_save_match_data ();
5132 Fset_match_data (tem
, Qt
);
5135 /* For speed, if a search happens within this code,
5136 save the match data in a special nonrecursive fashion. */
5137 running_asynch_code
= 1;
5139 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5140 text
= coding
->dst_object
;
5141 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5142 /* A new coding system might be found. */
5143 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5145 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5147 /* Don't call setup_coding_system for
5148 proc_decode_coding_system[channel] here. It is done in
5149 detect_coding called via decode_coding above. */
5151 /* If a coding system for encoding is not yet decided, we set
5152 it as the same as coding-system for decoding.
5154 But, before doing that we must check if
5155 proc_encode_coding_system[p->outfd] surely points to a
5156 valid memory because p->outfd will be changed once EOF is
5157 sent to the process. */
5158 if (NILP (p
->encode_coding_system
)
5159 && proc_encode_coding_system
[p
->outfd
])
5161 pset_encode_coding_system
5162 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5163 setup_coding_system (p
->encode_coding_system
,
5164 proc_encode_coding_system
[p
->outfd
]);
5168 if (coding
->carryover_bytes
> 0)
5170 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5171 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5172 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5173 coding
->carryover_bytes
);
5174 p
->decoding_carryover
= coding
->carryover_bytes
;
5176 if (SBYTES (text
) > 0)
5177 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5178 sometimes it's simply wrong to wrap (e.g. when called from
5179 accept-process-output). */
5180 internal_condition_case_1 (read_process_output_call
,
5181 list3 (outstream
, make_lisp_proc (p
), text
),
5182 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5183 read_process_output_error_handler
);
5185 /* If we saved the match data nonrecursively, restore it now. */
5186 restore_search_regs ();
5187 running_asynch_code
= outer_running_asynch_code
;
5189 /* Restore waiting_for_user_input_p as it was
5190 when we were called, in case the filter clobbered it. */
5191 waiting_for_user_input_p
= waiting
;
5193 #if 0 /* Call record_asynch_buffer_change unconditionally,
5194 because we might have changed minor modes or other things
5195 that affect key bindings. */
5196 if (! EQ (Fcurrent_buffer (), obuffer
)
5197 || ! EQ (current_buffer
->keymap
, okeymap
))
5199 /* But do it only if the caller is actually going to read events.
5200 Otherwise there's no need to make him wake up, and it could
5201 cause trouble (for example it would make sit_for return). */
5202 if (waiting_for_user_input_p
== -1)
5203 record_asynch_buffer_change ();
5206 DEFUN ("internal-default-process-filter", Finternal_default_process_filter
,
5207 Sinternal_default_process_filter
, 2, 2, 0,
5208 doc
: /* Function used as default process filter.
5209 This inserts the process's output into its buffer, if there is one.
5210 Otherwise it discards the output. */)
5211 (Lisp_Object proc
, Lisp_Object text
)
5213 struct Lisp_Process
*p
;
5216 CHECK_PROCESS (proc
);
5217 p
= XPROCESS (proc
);
5218 CHECK_STRING (text
);
5220 if (!NILP (p
->buffer
) && BUFFER_LIVE_P (XBUFFER (p
->buffer
)))
5222 Lisp_Object old_read_only
;
5223 ptrdiff_t old_begv
, old_zv
;
5224 ptrdiff_t old_begv_byte
, old_zv_byte
;
5225 ptrdiff_t before
, before_byte
;
5226 ptrdiff_t opoint_byte
;
5229 Fset_buffer (p
->buffer
);
5231 opoint_byte
= PT_BYTE
;
5232 old_read_only
= BVAR (current_buffer
, read_only
);
5235 old_begv_byte
= BEGV_BYTE
;
5236 old_zv_byte
= ZV_BYTE
;
5238 bset_read_only (current_buffer
, Qnil
);
5240 /* Insert new output into buffer at the current end-of-output
5241 marker, thus preserving logical ordering of input and output. */
5242 if (XMARKER (p
->mark
)->buffer
)
5243 set_point_from_marker (p
->mark
);
5245 SET_PT_BOTH (ZV
, ZV_BYTE
);
5247 before_byte
= PT_BYTE
;
5249 /* If the output marker is outside of the visible region, save
5250 the restriction and widen. */
5251 if (! (BEGV
<= PT
&& PT
<= ZV
))
5254 /* Adjust the multibyteness of TEXT to that of the buffer. */
5255 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5256 != ! STRING_MULTIBYTE (text
))
5257 text
= (STRING_MULTIBYTE (text
)
5258 ? Fstring_as_unibyte (text
)
5259 : Fstring_to_multibyte (text
));
5260 /* Insert before markers in case we are inserting where
5261 the buffer's mark is, and the user's next command is Meta-y. */
5262 insert_from_string_before_markers (text
, 0, 0,
5263 SCHARS (text
), SBYTES (text
), 0);
5265 /* Make sure the process marker's position is valid when the
5266 process buffer is changed in the signal_after_change above.
5267 W3 is known to do that. */
5268 if (BUFFERP (p
->buffer
)
5269 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5270 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5272 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5274 update_mode_lines
= 23;
5276 /* Make sure opoint and the old restrictions
5277 float ahead of any new text just as point would. */
5278 if (opoint
>= before
)
5280 opoint
+= PT
- before
;
5281 opoint_byte
+= PT_BYTE
- before_byte
;
5283 if (old_begv
> before
)
5285 old_begv
+= PT
- before
;
5286 old_begv_byte
+= PT_BYTE
- before_byte
;
5288 if (old_zv
>= before
)
5290 old_zv
+= PT
- before
;
5291 old_zv_byte
+= PT_BYTE
- before_byte
;
5294 /* If the restriction isn't what it should be, set it. */
5295 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5296 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5298 bset_read_only (current_buffer
, old_read_only
);
5299 SET_PT_BOTH (opoint
, opoint_byte
);
5304 /* Sending data to subprocess. */
5306 /* In send_process, when a write fails temporarily,
5307 wait_reading_process_output is called. It may execute user code,
5308 e.g. timers, that attempts to write new data to the same process.
5309 We must ensure that data is sent in the right order, and not
5310 interspersed half-completed with other writes (Bug#10815). This is
5311 handled by the write_queue element of struct process. It is a list
5312 with each entry having the form
5314 (string . (offset . length))
5316 where STRING is a lisp string, OFFSET is the offset into the
5317 string's byte sequence from which we should begin to send, and
5318 LENGTH is the number of bytes left to send. */
5320 /* Create a new entry in write_queue.
5321 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5322 BUF is a pointer to the string sequence of the input_obj or a C
5323 string in case of Qt or Qnil. */
5326 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5327 const char *buf
, ptrdiff_t len
, bool front
)
5330 Lisp_Object entry
, obj
;
5332 if (STRINGP (input_obj
))
5334 offset
= buf
- SSDATA (input_obj
);
5340 obj
= make_unibyte_string (buf
, len
);
5343 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5346 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5348 pset_write_queue (p
, nconc2 (p
->write_queue
, list1 (entry
)));
5351 /* Remove the first element in the write_queue of process P, put its
5352 contents in OBJ, BUF and LEN, and return true. If the
5353 write_queue is empty, return false. */
5356 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5357 const char **buf
, ptrdiff_t *len
)
5359 Lisp_Object entry
, offset_length
;
5362 if (NILP (p
->write_queue
))
5365 entry
= XCAR (p
->write_queue
);
5366 pset_write_queue (p
, XCDR (p
->write_queue
));
5368 *obj
= XCAR (entry
);
5369 offset_length
= XCDR (entry
);
5371 *len
= XINT (XCDR (offset_length
));
5372 offset
= XINT (XCAR (offset_length
));
5373 *buf
= SSDATA (*obj
) + offset
;
5378 /* Send some data to process PROC.
5379 BUF is the beginning of the data; LEN is the number of characters.
5380 OBJECT is the Lisp object that the data comes from. If OBJECT is
5381 nil or t, it means that the data comes from C string.
5383 If OBJECT is not nil, the data is encoded by PROC's coding-system
5384 for encoding before it is sent.
5386 This function can evaluate Lisp code and can garbage collect. */
5389 send_process (Lisp_Object proc
, const char *buf
, ptrdiff_t len
,
5392 struct Lisp_Process
*p
= XPROCESS (proc
);
5394 struct coding_system
*coding
;
5396 if (p
->raw_status_new
)
5398 if (! EQ (p
->status
, Qrun
))
5399 error ("Process %s not running", SDATA (p
->name
));
5401 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5403 coding
= proc_encode_coding_system
[p
->outfd
];
5404 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5406 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5407 || (BUFFERP (object
)
5408 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5411 pset_encode_coding_system
5412 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5413 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5415 /* The coding system for encoding was changed to raw-text
5416 because we sent a unibyte text previously. Now we are
5417 sending a multibyte text, thus we must encode it by the
5418 original coding system specified for the current process.
5420 Another reason we come here is that the coding system
5421 was just complemented and a new one was returned by
5422 complement_process_encoding_system. */
5423 setup_coding_system (p
->encode_coding_system
, coding
);
5424 Vlast_coding_system_used
= p
->encode_coding_system
;
5426 coding
->src_multibyte
= 1;
5430 coding
->src_multibyte
= 0;
5431 /* For sending a unibyte text, character code conversion should
5432 not take place but EOL conversion should. So, setup raw-text
5433 or one of the subsidiary if we have not yet done it. */
5434 if (CODING_REQUIRE_ENCODING (coding
))
5436 if (CODING_REQUIRE_FLUSHING (coding
))
5438 /* But, before changing the coding, we must flush out data. */
5439 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5440 send_process (proc
, "", 0, Qt
);
5441 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5443 setup_coding_system (raw_text_coding_system
5444 (Vlast_coding_system_used
),
5446 coding
->src_multibyte
= 0;
5449 coding
->dst_multibyte
= 0;
5451 if (CODING_REQUIRE_ENCODING (coding
))
5453 coding
->dst_object
= Qt
;
5454 if (BUFFERP (object
))
5456 ptrdiff_t from_byte
, from
, to
;
5457 ptrdiff_t save_pt
, save_pt_byte
;
5458 struct buffer
*cur
= current_buffer
;
5460 set_buffer_internal (XBUFFER (object
));
5461 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5463 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5464 from
= BYTE_TO_CHAR (from_byte
);
5465 to
= BYTE_TO_CHAR (from_byte
+ len
);
5466 TEMP_SET_PT_BOTH (from
, from_byte
);
5467 encode_coding_object (coding
, object
, from
, from_byte
,
5468 to
, from_byte
+ len
, Qt
);
5469 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5470 set_buffer_internal (cur
);
5472 else if (STRINGP (object
))
5474 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5475 SBYTES (object
), Qt
);
5479 coding
->dst_object
= make_unibyte_string (buf
, len
);
5480 coding
->produced
= len
;
5483 len
= coding
->produced
;
5484 object
= coding
->dst_object
;
5485 buf
= SSDATA (object
);
5488 /* If there is already data in the write_queue, put the new data
5489 in the back of queue. Otherwise, ignore it. */
5490 if (!NILP (p
->write_queue
))
5491 write_queue_push (p
, object
, buf
, len
, 0);
5493 do /* while !NILP (p->write_queue) */
5495 ptrdiff_t cur_len
= -1;
5496 const char *cur_buf
;
5497 Lisp_Object cur_object
;
5499 /* If write_queue is empty, ignore it. */
5500 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5504 cur_object
= object
;
5509 /* Send this batch, using one or more write calls. */
5510 ptrdiff_t written
= 0;
5511 int outfd
= p
->outfd
;
5512 #ifdef DATAGRAM_SOCKETS
5513 if (DATAGRAM_CHAN_P (outfd
))
5515 rv
= sendto (outfd
, cur_buf
, cur_len
,
5516 0, datagram_address
[outfd
].sa
,
5517 datagram_address
[outfd
].len
);
5520 else if (errno
== EMSGSIZE
)
5521 report_file_error ("Sending datagram", proc
);
5527 if (p
->gnutls_p
&& p
->gnutls_state
)
5528 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5531 written
= emacs_write_sig (outfd
, cur_buf
, cur_len
);
5532 rv
= (written
? 0 : -1);
5533 #ifdef ADAPTIVE_READ_BUFFERING
5534 if (p
->read_output_delay
> 0
5535 && p
->adaptive_read_buffering
== 1)
5537 p
->read_output_delay
= 0;
5538 process_output_delay_count
--;
5539 p
->read_output_skip
= 0;
5548 || errno
== EWOULDBLOCK
5551 /* Buffer is full. Wait, accepting input;
5552 that may allow the program
5553 to finish doing output and read more. */
5555 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5556 /* A gross hack to work around a bug in FreeBSD.
5557 In the following sequence, read(2) returns
5561 write(2) 954 bytes, get EAGAIN
5562 read(2) 1024 bytes in process_read_output
5563 read(2) 11 bytes in process_read_output
5565 That is, read(2) returns more bytes than have
5566 ever been written successfully. The 1033 bytes
5567 read are the 1022 bytes written successfully
5568 after processing (for example with CRs added if
5569 the terminal is set up that way which it is
5570 here). The same bytes will be seen again in a
5571 later read(2), without the CRs. */
5573 if (errno
== EAGAIN
)
5576 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5578 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5580 /* Put what we should have written in wait_queue. */
5581 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5582 wait_reading_process_output (0, 20 * 1000 * 1000,
5583 0, 0, Qnil
, NULL
, 0);
5584 /* Reread queue, to see what is left. */
5587 else if (errno
== EPIPE
)
5589 p
->raw_status_new
= 0;
5590 pset_status (p
, list2 (Qexit
, make_number (256)));
5591 p
->tick
= ++process_tick
;
5592 deactivate_process (proc
);
5593 error ("process %s no longer connected to pipe; closed it",
5597 /* This is a real error. */
5598 report_file_error ("Writing to process", proc
);
5604 while (!NILP (p
->write_queue
));
5607 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5609 doc
: /* Send current contents of region as input to PROCESS.
5610 PROCESS may be a process, a buffer, the name of a process or buffer, or
5611 nil, indicating the current buffer's process.
5612 Called from program, takes three arguments, PROCESS, START and END.
5613 If the region is more than 500 characters long,
5614 it is sent in several bunches. This may happen even for shorter regions.
5615 Output from processes can arrive in between bunches. */)
5616 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5618 Lisp_Object proc
= get_process (process
);
5619 ptrdiff_t start_byte
, end_byte
;
5621 validate_region (&start
, &end
);
5623 start_byte
= CHAR_TO_BYTE (XINT (start
));
5624 end_byte
= CHAR_TO_BYTE (XINT (end
));
5626 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5627 move_gap_both (XINT (start
), start_byte
);
5629 send_process (proc
, (char *) BYTE_POS_ADDR (start_byte
),
5630 end_byte
- start_byte
, Fcurrent_buffer ());
5635 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5637 doc
: /* Send PROCESS the contents of STRING as input.
5638 PROCESS may be a process, a buffer, the name of a process or buffer, or
5639 nil, indicating the current buffer's process.
5640 If STRING is more than 500 characters long,
5641 it is sent in several bunches. This may happen even for shorter strings.
5642 Output from processes can arrive in between bunches. */)
5643 (Lisp_Object process
, Lisp_Object string
)
5646 CHECK_STRING (string
);
5647 proc
= get_process (process
);
5648 send_process (proc
, SSDATA (string
),
5649 SBYTES (string
), string
);
5653 /* Return the foreground process group for the tty/pty that
5654 the process P uses. */
5656 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5661 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5664 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5665 master side. Try the slave side. */
5666 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5670 ioctl (fd
, TIOCGPGRP
, &gid
);
5674 #endif /* defined (TIOCGPGRP ) */
5679 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5680 Sprocess_running_child_p
, 0, 1, 0,
5681 doc
: /* Return t if PROCESS has given the terminal to a child.
5682 If the operating system does not make it possible to find out,
5683 return t unconditionally. */)
5684 (Lisp_Object process
)
5686 /* Initialize in case ioctl doesn't exist or gives an error,
5687 in a way that will cause returning t. */
5690 struct Lisp_Process
*p
;
5692 proc
= get_process (process
);
5693 p
= XPROCESS (proc
);
5695 if (!EQ (p
->type
, Qreal
))
5696 error ("Process %s is not a subprocess",
5699 error ("Process %s is not active",
5702 gid
= emacs_get_tty_pgrp (p
);
5709 /* send a signal number SIGNO to PROCESS.
5710 If CURRENT_GROUP is t, that means send to the process group
5711 that currently owns the terminal being used to communicate with PROCESS.
5712 This is used for various commands in shell mode.
5713 If CURRENT_GROUP is lambda, that means send to the process group
5714 that currently owns the terminal, but only if it is NOT the shell itself.
5716 If NOMSG is false, insert signal-announcements into process's buffers
5719 If we can, we try to signal PROCESS by sending control characters
5720 down the pty. This allows us to signal inferiors who have changed
5721 their uid, for which kill would return an EPERM error. */
5724 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5728 struct Lisp_Process
*p
;
5732 proc
= get_process (process
);
5733 p
= XPROCESS (proc
);
5735 if (!EQ (p
->type
, Qreal
))
5736 error ("Process %s is not a subprocess",
5739 error ("Process %s is not active",
5743 current_group
= Qnil
;
5745 /* If we are using pgrps, get a pgrp number and make it negative. */
5746 if (NILP (current_group
))
5747 /* Send the signal to the shell's process group. */
5751 #ifdef SIGNALS_VIA_CHARACTERS
5752 /* If possible, send signals to the entire pgrp
5753 by sending an input character to it. */
5756 cc_t
*sig_char
= NULL
;
5758 tcgetattr (p
->infd
, &t
);
5763 sig_char
= &t
.c_cc
[VINTR
];
5767 sig_char
= &t
.c_cc
[VQUIT
];
5771 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5772 sig_char
= &t
.c_cc
[VSWTCH
];
5774 sig_char
= &t
.c_cc
[VSUSP
];
5779 if (sig_char
&& *sig_char
!= CDISABLE
)
5781 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5784 /* If we can't send the signal with a character,
5785 fall through and send it another way. */
5787 /* The code above may fall through if it can't
5788 handle the signal. */
5789 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5792 /* Get the current pgrp using the tty itself, if we have that.
5793 Otherwise, use the pty to get the pgrp.
5794 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5795 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5796 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5797 His patch indicates that if TIOCGPGRP returns an error, then
5798 we should just assume that p->pid is also the process group id. */
5800 gid
= emacs_get_tty_pgrp (p
);
5803 /* If we can't get the information, assume
5804 the shell owns the tty. */
5807 /* It is not clear whether anything really can set GID to -1.
5808 Perhaps on some system one of those ioctls can or could do so.
5809 Or perhaps this is vestigial. */
5812 #else /* ! defined (TIOCGPGRP ) */
5813 /* Can't select pgrps on this system, so we know that
5814 the child itself heads the pgrp. */
5816 #endif /* ! defined (TIOCGPGRP ) */
5818 /* If current_group is lambda, and the shell owns the terminal,
5819 don't send any signal. */
5820 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5825 if (signo
== SIGCONT
)
5827 p
->raw_status_new
= 0;
5828 pset_status (p
, Qrun
);
5829 p
->tick
= ++process_tick
;
5832 status_notify (NULL
);
5833 redisplay_preserve_echo_area (13);
5838 /* If we don't have process groups, send the signal to the immediate
5839 subprocess. That isn't really right, but it's better than any
5840 obvious alternative. */
5843 kill (p
->pid
, signo
);
5847 /* gid may be a pid, or minus a pgrp's number */
5849 if (!NILP (current_group
))
5851 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
5859 #else /* ! defined (TIOCSIGSEND) */
5861 #endif /* ! defined (TIOCSIGSEND) */
5864 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5865 doc
: /* Interrupt process PROCESS.
5866 PROCESS may be a process, a buffer, or the name of a process or buffer.
5867 No arg or nil means current buffer's process.
5868 Second arg CURRENT-GROUP non-nil means send signal to
5869 the current process-group of the process's controlling terminal
5870 rather than to the process's own process group.
5871 If the process is a shell, this means interrupt current subjob
5872 rather than the shell.
5874 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5875 don't send the signal. */)
5876 (Lisp_Object process
, Lisp_Object current_group
)
5878 process_send_signal (process
, SIGINT
, current_group
, 0);
5882 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5883 doc
: /* Kill process PROCESS. May be process or name of one.
5884 See function `interrupt-process' for more details on usage. */)
5885 (Lisp_Object process
, Lisp_Object current_group
)
5887 process_send_signal (process
, SIGKILL
, current_group
, 0);
5891 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5892 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5893 See function `interrupt-process' for more details on usage. */)
5894 (Lisp_Object process
, Lisp_Object current_group
)
5896 process_send_signal (process
, SIGQUIT
, current_group
, 0);
5900 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
5901 doc
: /* Stop process PROCESS. May be process or name of one.
5902 See function `interrupt-process' for more details on usage.
5903 If PROCESS is a network or serial process, inhibit handling of incoming
5905 (Lisp_Object process
, Lisp_Object current_group
)
5907 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5909 struct Lisp_Process
*p
;
5911 p
= XPROCESS (process
);
5912 if (NILP (p
->command
)
5915 FD_CLR (p
->infd
, &input_wait_mask
);
5916 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
5918 pset_command (p
, Qt
);
5922 error ("No SIGTSTP support");
5924 process_send_signal (process
, SIGTSTP
, current_group
, 0);
5929 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
5930 doc
: /* Continue process PROCESS. May be process or name of one.
5931 See function `interrupt-process' for more details on usage.
5932 If PROCESS is a network or serial process, resume handling of incoming
5934 (Lisp_Object process
, Lisp_Object current_group
)
5936 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
5938 struct Lisp_Process
*p
;
5940 p
= XPROCESS (process
);
5941 if (EQ (p
->command
, Qt
)
5943 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
5945 FD_SET (p
->infd
, &input_wait_mask
);
5946 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5948 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
5949 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
5950 #else /* not WINDOWSNT */
5951 tcflush (p
->infd
, TCIFLUSH
);
5952 #endif /* not WINDOWSNT */
5954 pset_command (p
, Qnil
);
5958 process_send_signal (process
, SIGCONT
, current_group
, 0);
5960 error ("No SIGCONT support");
5965 /* Return the integer value of the signal whose abbreviation is ABBR,
5966 or a negative number if there is no such signal. */
5968 abbr_to_signal (char const *name
)
5971 char sigbuf
[20]; /* Large enough for all valid signal abbreviations. */
5973 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
5976 for (i
= 0; i
< sizeof sigbuf
; i
++)
5978 sigbuf
[i
] = c_toupper (name
[i
]);
5980 return str2sig (sigbuf
, &signo
) == 0 ? signo
: -1;
5986 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
5987 2, 2, "sProcess (name or number): \nnSignal code: ",
5988 doc
: /* Send PROCESS the signal with code SIGCODE.
5989 PROCESS may also be a number specifying the process id of the
5990 process to signal; in this case, the process need not be a child of
5992 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5993 (Lisp_Object process
, Lisp_Object sigcode
)
5998 if (STRINGP (process
))
6000 Lisp_Object tem
= Fget_process (process
);
6003 Lisp_Object process_number
=
6004 string_to_number (SSDATA (process
), 10, 1);
6005 if (INTEGERP (process_number
) || FLOATP (process_number
))
6006 tem
= process_number
;
6010 else if (!NUMBERP (process
))
6011 process
= get_process (process
);
6016 if (NUMBERP (process
))
6017 CONS_TO_INTEGER (process
, pid_t
, pid
);
6020 CHECK_PROCESS (process
);
6021 pid
= XPROCESS (process
)->pid
;
6023 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6026 if (INTEGERP (sigcode
))
6028 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6029 signo
= XINT (sigcode
);
6035 CHECK_SYMBOL (sigcode
);
6036 name
= SSDATA (SYMBOL_NAME (sigcode
));
6038 signo
= abbr_to_signal (name
);
6040 error ("Undefined signal name %s", name
);
6043 return make_number (kill (pid
, signo
));
6046 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6047 doc
: /* Make PROCESS see end-of-file in its input.
6048 EOF comes after any text already sent to it.
6049 PROCESS may be a process, a buffer, the name of a process or buffer, or
6050 nil, indicating the current buffer's process.
6051 If PROCESS is a network connection, or is a process communicating
6052 through a pipe (as opposed to a pty), then you cannot send any more
6053 text to PROCESS after you call this function.
6054 If PROCESS is a serial process, wait until all output written to the
6055 process has been transmitted to the serial port. */)
6056 (Lisp_Object process
)
6059 struct coding_system
*coding
= NULL
;
6062 if (DATAGRAM_CONN_P (process
))
6065 proc
= get_process (process
);
6066 outfd
= XPROCESS (proc
)->outfd
;
6068 coding
= proc_encode_coding_system
[outfd
];
6070 /* Make sure the process is really alive. */
6071 if (XPROCESS (proc
)->raw_status_new
)
6072 update_status (XPROCESS (proc
));
6073 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6074 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6076 if (coding
&& CODING_REQUIRE_FLUSHING (coding
))
6078 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6079 send_process (proc
, "", 0, Qnil
);
6082 if (XPROCESS (proc
)->pty_flag
)
6083 send_process (proc
, "\004", 1, Qnil
);
6084 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6087 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6088 report_file_error ("Failed tcdrain", Qnil
);
6089 #endif /* not WINDOWSNT */
6090 /* Do nothing on Windows because writes are blocking. */
6094 struct Lisp_Process
*p
= XPROCESS (proc
);
6095 int old_outfd
= p
->outfd
;
6098 #ifdef HAVE_SHUTDOWN
6099 /* If this is a network connection, or socketpair is used
6100 for communication with the subprocess, call shutdown to cause EOF.
6101 (In some old system, shutdown to socketpair doesn't work.
6102 Then we just can't win.) */
6103 if (EQ (p
->type
, Qnetwork
)
6104 || p
->infd
== old_outfd
)
6105 shutdown (old_outfd
, 1);
6107 close_process_fd (&p
->open_fd
[WRITE_TO_SUBPROCESS
]);
6108 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6110 report_file_error ("Opening null device", Qnil
);
6111 p
->open_fd
[WRITE_TO_SUBPROCESS
] = new_outfd
;
6112 p
->outfd
= new_outfd
;
6114 if (!proc_encode_coding_system
[new_outfd
])
6115 proc_encode_coding_system
[new_outfd
]
6116 = xmalloc (sizeof (struct coding_system
));
6119 *proc_encode_coding_system
[new_outfd
]
6120 = *proc_encode_coding_system
[old_outfd
];
6121 memset (proc_encode_coding_system
[old_outfd
], 0,
6122 sizeof (struct coding_system
));
6125 setup_coding_system (p
->encode_coding_system
,
6126 proc_encode_coding_system
[new_outfd
]);
6131 /* The main Emacs thread records child processes in three places:
6133 - Vprocess_alist, for asynchronous subprocesses, which are child
6134 processes visible to Lisp.
6136 - deleted_pid_list, for child processes invisible to Lisp,
6137 typically because of delete-process. These are recorded so that
6138 the processes can be reaped when they exit, so that the operating
6139 system's process table is not cluttered by zombies.
6141 - the local variable PID in Fcall_process, call_process_cleanup and
6142 call_process_kill, for synchronous subprocesses.
6143 record_unwind_protect is used to make sure this process is not
6144 forgotten: if the user interrupts call-process and the child
6145 process refuses to exit immediately even with two C-g's,
6146 call_process_kill adds PID's contents to deleted_pid_list before
6149 The main Emacs thread invokes waitpid only on child processes that
6150 it creates and that have not been reaped. This avoid races on
6151 platforms such as GTK, where other threads create their own
6152 subprocesses which the main thread should not reap. For example,
6153 if the main thread attempted to reap an already-reaped child, it
6154 might inadvertently reap a GTK-created process that happened to
6155 have the same process ID. */
6157 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6158 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6159 keep track of its own children. GNUstep is similar. */
6161 static void dummy_handler (int sig
) {}
6162 static signal_handler_t
volatile lib_child_handler
;
6164 /* Handle a SIGCHLD signal by looking for known child processes of
6165 Emacs whose status have changed. For each one found, record its
6168 All we do is change the status; we do not run sentinels or print
6169 notifications. That is saved for the next time keyboard input is
6170 done, in order to avoid timing errors.
6172 ** WARNING: this can be called during garbage collection.
6173 Therefore, it must not be fooled by the presence of mark bits in
6176 ** USG WARNING: Although it is not obvious from the documentation
6177 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6178 signal() before executing at least one wait(), otherwise the
6179 handler will be called again, resulting in an infinite loop. The
6180 relevant portion of the documentation reads "SIGCLD signals will be
6181 queued and the signal-catching function will be continually
6182 reentered until the queue is empty". Invoking signal() causes the
6183 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6186 ** Malloc WARNING: This should never call malloc either directly or
6187 indirectly; if it does, that is a bug */
6190 handle_child_signal (int sig
)
6192 Lisp_Object tail
, proc
;
6194 /* Find the process that signaled us, and record its status. */
6196 /* The process can have been deleted by Fdelete_process, or have
6197 been started asynchronously by Fcall_process. */
6198 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6200 bool all_pids_are_fixnums
6201 = (MOST_NEGATIVE_FIXNUM
<= TYPE_MINIMUM (pid_t
)
6202 && TYPE_MAXIMUM (pid_t
) <= MOST_POSITIVE_FIXNUM
);
6203 Lisp_Object head
= XCAR (tail
);
6208 if (all_pids_are_fixnums
? INTEGERP (xpid
) : NUMBERP (xpid
))
6211 if (INTEGERP (xpid
))
6212 deleted_pid
= XINT (xpid
);
6214 deleted_pid
= XFLOAT_DATA (xpid
);
6215 if (child_status_changed (deleted_pid
, 0, 0))
6217 if (STRINGP (XCDR (head
)))
6218 unlink (SSDATA (XCDR (head
)));
6219 XSETCAR (tail
, Qnil
);
6224 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6225 FOR_EACH_PROCESS (tail
, proc
)
6227 struct Lisp_Process
*p
= XPROCESS (proc
);
6231 && child_status_changed (p
->pid
, &status
, WUNTRACED
| WCONTINUED
))
6233 /* Change the status of the process that was found. */
6234 p
->tick
= ++process_tick
;
6235 p
->raw_status
= status
;
6236 p
->raw_status_new
= 1;
6238 /* If process has terminated, stop waiting for its output. */
6239 if (WIFSIGNALED (status
) || WIFEXITED (status
))
6241 bool clear_desc_flag
= 0;
6244 clear_desc_flag
= 1;
6246 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6247 if (clear_desc_flag
)
6249 FD_CLR (p
->infd
, &input_wait_mask
);
6250 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6256 lib_child_handler (sig
);
6257 #ifdef NS_IMPL_GNUSTEP
6258 /* NSTask in GNUstep sets its child handler each time it is called.
6259 So we must re-set ours. */
6260 catch_child_signal();
6265 deliver_child_signal (int sig
)
6267 deliver_process_signal (sig
, handle_child_signal
);
6272 exec_sentinel_error_handler (Lisp_Object error_val
)
6274 cmd_error_internal (error_val
, "error in process sentinel: ");
6276 update_echo_area ();
6277 Fsleep_for (make_number (2), Qnil
);
6282 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6284 Lisp_Object sentinel
, odeactivate
;
6285 struct Lisp_Process
*p
= XPROCESS (proc
);
6286 ptrdiff_t count
= SPECPDL_INDEX ();
6287 bool outer_running_asynch_code
= running_asynch_code
;
6288 int waiting
= waiting_for_user_input_p
;
6290 if (inhibit_sentinels
)
6293 /* No need to gcpro these, because all we do with them later
6294 is test them for EQness, and none of them should be a string. */
6295 odeactivate
= Vdeactivate_mark
;
6297 Lisp_Object obuffer
, okeymap
;
6298 XSETBUFFER (obuffer
, current_buffer
);
6299 okeymap
= BVAR (current_buffer
, keymap
);
6302 /* There's no good reason to let sentinels change the current
6303 buffer, and many callers of accept-process-output, sit-for, and
6304 friends don't expect current-buffer to be changed from under them. */
6305 record_unwind_current_buffer ();
6307 sentinel
= p
->sentinel
;
6309 /* Inhibit quit so that random quits don't screw up a running filter. */
6310 specbind (Qinhibit_quit
, Qt
);
6311 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6313 /* In case we get recursively called,
6314 and we already saved the match data nonrecursively,
6315 save the same match data in safely recursive fashion. */
6316 if (outer_running_asynch_code
)
6319 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6320 restore_search_regs ();
6321 record_unwind_save_match_data ();
6322 Fset_match_data (tem
, Qt
);
6325 /* For speed, if a search happens within this code,
6326 save the match data in a special nonrecursive fashion. */
6327 running_asynch_code
= 1;
6329 internal_condition_case_1 (read_process_output_call
,
6330 list3 (sentinel
, proc
, reason
),
6331 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6332 exec_sentinel_error_handler
);
6334 /* If we saved the match data nonrecursively, restore it now. */
6335 restore_search_regs ();
6336 running_asynch_code
= outer_running_asynch_code
;
6338 Vdeactivate_mark
= odeactivate
;
6340 /* Restore waiting_for_user_input_p as it was
6341 when we were called, in case the filter clobbered it. */
6342 waiting_for_user_input_p
= waiting
;
6345 if (! EQ (Fcurrent_buffer (), obuffer
)
6346 || ! EQ (current_buffer
->keymap
, okeymap
))
6348 /* But do it only if the caller is actually going to read events.
6349 Otherwise there's no need to make him wake up, and it could
6350 cause trouble (for example it would make sit_for return). */
6351 if (waiting_for_user_input_p
== -1)
6352 record_asynch_buffer_change ();
6354 unbind_to (count
, Qnil
);
6357 /* Report all recent events of a change in process status
6358 (either run the sentinel or output a message).
6359 This is usually done while Emacs is waiting for keyboard input
6360 but can be done at other times. */
6363 status_notify (struct Lisp_Process
*deleting_process
)
6365 register Lisp_Object proc
;
6366 Lisp_Object tail
, msg
;
6367 struct gcpro gcpro1
, gcpro2
;
6371 /* We need to gcpro tail; if read_process_output calls a filter
6372 which deletes a process and removes the cons to which tail points
6373 from Vprocess_alist, and then causes a GC, tail is an unprotected
6377 /* Set this now, so that if new processes are created by sentinels
6378 that we run, we get called again to handle their status changes. */
6379 update_tick
= process_tick
;
6381 FOR_EACH_PROCESS (tail
, proc
)
6384 register struct Lisp_Process
*p
= XPROCESS (proc
);
6386 if (p
->tick
!= p
->update_tick
)
6388 p
->update_tick
= p
->tick
;
6390 /* If process is still active, read any output that remains. */
6391 while (! EQ (p
->filter
, Qt
)
6392 && ! EQ (p
->status
, Qconnect
)
6393 && ! EQ (p
->status
, Qlisten
)
6394 /* Network or serial process not stopped: */
6395 && ! EQ (p
->command
, Qt
)
6397 && p
!= deleting_process
6398 && read_process_output (proc
, p
->infd
) > 0);
6400 /* Get the text to use for the message. */
6401 if (p
->raw_status_new
)
6403 msg
= status_message (p
);
6405 /* If process is terminated, deactivate it or delete it. */
6407 if (CONSP (p
->status
))
6408 symbol
= XCAR (p
->status
);
6410 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6411 || EQ (symbol
, Qclosed
))
6413 if (delete_exited_processes
)
6414 remove_process (proc
);
6416 deactivate_process (proc
);
6419 /* The actions above may have further incremented p->tick.
6420 So set p->update_tick again so that an error in the sentinel will
6421 not cause this code to be run again. */
6422 p
->update_tick
= p
->tick
;
6423 /* Now output the message suitably. */
6424 exec_sentinel (proc
, msg
);
6428 update_mode_lines
= 24; /* In case buffers use %s in mode-line-format. */
6432 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel
,
6433 Sinternal_default_process_sentinel
, 2, 2, 0,
6434 doc
: /* Function used as default sentinel for processes.
6435 This inserts a status message into the process's buffer, if there is one. */)
6436 (Lisp_Object proc
, Lisp_Object msg
)
6438 Lisp_Object buffer
, symbol
;
6439 struct Lisp_Process
*p
;
6440 CHECK_PROCESS (proc
);
6441 p
= XPROCESS (proc
);
6445 symbol
= XCAR (symbol
);
6447 if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6450 struct buffer
*old
= current_buffer
;
6451 ptrdiff_t opoint
, opoint_byte
;
6452 ptrdiff_t before
, before_byte
;
6454 /* Avoid error if buffer is deleted
6455 (probably that's why the process is dead, too). */
6456 if (!BUFFER_LIVE_P (XBUFFER (buffer
)))
6458 Fset_buffer (buffer
);
6460 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
6461 msg
= (code_convert_string_norecord
6462 (msg
, Vlocale_coding_system
, 1));
6465 opoint_byte
= PT_BYTE
;
6466 /* Insert new output into buffer
6467 at the current end-of-output marker,
6468 thus preserving logical ordering of input and output. */
6469 if (XMARKER (p
->mark
)->buffer
)
6470 Fgoto_char (p
->mark
);
6472 SET_PT_BOTH (ZV
, ZV_BYTE
);
6475 before_byte
= PT_BYTE
;
6477 tem
= BVAR (current_buffer
, read_only
);
6478 bset_read_only (current_buffer
, Qnil
);
6479 insert_string ("\nProcess ");
6480 { /* FIXME: temporary kludge. */
6481 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6482 insert_string (" ");
6484 bset_read_only (current_buffer
, tem
);
6485 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6487 if (opoint
>= before
)
6488 SET_PT_BOTH (opoint
+ (PT
- before
),
6489 opoint_byte
+ (PT_BYTE
- before_byte
));
6491 SET_PT_BOTH (opoint
, opoint_byte
);
6493 set_buffer_internal (old
);
6499 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6500 Sset_process_coding_system
, 1, 3, 0,
6501 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6502 DECODING will be used to decode subprocess output and ENCODING to
6503 encode subprocess input. */)
6504 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6506 register struct Lisp_Process
*p
;
6508 CHECK_PROCESS (process
);
6509 p
= XPROCESS (process
);
6511 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6513 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6514 Fcheck_coding_system (decoding
);
6515 Fcheck_coding_system (encoding
);
6516 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6517 pset_decode_coding_system (p
, decoding
);
6518 pset_encode_coding_system (p
, encoding
);
6519 setup_process_coding_systems (process
);
6524 DEFUN ("process-coding-system",
6525 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6526 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6527 (register Lisp_Object process
)
6529 CHECK_PROCESS (process
);
6530 return Fcons (XPROCESS (process
)->decode_coding_system
,
6531 XPROCESS (process
)->encode_coding_system
);
6534 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6535 Sset_process_filter_multibyte
, 2, 2, 0,
6536 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6537 If FLAG is non-nil, the filter is given multibyte strings.
6538 If FLAG is nil, the filter is given unibyte strings. In this case,
6539 all character code conversion except for end-of-line conversion is
6541 (Lisp_Object process
, Lisp_Object flag
)
6543 register struct Lisp_Process
*p
;
6545 CHECK_PROCESS (process
);
6546 p
= XPROCESS (process
);
6548 pset_decode_coding_system
6549 (p
, raw_text_coding_system (p
->decode_coding_system
));
6550 setup_process_coding_systems (process
);
6555 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6556 Sprocess_filter_multibyte_p
, 1, 1, 0,
6557 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6558 (Lisp_Object process
)
6560 register struct Lisp_Process
*p
;
6561 struct coding_system
*coding
;
6563 CHECK_PROCESS (process
);
6564 p
= XPROCESS (process
);
6565 coding
= proc_decode_coding_system
[p
->infd
];
6566 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6575 add_gpm_wait_descriptor (int desc
)
6577 add_keyboard_wait_descriptor (desc
);
6581 delete_gpm_wait_descriptor (int desc
)
6583 delete_keyboard_wait_descriptor (desc
);
6588 # ifdef USABLE_SIGIO
6590 /* Return true if *MASK has a bit set
6591 that corresponds to one of the keyboard input descriptors. */
6594 keyboard_bit_set (fd_set
*mask
)
6598 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6599 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6600 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6607 #else /* not subprocesses */
6609 /* Defined on msdos.c. */
6610 extern int sys_select (int, fd_set
*, fd_set
*, fd_set
*,
6611 struct timespec
*, void *);
6613 /* Implementation of wait_reading_process_output, assuming that there
6614 are no subprocesses. Used only by the MS-DOS build.
6616 Wait for timeout to elapse and/or keyboard input to be available.
6620 If negative, gobble data immediately available but don't wait for any.
6623 an additional duration to wait, measured in nanoseconds
6624 If TIME_LIMIT is zero, then:
6625 If NSECS == 0, there is no limit.
6626 If NSECS > 0, the timeout consists of NSECS only.
6627 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6630 0 to ignore keyboard input, or
6631 1 to return when input is available, or
6632 -1 means caller will actually read the input, so don't throw to
6635 see full version for other parameters. We know that wait_proc will
6636 always be NULL, since `subprocesses' isn't defined.
6638 DO_DISPLAY means redisplay should be done to show subprocess
6639 output that arrives.
6641 Return true if we received input from any process. */
6644 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6646 Lisp_Object wait_for_cell
,
6647 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6650 struct timespec end_time
, timeout
;
6657 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6658 time_limit
= TYPE_MAXIMUM (time_t);
6660 /* What does time_limit really mean? */
6661 if (time_limit
|| nsecs
> 0)
6663 timeout
= make_timespec (time_limit
, nsecs
);
6664 end_time
= timespec_add (current_timespec (), timeout
);
6667 /* Turn off periodic alarms (in case they are in use)
6668 and then turn off any other atimers,
6669 because the select emulator uses alarms. */
6671 turn_on_atimers (0);
6675 bool timeout_reduced_for_timers
= 0;
6676 fd_set waitchannels
;
6679 /* If calling from keyboard input, do not quit
6680 since we want to return C-g as an input character.
6681 Otherwise, do pending quit if requested. */
6685 /* Exit now if the cell we're waiting for became non-nil. */
6686 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6689 /* Compute time from now till when time limit is up. */
6690 /* Exit if already run out. */
6693 /* A negative timeout means
6694 gobble output available now
6695 but don't wait at all. */
6697 timeout
= make_timespec (0, 0);
6699 else if (time_limit
|| nsecs
> 0)
6701 struct timespec now
= current_timespec ();
6702 if (timespec_cmp (end_time
, now
) <= 0)
6704 timeout
= timespec_sub (end_time
, now
);
6708 timeout
= make_timespec (100000, 0);
6711 /* If our caller will not immediately handle keyboard events,
6712 run timer events directly.
6713 (Callers that will immediately read keyboard events
6714 call timer_delay on their own.) */
6715 if (NILP (wait_for_cell
))
6717 struct timespec timer_delay
;
6721 unsigned old_timers_run
= timers_run
;
6722 timer_delay
= timer_check ();
6723 if (timers_run
!= old_timers_run
&& do_display
)
6724 /* We must retry, since a timer may have requeued itself
6725 and that could alter the time delay. */
6726 redisplay_preserve_echo_area (14);
6730 while (!detect_input_pending ());
6732 /* If there is unread keyboard input, also return. */
6734 && requeued_events_pending_p ())
6737 if (timespec_valid_p (timer_delay
) && nsecs
>= 0)
6739 if (timespec_cmp (timer_delay
, timeout
) < 0)
6741 timeout
= timer_delay
;
6742 timeout_reduced_for_timers
= 1;
6747 /* Cause C-g and alarm signals to take immediate action,
6748 and cause input available signals to zero out timeout. */
6750 set_waiting_for_input (&timeout
);
6752 /* If a frame has been newly mapped and needs updating,
6753 reprocess its display stuff. */
6754 if (frame_garbaged
&& do_display
)
6756 clear_waiting_for_input ();
6757 redisplay_preserve_echo_area (15);
6759 set_waiting_for_input (&timeout
);
6762 /* Wait till there is something to do. */
6763 FD_ZERO (&waitchannels
);
6764 if (read_kbd
&& detect_input_pending ())
6768 if (read_kbd
|| !NILP (wait_for_cell
))
6769 FD_SET (0, &waitchannels
);
6770 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6775 /* Make C-g and alarm signals set flags again */
6776 clear_waiting_for_input ();
6778 /* If we woke up due to SIGWINCH, actually change size now. */
6779 do_pending_window_change (0);
6781 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6782 /* We waited the full specified time, so return now. */
6787 /* If the system call was interrupted, then go around the
6789 if (xerrno
== EINTR
)
6790 FD_ZERO (&waitchannels
);
6792 report_file_errno ("Failed select", Qnil
, xerrno
);
6795 /* Check for keyboard input */
6798 && detect_input_pending_run_timers (do_display
))
6800 swallow_events (do_display
);
6801 if (detect_input_pending_run_timers (do_display
))
6805 /* If there is unread keyboard input, also return. */
6807 && requeued_events_pending_p ())
6810 /* If wait_for_cell. check for keyboard input
6811 but don't run any timers.
6812 ??? (It seems wrong to me to check for keyboard
6813 input at all when wait_for_cell, but the code
6814 has been this way since July 1994.
6815 Try changing this after version 19.31.) */
6816 if (! NILP (wait_for_cell
)
6817 && detect_input_pending ())
6819 swallow_events (do_display
);
6820 if (detect_input_pending ())
6824 /* Exit now if the cell we're waiting for became non-nil. */
6825 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6834 #endif /* not subprocesses */
6836 /* The following functions are needed even if async subprocesses are
6837 not supported. Some of them are no-op stubs in that case. */
6839 /* Add DESC to the set of keyboard input descriptors. */
6842 add_keyboard_wait_descriptor (int desc
)
6844 #ifdef subprocesses /* actually means "not MSDOS" */
6845 FD_SET (desc
, &input_wait_mask
);
6846 FD_SET (desc
, &non_process_wait_mask
);
6847 if (desc
> max_input_desc
)
6848 max_input_desc
= desc
;
6852 /* From now on, do not expect DESC to give keyboard input. */
6855 delete_keyboard_wait_descriptor (int desc
)
6858 FD_CLR (desc
, &input_wait_mask
);
6859 FD_CLR (desc
, &non_process_wait_mask
);
6860 delete_input_desc (desc
);
6864 /* Setup coding systems of PROCESS. */
6867 setup_process_coding_systems (Lisp_Object process
)
6870 struct Lisp_Process
*p
= XPROCESS (process
);
6872 int outch
= p
->outfd
;
6873 Lisp_Object coding_system
;
6875 if (inch
< 0 || outch
< 0)
6878 if (!proc_decode_coding_system
[inch
])
6879 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
6880 coding_system
= p
->decode_coding_system
;
6881 if (EQ (p
->filter
, Qinternal_default_process_filter
)
6882 && BUFFERP (p
->buffer
))
6884 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
6885 coding_system
= raw_text_coding_system (coding_system
);
6887 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
6889 if (!proc_encode_coding_system
[outch
])
6890 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
6891 setup_coding_system (p
->encode_coding_system
,
6892 proc_encode_coding_system
[outch
]);
6896 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
6897 doc
: /* Return the (or a) process associated with BUFFER.
6898 BUFFER may be a buffer or the name of one. */)
6899 (register Lisp_Object buffer
)
6902 register Lisp_Object buf
, tail
, proc
;
6904 if (NILP (buffer
)) return Qnil
;
6905 buf
= Fget_buffer (buffer
);
6906 if (NILP (buf
)) return Qnil
;
6908 FOR_EACH_PROCESS (tail
, proc
)
6909 if (EQ (XPROCESS (proc
)->buffer
, buf
))
6911 #endif /* subprocesses */
6915 DEFUN ("process-inherit-coding-system-flag",
6916 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
6918 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
6919 If this flag is t, `buffer-file-coding-system' of the buffer
6920 associated with PROCESS will inherit the coding system used to decode
6921 the process output. */)
6922 (register Lisp_Object process
)
6925 CHECK_PROCESS (process
);
6926 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
6928 /* Ignore the argument and return the value of
6929 inherit-process-coding-system. */
6930 return inherit_process_coding_system
? Qt
: Qnil
;
6934 /* Kill all processes associated with `buffer'.
6935 If `buffer' is nil, kill all processes */
6938 kill_buffer_processes (Lisp_Object buffer
)
6941 Lisp_Object tail
, proc
;
6943 FOR_EACH_PROCESS (tail
, proc
)
6944 if (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
))
6946 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
6947 Fdelete_process (proc
);
6948 else if (XPROCESS (proc
)->infd
>= 0)
6949 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
6951 #else /* subprocesses */
6952 /* Since we have no subprocesses, this does nothing. */
6953 #endif /* subprocesses */
6956 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
6957 Swaiting_for_user_input_p
, 0, 0, 0,
6958 doc
: /* Return non-nil if Emacs is waiting for input from the user.
6959 This is intended for use by asynchronous process output filters and sentinels. */)
6963 return (waiting_for_user_input_p
? Qt
: Qnil
);
6969 /* Stop reading input from keyboard sources. */
6972 hold_keyboard_input (void)
6977 /* Resume reading input from keyboard sources. */
6980 unhold_keyboard_input (void)
6985 /* Return true if keyboard input is on hold, zero otherwise. */
6988 kbd_on_hold_p (void)
6990 return kbd_is_on_hold
;
6994 /* Enumeration of and access to system processes a-la ps(1). */
6996 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
6998 doc
: /* Return a list of numerical process IDs of all running processes.
6999 If this functionality is unsupported, return nil.
7001 See `process-attributes' for getting attributes of a process given its ID. */)
7004 return list_system_processes ();
7007 DEFUN ("process-attributes", Fprocess_attributes
,
7008 Sprocess_attributes
, 1, 1, 0,
7009 doc
: /* Return attributes of the process given by its PID, a number.
7011 Value is an alist where each element is a cons cell of the form
7015 If this functionality is unsupported, the value is nil.
7017 See `list-system-processes' for getting a list of all process IDs.
7019 The KEYs of the attributes that this function may return are listed
7020 below, together with the type of the associated VALUE (in parentheses).
7021 Not all platforms support all of these attributes; unsupported
7022 attributes will not appear in the returned alist.
7023 Unless explicitly indicated otherwise, numbers can have either
7024 integer or floating point values.
7026 euid -- Effective user User ID of the process (number)
7027 user -- User name corresponding to euid (string)
7028 egid -- Effective user Group ID of the process (number)
7029 group -- Group name corresponding to egid (string)
7030 comm -- Command name (executable name only) (string)
7031 state -- Process state code, such as "S", "R", or "T" (string)
7032 ppid -- Parent process ID (number)
7033 pgrp -- Process group ID (number)
7034 sess -- Session ID, i.e. process ID of session leader (number)
7035 ttname -- Controlling tty name (string)
7036 tpgid -- ID of foreground process group on the process's tty (number)
7037 minflt -- number of minor page faults (number)
7038 majflt -- number of major page faults (number)
7039 cminflt -- cumulative number of minor page faults (number)
7040 cmajflt -- cumulative number of major page faults (number)
7041 utime -- user time used by the process, in (current-time) format,
7042 which is a list of integers (HIGH LOW USEC PSEC)
7043 stime -- system time used by the process (current-time)
7044 time -- sum of utime and stime (current-time)
7045 cutime -- user time used by the process and its children (current-time)
7046 cstime -- system time used by the process and its children (current-time)
7047 ctime -- sum of cutime and cstime (current-time)
7048 pri -- priority of the process (number)
7049 nice -- nice value of the process (number)
7050 thcount -- process thread count (number)
7051 start -- time the process started (current-time)
7052 vsize -- virtual memory size of the process in KB's (number)
7053 rss -- resident set size of the process in KB's (number)
7054 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7055 pcpu -- percents of CPU time used by the process (floating-point number)
7056 pmem -- percents of total physical memory used by process's resident set
7057 (floating-point number)
7058 args -- command line which invoked the process (string). */)
7061 return system_process_attributes (pid
);
7065 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7066 Invoke this after init_process_emacs, and after glib and/or GNUstep
7067 futz with the SIGCHLD handler, but before Emacs forks any children.
7068 This function's caller should block SIGCHLD. */
7070 #ifndef NS_IMPL_GNUSTEP
7074 catch_child_signal (void)
7076 struct sigaction action
, old_action
;
7077 emacs_sigaction_init (&action
, deliver_child_signal
);
7078 block_child_signal ();
7079 sigaction (SIGCHLD
, &action
, &old_action
);
7080 eassert (! (old_action
.sa_flags
& SA_SIGINFO
));
7082 if (old_action
.sa_handler
!= deliver_child_signal
)
7084 = (old_action
.sa_handler
== SIG_DFL
|| old_action
.sa_handler
== SIG_IGN
7086 : old_action
.sa_handler
);
7087 unblock_child_signal ();
7089 #endif /* subprocesses */
7092 /* This is not called "init_process" because that is the name of a
7093 Mach system call, so it would cause problems on Darwin systems. */
7095 init_process_emacs (void)
7100 inhibit_sentinels
= 0;
7103 if (! noninteractive
|| initialized
)
7106 #if defined HAVE_GLIB && !defined WINDOWSNT
7107 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7108 this should always fail, but is enough to initialize glib's
7109 private SIGCHLD handler, allowing catch_child_signal to copy
7110 it into lib_child_handler. */
7111 g_source_unref (g_child_watch_source_new (getpid ()));
7113 catch_child_signal ();
7116 FD_ZERO (&input_wait_mask
);
7117 FD_ZERO (&non_keyboard_wait_mask
);
7118 FD_ZERO (&non_process_wait_mask
);
7119 FD_ZERO (&write_mask
);
7120 max_process_desc
= max_input_desc
= -1;
7121 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7123 #ifdef NON_BLOCKING_CONNECT
7124 FD_ZERO (&connect_wait_mask
);
7125 num_pending_connects
= 0;
7128 #ifdef ADAPTIVE_READ_BUFFERING
7129 process_output_delay_count
= 0;
7130 process_output_skip
= 0;
7133 /* Don't do this, it caused infinite select loops. The display
7134 method should call add_keyboard_wait_descriptor on stdin if it
7137 FD_SET (0, &input_wait_mask
);
7140 Vprocess_alist
= Qnil
;
7141 deleted_pid_list
= Qnil
;
7142 for (i
= 0; i
< FD_SETSIZE
; i
++)
7144 chan_process
[i
] = Qnil
;
7145 proc_buffered_char
[i
] = -1;
7147 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7148 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7149 #ifdef DATAGRAM_SOCKETS
7150 memset (datagram_address
, 0, sizeof datagram_address
);
7154 Lisp_Object subfeatures
= Qnil
;
7155 const struct socket_options
*sopt
;
7157 #define ADD_SUBFEATURE(key, val) \
7158 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7160 #ifdef NON_BLOCKING_CONNECT
7161 ADD_SUBFEATURE (QCnowait
, Qt
);
7163 #ifdef DATAGRAM_SOCKETS
7164 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7166 #ifdef HAVE_SEQPACKET
7167 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7169 #ifdef HAVE_LOCAL_SOCKETS
7170 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7172 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7174 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7176 #ifdef HAVE_GETSOCKNAME
7177 ADD_SUBFEATURE (QCservice
, Qt
);
7179 ADD_SUBFEATURE (QCserver
, Qt
);
7181 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7182 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7184 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7187 #if defined (DARWIN_OS)
7188 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7189 processes. As such, we only change the default value. */
7192 char const *release
= (STRINGP (Voperating_system_release
)
7193 ? SSDATA (Voperating_system_release
)
7195 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7196 Vprocess_connection_type
= Qnil
;
7200 #endif /* subprocesses */
7205 syms_of_process (void)
7209 DEFSYM (Qprocessp
, "processp");
7210 DEFSYM (Qrun
, "run");
7211 DEFSYM (Qstop
, "stop");
7212 DEFSYM (Qsignal
, "signal");
7214 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7217 Qexit = intern_c_string ("exit");
7218 staticpro (&Qexit); */
7220 DEFSYM (Qopen
, "open");
7221 DEFSYM (Qclosed
, "closed");
7222 DEFSYM (Qconnect
, "connect");
7223 DEFSYM (Qfailed
, "failed");
7224 DEFSYM (Qlisten
, "listen");
7225 DEFSYM (Qlocal
, "local");
7226 DEFSYM (Qipv4
, "ipv4");
7228 DEFSYM (Qipv6
, "ipv6");
7230 DEFSYM (Qdatagram
, "datagram");
7231 DEFSYM (Qseqpacket
, "seqpacket");
7233 DEFSYM (QCport
, ":port");
7234 DEFSYM (QCspeed
, ":speed");
7235 DEFSYM (QCprocess
, ":process");
7237 DEFSYM (QCbytesize
, ":bytesize");
7238 DEFSYM (QCstopbits
, ":stopbits");
7239 DEFSYM (QCparity
, ":parity");
7240 DEFSYM (Qodd
, "odd");
7241 DEFSYM (Qeven
, "even");
7242 DEFSYM (QCflowcontrol
, ":flowcontrol");
7245 DEFSYM (QCsummary
, ":summary");
7247 DEFSYM (Qreal
, "real");
7248 DEFSYM (Qnetwork
, "network");
7249 DEFSYM (Qserial
, "serial");
7250 DEFSYM (QCbuffer
, ":buffer");
7251 DEFSYM (QChost
, ":host");
7252 DEFSYM (QCservice
, ":service");
7253 DEFSYM (QClocal
, ":local");
7254 DEFSYM (QCremote
, ":remote");
7255 DEFSYM (QCcoding
, ":coding");
7256 DEFSYM (QCserver
, ":server");
7257 DEFSYM (QCnowait
, ":nowait");
7258 DEFSYM (QCsentinel
, ":sentinel");
7259 DEFSYM (QClog
, ":log");
7260 DEFSYM (QCnoquery
, ":noquery");
7261 DEFSYM (QCstop
, ":stop");
7262 DEFSYM (QCoptions
, ":options");
7263 DEFSYM (QCplist
, ":plist");
7265 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7267 staticpro (&Vprocess_alist
);
7268 staticpro (&deleted_pid_list
);
7270 #endif /* subprocesses */
7272 DEFSYM (QCname
, ":name");
7273 DEFSYM (QCtype
, ":type");
7275 DEFSYM (Qeuid
, "euid");
7276 DEFSYM (Qegid
, "egid");
7277 DEFSYM (Quser
, "user");
7278 DEFSYM (Qgroup
, "group");
7279 DEFSYM (Qcomm
, "comm");
7280 DEFSYM (Qstate
, "state");
7281 DEFSYM (Qppid
, "ppid");
7282 DEFSYM (Qpgrp
, "pgrp");
7283 DEFSYM (Qsess
, "sess");
7284 DEFSYM (Qttname
, "ttname");
7285 DEFSYM (Qtpgid
, "tpgid");
7286 DEFSYM (Qminflt
, "minflt");
7287 DEFSYM (Qmajflt
, "majflt");
7288 DEFSYM (Qcminflt
, "cminflt");
7289 DEFSYM (Qcmajflt
, "cmajflt");
7290 DEFSYM (Qutime
, "utime");
7291 DEFSYM (Qstime
, "stime");
7292 DEFSYM (Qtime
, "time");
7293 DEFSYM (Qcutime
, "cutime");
7294 DEFSYM (Qcstime
, "cstime");
7295 DEFSYM (Qctime
, "ctime");
7297 DEFSYM (Qinternal_default_process_sentinel
,
7298 "internal-default-process-sentinel");
7299 DEFSYM (Qinternal_default_process_filter
,
7300 "internal-default-process-filter");
7302 DEFSYM (Qpri
, "pri");
7303 DEFSYM (Qnice
, "nice");
7304 DEFSYM (Qthcount
, "thcount");
7305 DEFSYM (Qstart
, "start");
7306 DEFSYM (Qvsize
, "vsize");
7307 DEFSYM (Qrss
, "rss");
7308 DEFSYM (Qetime
, "etime");
7309 DEFSYM (Qpcpu
, "pcpu");
7310 DEFSYM (Qpmem
, "pmem");
7311 DEFSYM (Qargs
, "args");
7313 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7314 doc
: /* Non-nil means delete processes immediately when they exit.
7315 A value of nil means don't delete them until `list-processes' is run. */);
7317 delete_exited_processes
= 1;
7320 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7321 doc
: /* Control type of device used to communicate with subprocesses.
7322 Values are nil to use a pipe, or t or `pty' to use a pty.
7323 The value has no effect if the system has no ptys or if all ptys are busy:
7324 then a pipe is used in any case.
7325 The value takes effect when `start-process' is called. */);
7326 Vprocess_connection_type
= Qt
;
7328 #ifdef ADAPTIVE_READ_BUFFERING
7329 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7330 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7331 On some systems, when Emacs reads the output from a subprocess, the output data
7332 is read in very small blocks, potentially resulting in very poor performance.
7333 This behavior can be remedied to some extent by setting this variable to a
7334 non-nil value, as it will automatically delay reading from such processes, to
7335 allow them to produce more output before Emacs tries to read it.
7336 If the value is t, the delay is reset after each write to the process; any other
7337 non-nil value means that the delay is not reset on write.
7338 The variable takes effect when `start-process' is called. */);
7339 Vprocess_adaptive_read_buffering
= Qt
;
7342 defsubr (&Sprocessp
);
7343 defsubr (&Sget_process
);
7344 defsubr (&Sdelete_process
);
7345 defsubr (&Sprocess_status
);
7346 defsubr (&Sprocess_exit_status
);
7347 defsubr (&Sprocess_id
);
7348 defsubr (&Sprocess_name
);
7349 defsubr (&Sprocess_tty_name
);
7350 defsubr (&Sprocess_command
);
7351 defsubr (&Sset_process_buffer
);
7352 defsubr (&Sprocess_buffer
);
7353 defsubr (&Sprocess_mark
);
7354 defsubr (&Sset_process_filter
);
7355 defsubr (&Sprocess_filter
);
7356 defsubr (&Sset_process_sentinel
);
7357 defsubr (&Sprocess_sentinel
);
7358 defsubr (&Sset_process_window_size
);
7359 defsubr (&Sset_process_inherit_coding_system_flag
);
7360 defsubr (&Sset_process_query_on_exit_flag
);
7361 defsubr (&Sprocess_query_on_exit_flag
);
7362 defsubr (&Sprocess_contact
);
7363 defsubr (&Sprocess_plist
);
7364 defsubr (&Sset_process_plist
);
7365 defsubr (&Sprocess_list
);
7366 defsubr (&Sstart_process
);
7367 defsubr (&Sserial_process_configure
);
7368 defsubr (&Smake_serial_process
);
7369 defsubr (&Sset_network_process_option
);
7370 defsubr (&Smake_network_process
);
7371 defsubr (&Sformat_network_address
);
7372 defsubr (&Snetwork_interface_list
);
7373 defsubr (&Snetwork_interface_info
);
7374 #ifdef DATAGRAM_SOCKETS
7375 defsubr (&Sprocess_datagram_address
);
7376 defsubr (&Sset_process_datagram_address
);
7378 defsubr (&Saccept_process_output
);
7379 defsubr (&Sprocess_send_region
);
7380 defsubr (&Sprocess_send_string
);
7381 defsubr (&Sinterrupt_process
);
7382 defsubr (&Skill_process
);
7383 defsubr (&Squit_process
);
7384 defsubr (&Sstop_process
);
7385 defsubr (&Scontinue_process
);
7386 defsubr (&Sprocess_running_child_p
);
7387 defsubr (&Sprocess_send_eof
);
7388 defsubr (&Ssignal_process
);
7389 defsubr (&Swaiting_for_user_input_p
);
7390 defsubr (&Sprocess_type
);
7391 defsubr (&Sinternal_default_process_sentinel
);
7392 defsubr (&Sinternal_default_process_filter
);
7393 defsubr (&Sset_process_coding_system
);
7394 defsubr (&Sprocess_coding_system
);
7395 defsubr (&Sset_process_filter_multibyte
);
7396 defsubr (&Sprocess_filter_multibyte_p
);
7398 #endif /* subprocesses */
7400 defsubr (&Sget_buffer_process
);
7401 defsubr (&Sprocess_inherit_coding_system_flag
);
7402 defsubr (&Slist_system_processes
);
7403 defsubr (&Sprocess_attributes
);