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/>. */
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
37 /* Only MS-DOS does not define `subprocesses'. */
40 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
45 /* Are local (unix) sockets supported? */
46 #if defined (HAVE_SYS_UN_H)
47 #if !defined (AF_LOCAL) && defined (AF_UNIX)
48 #define AF_LOCAL AF_UNIX
51 #define HAVE_LOCAL_SOCKETS
56 #include <sys/ioctl.h>
57 #if defined (HAVE_NET_IF_H)
59 #endif /* HAVE_NET_IF_H */
61 #if defined (HAVE_IFADDRS_H)
62 /* Must be after net/if.h */
65 /* We only use structs from this header when we use getifaddrs. */
66 #if defined (HAVE_NET_IF_DL_H)
67 #include <net/if_dl.h>
77 #include <netinet/in.h>
78 #include <arpa/nameser.h>
90 #endif /* subprocesses */
96 #include "character.h"
101 #include "termhooks.h"
102 #include "termopts.h"
103 #include "commands.h"
104 #include "keyboard.h"
105 #include "blockinput.h"
106 #include "dispextern.h"
107 #include "composite.h"
109 #include "sysselect.h"
110 #include "syssignal.h"
116 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
117 #include "xgselect.h"
123 /* Work around GCC 4.7.0 bug with strict overflow checking; see
124 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
125 These lines can be removed once the GCC bug is fixed. */
126 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
127 # pragma GCC diagnostic ignored "-Wstrict-overflow"
130 Lisp_Object Qeuid
, Qegid
, Qcomm
, Qstate
, Qppid
, Qpgrp
, Qsess
, Qttname
, Qtpgid
;
131 Lisp_Object Qminflt
, Qmajflt
, Qcminflt
, Qcmajflt
, Qutime
, Qstime
, Qcstime
;
132 Lisp_Object Qcutime
, Qpri
, Qnice
, Qthcount
, Qstart
, Qvsize
, Qrss
, Qargs
;
133 Lisp_Object Quser
, Qgroup
, Qetime
, Qpcpu
, Qpmem
, Qtime
, Qctime
;
134 Lisp_Object QCname
, QCtype
;
136 /* Non-zero if keyboard input is on hold, zero otherwise. */
138 static int kbd_is_on_hold
;
140 /* Nonzero means don't run process sentinels. This is used
142 int inhibit_sentinels
;
146 Lisp_Object Qprocessp
;
147 static Lisp_Object Qrun
, Qstop
, Qsignal
;
148 static Lisp_Object Qopen
, Qclosed
, Qconnect
, Qfailed
, Qlisten
;
150 static Lisp_Object Qipv4
, Qdatagram
, Qseqpacket
;
151 static Lisp_Object Qreal
, Qnetwork
, Qserial
;
153 static Lisp_Object Qipv6
;
155 static Lisp_Object QCport
, QCprocess
;
157 Lisp_Object QCbytesize
, QCstopbits
, QCparity
, Qodd
, Qeven
;
158 Lisp_Object QCflowcontrol
, Qhw
, Qsw
, QCsummary
;
159 static Lisp_Object QCbuffer
, QChost
, QCservice
;
160 static Lisp_Object QClocal
, QCremote
, QCcoding
;
161 static Lisp_Object QCserver
, QCnowait
, QCnoquery
, QCstop
;
162 static Lisp_Object QCsentinel
, QClog
, QCoptions
, QCplist
;
163 static Lisp_Object Qlast_nonmenu_event
;
164 /* QCfamily is declared and initialized in xfaces.c,
165 QCfilter in keyboard.c. */
166 extern Lisp_Object QCfamily
, QCfilter
;
168 /* Qexit is declared and initialized in eval.c. */
170 /* QCfamily is defined in xfaces.c. */
171 extern Lisp_Object QCfamily
;
172 /* QCfilter is defined in keyboard.c. */
173 extern Lisp_Object QCfilter
;
175 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
176 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
177 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
178 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
184 /* Number of events of change of status of a process. */
185 static EMACS_INT process_tick
;
186 /* Number of events for which the user or sentinel has been notified. */
187 static EMACS_INT update_tick
;
189 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
191 /* Only W32 has this, it really means that select can't take write mask. */
192 #ifdef BROKEN_NON_BLOCKING_CONNECT
193 #undef NON_BLOCKING_CONNECT
194 #define SELECT_CANT_DO_WRITE_MASK
196 #ifndef NON_BLOCKING_CONNECT
198 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
199 #if defined (O_NONBLOCK) || defined (O_NDELAY)
200 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
201 #define NON_BLOCKING_CONNECT
202 #endif /* EWOULDBLOCK || EINPROGRESS */
203 #endif /* O_NONBLOCK || O_NDELAY */
204 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
205 #endif /* HAVE_SELECT */
206 #endif /* NON_BLOCKING_CONNECT */
207 #endif /* BROKEN_NON_BLOCKING_CONNECT */
209 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
210 this system. We need to read full packets, so we need a
211 "non-destructive" select. So we require either native select,
212 or emulation of select using FIONREAD. */
214 #ifdef BROKEN_DATAGRAM_SOCKETS
215 #undef DATAGRAM_SOCKETS
217 #ifndef DATAGRAM_SOCKETS
218 #if defined (HAVE_SELECT) || defined (FIONREAD)
219 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
220 #define DATAGRAM_SOCKETS
221 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
222 #endif /* HAVE_SELECT || FIONREAD */
223 #endif /* DATAGRAM_SOCKETS */
224 #endif /* BROKEN_DATAGRAM_SOCKETS */
226 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
227 # define HAVE_SEQPACKET
230 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
231 #define ADAPTIVE_READ_BUFFERING
234 #ifdef ADAPTIVE_READ_BUFFERING
235 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
236 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
237 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
239 /* Number of processes which have a non-zero read_output_delay,
240 and therefore might be delayed for adaptive read buffering. */
242 static int process_output_delay_count
;
244 /* Non-zero if any process has non-nil read_output_skip. */
246 static int process_output_skip
;
249 #define process_output_delay_count 0
252 static Lisp_Object
Fget_process (Lisp_Object
);
253 static void create_process (Lisp_Object
, char **, Lisp_Object
);
255 static int keyboard_bit_set (SELECT_TYPE
*);
257 static void deactivate_process (Lisp_Object
);
258 static void status_notify (struct Lisp_Process
*);
259 static int read_process_output (Lisp_Object
, int);
260 static void create_pty (Lisp_Object
);
262 /* If we support a window system, turn on the code to poll periodically
263 to detect C-g. It isn't actually used when doing interrupt input. */
264 #if defined (HAVE_WINDOW_SYSTEM) && !defined (USE_ASYNC_EVENTS)
265 #define POLL_FOR_INPUT
268 static Lisp_Object
get_process (register Lisp_Object name
);
269 static void exec_sentinel (Lisp_Object proc
, Lisp_Object reason
);
271 /* Mask of bits indicating the descriptors that we wait for input on. */
273 static SELECT_TYPE input_wait_mask
;
275 /* Mask that excludes keyboard input descriptor(s). */
277 static SELECT_TYPE non_keyboard_wait_mask
;
279 /* Mask that excludes process input descriptor(s). */
281 static SELECT_TYPE non_process_wait_mask
;
283 /* Mask for selecting for write. */
285 static SELECT_TYPE write_mask
;
287 #ifdef NON_BLOCKING_CONNECT
288 /* Mask of bits indicating the descriptors that we wait for connect to
289 complete on. Once they complete, they are removed from this mask
290 and added to the input_wait_mask and non_keyboard_wait_mask. */
292 static SELECT_TYPE connect_wait_mask
;
294 /* Number of bits set in connect_wait_mask. */
295 static int num_pending_connects
;
296 #endif /* NON_BLOCKING_CONNECT */
298 /* The largest descriptor currently in use for a process object. */
299 static int max_process_desc
;
301 /* The largest descriptor currently in use for input. */
302 static int max_input_desc
;
304 /* Indexed by descriptor, gives the process (if any) for that descriptor */
305 static Lisp_Object chan_process
[MAXDESC
];
307 /* Alist of elements (NAME . PROCESS) */
308 static Lisp_Object Vprocess_alist
;
310 /* Buffered-ahead input char from process, indexed by channel.
311 -1 means empty (no char is buffered).
312 Used on sys V where the only way to tell if there is any
313 output from the process is to read at least one char.
314 Always -1 on systems that support FIONREAD. */
316 static int proc_buffered_char
[MAXDESC
];
318 /* Table of `struct coding-system' for each process. */
319 static struct coding_system
*proc_decode_coding_system
[MAXDESC
];
320 static struct coding_system
*proc_encode_coding_system
[MAXDESC
];
322 #ifdef DATAGRAM_SOCKETS
323 /* Table of `partner address' for datagram sockets. */
324 static struct sockaddr_and_len
{
327 } datagram_address
[MAXDESC
];
328 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
329 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
331 #define DATAGRAM_CHAN_P(chan) (0)
332 #define DATAGRAM_CONN_P(proc) (0)
335 /* Maximum number of bytes to send to a pty without an eof. */
336 static int pty_max_bytes
;
340 static struct fd_callback_data
346 int condition
; /* mask of the defines above. */
347 } fd_callback_info
[MAXDESC
];
350 /* Add a file descriptor FD to be monitored for when read is possible.
351 When read is possible, call FUNC with argument DATA. */
354 add_read_fd (int fd
, fd_callback func
, void *data
)
356 eassert (fd
< MAXDESC
);
357 add_keyboard_wait_descriptor (fd
);
359 fd_callback_info
[fd
].func
= func
;
360 fd_callback_info
[fd
].data
= data
;
361 fd_callback_info
[fd
].condition
|= FOR_READ
;
364 /* Stop monitoring file descriptor FD for when read is possible. */
367 delete_read_fd (int fd
)
369 eassert (fd
< MAXDESC
);
370 delete_keyboard_wait_descriptor (fd
);
372 fd_callback_info
[fd
].condition
&= ~FOR_READ
;
373 if (fd_callback_info
[fd
].condition
== 0)
375 fd_callback_info
[fd
].func
= 0;
376 fd_callback_info
[fd
].data
= 0;
380 /* Add a file descriptor FD to be monitored for when write is possible.
381 When write is possible, call FUNC with argument DATA. */
384 add_write_fd (int fd
, fd_callback func
, void *data
)
386 eassert (fd
< MAXDESC
);
387 FD_SET (fd
, &write_mask
);
388 if (fd
> max_input_desc
)
391 fd_callback_info
[fd
].func
= func
;
392 fd_callback_info
[fd
].data
= data
;
393 fd_callback_info
[fd
].condition
|= FOR_WRITE
;
396 /* Stop monitoring file descriptor FD for when write is possible. */
399 delete_write_fd (int fd
)
401 int lim
= max_input_desc
;
403 eassert (fd
< MAXDESC
);
404 FD_CLR (fd
, &write_mask
);
405 fd_callback_info
[fd
].condition
&= ~FOR_WRITE
;
406 if (fd_callback_info
[fd
].condition
== 0)
408 fd_callback_info
[fd
].func
= 0;
409 fd_callback_info
[fd
].data
= 0;
411 if (fd
== max_input_desc
)
412 for (fd
= lim
; fd
>= 0; fd
--)
413 if (FD_ISSET (fd
, &input_wait_mask
) || FD_ISSET (fd
, &write_mask
))
423 /* Compute the Lisp form of the process status, p->status, from
424 the numeric status that was returned by `wait'. */
426 static Lisp_Object
status_convert (int);
429 update_status (struct Lisp_Process
*p
)
431 eassert (p
->raw_status_new
);
432 p
->status
= status_convert (p
->raw_status
);
433 p
->raw_status_new
= 0;
436 /* Convert a process status word in Unix format to
437 the list that we use internally. */
440 status_convert (int w
)
443 return Fcons (Qstop
, Fcons (make_number (WSTOPSIG (w
)), Qnil
));
444 else if (WIFEXITED (w
))
445 return Fcons (Qexit
, Fcons (make_number (WRETCODE (w
)),
446 WCOREDUMP (w
) ? Qt
: Qnil
));
447 else if (WIFSIGNALED (w
))
448 return Fcons (Qsignal
, Fcons (make_number (WTERMSIG (w
)),
449 WCOREDUMP (w
) ? Qt
: Qnil
));
454 /* Given a status-list, extract the three pieces of information
455 and store them individually through the three pointers. */
458 decode_status (Lisp_Object l
, Lisp_Object
*symbol
, int *code
, int *coredump
)
472 *code
= XFASTINT (XCAR (tem
));
474 *coredump
= !NILP (tem
);
478 /* Return a string describing a process status list. */
481 status_message (struct Lisp_Process
*p
)
483 Lisp_Object status
= p
->status
;
486 Lisp_Object string
, string2
;
488 decode_status (status
, &symbol
, &code
, &coredump
);
490 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qstop
))
493 synchronize_system_messages_locale ();
494 signame
= strsignal (code
);
496 string
= build_string ("unknown");
501 string
= make_unibyte_string (signame
, strlen (signame
));
502 if (! NILP (Vlocale_coding_system
))
503 string
= (code_convert_string_norecord
504 (string
, Vlocale_coding_system
, 0));
505 c1
= STRING_CHAR (SDATA (string
));
508 Faset (string
, make_number (0), make_number (c2
));
510 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
511 return concat2 (string
, string2
);
513 else if (EQ (symbol
, Qexit
))
516 return build_string (code
== 0 ? "deleted\n" : "connection broken by remote peer\n");
518 return build_string ("finished\n");
519 string
= Fnumber_to_string (make_number (code
));
520 string2
= build_string (coredump
? " (core dumped)\n" : "\n");
521 return concat3 (build_string ("exited abnormally with code "),
524 else if (EQ (symbol
, Qfailed
))
526 string
= Fnumber_to_string (make_number (code
));
527 string2
= build_string ("\n");
528 return concat3 (build_string ("failed with code "),
532 return Fcopy_sequence (Fsymbol_name (symbol
));
537 /* The file name of the pty opened by allocate_pty. */
538 static char pty_name
[24];
540 /* Open an available pty, returning a file descriptor.
541 Return -1 on failure.
542 The file name of the terminal corresponding to the pty
543 is left in the variable pty_name. */
554 for (c
= FIRST_PTY_LETTER
; c
<= 'z'; c
++)
555 for (i
= 0; i
< 16; i
++)
558 #ifdef PTY_NAME_SPRINTF
561 sprintf (pty_name
, "/dev/pty%c%x", c
, i
);
562 #endif /* no PTY_NAME_SPRINTF */
566 #else /* no PTY_OPEN */
568 { /* Some systems name their pseudoterminals so that there are gaps in
569 the usual sequence - for example, on HP9000/S700 systems, there
570 are no pseudoterminals with names ending in 'f'. So we wait for
571 three failures in a row before deciding that we've reached the
573 int failed_count
= 0;
576 if (stat (pty_name
, &stb
) < 0)
579 if (failed_count
>= 3)
586 fd
= emacs_open (pty_name
, O_RDWR
| O_NONBLOCK
, 0);
588 fd
= emacs_open (pty_name
, O_RDWR
| O_NDELAY
, 0);
591 #endif /* no PTY_OPEN */
595 /* check to make certain that both sides are available
596 this avoids a nasty yet stupid bug in rlogins */
597 #ifdef PTY_TTY_NAME_SPRINTF
600 sprintf (pty_name
, "/dev/tty%c%x", c
, i
);
601 #endif /* no PTY_TTY_NAME_SPRINTF */
602 if (access (pty_name
, 6) != 0)
617 #endif /* HAVE_PTYS */
620 make_process (Lisp_Object name
)
622 register Lisp_Object val
, tem
, name1
;
623 register struct Lisp_Process
*p
;
624 char suffix
[sizeof "<>" + INT_STRLEN_BOUND (printmax_t
)];
627 p
= allocate_process ();
628 /* Initialize Lisp data. Note that allocate_process initializes all
629 Lisp data to nil, so do it only for slots which should not be nil. */
631 p
->mark
= Fmake_marker ();
633 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
634 non-Lisp data, so do it only for slots which should not be zero. */
639 p
->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
642 /* If name is already in use, modify it until it is unused. */
647 tem
= Fget_process (name1
);
648 if (NILP (tem
)) break;
649 sprintf (suffix
, "<%"pMd
">", i
);
650 name1
= concat2 (name
, build_string (suffix
));
654 XSETPROCESS (val
, p
);
655 Vprocess_alist
= Fcons (Fcons (name
, val
), Vprocess_alist
);
660 remove_process (register Lisp_Object proc
)
662 register Lisp_Object pair
;
664 pair
= Frassq (proc
, Vprocess_alist
);
665 Vprocess_alist
= Fdelq (pair
, Vprocess_alist
);
667 deactivate_process (proc
);
671 DEFUN ("processp", Fprocessp
, Sprocessp
, 1, 1, 0,
672 doc
: /* Return t if OBJECT is a process. */)
675 return PROCESSP (object
) ? Qt
: Qnil
;
678 DEFUN ("get-process", Fget_process
, Sget_process
, 1, 1, 0,
679 doc
: /* Return the process named NAME, or nil if there is none. */)
680 (register Lisp_Object name
)
685 return Fcdr (Fassoc (name
, Vprocess_alist
));
688 /* This is how commands for the user decode process arguments. It
689 accepts a process, a process name, a buffer, a buffer name, or nil.
690 Buffers denote the first process in the buffer, and nil denotes the
694 get_process (register Lisp_Object name
)
696 register Lisp_Object proc
, obj
;
699 obj
= Fget_process (name
);
701 obj
= Fget_buffer (name
);
703 error ("Process %s does not exist", SDATA (name
));
705 else if (NILP (name
))
706 obj
= Fcurrent_buffer ();
710 /* Now obj should be either a buffer object or a process object.
714 proc
= Fget_buffer_process (obj
);
716 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj
), name
)));
728 /* Fdelete_process promises to immediately forget about the process, but in
729 reality, Emacs needs to remember those processes until they have been
730 treated by sigchld_handler; otherwise this handler would consider the
731 process as being synchronous and say that the synchronous process is
733 static Lisp_Object deleted_pid_list
;
736 DEFUN ("delete-process", Fdelete_process
, Sdelete_process
, 1, 1, 0,
737 doc
: /* Delete PROCESS: kill it and forget about it immediately.
738 PROCESS may be a process, a buffer, the name of a process or buffer, or
739 nil, indicating the current buffer's process. */)
740 (register Lisp_Object process
)
742 register struct Lisp_Process
*p
;
744 process
= get_process (process
);
745 p
= XPROCESS (process
);
747 p
->raw_status_new
= 0;
748 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
750 p
->status
= Fcons (Qexit
, Fcons (make_number (0), Qnil
));
751 p
->tick
= ++process_tick
;
753 redisplay_preserve_echo_area (13);
755 else if (p
->infd
>= 0)
761 /* No problem storing the pid here, as it is still in Vprocess_alist. */
762 deleted_pid_list
= Fcons (make_fixnum_or_float (pid
),
763 /* GC treated elements set to nil. */
764 Fdelq (Qnil
, deleted_pid_list
));
765 /* If the process has already signaled, remove it from the list. */
766 if (p
->raw_status_new
)
769 if (CONSP (p
->status
))
770 symbol
= XCAR (p
->status
);
771 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
))
773 = Fdelete (make_fixnum_or_float (pid
), deleted_pid_list
);
777 Fkill_process (process
, Qnil
);
778 /* Do this now, since remove_process will make sigchld_handler do nothing. */
780 = Fcons (Qsignal
, Fcons (make_number (SIGKILL
), Qnil
));
781 p
->tick
= ++process_tick
;
783 redisplay_preserve_echo_area (13);
786 remove_process (process
);
790 DEFUN ("process-status", Fprocess_status
, Sprocess_status
, 1, 1, 0,
791 doc
: /* Return the status of PROCESS.
792 The returned value is one of the following symbols:
793 run -- for a process that is running.
794 stop -- for a process stopped but continuable.
795 exit -- for a process that has exited.
796 signal -- for a process that has got a fatal signal.
797 open -- for a network stream connection that is open.
798 listen -- for a network stream server that is listening.
799 closed -- for a network stream connection that is closed.
800 connect -- when waiting for a non-blocking connection to complete.
801 failed -- when a non-blocking connection has failed.
802 nil -- if arg is a process name and no such process exists.
803 PROCESS may be a process, a buffer, the name of a process, or
804 nil, indicating the current buffer's process. */)
805 (register Lisp_Object process
)
807 register struct Lisp_Process
*p
;
808 register Lisp_Object status
;
810 if (STRINGP (process
))
811 process
= Fget_process (process
);
813 process
= get_process (process
);
818 p
= XPROCESS (process
);
819 if (p
->raw_status_new
)
823 status
= XCAR (status
);
824 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
826 if (EQ (status
, Qexit
))
828 else if (EQ (p
->command
, Qt
))
830 else if (EQ (status
, Qrun
))
836 DEFUN ("process-exit-status", Fprocess_exit_status
, Sprocess_exit_status
,
838 doc
: /* Return the exit status of PROCESS or the signal number that killed it.
839 If PROCESS has not yet exited or died, return 0. */)
840 (register Lisp_Object process
)
842 CHECK_PROCESS (process
);
843 if (XPROCESS (process
)->raw_status_new
)
844 update_status (XPROCESS (process
));
845 if (CONSP (XPROCESS (process
)->status
))
846 return XCAR (XCDR (XPROCESS (process
)->status
));
847 return make_number (0);
850 DEFUN ("process-id", Fprocess_id
, Sprocess_id
, 1, 1, 0,
851 doc
: /* Return the process id of PROCESS.
852 This is the pid of the external process which PROCESS uses or talks to.
853 For a network connection, this value is nil. */)
854 (register Lisp_Object process
)
858 CHECK_PROCESS (process
);
859 pid
= XPROCESS (process
)->pid
;
860 return (pid
? make_fixnum_or_float (pid
) : Qnil
);
863 DEFUN ("process-name", Fprocess_name
, Sprocess_name
, 1, 1, 0,
864 doc
: /* Return the name of PROCESS, as a string.
865 This is the name of the program invoked in PROCESS,
866 possibly modified to make it unique among process names. */)
867 (register Lisp_Object process
)
869 CHECK_PROCESS (process
);
870 return XPROCESS (process
)->name
;
873 DEFUN ("process-command", Fprocess_command
, Sprocess_command
, 1, 1, 0,
874 doc
: /* Return the command that was executed to start PROCESS.
875 This is a list of strings, the first string being the program executed
876 and the rest of the strings being the arguments given to it.
877 For a network or serial process, this is nil (process is running) or t
878 \(process is stopped). */)
879 (register Lisp_Object process
)
881 CHECK_PROCESS (process
);
882 return XPROCESS (process
)->command
;
885 DEFUN ("process-tty-name", Fprocess_tty_name
, Sprocess_tty_name
, 1, 1, 0,
886 doc
: /* Return the name of the terminal PROCESS uses, or nil if none.
887 This is the terminal that the process itself reads and writes on,
888 not the name of the pty that Emacs uses to talk with that terminal. */)
889 (register Lisp_Object process
)
891 CHECK_PROCESS (process
);
892 return XPROCESS (process
)->tty_name
;
895 DEFUN ("set-process-buffer", Fset_process_buffer
, Sset_process_buffer
,
897 doc
: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
899 (register Lisp_Object process
, Lisp_Object buffer
)
901 struct Lisp_Process
*p
;
903 CHECK_PROCESS (process
);
905 CHECK_BUFFER (buffer
);
906 p
= XPROCESS (process
);
908 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
909 p
->childp
= Fplist_put (p
->childp
, QCbuffer
, buffer
);
910 setup_process_coding_systems (process
);
914 DEFUN ("process-buffer", Fprocess_buffer
, Sprocess_buffer
,
916 doc
: /* Return the buffer PROCESS is associated with.
917 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
918 (register Lisp_Object process
)
920 CHECK_PROCESS (process
);
921 return XPROCESS (process
)->buffer
;
924 DEFUN ("process-mark", Fprocess_mark
, Sprocess_mark
,
926 doc
: /* Return the marker for the end of the last output from PROCESS. */)
927 (register Lisp_Object process
)
929 CHECK_PROCESS (process
);
930 return XPROCESS (process
)->mark
;
933 DEFUN ("set-process-filter", Fset_process_filter
, Sset_process_filter
,
935 doc
: /* Give PROCESS the filter function FILTER; nil means no filter.
936 A value of t means stop accepting output from the process.
938 When a process has a filter, its buffer is not used for output.
939 Instead, each time it does output, the entire string of output is
940 passed to the filter.
942 The filter gets two arguments: the process and the string of output.
943 The string argument is normally a multibyte string, except:
944 - if the process' input coding system is no-conversion or raw-text,
945 it is a unibyte string (the non-converted input), or else
946 - if `default-enable-multibyte-characters' is nil, it is a unibyte
947 string (the result of converting the decoded input multibyte
948 string to unibyte with `string-make-unibyte'). */)
949 (register Lisp_Object process
, Lisp_Object filter
)
951 struct Lisp_Process
*p
;
953 CHECK_PROCESS (process
);
954 p
= XPROCESS (process
);
956 /* Don't signal an error if the process' input file descriptor
957 is closed. This could make debugging Lisp more difficult,
958 for example when doing something like
960 (setq process (start-process ...))
962 (set-process-filter process ...) */
966 if (EQ (filter
, Qt
) && !EQ (p
->status
, Qlisten
))
968 FD_CLR (p
->infd
, &input_wait_mask
);
969 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
971 else if (EQ (p
->filter
, Qt
)
972 /* Network or serial process not stopped: */
973 && !EQ (p
->command
, Qt
))
975 FD_SET (p
->infd
, &input_wait_mask
);
976 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
981 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
982 p
->childp
= Fplist_put (p
->childp
, QCfilter
, filter
);
983 setup_process_coding_systems (process
);
987 DEFUN ("process-filter", Fprocess_filter
, Sprocess_filter
,
989 doc
: /* Returns the filter function of PROCESS; nil if none.
990 See `set-process-filter' for more info on filter functions. */)
991 (register Lisp_Object process
)
993 CHECK_PROCESS (process
);
994 return XPROCESS (process
)->filter
;
997 DEFUN ("set-process-sentinel", Fset_process_sentinel
, Sset_process_sentinel
,
999 doc
: /* Give PROCESS the sentinel SENTINEL; nil for none.
1000 The sentinel is called as a function when the process changes state.
1001 It gets two arguments: the process, and a string describing the change. */)
1002 (register Lisp_Object process
, Lisp_Object sentinel
)
1004 struct Lisp_Process
*p
;
1006 CHECK_PROCESS (process
);
1007 p
= XPROCESS (process
);
1009 p
->sentinel
= sentinel
;
1010 if (NETCONN1_P (p
) || SERIALCONN1_P (p
))
1011 p
->childp
= Fplist_put (p
->childp
, QCsentinel
, sentinel
);
1015 DEFUN ("process-sentinel", Fprocess_sentinel
, Sprocess_sentinel
,
1017 doc
: /* Return the sentinel of PROCESS; nil if none.
1018 See `set-process-sentinel' for more info on sentinels. */)
1019 (register Lisp_Object process
)
1021 CHECK_PROCESS (process
);
1022 return XPROCESS (process
)->sentinel
;
1025 DEFUN ("set-process-window-size", Fset_process_window_size
,
1026 Sset_process_window_size
, 3, 3, 0,
1027 doc
: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1028 (register Lisp_Object process
, Lisp_Object height
, Lisp_Object width
)
1030 CHECK_PROCESS (process
);
1031 CHECK_RANGED_INTEGER (height
, 0, INT_MAX
);
1032 CHECK_RANGED_INTEGER (width
, 0, INT_MAX
);
1034 if (XPROCESS (process
)->infd
< 0
1035 || set_window_size (XPROCESS (process
)->infd
,
1036 XINT (height
), XINT (width
)) <= 0)
1042 DEFUN ("set-process-inherit-coding-system-flag",
1043 Fset_process_inherit_coding_system_flag
,
1044 Sset_process_inherit_coding_system_flag
, 2, 2, 0,
1045 doc
: /* Determine whether buffer of PROCESS will inherit coding-system.
1046 If the second argument FLAG is non-nil, then the variable
1047 `buffer-file-coding-system' of the buffer associated with PROCESS
1048 will be bound to the value of the coding system used to decode
1051 This is useful when the coding system specified for the process buffer
1052 leaves either the character code conversion or the end-of-line conversion
1053 unspecified, or if the coding system used to decode the process output
1054 is more appropriate for saving the process buffer.
1056 Binding the variable `inherit-process-coding-system' to non-nil before
1057 starting the process is an alternative way of setting the inherit flag
1058 for the process which will run.
1060 This function returns FLAG. */)
1061 (register Lisp_Object process
, Lisp_Object flag
)
1063 CHECK_PROCESS (process
);
1064 XPROCESS (process
)->inherit_coding_system_flag
= !NILP (flag
);
1068 DEFUN ("set-process-query-on-exit-flag",
1069 Fset_process_query_on_exit_flag
, Sset_process_query_on_exit_flag
,
1071 doc
: /* Specify if query is needed for PROCESS when Emacs is exited.
1072 If the second argument FLAG is non-nil, Emacs will query the user before
1073 exiting or killing a buffer if PROCESS is running. This function
1075 (register Lisp_Object process
, Lisp_Object flag
)
1077 CHECK_PROCESS (process
);
1078 XPROCESS (process
)->kill_without_query
= NILP (flag
);
1082 DEFUN ("process-query-on-exit-flag",
1083 Fprocess_query_on_exit_flag
, Sprocess_query_on_exit_flag
,
1085 doc
: /* Return the current value of query-on-exit flag for PROCESS. */)
1086 (register Lisp_Object process
)
1088 CHECK_PROCESS (process
);
1089 return (XPROCESS (process
)->kill_without_query
? Qnil
: Qt
);
1092 #ifdef DATAGRAM_SOCKETS
1093 static Lisp_Object
Fprocess_datagram_address (Lisp_Object
);
1096 DEFUN ("process-contact", Fprocess_contact
, Sprocess_contact
,
1098 doc
: /* Return the contact info of PROCESS; t for a real child.
1099 For a network or serial connection, the value depends on the optional
1100 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1101 SERVICE) for a network connection or (PORT SPEED) for a serial
1102 connection. If KEY is t, the complete contact information for the
1103 connection is returned, else the specific value for the keyword KEY is
1104 returned. See `make-network-process' or `make-serial-process' for a
1105 list of keywords. */)
1106 (register Lisp_Object process
, Lisp_Object key
)
1108 Lisp_Object contact
;
1110 CHECK_PROCESS (process
);
1111 contact
= XPROCESS (process
)->childp
;
1113 #ifdef DATAGRAM_SOCKETS
1114 if (DATAGRAM_CONN_P (process
)
1115 && (EQ (key
, Qt
) || EQ (key
, QCremote
)))
1116 contact
= Fplist_put (contact
, QCremote
,
1117 Fprocess_datagram_address (process
));
1120 if ((!NETCONN_P (process
) && !SERIALCONN_P (process
)) || EQ (key
, Qt
))
1122 if (NILP (key
) && NETCONN_P (process
))
1123 return Fcons (Fplist_get (contact
, QChost
),
1124 Fcons (Fplist_get (contact
, QCservice
), Qnil
));
1125 if (NILP (key
) && SERIALCONN_P (process
))
1126 return Fcons (Fplist_get (contact
, QCport
),
1127 Fcons (Fplist_get (contact
, QCspeed
), Qnil
));
1128 return Fplist_get (contact
, key
);
1131 DEFUN ("process-plist", Fprocess_plist
, Sprocess_plist
,
1133 doc
: /* Return the plist of PROCESS. */)
1134 (register Lisp_Object process
)
1136 CHECK_PROCESS (process
);
1137 return XPROCESS (process
)->plist
;
1140 DEFUN ("set-process-plist", Fset_process_plist
, Sset_process_plist
,
1142 doc
: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1143 (register Lisp_Object process
, Lisp_Object plist
)
1145 CHECK_PROCESS (process
);
1148 XPROCESS (process
)->plist
= plist
;
1152 #if 0 /* Turned off because we don't currently record this info
1153 in the process. Perhaps add it. */
1154 DEFUN ("process-connection", Fprocess_connection
, Sprocess_connection
, 1, 1, 0,
1155 doc
: /* Return the connection type of PROCESS.
1156 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1157 a socket connection. */)
1158 (Lisp_Object process
)
1160 return XPROCESS (process
)->type
;
1164 DEFUN ("process-type", Fprocess_type
, Sprocess_type
, 1, 1, 0,
1165 doc
: /* Return the connection type of PROCESS.
1166 The value is either the symbol `real', `network', or `serial'.
1167 PROCESS may be a process, a buffer, the name of a process or buffer, or
1168 nil, indicating the current buffer's process. */)
1169 (Lisp_Object process
)
1172 proc
= get_process (process
);
1173 return XPROCESS (proc
)->type
;
1176 DEFUN ("format-network-address", Fformat_network_address
, Sformat_network_address
,
1178 doc
: /* Convert network ADDRESS from internal format to a string.
1179 A 4 or 5 element vector represents an IPv4 address (with port number).
1180 An 8 or 9 element vector represents an IPv6 address (with port number).
1181 If optional second argument OMIT-PORT is non-nil, don't include a port
1182 number in the string, even when present in ADDRESS.
1183 Returns nil if format of ADDRESS is invalid. */)
1184 (Lisp_Object address
, Lisp_Object omit_port
)
1189 if (STRINGP (address
)) /* AF_LOCAL */
1192 if (VECTORP (address
)) /* AF_INET or AF_INET6 */
1194 register struct Lisp_Vector
*p
= XVECTOR (address
);
1195 ptrdiff_t size
= p
->header
.size
;
1196 Lisp_Object args
[10];
1199 if (size
== 4 || (size
== 5 && !NILP (omit_port
)))
1201 args
[0] = build_string ("%d.%d.%d.%d");
1206 args
[0] = build_string ("%d.%d.%d.%d:%d");
1209 else if (size
== 8 || (size
== 9 && !NILP (omit_port
)))
1211 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1216 args
[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1222 for (i
= 0; i
< nargs
; i
++)
1224 if (! RANGED_INTEGERP (0, p
->contents
[i
], 65535))
1227 if (nargs
<= 5 /* IPv4 */
1228 && i
< 4 /* host, not port */
1229 && XINT (p
->contents
[i
]) > 255)
1232 args
[i
+1] = p
->contents
[i
];
1235 return Fformat (nargs
+1, args
);
1238 if (CONSP (address
))
1240 Lisp_Object args
[2];
1241 args
[0] = build_string ("<Family %d>");
1242 args
[1] = Fcar (address
);
1243 return Fformat (2, args
);
1249 DEFUN ("process-list", Fprocess_list
, Sprocess_list
, 0, 0, 0,
1250 doc
: /* Return a list of all processes. */)
1253 return Fmapcar (Qcdr
, Vprocess_alist
);
1256 /* Starting asynchronous inferior processes. */
1258 static Lisp_Object
start_process_unwind (Lisp_Object proc
);
1260 DEFUN ("start-process", Fstart_process
, Sstart_process
, 3, MANY
, 0,
1261 doc
: /* Start a program in a subprocess. Return the process object for it.
1262 NAME is name for process. It is modified if necessary to make it unique.
1263 BUFFER is the buffer (or buffer name) to associate with the process.
1265 Process output (both standard output and standard error streams) goes
1266 at end of BUFFER, unless you specify an output stream or filter
1267 function to handle the output. BUFFER may also be nil, meaning that
1268 this process is not associated with any buffer.
1270 PROGRAM is the program file name. It is searched for in `exec-path'
1271 (which see). If nil, just associate a pty with the buffer. Remaining
1272 arguments are strings to give program as arguments.
1274 If you want to separate standard output from standard error, invoke
1275 the command through a shell and redirect one of them using the shell
1278 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1279 (ptrdiff_t nargs
, Lisp_Object
*args
)
1281 Lisp_Object buffer
, name
, program
, proc
, current_dir
, tem
;
1282 register unsigned char **new_argv
;
1284 ptrdiff_t count
= SPECPDL_INDEX ();
1288 buffer
= Fget_buffer_create (buffer
);
1290 /* Make sure that the child will be able to chdir to the current
1291 buffer's current directory, or its unhandled equivalent. We
1292 can't just have the child check for an error when it does the
1293 chdir, since it's in a vfork.
1295 We have to GCPRO around this because Fexpand_file_name and
1296 Funhandled_file_name_directory might call a file name handling
1297 function. The argument list is protected by the caller, so all
1298 we really have to worry about is buffer. */
1300 struct gcpro gcpro1
, gcpro2
;
1302 current_dir
= BVAR (current_buffer
, directory
);
1304 GCPRO2 (buffer
, current_dir
);
1306 current_dir
= Funhandled_file_name_directory (current_dir
);
1307 if (NILP (current_dir
))
1308 /* If the file name handler says that current_dir is unreachable, use
1309 a sensible default. */
1310 current_dir
= build_string ("~/");
1311 current_dir
= expand_and_dir_to_file (current_dir
, Qnil
);
1312 if (NILP (Ffile_accessible_directory_p (current_dir
)))
1313 report_file_error ("Setting current directory",
1314 Fcons (BVAR (current_buffer
, directory
), Qnil
));
1320 CHECK_STRING (name
);
1324 if (!NILP (program
))
1325 CHECK_STRING (program
);
1327 proc
= make_process (name
);
1328 /* If an error occurs and we can't start the process, we want to
1329 remove it from the process list. This means that each error
1330 check in create_process doesn't need to call remove_process
1331 itself; it's all taken care of here. */
1332 record_unwind_protect (start_process_unwind
, proc
);
1334 XPROCESS (proc
)->childp
= Qt
;
1335 XPROCESS (proc
)->plist
= Qnil
;
1336 XPROCESS (proc
)->type
= Qreal
;
1337 XPROCESS (proc
)->buffer
= buffer
;
1338 XPROCESS (proc
)->sentinel
= Qnil
;
1339 XPROCESS (proc
)->filter
= Qnil
;
1340 XPROCESS (proc
)->command
= Flist (nargs
- 2, args
+ 2);
1343 /* AKA GNUTLS_INITSTAGE(proc). */
1344 XPROCESS (proc
)->gnutls_initstage
= GNUTLS_STAGE_EMPTY
;
1345 XPROCESS (proc
)->gnutls_cred_type
= Qnil
;
1348 #ifdef ADAPTIVE_READ_BUFFERING
1349 XPROCESS (proc
)->adaptive_read_buffering
1350 = (NILP (Vprocess_adaptive_read_buffering
) ? 0
1351 : EQ (Vprocess_adaptive_read_buffering
, Qt
) ? 1 : 2);
1354 /* Make the process marker point into the process buffer (if any). */
1355 if (BUFFERP (buffer
))
1356 set_marker_both (XPROCESS (proc
)->mark
, buffer
,
1357 BUF_ZV (XBUFFER (buffer
)),
1358 BUF_ZV_BYTE (XBUFFER (buffer
)));
1361 /* Decide coding systems for communicating with the process. Here
1362 we don't setup the structure coding_system nor pay attention to
1363 unibyte mode. They are done in create_process. */
1365 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1366 Lisp_Object coding_systems
= Qt
;
1367 Lisp_Object val
, *args2
;
1368 struct gcpro gcpro1
, gcpro2
;
1370 val
= Vcoding_system_for_read
;
1373 args2
= (Lisp_Object
*) alloca ((nargs
+ 1) * sizeof *args2
);
1374 args2
[0] = Qstart_process
;
1375 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1376 GCPRO2 (proc
, current_dir
);
1377 if (!NILP (program
))
1378 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1380 if (CONSP (coding_systems
))
1381 val
= XCAR (coding_systems
);
1382 else if (CONSP (Vdefault_process_coding_system
))
1383 val
= XCAR (Vdefault_process_coding_system
);
1385 XPROCESS (proc
)->decode_coding_system
= val
;
1387 val
= Vcoding_system_for_write
;
1390 if (EQ (coding_systems
, Qt
))
1392 args2
= (Lisp_Object
*) alloca ((nargs
+ 1) * sizeof *args2
);
1393 args2
[0] = Qstart_process
;
1394 for (i
= 0; i
< nargs
; i
++) args2
[i
+ 1] = args
[i
];
1395 GCPRO2 (proc
, current_dir
);
1396 if (!NILP (program
))
1397 coding_systems
= Ffind_operation_coding_system (nargs
+ 1, args2
);
1400 if (CONSP (coding_systems
))
1401 val
= XCDR (coding_systems
);
1402 else if (CONSP (Vdefault_process_coding_system
))
1403 val
= XCDR (Vdefault_process_coding_system
);
1405 XPROCESS (proc
)->encode_coding_system
= val
;
1406 /* Note: At this moment, the above coding system may leave
1407 text-conversion or eol-conversion unspecified. They will be
1408 decided after we read output from the process and decode it by
1409 some coding system, or just before we actually send a text to
1414 XPROCESS (proc
)->decoding_buf
= empty_unibyte_string
;
1415 XPROCESS (proc
)->decoding_carryover
= 0;
1416 XPROCESS (proc
)->encoding_buf
= empty_unibyte_string
;
1418 XPROCESS (proc
)->inherit_coding_system_flag
1419 = !(NILP (buffer
) || !inherit_process_coding_system
);
1421 if (!NILP (program
))
1423 /* If program file name is not absolute, search our path for it.
1424 Put the name we will really use in TEM. */
1425 if (!IS_DIRECTORY_SEP (SREF (program
, 0))
1426 && !(SCHARS (program
) > 1
1427 && IS_DEVICE_SEP (SREF (program
, 1))))
1429 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1432 GCPRO4 (name
, program
, buffer
, current_dir
);
1433 openp (Vexec_path
, program
, Vexec_suffixes
, &tem
, make_number (X_OK
));
1436 report_file_error ("Searching for program", Fcons (program
, Qnil
));
1437 tem
= Fexpand_file_name (tem
, Qnil
);
1441 if (!NILP (Ffile_directory_p (program
)))
1442 error ("Specified program for new process is a directory");
1446 /* If program file name starts with /: for quoting a magic name,
1448 if (SBYTES (tem
) > 2 && SREF (tem
, 0) == '/'
1449 && SREF (tem
, 1) == ':')
1450 tem
= Fsubstring (tem
, make_number (2), Qnil
);
1453 Lisp_Object arg_encoding
= Qnil
;
1454 struct gcpro gcpro1
;
1457 /* Encode the file name and put it in NEW_ARGV.
1458 That's where the child will use it to execute the program. */
1459 tem
= Fcons (ENCODE_FILE (tem
), Qnil
);
1461 /* Here we encode arguments by the coding system used for sending
1462 data to the process. We don't support using different coding
1463 systems for encoding arguments and for encoding data sent to the
1466 for (i
= 3; i
< nargs
; i
++)
1468 tem
= Fcons (args
[i
], tem
);
1469 CHECK_STRING (XCAR (tem
));
1470 if (STRING_MULTIBYTE (XCAR (tem
)))
1472 if (NILP (arg_encoding
))
1473 arg_encoding
= (complement_process_encoding_system
1474 (XPROCESS (proc
)->encode_coding_system
));
1476 code_convert_string_norecord
1477 (XCAR (tem
), arg_encoding
, 1));
1484 /* Now that everything is encoded we can collect the strings into
1486 new_argv
= (unsigned char **) alloca ((nargs
- 1) * sizeof (char *));
1487 new_argv
[nargs
- 2] = 0;
1489 for (i
= nargs
- 2; i
-- != 0; )
1491 new_argv
[i
] = SDATA (XCAR (tem
));
1495 create_process (proc
, (char **) new_argv
, current_dir
);
1500 return unbind_to (count
, proc
);
1503 /* This function is the unwind_protect form for Fstart_process. If
1504 PROC doesn't have its pid set, then we know someone has signaled
1505 an error and the process wasn't started successfully, so we should
1506 remove it from the process list. */
1508 start_process_unwind (Lisp_Object proc
)
1510 if (!PROCESSP (proc
))
1513 /* Was PROC started successfully?
1514 -2 is used for a pty with no process, eg for gdb. */
1515 if (XPROCESS (proc
)->pid
<= 0 && XPROCESS (proc
)->pid
!= -2)
1516 remove_process (proc
);
1522 create_process_1 (struct atimer
*timer
)
1524 /* Nothing to do. */
1529 create_process (Lisp_Object process
, char **new_argv
, Lisp_Object current_dir
)
1531 int inchannel
, outchannel
;
1534 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1535 int wait_child_setup
[2];
1539 struct sigaction sigint_action
;
1540 struct sigaction sigquit_action
;
1541 struct sigaction sigpipe_action
;
1543 struct sigaction sighup_action
;
1545 /* Use volatile to protect variables from being clobbered by longjmp. */
1546 volatile int forkin
, forkout
;
1547 volatile int pty_flag
= 0;
1549 extern char **environ
;
1552 inchannel
= outchannel
= -1;
1555 if (!NILP (Vprocess_connection_type
))
1556 outchannel
= inchannel
= allocate_pty ();
1560 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1561 /* On most USG systems it does not work to open the pty's tty here,
1562 then close it and reopen it in the child. */
1564 /* Don't let this terminal become our controlling terminal
1565 (in case we don't have one). */
1566 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1568 forkout
= forkin
= emacs_open (pty_name
, O_RDWR
, 0);
1571 report_file_error ("Opening pty", Qnil
);
1573 forkin
= forkout
= -1;
1574 #endif /* not USG, or USG_SUBTTY_WORKS */
1578 #endif /* HAVE_PTYS */
1583 report_file_error ("Creating pipe", Qnil
);
1589 emacs_close (inchannel
);
1590 emacs_close (forkout
);
1591 report_file_error ("Creating pipe", Qnil
);
1597 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1601 tem
= pipe (wait_child_setup
);
1603 report_file_error ("Creating pipe", Qnil
);
1604 tem
= fcntl (wait_child_setup
[1], F_GETFD
, 0);
1606 tem
= fcntl (wait_child_setup
[1], F_SETFD
, tem
| FD_CLOEXEC
);
1609 emacs_close (wait_child_setup
[0]);
1610 emacs_close (wait_child_setup
[1]);
1611 report_file_error ("Setting file descriptor flags", Qnil
);
1617 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1618 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1621 fcntl (inchannel
, F_SETFL
, O_NDELAY
);
1622 fcntl (outchannel
, F_SETFL
, O_NDELAY
);
1626 /* Record this as an active process, with its channels.
1627 As a result, child_setup will close Emacs's side of the pipes. */
1628 chan_process
[inchannel
] = process
;
1629 XPROCESS (process
)->infd
= inchannel
;
1630 XPROCESS (process
)->outfd
= outchannel
;
1632 /* Previously we recorded the tty descriptor used in the subprocess.
1633 It was only used for getting the foreground tty process, so now
1634 we just reopen the device (see emacs_get_tty_pgrp) as this is
1635 more portable (see USG_SUBTTY_WORKS above). */
1637 XPROCESS (process
)->pty_flag
= pty_flag
;
1638 XPROCESS (process
)->status
= Qrun
;
1640 /* Delay interrupts until we have a chance to store
1641 the new fork's pid in its process structure */
1642 sigemptyset (&blocked
);
1644 sigaddset (&blocked
, SIGCHLD
);
1646 #ifdef HAVE_WORKING_VFORK
1647 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1648 this sets the parent's signal handlers as well as the child's.
1649 So delay all interrupts whose handlers the child might munge,
1650 and record the current handlers so they can be restored later. */
1651 sigaddset (&blocked
, SIGINT
); sigaction (SIGINT
, 0, &sigint_action
);
1652 sigaddset (&blocked
, SIGQUIT
); sigaction (SIGQUIT
, 0, &sigquit_action
);
1653 sigaddset (&blocked
, SIGPIPE
); sigaction (SIGPIPE
, 0, &sigpipe_action
);
1655 sigaddset (&blocked
, SIGHUP
); sigaction (SIGHUP
, 0, &sighup_action
);
1657 #endif /* HAVE_WORKING_VFORK */
1658 pthread_sigmask (SIG_BLOCK
, &blocked
, &procmask
);
1660 FD_SET (inchannel
, &input_wait_mask
);
1661 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1662 if (inchannel
> max_process_desc
)
1663 max_process_desc
= inchannel
;
1665 /* Until we store the proper pid, enable sigchld_handler
1666 to recognize an unknown pid as standing for this process.
1667 It is very important not to let this `marker' value stay
1668 in the table after this function has returned; if it does
1669 it might cause call-process to hang and subsequent asynchronous
1670 processes to get their return values scrambled. */
1671 XPROCESS (process
)->pid
= -1;
1673 /* This must be called after the above line because it may signal an
1675 setup_process_coding_systems (process
);
1680 /* child_setup must clobber environ on systems with true vfork.
1681 Protect it from permanent change. */
1682 char **save_environ
= environ
;
1683 volatile Lisp_Object encoded_current_dir
= ENCODE_FILE (current_dir
);
1688 #endif /* not WINDOWSNT */
1690 int xforkin
= forkin
;
1691 int xforkout
= forkout
;
1693 #if 0 /* This was probably a mistake--it duplicates code later on,
1694 but fails to handle all the cases. */
1695 /* Make sure SIGCHLD is not blocked in the child. */
1696 sigsetmask (SIGEMPTYMASK
);
1699 /* Make the pty be the controlling terminal of the process. */
1701 /* First, disconnect its current controlling terminal. */
1703 /* We tried doing setsid only if pty_flag, but it caused
1704 process_set_signal to fail on SGI when using a pipe. */
1706 /* Make the pty's terminal the controlling terminal. */
1707 if (pty_flag
&& xforkin
>= 0)
1710 /* We ignore the return value
1711 because faith@cs.unc.edu says that is necessary on Linux. */
1712 ioctl (xforkin
, TIOCSCTTY
, 0);
1715 #else /* not HAVE_SETSID */
1717 /* It's very important to call setpgrp here and no time
1718 afterwards. Otherwise, we lose our controlling tty which
1719 is set when we open the pty. */
1722 #endif /* not HAVE_SETSID */
1723 #if defined (LDISC1)
1724 if (pty_flag
&& xforkin
>= 0)
1727 tcgetattr (xforkin
, &t
);
1729 if (tcsetattr (xforkin
, TCSANOW
, &t
) < 0)
1730 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1733 #if defined (NTTYDISC) && defined (TIOCSETD)
1734 if (pty_flag
&& xforkin
>= 0)
1736 /* Use new line discipline. */
1737 int ldisc
= NTTYDISC
;
1738 ioctl (xforkin
, TIOCSETD
, &ldisc
);
1743 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1744 can do TIOCSPGRP only to the process's controlling tty. */
1747 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1748 I can't test it since I don't have 4.3. */
1749 int j
= emacs_open ("/dev/tty", O_RDWR
, 0);
1752 ioctl (j
, TIOCNOTTY
, 0);
1756 /* In order to get a controlling terminal on some versions
1757 of BSD, it is necessary to put the process in pgrp 0
1758 before it opens the terminal. */
1766 #endif /* TIOCNOTTY */
1768 #if !defined (DONT_REOPEN_PTY)
1769 /*** There is a suggestion that this ought to be a
1770 conditional on TIOCSPGRP,
1771 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1772 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1773 that system does seem to need this code, even though
1774 both HAVE_SETSID and TIOCSCTTY are defined. */
1775 /* Now close the pty (if we had it open) and reopen it.
1776 This makes the pty the controlling terminal of the subprocess. */
1780 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1783 emacs_close (xforkin
);
1784 xforkout
= xforkin
= emacs_open (pty_name
, O_RDWR
, 0);
1788 emacs_write (1, "Couldn't open the pty terminal ", 31);
1789 emacs_write (1, pty_name
, strlen (pty_name
));
1790 emacs_write (1, "\n", 1);
1795 #endif /* not DONT_REOPEN_PTY */
1797 #ifdef SETUP_SLAVE_PTY
1802 #endif /* SETUP_SLAVE_PTY */
1804 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1805 Now reenable it in the child, so it will die when we want it to. */
1807 signal (SIGHUP
, SIG_DFL
);
1809 #endif /* HAVE_PTYS */
1811 signal (SIGINT
, SIG_DFL
);
1812 signal (SIGQUIT
, SIG_DFL
);
1813 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1815 signal (SIGPIPE
, SIG_DFL
);
1817 /* Stop blocking signals in the child. */
1818 pthread_sigmask (SIG_SETMASK
, &procmask
, 0);
1821 child_setup_tty (xforkout
);
1823 pid
= child_setup (xforkin
, xforkout
, xforkout
,
1824 new_argv
, 1, encoded_current_dir
);
1825 #else /* not WINDOWSNT */
1827 emacs_close (wait_child_setup
[0]);
1829 child_setup (xforkin
, xforkout
, xforkout
,
1830 new_argv
, 1, encoded_current_dir
);
1831 #endif /* not WINDOWSNT */
1833 environ
= save_environ
;
1838 /* This runs in the Emacs process. */
1842 emacs_close (forkin
);
1843 if (forkin
!= forkout
&& forkout
>= 0)
1844 emacs_close (forkout
);
1848 /* vfork succeeded. */
1849 XPROCESS (process
)->pid
= pid
;
1852 register_child (pid
, inchannel
);
1853 #endif /* WINDOWSNT */
1855 /* If the subfork execv fails, and it exits,
1856 this close hangs. I don't know why.
1857 So have an interrupt jar it loose. */
1859 struct atimer
*timer
;
1863 EMACS_SET_SECS_USECS (offset
, 1, 0);
1864 timer
= start_atimer (ATIMER_RELATIVE
, offset
, create_process_1
, 0);
1867 emacs_close (forkin
);
1869 cancel_atimer (timer
);
1873 if (forkin
!= forkout
&& forkout
>= 0)
1874 emacs_close (forkout
);
1878 XPROCESS (process
)->tty_name
= build_string (pty_name
);
1881 XPROCESS (process
)->tty_name
= Qnil
;
1883 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1884 /* Wait for child_setup to complete in case that vfork is
1885 actually defined as fork. The descriptor wait_child_setup[1]
1886 of a pipe is closed at the child side either by close-on-exec
1887 on successful execvp or the _exit call in child_setup. */
1891 emacs_close (wait_child_setup
[1]);
1892 emacs_read (wait_child_setup
[0], &dummy
, 1);
1893 emacs_close (wait_child_setup
[0]);
1898 /* Restore the signal state whether vfork succeeded or not.
1899 (We will signal an error, below, if it failed.) */
1900 #ifdef HAVE_WORKING_VFORK
1901 /* Restore the parent's signal handlers. */
1902 sigaction (SIGINT
, &sigint_action
, 0);
1903 sigaction (SIGQUIT
, &sigquit_action
, 0);
1904 sigaction (SIGPIPE
, &sigpipe_action
, 0);
1906 sigaction (SIGHUP
, &sighup_action
, 0);
1908 #endif /* HAVE_WORKING_VFORK */
1909 /* Stop blocking signals in the parent. */
1910 pthread_sigmask (SIG_SETMASK
, &procmask
, 0);
1912 /* Now generate the error if vfork failed. */
1914 report_file_error ("Doing vfork", Qnil
);
1918 create_pty (Lisp_Object process
)
1920 int inchannel
, outchannel
;
1923 inchannel
= outchannel
= -1;
1926 if (!NILP (Vprocess_connection_type
))
1927 outchannel
= inchannel
= allocate_pty ();
1931 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1932 /* On most USG systems it does not work to open the pty's tty here,
1933 then close it and reopen it in the child. */
1935 /* Don't let this terminal become our controlling terminal
1936 (in case we don't have one). */
1937 int forkout
= emacs_open (pty_name
, O_RDWR
| O_NOCTTY
, 0);
1939 int forkout
= emacs_open (pty_name
, O_RDWR
, 0);
1942 report_file_error ("Opening pty", Qnil
);
1943 #if defined (DONT_REOPEN_PTY)
1944 /* In the case that vfork is defined as fork, the parent process
1945 (Emacs) may send some data before the child process completes
1946 tty options setup. So we setup tty before forking. */
1947 child_setup_tty (forkout
);
1948 #endif /* DONT_REOPEN_PTY */
1949 #endif /* not USG, or USG_SUBTTY_WORKS */
1952 #endif /* HAVE_PTYS */
1955 fcntl (inchannel
, F_SETFL
, O_NONBLOCK
);
1956 fcntl (outchannel
, F_SETFL
, O_NONBLOCK
);
1959 fcntl (inchannel
, F_SETFL
, O_NDELAY
);
1960 fcntl (outchannel
, F_SETFL
, O_NDELAY
);
1964 /* Record this as an active process, with its channels.
1965 As a result, child_setup will close Emacs's side of the pipes. */
1966 chan_process
[inchannel
] = process
;
1967 XPROCESS (process
)->infd
= inchannel
;
1968 XPROCESS (process
)->outfd
= outchannel
;
1970 /* Previously we recorded the tty descriptor used in the subprocess.
1971 It was only used for getting the foreground tty process, so now
1972 we just reopen the device (see emacs_get_tty_pgrp) as this is
1973 more portable (see USG_SUBTTY_WORKS above). */
1975 XPROCESS (process
)->pty_flag
= pty_flag
;
1976 XPROCESS (process
)->status
= Qrun
;
1977 setup_process_coding_systems (process
);
1979 FD_SET (inchannel
, &input_wait_mask
);
1980 FD_SET (inchannel
, &non_keyboard_wait_mask
);
1981 if (inchannel
> max_process_desc
)
1982 max_process_desc
= inchannel
;
1984 XPROCESS (process
)->pid
= -2;
1987 XPROCESS (process
)->tty_name
= build_string (pty_name
);
1990 XPROCESS (process
)->tty_name
= Qnil
;
1994 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1995 The address family of sa is not included in the result. */
1998 conv_sockaddr_to_lisp (struct sockaddr
*sa
, int len
)
2000 Lisp_Object address
;
2003 register struct Lisp_Vector
*p
;
2005 /* Workaround for a bug in getsockname on BSD: Names bound to
2006 sockets in the UNIX domain are inaccessible; getsockname returns
2007 a zero length name. */
2008 if (len
< offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
))
2009 return empty_unibyte_string
;
2011 switch (sa
->sa_family
)
2015 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2016 len
= sizeof (sin
->sin_addr
) + 1;
2017 address
= Fmake_vector (make_number (len
), Qnil
);
2018 p
= XVECTOR (address
);
2019 p
->contents
[--len
] = make_number (ntohs (sin
->sin_port
));
2020 cp
= (unsigned char *) &sin
->sin_addr
;
2026 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2027 uint16_t *ip6
= (uint16_t *) &sin6
->sin6_addr
;
2028 len
= sizeof (sin6
->sin6_addr
)/2 + 1;
2029 address
= Fmake_vector (make_number (len
), Qnil
);
2030 p
= XVECTOR (address
);
2031 p
->contents
[--len
] = make_number (ntohs (sin6
->sin6_port
));
2032 for (i
= 0; i
< len
; i
++)
2033 p
->contents
[i
] = make_number (ntohs (ip6
[i
]));
2037 #ifdef HAVE_LOCAL_SOCKETS
2040 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2041 for (i
= 0; i
< sizeof (sockun
->sun_path
); i
++)
2042 if (sockun
->sun_path
[i
] == 0)
2044 return make_unibyte_string (sockun
->sun_path
, i
);
2048 len
-= offsetof (struct sockaddr
, sa_family
) + sizeof (sa
->sa_family
);
2049 address
= Fcons (make_number (sa
->sa_family
),
2050 Fmake_vector (make_number (len
), Qnil
));
2051 p
= XVECTOR (XCDR (address
));
2052 cp
= (unsigned char *) &sa
->sa_family
+ sizeof (sa
->sa_family
);
2058 p
->contents
[i
++] = make_number (*cp
++);
2064 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2067 get_lisp_to_sockaddr_size (Lisp_Object address
, int *familyp
)
2069 register struct Lisp_Vector
*p
;
2071 if (VECTORP (address
))
2073 p
= XVECTOR (address
);
2074 if (p
->header
.size
== 5)
2077 return sizeof (struct sockaddr_in
);
2080 else if (p
->header
.size
== 9)
2082 *familyp
= AF_INET6
;
2083 return sizeof (struct sockaddr_in6
);
2087 #ifdef HAVE_LOCAL_SOCKETS
2088 else if (STRINGP (address
))
2090 *familyp
= AF_LOCAL
;
2091 return sizeof (struct sockaddr_un
);
2094 else if (CONSP (address
) && TYPE_RANGED_INTEGERP (int, XCAR (address
))
2095 && VECTORP (XCDR (address
)))
2097 struct sockaddr
*sa
;
2098 *familyp
= XINT (XCAR (address
));
2099 p
= XVECTOR (XCDR (address
));
2100 return p
->header
.size
+ sizeof (sa
->sa_family
);
2105 /* Convert an address object (vector or string) to an internal sockaddr.
2107 The address format has been basically validated by
2108 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2109 it could have come from user data. So if FAMILY is not valid,
2110 we return after zeroing *SA. */
2113 conv_lisp_to_sockaddr (int family
, Lisp_Object address
, struct sockaddr
*sa
, int len
)
2115 register struct Lisp_Vector
*p
;
2116 register unsigned char *cp
= NULL
;
2120 memset (sa
, 0, len
);
2122 if (VECTORP (address
))
2124 p
= XVECTOR (address
);
2125 if (family
== AF_INET
)
2127 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
2128 len
= sizeof (sin
->sin_addr
) + 1;
2129 hostport
= XINT (p
->contents
[--len
]);
2130 sin
->sin_port
= htons (hostport
);
2131 cp
= (unsigned char *)&sin
->sin_addr
;
2132 sa
->sa_family
= family
;
2135 else if (family
== AF_INET6
)
2137 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
2138 uint16_t *ip6
= (uint16_t *)&sin6
->sin6_addr
;
2139 len
= sizeof (sin6
->sin6_addr
) + 1;
2140 hostport
= XINT (p
->contents
[--len
]);
2141 sin6
->sin6_port
= htons (hostport
);
2142 for (i
= 0; i
< len
; i
++)
2143 if (INTEGERP (p
->contents
[i
]))
2145 int j
= XFASTINT (p
->contents
[i
]) & 0xffff;
2148 sa
->sa_family
= family
;
2155 else if (STRINGP (address
))
2157 #ifdef HAVE_LOCAL_SOCKETS
2158 if (family
== AF_LOCAL
)
2160 struct sockaddr_un
*sockun
= (struct sockaddr_un
*) sa
;
2161 cp
= SDATA (address
);
2162 for (i
= 0; i
< sizeof (sockun
->sun_path
) && *cp
; i
++)
2163 sockun
->sun_path
[i
] = *cp
++;
2164 sa
->sa_family
= family
;
2171 p
= XVECTOR (XCDR (address
));
2172 cp
= (unsigned char *)sa
+ sizeof (sa
->sa_family
);
2175 for (i
= 0; i
< len
; i
++)
2176 if (INTEGERP (p
->contents
[i
]))
2177 *cp
++ = XFASTINT (p
->contents
[i
]) & 0xff;
2180 #ifdef DATAGRAM_SOCKETS
2181 DEFUN ("process-datagram-address", Fprocess_datagram_address
, Sprocess_datagram_address
,
2183 doc
: /* Get the current datagram address associated with PROCESS. */)
2184 (Lisp_Object process
)
2188 CHECK_PROCESS (process
);
2190 if (!DATAGRAM_CONN_P (process
))
2193 channel
= XPROCESS (process
)->infd
;
2194 return conv_sockaddr_to_lisp (datagram_address
[channel
].sa
,
2195 datagram_address
[channel
].len
);
2198 DEFUN ("set-process-datagram-address", Fset_process_datagram_address
, Sset_process_datagram_address
,
2200 doc
: /* Set the datagram address for PROCESS to ADDRESS.
2201 Returns nil upon error setting address, ADDRESS otherwise. */)
2202 (Lisp_Object process
, Lisp_Object address
)
2207 CHECK_PROCESS (process
);
2209 if (!DATAGRAM_CONN_P (process
))
2212 channel
= XPROCESS (process
)->infd
;
2214 len
= get_lisp_to_sockaddr_size (address
, &family
);
2215 if (datagram_address
[channel
].len
!= len
)
2217 conv_lisp_to_sockaddr (family
, address
, datagram_address
[channel
].sa
, len
);
2223 static const struct socket_options
{
2224 /* The name of this option. Should be lowercase version of option
2225 name without SO_ prefix. */
2227 /* Option level SOL_... */
2229 /* Option number SO_... */
2231 enum { SOPT_UNKNOWN
, SOPT_BOOL
, SOPT_INT
, SOPT_IFNAME
, SOPT_LINGER
} opttype
;
2232 enum { OPIX_NONE
=0, OPIX_MISC
=1, OPIX_REUSEADDR
=2 } optbit
;
2233 } socket_options
[] =
2235 #ifdef SO_BINDTODEVICE
2236 { ":bindtodevice", SOL_SOCKET
, SO_BINDTODEVICE
, SOPT_IFNAME
, OPIX_MISC
},
2239 { ":broadcast", SOL_SOCKET
, SO_BROADCAST
, SOPT_BOOL
, OPIX_MISC
},
2242 { ":dontroute", SOL_SOCKET
, SO_DONTROUTE
, SOPT_BOOL
, OPIX_MISC
},
2245 { ":keepalive", SOL_SOCKET
, SO_KEEPALIVE
, SOPT_BOOL
, OPIX_MISC
},
2248 { ":linger", SOL_SOCKET
, SO_LINGER
, SOPT_LINGER
, OPIX_MISC
},
2251 { ":oobinline", SOL_SOCKET
, SO_OOBINLINE
, SOPT_BOOL
, OPIX_MISC
},
2254 { ":priority", SOL_SOCKET
, SO_PRIORITY
, SOPT_INT
, OPIX_MISC
},
2257 { ":reuseaddr", SOL_SOCKET
, SO_REUSEADDR
, SOPT_BOOL
, OPIX_REUSEADDR
},
2259 { 0, 0, 0, SOPT_UNKNOWN
, OPIX_NONE
}
2262 /* Set option OPT to value VAL on socket S.
2264 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2265 Signals an error if setting a known option fails.
2269 set_socket_option (int s
, Lisp_Object opt
, Lisp_Object val
)
2272 const struct socket_options
*sopt
;
2277 name
= SSDATA (SYMBOL_NAME (opt
));
2278 for (sopt
= socket_options
; sopt
->name
; sopt
++)
2279 if (strcmp (name
, sopt
->name
) == 0)
2282 switch (sopt
->opttype
)
2287 optval
= NILP (val
) ? 0 : 1;
2288 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2289 &optval
, sizeof (optval
));
2296 if (TYPE_RANGED_INTEGERP (int, val
))
2297 optval
= XINT (val
);
2299 error ("Bad option value for %s", name
);
2300 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2301 &optval
, sizeof (optval
));
2305 #ifdef SO_BINDTODEVICE
2308 char devname
[IFNAMSIZ
+1];
2310 /* This is broken, at least in the Linux 2.4 kernel.
2311 To unbind, the arg must be a zero integer, not the empty string.
2312 This should work on all systems. KFS. 2003-09-23. */
2313 memset (devname
, 0, sizeof devname
);
2316 char *arg
= SSDATA (val
);
2317 int len
= min (strlen (arg
), IFNAMSIZ
);
2318 memcpy (devname
, arg
, len
);
2320 else if (!NILP (val
))
2321 error ("Bad option value for %s", name
);
2322 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2331 struct linger linger
;
2334 linger
.l_linger
= 0;
2335 if (TYPE_RANGED_INTEGERP (int, val
))
2336 linger
.l_linger
= XINT (val
);
2338 linger
.l_onoff
= NILP (val
) ? 0 : 1;
2339 ret
= setsockopt (s
, sopt
->optlevel
, sopt
->optnum
,
2340 &linger
, sizeof (linger
));
2350 report_file_error ("Cannot set network option",
2351 Fcons (opt
, Fcons (val
, Qnil
)));
2352 return (1 << sopt
->optbit
);
2356 DEFUN ("set-network-process-option",
2357 Fset_network_process_option
, Sset_network_process_option
,
2359 doc
: /* For network process PROCESS set option OPTION to value VALUE.
2360 See `make-network-process' for a list of options and values.
2361 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2362 OPTION is not a supported option, return nil instead; otherwise return t. */)
2363 (Lisp_Object process
, Lisp_Object option
, Lisp_Object value
, Lisp_Object no_error
)
2366 struct Lisp_Process
*p
;
2368 CHECK_PROCESS (process
);
2369 p
= XPROCESS (process
);
2370 if (!NETCONN1_P (p
))
2371 error ("Process is not a network process");
2375 error ("Process is not running");
2377 if (set_socket_option (s
, option
, value
))
2379 p
->childp
= Fplist_put (p
->childp
, option
, value
);
2383 if (NILP (no_error
))
2384 error ("Unknown or unsupported option");
2390 DEFUN ("serial-process-configure",
2391 Fserial_process_configure
,
2392 Sserial_process_configure
,
2394 doc
: /* Configure speed, bytesize, etc. of a serial process.
2396 Arguments are specified as keyword/argument pairs. Attributes that
2397 are not given are re-initialized from the process's current
2398 configuration (available via the function `process-contact') or set to
2399 reasonable default values. The following arguments are defined:
2405 -- Any of these arguments can be given to identify the process that is
2406 to be configured. If none of these arguments is given, the current
2407 buffer's process is used.
2409 :speed SPEED -- SPEED is the speed of the serial port in bits per
2410 second, also called baud rate. Any value can be given for SPEED, but
2411 most serial ports work only at a few defined values between 1200 and
2412 115200, with 9600 being the most common value. If SPEED is nil, the
2413 serial port is not configured any further, i.e., all other arguments
2414 are ignored. This may be useful for special serial ports such as
2415 Bluetooth-to-serial converters which can only be configured through AT
2416 commands. A value of nil for SPEED can be used only when passed
2417 through `make-serial-process' or `serial-term'.
2419 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2420 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2422 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2423 `odd' (use odd parity), or the symbol `even' (use even parity). If
2424 PARITY is not given, no parity is used.
2426 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2427 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2428 is not given or nil, 1 stopbit is used.
2430 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2431 flowcontrol to be used, which is either nil (don't use flowcontrol),
2432 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2433 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2434 flowcontrol is used.
2436 `serial-process-configure' is called by `make-serial-process' for the
2437 initial configuration of the serial port.
2441 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2443 \(serial-process-configure
2444 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2446 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2448 usage: (serial-process-configure &rest ARGS) */)
2449 (ptrdiff_t nargs
, Lisp_Object
*args
)
2451 struct Lisp_Process
*p
;
2452 Lisp_Object contact
= Qnil
;
2453 Lisp_Object proc
= Qnil
;
2454 struct gcpro gcpro1
;
2456 contact
= Flist (nargs
, args
);
2459 proc
= Fplist_get (contact
, QCprocess
);
2461 proc
= Fplist_get (contact
, QCname
);
2463 proc
= Fplist_get (contact
, QCbuffer
);
2465 proc
= Fplist_get (contact
, QCport
);
2466 proc
= get_process (proc
);
2467 p
= XPROCESS (proc
);
2468 if (!EQ (p
->type
, Qserial
))
2469 error ("Not a serial process");
2471 if (NILP (Fplist_get (p
->childp
, QCspeed
)))
2477 serial_configure (p
, contact
);
2483 /* Used by make-serial-process to recover from errors. */
2485 make_serial_process_unwind (Lisp_Object proc
)
2487 if (!PROCESSP (proc
))
2489 remove_process (proc
);
2493 DEFUN ("make-serial-process", Fmake_serial_process
, Smake_serial_process
,
2495 doc
: /* Create and return a serial port process.
2497 In Emacs, serial port connections are represented by process objects,
2498 so input and output work as for subprocesses, and `delete-process'
2499 closes a serial port connection. However, a serial process has no
2500 process id, it cannot be signaled, and the status codes are different
2501 from normal processes.
2503 `make-serial-process' creates a process and a buffer, on which you
2504 probably want to use `process-send-string'. Try \\[serial-term] for
2505 an interactive terminal. See below for examples.
2507 Arguments are specified as keyword/argument pairs. The following
2508 arguments are defined:
2510 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2511 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2512 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2513 the backslashes in strings).
2515 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2516 which this function calls.
2518 :name NAME -- NAME is the name of the process. If NAME is not given,
2519 the value of PORT is used.
2521 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2522 with the process. Process output goes at the end of that buffer,
2523 unless you specify an output stream or filter function to handle the
2524 output. If BUFFER is not given, the value of NAME is used.
2526 :coding CODING -- If CODING is a symbol, it specifies the coding
2527 system used for both reading and writing for this process. If CODING
2528 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2529 ENCODING is used for writing.
2531 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2532 the process is running. If BOOL is not given, query before exiting.
2534 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2535 In the stopped state, a serial process does not accept incoming data,
2536 but you can send outgoing data. The stopped state is cleared by
2537 `continue-process' and set by `stop-process'.
2539 :filter FILTER -- Install FILTER as the process filter.
2541 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2543 :plist PLIST -- Install PLIST as the initial plist of the process.
2549 -- This function calls `serial-process-configure' to handle these
2552 The original argument list, possibly modified by later configuration,
2553 is available via the function `process-contact'.
2557 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2559 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2561 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2563 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2565 usage: (make-serial-process &rest ARGS) */)
2566 (ptrdiff_t nargs
, Lisp_Object
*args
)
2569 Lisp_Object proc
, contact
, port
;
2570 struct Lisp_Process
*p
;
2571 struct gcpro gcpro1
;
2572 Lisp_Object name
, buffer
;
2573 Lisp_Object tem
, val
;
2574 ptrdiff_t specpdl_count
= -1;
2579 contact
= Flist (nargs
, args
);
2582 port
= Fplist_get (contact
, QCport
);
2584 error ("No port specified");
2585 CHECK_STRING (port
);
2587 if (NILP (Fplist_member (contact
, QCspeed
)))
2588 error (":speed not specified");
2589 if (!NILP (Fplist_get (contact
, QCspeed
)))
2590 CHECK_NUMBER (Fplist_get (contact
, QCspeed
));
2592 name
= Fplist_get (contact
, QCname
);
2595 CHECK_STRING (name
);
2596 proc
= make_process (name
);
2597 specpdl_count
= SPECPDL_INDEX ();
2598 record_unwind_protect (make_serial_process_unwind
, proc
);
2599 p
= XPROCESS (proc
);
2601 fd
= serial_open (SSDATA (port
));
2604 if (fd
> max_process_desc
)
2605 max_process_desc
= fd
;
2606 chan_process
[fd
] = proc
;
2608 buffer
= Fplist_get (contact
, QCbuffer
);
2611 buffer
= Fget_buffer_create (buffer
);
2614 p
->childp
= contact
;
2615 p
->plist
= Fcopy_sequence (Fplist_get (contact
, QCplist
));
2617 p
->sentinel
= Fplist_get (contact
, QCsentinel
);
2618 p
->filter
= Fplist_get (contact
, QCfilter
);
2620 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
2621 p
->kill_without_query
= 1;
2622 if (tem
= Fplist_get (contact
, QCstop
), !NILP (tem
))
2626 if (!EQ (p
->command
, Qt
))
2628 FD_SET (fd
, &input_wait_mask
);
2629 FD_SET (fd
, &non_keyboard_wait_mask
);
2632 if (BUFFERP (buffer
))
2634 set_marker_both (p
->mark
, buffer
,
2635 BUF_ZV (XBUFFER (buffer
)),
2636 BUF_ZV_BYTE (XBUFFER (buffer
)));
2639 tem
= Fplist_member (contact
, QCcoding
);
2640 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
2646 val
= XCAR (XCDR (tem
));
2650 else if (!NILP (Vcoding_system_for_read
))
2651 val
= Vcoding_system_for_read
;
2652 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2653 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2655 p
->decode_coding_system
= val
;
2660 val
= XCAR (XCDR (tem
));
2664 else if (!NILP (Vcoding_system_for_write
))
2665 val
= Vcoding_system_for_write
;
2666 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
2667 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
2669 p
->encode_coding_system
= val
;
2671 setup_process_coding_systems (proc
);
2672 p
->decoding_buf
= empty_unibyte_string
;
2673 p
->decoding_carryover
= 0;
2674 p
->encoding_buf
= empty_unibyte_string
;
2675 p
->inherit_coding_system_flag
2676 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
2678 Fserial_process_configure (nargs
, args
);
2680 specpdl_ptr
= specpdl
+ specpdl_count
;
2686 /* Create a network stream/datagram client/server process. Treated
2687 exactly like a normal process when reading and writing. Primary
2688 differences are in status display and process deletion. A network
2689 connection has no PID; you cannot signal it. All you can do is
2690 stop/continue it and deactivate/close it via delete-process */
2692 DEFUN ("make-network-process", Fmake_network_process
, Smake_network_process
,
2694 doc
: /* Create and return a network server or client process.
2696 In Emacs, network connections are represented by process objects, so
2697 input and output work as for subprocesses and `delete-process' closes
2698 a network connection. However, a network process has no process id,
2699 it cannot be signaled, and the status codes are different from normal
2702 Arguments are specified as keyword/argument pairs. The following
2703 arguments are defined:
2705 :name NAME -- NAME is name for process. It is modified if necessary
2708 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2709 with the process. Process output goes at end of that buffer, unless
2710 you specify an output stream or filter function to handle the output.
2711 BUFFER may be also nil, meaning that this process is not associated
2714 :host HOST -- HOST is name of the host to connect to, or its IP
2715 address. The symbol `local' specifies the local host. If specified
2716 for a server process, it must be a valid name or address for the local
2717 host, and only clients connecting to that address will be accepted.
2719 :service SERVICE -- SERVICE is name of the service desired, or an
2720 integer specifying a port number to connect to. If SERVICE is t,
2721 a random port number is selected for the server. (If Emacs was
2722 compiled with getaddrinfo, a port number can also be specified as a
2723 string, e.g. "80", as well as an integer. This is not portable.)
2725 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2726 stream type connection, `datagram' creates a datagram type connection,
2727 `seqpacket' creates a reliable datagram connection.
2729 :family FAMILY -- FAMILY is the address (and protocol) family for the
2730 service specified by HOST and SERVICE. The default (nil) is to use
2731 whatever address family (IPv4 or IPv6) that is defined for the host
2732 and port number specified by HOST and SERVICE. Other address families
2734 local -- for a local (i.e. UNIX) address specified by SERVICE.
2735 ipv4 -- use IPv4 address family only.
2736 ipv6 -- use IPv6 address family only.
2738 :local ADDRESS -- ADDRESS is the local address used for the connection.
2739 This parameter is ignored when opening a client process. When specified
2740 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2742 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2743 connection. This parameter is ignored when opening a stream server
2744 process. For a datagram server process, it specifies the initial
2745 setting of the remote datagram address. When specified for a client
2746 process, the FAMILY, HOST, and SERVICE args are ignored.
2748 The format of ADDRESS depends on the address family:
2749 - An IPv4 address is represented as an vector of integers [A B C D P]
2750 corresponding to numeric IP address A.B.C.D and port number P.
2751 - A local address is represented as a string with the address in the
2752 local address space.
2753 - An "unsupported family" address is represented by a cons (F . AV)
2754 where F is the family number and AV is a vector containing the socket
2755 address data with one element per address data byte. Do not rely on
2756 this format in portable code, as it may depend on implementation
2757 defined constants, data sizes, and data structure alignment.
2759 :coding CODING -- If CODING is a symbol, it specifies the coding
2760 system used for both reading and writing for this process. If CODING
2761 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2762 ENCODING is used for writing.
2764 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2765 return without waiting for the connection to complete; instead, the
2766 sentinel function will be called with second arg matching "open" (if
2767 successful) or "failed" when the connect completes. Default is to use
2768 a blocking connect (i.e. wait) for stream type connections.
2770 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2771 running when Emacs is exited.
2773 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2774 In the stopped state, a server process does not accept new
2775 connections, and a client process does not handle incoming traffic.
2776 The stopped state is cleared by `continue-process' and set by
2779 :filter FILTER -- Install FILTER as the process filter.
2781 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2782 process filter are multibyte, otherwise they are unibyte.
2783 If this keyword is not specified, the strings are multibyte if
2784 the default value of `enable-multibyte-characters' is non-nil.
2786 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2788 :log LOG -- Install LOG as the server process log function. This
2789 function is called when the server accepts a network connection from a
2790 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2791 is the server process, CLIENT is the new process for the connection,
2792 and MESSAGE is a string.
2794 :plist PLIST -- Install PLIST as the new process' initial plist.
2796 :server QLEN -- if QLEN is non-nil, create a server process for the
2797 specified FAMILY, SERVICE, and connection type (stream or datagram).
2798 If QLEN is an integer, it is used as the max. length of the server's
2799 pending connection queue (also known as the backlog); the default
2800 queue length is 5. Default is to create a client process.
2802 The following network options can be specified for this connection:
2804 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2805 :dontroute BOOL -- Only send to directly connected hosts.
2806 :keepalive BOOL -- Send keep-alive messages on network stream.
2807 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2808 :oobinline BOOL -- Place out-of-band data in receive data stream.
2809 :priority INT -- Set protocol defined priority for sent packets.
2810 :reuseaddr BOOL -- Allow reusing a recently used local address
2811 (this is allowed by default for a server process).
2812 :bindtodevice NAME -- bind to interface NAME. Using this may require
2813 special privileges on some systems.
2815 Consult the relevant system programmer's manual pages for more
2816 information on using these options.
2819 A server process will listen for and accept connections from clients.
2820 When a client connection is accepted, a new network process is created
2821 for the connection with the following parameters:
2823 - The client's process name is constructed by concatenating the server
2824 process' NAME and a client identification string.
2825 - If the FILTER argument is non-nil, the client process will not get a
2826 separate process buffer; otherwise, the client's process buffer is a newly
2827 created buffer named after the server process' BUFFER name or process
2828 NAME concatenated with the client identification string.
2829 - The connection type and the process filter and sentinel parameters are
2830 inherited from the server process' TYPE, FILTER and SENTINEL.
2831 - The client process' contact info is set according to the client's
2832 addressing information (typically an IP address and a port number).
2833 - The client process' plist is initialized from the server's plist.
2835 Notice that the FILTER and SENTINEL args are never used directly by
2836 the server process. Also, the BUFFER argument is not used directly by
2837 the server process, but via the optional :log function, accepted (and
2838 failed) connections may be logged in the server process' buffer.
2840 The original argument list, modified with the actual connection
2841 information, is available via the `process-contact' function.
2843 usage: (make-network-process &rest ARGS) */)
2844 (ptrdiff_t nargs
, Lisp_Object
*args
)
2847 Lisp_Object contact
;
2848 struct Lisp_Process
*p
;
2849 #ifdef HAVE_GETADDRINFO
2850 struct addrinfo ai
, *res
, *lres
;
2851 struct addrinfo hints
;
2852 const char *portstring
;
2854 #else /* HAVE_GETADDRINFO */
2855 struct _emacs_addrinfo
2861 struct sockaddr
*ai_addr
;
2862 struct _emacs_addrinfo
*ai_next
;
2864 #endif /* HAVE_GETADDRINFO */
2865 struct sockaddr_in address_in
;
2866 #ifdef HAVE_LOCAL_SOCKETS
2867 struct sockaddr_un address_un
;
2872 int s
= -1, outch
, inch
;
2873 struct gcpro gcpro1
;
2874 ptrdiff_t count
= SPECPDL_INDEX ();
2876 Lisp_Object QCaddress
; /* one of QClocal or QCremote */
2878 Lisp_Object name
, buffer
, host
, service
, address
;
2879 Lisp_Object filter
, sentinel
;
2880 int is_non_blocking_client
= 0;
2881 int is_server
= 0, backlog
= 5;
2888 /* Save arguments for process-contact and clone-process. */
2889 contact
= Flist (nargs
, args
);
2893 /* Ensure socket support is loaded if available. */
2894 init_winsock (TRUE
);
2897 /* :type TYPE (nil: stream, datagram */
2898 tem
= Fplist_get (contact
, QCtype
);
2900 socktype
= SOCK_STREAM
;
2901 #ifdef DATAGRAM_SOCKETS
2902 else if (EQ (tem
, Qdatagram
))
2903 socktype
= SOCK_DGRAM
;
2905 #ifdef HAVE_SEQPACKET
2906 else if (EQ (tem
, Qseqpacket
))
2907 socktype
= SOCK_SEQPACKET
;
2910 error ("Unsupported connection type");
2913 tem
= Fplist_get (contact
, QCserver
);
2916 /* Don't support network sockets when non-blocking mode is
2917 not available, since a blocked Emacs is not useful. */
2918 #if !defined (O_NONBLOCK) && !defined (O_NDELAY)
2919 error ("Network servers not supported");
2922 if (TYPE_RANGED_INTEGERP (int, tem
))
2923 backlog
= XINT (tem
);
2927 /* Make QCaddress an alias for :local (server) or :remote (client). */
2928 QCaddress
= is_server
? QClocal
: QCremote
;
2931 if (!is_server
&& socktype
!= SOCK_DGRAM
2932 && (tem
= Fplist_get (contact
, QCnowait
), !NILP (tem
)))
2934 #ifndef NON_BLOCKING_CONNECT
2935 error ("Non-blocking connect not supported");
2937 is_non_blocking_client
= 1;
2941 name
= Fplist_get (contact
, QCname
);
2942 buffer
= Fplist_get (contact
, QCbuffer
);
2943 filter
= Fplist_get (contact
, QCfilter
);
2944 sentinel
= Fplist_get (contact
, QCsentinel
);
2946 CHECK_STRING (name
);
2948 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2949 ai
.ai_socktype
= socktype
;
2954 /* :local ADDRESS or :remote ADDRESS */
2955 address
= Fplist_get (contact
, QCaddress
);
2956 if (!NILP (address
))
2958 host
= service
= Qnil
;
2960 if (!(ai
.ai_addrlen
= get_lisp_to_sockaddr_size (address
, &family
)))
2961 error ("Malformed :address");
2962 ai
.ai_family
= family
;
2963 ai
.ai_addr
= alloca (ai
.ai_addrlen
);
2964 conv_lisp_to_sockaddr (family
, address
, ai
.ai_addr
, ai
.ai_addrlen
);
2968 /* :family FAMILY -- nil (for Inet), local, or integer. */
2969 tem
= Fplist_get (contact
, QCfamily
);
2972 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2978 #ifdef HAVE_LOCAL_SOCKETS
2979 else if (EQ (tem
, Qlocal
))
2983 else if (EQ (tem
, Qipv6
))
2986 else if (EQ (tem
, Qipv4
))
2988 else if (TYPE_RANGED_INTEGERP (int, tem
))
2989 family
= XINT (tem
);
2991 error ("Unknown address family");
2993 ai
.ai_family
= family
;
2995 /* :service SERVICE -- string, integer (port number), or t (random port). */
2996 service
= Fplist_get (contact
, QCservice
);
2998 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2999 host
= Fplist_get (contact
, QChost
);
3002 if (EQ (host
, Qlocal
))
3003 /* Depending on setup, "localhost" may map to different IPv4 and/or
3004 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3005 host
= build_string ("127.0.0.1");
3006 CHECK_STRING (host
);
3009 #ifdef HAVE_LOCAL_SOCKETS
3010 if (family
== AF_LOCAL
)
3014 message (":family local ignores the :host \"%s\" property",
3016 contact
= Fplist_put (contact
, QChost
, Qnil
);
3019 CHECK_STRING (service
);
3020 memset (&address_un
, 0, sizeof address_un
);
3021 address_un
.sun_family
= AF_LOCAL
;
3022 strncpy (address_un
.sun_path
, SSDATA (service
), sizeof address_un
.sun_path
);
3023 ai
.ai_addr
= (struct sockaddr
*) &address_un
;
3024 ai
.ai_addrlen
= sizeof address_un
;
3029 /* Slow down polling to every ten seconds.
3030 Some kernels have a bug which causes retrying connect to fail
3031 after a connect. Polling can interfere with gethostbyname too. */
3032 #ifdef POLL_FOR_INPUT
3033 if (socktype
!= SOCK_DGRAM
)
3035 record_unwind_protect (unwind_stop_other_atimers
, Qnil
);
3036 bind_polling_period (10);
3040 #ifdef HAVE_GETADDRINFO
3041 /* If we have a host, use getaddrinfo to resolve both host and service.
3042 Otherwise, use getservbyname to lookup the service. */
3046 /* SERVICE can either be a string or int.
3047 Convert to a C string for later use by getaddrinfo. */
3048 if (EQ (service
, Qt
))
3050 else if (INTEGERP (service
))
3052 sprintf (portbuf
, "%"pI
"d", XINT (service
));
3053 portstring
= portbuf
;
3057 CHECK_STRING (service
);
3058 portstring
= SSDATA (service
);
3063 memset (&hints
, 0, sizeof (hints
));
3065 hints
.ai_family
= family
;
3066 hints
.ai_socktype
= socktype
;
3067 hints
.ai_protocol
= 0;
3069 #ifdef HAVE_RES_INIT
3073 ret
= getaddrinfo (SSDATA (host
), portstring
, &hints
, &res
);
3075 #ifdef HAVE_GAI_STRERROR
3076 error ("%s/%s %s", SSDATA (host
), portstring
, gai_strerror (ret
));
3078 error ("%s/%s getaddrinfo error %d", SSDATA (host
), portstring
, ret
);
3084 #endif /* HAVE_GETADDRINFO */
3086 /* We end up here if getaddrinfo is not defined, or in case no hostname
3087 has been specified (e.g. for a local server process). */
3089 if (EQ (service
, Qt
))
3091 else if (INTEGERP (service
))
3092 port
= htons ((unsigned short) XINT (service
));
3095 struct servent
*svc_info
;
3096 CHECK_STRING (service
);
3097 svc_info
= getservbyname (SSDATA (service
),
3098 (socktype
== SOCK_DGRAM
? "udp" : "tcp"));
3100 error ("Unknown service: %s", SDATA (service
));
3101 port
= svc_info
->s_port
;
3104 memset (&address_in
, 0, sizeof address_in
);
3105 address_in
.sin_family
= family
;
3106 address_in
.sin_addr
.s_addr
= INADDR_ANY
;
3107 address_in
.sin_port
= port
;
3109 #ifndef HAVE_GETADDRINFO
3112 struct hostent
*host_info_ptr
;
3114 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3115 as it may `hang' Emacs for a very long time. */
3119 #ifdef HAVE_RES_INIT
3123 host_info_ptr
= gethostbyname (SDATA (host
));
3128 memcpy (&address_in
.sin_addr
, host_info_ptr
->h_addr
,
3129 host_info_ptr
->h_length
);
3130 family
= host_info_ptr
->h_addrtype
;
3131 address_in
.sin_family
= family
;
3134 /* Attempt to interpret host as numeric inet address */
3136 unsigned long numeric_addr
;
3137 numeric_addr
= inet_addr (SSDATA (host
));
3138 if (numeric_addr
== -1)
3139 error ("Unknown host \"%s\"", SDATA (host
));
3141 memcpy (&address_in
.sin_addr
, &numeric_addr
,
3142 sizeof (address_in
.sin_addr
));
3146 #endif /* not HAVE_GETADDRINFO */
3148 ai
.ai_family
= family
;
3149 ai
.ai_addr
= (struct sockaddr
*) &address_in
;
3150 ai
.ai_addrlen
= sizeof address_in
;
3154 /* Do this in case we never enter the for-loop below. */
3155 count1
= SPECPDL_INDEX ();
3158 for (lres
= res
; lres
; lres
= lres
->ai_next
)
3167 s
= socket (lres
->ai_family
, lres
->ai_socktype
, lres
->ai_protocol
);
3174 #ifdef DATAGRAM_SOCKETS
3175 if (!is_server
&& socktype
== SOCK_DGRAM
)
3177 #endif /* DATAGRAM_SOCKETS */
3179 #ifdef NON_BLOCKING_CONNECT
3180 if (is_non_blocking_client
)
3183 ret
= fcntl (s
, F_SETFL
, O_NONBLOCK
);
3185 ret
= fcntl (s
, F_SETFL
, O_NDELAY
);
3197 /* Make us close S if quit. */
3198 record_unwind_protect (close_file_unwind
, make_number (s
));
3200 /* Parse network options in the arg list.
3201 We simply ignore anything which isn't a known option (including other keywords).
3202 An error is signaled if setting a known option fails. */
3203 for (optn
= optbits
= 0; optn
< nargs
-1; optn
+= 2)
3204 optbits
|= set_socket_option (s
, args
[optn
], args
[optn
+1]);
3208 /* Configure as a server socket. */
3210 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3211 explicit :reuseaddr key to override this. */
3212 #ifdef HAVE_LOCAL_SOCKETS
3213 if (family
!= AF_LOCAL
)
3215 if (!(optbits
& (1 << OPIX_REUSEADDR
)))
3218 if (setsockopt (s
, SOL_SOCKET
, SO_REUSEADDR
, &optval
, sizeof optval
))
3219 report_file_error ("Cannot set reuse option on server socket", Qnil
);
3222 if (bind (s
, lres
->ai_addr
, lres
->ai_addrlen
))
3223 report_file_error ("Cannot bind server socket", Qnil
);
3225 #ifdef HAVE_GETSOCKNAME
3226 if (EQ (service
, Qt
))
3228 struct sockaddr_in sa1
;
3229 socklen_t len1
= sizeof (sa1
);
3230 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3232 ((struct sockaddr_in
*)(lres
->ai_addr
))->sin_port
= sa1
.sin_port
;
3233 service
= make_number (ntohs (sa1
.sin_port
));
3234 contact
= Fplist_put (contact
, QCservice
, service
);
3239 if (socktype
!= SOCK_DGRAM
&& listen (s
, backlog
))
3240 report_file_error ("Cannot listen on server socket", Qnil
);
3248 ret
= connect (s
, lres
->ai_addr
, lres
->ai_addrlen
);
3251 if (ret
== 0 || xerrno
== EISCONN
)
3253 /* The unwind-protect will be discarded afterwards.
3254 Likewise for immediate_quit. */
3258 #ifdef NON_BLOCKING_CONNECT
3260 if (is_non_blocking_client
&& xerrno
== EINPROGRESS
)
3264 if (is_non_blocking_client
&& xerrno
== EWOULDBLOCK
)
3271 if (xerrno
== EINTR
)
3273 /* Unlike most other syscalls connect() cannot be called
3274 again. (That would return EALREADY.) The proper way to
3275 wait for completion is pselect(). */
3283 sc
= pselect (s
+ 1, NULL
, &fdset
, NULL
, NULL
, NULL
);
3289 report_file_error ("select failed", Qnil
);
3293 len
= sizeof xerrno
;
3294 eassert (FD_ISSET (s
, &fdset
));
3295 if (getsockopt (s
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &len
) == -1)
3296 report_file_error ("getsockopt failed", Qnil
);
3298 errno
= xerrno
, report_file_error ("error during connect", Qnil
);
3302 #endif /* !WINDOWSNT */
3306 /* Discard the unwind protect closing S. */
3307 specpdl_ptr
= specpdl
+ count1
;
3312 if (xerrno
== EINTR
)
3319 #ifdef DATAGRAM_SOCKETS
3320 if (socktype
== SOCK_DGRAM
)
3322 if (datagram_address
[s
].sa
)
3324 datagram_address
[s
].sa
= (struct sockaddr
*) xmalloc (lres
->ai_addrlen
);
3325 datagram_address
[s
].len
= lres
->ai_addrlen
;
3329 memset (datagram_address
[s
].sa
, 0, lres
->ai_addrlen
);
3330 if (remote
= Fplist_get (contact
, QCremote
), !NILP (remote
))
3333 rlen
= get_lisp_to_sockaddr_size (remote
, &rfamily
);
3334 if (rfamily
== lres
->ai_family
&& rlen
== lres
->ai_addrlen
)
3335 conv_lisp_to_sockaddr (rfamily
, remote
,
3336 datagram_address
[s
].sa
, rlen
);
3340 memcpy (datagram_address
[s
].sa
, lres
->ai_addr
, lres
->ai_addrlen
);
3343 contact
= Fplist_put (contact
, QCaddress
,
3344 conv_sockaddr_to_lisp (lres
->ai_addr
, lres
->ai_addrlen
));
3345 #ifdef HAVE_GETSOCKNAME
3348 struct sockaddr_in sa1
;
3349 socklen_t len1
= sizeof (sa1
);
3350 if (getsockname (s
, (struct sockaddr
*)&sa1
, &len1
) == 0)
3351 contact
= Fplist_put (contact
, QClocal
,
3352 conv_sockaddr_to_lisp ((struct sockaddr
*)&sa1
, len1
));
3359 #ifdef HAVE_GETADDRINFO
3368 /* Discard the unwind protect for closing S, if any. */
3369 specpdl_ptr
= specpdl
+ count1
;
3371 /* Unwind bind_polling_period and request_sigio. */
3372 unbind_to (count
, Qnil
);
3376 /* If non-blocking got this far - and failed - assume non-blocking is
3377 not supported after all. This is probably a wrong assumption, but
3378 the normal blocking calls to open-network-stream handles this error
3380 if (is_non_blocking_client
)
3385 report_file_error ("make server process failed", contact
);
3387 report_file_error ("make client process failed", contact
);
3394 buffer
= Fget_buffer_create (buffer
);
3395 proc
= make_process (name
);
3397 chan_process
[inch
] = proc
;
3400 fcntl (inch
, F_SETFL
, O_NONBLOCK
);
3403 fcntl (inch
, F_SETFL
, O_NDELAY
);
3407 p
= XPROCESS (proc
);
3409 p
->childp
= contact
;
3410 p
->plist
= Fcopy_sequence (Fplist_get (contact
, QCplist
));
3414 p
->sentinel
= sentinel
;
3416 p
->log
= Fplist_get (contact
, QClog
);
3417 if (tem
= Fplist_get (contact
, QCnoquery
), !NILP (tem
))
3418 p
->kill_without_query
= 1;
3419 if ((tem
= Fplist_get (contact
, QCstop
), !NILP (tem
)))
3424 if (is_server
&& socktype
!= SOCK_DGRAM
)
3425 p
->status
= Qlisten
;
3427 /* Make the process marker point into the process buffer (if any). */
3428 if (BUFFERP (buffer
))
3429 set_marker_both (p
->mark
, buffer
,
3430 BUF_ZV (XBUFFER (buffer
)),
3431 BUF_ZV_BYTE (XBUFFER (buffer
)));
3433 #ifdef NON_BLOCKING_CONNECT
3434 if (is_non_blocking_client
)
3436 /* We may get here if connect did succeed immediately. However,
3437 in that case, we still need to signal this like a non-blocking
3439 p
->status
= Qconnect
;
3440 if (!FD_ISSET (inch
, &connect_wait_mask
))
3442 FD_SET (inch
, &connect_wait_mask
);
3443 FD_SET (inch
, &write_mask
);
3444 num_pending_connects
++;
3449 /* A server may have a client filter setting of Qt, but it must
3450 still listen for incoming connects unless it is stopped. */
3451 if ((!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
3452 || (EQ (p
->status
, Qlisten
) && NILP (p
->command
)))
3454 FD_SET (inch
, &input_wait_mask
);
3455 FD_SET (inch
, &non_keyboard_wait_mask
);
3458 if (inch
> max_process_desc
)
3459 max_process_desc
= inch
;
3461 tem
= Fplist_member (contact
, QCcoding
);
3462 if (!NILP (tem
) && (!CONSP (tem
) || !CONSP (XCDR (tem
))))
3463 tem
= Qnil
; /* No error message (too late!). */
3466 /* Setup coding systems for communicating with the network stream. */
3467 struct gcpro gcpro1
;
3468 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3469 Lisp_Object coding_systems
= Qt
;
3470 Lisp_Object fargs
[5], val
;
3474 val
= XCAR (XCDR (tem
));
3478 else if (!NILP (Vcoding_system_for_read
))
3479 val
= Vcoding_system_for_read
;
3480 else if ((!NILP (buffer
) && NILP (BVAR (XBUFFER (buffer
), enable_multibyte_characters
)))
3481 || (NILP (buffer
) && NILP (BVAR (&buffer_defaults
, enable_multibyte_characters
))))
3482 /* We dare not decode end-of-line format by setting VAL to
3483 Qraw_text, because the existing Emacs Lisp libraries
3484 assume that they receive bare code including a sequence of
3489 if (NILP (host
) || NILP (service
))
3490 coding_systems
= Qnil
;
3493 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3494 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3496 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3499 if (CONSP (coding_systems
))
3500 val
= XCAR (coding_systems
);
3501 else if (CONSP (Vdefault_process_coding_system
))
3502 val
= XCAR (Vdefault_process_coding_system
);
3506 p
->decode_coding_system
= val
;
3510 val
= XCAR (XCDR (tem
));
3514 else if (!NILP (Vcoding_system_for_write
))
3515 val
= Vcoding_system_for_write
;
3516 else if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3520 if (EQ (coding_systems
, Qt
))
3522 if (NILP (host
) || NILP (service
))
3523 coding_systems
= Qnil
;
3526 fargs
[0] = Qopen_network_stream
, fargs
[1] = name
,
3527 fargs
[2] = buffer
, fargs
[3] = host
, fargs
[4] = service
;
3529 coding_systems
= Ffind_operation_coding_system (5, fargs
);
3533 if (CONSP (coding_systems
))
3534 val
= XCDR (coding_systems
);
3535 else if (CONSP (Vdefault_process_coding_system
))
3536 val
= XCDR (Vdefault_process_coding_system
);
3540 p
->encode_coding_system
= val
;
3542 setup_process_coding_systems (proc
);
3544 p
->decoding_buf
= empty_unibyte_string
;
3545 p
->decoding_carryover
= 0;
3546 p
->encoding_buf
= empty_unibyte_string
;
3548 p
->inherit_coding_system_flag
3549 = !(!NILP (tem
) || NILP (buffer
) || !inherit_process_coding_system
);
3556 #if defined (HAVE_NET_IF_H)
3559 DEFUN ("network-interface-list", Fnetwork_interface_list
, Snetwork_interface_list
, 0, 0, 0,
3560 doc
: /* Return an alist of all network interfaces and their network address.
3561 Each element is a cons, the car of which is a string containing the
3562 interface name, and the cdr is the network address in internal
3563 format; see the description of ADDRESS in `make-network-process'. */)
3566 struct ifconf ifconf
;
3567 struct ifreq
*ifreq
;
3569 ptrdiff_t buf_size
= 512;
3573 s
= socket (AF_INET
, SOCK_STREAM
, 0);
3579 buf
= xpalloc (buf
, &buf_size
, 1, INT_MAX
, 1);
3580 ifconf
.ifc_buf
= buf
;
3581 ifconf
.ifc_len
= buf_size
;
3582 if (ioctl (s
, SIOCGIFCONF
, &ifconf
))
3589 while (ifconf
.ifc_len
== buf_size
);
3594 ifreq
= ifconf
.ifc_req
;
3595 while ((char *) ifreq
< (char *) ifconf
.ifc_req
+ ifconf
.ifc_len
)
3597 struct ifreq
*ifq
= ifreq
;
3598 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3599 #define SIZEOF_IFREQ(sif) \
3600 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3601 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3603 int len
= SIZEOF_IFREQ (ifq
);
3605 int len
= sizeof (*ifreq
);
3607 char namebuf
[sizeof (ifq
->ifr_name
) + 1];
3609 ifreq
= (struct ifreq
*) ((char *) ifreq
+ len
);
3611 if (ifq
->ifr_addr
.sa_family
!= AF_INET
)
3614 memcpy (namebuf
, ifq
->ifr_name
, sizeof (ifq
->ifr_name
));
3615 namebuf
[sizeof (ifq
->ifr_name
)] = 0;
3616 res
= Fcons (Fcons (build_string (namebuf
),
3617 conv_sockaddr_to_lisp (&ifq
->ifr_addr
,
3618 sizeof (struct sockaddr
))),
3625 #endif /* SIOCGIFCONF */
3627 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3631 const char *flag_sym
;
3634 static const struct ifflag_def ifflag_table
[] = {
3638 #ifdef IFF_BROADCAST
3639 { IFF_BROADCAST
, "broadcast" },
3642 { IFF_DEBUG
, "debug" },
3645 { IFF_LOOPBACK
, "loopback" },
3647 #ifdef IFF_POINTOPOINT
3648 { IFF_POINTOPOINT
, "pointopoint" },
3651 { IFF_RUNNING
, "running" },
3654 { IFF_NOARP
, "noarp" },
3657 { IFF_PROMISC
, "promisc" },
3659 #ifdef IFF_NOTRAILERS
3660 #ifdef NS_IMPL_COCOA
3661 /* Really means smart, notrailers is obsolete */
3662 { IFF_NOTRAILERS
, "smart" },
3664 { IFF_NOTRAILERS
, "notrailers" },
3668 { IFF_ALLMULTI
, "allmulti" },
3671 { IFF_MASTER
, "master" },
3674 { IFF_SLAVE
, "slave" },
3676 #ifdef IFF_MULTICAST
3677 { IFF_MULTICAST
, "multicast" },
3680 { IFF_PORTSEL
, "portsel" },
3682 #ifdef IFF_AUTOMEDIA
3683 { IFF_AUTOMEDIA
, "automedia" },
3686 { IFF_DYNAMIC
, "dynamic" },
3689 { IFF_OACTIVE
, "oactive" }, /* OpenBSD: transmission in progress */
3692 { IFF_SIMPLEX
, "simplex" }, /* OpenBSD: can't hear own transmissions */
3695 { IFF_LINK0
, "link0" }, /* OpenBSD: per link layer defined bit */
3698 { IFF_LINK1
, "link1" }, /* OpenBSD: per link layer defined bit */
3701 { IFF_LINK2
, "link2" }, /* OpenBSD: per link layer defined bit */
3706 DEFUN ("network-interface-info", Fnetwork_interface_info
, Snetwork_interface_info
, 1, 1, 0,
3707 doc
: /* Return information about network interface named IFNAME.
3708 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3709 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3710 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3711 FLAGS is the current flags of the interface. */)
3712 (Lisp_Object ifname
)
3715 Lisp_Object res
= Qnil
;
3719 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3720 && defined HAVE_GETIFADDRS && defined LLADDR)
3721 struct ifaddrs
*ifap
;
3724 CHECK_STRING (ifname
);
3726 memset (rq
.ifr_name
, 0, sizeof rq
.ifr_name
);
3727 strncpy (rq
.ifr_name
, SSDATA (ifname
), sizeof (rq
.ifr_name
));
3729 s
= socket (AF_INET
, SOCK_STREAM
, 0);
3734 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3735 if (ioctl (s
, SIOCGIFFLAGS
, &rq
) == 0)
3737 int flags
= rq
.ifr_flags
;
3738 const struct ifflag_def
*fp
;
3741 /* If flags is smaller than int (i.e. short) it may have the high bit set
3742 due to IFF_MULTICAST. In that case, sign extending it into
3744 if (flags
< 0 && sizeof (rq
.ifr_flags
) < sizeof (flags
))
3745 flags
= (unsigned short) rq
.ifr_flags
;
3748 for (fp
= ifflag_table
; flags
!= 0 && fp
->flag_sym
; fp
++)
3750 if (flags
& fp
->flag_bit
)
3752 elt
= Fcons (intern (fp
->flag_sym
), elt
);
3753 flags
-= fp
->flag_bit
;
3756 for (fnum
= 0; flags
&& fnum
< 32; flags
>>= 1, fnum
++)
3760 elt
= Fcons (make_number (fnum
), elt
);
3765 res
= Fcons (elt
, res
);
3768 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3769 if (ioctl (s
, SIOCGIFHWADDR
, &rq
) == 0)
3771 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3772 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3776 for (n
= 0; n
< 6; n
++)
3777 p
->contents
[n
] = make_number (((unsigned char *)&rq
.ifr_hwaddr
.sa_data
[0])[n
]);
3778 elt
= Fcons (make_number (rq
.ifr_hwaddr
.sa_family
), hwaddr
);
3780 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3781 if (getifaddrs (&ifap
) != -1)
3783 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
3784 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
3787 for (it
= ifap
; it
!= NULL
; it
= it
->ifa_next
)
3789 struct sockaddr_dl
*sdl
= (struct sockaddr_dl
*) it
->ifa_addr
;
3790 unsigned char linkaddr
[6];
3793 if (it
->ifa_addr
->sa_family
!= AF_LINK
3794 || strcmp (it
->ifa_name
, SSDATA (ifname
)) != 0
3795 || sdl
->sdl_alen
!= 6)
3798 memcpy (linkaddr
, LLADDR (sdl
), sdl
->sdl_alen
);
3799 for (n
= 0; n
< 6; n
++)
3800 p
->contents
[n
] = make_number (linkaddr
[n
]);
3802 elt
= Fcons (make_number (it
->ifa_addr
->sa_family
), hwaddr
);
3806 #ifdef HAVE_FREEIFADDRS
3810 #endif /* HAVE_GETIFADDRS && LLADDR */
3812 res
= Fcons (elt
, res
);
3815 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3816 if (ioctl (s
, SIOCGIFNETMASK
, &rq
) == 0)
3819 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3820 elt
= conv_sockaddr_to_lisp (&rq
.ifr_netmask
, sizeof (rq
.ifr_netmask
));
3822 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3826 res
= Fcons (elt
, res
);
3829 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3830 if (ioctl (s
, SIOCGIFBRDADDR
, &rq
) == 0)
3833 elt
= conv_sockaddr_to_lisp (&rq
.ifr_broadaddr
, sizeof (rq
.ifr_broadaddr
));
3836 res
= Fcons (elt
, res
);
3839 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3840 if (ioctl (s
, SIOCGIFADDR
, &rq
) == 0)
3843 elt
= conv_sockaddr_to_lisp (&rq
.ifr_addr
, sizeof (rq
.ifr_addr
));
3846 res
= Fcons (elt
, res
);
3850 return any
? res
: Qnil
;
3853 #endif /* defined (HAVE_NET_IF_H) */
3855 /* Turn off input and output for process PROC. */
3858 deactivate_process (Lisp_Object proc
)
3860 register int inchannel
, outchannel
;
3861 register struct Lisp_Process
*p
= XPROCESS (proc
);
3864 /* Delete GnuTLS structures in PROC, if any. */
3865 emacs_gnutls_deinit (proc
);
3866 #endif /* HAVE_GNUTLS */
3868 inchannel
= p
->infd
;
3869 outchannel
= p
->outfd
;
3871 #ifdef ADAPTIVE_READ_BUFFERING
3872 if (p
->read_output_delay
> 0)
3874 if (--process_output_delay_count
< 0)
3875 process_output_delay_count
= 0;
3876 p
->read_output_delay
= 0;
3877 p
->read_output_skip
= 0;
3883 /* Beware SIGCHLD hereabouts. */
3884 flush_pending_output (inchannel
);
3885 emacs_close (inchannel
);
3886 if (outchannel
>= 0 && outchannel
!= inchannel
)
3887 emacs_close (outchannel
);
3891 #ifdef DATAGRAM_SOCKETS
3892 if (DATAGRAM_CHAN_P (inchannel
))
3894 xfree (datagram_address
[inchannel
].sa
);
3895 datagram_address
[inchannel
].sa
= 0;
3896 datagram_address
[inchannel
].len
= 0;
3899 chan_process
[inchannel
] = Qnil
;
3900 FD_CLR (inchannel
, &input_wait_mask
);
3901 FD_CLR (inchannel
, &non_keyboard_wait_mask
);
3902 #ifdef NON_BLOCKING_CONNECT
3903 if (FD_ISSET (inchannel
, &connect_wait_mask
))
3905 FD_CLR (inchannel
, &connect_wait_mask
);
3906 FD_CLR (inchannel
, &write_mask
);
3907 if (--num_pending_connects
< 0)
3911 if (inchannel
== max_process_desc
)
3914 /* We just closed the highest-numbered process input descriptor,
3915 so recompute the highest-numbered one now. */
3916 max_process_desc
= 0;
3917 for (i
= 0; i
< MAXDESC
; i
++)
3918 if (!NILP (chan_process
[i
]))
3919 max_process_desc
= i
;
3925 DEFUN ("accept-process-output", Faccept_process_output
, Saccept_process_output
,
3927 doc
: /* Allow any pending output from subprocesses to be read by Emacs.
3928 It is read into the process' buffers or given to their filter functions.
3929 Non-nil arg PROCESS means do not return until some output has been received
3932 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3933 and milliseconds to wait; return after that much time whether or not
3934 there is any subprocess output. If SECONDS is a floating point number,
3935 it specifies a fractional number of seconds to wait.
3936 The MILLISEC argument is obsolete and should be avoided.
3938 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3939 from PROCESS, suspending reading output from other processes.
3940 If JUST-THIS-ONE is an integer, don't run any timers either.
3941 Return non-nil if we received any output before the timeout expired. */)
3942 (register Lisp_Object process
, Lisp_Object seconds
, Lisp_Object millisec
, Lisp_Object just_this_one
)
3947 if (! NILP (process
))
3948 CHECK_PROCESS (process
);
3950 just_this_one
= Qnil
;
3952 if (!NILP (millisec
))
3953 { /* Obsolete calling convention using integers rather than floats. */
3954 CHECK_NUMBER (millisec
);
3956 seconds
= make_float (XINT (millisec
) / 1000.0);
3959 CHECK_NUMBER (seconds
);
3960 seconds
= make_float (XINT (millisec
) / 1000.0 + XINT (seconds
));
3967 if (!NILP (seconds
))
3969 if (INTEGERP (seconds
))
3971 if (0 < XINT (seconds
))
3973 secs
= XINT (seconds
);
3977 else if (FLOATP (seconds
))
3979 if (0 < XFLOAT_DATA (seconds
))
3981 EMACS_TIME t
= EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds
));
3982 secs
= min (EMACS_SECS (t
), WAIT_READING_MAX
);
3983 nsecs
= EMACS_NSECS (t
);
3987 wrong_type_argument (Qnumberp
, seconds
);
3989 else if (! NILP (process
))
3993 (wait_reading_process_output (secs
, nsecs
, 0, 0,
3995 !NILP (process
) ? XPROCESS (process
) : NULL
,
3996 NILP (just_this_one
) ? 0 :
3997 !INTEGERP (just_this_one
) ? 1 : -1)
4001 /* Accept a connection for server process SERVER on CHANNEL. */
4003 static int connect_counter
= 0;
4006 server_accept_connection (Lisp_Object server
, int channel
)
4008 Lisp_Object proc
, caller
, name
, buffer
;
4009 Lisp_Object contact
, host
, service
;
4010 struct Lisp_Process
*ps
= XPROCESS (server
);
4011 struct Lisp_Process
*p
;
4015 struct sockaddr_in in
;
4017 struct sockaddr_in6 in6
;
4019 #ifdef HAVE_LOCAL_SOCKETS
4020 struct sockaddr_un un
;
4023 socklen_t len
= sizeof saddr
;
4025 s
= accept (channel
, &saddr
.sa
, &len
);
4034 if (code
== EWOULDBLOCK
)
4038 if (!NILP (ps
->log
))
4039 call3 (ps
->log
, server
, Qnil
,
4040 concat3 (build_string ("accept failed with code"),
4041 Fnumber_to_string (make_number (code
)),
4042 build_string ("\n")));
4048 /* Setup a new process to handle the connection. */
4050 /* Generate a unique identification of the caller, and build contact
4051 information for this process. */
4054 switch (saddr
.sa
.sa_family
)
4058 Lisp_Object args
[5];
4059 unsigned char *ip
= (unsigned char *)&saddr
.in
.sin_addr
.s_addr
;
4060 args
[0] = build_string ("%d.%d.%d.%d");
4061 args
[1] = make_number (*ip
++);
4062 args
[2] = make_number (*ip
++);
4063 args
[3] = make_number (*ip
++);
4064 args
[4] = make_number (*ip
++);
4065 host
= Fformat (5, args
);
4066 service
= make_number (ntohs (saddr
.in
.sin_port
));
4068 args
[0] = build_string (" <%s:%d>");
4071 caller
= Fformat (3, args
);
4078 Lisp_Object args
[9];
4079 uint16_t *ip6
= (uint16_t *)&saddr
.in6
.sin6_addr
;
4081 args
[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4082 for (i
= 0; i
< 8; i
++)
4083 args
[i
+1] = make_number (ntohs (ip6
[i
]));
4084 host
= Fformat (9, args
);
4085 service
= make_number (ntohs (saddr
.in
.sin_port
));
4087 args
[0] = build_string (" <[%s]:%d>");
4090 caller
= Fformat (3, args
);
4095 #ifdef HAVE_LOCAL_SOCKETS
4099 caller
= Fnumber_to_string (make_number (connect_counter
));
4100 caller
= concat3 (build_string (" <"), caller
, build_string (">"));
4104 /* Create a new buffer name for this process if it doesn't have a
4105 filter. The new buffer name is based on the buffer name or
4106 process name of the server process concatenated with the caller
4109 if (!NILP (ps
->filter
) && !EQ (ps
->filter
, Qt
))
4113 buffer
= ps
->buffer
;
4115 buffer
= Fbuffer_name (buffer
);
4120 buffer
= concat2 (buffer
, caller
);
4121 buffer
= Fget_buffer_create (buffer
);
4125 /* Generate a unique name for the new server process. Combine the
4126 server process name with the caller identification. */
4128 name
= concat2 (ps
->name
, caller
);
4129 proc
= make_process (name
);
4131 chan_process
[s
] = proc
;
4134 fcntl (s
, F_SETFL
, O_NONBLOCK
);
4137 fcntl (s
, F_SETFL
, O_NDELAY
);
4141 p
= XPROCESS (proc
);
4143 /* Build new contact information for this setup. */
4144 contact
= Fcopy_sequence (ps
->childp
);
4145 contact
= Fplist_put (contact
, QCserver
, Qnil
);
4146 contact
= Fplist_put (contact
, QChost
, host
);
4147 if (!NILP (service
))
4148 contact
= Fplist_put (contact
, QCservice
, service
);
4149 contact
= Fplist_put (contact
, QCremote
,
4150 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4151 #ifdef HAVE_GETSOCKNAME
4153 if (getsockname (s
, &saddr
.sa
, &len
) == 0)
4154 contact
= Fplist_put (contact
, QClocal
,
4155 conv_sockaddr_to_lisp (&saddr
.sa
, len
));
4158 p
->childp
= contact
;
4159 p
->plist
= Fcopy_sequence (ps
->plist
);
4163 p
->sentinel
= ps
->sentinel
;
4164 p
->filter
= ps
->filter
;
4171 /* Client processes for accepted connections are not stopped initially. */
4172 if (!EQ (p
->filter
, Qt
))
4174 FD_SET (s
, &input_wait_mask
);
4175 FD_SET (s
, &non_keyboard_wait_mask
);
4178 if (s
> max_process_desc
)
4179 max_process_desc
= s
;
4181 /* Setup coding system for new process based on server process.
4182 This seems to be the proper thing to do, as the coding system
4183 of the new process should reflect the settings at the time the
4184 server socket was opened; not the current settings. */
4186 p
->decode_coding_system
= ps
->decode_coding_system
;
4187 p
->encode_coding_system
= ps
->encode_coding_system
;
4188 setup_process_coding_systems (proc
);
4190 p
->decoding_buf
= empty_unibyte_string
;
4191 p
->decoding_carryover
= 0;
4192 p
->encoding_buf
= empty_unibyte_string
;
4194 p
->inherit_coding_system_flag
4195 = (NILP (buffer
) ? 0 : ps
->inherit_coding_system_flag
);
4197 if (!NILP (ps
->log
))
4198 call3 (ps
->log
, server
, proc
,
4199 concat3 (build_string ("accept from "),
4200 (STRINGP (host
) ? host
: build_string ("-")),
4201 build_string ("\n")));
4203 if (!NILP (p
->sentinel
))
4204 exec_sentinel (proc
,
4205 concat3 (build_string ("open from "),
4206 (STRINGP (host
) ? host
: build_string ("-")),
4207 build_string ("\n")));
4210 /* This variable is different from waiting_for_input in keyboard.c.
4211 It is used to communicate to a lisp process-filter/sentinel (via the
4212 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4213 for user-input when that process-filter was called.
4214 waiting_for_input cannot be used as that is by definition 0 when
4215 lisp code is being evalled.
4216 This is also used in record_asynch_buffer_change.
4217 For that purpose, this must be 0
4218 when not inside wait_reading_process_output. */
4219 static int waiting_for_user_input_p
;
4222 wait_reading_process_output_unwind (Lisp_Object data
)
4224 waiting_for_user_input_p
= XINT (data
);
4228 /* This is here so breakpoints can be put on it. */
4230 wait_reading_process_output_1 (void)
4234 /* Read and dispose of subprocess output while waiting for timeout to
4235 elapse and/or keyboard input to be available.
4239 If negative, gobble data immediately available but don't wait for any.
4242 an additional duration to wait, measured in nanoseconds
4243 If TIME_LIMIT is zero, then:
4244 If NSECS == 0, there is no limit.
4245 If NSECS > 0, the timeout consists of NSECS only.
4246 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4248 READ_KBD is a lisp value:
4249 0 to ignore keyboard input, or
4250 1 to return when input is available, or
4251 -1 meaning caller will actually read the input, so don't throw to
4252 the quit handler, or
4254 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4255 output that arrives.
4257 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4258 (and gobble terminal input into the buffer if any arrives).
4260 If WAIT_PROC is specified, wait until something arrives from that
4261 process. The return value is true if we read some input from
4264 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4265 (suspending output from other processes). A negative value
4266 means don't run any timers either.
4268 If WAIT_PROC is specified, then the function returns true if we
4269 received input from that process before the timeout elapsed.
4270 Otherwise, return true if we received input from any process. */
4273 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
4275 Lisp_Object wait_for_cell
,
4276 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
4278 register int channel
, nfds
;
4279 SELECT_TYPE Available
;
4280 SELECT_TYPE Writeok
;
4282 int check_delay
, no_avail
;
4285 EMACS_TIME timeout
, end_time
;
4286 int wait_channel
= -1;
4287 int got_some_input
= 0;
4288 ptrdiff_t count
= SPECPDL_INDEX ();
4290 FD_ZERO (&Available
);
4293 if (time_limit
== 0 && nsecs
== 0 && wait_proc
&& !NILP (Vinhibit_quit
)
4294 && !(CONSP (wait_proc
->status
) && EQ (XCAR (wait_proc
->status
), Qexit
)))
4295 message ("Blocking call to accept-process-output with quit inhibited!!");
4297 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4298 if (wait_proc
!= NULL
)
4299 wait_channel
= wait_proc
->infd
;
4301 record_unwind_protect (wait_reading_process_output_unwind
,
4302 make_number (waiting_for_user_input_p
));
4303 waiting_for_user_input_p
= read_kbd
;
4310 else if (TYPE_MAXIMUM (time_t) < time_limit
)
4311 time_limit
= TYPE_MAXIMUM (time_t);
4313 /* Since we may need to wait several times,
4314 compute the absolute time to return at. */
4315 if (time_limit
|| nsecs
) /* FIXME neither should be negative, no? */
4317 EMACS_GET_TIME (end_time
);
4318 EMACS_SET_SECS_NSECS (timeout
, time_limit
, nsecs
);
4319 EMACS_ADD_TIME (end_time
, end_time
, timeout
);
4324 int timeout_reduced_for_timers
= 0;
4326 /* If calling from keyboard input, do not quit
4327 since we want to return C-g as an input character.
4328 Otherwise, do pending quit if requested. */
4333 process_pending_signals ();
4336 /* Exit now if the cell we're waiting for became non-nil. */
4337 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4340 /* Compute time from now till when time limit is up */
4341 /* Exit if already run out */
4344 /* -1 specified for timeout means
4345 gobble output available now
4346 but don't wait at all. */
4348 EMACS_SET_SECS_USECS (timeout
, 0, 0);
4350 else if (time_limit
|| nsecs
)
4352 EMACS_GET_TIME (timeout
);
4353 if (EMACS_TIME_LE (end_time
, timeout
))
4355 EMACS_SUB_TIME (timeout
, end_time
, timeout
);
4359 EMACS_SET_SECS_USECS (timeout
, 100000, 0);
4362 /* Normally we run timers here.
4363 But not if wait_for_cell; in those cases,
4364 the wait is supposed to be short,
4365 and those callers cannot handle running arbitrary Lisp code here. */
4366 if (NILP (wait_for_cell
)
4367 && just_wait_proc
>= 0)
4369 EMACS_TIME timer_delay
;
4373 int old_timers_run
= timers_run
;
4374 struct buffer
*old_buffer
= current_buffer
;
4375 Lisp_Object old_window
= selected_window
;
4377 timer_delay
= timer_check ();
4379 /* If a timer has run, this might have changed buffers
4380 an alike. Make read_key_sequence aware of that. */
4381 if (timers_run
!= old_timers_run
4382 && (old_buffer
!= current_buffer
4383 || !EQ (old_window
, selected_window
))
4384 && waiting_for_user_input_p
== -1)
4385 record_asynch_buffer_change ();
4387 if (timers_run
!= old_timers_run
&& do_display
)
4388 /* We must retry, since a timer may have requeued itself
4389 and that could alter the time_delay. */
4390 redisplay_preserve_echo_area (9);
4394 while (!detect_input_pending ());
4396 /* If there is unread keyboard input, also return. */
4398 && requeued_events_pending_p ())
4401 /* If time_limit is negative, we are not going to wait at all. */
4404 if (EMACS_TIME_VALID_P (timer_delay
))
4406 if (EMACS_TIME_LT (timer_delay
, timeout
))
4408 timeout
= timer_delay
;
4409 timeout_reduced_for_timers
= 1;
4414 /* This is so a breakpoint can be put here. */
4415 wait_reading_process_output_1 ();
4420 /* Cause C-g and alarm signals to take immediate action,
4421 and cause input available signals to zero out timeout.
4423 It is important that we do this before checking for process
4424 activity. If we get a SIGCHLD after the explicit checks for
4425 process activity, timeout is the only way we will know. */
4427 set_waiting_for_input (&timeout
);
4429 /* If status of something has changed, and no input is
4430 available, notify the user of the change right away. After
4431 this explicit check, we'll let the SIGCHLD handler zap
4432 timeout to get our attention. */
4433 if (update_tick
!= process_tick
)
4438 if (kbd_on_hold_p ())
4441 Atemp
= input_wait_mask
;
4444 EMACS_SET_SECS_USECS (timeout
, 0, 0);
4445 if ((pselect (max (max_process_desc
, max_input_desc
) + 1,
4447 #ifdef NON_BLOCKING_CONNECT
4448 (num_pending_connects
> 0 ? &Ctemp
: NULL
),
4452 NULL
, &timeout
, NULL
)
4455 /* It's okay for us to do this and then continue with
4456 the loop, since timeout has already been zeroed out. */
4457 clear_waiting_for_input ();
4458 status_notify (NULL
);
4459 if (do_display
) redisplay_preserve_echo_area (13);
4463 /* Don't wait for output from a non-running process. Just
4464 read whatever data has already been received. */
4465 if (wait_proc
&& wait_proc
->raw_status_new
)
4466 update_status (wait_proc
);
4468 && ! EQ (wait_proc
->status
, Qrun
)
4469 && ! EQ (wait_proc
->status
, Qconnect
))
4471 int nread
, total_nread
= 0;
4473 clear_waiting_for_input ();
4474 XSETPROCESS (proc
, wait_proc
);
4476 /* Read data from the process, until we exhaust it. */
4477 while (wait_proc
->infd
>= 0)
4479 nread
= read_process_output (proc
, wait_proc
->infd
);
4486 total_nread
+= nread
;
4490 else if (nread
== -1 && EIO
== errno
)
4494 else if (nread
== -1 && EAGAIN
== errno
)
4498 else if (nread
== -1 && EWOULDBLOCK
== errno
)
4502 if (total_nread
> 0 && do_display
)
4503 redisplay_preserve_echo_area (10);
4508 /* Wait till there is something to do */
4510 if (wait_proc
&& just_wait_proc
)
4512 if (wait_proc
->infd
< 0) /* Terminated */
4514 FD_SET (wait_proc
->infd
, &Available
);
4518 else if (!NILP (wait_for_cell
))
4520 Available
= non_process_wait_mask
;
4527 Available
= non_keyboard_wait_mask
;
4529 Available
= input_wait_mask
;
4530 Writeok
= write_mask
;
4531 #ifdef SELECT_CANT_DO_WRITE_MASK
4536 check_delay
= wait_channel
>= 0 ? 0 : process_output_delay_count
;
4539 /* If frame size has changed or the window is newly mapped,
4540 redisplay now, before we start to wait. There is a race
4541 condition here; if a SIGIO arrives between now and the select
4542 and indicates that a frame is trashed, the select may block
4543 displaying a trashed screen. */
4544 if (frame_garbaged
&& do_display
)
4546 clear_waiting_for_input ();
4547 redisplay_preserve_echo_area (11);
4549 set_waiting_for_input (&timeout
);
4552 /* Skip the `select' call if input is available and we're
4553 waiting for keyboard input or a cell change (which can be
4554 triggered by processing X events). In the latter case, set
4555 nfds to 1 to avoid breaking the loop. */
4557 if ((read_kbd
|| !NILP (wait_for_cell
))
4558 && detect_input_pending ())
4560 nfds
= read_kbd
? 0 : 1;
4567 #ifdef ADAPTIVE_READ_BUFFERING
4568 /* Set the timeout for adaptive read buffering if any
4569 process has non-zero read_output_skip and non-zero
4570 read_output_delay, and we are not reading output for a
4571 specific wait_channel. It is not executed if
4572 Vprocess_adaptive_read_buffering is nil. */
4573 if (process_output_skip
&& check_delay
> 0)
4575 int nsecs
= EMACS_NSECS (timeout
);
4576 if (EMACS_SECS (timeout
) > 0 || nsecs
> READ_OUTPUT_DELAY_MAX
)
4577 nsecs
= READ_OUTPUT_DELAY_MAX
;
4578 for (channel
= 0; check_delay
> 0 && channel
<= max_process_desc
; channel
++)
4580 proc
= chan_process
[channel
];
4583 /* Find minimum non-zero read_output_delay among the
4584 processes with non-zero read_output_skip. */
4585 if (XPROCESS (proc
)->read_output_delay
> 0)
4588 if (!XPROCESS (proc
)->read_output_skip
)
4590 FD_CLR (channel
, &Available
);
4591 XPROCESS (proc
)->read_output_skip
= 0;
4592 if (XPROCESS (proc
)->read_output_delay
< nsecs
)
4593 nsecs
= XPROCESS (proc
)->read_output_delay
;
4596 EMACS_SET_SECS_NSECS (timeout
, 0, nsecs
);
4597 process_output_skip
= 0;
4600 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4602 #elif defined (HAVE_NS)
4607 (max (max_process_desc
, max_input_desc
) + 1,
4609 (check_write
? &Writeok
: (SELECT_TYPE
*)0),
4610 NULL
, &timeout
, NULL
);
4613 /* GnuTLS buffers data internally. In lowat mode it leaves
4614 some data in the TCP buffers so that select works, but
4615 with custom pull/push functions we need to check if some
4616 data is available in the buffers manually. */
4621 /* We're not waiting on a specific process, so loop
4622 through all the channels and check for data.
4623 This is a workaround needed for some versions of
4624 the gnutls library -- 2.12.14 has been confirmed
4626 http://comments.gmane.org/gmane.emacs.devel/145074 */
4627 for (channel
= 0; channel
< MAXDESC
; ++channel
)
4628 if (! NILP (chan_process
[channel
]))
4630 struct Lisp_Process
*p
=
4631 XPROCESS (chan_process
[channel
]);
4632 if (p
&& p
->gnutls_p
&& p
->infd
4633 && ((emacs_gnutls_record_check_pending
4638 FD_SET (p
->infd
, &Available
);
4644 /* Check this specific channel. */
4645 if (wait_proc
->gnutls_p
/* Check for valid process. */
4646 /* Do we have pending data? */
4647 && ((emacs_gnutls_record_check_pending
4648 (wait_proc
->gnutls_state
))
4652 /* Set to Available. */
4653 FD_SET (wait_proc
->infd
, &Available
);
4662 /* Make C-g and alarm signals set flags again */
4663 clear_waiting_for_input ();
4665 /* If we woke up due to SIGWINCH, actually change size now. */
4666 do_pending_window_change (0);
4668 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
4669 /* We wanted the full specified time, so return now. */
4673 if (xerrno
== EINTR
)
4675 else if (xerrno
== EBADF
)
4678 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4679 the child's closure of the pts gives the parent a SIGHUP, and
4680 the ptc file descriptor is automatically closed,
4681 yielding EBADF here or at select() call above.
4682 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4683 in m/ibmrt-aix.h), and here we just ignore the select error.
4684 Cleanup occurs c/o status_notify after SIGCLD. */
4685 no_avail
= 1; /* Cannot depend on values returned */
4691 error ("select error: %s", emacs_strerror (xerrno
));
4696 FD_ZERO (&Available
);
4700 #if 0 /* When polling is used, interrupt_input is 0,
4701 so get_input_pending should read the input.
4702 So this should not be needed. */
4703 /* If we are using polling for input,
4704 and we see input available, make it get read now.
4705 Otherwise it might not actually get read for a second.
4706 And on hpux, since we turn off polling in wait_reading_process_output,
4707 it might never get read at all if we don't spend much time
4708 outside of wait_reading_process_output. */
4709 if (read_kbd
&& interrupt_input
4710 && keyboard_bit_set (&Available
)
4711 && input_polling_used ())
4712 kill (getpid (), SIGALRM
);
4715 /* Check for keyboard input */
4716 /* If there is any, return immediately
4717 to give it higher priority than subprocesses */
4721 int old_timers_run
= timers_run
;
4722 struct buffer
*old_buffer
= current_buffer
;
4723 Lisp_Object old_window
= selected_window
;
4726 if (detect_input_pending_run_timers (do_display
))
4728 swallow_events (do_display
);
4729 if (detect_input_pending_run_timers (do_display
))
4733 /* If a timer has run, this might have changed buffers
4734 an alike. Make read_key_sequence aware of that. */
4735 if (timers_run
!= old_timers_run
4736 && waiting_for_user_input_p
== -1
4737 && (old_buffer
!= current_buffer
4738 || !EQ (old_window
, selected_window
)))
4739 record_asynch_buffer_change ();
4745 /* If there is unread keyboard input, also return. */
4747 && requeued_events_pending_p ())
4750 /* If we are not checking for keyboard input now,
4751 do process events (but don't run any timers).
4752 This is so that X events will be processed.
4753 Otherwise they may have to wait until polling takes place.
4754 That would causes delays in pasting selections, for example.
4756 (We used to do this only if wait_for_cell.) */
4757 if (read_kbd
== 0 && detect_input_pending ())
4759 swallow_events (do_display
);
4760 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4761 if (detect_input_pending ())
4766 /* Exit now if the cell we're waiting for became non-nil. */
4767 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
4771 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4772 go read it. This can happen with X on BSD after logging out.
4773 In that case, there really is no input and no SIGIO,
4774 but select says there is input. */
4776 if (read_kbd
&& interrupt_input
4777 && keyboard_bit_set (&Available
) && ! noninteractive
)
4778 kill (getpid (), SIGIO
);
4782 got_some_input
|= nfds
> 0;
4784 /* If checking input just got us a size-change event from X,
4785 obey it now if we should. */
4786 if (read_kbd
|| ! NILP (wait_for_cell
))
4787 do_pending_window_change (0);
4789 /* Check for data from a process. */
4790 if (no_avail
|| nfds
== 0)
4793 for (channel
= 0; channel
<= max_input_desc
; ++channel
)
4795 struct fd_callback_data
*d
= &fd_callback_info
[channel
];
4796 if (FD_ISSET (channel
, &Available
)
4798 && (d
->condition
& FOR_READ
) != 0)
4799 d
->func (channel
, d
->data
, 1);
4800 if (FD_ISSET (channel
, &write_mask
)
4802 && (d
->condition
& FOR_WRITE
) != 0)
4803 d
->func (channel
, d
->data
, 0);
4806 for (channel
= 0; channel
<= max_process_desc
; channel
++)
4808 if (FD_ISSET (channel
, &Available
)
4809 && FD_ISSET (channel
, &non_keyboard_wait_mask
)
4810 && !FD_ISSET (channel
, &non_process_wait_mask
))
4814 /* If waiting for this channel, arrange to return as
4815 soon as no more input to be processed. No more
4817 if (wait_channel
== channel
)
4823 proc
= chan_process
[channel
];
4827 /* If this is a server stream socket, accept connection. */
4828 if (EQ (XPROCESS (proc
)->status
, Qlisten
))
4830 server_accept_connection (proc
, channel
);
4834 /* Read data from the process, starting with our
4835 buffered-ahead character if we have one. */
4837 nread
= read_process_output (proc
, channel
);
4840 /* Since read_process_output can run a filter,
4841 which can call accept-process-output,
4842 don't try to read from any other processes
4843 before doing the select again. */
4844 FD_ZERO (&Available
);
4847 redisplay_preserve_echo_area (12);
4850 else if (nread
== -1 && errno
== EWOULDBLOCK
)
4853 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4854 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4856 else if (nread
== -1 && errno
== EAGAIN
)
4860 else if (nread
== -1 && errno
== EAGAIN
)
4862 /* Note that we cannot distinguish between no input
4863 available now and a closed pipe.
4864 With luck, a closed pipe will be accompanied by
4865 subprocess termination and SIGCHLD. */
4866 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4868 #endif /* O_NDELAY */
4869 #endif /* O_NONBLOCK */
4871 /* On some OSs with ptys, when the process on one end of
4872 a pty exits, the other end gets an error reading with
4873 errno = EIO instead of getting an EOF (0 bytes read).
4874 Therefore, if we get an error reading and errno =
4875 EIO, just continue, because the child process has
4876 exited and should clean itself up soon (e.g. when we
4879 However, it has been known to happen that the SIGCHLD
4880 got lost. So raise the signal again just in case.
4882 else if (nread
== -1 && errno
== EIO
)
4884 struct Lisp_Process
*p
= XPROCESS (proc
);
4886 /* Clear the descriptor now, so we only raise the
4888 FD_CLR (channel
, &input_wait_mask
);
4889 FD_CLR (channel
, &non_keyboard_wait_mask
);
4893 /* If the EIO occurs on a pty, sigchld_handler's
4894 wait3() will not find the process object to
4895 delete. Do it here. */
4896 p
->tick
= ++process_tick
;
4897 p
->status
= Qfailed
;
4900 kill (getpid (), SIGCHLD
);
4902 #endif /* HAVE_PTYS */
4903 /* If we can detect process termination, don't consider the
4904 process gone just because its pipe is closed. */
4906 else if (nread
== 0 && !NETCONN_P (proc
) && !SERIALCONN_P (proc
))
4911 /* Preserve status of processes already terminated. */
4912 XPROCESS (proc
)->tick
= ++process_tick
;
4913 deactivate_process (proc
);
4914 if (XPROCESS (proc
)->raw_status_new
)
4915 update_status (XPROCESS (proc
));
4916 if (EQ (XPROCESS (proc
)->status
, Qrun
))
4917 XPROCESS (proc
)->status
4918 = Fcons (Qexit
, Fcons (make_number (256), Qnil
));
4921 #ifdef NON_BLOCKING_CONNECT
4922 if (FD_ISSET (channel
, &Writeok
)
4923 && FD_ISSET (channel
, &connect_wait_mask
))
4925 struct Lisp_Process
*p
;
4927 FD_CLR (channel
, &connect_wait_mask
);
4928 FD_CLR (channel
, &write_mask
);
4929 if (--num_pending_connects
< 0)
4932 proc
= chan_process
[channel
];
4936 p
= XPROCESS (proc
);
4939 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4940 So only use it on systems where it is known to work. */
4942 socklen_t xlen
= sizeof (xerrno
);
4943 if (getsockopt (channel
, SOL_SOCKET
, SO_ERROR
, &xerrno
, &xlen
))
4948 struct sockaddr pname
;
4949 int pnamelen
= sizeof (pname
);
4951 /* If connection failed, getpeername will fail. */
4953 if (getpeername (channel
, &pname
, &pnamelen
) < 0)
4955 /* Obtain connect failure code through error slippage. */
4958 if (errno
== ENOTCONN
&& read (channel
, &dummy
, 1) < 0)
4965 p
->tick
= ++process_tick
;
4966 p
->status
= Fcons (Qfailed
, Fcons (make_number (xerrno
), Qnil
));
4967 deactivate_process (proc
);
4972 /* Execute the sentinel here. If we had relied on
4973 status_notify to do it later, it will read input
4974 from the process before calling the sentinel. */
4975 exec_sentinel (proc
, build_string ("open\n"));
4976 if (!EQ (p
->filter
, Qt
) && !EQ (p
->command
, Qt
))
4978 FD_SET (p
->infd
, &input_wait_mask
);
4979 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
4983 #endif /* NON_BLOCKING_CONNECT */
4984 } /* end for each file descriptor */
4985 } /* end while exit conditions not met */
4987 unbind_to (count
, Qnil
);
4989 /* If calling from keyboard input, do not quit
4990 since we want to return C-g as an input character.
4991 Otherwise, do pending quit if requested. */
4994 /* Prevent input_pending from remaining set if we quit. */
4995 clear_input_pending ();
4999 return got_some_input
;
5002 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5005 read_process_output_call (Lisp_Object fun_and_args
)
5007 return apply1 (XCAR (fun_and_args
), XCDR (fun_and_args
));
5011 read_process_output_error_handler (Lisp_Object error_val
)
5013 cmd_error_internal (error_val
, "error in process filter: ");
5015 update_echo_area ();
5016 Fsleep_for (make_number (2), Qnil
);
5020 /* Read pending output from the process channel,
5021 starting with our buffered-ahead character if we have one.
5022 Yield number of decoded characters read.
5024 This function reads at most 4096 characters.
5025 If you want to read all available subprocess output,
5026 you must call it repeatedly until it returns zero.
5028 The characters read are decoded according to PROC's coding-system
5032 read_process_output (Lisp_Object proc
, register int channel
)
5034 register ssize_t nbytes
;
5036 register Lisp_Object outstream
;
5037 register struct Lisp_Process
*p
= XPROCESS (proc
);
5038 register ptrdiff_t opoint
;
5039 struct coding_system
*coding
= proc_decode_coding_system
[channel
];
5040 int carryover
= p
->decoding_carryover
;
5042 ptrdiff_t count
= SPECPDL_INDEX ();
5043 Lisp_Object odeactivate
;
5045 chars
= (char *) alloca (carryover
+ readmax
);
5047 /* See the comment above. */
5048 memcpy (chars
, SDATA (p
->decoding_buf
), carryover
);
5050 #ifdef DATAGRAM_SOCKETS
5051 /* We have a working select, so proc_buffered_char is always -1. */
5052 if (DATAGRAM_CHAN_P (channel
))
5054 socklen_t len
= datagram_address
[channel
].len
;
5055 nbytes
= recvfrom (channel
, chars
+ carryover
, readmax
,
5056 0, datagram_address
[channel
].sa
, &len
);
5061 int buffered
= 0 <= proc_buffered_char
[channel
];
5064 chars
[carryover
] = proc_buffered_char
[channel
];
5065 proc_buffered_char
[channel
] = -1;
5069 nbytes
= emacs_gnutls_read (p
, chars
+ carryover
+ buffered
,
5070 readmax
- buffered
);
5073 nbytes
= emacs_read (channel
, chars
+ carryover
+ buffered
,
5074 readmax
- buffered
);
5075 #ifdef ADAPTIVE_READ_BUFFERING
5076 if (nbytes
> 0 && p
->adaptive_read_buffering
)
5078 int delay
= p
->read_output_delay
;
5081 if (delay
< READ_OUTPUT_DELAY_MAX_MAX
)
5084 process_output_delay_count
++;
5085 delay
+= READ_OUTPUT_DELAY_INCREMENT
* 2;
5088 else if (delay
> 0 && nbytes
== readmax
- buffered
)
5090 delay
-= READ_OUTPUT_DELAY_INCREMENT
;
5092 process_output_delay_count
--;
5094 p
->read_output_delay
= delay
;
5097 p
->read_output_skip
= 1;
5098 process_output_skip
= 1;
5103 nbytes
+= buffered
&& nbytes
<= 0;
5106 p
->decoding_carryover
= 0;
5108 /* At this point, NBYTES holds number of bytes just received
5109 (including the one in proc_buffered_char[channel]). */
5112 if (nbytes
< 0 || coding
->mode
& CODING_MODE_LAST_BLOCK
)
5114 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5117 /* Now set NBYTES how many bytes we must decode. */
5118 nbytes
+= carryover
;
5120 odeactivate
= Vdeactivate_mark
;
5121 /* There's no good reason to let process filters change the current
5122 buffer, and many callers of accept-process-output, sit-for, and
5123 friends don't expect current-buffer to be changed from under them. */
5124 record_unwind_protect (set_buffer_if_live
, Fcurrent_buffer ());
5126 /* Read and dispose of the process output. */
5127 outstream
= p
->filter
;
5128 if (!NILP (outstream
))
5131 int outer_running_asynch_code
= running_asynch_code
;
5132 int waiting
= waiting_for_user_input_p
;
5134 /* No need to gcpro these, because all we do with them later
5135 is test them for EQness, and none of them should be a string. */
5137 Lisp_Object obuffer
, okeymap
;
5138 XSETBUFFER (obuffer
, current_buffer
);
5139 okeymap
= BVAR (current_buffer
, keymap
);
5142 /* We inhibit quit here instead of just catching it so that
5143 hitting ^G when a filter happens to be running won't screw
5145 specbind (Qinhibit_quit
, Qt
);
5146 specbind (Qlast_nonmenu_event
, Qt
);
5148 /* In case we get recursively called,
5149 and we already saved the match data nonrecursively,
5150 save the same match data in safely recursive fashion. */
5151 if (outer_running_asynch_code
)
5154 /* Don't clobber the CURRENT match data, either! */
5155 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
5156 restore_search_regs ();
5157 record_unwind_save_match_data ();
5158 Fset_match_data (tem
, Qt
);
5161 /* For speed, if a search happens within this code,
5162 save the match data in a special nonrecursive fashion. */
5163 running_asynch_code
= 1;
5165 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5166 text
= coding
->dst_object
;
5167 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5168 /* A new coding system might be found. */
5169 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5171 p
->decode_coding_system
= Vlast_coding_system_used
;
5173 /* Don't call setup_coding_system for
5174 proc_decode_coding_system[channel] here. It is done in
5175 detect_coding called via decode_coding above. */
5177 /* If a coding system for encoding is not yet decided, we set
5178 it as the same as coding-system for decoding.
5180 But, before doing that we must check if
5181 proc_encode_coding_system[p->outfd] surely points to a
5182 valid memory because p->outfd will be changed once EOF is
5183 sent to the process. */
5184 if (NILP (p
->encode_coding_system
)
5185 && proc_encode_coding_system
[p
->outfd
])
5187 p
->encode_coding_system
5188 = coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
);
5189 setup_coding_system (p
->encode_coding_system
,
5190 proc_encode_coding_system
[p
->outfd
]);
5194 if (coding
->carryover_bytes
> 0)
5196 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5197 p
->decoding_buf
= make_uninit_string (coding
->carryover_bytes
);
5198 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5199 coding
->carryover_bytes
);
5200 p
->decoding_carryover
= coding
->carryover_bytes
;
5202 if (SBYTES (text
) > 0)
5203 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5204 sometimes it's simply wrong to wrap (e.g. when called from
5205 accept-process-output). */
5206 internal_condition_case_1 (read_process_output_call
,
5208 Fcons (proc
, Fcons (text
, Qnil
))),
5209 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
5210 read_process_output_error_handler
);
5212 /* If we saved the match data nonrecursively, restore it now. */
5213 restore_search_regs ();
5214 running_asynch_code
= outer_running_asynch_code
;
5216 /* Restore waiting_for_user_input_p as it was
5217 when we were called, in case the filter clobbered it. */
5218 waiting_for_user_input_p
= waiting
;
5220 #if 0 /* Call record_asynch_buffer_change unconditionally,
5221 because we might have changed minor modes or other things
5222 that affect key bindings. */
5223 if (! EQ (Fcurrent_buffer (), obuffer
)
5224 || ! EQ (current_buffer
->keymap
, okeymap
))
5226 /* But do it only if the caller is actually going to read events.
5227 Otherwise there's no need to make him wake up, and it could
5228 cause trouble (for example it would make sit_for return). */
5229 if (waiting_for_user_input_p
== -1)
5230 record_asynch_buffer_change ();
5233 /* If no filter, write into buffer if it isn't dead. */
5234 else if (!NILP (p
->buffer
) && !NILP (BVAR (XBUFFER (p
->buffer
), name
)))
5236 Lisp_Object old_read_only
;
5237 ptrdiff_t old_begv
, old_zv
;
5238 ptrdiff_t old_begv_byte
, old_zv_byte
;
5239 ptrdiff_t before
, before_byte
;
5240 ptrdiff_t opoint_byte
;
5244 Fset_buffer (p
->buffer
);
5246 opoint_byte
= PT_BYTE
;
5247 old_read_only
= BVAR (current_buffer
, read_only
);
5250 old_begv_byte
= BEGV_BYTE
;
5251 old_zv_byte
= ZV_BYTE
;
5253 BVAR (current_buffer
, read_only
) = Qnil
;
5255 /* Insert new output into buffer
5256 at the current end-of-output marker,
5257 thus preserving logical ordering of input and output. */
5258 if (XMARKER (p
->mark
)->buffer
)
5259 SET_PT_BOTH (clip_to_bounds (BEGV
, marker_position (p
->mark
), ZV
),
5260 clip_to_bounds (BEGV_BYTE
, marker_byte_position (p
->mark
),
5263 SET_PT_BOTH (ZV
, ZV_BYTE
);
5265 before_byte
= PT_BYTE
;
5267 /* If the output marker is outside of the visible region, save
5268 the restriction and widen. */
5269 if (! (BEGV
<= PT
&& PT
<= ZV
))
5272 decode_coding_c_string (coding
, (unsigned char *) chars
, nbytes
, Qt
);
5273 text
= coding
->dst_object
;
5274 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5275 /* A new coding system might be found. See the comment in the
5276 similar code in the previous `if' block. */
5277 if (!EQ (p
->decode_coding_system
, Vlast_coding_system_used
))
5279 p
->decode_coding_system
= Vlast_coding_system_used
;
5280 if (NILP (p
->encode_coding_system
)
5281 && proc_encode_coding_system
[p
->outfd
])
5283 p
->encode_coding_system
5284 = coding_inherit_eol_type (Vlast_coding_system_used
, Qnil
);
5285 setup_coding_system (p
->encode_coding_system
,
5286 proc_encode_coding_system
[p
->outfd
]);
5289 if (coding
->carryover_bytes
> 0)
5291 if (SCHARS (p
->decoding_buf
) < coding
->carryover_bytes
)
5292 p
->decoding_buf
= make_uninit_string (coding
->carryover_bytes
);
5293 memcpy (SDATA (p
->decoding_buf
), coding
->carryover
,
5294 coding
->carryover_bytes
);
5295 p
->decoding_carryover
= coding
->carryover_bytes
;
5297 /* Adjust the multibyteness of TEXT to that of the buffer. */
5298 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
))
5299 != ! STRING_MULTIBYTE (text
))
5300 text
= (STRING_MULTIBYTE (text
)
5301 ? Fstring_as_unibyte (text
)
5302 : Fstring_to_multibyte (text
));
5303 /* Insert before markers in case we are inserting where
5304 the buffer's mark is, and the user's next command is Meta-y. */
5305 insert_from_string_before_markers (text
, 0, 0,
5306 SCHARS (text
), SBYTES (text
), 0);
5308 /* Make sure the process marker's position is valid when the
5309 process buffer is changed in the signal_after_change above.
5310 W3 is known to do that. */
5311 if (BUFFERP (p
->buffer
)
5312 && (b
= XBUFFER (p
->buffer
), b
!= current_buffer
))
5313 set_marker_both (p
->mark
, p
->buffer
, BUF_PT (b
), BUF_PT_BYTE (b
));
5315 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
5317 update_mode_lines
++;
5319 /* Make sure opoint and the old restrictions
5320 float ahead of any new text just as point would. */
5321 if (opoint
>= before
)
5323 opoint
+= PT
- before
;
5324 opoint_byte
+= PT_BYTE
- before_byte
;
5326 if (old_begv
> before
)
5328 old_begv
+= PT
- before
;
5329 old_begv_byte
+= PT_BYTE
- before_byte
;
5331 if (old_zv
>= before
)
5333 old_zv
+= PT
- before
;
5334 old_zv_byte
+= PT_BYTE
- before_byte
;
5337 /* If the restriction isn't what it should be, set it. */
5338 if (old_begv
!= BEGV
|| old_zv
!= ZV
)
5339 Fnarrow_to_region (make_number (old_begv
), make_number (old_zv
));
5342 BVAR (current_buffer
, read_only
) = old_read_only
;
5343 SET_PT_BOTH (opoint
, opoint_byte
);
5345 /* Handling the process output should not deactivate the mark. */
5346 Vdeactivate_mark
= odeactivate
;
5348 unbind_to (count
, Qnil
);
5352 /* Sending data to subprocess */
5354 static jmp_buf send_process_frame
;
5355 static Lisp_Object process_sent_to
;
5357 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5358 static _Noreturn
void send_process_trap (int);
5362 send_process_trap (int ignore
)
5364 SIGNAL_THREAD_CHECK (SIGPIPE
);
5365 sigunblock (sigmask (SIGPIPE
));
5366 longjmp (send_process_frame
, 1);
5369 /* In send_process, when a write fails temporarily,
5370 wait_reading_process_output is called. It may execute user code,
5371 e.g. timers, that attempts to write new data to the same process.
5372 We must ensure that data is sent in the right order, and not
5373 interspersed half-completed with other writes (Bug#10815). This is
5374 handled by the write_queue element of struct process. It is a list
5375 with each entry having the form
5377 (string . (offset . length))
5379 where STRING is a lisp string, OFFSET is the offset into the
5380 string's byte sequence from which we should begin to send, and
5381 LENGTH is the number of bytes left to send. */
5383 /* Create a new entry in write_queue.
5384 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5385 BUF is a pointer to the string sequence of the input_obj or a C
5386 string in case of Qt or Qnil. */
5389 write_queue_push (struct Lisp_Process
*p
, Lisp_Object input_obj
,
5390 const char *buf
, ptrdiff_t len
, int front
)
5393 Lisp_Object entry
, obj
;
5395 if (STRINGP (input_obj
))
5397 offset
= buf
- SSDATA (input_obj
);
5403 obj
= make_unibyte_string (buf
, len
);
5406 entry
= Fcons (obj
, Fcons (make_number (offset
), make_number (len
)));
5409 p
->write_queue
= Fcons (entry
, p
->write_queue
);
5411 p
->write_queue
= nconc2 (p
->write_queue
, Fcons (entry
, Qnil
));
5414 /* Remove the first element in the write_queue of process P, put its
5415 contents in OBJ, BUF and LEN, and return non-zero. If the
5416 write_queue is empty, return zero. */
5419 write_queue_pop (struct Lisp_Process
*p
, Lisp_Object
*obj
,
5420 const char **buf
, ptrdiff_t *len
)
5422 Lisp_Object entry
, offset_length
;
5425 if (NILP (p
->write_queue
))
5428 entry
= XCAR (p
->write_queue
);
5429 p
->write_queue
= XCDR (p
->write_queue
);
5431 *obj
= XCAR (entry
);
5432 offset_length
= XCDR (entry
);
5434 *len
= XINT (XCDR (offset_length
));
5435 offset
= XINT (XCAR (offset_length
));
5436 *buf
= SSDATA (*obj
) + offset
;
5441 /* Send some data to process PROC.
5442 BUF is the beginning of the data; LEN is the number of characters.
5443 OBJECT is the Lisp object that the data comes from. If OBJECT is
5444 nil or t, it means that the data comes from C string.
5446 If OBJECT is not nil, the data is encoded by PROC's coding-system
5447 for encoding before it is sent.
5449 This function can evaluate Lisp code and can garbage collect. */
5452 send_process (volatile Lisp_Object proc
, const char *volatile buf
,
5453 volatile ptrdiff_t len
, volatile Lisp_Object object
)
5455 /* Use volatile to protect variables from being clobbered by longjmp. */
5456 struct Lisp_Process
*p
= XPROCESS (proc
);
5458 struct coding_system
*coding
;
5459 void (*volatile old_sigpipe
) (int);
5461 if (p
->raw_status_new
)
5463 if (! EQ (p
->status
, Qrun
))
5464 error ("Process %s not running", SDATA (p
->name
));
5466 error ("Output file descriptor of %s is closed", SDATA (p
->name
));
5468 coding
= proc_encode_coding_system
[p
->outfd
];
5469 Vlast_coding_system_used
= CODING_ID_NAME (coding
->id
);
5471 if ((STRINGP (object
) && STRING_MULTIBYTE (object
))
5472 || (BUFFERP (object
)
5473 && !NILP (BVAR (XBUFFER (object
), enable_multibyte_characters
)))
5476 p
->encode_coding_system
5477 = complement_process_encoding_system (p
->encode_coding_system
);
5478 if (!EQ (Vlast_coding_system_used
, p
->encode_coding_system
))
5480 /* The coding system for encoding was changed to raw-text
5481 because we sent a unibyte text previously. Now we are
5482 sending a multibyte text, thus we must encode it by the
5483 original coding system specified for the current process.
5485 Another reason we come here is that the coding system
5486 was just complemented and a new one was returned by
5487 complement_process_encoding_system. */
5488 setup_coding_system (p
->encode_coding_system
, coding
);
5489 Vlast_coding_system_used
= p
->encode_coding_system
;
5491 coding
->src_multibyte
= 1;
5495 coding
->src_multibyte
= 0;
5496 /* For sending a unibyte text, character code conversion should
5497 not take place but EOL conversion should. So, setup raw-text
5498 or one of the subsidiary if we have not yet done it. */
5499 if (CODING_REQUIRE_ENCODING (coding
))
5501 if (CODING_REQUIRE_FLUSHING (coding
))
5503 /* But, before changing the coding, we must flush out data. */
5504 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
5505 send_process (proc
, "", 0, Qt
);
5506 coding
->mode
&= CODING_MODE_LAST_BLOCK
;
5508 setup_coding_system (raw_text_coding_system
5509 (Vlast_coding_system_used
),
5511 coding
->src_multibyte
= 0;
5514 coding
->dst_multibyte
= 0;
5516 if (CODING_REQUIRE_ENCODING (coding
))
5518 coding
->dst_object
= Qt
;
5519 if (BUFFERP (object
))
5521 ptrdiff_t from_byte
, from
, to
;
5522 ptrdiff_t save_pt
, save_pt_byte
;
5523 struct buffer
*cur
= current_buffer
;
5525 set_buffer_internal (XBUFFER (object
));
5526 save_pt
= PT
, save_pt_byte
= PT_BYTE
;
5528 from_byte
= PTR_BYTE_POS ((unsigned char *) buf
);
5529 from
= BYTE_TO_CHAR (from_byte
);
5530 to
= BYTE_TO_CHAR (from_byte
+ len
);
5531 TEMP_SET_PT_BOTH (from
, from_byte
);
5532 encode_coding_object (coding
, object
, from
, from_byte
,
5533 to
, from_byte
+ len
, Qt
);
5534 TEMP_SET_PT_BOTH (save_pt
, save_pt_byte
);
5535 set_buffer_internal (cur
);
5537 else if (STRINGP (object
))
5539 encode_coding_object (coding
, object
, 0, 0, SCHARS (object
),
5540 SBYTES (object
), Qt
);
5544 coding
->dst_object
= make_unibyte_string (buf
, len
);
5545 coding
->produced
= len
;
5548 len
= coding
->produced
;
5549 object
= coding
->dst_object
;
5550 buf
= SSDATA (object
);
5553 if (pty_max_bytes
== 0)
5555 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5556 pty_max_bytes
= fpathconf (p
->outfd
, _PC_MAX_CANON
);
5557 if (pty_max_bytes
< 0)
5558 pty_max_bytes
= 250;
5560 pty_max_bytes
= 250;
5562 /* Deduct one, to leave space for the eof. */
5566 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5567 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5568 when returning with longjmp despite being declared volatile. */
5569 if (!setjmp (send_process_frame
))
5571 p
= XPROCESS (proc
); /* Repair any setjmp clobbering. */
5572 process_sent_to
= proc
;
5574 /* If there is already data in the write_queue, put the new data
5575 in the back of queue. Otherwise, ignore it. */
5576 if (!NILP (p
->write_queue
))
5577 write_queue_push (p
, object
, buf
, len
, 0);
5579 do /* while !NILP (p->write_queue) */
5581 ptrdiff_t cur_len
= -1;
5582 const char *cur_buf
;
5583 Lisp_Object cur_object
;
5585 /* If write_queue is empty, ignore it. */
5586 if (!write_queue_pop (p
, &cur_object
, &cur_buf
, &cur_len
))
5590 cur_object
= object
;
5595 /* Send this batch, using one or more write calls. */
5596 ptrdiff_t written
= 0;
5597 int outfd
= p
->outfd
;
5598 old_sigpipe
= (void (*) (int)) signal (SIGPIPE
, send_process_trap
);
5599 #ifdef DATAGRAM_SOCKETS
5600 if (DATAGRAM_CHAN_P (outfd
))
5602 rv
= sendto (outfd
, cur_buf
, cur_len
,
5603 0, datagram_address
[outfd
].sa
,
5604 datagram_address
[outfd
].len
);
5607 else if (errno
== EMSGSIZE
)
5609 signal (SIGPIPE
, old_sigpipe
);
5610 report_file_error ("sending datagram",
5611 Fcons (proc
, Qnil
));
5619 written
= emacs_gnutls_write (p
, cur_buf
, cur_len
);
5622 written
= emacs_write (outfd
, cur_buf
, cur_len
);
5623 rv
= (written
? 0 : -1);
5624 #ifdef ADAPTIVE_READ_BUFFERING
5625 if (p
->read_output_delay
> 0
5626 && p
->adaptive_read_buffering
== 1)
5628 p
->read_output_delay
= 0;
5629 process_output_delay_count
--;
5630 p
->read_output_skip
= 0;
5634 signal (SIGPIPE
, old_sigpipe
);
5640 || errno
== EWOULDBLOCK
5646 /* Buffer is full. Wait, accepting input;
5647 that may allow the program
5648 to finish doing output and read more. */
5650 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5651 /* A gross hack to work around a bug in FreeBSD.
5652 In the following sequence, read(2) returns
5656 write(2) 954 bytes, get EAGAIN
5657 read(2) 1024 bytes in process_read_output
5658 read(2) 11 bytes in process_read_output
5660 That is, read(2) returns more bytes than have
5661 ever been written successfully. The 1033 bytes
5662 read are the 1022 bytes written successfully
5663 after processing (for example with CRs added if
5664 the terminal is set up that way which it is
5665 here). The same bytes will be seen again in a
5666 later read(2), without the CRs. */
5668 if (errno
== EAGAIN
)
5671 ioctl (p
->outfd
, TIOCFLUSH
, &flags
);
5673 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5675 /* Put what we should have written in wait_queue. */
5676 write_queue_push (p
, cur_object
, cur_buf
, cur_len
, 1);
5677 wait_reading_process_output (0, 20 * 1000 * 1000,
5678 0, 0, Qnil
, NULL
, 0);
5679 /* Reread queue, to see what is left. */
5683 /* This is a real error. */
5684 report_file_error ("writing to process", Fcons (proc
, Qnil
));
5690 while (!NILP (p
->write_queue
));
5694 signal (SIGPIPE
, old_sigpipe
);
5695 proc
= process_sent_to
;
5696 p
= XPROCESS (proc
);
5697 p
->raw_status_new
= 0;
5698 p
->status
= Fcons (Qexit
, Fcons (make_number (256), Qnil
));
5699 p
->tick
= ++process_tick
;
5700 deactivate_process (proc
);
5701 error ("SIGPIPE raised on process %s; closed it", SDATA (p
->name
));
5705 DEFUN ("process-send-region", Fprocess_send_region
, Sprocess_send_region
,
5707 doc
: /* Send current contents of region as input to PROCESS.
5708 PROCESS may be a process, a buffer, the name of a process or buffer, or
5709 nil, indicating the current buffer's process.
5710 Called from program, takes three arguments, PROCESS, START and END.
5711 If the region is more than 500 characters long,
5712 it is sent in several bunches. This may happen even for shorter regions.
5713 Output from processes can arrive in between bunches. */)
5714 (Lisp_Object process
, Lisp_Object start
, Lisp_Object end
)
5717 ptrdiff_t start1
, end1
;
5719 proc
= get_process (process
);
5720 validate_region (&start
, &end
);
5722 if (XINT (start
) < GPT
&& XINT (end
) > GPT
)
5723 move_gap (XINT (start
));
5725 start1
= CHAR_TO_BYTE (XINT (start
));
5726 end1
= CHAR_TO_BYTE (XINT (end
));
5727 send_process (proc
, (char *) BYTE_POS_ADDR (start1
), end1
- start1
,
5728 Fcurrent_buffer ());
5733 DEFUN ("process-send-string", Fprocess_send_string
, Sprocess_send_string
,
5735 doc
: /* Send PROCESS the contents of STRING as input.
5736 PROCESS may be a process, a buffer, the name of a process or buffer, or
5737 nil, indicating the current buffer's process.
5738 If STRING is more than 500 characters long,
5739 it is sent in several bunches. This may happen even for shorter strings.
5740 Output from processes can arrive in between bunches. */)
5741 (Lisp_Object process
, Lisp_Object string
)
5744 CHECK_STRING (string
);
5745 proc
= get_process (process
);
5746 send_process (proc
, SSDATA (string
),
5747 SBYTES (string
), string
);
5751 /* Return the foreground process group for the tty/pty that
5752 the process P uses. */
5754 emacs_get_tty_pgrp (struct Lisp_Process
*p
)
5759 if (ioctl (p
->infd
, TIOCGPGRP
, &gid
) == -1 && ! NILP (p
->tty_name
))
5762 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5763 master side. Try the slave side. */
5764 fd
= emacs_open (SSDATA (p
->tty_name
), O_RDONLY
, 0);
5768 ioctl (fd
, TIOCGPGRP
, &gid
);
5772 #endif /* defined (TIOCGPGRP ) */
5777 DEFUN ("process-running-child-p", Fprocess_running_child_p
,
5778 Sprocess_running_child_p
, 0, 1, 0,
5779 doc
: /* Return t if PROCESS has given the terminal to a child.
5780 If the operating system does not make it possible to find out,
5781 return t unconditionally. */)
5782 (Lisp_Object process
)
5784 /* Initialize in case ioctl doesn't exist or gives an error,
5785 in a way that will cause returning t. */
5788 struct Lisp_Process
*p
;
5790 proc
= get_process (process
);
5791 p
= XPROCESS (proc
);
5793 if (!EQ (p
->type
, Qreal
))
5794 error ("Process %s is not a subprocess",
5797 error ("Process %s is not active",
5800 gid
= emacs_get_tty_pgrp (p
);
5807 /* send a signal number SIGNO to PROCESS.
5808 If CURRENT_GROUP is t, that means send to the process group
5809 that currently owns the terminal being used to communicate with PROCESS.
5810 This is used for various commands in shell mode.
5811 If CURRENT_GROUP is lambda, that means send to the process group
5812 that currently owns the terminal, but only if it is NOT the shell itself.
5814 If NOMSG is zero, insert signal-announcements into process's buffers
5817 If we can, we try to signal PROCESS by sending control characters
5818 down the pty. This allows us to signal inferiors who have changed
5819 their uid, for which killpg would return an EPERM error. */
5822 process_send_signal (Lisp_Object process
, int signo
, Lisp_Object current_group
,
5826 register struct Lisp_Process
*p
;
5830 proc
= get_process (process
);
5831 p
= XPROCESS (proc
);
5833 if (!EQ (p
->type
, Qreal
))
5834 error ("Process %s is not a subprocess",
5837 error ("Process %s is not active",
5841 current_group
= Qnil
;
5843 /* If we are using pgrps, get a pgrp number and make it negative. */
5844 if (NILP (current_group
))
5845 /* Send the signal to the shell's process group. */
5849 #ifdef SIGNALS_VIA_CHARACTERS
5850 /* If possible, send signals to the entire pgrp
5851 by sending an input character to it. */
5854 cc_t
*sig_char
= NULL
;
5856 tcgetattr (p
->infd
, &t
);
5861 sig_char
= &t
.c_cc
[VINTR
];
5865 sig_char
= &t
.c_cc
[VQUIT
];
5869 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5870 sig_char
= &t
.c_cc
[VSWTCH
];
5872 sig_char
= &t
.c_cc
[VSUSP
];
5877 if (sig_char
&& *sig_char
!= CDISABLE
)
5879 send_process (proc
, (char *) sig_char
, 1, Qnil
);
5882 /* If we can't send the signal with a character,
5883 fall through and send it another way. */
5885 /* The code above may fall through if it can't
5886 handle the signal. */
5887 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5890 /* Get the current pgrp using the tty itself, if we have that.
5891 Otherwise, use the pty to get the pgrp.
5892 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5893 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5894 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5895 His patch indicates that if TIOCGPGRP returns an error, then
5896 we should just assume that p->pid is also the process group id. */
5898 gid
= emacs_get_tty_pgrp (p
);
5901 /* If we can't get the information, assume
5902 the shell owns the tty. */
5905 /* It is not clear whether anything really can set GID to -1.
5906 Perhaps on some system one of those ioctls can or could do so.
5907 Or perhaps this is vestigial. */
5910 #else /* ! defined (TIOCGPGRP ) */
5911 /* Can't select pgrps on this system, so we know that
5912 the child itself heads the pgrp. */
5914 #endif /* ! defined (TIOCGPGRP ) */
5916 /* If current_group is lambda, and the shell owns the terminal,
5917 don't send any signal. */
5918 if (EQ (current_group
, Qlambda
) && gid
== p
->pid
)
5926 p
->raw_status_new
= 0;
5928 p
->tick
= ++process_tick
;
5931 status_notify (NULL
);
5932 redisplay_preserve_echo_area (13);
5935 #endif /* ! defined (SIGCONT) */
5939 flush_pending_output (p
->infd
);
5943 /* If we don't have process groups, send the signal to the immediate
5944 subprocess. That isn't really right, but it's better than any
5945 obvious alternative. */
5948 kill (p
->pid
, signo
);
5952 /* gid may be a pid, or minus a pgrp's number */
5954 if (!NILP (current_group
))
5956 if (ioctl (p
->infd
, TIOCSIGSEND
, signo
) == -1)
5957 EMACS_KILLPG (gid
, signo
);
5964 #else /* ! defined (TIOCSIGSEND) */
5965 EMACS_KILLPG (gid
, signo
);
5966 #endif /* ! defined (TIOCSIGSEND) */
5969 DEFUN ("interrupt-process", Finterrupt_process
, Sinterrupt_process
, 0, 2, 0,
5970 doc
: /* Interrupt process PROCESS.
5971 PROCESS may be a process, a buffer, or the name of a process or buffer.
5972 No arg or nil means current buffer's process.
5973 Second arg CURRENT-GROUP non-nil means send signal to
5974 the current process-group of the process's controlling terminal
5975 rather than to the process's own process group.
5976 If the process is a shell, this means interrupt current subjob
5977 rather than the shell.
5979 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5980 don't send the signal. */)
5981 (Lisp_Object process
, Lisp_Object current_group
)
5983 process_send_signal (process
, SIGINT
, current_group
, 0);
5987 DEFUN ("kill-process", Fkill_process
, Skill_process
, 0, 2, 0,
5988 doc
: /* Kill process PROCESS. May be process or name of one.
5989 See function `interrupt-process' for more details on usage. */)
5990 (Lisp_Object process
, Lisp_Object current_group
)
5992 process_send_signal (process
, SIGKILL
, current_group
, 0);
5996 DEFUN ("quit-process", Fquit_process
, Squit_process
, 0, 2, 0,
5997 doc
: /* Send QUIT signal to process PROCESS. May be process or name of one.
5998 See function `interrupt-process' for more details on usage. */)
5999 (Lisp_Object process
, Lisp_Object current_group
)
6001 process_send_signal (process
, SIGQUIT
, current_group
, 0);
6005 DEFUN ("stop-process", Fstop_process
, Sstop_process
, 0, 2, 0,
6006 doc
: /* Stop process PROCESS. May be process or name of one.
6007 See function `interrupt-process' for more details on usage.
6008 If PROCESS is a network or serial process, inhibit handling of incoming
6010 (Lisp_Object process
, Lisp_Object current_group
)
6012 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6014 struct Lisp_Process
*p
;
6016 p
= XPROCESS (process
);
6017 if (NILP (p
->command
)
6020 FD_CLR (p
->infd
, &input_wait_mask
);
6021 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6027 error ("No SIGTSTP support");
6029 process_send_signal (process
, SIGTSTP
, current_group
, 0);
6034 DEFUN ("continue-process", Fcontinue_process
, Scontinue_process
, 0, 2, 0,
6035 doc
: /* Continue process PROCESS. May be process or name of one.
6036 See function `interrupt-process' for more details on usage.
6037 If PROCESS is a network or serial process, resume handling of incoming
6039 (Lisp_Object process
, Lisp_Object current_group
)
6041 if (PROCESSP (process
) && (NETCONN_P (process
) || SERIALCONN_P (process
)))
6043 struct Lisp_Process
*p
;
6045 p
= XPROCESS (process
);
6046 if (EQ (p
->command
, Qt
)
6048 && (!EQ (p
->filter
, Qt
) || EQ (p
->status
, Qlisten
)))
6050 FD_SET (p
->infd
, &input_wait_mask
);
6051 FD_SET (p
->infd
, &non_keyboard_wait_mask
);
6053 if (fd_info
[ p
->infd
].flags
& FILE_SERIAL
)
6054 PurgeComm (fd_info
[ p
->infd
].hnd
, PURGE_RXABORT
| PURGE_RXCLEAR
);
6055 #else /* not WINDOWSNT */
6056 tcflush (p
->infd
, TCIFLUSH
);
6057 #endif /* not WINDOWSNT */
6063 process_send_signal (process
, SIGCONT
, current_group
, 0);
6065 error ("No SIGCONT support");
6070 DEFUN ("signal-process", Fsignal_process
, Ssignal_process
,
6071 2, 2, "sProcess (name or number): \nnSignal code: ",
6072 doc
: /* Send PROCESS the signal with code SIGCODE.
6073 PROCESS may also be a number specifying the process id of the
6074 process to signal; in this case, the process need not be a child of
6076 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6077 (Lisp_Object process
, Lisp_Object sigcode
)
6081 if (STRINGP (process
))
6083 Lisp_Object tem
= Fget_process (process
);
6086 Lisp_Object process_number
=
6087 string_to_number (SSDATA (process
), 10, 1);
6088 if (INTEGERP (process_number
) || FLOATP (process_number
))
6089 tem
= process_number
;
6093 else if (!NUMBERP (process
))
6094 process
= get_process (process
);
6099 if (NUMBERP (process
))
6100 CONS_TO_INTEGER (process
, pid_t
, pid
);
6103 CHECK_PROCESS (process
);
6104 pid
= XPROCESS (process
)->pid
;
6106 error ("Cannot signal process %s", SDATA (XPROCESS (process
)->name
));
6109 #define parse_signal(NAME, VALUE) \
6110 else if (!xstrcasecmp (name, NAME)) \
6111 XSETINT (sigcode, VALUE)
6113 if (INTEGERP (sigcode
))
6114 CHECK_TYPE_RANGED_INTEGER (int, sigcode
);
6119 CHECK_SYMBOL (sigcode
);
6120 name
= SSDATA (SYMBOL_NAME (sigcode
));
6122 if (!strncmp (name
, "SIG", 3) || !strncmp (name
, "sig", 3))
6128 parse_signal ("usr1", SIGUSR1
);
6131 parse_signal ("usr2", SIGUSR2
);
6134 parse_signal ("term", SIGTERM
);
6137 parse_signal ("hup", SIGHUP
);
6140 parse_signal ("int", SIGINT
);
6143 parse_signal ("quit", SIGQUIT
);
6146 parse_signal ("ill", SIGILL
);
6149 parse_signal ("abrt", SIGABRT
);
6152 parse_signal ("emt", SIGEMT
);
6155 parse_signal ("kill", SIGKILL
);
6158 parse_signal ("fpe", SIGFPE
);
6161 parse_signal ("bus", SIGBUS
);
6164 parse_signal ("segv", SIGSEGV
);
6167 parse_signal ("sys", SIGSYS
);
6170 parse_signal ("pipe", SIGPIPE
);
6173 parse_signal ("alrm", SIGALRM
);
6176 parse_signal ("urg", SIGURG
);
6179 parse_signal ("stop", SIGSTOP
);
6182 parse_signal ("tstp", SIGTSTP
);
6185 parse_signal ("cont", SIGCONT
);
6188 parse_signal ("chld", SIGCHLD
);
6191 parse_signal ("ttin", SIGTTIN
);
6194 parse_signal ("ttou", SIGTTOU
);
6197 parse_signal ("io", SIGIO
);
6200 parse_signal ("xcpu", SIGXCPU
);
6203 parse_signal ("xfsz", SIGXFSZ
);
6206 parse_signal ("vtalrm", SIGVTALRM
);
6209 parse_signal ("prof", SIGPROF
);
6212 parse_signal ("winch", SIGWINCH
);
6215 parse_signal ("info", SIGINFO
);
6218 error ("Undefined signal name %s", name
);
6223 return make_number (kill (pid
, XINT (sigcode
)));
6226 DEFUN ("process-send-eof", Fprocess_send_eof
, Sprocess_send_eof
, 0, 1, 0,
6227 doc
: /* Make PROCESS see end-of-file in its input.
6228 EOF comes after any text already sent to it.
6229 PROCESS may be a process, a buffer, the name of a process or buffer, or
6230 nil, indicating the current buffer's process.
6231 If PROCESS is a network connection, or is a process communicating
6232 through a pipe (as opposed to a pty), then you cannot send any more
6233 text to PROCESS after you call this function.
6234 If PROCESS is a serial process, wait until all output written to the
6235 process has been transmitted to the serial port. */)
6236 (Lisp_Object process
)
6239 struct coding_system
*coding
;
6241 if (DATAGRAM_CONN_P (process
))
6244 proc
= get_process (process
);
6245 coding
= proc_encode_coding_system
[XPROCESS (proc
)->outfd
];
6247 /* Make sure the process is really alive. */
6248 if (XPROCESS (proc
)->raw_status_new
)
6249 update_status (XPROCESS (proc
));
6250 if (! EQ (XPROCESS (proc
)->status
, Qrun
))
6251 error ("Process %s not running", SDATA (XPROCESS (proc
)->name
));
6253 if (CODING_REQUIRE_FLUSHING (coding
))
6255 coding
->mode
|= CODING_MODE_LAST_BLOCK
;
6256 send_process (proc
, "", 0, Qnil
);
6259 if (XPROCESS (proc
)->pty_flag
)
6260 send_process (proc
, "\004", 1, Qnil
);
6261 else if (EQ (XPROCESS (proc
)->type
, Qserial
))
6264 if (tcdrain (XPROCESS (proc
)->outfd
) != 0)
6265 error ("tcdrain() failed: %s", emacs_strerror (errno
));
6266 #endif /* not WINDOWSNT */
6267 /* Do nothing on Windows because writes are blocking. */
6271 int old_outfd
, new_outfd
;
6273 #ifdef HAVE_SHUTDOWN
6274 /* If this is a network connection, or socketpair is used
6275 for communication with the subprocess, call shutdown to cause EOF.
6276 (In some old system, shutdown to socketpair doesn't work.
6277 Then we just can't win.) */
6278 if (EQ (XPROCESS (proc
)->type
, Qnetwork
)
6279 || XPROCESS (proc
)->outfd
== XPROCESS (proc
)->infd
)
6280 shutdown (XPROCESS (proc
)->outfd
, 1);
6281 /* In case of socketpair, outfd == infd, so don't close it. */
6282 if (XPROCESS (proc
)->outfd
!= XPROCESS (proc
)->infd
)
6283 emacs_close (XPROCESS (proc
)->outfd
);
6284 #else /* not HAVE_SHUTDOWN */
6285 emacs_close (XPROCESS (proc
)->outfd
);
6286 #endif /* not HAVE_SHUTDOWN */
6287 new_outfd
= emacs_open (NULL_DEVICE
, O_WRONLY
, 0);
6290 old_outfd
= XPROCESS (proc
)->outfd
;
6292 if (!proc_encode_coding_system
[new_outfd
])
6293 proc_encode_coding_system
[new_outfd
]
6294 = (struct coding_system
*) xmalloc (sizeof (struct coding_system
));
6295 memcpy (proc_encode_coding_system
[new_outfd
],
6296 proc_encode_coding_system
[old_outfd
],
6297 sizeof (struct coding_system
));
6298 memset (proc_encode_coding_system
[old_outfd
], 0,
6299 sizeof (struct coding_system
));
6301 XPROCESS (proc
)->outfd
= new_outfd
;
6306 /* On receipt of a signal that a child status has changed, loop asking
6307 about children with changed statuses until the system says there
6310 All we do is change the status; we do not run sentinels or print
6311 notifications. That is saved for the next time keyboard input is
6312 done, in order to avoid timing errors.
6314 ** WARNING: this can be called during garbage collection.
6315 Therefore, it must not be fooled by the presence of mark bits in
6318 ** USG WARNING: Although it is not obvious from the documentation
6319 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6320 signal() before executing at least one wait(), otherwise the
6321 handler will be called again, resulting in an infinite loop. The
6322 relevant portion of the documentation reads "SIGCLD signals will be
6323 queued and the signal-catching function will be continually
6324 reentered until the queue is empty". Invoking signal() causes the
6325 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6328 ** Malloc WARNING: This should never call malloc either directly or
6329 indirectly; if it does, that is a bug */
6333 sigchld_handler (int signo
)
6335 int old_errno
= errno
;
6337 struct Lisp_Process
*p
;
6339 SIGNAL_THREAD_CHECK (signo
);
6350 #endif /* no WUNTRACED */
6351 /* Keep trying to get a status until we get a definitive result. */
6355 pid
= wait3 (&w
, WNOHANG
| WUNTRACED
, 0);
6357 while (pid
< 0 && errno
== EINTR
);
6361 /* PID == 0 means no processes found, PID == -1 means a real
6362 failure. We have done all our job, so return. */
6369 #endif /* no WNOHANG */
6371 /* Find the process that signaled us, and record its status. */
6373 /* The process can have been deleted by Fdelete_process. */
6374 for (tail
= deleted_pid_list
; CONSP (tail
); tail
= XCDR (tail
))
6376 Lisp_Object xpid
= XCAR (tail
);
6377 if ((INTEGERP (xpid
) && pid
== XINT (xpid
))
6378 || (FLOATP (xpid
) && pid
== XFLOAT_DATA (xpid
)))
6380 XSETCAR (tail
, Qnil
);
6381 goto sigchld_end_of_loop
;
6385 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6387 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6389 proc
= XCDR (XCAR (tail
));
6390 p
= XPROCESS (proc
);
6391 if (EQ (p
->type
, Qreal
) && p
->pid
== pid
)
6396 /* Look for an asynchronous process whose pid hasn't been filled
6399 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6401 proc
= XCDR (XCAR (tail
));
6402 p
= XPROCESS (proc
);
6408 /* Change the status of the process that was found. */
6411 int clear_desc_flag
= 0;
6413 p
->tick
= ++process_tick
;
6415 p
->raw_status_new
= 1;
6417 /* If process has terminated, stop waiting for its output. */
6418 if ((WIFSIGNALED (w
) || WIFEXITED (w
))
6420 clear_desc_flag
= 1;
6422 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6423 if (clear_desc_flag
)
6425 FD_CLR (p
->infd
, &input_wait_mask
);
6426 FD_CLR (p
->infd
, &non_keyboard_wait_mask
);
6429 /* Tell wait_reading_process_output that it needs to wake up and
6431 if (input_available_clear_time
)
6432 EMACS_SET_SECS_USECS (*input_available_clear_time
, 0, 0);
6435 /* There was no asynchronous process found for that pid: we have
6436 a synchronous process. */
6439 synch_process_alive
= 0;
6441 /* Report the status of the synchronous process. */
6443 synch_process_retcode
= WRETCODE (w
);
6444 else if (WIFSIGNALED (w
))
6445 synch_process_termsig
= WTERMSIG (w
);
6447 /* Tell wait_reading_process_output that it needs to wake up and
6449 if (input_available_clear_time
)
6450 EMACS_SET_SECS_USECS (*input_available_clear_time
, 0, 0);
6453 sigchld_end_of_loop
:
6456 /* On some systems, we must return right away.
6457 If any more processes want to signal us, we will
6459 Otherwise (on systems that have WNOHANG), loop around
6460 to use up all the processes that have something to tell us. */
6461 #if (defined WINDOWSNT \
6462 || (defined USG && !defined GNU_LINUX \
6463 && !(defined HPUX && defined WNOHANG)))
6466 #endif /* USG, but not HPUX with WNOHANG */
6469 #endif /* SIGCHLD */
6473 exec_sentinel_unwind (Lisp_Object data
)
6475 XPROCESS (XCAR (data
))->sentinel
= XCDR (data
);
6480 exec_sentinel_error_handler (Lisp_Object error_val
)
6482 cmd_error_internal (error_val
, "error in process sentinel: ");
6484 update_echo_area ();
6485 Fsleep_for (make_number (2), Qnil
);
6490 exec_sentinel (Lisp_Object proc
, Lisp_Object reason
)
6492 Lisp_Object sentinel
, odeactivate
;
6493 register struct Lisp_Process
*p
= XPROCESS (proc
);
6494 ptrdiff_t count
= SPECPDL_INDEX ();
6495 int outer_running_asynch_code
= running_asynch_code
;
6496 int waiting
= waiting_for_user_input_p
;
6498 if (inhibit_sentinels
)
6501 /* No need to gcpro these, because all we do with them later
6502 is test them for EQness, and none of them should be a string. */
6503 odeactivate
= Vdeactivate_mark
;
6505 Lisp_Object obuffer
, okeymap
;
6506 XSETBUFFER (obuffer
, current_buffer
);
6507 okeymap
= BVAR (current_buffer
, keymap
);
6510 /* There's no good reason to let sentinels change the current
6511 buffer, and many callers of accept-process-output, sit-for, and
6512 friends don't expect current-buffer to be changed from under them. */
6513 record_unwind_protect (set_buffer_if_live
, Fcurrent_buffer ());
6515 sentinel
= p
->sentinel
;
6516 if (NILP (sentinel
))
6519 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6520 assure that it gets restored no matter how the sentinel exits. */
6522 record_unwind_protect (exec_sentinel_unwind
, Fcons (proc
, sentinel
));
6523 /* Inhibit quit so that random quits don't screw up a running filter. */
6524 specbind (Qinhibit_quit
, Qt
);
6525 specbind (Qlast_nonmenu_event
, Qt
); /* Why? --Stef */
6527 /* In case we get recursively called,
6528 and we already saved the match data nonrecursively,
6529 save the same match data in safely recursive fashion. */
6530 if (outer_running_asynch_code
)
6533 tem
= Fmatch_data (Qnil
, Qnil
, Qnil
);
6534 restore_search_regs ();
6535 record_unwind_save_match_data ();
6536 Fset_match_data (tem
, Qt
);
6539 /* For speed, if a search happens within this code,
6540 save the match data in a special nonrecursive fashion. */
6541 running_asynch_code
= 1;
6543 internal_condition_case_1 (read_process_output_call
,
6545 Fcons (proc
, Fcons (reason
, Qnil
))),
6546 !NILP (Vdebug_on_error
) ? Qnil
: Qerror
,
6547 exec_sentinel_error_handler
);
6549 /* If we saved the match data nonrecursively, restore it now. */
6550 restore_search_regs ();
6551 running_asynch_code
= outer_running_asynch_code
;
6553 Vdeactivate_mark
= odeactivate
;
6555 /* Restore waiting_for_user_input_p as it was
6556 when we were called, in case the filter clobbered it. */
6557 waiting_for_user_input_p
= waiting
;
6560 if (! EQ (Fcurrent_buffer (), obuffer
)
6561 || ! EQ (current_buffer
->keymap
, okeymap
))
6563 /* But do it only if the caller is actually going to read events.
6564 Otherwise there's no need to make him wake up, and it could
6565 cause trouble (for example it would make sit_for return). */
6566 if (waiting_for_user_input_p
== -1)
6567 record_asynch_buffer_change ();
6569 unbind_to (count
, Qnil
);
6572 /* Report all recent events of a change in process status
6573 (either run the sentinel or output a message).
6574 This is usually done while Emacs is waiting for keyboard input
6575 but can be done at other times. */
6578 status_notify (struct Lisp_Process
*deleting_process
)
6580 register Lisp_Object proc
, buffer
;
6581 Lisp_Object tail
, msg
;
6582 struct gcpro gcpro1
, gcpro2
;
6586 /* We need to gcpro tail; if read_process_output calls a filter
6587 which deletes a process and removes the cons to which tail points
6588 from Vprocess_alist, and then causes a GC, tail is an unprotected
6592 /* Set this now, so that if new processes are created by sentinels
6593 that we run, we get called again to handle their status changes. */
6594 update_tick
= process_tick
;
6596 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
6599 register struct Lisp_Process
*p
;
6601 proc
= Fcdr (XCAR (tail
));
6602 p
= XPROCESS (proc
);
6604 if (p
->tick
!= p
->update_tick
)
6606 p
->update_tick
= p
->tick
;
6608 /* If process is still active, read any output that remains. */
6609 while (! EQ (p
->filter
, Qt
)
6610 && ! EQ (p
->status
, Qconnect
)
6611 && ! EQ (p
->status
, Qlisten
)
6612 /* Network or serial process not stopped: */
6613 && ! EQ (p
->command
, Qt
)
6615 && p
!= deleting_process
6616 && read_process_output (proc
, p
->infd
) > 0);
6620 /* Get the text to use for the message. */
6621 if (p
->raw_status_new
)
6623 msg
= status_message (p
);
6625 /* If process is terminated, deactivate it or delete it. */
6627 if (CONSP (p
->status
))
6628 symbol
= XCAR (p
->status
);
6630 if (EQ (symbol
, Qsignal
) || EQ (symbol
, Qexit
)
6631 || EQ (symbol
, Qclosed
))
6633 if (delete_exited_processes
)
6634 remove_process (proc
);
6636 deactivate_process (proc
);
6639 /* The actions above may have further incremented p->tick.
6640 So set p->update_tick again
6641 so that an error in the sentinel will not cause
6642 this code to be run again. */
6643 p
->update_tick
= p
->tick
;
6644 /* Now output the message suitably. */
6645 if (!NILP (p
->sentinel
))
6646 exec_sentinel (proc
, msg
);
6647 /* Don't bother with a message in the buffer
6648 when a process becomes runnable. */
6649 else if (!EQ (symbol
, Qrun
) && !NILP (buffer
))
6652 struct buffer
*old
= current_buffer
;
6653 ptrdiff_t opoint
, opoint_byte
;
6654 ptrdiff_t before
, before_byte
;
6656 /* Avoid error if buffer is deleted
6657 (probably that's why the process is dead, too) */
6658 if (NILP (BVAR (XBUFFER (buffer
), name
)))
6660 Fset_buffer (buffer
);
6663 opoint_byte
= PT_BYTE
;
6664 /* Insert new output into buffer
6665 at the current end-of-output marker,
6666 thus preserving logical ordering of input and output. */
6667 if (XMARKER (p
->mark
)->buffer
)
6668 Fgoto_char (p
->mark
);
6670 SET_PT_BOTH (ZV
, ZV_BYTE
);
6673 before_byte
= PT_BYTE
;
6675 tem
= BVAR (current_buffer
, read_only
);
6676 BVAR (current_buffer
, read_only
) = Qnil
;
6677 insert_string ("\nProcess ");
6678 Finsert (1, &p
->name
);
6679 insert_string (" ");
6681 BVAR (current_buffer
, read_only
) = tem
;
6682 set_marker_both (p
->mark
, p
->buffer
, PT
, PT_BYTE
);
6684 if (opoint
>= before
)
6685 SET_PT_BOTH (opoint
+ (PT
- before
),
6686 opoint_byte
+ (PT_BYTE
- before_byte
));
6688 SET_PT_BOTH (opoint
, opoint_byte
);
6690 set_buffer_internal (old
);
6695 update_mode_lines
++; /* in case buffers use %s in mode-line-format */
6700 DEFUN ("set-process-coding-system", Fset_process_coding_system
,
6701 Sset_process_coding_system
, 1, 3, 0,
6702 doc
: /* Set coding systems of PROCESS to DECODING and ENCODING.
6703 DECODING will be used to decode subprocess output and ENCODING to
6704 encode subprocess input. */)
6705 (register Lisp_Object process
, Lisp_Object decoding
, Lisp_Object encoding
)
6707 register struct Lisp_Process
*p
;
6709 CHECK_PROCESS (process
);
6710 p
= XPROCESS (process
);
6712 error ("Input file descriptor of %s closed", SDATA (p
->name
));
6714 error ("Output file descriptor of %s closed", SDATA (p
->name
));
6715 Fcheck_coding_system (decoding
);
6716 Fcheck_coding_system (encoding
);
6717 encoding
= coding_inherit_eol_type (encoding
, Qnil
);
6718 p
->decode_coding_system
= decoding
;
6719 p
->encode_coding_system
= encoding
;
6720 setup_process_coding_systems (process
);
6725 DEFUN ("process-coding-system",
6726 Fprocess_coding_system
, Sprocess_coding_system
, 1, 1, 0,
6727 doc
: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6728 (register Lisp_Object process
)
6730 CHECK_PROCESS (process
);
6731 return Fcons (XPROCESS (process
)->decode_coding_system
,
6732 XPROCESS (process
)->encode_coding_system
);
6735 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte
,
6736 Sset_process_filter_multibyte
, 2, 2, 0,
6737 doc
: /* Set multibyteness of the strings given to PROCESS's filter.
6738 If FLAG is non-nil, the filter is given multibyte strings.
6739 If FLAG is nil, the filter is given unibyte strings. In this case,
6740 all character code conversion except for end-of-line conversion is
6742 (Lisp_Object process
, Lisp_Object flag
)
6744 register struct Lisp_Process
*p
;
6746 CHECK_PROCESS (process
);
6747 p
= XPROCESS (process
);
6749 p
->decode_coding_system
= raw_text_coding_system (p
->decode_coding_system
);
6750 setup_process_coding_systems (process
);
6755 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p
,
6756 Sprocess_filter_multibyte_p
, 1, 1, 0,
6757 doc
: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6758 (Lisp_Object process
)
6760 register struct Lisp_Process
*p
;
6761 struct coding_system
*coding
;
6763 CHECK_PROCESS (process
);
6764 p
= XPROCESS (process
);
6765 coding
= proc_decode_coding_system
[p
->infd
];
6766 return (CODING_FOR_UNIBYTE (coding
) ? Qnil
: Qt
);
6775 add_gpm_wait_descriptor (int desc
)
6777 add_keyboard_wait_descriptor (desc
);
6781 delete_gpm_wait_descriptor (int desc
)
6783 delete_keyboard_wait_descriptor (desc
);
6790 /* Return nonzero if *MASK has a bit set
6791 that corresponds to one of the keyboard input descriptors. */
6794 keyboard_bit_set (fd_set
*mask
)
6798 for (fd
= 0; fd
<= max_input_desc
; fd
++)
6799 if (FD_ISSET (fd
, mask
) && FD_ISSET (fd
, &input_wait_mask
)
6800 && !FD_ISSET (fd
, &non_keyboard_wait_mask
))
6807 #else /* not subprocesses */
6809 /* Defined on msdos.c. */
6810 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
6813 /* Implementation of wait_reading_process_output, assuming that there
6814 are no subprocesses. Used only by the MS-DOS build.
6816 Wait for timeout to elapse and/or keyboard input to be available.
6820 If negative, gobble data immediately available but don't wait for any.
6823 an additional duration to wait, measured in nanoseconds
6824 If TIME_LIMIT is zero, then:
6825 If NSECS == 0, there is no limit.
6826 If NSECS > 0, the timeout consists of NSECS only.
6827 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6829 READ_KBD is a Lisp_Object:
6830 0 to ignore keyboard input, or
6831 1 to return when input is available, or
6832 -1 means caller will actually read the input, so don't throw to
6835 see full version for other parameters. We know that wait_proc will
6836 always be NULL, since `subprocesses' isn't defined.
6838 DO_DISPLAY != 0 means redisplay should be done to show subprocess
6839 output that arrives.
6841 Return true if we received input from any process. */
6844 wait_reading_process_output (intmax_t time_limit
, int nsecs
, int read_kbd
,
6846 Lisp_Object wait_for_cell
,
6847 struct Lisp_Process
*wait_proc
, int just_wait_proc
)
6850 EMACS_TIME end_time
, timeout
;
6851 SELECT_TYPE waitchannels
;
6859 else if (TYPE_MAXIMUM (time_t) < time_limit
)
6860 time_limit
= TYPE_MAXIMUM (time_t);
6862 /* What does time_limit really mean? */
6863 if (time_limit
|| nsecs
) /* FIXME: what if negative? */
6865 EMACS_GET_TIME (end_time
);
6866 EMACS_SET_SECS_NSECS (timeout
, time_limit
, nsecs
);
6867 EMACS_ADD_TIME (end_time
, end_time
, timeout
);
6870 /* Turn off periodic alarms (in case they are in use)
6871 and then turn off any other atimers,
6872 because the select emulator uses alarms. */
6874 turn_on_atimers (0);
6878 int timeout_reduced_for_timers
= 0;
6880 /* If calling from keyboard input, do not quit
6881 since we want to return C-g as an input character.
6882 Otherwise, do pending quit if requested. */
6886 /* Exit now if the cell we're waiting for became non-nil. */
6887 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
6890 /* Compute time from now till when time limit is up */
6891 /* Exit if already run out */
6894 /* -1 specified for timeout means
6895 gobble output available now
6896 but don't wait at all. */
6898 EMACS_SET_SECS_USECS (timeout
, 0, 0);
6900 else if (time_limit
|| nsecs
)
6902 EMACS_GET_TIME (timeout
);
6903 if (EMACS_TIME_LE (end_time
, timeout
))
6905 EMACS_SUB_TIME (timeout
, end_time
, timeout
);
6909 EMACS_SET_SECS_USECS (timeout
, 100000, 0);
6912 /* If our caller will not immediately handle keyboard events,
6913 run timer events directly.
6914 (Callers that will immediately read keyboard events
6915 call timer_delay on their own.) */
6916 if (NILP (wait_for_cell
))
6918 EMACS_TIME timer_delay
;
6922 int old_timers_run
= timers_run
;
6923 timer_delay
= timer_check ();
6924 if (timers_run
!= old_timers_run
&& do_display
)
6925 /* We must retry, since a timer may have requeued itself
6926 and that could alter the time delay. */
6927 redisplay_preserve_echo_area (14);
6931 while (!detect_input_pending ());
6933 /* If there is unread keyboard input, also return. */
6935 && requeued_events_pending_p ())
6938 if (EMACS_TIME_VALID_P (timer_delay
) && 0 <= nsecs
)
6940 if (EMACS_TIME_LT (timer_delay
, timeout
))
6942 timeout
= timer_delay
;
6943 timeout_reduced_for_timers
= 1;
6948 /* Cause C-g and alarm signals to take immediate action,
6949 and cause input available signals to zero out timeout. */
6951 set_waiting_for_input (&timeout
);
6953 /* Wait till there is something to do. */
6955 if (! read_kbd
&& NILP (wait_for_cell
))
6956 FD_ZERO (&waitchannels
);
6958 FD_SET (0, &waitchannels
);
6960 /* If a frame has been newly mapped and needs updating,
6961 reprocess its display stuff. */
6962 if (frame_garbaged
&& do_display
)
6964 clear_waiting_for_input ();
6965 redisplay_preserve_echo_area (15);
6967 set_waiting_for_input (&timeout
);
6970 if (read_kbd
&& detect_input_pending ())
6973 FD_ZERO (&waitchannels
);
6976 nfds
= pselect (1, &waitchannels
, NULL
, NULL
, &timeout
, NULL
);
6980 /* Make C-g and alarm signals set flags again */
6981 clear_waiting_for_input ();
6983 /* If we woke up due to SIGWINCH, actually change size now. */
6984 do_pending_window_change (0);
6986 if ((time_limit
|| nsecs
) && nfds
== 0 && ! timeout_reduced_for_timers
)
6987 /* We waited the full specified time, so return now. */
6992 /* If the system call was interrupted, then go around the
6994 if (xerrno
== EINTR
)
6995 FD_ZERO (&waitchannels
);
6997 error ("select error: %s", emacs_strerror (xerrno
));
7000 /* Check for keyboard input */
7003 && detect_input_pending_run_timers (do_display
))
7005 swallow_events (do_display
);
7006 if (detect_input_pending_run_timers (do_display
))
7010 /* If there is unread keyboard input, also return. */
7012 && requeued_events_pending_p ())
7015 /* If wait_for_cell. check for keyboard input
7016 but don't run any timers.
7017 ??? (It seems wrong to me to check for keyboard
7018 input at all when wait_for_cell, but the code
7019 has been this way since July 1994.
7020 Try changing this after version 19.31.) */
7021 if (! NILP (wait_for_cell
)
7022 && detect_input_pending ())
7024 swallow_events (do_display
);
7025 if (detect_input_pending ())
7029 /* Exit now if the cell we're waiting for became non-nil. */
7030 if (! NILP (wait_for_cell
) && ! NILP (XCAR (wait_for_cell
)))
7039 #endif /* not subprocesses */
7041 /* The following functions are needed even if async subprocesses are
7042 not supported. Some of them are no-op stubs in that case. */
7044 /* Add DESC to the set of keyboard input descriptors. */
7047 add_keyboard_wait_descriptor (int desc
)
7049 #ifdef subprocesses /* actually means "not MSDOS" */
7050 FD_SET (desc
, &input_wait_mask
);
7051 FD_SET (desc
, &non_process_wait_mask
);
7052 if (desc
> max_input_desc
)
7053 max_input_desc
= desc
;
7057 /* From now on, do not expect DESC to give keyboard input. */
7060 delete_keyboard_wait_descriptor (int desc
)
7064 int lim
= max_input_desc
;
7066 FD_CLR (desc
, &input_wait_mask
);
7067 FD_CLR (desc
, &non_process_wait_mask
);
7069 if (desc
== max_input_desc
)
7070 for (fd
= 0; fd
< lim
; fd
++)
7071 if (FD_ISSET (fd
, &input_wait_mask
) || FD_ISSET (fd
, &write_mask
))
7072 max_input_desc
= fd
;
7076 /* Setup coding systems of PROCESS. */
7079 setup_process_coding_systems (Lisp_Object process
)
7082 struct Lisp_Process
*p
= XPROCESS (process
);
7084 int outch
= p
->outfd
;
7085 Lisp_Object coding_system
;
7087 if (inch
< 0 || outch
< 0)
7090 if (!proc_decode_coding_system
[inch
])
7091 proc_decode_coding_system
[inch
]
7092 = (struct coding_system
*) xmalloc (sizeof (struct coding_system
));
7093 coding_system
= p
->decode_coding_system
;
7094 if (! NILP (p
->filter
))
7096 else if (BUFFERP (p
->buffer
))
7098 if (NILP (BVAR (XBUFFER (p
->buffer
), enable_multibyte_characters
)))
7099 coding_system
= raw_text_coding_system (coding_system
);
7101 setup_coding_system (coding_system
, proc_decode_coding_system
[inch
]);
7103 if (!proc_encode_coding_system
[outch
])
7104 proc_encode_coding_system
[outch
]
7105 = (struct coding_system
*) xmalloc (sizeof (struct coding_system
));
7106 setup_coding_system (p
->encode_coding_system
,
7107 proc_encode_coding_system
[outch
]);
7111 /* Close all descriptors currently in use for communication
7112 with subprocess. This is used in a newly-forked subprocess
7113 to get rid of irrelevant descriptors. */
7116 close_process_descs (void)
7120 for (i
= 0; i
< MAXDESC
; i
++)
7122 Lisp_Object process
;
7123 process
= chan_process
[i
];
7124 if (!NILP (process
))
7126 int in
= XPROCESS (process
)->infd
;
7127 int out
= XPROCESS (process
)->outfd
;
7130 if (out
>= 0 && in
!= out
)
7137 DEFUN ("get-buffer-process", Fget_buffer_process
, Sget_buffer_process
, 1, 1, 0,
7138 doc
: /* Return the (or a) process associated with BUFFER.
7139 BUFFER may be a buffer or the name of one. */)
7140 (register Lisp_Object buffer
)
7143 register Lisp_Object buf
, tail
, proc
;
7145 if (NILP (buffer
)) return Qnil
;
7146 buf
= Fget_buffer (buffer
);
7147 if (NILP (buf
)) return Qnil
;
7149 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
7151 proc
= Fcdr (XCAR (tail
));
7152 if (PROCESSP (proc
) && EQ (XPROCESS (proc
)->buffer
, buf
))
7155 #endif /* subprocesses */
7159 DEFUN ("process-inherit-coding-system-flag",
7160 Fprocess_inherit_coding_system_flag
, Sprocess_inherit_coding_system_flag
,
7162 doc
: /* Return the value of inherit-coding-system flag for PROCESS.
7163 If this flag is t, `buffer-file-coding-system' of the buffer
7164 associated with PROCESS will inherit the coding system used to decode
7165 the process output. */)
7166 (register Lisp_Object process
)
7169 CHECK_PROCESS (process
);
7170 return XPROCESS (process
)->inherit_coding_system_flag
? Qt
: Qnil
;
7172 /* Ignore the argument and return the value of
7173 inherit-process-coding-system. */
7174 return inherit_process_coding_system
? Qt
: Qnil
;
7178 /* Kill all processes associated with `buffer'.
7179 If `buffer' is nil, kill all processes */
7182 kill_buffer_processes (Lisp_Object buffer
)
7185 Lisp_Object tail
, proc
;
7187 for (tail
= Vprocess_alist
; CONSP (tail
); tail
= XCDR (tail
))
7189 proc
= XCDR (XCAR (tail
));
7191 && (NILP (buffer
) || EQ (XPROCESS (proc
)->buffer
, buffer
)))
7193 if (NETCONN_P (proc
) || SERIALCONN_P (proc
))
7194 Fdelete_process (proc
);
7195 else if (XPROCESS (proc
)->infd
>= 0)
7196 process_send_signal (proc
, SIGHUP
, Qnil
, 1);
7199 #else /* subprocesses */
7200 /* Since we have no subprocesses, this does nothing. */
7201 #endif /* subprocesses */
7204 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p
,
7205 Swaiting_for_user_input_p
, 0, 0, 0,
7206 doc
: /* Returns non-nil if Emacs is waiting for input from the user.
7207 This is intended for use by asynchronous process output filters and sentinels. */)
7211 return (waiting_for_user_input_p
? Qt
: Qnil
);
7217 /* Stop reading input from keyboard sources. */
7220 hold_keyboard_input (void)
7225 /* Resume reading input from keyboard sources. */
7228 unhold_keyboard_input (void)
7233 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7236 kbd_on_hold_p (void)
7238 return kbd_is_on_hold
;
7242 /* Enumeration of and access to system processes a-la ps(1). */
7244 DEFUN ("list-system-processes", Flist_system_processes
, Slist_system_processes
,
7246 doc
: /* Return a list of numerical process IDs of all running processes.
7247 If this functionality is unsupported, return nil.
7249 See `process-attributes' for getting attributes of a process given its ID. */)
7252 return list_system_processes ();
7255 DEFUN ("process-attributes", Fprocess_attributes
,
7256 Sprocess_attributes
, 1, 1, 0,
7257 doc
: /* Return attributes of the process given by its PID, a number.
7259 Value is an alist where each element is a cons cell of the form
7263 If this functionality is unsupported, the value is nil.
7265 See `list-system-processes' for getting a list of all process IDs.
7267 The KEYs of the attributes that this function may return are listed
7268 below, together with the type of the associated VALUE (in parentheses).
7269 Not all platforms support all of these attributes; unsupported
7270 attributes will not appear in the returned alist.
7271 Unless explicitly indicated otherwise, numbers can have either
7272 integer or floating point values.
7274 euid -- Effective user User ID of the process (number)
7275 user -- User name corresponding to euid (string)
7276 egid -- Effective user Group ID of the process (number)
7277 group -- Group name corresponding to egid (string)
7278 comm -- Command name (executable name only) (string)
7279 state -- Process state code, such as "S", "R", or "T" (string)
7280 ppid -- Parent process ID (number)
7281 pgrp -- Process group ID (number)
7282 sess -- Session ID, i.e. process ID of session leader (number)
7283 ttname -- Controlling tty name (string)
7284 tpgid -- ID of foreground process group on the process's tty (number)
7285 minflt -- number of minor page faults (number)
7286 majflt -- number of major page faults (number)
7287 cminflt -- cumulative number of minor page faults (number)
7288 cmajflt -- cumulative number of major page faults (number)
7289 utime -- user time used by the process, in (current-time) format,
7290 which is a list of integers (HIGH LOW USEC PSEC)
7291 stime -- system time used by the process (current-time)
7292 time -- sum of utime and stime (current-time)
7293 cutime -- user time used by the process and its children (current-time)
7294 cstime -- system time used by the process and its children (current-time)
7295 ctime -- sum of cutime and cstime (current-time)
7296 pri -- priority of the process (number)
7297 nice -- nice value of the process (number)
7298 thcount -- process thread count (number)
7299 start -- time the process started (current-time)
7300 vsize -- virtual memory size of the process in KB's (number)
7301 rss -- resident set size of the process in KB's (number)
7302 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7303 pcpu -- percents of CPU time used by the process (floating-point number)
7304 pmem -- percents of total physical memory used by process's resident set
7305 (floating-point number)
7306 args -- command line which invoked the process (string). */)
7309 return system_process_attributes (pid
);
7319 inhibit_sentinels
= 0;
7323 if (! noninteractive
|| initialized
)
7325 signal (SIGCHLD
, sigchld_handler
);
7328 FD_ZERO (&input_wait_mask
);
7329 FD_ZERO (&non_keyboard_wait_mask
);
7330 FD_ZERO (&non_process_wait_mask
);
7331 FD_ZERO (&write_mask
);
7332 max_process_desc
= 0;
7333 memset (fd_callback_info
, 0, sizeof (fd_callback_info
));
7335 #ifdef NON_BLOCKING_CONNECT
7336 FD_ZERO (&connect_wait_mask
);
7337 num_pending_connects
= 0;
7340 #ifdef ADAPTIVE_READ_BUFFERING
7341 process_output_delay_count
= 0;
7342 process_output_skip
= 0;
7345 /* Don't do this, it caused infinite select loops. The display
7346 method should call add_keyboard_wait_descriptor on stdin if it
7349 FD_SET (0, &input_wait_mask
);
7352 Vprocess_alist
= Qnil
;
7354 deleted_pid_list
= Qnil
;
7356 for (i
= 0; i
< MAXDESC
; i
++)
7358 chan_process
[i
] = Qnil
;
7359 proc_buffered_char
[i
] = -1;
7361 memset (proc_decode_coding_system
, 0, sizeof proc_decode_coding_system
);
7362 memset (proc_encode_coding_system
, 0, sizeof proc_encode_coding_system
);
7363 #ifdef DATAGRAM_SOCKETS
7364 memset (datagram_address
, 0, sizeof datagram_address
);
7368 Lisp_Object subfeatures
= Qnil
;
7369 const struct socket_options
*sopt
;
7371 #define ADD_SUBFEATURE(key, val) \
7372 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7374 #ifdef NON_BLOCKING_CONNECT
7375 ADD_SUBFEATURE (QCnowait
, Qt
);
7377 #ifdef DATAGRAM_SOCKETS
7378 ADD_SUBFEATURE (QCtype
, Qdatagram
);
7380 #ifdef HAVE_SEQPACKET
7381 ADD_SUBFEATURE (QCtype
, Qseqpacket
);
7383 #ifdef HAVE_LOCAL_SOCKETS
7384 ADD_SUBFEATURE (QCfamily
, Qlocal
);
7386 ADD_SUBFEATURE (QCfamily
, Qipv4
);
7388 ADD_SUBFEATURE (QCfamily
, Qipv6
);
7390 #ifdef HAVE_GETSOCKNAME
7391 ADD_SUBFEATURE (QCservice
, Qt
);
7393 #if defined (O_NONBLOCK) || defined (O_NDELAY)
7394 ADD_SUBFEATURE (QCserver
, Qt
);
7397 for (sopt
= socket_options
; sopt
->name
; sopt
++)
7398 subfeatures
= pure_cons (intern_c_string (sopt
->name
), subfeatures
);
7400 Fprovide (intern_c_string ("make-network-process"), subfeatures
);
7403 #if defined (DARWIN_OS)
7404 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7405 processes. As such, we only change the default value. */
7408 char const *release
= (STRINGP (Voperating_system_release
)
7409 ? SSDATA (Voperating_system_release
)
7411 if (!release
|| !release
[0] || (release
[0] < MIN_PTY_KERNEL_VERSION
7412 && release
[1] == '.')) {
7413 Vprocess_connection_type
= Qnil
;
7417 #endif /* subprocesses */
7422 syms_of_process (void)
7426 DEFSYM (Qprocessp
, "processp");
7427 DEFSYM (Qrun
, "run");
7428 DEFSYM (Qstop
, "stop");
7429 DEFSYM (Qsignal
, "signal");
7431 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7434 Qexit = intern_c_string ("exit");
7435 staticpro (&Qexit); */
7437 DEFSYM (Qopen
, "open");
7438 DEFSYM (Qclosed
, "closed");
7439 DEFSYM (Qconnect
, "connect");
7440 DEFSYM (Qfailed
, "failed");
7441 DEFSYM (Qlisten
, "listen");
7442 DEFSYM (Qlocal
, "local");
7443 DEFSYM (Qipv4
, "ipv4");
7445 DEFSYM (Qipv6
, "ipv6");
7447 DEFSYM (Qdatagram
, "datagram");
7448 DEFSYM (Qseqpacket
, "seqpacket");
7450 DEFSYM (QCport
, ":port");
7451 DEFSYM (QCspeed
, ":speed");
7452 DEFSYM (QCprocess
, ":process");
7454 DEFSYM (QCbytesize
, ":bytesize");
7455 DEFSYM (QCstopbits
, ":stopbits");
7456 DEFSYM (QCparity
, ":parity");
7457 DEFSYM (Qodd
, "odd");
7458 DEFSYM (Qeven
, "even");
7459 DEFSYM (QCflowcontrol
, ":flowcontrol");
7462 DEFSYM (QCsummary
, ":summary");
7464 DEFSYM (Qreal
, "real");
7465 DEFSYM (Qnetwork
, "network");
7466 DEFSYM (Qserial
, "serial");
7467 DEFSYM (QCbuffer
, ":buffer");
7468 DEFSYM (QChost
, ":host");
7469 DEFSYM (QCservice
, ":service");
7470 DEFSYM (QClocal
, ":local");
7471 DEFSYM (QCremote
, ":remote");
7472 DEFSYM (QCcoding
, ":coding");
7473 DEFSYM (QCserver
, ":server");
7474 DEFSYM (QCnowait
, ":nowait");
7475 DEFSYM (QCsentinel
, ":sentinel");
7476 DEFSYM (QClog
, ":log");
7477 DEFSYM (QCnoquery
, ":noquery");
7478 DEFSYM (QCstop
, ":stop");
7479 DEFSYM (QCoptions
, ":options");
7480 DEFSYM (QCplist
, ":plist");
7482 DEFSYM (Qlast_nonmenu_event
, "last-nonmenu-event");
7484 staticpro (&Vprocess_alist
);
7486 staticpro (&deleted_pid_list
);
7489 #endif /* subprocesses */
7491 DEFSYM (QCname
, ":name");
7492 DEFSYM (QCtype
, ":type");
7494 DEFSYM (Qeuid
, "euid");
7495 DEFSYM (Qegid
, "egid");
7496 DEFSYM (Quser
, "user");
7497 DEFSYM (Qgroup
, "group");
7498 DEFSYM (Qcomm
, "comm");
7499 DEFSYM (Qstate
, "state");
7500 DEFSYM (Qppid
, "ppid");
7501 DEFSYM (Qpgrp
, "pgrp");
7502 DEFSYM (Qsess
, "sess");
7503 DEFSYM (Qttname
, "ttname");
7504 DEFSYM (Qtpgid
, "tpgid");
7505 DEFSYM (Qminflt
, "minflt");
7506 DEFSYM (Qmajflt
, "majflt");
7507 DEFSYM (Qcminflt
, "cminflt");
7508 DEFSYM (Qcmajflt
, "cmajflt");
7509 DEFSYM (Qutime
, "utime");
7510 DEFSYM (Qstime
, "stime");
7511 DEFSYM (Qtime
, "time");
7512 DEFSYM (Qcutime
, "cutime");
7513 DEFSYM (Qcstime
, "cstime");
7514 DEFSYM (Qctime
, "ctime");
7515 DEFSYM (Qpri
, "pri");
7516 DEFSYM (Qnice
, "nice");
7517 DEFSYM (Qthcount
, "thcount");
7518 DEFSYM (Qstart
, "start");
7519 DEFSYM (Qvsize
, "vsize");
7520 DEFSYM (Qrss
, "rss");
7521 DEFSYM (Qetime
, "etime");
7522 DEFSYM (Qpcpu
, "pcpu");
7523 DEFSYM (Qpmem
, "pmem");
7524 DEFSYM (Qargs
, "args");
7526 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes
,
7527 doc
: /* Non-nil means delete processes immediately when they exit.
7528 A value of nil means don't delete them until `list-processes' is run. */);
7530 delete_exited_processes
= 1;
7533 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type
,
7534 doc
: /* Control type of device used to communicate with subprocesses.
7535 Values are nil to use a pipe, or t or `pty' to use a pty.
7536 The value has no effect if the system has no ptys or if all ptys are busy:
7537 then a pipe is used in any case.
7538 The value takes effect when `start-process' is called. */);
7539 Vprocess_connection_type
= Qt
;
7541 #ifdef ADAPTIVE_READ_BUFFERING
7542 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering
,
7543 doc
: /* If non-nil, improve receive buffering by delaying after short reads.
7544 On some systems, when Emacs reads the output from a subprocess, the output data
7545 is read in very small blocks, potentially resulting in very poor performance.
7546 This behavior can be remedied to some extent by setting this variable to a
7547 non-nil value, as it will automatically delay reading from such processes, to
7548 allow them to produce more output before Emacs tries to read it.
7549 If the value is t, the delay is reset after each write to the process; any other
7550 non-nil value means that the delay is not reset on write.
7551 The variable takes effect when `start-process' is called. */);
7552 Vprocess_adaptive_read_buffering
= Qt
;
7555 defsubr (&Sprocessp
);
7556 defsubr (&Sget_process
);
7557 defsubr (&Sdelete_process
);
7558 defsubr (&Sprocess_status
);
7559 defsubr (&Sprocess_exit_status
);
7560 defsubr (&Sprocess_id
);
7561 defsubr (&Sprocess_name
);
7562 defsubr (&Sprocess_tty_name
);
7563 defsubr (&Sprocess_command
);
7564 defsubr (&Sset_process_buffer
);
7565 defsubr (&Sprocess_buffer
);
7566 defsubr (&Sprocess_mark
);
7567 defsubr (&Sset_process_filter
);
7568 defsubr (&Sprocess_filter
);
7569 defsubr (&Sset_process_sentinel
);
7570 defsubr (&Sprocess_sentinel
);
7571 defsubr (&Sset_process_window_size
);
7572 defsubr (&Sset_process_inherit_coding_system_flag
);
7573 defsubr (&Sset_process_query_on_exit_flag
);
7574 defsubr (&Sprocess_query_on_exit_flag
);
7575 defsubr (&Sprocess_contact
);
7576 defsubr (&Sprocess_plist
);
7577 defsubr (&Sset_process_plist
);
7578 defsubr (&Sprocess_list
);
7579 defsubr (&Sstart_process
);
7580 defsubr (&Sserial_process_configure
);
7581 defsubr (&Smake_serial_process
);
7582 defsubr (&Sset_network_process_option
);
7583 defsubr (&Smake_network_process
);
7584 defsubr (&Sformat_network_address
);
7585 #if defined (HAVE_NET_IF_H)
7587 defsubr (&Snetwork_interface_list
);
7589 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7590 defsubr (&Snetwork_interface_info
);
7592 #endif /* defined (HAVE_NET_IF_H) */
7593 #ifdef DATAGRAM_SOCKETS
7594 defsubr (&Sprocess_datagram_address
);
7595 defsubr (&Sset_process_datagram_address
);
7597 defsubr (&Saccept_process_output
);
7598 defsubr (&Sprocess_send_region
);
7599 defsubr (&Sprocess_send_string
);
7600 defsubr (&Sinterrupt_process
);
7601 defsubr (&Skill_process
);
7602 defsubr (&Squit_process
);
7603 defsubr (&Sstop_process
);
7604 defsubr (&Scontinue_process
);
7605 defsubr (&Sprocess_running_child_p
);
7606 defsubr (&Sprocess_send_eof
);
7607 defsubr (&Ssignal_process
);
7608 defsubr (&Swaiting_for_user_input_p
);
7609 defsubr (&Sprocess_type
);
7610 defsubr (&Sset_process_coding_system
);
7611 defsubr (&Sprocess_coding_system
);
7612 defsubr (&Sset_process_filter_multibyte
);
7613 defsubr (&Sprocess_filter_multibyte_p
);
7615 #endif /* subprocesses */
7617 defsubr (&Sget_buffer_process
);
7618 defsubr (&Sprocess_inherit_coding_system_flag
);
7619 defsubr (&Slist_system_processes
);
7620 defsubr (&Sprocess_attributes
);