process changes
[emacs.git] / src / process.c
blobada673e3c3477b4670c885ba6af66e59fe8aeecc
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/>. */
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
32 #include <unistd.h>
33 #include <fcntl.h>
35 #include "lisp.h"
37 /* Only MS-DOS does not define `subprocesses'. */
38 #ifdef subprocesses
40 #include <sys/socket.h>
41 #include <netdb.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
49 #endif
50 #ifdef AF_LOCAL
51 #define HAVE_LOCAL_SOCKETS
52 #include <sys/un.h>
53 #endif
54 #endif
56 #include <sys/ioctl.h>
57 #if defined (HAVE_NET_IF_H)
58 #include <net/if.h>
59 #endif /* HAVE_NET_IF_H */
61 #if defined (HAVE_IFADDRS_H)
62 /* Must be after net/if.h */
63 #include <ifaddrs.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>
68 #endif
70 #endif
72 #ifdef NEED_BSDTTY
73 #include <bsdtty.h>
74 #endif
76 #ifdef HAVE_RES_INIT
77 #include <netinet/in.h>
78 #include <arpa/nameser.h>
79 #include <resolv.h>
80 #endif
82 #ifdef HAVE_UTIL_H
83 #include <util.h>
84 #endif
86 #ifdef HAVE_PTY_H
87 #include <pty.h>
88 #endif
90 #endif /* subprocesses */
92 #include "systime.h"
93 #include "systty.h"
95 #include "window.h"
96 #include "character.h"
97 #include "buffer.h"
98 #include "coding.h"
99 #include "process.h"
100 #include "frame.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"
108 #include "atimer.h"
109 #include "sysselect.h"
110 #include "syssignal.h"
111 #include "syswait.h"
112 #ifdef HAVE_GNUTLS
113 #include "gnutls.h"
114 #endif
116 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
117 #include "xgselect.h"
118 #endif
119 #ifdef HAVE_NS
120 #include "nsterm.h"
121 #endif
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"
128 #endif
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
141 when exiting. */
142 int inhibit_sentinels;
144 #ifdef subprocesses
146 Lisp_Object Qprocessp;
147 static Lisp_Object Qrun, Qstop, Qsignal;
148 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
149 Lisp_Object Qlocal;
150 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
151 static Lisp_Object Qreal, Qnetwork, Qserial;
152 #ifdef AF_INET6
153 static Lisp_Object Qipv6;
154 #endif
155 static Lisp_Object QCport, QCprocess;
156 Lisp_Object QCspeed;
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))
180 #ifndef HAVE_H_ERRNO
181 extern int h_errno;
182 #endif
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
195 #else
196 #ifndef NON_BLOCKING_CONNECT
197 #ifdef HAVE_SELECT
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
216 #else
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
228 #endif
230 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
231 #define ADAPTIVE_READ_BUFFERING
232 #endif
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;
248 #else
249 #define process_output_delay_count 0
250 #endif
252 static void create_process (Lisp_Object, char **, Lisp_Object);
253 #ifdef SIGIO
254 static int keyboard_bit_set (SELECT_TYPE *);
255 #endif
256 static void deactivate_process (Lisp_Object);
257 static void status_notify (struct Lisp_Process *);
258 static int read_process_output (Lisp_Object, int);
259 static void create_pty (Lisp_Object);
261 /* If we support a window system, turn on the code to poll periodically
262 to detect C-g. It isn't actually used when doing interrupt input. */
263 #if defined (HAVE_WINDOW_SYSTEM) && !defined (USE_ASYNC_EVENTS)
264 #define POLL_FOR_INPUT
265 #endif
267 static Lisp_Object get_process (register Lisp_Object name);
268 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
270 #ifdef NON_BLOCKING_CONNECT
271 /* Number of bits set in connect_wait_mask. */
272 static int num_pending_connects;
273 #endif /* NON_BLOCKING_CONNECT */
275 /* The largest descriptor currently in use for a process object. */
276 static int max_process_desc;
278 /* The largest descriptor currently in use for input. */
279 static int max_input_desc;
281 /* Indexed by descriptor, gives the process (if any) for that descriptor */
282 static Lisp_Object chan_process[MAXDESC];
284 /* Alist of elements (NAME . PROCESS) */
285 static Lisp_Object Vprocess_alist;
287 /* Buffered-ahead input char from process, indexed by channel.
288 -1 means empty (no char is buffered).
289 Used on sys V where the only way to tell if there is any
290 output from the process is to read at least one char.
291 Always -1 on systems that support FIONREAD. */
293 static int proc_buffered_char[MAXDESC];
295 /* Table of `struct coding-system' for each process. */
296 static struct coding_system *proc_decode_coding_system[MAXDESC];
297 static struct coding_system *proc_encode_coding_system[MAXDESC];
299 #ifdef DATAGRAM_SOCKETS
300 /* Table of `partner address' for datagram sockets. */
301 static struct sockaddr_and_len {
302 struct sockaddr *sa;
303 int len;
304 } datagram_address[MAXDESC];
305 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
306 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
307 #else
308 #define DATAGRAM_CHAN_P(chan) (0)
309 #define DATAGRAM_CONN_P(proc) (0)
310 #endif
312 /* Maximum number of bytes to send to a pty without an eof. */
313 static int pty_max_bytes;
317 enum fd_bits
319 /* Read from file descriptor. */
320 FOR_READ = 1,
321 /* Write to file descriptor. */
322 FOR_WRITE = 2,
323 /* This descriptor refers to a keyboard. Only valid if FOR_READ is
324 set. */
325 KEYBOARD_FD = 4,
326 /* This descriptor refers to a process. */
327 PROCESS_FD = 8,
328 /* A non-blocking connect. Only valid if FOR_WRITE is set. */
329 NON_BLOCKING_CONNECT_FD = 16
332 static struct fd_callback_data
334 fd_callback func;
335 void *data;
336 /* Flags from enum fd_bits. */
337 int flags;
338 /* If this fd is locked to a certain thread, this points to it.
339 Otherwise, this is NULL. If an fd is locked to a thread, then
340 only that thread is permitted to wait on it. */
341 struct thread_state *thread;
342 /* If this fd is currently being selected on by a thread, this
343 points to the thread. Otherwise it is NULL. */
344 struct thread_state *waiting_thread;
345 } fd_callback_info[MAXDESC];
348 /* Add a file descriptor FD to be monitored for when read is possible.
349 When read is possible, call FUNC with argument DATA. */
351 void
352 add_read_fd (int fd, fd_callback func, void *data)
354 eassert (fd < MAXDESC);
355 add_keyboard_wait_descriptor (fd);
357 fd_callback_info[fd].func = func;
358 fd_callback_info[fd].data = data;
361 void
362 add_non_keyboard_read_fd (int fd)
364 eassert (fd >= 0 && fd < MAXDESC);
365 eassert (fd_callback_info[fd].func == NULL);
366 fd_callback_info[fd].flags |= FOR_READ;
367 if (fd > max_input_desc)
368 max_input_desc = fd;
371 void
372 add_process_read_fd (int fd)
374 add_non_keyboard_read_fd (fd);
375 fd_callback_info[fd].flags |= PROCESS_FD;
378 /* Stop monitoring file descriptor FD for when read is possible. */
380 void
381 delete_read_fd (int fd)
383 eassert (fd < MAXDESC);
384 delete_keyboard_wait_descriptor (fd);
386 if (fd_callback_info[fd].flags == 0)
388 fd_callback_info[fd].func = 0;
389 fd_callback_info[fd].data = 0;
393 /* Add a file descriptor FD to be monitored for when write is possible.
394 When write is possible, call FUNC with argument DATA. */
396 void
397 add_write_fd (int fd, fd_callback func, void *data)
399 eassert (fd < MAXDESC);
400 if (fd > max_input_desc)
401 max_input_desc = fd;
403 fd_callback_info[fd].func = func;
404 fd_callback_info[fd].data = data;
405 fd_callback_info[fd].flags |= FOR_WRITE;
408 void
409 add_non_blocking_write_fd (int fd)
411 eassert (fd >= 0 && fd < MAXDESC);
412 eassert (fd_callback_info[fd].func == NULL);
414 fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
415 if (fd > max_input_desc)
416 max_input_desc = fd;
417 ++num_pending_connects;
420 /* Stop monitoring file descriptor FD for when write is possible. */
422 void
423 delete_write_fd (int fd)
425 int lim = max_input_desc;
427 eassert (fd < MAXDESC);
428 if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
430 if (--num_pending_connects < 0)
431 abort ();
433 fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
434 if (fd_callback_info[fd].flags == 0)
436 fd_callback_info[fd].func = 0;
437 fd_callback_info[fd].data = 0;
439 if (fd == max_input_desc)
441 for (fd = max_input_desc; fd >= 0; --fd)
443 if (fd_callback_info[fd].flags != 0)
445 max_input_desc = fd;
446 break;
453 static void
454 compute_input_wait_mask (SELECT_TYPE *mask)
456 int fd;
458 FD_ZERO (mask);
459 for (fd = 0; fd < max (max_process_desc, max_input_desc); ++fd)
461 if (fd_callback_info[fd].thread != NULL
462 && fd_callback_info[fd].thread != current_thread)
463 continue;
464 if (fd_callback_info[fd].waiting_thread != NULL
465 && fd_callback_info[fd].waiting_thread != current_thread)
466 continue;
467 if ((fd_callback_info[fd].flags & FOR_READ) != 0)
469 FD_SET (fd, mask);
470 fd_callback_info[fd].waiting_thread = current_thread;
475 static void
476 compute_non_process_wait_mask (SELECT_TYPE *mask)
478 int fd;
480 FD_ZERO (mask);
481 for (fd = 0; fd < max (max_process_desc, max_input_desc); ++fd)
483 if (fd_callback_info[fd].thread != NULL
484 && fd_callback_info[fd].thread != current_thread)
485 continue;
486 if (fd_callback_info[fd].waiting_thread != NULL
487 && fd_callback_info[fd].waiting_thread != current_thread)
488 continue;
489 if ((fd_callback_info[fd].flags & FOR_READ) != 0
490 && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
492 FD_SET (fd, mask);
493 fd_callback_info[fd].waiting_thread = current_thread;
498 static void
499 compute_non_keyboard_wait_mask (SELECT_TYPE *mask)
501 int fd;
503 FD_ZERO (mask);
504 for (fd = 0; fd < max (max_process_desc, max_input_desc); ++fd)
506 if (fd_callback_info[fd].thread != NULL
507 && fd_callback_info[fd].thread != current_thread)
508 continue;
509 if (fd_callback_info[fd].waiting_thread != NULL
510 && fd_callback_info[fd].waiting_thread != current_thread)
511 continue;
512 if ((fd_callback_info[fd].flags & FOR_READ) != 0
513 && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
515 FD_SET (fd, mask);
516 fd_callback_info[fd].waiting_thread = current_thread;
521 static void
522 compute_write_mask (SELECT_TYPE *mask)
524 int fd;
526 FD_ZERO (mask);
527 for (fd = 0; fd < max (max_process_desc, max_input_desc); ++fd)
529 if (fd_callback_info[fd].thread != NULL
530 && fd_callback_info[fd].thread != current_thread)
531 continue;
532 if (fd_callback_info[fd].waiting_thread != NULL
533 && fd_callback_info[fd].waiting_thread != current_thread)
534 continue;
535 if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
537 FD_SET (fd, mask);
538 fd_callback_info[fd].waiting_thread = current_thread;
543 static void
544 clear_waiting_thread_info (void)
546 int fd;
548 for (fd = 0; fd < max (max_process_desc, max_input_desc); ++fd)
550 if (fd_callback_info[fd].waiting_thread == current_thread)
551 fd_callback_info[fd].waiting_thread = NULL;
556 /* Compute the Lisp form of the process status, p->status, from
557 the numeric status that was returned by `wait'. */
559 static Lisp_Object status_convert (int);
561 static void
562 update_status (struct Lisp_Process *p)
564 eassert (p->raw_status_new);
565 PSET (p, status, status_convert (p->raw_status));
566 p->raw_status_new = 0;
569 /* Convert a process status word in Unix format to
570 the list that we use internally. */
572 static Lisp_Object
573 status_convert (int w)
575 if (WIFSTOPPED (w))
576 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
577 else if (WIFEXITED (w))
578 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
579 WCOREDUMP (w) ? Qt : Qnil));
580 else if (WIFSIGNALED (w))
581 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
582 WCOREDUMP (w) ? Qt : Qnil));
583 else
584 return Qrun;
587 /* Given a status-list, extract the three pieces of information
588 and store them individually through the three pointers. */
590 static void
591 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
593 Lisp_Object tem;
595 if (SYMBOLP (l))
597 *symbol = l;
598 *code = 0;
599 *coredump = 0;
601 else
603 *symbol = XCAR (l);
604 tem = XCDR (l);
605 *code = XFASTINT (XCAR (tem));
606 tem = XCDR (tem);
607 *coredump = !NILP (tem);
611 /* Return a string describing a process status list. */
613 static Lisp_Object
614 status_message (struct Lisp_Process *p)
616 Lisp_Object status = p->status;
617 Lisp_Object symbol;
618 int code, coredump;
619 Lisp_Object string, string2;
621 decode_status (status, &symbol, &code, &coredump);
623 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
625 char *signame;
626 synchronize_system_messages_locale ();
627 signame = strsignal (code);
628 if (signame == 0)
629 string = build_string ("unknown");
630 else
632 int c1, c2;
634 string = build_unibyte_string (signame);
635 if (! NILP (Vlocale_coding_system))
636 string = (code_convert_string_norecord
637 (string, Vlocale_coding_system, 0));
638 c1 = STRING_CHAR (SDATA (string));
639 c2 = downcase (c1);
640 if (c1 != c2)
641 Faset (string, make_number (0), make_number (c2));
643 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
644 return concat2 (string, string2);
646 else if (EQ (symbol, Qexit))
648 if (NETCONN1_P (p))
649 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
650 if (code == 0)
651 return build_string ("finished\n");
652 string = Fnumber_to_string (make_number (code));
653 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
654 return concat3 (build_string ("exited abnormally with code "),
655 string, string2);
657 else if (EQ (symbol, Qfailed))
659 string = Fnumber_to_string (make_number (code));
660 string2 = build_string ("\n");
661 return concat3 (build_string ("failed with code "),
662 string, string2);
664 else
665 return Fcopy_sequence (Fsymbol_name (symbol));
668 #ifdef HAVE_PTYS
670 /* The file name of the pty opened by allocate_pty. */
671 static char pty_name[24];
673 /* Open an available pty, returning a file descriptor.
674 Return -1 on failure.
675 The file name of the terminal corresponding to the pty
676 is left in the variable pty_name. */
678 static int
679 allocate_pty (void)
681 int fd;
683 #ifdef PTY_ITERATION
684 PTY_ITERATION
685 #else
686 register int c, i;
687 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
688 for (i = 0; i < 16; i++)
689 #endif
691 #ifdef PTY_NAME_SPRINTF
692 PTY_NAME_SPRINTF
693 #else
694 sprintf (pty_name, "/dev/pty%c%x", c, i);
695 #endif /* no PTY_NAME_SPRINTF */
697 #ifdef PTY_OPEN
698 PTY_OPEN;
699 #else /* no PTY_OPEN */
701 { /* Some systems name their pseudoterminals so that there are gaps in
702 the usual sequence - for example, on HP9000/S700 systems, there
703 are no pseudoterminals with names ending in 'f'. So we wait for
704 three failures in a row before deciding that we've reached the
705 end of the ptys. */
706 int failed_count = 0;
707 struct stat stb;
709 if (stat (pty_name, &stb) < 0)
711 failed_count++;
712 if (failed_count >= 3)
713 return -1;
715 else
716 failed_count = 0;
718 # ifdef O_NONBLOCK
719 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
720 # else
721 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
722 # endif
724 #endif /* no PTY_OPEN */
726 if (fd >= 0)
728 /* check to make certain that both sides are available
729 this avoids a nasty yet stupid bug in rlogins */
730 #ifdef PTY_TTY_NAME_SPRINTF
731 PTY_TTY_NAME_SPRINTF
732 #else
733 sprintf (pty_name, "/dev/tty%c%x", c, i);
734 #endif /* no PTY_TTY_NAME_SPRINTF */
735 if (access (pty_name, 6) != 0)
737 emacs_close (fd);
738 # ifndef __sgi
739 continue;
740 # else
741 return -1;
742 # endif /* __sgi */
744 setup_pty (fd);
745 return fd;
748 return -1;
750 #endif /* HAVE_PTYS */
752 static Lisp_Object
753 make_process (Lisp_Object name)
755 register Lisp_Object val, tem, name1;
756 register struct Lisp_Process *p;
757 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
758 printmax_t i;
760 p = allocate_process ();
761 /* Initialize Lisp data. Note that allocate_process initializes all
762 Lisp data to nil, so do it only for slots which should not be nil. */
763 PSET (p, status, Qrun);
764 PSET (p, mark, Fmake_marker ());
765 PSET (p, thread, Fcurrent_thread ());
767 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
768 non-Lisp data, so do it only for slots which should not be zero. */
769 p->infd = -1;
770 p->outfd = -1;
772 #ifdef HAVE_GNUTLS
773 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
774 #endif
776 /* If name is already in use, modify it until it is unused. */
778 name1 = name;
779 for (i = 1; ; i++)
781 tem = Fget_process (name1);
782 if (NILP (tem)) break;
783 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
785 name = name1;
786 PSET (p, name, name);
787 XSETPROCESS (val, p);
788 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
789 return val;
792 static void
793 remove_process (register Lisp_Object proc)
795 register Lisp_Object pair;
797 pair = Frassq (proc, Vprocess_alist);
798 Vprocess_alist = Fdelq (pair, Vprocess_alist);
800 deactivate_process (proc);
803 void
804 update_processes_for_thread_death (Lisp_Object dying_thread)
806 Lisp_Object pair;
808 for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
810 Lisp_Object process = XCDR (XCAR (pair));
811 if (EQ (XPROCESS (process)->thread, dying_thread))
813 struct Lisp_Process *proc = XPROCESS (process);
815 proc->thread = Qnil;
816 if (proc->infd >= 0)
817 fd_callback_info[proc->infd].thread = NULL;
818 if (proc->outfd >= 0)
819 fd_callback_info[proc->outfd].thread = NULL;
825 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
826 doc: /* Return t if OBJECT is a process. */)
827 (Lisp_Object object)
829 return PROCESSP (object) ? Qt : Qnil;
832 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
833 doc: /* Return the process named NAME, or nil if there is none. */)
834 (register Lisp_Object name)
836 if (PROCESSP (name))
837 return name;
838 CHECK_STRING (name);
839 return Fcdr (Fassoc (name, Vprocess_alist));
842 /* This is how commands for the user decode process arguments. It
843 accepts a process, a process name, a buffer, a buffer name, or nil.
844 Buffers denote the first process in the buffer, and nil denotes the
845 current buffer. */
847 static Lisp_Object
848 get_process (register Lisp_Object name)
850 register Lisp_Object proc, obj;
851 if (STRINGP (name))
853 obj = Fget_process (name);
854 if (NILP (obj))
855 obj = Fget_buffer (name);
856 if (NILP (obj))
857 error ("Process %s does not exist", SDATA (name));
859 else if (NILP (name))
860 obj = Fcurrent_buffer ();
861 else
862 obj = name;
864 /* Now obj should be either a buffer object or a process object.
866 if (BUFFERP (obj))
868 proc = Fget_buffer_process (obj);
869 if (NILP (proc))
870 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
872 else
874 CHECK_PROCESS (obj);
875 proc = obj;
877 return proc;
881 #ifdef SIGCHLD
882 /* Fdelete_process promises to immediately forget about the process, but in
883 reality, Emacs needs to remember those processes until they have been
884 treated by sigchld_handler; otherwise this handler would consider the
885 process as being synchronous and say that the synchronous process is
886 dead. */
887 static Lisp_Object deleted_pid_list;
888 #endif
890 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
891 doc: /* Delete PROCESS: kill it and forget about it immediately.
892 PROCESS may be a process, a buffer, the name of a process or buffer, or
893 nil, indicating the current buffer's process. */)
894 (register Lisp_Object process)
896 register struct Lisp_Process *p;
898 process = get_process (process);
899 p = XPROCESS (process);
901 p->raw_status_new = 0;
902 if (NETCONN1_P (p) || SERIALCONN1_P (p))
904 PSET (p, status, Fcons (Qexit, Fcons (make_number (0), Qnil)));
905 p->tick = ++process_tick;
906 status_notify (p);
907 redisplay_preserve_echo_area (13);
909 else if (p->infd >= 0)
911 #ifdef SIGCHLD
912 Lisp_Object symbol;
913 pid_t pid = p->pid;
915 /* No problem storing the pid here, as it is still in Vprocess_alist. */
916 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
917 /* GC treated elements set to nil. */
918 Fdelq (Qnil, deleted_pid_list));
919 /* If the process has already signaled, remove it from the list. */
920 if (p->raw_status_new)
921 update_status (p);
922 symbol = p->status;
923 if (CONSP (p->status))
924 symbol = XCAR (p->status);
925 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
926 deleted_pid_list
927 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
928 else
929 #endif
931 Fkill_process (process, Qnil);
932 /* Do this now, since remove_process will make sigchld_handler do nothing. */
933 PSET (p, status, Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil)));
934 p->tick = ++process_tick;
935 status_notify (p);
936 redisplay_preserve_echo_area (13);
939 remove_process (process);
940 return Qnil;
943 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
944 doc: /* Return the status of PROCESS.
945 The returned value is one of the following symbols:
946 run -- for a process that is running.
947 stop -- for a process stopped but continuable.
948 exit -- for a process that has exited.
949 signal -- for a process that has got a fatal signal.
950 open -- for a network stream connection that is open.
951 listen -- for a network stream server that is listening.
952 closed -- for a network stream connection that is closed.
953 connect -- when waiting for a non-blocking connection to complete.
954 failed -- when a non-blocking connection has failed.
955 nil -- if arg is a process name and no such process exists.
956 PROCESS may be a process, a buffer, the name of a process, or
957 nil, indicating the current buffer's process. */)
958 (register Lisp_Object process)
960 register struct Lisp_Process *p;
961 register Lisp_Object status;
963 if (STRINGP (process))
964 process = Fget_process (process);
965 else
966 process = get_process (process);
968 if (NILP (process))
969 return process;
971 p = XPROCESS (process);
972 if (p->raw_status_new)
973 update_status (p);
974 status = p->status;
975 if (CONSP (status))
976 status = XCAR (status);
977 if (NETCONN1_P (p) || SERIALCONN1_P (p))
979 if (EQ (status, Qexit))
980 status = Qclosed;
981 else if (EQ (p->command, Qt))
982 status = Qstop;
983 else if (EQ (status, Qrun))
984 status = Qopen;
986 return status;
989 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
990 1, 1, 0,
991 doc: /* Return the exit status of PROCESS or the signal number that killed it.
992 If PROCESS has not yet exited or died, return 0. */)
993 (register Lisp_Object process)
995 CHECK_PROCESS (process);
996 if (XPROCESS (process)->raw_status_new)
997 update_status (XPROCESS (process));
998 if (CONSP (XPROCESS (process)->status))
999 return XCAR (XCDR (XPROCESS (process)->status));
1000 return make_number (0);
1003 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
1004 doc: /* Return the process id of PROCESS.
1005 This is the pid of the external process which PROCESS uses or talks to.
1006 For a network connection, this value is nil. */)
1007 (register Lisp_Object process)
1009 pid_t pid;
1011 CHECK_PROCESS (process);
1012 pid = XPROCESS (process)->pid;
1013 return (pid ? make_fixnum_or_float (pid) : Qnil);
1016 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
1017 doc: /* Return the name of PROCESS, as a string.
1018 This is the name of the program invoked in PROCESS,
1019 possibly modified to make it unique among process names. */)
1020 (register Lisp_Object process)
1022 CHECK_PROCESS (process);
1023 return XPROCESS (process)->name;
1026 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1027 doc: /* Return the command that was executed to start PROCESS.
1028 This is a list of strings, the first string being the program executed
1029 and the rest of the strings being the arguments given to it.
1030 For a network or serial process, this is nil (process is running) or t
1031 \(process is stopped). */)
1032 (register Lisp_Object process)
1034 CHECK_PROCESS (process);
1035 return XPROCESS (process)->command;
1038 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1039 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1040 This is the terminal that the process itself reads and writes on,
1041 not the name of the pty that Emacs uses to talk with that terminal. */)
1042 (register Lisp_Object process)
1044 CHECK_PROCESS (process);
1045 return XPROCESS (process)->tty_name;
1048 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1049 2, 2, 0,
1050 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1051 Return BUFFER. */)
1052 (register Lisp_Object process, Lisp_Object buffer)
1054 struct Lisp_Process *p;
1056 CHECK_PROCESS (process);
1057 if (!NILP (buffer))
1058 CHECK_BUFFER (buffer);
1059 p = XPROCESS (process);
1060 PSET (p, buffer, buffer);
1061 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1062 PSET (p, childp, Fplist_put (p->childp, QCbuffer, buffer));
1063 setup_process_coding_systems (process);
1064 return buffer;
1067 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1068 1, 1, 0,
1069 doc: /* Return the buffer PROCESS is associated with.
1070 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1071 (register Lisp_Object process)
1073 CHECK_PROCESS (process);
1074 return XPROCESS (process)->buffer;
1077 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1078 1, 1, 0,
1079 doc: /* Return the marker for the end of the last output from PROCESS. */)
1080 (register Lisp_Object process)
1082 CHECK_PROCESS (process);
1083 return XPROCESS (process)->mark;
1086 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1087 2, 2, 0,
1088 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
1089 A value of t means stop accepting output from the process.
1091 When a process has a filter, its buffer is not used for output.
1092 Instead, each time it does output, the entire string of output is
1093 passed to the filter.
1095 The filter gets two arguments: the process and the string of output.
1096 The string argument is normally a multibyte string, except:
1097 - if the process' input coding system is no-conversion or raw-text,
1098 it is a unibyte string (the non-converted input), or else
1099 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1100 string (the result of converting the decoded input multibyte
1101 string to unibyte with `string-make-unibyte'). */)
1102 (register Lisp_Object process, Lisp_Object filter)
1104 struct Lisp_Process *p;
1106 CHECK_PROCESS (process);
1107 p = XPROCESS (process);
1109 /* Don't signal an error if the process' input file descriptor
1110 is closed. This could make debugging Lisp more difficult,
1111 for example when doing something like
1113 (setq process (start-process ...))
1114 (debug)
1115 (set-process-filter process ...) */
1117 if (p->infd >= 0)
1119 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1120 delete_read_fd (p->infd);
1121 else if (EQ (p->filter, Qt)
1122 /* Network or serial process not stopped: */
1123 && !EQ (p->command, Qt))
1124 delete_read_fd (p->infd);
1127 PSET (p, filter, filter);
1128 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1129 PSET (p, childp, Fplist_put (p->childp, QCfilter, filter));
1130 setup_process_coding_systems (process);
1131 return filter;
1134 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1135 1, 1, 0,
1136 doc: /* Returns the filter function of PROCESS; nil if none.
1137 See `set-process-filter' for more info on filter functions. */)
1138 (register Lisp_Object process)
1140 CHECK_PROCESS (process);
1141 return XPROCESS (process)->filter;
1144 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1145 2, 2, 0,
1146 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1147 The sentinel is called as a function when the process changes state.
1148 It gets two arguments: the process, and a string describing the change. */)
1149 (register Lisp_Object process, Lisp_Object sentinel)
1151 struct Lisp_Process *p;
1153 CHECK_PROCESS (process);
1154 p = XPROCESS (process);
1156 PSET (p, sentinel, sentinel);
1157 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1158 PSET (p, childp, Fplist_put (p->childp, QCsentinel, sentinel));
1159 return sentinel;
1162 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1163 1, 1, 0,
1164 doc: /* Return the sentinel of PROCESS; nil if none.
1165 See `set-process-sentinel' for more info on sentinels. */)
1166 (register Lisp_Object process)
1168 CHECK_PROCESS (process);
1169 return XPROCESS (process)->sentinel;
1172 DEFUN ("set-process-thread", Fset_process_thread, Sset_process_thread,
1173 2, 2, 0,
1174 doc: /* FIXME */)
1175 (Lisp_Object process, Lisp_Object thread)
1177 struct Lisp_Process *proc;
1178 struct thread_state *tstate;
1180 CHECK_PROCESS (process);
1181 if (NILP (thread))
1182 tstate = NULL;
1183 else
1185 CHECK_THREAD (thread);
1186 tstate = XTHREAD (thread);
1189 proc = XPROCESS (process);
1190 proc->thread = thread;
1191 if (proc->infd >= 0)
1192 fd_callback_info[proc->infd].thread = tstate;
1193 if (proc->outfd >= 0)
1194 fd_callback_info[proc->outfd].thread = tstate;
1196 return thread;
1199 DEFUN ("process-thread", Fprocess_thread, Sprocess_thread,
1200 1, 1, 0,
1201 doc: /* FIXME */)
1202 (Lisp_Object process)
1204 CHECK_PROCESS (process);
1205 return XPROCESS (process)->thread;
1208 DEFUN ("set-process-window-size", Fset_process_window_size,
1209 Sset_process_window_size, 3, 3, 0,
1210 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1211 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1213 CHECK_PROCESS (process);
1214 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1215 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1217 if (XPROCESS (process)->infd < 0
1218 || set_window_size (XPROCESS (process)->infd,
1219 XINT (height), XINT (width)) <= 0)
1220 return Qnil;
1221 else
1222 return Qt;
1225 DEFUN ("set-process-inherit-coding-system-flag",
1226 Fset_process_inherit_coding_system_flag,
1227 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1228 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1229 If the second argument FLAG is non-nil, then the variable
1230 `buffer-file-coding-system' of the buffer associated with PROCESS
1231 will be bound to the value of the coding system used to decode
1232 the process output.
1234 This is useful when the coding system specified for the process buffer
1235 leaves either the character code conversion or the end-of-line conversion
1236 unspecified, or if the coding system used to decode the process output
1237 is more appropriate for saving the process buffer.
1239 Binding the variable `inherit-process-coding-system' to non-nil before
1240 starting the process is an alternative way of setting the inherit flag
1241 for the process which will run.
1243 This function returns FLAG. */)
1244 (register Lisp_Object process, Lisp_Object flag)
1246 CHECK_PROCESS (process);
1247 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1248 return flag;
1251 DEFUN ("set-process-query-on-exit-flag",
1252 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1253 2, 2, 0,
1254 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1255 If the second argument FLAG is non-nil, Emacs will query the user before
1256 exiting or killing a buffer if PROCESS is running. This function
1257 returns FLAG. */)
1258 (register Lisp_Object process, Lisp_Object flag)
1260 CHECK_PROCESS (process);
1261 XPROCESS (process)->kill_without_query = NILP (flag);
1262 return flag;
1265 DEFUN ("process-query-on-exit-flag",
1266 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1267 1, 1, 0,
1268 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1269 (register Lisp_Object process)
1271 CHECK_PROCESS (process);
1272 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1275 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1276 1, 2, 0,
1277 doc: /* Return the contact info of PROCESS; t for a real child.
1278 For a network or serial connection, the value depends on the optional
1279 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1280 SERVICE) for a network connection or (PORT SPEED) for a serial
1281 connection. If KEY is t, the complete contact information for the
1282 connection is returned, else the specific value for the keyword KEY is
1283 returned. See `make-network-process' or `make-serial-process' for a
1284 list of keywords. */)
1285 (register Lisp_Object process, Lisp_Object key)
1287 Lisp_Object contact;
1289 CHECK_PROCESS (process);
1290 contact = XPROCESS (process)->childp;
1292 #ifdef DATAGRAM_SOCKETS
1293 if (DATAGRAM_CONN_P (process)
1294 && (EQ (key, Qt) || EQ (key, QCremote)))
1295 contact = Fplist_put (contact, QCremote,
1296 Fprocess_datagram_address (process));
1297 #endif
1299 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1300 return contact;
1301 if (NILP (key) && NETCONN_P (process))
1302 return Fcons (Fplist_get (contact, QChost),
1303 Fcons (Fplist_get (contact, QCservice), Qnil));
1304 if (NILP (key) && SERIALCONN_P (process))
1305 return Fcons (Fplist_get (contact, QCport),
1306 Fcons (Fplist_get (contact, QCspeed), Qnil));
1307 return Fplist_get (contact, key);
1310 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1311 1, 1, 0,
1312 doc: /* Return the plist of PROCESS. */)
1313 (register Lisp_Object process)
1315 CHECK_PROCESS (process);
1316 return XPROCESS (process)->plist;
1319 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1320 2, 2, 0,
1321 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1322 (register Lisp_Object process, Lisp_Object plist)
1324 CHECK_PROCESS (process);
1325 CHECK_LIST (plist);
1327 PSET (XPROCESS (process), plist, plist);
1328 return plist;
1331 #if 0 /* Turned off because we don't currently record this info
1332 in the process. Perhaps add it. */
1333 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1334 doc: /* Return the connection type of PROCESS.
1335 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1336 a socket connection. */)
1337 (Lisp_Object process)
1339 return XPROCESS (process)->type;
1341 #endif
1343 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1344 doc: /* Return the connection type of PROCESS.
1345 The value is either the symbol `real', `network', or `serial'.
1346 PROCESS may be a process, a buffer, the name of a process or buffer, or
1347 nil, indicating the current buffer's process. */)
1348 (Lisp_Object process)
1350 Lisp_Object proc;
1351 proc = get_process (process);
1352 return XPROCESS (proc)->type;
1355 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1356 1, 2, 0,
1357 doc: /* Convert network ADDRESS from internal format to a string.
1358 A 4 or 5 element vector represents an IPv4 address (with port number).
1359 An 8 or 9 element vector represents an IPv6 address (with port number).
1360 If optional second argument OMIT-PORT is non-nil, don't include a port
1361 number in the string, even when present in ADDRESS.
1362 Returns nil if format of ADDRESS is invalid. */)
1363 (Lisp_Object address, Lisp_Object omit_port)
1365 if (NILP (address))
1366 return Qnil;
1368 if (STRINGP (address)) /* AF_LOCAL */
1369 return address;
1371 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1373 register struct Lisp_Vector *p = XVECTOR (address);
1374 ptrdiff_t size = p->header.size;
1375 Lisp_Object args[10];
1376 int nargs, i;
1378 if (size == 4 || (size == 5 && !NILP (omit_port)))
1380 args[0] = build_string ("%d.%d.%d.%d");
1381 nargs = 4;
1383 else if (size == 5)
1385 args[0] = build_string ("%d.%d.%d.%d:%d");
1386 nargs = 5;
1388 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1390 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1391 nargs = 8;
1393 else if (size == 9)
1395 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1396 nargs = 9;
1398 else
1399 return Qnil;
1401 for (i = 0; i < nargs; i++)
1403 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1404 return Qnil;
1406 if (nargs <= 5 /* IPv4 */
1407 && i < 4 /* host, not port */
1408 && XINT (p->contents[i]) > 255)
1409 return Qnil;
1411 args[i+1] = p->contents[i];
1414 return Fformat (nargs+1, args);
1417 if (CONSP (address))
1419 Lisp_Object args[2];
1420 args[0] = build_string ("<Family %d>");
1421 args[1] = Fcar (address);
1422 return Fformat (2, args);
1425 return Qnil;
1428 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1429 doc: /* Return a list of all processes. */)
1430 (void)
1432 return Fmapcar (Qcdr, Vprocess_alist);
1435 /* Starting asynchronous inferior processes. */
1437 static Lisp_Object start_process_unwind (Lisp_Object proc);
1439 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1440 doc: /* Start a program in a subprocess. Return the process object for it.
1441 NAME is name for process. It is modified if necessary to make it unique.
1442 BUFFER is the buffer (or buffer name) to associate with the process.
1444 Process output (both standard output and standard error streams) goes
1445 at end of BUFFER, unless you specify an output stream or filter
1446 function to handle the output. BUFFER may also be nil, meaning that
1447 this process is not associated with any buffer.
1449 PROGRAM is the program file name. It is searched for in `exec-path'
1450 (which see). If nil, just associate a pty with the buffer. Remaining
1451 arguments are strings to give program as arguments.
1453 If you want to separate standard output from standard error, invoke
1454 the command through a shell and redirect one of them using the shell
1455 syntax.
1457 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1458 (ptrdiff_t nargs, Lisp_Object *args)
1460 Lisp_Object buffer, name, program, proc, current_dir, tem;
1461 register unsigned char **new_argv;
1462 ptrdiff_t i;
1463 ptrdiff_t count = SPECPDL_INDEX ();
1465 buffer = args[1];
1466 if (!NILP (buffer))
1467 buffer = Fget_buffer_create (buffer);
1469 /* Make sure that the child will be able to chdir to the current
1470 buffer's current directory, or its unhandled equivalent. We
1471 can't just have the child check for an error when it does the
1472 chdir, since it's in a vfork.
1474 We have to GCPRO around this because Fexpand_file_name and
1475 Funhandled_file_name_directory might call a file name handling
1476 function. The argument list is protected by the caller, so all
1477 we really have to worry about is buffer. */
1479 struct gcpro gcpro1, gcpro2;
1481 current_dir = BVAR (current_buffer, directory);
1483 GCPRO2 (buffer, current_dir);
1485 current_dir = Funhandled_file_name_directory (current_dir);
1486 if (NILP (current_dir))
1487 /* If the file name handler says that current_dir is unreachable, use
1488 a sensible default. */
1489 current_dir = build_string ("~/");
1490 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1491 if (NILP (Ffile_accessible_directory_p (current_dir)))
1492 report_file_error ("Setting current directory",
1493 Fcons (BVAR (current_buffer, directory), Qnil));
1495 UNGCPRO;
1498 name = args[0];
1499 CHECK_STRING (name);
1501 program = args[2];
1503 if (!NILP (program))
1504 CHECK_STRING (program);
1506 proc = make_process (name);
1507 /* If an error occurs and we can't start the process, we want to
1508 remove it from the process list. This means that each error
1509 check in create_process doesn't need to call remove_process
1510 itself; it's all taken care of here. */
1511 record_unwind_protect (start_process_unwind, proc);
1513 PSET (XPROCESS (proc), childp, Qt);
1514 PSET (XPROCESS (proc), plist, Qnil);
1515 PSET (XPROCESS (proc), type, Qreal);
1516 PSET (XPROCESS (proc), buffer, buffer);
1517 PSET (XPROCESS (proc), sentinel, Qnil);
1518 PSET (XPROCESS (proc), filter, Qnil);
1519 PSET (XPROCESS (proc), command, Flist (nargs - 2, args + 2));
1521 #ifdef HAVE_GNUTLS
1522 /* AKA GNUTLS_INITSTAGE(proc). */
1523 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1524 PSET (XPROCESS (proc), gnutls_cred_type, Qnil);
1525 #endif
1527 #ifdef ADAPTIVE_READ_BUFFERING
1528 XPROCESS (proc)->adaptive_read_buffering
1529 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1530 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1531 #endif
1533 /* Make the process marker point into the process buffer (if any). */
1534 if (BUFFERP (buffer))
1535 set_marker_both (XPROCESS (proc)->mark, buffer,
1536 BUF_ZV (XBUFFER (buffer)),
1537 BUF_ZV_BYTE (XBUFFER (buffer)));
1540 /* Decide coding systems for communicating with the process. Here
1541 we don't setup the structure coding_system nor pay attention to
1542 unibyte mode. They are done in create_process. */
1544 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1545 Lisp_Object coding_systems = Qt;
1546 Lisp_Object val, *args2;
1547 struct gcpro gcpro1, gcpro2;
1549 val = Vcoding_system_for_read;
1550 if (NILP (val))
1552 args2 = alloca ((nargs + 1) * sizeof *args2);
1553 args2[0] = Qstart_process;
1554 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1555 GCPRO2 (proc, current_dir);
1556 if (!NILP (program))
1557 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1558 UNGCPRO;
1559 if (CONSP (coding_systems))
1560 val = XCAR (coding_systems);
1561 else if (CONSP (Vdefault_process_coding_system))
1562 val = XCAR (Vdefault_process_coding_system);
1564 PSET (XPROCESS (proc), decode_coding_system, val);
1566 val = Vcoding_system_for_write;
1567 if (NILP (val))
1569 if (EQ (coding_systems, Qt))
1571 args2 = alloca ((nargs + 1) * sizeof *args2);
1572 args2[0] = Qstart_process;
1573 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1574 GCPRO2 (proc, current_dir);
1575 if (!NILP (program))
1576 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1577 UNGCPRO;
1579 if (CONSP (coding_systems))
1580 val = XCDR (coding_systems);
1581 else if (CONSP (Vdefault_process_coding_system))
1582 val = XCDR (Vdefault_process_coding_system);
1584 PSET (XPROCESS (proc), encode_coding_system, val);
1585 /* Note: At this moment, the above coding system may leave
1586 text-conversion or eol-conversion unspecified. They will be
1587 decided after we read output from the process and decode it by
1588 some coding system, or just before we actually send a text to
1589 the process. */
1593 PSET (XPROCESS (proc), decoding_buf, empty_unibyte_string);
1594 XPROCESS (proc)->decoding_carryover = 0;
1595 PSET (XPROCESS (proc), encoding_buf, empty_unibyte_string);
1597 XPROCESS (proc)->inherit_coding_system_flag
1598 = !(NILP (buffer) || !inherit_process_coding_system);
1600 if (!NILP (program))
1602 /* If program file name is not absolute, search our path for it.
1603 Put the name we will really use in TEM. */
1604 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1605 && !(SCHARS (program) > 1
1606 && IS_DEVICE_SEP (SREF (program, 1))))
1608 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1610 tem = Qnil;
1611 GCPRO4 (name, program, buffer, current_dir);
1612 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1613 UNGCPRO;
1614 if (NILP (tem))
1615 report_file_error ("Searching for program", Fcons (program, Qnil));
1616 tem = Fexpand_file_name (tem, Qnil);
1618 else
1620 if (!NILP (Ffile_directory_p (program)))
1621 error ("Specified program for new process is a directory");
1622 tem = program;
1625 /* If program file name starts with /: for quoting a magic name,
1626 discard that. */
1627 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1628 && SREF (tem, 1) == ':')
1629 tem = Fsubstring (tem, make_number (2), Qnil);
1632 Lisp_Object arg_encoding = Qnil;
1633 struct gcpro gcpro1;
1634 GCPRO1 (tem);
1636 /* Encode the file name and put it in NEW_ARGV.
1637 That's where the child will use it to execute the program. */
1638 tem = Fcons (ENCODE_FILE (tem), Qnil);
1640 /* Here we encode arguments by the coding system used for sending
1641 data to the process. We don't support using different coding
1642 systems for encoding arguments and for encoding data sent to the
1643 process. */
1645 for (i = 3; i < nargs; i++)
1647 tem = Fcons (args[i], tem);
1648 CHECK_STRING (XCAR (tem));
1649 if (STRING_MULTIBYTE (XCAR (tem)))
1651 if (NILP (arg_encoding))
1652 arg_encoding = (complement_process_encoding_system
1653 (XPROCESS (proc)->encode_coding_system));
1654 XSETCAR (tem,
1655 code_convert_string_norecord
1656 (XCAR (tem), arg_encoding, 1));
1660 UNGCPRO;
1663 /* Now that everything is encoded we can collect the strings into
1664 NEW_ARGV. */
1665 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1666 new_argv[nargs - 2] = 0;
1668 for (i = nargs - 2; i-- != 0; )
1670 new_argv[i] = SDATA (XCAR (tem));
1671 tem = XCDR (tem);
1674 create_process (proc, (char **) new_argv, current_dir);
1676 else
1677 create_pty (proc);
1679 return unbind_to (count, proc);
1682 /* This function is the unwind_protect form for Fstart_process. If
1683 PROC doesn't have its pid set, then we know someone has signaled
1684 an error and the process wasn't started successfully, so we should
1685 remove it from the process list. */
1686 static Lisp_Object
1687 start_process_unwind (Lisp_Object proc)
1689 if (!PROCESSP (proc))
1690 abort ();
1692 /* Was PROC started successfully?
1693 -2 is used for a pty with no process, eg for gdb. */
1694 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1695 remove_process (proc);
1697 return Qnil;
1700 static void
1701 create_process_1 (struct atimer *timer)
1703 /* Nothing to do. */
1707 static void
1708 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1710 int inchannel, outchannel;
1711 pid_t pid;
1712 int sv[2];
1713 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1714 int wait_child_setup[2];
1715 #endif
1716 sigset_t procmask;
1717 sigset_t blocked;
1718 struct sigaction sigint_action;
1719 struct sigaction sigquit_action;
1720 struct sigaction sigpipe_action;
1721 #ifdef AIX
1722 struct sigaction sighup_action;
1723 #endif
1724 /* Use volatile to protect variables from being clobbered by longjmp. */
1725 volatile int forkin, forkout;
1726 volatile int pty_flag = 0;
1727 #ifndef USE_CRT_DLL
1728 extern char **environ;
1729 #endif
1731 inchannel = outchannel = -1;
1733 #ifdef HAVE_PTYS
1734 if (!NILP (Vprocess_connection_type))
1735 outchannel = inchannel = allocate_pty ();
1737 if (inchannel >= 0)
1739 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1740 /* On most USG systems it does not work to open the pty's tty here,
1741 then close it and reopen it in the child. */
1742 #ifdef O_NOCTTY
1743 /* Don't let this terminal become our controlling terminal
1744 (in case we don't have one). */
1745 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1746 #else
1747 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1748 #endif
1749 if (forkin < 0)
1750 report_file_error ("Opening pty", Qnil);
1751 #else
1752 forkin = forkout = -1;
1753 #endif /* not USG, or USG_SUBTTY_WORKS */
1754 pty_flag = 1;
1756 else
1757 #endif /* HAVE_PTYS */
1759 int tem;
1760 tem = pipe (sv);
1761 if (tem < 0)
1762 report_file_error ("Creating pipe", Qnil);
1763 inchannel = sv[0];
1764 forkout = sv[1];
1765 tem = pipe (sv);
1766 if (tem < 0)
1768 emacs_close (inchannel);
1769 emacs_close (forkout);
1770 report_file_error ("Creating pipe", Qnil);
1772 outchannel = sv[1];
1773 forkin = sv[0];
1776 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1778 int tem;
1780 tem = pipe (wait_child_setup);
1781 if (tem < 0)
1782 report_file_error ("Creating pipe", Qnil);
1783 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1784 if (tem >= 0)
1785 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1786 if (tem < 0)
1788 emacs_close (wait_child_setup[0]);
1789 emacs_close (wait_child_setup[1]);
1790 report_file_error ("Setting file descriptor flags", Qnil);
1793 #endif
1795 #ifdef O_NONBLOCK
1796 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1797 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1798 #else
1799 #ifdef O_NDELAY
1800 fcntl (inchannel, F_SETFL, O_NDELAY);
1801 fcntl (outchannel, F_SETFL, O_NDELAY);
1802 #endif
1803 #endif
1805 /* Record this as an active process, with its channels.
1806 As a result, child_setup will close Emacs's side of the pipes. */
1807 chan_process[inchannel] = process;
1808 XPROCESS (process)->infd = inchannel;
1809 XPROCESS (process)->outfd = outchannel;
1811 /* Previously we recorded the tty descriptor used in the subprocess.
1812 It was only used for getting the foreground tty process, so now
1813 we just reopen the device (see emacs_get_tty_pgrp) as this is
1814 more portable (see USG_SUBTTY_WORKS above). */
1816 XPROCESS (process)->pty_flag = pty_flag;
1817 PSET (XPROCESS (process), status, Qrun);
1819 /* Delay interrupts until we have a chance to store
1820 the new fork's pid in its process structure */
1821 sigemptyset (&blocked);
1822 #ifdef SIGCHLD
1823 sigaddset (&blocked, SIGCHLD);
1824 #endif
1825 #ifdef HAVE_WORKING_VFORK
1826 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1827 this sets the parent's signal handlers as well as the child's.
1828 So delay all interrupts whose handlers the child might munge,
1829 and record the current handlers so they can be restored later. */
1830 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1831 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1832 sigaddset (&blocked, SIGPIPE); sigaction (SIGPIPE, 0, &sigpipe_action);
1833 #ifdef AIX
1834 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1835 #endif
1836 #endif /* HAVE_WORKING_VFORK */
1837 pthread_sigmask (SIG_BLOCK, &blocked, &procmask);
1839 add_non_keyboard_read_fd (inchannel);
1841 /* Until we store the proper pid, enable sigchld_handler
1842 to recognize an unknown pid as standing for this process.
1843 It is very important not to let this `marker' value stay
1844 in the table after this function has returned; if it does
1845 it might cause call-process to hang and subsequent asynchronous
1846 processes to get their return values scrambled. */
1847 XPROCESS (process)->pid = -1;
1849 /* This must be called after the above line because it may signal an
1850 error. */
1851 setup_process_coding_systems (process);
1853 BLOCK_INPUT;
1856 /* child_setup must clobber environ on systems with true vfork.
1857 Protect it from permanent change. */
1858 char **save_environ = environ;
1859 volatile Lisp_Object encoded_current_dir = ENCODE_FILE (current_dir);
1861 #ifndef WINDOWSNT
1862 pid = vfork ();
1863 if (pid == 0)
1864 #endif /* not WINDOWSNT */
1866 int xforkin = forkin;
1867 int xforkout = forkout;
1869 #if 0 /* This was probably a mistake--it duplicates code later on,
1870 but fails to handle all the cases. */
1871 /* Make sure SIGCHLD is not blocked in the child. */
1872 sigsetmask (SIGEMPTYMASK);
1873 #endif
1875 /* Make the pty be the controlling terminal of the process. */
1876 #ifdef HAVE_PTYS
1877 /* First, disconnect its current controlling terminal. */
1878 #ifdef HAVE_SETSID
1879 /* We tried doing setsid only if pty_flag, but it caused
1880 process_set_signal to fail on SGI when using a pipe. */
1881 setsid ();
1882 /* Make the pty's terminal the controlling terminal. */
1883 if (pty_flag && xforkin >= 0)
1885 #ifdef TIOCSCTTY
1886 /* We ignore the return value
1887 because faith@cs.unc.edu says that is necessary on Linux. */
1888 ioctl (xforkin, TIOCSCTTY, 0);
1889 #endif
1891 #else /* not HAVE_SETSID */
1892 #ifdef USG
1893 /* It's very important to call setpgrp here and no time
1894 afterwards. Otherwise, we lose our controlling tty which
1895 is set when we open the pty. */
1896 setpgrp ();
1897 #endif /* USG */
1898 #endif /* not HAVE_SETSID */
1899 #if defined (LDISC1)
1900 if (pty_flag && xforkin >= 0)
1902 struct termios t;
1903 tcgetattr (xforkin, &t);
1904 t.c_lflag = LDISC1;
1905 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1906 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1908 #else
1909 #if defined (NTTYDISC) && defined (TIOCSETD)
1910 if (pty_flag && xforkin >= 0)
1912 /* Use new line discipline. */
1913 int ldisc = NTTYDISC;
1914 ioctl (xforkin, TIOCSETD, &ldisc);
1916 #endif
1917 #endif
1918 #ifdef TIOCNOTTY
1919 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1920 can do TIOCSPGRP only to the process's controlling tty. */
1921 if (pty_flag)
1923 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1924 I can't test it since I don't have 4.3. */
1925 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1926 if (j >= 0)
1928 ioctl (j, TIOCNOTTY, 0);
1929 emacs_close (j);
1931 #ifndef USG
1932 /* In order to get a controlling terminal on some versions
1933 of BSD, it is necessary to put the process in pgrp 0
1934 before it opens the terminal. */
1935 #ifdef HAVE_SETPGID
1936 setpgid (0, 0);
1937 #else
1938 setpgrp (0, 0);
1939 #endif
1940 #endif
1942 #endif /* TIOCNOTTY */
1944 #if !defined (DONT_REOPEN_PTY)
1945 /*** There is a suggestion that this ought to be a
1946 conditional on TIOCSPGRP,
1947 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1948 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1949 that system does seem to need this code, even though
1950 both HAVE_SETSID and TIOCSCTTY are defined. */
1951 /* Now close the pty (if we had it open) and reopen it.
1952 This makes the pty the controlling terminal of the subprocess. */
1953 if (pty_flag)
1956 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1957 would work? */
1958 if (xforkin >= 0)
1959 emacs_close (xforkin);
1960 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1962 if (xforkin < 0)
1964 emacs_write (1, "Couldn't open the pty terminal ", 31);
1965 emacs_write (1, pty_name, strlen (pty_name));
1966 emacs_write (1, "\n", 1);
1967 _exit (1);
1971 #endif /* not DONT_REOPEN_PTY */
1973 #ifdef SETUP_SLAVE_PTY
1974 if (pty_flag)
1976 SETUP_SLAVE_PTY;
1978 #endif /* SETUP_SLAVE_PTY */
1979 #ifdef AIX
1980 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1981 Now reenable it in the child, so it will die when we want it to. */
1982 if (pty_flag)
1983 signal (SIGHUP, SIG_DFL);
1984 #endif
1985 #endif /* HAVE_PTYS */
1987 signal (SIGINT, SIG_DFL);
1988 signal (SIGQUIT, SIG_DFL);
1989 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1990 in the child. */
1991 signal (SIGPIPE, SIG_DFL);
1993 /* Stop blocking signals in the child. */
1994 pthread_sigmask (SIG_SETMASK, &procmask, 0);
1996 if (pty_flag)
1997 child_setup_tty (xforkout);
1998 #ifdef WINDOWSNT
1999 pid = child_setup (xforkin, xforkout, xforkout,
2000 new_argv, 1, encoded_current_dir);
2001 #else /* not WINDOWSNT */
2002 #ifdef FD_CLOEXEC
2003 emacs_close (wait_child_setup[0]);
2004 #endif
2005 child_setup (xforkin, xforkout, xforkout,
2006 new_argv, 1, encoded_current_dir);
2007 #endif /* not WINDOWSNT */
2009 environ = save_environ;
2012 UNBLOCK_INPUT;
2014 /* This runs in the Emacs process. */
2015 if (pid < 0)
2017 if (forkin >= 0)
2018 emacs_close (forkin);
2019 if (forkin != forkout && forkout >= 0)
2020 emacs_close (forkout);
2022 else
2024 /* vfork succeeded. */
2025 XPROCESS (process)->pid = pid;
2027 #ifdef WINDOWSNT
2028 register_child (pid, inchannel);
2029 #endif /* WINDOWSNT */
2031 /* If the subfork execv fails, and it exits,
2032 this close hangs. I don't know why.
2033 So have an interrupt jar it loose. */
2035 struct atimer *timer;
2036 EMACS_TIME offset = make_emacs_time (1, 0);
2038 stop_polling ();
2039 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2041 if (forkin >= 0)
2042 emacs_close (forkin);
2044 cancel_atimer (timer);
2045 start_polling ();
2048 if (forkin != forkout && forkout >= 0)
2049 emacs_close (forkout);
2051 #ifdef HAVE_PTYS
2052 if (pty_flag)
2053 PSET (XPROCESS (process), tty_name, build_string (pty_name));
2054 else
2055 #endif
2056 PSET (XPROCESS (process), tty_name, Qnil);
2058 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2059 /* Wait for child_setup to complete in case that vfork is
2060 actually defined as fork. The descriptor wait_child_setup[1]
2061 of a pipe is closed at the child side either by close-on-exec
2062 on successful execvp or the _exit call in child_setup. */
2064 char dummy;
2066 emacs_close (wait_child_setup[1]);
2067 emacs_read (wait_child_setup[0], &dummy, 1);
2068 emacs_close (wait_child_setup[0]);
2070 #endif
2073 /* Restore the signal state whether vfork succeeded or not.
2074 (We will signal an error, below, if it failed.) */
2075 #ifdef HAVE_WORKING_VFORK
2076 /* Restore the parent's signal handlers. */
2077 sigaction (SIGINT, &sigint_action, 0);
2078 sigaction (SIGQUIT, &sigquit_action, 0);
2079 sigaction (SIGPIPE, &sigpipe_action, 0);
2080 #ifdef AIX
2081 sigaction (SIGHUP, &sighup_action, 0);
2082 #endif
2083 #endif /* HAVE_WORKING_VFORK */
2084 /* Stop blocking signals in the parent. */
2085 pthread_sigmask (SIG_SETMASK, &procmask, 0);
2087 /* Now generate the error if vfork failed. */
2088 if (pid < 0)
2089 report_file_error ("Doing vfork", Qnil);
2092 void
2093 create_pty (Lisp_Object process)
2095 int inchannel, outchannel;
2096 int pty_flag = 0;
2098 inchannel = outchannel = -1;
2100 #ifdef HAVE_PTYS
2101 if (!NILP (Vprocess_connection_type))
2102 outchannel = inchannel = allocate_pty ();
2104 if (inchannel >= 0)
2106 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2107 /* On most USG systems it does not work to open the pty's tty here,
2108 then close it and reopen it in the child. */
2109 #ifdef O_NOCTTY
2110 /* Don't let this terminal become our controlling terminal
2111 (in case we don't have one). */
2112 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2113 #else
2114 int forkout = emacs_open (pty_name, O_RDWR, 0);
2115 #endif
2116 if (forkout < 0)
2117 report_file_error ("Opening pty", Qnil);
2118 #if defined (DONT_REOPEN_PTY)
2119 /* In the case that vfork is defined as fork, the parent process
2120 (Emacs) may send some data before the child process completes
2121 tty options setup. So we setup tty before forking. */
2122 child_setup_tty (forkout);
2123 #endif /* DONT_REOPEN_PTY */
2124 #endif /* not USG, or USG_SUBTTY_WORKS */
2125 pty_flag = 1;
2127 #endif /* HAVE_PTYS */
2129 #ifdef O_NONBLOCK
2130 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2131 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2132 #else
2133 #ifdef O_NDELAY
2134 fcntl (inchannel, F_SETFL, O_NDELAY);
2135 fcntl (outchannel, F_SETFL, O_NDELAY);
2136 #endif
2137 #endif
2139 /* Record this as an active process, with its channels.
2140 As a result, child_setup will close Emacs's side of the pipes. */
2141 chan_process[inchannel] = process;
2142 XPROCESS (process)->infd = inchannel;
2143 XPROCESS (process)->outfd = outchannel;
2145 /* Previously we recorded the tty descriptor used in the subprocess.
2146 It was only used for getting the foreground tty process, so now
2147 we just reopen the device (see emacs_get_tty_pgrp) as this is
2148 more portable (see USG_SUBTTY_WORKS above). */
2150 XPROCESS (process)->pty_flag = pty_flag;
2151 PSET (XPROCESS (process), status, Qrun);
2152 setup_process_coding_systems (process);
2154 add_non_keyboard_read_fd (inchannel);
2156 XPROCESS (process)->pid = -2;
2157 #ifdef HAVE_PTYS
2158 if (pty_flag)
2159 PSET (XPROCESS (process), tty_name, build_string (pty_name));
2160 else
2161 #endif
2162 PSET (XPROCESS (process), tty_name, Qnil);
2166 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2167 The address family of sa is not included in the result. */
2169 static Lisp_Object
2170 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2172 Lisp_Object address;
2173 int i;
2174 unsigned char *cp;
2175 register struct Lisp_Vector *p;
2177 /* Workaround for a bug in getsockname on BSD: Names bound to
2178 sockets in the UNIX domain are inaccessible; getsockname returns
2179 a zero length name. */
2180 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2181 return empty_unibyte_string;
2183 switch (sa->sa_family)
2185 case AF_INET:
2187 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2188 len = sizeof (sin->sin_addr) + 1;
2189 address = Fmake_vector (make_number (len), Qnil);
2190 p = XVECTOR (address);
2191 p->contents[--len] = make_number (ntohs (sin->sin_port));
2192 cp = (unsigned char *) &sin->sin_addr;
2193 break;
2195 #ifdef AF_INET6
2196 case AF_INET6:
2198 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2199 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2200 len = sizeof (sin6->sin6_addr)/2 + 1;
2201 address = Fmake_vector (make_number (len), Qnil);
2202 p = XVECTOR (address);
2203 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2204 for (i = 0; i < len; i++)
2205 p->contents[i] = make_number (ntohs (ip6[i]));
2206 return address;
2208 #endif
2209 #ifdef HAVE_LOCAL_SOCKETS
2210 case AF_LOCAL:
2212 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2213 for (i = 0; i < sizeof (sockun->sun_path); i++)
2214 if (sockun->sun_path[i] == 0)
2215 break;
2216 return make_unibyte_string (sockun->sun_path, i);
2218 #endif
2219 default:
2220 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2221 address = Fcons (make_number (sa->sa_family),
2222 Fmake_vector (make_number (len), Qnil));
2223 p = XVECTOR (XCDR (address));
2224 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2225 break;
2228 i = 0;
2229 while (i < len)
2230 p->contents[i++] = make_number (*cp++);
2232 return address;
2236 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2238 static int
2239 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2241 register struct Lisp_Vector *p;
2243 if (VECTORP (address))
2245 p = XVECTOR (address);
2246 if (p->header.size == 5)
2248 *familyp = AF_INET;
2249 return sizeof (struct sockaddr_in);
2251 #ifdef AF_INET6
2252 else if (p->header.size == 9)
2254 *familyp = AF_INET6;
2255 return sizeof (struct sockaddr_in6);
2257 #endif
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 else if (STRINGP (address))
2262 *familyp = AF_LOCAL;
2263 return sizeof (struct sockaddr_un);
2265 #endif
2266 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2267 && VECTORP (XCDR (address)))
2269 struct sockaddr *sa;
2270 *familyp = XINT (XCAR (address));
2271 p = XVECTOR (XCDR (address));
2272 return p->header.size + sizeof (sa->sa_family);
2274 return 0;
2277 /* Convert an address object (vector or string) to an internal sockaddr.
2279 The address format has been basically validated by
2280 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2281 it could have come from user data. So if FAMILY is not valid,
2282 we return after zeroing *SA. */
2284 static void
2285 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2287 register struct Lisp_Vector *p;
2288 register unsigned char *cp = NULL;
2289 register int i;
2290 EMACS_INT hostport;
2292 memset (sa, 0, len);
2294 if (VECTORP (address))
2296 p = XVECTOR (address);
2297 if (family == AF_INET)
2299 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2300 len = sizeof (sin->sin_addr) + 1;
2301 hostport = XINT (p->contents[--len]);
2302 sin->sin_port = htons (hostport);
2303 cp = (unsigned char *)&sin->sin_addr;
2304 sa->sa_family = family;
2306 #ifdef AF_INET6
2307 else if (family == AF_INET6)
2309 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2310 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2311 len = sizeof (sin6->sin6_addr) + 1;
2312 hostport = XINT (p->contents[--len]);
2313 sin6->sin6_port = htons (hostport);
2314 for (i = 0; i < len; i++)
2315 if (INTEGERP (p->contents[i]))
2317 int j = XFASTINT (p->contents[i]) & 0xffff;
2318 ip6[i] = ntohs (j);
2320 sa->sa_family = family;
2321 return;
2323 #endif
2324 else
2325 return;
2327 else if (STRINGP (address))
2329 #ifdef HAVE_LOCAL_SOCKETS
2330 if (family == AF_LOCAL)
2332 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2333 cp = SDATA (address);
2334 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2335 sockun->sun_path[i] = *cp++;
2336 sa->sa_family = family;
2338 #endif
2339 return;
2341 else
2343 p = XVECTOR (XCDR (address));
2344 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2347 for (i = 0; i < len; i++)
2348 if (INTEGERP (p->contents[i]))
2349 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2352 #ifdef DATAGRAM_SOCKETS
2353 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2354 1, 1, 0,
2355 doc: /* Get the current datagram address associated with PROCESS. */)
2356 (Lisp_Object process)
2358 int channel;
2360 CHECK_PROCESS (process);
2362 if (!DATAGRAM_CONN_P (process))
2363 return Qnil;
2365 channel = XPROCESS (process)->infd;
2366 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2367 datagram_address[channel].len);
2370 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2371 2, 2, 0,
2372 doc: /* Set the datagram address for PROCESS to ADDRESS.
2373 Returns nil upon error setting address, ADDRESS otherwise. */)
2374 (Lisp_Object process, Lisp_Object address)
2376 int channel;
2377 int family, len;
2379 CHECK_PROCESS (process);
2381 if (!DATAGRAM_CONN_P (process))
2382 return Qnil;
2384 channel = XPROCESS (process)->infd;
2386 len = get_lisp_to_sockaddr_size (address, &family);
2387 if (datagram_address[channel].len != len)
2388 return Qnil;
2389 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2390 return address;
2392 #endif
2395 static const struct socket_options {
2396 /* The name of this option. Should be lowercase version of option
2397 name without SO_ prefix. */
2398 const char *name;
2399 /* Option level SOL_... */
2400 int optlevel;
2401 /* Option number SO_... */
2402 int optnum;
2403 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2404 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2405 } socket_options[] =
2407 #ifdef SO_BINDTODEVICE
2408 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2409 #endif
2410 #ifdef SO_BROADCAST
2411 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2412 #endif
2413 #ifdef SO_DONTROUTE
2414 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2415 #endif
2416 #ifdef SO_KEEPALIVE
2417 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2418 #endif
2419 #ifdef SO_LINGER
2420 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2421 #endif
2422 #ifdef SO_OOBINLINE
2423 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2424 #endif
2425 #ifdef SO_PRIORITY
2426 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2427 #endif
2428 #ifdef SO_REUSEADDR
2429 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2430 #endif
2431 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2434 /* Set option OPT to value VAL on socket S.
2436 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2437 Signals an error if setting a known option fails.
2440 static int
2441 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2443 char *name;
2444 const struct socket_options *sopt;
2445 int ret = 0;
2447 CHECK_SYMBOL (opt);
2449 name = SSDATA (SYMBOL_NAME (opt));
2450 for (sopt = socket_options; sopt->name; sopt++)
2451 if (strcmp (name, sopt->name) == 0)
2452 break;
2454 switch (sopt->opttype)
2456 case SOPT_BOOL:
2458 int optval;
2459 optval = NILP (val) ? 0 : 1;
2460 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2461 &optval, sizeof (optval));
2462 break;
2465 case SOPT_INT:
2467 int optval;
2468 if (TYPE_RANGED_INTEGERP (int, val))
2469 optval = XINT (val);
2470 else
2471 error ("Bad option value for %s", name);
2472 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2473 &optval, sizeof (optval));
2474 break;
2477 #ifdef SO_BINDTODEVICE
2478 case SOPT_IFNAME:
2480 char devname[IFNAMSIZ+1];
2482 /* This is broken, at least in the Linux 2.4 kernel.
2483 To unbind, the arg must be a zero integer, not the empty string.
2484 This should work on all systems. KFS. 2003-09-23. */
2485 memset (devname, 0, sizeof devname);
2486 if (STRINGP (val))
2488 char *arg = SSDATA (val);
2489 int len = min (strlen (arg), IFNAMSIZ);
2490 memcpy (devname, arg, len);
2492 else if (!NILP (val))
2493 error ("Bad option value for %s", name);
2494 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2495 devname, IFNAMSIZ);
2496 break;
2498 #endif
2500 #ifdef SO_LINGER
2501 case SOPT_LINGER:
2503 struct linger linger;
2505 linger.l_onoff = 1;
2506 linger.l_linger = 0;
2507 if (TYPE_RANGED_INTEGERP (int, val))
2508 linger.l_linger = XINT (val);
2509 else
2510 linger.l_onoff = NILP (val) ? 0 : 1;
2511 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2512 &linger, sizeof (linger));
2513 break;
2515 #endif
2517 default:
2518 return 0;
2521 if (ret < 0)
2522 report_file_error ("Cannot set network option",
2523 Fcons (opt, Fcons (val, Qnil)));
2524 return (1 << sopt->optbit);
2528 DEFUN ("set-network-process-option",
2529 Fset_network_process_option, Sset_network_process_option,
2530 3, 4, 0,
2531 doc: /* For network process PROCESS set option OPTION to value VALUE.
2532 See `make-network-process' for a list of options and values.
2533 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2534 OPTION is not a supported option, return nil instead; otherwise return t. */)
2535 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2537 int s;
2538 struct Lisp_Process *p;
2540 CHECK_PROCESS (process);
2541 p = XPROCESS (process);
2542 if (!NETCONN1_P (p))
2543 error ("Process is not a network process");
2545 s = p->infd;
2546 if (s < 0)
2547 error ("Process is not running");
2549 if (set_socket_option (s, option, value))
2551 PSET (p, childp, Fplist_put (p->childp, option, value));
2552 return Qt;
2555 if (NILP (no_error))
2556 error ("Unknown or unsupported option");
2558 return Qnil;
2562 DEFUN ("serial-process-configure",
2563 Fserial_process_configure,
2564 Sserial_process_configure,
2565 0, MANY, 0,
2566 doc: /* Configure speed, bytesize, etc. of a serial process.
2568 Arguments are specified as keyword/argument pairs. Attributes that
2569 are not given are re-initialized from the process's current
2570 configuration (available via the function `process-contact') or set to
2571 reasonable default values. The following arguments are defined:
2573 :process PROCESS
2574 :name NAME
2575 :buffer BUFFER
2576 :port PORT
2577 -- Any of these arguments can be given to identify the process that is
2578 to be configured. If none of these arguments is given, the current
2579 buffer's process is used.
2581 :speed SPEED -- SPEED is the speed of the serial port in bits per
2582 second, also called baud rate. Any value can be given for SPEED, but
2583 most serial ports work only at a few defined values between 1200 and
2584 115200, with 9600 being the most common value. If SPEED is nil, the
2585 serial port is not configured any further, i.e., all other arguments
2586 are ignored. This may be useful for special serial ports such as
2587 Bluetooth-to-serial converters which can only be configured through AT
2588 commands. A value of nil for SPEED can be used only when passed
2589 through `make-serial-process' or `serial-term'.
2591 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2592 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2594 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2595 `odd' (use odd parity), or the symbol `even' (use even parity). If
2596 PARITY is not given, no parity is used.
2598 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2599 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2600 is not given or nil, 1 stopbit is used.
2602 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2603 flowcontrol to be used, which is either nil (don't use flowcontrol),
2604 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2605 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2606 flowcontrol is used.
2608 `serial-process-configure' is called by `make-serial-process' for the
2609 initial configuration of the serial port.
2611 Examples:
2613 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2615 \(serial-process-configure
2616 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2618 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2620 usage: (serial-process-configure &rest ARGS) */)
2621 (ptrdiff_t nargs, Lisp_Object *args)
2623 struct Lisp_Process *p;
2624 Lisp_Object contact = Qnil;
2625 Lisp_Object proc = Qnil;
2626 struct gcpro gcpro1;
2628 contact = Flist (nargs, args);
2629 GCPRO1 (contact);
2631 proc = Fplist_get (contact, QCprocess);
2632 if (NILP (proc))
2633 proc = Fplist_get (contact, QCname);
2634 if (NILP (proc))
2635 proc = Fplist_get (contact, QCbuffer);
2636 if (NILP (proc))
2637 proc = Fplist_get (contact, QCport);
2638 proc = get_process (proc);
2639 p = XPROCESS (proc);
2640 if (!EQ (p->type, Qserial))
2641 error ("Not a serial process");
2643 if (NILP (Fplist_get (p->childp, QCspeed)))
2645 UNGCPRO;
2646 return Qnil;
2649 serial_configure (p, contact);
2651 UNGCPRO;
2652 return Qnil;
2655 /* Used by make-serial-process to recover from errors. */
2656 static Lisp_Object
2657 make_serial_process_unwind (Lisp_Object proc)
2659 if (!PROCESSP (proc))
2660 abort ();
2661 remove_process (proc);
2662 return Qnil;
2665 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2666 0, MANY, 0,
2667 doc: /* Create and return a serial port process.
2669 In Emacs, serial port connections are represented by process objects,
2670 so input and output work as for subprocesses, and `delete-process'
2671 closes a serial port connection. However, a serial process has no
2672 process id, it cannot be signaled, and the status codes are different
2673 from normal processes.
2675 `make-serial-process' creates a process and a buffer, on which you
2676 probably want to use `process-send-string'. Try \\[serial-term] for
2677 an interactive terminal. See below for examples.
2679 Arguments are specified as keyword/argument pairs. The following
2680 arguments are defined:
2682 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2683 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2684 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2685 the backslashes in strings).
2687 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2688 which this function calls.
2690 :name NAME -- NAME is the name of the process. If NAME is not given,
2691 the value of PORT is used.
2693 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2694 with the process. Process output goes at the end of that buffer,
2695 unless you specify an output stream or filter function to handle the
2696 output. If BUFFER is not given, the value of NAME is used.
2698 :coding CODING -- If CODING is a symbol, it specifies the coding
2699 system used for both reading and writing for this process. If CODING
2700 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2701 ENCODING is used for writing.
2703 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2704 the process is running. If BOOL is not given, query before exiting.
2706 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2707 In the stopped state, a serial process does not accept incoming data,
2708 but you can send outgoing data. The stopped state is cleared by
2709 `continue-process' and set by `stop-process'.
2711 :filter FILTER -- Install FILTER as the process filter.
2713 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2715 :plist PLIST -- Install PLIST as the initial plist of the process.
2717 :bytesize
2718 :parity
2719 :stopbits
2720 :flowcontrol
2721 -- This function calls `serial-process-configure' to handle these
2722 arguments.
2724 The original argument list, possibly modified by later configuration,
2725 is available via the function `process-contact'.
2727 Examples:
2729 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2731 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2733 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2735 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2737 usage: (make-serial-process &rest ARGS) */)
2738 (ptrdiff_t nargs, Lisp_Object *args)
2740 int fd = -1;
2741 Lisp_Object proc, contact, port;
2742 struct Lisp_Process *p;
2743 struct gcpro gcpro1;
2744 Lisp_Object name, buffer;
2745 Lisp_Object tem, val;
2746 ptrdiff_t specpdl_count = -1;
2748 if (nargs == 0)
2749 return Qnil;
2751 contact = Flist (nargs, args);
2752 GCPRO1 (contact);
2754 port = Fplist_get (contact, QCport);
2755 if (NILP (port))
2756 error ("No port specified");
2757 CHECK_STRING (port);
2759 if (NILP (Fplist_member (contact, QCspeed)))
2760 error (":speed not specified");
2761 if (!NILP (Fplist_get (contact, QCspeed)))
2762 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2764 name = Fplist_get (contact, QCname);
2765 if (NILP (name))
2766 name = port;
2767 CHECK_STRING (name);
2768 proc = make_process (name);
2769 specpdl_count = SPECPDL_INDEX ();
2770 record_unwind_protect (make_serial_process_unwind, proc);
2771 p = XPROCESS (proc);
2773 fd = serial_open (SSDATA (port));
2774 p->infd = fd;
2775 p->outfd = fd;
2776 if (fd > max_process_desc)
2777 max_process_desc = fd;
2778 chan_process[fd] = proc;
2780 buffer = Fplist_get (contact, QCbuffer);
2781 if (NILP (buffer))
2782 buffer = name;
2783 buffer = Fget_buffer_create (buffer);
2784 PSET (p, buffer, buffer);
2786 PSET (p, childp, contact);
2787 PSET (p, plist, Fcopy_sequence (Fplist_get (contact, QCplist)));
2788 PSET (p, type, Qserial);
2789 PSET (p, sentinel, Fplist_get (contact, QCsentinel));
2790 PSET (p, filter, Fplist_get (contact, QCfilter));
2791 PSET (p, log, Qnil);
2792 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2793 p->kill_without_query = 1;
2794 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2795 PSET (p, command, Qt);
2796 p->pty_flag = 0;
2798 if (!EQ (p->command, Qt))
2799 add_non_keyboard_read_fd (fd);
2801 if (BUFFERP (buffer))
2803 set_marker_both (p->mark, buffer,
2804 BUF_ZV (XBUFFER (buffer)),
2805 BUF_ZV_BYTE (XBUFFER (buffer)));
2808 tem = Fplist_member (contact, QCcoding);
2809 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2810 tem = Qnil;
2812 val = Qnil;
2813 if (!NILP (tem))
2815 val = XCAR (XCDR (tem));
2816 if (CONSP (val))
2817 val = XCAR (val);
2819 else if (!NILP (Vcoding_system_for_read))
2820 val = Vcoding_system_for_read;
2821 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2822 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2823 val = Qnil;
2824 PSET (p, decode_coding_system, val);
2826 val = Qnil;
2827 if (!NILP (tem))
2829 val = XCAR (XCDR (tem));
2830 if (CONSP (val))
2831 val = XCDR (val);
2833 else if (!NILP (Vcoding_system_for_write))
2834 val = Vcoding_system_for_write;
2835 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2836 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2837 val = Qnil;
2838 PSET (p, encode_coding_system, val);
2840 setup_process_coding_systems (proc);
2841 PSET (p, decoding_buf, empty_unibyte_string);
2842 p->decoding_carryover = 0;
2843 PSET (p, encoding_buf, empty_unibyte_string);
2844 p->inherit_coding_system_flag
2845 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2847 Fserial_process_configure (nargs, args);
2849 specpdl_ptr = specpdl + specpdl_count;
2851 UNGCPRO;
2852 return proc;
2855 /* Create a network stream/datagram client/server process. Treated
2856 exactly like a normal process when reading and writing. Primary
2857 differences are in status display and process deletion. A network
2858 connection has no PID; you cannot signal it. All you can do is
2859 stop/continue it and deactivate/close it via delete-process */
2861 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2862 0, MANY, 0,
2863 doc: /* Create and return a network server or client process.
2865 In Emacs, network connections are represented by process objects, so
2866 input and output work as for subprocesses and `delete-process' closes
2867 a network connection. However, a network process has no process id,
2868 it cannot be signaled, and the status codes are different from normal
2869 processes.
2871 Arguments are specified as keyword/argument pairs. The following
2872 arguments are defined:
2874 :name NAME -- NAME is name for process. It is modified if necessary
2875 to make it unique.
2877 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2878 with the process. Process output goes at end of that buffer, unless
2879 you specify an output stream or filter function to handle the output.
2880 BUFFER may be also nil, meaning that this process is not associated
2881 with any buffer.
2883 :host HOST -- HOST is name of the host to connect to, or its IP
2884 address. The symbol `local' specifies the local host. If specified
2885 for a server process, it must be a valid name or address for the local
2886 host, and only clients connecting to that address will be accepted.
2888 :service SERVICE -- SERVICE is name of the service desired, or an
2889 integer specifying a port number to connect to. If SERVICE is t,
2890 a random port number is selected for the server. (If Emacs was
2891 compiled with getaddrinfo, a port number can also be specified as a
2892 string, e.g. "80", as well as an integer. This is not portable.)
2894 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2895 stream type connection, `datagram' creates a datagram type connection,
2896 `seqpacket' creates a reliable datagram connection.
2898 :family FAMILY -- FAMILY is the address (and protocol) family for the
2899 service specified by HOST and SERVICE. The default (nil) is to use
2900 whatever address family (IPv4 or IPv6) that is defined for the host
2901 and port number specified by HOST and SERVICE. Other address families
2902 supported are:
2903 local -- for a local (i.e. UNIX) address specified by SERVICE.
2904 ipv4 -- use IPv4 address family only.
2905 ipv6 -- use IPv6 address family only.
2907 :local ADDRESS -- ADDRESS is the local address used for the connection.
2908 This parameter is ignored when opening a client process. When specified
2909 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2911 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2912 connection. This parameter is ignored when opening a stream server
2913 process. For a datagram server process, it specifies the initial
2914 setting of the remote datagram address. When specified for a client
2915 process, the FAMILY, HOST, and SERVICE args are ignored.
2917 The format of ADDRESS depends on the address family:
2918 - An IPv4 address is represented as an vector of integers [A B C D P]
2919 corresponding to numeric IP address A.B.C.D and port number P.
2920 - A local address is represented as a string with the address in the
2921 local address space.
2922 - An "unsupported family" address is represented by a cons (F . AV)
2923 where F is the family number and AV is a vector containing the socket
2924 address data with one element per address data byte. Do not rely on
2925 this format in portable code, as it may depend on implementation
2926 defined constants, data sizes, and data structure alignment.
2928 :coding CODING -- If CODING is a symbol, it specifies the coding
2929 system used for both reading and writing for this process. If CODING
2930 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2931 ENCODING is used for writing.
2933 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2934 return without waiting for the connection to complete; instead, the
2935 sentinel function will be called with second arg matching "open" (if
2936 successful) or "failed" when the connect completes. Default is to use
2937 a blocking connect (i.e. wait) for stream type connections.
2939 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2940 running when Emacs is exited.
2942 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2943 In the stopped state, a server process does not accept new
2944 connections, and a client process does not handle incoming traffic.
2945 The stopped state is cleared by `continue-process' and set by
2946 `stop-process'.
2948 :filter FILTER -- Install FILTER as the process filter.
2950 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2951 process filter are multibyte, otherwise they are unibyte.
2952 If this keyword is not specified, the strings are multibyte if
2953 the default value of `enable-multibyte-characters' is non-nil.
2955 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2957 :log LOG -- Install LOG as the server process log function. This
2958 function is called when the server accepts a network connection from a
2959 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2960 is the server process, CLIENT is the new process for the connection,
2961 and MESSAGE is a string.
2963 :plist PLIST -- Install PLIST as the new process' initial plist.
2965 :server QLEN -- if QLEN is non-nil, create a server process for the
2966 specified FAMILY, SERVICE, and connection type (stream or datagram).
2967 If QLEN is an integer, it is used as the max. length of the server's
2968 pending connection queue (also known as the backlog); the default
2969 queue length is 5. Default is to create a client process.
2971 The following network options can be specified for this connection:
2973 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2974 :dontroute BOOL -- Only send to directly connected hosts.
2975 :keepalive BOOL -- Send keep-alive messages on network stream.
2976 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2977 :oobinline BOOL -- Place out-of-band data in receive data stream.
2978 :priority INT -- Set protocol defined priority for sent packets.
2979 :reuseaddr BOOL -- Allow reusing a recently used local address
2980 (this is allowed by default for a server process).
2981 :bindtodevice NAME -- bind to interface NAME. Using this may require
2982 special privileges on some systems.
2984 Consult the relevant system programmer's manual pages for more
2985 information on using these options.
2988 A server process will listen for and accept connections from clients.
2989 When a client connection is accepted, a new network process is created
2990 for the connection with the following parameters:
2992 - The client's process name is constructed by concatenating the server
2993 process' NAME and a client identification string.
2994 - If the FILTER argument is non-nil, the client process will not get a
2995 separate process buffer; otherwise, the client's process buffer is a newly
2996 created buffer named after the server process' BUFFER name or process
2997 NAME concatenated with the client identification string.
2998 - The connection type and the process filter and sentinel parameters are
2999 inherited from the server process' TYPE, FILTER and SENTINEL.
3000 - The client process' contact info is set according to the client's
3001 addressing information (typically an IP address and a port number).
3002 - The client process' plist is initialized from the server's plist.
3004 Notice that the FILTER and SENTINEL args are never used directly by
3005 the server process. Also, the BUFFER argument is not used directly by
3006 the server process, but via the optional :log function, accepted (and
3007 failed) connections may be logged in the server process' buffer.
3009 The original argument list, modified with the actual connection
3010 information, is available via the `process-contact' function.
3012 usage: (make-network-process &rest ARGS) */)
3013 (ptrdiff_t nargs, Lisp_Object *args)
3015 Lisp_Object proc;
3016 Lisp_Object contact;
3017 struct Lisp_Process *p;
3018 #ifdef HAVE_GETADDRINFO
3019 struct addrinfo ai, *res, *lres;
3020 struct addrinfo hints;
3021 const char *portstring;
3022 char portbuf[128];
3023 #else /* HAVE_GETADDRINFO */
3024 struct _emacs_addrinfo
3026 int ai_family;
3027 int ai_socktype;
3028 int ai_protocol;
3029 int ai_addrlen;
3030 struct sockaddr *ai_addr;
3031 struct _emacs_addrinfo *ai_next;
3032 } ai, *res, *lres;
3033 #endif /* HAVE_GETADDRINFO */
3034 struct sockaddr_in address_in;
3035 #ifdef HAVE_LOCAL_SOCKETS
3036 struct sockaddr_un address_un;
3037 #endif
3038 int port;
3039 int ret = 0;
3040 int xerrno = 0;
3041 int s = -1, outch, inch;
3042 struct gcpro gcpro1;
3043 ptrdiff_t count = SPECPDL_INDEX ();
3044 ptrdiff_t count1;
3045 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3046 Lisp_Object tem;
3047 Lisp_Object name, buffer, host, service, address;
3048 Lisp_Object filter, sentinel;
3049 int is_non_blocking_client = 0;
3050 int is_server = 0, backlog = 5;
3051 int socktype;
3052 int family = -1;
3054 if (nargs == 0)
3055 return Qnil;
3057 /* Save arguments for process-contact and clone-process. */
3058 contact = Flist (nargs, args);
3059 GCPRO1 (contact);
3061 #ifdef WINDOWSNT
3062 /* Ensure socket support is loaded if available. */
3063 init_winsock (TRUE);
3064 #endif
3066 /* :type TYPE (nil: stream, datagram */
3067 tem = Fplist_get (contact, QCtype);
3068 if (NILP (tem))
3069 socktype = SOCK_STREAM;
3070 #ifdef DATAGRAM_SOCKETS
3071 else if (EQ (tem, Qdatagram))
3072 socktype = SOCK_DGRAM;
3073 #endif
3074 #ifdef HAVE_SEQPACKET
3075 else if (EQ (tem, Qseqpacket))
3076 socktype = SOCK_SEQPACKET;
3077 #endif
3078 else
3079 error ("Unsupported connection type");
3081 /* :server BOOL */
3082 tem = Fplist_get (contact, QCserver);
3083 if (!NILP (tem))
3085 /* Don't support network sockets when non-blocking mode is
3086 not available, since a blocked Emacs is not useful. */
3087 #if !defined (O_NONBLOCK) && !defined (O_NDELAY)
3088 error ("Network servers not supported");
3089 #else
3090 is_server = 1;
3091 if (TYPE_RANGED_INTEGERP (int, tem))
3092 backlog = XINT (tem);
3093 #endif
3096 /* Make QCaddress an alias for :local (server) or :remote (client). */
3097 QCaddress = is_server ? QClocal : QCremote;
3099 /* :nowait BOOL */
3100 if (!is_server && socktype != SOCK_DGRAM
3101 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3103 #ifndef NON_BLOCKING_CONNECT
3104 error ("Non-blocking connect not supported");
3105 #else
3106 is_non_blocking_client = 1;
3107 #endif
3110 name = Fplist_get (contact, QCname);
3111 buffer = Fplist_get (contact, QCbuffer);
3112 filter = Fplist_get (contact, QCfilter);
3113 sentinel = Fplist_get (contact, QCsentinel);
3115 CHECK_STRING (name);
3117 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3118 ai.ai_socktype = socktype;
3119 ai.ai_protocol = 0;
3120 ai.ai_next = NULL;
3121 res = &ai;
3123 /* :local ADDRESS or :remote ADDRESS */
3124 address = Fplist_get (contact, QCaddress);
3125 if (!NILP (address))
3127 host = service = Qnil;
3129 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3130 error ("Malformed :address");
3131 ai.ai_family = family;
3132 ai.ai_addr = alloca (ai.ai_addrlen);
3133 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3134 goto open_socket;
3137 /* :family FAMILY -- nil (for Inet), local, or integer. */
3138 tem = Fplist_get (contact, QCfamily);
3139 if (NILP (tem))
3141 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3142 family = AF_UNSPEC;
3143 #else
3144 family = AF_INET;
3145 #endif
3147 #ifdef HAVE_LOCAL_SOCKETS
3148 else if (EQ (tem, Qlocal))
3149 family = AF_LOCAL;
3150 #endif
3151 #ifdef AF_INET6
3152 else if (EQ (tem, Qipv6))
3153 family = AF_INET6;
3154 #endif
3155 else if (EQ (tem, Qipv4))
3156 family = AF_INET;
3157 else if (TYPE_RANGED_INTEGERP (int, tem))
3158 family = XINT (tem);
3159 else
3160 error ("Unknown address family");
3162 ai.ai_family = family;
3164 /* :service SERVICE -- string, integer (port number), or t (random port). */
3165 service = Fplist_get (contact, QCservice);
3167 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3168 host = Fplist_get (contact, QChost);
3169 if (!NILP (host))
3171 if (EQ (host, Qlocal))
3172 /* Depending on setup, "localhost" may map to different IPv4 and/or
3173 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3174 host = build_string ("127.0.0.1");
3175 CHECK_STRING (host);
3178 #ifdef HAVE_LOCAL_SOCKETS
3179 if (family == AF_LOCAL)
3181 if (!NILP (host))
3183 message (":family local ignores the :host \"%s\" property",
3184 SDATA (host));
3185 contact = Fplist_put (contact, QChost, Qnil);
3186 host = Qnil;
3188 CHECK_STRING (service);
3189 memset (&address_un, 0, sizeof address_un);
3190 address_un.sun_family = AF_LOCAL;
3191 if (sizeof address_un.sun_path <= SBYTES (service))
3192 error ("Service name too long");
3193 strcpy (address_un.sun_path, SSDATA (service));
3194 ai.ai_addr = (struct sockaddr *) &address_un;
3195 ai.ai_addrlen = sizeof address_un;
3196 goto open_socket;
3198 #endif
3200 /* Slow down polling to every ten seconds.
3201 Some kernels have a bug which causes retrying connect to fail
3202 after a connect. Polling can interfere with gethostbyname too. */
3203 #ifdef POLL_FOR_INPUT
3204 if (socktype != SOCK_DGRAM)
3206 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3207 bind_polling_period (10);
3209 #endif
3211 #ifdef HAVE_GETADDRINFO
3212 /* If we have a host, use getaddrinfo to resolve both host and service.
3213 Otherwise, use getservbyname to lookup the service. */
3214 if (!NILP (host))
3217 /* SERVICE can either be a string or int.
3218 Convert to a C string for later use by getaddrinfo. */
3219 if (EQ (service, Qt))
3220 portstring = "0";
3221 else if (INTEGERP (service))
3223 sprintf (portbuf, "%"pI"d", XINT (service));
3224 portstring = portbuf;
3226 else
3228 CHECK_STRING (service);
3229 portstring = SSDATA (service);
3232 immediate_quit = 1;
3233 QUIT;
3234 memset (&hints, 0, sizeof (hints));
3235 hints.ai_flags = 0;
3236 hints.ai_family = family;
3237 hints.ai_socktype = socktype;
3238 hints.ai_protocol = 0;
3240 #ifdef HAVE_RES_INIT
3241 res_init ();
3242 #endif
3244 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3245 if (ret)
3246 #ifdef HAVE_GAI_STRERROR
3247 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3248 #else
3249 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3250 #endif
3251 immediate_quit = 0;
3253 goto open_socket;
3255 #endif /* HAVE_GETADDRINFO */
3257 /* We end up here if getaddrinfo is not defined, or in case no hostname
3258 has been specified (e.g. for a local server process). */
3260 if (EQ (service, Qt))
3261 port = 0;
3262 else if (INTEGERP (service))
3263 port = htons ((unsigned short) XINT (service));
3264 else
3266 struct servent *svc_info;
3267 CHECK_STRING (service);
3268 svc_info = getservbyname (SSDATA (service),
3269 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3270 if (svc_info == 0)
3271 error ("Unknown service: %s", SDATA (service));
3272 port = svc_info->s_port;
3275 memset (&address_in, 0, sizeof address_in);
3276 address_in.sin_family = family;
3277 address_in.sin_addr.s_addr = INADDR_ANY;
3278 address_in.sin_port = port;
3280 #ifndef HAVE_GETADDRINFO
3281 if (!NILP (host))
3283 struct hostent *host_info_ptr;
3285 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3286 as it may `hang' Emacs for a very long time. */
3287 immediate_quit = 1;
3288 QUIT;
3290 #ifdef HAVE_RES_INIT
3291 res_init ();
3292 #endif
3294 host_info_ptr = gethostbyname (SDATA (host));
3295 immediate_quit = 0;
3297 if (host_info_ptr)
3299 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3300 host_info_ptr->h_length);
3301 family = host_info_ptr->h_addrtype;
3302 address_in.sin_family = family;
3304 else
3305 /* Attempt to interpret host as numeric inet address */
3307 unsigned long numeric_addr;
3308 numeric_addr = inet_addr (SSDATA (host));
3309 if (numeric_addr == -1)
3310 error ("Unknown host \"%s\"", SDATA (host));
3312 memcpy (&address_in.sin_addr, &numeric_addr,
3313 sizeof (address_in.sin_addr));
3317 #endif /* not HAVE_GETADDRINFO */
3319 ai.ai_family = family;
3320 ai.ai_addr = (struct sockaddr *) &address_in;
3321 ai.ai_addrlen = sizeof address_in;
3323 open_socket:
3325 /* Do this in case we never enter the for-loop below. */
3326 count1 = SPECPDL_INDEX ();
3327 s = -1;
3329 for (lres = res; lres; lres = lres->ai_next)
3331 ptrdiff_t optn;
3332 int optbits;
3334 #ifdef WINDOWSNT
3335 retry_connect:
3336 #endif
3338 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3339 if (s < 0)
3341 xerrno = errno;
3342 continue;
3345 #ifdef DATAGRAM_SOCKETS
3346 if (!is_server && socktype == SOCK_DGRAM)
3347 break;
3348 #endif /* DATAGRAM_SOCKETS */
3350 #ifdef NON_BLOCKING_CONNECT
3351 if (is_non_blocking_client)
3353 #ifdef O_NONBLOCK
3354 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3355 #else
3356 ret = fcntl (s, F_SETFL, O_NDELAY);
3357 #endif
3358 if (ret < 0)
3360 xerrno = errno;
3361 emacs_close (s);
3362 s = -1;
3363 continue;
3366 #endif
3368 /* Make us close S if quit. */
3369 record_unwind_protect (close_file_unwind, make_number (s));
3371 /* Parse network options in the arg list.
3372 We simply ignore anything which isn't a known option (including other keywords).
3373 An error is signaled if setting a known option fails. */
3374 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3375 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3377 if (is_server)
3379 /* Configure as a server socket. */
3381 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3382 explicit :reuseaddr key to override this. */
3383 #ifdef HAVE_LOCAL_SOCKETS
3384 if (family != AF_LOCAL)
3385 #endif
3386 if (!(optbits & (1 << OPIX_REUSEADDR)))
3388 int optval = 1;
3389 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3390 report_file_error ("Cannot set reuse option on server socket", Qnil);
3393 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3394 report_file_error ("Cannot bind server socket", Qnil);
3396 #ifdef HAVE_GETSOCKNAME
3397 if (EQ (service, Qt))
3399 struct sockaddr_in sa1;
3400 socklen_t len1 = sizeof (sa1);
3401 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3403 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3404 service = make_number (ntohs (sa1.sin_port));
3405 contact = Fplist_put (contact, QCservice, service);
3408 #endif
3410 if (socktype != SOCK_DGRAM && listen (s, backlog))
3411 report_file_error ("Cannot listen on server socket", Qnil);
3413 break;
3416 immediate_quit = 1;
3417 QUIT;
3419 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3420 xerrno = errno;
3422 if (ret == 0 || xerrno == EISCONN)
3424 /* The unwind-protect will be discarded afterwards.
3425 Likewise for immediate_quit. */
3426 break;
3429 #ifdef NON_BLOCKING_CONNECT
3430 #ifdef EINPROGRESS
3431 if (is_non_blocking_client && xerrno == EINPROGRESS)
3432 break;
3433 #else
3434 #ifdef EWOULDBLOCK
3435 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3436 break;
3437 #endif
3438 #endif
3439 #endif
3441 #ifndef WINDOWSNT
3442 if (xerrno == EINTR)
3444 /* Unlike most other syscalls connect() cannot be called
3445 again. (That would return EALREADY.) The proper way to
3446 wait for completion is pselect(). */
3447 int sc;
3448 socklen_t len;
3449 SELECT_TYPE fdset;
3450 retry_select:
3451 FD_ZERO (&fdset);
3452 FD_SET (s, &fdset);
3453 QUIT;
3454 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3455 if (sc == -1)
3457 if (errno == EINTR)
3458 goto retry_select;
3459 else
3460 report_file_error ("select failed", Qnil);
3462 eassert (sc > 0);
3464 len = sizeof xerrno;
3465 eassert (FD_ISSET (s, &fdset));
3466 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3467 report_file_error ("getsockopt failed", Qnil);
3468 if (xerrno)
3469 errno = xerrno, report_file_error ("error during connect", Qnil);
3470 else
3471 break;
3473 #endif /* !WINDOWSNT */
3475 immediate_quit = 0;
3477 /* Discard the unwind protect closing S. */
3478 specpdl_ptr = specpdl + count1;
3479 emacs_close (s);
3480 s = -1;
3482 #ifdef WINDOWSNT
3483 if (xerrno == EINTR)
3484 goto retry_connect;
3485 #endif
3488 if (s >= 0)
3490 #ifdef DATAGRAM_SOCKETS
3491 if (socktype == SOCK_DGRAM)
3493 if (datagram_address[s].sa)
3494 abort ();
3495 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3496 datagram_address[s].len = lres->ai_addrlen;
3497 if (is_server)
3499 Lisp_Object remote;
3500 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3501 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3503 int rfamily, rlen;
3504 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3505 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3506 conv_lisp_to_sockaddr (rfamily, remote,
3507 datagram_address[s].sa, rlen);
3510 else
3511 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3513 #endif
3514 contact = Fplist_put (contact, QCaddress,
3515 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3516 #ifdef HAVE_GETSOCKNAME
3517 if (!is_server)
3519 struct sockaddr_in sa1;
3520 socklen_t len1 = sizeof (sa1);
3521 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3522 contact = Fplist_put (contact, QClocal,
3523 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3525 #endif
3528 immediate_quit = 0;
3530 #ifdef HAVE_GETADDRINFO
3531 if (res != &ai)
3533 BLOCK_INPUT;
3534 freeaddrinfo (res);
3535 UNBLOCK_INPUT;
3537 #endif
3539 /* Discard the unwind protect for closing S, if any. */
3540 specpdl_ptr = specpdl + count1;
3542 /* Unwind bind_polling_period and request_sigio. */
3543 unbind_to (count, Qnil);
3545 if (s < 0)
3547 /* If non-blocking got this far - and failed - assume non-blocking is
3548 not supported after all. This is probably a wrong assumption, but
3549 the normal blocking calls to open-network-stream handles this error
3550 better. */
3551 if (is_non_blocking_client)
3552 return Qnil;
3554 errno = xerrno;
3555 if (is_server)
3556 report_file_error ("make server process failed", contact);
3557 else
3558 report_file_error ("make client process failed", contact);
3561 inch = s;
3562 outch = s;
3564 if (!NILP (buffer))
3565 buffer = Fget_buffer_create (buffer);
3566 proc = make_process (name);
3568 chan_process[inch] = proc;
3570 #ifdef O_NONBLOCK
3571 fcntl (inch, F_SETFL, O_NONBLOCK);
3572 #else
3573 #ifdef O_NDELAY
3574 fcntl (inch, F_SETFL, O_NDELAY);
3575 #endif
3576 #endif
3578 p = XPROCESS (proc);
3580 PSET (p, childp, contact);
3581 PSET (p, plist, Fcopy_sequence (Fplist_get (contact, QCplist)));
3582 PSET (p, type, Qnetwork);
3584 PSET (p, buffer, buffer);
3585 PSET (p, sentinel, sentinel);
3586 PSET (p, filter, filter);
3587 PSET (p, log, Fplist_get (contact, QClog));
3588 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3589 p->kill_without_query = 1;
3590 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3591 PSET (p, command, Qt);
3592 p->pid = 0;
3593 p->infd = inch;
3594 p->outfd = outch;
3595 if (is_server && socktype != SOCK_DGRAM)
3596 PSET (p, status, Qlisten);
3598 /* Make the process marker point into the process buffer (if any). */
3599 if (BUFFERP (buffer))
3600 set_marker_both (p->mark, buffer,
3601 BUF_ZV (XBUFFER (buffer)),
3602 BUF_ZV_BYTE (XBUFFER (buffer)));
3604 #ifdef NON_BLOCKING_CONNECT
3605 if (is_non_blocking_client)
3607 /* We may get here if connect did succeed immediately. However,
3608 in that case, we still need to signal this like a non-blocking
3609 connection. */
3610 PSET (p, status, Qconnect);
3611 if ((fd_callback_info[inch].flags & NON_BLOCKING_CONNECT_FD) == 0)
3612 add_non_blocking_write_fd (inch);
3614 else
3615 #endif
3616 /* A server may have a client filter setting of Qt, but it must
3617 still listen for incoming connects unless it is stopped. */
3618 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3619 || (EQ (p->status, Qlisten) && NILP (p->command)))
3620 add_non_keyboard_read_fd (inch);
3622 if (inch > max_process_desc)
3623 max_process_desc = inch;
3625 tem = Fplist_member (contact, QCcoding);
3626 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3627 tem = Qnil; /* No error message (too late!). */
3630 /* Setup coding systems for communicating with the network stream. */
3631 struct gcpro gcpro1;
3632 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3633 Lisp_Object coding_systems = Qt;
3634 Lisp_Object fargs[5], val;
3636 if (!NILP (tem))
3638 val = XCAR (XCDR (tem));
3639 if (CONSP (val))
3640 val = XCAR (val);
3642 else if (!NILP (Vcoding_system_for_read))
3643 val = Vcoding_system_for_read;
3644 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3645 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3646 /* We dare not decode end-of-line format by setting VAL to
3647 Qraw_text, because the existing Emacs Lisp libraries
3648 assume that they receive bare code including a sequence of
3649 CR LF. */
3650 val = Qnil;
3651 else
3653 if (NILP (host) || NILP (service))
3654 coding_systems = Qnil;
3655 else
3657 fargs[0] = Qopen_network_stream, fargs[1] = name,
3658 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3659 GCPRO1 (proc);
3660 coding_systems = Ffind_operation_coding_system (5, fargs);
3661 UNGCPRO;
3663 if (CONSP (coding_systems))
3664 val = XCAR (coding_systems);
3665 else if (CONSP (Vdefault_process_coding_system))
3666 val = XCAR (Vdefault_process_coding_system);
3667 else
3668 val = Qnil;
3670 PSET (p, decode_coding_system, val);
3672 if (!NILP (tem))
3674 val = XCAR (XCDR (tem));
3675 if (CONSP (val))
3676 val = XCDR (val);
3678 else if (!NILP (Vcoding_system_for_write))
3679 val = Vcoding_system_for_write;
3680 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3681 val = Qnil;
3682 else
3684 if (EQ (coding_systems, Qt))
3686 if (NILP (host) || NILP (service))
3687 coding_systems = Qnil;
3688 else
3690 fargs[0] = Qopen_network_stream, fargs[1] = name,
3691 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3692 GCPRO1 (proc);
3693 coding_systems = Ffind_operation_coding_system (5, fargs);
3694 UNGCPRO;
3697 if (CONSP (coding_systems))
3698 val = XCDR (coding_systems);
3699 else if (CONSP (Vdefault_process_coding_system))
3700 val = XCDR (Vdefault_process_coding_system);
3701 else
3702 val = Qnil;
3704 PSET (p, encode_coding_system, val);
3706 setup_process_coding_systems (proc);
3708 PSET (p, decoding_buf, empty_unibyte_string);
3709 p->decoding_carryover = 0;
3710 PSET (p, encoding_buf, empty_unibyte_string);
3712 p->inherit_coding_system_flag
3713 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3715 UNGCPRO;
3716 return proc;
3720 #if defined (HAVE_NET_IF_H)
3722 #ifdef SIOCGIFCONF
3723 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3724 doc: /* Return an alist of all network interfaces and their network address.
3725 Each element is a cons, the car of which is a string containing the
3726 interface name, and the cdr is the network address in internal
3727 format; see the description of ADDRESS in `make-network-process'. */)
3728 (void)
3730 struct ifconf ifconf;
3731 struct ifreq *ifreq;
3732 void *buf = NULL;
3733 ptrdiff_t buf_size = 512;
3734 int s, i;
3735 Lisp_Object res;
3737 s = socket (AF_INET, SOCK_STREAM, 0);
3738 if (s < 0)
3739 return Qnil;
3743 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3744 ifconf.ifc_buf = buf;
3745 ifconf.ifc_len = buf_size;
3746 if (ioctl (s, SIOCGIFCONF, &ifconf))
3748 close (s);
3749 xfree (buf);
3750 return Qnil;
3753 while (ifconf.ifc_len == buf_size);
3755 close (s);
3757 res = Qnil;
3758 ifreq = ifconf.ifc_req;
3759 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3761 struct ifreq *ifq = ifreq;
3762 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3763 #define SIZEOF_IFREQ(sif) \
3764 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3765 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3767 int len = SIZEOF_IFREQ (ifq);
3768 #else
3769 int len = sizeof (*ifreq);
3770 #endif
3771 char namebuf[sizeof (ifq->ifr_name) + 1];
3772 i += len;
3773 ifreq = (struct ifreq *) ((char *) ifreq + len);
3775 if (ifq->ifr_addr.sa_family != AF_INET)
3776 continue;
3778 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3779 namebuf[sizeof (ifq->ifr_name)] = 0;
3780 res = Fcons (Fcons (build_string (namebuf),
3781 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3782 sizeof (struct sockaddr))),
3783 res);
3786 xfree (buf);
3787 return res;
3789 #endif /* SIOCGIFCONF */
3791 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3793 struct ifflag_def {
3794 int flag_bit;
3795 const char *flag_sym;
3798 static const struct ifflag_def ifflag_table[] = {
3799 #ifdef IFF_UP
3800 { IFF_UP, "up" },
3801 #endif
3802 #ifdef IFF_BROADCAST
3803 { IFF_BROADCAST, "broadcast" },
3804 #endif
3805 #ifdef IFF_DEBUG
3806 { IFF_DEBUG, "debug" },
3807 #endif
3808 #ifdef IFF_LOOPBACK
3809 { IFF_LOOPBACK, "loopback" },
3810 #endif
3811 #ifdef IFF_POINTOPOINT
3812 { IFF_POINTOPOINT, "pointopoint" },
3813 #endif
3814 #ifdef IFF_RUNNING
3815 { IFF_RUNNING, "running" },
3816 #endif
3817 #ifdef IFF_NOARP
3818 { IFF_NOARP, "noarp" },
3819 #endif
3820 #ifdef IFF_PROMISC
3821 { IFF_PROMISC, "promisc" },
3822 #endif
3823 #ifdef IFF_NOTRAILERS
3824 #ifdef NS_IMPL_COCOA
3825 /* Really means smart, notrailers is obsolete */
3826 { IFF_NOTRAILERS, "smart" },
3827 #else
3828 { IFF_NOTRAILERS, "notrailers" },
3829 #endif
3830 #endif
3831 #ifdef IFF_ALLMULTI
3832 { IFF_ALLMULTI, "allmulti" },
3833 #endif
3834 #ifdef IFF_MASTER
3835 { IFF_MASTER, "master" },
3836 #endif
3837 #ifdef IFF_SLAVE
3838 { IFF_SLAVE, "slave" },
3839 #endif
3840 #ifdef IFF_MULTICAST
3841 { IFF_MULTICAST, "multicast" },
3842 #endif
3843 #ifdef IFF_PORTSEL
3844 { IFF_PORTSEL, "portsel" },
3845 #endif
3846 #ifdef IFF_AUTOMEDIA
3847 { IFF_AUTOMEDIA, "automedia" },
3848 #endif
3849 #ifdef IFF_DYNAMIC
3850 { IFF_DYNAMIC, "dynamic" },
3851 #endif
3852 #ifdef IFF_OACTIVE
3853 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3854 #endif
3855 #ifdef IFF_SIMPLEX
3856 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3857 #endif
3858 #ifdef IFF_LINK0
3859 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3860 #endif
3861 #ifdef IFF_LINK1
3862 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3863 #endif
3864 #ifdef IFF_LINK2
3865 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3866 #endif
3867 { 0, 0 }
3870 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3871 doc: /* Return information about network interface named IFNAME.
3872 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3873 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3874 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3875 FLAGS is the current flags of the interface. */)
3876 (Lisp_Object ifname)
3878 struct ifreq rq;
3879 Lisp_Object res = Qnil;
3880 Lisp_Object elt;
3881 int s;
3882 int any = 0;
3883 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3884 && defined HAVE_GETIFADDRS && defined LLADDR)
3885 struct ifaddrs *ifap;
3886 #endif
3888 CHECK_STRING (ifname);
3890 if (sizeof rq.ifr_name <= SBYTES (ifname))
3891 error ("interface name too long");
3892 strcpy (rq.ifr_name, SSDATA (ifname));
3894 s = socket (AF_INET, SOCK_STREAM, 0);
3895 if (s < 0)
3896 return Qnil;
3898 elt = Qnil;
3899 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3900 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3902 int flags = rq.ifr_flags;
3903 const struct ifflag_def *fp;
3904 int fnum;
3906 /* If flags is smaller than int (i.e. short) it may have the high bit set
3907 due to IFF_MULTICAST. In that case, sign extending it into
3908 an int is wrong. */
3909 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3910 flags = (unsigned short) rq.ifr_flags;
3912 any = 1;
3913 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3915 if (flags & fp->flag_bit)
3917 elt = Fcons (intern (fp->flag_sym), elt);
3918 flags -= fp->flag_bit;
3921 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3923 if (flags & 1)
3925 elt = Fcons (make_number (fnum), elt);
3929 #endif
3930 res = Fcons (elt, res);
3932 elt = Qnil;
3933 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3934 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3936 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3937 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3938 int n;
3940 any = 1;
3941 for (n = 0; n < 6; n++)
3942 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3943 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3945 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3946 if (getifaddrs (&ifap) != -1)
3948 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3949 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3950 struct ifaddrs *it;
3952 for (it = ifap; it != NULL; it = it->ifa_next)
3954 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3955 unsigned char linkaddr[6];
3956 int n;
3958 if (it->ifa_addr->sa_family != AF_LINK
3959 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3960 || sdl->sdl_alen != 6)
3961 continue;
3963 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3964 for (n = 0; n < 6; n++)
3965 p->contents[n] = make_number (linkaddr[n]);
3967 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3968 break;
3971 #ifdef HAVE_FREEIFADDRS
3972 freeifaddrs (ifap);
3973 #endif
3975 #endif /* HAVE_GETIFADDRS && LLADDR */
3977 res = Fcons (elt, res);
3979 elt = Qnil;
3980 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3981 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3983 any = 1;
3984 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3985 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3986 #else
3987 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3988 #endif
3990 #endif
3991 res = Fcons (elt, res);
3993 elt = Qnil;
3994 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3995 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3997 any = 1;
3998 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4000 #endif
4001 res = Fcons (elt, res);
4003 elt = Qnil;
4004 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4005 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4007 any = 1;
4008 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4010 #endif
4011 res = Fcons (elt, res);
4013 close (s);
4015 return any ? res : Qnil;
4017 #endif
4018 #endif /* defined (HAVE_NET_IF_H) */
4020 /* Turn off input and output for process PROC. */
4022 static void
4023 deactivate_process (Lisp_Object proc)
4025 register int inchannel, outchannel;
4026 register struct Lisp_Process *p = XPROCESS (proc);
4028 #ifdef HAVE_GNUTLS
4029 /* Delete GnuTLS structures in PROC, if any. */
4030 emacs_gnutls_deinit (proc);
4031 #endif /* HAVE_GNUTLS */
4033 inchannel = p->infd;
4034 outchannel = p->outfd;
4036 #ifdef ADAPTIVE_READ_BUFFERING
4037 if (p->read_output_delay > 0)
4039 if (--process_output_delay_count < 0)
4040 process_output_delay_count = 0;
4041 p->read_output_delay = 0;
4042 p->read_output_skip = 0;
4044 #endif
4046 if (inchannel >= 0)
4048 /* Beware SIGCHLD hereabouts. */
4049 flush_pending_output (inchannel);
4050 emacs_close (inchannel);
4051 if (outchannel >= 0 && outchannel != inchannel)
4052 emacs_close (outchannel);
4054 p->infd = -1;
4055 p->outfd = -1;
4056 #ifdef DATAGRAM_SOCKETS
4057 if (DATAGRAM_CHAN_P (inchannel))
4059 xfree (datagram_address[inchannel].sa);
4060 datagram_address[inchannel].sa = 0;
4061 datagram_address[inchannel].len = 0;
4063 #endif
4064 chan_process[inchannel] = Qnil;
4065 delete_read_fd (inchannel);
4066 #ifdef NON_BLOCKING_CONNECT
4067 if ((fd_callback_info[inchannel].flags & NON_BLOCKING_CONNECT_FD) != 0)
4068 delete_write_fd (inchannel);
4069 #endif
4070 if (inchannel == max_process_desc)
4072 int i;
4073 /* We just closed the highest-numbered process input descriptor,
4074 so recompute the highest-numbered one now. */
4075 max_process_desc = 0;
4076 for (i = 0; i < MAXDESC; i++)
4077 if (!NILP (chan_process[i]))
4078 max_process_desc = i;
4084 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4085 0, 4, 0,
4086 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4087 It is read into the process' buffers or given to their filter functions.
4088 Non-nil arg PROCESS means do not return until some output has been received
4089 from PROCESS.
4091 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4092 and milliseconds to wait; return after that much time whether or not
4093 there is any subprocess output. If SECONDS is a floating point number,
4094 it specifies a fractional number of seconds to wait.
4095 The MILLISEC argument is obsolete and should be avoided.
4097 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4098 from PROCESS, suspending reading output from other processes.
4099 If JUST-THIS-ONE is an integer, don't run any timers either.
4100 Return non-nil if we received any output before the timeout expired. */)
4101 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4103 intmax_t secs;
4104 int nsecs;
4106 if (! NILP (process))
4108 struct Lisp_Process *procp;
4110 CHECK_PROCESS (process);
4111 procp = XPROCESS (process);
4113 /* Can't wait for a process that is dedicated to a different
4114 thread. */
4115 if (!EQ (procp->thread, Qnil) && !EQ (procp->thread, Fcurrent_thread ()))
4116 error ("FIXME");
4118 else
4119 just_this_one = Qnil;
4121 if (!NILP (millisec))
4122 { /* Obsolete calling convention using integers rather than floats. */
4123 CHECK_NUMBER (millisec);
4124 if (NILP (seconds))
4125 seconds = make_float (XINT (millisec) / 1000.0);
4126 else
4128 CHECK_NUMBER (seconds);
4129 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4133 secs = 0;
4134 nsecs = -1;
4136 if (!NILP (seconds))
4138 if (INTEGERP (seconds))
4140 if (0 < XINT (seconds))
4142 secs = XINT (seconds);
4143 nsecs = 0;
4146 else if (FLOATP (seconds))
4148 if (0 < XFLOAT_DATA (seconds))
4150 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
4151 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
4152 nsecs = EMACS_NSECS (t);
4155 else
4156 wrong_type_argument (Qnumberp, seconds);
4158 else if (! NILP (process))
4159 nsecs = 0;
4161 return
4162 (wait_reading_process_output (secs, nsecs, 0, 0,
4163 Qnil,
4164 !NILP (process) ? XPROCESS (process) : NULL,
4165 NILP (just_this_one) ? 0 :
4166 !INTEGERP (just_this_one) ? 1 : -1)
4167 ? Qt : Qnil);
4170 /* Accept a connection for server process SERVER on CHANNEL. */
4172 static int connect_counter = 0;
4174 static void
4175 server_accept_connection (Lisp_Object server, int channel)
4177 Lisp_Object proc, caller, name, buffer;
4178 Lisp_Object contact, host, service;
4179 struct Lisp_Process *ps= XPROCESS (server);
4180 struct Lisp_Process *p;
4181 int s;
4182 union u_sockaddr {
4183 struct sockaddr sa;
4184 struct sockaddr_in in;
4185 #ifdef AF_INET6
4186 struct sockaddr_in6 in6;
4187 #endif
4188 #ifdef HAVE_LOCAL_SOCKETS
4189 struct sockaddr_un un;
4190 #endif
4191 } saddr;
4192 socklen_t len = sizeof saddr;
4194 s = accept (channel, &saddr.sa, &len);
4196 if (s < 0)
4198 int code = errno;
4200 if (code == EAGAIN)
4201 return;
4202 #ifdef EWOULDBLOCK
4203 if (code == EWOULDBLOCK)
4204 return;
4205 #endif
4207 if (!NILP (ps->log))
4208 call3 (ps->log, server, Qnil,
4209 concat3 (build_string ("accept failed with code"),
4210 Fnumber_to_string (make_number (code)),
4211 build_string ("\n")));
4212 return;
4215 connect_counter++;
4217 /* Setup a new process to handle the connection. */
4219 /* Generate a unique identification of the caller, and build contact
4220 information for this process. */
4221 host = Qt;
4222 service = Qnil;
4223 switch (saddr.sa.sa_family)
4225 case AF_INET:
4227 Lisp_Object args[5];
4228 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4229 args[0] = build_string ("%d.%d.%d.%d");
4230 args[1] = make_number (*ip++);
4231 args[2] = make_number (*ip++);
4232 args[3] = make_number (*ip++);
4233 args[4] = make_number (*ip++);
4234 host = Fformat (5, args);
4235 service = make_number (ntohs (saddr.in.sin_port));
4237 args[0] = build_string (" <%s:%d>");
4238 args[1] = host;
4239 args[2] = service;
4240 caller = Fformat (3, args);
4242 break;
4244 #ifdef AF_INET6
4245 case AF_INET6:
4247 Lisp_Object args[9];
4248 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4249 int i;
4250 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4251 for (i = 0; i < 8; i++)
4252 args[i+1] = make_number (ntohs (ip6[i]));
4253 host = Fformat (9, args);
4254 service = make_number (ntohs (saddr.in.sin_port));
4256 args[0] = build_string (" <[%s]:%d>");
4257 args[1] = host;
4258 args[2] = service;
4259 caller = Fformat (3, args);
4261 break;
4262 #endif
4264 #ifdef HAVE_LOCAL_SOCKETS
4265 case AF_LOCAL:
4266 #endif
4267 default:
4268 caller = Fnumber_to_string (make_number (connect_counter));
4269 caller = concat3 (build_string (" <"), caller, build_string (">"));
4270 break;
4273 /* Create a new buffer name for this process if it doesn't have a
4274 filter. The new buffer name is based on the buffer name or
4275 process name of the server process concatenated with the caller
4276 identification. */
4278 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4279 buffer = Qnil;
4280 else
4282 buffer = ps->buffer;
4283 if (!NILP (buffer))
4284 buffer = Fbuffer_name (buffer);
4285 else
4286 buffer = ps->name;
4287 if (!NILP (buffer))
4289 buffer = concat2 (buffer, caller);
4290 buffer = Fget_buffer_create (buffer);
4294 /* Generate a unique name for the new server process. Combine the
4295 server process name with the caller identification. */
4297 name = concat2 (ps->name, caller);
4298 proc = make_process (name);
4300 chan_process[s] = proc;
4302 #ifdef O_NONBLOCK
4303 fcntl (s, F_SETFL, O_NONBLOCK);
4304 #else
4305 #ifdef O_NDELAY
4306 fcntl (s, F_SETFL, O_NDELAY);
4307 #endif
4308 #endif
4310 p = XPROCESS (proc);
4312 /* Build new contact information for this setup. */
4313 contact = Fcopy_sequence (ps->childp);
4314 contact = Fplist_put (contact, QCserver, Qnil);
4315 contact = Fplist_put (contact, QChost, host);
4316 if (!NILP (service))
4317 contact = Fplist_put (contact, QCservice, service);
4318 contact = Fplist_put (contact, QCremote,
4319 conv_sockaddr_to_lisp (&saddr.sa, len));
4320 #ifdef HAVE_GETSOCKNAME
4321 len = sizeof saddr;
4322 if (getsockname (s, &saddr.sa, &len) == 0)
4323 contact = Fplist_put (contact, QClocal,
4324 conv_sockaddr_to_lisp (&saddr.sa, len));
4325 #endif
4327 PSET (p, childp, contact);
4328 PSET (p, plist, Fcopy_sequence (ps->plist));
4329 PSET (p, type, Qnetwork);
4331 PSET (p, buffer, buffer);
4332 PSET (p, sentinel, ps->sentinel);
4333 PSET (p, filter, ps->filter);
4334 PSET (p, command, Qnil);
4335 p->pid = 0;
4336 p->infd = s;
4337 p->outfd = s;
4338 PSET (p, status, Qrun);
4340 /* Client processes for accepted connections are not stopped initially. */
4341 if (!EQ (p->filter, Qt))
4342 add_non_keyboard_read_fd (s);
4344 /* Setup coding system for new process based on server process.
4345 This seems to be the proper thing to do, as the coding system
4346 of the new process should reflect the settings at the time the
4347 server socket was opened; not the current settings. */
4349 PSET (p, decode_coding_system, ps->decode_coding_system);
4350 PSET (p, encode_coding_system, ps->encode_coding_system);
4351 setup_process_coding_systems (proc);
4353 PSET (p, decoding_buf, empty_unibyte_string);
4354 p->decoding_carryover = 0;
4355 PSET (p, encoding_buf, empty_unibyte_string);
4357 p->inherit_coding_system_flag
4358 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4360 if (!NILP (ps->log))
4361 call3 (ps->log, server, proc,
4362 concat3 (build_string ("accept from "),
4363 (STRINGP (host) ? host : build_string ("-")),
4364 build_string ("\n")));
4366 if (!NILP (p->sentinel))
4367 exec_sentinel (proc,
4368 concat3 (build_string ("open from "),
4369 (STRINGP (host) ? host : build_string ("-")),
4370 build_string ("\n")));
4373 static Lisp_Object
4374 wait_reading_process_output_unwind (Lisp_Object data)
4376 clear_waiting_thread_info ();
4377 waiting_for_user_input_p = XINT (data);
4378 return Qnil;
4381 /* This is here so breakpoints can be put on it. */
4382 static void
4383 wait_reading_process_output_1 (void)
4387 /* Read and dispose of subprocess output while waiting for timeout to
4388 elapse and/or keyboard input to be available.
4390 TIME_LIMIT is:
4391 timeout in seconds
4392 If negative, gobble data immediately available but don't wait for any.
4394 NSECS is:
4395 an additional duration to wait, measured in nanoseconds
4396 If TIME_LIMIT is zero, then:
4397 If NSECS == 0, there is no limit.
4398 If NSECS > 0, the timeout consists of NSECS only.
4399 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4401 READ_KBD is:
4402 0 to ignore keyboard input, or
4403 1 to return when input is available, or
4404 -1 meaning caller will actually read the input, so don't throw to
4405 the quit handler, or
4407 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4408 output that arrives.
4410 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4411 (and gobble terminal input into the buffer if any arrives).
4413 If WAIT_PROC is specified, wait until something arrives from that
4414 process. The return value is true if we read some input from
4415 that process.
4417 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4418 (suspending output from other processes). A negative value
4419 means don't run any timers either.
4421 If WAIT_PROC is specified, then the function returns true if we
4422 received input from that process before the timeout elapsed.
4423 Otherwise, return true if we received input from any process. */
4426 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4427 int do_display,
4428 Lisp_Object wait_for_cell,
4429 struct Lisp_Process *wait_proc, int just_wait_proc)
4431 register int channel, nfds;
4432 SELECT_TYPE Available;
4433 SELECT_TYPE Writeok;
4434 int check_write;
4435 int check_delay, no_avail;
4436 int xerrno;
4437 Lisp_Object proc;
4438 EMACS_TIME timeout, end_time;
4439 int wait_channel = -1;
4440 int got_some_input = 0;
4441 ptrdiff_t count = SPECPDL_INDEX ();
4443 eassert (wait_proc == NULL
4444 || EQ (wait_proc->thread, Qnil)
4445 || XTHREAD (wait_proc->thread) == current_thread);
4447 FD_ZERO (&Available);
4448 FD_ZERO (&Writeok);
4450 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4451 && !(CONSP (wait_proc->status)
4452 && EQ (XCAR (wait_proc->status), Qexit)))
4453 message ("Blocking call to accept-process-output with quit inhibited!!");
4455 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4456 if (wait_proc != NULL)
4457 wait_channel = wait_proc->infd;
4459 record_unwind_protect (wait_reading_process_output_unwind,
4460 make_number (waiting_for_user_input_p));
4461 waiting_for_user_input_p = read_kbd;
4463 if (time_limit < 0)
4465 time_limit = 0;
4466 nsecs = -1;
4468 else if (TYPE_MAXIMUM (time_t) < time_limit)
4469 time_limit = TYPE_MAXIMUM (time_t);
4471 /* Since we may need to wait several times,
4472 compute the absolute time to return at. */
4473 if (time_limit || 0 < nsecs)
4475 timeout = make_emacs_time (time_limit, nsecs);
4476 end_time = add_emacs_time (current_emacs_time (), timeout);
4479 while (1)
4481 int timeout_reduced_for_timers = 0;
4483 /* If calling from keyboard input, do not quit
4484 since we want to return C-g as an input character.
4485 Otherwise, do pending quit if requested. */
4486 if (read_kbd >= 0)
4487 QUIT;
4488 #ifdef SYNC_INPUT
4489 else
4490 process_pending_signals ();
4491 #endif
4493 /* Exit now if the cell we're waiting for became non-nil. */
4494 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4495 break;
4497 /* Compute time from now till when time limit is up */
4498 /* Exit if already run out */
4499 if (nsecs < 0)
4501 /* A negative timeout means
4502 gobble output available now
4503 but don't wait at all. */
4505 timeout = make_emacs_time (0, 0);
4507 else if (time_limit || 0 < nsecs)
4509 EMACS_TIME now = current_emacs_time ();
4510 if (EMACS_TIME_LE (end_time, now))
4511 break;
4512 timeout = sub_emacs_time (end_time, now);
4514 else
4516 timeout = make_emacs_time (100000, 0);
4519 /* Normally we run timers here.
4520 But not if wait_for_cell; in those cases,
4521 the wait is supposed to be short,
4522 and those callers cannot handle running arbitrary Lisp code here. */
4523 if (NILP (wait_for_cell)
4524 && just_wait_proc >= 0)
4526 EMACS_TIME timer_delay;
4530 int old_timers_run = timers_run;
4531 struct buffer *old_buffer = current_buffer;
4532 Lisp_Object old_window = selected_window;
4534 timer_delay = timer_check ();
4536 /* If a timer has run, this might have changed buffers
4537 an alike. Make read_key_sequence aware of that. */
4538 if (timers_run != old_timers_run
4539 && (old_buffer != current_buffer
4540 || !EQ (old_window, selected_window))
4541 && waiting_for_user_input_p == -1)
4542 record_asynch_buffer_change ();
4544 if (timers_run != old_timers_run && do_display)
4545 /* We must retry, since a timer may have requeued itself
4546 and that could alter the time_delay. */
4547 redisplay_preserve_echo_area (9);
4548 else
4549 break;
4551 while (!detect_input_pending ());
4553 /* If there is unread keyboard input, also return. */
4554 if (read_kbd != 0
4555 && requeued_events_pending_p ())
4556 break;
4558 /* A negative timeout means do not wait at all. */
4559 if (0 <= nsecs)
4561 if (EMACS_TIME_VALID_P (timer_delay))
4563 if (EMACS_TIME_LT (timer_delay, timeout))
4565 timeout = timer_delay;
4566 timeout_reduced_for_timers = 1;
4569 else
4571 /* This is so a breakpoint can be put here. */
4572 wait_reading_process_output_1 ();
4577 /* Cause C-g and alarm signals to take immediate action,
4578 and cause input available signals to zero out timeout.
4580 It is important that we do this before checking for process
4581 activity. If we get a SIGCHLD after the explicit checks for
4582 process activity, timeout is the only way we will know. */
4583 if (read_kbd < 0)
4584 set_waiting_for_input (&timeout);
4586 /* If status of something has changed, and no input is
4587 available, notify the user of the change right away. After
4588 this explicit check, we'll let the SIGCHLD handler zap
4589 timeout to get our attention. */
4590 if (update_tick != process_tick)
4592 SELECT_TYPE Atemp;
4593 SELECT_TYPE Ctemp;
4595 if (kbd_on_hold_p ())
4596 FD_ZERO (&Atemp);
4597 else
4598 compute_input_wait_mask (&Atemp);
4599 compute_write_mask (&Ctemp);
4601 timeout = make_emacs_time (0, 0);
4602 if ((thread_select (pselect,
4603 max (max_process_desc, max_input_desc) + 1,
4604 &Atemp,
4605 #ifdef NON_BLOCKING_CONNECT
4606 (num_pending_connects > 0 ? &Ctemp : NULL),
4607 #else
4608 NULL,
4609 #endif
4610 NULL, &timeout, NULL)
4611 <= 0))
4613 /* It's okay for us to do this and then continue with
4614 the loop, since timeout has already been zeroed out. */
4615 clear_waiting_for_input ();
4616 status_notify (NULL);
4617 if (do_display) redisplay_preserve_echo_area (13);
4621 /* Don't wait for output from a non-running process. Just
4622 read whatever data has already been received. */
4623 if (wait_proc && wait_proc->raw_status_new)
4624 update_status (wait_proc);
4625 if (wait_proc
4626 && ! EQ (wait_proc->status, Qrun)
4627 && ! EQ (wait_proc->status, Qconnect))
4629 int nread, total_nread = 0;
4631 clear_waiting_for_input ();
4632 XSETPROCESS (proc, wait_proc);
4634 /* Read data from the process, until we exhaust it. */
4635 while (wait_proc->infd >= 0)
4637 nread = read_process_output (proc, wait_proc->infd);
4639 if (nread == 0)
4640 break;
4642 if (0 < nread)
4644 total_nread += nread;
4645 got_some_input = 1;
4647 #ifdef EIO
4648 else if (nread == -1 && EIO == errno)
4649 break;
4650 #endif
4651 #ifdef EAGAIN
4652 else if (nread == -1 && EAGAIN == errno)
4653 break;
4654 #endif
4655 #ifdef EWOULDBLOCK
4656 else if (nread == -1 && EWOULDBLOCK == errno)
4657 break;
4658 #endif
4660 if (total_nread > 0 && do_display)
4661 redisplay_preserve_echo_area (10);
4663 break;
4666 /* Wait till there is something to do */
4668 if (wait_proc && just_wait_proc)
4670 if (wait_proc->infd < 0) /* Terminated */
4671 break;
4672 FD_SET (wait_proc->infd, &Available);
4673 check_delay = 0;
4674 check_write = 0;
4676 else if (!NILP (wait_for_cell))
4678 compute_non_process_wait_mask (&Available);
4679 check_delay = 0;
4680 check_write = 0;
4682 else
4684 if (! read_kbd)
4685 compute_non_keyboard_wait_mask (&Available);
4686 else
4687 compute_input_wait_mask (&Available);
4688 compute_write_mask (&Writeok);
4689 #ifdef SELECT_CANT_DO_WRITE_MASK
4690 check_write = 0;
4691 #else
4692 check_write = 1;
4693 #endif
4694 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4697 /* If frame size has changed or the window is newly mapped,
4698 redisplay now, before we start to wait. There is a race
4699 condition here; if a SIGIO arrives between now and the select
4700 and indicates that a frame is trashed, the select may block
4701 displaying a trashed screen. */
4702 if (frame_garbaged && do_display)
4704 clear_waiting_for_input ();
4705 redisplay_preserve_echo_area (11);
4706 if (read_kbd < 0)
4707 set_waiting_for_input (&timeout);
4710 /* Skip the `select' call if input is available and we're
4711 waiting for keyboard input or a cell change (which can be
4712 triggered by processing X events). In the latter case, set
4713 nfds to 1 to avoid breaking the loop. */
4714 no_avail = 0;
4715 if ((read_kbd || !NILP (wait_for_cell))
4716 && detect_input_pending ())
4718 nfds = read_kbd ? 0 : 1;
4719 no_avail = 1;
4722 if (!no_avail)
4725 #ifdef ADAPTIVE_READ_BUFFERING
4726 /* Set the timeout for adaptive read buffering if any
4727 process has non-zero read_output_skip and non-zero
4728 read_output_delay, and we are not reading output for a
4729 specific wait_channel. It is not executed if
4730 Vprocess_adaptive_read_buffering is nil. */
4731 if (process_output_skip && check_delay > 0)
4733 int nsecs = EMACS_NSECS (timeout);
4734 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4735 nsecs = READ_OUTPUT_DELAY_MAX;
4736 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4738 proc = chan_process[channel];
4739 if (NILP (proc))
4740 continue;
4741 /* Find minimum non-zero read_output_delay among the
4742 processes with non-zero read_output_skip. */
4743 if (XPROCESS (proc)->read_output_delay > 0)
4745 check_delay--;
4746 if (!XPROCESS (proc)->read_output_skip)
4747 continue;
4748 FD_CLR (channel, &Available);
4749 XPROCESS (proc)->read_output_skip = 0;
4750 if (XPROCESS (proc)->read_output_delay < nsecs)
4751 nsecs = XPROCESS (proc)->read_output_delay;
4754 timeout = make_emacs_time (0, nsecs);
4755 process_output_skip = 0;
4757 #endif
4758 nfds = thread_select (
4759 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4760 xg_select
4761 #elif defined (HAVE_NS)
4762 ns_select
4763 #else
4764 pselect
4765 #endif
4766 , max (max_process_desc, max_input_desc) + 1,
4767 &Available,
4768 (check_write ? &Writeok : (SELECT_TYPE *)0),
4769 NULL, &timeout, NULL);
4771 #ifdef HAVE_GNUTLS
4772 /* GnuTLS buffers data internally. In lowat mode it leaves
4773 some data in the TCP buffers so that select works, but
4774 with custom pull/push functions we need to check if some
4775 data is available in the buffers manually. */
4776 if (nfds == 0)
4778 if (! wait_proc)
4780 /* We're not waiting on a specific process, so loop
4781 through all the channels and check for data.
4782 This is a workaround needed for some versions of
4783 the gnutls library -- 2.12.14 has been confirmed
4784 to need it. See
4785 http://comments.gmane.org/gmane.emacs.devel/145074 */
4786 for (channel = 0; channel < MAXDESC; ++channel)
4787 if (! NILP (chan_process[channel]))
4789 struct Lisp_Process *p =
4790 XPROCESS (chan_process[channel]);
4791 if (p && p->gnutls_p && p->infd
4792 && ((emacs_gnutls_record_check_pending
4793 (p->gnutls_state))
4794 > 0))
4796 nfds++;
4797 FD_SET (p->infd, &Available);
4801 else
4803 /* Check this specific channel. */
4804 if (wait_proc->gnutls_p /* Check for valid process. */
4805 /* Do we have pending data? */
4806 && ((emacs_gnutls_record_check_pending
4807 (wait_proc->gnutls_state))
4808 > 0))
4810 nfds = 1;
4811 /* Set to Available. */
4812 FD_SET (wait_proc->infd, &Available);
4816 #endif
4819 xerrno = errno;
4821 /* Make C-g and alarm signals set flags again */
4822 clear_waiting_for_input ();
4824 /* If we woke up due to SIGWINCH, actually change size now. */
4825 do_pending_window_change (0);
4827 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4828 /* We waited the full specified time, so return now. */
4829 break;
4830 if (nfds < 0)
4832 if (xerrno == EINTR)
4833 no_avail = 1;
4834 else if (xerrno == EBADF)
4836 #ifdef AIX
4837 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4838 the child's closure of the pts gives the parent a SIGHUP, and
4839 the ptc file descriptor is automatically closed,
4840 yielding EBADF here or at select() call above.
4841 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4842 in m/ibmrt-aix.h), and here we just ignore the select error.
4843 Cleanup occurs c/o status_notify after SIGCLD. */
4844 no_avail = 1; /* Cannot depend on values returned */
4845 #else
4846 abort ();
4847 #endif
4849 else
4850 error ("select error: %s", emacs_strerror (xerrno));
4853 if (no_avail)
4855 FD_ZERO (&Available);
4856 check_write = 0;
4859 #if 0 /* When polling is used, interrupt_input is 0,
4860 so get_input_pending should read the input.
4861 So this should not be needed. */
4862 /* If we are using polling for input,
4863 and we see input available, make it get read now.
4864 Otherwise it might not actually get read for a second.
4865 And on hpux, since we turn off polling in wait_reading_process_output,
4866 it might never get read at all if we don't spend much time
4867 outside of wait_reading_process_output. */
4868 if (read_kbd && interrupt_input
4869 && keyboard_bit_set (&Available)
4870 && input_polling_used ())
4871 kill (getpid (), SIGALRM);
4872 #endif
4874 /* Check for keyboard input */
4875 /* If there is any, return immediately
4876 to give it higher priority than subprocesses */
4878 if (read_kbd != 0)
4880 int old_timers_run = timers_run;
4881 struct buffer *old_buffer = current_buffer;
4882 Lisp_Object old_window = selected_window;
4883 int leave = 0;
4885 if (detect_input_pending_run_timers (do_display))
4887 swallow_events (do_display);
4888 if (detect_input_pending_run_timers (do_display))
4889 leave = 1;
4892 /* If a timer has run, this might have changed buffers
4893 an alike. Make read_key_sequence aware of that. */
4894 if (timers_run != old_timers_run
4895 && waiting_for_user_input_p == -1
4896 && (old_buffer != current_buffer
4897 || !EQ (old_window, selected_window)))
4898 record_asynch_buffer_change ();
4900 if (leave)
4901 break;
4904 /* If there is unread keyboard input, also return. */
4905 if (read_kbd != 0
4906 && requeued_events_pending_p ())
4907 break;
4909 /* If we are not checking for keyboard input now,
4910 do process events (but don't run any timers).
4911 This is so that X events will be processed.
4912 Otherwise they may have to wait until polling takes place.
4913 That would causes delays in pasting selections, for example.
4915 (We used to do this only if wait_for_cell.) */
4916 if (read_kbd == 0 && detect_input_pending ())
4918 swallow_events (do_display);
4919 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4920 if (detect_input_pending ())
4921 break;
4922 #endif
4925 /* Exit now if the cell we're waiting for became non-nil. */
4926 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4927 break;
4929 #ifdef SIGIO
4930 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4931 go read it. This can happen with X on BSD after logging out.
4932 In that case, there really is no input and no SIGIO,
4933 but select says there is input. */
4935 if (read_kbd && interrupt_input
4936 && keyboard_bit_set (&Available) && ! noninteractive)
4937 kill (getpid (), SIGIO);
4938 #endif
4940 if (! wait_proc)
4941 got_some_input |= nfds > 0;
4943 /* If checking input just got us a size-change event from X,
4944 obey it now if we should. */
4945 if (read_kbd || ! NILP (wait_for_cell))
4946 do_pending_window_change (0);
4948 /* Check for data from a process. */
4949 if (no_avail || nfds == 0)
4950 continue;
4952 for (channel = 0; channel <= max_input_desc; ++channel)
4954 struct fd_callback_data *d = &fd_callback_info[channel];
4955 if (FD_ISSET (channel, &Available)
4956 && d->func != 0
4957 && (d->flags & FOR_READ) != 0)
4958 d->func (channel, d->data, 1);
4959 if (FD_ISSET (channel, &Writeok)
4960 && d->func != 0
4961 && (d->flags & FOR_WRITE) != 0)
4962 d->func (channel, d->data, 0);
4965 for (channel = 0; channel <= max_process_desc; channel++)
4967 if (FD_ISSET (channel, &Available)
4968 && ((fd_callback_info[channel].flags & (KEYBOARD_FD | PROCESS_FD))
4969 == PROCESS_FD))
4971 int nread;
4973 /* If waiting for this channel, arrange to return as
4974 soon as no more input to be processed. No more
4975 waiting. */
4976 if (wait_channel == channel)
4978 wait_channel = -1;
4979 nsecs = -1;
4980 got_some_input = 1;
4982 proc = chan_process[channel];
4983 if (NILP (proc))
4984 continue;
4986 /* If this is a server stream socket, accept connection. */
4987 if (EQ (XPROCESS (proc)->status, Qlisten))
4989 server_accept_connection (proc, channel);
4990 continue;
4993 /* Read data from the process, starting with our
4994 buffered-ahead character if we have one. */
4996 nread = read_process_output (proc, channel);
4997 if (nread > 0)
4999 /* Since read_process_output can run a filter,
5000 which can call accept-process-output,
5001 don't try to read from any other processes
5002 before doing the select again. */
5003 FD_ZERO (&Available);
5005 if (do_display)
5006 redisplay_preserve_echo_area (12);
5008 #ifdef EWOULDBLOCK
5009 else if (nread == -1 && errno == EWOULDBLOCK)
5011 #endif
5012 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5013 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5014 #ifdef O_NONBLOCK
5015 else if (nread == -1 && errno == EAGAIN)
5017 #else
5018 #ifdef O_NDELAY
5019 else if (nread == -1 && errno == EAGAIN)
5021 /* Note that we cannot distinguish between no input
5022 available now and a closed pipe.
5023 With luck, a closed pipe will be accompanied by
5024 subprocess termination and SIGCHLD. */
5025 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5027 #endif /* O_NDELAY */
5028 #endif /* O_NONBLOCK */
5029 #ifdef HAVE_PTYS
5030 /* On some OSs with ptys, when the process on one end of
5031 a pty exits, the other end gets an error reading with
5032 errno = EIO instead of getting an EOF (0 bytes read).
5033 Therefore, if we get an error reading and errno =
5034 EIO, just continue, because the child process has
5035 exited and should clean itself up soon (e.g. when we
5036 get a SIGCHLD).
5038 However, it has been known to happen that the SIGCHLD
5039 got lost. So raise the signal again just in case.
5040 It can't hurt. */
5041 else if (nread == -1 && errno == EIO)
5043 struct Lisp_Process *p = XPROCESS (proc);
5045 /* Clear the descriptor now, so we only raise the
5046 signal once. */
5047 delete_read_fd (channel);
5049 if (p->pid == -2)
5051 /* If the EIO occurs on a pty, sigchld_handler's
5052 waitpid() will not find the process object to
5053 delete. Do it here. */
5054 p->tick = ++process_tick;
5055 PSET (p, status, Qfailed);
5057 else
5058 kill (getpid (), SIGCHLD);
5060 #endif /* HAVE_PTYS */
5061 /* If we can detect process termination, don't consider the
5062 process gone just because its pipe is closed. */
5063 #ifdef SIGCHLD
5064 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5066 #endif
5067 else
5069 /* Preserve status of processes already terminated. */
5070 XPROCESS (proc)->tick = ++process_tick;
5071 deactivate_process (proc);
5072 if (XPROCESS (proc)->raw_status_new)
5073 update_status (XPROCESS (proc));
5074 if (EQ (XPROCESS (proc)->status, Qrun))
5075 PSET (XPROCESS (proc), status,
5076 Fcons (Qexit, Fcons (make_number (256), Qnil)));
5079 #ifdef NON_BLOCKING_CONNECT
5080 if (FD_ISSET (channel, &Writeok)
5081 && (fd_callback_info[channel].flags
5082 & NON_BLOCKING_CONNECT_FD) != 0)
5084 struct Lisp_Process *p;
5086 delete_write_fd (channel);
5088 proc = chan_process[channel];
5089 if (NILP (proc))
5090 continue;
5092 p = XPROCESS (proc);
5094 #ifdef GNU_LINUX
5095 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5096 So only use it on systems where it is known to work. */
5098 socklen_t xlen = sizeof (xerrno);
5099 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5100 xerrno = errno;
5102 #else
5104 struct sockaddr pname;
5105 int pnamelen = sizeof (pname);
5107 /* If connection failed, getpeername will fail. */
5108 xerrno = 0;
5109 if (getpeername (channel, &pname, &pnamelen) < 0)
5111 /* Obtain connect failure code through error slippage. */
5112 char dummy;
5113 xerrno = errno;
5114 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5115 xerrno = errno;
5118 #endif
5119 if (xerrno)
5121 p->tick = ++process_tick;
5122 PSET (p, status,
5123 Fcons (Qfailed, Fcons (make_number (xerrno), Qnil)));
5124 deactivate_process (proc);
5126 else
5128 PSET (p, status, Qrun);
5129 /* Execute the sentinel here. If we had relied on
5130 status_notify to do it later, it will read input
5131 from the process before calling the sentinel. */
5132 exec_sentinel (proc, build_string ("open\n"));
5133 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5134 delete_read_fd (p->infd);
5137 #endif /* NON_BLOCKING_CONNECT */
5138 } /* end for each file descriptor */
5139 } /* end while exit conditions not met */
5141 unbind_to (count, Qnil);
5143 /* If calling from keyboard input, do not quit
5144 since we want to return C-g as an input character.
5145 Otherwise, do pending quit if requested. */
5146 if (read_kbd >= 0)
5148 /* Prevent input_pending from remaining set if we quit. */
5149 clear_input_pending ();
5150 QUIT;
5153 return got_some_input;
5156 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5158 static Lisp_Object
5159 read_process_output_call (Lisp_Object fun_and_args)
5161 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5164 static Lisp_Object
5165 read_process_output_error_handler (Lisp_Object error_val)
5167 cmd_error_internal (error_val, "error in process filter: ");
5168 Vinhibit_quit = Qt;
5169 update_echo_area ();
5170 Fsleep_for (make_number (2), Qnil);
5171 return Qt;
5174 /* Read pending output from the process channel,
5175 starting with our buffered-ahead character if we have one.
5176 Yield number of decoded characters read.
5178 This function reads at most 4096 characters.
5179 If you want to read all available subprocess output,
5180 you must call it repeatedly until it returns zero.
5182 The characters read are decoded according to PROC's coding-system
5183 for decoding. */
5185 static int
5186 read_process_output (Lisp_Object proc, register int channel)
5188 register ssize_t nbytes;
5189 char *chars;
5190 register Lisp_Object outstream;
5191 register struct Lisp_Process *p = XPROCESS (proc);
5192 register ptrdiff_t opoint;
5193 struct coding_system *coding = proc_decode_coding_system[channel];
5194 int carryover = p->decoding_carryover;
5195 int readmax = 4096;
5196 ptrdiff_t count = SPECPDL_INDEX ();
5197 Lisp_Object odeactivate;
5199 chars = alloca (carryover + readmax);
5200 if (carryover)
5201 /* See the comment above. */
5202 memcpy (chars, SDATA (p->decoding_buf), carryover);
5204 #ifdef DATAGRAM_SOCKETS
5205 /* We have a working select, so proc_buffered_char is always -1. */
5206 if (DATAGRAM_CHAN_P (channel))
5208 socklen_t len = datagram_address[channel].len;
5209 nbytes = recvfrom (channel, chars + carryover, readmax,
5210 0, datagram_address[channel].sa, &len);
5212 else
5213 #endif
5215 int buffered = 0 <= proc_buffered_char[channel];
5216 if (buffered)
5218 chars[carryover] = proc_buffered_char[channel];
5219 proc_buffered_char[channel] = -1;
5221 #ifdef HAVE_GNUTLS
5222 if (p->gnutls_p)
5223 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5224 readmax - buffered);
5225 else
5226 #endif
5227 nbytes = emacs_read (channel, chars + carryover + buffered,
5228 readmax - buffered);
5229 #ifdef ADAPTIVE_READ_BUFFERING
5230 if (nbytes > 0 && p->adaptive_read_buffering)
5232 int delay = p->read_output_delay;
5233 if (nbytes < 256)
5235 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5237 if (delay == 0)
5238 process_output_delay_count++;
5239 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5242 else if (delay > 0 && nbytes == readmax - buffered)
5244 delay -= READ_OUTPUT_DELAY_INCREMENT;
5245 if (delay == 0)
5246 process_output_delay_count--;
5248 p->read_output_delay = delay;
5249 if (delay)
5251 p->read_output_skip = 1;
5252 process_output_skip = 1;
5255 #endif
5256 nbytes += buffered;
5257 nbytes += buffered && nbytes <= 0;
5260 p->decoding_carryover = 0;
5262 /* At this point, NBYTES holds number of bytes just received
5263 (including the one in proc_buffered_char[channel]). */
5264 if (nbytes <= 0)
5266 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5267 return nbytes;
5268 coding->mode |= CODING_MODE_LAST_BLOCK;
5271 /* Now set NBYTES how many bytes we must decode. */
5272 nbytes += carryover;
5274 odeactivate = Vdeactivate_mark;
5275 /* There's no good reason to let process filters change the current
5276 buffer, and many callers of accept-process-output, sit-for, and
5277 friends don't expect current-buffer to be changed from under them. */
5278 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5280 /* Read and dispose of the process output. */
5281 outstream = p->filter;
5282 if (!NILP (outstream))
5284 Lisp_Object text;
5285 int outer_running_asynch_code = running_asynch_code;
5286 int waiting = waiting_for_user_input_p;
5288 /* No need to gcpro these, because all we do with them later
5289 is test them for EQness, and none of them should be a string. */
5290 #if 0
5291 Lisp_Object obuffer, okeymap;
5292 XSETBUFFER (obuffer, current_buffer);
5293 okeymap = BVAR (current_buffer, keymap);
5294 #endif
5296 /* We inhibit quit here instead of just catching it so that
5297 hitting ^G when a filter happens to be running won't screw
5298 it up. */
5299 specbind (Qinhibit_quit, Qt);
5300 specbind (Qlast_nonmenu_event, Qt);
5302 /* In case we get recursively called,
5303 and we already saved the match data nonrecursively,
5304 save the same match data in safely recursive fashion. */
5305 if (outer_running_asynch_code)
5307 Lisp_Object tem;
5308 /* Don't clobber the CURRENT match data, either! */
5309 tem = Fmatch_data (Qnil, Qnil, Qnil);
5310 restore_search_regs ();
5311 record_unwind_save_match_data ();
5312 Fset_match_data (tem, Qt);
5315 /* For speed, if a search happens within this code,
5316 save the match data in a special nonrecursive fashion. */
5317 running_asynch_code = 1;
5319 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5320 text = coding->dst_object;
5321 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5322 /* A new coding system might be found. */
5323 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5325 PSET (p, decode_coding_system, Vlast_coding_system_used);
5327 /* Don't call setup_coding_system for
5328 proc_decode_coding_system[channel] here. It is done in
5329 detect_coding called via decode_coding above. */
5331 /* If a coding system for encoding is not yet decided, we set
5332 it as the same as coding-system for decoding.
5334 But, before doing that we must check if
5335 proc_encode_coding_system[p->outfd] surely points to a
5336 valid memory because p->outfd will be changed once EOF is
5337 sent to the process. */
5338 if (NILP (p->encode_coding_system)
5339 && proc_encode_coding_system[p->outfd])
5341 PSET (p, encode_coding_system,
5342 coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5343 setup_coding_system (p->encode_coding_system,
5344 proc_encode_coding_system[p->outfd]);
5348 if (coding->carryover_bytes > 0)
5350 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5351 PSET (p, decoding_buf, make_uninit_string (coding->carryover_bytes));
5352 memcpy (SDATA (p->decoding_buf), coding->carryover,
5353 coding->carryover_bytes);
5354 p->decoding_carryover = coding->carryover_bytes;
5356 if (SBYTES (text) > 0)
5357 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5358 sometimes it's simply wrong to wrap (e.g. when called from
5359 accept-process-output). */
5360 internal_condition_case_1 (read_process_output_call,
5361 Fcons (outstream,
5362 Fcons (proc, Fcons (text, Qnil))),
5363 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5364 read_process_output_error_handler);
5366 /* If we saved the match data nonrecursively, restore it now. */
5367 restore_search_regs ();
5368 running_asynch_code = outer_running_asynch_code;
5370 /* Restore waiting_for_user_input_p as it was
5371 when we were called, in case the filter clobbered it. */
5372 waiting_for_user_input_p = waiting;
5374 #if 0 /* Call record_asynch_buffer_change unconditionally,
5375 because we might have changed minor modes or other things
5376 that affect key bindings. */
5377 if (! EQ (Fcurrent_buffer (), obuffer)
5378 || ! EQ (current_buffer->keymap, okeymap))
5379 #endif
5380 /* But do it only if the caller is actually going to read events.
5381 Otherwise there's no need to make him wake up, and it could
5382 cause trouble (for example it would make sit_for return). */
5383 if (waiting_for_user_input_p == -1)
5384 record_asynch_buffer_change ();
5387 /* If no filter, write into buffer if it isn't dead. */
5388 else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
5390 Lisp_Object old_read_only;
5391 ptrdiff_t old_begv, old_zv;
5392 ptrdiff_t old_begv_byte, old_zv_byte;
5393 ptrdiff_t before, before_byte;
5394 ptrdiff_t opoint_byte;
5395 Lisp_Object text;
5396 struct buffer *b;
5398 Fset_buffer (p->buffer);
5399 opoint = PT;
5400 opoint_byte = PT_BYTE;
5401 old_read_only = BVAR (current_buffer, read_only);
5402 old_begv = BEGV;
5403 old_zv = ZV;
5404 old_begv_byte = BEGV_BYTE;
5405 old_zv_byte = ZV_BYTE;
5407 BSET (current_buffer, read_only, Qnil);
5409 /* Insert new output into buffer
5410 at the current end-of-output marker,
5411 thus preserving logical ordering of input and output. */
5412 if (XMARKER (p->mark)->buffer)
5413 SET_PT_BOTH (clip_to_bounds (BEGV,
5414 marker_position (p->mark), ZV),
5415 clip_to_bounds (BEGV_BYTE,
5416 marker_byte_position (p->mark),
5417 ZV_BYTE));
5418 else
5419 SET_PT_BOTH (ZV, ZV_BYTE);
5420 before = PT;
5421 before_byte = PT_BYTE;
5423 /* If the output marker is outside of the visible region, save
5424 the restriction and widen. */
5425 if (! (BEGV <= PT && PT <= ZV))
5426 Fwiden ();
5428 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5429 text = coding->dst_object;
5430 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5431 /* A new coding system might be found. See the comment in the
5432 similar code in the previous `if' block. */
5433 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5435 PSET (p, decode_coding_system, Vlast_coding_system_used);
5436 if (NILP (p->encode_coding_system)
5437 && proc_encode_coding_system[p->outfd])
5439 PSET (p, encode_coding_system,
5440 coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5441 setup_coding_system (p->encode_coding_system,
5442 proc_encode_coding_system[p->outfd]);
5445 if (coding->carryover_bytes > 0)
5447 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5448 PSET (p, decoding_buf, make_uninit_string (coding->carryover_bytes));
5449 memcpy (SDATA (p->decoding_buf), coding->carryover,
5450 coding->carryover_bytes);
5451 p->decoding_carryover = coding->carryover_bytes;
5453 /* Adjust the multibyteness of TEXT to that of the buffer. */
5454 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5455 != ! STRING_MULTIBYTE (text))
5456 text = (STRING_MULTIBYTE (text)
5457 ? Fstring_as_unibyte (text)
5458 : Fstring_to_multibyte (text));
5459 /* Insert before markers in case we are inserting where
5460 the buffer's mark is, and the user's next command is Meta-y. */
5461 insert_from_string_before_markers (text, 0, 0,
5462 SCHARS (text), SBYTES (text), 0);
5464 /* Make sure the process marker's position is valid when the
5465 process buffer is changed in the signal_after_change above.
5466 W3 is known to do that. */
5467 if (BUFFERP (p->buffer)
5468 && (b = XBUFFER (p->buffer), b != current_buffer))
5469 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5470 else
5471 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5473 update_mode_lines++;
5475 /* Make sure opoint and the old restrictions
5476 float ahead of any new text just as point would. */
5477 if (opoint >= before)
5479 opoint += PT - before;
5480 opoint_byte += PT_BYTE - before_byte;
5482 if (old_begv > before)
5484 old_begv += PT - before;
5485 old_begv_byte += PT_BYTE - before_byte;
5487 if (old_zv >= before)
5489 old_zv += PT - before;
5490 old_zv_byte += PT_BYTE - before_byte;
5493 /* If the restriction isn't what it should be, set it. */
5494 if (old_begv != BEGV || old_zv != ZV)
5495 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5498 BSET (current_buffer, read_only, old_read_only);
5499 SET_PT_BOTH (opoint, opoint_byte);
5501 /* Handling the process output should not deactivate the mark. */
5502 Vdeactivate_mark = odeactivate;
5504 unbind_to (count, Qnil);
5505 return nbytes;
5508 /* Sending data to subprocess */
5510 static jmp_buf send_process_frame;
5511 static Lisp_Object process_sent_to;
5513 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5514 static _Noreturn void send_process_trap (int);
5515 #endif
5517 static void
5518 send_process_trap (int ignore)
5520 SIGNAL_THREAD_CHECK (SIGPIPE);
5521 sigunblock (sigmask (SIGPIPE));
5522 longjmp (send_process_frame, 1);
5525 /* In send_process, when a write fails temporarily,
5526 wait_reading_process_output is called. It may execute user code,
5527 e.g. timers, that attempts to write new data to the same process.
5528 We must ensure that data is sent in the right order, and not
5529 interspersed half-completed with other writes (Bug#10815). This is
5530 handled by the write_queue element of struct process. It is a list
5531 with each entry having the form
5533 (string . (offset . length))
5535 where STRING is a lisp string, OFFSET is the offset into the
5536 string's byte sequence from which we should begin to send, and
5537 LENGTH is the number of bytes left to send. */
5539 /* Create a new entry in write_queue.
5540 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5541 BUF is a pointer to the string sequence of the input_obj or a C
5542 string in case of Qt or Qnil. */
5544 static void
5545 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5546 const char *buf, ptrdiff_t len, int front)
5548 ptrdiff_t offset;
5549 Lisp_Object entry, obj;
5551 if (STRINGP (input_obj))
5553 offset = buf - SSDATA (input_obj);
5554 obj = input_obj;
5556 else
5558 offset = 0;
5559 obj = make_unibyte_string (buf, len);
5562 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5564 if (front)
5565 PSET (p, write_queue, Fcons (entry, p->write_queue));
5566 else
5567 PSET (p, write_queue, nconc2 (p->write_queue, Fcons (entry, Qnil)));
5570 /* Remove the first element in the write_queue of process P, put its
5571 contents in OBJ, BUF and LEN, and return non-zero. If the
5572 write_queue is empty, return zero. */
5574 static int
5575 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5576 const char **buf, ptrdiff_t *len)
5578 Lisp_Object entry, offset_length;
5579 ptrdiff_t offset;
5581 if (NILP (p->write_queue))
5582 return 0;
5584 entry = XCAR (p->write_queue);
5585 PSET (p, write_queue, XCDR (p->write_queue));
5587 *obj = XCAR (entry);
5588 offset_length = XCDR (entry);
5590 *len = XINT (XCDR (offset_length));
5591 offset = XINT (XCAR (offset_length));
5592 *buf = SSDATA (*obj) + offset;
5594 return 1;
5597 /* Send some data to process PROC.
5598 BUF is the beginning of the data; LEN is the number of characters.
5599 OBJECT is the Lisp object that the data comes from. If OBJECT is
5600 nil or t, it means that the data comes from C string.
5602 If OBJECT is not nil, the data is encoded by PROC's coding-system
5603 for encoding before it is sent.
5605 This function can evaluate Lisp code and can garbage collect. */
5607 static void
5608 send_process (volatile Lisp_Object proc, const char *volatile buf,
5609 volatile ptrdiff_t len, volatile Lisp_Object object)
5611 /* Use volatile to protect variables from being clobbered by longjmp. */
5612 struct Lisp_Process *p = XPROCESS (proc);
5613 ssize_t rv;
5614 struct coding_system *coding;
5615 void (*volatile old_sigpipe) (int);
5617 if (p->raw_status_new)
5618 update_status (p);
5619 if (! EQ (p->status, Qrun))
5620 error ("Process %s not running", SDATA (p->name));
5621 if (p->outfd < 0)
5622 error ("Output file descriptor of %s is closed", SDATA (p->name));
5624 coding = proc_encode_coding_system[p->outfd];
5625 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5627 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5628 || (BUFFERP (object)
5629 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5630 || EQ (object, Qt))
5632 PSET (p, encode_coding_system,
5633 complement_process_encoding_system (p->encode_coding_system));
5634 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5636 /* The coding system for encoding was changed to raw-text
5637 because we sent a unibyte text previously. Now we are
5638 sending a multibyte text, thus we must encode it by the
5639 original coding system specified for the current process.
5641 Another reason we come here is that the coding system
5642 was just complemented and a new one was returned by
5643 complement_process_encoding_system. */
5644 setup_coding_system (p->encode_coding_system, coding);
5645 Vlast_coding_system_used = p->encode_coding_system;
5647 coding->src_multibyte = 1;
5649 else
5651 coding->src_multibyte = 0;
5652 /* For sending a unibyte text, character code conversion should
5653 not take place but EOL conversion should. So, setup raw-text
5654 or one of the subsidiary if we have not yet done it. */
5655 if (CODING_REQUIRE_ENCODING (coding))
5657 if (CODING_REQUIRE_FLUSHING (coding))
5659 /* But, before changing the coding, we must flush out data. */
5660 coding->mode |= CODING_MODE_LAST_BLOCK;
5661 send_process (proc, "", 0, Qt);
5662 coding->mode &= CODING_MODE_LAST_BLOCK;
5664 setup_coding_system (raw_text_coding_system
5665 (Vlast_coding_system_used),
5666 coding);
5667 coding->src_multibyte = 0;
5670 coding->dst_multibyte = 0;
5672 if (CODING_REQUIRE_ENCODING (coding))
5674 coding->dst_object = Qt;
5675 if (BUFFERP (object))
5677 ptrdiff_t from_byte, from, to;
5678 ptrdiff_t save_pt, save_pt_byte;
5679 struct buffer *cur = current_buffer;
5681 set_buffer_internal (XBUFFER (object));
5682 save_pt = PT, save_pt_byte = PT_BYTE;
5684 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5685 from = BYTE_TO_CHAR (from_byte);
5686 to = BYTE_TO_CHAR (from_byte + len);
5687 TEMP_SET_PT_BOTH (from, from_byte);
5688 encode_coding_object (coding, object, from, from_byte,
5689 to, from_byte + len, Qt);
5690 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5691 set_buffer_internal (cur);
5693 else if (STRINGP (object))
5695 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5696 SBYTES (object), Qt);
5698 else
5700 coding->dst_object = make_unibyte_string (buf, len);
5701 coding->produced = len;
5704 len = coding->produced;
5705 object = coding->dst_object;
5706 buf = SSDATA (object);
5709 if (pty_max_bytes == 0)
5711 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5712 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5713 if (pty_max_bytes < 0)
5714 pty_max_bytes = 250;
5715 #else
5716 pty_max_bytes = 250;
5717 #endif
5718 /* Deduct one, to leave space for the eof. */
5719 pty_max_bytes--;
5722 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5723 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5724 when returning with longjmp despite being declared volatile. */
5725 if (!setjmp (send_process_frame))
5727 p = XPROCESS (proc); /* Repair any setjmp clobbering. */
5728 process_sent_to = proc;
5730 /* If there is already data in the write_queue, put the new data
5731 in the back of queue. Otherwise, ignore it. */
5732 if (!NILP (p->write_queue))
5733 write_queue_push (p, object, buf, len, 0);
5735 do /* while !NILP (p->write_queue) */
5737 ptrdiff_t cur_len = -1;
5738 const char *cur_buf;
5739 Lisp_Object cur_object;
5741 /* If write_queue is empty, ignore it. */
5742 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5744 cur_len = len;
5745 cur_buf = buf;
5746 cur_object = object;
5749 while (cur_len > 0)
5751 /* Send this batch, using one or more write calls. */
5752 ptrdiff_t written = 0;
5753 int outfd = p->outfd;
5754 old_sigpipe = (void (*) (int)) signal (SIGPIPE, send_process_trap);
5755 #ifdef DATAGRAM_SOCKETS
5756 if (DATAGRAM_CHAN_P (outfd))
5758 rv = sendto (outfd, cur_buf, cur_len,
5759 0, datagram_address[outfd].sa,
5760 datagram_address[outfd].len);
5761 if (0 <= rv)
5762 written = rv;
5763 else if (errno == EMSGSIZE)
5765 signal (SIGPIPE, old_sigpipe);
5766 report_file_error ("sending datagram",
5767 Fcons (proc, Qnil));
5770 else
5771 #endif
5773 #ifdef HAVE_GNUTLS
5774 if (p->gnutls_p)
5775 written = emacs_gnutls_write (p, cur_buf, cur_len);
5776 else
5777 #endif
5778 written = emacs_write (outfd, cur_buf, cur_len);
5779 rv = (written ? 0 : -1);
5780 #ifdef ADAPTIVE_READ_BUFFERING
5781 if (p->read_output_delay > 0
5782 && p->adaptive_read_buffering == 1)
5784 p->read_output_delay = 0;
5785 process_output_delay_count--;
5786 p->read_output_skip = 0;
5788 #endif
5790 signal (SIGPIPE, old_sigpipe);
5792 if (rv < 0)
5794 if (0
5795 #ifdef EWOULDBLOCK
5796 || errno == EWOULDBLOCK
5797 #endif
5798 #ifdef EAGAIN
5799 || errno == EAGAIN
5800 #endif
5802 /* Buffer is full. Wait, accepting input;
5803 that may allow the program
5804 to finish doing output and read more. */
5806 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5807 /* A gross hack to work around a bug in FreeBSD.
5808 In the following sequence, read(2) returns
5809 bogus data:
5811 write(2) 1022 bytes
5812 write(2) 954 bytes, get EAGAIN
5813 read(2) 1024 bytes in process_read_output
5814 read(2) 11 bytes in process_read_output
5816 That is, read(2) returns more bytes than have
5817 ever been written successfully. The 1033 bytes
5818 read are the 1022 bytes written successfully
5819 after processing (for example with CRs added if
5820 the terminal is set up that way which it is
5821 here). The same bytes will be seen again in a
5822 later read(2), without the CRs. */
5824 if (errno == EAGAIN)
5826 int flags = FWRITE;
5827 ioctl (p->outfd, TIOCFLUSH, &flags);
5829 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5831 /* Put what we should have written in wait_queue. */
5832 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5833 wait_reading_process_output (0, 20 * 1000 * 1000,
5834 0, 0, Qnil, NULL, 0);
5835 /* Reread queue, to see what is left. */
5836 break;
5838 else
5839 /* This is a real error. */
5840 report_file_error ("writing to process", Fcons (proc, Qnil));
5842 cur_buf += written;
5843 cur_len -= written;
5846 while (!NILP (p->write_queue));
5848 else
5850 signal (SIGPIPE, old_sigpipe);
5851 proc = process_sent_to;
5852 p = XPROCESS (proc);
5853 p->raw_status_new = 0;
5854 PSET (p, status, Fcons (Qexit, Fcons (make_number (256), Qnil)));
5855 p->tick = ++process_tick;
5856 deactivate_process (proc);
5857 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5861 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5862 3, 3, 0,
5863 doc: /* Send current contents of region as input to PROCESS.
5864 PROCESS may be a process, a buffer, the name of a process or buffer, or
5865 nil, indicating the current buffer's process.
5866 Called from program, takes three arguments, PROCESS, START and END.
5867 If the region is more than 500 characters long,
5868 it is sent in several bunches. This may happen even for shorter regions.
5869 Output from processes can arrive in between bunches. */)
5870 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5872 Lisp_Object proc;
5873 ptrdiff_t start1, end1;
5875 proc = get_process (process);
5876 validate_region (&start, &end);
5878 if (XINT (start) < GPT && XINT (end) > GPT)
5879 move_gap (XINT (start));
5881 start1 = CHAR_TO_BYTE (XINT (start));
5882 end1 = CHAR_TO_BYTE (XINT (end));
5883 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5884 Fcurrent_buffer ());
5886 return Qnil;
5889 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5890 2, 2, 0,
5891 doc: /* Send PROCESS the contents of STRING as input.
5892 PROCESS may be a process, a buffer, the name of a process or buffer, or
5893 nil, indicating the current buffer's process.
5894 If STRING is more than 500 characters long,
5895 it is sent in several bunches. This may happen even for shorter strings.
5896 Output from processes can arrive in between bunches. */)
5897 (Lisp_Object process, Lisp_Object string)
5899 Lisp_Object proc;
5900 CHECK_STRING (string);
5901 proc = get_process (process);
5902 send_process (proc, SSDATA (string),
5903 SBYTES (string), string);
5904 return Qnil;
5907 /* Return the foreground process group for the tty/pty that
5908 the process P uses. */
5909 static pid_t
5910 emacs_get_tty_pgrp (struct Lisp_Process *p)
5912 pid_t gid = -1;
5914 #ifdef TIOCGPGRP
5915 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5917 int fd;
5918 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5919 master side. Try the slave side. */
5920 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5922 if (fd != -1)
5924 ioctl (fd, TIOCGPGRP, &gid);
5925 emacs_close (fd);
5928 #endif /* defined (TIOCGPGRP ) */
5930 return gid;
5933 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5934 Sprocess_running_child_p, 0, 1, 0,
5935 doc: /* Return t if PROCESS has given the terminal to a child.
5936 If the operating system does not make it possible to find out,
5937 return t unconditionally. */)
5938 (Lisp_Object process)
5940 /* Initialize in case ioctl doesn't exist or gives an error,
5941 in a way that will cause returning t. */
5942 pid_t gid;
5943 Lisp_Object proc;
5944 struct Lisp_Process *p;
5946 proc = get_process (process);
5947 p = XPROCESS (proc);
5949 if (!EQ (p->type, Qreal))
5950 error ("Process %s is not a subprocess",
5951 SDATA (p->name));
5952 if (p->infd < 0)
5953 error ("Process %s is not active",
5954 SDATA (p->name));
5956 gid = emacs_get_tty_pgrp (p);
5958 if (gid == p->pid)
5959 return Qnil;
5960 return Qt;
5963 /* send a signal number SIGNO to PROCESS.
5964 If CURRENT_GROUP is t, that means send to the process group
5965 that currently owns the terminal being used to communicate with PROCESS.
5966 This is used for various commands in shell mode.
5967 If CURRENT_GROUP is lambda, that means send to the process group
5968 that currently owns the terminal, but only if it is NOT the shell itself.
5970 If NOMSG is zero, insert signal-announcements into process's buffers
5971 right away.
5973 If we can, we try to signal PROCESS by sending control characters
5974 down the pty. This allows us to signal inferiors who have changed
5975 their uid, for which killpg would return an EPERM error. */
5977 static void
5978 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5979 int nomsg)
5981 Lisp_Object proc;
5982 register struct Lisp_Process *p;
5983 pid_t gid;
5984 int no_pgrp = 0;
5986 proc = get_process (process);
5987 p = XPROCESS (proc);
5989 if (!EQ (p->type, Qreal))
5990 error ("Process %s is not a subprocess",
5991 SDATA (p->name));
5992 if (p->infd < 0)
5993 error ("Process %s is not active",
5994 SDATA (p->name));
5996 if (!p->pty_flag)
5997 current_group = Qnil;
5999 /* If we are using pgrps, get a pgrp number and make it negative. */
6000 if (NILP (current_group))
6001 /* Send the signal to the shell's process group. */
6002 gid = p->pid;
6003 else
6005 #ifdef SIGNALS_VIA_CHARACTERS
6006 /* If possible, send signals to the entire pgrp
6007 by sending an input character to it. */
6009 struct termios t;
6010 cc_t *sig_char = NULL;
6012 tcgetattr (p->infd, &t);
6014 switch (signo)
6016 case SIGINT:
6017 sig_char = &t.c_cc[VINTR];
6018 break;
6020 case SIGQUIT:
6021 sig_char = &t.c_cc[VQUIT];
6022 break;
6024 case SIGTSTP:
6025 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6026 sig_char = &t.c_cc[VSWTCH];
6027 #else
6028 sig_char = &t.c_cc[VSUSP];
6029 #endif
6030 break;
6033 if (sig_char && *sig_char != CDISABLE)
6035 send_process (proc, (char *) sig_char, 1, Qnil);
6036 return;
6038 /* If we can't send the signal with a character,
6039 fall through and send it another way. */
6041 /* The code above may fall through if it can't
6042 handle the signal. */
6043 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6045 #ifdef TIOCGPGRP
6046 /* Get the current pgrp using the tty itself, if we have that.
6047 Otherwise, use the pty to get the pgrp.
6048 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6049 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6050 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6051 His patch indicates that if TIOCGPGRP returns an error, then
6052 we should just assume that p->pid is also the process group id. */
6054 gid = emacs_get_tty_pgrp (p);
6056 if (gid == -1)
6057 /* If we can't get the information, assume
6058 the shell owns the tty. */
6059 gid = p->pid;
6061 /* It is not clear whether anything really can set GID to -1.
6062 Perhaps on some system one of those ioctls can or could do so.
6063 Or perhaps this is vestigial. */
6064 if (gid == -1)
6065 no_pgrp = 1;
6066 #else /* ! defined (TIOCGPGRP ) */
6067 /* Can't select pgrps on this system, so we know that
6068 the child itself heads the pgrp. */
6069 gid = p->pid;
6070 #endif /* ! defined (TIOCGPGRP ) */
6072 /* If current_group is lambda, and the shell owns the terminal,
6073 don't send any signal. */
6074 if (EQ (current_group, Qlambda) && gid == p->pid)
6075 return;
6078 switch (signo)
6080 #ifdef SIGCONT
6081 case SIGCONT:
6082 p->raw_status_new = 0;
6083 PSET (p, status, Qrun);
6084 p->tick = ++process_tick;
6085 if (!nomsg)
6087 status_notify (NULL);
6088 redisplay_preserve_echo_area (13);
6090 break;
6091 #endif /* ! defined (SIGCONT) */
6092 case SIGINT:
6093 case SIGQUIT:
6094 case SIGKILL:
6095 flush_pending_output (p->infd);
6096 break;
6099 /* If we don't have process groups, send the signal to the immediate
6100 subprocess. That isn't really right, but it's better than any
6101 obvious alternative. */
6102 if (no_pgrp)
6104 kill (p->pid, signo);
6105 return;
6108 /* gid may be a pid, or minus a pgrp's number */
6109 #ifdef TIOCSIGSEND
6110 if (!NILP (current_group))
6112 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6113 EMACS_KILLPG (gid, signo);
6115 else
6117 gid = - p->pid;
6118 kill (gid, signo);
6120 #else /* ! defined (TIOCSIGSEND) */
6121 EMACS_KILLPG (gid, signo);
6122 #endif /* ! defined (TIOCSIGSEND) */
6125 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6126 doc: /* Interrupt process PROCESS.
6127 PROCESS may be a process, a buffer, or the name of a process or buffer.
6128 No arg or nil means current buffer's process.
6129 Second arg CURRENT-GROUP non-nil means send signal to
6130 the current process-group of the process's controlling terminal
6131 rather than to the process's own process group.
6132 If the process is a shell, this means interrupt current subjob
6133 rather than the shell.
6135 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6136 don't send the signal. */)
6137 (Lisp_Object process, Lisp_Object current_group)
6139 process_send_signal (process, SIGINT, current_group, 0);
6140 return process;
6143 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6144 doc: /* Kill process PROCESS. May be process or name of one.
6145 See function `interrupt-process' for more details on usage. */)
6146 (Lisp_Object process, Lisp_Object current_group)
6148 process_send_signal (process, SIGKILL, current_group, 0);
6149 return process;
6152 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6153 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6154 See function `interrupt-process' for more details on usage. */)
6155 (Lisp_Object process, Lisp_Object current_group)
6157 process_send_signal (process, SIGQUIT, current_group, 0);
6158 return process;
6161 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6162 doc: /* Stop process PROCESS. May be process or name of one.
6163 See function `interrupt-process' for more details on usage.
6164 If PROCESS is a network or serial process, inhibit handling of incoming
6165 traffic. */)
6166 (Lisp_Object process, Lisp_Object current_group)
6168 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6170 struct Lisp_Process *p;
6172 p = XPROCESS (process);
6173 if (NILP (p->command)
6174 && p->infd >= 0)
6175 delete_read_fd (p->infd);
6176 PSET (p, command, Qt);
6177 return process;
6179 #ifndef SIGTSTP
6180 error ("No SIGTSTP support");
6181 #else
6182 process_send_signal (process, SIGTSTP, current_group, 0);
6183 #endif
6184 return process;
6187 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6188 doc: /* Continue process PROCESS. May be process or name of one.
6189 See function `interrupt-process' for more details on usage.
6190 If PROCESS is a network or serial process, resume handling of incoming
6191 traffic. */)
6192 (Lisp_Object process, Lisp_Object current_group)
6194 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6196 struct Lisp_Process *p;
6198 p = XPROCESS (process);
6199 if (EQ (p->command, Qt)
6200 && p->infd >= 0
6201 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6203 add_non_keyboard_read_fd (p->infd);
6204 #ifdef WINDOWSNT
6205 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6206 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6207 #else /* not WINDOWSNT */
6208 tcflush (p->infd, TCIFLUSH);
6209 #endif /* not WINDOWSNT */
6211 PSET (p, command, Qnil);
6212 return process;
6214 #ifdef SIGCONT
6215 process_send_signal (process, SIGCONT, current_group, 0);
6216 #else
6217 error ("No SIGCONT support");
6218 #endif
6219 return process;
6222 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6223 2, 2, "sProcess (name or number): \nnSignal code: ",
6224 doc: /* Send PROCESS the signal with code SIGCODE.
6225 PROCESS may also be a number specifying the process id of the
6226 process to signal; in this case, the process need not be a child of
6227 this Emacs.
6228 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6229 (Lisp_Object process, Lisp_Object sigcode)
6231 pid_t pid;
6233 if (STRINGP (process))
6235 Lisp_Object tem = Fget_process (process);
6236 if (NILP (tem))
6238 Lisp_Object process_number =
6239 string_to_number (SSDATA (process), 10, 1);
6240 if (INTEGERP (process_number) || FLOATP (process_number))
6241 tem = process_number;
6243 process = tem;
6245 else if (!NUMBERP (process))
6246 process = get_process (process);
6248 if (NILP (process))
6249 return process;
6251 if (NUMBERP (process))
6252 CONS_TO_INTEGER (process, pid_t, pid);
6253 else
6255 CHECK_PROCESS (process);
6256 pid = XPROCESS (process)->pid;
6257 if (pid <= 0)
6258 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6261 #define parse_signal(NAME, VALUE) \
6262 else if (!xstrcasecmp (name, NAME)) \
6263 XSETINT (sigcode, VALUE)
6265 if (INTEGERP (sigcode))
6266 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6267 else
6269 char *name;
6271 CHECK_SYMBOL (sigcode);
6272 name = SSDATA (SYMBOL_NAME (sigcode));
6274 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6275 name += 3;
6277 if (0)
6279 #ifdef SIGUSR1
6280 parse_signal ("usr1", SIGUSR1);
6281 #endif
6282 #ifdef SIGUSR2
6283 parse_signal ("usr2", SIGUSR2);
6284 #endif
6285 #ifdef SIGTERM
6286 parse_signal ("term", SIGTERM);
6287 #endif
6288 #ifdef SIGHUP
6289 parse_signal ("hup", SIGHUP);
6290 #endif
6291 #ifdef SIGINT
6292 parse_signal ("int", SIGINT);
6293 #endif
6294 #ifdef SIGQUIT
6295 parse_signal ("quit", SIGQUIT);
6296 #endif
6297 #ifdef SIGILL
6298 parse_signal ("ill", SIGILL);
6299 #endif
6300 #ifdef SIGABRT
6301 parse_signal ("abrt", SIGABRT);
6302 #endif
6303 #ifdef SIGEMT
6304 parse_signal ("emt", SIGEMT);
6305 #endif
6306 #ifdef SIGKILL
6307 parse_signal ("kill", SIGKILL);
6308 #endif
6309 #ifdef SIGFPE
6310 parse_signal ("fpe", SIGFPE);
6311 #endif
6312 #ifdef SIGBUS
6313 parse_signal ("bus", SIGBUS);
6314 #endif
6315 #ifdef SIGSEGV
6316 parse_signal ("segv", SIGSEGV);
6317 #endif
6318 #ifdef SIGSYS
6319 parse_signal ("sys", SIGSYS);
6320 #endif
6321 #ifdef SIGPIPE
6322 parse_signal ("pipe", SIGPIPE);
6323 #endif
6324 #ifdef SIGALRM
6325 parse_signal ("alrm", SIGALRM);
6326 #endif
6327 #ifdef SIGURG
6328 parse_signal ("urg", SIGURG);
6329 #endif
6330 #ifdef SIGSTOP
6331 parse_signal ("stop", SIGSTOP);
6332 #endif
6333 #ifdef SIGTSTP
6334 parse_signal ("tstp", SIGTSTP);
6335 #endif
6336 #ifdef SIGCONT
6337 parse_signal ("cont", SIGCONT);
6338 #endif
6339 #ifdef SIGCHLD
6340 parse_signal ("chld", SIGCHLD);
6341 #endif
6342 #ifdef SIGTTIN
6343 parse_signal ("ttin", SIGTTIN);
6344 #endif
6345 #ifdef SIGTTOU
6346 parse_signal ("ttou", SIGTTOU);
6347 #endif
6348 #ifdef SIGIO
6349 parse_signal ("io", SIGIO);
6350 #endif
6351 #ifdef SIGXCPU
6352 parse_signal ("xcpu", SIGXCPU);
6353 #endif
6354 #ifdef SIGXFSZ
6355 parse_signal ("xfsz", SIGXFSZ);
6356 #endif
6357 #ifdef SIGVTALRM
6358 parse_signal ("vtalrm", SIGVTALRM);
6359 #endif
6360 #ifdef SIGPROF
6361 parse_signal ("prof", SIGPROF);
6362 #endif
6363 #ifdef SIGWINCH
6364 parse_signal ("winch", SIGWINCH);
6365 #endif
6366 #ifdef SIGINFO
6367 parse_signal ("info", SIGINFO);
6368 #endif
6369 else
6370 error ("Undefined signal name %s", name);
6373 #undef parse_signal
6375 return make_number (kill (pid, XINT (sigcode)));
6378 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6379 doc: /* Make PROCESS see end-of-file in its input.
6380 EOF comes after any text already sent to it.
6381 PROCESS may be a process, a buffer, the name of a process or buffer, or
6382 nil, indicating the current buffer's process.
6383 If PROCESS is a network connection, or is a process communicating
6384 through a pipe (as opposed to a pty), then you cannot send any more
6385 text to PROCESS after you call this function.
6386 If PROCESS is a serial process, wait until all output written to the
6387 process has been transmitted to the serial port. */)
6388 (Lisp_Object process)
6390 Lisp_Object proc;
6391 struct coding_system *coding;
6393 if (DATAGRAM_CONN_P (process))
6394 return process;
6396 proc = get_process (process);
6397 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6399 /* Make sure the process is really alive. */
6400 if (XPROCESS (proc)->raw_status_new)
6401 update_status (XPROCESS (proc));
6402 if (! EQ (XPROCESS (proc)->status, Qrun))
6403 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6405 if (CODING_REQUIRE_FLUSHING (coding))
6407 coding->mode |= CODING_MODE_LAST_BLOCK;
6408 send_process (proc, "", 0, Qnil);
6411 if (XPROCESS (proc)->pty_flag)
6412 send_process (proc, "\004", 1, Qnil);
6413 else if (EQ (XPROCESS (proc)->type, Qserial))
6415 #ifndef WINDOWSNT
6416 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6417 error ("tcdrain() failed: %s", emacs_strerror (errno));
6418 #endif /* not WINDOWSNT */
6419 /* Do nothing on Windows because writes are blocking. */
6421 else
6423 int old_outfd, new_outfd;
6425 #ifdef HAVE_SHUTDOWN
6426 /* If this is a network connection, or socketpair is used
6427 for communication with the subprocess, call shutdown to cause EOF.
6428 (In some old system, shutdown to socketpair doesn't work.
6429 Then we just can't win.) */
6430 if (EQ (XPROCESS (proc)->type, Qnetwork)
6431 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6432 shutdown (XPROCESS (proc)->outfd, 1);
6433 /* In case of socketpair, outfd == infd, so don't close it. */
6434 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6435 emacs_close (XPROCESS (proc)->outfd);
6436 #else /* not HAVE_SHUTDOWN */
6437 emacs_close (XPROCESS (proc)->outfd);
6438 #endif /* not HAVE_SHUTDOWN */
6439 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6440 if (new_outfd < 0)
6441 abort ();
6442 old_outfd = XPROCESS (proc)->outfd;
6444 if (!proc_encode_coding_system[new_outfd])
6445 proc_encode_coding_system[new_outfd]
6446 = xmalloc (sizeof (struct coding_system));
6447 memcpy (proc_encode_coding_system[new_outfd],
6448 proc_encode_coding_system[old_outfd],
6449 sizeof (struct coding_system));
6450 memset (proc_encode_coding_system[old_outfd], 0,
6451 sizeof (struct coding_system));
6453 XPROCESS (proc)->outfd = new_outfd;
6455 return process;
6458 /* On receipt of a signal that a child status has changed, loop asking
6459 about children with changed statuses until the system says there
6460 are no more.
6462 All we do is change the status; we do not run sentinels or print
6463 notifications. That is saved for the next time keyboard input is
6464 done, in order to avoid timing errors.
6466 ** WARNING: this can be called during garbage collection.
6467 Therefore, it must not be fooled by the presence of mark bits in
6468 Lisp objects.
6470 ** USG WARNING: Although it is not obvious from the documentation
6471 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6472 signal() before executing at least one wait(), otherwise the
6473 handler will be called again, resulting in an infinite loop. The
6474 relevant portion of the documentation reads "SIGCLD signals will be
6475 queued and the signal-catching function will be continually
6476 reentered until the queue is empty". Invoking signal() causes the
6477 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6478 Inc.
6480 ** Malloc WARNING: This should never call malloc either directly or
6481 indirectly; if it does, that is a bug */
6483 #ifdef SIGCHLD
6484 static void
6485 sigchld_handler (int signo)
6487 int old_errno = errno;
6488 Lisp_Object proc;
6489 struct Lisp_Process *p;
6491 SIGNAL_THREAD_CHECK (signo);
6493 while (1)
6495 pid_t pid;
6496 int w;
6497 Lisp_Object tail;
6499 #ifdef WNOHANG
6500 #ifndef WUNTRACED
6501 #define WUNTRACED 0
6502 #endif /* no WUNTRACED */
6503 /* Keep trying to get a status until we get a definitive result. */
6506 errno = 0;
6507 pid = waitpid (-1, &w, WNOHANG | WUNTRACED);
6509 while (pid < 0 && errno == EINTR);
6511 if (pid <= 0)
6513 /* PID == 0 means no processes found, PID == -1 means a real
6514 failure. We have done all our job, so return. */
6516 errno = old_errno;
6517 return;
6519 #else
6520 pid = wait (&w);
6521 #endif /* no WNOHANG */
6523 /* Find the process that signaled us, and record its status. */
6525 /* The process can have been deleted by Fdelete_process. */
6526 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6528 Lisp_Object xpid = XCAR (tail);
6529 if ((INTEGERP (xpid) && pid == XINT (xpid))
6530 || (FLOATP (xpid) && pid == XFLOAT_DATA (xpid)))
6532 XSETCAR (tail, Qnil);
6533 goto sigchld_end_of_loop;
6537 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6538 p = 0;
6539 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6541 proc = XCDR (XCAR (tail));
6542 p = XPROCESS (proc);
6543 if (EQ (p->type, Qreal) && p->pid == pid)
6544 break;
6545 p = 0;
6548 /* Look for an asynchronous process whose pid hasn't been filled
6549 in yet. */
6550 if (p == 0)
6551 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6553 proc = XCDR (XCAR (tail));
6554 p = XPROCESS (proc);
6555 if (p->pid == -1)
6556 break;
6557 p = 0;
6560 /* Change the status of the process that was found. */
6561 if (p != 0)
6563 int clear_desc_flag = 0;
6565 p->tick = ++process_tick;
6566 p->raw_status = w;
6567 p->raw_status_new = 1;
6569 /* If process has terminated, stop waiting for its output. */
6570 if ((WIFSIGNALED (w) || WIFEXITED (w))
6571 && p->infd >= 0)
6572 clear_desc_flag = 1;
6574 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6575 if (clear_desc_flag)
6576 delete_read_fd (p->infd);
6578 /* Tell wait_reading_process_output that it needs to wake up and
6579 look around. */
6580 if (input_available_clear_time)
6581 *input_available_clear_time = make_emacs_time (0, 0);
6584 /* There was no asynchronous process found for that pid: we have
6585 a synchronous process. */
6586 else
6588 synch_process_alive = 0;
6590 /* Report the status of the synchronous process. */
6591 if (WIFEXITED (w))
6592 synch_process_retcode = WEXITSTATUS (w);
6593 else if (WIFSIGNALED (w))
6594 synch_process_termsig = WTERMSIG (w);
6596 /* Tell wait_reading_process_output that it needs to wake up and
6597 look around. */
6598 if (input_available_clear_time)
6599 *input_available_clear_time = make_emacs_time (0, 0);
6602 sigchld_end_of_loop:
6605 /* On some systems, we must return right away.
6606 If any more processes want to signal us, we will
6607 get another signal.
6608 Otherwise (on systems that have WNOHANG), loop around
6609 to use up all the processes that have something to tell us. */
6610 #if (defined WINDOWSNT \
6611 || (defined USG && !defined GNU_LINUX \
6612 && !(defined HPUX && defined WNOHANG)))
6613 errno = old_errno;
6614 return;
6615 #endif /* USG, but not HPUX with WNOHANG */
6618 #endif /* SIGCHLD */
6621 static Lisp_Object
6622 exec_sentinel_unwind (Lisp_Object data)
6624 PSET (XPROCESS (XCAR (data)), sentinel, XCDR (data));
6625 return Qnil;
6628 static Lisp_Object
6629 exec_sentinel_error_handler (Lisp_Object error_val)
6631 cmd_error_internal (error_val, "error in process sentinel: ");
6632 Vinhibit_quit = Qt;
6633 update_echo_area ();
6634 Fsleep_for (make_number (2), Qnil);
6635 return Qt;
6638 static void
6639 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6641 Lisp_Object sentinel, odeactivate;
6642 register struct Lisp_Process *p = XPROCESS (proc);
6643 ptrdiff_t count = SPECPDL_INDEX ();
6644 int outer_running_asynch_code = running_asynch_code;
6645 int waiting = waiting_for_user_input_p;
6647 if (inhibit_sentinels)
6648 return;
6650 /* No need to gcpro these, because all we do with them later
6651 is test them for EQness, and none of them should be a string. */
6652 odeactivate = Vdeactivate_mark;
6653 #if 0
6654 Lisp_Object obuffer, okeymap;
6655 XSETBUFFER (obuffer, current_buffer);
6656 okeymap = BVAR (current_buffer, keymap);
6657 #endif
6659 /* There's no good reason to let sentinels change the current
6660 buffer, and many callers of accept-process-output, sit-for, and
6661 friends don't expect current-buffer to be changed from under them. */
6662 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6664 sentinel = p->sentinel;
6665 if (NILP (sentinel))
6666 return;
6668 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6669 assure that it gets restored no matter how the sentinel exits. */
6670 PSET (p, sentinel, Qnil);
6671 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6672 /* Inhibit quit so that random quits don't screw up a running filter. */
6673 specbind (Qinhibit_quit, Qt);
6674 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6676 /* In case we get recursively called,
6677 and we already saved the match data nonrecursively,
6678 save the same match data in safely recursive fashion. */
6679 if (outer_running_asynch_code)
6681 Lisp_Object tem;
6682 tem = Fmatch_data (Qnil, Qnil, Qnil);
6683 restore_search_regs ();
6684 record_unwind_save_match_data ();
6685 Fset_match_data (tem, Qt);
6688 /* For speed, if a search happens within this code,
6689 save the match data in a special nonrecursive fashion. */
6690 running_asynch_code = 1;
6692 internal_condition_case_1 (read_process_output_call,
6693 Fcons (sentinel,
6694 Fcons (proc, Fcons (reason, Qnil))),
6695 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6696 exec_sentinel_error_handler);
6698 /* If we saved the match data nonrecursively, restore it now. */
6699 restore_search_regs ();
6700 running_asynch_code = outer_running_asynch_code;
6702 Vdeactivate_mark = odeactivate;
6704 /* Restore waiting_for_user_input_p as it was
6705 when we were called, in case the filter clobbered it. */
6706 waiting_for_user_input_p = waiting;
6708 #if 0
6709 if (! EQ (Fcurrent_buffer (), obuffer)
6710 || ! EQ (current_buffer->keymap, okeymap))
6711 #endif
6712 /* But do it only if the caller is actually going to read events.
6713 Otherwise there's no need to make him wake up, and it could
6714 cause trouble (for example it would make sit_for return). */
6715 if (waiting_for_user_input_p == -1)
6716 record_asynch_buffer_change ();
6718 unbind_to (count, Qnil);
6721 /* Report all recent events of a change in process status
6722 (either run the sentinel or output a message).
6723 This is usually done while Emacs is waiting for keyboard input
6724 but can be done at other times. */
6726 static void
6727 status_notify (struct Lisp_Process *deleting_process)
6729 register Lisp_Object proc, buffer;
6730 Lisp_Object tail, msg;
6731 struct gcpro gcpro1, gcpro2;
6733 tail = Qnil;
6734 msg = Qnil;
6735 /* We need to gcpro tail; if read_process_output calls a filter
6736 which deletes a process and removes the cons to which tail points
6737 from Vprocess_alist, and then causes a GC, tail is an unprotected
6738 reference. */
6739 GCPRO2 (tail, msg);
6741 /* Set this now, so that if new processes are created by sentinels
6742 that we run, we get called again to handle their status changes. */
6743 update_tick = process_tick;
6745 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6747 Lisp_Object symbol;
6748 register struct Lisp_Process *p;
6750 proc = Fcdr (XCAR (tail));
6751 p = XPROCESS (proc);
6753 if (p->tick != p->update_tick)
6755 p->update_tick = p->tick;
6757 /* If process is still active, read any output that remains. */
6758 while (! EQ (p->filter, Qt)
6759 && ! EQ (p->status, Qconnect)
6760 && ! EQ (p->status, Qlisten)
6761 /* Network or serial process not stopped: */
6762 && ! EQ (p->command, Qt)
6763 && p->infd >= 0
6764 && p != deleting_process
6765 && read_process_output (proc, p->infd) > 0);
6767 buffer = p->buffer;
6769 /* Get the text to use for the message. */
6770 if (p->raw_status_new)
6771 update_status (p);
6772 msg = status_message (p);
6774 /* If process is terminated, deactivate it or delete it. */
6775 symbol = p->status;
6776 if (CONSP (p->status))
6777 symbol = XCAR (p->status);
6779 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6780 || EQ (symbol, Qclosed))
6782 if (delete_exited_processes)
6783 remove_process (proc);
6784 else
6785 deactivate_process (proc);
6788 /* The actions above may have further incremented p->tick.
6789 So set p->update_tick again
6790 so that an error in the sentinel will not cause
6791 this code to be run again. */
6792 p->update_tick = p->tick;
6793 /* Now output the message suitably. */
6794 if (!NILP (p->sentinel))
6795 exec_sentinel (proc, msg);
6796 /* Don't bother with a message in the buffer
6797 when a process becomes runnable. */
6798 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6800 Lisp_Object tem;
6801 struct buffer *old = current_buffer;
6802 ptrdiff_t opoint, opoint_byte;
6803 ptrdiff_t before, before_byte;
6805 /* Avoid error if buffer is deleted
6806 (probably that's why the process is dead, too) */
6807 if (NILP (BVAR (XBUFFER (buffer), name)))
6808 continue;
6809 Fset_buffer (buffer);
6811 opoint = PT;
6812 opoint_byte = PT_BYTE;
6813 /* Insert new output into buffer
6814 at the current end-of-output marker,
6815 thus preserving logical ordering of input and output. */
6816 if (XMARKER (p->mark)->buffer)
6817 Fgoto_char (p->mark);
6818 else
6819 SET_PT_BOTH (ZV, ZV_BYTE);
6821 before = PT;
6822 before_byte = PT_BYTE;
6824 tem = BVAR (current_buffer, read_only);
6825 BSET (current_buffer, read_only, Qnil);
6826 insert_string ("\nProcess ");
6827 { /* FIXME: temporary kludge */
6828 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6829 insert_string (" ");
6830 Finsert (1, &msg);
6831 BSET (current_buffer, read_only, tem);
6832 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6834 if (opoint >= before)
6835 SET_PT_BOTH (opoint + (PT - before),
6836 opoint_byte + (PT_BYTE - before_byte));
6837 else
6838 SET_PT_BOTH (opoint, opoint_byte);
6840 set_buffer_internal (old);
6843 } /* end for */
6845 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6846 UNGCPRO;
6850 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6851 Sset_process_coding_system, 1, 3, 0,
6852 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6853 DECODING will be used to decode subprocess output and ENCODING to
6854 encode subprocess input. */)
6855 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6857 register struct Lisp_Process *p;
6859 CHECK_PROCESS (process);
6860 p = XPROCESS (process);
6861 if (p->infd < 0)
6862 error ("Input file descriptor of %s closed", SDATA (p->name));
6863 if (p->outfd < 0)
6864 error ("Output file descriptor of %s closed", SDATA (p->name));
6865 Fcheck_coding_system (decoding);
6866 Fcheck_coding_system (encoding);
6867 encoding = coding_inherit_eol_type (encoding, Qnil);
6868 PSET (p, decode_coding_system, decoding);
6869 PSET (p, encode_coding_system, encoding);
6870 setup_process_coding_systems (process);
6872 return Qnil;
6875 DEFUN ("process-coding-system",
6876 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6877 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6878 (register Lisp_Object process)
6880 CHECK_PROCESS (process);
6881 return Fcons (XPROCESS (process)->decode_coding_system,
6882 XPROCESS (process)->encode_coding_system);
6885 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6886 Sset_process_filter_multibyte, 2, 2, 0,
6887 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6888 If FLAG is non-nil, the filter is given multibyte strings.
6889 If FLAG is nil, the filter is given unibyte strings. In this case,
6890 all character code conversion except for end-of-line conversion is
6891 suppressed. */)
6892 (Lisp_Object process, Lisp_Object flag)
6894 register struct Lisp_Process *p;
6896 CHECK_PROCESS (process);
6897 p = XPROCESS (process);
6898 if (NILP (flag))
6899 PSET (p, decode_coding_system,
6900 raw_text_coding_system (p->decode_coding_system));
6901 setup_process_coding_systems (process);
6903 return Qnil;
6906 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6907 Sprocess_filter_multibyte_p, 1, 1, 0,
6908 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6909 (Lisp_Object process)
6911 register struct Lisp_Process *p;
6912 struct coding_system *coding;
6914 CHECK_PROCESS (process);
6915 p = XPROCESS (process);
6916 coding = proc_decode_coding_system[p->infd];
6917 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6923 # ifdef HAVE_GPM
6925 void
6926 add_gpm_wait_descriptor (int desc)
6928 add_keyboard_wait_descriptor (desc);
6931 void
6932 delete_gpm_wait_descriptor (int desc)
6934 delete_keyboard_wait_descriptor (desc);
6937 # endif
6939 # ifdef SIGIO
6941 /* Return nonzero if *MASK has a bit set
6942 that corresponds to one of the keyboard input descriptors. */
6944 static int
6945 keyboard_bit_set (fd_set *mask)
6947 int fd;
6949 for (fd = 0; fd <= max_input_desc; fd++)
6950 if (FD_ISSET (fd, mask)
6951 && ((fd_callback_info[fd].flags & KEYBOARD_FD) != 0))
6952 return 1;
6954 return 0;
6956 # endif
6958 #else /* not subprocesses */
6960 /* Defined on msdos.c. */
6961 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6962 EMACS_TIME *, void *);
6964 /* Implementation of wait_reading_process_output, assuming that there
6965 are no subprocesses. Used only by the MS-DOS build.
6967 Wait for timeout to elapse and/or keyboard input to be available.
6969 TIME_LIMIT is:
6970 timeout in seconds
6971 If negative, gobble data immediately available but don't wait for any.
6973 NSECS is:
6974 an additional duration to wait, measured in nanoseconds
6975 If TIME_LIMIT is zero, then:
6976 If NSECS == 0, there is no limit.
6977 If NSECS > 0, the timeout consists of NSECS only.
6978 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6980 READ_KBD is:
6981 0 to ignore keyboard input, or
6982 1 to return when input is available, or
6983 -1 means caller will actually read the input, so don't throw to
6984 the quit handler.
6986 see full version for other parameters. We know that wait_proc will
6987 always be NULL, since `subprocesses' isn't defined.
6989 DO_DISPLAY != 0 means redisplay should be done to show subprocess
6990 output that arrives.
6992 Return true if we received input from any process. */
6995 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6996 int do_display,
6997 Lisp_Object wait_for_cell,
6998 struct Lisp_Process *wait_proc, int just_wait_proc)
7000 register int nfds;
7001 EMACS_TIME end_time, timeout;
7003 if (time_limit < 0)
7005 time_limit = 0;
7006 nsecs = -1;
7008 else if (TYPE_MAXIMUM (time_t) < time_limit)
7009 time_limit = TYPE_MAXIMUM (time_t);
7011 /* What does time_limit really mean? */
7012 if (time_limit || 0 < nsecs)
7014 timeout = make_emacs_time (time_limit, nsecs);
7015 end_time = add_emacs_time (current_emacs_time (), timeout);
7018 /* Turn off periodic alarms (in case they are in use)
7019 and then turn off any other atimers,
7020 because the select emulator uses alarms. */
7021 stop_polling ();
7022 turn_on_atimers (0);
7024 while (1)
7026 int timeout_reduced_for_timers = 0;
7027 SELECT_TYPE waitchannels;
7028 int xerrno;
7030 /* If calling from keyboard input, do not quit
7031 since we want to return C-g as an input character.
7032 Otherwise, do pending quit if requested. */
7033 if (read_kbd >= 0)
7034 QUIT;
7036 /* Exit now if the cell we're waiting for became non-nil. */
7037 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7038 break;
7040 /* Compute time from now till when time limit is up */
7041 /* Exit if already run out */
7042 if (nsecs < 0)
7044 /* A negative timeout means
7045 gobble output available now
7046 but don't wait at all. */
7048 timeout = make_emacs_time (0, 0);
7050 else if (time_limit || 0 < nsecs)
7052 EMACS_TIME now = current_emacs_time ();
7053 if (EMACS_TIME_LE (end_time, now))
7054 break;
7055 timeout = sub_emacs_time (end_time, now);
7057 else
7059 timeout = make_emacs_time (100000, 0);
7062 /* If our caller will not immediately handle keyboard events,
7063 run timer events directly.
7064 (Callers that will immediately read keyboard events
7065 call timer_delay on their own.) */
7066 if (NILP (wait_for_cell))
7068 EMACS_TIME timer_delay;
7072 int old_timers_run = timers_run;
7073 timer_delay = timer_check ();
7074 if (timers_run != old_timers_run && do_display)
7075 /* We must retry, since a timer may have requeued itself
7076 and that could alter the time delay. */
7077 redisplay_preserve_echo_area (14);
7078 else
7079 break;
7081 while (!detect_input_pending ());
7083 /* If there is unread keyboard input, also return. */
7084 if (read_kbd != 0
7085 && requeued_events_pending_p ())
7086 break;
7088 if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
7090 if (EMACS_TIME_LT (timer_delay, timeout))
7092 timeout = timer_delay;
7093 timeout_reduced_for_timers = 1;
7098 /* Cause C-g and alarm signals to take immediate action,
7099 and cause input available signals to zero out timeout. */
7100 if (read_kbd < 0)
7101 set_waiting_for_input (&timeout);
7103 /* If a frame has been newly mapped and needs updating,
7104 reprocess its display stuff. */
7105 if (frame_garbaged && do_display)
7107 clear_waiting_for_input ();
7108 redisplay_preserve_echo_area (15);
7109 if (read_kbd < 0)
7110 set_waiting_for_input (&timeout);
7113 /* Wait till there is something to do. */
7114 FD_ZERO (&waitchannels);
7115 if (read_kbd && detect_input_pending ())
7116 nfds = 0;
7117 else
7119 if (read_kbd || !NILP (wait_for_cell))
7120 FD_SET (0, &waitchannels);
7121 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7124 xerrno = errno;
7126 /* Make C-g and alarm signals set flags again */
7127 clear_waiting_for_input ();
7129 /* If we woke up due to SIGWINCH, actually change size now. */
7130 do_pending_window_change (0);
7132 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7133 /* We waited the full specified time, so return now. */
7134 break;
7136 if (nfds == -1)
7138 /* If the system call was interrupted, then go around the
7139 loop again. */
7140 if (xerrno == EINTR)
7141 FD_ZERO (&waitchannels);
7142 else
7143 error ("select error: %s", emacs_strerror (xerrno));
7146 /* Check for keyboard input */
7148 if (read_kbd
7149 && detect_input_pending_run_timers (do_display))
7151 swallow_events (do_display);
7152 if (detect_input_pending_run_timers (do_display))
7153 break;
7156 /* If there is unread keyboard input, also return. */
7157 if (read_kbd
7158 && requeued_events_pending_p ())
7159 break;
7161 /* If wait_for_cell. check for keyboard input
7162 but don't run any timers.
7163 ??? (It seems wrong to me to check for keyboard
7164 input at all when wait_for_cell, but the code
7165 has been this way since July 1994.
7166 Try changing this after version 19.31.) */
7167 if (! NILP (wait_for_cell)
7168 && detect_input_pending ())
7170 swallow_events (do_display);
7171 if (detect_input_pending ())
7172 break;
7175 /* Exit now if the cell we're waiting for became non-nil. */
7176 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7177 break;
7180 start_polling ();
7182 return 0;
7185 #endif /* not subprocesses */
7187 /* The following functions are needed even if async subprocesses are
7188 not supported. Some of them are no-op stubs in that case. */
7190 /* Add DESC to the set of keyboard input descriptors. */
7192 void
7193 add_keyboard_wait_descriptor (int desc)
7195 #ifdef subprocesses /* actually means "not MSDOS" */
7196 eassert (desc >= 0 && desc < MAXDESC);
7197 fd_callback_info[desc].flags |= FOR_READ | KEYBOARD_FD;
7198 if (desc > max_input_desc)
7199 max_input_desc = desc;
7200 #endif
7203 /* From now on, do not expect DESC to give keyboard input. */
7205 void
7206 delete_keyboard_wait_descriptor (int desc)
7208 #ifdef subprocesses
7209 int fd;
7210 int lim = max_input_desc;
7212 fd_callback_info[desc].flags &= ~(FOR_READ | KEYBOARD_FD | PROCESS_FD);
7214 if (desc == max_input_desc)
7216 for (fd = max_input_desc; fd >= 0; --fd)
7218 if (fd_callback_info[desc].flags != 0)
7220 max_input_desc = fd;
7221 break;
7225 #endif
7228 /* Setup coding systems of PROCESS. */
7230 void
7231 setup_process_coding_systems (Lisp_Object process)
7233 #ifdef subprocesses
7234 struct Lisp_Process *p = XPROCESS (process);
7235 int inch = p->infd;
7236 int outch = p->outfd;
7237 Lisp_Object coding_system;
7239 if (inch < 0 || outch < 0)
7240 return;
7242 if (!proc_decode_coding_system[inch])
7243 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7244 coding_system = p->decode_coding_system;
7245 if (! NILP (p->filter))
7247 else if (BUFFERP (p->buffer))
7249 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7250 coding_system = raw_text_coding_system (coding_system);
7252 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7254 if (!proc_encode_coding_system[outch])
7255 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7256 setup_coding_system (p->encode_coding_system,
7257 proc_encode_coding_system[outch]);
7258 #endif
7261 /* Close all descriptors currently in use for communication
7262 with subprocess. This is used in a newly-forked subprocess
7263 to get rid of irrelevant descriptors. */
7265 void
7266 close_process_descs (void)
7268 #ifndef DOS_NT
7269 int i;
7270 for (i = 0; i < MAXDESC; i++)
7272 Lisp_Object process;
7273 process = chan_process[i];
7274 if (!NILP (process))
7276 int in = XPROCESS (process)->infd;
7277 int out = XPROCESS (process)->outfd;
7278 if (in >= 0)
7279 emacs_close (in);
7280 if (out >= 0 && in != out)
7281 emacs_close (out);
7284 #endif
7287 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7288 doc: /* Return the (or a) process associated with BUFFER.
7289 BUFFER may be a buffer or the name of one. */)
7290 (register Lisp_Object buffer)
7292 #ifdef subprocesses
7293 register Lisp_Object buf, tail, proc;
7295 if (NILP (buffer)) return Qnil;
7296 buf = Fget_buffer (buffer);
7297 if (NILP (buf)) return Qnil;
7299 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7301 proc = Fcdr (XCAR (tail));
7302 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7303 return proc;
7305 #endif /* subprocesses */
7306 return Qnil;
7309 DEFUN ("process-inherit-coding-system-flag",
7310 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7311 1, 1, 0,
7312 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7313 If this flag is t, `buffer-file-coding-system' of the buffer
7314 associated with PROCESS will inherit the coding system used to decode
7315 the process output. */)
7316 (register Lisp_Object process)
7318 #ifdef subprocesses
7319 CHECK_PROCESS (process);
7320 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7321 #else
7322 /* Ignore the argument and return the value of
7323 inherit-process-coding-system. */
7324 return inherit_process_coding_system ? Qt : Qnil;
7325 #endif
7328 /* Kill all processes associated with `buffer'.
7329 If `buffer' is nil, kill all processes */
7331 void
7332 kill_buffer_processes (Lisp_Object buffer)
7334 #ifdef subprocesses
7335 Lisp_Object tail, proc;
7337 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7339 proc = XCDR (XCAR (tail));
7340 if (PROCESSP (proc)
7341 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7343 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7344 Fdelete_process (proc);
7345 else if (XPROCESS (proc)->infd >= 0)
7346 process_send_signal (proc, SIGHUP, Qnil, 1);
7349 #else /* subprocesses */
7350 /* Since we have no subprocesses, this does nothing. */
7351 #endif /* subprocesses */
7354 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7355 Swaiting_for_user_input_p, 0, 0, 0,
7356 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7357 This is intended for use by asynchronous process output filters and sentinels. */)
7358 (void)
7360 #ifdef subprocesses
7361 return (waiting_for_user_input_p ? Qt : Qnil);
7362 #else
7363 return Qnil;
7364 #endif
7367 /* Stop reading input from keyboard sources. */
7369 void
7370 hold_keyboard_input (void)
7372 kbd_is_on_hold = 1;
7375 /* Resume reading input from keyboard sources. */
7377 void
7378 unhold_keyboard_input (void)
7380 kbd_is_on_hold = 0;
7383 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7386 kbd_on_hold_p (void)
7388 return kbd_is_on_hold;
7392 /* Enumeration of and access to system processes a-la ps(1). */
7394 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7395 0, 0, 0,
7396 doc: /* Return a list of numerical process IDs of all running processes.
7397 If this functionality is unsupported, return nil.
7399 See `process-attributes' for getting attributes of a process given its ID. */)
7400 (void)
7402 return list_system_processes ();
7405 DEFUN ("process-attributes", Fprocess_attributes,
7406 Sprocess_attributes, 1, 1, 0,
7407 doc: /* Return attributes of the process given by its PID, a number.
7409 Value is an alist where each element is a cons cell of the form
7411 \(KEY . VALUE)
7413 If this functionality is unsupported, the value is nil.
7415 See `list-system-processes' for getting a list of all process IDs.
7417 The KEYs of the attributes that this function may return are listed
7418 below, together with the type of the associated VALUE (in parentheses).
7419 Not all platforms support all of these attributes; unsupported
7420 attributes will not appear in the returned alist.
7421 Unless explicitly indicated otherwise, numbers can have either
7422 integer or floating point values.
7424 euid -- Effective user User ID of the process (number)
7425 user -- User name corresponding to euid (string)
7426 egid -- Effective user Group ID of the process (number)
7427 group -- Group name corresponding to egid (string)
7428 comm -- Command name (executable name only) (string)
7429 state -- Process state code, such as "S", "R", or "T" (string)
7430 ppid -- Parent process ID (number)
7431 pgrp -- Process group ID (number)
7432 sess -- Session ID, i.e. process ID of session leader (number)
7433 ttname -- Controlling tty name (string)
7434 tpgid -- ID of foreground process group on the process's tty (number)
7435 minflt -- number of minor page faults (number)
7436 majflt -- number of major page faults (number)
7437 cminflt -- cumulative number of minor page faults (number)
7438 cmajflt -- cumulative number of major page faults (number)
7439 utime -- user time used by the process, in (current-time) format,
7440 which is a list of integers (HIGH LOW USEC PSEC)
7441 stime -- system time used by the process (current-time)
7442 time -- sum of utime and stime (current-time)
7443 cutime -- user time used by the process and its children (current-time)
7444 cstime -- system time used by the process and its children (current-time)
7445 ctime -- sum of cutime and cstime (current-time)
7446 pri -- priority of the process (number)
7447 nice -- nice value of the process (number)
7448 thcount -- process thread count (number)
7449 start -- time the process started (current-time)
7450 vsize -- virtual memory size of the process in KB's (number)
7451 rss -- resident set size of the process in KB's (number)
7452 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7453 pcpu -- percents of CPU time used by the process (floating-point number)
7454 pmem -- percents of total physical memory used by process's resident set
7455 (floating-point number)
7456 args -- command line which invoked the process (string). */)
7457 ( Lisp_Object pid)
7459 return system_process_attributes (pid);
7463 /* This is not called "init_process" because that is the name of a
7464 Mach system call, so it would cause problems on Darwin systems. */
7465 void
7466 init_process_emacs (void)
7468 #ifdef subprocesses
7469 register int i;
7471 inhibit_sentinels = 0;
7473 #ifdef SIGCHLD
7474 #ifndef CANNOT_DUMP
7475 if (! noninteractive || initialized)
7476 #endif
7477 signal (SIGCHLD, sigchld_handler);
7478 #endif
7480 max_process_desc = 0;
7481 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7483 #ifdef NON_BLOCKING_CONNECT
7484 num_pending_connects = 0;
7485 #endif
7487 #ifdef ADAPTIVE_READ_BUFFERING
7488 process_output_delay_count = 0;
7489 process_output_skip = 0;
7490 #endif
7492 /* Don't do this, it caused infinite select loops. The display
7493 method should call add_keyboard_wait_descriptor on stdin if it
7494 needs that. */
7495 #if 0
7496 FD_SET (0, &input_wait_mask);
7497 #endif
7499 Vprocess_alist = Qnil;
7500 #ifdef SIGCHLD
7501 deleted_pid_list = Qnil;
7502 #endif
7503 for (i = 0; i < MAXDESC; i++)
7505 chan_process[i] = Qnil;
7506 proc_buffered_char[i] = -1;
7508 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7509 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7510 #ifdef DATAGRAM_SOCKETS
7511 memset (datagram_address, 0, sizeof datagram_address);
7512 #endif
7515 Lisp_Object subfeatures = Qnil;
7516 const struct socket_options *sopt;
7518 #define ADD_SUBFEATURE(key, val) \
7519 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7521 #ifdef NON_BLOCKING_CONNECT
7522 ADD_SUBFEATURE (QCnowait, Qt);
7523 #endif
7524 #ifdef DATAGRAM_SOCKETS
7525 ADD_SUBFEATURE (QCtype, Qdatagram);
7526 #endif
7527 #ifdef HAVE_SEQPACKET
7528 ADD_SUBFEATURE (QCtype, Qseqpacket);
7529 #endif
7530 #ifdef HAVE_LOCAL_SOCKETS
7531 ADD_SUBFEATURE (QCfamily, Qlocal);
7532 #endif
7533 ADD_SUBFEATURE (QCfamily, Qipv4);
7534 #ifdef AF_INET6
7535 ADD_SUBFEATURE (QCfamily, Qipv6);
7536 #endif
7537 #ifdef HAVE_GETSOCKNAME
7538 ADD_SUBFEATURE (QCservice, Qt);
7539 #endif
7540 #if defined (O_NONBLOCK) || defined (O_NDELAY)
7541 ADD_SUBFEATURE (QCserver, Qt);
7542 #endif
7544 for (sopt = socket_options; sopt->name; sopt++)
7545 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7547 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7550 #if defined (DARWIN_OS)
7551 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7552 processes. As such, we only change the default value. */
7553 if (initialized)
7555 char const *release = (STRINGP (Voperating_system_release)
7556 ? SSDATA (Voperating_system_release)
7557 : 0);
7558 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7559 Vprocess_connection_type = Qnil;
7562 #endif
7563 #endif /* subprocesses */
7564 kbd_is_on_hold = 0;
7567 void
7568 syms_of_process (void)
7570 #ifdef subprocesses
7572 DEFSYM (Qprocessp, "processp");
7573 DEFSYM (Qrun, "run");
7574 DEFSYM (Qstop, "stop");
7575 DEFSYM (Qsignal, "signal");
7577 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7578 here again.
7580 Qexit = intern_c_string ("exit");
7581 staticpro (&Qexit); */
7583 DEFSYM (Qopen, "open");
7584 DEFSYM (Qclosed, "closed");
7585 DEFSYM (Qconnect, "connect");
7586 DEFSYM (Qfailed, "failed");
7587 DEFSYM (Qlisten, "listen");
7588 DEFSYM (Qlocal, "local");
7589 DEFSYM (Qipv4, "ipv4");
7590 #ifdef AF_INET6
7591 DEFSYM (Qipv6, "ipv6");
7592 #endif
7593 DEFSYM (Qdatagram, "datagram");
7594 DEFSYM (Qseqpacket, "seqpacket");
7596 DEFSYM (QCport, ":port");
7597 DEFSYM (QCspeed, ":speed");
7598 DEFSYM (QCprocess, ":process");
7600 DEFSYM (QCbytesize, ":bytesize");
7601 DEFSYM (QCstopbits, ":stopbits");
7602 DEFSYM (QCparity, ":parity");
7603 DEFSYM (Qodd, "odd");
7604 DEFSYM (Qeven, "even");
7605 DEFSYM (QCflowcontrol, ":flowcontrol");
7606 DEFSYM (Qhw, "hw");
7607 DEFSYM (Qsw, "sw");
7608 DEFSYM (QCsummary, ":summary");
7610 DEFSYM (Qreal, "real");
7611 DEFSYM (Qnetwork, "network");
7612 DEFSYM (Qserial, "serial");
7613 DEFSYM (QCbuffer, ":buffer");
7614 DEFSYM (QChost, ":host");
7615 DEFSYM (QCservice, ":service");
7616 DEFSYM (QClocal, ":local");
7617 DEFSYM (QCremote, ":remote");
7618 DEFSYM (QCcoding, ":coding");
7619 DEFSYM (QCserver, ":server");
7620 DEFSYM (QCnowait, ":nowait");
7621 DEFSYM (QCsentinel, ":sentinel");
7622 DEFSYM (QClog, ":log");
7623 DEFSYM (QCnoquery, ":noquery");
7624 DEFSYM (QCstop, ":stop");
7625 DEFSYM (QCoptions, ":options");
7626 DEFSYM (QCplist, ":plist");
7628 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7630 staticpro (&Vprocess_alist);
7631 #ifdef SIGCHLD
7632 staticpro (&deleted_pid_list);
7633 #endif
7635 #endif /* subprocesses */
7637 DEFSYM (QCname, ":name");
7638 DEFSYM (QCtype, ":type");
7640 DEFSYM (Qeuid, "euid");
7641 DEFSYM (Qegid, "egid");
7642 DEFSYM (Quser, "user");
7643 DEFSYM (Qgroup, "group");
7644 DEFSYM (Qcomm, "comm");
7645 DEFSYM (Qstate, "state");
7646 DEFSYM (Qppid, "ppid");
7647 DEFSYM (Qpgrp, "pgrp");
7648 DEFSYM (Qsess, "sess");
7649 DEFSYM (Qttname, "ttname");
7650 DEFSYM (Qtpgid, "tpgid");
7651 DEFSYM (Qminflt, "minflt");
7652 DEFSYM (Qmajflt, "majflt");
7653 DEFSYM (Qcminflt, "cminflt");
7654 DEFSYM (Qcmajflt, "cmajflt");
7655 DEFSYM (Qutime, "utime");
7656 DEFSYM (Qstime, "stime");
7657 DEFSYM (Qtime, "time");
7658 DEFSYM (Qcutime, "cutime");
7659 DEFSYM (Qcstime, "cstime");
7660 DEFSYM (Qctime, "ctime");
7661 DEFSYM (Qpri, "pri");
7662 DEFSYM (Qnice, "nice");
7663 DEFSYM (Qthcount, "thcount");
7664 DEFSYM (Qstart, "start");
7665 DEFSYM (Qvsize, "vsize");
7666 DEFSYM (Qrss, "rss");
7667 DEFSYM (Qetime, "etime");
7668 DEFSYM (Qpcpu, "pcpu");
7669 DEFSYM (Qpmem, "pmem");
7670 DEFSYM (Qargs, "args");
7672 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7673 doc: /* Non-nil means delete processes immediately when they exit.
7674 A value of nil means don't delete them until `list-processes' is run. */);
7676 delete_exited_processes = 1;
7678 #ifdef subprocesses
7679 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7680 doc: /* Control type of device used to communicate with subprocesses.
7681 Values are nil to use a pipe, or t or `pty' to use a pty.
7682 The value has no effect if the system has no ptys or if all ptys are busy:
7683 then a pipe is used in any case.
7684 The value takes effect when `start-process' is called. */);
7685 Vprocess_connection_type = Qt;
7687 #ifdef ADAPTIVE_READ_BUFFERING
7688 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7689 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7690 On some systems, when Emacs reads the output from a subprocess, the output data
7691 is read in very small blocks, potentially resulting in very poor performance.
7692 This behavior can be remedied to some extent by setting this variable to a
7693 non-nil value, as it will automatically delay reading from such processes, to
7694 allow them to produce more output before Emacs tries to read it.
7695 If the value is t, the delay is reset after each write to the process; any other
7696 non-nil value means that the delay is not reset on write.
7697 The variable takes effect when `start-process' is called. */);
7698 Vprocess_adaptive_read_buffering = Qt;
7699 #endif
7701 defsubr (&Sprocessp);
7702 defsubr (&Sget_process);
7703 defsubr (&Sdelete_process);
7704 defsubr (&Sprocess_status);
7705 defsubr (&Sprocess_exit_status);
7706 defsubr (&Sprocess_id);
7707 defsubr (&Sprocess_name);
7708 defsubr (&Sprocess_tty_name);
7709 defsubr (&Sprocess_command);
7710 defsubr (&Sset_process_buffer);
7711 defsubr (&Sprocess_buffer);
7712 defsubr (&Sprocess_mark);
7713 defsubr (&Sset_process_filter);
7714 defsubr (&Sprocess_filter);
7715 defsubr (&Sset_process_sentinel);
7716 defsubr (&Sprocess_sentinel);
7717 defsubr (&Sset_process_thread);
7718 defsubr (&Sprocess_thread);
7719 defsubr (&Sset_process_window_size);
7720 defsubr (&Sset_process_inherit_coding_system_flag);
7721 defsubr (&Sset_process_query_on_exit_flag);
7722 defsubr (&Sprocess_query_on_exit_flag);
7723 defsubr (&Sprocess_contact);
7724 defsubr (&Sprocess_plist);
7725 defsubr (&Sset_process_plist);
7726 defsubr (&Sprocess_list);
7727 defsubr (&Sstart_process);
7728 defsubr (&Sserial_process_configure);
7729 defsubr (&Smake_serial_process);
7730 defsubr (&Sset_network_process_option);
7731 defsubr (&Smake_network_process);
7732 defsubr (&Sformat_network_address);
7733 #if defined (HAVE_NET_IF_H)
7734 #ifdef SIOCGIFCONF
7735 defsubr (&Snetwork_interface_list);
7736 #endif
7737 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7738 defsubr (&Snetwork_interface_info);
7739 #endif
7740 #endif /* defined (HAVE_NET_IF_H) */
7741 #ifdef DATAGRAM_SOCKETS
7742 defsubr (&Sprocess_datagram_address);
7743 defsubr (&Sset_process_datagram_address);
7744 #endif
7745 defsubr (&Saccept_process_output);
7746 defsubr (&Sprocess_send_region);
7747 defsubr (&Sprocess_send_string);
7748 defsubr (&Sinterrupt_process);
7749 defsubr (&Skill_process);
7750 defsubr (&Squit_process);
7751 defsubr (&Sstop_process);
7752 defsubr (&Scontinue_process);
7753 defsubr (&Sprocess_running_child_p);
7754 defsubr (&Sprocess_send_eof);
7755 defsubr (&Ssignal_process);
7756 defsubr (&Swaiting_for_user_input_p);
7757 defsubr (&Sprocess_type);
7758 defsubr (&Sset_process_coding_system);
7759 defsubr (&Sprocess_coding_system);
7760 defsubr (&Sset_process_filter_multibyte);
7761 defsubr (&Sprocess_filter_multibyte_p);
7763 #endif /* subprocesses */
7765 defsubr (&Sget_buffer_process);
7766 defsubr (&Sprocess_inherit_coding_system_flag);
7767 defsubr (&Slist_system_processes);
7768 defsubr (&Sprocess_attributes);