1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2012
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/>. */
24 #define PROCESS_INLINE EXTERN_INLINE
30 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
40 /* Only MS-DOS does not define `subprocesses'. */
43 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
48 /* Are local (unix) sockets supported? */
49 #if defined (HAVE_SYS_UN_H)
50 #if !defined (AF_LOCAL) && defined (AF_UNIX)
51 #define AF_LOCAL AF_UNIX
54 #define HAVE_LOCAL_SOCKETS
59 #include <sys/ioctl.h>
60 #if defined (HAVE_NET_IF_H)
62 #endif /* HAVE_NET_IF_H */
64 #if defined (HAVE_IFADDRS_H)
65 /* Must be after net/if.h */
68 /* We only use structs from this header when we use getifaddrs. */
69 #if defined (HAVE_NET_IF_DL_H)
70 #include <net/if_dl.h>
80 #include <netinet/in.h>
81 #include <arpa/nameser.h>
93 #endif /* subprocesses */
99 #include "character.h"
104 #include "termhooks.h"
105 #include "termopts.h"
106 #include "commands.h"
107 #include "keyboard.h"
108 #include "blockinput.h"
109 #include "dispextern.h"
110 #include "composite.h"
112 #include "sysselect.h"
113 #include "syssignal.h"
119 #ifdef HAVE_WINDOW_SYSTEM
121 #endif /* HAVE_WINDOW_SYSTEM */
123 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
124 #include "xgselect.h"
127 /* Work around GCC 4.7.0 bug with strict overflow checking; see
128 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
129 These lines can be removed once the GCC bug is fixed. */
130 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
131 # pragma GCC diagnostic ignored "-Wstrict-overflow"
134 Lisp_Object Qeuid
, Qegid
, Qcomm
, Qstate
, Qppid
, Qpgrp
, Qsess
, Qttname
, Qtpgid
;
135 Lisp_Object Qminflt
, Qmajflt
, Qcminflt
, Qcmajflt
, Qutime
, Qstime
, Qcstime
;
136 Lisp_Object Qcutime
, Qpri
, Qnice
, Qthcount
, Qstart
, Qvsize
, Qrss
, Qargs
;
137 Lisp_Object Quser
, Qgroup
, Qetime
, Qpcpu
, Qpmem
, Qtime
, Qctime
;
138 Lisp_Object QCname
, QCtype
;
140 /* Non-zero if keyboard input is on hold, zero otherwise. */
142 static int kbd_is_on_hold
;
144 /* Nonzero means don't run process sentinels. This is used
146 int inhibit_sentinels
;
150 Lisp_Object Qprocessp
;
151 static Lisp_Object Qrun
, Qstop
, Qsignal
;
152 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
154 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
155 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
157 static Lisp_Object Qipv6
;
159 static Lisp_Object QCport
, QCprocess
;
161 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
162 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
163 static Lisp_Object QCbuffer
, QChost
, QCservice
;
164 static Lisp_Object QClocal
, QCremote
, QCcoding
;
165 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
166 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
167 static Lisp_Object Qlast_nonmenu_event
;
169 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
170 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
171 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
172 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
178 /* Number of events of change of status of a process. */
179 static EMACS_INT process_tick
;
180 /* Number of events for which the user or sentinel has been notified. */
181 static EMACS_INT update_tick
;
183 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
185 /* Only W32 has this, it really means that select can't take write mask. */
186 #ifdef BROKEN_NON_BLOCKING_CONNECT
187 #undef NON_BLOCKING_CONNECT
188 #define SELECT_CANT_DO_WRITE_MASK
190 #ifndef NON_BLOCKING_CONNECT
192 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
193 #if defined (O_NONBLOCK) || defined (O_NDELAY)
194 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
195 #define NON_BLOCKING_CONNECT
196 #endif /* EWOULDBLOCK || EINPROGRESS */
197 #endif /* O_NONBLOCK || O_NDELAY */
198 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
199 #endif /* HAVE_SELECT */
200 #endif /* NON_BLOCKING_CONNECT */
201 #endif /* BROKEN_NON_BLOCKING_CONNECT */
203 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
204 this system. We need to read full packets, so we need a
205 "non-destructive" select. So we require either native select,
206 or emulation of select using FIONREAD. */
208 #ifdef BROKEN_DATAGRAM_SOCKETS
209 #undef DATAGRAM_SOCKETS
211 #ifndef DATAGRAM_SOCKETS
212 #if defined (HAVE_SELECT) || defined (FIONREAD)
213 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
214 #define DATAGRAM_SOCKETS
215 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
216 #endif /* HAVE_SELECT || FIONREAD */
217 #endif /* DATAGRAM_SOCKETS */
218 #endif /* BROKEN_DATAGRAM_SOCKETS */
220 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
221 # define HAVE_SEQPACKET
224 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
225 #define ADAPTIVE_READ_BUFFERING
228 #ifdef ADAPTIVE_READ_BUFFERING
229 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
230 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
231 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
233 /* Number of processes which have a non-zero read_output_delay,
234 and therefore might be delayed for adaptive read buffering. */
236 static int process_output_delay_count
;
238 /* Non-zero if any process has non-nil read_output_skip. */
240 static int process_output_skip
;
243 #define process_output_delay_count 0
246 static void create_process (Lisp_Object
, char **, Lisp_Object
);
248 static int keyboard_bit_set (SELECT_TYPE
*);
250 static void deactivate_process (Lisp_Object
);
251 static void status_notify (struct Lisp_Process
*);
252 static int read_process_output (Lisp_Object
, int);
253 static void create_pty (Lisp_Object
);
255 /* If we support a window system, turn on the code to poll periodically
256 to detect C-g. It isn't actually used when doing interrupt input. */
257 #if defined (HAVE_WINDOW_SYSTEM) && !defined (USE_ASYNC_EVENTS)
258 #define POLL_FOR_INPUT
261 static Lisp_Object
get_process (register Lisp_Object name
);
262 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
264 /* Mask of bits indicating the descriptors that we wait for input on. */
266 static SELECT_TYPE input_wait_mask
;
268 /* Mask that excludes keyboard input descriptor(s). */
270 static SELECT_TYPE non_keyboard_wait_mask
;
272 /* Mask that excludes process input descriptor(s). */
274 static SELECT_TYPE non_process_wait_mask
;
276 /* Mask for selecting for write. */
278 static SELECT_TYPE write_mask
;
280 #ifdef NON_BLOCKING_CONNECT
281 /* Mask of bits indicating the descriptors that we wait for connect to
282 complete on. Once they complete, they are removed from this mask
283 and added to the input_wait_mask and non_keyboard_wait_mask. */
285 static SELECT_TYPE connect_wait_mask
;
287 /* Number of bits set in connect_wait_mask. */
288 static int num_pending_connects
;
289 #endif /* NON_BLOCKING_CONNECT */
291 /* The largest descriptor currently in use for a process object. */
292 static int max_process_desc
;
294 /* The largest descriptor currently in use for input. */
295 static int max_input_desc
;
297 /* Indexed by descriptor, gives the process (if any) for that descriptor */
298 static Lisp_Object chan_process
[MAXDESC
];
300 /* Alist of elements (NAME . PROCESS) */
301 static Lisp_Object Vprocess_alist
;
303 /* Buffered-ahead input char from process, indexed by channel.
304 -1 means empty (no char is buffered).
305 Used on sys V where the only way to tell if there is any
306 output from the process is to read at least one char.
307 Always -1 on systems that support FIONREAD. */
309 static int proc_buffered_char
[MAXDESC
];
311 /* Table of `struct coding-system' for each process. */
312 static struct coding_system
*proc_decode_coding_system
[MAXDESC
];
313 static struct coding_system
*proc_encode_coding_system
[MAXDESC
];
315 #ifdef DATAGRAM_SOCKETS
316 /* Table of `partner address' for datagram sockets. */
317 static struct sockaddr_and_len
{
320 } datagram_address
[MAXDESC
];
321 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
322 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #define DATAGRAM_CHAN_P(chan) (0)
325 #define DATAGRAM_CONN_P(proc) (0)
328 /* Maximum number of bytes to send to a pty without an eof. */
329 static int pty_max_bytes
;
331 /* These setters are used only in this file, so they can be private. */
333 pset_buffer (struct Lisp_Process
*p
, Lisp_Object val
)
338 pset_command (struct Lisp_Process
*p
, Lisp_Object val
)
343 pset_decode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
345 p
->decode_coding_system
= val
;
348 pset_decoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
350 p
->decoding_buf
= val
;
353 pset_encode_coding_system (struct Lisp_Process
*p
, Lisp_Object val
)
355 p
->encode_coding_system
= val
;
358 pset_encoding_buf (struct Lisp_Process
*p
, Lisp_Object val
)
360 p
->encoding_buf
= val
;
363 pset_filter (struct Lisp_Process
*p
, Lisp_Object val
)
368 pset_log (struct Lisp_Process
*p
, Lisp_Object val
)
373 pset_mark (struct Lisp_Process
*p
, Lisp_Object val
)
378 pset_name (struct Lisp_Process
*p
, Lisp_Object val
)
383 pset_plist (struct Lisp_Process
*p
, Lisp_Object val
)
388 pset_sentinel (struct Lisp_Process
*p
, Lisp_Object val
)
393 pset_status (struct Lisp_Process
*p
, Lisp_Object val
)
398 pset_tty_name (struct Lisp_Process
*p
, Lisp_Object val
)
403 pset_type (struct Lisp_Process
*p
, Lisp_Object val
)
408 pset_write_queue (struct Lisp_Process
*p
, Lisp_Object val
)
410 p
->write_queue
= val
;
415 static struct fd_callback_data
421 int condition
; /* mask of the defines above. */
422 } fd_callback_info
[MAXDESC
];
425 /* Add a file descriptor FD to be monitored for when read is possible.
426 When read is possible, call FUNC with argument DATA. */
429 add_read_fd (int fd
, fd_callback func
, void *data
)
431 eassert (fd
< MAXDESC
);
432 add_keyboard_wait_descriptor (fd
);
434 fd_callback_info
[fd
].func
= func
;
435 fd_callback_info
[fd
].data
= data
;
436 fd_callback_info
[fd
].condition
|= FOR_READ
;
439 /* Stop monitoring file descriptor FD for when read is possible. */
442 delete_read_fd (int fd
)
444 eassert (fd
< MAXDESC
);
445 delete_keyboard_wait_descriptor (fd
);
447 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
448 if (fd_callback_info
[fd
].condition
== 0)
450 fd_callback_info
[fd
].func
= 0;
451 fd_callback_info
[fd
].data
= 0;
455 /* Add a file descriptor FD to be monitored for when write is possible.
456 When write is possible, call FUNC with argument DATA. */
459 add_write_fd (int fd
, fd_callback func
, void *data
)
461 eassert (fd
< MAXDESC
);
462 FD_SET (fd
, &write_mask
);
463 if (fd
> max_input_desc
)
466 fd_callback_info
[fd
].func
= func
;
467 fd_callback_info
[fd
].data
= data
;
468 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
471 /* Stop monitoring file descriptor FD for when write is possible. */
474 delete_write_fd (int fd
)
476 int lim
= max_input_desc
;
478 eassert (fd
< MAXDESC
);
479 FD_CLR (fd
, &write_mask
);
480 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
481 if (fd_callback_info
[fd
].condition
== 0)
483 fd_callback_info
[fd
].func
= 0;
484 fd_callback_info
[fd
].data
= 0;
486 if (fd
== max_input_desc
)
487 for (fd
= lim
; fd
>= 0; fd
--)
488 if (FD_ISSET (fd
, &input_wait_mask
) || FD_ISSET (fd
, &write_mask
))
498 /* Compute the Lisp form of the process status, p->status, from
499 the numeric status that was returned by `wait'. */
501 static Lisp_Object
status_convert (int);
504 update_status (struct Lisp_Process
*p
)
506 eassert (p
->raw_status_new
);
507 pset_status (p
, status_convert (p
->raw_status
));
508 p
->raw_status_new
= 0;
511 /* Convert a process status word in Unix format to
512 the list that we use internally. */
515 status_convert (int w
)
518 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
519 else if (WIFEXITED (w
))
520 return Fcons (Qexit
, Fcons (make_number (WEXITSTATUS (w
)),
521 WCOREDUMP (w
) ? Qt
: Qnil
));
522 else if (WIFSIGNALED (w
))
523 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
524 WCOREDUMP (w
) ? Qt
: Qnil
));
529 /* Given a status-list, extract the three pieces of information
530 and store them individually through the three pointers. */
533 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, int *coredump
)
547 *code
= XFASTINT (XCAR (tem
));
549 *coredump
= !NILP (tem
);
553 /* Return a string describing a process status list. */
556 status_message (struct Lisp_Process
*p
)
558 Lisp_Object status
= p
->status
;
561 Lisp_Object string
, string2
;
563 decode_status (status
, &symbol
, &code
, &coredump
);
565 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
568 synchronize_system_messages_locale ();
569 signame
= strsignal (code
);
571 string
= build_string ("unknown");
576 string
= build_unibyte_string (signame
);
577 if (! NILP (Vlocale_coding_system
))
578 string
= (code_convert_string_norecord
579 (string
, Vlocale_coding_system
, 0));
580 c1
= STRING_CHAR (SDATA (string
));
583 Faset (string
, make_number (0), make_number (c2
));
585 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
586 return concat2 (string
, string2
);
588 else if (EQ (symbol
, Qexit
))
591 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
593 return build_string ("finished\n");
594 string
= Fnumber_to_string (make_number (code
));
595 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
596 return concat3 (build_string ("exited abnormally with code "),
599 else if (EQ (symbol
, Qfailed
))
601 string
= Fnumber_to_string (make_number (code
));
602 string2
= build_string ("\n");
603 return concat3 (build_string ("failed with code "),
607 return Fcopy_sequence (Fsymbol_name (symbol
));
612 /* The file name of the pty opened by allocate_pty. */
613 static char pty_name
[24];
615 /* Open an available pty, returning a file descriptor.
616 Return -1 on failure.
617 The file name of the terminal corresponding to the pty
618 is left in the variable pty_name. */
629 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
630 for (i
= 0; i
< 16; i
++)
633 #ifdef PTY_NAME_SPRINTF
636 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
637 #endif /* no PTY_NAME_SPRINTF */
641 #else /* no PTY_OPEN */
643 { /* Some systems name their pseudoterminals so that there are gaps in
644 the usual sequence - for example, on HP9000/S700 systems, there
645 are no pseudoterminals with names ending in 'f'. So we wait for
646 three failures in a row before deciding that we've reached the
648 int failed_count
= 0;
651 if (stat (pty_name
, &stb
) < 0)
654 if (failed_count
>= 3)
661 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
663 fd
= emacs_open (pty_name
, O_RDWR
| O_NDELAY
, 0);
666 #endif /* no PTY_OPEN */
670 /* check to make certain that both sides are available
671 this avoids a nasty yet stupid bug in rlogins */
672 #ifdef PTY_TTY_NAME_SPRINTF
675 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
676 #endif /* no PTY_TTY_NAME_SPRINTF */
677 if (access (pty_name
, 6) != 0)
692 #endif /* HAVE_PTYS */
695 make_process (Lisp_Object name
)
697 register Lisp_Object val
, tem
, name1
;
698 register struct Lisp_Process
*p
;
699 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
702 p
= allocate_process ();
703 /* Initialize Lisp data. Note that allocate_process initializes all
704 Lisp data to nil, so do it only for slots which should not be nil. */
705 pset_status (p
, Qrun
);
706 pset_mark (p
, Fmake_marker ());
708 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
709 non-Lisp data, so do it only for slots which should not be zero. */
714 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
717 /* If name is already in use, modify it until it is unused. */
722 tem
= Fget_process (name1
);
723 if (NILP (tem
)) break;
724 name1
= concat2 (name
, make_formatted_string (suffix
, "<%"pMd
">", i
));
728 XSETPROCESS (val
, p
);
729 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
734 remove_process (register Lisp_Object proc
)
736 register Lisp_Object pair
;
738 pair
= Frassq (proc
, Vprocess_alist
);
739 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
741 deactivate_process (proc
);
745 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
746 doc
: /* Return t if OBJECT is a process. */)
749 return PROCESSP (object
) ? Qt
: Qnil
;
752 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
753 doc
: /* Return the process named NAME, or nil if there is none. */)
754 (register Lisp_Object name
)
759 return Fcdr (Fassoc (name
, Vprocess_alist
));
762 /* This is how commands for the user decode process arguments. It
763 accepts a process, a process name, a buffer, a buffer name, or nil.
764 Buffers denote the first process in the buffer, and nil denotes the
768 get_process (register Lisp_Object name
)
770 register Lisp_Object proc
, obj
;
773 obj
= Fget_process (name
);
775 obj
= Fget_buffer (name
);
777 error ("Process %s does not exist", SDATA (name
));
779 else if (NILP (name
))
780 obj
= Fcurrent_buffer ();
784 /* Now obj should be either a buffer object or a process object.
788 proc
= Fget_buffer_process (obj
);
790 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
802 /* Fdelete_process promises to immediately forget about the process, but in
803 reality, Emacs needs to remember those processes until they have been
804 treated by sigchld_handler; otherwise this handler would consider the
805 process as being synchronous and say that the synchronous process is
807 static Lisp_Object deleted_pid_list
;
810 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
811 doc
: /* Delete PROCESS: kill it and forget about it immediately.
812 PROCESS may be a process, a buffer, the name of a process or buffer, or
813 nil, indicating the current buffer's process. */)
814 (register Lisp_Object process
)
816 register struct Lisp_Process
*p
;
818 process
= get_process (process
);
819 p
= XPROCESS (process
);
821 p
->raw_status_new
= 0;
822 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
824 pset_status (p
, Fcons (Qexit
, Fcons (make_number (0), Qnil
)));
825 p
->tick
= ++process_tick
;
827 redisplay_preserve_echo_area (13);
829 else if (p
->infd
>= 0)
835 /* No problem storing the pid here, as it is still in Vprocess_alist. */
836 deleted_pid_list
= Fcons (make_fixnum_or_float (pid
),
837 /* GC treated elements set to nil. */
838 Fdelq (Qnil
, deleted_pid_list
));
839 /* If the process has already signaled, remove it from the list. */
840 if (p
->raw_status_new
)
843 if (CONSP (p
->status
))
844 symbol
= XCAR (p
->status
);
845 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
))
847 = Fdelete (make_fixnum_or_float (pid
), deleted_pid_list
);
851 Fkill_process (process
, Qnil
);
852 /* Do this now, since remove_process will make sigchld_handler do nothing. */
853 pset_status (p
, Fcons (Qsignal
, Fcons (make_number (SIGKILL
), Qnil
)));
854 p
->tick
= ++process_tick
;
856 redisplay_preserve_echo_area (13);
859 remove_process (process
);
863 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
864 doc
: /* Return the status of PROCESS.
865 The returned value is one of the following symbols:
866 run -- for a process that is running.
867 stop -- for a process stopped but continuable.
868 exit -- for a process that has exited.
869 signal -- for a process that has got a fatal signal.
870 open -- for a network stream connection that is open.
871 listen -- for a network stream server that is listening.
872 closed -- for a network stream connection that is closed.
873 connect -- when waiting for a non-blocking connection to complete.
874 failed -- when a non-blocking connection has failed.
875 nil -- if arg is a process name and no such process exists.
876 PROCESS may be a process, a buffer, the name of a process, or
877 nil, indicating the current buffer's process. */)
878 (register Lisp_Object process
)
880 register struct Lisp_Process
*p
;
881 register Lisp_Object status
;
883 if (STRINGP (process
))
884 process
= Fget_process (process
);
886 process
= get_process (process
);
891 p
= XPROCESS (process
);
892 if (p
->raw_status_new
)
896 status
= XCAR (status
);
897 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
899 if (EQ (status
, Qexit
))
901 else if (EQ (p
->command
, Qt
))
903 else if (EQ (status
, Qrun
))
909 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
911 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
912 If PROCESS has not yet exited or died, return 0. */)
913 (register Lisp_Object process
)
915 CHECK_PROCESS (process
);
916 if (XPROCESS (process
)->raw_status_new
)
917 update_status (XPROCESS (process
));
918 if (CONSP (XPROCESS (process
)->status
))
919 return XCAR (XCDR (XPROCESS (process
)->status
));
920 return make_number (0);
923 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
924 doc
: /* Return the process id of PROCESS.
925 This is the pid of the external process which PROCESS uses or talks to.
926 For a network connection, this value is nil. */)
927 (register Lisp_Object process
)
931 CHECK_PROCESS (process
);
932 pid
= XPROCESS (process
)->pid
;
933 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
936 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
937 doc
: /* Return the name of PROCESS, as a string.
938 This is the name of the program invoked in PROCESS,
939 possibly modified to make it unique among process names. */)
940 (register Lisp_Object process
)
942 CHECK_PROCESS (process
);
943 return XPROCESS (process
)->name
;
946 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
947 doc
: /* Return the command that was executed to start PROCESS.
948 This is a list of strings, the first string being the program executed
949 and the rest of the strings being the arguments given to it.
950 For a network or serial process, this is nil (process is running) or t
951 \(process is stopped). */)
952 (register Lisp_Object process
)
954 CHECK_PROCESS (process
);
955 return XPROCESS (process
)->command
;
958 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
959 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
960 This is the terminal that the process itself reads and writes on,
961 not the name of the pty that Emacs uses to talk with that terminal. */)
962 (register Lisp_Object process
)
964 CHECK_PROCESS (process
);
965 return XPROCESS (process
)->tty_name
;
968 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
970 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
972 (register Lisp_Object process
, Lisp_Object buffer
)
974 struct Lisp_Process
*p
;
976 CHECK_PROCESS (process
);
978 CHECK_BUFFER (buffer
);
979 p
= XPROCESS (process
);
980 pset_buffer (p
, buffer
);
981 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
982 pset_childp (p
, Fplist_put (p
->childp
, QCbuffer
, buffer
));
983 setup_process_coding_systems (process
);
987 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
989 doc
: /* Return the buffer PROCESS is associated with.
990 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
991 (register Lisp_Object process
)
993 CHECK_PROCESS (process
);
994 return XPROCESS (process
)->buffer
;
997 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
999 doc
: /* Return the marker for the end of the last output from PROCESS. */)
1000 (register Lisp_Object process
)
1002 CHECK_PROCESS (process
);
1003 return XPROCESS (process
)->mark
;
1006 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
1008 doc
: /* Give PROCESS the filter function FILTER; nil means no filter.
1009 A value of t means stop accepting output from the process.
1011 When a process has a filter, its buffer is not used for output.
1012 Instead, each time it does output, the entire string of output is
1013 passed to the filter.
1015 The filter gets two arguments: the process and the string of output.
1016 The string argument is normally a multibyte string, except:
1017 - if the process' input coding system is no-conversion or raw-text,
1018 it is a unibyte string (the non-converted input), or else
1019 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1020 string (the result of converting the decoded input multibyte
1021 string to unibyte with `string-make-unibyte'). */)
1022 (register Lisp_Object process
, Lisp_Object filter
)
1024 struct Lisp_Process
*p
;
1026 CHECK_PROCESS (process
);
1027 p
= XPROCESS (process
);
1029 /* Don't signal an error if the process' input file descriptor
1030 is closed. This could make debugging Lisp more difficult,
1031 for example when doing something like
1033 (setq process (start-process ...))
1035 (set-process-filter process ...) */
1039 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
1041 FD_CLR (p
->infd
, &input_wait_mask
);
1042 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
1044 else if (EQ (p
->filter
, Qt
)
1045 /* Network or serial process not stopped: */
1046 && !EQ (p
->command
, Qt
))
1048 FD_SET (p
->infd
, &input_wait_mask
);
1049 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
1053 pset_filter (p
, filter
);
1054 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1055 pset_childp (p
, Fplist_put (p
->childp
, QCfilter
, filter
));
1056 setup_process_coding_systems (process
);
1060 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
1062 doc
: /* Returns the filter function of PROCESS; nil if none.
1063 See `set-process-filter' for more info on filter functions. */)
1064 (register Lisp_Object process
)
1066 CHECK_PROCESS (process
);
1067 return XPROCESS (process
)->filter
;
1070 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
1072 doc
: /* Give PROCESS the sentinel SENTINEL; nil for none.
1073 The sentinel is called as a function when the process changes state.
1074 It gets two arguments: the process, and a string describing the change. */)
1075 (register Lisp_Object process
, Lisp_Object sentinel
)
1077 struct Lisp_Process
*p
;
1079 CHECK_PROCESS (process
);
1080 p
= XPROCESS (process
);
1082 pset_sentinel (p
, sentinel
);
1083 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1084 pset_childp (p
, Fplist_put (p
->childp
, QCsentinel
, sentinel
));
1088 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1090 doc
: /* Return the sentinel of PROCESS; nil if none.
1091 See `set-process-sentinel' for more info on sentinels. */)
1092 (register Lisp_Object process
)
1094 CHECK_PROCESS (process
);
1095 return XPROCESS (process
)->sentinel
;
1098 DEFUN ("set-process-window-size", Fset_process_window_size
,
1099 Sset_process_window_size
, 3, 3, 0,
1100 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1101 (register Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1103 CHECK_PROCESS (process
);
1104 CHECK_RANGED_INTEGER (height
, 0, INT_MAX
);
1105 CHECK_RANGED_INTEGER (width
, 0, INT_MAX
);
1107 if (XPROCESS (process
)->infd
< 0
1108 || set_window_size (XPROCESS (process
)->infd
,
1109 XINT (height
), XINT (width
)) <= 0)
1115 DEFUN ("set-process-inherit-coding-system-flag",
1116 Fset_process_inherit_coding_system_flag
,
1117 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1118 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1119 If the second argument FLAG is non-nil, then the variable
1120 `buffer-file-coding-system' of the buffer associated with PROCESS
1121 will be bound to the value of the coding system used to decode
1124 This is useful when the coding system specified for the process buffer
1125 leaves either the character code conversion or the end-of-line conversion
1126 unspecified, or if the coding system used to decode the process output
1127 is more appropriate for saving the process buffer.
1129 Binding the variable `inherit-process-coding-system' to non-nil before
1130 starting the process is an alternative way of setting the inherit flag
1131 for the process which will run.
1133 This function returns FLAG. */)
1134 (register Lisp_Object process
, Lisp_Object flag
)
1136 CHECK_PROCESS (process
);
1137 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1141 DEFUN ("set-process-query-on-exit-flag",
1142 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1144 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1145 If the second argument FLAG is non-nil, Emacs will query the user before
1146 exiting or killing a buffer if PROCESS is running. This function
1148 (register Lisp_Object process
, Lisp_Object flag
)
1150 CHECK_PROCESS (process
);
1151 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1155 DEFUN ("process-query-on-exit-flag",
1156 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1158 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1159 (register Lisp_Object process
)
1161 CHECK_PROCESS (process
);
1162 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1165 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1167 doc
: /* Return the contact info of PROCESS; t for a real child.
1168 For a network or serial connection, the value depends on the optional
1169 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1170 SERVICE) for a network connection or (PORT SPEED) for a serial
1171 connection. If KEY is t, the complete contact information for the
1172 connection is returned, else the specific value for the keyword KEY is
1173 returned. See `make-network-process' or `make-serial-process' for a
1174 list of keywords. */)
1175 (register Lisp_Object process
, Lisp_Object key
)
1177 Lisp_Object contact
;
1179 CHECK_PROCESS (process
);
1180 contact
= XPROCESS (process
)->childp
;
1182 #ifdef DATAGRAM_SOCKETS
1183 if (DATAGRAM_CONN_P (process
)
1184 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1185 contact
= Fplist_put (contact
, QCremote
,
1186 Fprocess_datagram_address (process
));
1189 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1191 if (NILP (key
) && NETCONN_P (process
))
1192 return Fcons (Fplist_get (contact
, QChost
),
1193 Fcons (Fplist_get (contact
, QCservice
), Qnil
));
1194 if (NILP (key
) && SERIALCONN_P (process
))
1195 return Fcons (Fplist_get (contact
, QCport
),
1196 Fcons (Fplist_get (contact
, QCspeed
), Qnil
));
1197 return Fplist_get (contact
, key
);
1200 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1202 doc
: /* Return the plist of PROCESS. */)
1203 (register Lisp_Object process
)
1205 CHECK_PROCESS (process
);
1206 return XPROCESS (process
)->plist
;
1209 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1211 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1212 (register Lisp_Object process
, Lisp_Object plist
)
1214 CHECK_PROCESS (process
);
1217 pset_plist (XPROCESS (process
), plist
);
1221 #if 0 /* Turned off because we don't currently record this info
1222 in the process. Perhaps add it. */
1223 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1224 doc
: /* Return the connection type of PROCESS.
1225 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1226 a socket connection. */)
1227 (Lisp_Object process
)
1229 return XPROCESS (process
)->type
;
1233 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1234 doc
: /* Return the connection type of PROCESS.
1235 The value is either the symbol `real', `network', or `serial'.
1236 PROCESS may be a process, a buffer, the name of a process or buffer, or
1237 nil, indicating the current buffer's process. */)
1238 (Lisp_Object process
)
1241 proc
= get_process (process
);
1242 return XPROCESS (proc
)->type
;
1245 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1247 doc
: /* Convert network ADDRESS from internal format to a string.
1248 A 4 or 5 element vector represents an IPv4 address (with port number).
1249 An 8 or 9 element vector represents an IPv6 address (with port number).
1250 If optional second argument OMIT-PORT is non-nil, don't include a port
1251 number in the string, even when present in ADDRESS.
1252 Returns nil if format of ADDRESS is invalid. */)
1253 (Lisp_Object address
, Lisp_Object omit_port
)
1258 if (STRINGP (address
)) /* AF_LOCAL */
1261 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1263 register struct Lisp_Vector
*p
= XVECTOR (address
);
1264 ptrdiff_t size
= p
->header
.size
;
1265 Lisp_Object args
[10];
1268 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1270 args
[0] = build_string ("%d.%d.%d.%d");
1275 args
[0] = build_string ("%d.%d.%d.%d:%d");
1278 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1280 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1285 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1291 for (i
= 0; i
< nargs
; i
++)
1293 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1296 if (nargs
<= 5 /* IPv4 */
1297 && i
< 4 /* host, not port */
1298 && XINT (p
->contents
[i
]) > 255)
1301 args
[i
+1] = p
->contents
[i
];
1304 return Fformat (nargs
+1, args
);
1307 if (CONSP (address
))
1309 Lisp_Object args
[2];
1310 args
[0] = build_string ("<Family %d>");
1311 args
[1] = Fcar (address
);
1312 return Fformat (2, args
);
1318 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1319 doc
: /* Return a list of all processes. */)
1322 return Fmapcar (Qcdr
, Vprocess_alist
);
1325 /* Starting asynchronous inferior processes. */
1327 static Lisp_Object
start_process_unwind (Lisp_Object proc
);
1329 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1330 doc
: /* Start a program in a subprocess. Return the process object for it.
1331 NAME is name for process. It is modified if necessary to make it unique.
1332 BUFFER is the buffer (or buffer name) to associate with the process.
1334 Process output (both standard output and standard error streams) goes
1335 at end of BUFFER, unless you specify an output stream or filter
1336 function to handle the output. BUFFER may also be nil, meaning that
1337 this process is not associated with any buffer.
1339 PROGRAM is the program file name. It is searched for in `exec-path'
1340 (which see). If nil, just associate a pty with the buffer. Remaining
1341 arguments are strings to give program as arguments.
1343 If you want to separate standard output from standard error, invoke
1344 the command through a shell and redirect one of them using the shell
1347 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1348 (ptrdiff_t nargs
, Lisp_Object
*args
)
1350 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1351 register unsigned char **new_argv
;
1353 ptrdiff_t count
= SPECPDL_INDEX ();
1357 buffer
= Fget_buffer_create (buffer
);
1359 /* Make sure that the child will be able to chdir to the current
1360 buffer's current directory, or its unhandled equivalent. We
1361 can't just have the child check for an error when it does the
1362 chdir, since it's in a vfork.
1364 We have to GCPRO around this because Fexpand_file_name and
1365 Funhandled_file_name_directory might call a file name handling
1366 function. The argument list is protected by the caller, so all
1367 we really have to worry about is buffer. */
1369 struct gcpro gcpro1
, gcpro2
;
1371 current_dir
= BVAR (current_buffer
, directory
);
1373 GCPRO2 (buffer
, current_dir
);
1375 current_dir
= Funhandled_file_name_directory (current_dir
);
1376 if (NILP (current_dir
))
1377 /* If the file name handler says that current_dir is unreachable, use
1378 a sensible default. */
1379 current_dir
= build_string ("~/");
1380 current_dir
= expand_and_dir_to_file (current_dir
, Qnil
);
1381 if (NILP (Ffile_accessible_directory_p (current_dir
)))
1382 report_file_error ("Setting current directory",
1383 Fcons (BVAR (current_buffer
, directory
), Qnil
));
1389 CHECK_STRING (name
);
1393 if (!NILP (program
))
1394 CHECK_STRING (program
);
1396 proc
= make_process (name
);
1397 /* If an error occurs and we can't start the process, we want to
1398 remove it from the process list. This means that each error
1399 check in create_process doesn't need to call remove_process
1400 itself; it's all taken care of here. */
1401 record_unwind_protect (start_process_unwind
, proc
);
1403 pset_childp (XPROCESS (proc
), Qt
);
1404 pset_plist (XPROCESS (proc
), Qnil
);
1405 pset_type (XPROCESS (proc
), Qreal
);
1406 pset_buffer (XPROCESS (proc
), buffer
);
1407 pset_sentinel (XPROCESS (proc
), Qnil
);
1408 pset_filter (XPROCESS (proc
), Qnil
);
1409 pset_command (XPROCESS (proc
), Flist (nargs
- 2, args
+ 2));
1412 /* AKA GNUTLS_INITSTAGE(proc). */
1413 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1414 pset_gnutls_cred_type (XPROCESS (proc
), Qnil
);
1417 #ifdef ADAPTIVE_READ_BUFFERING
1418 XPROCESS (proc
)->adaptive_read_buffering
1419 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1420 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1423 /* Make the process marker point into the process buffer (if any). */
1424 if (BUFFERP (buffer
))
1425 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1426 BUF_ZV (XBUFFER (buffer
)),
1427 BUF_ZV_BYTE (XBUFFER (buffer
)));
1430 /* Decide coding systems for communicating with the process. Here
1431 we don't setup the structure coding_system nor pay attention to
1432 unibyte mode. They are done in create_process. */
1434 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1435 Lisp_Object coding_systems
= Qt
;
1436 Lisp_Object val
, *args2
;
1437 struct gcpro gcpro1
, gcpro2
;
1439 val
= Vcoding_system_for_read
;
1442 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1443 args2
[0] = Qstart_process
;
1444 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1445 GCPRO2 (proc
, current_dir
);
1446 if (!NILP (program
))
1447 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1449 if (CONSP (coding_systems
))
1450 val
= XCAR (coding_systems
);
1451 else if (CONSP (Vdefault_process_coding_system
))
1452 val
= XCAR (Vdefault_process_coding_system
);
1454 pset_decode_coding_system (XPROCESS (proc
), val
);
1456 val
= Vcoding_system_for_write
;
1459 if (EQ (coding_systems
, Qt
))
1461 args2
= alloca ((nargs
+ 1) * sizeof *args2
);
1462 args2
[0] = Qstart_process
;
1463 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1464 GCPRO2 (proc
, current_dir
);
1465 if (!NILP (program
))
1466 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1469 if (CONSP (coding_systems
))
1470 val
= XCDR (coding_systems
);
1471 else if (CONSP (Vdefault_process_coding_system
))
1472 val
= XCDR (Vdefault_process_coding_system
);
1474 pset_encode_coding_system (XPROCESS (proc
), val
);
1475 /* Note: At this moment, the above coding system may leave
1476 text-conversion or eol-conversion unspecified. They will be
1477 decided after we read output from the process and decode it by
1478 some coding system, or just before we actually send a text to
1483 pset_decoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1484 XPROCESS (proc
)->decoding_carryover
= 0;
1485 pset_encoding_buf (XPROCESS (proc
), empty_unibyte_string
);
1487 XPROCESS (proc
)->inherit_coding_system_flag
1488 = !(NILP (buffer
) || !inherit_process_coding_system
);
1490 if (!NILP (program
))
1492 /* If program file name is not absolute, search our path for it.
1493 Put the name we will really use in TEM. */
1494 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1495 && !(SCHARS (program
) > 1
1496 && IS_DEVICE_SEP (SREF (program
, 1))))
1498 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1501 GCPRO4 (name
, program
, buffer
, current_dir
);
1502 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
, make_number (X_OK
));
1505 report_file_error ("Searching for program", Fcons (program
, Qnil
));
1506 tem
= Fexpand_file_name (tem
, Qnil
);
1510 if (!NILP (Ffile_directory_p (program
)))
1511 error ("Specified program for new process is a directory");
1515 /* If program file name starts with /: for quoting a magic name,
1517 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1518 && SREF (tem
, 1) == ':')
1519 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1522 Lisp_Object arg_encoding
= Qnil
;
1523 struct gcpro gcpro1
;
1526 /* Encode the file name and put it in NEW_ARGV.
1527 That's where the child will use it to execute the program. */
1528 tem
= Fcons (ENCODE_FILE (tem
), Qnil
);
1530 /* Here we encode arguments by the coding system used for sending
1531 data to the process. We don't support using different coding
1532 systems for encoding arguments and for encoding data sent to the
1535 for (i
= 3; i
< nargs
; i
++)
1537 tem
= Fcons (args
[i
], tem
);
1538 CHECK_STRING (XCAR (tem
));
1539 if (STRING_MULTIBYTE (XCAR (tem
)))
1541 if (NILP (arg_encoding
))
1542 arg_encoding
= (complement_process_encoding_system
1543 (XPROCESS (proc
)->encode_coding_system
));
1545 code_convert_string_norecord
1546 (XCAR (tem
), arg_encoding
, 1));
1553 /* Now that everything is encoded we can collect the strings into
1555 new_argv
= alloca ((nargs
- 1) * sizeof *new_argv
);
1556 new_argv
[nargs
- 2] = 0;
1558 for (i
= nargs
- 2; i
-- != 0; )
1560 new_argv
[i
] = SDATA (XCAR (tem
));
1564 create_process (proc
, (char **) new_argv
, current_dir
);
1569 return unbind_to (count
, proc
);
1572 /* This function is the unwind_protect form for Fstart_process. If
1573 PROC doesn't have its pid set, then we know someone has signaled
1574 an error and the process wasn't started successfully, so we should
1575 remove it from the process list. */
1577 start_process_unwind (Lisp_Object proc
)
1579 if (!PROCESSP (proc
))
1582 /* Was PROC started successfully?
1583 -2 is used for a pty with no process, eg for gdb. */
1584 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1585 remove_process (proc
);
1591 create_process_1 (struct atimer
*timer
)
1593 /* Nothing to do. */
1598 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1600 int inchannel
, outchannel
;
1603 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1604 int wait_child_setup
[2];
1608 struct sigaction sigint_action
;
1609 struct sigaction sigquit_action
;
1610 struct sigaction sigpipe_action
;
1612 struct sigaction sighup_action
;
1614 /* Use volatile to protect variables from being clobbered by longjmp. */
1615 volatile int forkin
, forkout
;
1616 volatile int pty_flag
= 0;
1618 inchannel
= outchannel
= -1;
1621 if (!NILP (Vprocess_connection_type
))
1622 outchannel
= inchannel
= allocate_pty ();
1626 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1627 /* On most USG systems it does not work to open the pty's tty here,
1628 then close it and reopen it in the child. */
1630 /* Don't let this terminal become our controlling terminal
1631 (in case we don't have one). */
1632 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1634 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
, 0);
1637 report_file_error ("Opening pty", Qnil
);
1639 forkin
= forkout
= -1;
1640 #endif /* not USG, or USG_SUBTTY_WORKS */
1644 #endif /* HAVE_PTYS */
1649 report_file_error ("Creating pipe", Qnil
);
1655 emacs_close (inchannel
);
1656 emacs_close (forkout
);
1657 report_file_error ("Creating pipe", Qnil
);
1663 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1667 tem
= pipe (wait_child_setup
);
1669 report_file_error ("Creating pipe", Qnil
);
1670 tem
= fcntl (wait_child_setup
[1], F_GETFD
, 0);
1672 tem
= fcntl (wait_child_setup
[1], F_SETFD
, tem
| FD_CLOEXEC
);
1675 emacs_close (wait_child_setup
[0]);
1676 emacs_close (wait_child_setup
[1]);
1677 report_file_error ("Setting file descriptor flags", Qnil
);
1683 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1684 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1687 fcntl (inchannel
, F_SETFL
, O_NDELAY
);
1688 fcntl (outchannel
, F_SETFL
, O_NDELAY
);
1692 /* Record this as an active process, with its channels.
1693 As a result, child_setup will close Emacs's side of the pipes. */
1694 chan_process
[inchannel
] = process
;
1695 XPROCESS (process
)->infd
= inchannel
;
1696 XPROCESS (process
)->outfd
= outchannel
;
1698 /* Previously we recorded the tty descriptor used in the subprocess.
1699 It was only used for getting the foreground tty process, so now
1700 we just reopen the device (see emacs_get_tty_pgrp) as this is
1701 more portable (see USG_SUBTTY_WORKS above). */
1703 XPROCESS (process
)->pty_flag
= pty_flag
;
1704 pset_status (XPROCESS (process
), Qrun
);
1706 /* Delay interrupts until we have a chance to store
1707 the new fork's pid in its process structure */
1708 sigemptyset (&blocked
);
1710 sigaddset (&blocked
, SIGCHLD
);
1712 #ifdef HAVE_WORKING_VFORK
1713 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1714 this sets the parent's signal handlers as well as the child's.
1715 So delay all interrupts whose handlers the child might munge,
1716 and record the current handlers so they can be restored later. */
1717 sigaddset (&blocked
, SIGINT
); sigaction (SIGINT
, 0, &sigint_action
);
1718 sigaddset (&blocked
, SIGQUIT
); sigaction (SIGQUIT
, 0, &sigquit_action
);
1719 sigaddset (&blocked
, SIGPIPE
); sigaction (SIGPIPE
, 0, &sigpipe_action
);
1721 sigaddset (&blocked
, SIGHUP
); sigaction (SIGHUP
, 0, &sighup_action
);
1723 #endif /* HAVE_WORKING_VFORK */
1724 pthread_sigmask (SIG_BLOCK
, &blocked
, &procmask
);
1726 FD_SET (inchannel
, &input_wait_mask
);
1727 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1728 if (inchannel
> max_process_desc
)
1729 max_process_desc
= inchannel
;
1731 /* Until we store the proper pid, enable sigchld_handler
1732 to recognize an unknown pid as standing for this process.
1733 It is very important not to let this `marker' value stay
1734 in the table after this function has returned; if it does
1735 it might cause call-process to hang and subsequent asynchronous
1736 processes to get their return values scrambled. */
1737 XPROCESS (process
)->pid
= -1;
1739 /* This must be called after the above line because it may signal an
1741 setup_process_coding_systems (process
);
1746 /* child_setup must clobber environ on systems with true vfork.
1747 Protect it from permanent change. */
1748 char **save_environ
= environ
;
1749 volatile Lisp_Object encoded_current_dir
= ENCODE_FILE (current_dir
);
1754 #endif /* not WINDOWSNT */
1756 int xforkin
= forkin
;
1757 int xforkout
= forkout
;
1759 #if 0 /* This was probably a mistake--it duplicates code later on,
1760 but fails to handle all the cases. */
1761 /* Make sure SIGCHLD is not blocked in the child. */
1762 sigsetmask (SIGEMPTYMASK
);
1765 /* Make the pty be the controlling terminal of the process. */
1767 /* First, disconnect its current controlling terminal. */
1769 /* We tried doing setsid only if pty_flag, but it caused
1770 process_set_signal to fail on SGI when using a pipe. */
1772 /* Make the pty's terminal the controlling terminal. */
1773 if (pty_flag
&& xforkin
>= 0)
1776 /* We ignore the return value
1777 because faith@cs.unc.edu says that is necessary on Linux. */
1778 ioctl (xforkin
, TIOCSCTTY
, 0);
1781 #else /* not HAVE_SETSID */
1783 /* It's very important to call setpgrp here and no time
1784 afterwards. Otherwise, we lose our controlling tty which
1785 is set when we open the pty. */
1788 #endif /* not HAVE_SETSID */
1789 #if defined (LDISC1)
1790 if (pty_flag
&& xforkin
>= 0)
1793 tcgetattr (xforkin
, &t
);
1795 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1796 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1799 #if defined (NTTYDISC) && defined (TIOCSETD)
1800 if (pty_flag
&& xforkin
>= 0)
1802 /* Use new line discipline. */
1803 int ldisc
= NTTYDISC
;
1804 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1809 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1810 can do TIOCSPGRP only to the process's controlling tty. */
1813 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1814 I can't test it since I don't have 4.3. */
1815 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1818 ioctl (j
, TIOCNOTTY
, 0);
1822 /* In order to get a controlling terminal on some versions
1823 of BSD, it is necessary to put the process in pgrp 0
1824 before it opens the terminal. */
1832 #endif /* TIOCNOTTY */
1834 #if !defined (DONT_REOPEN_PTY)
1835 /*** There is a suggestion that this ought to be a
1836 conditional on TIOCSPGRP,
1837 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1838 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1839 that system does seem to need this code, even though
1840 both HAVE_SETSID and TIOCSCTTY are defined. */
1841 /* Now close the pty (if we had it open) and reopen it.
1842 This makes the pty the controlling terminal of the subprocess. */
1846 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1849 emacs_close (xforkin
);
1850 xforkout
= xforkin
= emacs_open (pty_name
, O_RDWR
, 0);
1854 emacs_write (1, "Couldn't open the pty terminal ", 31);
1855 emacs_write (1, pty_name
, strlen (pty_name
));
1856 emacs_write (1, "\n", 1);
1861 #endif /* not DONT_REOPEN_PTY */
1863 #ifdef SETUP_SLAVE_PTY
1868 #endif /* SETUP_SLAVE_PTY */
1870 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1871 Now reenable it in the child, so it will die when we want it to. */
1873 signal (SIGHUP
, SIG_DFL
);
1875 #endif /* HAVE_PTYS */
1877 signal (SIGINT
, SIG_DFL
);
1878 signal (SIGQUIT
, SIG_DFL
);
1879 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1881 signal (SIGPIPE
, SIG_DFL
);
1883 /* Stop blocking signals in the child. */
1884 pthread_sigmask (SIG_SETMASK
, &procmask
, 0);
1887 child_setup_tty (xforkout
);
1889 pid
= child_setup (xforkin
, xforkout
, xforkout
,
1890 new_argv
, 1, encoded_current_dir
);
1891 #else /* not WINDOWSNT */
1893 emacs_close (wait_child_setup
[0]);
1895 child_setup (xforkin
, xforkout
, xforkout
,
1896 new_argv
, 1, encoded_current_dir
);
1897 #endif /* not WINDOWSNT */
1899 environ
= save_environ
;
1904 /* This runs in the Emacs process. */
1908 emacs_close (forkin
);
1909 if (forkin
!= forkout
&& forkout
>= 0)
1910 emacs_close (forkout
);
1914 /* vfork succeeded. */
1915 XPROCESS (process
)->pid
= pid
;
1918 register_child (pid
, inchannel
);
1919 #endif /* WINDOWSNT */
1921 /* If the subfork execv fails, and it exits,
1922 this close hangs. I don't know why.
1923 So have an interrupt jar it loose. */
1925 struct atimer
*timer
;
1926 EMACS_TIME offset
= make_emacs_time (1, 0);
1929 timer
= start_atimer (ATIMER_RELATIVE
, offset
, create_process_1
, 0);
1932 emacs_close (forkin
);
1934 cancel_atimer (timer
);
1938 if (forkin
!= forkout
&& forkout
>= 0)
1939 emacs_close (forkout
);
1943 pset_tty_name (XPROCESS (process
), build_string (pty_name
));
1946 pset_tty_name (XPROCESS (process
), Qnil
);
1948 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1949 /* Wait for child_setup to complete in case that vfork is
1950 actually defined as fork. The descriptor wait_child_setup[1]
1951 of a pipe is closed at the child side either by close-on-exec
1952 on successful execvp or the _exit call in child_setup. */
1956 emacs_close (wait_child_setup
[1]);
1957 emacs_read (wait_child_setup
[0], &dummy
, 1);
1958 emacs_close (wait_child_setup
[0]);
1963 /* Restore the signal state whether vfork succeeded or not.
1964 (We will signal an error, below, if it failed.) */
1965 #ifdef HAVE_WORKING_VFORK
1966 /* Restore the parent's signal handlers. */
1967 sigaction (SIGINT
, &sigint_action
, 0);
1968 sigaction (SIGQUIT
, &sigquit_action
, 0);
1969 sigaction (SIGPIPE
, &sigpipe_action
, 0);
1971 sigaction (SIGHUP
, &sighup_action
, 0);
1973 #endif /* HAVE_WORKING_VFORK */
1974 /* Stop blocking signals in the parent. */
1975 pthread_sigmask (SIG_SETMASK
, &procmask
, 0);
1977 /* Now generate the error if vfork failed. */
1979 report_file_error ("Doing vfork", Qnil
);
1983 create_pty (Lisp_Object process
)
1985 int inchannel
, outchannel
;
1988 inchannel
= outchannel
= -1;
1991 if (!NILP (Vprocess_connection_type
))
1992 outchannel
= inchannel
= allocate_pty ();
1996 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1997 /* On most USG systems it does not work to open the pty's tty here,
1998 then close it and reopen it in the child. */
2000 /* Don't let this terminal become our controlling terminal
2001 (in case we don't have one). */
2002 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
2004 int forkout
= emacs_open (pty_name
, O_RDWR
, 0);
2007 report_file_error ("Opening pty", Qnil
);
2008 #if defined (DONT_REOPEN_PTY)
2009 /* In the case that vfork is defined as fork, the parent process
2010 (Emacs) may send some data before the child process completes
2011 tty options setup. So we setup tty before forking. */
2012 child_setup_tty (forkout
);
2013 #endif /* DONT_REOPEN_PTY */
2014 #endif /* not USG, or USG_SUBTTY_WORKS */
2017 #endif /* HAVE_PTYS */
2020 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
2021 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
2024 fcntl (inchannel
, F_SETFL
, O_NDELAY
);
2025 fcntl (outchannel
, F_SETFL
, O_NDELAY
);
2029 /* Record this as an active process, with its channels.
2030 As a result, child_setup will close Emacs's side of the pipes. */
2031 chan_process
[inchannel
] = process
;
2032 XPROCESS (process
)->infd
= inchannel
;
2033 XPROCESS (process
)->outfd
= outchannel
;
2035 /* Previously we recorded the tty descriptor used in the subprocess.
2036 It was only used for getting the foreground tty process, so now
2037 we just reopen the device (see emacs_get_tty_pgrp) as this is
2038 more portable (see USG_SUBTTY_WORKS above). */
2040 XPROCESS (process
)->pty_flag
= pty_flag
;
2041 pset_status (XPROCESS (process
), Qrun
);
2042 setup_process_coding_systems (process
);
2044 FD_SET (inchannel
, &input_wait_mask
);
2045 FD_SET (inchannel
, &non_keyboard_wait_mask
);
2046 if (inchannel
> max_process_desc
)
2047 max_process_desc
= inchannel
;
2049 XPROCESS (process
)->pid
= -2;
2052 pset_tty_name (XPROCESS (process
), build_string (pty_name
));
2055 pset_tty_name (XPROCESS (process
), Qnil
);
2059 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2060 The address family of sa is not included in the result. */
2063 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2065 Lisp_Object address
;
2068 register struct Lisp_Vector
*p
;
2070 /* Workaround for a bug in getsockname on BSD: Names bound to
2071 sockets in the UNIX domain are inaccessible; getsockname returns
2072 a zero length name. */
2073 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2074 return empty_unibyte_string
;
2076 switch (sa
->sa_family
)
2080 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2081 len
= sizeof (sin
->sin_addr
) + 1;
2082 address
= Fmake_vector (make_number (len
), Qnil
);
2083 p
= XVECTOR (address
);
2084 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2085 cp
= (unsigned char *) &sin
->sin_addr
;
2091 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2092 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2093 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2094 address
= Fmake_vector (make_number (len
), Qnil
);
2095 p
= XVECTOR (address
);
2096 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2097 for (i
= 0; i
< len
; i
++)
2098 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2102 #ifdef HAVE_LOCAL_SOCKETS
2105 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2106 for (i
= 0; i
< sizeof (sockun
->sun_path
); i
++)
2107 if (sockun
->sun_path
[i
] == 0)
2109 return make_unibyte_string (sockun
->sun_path
, i
);
2113 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2114 address
= Fcons (make_number (sa
->sa_family
),
2115 Fmake_vector (make_number (len
), Qnil
));
2116 p
= XVECTOR (XCDR (address
));
2117 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2123 p
->contents
[i
++] = make_number (*cp
++);
2129 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2132 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2134 register struct Lisp_Vector
*p
;
2136 if (VECTORP (address
))
2138 p
= XVECTOR (address
);
2139 if (p
->header
.size
== 5)
2142 return sizeof (struct sockaddr_in
);
2145 else if (p
->header
.size
== 9)
2147 *familyp
= AF_INET6
;
2148 return sizeof (struct sockaddr_in6
);
2152 #ifdef HAVE_LOCAL_SOCKETS
2153 else if (STRINGP (address
))
2155 *familyp
= AF_LOCAL
;
2156 return sizeof (struct sockaddr_un
);
2159 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2160 && VECTORP (XCDR (address
)))
2162 struct sockaddr
*sa
;
2163 *familyp
= XINT (XCAR (address
));
2164 p
= XVECTOR (XCDR (address
));
2165 return p
->header
.size
+ sizeof (sa
->sa_family
);
2170 /* Convert an address object (vector or string) to an internal sockaddr.
2172 The address format has been basically validated by
2173 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2174 it could have come from user data. So if FAMILY is not valid,
2175 we return after zeroing *SA. */
2178 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2180 register struct Lisp_Vector
*p
;
2181 register unsigned char *cp
= NULL
;
2185 memset (sa
, 0, len
);
2187 if (VECTORP (address
))
2189 p
= XVECTOR (address
);
2190 if (family
== AF_INET
)
2192 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2193 len
= sizeof (sin
->sin_addr
) + 1;
2194 hostport
= XINT (p
->contents
[--len
]);
2195 sin
->sin_port
= htons (hostport
);
2196 cp
= (unsigned char *)&sin
->sin_addr
;
2197 sa
->sa_family
= family
;
2200 else if (family
== AF_INET6
)
2202 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2203 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2204 len
= sizeof (sin6
->sin6_addr
) + 1;
2205 hostport
= XINT (p
->contents
[--len
]);
2206 sin6
->sin6_port
= htons (hostport
);
2207 for (i
= 0; i
< len
; i
++)
2208 if (INTEGERP (p
->contents
[i
]))
2210 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2213 sa
->sa_family
= family
;
2220 else if (STRINGP (address
))
2222 #ifdef HAVE_LOCAL_SOCKETS
2223 if (family
== AF_LOCAL
)
2225 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2226 cp
= SDATA (address
);
2227 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2228 sockun
->sun_path
[i
] = *cp
++;
2229 sa
->sa_family
= family
;
2236 p
= XVECTOR (XCDR (address
));
2237 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2240 for (i
= 0; i
< len
; i
++)
2241 if (INTEGERP (p
->contents
[i
]))
2242 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2245 #ifdef DATAGRAM_SOCKETS
2246 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2248 doc
: /* Get the current datagram address associated with PROCESS. */)
2249 (Lisp_Object process
)
2253 CHECK_PROCESS (process
);
2255 if (!DATAGRAM_CONN_P (process
))
2258 channel
= XPROCESS (process
)->infd
;
2259 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2260 datagram_address
[channel
].len
);
2263 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2265 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2266 Returns nil upon error setting address, ADDRESS otherwise. */)
2267 (Lisp_Object process
, Lisp_Object address
)
2272 CHECK_PROCESS (process
);
2274 if (!DATAGRAM_CONN_P (process
))
2277 channel
= XPROCESS (process
)->infd
;
2279 len
= get_lisp_to_sockaddr_size (address
, &family
);
2280 if (datagram_address
[channel
].len
!= len
)
2282 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2288 static const struct socket_options
{
2289 /* The name of this option. Should be lowercase version of option
2290 name without SO_ prefix. */
2292 /* Option level SOL_... */
2294 /* Option number SO_... */
2296 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2297 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2298 } socket_options
[] =
2300 #ifdef SO_BINDTODEVICE
2301 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2304 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2307 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2310 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2313 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2316 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2319 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2322 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2324 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2327 /* Set option OPT to value VAL on socket S.
2329 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2330 Signals an error if setting a known option fails.
2334 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2337 const struct socket_options
*sopt
;
2342 name
= SSDATA (SYMBOL_NAME (opt
));
2343 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2344 if (strcmp (name
, sopt
->name
) == 0)
2347 switch (sopt
->opttype
)
2352 optval
= NILP (val
) ? 0 : 1;
2353 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2354 &optval
, sizeof (optval
));
2361 if (TYPE_RANGED_INTEGERP (int, val
))
2362 optval
= XINT (val
);
2364 error ("Bad option value for %s", name
);
2365 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2366 &optval
, sizeof (optval
));
2370 #ifdef SO_BINDTODEVICE
2373 char devname
[IFNAMSIZ
+1];
2375 /* This is broken, at least in the Linux 2.4 kernel.
2376 To unbind, the arg must be a zero integer, not the empty string.
2377 This should work on all systems. KFS. 2003-09-23. */
2378 memset (devname
, 0, sizeof devname
);
2381 char *arg
= SSDATA (val
);
2382 int len
= min (strlen (arg
), IFNAMSIZ
);
2383 memcpy (devname
, arg
, len
);
2385 else if (!NILP (val
))
2386 error ("Bad option value for %s", name
);
2387 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2396 struct linger linger
;
2399 linger
.l_linger
= 0;
2400 if (TYPE_RANGED_INTEGERP (int, val
))
2401 linger
.l_linger
= XINT (val
);
2403 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2404 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2405 &linger
, sizeof (linger
));
2415 report_file_error ("Cannot set network option",
2416 Fcons (opt
, Fcons (val
, Qnil
)));
2417 return (1 << sopt
->optbit
);
2421 DEFUN ("set-network-process-option",
2422 Fset_network_process_option
, Sset_network_process_option
,
2424 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2425 See `make-network-process' for a list of options and values.
2426 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2427 OPTION is not a supported option, return nil instead; otherwise return t. */)
2428 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2431 struct Lisp_Process
*p
;
2433 CHECK_PROCESS (process
);
2434 p
= XPROCESS (process
);
2435 if (!NETCONN1_P (p
))
2436 error ("Process is not a network process");
2440 error ("Process is not running");
2442 if (set_socket_option (s
, option
, value
))
2444 pset_childp (p
, Fplist_put (p
->childp
, option
, value
));
2448 if (NILP (no_error
))
2449 error ("Unknown or unsupported option");
2455 DEFUN ("serial-process-configure",
2456 Fserial_process_configure
,
2457 Sserial_process_configure
,
2459 doc
: /* Configure speed, bytesize, etc. of a serial process.
2461 Arguments are specified as keyword/argument pairs. Attributes that
2462 are not given are re-initialized from the process's current
2463 configuration (available via the function `process-contact') or set to
2464 reasonable default values. The following arguments are defined:
2470 -- Any of these arguments can be given to identify the process that is
2471 to be configured. If none of these arguments is given, the current
2472 buffer's process is used.
2474 :speed SPEED -- SPEED is the speed of the serial port in bits per
2475 second, also called baud rate. Any value can be given for SPEED, but
2476 most serial ports work only at a few defined values between 1200 and
2477 115200, with 9600 being the most common value. If SPEED is nil, the
2478 serial port is not configured any further, i.e., all other arguments
2479 are ignored. This may be useful for special serial ports such as
2480 Bluetooth-to-serial converters which can only be configured through AT
2481 commands. A value of nil for SPEED can be used only when passed
2482 through `make-serial-process' or `serial-term'.
2484 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2485 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2487 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2488 `odd' (use odd parity), or the symbol `even' (use even parity). If
2489 PARITY is not given, no parity is used.
2491 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2492 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2493 is not given or nil, 1 stopbit is used.
2495 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2496 flowcontrol to be used, which is either nil (don't use flowcontrol),
2497 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2498 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2499 flowcontrol is used.
2501 `serial-process-configure' is called by `make-serial-process' for the
2502 initial configuration of the serial port.
2506 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2508 \(serial-process-configure
2509 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2511 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2513 usage: (serial-process-configure &rest ARGS) */)
2514 (ptrdiff_t nargs
, Lisp_Object
*args
)
2516 struct Lisp_Process
*p
;
2517 Lisp_Object contact
= Qnil
;
2518 Lisp_Object proc
= Qnil
;
2519 struct gcpro gcpro1
;
2521 contact
= Flist (nargs
, args
);
2524 proc
= Fplist_get (contact
, QCprocess
);
2526 proc
= Fplist_get (contact
, QCname
);
2528 proc
= Fplist_get (contact
, QCbuffer
);
2530 proc
= Fplist_get (contact
, QCport
);
2531 proc
= get_process (proc
);
2532 p
= XPROCESS (proc
);
2533 if (!EQ (p
->type
, Qserial
))
2534 error ("Not a serial process");
2536 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2542 serial_configure (p
, contact
);
2548 /* Used by make-serial-process to recover from errors. */
2550 make_serial_process_unwind (Lisp_Object proc
)
2552 if (!PROCESSP (proc
))
2554 remove_process (proc
);
2558 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2560 doc
: /* Create and return a serial port process.
2562 In Emacs, serial port connections are represented by process objects,
2563 so input and output work as for subprocesses, and `delete-process'
2564 closes a serial port connection. However, a serial process has no
2565 process id, it cannot be signaled, and the status codes are different
2566 from normal processes.
2568 `make-serial-process' creates a process and a buffer, on which you
2569 probably want to use `process-send-string'. Try \\[serial-term] for
2570 an interactive terminal. See below for examples.
2572 Arguments are specified as keyword/argument pairs. The following
2573 arguments are defined:
2575 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2576 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2577 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2578 the backslashes in strings).
2580 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2581 which this function calls.
2583 :name NAME -- NAME is the name of the process. If NAME is not given,
2584 the value of PORT is used.
2586 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2587 with the process. Process output goes at the end of that buffer,
2588 unless you specify an output stream or filter function to handle the
2589 output. If BUFFER is not given, the value of NAME is used.
2591 :coding CODING -- If CODING is a symbol, it specifies the coding
2592 system used for both reading and writing for this process. If CODING
2593 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2594 ENCODING is used for writing.
2596 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2597 the process is running. If BOOL is not given, query before exiting.
2599 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2600 In the stopped state, a serial process does not accept incoming data,
2601 but you can send outgoing data. The stopped state is cleared by
2602 `continue-process' and set by `stop-process'.
2604 :filter FILTER -- Install FILTER as the process filter.
2606 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2608 :plist PLIST -- Install PLIST as the initial plist of the process.
2614 -- This function calls `serial-process-configure' to handle these
2617 The original argument list, possibly modified by later configuration,
2618 is available via the function `process-contact'.
2622 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2624 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2626 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2628 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2630 usage: (make-serial-process &rest ARGS) */)
2631 (ptrdiff_t nargs
, Lisp_Object
*args
)
2634 Lisp_Object proc
, contact
, port
;
2635 struct Lisp_Process
*p
;
2636 struct gcpro gcpro1
;
2637 Lisp_Object name
, buffer
;
2638 Lisp_Object tem
, val
;
2639 ptrdiff_t specpdl_count
= -1;
2644 contact
= Flist (nargs
, args
);
2647 port
= Fplist_get (contact
, QCport
);
2649 error ("No port specified");
2650 CHECK_STRING (port
);
2652 if (NILP (Fplist_member (contact
, QCspeed
)))
2653 error (":speed not specified");
2654 if (!NILP (Fplist_get (contact
, QCspeed
)))
2655 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2657 name
= Fplist_get (contact
, QCname
);
2660 CHECK_STRING (name
);
2661 proc
= make_process (name
);
2662 specpdl_count
= SPECPDL_INDEX ();
2663 record_unwind_protect (make_serial_process_unwind
, proc
);
2664 p
= XPROCESS (proc
);
2666 fd
= serial_open (SSDATA (port
));
2669 if (fd
> max_process_desc
)
2670 max_process_desc
= fd
;
2671 chan_process
[fd
] = proc
;
2673 buffer
= Fplist_get (contact
, QCbuffer
);
2676 buffer
= Fget_buffer_create (buffer
);
2677 pset_buffer (p
, buffer
);
2679 pset_childp (p
, contact
);
2680 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
2681 pset_type (p
, Qserial
);
2682 pset_sentinel (p
, Fplist_get (contact
, QCsentinel
));
2683 pset_filter (p
, Fplist_get (contact
, QCfilter
));
2685 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2686 p
->kill_without_query
= 1;
2687 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2688 pset_command (p
, Qt
);
2691 if (!EQ (p
->command
, Qt
))
2693 FD_SET (fd
, &input_wait_mask
);
2694 FD_SET (fd
, &non_keyboard_wait_mask
);
2697 if (BUFFERP (buffer
))
2699 set_marker_both (p
->mark
, buffer
,
2700 BUF_ZV (XBUFFER (buffer
)),
2701 BUF_ZV_BYTE (XBUFFER (buffer
)));
2704 tem
= Fplist_member (contact
, QCcoding
);
2705 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2711 val
= XCAR (XCDR (tem
));
2715 else if (!NILP (Vcoding_system_for_read
))
2716 val
= Vcoding_system_for_read
;
2717 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2718 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2720 pset_decode_coding_system (p
, val
);
2725 val
= XCAR (XCDR (tem
));
2729 else if (!NILP (Vcoding_system_for_write
))
2730 val
= Vcoding_system_for_write
;
2731 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2732 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2734 pset_encode_coding_system (p
, val
);
2736 setup_process_coding_systems (proc
);
2737 pset_decoding_buf (p
, empty_unibyte_string
);
2738 p
->decoding_carryover
= 0;
2739 pset_encoding_buf (p
, empty_unibyte_string
);
2740 p
->inherit_coding_system_flag
2741 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2743 Fserial_process_configure (nargs
, args
);
2745 specpdl_ptr
= specpdl
+ specpdl_count
;
2751 /* Create a network stream/datagram client/server process. Treated
2752 exactly like a normal process when reading and writing. Primary
2753 differences are in status display and process deletion. A network
2754 connection has no PID; you cannot signal it. All you can do is
2755 stop/continue it and deactivate/close it via delete-process */
2757 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2759 doc
: /* Create and return a network server or client process.
2761 In Emacs, network connections are represented by process objects, so
2762 input and output work as for subprocesses and `delete-process' closes
2763 a network connection. However, a network process has no process id,
2764 it cannot be signaled, and the status codes are different from normal
2767 Arguments are specified as keyword/argument pairs. The following
2768 arguments are defined:
2770 :name NAME -- NAME is name for process. It is modified if necessary
2773 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2774 with the process. Process output goes at end of that buffer, unless
2775 you specify an output stream or filter function to handle the output.
2776 BUFFER may be also nil, meaning that this process is not associated
2779 :host HOST -- HOST is name of the host to connect to, or its IP
2780 address. The symbol `local' specifies the local host. If specified
2781 for a server process, it must be a valid name or address for the local
2782 host, and only clients connecting to that address will be accepted.
2784 :service SERVICE -- SERVICE is name of the service desired, or an
2785 integer specifying a port number to connect to. If SERVICE is t,
2786 a random port number is selected for the server. (If Emacs was
2787 compiled with getaddrinfo, a port number can also be specified as a
2788 string, e.g. "80", as well as an integer. This is not portable.)
2790 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2791 stream type connection, `datagram' creates a datagram type connection,
2792 `seqpacket' creates a reliable datagram connection.
2794 :family FAMILY -- FAMILY is the address (and protocol) family for the
2795 service specified by HOST and SERVICE. The default (nil) is to use
2796 whatever address family (IPv4 or IPv6) that is defined for the host
2797 and port number specified by HOST and SERVICE. Other address families
2799 local -- for a local (i.e. UNIX) address specified by SERVICE.
2800 ipv4 -- use IPv4 address family only.
2801 ipv6 -- use IPv6 address family only.
2803 :local ADDRESS -- ADDRESS is the local address used for the connection.
2804 This parameter is ignored when opening a client process. When specified
2805 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2807 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2808 connection. This parameter is ignored when opening a stream server
2809 process. For a datagram server process, it specifies the initial
2810 setting of the remote datagram address. When specified for a client
2811 process, the FAMILY, HOST, and SERVICE args are ignored.
2813 The format of ADDRESS depends on the address family:
2814 - An IPv4 address is represented as an vector of integers [A B C D P]
2815 corresponding to numeric IP address A.B.C.D and port number P.
2816 - A local address is represented as a string with the address in the
2817 local address space.
2818 - An "unsupported family" address is represented by a cons (F . AV)
2819 where F is the family number and AV is a vector containing the socket
2820 address data with one element per address data byte. Do not rely on
2821 this format in portable code, as it may depend on implementation
2822 defined constants, data sizes, and data structure alignment.
2824 :coding CODING -- If CODING is a symbol, it specifies the coding
2825 system used for both reading and writing for this process. If CODING
2826 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2827 ENCODING is used for writing.
2829 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2830 return without waiting for the connection to complete; instead, the
2831 sentinel function will be called with second arg matching "open" (if
2832 successful) or "failed" when the connect completes. Default is to use
2833 a blocking connect (i.e. wait) for stream type connections.
2835 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2836 running when Emacs is exited.
2838 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2839 In the stopped state, a server process does not accept new
2840 connections, and a client process does not handle incoming traffic.
2841 The stopped state is cleared by `continue-process' and set by
2844 :filter FILTER -- Install FILTER as the process filter.
2846 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2847 process filter are multibyte, otherwise they are unibyte.
2848 If this keyword is not specified, the strings are multibyte if
2849 the default value of `enable-multibyte-characters' is non-nil.
2851 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2853 :log LOG -- Install LOG as the server process log function. This
2854 function is called when the server accepts a network connection from a
2855 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2856 is the server process, CLIENT is the new process for the connection,
2857 and MESSAGE is a string.
2859 :plist PLIST -- Install PLIST as the new process' initial plist.
2861 :server QLEN -- if QLEN is non-nil, create a server process for the
2862 specified FAMILY, SERVICE, and connection type (stream or datagram).
2863 If QLEN is an integer, it is used as the max. length of the server's
2864 pending connection queue (also known as the backlog); the default
2865 queue length is 5. Default is to create a client process.
2867 The following network options can be specified for this connection:
2869 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2870 :dontroute BOOL -- Only send to directly connected hosts.
2871 :keepalive BOOL -- Send keep-alive messages on network stream.
2872 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2873 :oobinline BOOL -- Place out-of-band data in receive data stream.
2874 :priority INT -- Set protocol defined priority for sent packets.
2875 :reuseaddr BOOL -- Allow reusing a recently used local address
2876 (this is allowed by default for a server process).
2877 :bindtodevice NAME -- bind to interface NAME. Using this may require
2878 special privileges on some systems.
2880 Consult the relevant system programmer's manual pages for more
2881 information on using these options.
2884 A server process will listen for and accept connections from clients.
2885 When a client connection is accepted, a new network process is created
2886 for the connection with the following parameters:
2888 - The client's process name is constructed by concatenating the server
2889 process' NAME and a client identification string.
2890 - If the FILTER argument is non-nil, the client process will not get a
2891 separate process buffer; otherwise, the client's process buffer is a newly
2892 created buffer named after the server process' BUFFER name or process
2893 NAME concatenated with the client identification string.
2894 - The connection type and the process filter and sentinel parameters are
2895 inherited from the server process' TYPE, FILTER and SENTINEL.
2896 - The client process' contact info is set according to the client's
2897 addressing information (typically an IP address and a port number).
2898 - The client process' plist is initialized from the server's plist.
2900 Notice that the FILTER and SENTINEL args are never used directly by
2901 the server process. Also, the BUFFER argument is not used directly by
2902 the server process, but via the optional :log function, accepted (and
2903 failed) connections may be logged in the server process' buffer.
2905 The original argument list, modified with the actual connection
2906 information, is available via the `process-contact' function.
2908 usage: (make-network-process &rest ARGS) */)
2909 (ptrdiff_t nargs
, Lisp_Object
*args
)
2912 Lisp_Object contact
;
2913 struct Lisp_Process
*p
;
2914 #ifdef HAVE_GETADDRINFO
2915 struct addrinfo ai
, *res
, *lres
;
2916 struct addrinfo hints
;
2917 const char *portstring
;
2919 #else /* HAVE_GETADDRINFO */
2920 struct _emacs_addrinfo
2926 struct sockaddr
*ai_addr
;
2927 struct _emacs_addrinfo
*ai_next
;
2929 #endif /* HAVE_GETADDRINFO */
2930 struct sockaddr_in address_in
;
2931 #ifdef HAVE_LOCAL_SOCKETS
2932 struct sockaddr_un address_un
;
2937 int s
= -1, outch
, inch
;
2938 struct gcpro gcpro1
;
2939 ptrdiff_t count
= SPECPDL_INDEX ();
2941 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
2943 Lisp_Object name
, buffer
, host
, service
, address
;
2944 Lisp_Object filter
, sentinel
;
2945 int is_non_blocking_client
= 0;
2946 int is_server
= 0, backlog
= 5;
2953 /* Save arguments for process-contact and clone-process. */
2954 contact
= Flist (nargs
, args
);
2958 /* Ensure socket support is loaded if available. */
2959 init_winsock (TRUE
);
2962 /* :type TYPE (nil: stream, datagram */
2963 tem
= Fplist_get (contact
, QCtype
);
2965 socktype
= SOCK_STREAM
;
2966 #ifdef DATAGRAM_SOCKETS
2967 else if (EQ (tem
, Qdatagram
))
2968 socktype
= SOCK_DGRAM
;
2970 #ifdef HAVE_SEQPACKET
2971 else if (EQ (tem
, Qseqpacket
))
2972 socktype
= SOCK_SEQPACKET
;
2975 error ("Unsupported connection type");
2978 tem
= Fplist_get (contact
, QCserver
);
2981 /* Don't support network sockets when non-blocking mode is
2982 not available, since a blocked Emacs is not useful. */
2983 #if !defined (O_NONBLOCK) && !defined (O_NDELAY)
2984 error ("Network servers not supported");
2987 if (TYPE_RANGED_INTEGERP (int, tem
))
2988 backlog
= XINT (tem
);
2992 /* Make QCaddress an alias for :local (server) or :remote (client). */
2993 QCaddress
= is_server
? QClocal
: QCremote
;
2996 if (!is_server
&& socktype
!= SOCK_DGRAM
2997 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2999 #ifndef NON_BLOCKING_CONNECT
3000 error ("Non-blocking connect not supported");
3002 is_non_blocking_client
= 1;
3006 name
= Fplist_get (contact
, QCname
);
3007 buffer
= Fplist_get (contact
, QCbuffer
);
3008 filter
= Fplist_get (contact
, QCfilter
);
3009 sentinel
= Fplist_get (contact
, QCsentinel
);
3011 CHECK_STRING (name
);
3013 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3014 ai
.ai_socktype
= socktype
;
3019 /* :local ADDRESS or :remote ADDRESS */
3020 address
= Fplist_get (contact
, QCaddress
);
3021 if (!NILP (address
))
3023 host
= service
= Qnil
;
3025 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
3026 error ("Malformed :address");
3027 ai
.ai_family
= family
;
3028 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
3029 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
3033 /* :family FAMILY -- nil (for Inet), local, or integer. */
3034 tem
= Fplist_get (contact
, QCfamily
);
3037 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3043 #ifdef HAVE_LOCAL_SOCKETS
3044 else if (EQ (tem
, Qlocal
))
3048 else if (EQ (tem
, Qipv6
))
3051 else if (EQ (tem
, Qipv4
))
3053 else if (TYPE_RANGED_INTEGERP (int, tem
))
3054 family
= XINT (tem
);
3056 error ("Unknown address family");
3058 ai
.ai_family
= family
;
3060 /* :service SERVICE -- string, integer (port number), or t (random port). */
3061 service
= Fplist_get (contact
, QCservice
);
3063 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3064 host
= Fplist_get (contact
, QChost
);
3067 if (EQ (host
, Qlocal
))
3068 /* Depending on setup, "localhost" may map to different IPv4 and/or
3069 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3070 host
= build_string ("127.0.0.1");
3071 CHECK_STRING (host
);
3074 #ifdef HAVE_LOCAL_SOCKETS
3075 if (family
== AF_LOCAL
)
3079 message (":family local ignores the :host \"%s\" property",
3081 contact
= Fplist_put (contact
, QChost
, Qnil
);
3084 CHECK_STRING (service
);
3085 memset (&address_un
, 0, sizeof address_un
);
3086 address_un
.sun_family
= AF_LOCAL
;
3087 if (sizeof address_un
.sun_path
<= SBYTES (service
))
3088 error ("Service name too long");
3089 strcpy (address_un
.sun_path
, SSDATA (service
));
3090 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3091 ai
.ai_addrlen
= sizeof address_un
;
3096 /* Slow down polling to every ten seconds.
3097 Some kernels have a bug which causes retrying connect to fail
3098 after a connect. Polling can interfere with gethostbyname too. */
3099 #ifdef POLL_FOR_INPUT
3100 if (socktype
!= SOCK_DGRAM
)
3102 record_unwind_protect (unwind_stop_other_atimers
, Qnil
);
3103 bind_polling_period (10);
3107 #ifdef HAVE_GETADDRINFO
3108 /* If we have a host, use getaddrinfo to resolve both host and service.
3109 Otherwise, use getservbyname to lookup the service. */
3113 /* SERVICE can either be a string or int.
3114 Convert to a C string for later use by getaddrinfo. */
3115 if (EQ (service
, Qt
))
3117 else if (INTEGERP (service
))
3119 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3120 portstring
= portbuf
;
3124 CHECK_STRING (service
);
3125 portstring
= SSDATA (service
);
3130 memset (&hints
, 0, sizeof (hints
));
3132 hints
.ai_family
= family
;
3133 hints
.ai_socktype
= socktype
;
3134 hints
.ai_protocol
= 0;
3136 #ifdef HAVE_RES_INIT
3140 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3142 #ifdef HAVE_GAI_STRERROR
3143 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3145 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3151 #endif /* HAVE_GETADDRINFO */
3153 /* We end up here if getaddrinfo is not defined, or in case no hostname
3154 has been specified (e.g. for a local server process). */
3156 if (EQ (service
, Qt
))
3158 else if (INTEGERP (service
))
3159 port
= htons ((unsigned short) XINT (service
));
3162 struct servent
*svc_info
;
3163 CHECK_STRING (service
);
3164 svc_info
= getservbyname (SSDATA (service
),
3165 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3167 error ("Unknown service: %s", SDATA (service
));
3168 port
= svc_info
->s_port
;
3171 memset (&address_in
, 0, sizeof address_in
);
3172 address_in
.sin_family
= family
;
3173 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3174 address_in
.sin_port
= port
;
3176 #ifndef HAVE_GETADDRINFO
3179 struct hostent
*host_info_ptr
;
3181 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3182 as it may `hang' Emacs for a very long time. */
3186 #ifdef HAVE_RES_INIT
3190 host_info_ptr
= gethostbyname (SDATA (host
));
3195 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3196 host_info_ptr
->h_length
);
3197 family
= host_info_ptr
->h_addrtype
;
3198 address_in
.sin_family
= family
;
3201 /* Attempt to interpret host as numeric inet address */
3203 unsigned long numeric_addr
;
3204 numeric_addr
= inet_addr (SSDATA (host
));
3205 if (numeric_addr
== -1)
3206 error ("Unknown host \"%s\"", SDATA (host
));
3208 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3209 sizeof (address_in
.sin_addr
));
3213 #endif /* not HAVE_GETADDRINFO */
3215 ai
.ai_family
= family
;
3216 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3217 ai
.ai_addrlen
= sizeof address_in
;
3221 /* Do this in case we never enter the for-loop below. */
3222 count1
= SPECPDL_INDEX ();
3225 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3234 s
= socket (lres
->ai_family
, lres
->ai_socktype
, lres
->ai_protocol
);
3241 #ifdef DATAGRAM_SOCKETS
3242 if (!is_server
&& socktype
== SOCK_DGRAM
)
3244 #endif /* DATAGRAM_SOCKETS */
3246 #ifdef NON_BLOCKING_CONNECT
3247 if (is_non_blocking_client
)
3250 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3252 ret
= fcntl (s
, F_SETFL
, O_NDELAY
);
3264 /* Make us close S if quit. */
3265 record_unwind_protect (close_file_unwind
, make_number (s
));
3267 /* Parse network options in the arg list.
3268 We simply ignore anything which isn't a known option (including other keywords).
3269 An error is signaled if setting a known option fails. */
3270 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3271 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3275 /* Configure as a server socket. */
3277 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3278 explicit :reuseaddr key to override this. */
3279 #ifdef HAVE_LOCAL_SOCKETS
3280 if (family
!= AF_LOCAL
)
3282 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3285 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3286 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3289 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3290 report_file_error ("Cannot bind server socket", Qnil
);
3292 #ifdef HAVE_GETSOCKNAME
3293 if (EQ (service
, Qt
))
3295 struct sockaddr_in sa1
;
3296 socklen_t len1
= sizeof (sa1
);
3297 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3299 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3300 service
= make_number (ntohs (sa1
.sin_port
));
3301 contact
= Fplist_put (contact
, QCservice
, service
);
3306 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3307 report_file_error ("Cannot listen on server socket", Qnil
);
3315 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3318 if (ret
== 0 || xerrno
== EISCONN
)
3320 /* The unwind-protect will be discarded afterwards.
3321 Likewise for immediate_quit. */
3325 #ifdef NON_BLOCKING_CONNECT
3327 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3331 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3338 if (xerrno
== EINTR
)
3340 /* Unlike most other syscalls connect() cannot be called
3341 again. (That would return EALREADY.) The proper way to
3342 wait for completion is pselect(). */
3350 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3356 report_file_error ("select failed", Qnil
);
3360 len
= sizeof xerrno
;
3361 eassert (FD_ISSET (s
, &fdset
));
3362 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) == -1)
3363 report_file_error ("getsockopt failed", Qnil
);
3365 errno
= xerrno
, report_file_error ("error during connect", Qnil
);
3369 #endif /* !WINDOWSNT */
3373 /* Discard the unwind protect closing S. */
3374 specpdl_ptr
= specpdl
+ count1
;
3379 if (xerrno
== EINTR
)
3386 #ifdef DATAGRAM_SOCKETS
3387 if (socktype
== SOCK_DGRAM
)
3389 if (datagram_address
[s
].sa
)
3391 datagram_address
[s
].sa
= xmalloc (lres
->ai_addrlen
);
3392 datagram_address
[s
].len
= lres
->ai_addrlen
;
3396 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3397 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3400 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3401 if (rfamily
== lres
->ai_family
&& rlen
== lres
->ai_addrlen
)
3402 conv_lisp_to_sockaddr (rfamily
, remote
,
3403 datagram_address
[s
].sa
, rlen
);
3407 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3410 contact
= Fplist_put (contact
, QCaddress
,
3411 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3412 #ifdef HAVE_GETSOCKNAME
3415 struct sockaddr_in sa1
;
3416 socklen_t len1
= sizeof (sa1
);
3417 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3418 contact
= Fplist_put (contact
, QClocal
,
3419 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3426 #ifdef HAVE_GETADDRINFO
3435 /* Discard the unwind protect for closing S, if any. */
3436 specpdl_ptr
= specpdl
+ count1
;
3438 /* Unwind bind_polling_period and request_sigio. */
3439 unbind_to (count
, Qnil
);
3443 /* If non-blocking got this far - and failed - assume non-blocking is
3444 not supported after all. This is probably a wrong assumption, but
3445 the normal blocking calls to open-network-stream handles this error
3447 if (is_non_blocking_client
)
3452 report_file_error ("make server process failed", contact
);
3454 report_file_error ("make client process failed", contact
);
3461 buffer
= Fget_buffer_create (buffer
);
3462 proc
= make_process (name
);
3464 chan_process
[inch
] = proc
;
3467 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3470 fcntl (inch
, F_SETFL
, O_NDELAY
);
3474 p
= XPROCESS (proc
);
3476 pset_childp (p
, contact
);
3477 pset_plist (p
, Fcopy_sequence (Fplist_get (contact
, QCplist
)));
3478 pset_type (p
, Qnetwork
);
3480 pset_buffer (p
, buffer
);
3481 pset_sentinel (p
, sentinel
);
3482 pset_filter (p
, filter
);
3483 pset_log (p
, Fplist_get (contact
, QClog
));
3484 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3485 p
->kill_without_query
= 1;
3486 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3487 pset_command (p
, Qt
);
3491 if (is_server
&& socktype
!= SOCK_DGRAM
)
3492 pset_status (p
, Qlisten
);
3494 /* Make the process marker point into the process buffer (if any). */
3495 if (BUFFERP (buffer
))
3496 set_marker_both (p
->mark
, buffer
,
3497 BUF_ZV (XBUFFER (buffer
)),
3498 BUF_ZV_BYTE (XBUFFER (buffer
)));
3500 #ifdef NON_BLOCKING_CONNECT
3501 if (is_non_blocking_client
)
3503 /* We may get here if connect did succeed immediately. However,
3504 in that case, we still need to signal this like a non-blocking
3506 pset_status (p
, Qconnect
);
3507 if (!FD_ISSET (inch
, &connect_wait_mask
))
3509 FD_SET (inch
, &connect_wait_mask
);
3510 FD_SET (inch
, &write_mask
);
3511 num_pending_connects
++;
3516 /* A server may have a client filter setting of Qt, but it must
3517 still listen for incoming connects unless it is stopped. */
3518 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3519 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3521 FD_SET (inch
, &input_wait_mask
);
3522 FD_SET (inch
, &non_keyboard_wait_mask
);
3525 if (inch
> max_process_desc
)
3526 max_process_desc
= inch
;
3528 tem
= Fplist_member (contact
, QCcoding
);
3529 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3530 tem
= Qnil
; /* No error message (too late!). */
3533 /* Setup coding systems for communicating with the network stream. */
3534 struct gcpro gcpro1
;
3535 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3536 Lisp_Object coding_systems
= Qt
;
3537 Lisp_Object fargs
[5], val
;
3541 val
= XCAR (XCDR (tem
));
3545 else if (!NILP (Vcoding_system_for_read
))
3546 val
= Vcoding_system_for_read
;
3547 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3548 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3549 /* We dare not decode end-of-line format by setting VAL to
3550 Qraw_text, because the existing Emacs Lisp libraries
3551 assume that they receive bare code including a sequence of
3556 if (NILP (host
) || NILP (service
))
3557 coding_systems
= Qnil
;
3560 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3561 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3563 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3566 if (CONSP (coding_systems
))
3567 val
= XCAR (coding_systems
);
3568 else if (CONSP (Vdefault_process_coding_system
))
3569 val
= XCAR (Vdefault_process_coding_system
);
3573 pset_decode_coding_system (p
, val
);
3577 val
= XCAR (XCDR (tem
));
3581 else if (!NILP (Vcoding_system_for_write
))
3582 val
= Vcoding_system_for_write
;
3583 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3587 if (EQ (coding_systems
, Qt
))
3589 if (NILP (host
) || NILP (service
))
3590 coding_systems
= Qnil
;
3593 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3594 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3596 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3600 if (CONSP (coding_systems
))
3601 val
= XCDR (coding_systems
);
3602 else if (CONSP (Vdefault_process_coding_system
))
3603 val
= XCDR (Vdefault_process_coding_system
);
3607 pset_encode_coding_system (p
, val
);
3609 setup_process_coding_systems (proc
);
3611 pset_decoding_buf (p
, empty_unibyte_string
);
3612 p
->decoding_carryover
= 0;
3613 pset_encoding_buf (p
, empty_unibyte_string
);
3615 p
->inherit_coding_system_flag
3616 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3623 #if defined (HAVE_NET_IF_H)
3626 DEFUN ("network-interface-list", Fnetwork_interface_list
, Snetwork_interface_list
, 0, 0, 0,
3627 doc
: /* Return an alist of all network interfaces and their network address.
3628 Each element is a cons, the car of which is a string containing the
3629 interface name, and the cdr is the network address in internal
3630 format; see the description of ADDRESS in `make-network-process'. */)
3633 struct ifconf ifconf
;
3634 struct ifreq
*ifreq
;
3636 ptrdiff_t buf_size
= 512;
3640 s
= socket (AF_INET
, SOCK_STREAM
, 0);
3646 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3647 ifconf
.ifc_buf
= buf
;
3648 ifconf
.ifc_len
= buf_size
;
3649 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3656 while (ifconf
.ifc_len
== buf_size
);
3661 ifreq
= ifconf
.ifc_req
;
3662 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3664 struct ifreq
*ifq
= ifreq
;
3665 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3666 #define SIZEOF_IFREQ(sif) \
3667 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3668 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3670 int len
= SIZEOF_IFREQ (ifq
);
3672 int len
= sizeof (*ifreq
);
3674 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3676 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3678 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3681 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3682 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3683 res
= Fcons (Fcons (build_string (namebuf
),
3684 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3685 sizeof (struct sockaddr
))),
3692 #endif /* SIOCGIFCONF */
3694 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3698 const char *flag_sym
;
3701 static const struct ifflag_def ifflag_table
[] = {
3705 #ifdef IFF_BROADCAST
3706 { IFF_BROADCAST
, "broadcast" },
3709 { IFF_DEBUG
, "debug" },
3712 { IFF_LOOPBACK
, "loopback" },
3714 #ifdef IFF_POINTOPOINT
3715 { IFF_POINTOPOINT
, "pointopoint" },
3718 { IFF_RUNNING
, "running" },
3721 { IFF_NOARP
, "noarp" },
3724 { IFF_PROMISC
, "promisc" },
3726 #ifdef IFF_NOTRAILERS
3727 #ifdef NS_IMPL_COCOA
3728 /* Really means smart, notrailers is obsolete */
3729 { IFF_NOTRAILERS
, "smart" },
3731 { IFF_NOTRAILERS
, "notrailers" },
3735 { IFF_ALLMULTI
, "allmulti" },
3738 { IFF_MASTER
, "master" },
3741 { IFF_SLAVE
, "slave" },
3743 #ifdef IFF_MULTICAST
3744 { IFF_MULTICAST
, "multicast" },
3747 { IFF_PORTSEL
, "portsel" },
3749 #ifdef IFF_AUTOMEDIA
3750 { IFF_AUTOMEDIA
, "automedia" },
3753 { IFF_DYNAMIC
, "dynamic" },
3756 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3759 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3762 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3765 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3768 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3773 DEFUN ("network-interface-info", Fnetwork_interface_info
, Snetwork_interface_info
, 1, 1, 0,
3774 doc
: /* Return information about network interface named IFNAME.
3775 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3776 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3777 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3778 FLAGS is the current flags of the interface. */)
3779 (Lisp_Object ifname
)
3782 Lisp_Object res
= Qnil
;
3786 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3787 && defined HAVE_GETIFADDRS && defined LLADDR)
3788 struct ifaddrs
*ifap
;
3791 CHECK_STRING (ifname
);
3793 if (sizeof rq
.ifr_name
<= SBYTES (ifname
))
3794 error ("interface name too long");
3795 strcpy (rq
.ifr_name
, SSDATA (ifname
));
3797 s
= socket (AF_INET
, SOCK_STREAM
, 0);
3802 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3803 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3805 int flags
= rq
.ifr_flags
;
3806 const struct ifflag_def
*fp
;
3809 /* If flags is smaller than int (i.e. short) it may have the high bit set
3810 due to IFF_MULTICAST. In that case, sign extending it into
3812 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3813 flags
= (unsigned short) rq
.ifr_flags
;
3816 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3818 if (flags
& fp
->flag_bit
)
3820 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3821 flags
-= fp
->flag_bit
;
3824 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3828 elt
= Fcons (make_number (fnum
), elt
);
3833 res
= Fcons (elt
, res
);
3836 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3837 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3839 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3840 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3844 for (n
= 0; n
< 6; n
++)
3845 p
->contents
[n
] = make_number (((unsigned char *)&rq
.ifr_hwaddr
.sa_data
[0])[n
]);
3846 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3848 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3849 if (getifaddrs (&ifap
) != -1)
3851 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3852 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3855 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3857 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3858 unsigned char linkaddr
[6];
3861 if (it
->ifa_addr
->sa_family
!= AF_LINK
3862 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3863 || sdl
->sdl_alen
!= 6)
3866 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3867 for (n
= 0; n
< 6; n
++)
3868 p
->contents
[n
] = make_number (linkaddr
[n
]);
3870 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3874 #ifdef HAVE_FREEIFADDRS
3878 #endif /* HAVE_GETIFADDRS && LLADDR */
3880 res
= Fcons (elt
, res
);
3883 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3884 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3887 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3888 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3890 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3894 res
= Fcons (elt
, res
);
3897 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3898 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3901 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3904 res
= Fcons (elt
, res
);
3907 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3908 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3911 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3914 res
= Fcons (elt
, res
);
3918 return any
? res
: Qnil
;
3921 #endif /* defined (HAVE_NET_IF_H) */
3923 /* Turn off input and output for process PROC. */
3926 deactivate_process (Lisp_Object proc
)
3928 register int inchannel
, outchannel
;
3929 register struct Lisp_Process
*p
= XPROCESS (proc
);
3932 /* Delete GnuTLS structures in PROC, if any. */
3933 emacs_gnutls_deinit (proc
);
3934 #endif /* HAVE_GNUTLS */
3936 inchannel
= p
->infd
;
3937 outchannel
= p
->outfd
;
3939 #ifdef ADAPTIVE_READ_BUFFERING
3940 if (p
->read_output_delay
> 0)
3942 if (--process_output_delay_count
< 0)
3943 process_output_delay_count
= 0;
3944 p
->read_output_delay
= 0;
3945 p
->read_output_skip
= 0;
3951 /* Beware SIGCHLD hereabouts. */
3952 flush_pending_output (inchannel
);
3953 emacs_close (inchannel
);
3954 if (outchannel
>= 0 && outchannel
!= inchannel
)
3955 emacs_close (outchannel
);
3959 #ifdef DATAGRAM_SOCKETS
3960 if (DATAGRAM_CHAN_P (inchannel
))
3962 xfree (datagram_address
[inchannel
].sa
);
3963 datagram_address
[inchannel
].sa
= 0;
3964 datagram_address
[inchannel
].len
= 0;
3967 chan_process
[inchannel
] = Qnil
;
3968 FD_CLR (inchannel
, &input_wait_mask
);
3969 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3970 #ifdef NON_BLOCKING_CONNECT
3971 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3973 FD_CLR (inchannel
, &connect_wait_mask
);
3974 FD_CLR (inchannel
, &write_mask
);
3975 if (--num_pending_connects
< 0)
3979 if (inchannel
== max_process_desc
)
3982 /* We just closed the highest-numbered process input descriptor,
3983 so recompute the highest-numbered one now. */
3984 max_process_desc
= 0;
3985 for (i
= 0; i
< MAXDESC
; i
++)
3986 if (!NILP (chan_process
[i
]))
3987 max_process_desc
= i
;
3993 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3995 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3996 It is read into the process' buffers or given to their filter functions.
3997 Non-nil arg PROCESS means do not return until some output has been received
4000 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4001 and milliseconds to wait; return after that much time whether or not
4002 there is any subprocess output. If SECONDS is a floating point number,
4003 it specifies a fractional number of seconds to wait.
4004 The MILLISEC argument is obsolete and should be avoided.
4006 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4007 from PROCESS, suspending reading output from other processes.
4008 If JUST-THIS-ONE is an integer, don't run any timers either.
4009 Return non-nil if we received any output before the timeout expired. */)
4010 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
4015 if (! NILP (process
))
4016 CHECK_PROCESS (process
);
4018 just_this_one
= Qnil
;
4020 if (!NILP (millisec
))
4021 { /* Obsolete calling convention using integers rather than floats. */
4022 CHECK_NUMBER (millisec
);
4024 seconds
= make_float (XINT (millisec
) / 1000.0);
4027 CHECK_NUMBER (seconds
);
4028 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
4035 if (!NILP (seconds
))
4037 if (INTEGERP (seconds
))
4039 if (0 < XINT (seconds
))
4041 secs
= XINT (seconds
);
4045 else if (FLOATP (seconds
))
4047 if (0 < XFLOAT_DATA (seconds
))
4049 EMACS_TIME t
= EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds
));
4050 secs
= min (EMACS_SECS (t
), WAIT_READING_MAX
);
4051 nsecs
= EMACS_NSECS (t
);
4055 wrong_type_argument (Qnumberp
, seconds
);
4057 else if (! NILP (process
))
4061 (wait_reading_process_output (secs
, nsecs
, 0, 0,
4063 !NILP (process
) ? XPROCESS (process
) : NULL
,
4064 NILP (just_this_one
) ? 0 :
4065 !INTEGERP (just_this_one
) ? 1 : -1)
4069 /* Accept a connection for server process SERVER on CHANNEL. */
4071 static int connect_counter
= 0;
4074 server_accept_connection (Lisp_Object server
, int channel
)
4076 Lisp_Object proc
, caller
, name
, buffer
;
4077 Lisp_Object contact
, host
, service
;
4078 struct Lisp_Process
*ps
= XPROCESS (server
);
4079 struct Lisp_Process
*p
;
4083 struct sockaddr_in in
;
4085 struct sockaddr_in6 in6
;
4087 #ifdef HAVE_LOCAL_SOCKETS
4088 struct sockaddr_un un
;
4091 socklen_t len
= sizeof saddr
;
4093 s
= accept (channel
, &saddr
.sa
, &len
);
4102 if (code
== EWOULDBLOCK
)
4106 if (!NILP (ps
->log
))
4107 call3 (ps
->log
, server
, Qnil
,
4108 concat3 (build_string ("accept failed with code"),
4109 Fnumber_to_string (make_number (code
)),
4110 build_string ("\n")));
4116 /* Setup a new process to handle the connection. */
4118 /* Generate a unique identification of the caller, and build contact
4119 information for this process. */
4122 switch (saddr
.sa
.sa_family
)
4126 Lisp_Object args
[5];
4127 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4128 args
[0] = build_string ("%d.%d.%d.%d");
4129 args
[1] = make_number (*ip
++);
4130 args
[2] = make_number (*ip
++);
4131 args
[3] = make_number (*ip
++);
4132 args
[4] = make_number (*ip
++);
4133 host
= Fformat (5, args
);
4134 service
= make_number (ntohs (saddr
.in
.sin_port
));
4136 args
[0] = build_string (" <%s:%d>");
4139 caller
= Fformat (3, args
);
4146 Lisp_Object args
[9];
4147 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4149 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4150 for (i
= 0; i
< 8; i
++)
4151 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4152 host
= Fformat (9, args
);
4153 service
= make_number (ntohs (saddr
.in
.sin_port
));
4155 args
[0] = build_string (" <[%s]:%d>");
4158 caller
= Fformat (3, args
);
4163 #ifdef HAVE_LOCAL_SOCKETS
4167 caller
= Fnumber_to_string (make_number (connect_counter
));
4168 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4172 /* Create a new buffer name for this process if it doesn't have a
4173 filter. The new buffer name is based on the buffer name or
4174 process name of the server process concatenated with the caller
4177 if (!NILP (ps
->filter
) && !EQ (ps
->filter
, Qt
))
4181 buffer
= ps
->buffer
;
4183 buffer
= Fbuffer_name (buffer
);
4188 buffer
= concat2 (buffer
, caller
);
4189 buffer
= Fget_buffer_create (buffer
);
4193 /* Generate a unique name for the new server process. Combine the
4194 server process name with the caller identification. */
4196 name
= concat2 (ps
->name
, caller
);
4197 proc
= make_process (name
);
4199 chan_process
[s
] = proc
;
4202 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4205 fcntl (s
, F_SETFL
, O_NDELAY
);
4209 p
= XPROCESS (proc
);
4211 /* Build new contact information for this setup. */
4212 contact
= Fcopy_sequence (ps
->childp
);
4213 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4214 contact
= Fplist_put (contact
, QChost
, host
);
4215 if (!NILP (service
))
4216 contact
= Fplist_put (contact
, QCservice
, service
);
4217 contact
= Fplist_put (contact
, QCremote
,
4218 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4219 #ifdef HAVE_GETSOCKNAME
4221 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4222 contact
= Fplist_put (contact
, QClocal
,
4223 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4226 pset_childp (p
, contact
);
4227 pset_plist (p
, Fcopy_sequence (ps
->plist
));
4228 pset_type (p
, Qnetwork
);
4230 pset_buffer (p
, buffer
);
4231 pset_sentinel (p
, ps
->sentinel
);
4232 pset_filter (p
, ps
->filter
);
4233 pset_command (p
, Qnil
);
4237 pset_status (p
, Qrun
);
4239 /* Client processes for accepted connections are not stopped initially. */
4240 if (!EQ (p
->filter
, Qt
))
4242 FD_SET (s
, &input_wait_mask
);
4243 FD_SET (s
, &non_keyboard_wait_mask
);
4246 if (s
> max_process_desc
)
4247 max_process_desc
= s
;
4249 /* Setup coding system for new process based on server process.
4250 This seems to be the proper thing to do, as the coding system
4251 of the new process should reflect the settings at the time the
4252 server socket was opened; not the current settings. */
4254 pset_decode_coding_system (p
, ps
->decode_coding_system
);
4255 pset_encode_coding_system (p
, ps
->encode_coding_system
);
4256 setup_process_coding_systems (proc
);
4258 pset_decoding_buf (p
, empty_unibyte_string
);
4259 p
->decoding_carryover
= 0;
4260 pset_encoding_buf (p
, empty_unibyte_string
);
4262 p
->inherit_coding_system_flag
4263 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4265 if (!NILP (ps
->log
))
4266 call3 (ps
->log
, server
, proc
,
4267 concat3 (build_string ("accept from "),
4268 (STRINGP (host
) ? host
: build_string ("-")),
4269 build_string ("\n")));
4271 if (!NILP (p
->sentinel
))
4272 exec_sentinel (proc
,
4273 concat3 (build_string ("open from "),
4274 (STRINGP (host
) ? host
: build_string ("-")),
4275 build_string ("\n")));
4278 /* This variable is different from waiting_for_input in keyboard.c.
4279 It is used to communicate to a lisp process-filter/sentinel (via the
4280 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4281 for user-input when that process-filter was called.
4282 waiting_for_input cannot be used as that is by definition 0 when
4283 lisp code is being evalled.
4284 This is also used in record_asynch_buffer_change.
4285 For that purpose, this must be 0
4286 when not inside wait_reading_process_output. */
4287 static int waiting_for_user_input_p
;
4290 wait_reading_process_output_unwind (Lisp_Object data
)
4292 waiting_for_user_input_p
= XINT (data
);
4296 /* This is here so breakpoints can be put on it. */
4298 wait_reading_process_output_1 (void)
4302 /* Read and dispose of subprocess output while waiting for timeout to
4303 elapse and/or keyboard input to be available.
4307 If negative, gobble data immediately available but don't wait for any.
4310 an additional duration to wait, measured in nanoseconds
4311 If TIME_LIMIT is zero, then:
4312 If NSECS == 0, there is no limit.
4313 If NSECS > 0, the timeout consists of NSECS only.
4314 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4317 0 to ignore keyboard input, or
4318 1 to return when input is available, or
4319 -1 meaning caller will actually read the input, so don't throw to
4320 the quit handler, or
4322 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4323 output that arrives.
4325 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4326 (and gobble terminal input into the buffer if any arrives).
4328 If WAIT_PROC is specified, wait until something arrives from that
4329 process. The return value is true if we read some input from
4332 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4333 (suspending output from other processes). A negative value
4334 means don't run any timers either.
4336 If WAIT_PROC is specified, then the function returns true if we
4337 received input from that process before the timeout elapsed.
4338 Otherwise, return true if we received input from any process. */
4341 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4343 Lisp_Object wait_for_cell
,
4344 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4346 register int channel
, nfds
;
4347 SELECT_TYPE Available
;
4348 SELECT_TYPE Writeok
;
4350 int check_delay
, no_avail
;
4353 EMACS_TIME timeout
, end_time
;
4354 int wait_channel
= -1;
4355 int got_some_input
= 0;
4356 ptrdiff_t count
= SPECPDL_INDEX ();
4358 FD_ZERO (&Available
);
4361 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4362 && !(CONSP (wait_proc
->status
)
4363 && EQ (XCAR (wait_proc
->status
), Qexit
)))
4364 message ("Blocking call to accept-process-output with quit inhibited!!");
4366 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4367 if (wait_proc
!= NULL
)
4368 wait_channel
= wait_proc
->infd
;
4370 record_unwind_protect (wait_reading_process_output_unwind
,
4371 make_number (waiting_for_user_input_p
));
4372 waiting_for_user_input_p
= read_kbd
;
4379 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4380 time_limit
= TYPE_MAXIMUM (time_t);
4382 /* Since we may need to wait several times,
4383 compute the absolute time to return at. */
4384 if (time_limit
|| 0 < nsecs
)
4386 timeout
= make_emacs_time (time_limit
, nsecs
);
4387 end_time
= add_emacs_time (current_emacs_time (), timeout
);
4392 int timeout_reduced_for_timers
= 0;
4394 /* If calling from keyboard input, do not quit
4395 since we want to return C-g as an input character.
4396 Otherwise, do pending quit if requested. */
4401 process_pending_signals ();
4404 /* Exit now if the cell we're waiting for became non-nil. */
4405 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4408 /* Compute time from now till when time limit is up */
4409 /* Exit if already run out */
4412 /* A negative timeout means
4413 gobble output available now
4414 but don't wait at all. */
4416 timeout
= make_emacs_time (0, 0);
4418 else if (time_limit
|| 0 < nsecs
)
4420 EMACS_TIME now
= current_emacs_time ();
4421 if (EMACS_TIME_LE (end_time
, now
))
4423 timeout
= sub_emacs_time (end_time
, now
);
4427 timeout
= make_emacs_time (100000, 0);
4430 /* Normally we run timers here.
4431 But not if wait_for_cell; in those cases,
4432 the wait is supposed to be short,
4433 and those callers cannot handle running arbitrary Lisp code here. */
4434 if (NILP (wait_for_cell
)
4435 && just_wait_proc
>= 0)
4437 EMACS_TIME timer_delay
;
4441 int old_timers_run
= timers_run
;
4442 struct buffer
*old_buffer
= current_buffer
;
4443 Lisp_Object old_window
= selected_window
;
4445 timer_delay
= timer_check ();
4447 /* If a timer has run, this might have changed buffers
4448 an alike. Make read_key_sequence aware of that. */
4449 if (timers_run
!= old_timers_run
4450 && (old_buffer
!= current_buffer
4451 || !EQ (old_window
, selected_window
))
4452 && waiting_for_user_input_p
== -1)
4453 record_asynch_buffer_change ();
4455 if (timers_run
!= old_timers_run
&& do_display
)
4456 /* We must retry, since a timer may have requeued itself
4457 and that could alter the time_delay. */
4458 redisplay_preserve_echo_area (9);
4462 while (!detect_input_pending ());
4464 /* If there is unread keyboard input, also return. */
4466 && requeued_events_pending_p ())
4469 /* A negative timeout means do not wait at all. */
4472 if (EMACS_TIME_VALID_P (timer_delay
))
4474 if (EMACS_TIME_LT (timer_delay
, timeout
))
4476 timeout
= timer_delay
;
4477 timeout_reduced_for_timers
= 1;
4482 /* This is so a breakpoint can be put here. */
4483 wait_reading_process_output_1 ();
4488 /* Cause C-g and alarm signals to take immediate action,
4489 and cause input available signals to zero out timeout.
4491 It is important that we do this before checking for process
4492 activity. If we get a SIGCHLD after the explicit checks for
4493 process activity, timeout is the only way we will know. */
4495 set_waiting_for_input (&timeout
);
4497 /* If status of something has changed, and no input is
4498 available, notify the user of the change right away. After
4499 this explicit check, we'll let the SIGCHLD handler zap
4500 timeout to get our attention. */
4501 if (update_tick
!= process_tick
)
4506 if (kbd_on_hold_p ())
4509 Atemp
= input_wait_mask
;
4512 timeout
= make_emacs_time (0, 0);
4513 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4515 #ifdef NON_BLOCKING_CONNECT
4516 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4520 NULL
, &timeout
, NULL
)
4523 /* It's okay for us to do this and then continue with
4524 the loop, since timeout has already been zeroed out. */
4525 clear_waiting_for_input ();
4526 status_notify (NULL
);
4527 if (do_display
) redisplay_preserve_echo_area (13);
4531 /* Don't wait for output from a non-running process. Just
4532 read whatever data has already been received. */
4533 if (wait_proc
&& wait_proc
->raw_status_new
)
4534 update_status (wait_proc
);
4536 && ! EQ (wait_proc
->status
, Qrun
)
4537 && ! EQ (wait_proc
->status
, Qconnect
))
4539 int nread
, total_nread
= 0;
4541 clear_waiting_for_input ();
4542 XSETPROCESS (proc
, wait_proc
);
4544 /* Read data from the process, until we exhaust it. */
4545 while (wait_proc
->infd
>= 0)
4547 nread
= read_process_output (proc
, wait_proc
->infd
);
4554 total_nread
+= nread
;
4558 else if (nread
== -1 && EIO
== errno
)
4562 else if (nread
== -1 && EAGAIN
== errno
)
4566 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4570 if (total_nread
> 0 && do_display
)
4571 redisplay_preserve_echo_area (10);
4576 /* Wait till there is something to do */
4578 if (wait_proc
&& just_wait_proc
)
4580 if (wait_proc
->infd
< 0) /* Terminated */
4582 FD_SET (wait_proc
->infd
, &Available
);
4586 else if (!NILP (wait_for_cell
))
4588 Available
= non_process_wait_mask
;
4595 Available
= non_keyboard_wait_mask
;
4597 Available
= input_wait_mask
;
4598 Writeok
= write_mask
;
4599 #ifdef SELECT_CANT_DO_WRITE_MASK
4604 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4607 /* If frame size has changed or the window is newly mapped,
4608 redisplay now, before we start to wait. There is a race
4609 condition here; if a SIGIO arrives between now and the select
4610 and indicates that a frame is trashed, the select may block
4611 displaying a trashed screen. */
4612 if (frame_garbaged
&& do_display
)
4614 clear_waiting_for_input ();
4615 redisplay_preserve_echo_area (11);
4617 set_waiting_for_input (&timeout
);
4620 /* Skip the `select' call if input is available and we're
4621 waiting for keyboard input or a cell change (which can be
4622 triggered by processing X events). In the latter case, set
4623 nfds to 1 to avoid breaking the loop. */
4625 if ((read_kbd
|| !NILP (wait_for_cell
))
4626 && detect_input_pending ())
4628 nfds
= read_kbd
? 0 : 1;
4635 #ifdef ADAPTIVE_READ_BUFFERING
4636 /* Set the timeout for adaptive read buffering if any
4637 process has non-zero read_output_skip and non-zero
4638 read_output_delay, and we are not reading output for a
4639 specific wait_channel. It is not executed if
4640 Vprocess_adaptive_read_buffering is nil. */
4641 if (process_output_skip
&& check_delay
> 0)
4643 int nsecs
= EMACS_NSECS (timeout
);
4644 if (EMACS_SECS (timeout
) > 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4645 nsecs
= READ_OUTPUT_DELAY_MAX
;
4646 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4648 proc
= chan_process
[channel
];
4651 /* Find minimum non-zero read_output_delay among the
4652 processes with non-zero read_output_skip. */
4653 if (XPROCESS (proc
)->read_output_delay
> 0)
4656 if (!XPROCESS (proc
)->read_output_skip
)
4658 FD_CLR (channel
, &Available
);
4659 XPROCESS (proc
)->read_output_skip
= 0;
4660 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4661 nsecs
= XPROCESS (proc
)->read_output_delay
;
4664 timeout
= make_emacs_time (0, nsecs
);
4665 process_output_skip
= 0;
4668 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4670 #elif defined (HAVE_NS)
4675 (max (max_process_desc
, max_input_desc
) + 1,
4677 (check_write
? &Writeok
: (SELECT_TYPE
*)0),
4678 NULL
, &timeout
, NULL
);
4681 /* GnuTLS buffers data internally. In lowat mode it leaves
4682 some data in the TCP buffers so that select works, but
4683 with custom pull/push functions we need to check if some
4684 data is available in the buffers manually. */
4689 /* We're not waiting on a specific process, so loop
4690 through all the channels and check for data.
4691 This is a workaround needed for some versions of
4692 the gnutls library -- 2.12.14 has been confirmed
4694 http://comments.gmane.org/gmane.emacs.devel/145074 */
4695 for (channel
= 0; channel
< MAXDESC
; ++channel
)
4696 if (! NILP (chan_process
[channel
]))
4698 struct Lisp_Process
*p
=
4699 XPROCESS (chan_process
[channel
]);
4700 if (p
&& p
->gnutls_p
&& p
->infd
4701 && ((emacs_gnutls_record_check_pending
4706 FD_SET (p
->infd
, &Available
);
4712 /* Check this specific channel. */
4713 if (wait_proc
->gnutls_p
/* Check for valid process. */
4714 /* Do we have pending data? */
4715 && ((emacs_gnutls_record_check_pending
4716 (wait_proc
->gnutls_state
))
4720 /* Set to Available. */
4721 FD_SET (wait_proc
->infd
, &Available
);
4730 /* Make C-g and alarm signals set flags again */
4731 clear_waiting_for_input ();
4733 /* If we woke up due to SIGWINCH, actually change size now. */
4734 do_pending_window_change (0);
4736 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4737 /* We waited the full specified time, so return now. */
4741 if (xerrno
== EINTR
)
4743 else if (xerrno
== EBADF
)
4746 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4747 the child's closure of the pts gives the parent a SIGHUP, and
4748 the ptc file descriptor is automatically closed,
4749 yielding EBADF here or at select() call above.
4750 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4751 in m/ibmrt-aix.h), and here we just ignore the select error.
4752 Cleanup occurs c/o status_notify after SIGCLD. */
4753 no_avail
= 1; /* Cannot depend on values returned */
4759 error ("select error: %s", emacs_strerror (xerrno
));
4764 FD_ZERO (&Available
);
4768 #if 0 /* When polling is used, interrupt_input is 0,
4769 so get_input_pending should read the input.
4770 So this should not be needed. */
4771 /* If we are using polling for input,
4772 and we see input available, make it get read now.
4773 Otherwise it might not actually get read for a second.
4774 And on hpux, since we turn off polling in wait_reading_process_output,
4775 it might never get read at all if we don't spend much time
4776 outside of wait_reading_process_output. */
4777 if (read_kbd
&& interrupt_input
4778 && keyboard_bit_set (&Available
)
4779 && input_polling_used ())
4780 kill (getpid (), SIGALRM
);
4783 /* Check for keyboard input */
4784 /* If there is any, return immediately
4785 to give it higher priority than subprocesses */
4789 int old_timers_run
= timers_run
;
4790 struct buffer
*old_buffer
= current_buffer
;
4791 Lisp_Object old_window
= selected_window
;
4794 if (detect_input_pending_run_timers (do_display
))
4796 swallow_events (do_display
);
4797 if (detect_input_pending_run_timers (do_display
))
4801 /* If a timer has run, this might have changed buffers
4802 an alike. Make read_key_sequence aware of that. */
4803 if (timers_run
!= old_timers_run
4804 && waiting_for_user_input_p
== -1
4805 && (old_buffer
!= current_buffer
4806 || !EQ (old_window
, selected_window
)))
4807 record_asynch_buffer_change ();
4813 /* If there is unread keyboard input, also return. */
4815 && requeued_events_pending_p ())
4818 /* If we are not checking for keyboard input now,
4819 do process events (but don't run any timers).
4820 This is so that X events will be processed.
4821 Otherwise they may have to wait until polling takes place.
4822 That would causes delays in pasting selections, for example.
4824 (We used to do this only if wait_for_cell.) */
4825 if (read_kbd
== 0 && detect_input_pending ())
4827 swallow_events (do_display
);
4828 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4829 if (detect_input_pending ())
4834 /* Exit now if the cell we're waiting for became non-nil. */
4835 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4839 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4840 go read it. This can happen with X on BSD after logging out.
4841 In that case, there really is no input and no SIGIO,
4842 but select says there is input. */
4844 if (read_kbd
&& interrupt_input
4845 && keyboard_bit_set (&Available
) && ! noninteractive
)
4846 kill (getpid (), SIGIO
);
4850 got_some_input
|= nfds
> 0;
4852 /* If checking input just got us a size-change event from X,
4853 obey it now if we should. */
4854 if (read_kbd
|| ! NILP (wait_for_cell
))
4855 do_pending_window_change (0);
4857 /* Check for data from a process. */
4858 if (no_avail
|| nfds
== 0)
4861 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4863 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4865 && ((d
->condition
& FOR_READ
4866 && FD_ISSET (channel
, &Available
))
4867 || (d
->condition
& FOR_WRITE
4868 && FD_ISSET (channel
, &write_mask
))))
4869 d
->func (channel
, d
->data
);
4872 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4874 if (FD_ISSET (channel
, &Available
)
4875 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4876 && !FD_ISSET (channel
, &non_process_wait_mask
))
4880 /* If waiting for this channel, arrange to return as
4881 soon as no more input to be processed. No more
4883 if (wait_channel
== channel
)
4889 proc
= chan_process
[channel
];
4893 /* If this is a server stream socket, accept connection. */
4894 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4896 server_accept_connection (proc
, channel
);
4900 /* Read data from the process, starting with our
4901 buffered-ahead character if we have one. */
4903 nread
= read_process_output (proc
, channel
);
4906 /* Since read_process_output can run a filter,
4907 which can call accept-process-output,
4908 don't try to read from any other processes
4909 before doing the select again. */
4910 FD_ZERO (&Available
);
4913 redisplay_preserve_echo_area (12);
4916 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4919 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4920 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4922 else if (nread
== -1 && errno
== EAGAIN
)
4926 else if (nread
== -1 && errno
== EAGAIN
)
4928 /* Note that we cannot distinguish between no input
4929 available now and a closed pipe.
4930 With luck, a closed pipe will be accompanied by
4931 subprocess termination and SIGCHLD. */
4932 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4934 #endif /* O_NDELAY */
4935 #endif /* O_NONBLOCK */
4937 /* On some OSs with ptys, when the process on one end of
4938 a pty exits, the other end gets an error reading with
4939 errno = EIO instead of getting an EOF (0 bytes read).
4940 Therefore, if we get an error reading and errno =
4941 EIO, just continue, because the child process has
4942 exited and should clean itself up soon (e.g. when we
4945 However, it has been known to happen that the SIGCHLD
4946 got lost. So raise the signal again just in case.
4948 else if (nread
== -1 && errno
== EIO
)
4950 struct Lisp_Process
*p
= XPROCESS (proc
);
4952 /* Clear the descriptor now, so we only raise the
4954 FD_CLR (channel
, &input_wait_mask
);
4955 FD_CLR (channel
, &non_keyboard_wait_mask
);
4959 /* If the EIO occurs on a pty, sigchld_handler's
4960 waitpid() will not find the process object to
4961 delete. Do it here. */
4962 p
->tick
= ++process_tick
;
4963 pset_status (p
, Qfailed
);
4966 kill (getpid (), SIGCHLD
);
4968 #endif /* HAVE_PTYS */
4969 /* If we can detect process termination, don't consider the
4970 process gone just because its pipe is closed. */
4972 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4977 /* Preserve status of processes already terminated. */
4978 XPROCESS (proc
)->tick
= ++process_tick
;
4979 deactivate_process (proc
);
4980 if (XPROCESS (proc
)->raw_status_new
)
4981 update_status (XPROCESS (proc
));
4982 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4983 pset_status (XPROCESS (proc
),
4984 list2 (Qexit
, make_number (256)));
4987 #ifdef NON_BLOCKING_CONNECT
4988 if (FD_ISSET (channel
, &Writeok
)
4989 && FD_ISSET (channel
, &connect_wait_mask
))
4991 struct Lisp_Process
*p
;
4993 FD_CLR (channel
, &connect_wait_mask
);
4994 FD_CLR (channel
, &write_mask
);
4995 if (--num_pending_connects
< 0)
4998 proc
= chan_process
[channel
];
5002 p
= XPROCESS (proc
);
5005 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5006 So only use it on systems where it is known to work. */
5008 socklen_t xlen
= sizeof (xerrno
);
5009 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
5014 struct sockaddr pname
;
5015 int pnamelen
= sizeof (pname
);
5017 /* If connection failed, getpeername will fail. */
5019 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
5021 /* Obtain connect failure code through error slippage. */
5024 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
5031 p
->tick
= ++process_tick
;
5032 pset_status (p
, list2 (Qfailed
, make_number (xerrno
)));
5033 deactivate_process (proc
);
5037 pset_status (p
, Qrun
);
5038 /* Execute the sentinel here. If we had relied on
5039 status_notify to do it later, it will read input
5040 from the process before calling the sentinel. */
5041 exec_sentinel (proc
, build_string ("open\n"));
5042 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
5044 FD_SET (p
->infd
, &input_wait_mask
);
5045 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
5049 #endif /* NON_BLOCKING_CONNECT */
5050 } /* end for each file descriptor */
5051 } /* end while exit conditions not met */
5053 unbind_to (count
, Qnil
);
5055 /* If calling from keyboard input, do not quit
5056 since we want to return C-g as an input character.
5057 Otherwise, do pending quit if requested. */
5060 /* Prevent input_pending from remaining set if we quit. */
5061 clear_input_pending ();
5065 return got_some_input
;
5068 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5071 read_process_output_call (Lisp_Object fun_and_args
)
5073 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5077 read_process_output_error_handler (Lisp_Object error_val
)
5079 cmd_error_internal (error_val
, "error in process filter: ");
5081 update_echo_area ();
5082 Fsleep_for (make_number (2), Qnil
);
5086 /* Read pending output from the process channel,
5087 starting with our buffered-ahead character if we have one.
5088 Yield number of decoded characters read.
5090 This function reads at most 4096 characters.
5091 If you want to read all available subprocess output,
5092 you must call it repeatedly until it returns zero.
5094 The characters read are decoded according to PROC's coding-system
5098 read_process_output (Lisp_Object proc
, register int channel
)
5100 register ssize_t nbytes
;
5102 register Lisp_Object outstream
;
5103 register struct Lisp_Process
*p
= XPROCESS (proc
);
5104 register ptrdiff_t opoint
;
5105 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5106 int carryover
= p
->decoding_carryover
;
5108 ptrdiff_t count
= SPECPDL_INDEX ();
5109 Lisp_Object odeactivate
;
5111 chars
= alloca (carryover
+ readmax
);
5113 /* See the comment above. */
5114 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5116 #ifdef DATAGRAM_SOCKETS
5117 /* We have a working select, so proc_buffered_char is always -1. */
5118 if (DATAGRAM_CHAN_P (channel
))
5120 socklen_t len
= datagram_address
[channel
].len
;
5121 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5122 0, datagram_address
[channel
].sa
, &len
);
5127 int buffered
= 0 <= proc_buffered_char
[channel
];
5130 chars
[carryover
] = proc_buffered_char
[channel
];
5131 proc_buffered_char
[channel
] = -1;
5135 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5136 readmax
- buffered
);
5139 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5140 readmax
- buffered
);
5141 #ifdef ADAPTIVE_READ_BUFFERING
5142 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5144 int delay
= p
->read_output_delay
;
5147 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5150 process_output_delay_count
++;
5151 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5154 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5156 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5158 process_output_delay_count
--;
5160 p
->read_output_delay
= delay
;
5163 p
->read_output_skip
= 1;
5164 process_output_skip
= 1;
5169 nbytes
+= buffered
&& nbytes
<= 0;
5172 p
->decoding_carryover
= 0;
5174 /* At this point, NBYTES holds number of bytes just received
5175 (including the one in proc_buffered_char[channel]). */
5178 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5180 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5183 /* Now set NBYTES how many bytes we must decode. */
5184 nbytes
+= carryover
;
5186 odeactivate
= Vdeactivate_mark
;
5187 /* There's no good reason to let process filters change the current
5188 buffer, and many callers of accept-process-output, sit-for, and
5189 friends don't expect current-buffer to be changed from under them. */
5190 record_unwind_current_buffer ();
5192 /* Read and dispose of the process output. */
5193 outstream
= p
->filter
;
5194 if (!NILP (outstream
))
5197 bool outer_running_asynch_code
= running_asynch_code
;
5198 int waiting
= waiting_for_user_input_p
;
5200 /* No need to gcpro these, because all we do with them later
5201 is test them for EQness, and none of them should be a string. */
5203 Lisp_Object obuffer
, okeymap
;
5204 XSETBUFFER (obuffer
, current_buffer
);
5205 okeymap
= BVAR (current_buffer
, keymap
);
5208 /* We inhibit quit here instead of just catching it so that
5209 hitting ^G when a filter happens to be running won't screw
5211 specbind (Qinhibit_quit
, Qt
);
5212 specbind (Qlast_nonmenu_event
, Qt
);
5214 /* In case we get recursively called,
5215 and we already saved the match data nonrecursively,
5216 save the same match data in safely recursive fashion. */
5217 if (outer_running_asynch_code
)
5220 /* Don't clobber the CURRENT match data, either! */
5221 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5222 restore_search_regs ();
5223 record_unwind_save_match_data ();
5224 Fset_match_data (tem
, Qt
);
5227 /* For speed, if a search happens within this code,
5228 save the match data in a special nonrecursive fashion. */
5229 running_asynch_code
= 1;
5231 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5232 text
= coding
->dst_object
;
5233 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5234 /* A new coding system might be found. */
5235 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5237 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5239 /* Don't call setup_coding_system for
5240 proc_decode_coding_system[channel] here. It is done in
5241 detect_coding called via decode_coding above. */
5243 /* If a coding system for encoding is not yet decided, we set
5244 it as the same as coding-system for decoding.
5246 But, before doing that we must check if
5247 proc_encode_coding_system[p->outfd] surely points to a
5248 valid memory because p->outfd will be changed once EOF is
5249 sent to the process. */
5250 if (NILP (p
->encode_coding_system
)
5251 && proc_encode_coding_system
[p
->outfd
])
5253 pset_encode_coding_system
5254 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5255 setup_coding_system (p
->encode_coding_system
,
5256 proc_encode_coding_system
[p
->outfd
]);
5260 if (coding
->carryover_bytes
> 0)
5262 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5263 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5264 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5265 coding
->carryover_bytes
);
5266 p
->decoding_carryover
= coding
->carryover_bytes
;
5268 if (SBYTES (text
) > 0)
5269 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5270 sometimes it's simply wrong to wrap (e.g. when called from
5271 accept-process-output). */
5272 internal_condition_case_1 (read_process_output_call
,
5274 Fcons (proc
, Fcons (text
, Qnil
))),
5275 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5276 read_process_output_error_handler
);
5278 /* If we saved the match data nonrecursively, restore it now. */
5279 restore_search_regs ();
5280 running_asynch_code
= outer_running_asynch_code
;
5282 /* Restore waiting_for_user_input_p as it was
5283 when we were called, in case the filter clobbered it. */
5284 waiting_for_user_input_p
= waiting
;
5286 #if 0 /* Call record_asynch_buffer_change unconditionally,
5287 because we might have changed minor modes or other things
5288 that affect key bindings. */
5289 if (! EQ (Fcurrent_buffer (), obuffer
)
5290 || ! EQ (current_buffer
->keymap
, okeymap
))
5292 /* But do it only if the caller is actually going to read events.
5293 Otherwise there's no need to make him wake up, and it could
5294 cause trouble (for example it would make sit_for return). */
5295 if (waiting_for_user_input_p
== -1)
5296 record_asynch_buffer_change ();
5299 /* If no filter, write into buffer if it isn't dead. */
5300 else if (!NILP (p
->buffer
) && !NILP (BVAR (XBUFFER (p
->buffer
), name
)))
5302 Lisp_Object old_read_only
;
5303 ptrdiff_t old_begv
, old_zv
;
5304 ptrdiff_t old_begv_byte
, old_zv_byte
;
5305 ptrdiff_t before
, before_byte
;
5306 ptrdiff_t opoint_byte
;
5310 Fset_buffer (p
->buffer
);
5312 opoint_byte
= PT_BYTE
;
5313 old_read_only
= BVAR (current_buffer
, read_only
);
5316 old_begv_byte
= BEGV_BYTE
;
5317 old_zv_byte
= ZV_BYTE
;
5319 bset_read_only (current_buffer
, Qnil
);
5321 /* Insert new output into buffer
5322 at the current end-of-output marker,
5323 thus preserving logical ordering of input and output. */
5324 if (XMARKER (p
->mark
)->buffer
)
5325 SET_PT_BOTH (clip_to_bounds (BEGV
,
5326 marker_position (p
->mark
), ZV
),
5327 clip_to_bounds (BEGV_BYTE
,
5328 marker_byte_position (p
->mark
),
5331 SET_PT_BOTH (ZV
, ZV_BYTE
);
5333 before_byte
= PT_BYTE
;
5335 /* If the output marker is outside of the visible region, save
5336 the restriction and widen. */
5337 if (! (BEGV
<= PT
&& PT
<= ZV
))
5340 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5341 text
= coding
->dst_object
;
5342 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5343 /* A new coding system might be found. See the comment in the
5344 similar code in the previous `if' block. */
5345 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5347 pset_decode_coding_system (p
, Vlast_coding_system_used
);
5348 if (NILP (p
->encode_coding_system
)
5349 && proc_encode_coding_system
[p
->outfd
])
5351 pset_encode_coding_system
5352 (p
, coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
));
5353 setup_coding_system (p
->encode_coding_system
,
5354 proc_encode_coding_system
[p
->outfd
]);
5357 if (coding
->carryover_bytes
> 0)
5359 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5360 pset_decoding_buf (p
, make_uninit_string (coding
->carryover_bytes
));
5361 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5362 coding
->carryover_bytes
);
5363 p
->decoding_carryover
= coding
->carryover_bytes
;
5365 /* Adjust the multibyteness of TEXT to that of the buffer. */
5366 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5367 != ! STRING_MULTIBYTE (text
))
5368 text
= (STRING_MULTIBYTE (text
)
5369 ? Fstring_as_unibyte (text
)
5370 : Fstring_to_multibyte (text
));
5371 /* Insert before markers in case we are inserting where
5372 the buffer's mark is, and the user's next command is Meta-y. */
5373 insert_from_string_before_markers (text
, 0, 0,
5374 SCHARS (text
), SBYTES (text
), 0);
5376 /* Make sure the process marker's position is valid when the
5377 process buffer is changed in the signal_after_change above.
5378 W3 is known to do that. */
5379 if (BUFFERP (p
->buffer
)
5380 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5381 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5383 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5385 update_mode_lines
++;
5387 /* Make sure opoint and the old restrictions
5388 float ahead of any new text just as point would. */
5389 if (opoint
>= before
)
5391 opoint
+= PT
- before
;
5392 opoint_byte
+= PT_BYTE
- before_byte
;
5394 if (old_begv
> before
)
5396 old_begv
+= PT
- before
;
5397 old_begv_byte
+= PT_BYTE
- before_byte
;
5399 if (old_zv
>= before
)
5401 old_zv
+= PT
- before
;
5402 old_zv_byte
+= PT_BYTE
- before_byte
;
5405 /* If the restriction isn't what it should be, set it. */
5406 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5407 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5410 bset_read_only (current_buffer
, old_read_only
);
5411 SET_PT_BOTH (opoint
, opoint_byte
);
5413 /* Handling the process output should not deactivate the mark. */
5414 Vdeactivate_mark
= odeactivate
;
5416 unbind_to (count
, Qnil
);
5420 /* Sending data to subprocess */
5422 static jmp_buf send_process_frame
;
5423 static Lisp_Object process_sent_to
;
5425 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5426 static _Noreturn
void send_process_trap (int);
5430 send_process_trap (int ignore
)
5432 SIGNAL_THREAD_CHECK (SIGPIPE
);
5433 sigunblock (sigmask (SIGPIPE
));
5434 _longjmp (send_process_frame
, 1);
5437 /* In send_process, when a write fails temporarily,
5438 wait_reading_process_output is called. It may execute user code,
5439 e.g. timers, that attempts to write new data to the same process.
5440 We must ensure that data is sent in the right order, and not
5441 interspersed half-completed with other writes (Bug#10815). This is
5442 handled by the write_queue element of struct process. It is a list
5443 with each entry having the form
5445 (string . (offset . length))
5447 where STRING is a lisp string, OFFSET is the offset into the
5448 string's byte sequence from which we should begin to send, and
5449 LENGTH is the number of bytes left to send. */
5451 /* Create a new entry in write_queue.
5452 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5453 BUF is a pointer to the string sequence of the input_obj or a C
5454 string in case of Qt or Qnil. */
5457 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5458 const char *buf
, ptrdiff_t len
, int front
)
5461 Lisp_Object entry
, obj
;
5463 if (STRINGP (input_obj
))
5465 offset
= buf
- SSDATA (input_obj
);
5471 obj
= make_unibyte_string (buf
, len
);
5474 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5477 pset_write_queue (p
, Fcons (entry
, p
->write_queue
));
5479 pset_write_queue (p
, nconc2 (p
->write_queue
, Fcons (entry
, Qnil
)));
5482 /* Remove the first element in the write_queue of process P, put its
5483 contents in OBJ, BUF and LEN, and return non-zero. If the
5484 write_queue is empty, return zero. */
5487 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5488 const char **buf
, ptrdiff_t *len
)
5490 Lisp_Object entry
, offset_length
;
5493 if (NILP (p
->write_queue
))
5496 entry
= XCAR (p
->write_queue
);
5497 pset_write_queue (p
, XCDR (p
->write_queue
));
5499 *obj
= XCAR (entry
);
5500 offset_length
= XCDR (entry
);
5502 *len
= XINT (XCDR (offset_length
));
5503 offset
= XINT (XCAR (offset_length
));
5504 *buf
= SSDATA (*obj
) + offset
;
5509 /* Send some data to process PROC.
5510 BUF is the beginning of the data; LEN is the number of characters.
5511 OBJECT is the Lisp object that the data comes from. If OBJECT is
5512 nil or t, it means that the data comes from C string.
5514 If OBJECT is not nil, the data is encoded by PROC's coding-system
5515 for encoding before it is sent.
5517 This function can evaluate Lisp code and can garbage collect. */
5520 send_process (volatile Lisp_Object proc
, const char *volatile buf
,
5521 volatile ptrdiff_t len
, volatile Lisp_Object object
)
5523 /* Use volatile to protect variables from being clobbered by longjmp. */
5524 struct Lisp_Process
*p
= XPROCESS (proc
);
5526 struct coding_system
*coding
;
5527 void (*volatile old_sigpipe
) (int);
5529 if (p
->raw_status_new
)
5531 if (! EQ (p
->status
, Qrun
))
5532 error ("Process %s not running", SDATA (p
->name
));
5534 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5536 coding
= proc_encode_coding_system
[p
->outfd
];
5537 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5539 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5540 || (BUFFERP (object
)
5541 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5544 pset_encode_coding_system
5545 (p
, complement_process_encoding_system (p
->encode_coding_system
));
5546 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5548 /* The coding system for encoding was changed to raw-text
5549 because we sent a unibyte text previously. Now we are
5550 sending a multibyte text, thus we must encode it by the
5551 original coding system specified for the current process.
5553 Another reason we come here is that the coding system
5554 was just complemented and a new one was returned by
5555 complement_process_encoding_system. */
5556 setup_coding_system (p
->encode_coding_system
, coding
);
5557 Vlast_coding_system_used
= p
->encode_coding_system
;
5559 coding
->src_multibyte
= 1;
5563 coding
->src_multibyte
= 0;
5564 /* For sending a unibyte text, character code conversion should
5565 not take place but EOL conversion should. So, setup raw-text
5566 or one of the subsidiary if we have not yet done it. */
5567 if (CODING_REQUIRE_ENCODING (coding
))
5569 if (CODING_REQUIRE_FLUSHING (coding
))
5571 /* But, before changing the coding, we must flush out data. */
5572 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5573 send_process (proc
, "", 0, Qt
);
5574 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5576 setup_coding_system (raw_text_coding_system
5577 (Vlast_coding_system_used
),
5579 coding
->src_multibyte
= 0;
5582 coding
->dst_multibyte
= 0;
5584 if (CODING_REQUIRE_ENCODING (coding
))
5586 coding
->dst_object
= Qt
;
5587 if (BUFFERP (object
))
5589 ptrdiff_t from_byte
, from
, to
;
5590 ptrdiff_t save_pt
, save_pt_byte
;
5591 struct buffer
*cur
= current_buffer
;
5593 set_buffer_internal (XBUFFER (object
));
5594 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5596 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5597 from
= BYTE_TO_CHAR (from_byte
);
5598 to
= BYTE_TO_CHAR (from_byte
+ len
);
5599 TEMP_SET_PT_BOTH (from
, from_byte
);
5600 encode_coding_object (coding
, object
, from
, from_byte
,
5601 to
, from_byte
+ len
, Qt
);
5602 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5603 set_buffer_internal (cur
);
5605 else if (STRINGP (object
))
5607 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5608 SBYTES (object
), Qt
);
5612 coding
->dst_object
= make_unibyte_string (buf
, len
);
5613 coding
->produced
= len
;
5616 len
= coding
->produced
;
5617 object
= coding
->dst_object
;
5618 buf
= SSDATA (object
);
5621 if (pty_max_bytes
== 0)
5623 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5624 pty_max_bytes
= fpathconf (p
->outfd
, _PC_MAX_CANON
);
5625 if (pty_max_bytes
< 0)
5626 pty_max_bytes
= 250;
5628 pty_max_bytes
= 250;
5630 /* Deduct one, to leave space for the eof. */
5634 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5635 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5636 when returning with longjmp despite being declared volatile. */
5637 if (!_setjmp (send_process_frame
))
5639 p
= XPROCESS (proc
); /* Repair any setjmp clobbering. */
5640 process_sent_to
= proc
;
5642 /* If there is already data in the write_queue, put the new data
5643 in the back of queue. Otherwise, ignore it. */
5644 if (!NILP (p
->write_queue
))
5645 write_queue_push (p
, object
, buf
, len
, 0);
5647 do /* while !NILP (p->write_queue) */
5649 ptrdiff_t cur_len
= -1;
5650 const char *cur_buf
;
5651 Lisp_Object cur_object
;
5653 /* If write_queue is empty, ignore it. */
5654 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5658 cur_object
= object
;
5663 /* Send this batch, using one or more write calls. */
5664 ptrdiff_t written
= 0;
5665 int outfd
= p
->outfd
;
5666 old_sigpipe
= (void (*) (int)) signal (SIGPIPE
, send_process_trap
);
5667 #ifdef DATAGRAM_SOCKETS
5668 if (DATAGRAM_CHAN_P (outfd
))
5670 rv
= sendto (outfd
, cur_buf
, cur_len
,
5671 0, datagram_address
[outfd
].sa
,
5672 datagram_address
[outfd
].len
);
5675 else if (errno
== EMSGSIZE
)
5677 signal (SIGPIPE
, old_sigpipe
);
5678 report_file_error ("sending datagram",
5679 Fcons (proc
, Qnil
));
5687 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5690 written
= emacs_write (outfd
, cur_buf
, cur_len
);
5691 rv
= (written
? 0 : -1);
5692 #ifdef ADAPTIVE_READ_BUFFERING
5693 if (p
->read_output_delay
> 0
5694 && p
->adaptive_read_buffering
== 1)
5696 p
->read_output_delay
= 0;
5697 process_output_delay_count
--;
5698 p
->read_output_skip
= 0;
5702 signal (SIGPIPE
, old_sigpipe
);
5708 || errno
== EWOULDBLOCK
5714 /* Buffer is full. Wait, accepting input;
5715 that may allow the program
5716 to finish doing output and read more. */
5718 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5719 /* A gross hack to work around a bug in FreeBSD.
5720 In the following sequence, read(2) returns
5724 write(2) 954 bytes, get EAGAIN
5725 read(2) 1024 bytes in process_read_output
5726 read(2) 11 bytes in process_read_output
5728 That is, read(2) returns more bytes than have
5729 ever been written successfully. The 1033 bytes
5730 read are the 1022 bytes written successfully
5731 after processing (for example with CRs added if
5732 the terminal is set up that way which it is
5733 here). The same bytes will be seen again in a
5734 later read(2), without the CRs. */
5736 if (errno
== EAGAIN
)
5739 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5741 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5743 /* Put what we should have written in wait_queue. */
5744 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5745 wait_reading_process_output (0, 20 * 1000 * 1000,
5746 0, 0, Qnil
, NULL
, 0);
5747 /* Reread queue, to see what is left. */
5751 /* This is a real error. */
5752 report_file_error ("writing to process", Fcons (proc
, Qnil
));
5758 while (!NILP (p
->write_queue
));
5762 signal (SIGPIPE
, old_sigpipe
);
5763 proc
= process_sent_to
;
5764 p
= XPROCESS (proc
);
5765 p
->raw_status_new
= 0;
5766 pset_status (p
, Fcons (Qexit
, Fcons (make_number (256), Qnil
)));
5767 p
->tick
= ++process_tick
;
5768 deactivate_process (proc
);
5769 error ("SIGPIPE raised on process %s; closed it", SDATA (p
->name
));
5773 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5775 doc
: /* Send current contents of region as input to PROCESS.
5776 PROCESS may be a process, a buffer, the name of a process or buffer, or
5777 nil, indicating the current buffer's process.
5778 Called from program, takes three arguments, PROCESS, START and END.
5779 If the region is more than 500 characters long,
5780 it is sent in several bunches. This may happen even for shorter regions.
5781 Output from processes can arrive in between bunches. */)
5782 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5785 ptrdiff_t start1
, end1
;
5787 proc
= get_process (process
);
5788 validate_region (&start
, &end
);
5790 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5791 move_gap (XINT (start
));
5793 start1
= CHAR_TO_BYTE (XINT (start
));
5794 end1
= CHAR_TO_BYTE (XINT (end
));
5795 send_process (proc
, (char *) BYTE_POS_ADDR (start1
), end1
- start1
,
5796 Fcurrent_buffer ());
5801 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5803 doc
: /* Send PROCESS the contents of STRING as input.
5804 PROCESS may be a process, a buffer, the name of a process or buffer, or
5805 nil, indicating the current buffer's process.
5806 If STRING is more than 500 characters long,
5807 it is sent in several bunches. This may happen even for shorter strings.
5808 Output from processes can arrive in between bunches. */)
5809 (Lisp_Object process
, Lisp_Object string
)
5812 CHECK_STRING (string
);
5813 proc
= get_process (process
);
5814 send_process (proc
, SSDATA (string
),
5815 SBYTES (string
), string
);
5819 /* Return the foreground process group for the tty/pty that
5820 the process P uses. */
5822 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5827 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5830 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5831 master side. Try the slave side. */
5832 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5836 ioctl (fd
, TIOCGPGRP
, &gid
);
5840 #endif /* defined (TIOCGPGRP ) */
5845 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5846 Sprocess_running_child_p
, 0, 1, 0,
5847 doc
: /* Return t if PROCESS has given the terminal to a child.
5848 If the operating system does not make it possible to find out,
5849 return t unconditionally. */)
5850 (Lisp_Object process
)
5852 /* Initialize in case ioctl doesn't exist or gives an error,
5853 in a way that will cause returning t. */
5856 struct Lisp_Process
*p
;
5858 proc
= get_process (process
);
5859 p
= XPROCESS (proc
);
5861 if (!EQ (p
->type
, Qreal
))
5862 error ("Process %s is not a subprocess",
5865 error ("Process %s is not active",
5868 gid
= emacs_get_tty_pgrp (p
);
5875 /* send a signal number SIGNO to PROCESS.
5876 If CURRENT_GROUP is t, that means send to the process group
5877 that currently owns the terminal being used to communicate with PROCESS.
5878 This is used for various commands in shell mode.
5879 If CURRENT_GROUP is lambda, that means send to the process group
5880 that currently owns the terminal, but only if it is NOT the shell itself.
5882 If NOMSG is zero, insert signal-announcements into process's buffers
5885 If we can, we try to signal PROCESS by sending control characters
5886 down the pty. This allows us to signal inferiors who have changed
5887 their uid, for which killpg would return an EPERM error. */
5890 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5894 register struct Lisp_Process
*p
;
5898 proc
= get_process (process
);
5899 p
= XPROCESS (proc
);
5901 if (!EQ (p
->type
, Qreal
))
5902 error ("Process %s is not a subprocess",
5905 error ("Process %s is not active",
5909 current_group
= Qnil
;
5911 /* If we are using pgrps, get a pgrp number and make it negative. */
5912 if (NILP (current_group
))
5913 /* Send the signal to the shell's process group. */
5917 #ifdef SIGNALS_VIA_CHARACTERS
5918 /* If possible, send signals to the entire pgrp
5919 by sending an input character to it. */
5922 cc_t
*sig_char
= NULL
;
5924 tcgetattr (p
->infd
, &t
);
5929 sig_char
= &t
.c_cc
[VINTR
];
5933 sig_char
= &t
.c_cc
[VQUIT
];
5937 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5938 sig_char
= &t
.c_cc
[VSWTCH
];
5940 sig_char
= &t
.c_cc
[VSUSP
];
5945 if (sig_char
&& *sig_char
!= CDISABLE
)
5947 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5950 /* If we can't send the signal with a character,
5951 fall through and send it another way. */
5953 /* The code above may fall through if it can't
5954 handle the signal. */
5955 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5958 /* Get the current pgrp using the tty itself, if we have that.
5959 Otherwise, use the pty to get the pgrp.
5960 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5961 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5962 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5963 His patch indicates that if TIOCGPGRP returns an error, then
5964 we should just assume that p->pid is also the process group id. */
5966 gid
= emacs_get_tty_pgrp (p
);
5969 /* If we can't get the information, assume
5970 the shell owns the tty. */
5973 /* It is not clear whether anything really can set GID to -1.
5974 Perhaps on some system one of those ioctls can or could do so.
5975 Or perhaps this is vestigial. */
5978 #else /* ! defined (TIOCGPGRP ) */
5979 /* Can't select pgrps on this system, so we know that
5980 the child itself heads the pgrp. */
5982 #endif /* ! defined (TIOCGPGRP ) */
5984 /* If current_group is lambda, and the shell owns the terminal,
5985 don't send any signal. */
5986 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5994 p
->raw_status_new
= 0;
5995 pset_status (p
, Qrun
);
5996 p
->tick
= ++process_tick
;
5999 status_notify (NULL
);
6000 redisplay_preserve_echo_area (13);
6003 #endif /* ! defined (SIGCONT) */
6007 flush_pending_output (p
->infd
);
6011 /* If we don't have process groups, send the signal to the immediate
6012 subprocess. That isn't really right, but it's better than any
6013 obvious alternative. */
6016 kill (p
->pid
, signo
);
6020 /* gid may be a pid, or minus a pgrp's number */
6022 if (!NILP (current_group
))
6024 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
6025 EMACS_KILLPG (gid
, signo
);
6032 #else /* ! defined (TIOCSIGSEND) */
6033 EMACS_KILLPG (gid
, signo
);
6034 #endif /* ! defined (TIOCSIGSEND) */
6037 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
6038 doc
: /* Interrupt process PROCESS.
6039 PROCESS may be a process, a buffer, or the name of a process or buffer.
6040 No arg or nil means current buffer's process.
6041 Second arg CURRENT-GROUP non-nil means send signal to
6042 the current process-group of the process's controlling terminal
6043 rather than to the process's own process group.
6044 If the process is a shell, this means interrupt current subjob
6045 rather than the shell.
6047 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6048 don't send the signal. */)
6049 (Lisp_Object process
, Lisp_Object current_group
)
6051 process_send_signal (process
, SIGINT
, current_group
, 0);
6055 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
6056 doc
: /* Kill process PROCESS. May be process or name of one.
6057 See function `interrupt-process' for more details on usage. */)
6058 (Lisp_Object process
, Lisp_Object current_group
)
6060 process_send_signal (process
, SIGKILL
, current_group
, 0);
6064 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
6065 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
6066 See function `interrupt-process' for more details on usage. */)
6067 (Lisp_Object process
, Lisp_Object current_group
)
6069 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6073 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6074 doc
: /* Stop process PROCESS. May be process or name of one.
6075 See function `interrupt-process' for more details on usage.
6076 If PROCESS is a network or serial process, inhibit handling of incoming
6078 (Lisp_Object process
, Lisp_Object current_group
)
6080 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6082 struct Lisp_Process
*p
;
6084 p
= XPROCESS (process
);
6085 if (NILP (p
->command
)
6088 FD_CLR (p
->infd
, &input_wait_mask
);
6089 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6091 pset_command (p
, Qt
);
6095 error ("No SIGTSTP support");
6097 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6102 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6103 doc
: /* Continue process PROCESS. May be process or name of one.
6104 See function `interrupt-process' for more details on usage.
6105 If PROCESS is a network or serial process, resume handling of incoming
6107 (Lisp_Object process
, Lisp_Object current_group
)
6109 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6111 struct Lisp_Process
*p
;
6113 p
= XPROCESS (process
);
6114 if (EQ (p
->command
, Qt
)
6116 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6118 FD_SET (p
->infd
, &input_wait_mask
);
6119 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6121 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6122 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6123 #else /* not WINDOWSNT */
6124 tcflush (p
->infd
, TCIFLUSH
);
6125 #endif /* not WINDOWSNT */
6127 pset_command (p
, Qnil
);
6131 process_send_signal (process
, SIGCONT
, current_group
, 0);
6133 error ("No SIGCONT support");
6138 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6139 2, 2, "sProcess (name or number): \nnSignal code: ",
6140 doc
: /* Send PROCESS the signal with code SIGCODE.
6141 PROCESS may also be a number specifying the process id of the
6142 process to signal; in this case, the process need not be a child of
6144 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6145 (Lisp_Object process
, Lisp_Object sigcode
)
6149 if (STRINGP (process
))
6151 Lisp_Object tem
= Fget_process (process
);
6154 Lisp_Object process_number
=
6155 string_to_number (SSDATA (process
), 10, 1);
6156 if (INTEGERP (process_number
) || FLOATP (process_number
))
6157 tem
= process_number
;
6161 else if (!NUMBERP (process
))
6162 process
= get_process (process
);
6167 if (NUMBERP (process
))
6168 CONS_TO_INTEGER (process
, pid_t
, pid
);
6171 CHECK_PROCESS (process
);
6172 pid
= XPROCESS (process
)->pid
;
6174 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6177 #define parse_signal(NAME, VALUE) \
6178 else if (!xstrcasecmp (name, NAME)) \
6179 XSETINT (sigcode, VALUE)
6181 if (INTEGERP (sigcode
))
6182 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6187 CHECK_SYMBOL (sigcode
);
6188 name
= SSDATA (SYMBOL_NAME (sigcode
));
6190 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6196 parse_signal ("usr1", SIGUSR1
);
6199 parse_signal ("usr2", SIGUSR2
);
6202 parse_signal ("term", SIGTERM
);
6205 parse_signal ("hup", SIGHUP
);
6208 parse_signal ("int", SIGINT
);
6211 parse_signal ("quit", SIGQUIT
);
6214 parse_signal ("ill", SIGILL
);
6217 parse_signal ("abrt", SIGABRT
);
6220 parse_signal ("emt", SIGEMT
);
6223 parse_signal ("kill", SIGKILL
);
6226 parse_signal ("fpe", SIGFPE
);
6229 parse_signal ("bus", SIGBUS
);
6232 parse_signal ("segv", SIGSEGV
);
6235 parse_signal ("sys", SIGSYS
);
6238 parse_signal ("pipe", SIGPIPE
);
6241 parse_signal ("alrm", SIGALRM
);
6244 parse_signal ("urg", SIGURG
);
6247 parse_signal ("stop", SIGSTOP
);
6250 parse_signal ("tstp", SIGTSTP
);
6253 parse_signal ("cont", SIGCONT
);
6256 parse_signal ("chld", SIGCHLD
);
6259 parse_signal ("ttin", SIGTTIN
);
6262 parse_signal ("ttou", SIGTTOU
);
6265 parse_signal ("io", SIGIO
);
6268 parse_signal ("xcpu", SIGXCPU
);
6271 parse_signal ("xfsz", SIGXFSZ
);
6274 parse_signal ("vtalrm", SIGVTALRM
);
6277 parse_signal ("prof", SIGPROF
);
6280 parse_signal ("winch", SIGWINCH
);
6283 parse_signal ("info", SIGINFO
);
6286 error ("Undefined signal name %s", name
);
6291 return make_number (kill (pid
, XINT (sigcode
)));
6294 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6295 doc
: /* Make PROCESS see end-of-file in its input.
6296 EOF comes after any text already sent to it.
6297 PROCESS may be a process, a buffer, the name of a process or buffer, or
6298 nil, indicating the current buffer's process.
6299 If PROCESS is a network connection, or is a process communicating
6300 through a pipe (as opposed to a pty), then you cannot send any more
6301 text to PROCESS after you call this function.
6302 If PROCESS is a serial process, wait until all output written to the
6303 process has been transmitted to the serial port. */)
6304 (Lisp_Object process
)
6307 struct coding_system
*coding
;
6309 if (DATAGRAM_CONN_P (process
))
6312 proc
= get_process (process
);
6313 coding
= proc_encode_coding_system
[XPROCESS (proc
)->outfd
];
6315 /* Make sure the process is really alive. */
6316 if (XPROCESS (proc
)->raw_status_new
)
6317 update_status (XPROCESS (proc
));
6318 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6319 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6321 if (CODING_REQUIRE_FLUSHING (coding
))
6323 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6324 send_process (proc
, "", 0, Qnil
);
6327 if (XPROCESS (proc
)->pty_flag
)
6328 send_process (proc
, "\004", 1, Qnil
);
6329 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6332 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6333 error ("tcdrain() failed: %s", emacs_strerror (errno
));
6334 #endif /* not WINDOWSNT */
6335 /* Do nothing on Windows because writes are blocking. */
6339 int old_outfd
, new_outfd
;
6341 #ifdef HAVE_SHUTDOWN
6342 /* If this is a network connection, or socketpair is used
6343 for communication with the subprocess, call shutdown to cause EOF.
6344 (In some old system, shutdown to socketpair doesn't work.
6345 Then we just can't win.) */
6346 if (EQ (XPROCESS (proc
)->type
, Qnetwork
)
6347 || XPROCESS (proc
)->outfd
== XPROCESS (proc
)->infd
)
6348 shutdown (XPROCESS (proc
)->outfd
, 1);
6349 /* In case of socketpair, outfd == infd, so don't close it. */
6350 if (XPROCESS (proc
)->outfd
!= XPROCESS (proc
)->infd
)
6351 emacs_close (XPROCESS (proc
)->outfd
);
6352 #else /* not HAVE_SHUTDOWN */
6353 emacs_close (XPROCESS (proc
)->outfd
);
6354 #endif /* not HAVE_SHUTDOWN */
6355 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6358 old_outfd
= XPROCESS (proc
)->outfd
;
6360 if (!proc_encode_coding_system
[new_outfd
])
6361 proc_encode_coding_system
[new_outfd
]
6362 = xmalloc (sizeof (struct coding_system
));
6363 memcpy (proc_encode_coding_system
[new_outfd
],
6364 proc_encode_coding_system
[old_outfd
],
6365 sizeof (struct coding_system
));
6366 memset (proc_encode_coding_system
[old_outfd
], 0,
6367 sizeof (struct coding_system
));
6369 XPROCESS (proc
)->outfd
= new_outfd
;
6374 /* On receipt of a signal that a child status has changed, loop asking
6375 about children with changed statuses until the system says there
6378 All we do is change the status; we do not run sentinels or print
6379 notifications. That is saved for the next time keyboard input is
6380 done, in order to avoid timing errors.
6382 ** WARNING: this can be called during garbage collection.
6383 Therefore, it must not be fooled by the presence of mark bits in
6386 ** USG WARNING: Although it is not obvious from the documentation
6387 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6388 signal() before executing at least one wait(), otherwise the
6389 handler will be called again, resulting in an infinite loop. The
6390 relevant portion of the documentation reads "SIGCLD signals will be
6391 queued and the signal-catching function will be continually
6392 reentered until the queue is empty". Invoking signal() causes the
6393 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6396 ** Malloc WARNING: This should never call malloc either directly or
6397 indirectly; if it does, that is a bug */
6401 sigchld_handler (int signo
)
6403 int old_errno
= errno
;
6405 struct Lisp_Process
*p
;
6407 SIGNAL_THREAD_CHECK (signo
);
6418 #endif /* no WUNTRACED */
6419 /* Keep trying to get a status until we get a definitive result. */
6423 pid
= waitpid (-1, &w
, WNOHANG
| WUNTRACED
);
6425 while (pid
< 0 && errno
== EINTR
);
6429 /* PID == 0 means no processes found, PID == -1 means a real
6430 failure. We have done all our job, so return. */
6437 #endif /* no WNOHANG */
6439 /* Find the process that signaled us, and record its status. */
6441 /* The process can have been deleted by Fdelete_process. */
6442 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6444 Lisp_Object xpid
= XCAR (tail
);
6445 if ((INTEGERP (xpid
) && pid
== XINT (xpid
))
6446 || (FLOATP (xpid
) && pid
== XFLOAT_DATA (xpid
)))
6448 XSETCAR (tail
, Qnil
);
6449 goto sigchld_end_of_loop
;
6453 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6455 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6457 proc
= XCDR (XCAR (tail
));
6458 p
= XPROCESS (proc
);
6459 if (EQ (p
->type
, Qreal
) && p
->pid
== pid
)
6464 /* Look for an asynchronous process whose pid hasn't been filled
6467 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6469 proc
= XCDR (XCAR (tail
));
6470 p
= XPROCESS (proc
);
6476 /* Change the status of the process that was found. */
6479 int clear_desc_flag
= 0;
6481 p
->tick
= ++process_tick
;
6483 p
->raw_status_new
= 1;
6485 /* If process has terminated, stop waiting for its output. */
6486 if ((WIFSIGNALED (w
) || WIFEXITED (w
))
6488 clear_desc_flag
= 1;
6490 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6491 if (clear_desc_flag
)
6493 FD_CLR (p
->infd
, &input_wait_mask
);
6494 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6497 /* Tell wait_reading_process_output that it needs to wake up and
6499 if (input_available_clear_time
)
6500 *input_available_clear_time
= make_emacs_time (0, 0);
6503 /* There was no asynchronous process found for that pid: we have
6504 a synchronous process. */
6507 synch_process_alive
= 0;
6509 /* Report the status of the synchronous process. */
6511 synch_process_retcode
= WEXITSTATUS (w
);
6512 else if (WIFSIGNALED (w
))
6513 synch_process_termsig
= WTERMSIG (w
);
6515 /* Tell wait_reading_process_output that it needs to wake up and
6517 if (input_available_clear_time
)
6518 *input_available_clear_time
= make_emacs_time (0, 0);
6521 sigchld_end_of_loop
:
6524 /* On some systems, we must return right away.
6525 If any more processes want to signal us, we will
6527 Otherwise (on systems that have WNOHANG), loop around
6528 to use up all the processes that have something to tell us. */
6529 #if (defined WINDOWSNT \
6530 || (defined USG && !defined GNU_LINUX \
6531 && !(defined HPUX && defined WNOHANG)))
6534 #endif /* USG, but not HPUX with WNOHANG */
6537 #endif /* SIGCHLD */
6541 exec_sentinel_unwind (Lisp_Object data
)
6543 pset_sentinel (XPROCESS (XCAR (data
)), XCDR (data
));
6548 exec_sentinel_error_handler (Lisp_Object error_val
)
6550 cmd_error_internal (error_val
, "error in process sentinel: ");
6552 update_echo_area ();
6553 Fsleep_for (make_number (2), Qnil
);
6558 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6560 Lisp_Object sentinel
, odeactivate
;
6561 struct Lisp_Process
*p
= XPROCESS (proc
);
6562 ptrdiff_t count
= SPECPDL_INDEX ();
6563 bool outer_running_asynch_code
= running_asynch_code
;
6564 int waiting
= waiting_for_user_input_p
;
6566 if (inhibit_sentinels
)
6569 /* No need to gcpro these, because all we do with them later
6570 is test them for EQness, and none of them should be a string. */
6571 odeactivate
= Vdeactivate_mark
;
6573 Lisp_Object obuffer
, okeymap
;
6574 XSETBUFFER (obuffer
, current_buffer
);
6575 okeymap
= BVAR (current_buffer
, keymap
);
6578 /* There's no good reason to let sentinels change the current
6579 buffer, and many callers of accept-process-output, sit-for, and
6580 friends don't expect current-buffer to be changed from under them. */
6581 record_unwind_current_buffer ();
6583 sentinel
= p
->sentinel
;
6584 if (NILP (sentinel
))
6587 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6588 assure that it gets restored no matter how the sentinel exits. */
6589 pset_sentinel (p
, Qnil
);
6590 record_unwind_protect (exec_sentinel_unwind
, Fcons (proc
, sentinel
));
6591 /* Inhibit quit so that random quits don't screw up a running filter. */
6592 specbind (Qinhibit_quit
, Qt
);
6593 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6595 /* In case we get recursively called,
6596 and we already saved the match data nonrecursively,
6597 save the same match data in safely recursive fashion. */
6598 if (outer_running_asynch_code
)
6601 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6602 restore_search_regs ();
6603 record_unwind_save_match_data ();
6604 Fset_match_data (tem
, Qt
);
6607 /* For speed, if a search happens within this code,
6608 save the match data in a special nonrecursive fashion. */
6609 running_asynch_code
= 1;
6611 internal_condition_case_1 (read_process_output_call
,
6613 Fcons (proc
, Fcons (reason
, Qnil
))),
6614 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6615 exec_sentinel_error_handler
);
6617 /* If we saved the match data nonrecursively, restore it now. */
6618 restore_search_regs ();
6619 running_asynch_code
= outer_running_asynch_code
;
6621 Vdeactivate_mark
= odeactivate
;
6623 /* Restore waiting_for_user_input_p as it was
6624 when we were called, in case the filter clobbered it. */
6625 waiting_for_user_input_p
= waiting
;
6628 if (! EQ (Fcurrent_buffer (), obuffer
)
6629 || ! EQ (current_buffer
->keymap
, okeymap
))
6631 /* But do it only if the caller is actually going to read events.
6632 Otherwise there's no need to make him wake up, and it could
6633 cause trouble (for example it would make sit_for return). */
6634 if (waiting_for_user_input_p
== -1)
6635 record_asynch_buffer_change ();
6637 unbind_to (count
, Qnil
);
6640 /* Report all recent events of a change in process status
6641 (either run the sentinel or output a message).
6642 This is usually done while Emacs is waiting for keyboard input
6643 but can be done at other times. */
6646 status_notify (struct Lisp_Process
*deleting_process
)
6648 register Lisp_Object proc
, buffer
;
6649 Lisp_Object tail
, msg
;
6650 struct gcpro gcpro1
, gcpro2
;
6654 /* We need to gcpro tail; if read_process_output calls a filter
6655 which deletes a process and removes the cons to which tail points
6656 from Vprocess_alist, and then causes a GC, tail is an unprotected
6660 /* Set this now, so that if new processes are created by sentinels
6661 that we run, we get called again to handle their status changes. */
6662 update_tick
= process_tick
;
6664 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6667 register struct Lisp_Process
*p
;
6669 proc
= Fcdr (XCAR (tail
));
6670 p
= XPROCESS (proc
);
6672 if (p
->tick
!= p
->update_tick
)
6674 p
->update_tick
= p
->tick
;
6676 /* If process is still active, read any output that remains. */
6677 while (! EQ (p
->filter
, Qt
)
6678 && ! EQ (p
->status
, Qconnect
)
6679 && ! EQ (p
->status
, Qlisten
)
6680 /* Network or serial process not stopped: */
6681 && ! EQ (p
->command
, Qt
)
6683 && p
!= deleting_process
6684 && read_process_output (proc
, p
->infd
) > 0);
6688 /* Get the text to use for the message. */
6689 if (p
->raw_status_new
)
6691 msg
= status_message (p
);
6693 /* If process is terminated, deactivate it or delete it. */
6695 if (CONSP (p
->status
))
6696 symbol
= XCAR (p
->status
);
6698 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6699 || EQ (symbol
, Qclosed
))
6701 if (delete_exited_processes
)
6702 remove_process (proc
);
6704 deactivate_process (proc
);
6707 /* The actions above may have further incremented p->tick.
6708 So set p->update_tick again
6709 so that an error in the sentinel will not cause
6710 this code to be run again. */
6711 p
->update_tick
= p
->tick
;
6712 /* Now output the message suitably. */
6713 if (!NILP (p
->sentinel
))
6714 exec_sentinel (proc
, msg
);
6715 /* Don't bother with a message in the buffer
6716 when a process becomes runnable. */
6717 else if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6720 struct buffer
*old
= current_buffer
;
6721 ptrdiff_t opoint
, opoint_byte
;
6722 ptrdiff_t before
, before_byte
;
6724 /* Avoid error if buffer is deleted
6725 (probably that's why the process is dead, too) */
6726 if (NILP (BVAR (XBUFFER (buffer
), name
)))
6728 Fset_buffer (buffer
);
6731 opoint_byte
= PT_BYTE
;
6732 /* Insert new output into buffer
6733 at the current end-of-output marker,
6734 thus preserving logical ordering of input and output. */
6735 if (XMARKER (p
->mark
)->buffer
)
6736 Fgoto_char (p
->mark
);
6738 SET_PT_BOTH (ZV
, ZV_BYTE
);
6741 before_byte
= PT_BYTE
;
6743 tem
= BVAR (current_buffer
, read_only
);
6744 bset_read_only (current_buffer
, Qnil
);
6745 insert_string ("\nProcess ");
6746 { /* FIXME: temporary kludge */
6747 Lisp_Object tem2
= p
->name
; Finsert (1, &tem2
); }
6748 insert_string (" ");
6750 bset_read_only (current_buffer
, tem
);
6751 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6753 if (opoint
>= before
)
6754 SET_PT_BOTH (opoint
+ (PT
- before
),
6755 opoint_byte
+ (PT_BYTE
- before_byte
));
6757 SET_PT_BOTH (opoint
, opoint_byte
);
6759 set_buffer_internal (old
);
6764 update_mode_lines
++; /* in case buffers use %s in mode-line-format */
6769 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6770 Sset_process_coding_system
, 1, 3, 0,
6771 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6772 DECODING will be used to decode subprocess output and ENCODING to
6773 encode subprocess input. */)
6774 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6776 register struct Lisp_Process
*p
;
6778 CHECK_PROCESS (process
);
6779 p
= XPROCESS (process
);
6781 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6783 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6784 Fcheck_coding_system (decoding
);
6785 Fcheck_coding_system (encoding
);
6786 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6787 pset_decode_coding_system (p
, decoding
);
6788 pset_encode_coding_system (p
, encoding
);
6789 setup_process_coding_systems (process
);
6794 DEFUN ("process-coding-system",
6795 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6796 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6797 (register Lisp_Object process
)
6799 CHECK_PROCESS (process
);
6800 return Fcons (XPROCESS (process
)->decode_coding_system
,
6801 XPROCESS (process
)->encode_coding_system
);
6804 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6805 Sset_process_filter_multibyte
, 2, 2, 0,
6806 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6807 If FLAG is non-nil, the filter is given multibyte strings.
6808 If FLAG is nil, the filter is given unibyte strings. In this case,
6809 all character code conversion except for end-of-line conversion is
6811 (Lisp_Object process
, Lisp_Object flag
)
6813 register struct Lisp_Process
*p
;
6815 CHECK_PROCESS (process
);
6816 p
= XPROCESS (process
);
6818 pset_decode_coding_system
6819 (p
, raw_text_coding_system (p
->decode_coding_system
));
6820 setup_process_coding_systems (process
);
6825 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6826 Sprocess_filter_multibyte_p
, 1, 1, 0,
6827 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6828 (Lisp_Object process
)
6830 register struct Lisp_Process
*p
;
6831 struct coding_system
*coding
;
6833 CHECK_PROCESS (process
);
6834 p
= XPROCESS (process
);
6835 coding
= proc_decode_coding_system
[p
->infd
];
6836 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6845 add_gpm_wait_descriptor (int desc
)
6847 add_keyboard_wait_descriptor (desc
);
6851 delete_gpm_wait_descriptor (int desc
)
6853 delete_keyboard_wait_descriptor (desc
);
6860 /* Return nonzero if *MASK has a bit set
6861 that corresponds to one of the keyboard input descriptors. */
6864 keyboard_bit_set (fd_set
*mask
)
6868 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6869 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6870 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6877 #else /* not subprocesses */
6879 /* Defined on msdos.c. */
6880 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
6881 EMACS_TIME
*, void *);
6883 /* Implementation of wait_reading_process_output, assuming that there
6884 are no subprocesses. Used only by the MS-DOS build.
6886 Wait for timeout to elapse and/or keyboard input to be available.
6890 If negative, gobble data immediately available but don't wait for any.
6893 an additional duration to wait, measured in nanoseconds
6894 If TIME_LIMIT is zero, then:
6895 If NSECS == 0, there is no limit.
6896 If NSECS > 0, the timeout consists of NSECS only.
6897 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6900 0 to ignore keyboard input, or
6901 1 to return when input is available, or
6902 -1 means caller will actually read the input, so don't throw to
6905 see full version for other parameters. We know that wait_proc will
6906 always be NULL, since `subprocesses' isn't defined.
6908 DO_DISPLAY != 0 means redisplay should be done to show subprocess
6909 output that arrives.
6911 Return true if we received input from any process. */
6914 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6916 Lisp_Object wait_for_cell
,
6917 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6920 EMACS_TIME end_time
, timeout
;
6927 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6928 time_limit
= TYPE_MAXIMUM (time_t);
6930 /* What does time_limit really mean? */
6931 if (time_limit
|| 0 < nsecs
)
6933 timeout
= make_emacs_time (time_limit
, nsecs
);
6934 end_time
= add_emacs_time (current_emacs_time (), timeout
);
6937 /* Turn off periodic alarms (in case they are in use)
6938 and then turn off any other atimers,
6939 because the select emulator uses alarms. */
6941 turn_on_atimers (0);
6945 int timeout_reduced_for_timers
= 0;
6946 SELECT_TYPE waitchannels
;
6949 /* If calling from keyboard input, do not quit
6950 since we want to return C-g as an input character.
6951 Otherwise, do pending quit if requested. */
6955 /* Exit now if the cell we're waiting for became non-nil. */
6956 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6959 /* Compute time from now till when time limit is up */
6960 /* Exit if already run out */
6963 /* A negative timeout means
6964 gobble output available now
6965 but don't wait at all. */
6967 timeout
= make_emacs_time (0, 0);
6969 else if (time_limit
|| 0 < nsecs
)
6971 EMACS_TIME now
= current_emacs_time ();
6972 if (EMACS_TIME_LE (end_time
, now
))
6974 timeout
= sub_emacs_time (end_time
, now
);
6978 timeout
= make_emacs_time (100000, 0);
6981 /* If our caller will not immediately handle keyboard events,
6982 run timer events directly.
6983 (Callers that will immediately read keyboard events
6984 call timer_delay on their own.) */
6985 if (NILP (wait_for_cell
))
6987 EMACS_TIME timer_delay
;
6991 int old_timers_run
= timers_run
;
6992 timer_delay
= timer_check ();
6993 if (timers_run
!= old_timers_run
&& do_display
)
6994 /* We must retry, since a timer may have requeued itself
6995 and that could alter the time delay. */
6996 redisplay_preserve_echo_area (14);
7000 while (!detect_input_pending ());
7002 /* If there is unread keyboard input, also return. */
7004 && requeued_events_pending_p ())
7007 if (EMACS_TIME_VALID_P (timer_delay
) && 0 <= nsecs
)
7009 if (EMACS_TIME_LT (timer_delay
, timeout
))
7011 timeout
= timer_delay
;
7012 timeout_reduced_for_timers
= 1;
7017 /* Cause C-g and alarm signals to take immediate action,
7018 and cause input available signals to zero out timeout. */
7020 set_waiting_for_input (&timeout
);
7022 /* If a frame has been newly mapped and needs updating,
7023 reprocess its display stuff. */
7024 if (frame_garbaged
&& do_display
)
7026 clear_waiting_for_input ();
7027 redisplay_preserve_echo_area (15);
7029 set_waiting_for_input (&timeout
);
7032 /* Wait till there is something to do. */
7033 FD_ZERO (&waitchannels
);
7034 if (read_kbd
&& detect_input_pending ())
7038 if (read_kbd
|| !NILP (wait_for_cell
))
7039 FD_SET (0, &waitchannels
);
7040 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
7045 /* Make C-g and alarm signals set flags again */
7046 clear_waiting_for_input ();
7048 /* If we woke up due to SIGWINCH, actually change size now. */
7049 do_pending_window_change (0);
7051 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
7052 /* We waited the full specified time, so return now. */
7057 /* If the system call was interrupted, then go around the
7059 if (xerrno
== EINTR
)
7060 FD_ZERO (&waitchannels
);
7062 error ("select error: %s", emacs_strerror (xerrno
));
7065 /* Check for keyboard input */
7068 && detect_input_pending_run_timers (do_display
))
7070 swallow_events (do_display
);
7071 if (detect_input_pending_run_timers (do_display
))
7075 /* If there is unread keyboard input, also return. */
7077 && requeued_events_pending_p ())
7080 /* If wait_for_cell. check for keyboard input
7081 but don't run any timers.
7082 ??? (It seems wrong to me to check for keyboard
7083 input at all when wait_for_cell, but the code
7084 has been this way since July 1994.
7085 Try changing this after version 19.31.) */
7086 if (! NILP (wait_for_cell
)
7087 && detect_input_pending ())
7089 swallow_events (do_display
);
7090 if (detect_input_pending ())
7094 /* Exit now if the cell we're waiting for became non-nil. */
7095 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7104 #endif /* not subprocesses */
7106 /* The following functions are needed even if async subprocesses are
7107 not supported. Some of them are no-op stubs in that case. */
7109 /* Add DESC to the set of keyboard input descriptors. */
7112 add_keyboard_wait_descriptor (int desc
)
7114 #ifdef subprocesses /* actually means "not MSDOS" */
7115 FD_SET (desc
, &input_wait_mask
);
7116 FD_SET (desc
, &non_process_wait_mask
);
7117 if (desc
> max_input_desc
)
7118 max_input_desc
= desc
;
7122 /* From now on, do not expect DESC to give keyboard input. */
7125 delete_keyboard_wait_descriptor (int desc
)
7129 int lim
= max_input_desc
;
7131 FD_CLR (desc
, &input_wait_mask
);
7132 FD_CLR (desc
, &non_process_wait_mask
);
7134 if (desc
== max_input_desc
)
7135 for (fd
= 0; fd
< lim
; fd
++)
7136 if (FD_ISSET (fd
, &input_wait_mask
) || FD_ISSET (fd
, &write_mask
))
7137 max_input_desc
= fd
;
7141 /* Setup coding systems of PROCESS. */
7144 setup_process_coding_systems (Lisp_Object process
)
7147 struct Lisp_Process
*p
= XPROCESS (process
);
7149 int outch
= p
->outfd
;
7150 Lisp_Object coding_system
;
7152 if (inch
< 0 || outch
< 0)
7155 if (!proc_decode_coding_system
[inch
])
7156 proc_decode_coding_system
[inch
] = xmalloc (sizeof (struct coding_system
));
7157 coding_system
= p
->decode_coding_system
;
7158 if (! NILP (p
->filter
))
7160 else if (BUFFERP (p
->buffer
))
7162 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7163 coding_system
= raw_text_coding_system (coding_system
);
7165 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7167 if (!proc_encode_coding_system
[outch
])
7168 proc_encode_coding_system
[outch
] = xmalloc (sizeof (struct coding_system
));
7169 setup_coding_system (p
->encode_coding_system
,
7170 proc_encode_coding_system
[outch
]);
7174 /* Close all descriptors currently in use for communication
7175 with subprocess. This is used in a newly-forked subprocess
7176 to get rid of irrelevant descriptors. */
7179 close_process_descs (void)
7183 for (i
= 0; i
< MAXDESC
; i
++)
7185 Lisp_Object process
;
7186 process
= chan_process
[i
];
7187 if (!NILP (process
))
7189 int in
= XPROCESS (process
)->infd
;
7190 int out
= XPROCESS (process
)->outfd
;
7193 if (out
>= 0 && in
!= out
)
7200 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7201 doc
: /* Return the (or a) process associated with BUFFER.
7202 BUFFER may be a buffer or the name of one. */)
7203 (register Lisp_Object buffer
)
7206 register Lisp_Object buf
, tail
, proc
;
7208 if (NILP (buffer
)) return Qnil
;
7209 buf
= Fget_buffer (buffer
);
7210 if (NILP (buf
)) return Qnil
;
7212 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
7214 proc
= Fcdr (XCAR (tail
));
7215 if (PROCESSP (proc
) && EQ (XPROCESS (proc
)->buffer
, buf
))
7218 #endif /* subprocesses */
7222 DEFUN ("process-inherit-coding-system-flag",
7223 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7225 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7226 If this flag is t, `buffer-file-coding-system' of the buffer
7227 associated with PROCESS will inherit the coding system used to decode
7228 the process output. */)
7229 (register Lisp_Object process
)
7232 CHECK_PROCESS (process
);
7233 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7235 /* Ignore the argument and return the value of
7236 inherit-process-coding-system. */
7237 return inherit_process_coding_system
? Qt
: Qnil
;
7241 /* Kill all processes associated with `buffer'.
7242 If `buffer' is nil, kill all processes */
7245 kill_buffer_processes (Lisp_Object buffer
)
7248 Lisp_Object tail
, proc
;
7250 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
7252 proc
= XCDR (XCAR (tail
));
7254 && (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
)))
7256 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
7257 Fdelete_process (proc
);
7258 else if (XPROCESS (proc
)->infd
>= 0)
7259 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7262 #else /* subprocesses */
7263 /* Since we have no subprocesses, this does nothing. */
7264 #endif /* subprocesses */
7267 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7268 Swaiting_for_user_input_p
, 0, 0, 0,
7269 doc
: /* Returns non-nil if Emacs is waiting for input from the user.
7270 This is intended for use by asynchronous process output filters and sentinels. */)
7274 return (waiting_for_user_input_p
? Qt
: Qnil
);
7280 /* Stop reading input from keyboard sources. */
7283 hold_keyboard_input (void)
7288 /* Resume reading input from keyboard sources. */
7291 unhold_keyboard_input (void)
7296 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7299 kbd_on_hold_p (void)
7301 return kbd_is_on_hold
;
7305 /* Enumeration of and access to system processes a-la ps(1). */
7307 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7309 doc
: /* Return a list of numerical process IDs of all running processes.
7310 If this functionality is unsupported, return nil.
7312 See `process-attributes' for getting attributes of a process given its ID. */)
7315 return list_system_processes ();
7318 DEFUN ("process-attributes", Fprocess_attributes
,
7319 Sprocess_attributes
, 1, 1, 0,
7320 doc
: /* Return attributes of the process given by its PID, a number.
7322 Value is an alist where each element is a cons cell of the form
7326 If this functionality is unsupported, the value is nil.
7328 See `list-system-processes' for getting a list of all process IDs.
7330 The KEYs of the attributes that this function may return are listed
7331 below, together with the type of the associated VALUE (in parentheses).
7332 Not all platforms support all of these attributes; unsupported
7333 attributes will not appear in the returned alist.
7334 Unless explicitly indicated otherwise, numbers can have either
7335 integer or floating point values.
7337 euid -- Effective user User ID of the process (number)
7338 user -- User name corresponding to euid (string)
7339 egid -- Effective user Group ID of the process (number)
7340 group -- Group name corresponding to egid (string)
7341 comm -- Command name (executable name only) (string)
7342 state -- Process state code, such as "S", "R", or "T" (string)
7343 ppid -- Parent process ID (number)
7344 pgrp -- Process group ID (number)
7345 sess -- Session ID, i.e. process ID of session leader (number)
7346 ttname -- Controlling tty name (string)
7347 tpgid -- ID of foreground process group on the process's tty (number)
7348 minflt -- number of minor page faults (number)
7349 majflt -- number of major page faults (number)
7350 cminflt -- cumulative number of minor page faults (number)
7351 cmajflt -- cumulative number of major page faults (number)
7352 utime -- user time used by the process, in (current-time) format,
7353 which is a list of integers (HIGH LOW USEC PSEC)
7354 stime -- system time used by the process (current-time)
7355 time -- sum of utime and stime (current-time)
7356 cutime -- user time used by the process and its children (current-time)
7357 cstime -- system time used by the process and its children (current-time)
7358 ctime -- sum of cutime and cstime (current-time)
7359 pri -- priority of the process (number)
7360 nice -- nice value of the process (number)
7361 thcount -- process thread count (number)
7362 start -- time the process started (current-time)
7363 vsize -- virtual memory size of the process in KB's (number)
7364 rss -- resident set size of the process in KB's (number)
7365 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7366 pcpu -- percents of CPU time used by the process (floating-point number)
7367 pmem -- percents of total physical memory used by process's resident set
7368 (floating-point number)
7369 args -- command line which invoked the process (string). */)
7372 return system_process_attributes (pid
);
7376 /* This is not called "init_process" because that is the name of a
7377 Mach system call, so it would cause problems on Darwin systems. */
7379 init_process_emacs (void)
7384 inhibit_sentinels
= 0;
7388 if (! noninteractive
|| initialized
)
7390 signal (SIGCHLD
, sigchld_handler
);
7393 FD_ZERO (&input_wait_mask
);
7394 FD_ZERO (&non_keyboard_wait_mask
);
7395 FD_ZERO (&non_process_wait_mask
);
7396 FD_ZERO (&write_mask
);
7397 max_process_desc
= 0;
7398 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7400 #ifdef NON_BLOCKING_CONNECT
7401 FD_ZERO (&connect_wait_mask
);
7402 num_pending_connects
= 0;
7405 #ifdef ADAPTIVE_READ_BUFFERING
7406 process_output_delay_count
= 0;
7407 process_output_skip
= 0;
7410 /* Don't do this, it caused infinite select loops. The display
7411 method should call add_keyboard_wait_descriptor on stdin if it
7414 FD_SET (0, &input_wait_mask
);
7417 Vprocess_alist
= Qnil
;
7419 deleted_pid_list
= Qnil
;
7421 for (i
= 0; i
< MAXDESC
; i
++)
7423 chan_process
[i
] = Qnil
;
7424 proc_buffered_char
[i
] = -1;
7426 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7427 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7428 #ifdef DATAGRAM_SOCKETS
7429 memset (datagram_address
, 0, sizeof datagram_address
);
7433 Lisp_Object subfeatures
= Qnil
;
7434 const struct socket_options
*sopt
;
7436 #define ADD_SUBFEATURE(key, val) \
7437 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7439 #ifdef NON_BLOCKING_CONNECT
7440 ADD_SUBFEATURE (QCnowait
, Qt
);
7442 #ifdef DATAGRAM_SOCKETS
7443 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7445 #ifdef HAVE_SEQPACKET
7446 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7448 #ifdef HAVE_LOCAL_SOCKETS
7449 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7451 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7453 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7455 #ifdef HAVE_GETSOCKNAME
7456 ADD_SUBFEATURE (QCservice
, Qt
);
7458 #if defined (O_NONBLOCK) || defined (O_NDELAY)
7459 ADD_SUBFEATURE (QCserver
, Qt
);
7462 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7463 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7465 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7468 #if defined (DARWIN_OS)
7469 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7470 processes. As such, we only change the default value. */
7473 char const *release
= (STRINGP (Voperating_system_release
)
7474 ? SSDATA (Voperating_system_release
)
7476 if (!release
|| !release
[0] || (release
[0] < '7' && release
[1] == '.')) {
7477 Vprocess_connection_type
= Qnil
;
7481 #endif /* subprocesses */
7486 syms_of_process (void)
7490 DEFSYM (Qprocessp
, "processp");
7491 DEFSYM (Qrun
, "run");
7492 DEFSYM (Qstop
, "stop");
7493 DEFSYM (Qsignal
, "signal");
7495 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7498 Qexit = intern_c_string ("exit");
7499 staticpro (&Qexit); */
7501 DEFSYM (Qopen
, "open");
7502 DEFSYM (Qclosed
, "closed");
7503 DEFSYM (Qconnect
, "connect");
7504 DEFSYM (Qfailed
, "failed");
7505 DEFSYM (Qlisten
, "listen");
7506 DEFSYM (Qlocal
, "local");
7507 DEFSYM (Qipv4
, "ipv4");
7509 DEFSYM (Qipv6
, "ipv6");
7511 DEFSYM (Qdatagram
, "datagram");
7512 DEFSYM (Qseqpacket
, "seqpacket");
7514 DEFSYM (QCport
, ":port");
7515 DEFSYM (QCspeed
, ":speed");
7516 DEFSYM (QCprocess
, ":process");
7518 DEFSYM (QCbytesize
, ":bytesize");
7519 DEFSYM (QCstopbits
, ":stopbits");
7520 DEFSYM (QCparity
, ":parity");
7521 DEFSYM (Qodd
, "odd");
7522 DEFSYM (Qeven
, "even");
7523 DEFSYM (QCflowcontrol
, ":flowcontrol");
7526 DEFSYM (QCsummary
, ":summary");
7528 DEFSYM (Qreal
, "real");
7529 DEFSYM (Qnetwork
, "network");
7530 DEFSYM (Qserial
, "serial");
7531 DEFSYM (QCbuffer
, ":buffer");
7532 DEFSYM (QChost
, ":host");
7533 DEFSYM (QCservice
, ":service");
7534 DEFSYM (QClocal
, ":local");
7535 DEFSYM (QCremote
, ":remote");
7536 DEFSYM (QCcoding
, ":coding");
7537 DEFSYM (QCserver
, ":server");
7538 DEFSYM (QCnowait
, ":nowait");
7539 DEFSYM (QCsentinel
, ":sentinel");
7540 DEFSYM (QClog
, ":log");
7541 DEFSYM (QCnoquery
, ":noquery");
7542 DEFSYM (QCstop
, ":stop");
7543 DEFSYM (QCoptions
, ":options");
7544 DEFSYM (QCplist
, ":plist");
7546 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7548 staticpro (&Vprocess_alist
);
7550 staticpro (&deleted_pid_list
);
7553 #endif /* subprocesses */
7555 DEFSYM (QCname
, ":name");
7556 DEFSYM (QCtype
, ":type");
7558 DEFSYM (Qeuid
, "euid");
7559 DEFSYM (Qegid
, "egid");
7560 DEFSYM (Quser
, "user");
7561 DEFSYM (Qgroup
, "group");
7562 DEFSYM (Qcomm
, "comm");
7563 DEFSYM (Qstate
, "state");
7564 DEFSYM (Qppid
, "ppid");
7565 DEFSYM (Qpgrp
, "pgrp");
7566 DEFSYM (Qsess
, "sess");
7567 DEFSYM (Qttname
, "ttname");
7568 DEFSYM (Qtpgid
, "tpgid");
7569 DEFSYM (Qminflt
, "minflt");
7570 DEFSYM (Qmajflt
, "majflt");
7571 DEFSYM (Qcminflt
, "cminflt");
7572 DEFSYM (Qcmajflt
, "cmajflt");
7573 DEFSYM (Qutime
, "utime");
7574 DEFSYM (Qstime
, "stime");
7575 DEFSYM (Qtime
, "time");
7576 DEFSYM (Qcutime
, "cutime");
7577 DEFSYM (Qcstime
, "cstime");
7578 DEFSYM (Qctime
, "ctime");
7579 DEFSYM (Qpri
, "pri");
7580 DEFSYM (Qnice
, "nice");
7581 DEFSYM (Qthcount
, "thcount");
7582 DEFSYM (Qstart
, "start");
7583 DEFSYM (Qvsize
, "vsize");
7584 DEFSYM (Qrss
, "rss");
7585 DEFSYM (Qetime
, "etime");
7586 DEFSYM (Qpcpu
, "pcpu");
7587 DEFSYM (Qpmem
, "pmem");
7588 DEFSYM (Qargs
, "args");
7590 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7591 doc
: /* Non-nil means delete processes immediately when they exit.
7592 A value of nil means don't delete them until `list-processes' is run. */);
7594 delete_exited_processes
= 1;
7597 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7598 doc
: /* Control type of device used to communicate with subprocesses.
7599 Values are nil to use a pipe, or t or `pty' to use a pty.
7600 The value has no effect if the system has no ptys or if all ptys are busy:
7601 then a pipe is used in any case.
7602 The value takes effect when `start-process' is called. */);
7603 Vprocess_connection_type
= Qt
;
7605 #ifdef ADAPTIVE_READ_BUFFERING
7606 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7607 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7608 On some systems, when Emacs reads the output from a subprocess, the output data
7609 is read in very small blocks, potentially resulting in very poor performance.
7610 This behavior can be remedied to some extent by setting this variable to a
7611 non-nil value, as it will automatically delay reading from such processes, to
7612 allow them to produce more output before Emacs tries to read it.
7613 If the value is t, the delay is reset after each write to the process; any other
7614 non-nil value means that the delay is not reset on write.
7615 The variable takes effect when `start-process' is called. */);
7616 Vprocess_adaptive_read_buffering
= Qt
;
7619 defsubr (&Sprocessp
);
7620 defsubr (&Sget_process
);
7621 defsubr (&Sdelete_process
);
7622 defsubr (&Sprocess_status
);
7623 defsubr (&Sprocess_exit_status
);
7624 defsubr (&Sprocess_id
);
7625 defsubr (&Sprocess_name
);
7626 defsubr (&Sprocess_tty_name
);
7627 defsubr (&Sprocess_command
);
7628 defsubr (&Sset_process_buffer
);
7629 defsubr (&Sprocess_buffer
);
7630 defsubr (&Sprocess_mark
);
7631 defsubr (&Sset_process_filter
);
7632 defsubr (&Sprocess_filter
);
7633 defsubr (&Sset_process_sentinel
);
7634 defsubr (&Sprocess_sentinel
);
7635 defsubr (&Sset_process_window_size
);
7636 defsubr (&Sset_process_inherit_coding_system_flag
);
7637 defsubr (&Sset_process_query_on_exit_flag
);
7638 defsubr (&Sprocess_query_on_exit_flag
);
7639 defsubr (&Sprocess_contact
);
7640 defsubr (&Sprocess_plist
);
7641 defsubr (&Sset_process_plist
);
7642 defsubr (&Sprocess_list
);
7643 defsubr (&Sstart_process
);
7644 defsubr (&Sserial_process_configure
);
7645 defsubr (&Smake_serial_process
);
7646 defsubr (&Sset_network_process_option
);
7647 defsubr (&Smake_network_process
);
7648 defsubr (&Sformat_network_address
);
7649 #if defined (HAVE_NET_IF_H)
7651 defsubr (&Snetwork_interface_list
);
7653 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7654 defsubr (&Snetwork_interface_info
);
7656 #endif /* defined (HAVE_NET_IF_H) */
7657 #ifdef DATAGRAM_SOCKETS
7658 defsubr (&Sprocess_datagram_address
);
7659 defsubr (&Sset_process_datagram_address
);
7661 defsubr (&Saccept_process_output
);
7662 defsubr (&Sprocess_send_region
);
7663 defsubr (&Sprocess_send_string
);
7664 defsubr (&Sinterrupt_process
);
7665 defsubr (&Skill_process
);
7666 defsubr (&Squit_process
);
7667 defsubr (&Sstop_process
);
7668 defsubr (&Scontinue_process
);
7669 defsubr (&Sprocess_running_child_p
);
7670 defsubr (&Sprocess_send_eof
);
7671 defsubr (&Ssignal_process
);
7672 defsubr (&Swaiting_for_user_input_p
);
7673 defsubr (&Sprocess_type
);
7674 defsubr (&Sset_process_coding_system
);
7675 defsubr (&Sprocess_coding_system
);
7676 defsubr (&Sset_process_filter_multibyte
);
7677 defsubr (&Sprocess_filter_multibyte_p
);
7679 #endif /* subprocesses */
7681 defsubr (&Sget_buffer_process
);
7682 defsubr (&Sprocess_inherit_coding_system_flag
);
7683 defsubr (&Slist_system_processes
);
7684 defsubr (&Sprocess_attributes
);