* src/mem-limits.h: Remove duplicated includes.
[emacs.git] / src / process.c
blob6597da4b22bf179f4e71921eeeda70a163075617
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 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>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34 #ifdef STDC_HEADERS
35 #include <stdlib.h>
36 #endif
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #include <fcntl.h>
43 /* Only MS-DOS does not define `subprocesses'. */
44 #ifdef subprocesses
46 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
47 #include <sys/socket.h>
48 #include <netdb.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
52 /* Are local (unix) sockets supported? */
53 #if defined (HAVE_SYS_UN_H)
54 #if !defined (AF_LOCAL) && defined (AF_UNIX)
55 #define AF_LOCAL AF_UNIX
56 #endif
57 #ifdef AF_LOCAL
58 #define HAVE_LOCAL_SOCKETS
59 #include <sys/un.h>
60 #endif
61 #endif
62 #endif /* HAVE_SOCKETS */
64 #if defined(HAVE_SYS_IOCTL_H)
65 #include <sys/ioctl.h>
66 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
67 #include <fcntl.h>
68 #endif /* HAVE_PTYS and no O_NDELAY */
69 #endif /* HAVE_SYS_IOCTL_H */
71 #ifdef NEED_BSDTTY
72 #include <bsdtty.h>
73 #endif
75 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
76 #ifdef HAVE_SOCKETS
77 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
78 /* sys/ioctl.h may have been included already */
79 #ifndef SIOCGIFADDR
80 #include <sys/ioctl.h>
81 #endif
82 #include <net/if.h>
83 #endif
84 #endif
86 #ifdef HAVE_SYS_WAIT
87 #include <sys/wait.h>
88 #endif
90 #ifdef HAVE_RES_INIT
91 #include <netinet/in.h>
92 #include <arpa/nameser.h>
93 #include <resolv.h>
94 #endif
96 #endif /* subprocesses */
98 #include "lisp.h"
99 #include "systime.h"
100 #include "systty.h"
102 #include "window.h"
103 #include "buffer.h"
104 #include "character.h"
105 #include "coding.h"
106 #include "process.h"
107 #include "frame.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
120 #if defined (USE_GTK) || defined (HAVE_GCONF)
121 #include "xgselect.h"
122 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
124 extern int timers_run;
126 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
127 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
128 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
129 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
130 Lisp_Object QCname, QCtype;
132 /* Non-zero if keyboard input is on hold, zero otherwise. */
134 static int kbd_is_on_hold;
136 /* Nonzero means delete a process right away if it exits. */
137 static int delete_exited_processes;
139 /* Nonzero means don't run process sentinels. This is used
140 when exiting. */
141 int inhibit_sentinels;
143 #ifdef subprocesses
145 Lisp_Object Qprocessp;
146 Lisp_Object Qrun, Qstop, Qsignal;
147 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
148 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
149 Lisp_Object Qreal, Qnetwork, Qserial;
150 #ifdef AF_INET6
151 Lisp_Object Qipv6;
152 #endif
153 Lisp_Object QCport, QCspeed, QCprocess;
154 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
155 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
156 Lisp_Object QCbuffer, QChost, QCservice;
157 Lisp_Object QClocal, QCremote, QCcoding;
158 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
159 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
160 Lisp_Object Qlast_nonmenu_event;
161 /* QCfamily is declared and initialized in xfaces.c,
162 QCfilter in keyboard.c. */
163 extern Lisp_Object QCfamily, QCfilter;
165 /* Qexit is declared and initialized in eval.c. */
167 /* QCfamily is defined in xfaces.c. */
168 extern Lisp_Object QCfamily;
169 /* QCfilter is defined in keyboard.c. */
170 extern Lisp_Object QCfilter;
172 #ifdef HAVE_SOCKETS
173 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
174 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
175 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
176 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
177 #else
178 #define NETCONN_P(p) 0
179 #define NETCONN1_P(p) 0
180 #define SERIALCONN_P(p) 0
181 #define SERIALCONN1_P(p) 0
182 #endif /* HAVE_SOCKETS */
184 /* Define first descriptor number available for subprocesses. */
185 #define FIRST_PROC_DESC 3
187 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
188 testing SIGCHLD. */
190 #if !defined (SIGCHLD) && defined (SIGCLD)
191 #define SIGCHLD SIGCLD
192 #endif /* SIGCLD */
194 extern char *get_operating_system_release (void);
196 /* Serial processes require termios or Windows. */
197 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
198 #define HAVE_SERIAL
199 #endif
201 #ifdef HAVE_SERIAL
202 /* From sysdep.c or w32.c */
203 extern int serial_open (char *port);
204 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
205 #endif
207 #ifndef HAVE_H_ERRNO
208 extern int h_errno;
209 #endif
211 /* t means use pty, nil means use a pipe,
212 maybe other values to come. */
213 static Lisp_Object Vprocess_connection_type;
215 /* These next two vars are non-static since sysdep.c uses them in the
216 emulation of `select'. */
217 /* Number of events of change of status of a process. */
218 int process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 int update_tick;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 #ifdef BROKEN_NON_BLOCKING_CONNECT
225 #undef NON_BLOCKING_CONNECT
226 #else
227 #ifndef NON_BLOCKING_CONNECT
228 #ifdef HAVE_SOCKETS
229 #ifdef HAVE_SELECT
230 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
231 #if defined (O_NONBLOCK) || defined (O_NDELAY)
232 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
233 #define NON_BLOCKING_CONNECT
234 #endif /* EWOULDBLOCK || EINPROGRESS */
235 #endif /* O_NONBLOCK || O_NDELAY */
236 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
237 #endif /* HAVE_SELECT */
238 #endif /* HAVE_SOCKETS */
239 #endif /* NON_BLOCKING_CONNECT */
240 #endif /* BROKEN_NON_BLOCKING_CONNECT */
242 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
243 this system. We need to read full packets, so we need a
244 "non-destructive" select. So we require either native select,
245 or emulation of select using FIONREAD. */
247 #ifdef BROKEN_DATAGRAM_SOCKETS
248 #undef DATAGRAM_SOCKETS
249 #else
250 #ifndef DATAGRAM_SOCKETS
251 #ifdef HAVE_SOCKETS
252 #if defined (HAVE_SELECT) || defined (FIONREAD)
253 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
254 #define DATAGRAM_SOCKETS
255 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
256 #endif /* HAVE_SELECT || FIONREAD */
257 #endif /* HAVE_SOCKETS */
258 #endif /* DATAGRAM_SOCKETS */
259 #endif /* BROKEN_DATAGRAM_SOCKETS */
261 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
262 # define HAVE_SEQPACKET
263 #endif
265 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
266 #ifdef EMACS_HAS_USECS
267 #define ADAPTIVE_READ_BUFFERING
268 #endif
269 #endif
271 #ifdef ADAPTIVE_READ_BUFFERING
272 #define READ_OUTPUT_DELAY_INCREMENT 10000
273 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
274 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
276 /* Number of processes which have a non-zero read_output_delay,
277 and therefore might be delayed for adaptive read buffering. */
279 static int process_output_delay_count;
281 /* Non-zero if any process has non-nil read_output_skip. */
283 static int process_output_skip;
285 /* Non-nil means to delay reading process output to improve buffering.
286 A value of t means that delay is reset after each send, any other
287 non-nil value does not reset the delay. A value of nil disables
288 adaptive read buffering completely. */
289 static Lisp_Object Vprocess_adaptive_read_buffering;
290 #else
291 #define process_output_delay_count 0
292 #endif
294 static int keyboard_bit_set (SELECT_TYPE *);
295 static void deactivate_process (Lisp_Object);
296 static void status_notify (struct Lisp_Process *);
297 static int read_process_output (Lisp_Object, int);
298 static void create_pty (Lisp_Object);
300 /* If we support a window system, turn on the code to poll periodically
301 to detect C-g. It isn't actually used when doing interrupt input. */
302 #ifdef HAVE_WINDOW_SYSTEM
303 #define POLL_FOR_INPUT
304 #endif
306 static Lisp_Object get_process (register Lisp_Object name);
307 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
309 /* Mask of bits indicating the descriptors that we wait for input on. */
311 static SELECT_TYPE input_wait_mask;
313 /* Mask that excludes keyboard input descriptor(s). */
315 static SELECT_TYPE non_keyboard_wait_mask;
317 /* Mask that excludes process input descriptor(s). */
319 static SELECT_TYPE non_process_wait_mask;
321 /* Mask for the gpm mouse input descriptor. */
323 static SELECT_TYPE gpm_wait_mask;
325 #ifdef NON_BLOCKING_CONNECT
326 /* Mask of bits indicating the descriptors that we wait for connect to
327 complete on. Once they complete, they are removed from this mask
328 and added to the input_wait_mask and non_keyboard_wait_mask. */
330 static SELECT_TYPE connect_wait_mask;
332 /* Number of bits set in connect_wait_mask. */
333 static int num_pending_connects;
335 #define IF_NON_BLOCKING_CONNECT(s) s
336 #else /* NON_BLOCKING_CONNECT */
337 #define IF_NON_BLOCKING_CONNECT(s)
338 #endif /* NON_BLOCKING_CONNECT */
340 /* The largest descriptor currently in use for a process object. */
341 static int max_process_desc;
343 /* The largest descriptor currently in use for keyboard input. */
344 static int max_keyboard_desc;
346 /* The largest descriptor currently in use for gpm mouse input. */
347 static int max_gpm_desc;
349 /* Indexed by descriptor, gives the process (if any) for that descriptor */
350 Lisp_Object chan_process[MAXDESC];
352 /* Alist of elements (NAME . PROCESS) */
353 Lisp_Object Vprocess_alist;
355 /* Buffered-ahead input char from process, indexed by channel.
356 -1 means empty (no char is buffered).
357 Used on sys V where the only way to tell if there is any
358 output from the process is to read at least one char.
359 Always -1 on systems that support FIONREAD. */
361 /* Don't make static; need to access externally. */
362 int proc_buffered_char[MAXDESC];
364 /* Table of `struct coding-system' for each process. */
365 static struct coding_system *proc_decode_coding_system[MAXDESC];
366 static struct coding_system *proc_encode_coding_system[MAXDESC];
368 #ifdef DATAGRAM_SOCKETS
369 /* Table of `partner address' for datagram sockets. */
370 struct sockaddr_and_len {
371 struct sockaddr *sa;
372 int len;
373 } datagram_address[MAXDESC];
374 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
375 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
376 #else
377 #define DATAGRAM_CHAN_P(chan) (0)
378 #define DATAGRAM_CONN_P(proc) (0)
379 #endif
381 /* Maximum number of bytes to send to a pty without an eof. */
382 static int pty_max_bytes;
384 #ifdef HAVE_PTYS
385 #ifdef HAVE_PTY_H
386 #include <pty.h>
387 #endif
388 /* The file name of the pty opened by allocate_pty. */
390 static char pty_name[24];
391 #endif
393 /* Compute the Lisp form of the process status, p->status, from
394 the numeric status that was returned by `wait'. */
396 static Lisp_Object status_convert (int);
398 static void
399 update_status (struct Lisp_Process *p)
401 eassert (p->raw_status_new);
402 p->status = status_convert (p->raw_status);
403 p->raw_status_new = 0;
406 /* Convert a process status word in Unix format to
407 the list that we use internally. */
409 static Lisp_Object
410 status_convert (int w)
412 if (WIFSTOPPED (w))
413 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
414 else if (WIFEXITED (w))
415 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
416 WCOREDUMP (w) ? Qt : Qnil));
417 else if (WIFSIGNALED (w))
418 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
419 WCOREDUMP (w) ? Qt : Qnil));
420 else
421 return Qrun;
424 /* Given a status-list, extract the three pieces of information
425 and store them individually through the three pointers. */
427 static void
428 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
430 Lisp_Object tem;
432 if (SYMBOLP (l))
434 *symbol = l;
435 *code = 0;
436 *coredump = 0;
438 else
440 *symbol = XCAR (l);
441 tem = XCDR (l);
442 *code = XFASTINT (XCAR (tem));
443 tem = XCDR (tem);
444 *coredump = !NILP (tem);
448 /* Return a string describing a process status list. */
450 static Lisp_Object
451 status_message (struct Lisp_Process *p)
453 Lisp_Object status = p->status;
454 Lisp_Object symbol;
455 int code, coredump;
456 Lisp_Object string, string2;
458 decode_status (status, &symbol, &code, &coredump);
460 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
462 char *signame;
463 synchronize_system_messages_locale ();
464 signame = strsignal (code);
465 if (signame == 0)
466 string = build_string ("unknown");
467 else
469 int c1, c2;
471 string = make_unibyte_string (signame, strlen (signame));
472 if (! NILP (Vlocale_coding_system))
473 string = (code_convert_string_norecord
474 (string, Vlocale_coding_system, 0));
475 c1 = STRING_CHAR ((char *) SDATA (string));
476 c2 = DOWNCASE (c1);
477 if (c1 != c2)
478 Faset (string, make_number (0), make_number (c2));
480 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
481 return concat2 (string, string2);
483 else if (EQ (symbol, Qexit))
485 if (NETCONN1_P (p))
486 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
487 if (code == 0)
488 return build_string ("finished\n");
489 string = Fnumber_to_string (make_number (code));
490 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
491 return concat3 (build_string ("exited abnormally with code "),
492 string, string2);
494 else if (EQ (symbol, Qfailed))
496 string = Fnumber_to_string (make_number (code));
497 string2 = build_string ("\n");
498 return concat3 (build_string ("failed with code "),
499 string, string2);
501 else
502 return Fcopy_sequence (Fsymbol_name (symbol));
505 #ifdef HAVE_PTYS
507 /* Open an available pty, returning a file descriptor.
508 Return -1 on failure.
509 The file name of the terminal corresponding to the pty
510 is left in the variable pty_name. */
512 static int
513 allocate_pty (void)
515 register int c, i;
516 int fd;
518 #ifdef PTY_ITERATION
519 PTY_ITERATION
520 #else
521 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
522 for (i = 0; i < 16; i++)
523 #endif
525 struct stat stb; /* Used in some PTY_OPEN. */
526 #ifdef PTY_NAME_SPRINTF
527 PTY_NAME_SPRINTF
528 #else
529 sprintf (pty_name, "/dev/pty%c%x", c, i);
530 #endif /* no PTY_NAME_SPRINTF */
532 #ifdef PTY_OPEN
533 PTY_OPEN;
534 #else /* no PTY_OPEN */
536 { /* Some systems name their pseudoterminals so that there are gaps in
537 the usual sequence - for example, on HP9000/S700 systems, there
538 are no pseudoterminals with names ending in 'f'. So we wait for
539 three failures in a row before deciding that we've reached the
540 end of the ptys. */
541 int failed_count = 0;
543 if (stat (pty_name, &stb) < 0)
545 failed_count++;
546 if (failed_count >= 3)
547 return -1;
549 else
550 failed_count = 0;
552 # ifdef O_NONBLOCK
553 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
554 # else
555 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
556 # endif
558 #endif /* no PTY_OPEN */
560 if (fd >= 0)
562 /* check to make certain that both sides are available
563 this avoids a nasty yet stupid bug in rlogins */
564 #ifdef PTY_TTY_NAME_SPRINTF
565 PTY_TTY_NAME_SPRINTF
566 #else
567 sprintf (pty_name, "/dev/tty%c%x", c, i);
568 #endif /* no PTY_TTY_NAME_SPRINTF */
569 if (access (pty_name, 6) != 0)
571 emacs_close (fd);
572 # ifndef __sgi
573 continue;
574 # else
575 return -1;
576 # endif /* __sgi */
578 setup_pty (fd);
579 return fd;
582 return -1;
584 #endif /* HAVE_PTYS */
586 static Lisp_Object
587 make_process (Lisp_Object name)
589 register Lisp_Object val, tem, name1;
590 register struct Lisp_Process *p;
591 char suffix[10];
592 register int i;
594 p = allocate_process ();
596 p->infd = -1;
597 p->outfd = -1;
598 p->tick = 0;
599 p->update_tick = 0;
600 p->pid = 0;
601 p->pty_flag = 0;
602 p->raw_status_new = 0;
603 p->status = Qrun;
604 p->mark = Fmake_marker ();
605 p->kill_without_query = 0;
607 #ifdef ADAPTIVE_READ_BUFFERING
608 p->adaptive_read_buffering = 0;
609 p->read_output_delay = 0;
610 p->read_output_skip = 0;
611 #endif
613 /* If name is already in use, modify it until it is unused. */
615 name1 = name;
616 for (i = 1; ; i++)
618 tem = Fget_process (name1);
619 if (NILP (tem)) break;
620 sprintf (suffix, "<%d>", i);
621 name1 = concat2 (name, build_string (suffix));
623 name = name1;
624 p->name = name;
625 XSETPROCESS (val, p);
626 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
627 return val;
630 static void
631 remove_process (register Lisp_Object proc)
633 register Lisp_Object pair;
635 pair = Frassq (proc, Vprocess_alist);
636 Vprocess_alist = Fdelq (pair, Vprocess_alist);
638 deactivate_process (proc);
642 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
643 doc: /* Return t if OBJECT is a process. */)
644 (Lisp_Object object)
646 return PROCESSP (object) ? Qt : Qnil;
649 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
650 doc: /* Return the process named NAME, or nil if there is none. */)
651 (register Lisp_Object name)
653 if (PROCESSP (name))
654 return name;
655 CHECK_STRING (name);
656 return Fcdr (Fassoc (name, Vprocess_alist));
659 /* This is how commands for the user decode process arguments. It
660 accepts a process, a process name, a buffer, a buffer name, or nil.
661 Buffers denote the first process in the buffer, and nil denotes the
662 current buffer. */
664 static Lisp_Object
665 get_process (register Lisp_Object name)
667 register Lisp_Object proc, obj;
668 if (STRINGP (name))
670 obj = Fget_process (name);
671 if (NILP (obj))
672 obj = Fget_buffer (name);
673 if (NILP (obj))
674 error ("Process %s does not exist", SDATA (name));
676 else if (NILP (name))
677 obj = Fcurrent_buffer ();
678 else
679 obj = name;
681 /* Now obj should be either a buffer object or a process object.
683 if (BUFFERP (obj))
685 proc = Fget_buffer_process (obj);
686 if (NILP (proc))
687 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
689 else
691 CHECK_PROCESS (obj);
692 proc = obj;
694 return proc;
698 #ifdef SIGCHLD
699 /* Fdelete_process promises to immediately forget about the process, but in
700 reality, Emacs needs to remember those processes until they have been
701 treated by sigchld_handler; otherwise this handler would consider the
702 process as being synchronous and say that the synchronous process is
703 dead. */
704 static Lisp_Object deleted_pid_list;
705 #endif
707 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
708 doc: /* Delete PROCESS: kill it and forget about it immediately.
709 PROCESS may be a process, a buffer, the name of a process or buffer, or
710 nil, indicating the current buffer's process. */)
711 (register Lisp_Object process)
713 register struct Lisp_Process *p;
715 process = get_process (process);
716 p = XPROCESS (process);
718 p->raw_status_new = 0;
719 if (NETCONN1_P (p) || SERIALCONN1_P (p))
721 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
722 p->tick = ++process_tick;
723 status_notify (p);
724 redisplay_preserve_echo_area (13);
726 else if (p->infd >= 0)
728 #ifdef SIGCHLD
729 Lisp_Object symbol;
730 /* Assignment to EMACS_INT stops GCC whining about limited range
731 of data type. */
732 EMACS_INT pid = p->pid;
734 /* No problem storing the pid here, as it is still in Vprocess_alist. */
735 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
736 /* GC treated elements set to nil. */
737 Fdelq (Qnil, deleted_pid_list));
738 /* If the process has already signaled, remove it from the list. */
739 if (p->raw_status_new)
740 update_status (p);
741 symbol = p->status;
742 if (CONSP (p->status))
743 symbol = XCAR (p->status);
744 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
745 deleted_pid_list
746 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
747 else
748 #endif
750 Fkill_process (process, Qnil);
751 /* Do this now, since remove_process will make sigchld_handler do nothing. */
752 p->status
753 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
754 p->tick = ++process_tick;
755 status_notify (p);
756 redisplay_preserve_echo_area (13);
759 remove_process (process);
760 return Qnil;
763 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
764 doc: /* Return the status of PROCESS.
765 The returned value is one of the following symbols:
766 run -- for a process that is running.
767 stop -- for a process stopped but continuable.
768 exit -- for a process that has exited.
769 signal -- for a process that has got a fatal signal.
770 open -- for a network stream connection that is open.
771 listen -- for a network stream server that is listening.
772 closed -- for a network stream connection that is closed.
773 connect -- when waiting for a non-blocking connection to complete.
774 failed -- when a non-blocking connection has failed.
775 nil -- if arg is a process name and no such process exists.
776 PROCESS may be a process, a buffer, the name of a process, or
777 nil, indicating the current buffer's process. */)
778 (register Lisp_Object process)
780 register struct Lisp_Process *p;
781 register Lisp_Object status;
783 if (STRINGP (process))
784 process = Fget_process (process);
785 else
786 process = get_process (process);
788 if (NILP (process))
789 return process;
791 p = XPROCESS (process);
792 if (p->raw_status_new)
793 update_status (p);
794 status = p->status;
795 if (CONSP (status))
796 status = XCAR (status);
797 if (NETCONN1_P (p) || SERIALCONN1_P (p))
799 if (EQ (status, Qexit))
800 status = Qclosed;
801 else if (EQ (p->command, Qt))
802 status = Qstop;
803 else if (EQ (status, Qrun))
804 status = Qopen;
806 return status;
809 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
810 1, 1, 0,
811 doc: /* Return the exit status of PROCESS or the signal number that killed it.
812 If PROCESS has not yet exited or died, return 0. */)
813 (register Lisp_Object process)
815 CHECK_PROCESS (process);
816 if (XPROCESS (process)->raw_status_new)
817 update_status (XPROCESS (process));
818 if (CONSP (XPROCESS (process)->status))
819 return XCAR (XCDR (XPROCESS (process)->status));
820 return make_number (0);
823 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
824 doc: /* Return the process id of PROCESS.
825 This is the pid of the external process which PROCESS uses or talks to.
826 For a network connection, this value is nil. */)
827 (register Lisp_Object process)
829 /* Assignment to EMACS_INT stops GCC whining about limited range of
830 data type. */
831 EMACS_INT pid;
833 CHECK_PROCESS (process);
834 pid = XPROCESS (process)->pid;
835 return (pid ? make_fixnum_or_float (pid) : Qnil);
838 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
839 doc: /* Return the name of PROCESS, as a string.
840 This is the name of the program invoked in PROCESS,
841 possibly modified to make it unique among process names. */)
842 (register Lisp_Object process)
844 CHECK_PROCESS (process);
845 return XPROCESS (process)->name;
848 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
849 doc: /* Return the command that was executed to start PROCESS.
850 This is a list of strings, the first string being the program executed
851 and the rest of the strings being the arguments given to it.
852 For a network or serial process, this is nil (process is running) or t
853 \(process is stopped). */)
854 (register Lisp_Object process)
856 CHECK_PROCESS (process);
857 return XPROCESS (process)->command;
860 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
861 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
862 This is the terminal that the process itself reads and writes on,
863 not the name of the pty that Emacs uses to talk with that terminal. */)
864 (register Lisp_Object process)
866 CHECK_PROCESS (process);
867 return XPROCESS (process)->tty_name;
870 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
871 2, 2, 0,
872 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
873 (register Lisp_Object process, Lisp_Object buffer)
875 struct Lisp_Process *p;
877 CHECK_PROCESS (process);
878 if (!NILP (buffer))
879 CHECK_BUFFER (buffer);
880 p = XPROCESS (process);
881 p->buffer = buffer;
882 if (NETCONN1_P (p) || SERIALCONN1_P (p))
883 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
884 setup_process_coding_systems (process);
885 return buffer;
888 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
889 1, 1, 0,
890 doc: /* Return the buffer PROCESS is associated with.
891 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
892 (register Lisp_Object process)
894 CHECK_PROCESS (process);
895 return XPROCESS (process)->buffer;
898 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
899 1, 1, 0,
900 doc: /* Return the marker for the end of the last output from PROCESS. */)
901 (register Lisp_Object process)
903 CHECK_PROCESS (process);
904 return XPROCESS (process)->mark;
907 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
908 2, 2, 0,
909 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
910 A value of t means stop accepting output from the process.
912 When a process has a filter, its buffer is not used for output.
913 Instead, each time it does output, the entire string of output is
914 passed to the filter.
916 The filter gets two arguments: the process and the string of output.
917 The string argument is normally a multibyte string, except:
918 - if the process' input coding system is no-conversion or raw-text,
919 it is a unibyte string (the non-converted input), or else
920 - if `default-enable-multibyte-characters' is nil, it is a unibyte
921 string (the result of converting the decoded input multibyte
922 string to unibyte with `string-make-unibyte'). */)
923 (register Lisp_Object process, Lisp_Object filter)
925 struct Lisp_Process *p;
927 CHECK_PROCESS (process);
928 p = XPROCESS (process);
930 /* Don't signal an error if the process' input file descriptor
931 is closed. This could make debugging Lisp more difficult,
932 for example when doing something like
934 (setq process (start-process ...))
935 (debug)
936 (set-process-filter process ...) */
938 if (p->infd >= 0)
940 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
942 FD_CLR (p->infd, &input_wait_mask);
943 FD_CLR (p->infd, &non_keyboard_wait_mask);
945 else if (EQ (p->filter, Qt)
946 /* Network or serial process not stopped: */
947 && !EQ (p->command, Qt))
949 FD_SET (p->infd, &input_wait_mask);
950 FD_SET (p->infd, &non_keyboard_wait_mask);
954 p->filter = filter;
955 if (NETCONN1_P (p) || SERIALCONN1_P (p))
956 p->childp = Fplist_put (p->childp, QCfilter, filter);
957 setup_process_coding_systems (process);
958 return filter;
961 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
962 1, 1, 0,
963 doc: /* Returns the filter function of PROCESS; nil if none.
964 See `set-process-filter' for more info on filter functions. */)
965 (register Lisp_Object process)
967 CHECK_PROCESS (process);
968 return XPROCESS (process)->filter;
971 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
972 2, 2, 0,
973 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
974 The sentinel is called as a function when the process changes state.
975 It gets two arguments: the process, and a string describing the change. */)
976 (register Lisp_Object process, Lisp_Object sentinel)
978 struct Lisp_Process *p;
980 CHECK_PROCESS (process);
981 p = XPROCESS (process);
983 p->sentinel = sentinel;
984 if (NETCONN1_P (p) || SERIALCONN1_P (p))
985 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
986 return sentinel;
989 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
990 1, 1, 0,
991 doc: /* Return the sentinel of PROCESS; nil if none.
992 See `set-process-sentinel' for more info on sentinels. */)
993 (register Lisp_Object process)
995 CHECK_PROCESS (process);
996 return XPROCESS (process)->sentinel;
999 DEFUN ("set-process-window-size", Fset_process_window_size,
1000 Sset_process_window_size, 3, 3, 0,
1001 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1002 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1004 CHECK_PROCESS (process);
1005 CHECK_NATNUM (height);
1006 CHECK_NATNUM (width);
1008 if (XPROCESS (process)->infd < 0
1009 || set_window_size (XPROCESS (process)->infd,
1010 XINT (height), XINT (width)) <= 0)
1011 return Qnil;
1012 else
1013 return Qt;
1016 DEFUN ("set-process-inherit-coding-system-flag",
1017 Fset_process_inherit_coding_system_flag,
1018 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1019 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1020 If the second argument FLAG is non-nil, then the variable
1021 `buffer-file-coding-system' of the buffer associated with PROCESS
1022 will be bound to the value of the coding system used to decode
1023 the process output.
1025 This is useful when the coding system specified for the process buffer
1026 leaves either the character code conversion or the end-of-line conversion
1027 unspecified, or if the coding system used to decode the process output
1028 is more appropriate for saving the process buffer.
1030 Binding the variable `inherit-process-coding-system' to non-nil before
1031 starting the process is an alternative way of setting the inherit flag
1032 for the process which will run. */)
1033 (register Lisp_Object process, Lisp_Object flag)
1035 CHECK_PROCESS (process);
1036 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1037 return flag;
1040 DEFUN ("set-process-query-on-exit-flag",
1041 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1042 2, 2, 0,
1043 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1044 If the second argument FLAG is non-nil, Emacs will query the user before
1045 exiting or killing a buffer if PROCESS is running. */)
1046 (register Lisp_Object process, Lisp_Object flag)
1048 CHECK_PROCESS (process);
1049 XPROCESS (process)->kill_without_query = NILP (flag);
1050 return flag;
1053 DEFUN ("process-query-on-exit-flag",
1054 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1055 1, 1, 0,
1056 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1057 (register Lisp_Object process)
1059 CHECK_PROCESS (process);
1060 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1063 #ifdef DATAGRAM_SOCKETS
1064 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1065 #endif
1067 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1068 1, 2, 0,
1069 doc: /* Return the contact info of PROCESS; t for a real child.
1070 For a network or serial connection, the value depends on the optional
1071 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1072 SERVICE) for a network connection or (PORT SPEED) for a serial
1073 connection. If KEY is t, the complete contact information for the
1074 connection is returned, else the specific value for the keyword KEY is
1075 returned. See `make-network-process' or `make-serial-process' for a
1076 list of keywords. */)
1077 (register Lisp_Object process, Lisp_Object key)
1079 Lisp_Object contact;
1081 CHECK_PROCESS (process);
1082 contact = XPROCESS (process)->childp;
1084 #ifdef DATAGRAM_SOCKETS
1085 if (DATAGRAM_CONN_P (process)
1086 && (EQ (key, Qt) || EQ (key, QCremote)))
1087 contact = Fplist_put (contact, QCremote,
1088 Fprocess_datagram_address (process));
1089 #endif
1091 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1092 return contact;
1093 if (NILP (key) && NETCONN_P (process))
1094 return Fcons (Fplist_get (contact, QChost),
1095 Fcons (Fplist_get (contact, QCservice), Qnil));
1096 if (NILP (key) && SERIALCONN_P (process))
1097 return Fcons (Fplist_get (contact, QCport),
1098 Fcons (Fplist_get (contact, QCspeed), Qnil));
1099 return Fplist_get (contact, key);
1102 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1103 1, 1, 0,
1104 doc: /* Return the plist of PROCESS. */)
1105 (register Lisp_Object process)
1107 CHECK_PROCESS (process);
1108 return XPROCESS (process)->plist;
1111 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1112 2, 2, 0,
1113 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1114 (register Lisp_Object process, Lisp_Object plist)
1116 CHECK_PROCESS (process);
1117 CHECK_LIST (plist);
1119 XPROCESS (process)->plist = plist;
1120 return plist;
1123 #if 0 /* Turned off because we don't currently record this info
1124 in the process. Perhaps add it. */
1125 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1126 doc: /* Return the connection type of PROCESS.
1127 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1128 a socket connection. */)
1129 (Lisp_Object process)
1131 return XPROCESS (process)->type;
1133 #endif
1135 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1136 doc: /* Return the connection type of PROCESS.
1137 The value is either the symbol `real', `network', or `serial'.
1138 PROCESS may be a process, a buffer, the name of a process or buffer, or
1139 nil, indicating the current buffer's process. */)
1140 (Lisp_Object process)
1142 Lisp_Object proc;
1143 proc = get_process (process);
1144 return XPROCESS (proc)->type;
1147 #ifdef HAVE_SOCKETS
1148 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1149 1, 2, 0,
1150 doc: /* Convert network ADDRESS from internal format to a string.
1151 A 4 or 5 element vector represents an IPv4 address (with port number).
1152 An 8 or 9 element vector represents an IPv6 address (with port number).
1153 If optional second argument OMIT-PORT is non-nil, don't include a port
1154 number in the string, even when present in ADDRESS.
1155 Returns nil if format of ADDRESS is invalid. */)
1156 (Lisp_Object address, Lisp_Object omit_port)
1158 if (NILP (address))
1159 return Qnil;
1161 if (STRINGP (address)) /* AF_LOCAL */
1162 return address;
1164 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1166 register struct Lisp_Vector *p = XVECTOR (address);
1167 Lisp_Object args[10];
1168 int nargs, i;
1170 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1172 args[0] = build_string ("%d.%d.%d.%d");
1173 nargs = 4;
1175 else if (p->size == 5)
1177 args[0] = build_string ("%d.%d.%d.%d:%d");
1178 nargs = 5;
1180 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1182 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1183 nargs = 8;
1185 else if (p->size == 9)
1187 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1188 nargs = 9;
1190 else
1191 return Qnil;
1193 for (i = 0; i < nargs; i++)
1195 EMACS_INT element = XINT (p->contents[i]);
1197 if (element < 0 || element > 65535)
1198 return Qnil;
1200 if (nargs <= 5 /* IPv4 */
1201 && i < 4 /* host, not port */
1202 && element > 255)
1203 return Qnil;
1205 args[i+1] = p->contents[i];
1208 return Fformat (nargs+1, args);
1211 if (CONSP (address))
1213 Lisp_Object args[2];
1214 args[0] = build_string ("<Family %d>");
1215 args[1] = Fcar (address);
1216 return Fformat (2, args);
1219 return Qnil;
1221 #endif
1223 static Lisp_Object
1224 list_processes_1 (Lisp_Object query_only)
1226 register Lisp_Object tail, tem;
1227 Lisp_Object proc, minspace, tem1;
1228 register struct Lisp_Process *p;
1229 char tembuf[300];
1230 int w_proc, w_buffer, w_tty;
1231 int exited = 0;
1232 Lisp_Object i_status, i_buffer, i_tty, i_command;
1234 w_proc = 4; /* Proc */
1235 w_buffer = 6; /* Buffer */
1236 w_tty = 0; /* Omit if no ttys */
1238 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1240 int i;
1242 proc = Fcdr (XCAR (tail));
1243 p = XPROCESS (proc);
1244 if (NILP (p->type))
1245 continue;
1246 if (!NILP (query_only) && p->kill_without_query)
1247 continue;
1248 if (STRINGP (p->name)
1249 && ( i = SCHARS (p->name), (i > w_proc)))
1250 w_proc = i;
1251 if (!NILP (p->buffer))
1253 if (NILP (XBUFFER (p->buffer)->name))
1255 if (w_buffer < 8)
1256 w_buffer = 8; /* (Killed) */
1258 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1259 w_buffer = i;
1261 if (STRINGP (p->tty_name)
1262 && (i = SCHARS (p->tty_name), (i > w_tty)))
1263 w_tty = i;
1266 XSETFASTINT (i_status, w_proc + 1);
1267 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1268 if (w_tty)
1270 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1271 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1273 else
1275 i_tty = Qnil;
1276 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1279 XSETFASTINT (minspace, 1);
1281 set_buffer_internal (XBUFFER (Vstandard_output));
1282 current_buffer->undo_list = Qt;
1284 current_buffer->truncate_lines = Qt;
1286 write_string ("Proc", -1);
1287 Findent_to (i_status, minspace); write_string ("Status", -1);
1288 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1289 if (!NILP (i_tty))
1291 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1293 Findent_to (i_command, minspace); write_string ("Command", -1);
1294 write_string ("\n", -1);
1296 write_string ("----", -1);
1297 Findent_to (i_status, minspace); write_string ("------", -1);
1298 Findent_to (i_buffer, minspace); write_string ("------", -1);
1299 if (!NILP (i_tty))
1301 Findent_to (i_tty, minspace); write_string ("---", -1);
1303 Findent_to (i_command, minspace); write_string ("-------", -1);
1304 write_string ("\n", -1);
1306 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1308 Lisp_Object symbol;
1310 proc = Fcdr (XCAR (tail));
1311 p = XPROCESS (proc);
1312 if (NILP (p->type))
1313 continue;
1314 if (!NILP (query_only) && p->kill_without_query)
1315 continue;
1317 Finsert (1, &p->name);
1318 Findent_to (i_status, minspace);
1320 if (p->raw_status_new)
1321 update_status (p);
1322 symbol = p->status;
1323 if (CONSP (p->status))
1324 symbol = XCAR (p->status);
1326 if (EQ (symbol, Qsignal))
1328 Lisp_Object tem;
1329 tem = Fcar (Fcdr (p->status));
1330 Fprinc (symbol, Qnil);
1332 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1334 if (EQ (symbol, Qexit))
1335 write_string ("closed", -1);
1336 else if (EQ (p->command, Qt))
1337 write_string ("stopped", -1);
1338 else if (EQ (symbol, Qrun))
1339 write_string ("open", -1);
1340 else
1341 Fprinc (symbol, Qnil);
1343 else if (SERIALCONN1_P (p))
1345 write_string ("running", -1);
1347 else
1348 Fprinc (symbol, Qnil);
1350 if (EQ (symbol, Qexit))
1352 Lisp_Object tem;
1353 tem = Fcar (Fcdr (p->status));
1354 if (XFASTINT (tem))
1356 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1357 write_string (tembuf, -1);
1361 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1362 exited++;
1364 Findent_to (i_buffer, minspace);
1365 if (NILP (p->buffer))
1366 insert_string ("(none)");
1367 else if (NILP (XBUFFER (p->buffer)->name))
1368 insert_string ("(Killed)");
1369 else
1370 Finsert (1, &XBUFFER (p->buffer)->name);
1372 if (!NILP (i_tty))
1374 Findent_to (i_tty, minspace);
1375 if (STRINGP (p->tty_name))
1376 Finsert (1, &p->tty_name);
1379 Findent_to (i_command, minspace);
1381 if (EQ (p->status, Qlisten))
1383 Lisp_Object port = Fplist_get (p->childp, QCservice);
1384 if (INTEGERP (port))
1385 port = Fnumber_to_string (port);
1386 if (NILP (port))
1387 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1388 sprintf (tembuf, "(network %s server on %s)\n",
1389 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1390 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1391 insert_string (tembuf);
1393 else if (NETCONN1_P (p))
1395 /* For a local socket, there is no host name,
1396 so display service instead. */
1397 Lisp_Object host = Fplist_get (p->childp, QChost);
1398 if (!STRINGP (host))
1400 host = Fplist_get (p->childp, QCservice);
1401 if (INTEGERP (host))
1402 host = Fnumber_to_string (host);
1404 if (NILP (host))
1405 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1406 sprintf (tembuf, "(network %s connection to %s)\n",
1407 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1408 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1409 insert_string (tembuf);
1411 else if (SERIALCONN1_P (p))
1413 Lisp_Object port = Fplist_get (p->childp, QCport);
1414 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1415 insert_string ("(serial port ");
1416 if (STRINGP (port))
1417 insert_string (SDATA (port));
1418 else
1419 insert_string ("?");
1420 if (INTEGERP (speed))
1422 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1423 insert_string (tembuf);
1425 insert_string (")\n");
1427 else
1429 tem = p->command;
1430 while (1)
1432 tem1 = Fcar (tem);
1433 if (NILP (tem1))
1434 break;
1435 Finsert (1, &tem1);
1436 tem = Fcdr (tem);
1437 if (NILP (tem))
1438 break;
1439 insert_string (" ");
1441 insert_string ("\n");
1444 if (exited)
1446 status_notify (NULL);
1447 redisplay_preserve_echo_area (13);
1449 return Qnil;
1452 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1453 doc: /* Display a list of all processes.
1454 If optional argument QUERY-ONLY is non-nil, only processes with
1455 the query-on-exit flag set will be listed.
1456 Any process listed as exited or signaled is actually eliminated
1457 after the listing is made. */)
1458 (Lisp_Object query_only)
1460 internal_with_output_to_temp_buffer ("*Process List*",
1461 list_processes_1, query_only);
1462 return Qnil;
1465 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1466 doc: /* Return a list of all processes. */)
1467 (void)
1469 return Fmapcar (Qcdr, Vprocess_alist);
1472 /* Starting asynchronous inferior processes. */
1474 static Lisp_Object start_process_unwind (Lisp_Object proc);
1476 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1477 doc: /* Start a program in a subprocess. Return the process object for it.
1478 NAME is name for process. It is modified if necessary to make it unique.
1479 BUFFER is the buffer (or buffer name) to associate with the process.
1481 Process output (both standard output and standard error streams) goes
1482 at end of BUFFER, unless you specify an output stream or filter
1483 function to handle the output. BUFFER may also be nil, meaning that
1484 this process is not associated with any buffer.
1486 PROGRAM is the program file name. It is searched for in PATH. If
1487 nil, just associate a pty with the buffer. Remaining arguments are
1488 strings to give program as arguments.
1490 If you want to separate standard output from standard error, invoke
1491 the command through a shell and redirect one of them using the shell
1492 syntax.
1494 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1495 (int nargs, register Lisp_Object *args)
1497 Lisp_Object buffer, name, program, proc, current_dir, tem;
1498 register unsigned char **new_argv;
1499 register int i;
1500 int count = SPECPDL_INDEX ();
1502 buffer = args[1];
1503 if (!NILP (buffer))
1504 buffer = Fget_buffer_create (buffer);
1506 /* Make sure that the child will be able to chdir to the current
1507 buffer's current directory, or its unhandled equivalent. We
1508 can't just have the child check for an error when it does the
1509 chdir, since it's in a vfork.
1511 We have to GCPRO around this because Fexpand_file_name and
1512 Funhandled_file_name_directory might call a file name handling
1513 function. The argument list is protected by the caller, so all
1514 we really have to worry about is buffer. */
1516 struct gcpro gcpro1, gcpro2;
1518 current_dir = current_buffer->directory;
1520 GCPRO2 (buffer, current_dir);
1522 current_dir = Funhandled_file_name_directory (current_dir);
1523 if (NILP (current_dir))
1524 /* If the file name handler says that current_dir is unreachable, use
1525 a sensible default. */
1526 current_dir = build_string ("~/");
1527 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1528 if (NILP (Ffile_accessible_directory_p (current_dir)))
1529 report_file_error ("Setting current directory",
1530 Fcons (current_buffer->directory, Qnil));
1532 UNGCPRO;
1535 name = args[0];
1536 CHECK_STRING (name);
1538 program = args[2];
1540 if (!NILP (program))
1541 CHECK_STRING (program);
1543 proc = make_process (name);
1544 /* If an error occurs and we can't start the process, we want to
1545 remove it from the process list. This means that each error
1546 check in create_process doesn't need to call remove_process
1547 itself; it's all taken care of here. */
1548 record_unwind_protect (start_process_unwind, proc);
1550 XPROCESS (proc)->childp = Qt;
1551 XPROCESS (proc)->plist = Qnil;
1552 XPROCESS (proc)->type = Qreal;
1553 XPROCESS (proc)->buffer = buffer;
1554 XPROCESS (proc)->sentinel = Qnil;
1555 XPROCESS (proc)->filter = Qnil;
1556 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1558 #ifdef ADAPTIVE_READ_BUFFERING
1559 XPROCESS (proc)->adaptive_read_buffering
1560 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1561 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1562 #endif
1564 /* Make the process marker point into the process buffer (if any). */
1565 if (BUFFERP (buffer))
1566 set_marker_both (XPROCESS (proc)->mark, buffer,
1567 BUF_ZV (XBUFFER (buffer)),
1568 BUF_ZV_BYTE (XBUFFER (buffer)));
1571 /* Decide coding systems for communicating with the process. Here
1572 we don't setup the structure coding_system nor pay attention to
1573 unibyte mode. They are done in create_process. */
1575 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1576 Lisp_Object coding_systems = Qt;
1577 Lisp_Object val, *args2;
1578 struct gcpro gcpro1, gcpro2;
1580 val = Vcoding_system_for_read;
1581 if (NILP (val))
1583 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1584 args2[0] = Qstart_process;
1585 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1586 GCPRO2 (proc, current_dir);
1587 if (!NILP (program))
1588 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1589 UNGCPRO;
1590 if (CONSP (coding_systems))
1591 val = XCAR (coding_systems);
1592 else if (CONSP (Vdefault_process_coding_system))
1593 val = XCAR (Vdefault_process_coding_system);
1595 XPROCESS (proc)->decode_coding_system = val;
1597 val = Vcoding_system_for_write;
1598 if (NILP (val))
1600 if (EQ (coding_systems, Qt))
1602 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1603 args2[0] = Qstart_process;
1604 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1605 GCPRO2 (proc, current_dir);
1606 if (!NILP (program))
1607 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1608 UNGCPRO;
1610 if (CONSP (coding_systems))
1611 val = XCDR (coding_systems);
1612 else if (CONSP (Vdefault_process_coding_system))
1613 val = XCDR (Vdefault_process_coding_system);
1615 XPROCESS (proc)->encode_coding_system = val;
1619 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1620 XPROCESS (proc)->decoding_carryover = 0;
1621 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1623 XPROCESS (proc)->inherit_coding_system_flag
1624 = !(NILP (buffer) || !inherit_process_coding_system);
1626 if (!NILP (program))
1628 /* If program file name is not absolute, search our path for it.
1629 Put the name we will really use in TEM. */
1630 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1631 && !(SCHARS (program) > 1
1632 && IS_DEVICE_SEP (SREF (program, 1))))
1634 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1636 tem = Qnil;
1637 GCPRO4 (name, program, buffer, current_dir);
1638 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1639 UNGCPRO;
1640 if (NILP (tem))
1641 report_file_error ("Searching for program", Fcons (program, Qnil));
1642 tem = Fexpand_file_name (tem, Qnil);
1644 else
1646 if (!NILP (Ffile_directory_p (program)))
1647 error ("Specified program for new process is a directory");
1648 tem = program;
1651 /* If program file name starts with /: for quoting a magic name,
1652 discard that. */
1653 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1654 && SREF (tem, 1) == ':')
1655 tem = Fsubstring (tem, make_number (2), Qnil);
1658 struct gcpro gcpro1;
1659 GCPRO1 (tem);
1661 /* Encode the file name and put it in NEW_ARGV.
1662 That's where the child will use it to execute the program. */
1663 tem = Fcons (ENCODE_FILE (tem), Qnil);
1665 /* Here we encode arguments by the coding system used for sending
1666 data to the process. We don't support using different coding
1667 systems for encoding arguments and for encoding data sent to the
1668 process. */
1670 for (i = 3; i < nargs; i++)
1672 tem = Fcons (args[i], tem);
1673 CHECK_STRING (XCAR (tem));
1674 if (STRING_MULTIBYTE (XCAR (tem)))
1675 XSETCAR (tem,
1676 code_convert_string_norecord
1677 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1680 UNGCPRO;
1683 /* Now that everything is encoded we can collect the strings into
1684 NEW_ARGV. */
1685 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1686 new_argv[nargs - 2] = 0;
1688 for (i = nargs - 3; i >= 0; i--)
1690 new_argv[i] = SDATA (XCAR (tem));
1691 tem = XCDR (tem);
1694 create_process (proc, (char **) new_argv, current_dir);
1696 else
1697 create_pty (proc);
1699 return unbind_to (count, proc);
1702 /* This function is the unwind_protect form for Fstart_process. If
1703 PROC doesn't have its pid set, then we know someone has signaled
1704 an error and the process wasn't started successfully, so we should
1705 remove it from the process list. */
1706 static Lisp_Object
1707 start_process_unwind (Lisp_Object proc)
1709 if (!PROCESSP (proc))
1710 abort ();
1712 /* Was PROC started successfully? */
1713 if (XPROCESS (proc)->pid == -1)
1714 remove_process (proc);
1716 return Qnil;
1719 static void
1720 create_process_1 (struct atimer *timer)
1722 /* Nothing to do. */
1726 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1727 #ifdef USG
1728 #ifdef SIGCHLD
1729 /* Mimic blocking of signals on system V, which doesn't really have it. */
1731 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1732 int sigchld_deferred;
1734 SIGTYPE
1735 create_process_sigchld ()
1737 signal (SIGCHLD, create_process_sigchld);
1739 sigchld_deferred = 1;
1741 #endif
1742 #endif
1743 #endif
1745 void
1746 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1748 int inchannel, outchannel;
1749 pid_t pid;
1750 int sv[2];
1751 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1752 int wait_child_setup[2];
1753 #endif
1754 sigset_t procmask;
1755 sigset_t blocked;
1756 struct sigaction sigint_action;
1757 struct sigaction sigquit_action;
1758 #ifdef AIX
1759 struct sigaction sighup_action;
1760 #endif
1761 /* Use volatile to protect variables from being clobbered by longjmp. */
1762 volatile int forkin, forkout;
1763 volatile int pty_flag = 0;
1764 #ifndef USE_CRT_DLL
1765 extern char **environ;
1766 #endif
1768 inchannel = outchannel = -1;
1770 #ifdef HAVE_PTYS
1771 if (!NILP (Vprocess_connection_type))
1772 outchannel = inchannel = allocate_pty ();
1774 if (inchannel >= 0)
1776 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1777 /* On most USG systems it does not work to open the pty's tty here,
1778 then close it and reopen it in the child. */
1779 #ifdef O_NOCTTY
1780 /* Don't let this terminal become our controlling terminal
1781 (in case we don't have one). */
1782 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1783 #else
1784 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1785 #endif
1786 if (forkin < 0)
1787 report_file_error ("Opening pty", Qnil);
1788 #else
1789 forkin = forkout = -1;
1790 #endif /* not USG, or USG_SUBTTY_WORKS */
1791 pty_flag = 1;
1793 else
1794 #endif /* HAVE_PTYS */
1796 int tem;
1797 tem = pipe (sv);
1798 if (tem < 0)
1799 report_file_error ("Creating pipe", Qnil);
1800 inchannel = sv[0];
1801 forkout = sv[1];
1802 tem = pipe (sv);
1803 if (tem < 0)
1805 emacs_close (inchannel);
1806 emacs_close (forkout);
1807 report_file_error ("Creating pipe", Qnil);
1809 outchannel = sv[1];
1810 forkin = sv[0];
1813 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1815 int tem;
1817 tem = pipe (wait_child_setup);
1818 if (tem < 0)
1819 report_file_error ("Creating pipe", Qnil);
1820 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1821 if (tem >= 0)
1822 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1823 if (tem < 0)
1825 emacs_close (wait_child_setup[0]);
1826 emacs_close (wait_child_setup[1]);
1827 report_file_error ("Setting file descriptor flags", Qnil);
1830 #endif
1832 #if 0
1833 /* Replaced by close_process_descs */
1834 set_exclusive_use (inchannel);
1835 set_exclusive_use (outchannel);
1836 #endif
1838 #ifdef O_NONBLOCK
1839 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1840 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1841 #else
1842 #ifdef O_NDELAY
1843 fcntl (inchannel, F_SETFL, O_NDELAY);
1844 fcntl (outchannel, F_SETFL, O_NDELAY);
1845 #endif
1846 #endif
1848 /* Record this as an active process, with its channels.
1849 As a result, child_setup will close Emacs's side of the pipes. */
1850 chan_process[inchannel] = process;
1851 XPROCESS (process)->infd = inchannel;
1852 XPROCESS (process)->outfd = outchannel;
1854 /* Previously we recorded the tty descriptor used in the subprocess.
1855 It was only used for getting the foreground tty process, so now
1856 we just reopen the device (see emacs_get_tty_pgrp) as this is
1857 more portable (see USG_SUBTTY_WORKS above). */
1859 XPROCESS (process)->pty_flag = pty_flag;
1860 XPROCESS (process)->status = Qrun;
1861 setup_process_coding_systems (process);
1863 /* Delay interrupts until we have a chance to store
1864 the new fork's pid in its process structure */
1865 sigemptyset (&blocked);
1866 #ifdef SIGCHLD
1867 sigaddset (&blocked, SIGCHLD);
1868 #endif
1869 #ifdef HAVE_WORKING_VFORK
1870 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1871 this sets the parent's signal handlers as well as the child's.
1872 So delay all interrupts whose handlers the child might munge,
1873 and record the current handlers so they can be restored later. */
1874 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1875 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1876 #ifdef AIX
1877 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1878 #endif
1879 #endif /* HAVE_WORKING_VFORK */
1880 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1882 FD_SET (inchannel, &input_wait_mask);
1883 FD_SET (inchannel, &non_keyboard_wait_mask);
1884 if (inchannel > max_process_desc)
1885 max_process_desc = inchannel;
1887 /* Until we store the proper pid, enable sigchld_handler
1888 to recognize an unknown pid as standing for this process.
1889 It is very important not to let this `marker' value stay
1890 in the table after this function has returned; if it does
1891 it might cause call-process to hang and subsequent asynchronous
1892 processes to get their return values scrambled. */
1893 XPROCESS (process)->pid = -1;
1895 BLOCK_INPUT;
1898 /* child_setup must clobber environ on systems with true vfork.
1899 Protect it from permanent change. */
1900 char **save_environ = environ;
1902 current_dir = ENCODE_FILE (current_dir);
1904 #ifndef WINDOWSNT
1905 pid = vfork ();
1906 if (pid == 0)
1907 #endif /* not WINDOWSNT */
1909 int xforkin = forkin;
1910 int xforkout = forkout;
1912 #if 0 /* This was probably a mistake--it duplicates code later on,
1913 but fails to handle all the cases. */
1914 /* Make sure SIGCHLD is not blocked in the child. */
1915 sigsetmask (SIGEMPTYMASK);
1916 #endif
1918 /* Make the pty be the controlling terminal of the process. */
1919 #ifdef HAVE_PTYS
1920 /* First, disconnect its current controlling terminal. */
1921 #ifdef HAVE_SETSID
1922 /* We tried doing setsid only if pty_flag, but it caused
1923 process_set_signal to fail on SGI when using a pipe. */
1924 setsid ();
1925 /* Make the pty's terminal the controlling terminal. */
1926 if (pty_flag && xforkin >= 0)
1928 #ifdef TIOCSCTTY
1929 /* We ignore the return value
1930 because faith@cs.unc.edu says that is necessary on Linux. */
1931 ioctl (xforkin, TIOCSCTTY, 0);
1932 #endif
1934 #else /* not HAVE_SETSID */
1935 #ifdef USG
1936 /* It's very important to call setpgrp here and no time
1937 afterwards. Otherwise, we lose our controlling tty which
1938 is set when we open the pty. */
1939 setpgrp ();
1940 #endif /* USG */
1941 #endif /* not HAVE_SETSID */
1942 #if defined (HAVE_TERMIOS) && defined (LDISC1)
1943 if (pty_flag && xforkin >= 0)
1945 struct termios t;
1946 tcgetattr (xforkin, &t);
1947 t.c_lflag = LDISC1;
1948 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1949 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1951 #else
1952 #if defined (NTTYDISC) && defined (TIOCSETD)
1953 if (pty_flag && xforkin >= 0)
1955 /* Use new line discipline. */
1956 int ldisc = NTTYDISC;
1957 ioctl (xforkin, TIOCSETD, &ldisc);
1959 #endif
1960 #endif
1961 #ifdef TIOCNOTTY
1962 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1963 can do TIOCSPGRP only to the process's controlling tty. */
1964 if (pty_flag)
1966 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1967 I can't test it since I don't have 4.3. */
1968 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1969 if (j >= 0)
1971 ioctl (j, TIOCNOTTY, 0);
1972 emacs_close (j);
1974 #ifndef USG
1975 /* In order to get a controlling terminal on some versions
1976 of BSD, it is necessary to put the process in pgrp 0
1977 before it opens the terminal. */
1978 #ifdef HAVE_SETPGID
1979 setpgid (0, 0);
1980 #else
1981 setpgrp (0, 0);
1982 #endif
1983 #endif
1985 #endif /* TIOCNOTTY */
1987 #if !defined (DONT_REOPEN_PTY)
1988 /*** There is a suggestion that this ought to be a
1989 conditional on TIOCSPGRP,
1990 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1991 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1992 that system does seem to need this code, even though
1993 both HAVE_SETSID and TIOCSCTTY are defined. */
1994 /* Now close the pty (if we had it open) and reopen it.
1995 This makes the pty the controlling terminal of the subprocess. */
1996 if (pty_flag)
1999 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2000 would work? */
2001 if (xforkin >= 0)
2002 emacs_close (xforkin);
2003 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2005 if (xforkin < 0)
2007 emacs_write (1, "Couldn't open the pty terminal ", 31);
2008 emacs_write (1, pty_name, strlen (pty_name));
2009 emacs_write (1, "\n", 1);
2010 _exit (1);
2014 #endif /* not DONT_REOPEN_PTY */
2016 #ifdef SETUP_SLAVE_PTY
2017 if (pty_flag)
2019 SETUP_SLAVE_PTY;
2021 #endif /* SETUP_SLAVE_PTY */
2022 #ifdef AIX
2023 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2024 Now reenable it in the child, so it will die when we want it to. */
2025 if (pty_flag)
2026 signal (SIGHUP, SIG_DFL);
2027 #endif
2028 #endif /* HAVE_PTYS */
2030 signal (SIGINT, SIG_DFL);
2031 signal (SIGQUIT, SIG_DFL);
2033 /* Stop blocking signals in the child. */
2034 sigprocmask (SIG_SETMASK, &procmask, 0);
2036 if (pty_flag)
2037 child_setup_tty (xforkout);
2038 #ifdef WINDOWSNT
2039 pid = child_setup (xforkin, xforkout, xforkout,
2040 new_argv, 1, current_dir);
2041 #else /* not WINDOWSNT */
2042 #ifdef FD_CLOEXEC
2043 emacs_close (wait_child_setup[0]);
2044 #endif
2045 child_setup (xforkin, xforkout, xforkout,
2046 new_argv, 1, current_dir);
2047 #endif /* not WINDOWSNT */
2049 environ = save_environ;
2052 UNBLOCK_INPUT;
2054 /* This runs in the Emacs process. */
2055 if (pid < 0)
2057 if (forkin >= 0)
2058 emacs_close (forkin);
2059 if (forkin != forkout && forkout >= 0)
2060 emacs_close (forkout);
2062 else
2064 /* vfork succeeded. */
2065 XPROCESS (process)->pid = pid;
2067 #ifdef WINDOWSNT
2068 register_child (pid, inchannel);
2069 #endif /* WINDOWSNT */
2071 /* If the subfork execv fails, and it exits,
2072 this close hangs. I don't know why.
2073 So have an interrupt jar it loose. */
2075 struct atimer *timer;
2076 EMACS_TIME offset;
2078 stop_polling ();
2079 EMACS_SET_SECS_USECS (offset, 1, 0);
2080 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2082 if (forkin >= 0)
2083 emacs_close (forkin);
2085 cancel_atimer (timer);
2086 start_polling ();
2089 if (forkin != forkout && forkout >= 0)
2090 emacs_close (forkout);
2092 #ifdef HAVE_PTYS
2093 if (pty_flag)
2094 XPROCESS (process)->tty_name = build_string (pty_name);
2095 else
2096 #endif
2097 XPROCESS (process)->tty_name = Qnil;
2099 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2100 /* Wait for child_setup to complete in case that vfork is
2101 actually defined as fork. The descriptor wait_child_setup[1]
2102 of a pipe is closed at the child side either by close-on-exec
2103 on successful execvp or the _exit call in child_setup. */
2105 char dummy;
2107 emacs_close (wait_child_setup[1]);
2108 emacs_read (wait_child_setup[0], &dummy, 1);
2109 emacs_close (wait_child_setup[0]);
2111 #endif
2114 /* Restore the signal state whether vfork succeeded or not.
2115 (We will signal an error, below, if it failed.) */
2116 #ifdef HAVE_WORKING_VFORK
2117 /* Restore the parent's signal handlers. */
2118 sigaction (SIGINT, &sigint_action, 0);
2119 sigaction (SIGQUIT, &sigquit_action, 0);
2120 #ifdef AIX
2121 sigaction (SIGHUP, &sighup_action, 0);
2122 #endif
2123 #endif /* HAVE_WORKING_VFORK */
2124 /* Stop blocking signals in the parent. */
2125 sigprocmask (SIG_SETMASK, &procmask, 0);
2127 /* Now generate the error if vfork failed. */
2128 if (pid < 0)
2129 report_file_error ("Doing vfork", Qnil);
2132 void
2133 create_pty (Lisp_Object process)
2135 int inchannel, outchannel;
2137 /* Use volatile to protect variables from being clobbered by longjmp. */
2138 volatile int forkin, forkout;
2139 volatile int pty_flag = 0;
2141 inchannel = outchannel = -1;
2143 #ifdef HAVE_PTYS
2144 if (!NILP (Vprocess_connection_type))
2145 outchannel = inchannel = allocate_pty ();
2147 if (inchannel >= 0)
2149 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2150 /* On most USG systems it does not work to open the pty's tty here,
2151 then close it and reopen it in the child. */
2152 #ifdef O_NOCTTY
2153 /* Don't let this terminal become our controlling terminal
2154 (in case we don't have one). */
2155 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2156 #else
2157 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2158 #endif
2159 if (forkin < 0)
2160 report_file_error ("Opening pty", Qnil);
2161 #if defined (DONT_REOPEN_PTY)
2162 /* In the case that vfork is defined as fork, the parent process
2163 (Emacs) may send some data before the child process completes
2164 tty options setup. So we setup tty before forking. */
2165 child_setup_tty (forkout);
2166 #endif /* DONT_REOPEN_PTY */
2167 #else
2168 forkin = forkout = -1;
2169 #endif /* not USG, or USG_SUBTTY_WORKS */
2170 pty_flag = 1;
2172 #endif /* HAVE_PTYS */
2174 #ifdef O_NONBLOCK
2175 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2176 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2177 #else
2178 #ifdef O_NDELAY
2179 fcntl (inchannel, F_SETFL, O_NDELAY);
2180 fcntl (outchannel, F_SETFL, O_NDELAY);
2181 #endif
2182 #endif
2184 /* Record this as an active process, with its channels.
2185 As a result, child_setup will close Emacs's side of the pipes. */
2186 chan_process[inchannel] = process;
2187 XPROCESS (process)->infd = inchannel;
2188 XPROCESS (process)->outfd = outchannel;
2190 /* Previously we recorded the tty descriptor used in the subprocess.
2191 It was only used for getting the foreground tty process, so now
2192 we just reopen the device (see emacs_get_tty_pgrp) as this is
2193 more portable (see USG_SUBTTY_WORKS above). */
2195 XPROCESS (process)->pty_flag = pty_flag;
2196 XPROCESS (process)->status = Qrun;
2197 setup_process_coding_systems (process);
2199 FD_SET (inchannel, &input_wait_mask);
2200 FD_SET (inchannel, &non_keyboard_wait_mask);
2201 if (inchannel > max_process_desc)
2202 max_process_desc = inchannel;
2204 XPROCESS (process)->pid = -2;
2205 #ifdef HAVE_PTYS
2206 if (pty_flag)
2207 XPROCESS (process)->tty_name = build_string (pty_name);
2208 else
2209 #endif
2210 XPROCESS (process)->tty_name = Qnil;
2214 #ifdef HAVE_SOCKETS
2216 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2217 The address family of sa is not included in the result. */
2219 static Lisp_Object
2220 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2222 Lisp_Object address;
2223 int i;
2224 unsigned char *cp;
2225 register struct Lisp_Vector *p;
2227 /* Workaround for a bug in getsockname on BSD: Names bound to
2228 sockets in the UNIX domain are inaccessible; getsockname returns
2229 a zero length name. */
2230 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2231 return empty_unibyte_string;
2233 switch (sa->sa_family)
2235 case AF_INET:
2237 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2238 len = sizeof (sin->sin_addr) + 1;
2239 address = Fmake_vector (make_number (len), Qnil);
2240 p = XVECTOR (address);
2241 p->contents[--len] = make_number (ntohs (sin->sin_port));
2242 cp = (unsigned char *) &sin->sin_addr;
2243 break;
2245 #ifdef AF_INET6
2246 case AF_INET6:
2248 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2249 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2250 len = sizeof (sin6->sin6_addr)/2 + 1;
2251 address = Fmake_vector (make_number (len), Qnil);
2252 p = XVECTOR (address);
2253 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2254 for (i = 0; i < len; i++)
2255 p->contents[i] = make_number (ntohs (ip6[i]));
2256 return address;
2258 #endif
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 case AF_LOCAL:
2262 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2263 for (i = 0; i < sizeof (sockun->sun_path); i++)
2264 if (sockun->sun_path[i] == 0)
2265 break;
2266 return make_unibyte_string (sockun->sun_path, i);
2268 #endif
2269 default:
2270 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2271 address = Fcons (make_number (sa->sa_family),
2272 Fmake_vector (make_number (len), Qnil));
2273 p = XVECTOR (XCDR (address));
2274 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2275 break;
2278 i = 0;
2279 while (i < len)
2280 p->contents[i++] = make_number (*cp++);
2282 return address;
2286 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2288 static int
2289 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2291 register struct Lisp_Vector *p;
2293 if (VECTORP (address))
2295 p = XVECTOR (address);
2296 if (p->size == 5)
2298 *familyp = AF_INET;
2299 return sizeof (struct sockaddr_in);
2301 #ifdef AF_INET6
2302 else if (p->size == 9)
2304 *familyp = AF_INET6;
2305 return sizeof (struct sockaddr_in6);
2307 #endif
2309 #ifdef HAVE_LOCAL_SOCKETS
2310 else if (STRINGP (address))
2312 *familyp = AF_LOCAL;
2313 return sizeof (struct sockaddr_un);
2315 #endif
2316 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2318 struct sockaddr *sa;
2319 *familyp = XINT (XCAR (address));
2320 p = XVECTOR (XCDR (address));
2321 return p->size + sizeof (sa->sa_family);
2323 return 0;
2326 /* Convert an address object (vector or string) to an internal sockaddr.
2328 The address format has been basically validated by
2329 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2330 it could have come from user data. So if FAMILY is not valid,
2331 we return after zeroing *SA. */
2333 static void
2334 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2336 register struct Lisp_Vector *p;
2337 register unsigned char *cp = NULL;
2338 register int i;
2340 memset (sa, 0, len);
2342 if (VECTORP (address))
2344 p = XVECTOR (address);
2345 if (family == AF_INET)
2347 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2348 len = sizeof (sin->sin_addr) + 1;
2349 i = XINT (p->contents[--len]);
2350 sin->sin_port = htons (i);
2351 cp = (unsigned char *)&sin->sin_addr;
2352 sa->sa_family = family;
2354 #ifdef AF_INET6
2355 else if (family == AF_INET6)
2357 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2358 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2359 len = sizeof (sin6->sin6_addr) + 1;
2360 i = XINT (p->contents[--len]);
2361 sin6->sin6_port = htons (i);
2362 for (i = 0; i < len; i++)
2363 if (INTEGERP (p->contents[i]))
2365 int j = XFASTINT (p->contents[i]) & 0xffff;
2366 ip6[i] = ntohs (j);
2368 sa->sa_family = family;
2369 return;
2371 #endif
2372 else
2373 return;
2375 else if (STRINGP (address))
2377 #ifdef HAVE_LOCAL_SOCKETS
2378 if (family == AF_LOCAL)
2380 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2381 cp = SDATA (address);
2382 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2383 sockun->sun_path[i] = *cp++;
2384 sa->sa_family = family;
2386 #endif
2387 return;
2389 else
2391 p = XVECTOR (XCDR (address));
2392 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2395 for (i = 0; i < len; i++)
2396 if (INTEGERP (p->contents[i]))
2397 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2400 #ifdef DATAGRAM_SOCKETS
2401 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2402 1, 1, 0,
2403 doc: /* Get the current datagram address associated with PROCESS. */)
2404 (Lisp_Object process)
2406 int channel;
2408 CHECK_PROCESS (process);
2410 if (!DATAGRAM_CONN_P (process))
2411 return Qnil;
2413 channel = XPROCESS (process)->infd;
2414 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2415 datagram_address[channel].len);
2418 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2419 2, 2, 0,
2420 doc: /* Set the datagram address for PROCESS to ADDRESS.
2421 Returns nil upon error setting address, ADDRESS otherwise. */)
2422 (Lisp_Object process, Lisp_Object address)
2424 int channel;
2425 int family, len;
2427 CHECK_PROCESS (process);
2429 if (!DATAGRAM_CONN_P (process))
2430 return Qnil;
2432 channel = XPROCESS (process)->infd;
2434 len = get_lisp_to_sockaddr_size (address, &family);
2435 if (datagram_address[channel].len != len)
2436 return Qnil;
2437 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2438 return address;
2440 #endif
2443 static const struct socket_options {
2444 /* The name of this option. Should be lowercase version of option
2445 name without SO_ prefix. */
2446 char *name;
2447 /* Option level SOL_... */
2448 int optlevel;
2449 /* Option number SO_... */
2450 int optnum;
2451 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2452 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2453 } socket_options[] =
2455 #ifdef SO_BINDTODEVICE
2456 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2457 #endif
2458 #ifdef SO_BROADCAST
2459 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2460 #endif
2461 #ifdef SO_DONTROUTE
2462 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2463 #endif
2464 #ifdef SO_KEEPALIVE
2465 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2466 #endif
2467 #ifdef SO_LINGER
2468 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2469 #endif
2470 #ifdef SO_OOBINLINE
2471 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2472 #endif
2473 #ifdef SO_PRIORITY
2474 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2475 #endif
2476 #ifdef SO_REUSEADDR
2477 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2478 #endif
2479 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2482 /* Set option OPT to value VAL on socket S.
2484 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2485 Signals an error if setting a known option fails.
2488 static int
2489 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2491 char *name;
2492 const struct socket_options *sopt;
2493 int ret = 0;
2495 CHECK_SYMBOL (opt);
2497 name = (char *) SDATA (SYMBOL_NAME (opt));
2498 for (sopt = socket_options; sopt->name; sopt++)
2499 if (strcmp (name, sopt->name) == 0)
2500 break;
2502 switch (sopt->opttype)
2504 case SOPT_BOOL:
2506 int optval;
2507 optval = NILP (val) ? 0 : 1;
2508 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2509 &optval, sizeof (optval));
2510 break;
2513 case SOPT_INT:
2515 int optval;
2516 if (INTEGERP (val))
2517 optval = XINT (val);
2518 else
2519 error ("Bad option value for %s", name);
2520 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2521 &optval, sizeof (optval));
2522 break;
2525 #ifdef SO_BINDTODEVICE
2526 case SOPT_IFNAME:
2528 char devname[IFNAMSIZ+1];
2530 /* This is broken, at least in the Linux 2.4 kernel.
2531 To unbind, the arg must be a zero integer, not the empty string.
2532 This should work on all systems. KFS. 2003-09-23. */
2533 memset (devname, 0, sizeof devname);
2534 if (STRINGP (val))
2536 char *arg = (char *) SDATA (val);
2537 int len = min (strlen (arg), IFNAMSIZ);
2538 memcpy (devname, arg, len);
2540 else if (!NILP (val))
2541 error ("Bad option value for %s", name);
2542 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2543 devname, IFNAMSIZ);
2544 break;
2546 #endif
2548 #ifdef SO_LINGER
2549 case SOPT_LINGER:
2551 struct linger linger;
2553 linger.l_onoff = 1;
2554 linger.l_linger = 0;
2555 if (INTEGERP (val))
2556 linger.l_linger = XINT (val);
2557 else
2558 linger.l_onoff = NILP (val) ? 0 : 1;
2559 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2560 &linger, sizeof (linger));
2561 break;
2563 #endif
2565 default:
2566 return 0;
2569 if (ret < 0)
2570 report_file_error ("Cannot set network option",
2571 Fcons (opt, Fcons (val, Qnil)));
2572 return (1 << sopt->optbit);
2576 DEFUN ("set-network-process-option",
2577 Fset_network_process_option, Sset_network_process_option,
2578 3, 4, 0,
2579 doc: /* For network process PROCESS set option OPTION to value VALUE.
2580 See `make-network-process' for a list of options and values.
2581 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2582 OPTION is not a supported option, return nil instead; otherwise return t. */)
2583 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2585 int s;
2586 struct Lisp_Process *p;
2588 CHECK_PROCESS (process);
2589 p = XPROCESS (process);
2590 if (!NETCONN1_P (p))
2591 error ("Process is not a network process");
2593 s = p->infd;
2594 if (s < 0)
2595 error ("Process is not running");
2597 if (set_socket_option (s, option, value))
2599 p->childp = Fplist_put (p->childp, option, value);
2600 return Qt;
2603 if (NILP (no_error))
2604 error ("Unknown or unsupported option");
2606 return Qnil;
2610 #ifdef HAVE_SERIAL
2611 DEFUN ("serial-process-configure",
2612 Fserial_process_configure,
2613 Sserial_process_configure,
2614 0, MANY, 0,
2615 doc: /* Configure speed, bytesize, etc. of a serial process.
2617 Arguments are specified as keyword/argument pairs. Attributes that
2618 are not given are re-initialized from the process's current
2619 configuration (available via the function `process-contact') or set to
2620 reasonable default values. The following arguments are defined:
2622 :process PROCESS
2623 :name NAME
2624 :buffer BUFFER
2625 :port PORT
2626 -- Any of these arguments can be given to identify the process that is
2627 to be configured. If none of these arguments is given, the current
2628 buffer's process is used.
2630 :speed SPEED -- SPEED is the speed of the serial port in bits per
2631 second, also called baud rate. Any value can be given for SPEED, but
2632 most serial ports work only at a few defined values between 1200 and
2633 115200, with 9600 being the most common value. If SPEED is nil, the
2634 serial port is not configured any further, i.e., all other arguments
2635 are ignored. This may be useful for special serial ports such as
2636 Bluetooth-to-serial converters which can only be configured through AT
2637 commands. A value of nil for SPEED can be used only when passed
2638 through `make-serial-process' or `serial-term'.
2640 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2641 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2643 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2644 `odd' (use odd parity), or the symbol `even' (use even parity). If
2645 PARITY is not given, no parity is used.
2647 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2648 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2649 is not given or nil, 1 stopbit is used.
2651 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2652 flowcontrol to be used, which is either nil (don't use flowcontrol),
2653 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2654 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2655 flowcontrol is used.
2657 `serial-process-configure' is called by `make-serial-process' for the
2658 initial configuration of the serial port.
2660 Examples:
2662 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2664 \(serial-process-configure
2665 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2667 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2669 usage: (serial-process-configure &rest ARGS) */)
2670 (int nargs, Lisp_Object *args)
2672 struct Lisp_Process *p;
2673 Lisp_Object contact = Qnil;
2674 Lisp_Object proc = Qnil;
2675 struct gcpro gcpro1;
2677 contact = Flist (nargs, args);
2678 GCPRO1 (contact);
2680 proc = Fplist_get (contact, QCprocess);
2681 if (NILP (proc))
2682 proc = Fplist_get (contact, QCname);
2683 if (NILP (proc))
2684 proc = Fplist_get (contact, QCbuffer);
2685 if (NILP (proc))
2686 proc = Fplist_get (contact, QCport);
2687 proc = get_process (proc);
2688 p = XPROCESS (proc);
2689 if (!EQ (p->type, Qserial))
2690 error ("Not a serial process");
2692 if (NILP (Fplist_get (p->childp, QCspeed)))
2694 UNGCPRO;
2695 return Qnil;
2698 serial_configure (p, contact);
2700 UNGCPRO;
2701 return Qnil;
2704 /* Used by make-serial-process to recover from errors. */
2705 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2707 if (!PROCESSP (proc))
2708 abort ();
2709 remove_process (proc);
2710 return Qnil;
2713 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2714 0, MANY, 0,
2715 doc: /* Create and return a serial port process.
2717 In Emacs, serial port connections are represented by process objects,
2718 so input and output work as for subprocesses, and `delete-process'
2719 closes a serial port connection. However, a serial process has no
2720 process id, it cannot be signaled, and the status codes are different
2721 from normal processes.
2723 `make-serial-process' creates a process and a buffer, on which you
2724 probably want to use `process-send-string'. Try \\[serial-term] for
2725 an interactive terminal. See below for examples.
2727 Arguments are specified as keyword/argument pairs. The following
2728 arguments are defined:
2730 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2731 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2732 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2733 the backslashes in strings).
2735 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2736 which is called by `make-serial-process'.
2738 :name NAME -- NAME is the name of the process. If NAME is not given,
2739 the value of PORT is used.
2741 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2742 with the process. Process output goes at the end of that buffer,
2743 unless you specify an output stream or filter function to handle the
2744 output. If BUFFER is not given, the value of NAME is used.
2746 :coding CODING -- If CODING is a symbol, it specifies the coding
2747 system used for both reading and writing for this process. If CODING
2748 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2749 ENCODING is used for writing.
2751 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2752 the process is running. If BOOL is not given, query before exiting.
2754 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2755 In the stopped state, a serial process does not accept incoming data,
2756 but you can send outgoing data. The stopped state is cleared by
2757 `continue-process' and set by `stop-process'.
2759 :filter FILTER -- Install FILTER as the process filter.
2761 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2763 :plist PLIST -- Install PLIST as the initial plist of the process.
2765 :speed
2766 :bytesize
2767 :parity
2768 :stopbits
2769 :flowcontrol
2770 -- These arguments are handled by `serial-process-configure', which is
2771 called by `make-serial-process'.
2773 The original argument list, possibly modified by later configuration,
2774 is available via the function `process-contact'.
2776 Examples:
2778 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2780 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2782 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2784 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2786 usage: (make-serial-process &rest ARGS) */)
2787 (int nargs, Lisp_Object *args)
2789 int fd = -1;
2790 Lisp_Object proc, contact, port;
2791 struct Lisp_Process *p;
2792 struct gcpro gcpro1;
2793 Lisp_Object name, buffer;
2794 Lisp_Object tem, val;
2795 int specpdl_count = -1;
2797 if (nargs == 0)
2798 return Qnil;
2800 contact = Flist (nargs, args);
2801 GCPRO1 (contact);
2803 port = Fplist_get (contact, QCport);
2804 if (NILP (port))
2805 error ("No port specified");
2806 CHECK_STRING (port);
2808 if (NILP (Fplist_member (contact, QCspeed)))
2809 error (":speed not specified");
2810 if (!NILP (Fplist_get (contact, QCspeed)))
2811 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2813 name = Fplist_get (contact, QCname);
2814 if (NILP (name))
2815 name = port;
2816 CHECK_STRING (name);
2817 proc = make_process (name);
2818 specpdl_count = SPECPDL_INDEX ();
2819 record_unwind_protect (make_serial_process_unwind, proc);
2820 p = XPROCESS (proc);
2822 fd = serial_open ((char*) SDATA (port));
2823 p->infd = fd;
2824 p->outfd = fd;
2825 if (fd > max_process_desc)
2826 max_process_desc = fd;
2827 chan_process[fd] = proc;
2829 buffer = Fplist_get (contact, QCbuffer);
2830 if (NILP (buffer))
2831 buffer = name;
2832 buffer = Fget_buffer_create (buffer);
2833 p->buffer = buffer;
2835 p->childp = contact;
2836 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2837 p->type = Qserial;
2838 p->sentinel = Fplist_get (contact, QCsentinel);
2839 p->filter = Fplist_get (contact, QCfilter);
2840 p->log = Qnil;
2841 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2842 p->kill_without_query = 1;
2843 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2844 p->command = Qt;
2845 p->pty_flag = 0;
2847 if (!EQ (p->command, Qt))
2849 FD_SET (fd, &input_wait_mask);
2850 FD_SET (fd, &non_keyboard_wait_mask);
2853 if (BUFFERP (buffer))
2855 set_marker_both (p->mark, buffer,
2856 BUF_ZV (XBUFFER (buffer)),
2857 BUF_ZV_BYTE (XBUFFER (buffer)));
2860 tem = Fplist_member (contact, QCcoding);
2861 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2862 tem = Qnil;
2864 val = Qnil;
2865 if (!NILP (tem))
2867 val = XCAR (XCDR (tem));
2868 if (CONSP (val))
2869 val = XCAR (val);
2871 else if (!NILP (Vcoding_system_for_read))
2872 val = Vcoding_system_for_read;
2873 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2874 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2875 val = Qnil;
2876 p->decode_coding_system = val;
2878 val = Qnil;
2879 if (!NILP (tem))
2881 val = XCAR (XCDR (tem));
2882 if (CONSP (val))
2883 val = XCDR (val);
2885 else if (!NILP (Vcoding_system_for_write))
2886 val = Vcoding_system_for_write;
2887 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2888 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2889 val = Qnil;
2890 p->encode_coding_system = val;
2892 setup_process_coding_systems (proc);
2893 p->decoding_buf = make_uninit_string (0);
2894 p->decoding_carryover = 0;
2895 p->encoding_buf = make_uninit_string (0);
2896 p->inherit_coding_system_flag
2897 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2899 Fserial_process_configure (nargs, args);
2901 specpdl_ptr = specpdl + specpdl_count;
2903 UNGCPRO;
2904 return proc;
2906 #endif /* HAVE_SERIAL */
2908 /* Create a network stream/datagram client/server process. Treated
2909 exactly like a normal process when reading and writing. Primary
2910 differences are in status display and process deletion. A network
2911 connection has no PID; you cannot signal it. All you can do is
2912 stop/continue it and deactivate/close it via delete-process */
2914 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2915 0, MANY, 0,
2916 doc: /* Create and return a network server or client process.
2918 In Emacs, network connections are represented by process objects, so
2919 input and output work as for subprocesses and `delete-process' closes
2920 a network connection. However, a network process has no process id,
2921 it cannot be signaled, and the status codes are different from normal
2922 processes.
2924 Arguments are specified as keyword/argument pairs. The following
2925 arguments are defined:
2927 :name NAME -- NAME is name for process. It is modified if necessary
2928 to make it unique.
2930 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2931 with the process. Process output goes at end of that buffer, unless
2932 you specify an output stream or filter function to handle the output.
2933 BUFFER may be also nil, meaning that this process is not associated
2934 with any buffer.
2936 :host HOST -- HOST is name of the host to connect to, or its IP
2937 address. The symbol `local' specifies the local host. If specified
2938 for a server process, it must be a valid name or address for the local
2939 host, and only clients connecting to that address will be accepted.
2941 :service SERVICE -- SERVICE is name of the service desired, or an
2942 integer specifying a port number to connect to. If SERVICE is t,
2943 a random port number is selected for the server. (If Emacs was
2944 compiled with getaddrinfo, a port number can also be specified as a
2945 string, e.g. "80", as well as an integer. This is not portable.)
2947 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2948 stream type connection, `datagram' creates a datagram type connection,
2949 `seqpacket' creates a reliable datagram connection.
2951 :family FAMILY -- FAMILY is the address (and protocol) family for the
2952 service specified by HOST and SERVICE. The default (nil) is to use
2953 whatever address family (IPv4 or IPv6) that is defined for the host
2954 and port number specified by HOST and SERVICE. Other address families
2955 supported are:
2956 local -- for a local (i.e. UNIX) address specified by SERVICE.
2957 ipv4 -- use IPv4 address family only.
2958 ipv6 -- use IPv6 address family only.
2960 :local ADDRESS -- ADDRESS is the local address used for the connection.
2961 This parameter is ignored when opening a client process. When specified
2962 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2964 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2965 connection. This parameter is ignored when opening a stream server
2966 process. For a datagram server process, it specifies the initial
2967 setting of the remote datagram address. When specified for a client
2968 process, the FAMILY, HOST, and SERVICE args are ignored.
2970 The format of ADDRESS depends on the address family:
2971 - An IPv4 address is represented as an vector of integers [A B C D P]
2972 corresponding to numeric IP address A.B.C.D and port number P.
2973 - A local address is represented as a string with the address in the
2974 local address space.
2975 - An "unsupported family" address is represented by a cons (F . AV)
2976 where F is the family number and AV is a vector containing the socket
2977 address data with one element per address data byte. Do not rely on
2978 this format in portable code, as it may depend on implementation
2979 defined constants, data sizes, and data structure alignment.
2981 :coding CODING -- If CODING is a symbol, it specifies the coding
2982 system used for both reading and writing for this process. If CODING
2983 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2984 ENCODING is used for writing.
2986 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2987 return without waiting for the connection to complete; instead, the
2988 sentinel function will be called with second arg matching "open" (if
2989 successful) or "failed" when the connect completes. Default is to use
2990 a blocking connect (i.e. wait) for stream type connections.
2992 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2993 running when Emacs is exited.
2995 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2996 In the stopped state, a server process does not accept new
2997 connections, and a client process does not handle incoming traffic.
2998 The stopped state is cleared by `continue-process' and set by
2999 `stop-process'.
3001 :filter FILTER -- Install FILTER as the process filter.
3003 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3004 process filter are multibyte, otherwise they are unibyte.
3005 If this keyword is not specified, the strings are multibyte if
3006 `default-enable-multibyte-characters' is non-nil.
3008 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3010 :log LOG -- Install LOG as the server process log function. This
3011 function is called when the server accepts a network connection from a
3012 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3013 is the server process, CLIENT is the new process for the connection,
3014 and MESSAGE is a string.
3016 :plist PLIST -- Install PLIST as the new process' initial plist.
3018 :server QLEN -- if QLEN is non-nil, create a server process for the
3019 specified FAMILY, SERVICE, and connection type (stream or datagram).
3020 If QLEN is an integer, it is used as the max. length of the server's
3021 pending connection queue (also known as the backlog); the default
3022 queue length is 5. Default is to create a client process.
3024 The following network options can be specified for this connection:
3026 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3027 :dontroute BOOL -- Only send to directly connected hosts.
3028 :keepalive BOOL -- Send keep-alive messages on network stream.
3029 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3030 :oobinline BOOL -- Place out-of-band data in receive data stream.
3031 :priority INT -- Set protocol defined priority for sent packets.
3032 :reuseaddr BOOL -- Allow reusing a recently used local address
3033 (this is allowed by default for a server process).
3034 :bindtodevice NAME -- bind to interface NAME. Using this may require
3035 special privileges on some systems.
3037 Consult the relevant system programmer's manual pages for more
3038 information on using these options.
3041 A server process will listen for and accept connections from clients.
3042 When a client connection is accepted, a new network process is created
3043 for the connection with the following parameters:
3045 - The client's process name is constructed by concatenating the server
3046 process' NAME and a client identification string.
3047 - If the FILTER argument is non-nil, the client process will not get a
3048 separate process buffer; otherwise, the client's process buffer is a newly
3049 created buffer named after the server process' BUFFER name or process
3050 NAME concatenated with the client identification string.
3051 - The connection type and the process filter and sentinel parameters are
3052 inherited from the server process' TYPE, FILTER and SENTINEL.
3053 - The client process' contact info is set according to the client's
3054 addressing information (typically an IP address and a port number).
3055 - The client process' plist is initialized from the server's plist.
3057 Notice that the FILTER and SENTINEL args are never used directly by
3058 the server process. Also, the BUFFER argument is not used directly by
3059 the server process, but via the optional :log function, accepted (and
3060 failed) connections may be logged in the server process' buffer.
3062 The original argument list, modified with the actual connection
3063 information, is available via the `process-contact' function.
3065 usage: (make-network-process &rest ARGS) */)
3066 (int nargs, Lisp_Object *args)
3068 Lisp_Object proc;
3069 Lisp_Object contact;
3070 struct Lisp_Process *p;
3071 #ifdef HAVE_GETADDRINFO
3072 struct addrinfo ai, *res, *lres;
3073 struct addrinfo hints;
3074 char *portstring, portbuf[128];
3075 #else /* HAVE_GETADDRINFO */
3076 struct _emacs_addrinfo
3078 int ai_family;
3079 int ai_socktype;
3080 int ai_protocol;
3081 int ai_addrlen;
3082 struct sockaddr *ai_addr;
3083 struct _emacs_addrinfo *ai_next;
3084 } ai, *res, *lres;
3085 #endif /* HAVE_GETADDRINFO */
3086 struct sockaddr_in address_in;
3087 #ifdef HAVE_LOCAL_SOCKETS
3088 struct sockaddr_un address_un;
3089 #endif
3090 int port;
3091 int ret = 0;
3092 int xerrno = 0;
3093 int s = -1, outch, inch;
3094 struct gcpro gcpro1;
3095 int count = SPECPDL_INDEX ();
3096 int count1;
3097 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3098 Lisp_Object tem;
3099 Lisp_Object name, buffer, host, service, address;
3100 Lisp_Object filter, sentinel;
3101 int is_non_blocking_client = 0;
3102 int is_server = 0, backlog = 5;
3103 int socktype;
3104 int family = -1;
3106 if (nargs == 0)
3107 return Qnil;
3109 /* Save arguments for process-contact and clone-process. */
3110 contact = Flist (nargs, args);
3111 GCPRO1 (contact);
3113 #ifdef WINDOWSNT
3114 /* Ensure socket support is loaded if available. */
3115 init_winsock (TRUE);
3116 #endif
3118 /* :type TYPE (nil: stream, datagram */
3119 tem = Fplist_get (contact, QCtype);
3120 if (NILP (tem))
3121 socktype = SOCK_STREAM;
3122 #ifdef DATAGRAM_SOCKETS
3123 else if (EQ (tem, Qdatagram))
3124 socktype = SOCK_DGRAM;
3125 #endif
3126 #ifdef HAVE_SEQPACKET
3127 else if (EQ (tem, Qseqpacket))
3128 socktype = SOCK_SEQPACKET;
3129 #endif
3130 else
3131 error ("Unsupported connection type");
3133 /* :server BOOL */
3134 tem = Fplist_get (contact, QCserver);
3135 if (!NILP (tem))
3137 /* Don't support network sockets when non-blocking mode is
3138 not available, since a blocked Emacs is not useful. */
3139 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3140 error ("Network servers not supported");
3141 #else
3142 is_server = 1;
3143 if (INTEGERP (tem))
3144 backlog = XINT (tem);
3145 #endif
3148 /* Make QCaddress an alias for :local (server) or :remote (client). */
3149 QCaddress = is_server ? QClocal : QCremote;
3151 /* :nowait BOOL */
3152 if (!is_server && socktype != SOCK_DGRAM
3153 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3155 #ifndef NON_BLOCKING_CONNECT
3156 error ("Non-blocking connect not supported");
3157 #else
3158 is_non_blocking_client = 1;
3159 #endif
3162 name = Fplist_get (contact, QCname);
3163 buffer = Fplist_get (contact, QCbuffer);
3164 filter = Fplist_get (contact, QCfilter);
3165 sentinel = Fplist_get (contact, QCsentinel);
3167 CHECK_STRING (name);
3169 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3170 ai.ai_socktype = socktype;
3171 ai.ai_protocol = 0;
3172 ai.ai_next = NULL;
3173 res = &ai;
3175 /* :local ADDRESS or :remote ADDRESS */
3176 address = Fplist_get (contact, QCaddress);
3177 if (!NILP (address))
3179 host = service = Qnil;
3181 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3182 error ("Malformed :address");
3183 ai.ai_family = family;
3184 ai.ai_addr = alloca (ai.ai_addrlen);
3185 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3186 goto open_socket;
3189 /* :family FAMILY -- nil (for Inet), local, or integer. */
3190 tem = Fplist_get (contact, QCfamily);
3191 if (NILP (tem))
3193 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3194 family = AF_UNSPEC;
3195 #else
3196 family = AF_INET;
3197 #endif
3199 #ifdef HAVE_LOCAL_SOCKETS
3200 else if (EQ (tem, Qlocal))
3201 family = AF_LOCAL;
3202 #endif
3203 #ifdef AF_INET6
3204 else if (EQ (tem, Qipv6))
3205 family = AF_INET6;
3206 #endif
3207 else if (EQ (tem, Qipv4))
3208 family = AF_INET;
3209 else if (INTEGERP (tem))
3210 family = XINT (tem);
3211 else
3212 error ("Unknown address family");
3214 ai.ai_family = family;
3216 /* :service SERVICE -- string, integer (port number), or t (random port). */
3217 service = Fplist_get (contact, QCservice);
3219 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3220 host = Fplist_get (contact, QChost);
3221 if (!NILP (host))
3223 if (EQ (host, Qlocal))
3224 host = build_string ("localhost");
3225 CHECK_STRING (host);
3228 #ifdef HAVE_LOCAL_SOCKETS
3229 if (family == AF_LOCAL)
3231 if (!NILP (host))
3233 message (":family local ignores the :host \"%s\" property",
3234 SDATA (host));
3235 contact = Fplist_put (contact, QChost, Qnil);
3236 host = Qnil;
3238 CHECK_STRING (service);
3239 memset (&address_un, 0, sizeof address_un);
3240 address_un.sun_family = AF_LOCAL;
3241 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3242 ai.ai_addr = (struct sockaddr *) &address_un;
3243 ai.ai_addrlen = sizeof address_un;
3244 goto open_socket;
3246 #endif
3248 /* Slow down polling to every ten seconds.
3249 Some kernels have a bug which causes retrying connect to fail
3250 after a connect. Polling can interfere with gethostbyname too. */
3251 #ifdef POLL_FOR_INPUT
3252 if (socktype != SOCK_DGRAM)
3254 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3255 bind_polling_period (10);
3257 #endif
3259 #ifdef HAVE_GETADDRINFO
3260 /* If we have a host, use getaddrinfo to resolve both host and service.
3261 Otherwise, use getservbyname to lookup the service. */
3262 if (!NILP (host))
3265 /* SERVICE can either be a string or int.
3266 Convert to a C string for later use by getaddrinfo. */
3267 if (EQ (service, Qt))
3268 portstring = "0";
3269 else if (INTEGERP (service))
3271 sprintf (portbuf, "%ld", (long) XINT (service));
3272 portstring = portbuf;
3274 else
3276 CHECK_STRING (service);
3277 portstring = SDATA (service);
3280 immediate_quit = 1;
3281 QUIT;
3282 memset (&hints, 0, sizeof (hints));
3283 hints.ai_flags = 0;
3284 hints.ai_family = family;
3285 hints.ai_socktype = socktype;
3286 hints.ai_protocol = 0;
3288 #ifdef HAVE_RES_INIT
3289 res_init ();
3290 #endif
3292 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3293 if (ret)
3294 #ifdef HAVE_GAI_STRERROR
3295 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3296 #else
3297 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3298 #endif
3299 immediate_quit = 0;
3301 goto open_socket;
3303 #endif /* HAVE_GETADDRINFO */
3305 /* We end up here if getaddrinfo is not defined, or in case no hostname
3306 has been specified (e.g. for a local server process). */
3308 if (EQ (service, Qt))
3309 port = 0;
3310 else if (INTEGERP (service))
3311 port = htons ((unsigned short) XINT (service));
3312 else
3314 struct servent *svc_info;
3315 CHECK_STRING (service);
3316 svc_info = getservbyname (SDATA (service),
3317 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3318 if (svc_info == 0)
3319 error ("Unknown service: %s", SDATA (service));
3320 port = svc_info->s_port;
3323 memset (&address_in, 0, sizeof address_in);
3324 address_in.sin_family = family;
3325 address_in.sin_addr.s_addr = INADDR_ANY;
3326 address_in.sin_port = port;
3328 #ifndef HAVE_GETADDRINFO
3329 if (!NILP (host))
3331 struct hostent *host_info_ptr;
3333 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3334 as it may `hang' Emacs for a very long time. */
3335 immediate_quit = 1;
3336 QUIT;
3338 #ifdef HAVE_RES_INIT
3339 res_init ();
3340 #endif
3342 host_info_ptr = gethostbyname (SDATA (host));
3343 immediate_quit = 0;
3345 if (host_info_ptr)
3347 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3348 host_info_ptr->h_length);
3349 family = host_info_ptr->h_addrtype;
3350 address_in.sin_family = family;
3352 else
3353 /* Attempt to interpret host as numeric inet address */
3355 unsigned long numeric_addr;
3356 numeric_addr = inet_addr ((char *) SDATA (host));
3357 if (numeric_addr == -1)
3358 error ("Unknown host \"%s\"", SDATA (host));
3360 memcpy (&address_in.sin_addr, &numeric_addr,
3361 sizeof (address_in.sin_addr));
3365 #endif /* not HAVE_GETADDRINFO */
3367 ai.ai_family = family;
3368 ai.ai_addr = (struct sockaddr *) &address_in;
3369 ai.ai_addrlen = sizeof address_in;
3371 open_socket:
3373 /* Do this in case we never enter the for-loop below. */
3374 count1 = SPECPDL_INDEX ();
3375 s = -1;
3377 for (lres = res; lres; lres = lres->ai_next)
3379 int optn, optbits;
3381 retry_connect:
3383 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3384 if (s < 0)
3386 xerrno = errno;
3387 continue;
3390 #ifdef DATAGRAM_SOCKETS
3391 if (!is_server && socktype == SOCK_DGRAM)
3392 break;
3393 #endif /* DATAGRAM_SOCKETS */
3395 #ifdef NON_BLOCKING_CONNECT
3396 if (is_non_blocking_client)
3398 #ifdef O_NONBLOCK
3399 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3400 #else
3401 ret = fcntl (s, F_SETFL, O_NDELAY);
3402 #endif
3403 if (ret < 0)
3405 xerrno = errno;
3406 emacs_close (s);
3407 s = -1;
3408 continue;
3411 #endif
3413 /* Make us close S if quit. */
3414 record_unwind_protect (close_file_unwind, make_number (s));
3416 /* Parse network options in the arg list.
3417 We simply ignore anything which isn't a known option (including other keywords).
3418 An error is signaled if setting a known option fails. */
3419 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3420 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3422 if (is_server)
3424 /* Configure as a server socket. */
3426 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3427 explicit :reuseaddr key to override this. */
3428 #ifdef HAVE_LOCAL_SOCKETS
3429 if (family != AF_LOCAL)
3430 #endif
3431 if (!(optbits & (1 << OPIX_REUSEADDR)))
3433 int optval = 1;
3434 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3435 report_file_error ("Cannot set reuse option on server socket", Qnil);
3438 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3439 report_file_error ("Cannot bind server socket", Qnil);
3441 #ifdef HAVE_GETSOCKNAME
3442 if (EQ (service, Qt))
3444 struct sockaddr_in sa1;
3445 int len1 = sizeof (sa1);
3446 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3448 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3449 service = make_number (ntohs (sa1.sin_port));
3450 contact = Fplist_put (contact, QCservice, service);
3453 #endif
3455 if (socktype != SOCK_DGRAM && listen (s, backlog))
3456 report_file_error ("Cannot listen on server socket", Qnil);
3458 break;
3461 immediate_quit = 1;
3462 QUIT;
3464 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3465 xerrno = errno;
3467 if (ret == 0 || xerrno == EISCONN)
3469 /* The unwind-protect will be discarded afterwards.
3470 Likewise for immediate_quit. */
3471 break;
3474 #ifdef NON_BLOCKING_CONNECT
3475 #ifdef EINPROGRESS
3476 if (is_non_blocking_client && xerrno == EINPROGRESS)
3477 break;
3478 #else
3479 #ifdef EWOULDBLOCK
3480 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3481 break;
3482 #endif
3483 #endif
3484 #endif
3486 #ifndef WINDOWSNT
3487 if (xerrno == EINTR)
3489 /* Unlike most other syscalls connect() cannot be called
3490 again. (That would return EALREADY.) The proper way to
3491 wait for completion is select(). */
3492 int sc, len;
3493 SELECT_TYPE fdset;
3494 retry_select:
3495 FD_ZERO (&fdset);
3496 FD_SET (s, &fdset);
3497 QUIT;
3498 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3499 (EMACS_TIME *)0);
3500 if (sc == -1)
3502 if (errno == EINTR)
3503 goto retry_select;
3504 else
3505 report_file_error ("select failed", Qnil);
3507 eassert (sc > 0);
3509 len = sizeof xerrno;
3510 eassert (FD_ISSET (s, &fdset));
3511 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3512 report_file_error ("getsockopt failed", Qnil);
3513 if (xerrno)
3514 errno = xerrno, report_file_error ("error during connect", Qnil);
3515 else
3516 break;
3518 #endif /* !WINDOWSNT */
3520 immediate_quit = 0;
3522 /* Discard the unwind protect closing S. */
3523 specpdl_ptr = specpdl + count1;
3524 emacs_close (s);
3525 s = -1;
3527 #ifdef WINDOWSNT
3528 if (xerrno == EINTR)
3529 goto retry_connect;
3530 #endif
3533 if (s >= 0)
3535 #ifdef DATAGRAM_SOCKETS
3536 if (socktype == SOCK_DGRAM)
3538 if (datagram_address[s].sa)
3539 abort ();
3540 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3541 datagram_address[s].len = lres->ai_addrlen;
3542 if (is_server)
3544 Lisp_Object remote;
3545 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3546 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3548 int rfamily, rlen;
3549 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3550 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3551 conv_lisp_to_sockaddr (rfamily, remote,
3552 datagram_address[s].sa, rlen);
3555 else
3556 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3558 #endif
3559 contact = Fplist_put (contact, QCaddress,
3560 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3561 #ifdef HAVE_GETSOCKNAME
3562 if (!is_server)
3564 struct sockaddr_in sa1;
3565 int len1 = sizeof (sa1);
3566 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3567 contact = Fplist_put (contact, QClocal,
3568 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3570 #endif
3573 immediate_quit = 0;
3575 #ifdef HAVE_GETADDRINFO
3576 if (res != &ai)
3578 BLOCK_INPUT;
3579 freeaddrinfo (res);
3580 UNBLOCK_INPUT;
3582 #endif
3584 /* Discard the unwind protect for closing S, if any. */
3585 specpdl_ptr = specpdl + count1;
3587 /* Unwind bind_polling_period and request_sigio. */
3588 unbind_to (count, Qnil);
3590 if (s < 0)
3592 /* If non-blocking got this far - and failed - assume non-blocking is
3593 not supported after all. This is probably a wrong assumption, but
3594 the normal blocking calls to open-network-stream handles this error
3595 better. */
3596 if (is_non_blocking_client)
3597 return Qnil;
3599 errno = xerrno;
3600 if (is_server)
3601 report_file_error ("make server process failed", contact);
3602 else
3603 report_file_error ("make client process failed", contact);
3606 inch = s;
3607 outch = s;
3609 if (!NILP (buffer))
3610 buffer = Fget_buffer_create (buffer);
3611 proc = make_process (name);
3613 chan_process[inch] = proc;
3615 #ifdef O_NONBLOCK
3616 fcntl (inch, F_SETFL, O_NONBLOCK);
3617 #else
3618 #ifdef O_NDELAY
3619 fcntl (inch, F_SETFL, O_NDELAY);
3620 #endif
3621 #endif
3623 p = XPROCESS (proc);
3625 p->childp = contact;
3626 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3627 p->type = Qnetwork;
3629 p->buffer = buffer;
3630 p->sentinel = sentinel;
3631 p->filter = filter;
3632 p->log = Fplist_get (contact, QClog);
3633 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3634 p->kill_without_query = 1;
3635 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3636 p->command = Qt;
3637 p->pid = 0;
3638 p->infd = inch;
3639 p->outfd = outch;
3640 if (is_server && socktype != SOCK_DGRAM)
3641 p->status = Qlisten;
3643 /* Make the process marker point into the process buffer (if any). */
3644 if (BUFFERP (buffer))
3645 set_marker_both (p->mark, buffer,
3646 BUF_ZV (XBUFFER (buffer)),
3647 BUF_ZV_BYTE (XBUFFER (buffer)));
3649 #ifdef NON_BLOCKING_CONNECT
3650 if (is_non_blocking_client)
3652 /* We may get here if connect did succeed immediately. However,
3653 in that case, we still need to signal this like a non-blocking
3654 connection. */
3655 p->status = Qconnect;
3656 if (!FD_ISSET (inch, &connect_wait_mask))
3658 FD_SET (inch, &connect_wait_mask);
3659 num_pending_connects++;
3662 else
3663 #endif
3664 /* A server may have a client filter setting of Qt, but it must
3665 still listen for incoming connects unless it is stopped. */
3666 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3667 || (EQ (p->status, Qlisten) && NILP (p->command)))
3669 FD_SET (inch, &input_wait_mask);
3670 FD_SET (inch, &non_keyboard_wait_mask);
3673 if (inch > max_process_desc)
3674 max_process_desc = inch;
3676 tem = Fplist_member (contact, QCcoding);
3677 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3678 tem = Qnil; /* No error message (too late!). */
3681 /* Setup coding systems for communicating with the network stream. */
3682 struct gcpro gcpro1;
3683 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3684 Lisp_Object coding_systems = Qt;
3685 Lisp_Object args[5], val;
3687 if (!NILP (tem))
3689 val = XCAR (XCDR (tem));
3690 if (CONSP (val))
3691 val = XCAR (val);
3693 else if (!NILP (Vcoding_system_for_read))
3694 val = Vcoding_system_for_read;
3695 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3696 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3697 /* We dare not decode end-of-line format by setting VAL to
3698 Qraw_text, because the existing Emacs Lisp libraries
3699 assume that they receive bare code including a sequene of
3700 CR LF. */
3701 val = Qnil;
3702 else
3704 if (NILP (host) || NILP (service))
3705 coding_systems = Qnil;
3706 else
3708 args[0] = Qopen_network_stream, args[1] = name,
3709 args[2] = buffer, args[3] = host, args[4] = service;
3710 GCPRO1 (proc);
3711 coding_systems = Ffind_operation_coding_system (5, args);
3712 UNGCPRO;
3714 if (CONSP (coding_systems))
3715 val = XCAR (coding_systems);
3716 else if (CONSP (Vdefault_process_coding_system))
3717 val = XCAR (Vdefault_process_coding_system);
3718 else
3719 val = Qnil;
3721 p->decode_coding_system = val;
3723 if (!NILP (tem))
3725 val = XCAR (XCDR (tem));
3726 if (CONSP (val))
3727 val = XCDR (val);
3729 else if (!NILP (Vcoding_system_for_write))
3730 val = Vcoding_system_for_write;
3731 else if (NILP (current_buffer->enable_multibyte_characters))
3732 val = Qnil;
3733 else
3735 if (EQ (coding_systems, Qt))
3737 if (NILP (host) || NILP (service))
3738 coding_systems = Qnil;
3739 else
3741 args[0] = Qopen_network_stream, args[1] = name,
3742 args[2] = buffer, args[3] = host, args[4] = service;
3743 GCPRO1 (proc);
3744 coding_systems = Ffind_operation_coding_system (5, args);
3745 UNGCPRO;
3748 if (CONSP (coding_systems))
3749 val = XCDR (coding_systems);
3750 else if (CONSP (Vdefault_process_coding_system))
3751 val = XCDR (Vdefault_process_coding_system);
3752 else
3753 val = Qnil;
3755 p->encode_coding_system = val;
3757 setup_process_coding_systems (proc);
3759 p->decoding_buf = make_uninit_string (0);
3760 p->decoding_carryover = 0;
3761 p->encoding_buf = make_uninit_string (0);
3763 p->inherit_coding_system_flag
3764 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3766 UNGCPRO;
3767 return proc;
3769 #endif /* HAVE_SOCKETS */
3772 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3774 #ifdef SIOCGIFCONF
3775 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3776 doc: /* Return an alist of all network interfaces and their network address.
3777 Each element is a cons, the car of which is a string containing the
3778 interface name, and the cdr is the network address in internal
3779 format; see the description of ADDRESS in `make-network-process'. */)
3780 (void)
3782 struct ifconf ifconf;
3783 struct ifreq *ifreqs = NULL;
3784 int ifaces = 0;
3785 int buf_size, s;
3786 Lisp_Object res;
3788 s = socket (AF_INET, SOCK_STREAM, 0);
3789 if (s < 0)
3790 return Qnil;
3792 again:
3793 ifaces += 25;
3794 buf_size = ifaces * sizeof (ifreqs[0]);
3795 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3796 if (!ifreqs)
3798 close (s);
3799 return Qnil;
3802 ifconf.ifc_len = buf_size;
3803 ifconf.ifc_req = ifreqs;
3804 if (ioctl (s, SIOCGIFCONF, &ifconf))
3806 close (s);
3807 return Qnil;
3810 if (ifconf.ifc_len == buf_size)
3811 goto again;
3813 close (s);
3814 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3816 res = Qnil;
3817 while (--ifaces >= 0)
3819 struct ifreq *ifq = &ifreqs[ifaces];
3820 char namebuf[sizeof (ifq->ifr_name) + 1];
3821 if (ifq->ifr_addr.sa_family != AF_INET)
3822 continue;
3823 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3824 namebuf[sizeof (ifq->ifr_name)] = 0;
3825 res = Fcons (Fcons (build_string (namebuf),
3826 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3827 sizeof (struct sockaddr))),
3828 res);
3831 return res;
3833 #endif /* SIOCGIFCONF */
3835 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3837 struct ifflag_def {
3838 int flag_bit;
3839 const char *flag_sym;
3842 static const struct ifflag_def ifflag_table[] = {
3843 #ifdef IFF_UP
3844 { IFF_UP, "up" },
3845 #endif
3846 #ifdef IFF_BROADCAST
3847 { IFF_BROADCAST, "broadcast" },
3848 #endif
3849 #ifdef IFF_DEBUG
3850 { IFF_DEBUG, "debug" },
3851 #endif
3852 #ifdef IFF_LOOPBACK
3853 { IFF_LOOPBACK, "loopback" },
3854 #endif
3855 #ifdef IFF_POINTOPOINT
3856 { IFF_POINTOPOINT, "pointopoint" },
3857 #endif
3858 #ifdef IFF_RUNNING
3859 { IFF_RUNNING, "running" },
3860 #endif
3861 #ifdef IFF_NOARP
3862 { IFF_NOARP, "noarp" },
3863 #endif
3864 #ifdef IFF_PROMISC
3865 { IFF_PROMISC, "promisc" },
3866 #endif
3867 #ifdef IFF_NOTRAILERS
3868 { IFF_NOTRAILERS, "notrailers" },
3869 #endif
3870 #ifdef IFF_ALLMULTI
3871 { IFF_ALLMULTI, "allmulti" },
3872 #endif
3873 #ifdef IFF_MASTER
3874 { IFF_MASTER, "master" },
3875 #endif
3876 #ifdef IFF_SLAVE
3877 { IFF_SLAVE, "slave" },
3878 #endif
3879 #ifdef IFF_MULTICAST
3880 { IFF_MULTICAST, "multicast" },
3881 #endif
3882 #ifdef IFF_PORTSEL
3883 { IFF_PORTSEL, "portsel" },
3884 #endif
3885 #ifdef IFF_AUTOMEDIA
3886 { IFF_AUTOMEDIA, "automedia" },
3887 #endif
3888 #ifdef IFF_DYNAMIC
3889 { IFF_DYNAMIC, "dynamic" },
3890 #endif
3891 #ifdef IFF_OACTIVE
3892 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3893 #endif
3894 #ifdef IFF_SIMPLEX
3895 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3896 #endif
3897 #ifdef IFF_LINK0
3898 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3899 #endif
3900 #ifdef IFF_LINK1
3901 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3902 #endif
3903 #ifdef IFF_LINK2
3904 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3905 #endif
3906 { 0, 0 }
3909 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3910 doc: /* Return information about network interface named IFNAME.
3911 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3912 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3913 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3914 FLAGS is the current flags of the interface. */)
3915 (Lisp_Object ifname)
3917 struct ifreq rq;
3918 Lisp_Object res = Qnil;
3919 Lisp_Object elt;
3920 int s;
3921 int any = 0;
3923 CHECK_STRING (ifname);
3925 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3926 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3928 s = socket (AF_INET, SOCK_STREAM, 0);
3929 if (s < 0)
3930 return Qnil;
3932 elt = Qnil;
3933 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3934 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3936 int flags = rq.ifr_flags;
3937 const struct ifflag_def *fp;
3938 int fnum;
3940 any++;
3941 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3943 if (flags & fp->flag_bit)
3945 elt = Fcons (intern (fp->flag_sym), elt);
3946 flags -= fp->flag_bit;
3949 for (fnum = 0; flags && fnum < 32; fnum++)
3951 if (flags & (1 << fnum))
3953 elt = Fcons (make_number (fnum), elt);
3957 #endif
3958 res = Fcons (elt, res);
3960 elt = Qnil;
3961 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3962 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3964 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3965 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3966 int n;
3968 any++;
3969 for (n = 0; n < 6; n++)
3970 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3971 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3973 #endif
3974 res = Fcons (elt, res);
3976 elt = Qnil;
3977 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3978 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3980 any++;
3981 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3982 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3983 #else
3984 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3985 #endif
3987 #endif
3988 res = Fcons (elt, res);
3990 elt = Qnil;
3991 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3992 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3994 any++;
3995 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3997 #endif
3998 res = Fcons (elt, res);
4000 elt = Qnil;
4001 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4002 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4004 any++;
4005 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4007 #endif
4008 res = Fcons (elt, res);
4010 close (s);
4012 return any ? res : Qnil;
4014 #endif
4015 #endif /* HAVE_SOCKETS */
4017 /* Turn off input and output for process PROC. */
4019 void
4020 deactivate_process (Lisp_Object proc)
4022 register int inchannel, outchannel;
4023 register struct Lisp_Process *p = XPROCESS (proc);
4025 inchannel = p->infd;
4026 outchannel = p->outfd;
4028 #ifdef ADAPTIVE_READ_BUFFERING
4029 if (p->read_output_delay > 0)
4031 if (--process_output_delay_count < 0)
4032 process_output_delay_count = 0;
4033 p->read_output_delay = 0;
4034 p->read_output_skip = 0;
4036 #endif
4038 if (inchannel >= 0)
4040 /* Beware SIGCHLD hereabouts. */
4041 flush_pending_output (inchannel);
4042 emacs_close (inchannel);
4043 if (outchannel >= 0 && outchannel != inchannel)
4044 emacs_close (outchannel);
4046 p->infd = -1;
4047 p->outfd = -1;
4048 #ifdef DATAGRAM_SOCKETS
4049 if (DATAGRAM_CHAN_P (inchannel))
4051 xfree (datagram_address[inchannel].sa);
4052 datagram_address[inchannel].sa = 0;
4053 datagram_address[inchannel].len = 0;
4055 #endif
4056 chan_process[inchannel] = Qnil;
4057 FD_CLR (inchannel, &input_wait_mask);
4058 FD_CLR (inchannel, &non_keyboard_wait_mask);
4059 #ifdef NON_BLOCKING_CONNECT
4060 if (FD_ISSET (inchannel, &connect_wait_mask))
4062 FD_CLR (inchannel, &connect_wait_mask);
4063 if (--num_pending_connects < 0)
4064 abort ();
4066 #endif
4067 if (inchannel == max_process_desc)
4069 int i;
4070 /* We just closed the highest-numbered process input descriptor,
4071 so recompute the highest-numbered one now. */
4072 max_process_desc = 0;
4073 for (i = 0; i < MAXDESC; i++)
4074 if (!NILP (chan_process[i]))
4075 max_process_desc = i;
4081 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4082 0, 4, 0,
4083 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4084 It is read into the process' buffers or given to their filter functions.
4085 Non-nil arg PROCESS means do not return until some output has been received
4086 from PROCESS.
4088 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4089 and milliseconds to wait; return after that much time whether or not
4090 there is any subprocess output. If SECONDS is a floating point number,
4091 it specifies a fractional number of seconds to wait.
4092 The MILLISEC argument is obsolete and should be avoided.
4094 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4095 from PROCESS, suspending reading output from other processes.
4096 If JUST-THIS-ONE is an integer, don't run any timers either.
4097 Return non-nil if we received any output before the timeout expired. */)
4098 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4100 int secs, usecs = 0;
4102 if (! NILP (process))
4103 CHECK_PROCESS (process);
4104 else
4105 just_this_one = Qnil;
4107 if (!NILP (millisec))
4108 { /* Obsolete calling convention using integers rather than floats. */
4109 CHECK_NUMBER (millisec);
4110 if (NILP (seconds))
4111 seconds = make_float (XINT (millisec) / 1000.0);
4112 else
4114 CHECK_NUMBER (seconds);
4115 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4119 if (!NILP (seconds))
4121 if (INTEGERP (seconds))
4122 secs = XINT (seconds);
4123 else if (FLOATP (seconds))
4125 double timeout = XFLOAT_DATA (seconds);
4126 secs = (int) timeout;
4127 usecs = (int) ((timeout - (double) secs) * 1000000);
4129 else
4130 wrong_type_argument (Qnumberp, seconds);
4132 if (secs < 0 || (secs == 0 && usecs == 0))
4133 secs = -1, usecs = 0;
4135 else
4136 secs = NILP (process) ? -1 : 0;
4138 return
4139 (wait_reading_process_output (secs, usecs, 0, 0,
4140 Qnil,
4141 !NILP (process) ? XPROCESS (process) : NULL,
4142 NILP (just_this_one) ? 0 :
4143 !INTEGERP (just_this_one) ? 1 : -1)
4144 ? Qt : Qnil);
4147 /* Accept a connection for server process SERVER on CHANNEL. */
4149 static int connect_counter = 0;
4151 static void
4152 server_accept_connection (Lisp_Object server, int channel)
4154 Lisp_Object proc, caller, name, buffer;
4155 Lisp_Object contact, host, service;
4156 struct Lisp_Process *ps= XPROCESS (server);
4157 struct Lisp_Process *p;
4158 int s;
4159 union u_sockaddr {
4160 struct sockaddr sa;
4161 struct sockaddr_in in;
4162 #ifdef AF_INET6
4163 struct sockaddr_in6 in6;
4164 #endif
4165 #ifdef HAVE_LOCAL_SOCKETS
4166 struct sockaddr_un un;
4167 #endif
4168 } saddr;
4169 int len = sizeof saddr;
4171 s = accept (channel, &saddr.sa, &len);
4173 if (s < 0)
4175 int code = errno;
4177 if (code == EAGAIN)
4178 return;
4179 #ifdef EWOULDBLOCK
4180 if (code == EWOULDBLOCK)
4181 return;
4182 #endif
4184 if (!NILP (ps->log))
4185 call3 (ps->log, server, Qnil,
4186 concat3 (build_string ("accept failed with code"),
4187 Fnumber_to_string (make_number (code)),
4188 build_string ("\n")));
4189 return;
4192 connect_counter++;
4194 /* Setup a new process to handle the connection. */
4196 /* Generate a unique identification of the caller, and build contact
4197 information for this process. */
4198 host = Qt;
4199 service = Qnil;
4200 switch (saddr.sa.sa_family)
4202 case AF_INET:
4204 Lisp_Object args[5];
4205 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4206 args[0] = build_string ("%d.%d.%d.%d");
4207 args[1] = make_number (*ip++);
4208 args[2] = make_number (*ip++);
4209 args[3] = make_number (*ip++);
4210 args[4] = make_number (*ip++);
4211 host = Fformat (5, args);
4212 service = make_number (ntohs (saddr.in.sin_port));
4214 args[0] = build_string (" <%s:%d>");
4215 args[1] = host;
4216 args[2] = service;
4217 caller = Fformat (3, args);
4219 break;
4221 #ifdef AF_INET6
4222 case AF_INET6:
4224 Lisp_Object args[9];
4225 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4226 int i;
4227 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4228 for (i = 0; i < 8; i++)
4229 args[i+1] = make_number (ntohs (ip6[i]));
4230 host = Fformat (9, args);
4231 service = make_number (ntohs (saddr.in.sin_port));
4233 args[0] = build_string (" <[%s]:%d>");
4234 args[1] = host;
4235 args[2] = service;
4236 caller = Fformat (3, args);
4238 break;
4239 #endif
4241 #ifdef HAVE_LOCAL_SOCKETS
4242 case AF_LOCAL:
4243 #endif
4244 default:
4245 caller = Fnumber_to_string (make_number (connect_counter));
4246 caller = concat3 (build_string (" <"), caller, build_string (">"));
4247 break;
4250 /* Create a new buffer name for this process if it doesn't have a
4251 filter. The new buffer name is based on the buffer name or
4252 process name of the server process concatenated with the caller
4253 identification. */
4255 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4256 buffer = Qnil;
4257 else
4259 buffer = ps->buffer;
4260 if (!NILP (buffer))
4261 buffer = Fbuffer_name (buffer);
4262 else
4263 buffer = ps->name;
4264 if (!NILP (buffer))
4266 buffer = concat2 (buffer, caller);
4267 buffer = Fget_buffer_create (buffer);
4271 /* Generate a unique name for the new server process. Combine the
4272 server process name with the caller identification. */
4274 name = concat2 (ps->name, caller);
4275 proc = make_process (name);
4277 chan_process[s] = proc;
4279 #ifdef O_NONBLOCK
4280 fcntl (s, F_SETFL, O_NONBLOCK);
4281 #else
4282 #ifdef O_NDELAY
4283 fcntl (s, F_SETFL, O_NDELAY);
4284 #endif
4285 #endif
4287 p = XPROCESS (proc);
4289 /* Build new contact information for this setup. */
4290 contact = Fcopy_sequence (ps->childp);
4291 contact = Fplist_put (contact, QCserver, Qnil);
4292 contact = Fplist_put (contact, QChost, host);
4293 if (!NILP (service))
4294 contact = Fplist_put (contact, QCservice, service);
4295 contact = Fplist_put (contact, QCremote,
4296 conv_sockaddr_to_lisp (&saddr.sa, len));
4297 #ifdef HAVE_GETSOCKNAME
4298 len = sizeof saddr;
4299 if (getsockname (s, &saddr.sa, &len) == 0)
4300 contact = Fplist_put (contact, QClocal,
4301 conv_sockaddr_to_lisp (&saddr.sa, len));
4302 #endif
4304 p->childp = contact;
4305 p->plist = Fcopy_sequence (ps->plist);
4306 p->type = Qnetwork;
4308 p->buffer = buffer;
4309 p->sentinel = ps->sentinel;
4310 p->filter = ps->filter;
4311 p->command = Qnil;
4312 p->pid = 0;
4313 p->infd = s;
4314 p->outfd = s;
4315 p->status = Qrun;
4317 /* Client processes for accepted connections are not stopped initially. */
4318 if (!EQ (p->filter, Qt))
4320 FD_SET (s, &input_wait_mask);
4321 FD_SET (s, &non_keyboard_wait_mask);
4324 if (s > max_process_desc)
4325 max_process_desc = s;
4327 /* Setup coding system for new process based on server process.
4328 This seems to be the proper thing to do, as the coding system
4329 of the new process should reflect the settings at the time the
4330 server socket was opened; not the current settings. */
4332 p->decode_coding_system = ps->decode_coding_system;
4333 p->encode_coding_system = ps->encode_coding_system;
4334 setup_process_coding_systems (proc);
4336 p->decoding_buf = make_uninit_string (0);
4337 p->decoding_carryover = 0;
4338 p->encoding_buf = make_uninit_string (0);
4340 p->inherit_coding_system_flag
4341 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4343 if (!NILP (ps->log))
4344 call3 (ps->log, server, proc,
4345 concat3 (build_string ("accept from "),
4346 (STRINGP (host) ? host : build_string ("-")),
4347 build_string ("\n")));
4349 if (!NILP (p->sentinel))
4350 exec_sentinel (proc,
4351 concat3 (build_string ("open from "),
4352 (STRINGP (host) ? host : build_string ("-")),
4353 build_string ("\n")));
4356 /* This variable is different from waiting_for_input in keyboard.c.
4357 It is used to communicate to a lisp process-filter/sentinel (via the
4358 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4359 for user-input when that process-filter was called.
4360 waiting_for_input cannot be used as that is by definition 0 when
4361 lisp code is being evalled.
4362 This is also used in record_asynch_buffer_change.
4363 For that purpose, this must be 0
4364 when not inside wait_reading_process_output. */
4365 static int waiting_for_user_input_p;
4367 static Lisp_Object
4368 wait_reading_process_output_unwind (Lisp_Object data)
4370 waiting_for_user_input_p = XINT (data);
4371 return Qnil;
4374 /* This is here so breakpoints can be put on it. */
4375 static void
4376 wait_reading_process_output_1 (void)
4380 /* Use a wrapper around select to work around a bug in gdb 5.3.
4381 Normally, the wrapper is optimized away by inlining.
4383 If emacs is stopped inside select, the gdb backtrace doesn't
4384 show the function which called select, so it is practically
4385 impossible to step through wait_reading_process_output. */
4387 #ifndef select
4388 static INLINE int
4389 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4391 return select (n, rfd, wfd, xfd, tmo);
4393 #define select select_wrapper
4394 #endif
4396 /* Read and dispose of subprocess output while waiting for timeout to
4397 elapse and/or keyboard input to be available.
4399 TIME_LIMIT is:
4400 timeout in seconds, or
4401 zero for no limit, or
4402 -1 means gobble data immediately available but don't wait for any.
4404 MICROSECS is:
4405 an additional duration to wait, measured in microseconds.
4406 If this is nonzero and time_limit is 0, then the timeout
4407 consists of MICROSECS only.
4409 READ_KBD is a lisp value:
4410 0 to ignore keyboard input, or
4411 1 to return when input is available, or
4412 -1 meaning caller will actually read the input, so don't throw to
4413 the quit handler, or
4415 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4416 output that arrives.
4418 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4419 (and gobble terminal input into the buffer if any arrives).
4421 If WAIT_PROC is specified, wait until something arrives from that
4422 process. The return value is true if we read some input from
4423 that process.
4425 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4426 (suspending output from other processes). A negative value
4427 means don't run any timers either.
4429 If WAIT_PROC is specified, then the function returns true if we
4430 received input from that process before the timeout elapsed.
4431 Otherwise, return true if we received input from any process. */
4434 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4435 int do_display,
4436 Lisp_Object wait_for_cell,
4437 struct Lisp_Process *wait_proc, int just_wait_proc)
4439 register int channel, nfds;
4440 SELECT_TYPE Available;
4441 #ifdef NON_BLOCKING_CONNECT
4442 SELECT_TYPE Connecting;
4443 int check_connect;
4444 #endif
4445 int check_delay, no_avail;
4446 int xerrno;
4447 Lisp_Object proc;
4448 EMACS_TIME timeout, end_time;
4449 int wait_channel = -1;
4450 int got_some_input = 0;
4451 int count = SPECPDL_INDEX ();
4453 FD_ZERO (&Available);
4454 #ifdef NON_BLOCKING_CONNECT
4455 FD_ZERO (&Connecting);
4456 #endif
4458 if (time_limit == 0 && wait_proc && !NILP (Vinhibit_quit)
4459 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4460 message ("Blocking call to accept-process-output with quit inhibited!!");
4462 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4463 if (wait_proc != NULL)
4464 wait_channel = wait_proc->infd;
4466 record_unwind_protect (wait_reading_process_output_unwind,
4467 make_number (waiting_for_user_input_p));
4468 waiting_for_user_input_p = read_kbd;
4470 /* Since we may need to wait several times,
4471 compute the absolute time to return at. */
4472 if (time_limit || microsecs)
4474 EMACS_GET_TIME (end_time);
4475 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4476 EMACS_ADD_TIME (end_time, end_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 (time_limit == -1)
4501 /* -1 specified for timeout means
4502 gobble output available now
4503 but don't wait at all. */
4505 EMACS_SET_SECS_USECS (timeout, 0, 0);
4507 else if (time_limit || microsecs)
4509 EMACS_GET_TIME (timeout);
4510 EMACS_SUB_TIME (timeout, end_time, timeout);
4511 if (EMACS_TIME_NEG_P (timeout))
4512 break;
4514 else
4516 EMACS_SET_SECS_USECS (timeout, 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 (1);
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 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4560 EMACS_TIME difference;
4561 EMACS_SUB_TIME (difference, timer_delay, timeout);
4562 if (EMACS_TIME_NEG_P (difference))
4564 timeout = timer_delay;
4565 timeout_reduced_for_timers = 1;
4568 /* If time_limit is -1, we are not going to wait at all. */
4569 else if (time_limit != -1)
4571 /* This is so a breakpoint can be put here. */
4572 wait_reading_process_output_1 ();
4576 /* Cause C-g and alarm signals to take immediate action,
4577 and cause input available signals to zero out timeout.
4579 It is important that we do this before checking for process
4580 activity. If we get a SIGCHLD after the explicit checks for
4581 process activity, timeout is the only way we will know. */
4582 if (read_kbd < 0)
4583 set_waiting_for_input (&timeout);
4585 /* If status of something has changed, and no input is
4586 available, notify the user of the change right away. After
4587 this explicit check, we'll let the SIGCHLD handler zap
4588 timeout to get our attention. */
4589 if (update_tick != process_tick)
4591 SELECT_TYPE Atemp;
4592 #ifdef NON_BLOCKING_CONNECT
4593 SELECT_TYPE Ctemp;
4594 #endif
4596 if (kbd_on_hold_p ())
4597 FD_ZERO (&Atemp);
4598 else
4599 Atemp = input_wait_mask;
4600 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4602 EMACS_SET_SECS_USECS (timeout, 0, 0);
4603 if ((select (max (max (max_process_desc, max_keyboard_desc),
4604 max_gpm_desc) + 1,
4605 &Atemp,
4606 #ifdef NON_BLOCKING_CONNECT
4607 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4608 #else
4609 (SELECT_TYPE *)0,
4610 #endif
4611 (SELECT_TYPE *)0, &timeout)
4612 <= 0))
4614 /* It's okay for us to do this and then continue with
4615 the loop, since timeout has already been zeroed out. */
4616 clear_waiting_for_input ();
4617 status_notify (NULL);
4618 if (do_display) redisplay_preserve_echo_area (13);
4622 /* Don't wait for output from a non-running process. Just
4623 read whatever data has already been received. */
4624 if (wait_proc && wait_proc->raw_status_new)
4625 update_status (wait_proc);
4626 if (wait_proc
4627 && ! EQ (wait_proc->status, Qrun)
4628 && ! EQ (wait_proc->status, Qconnect))
4630 int nread, total_nread = 0;
4632 clear_waiting_for_input ();
4633 XSETPROCESS (proc, wait_proc);
4635 /* Read data from the process, until we exhaust it. */
4636 while (wait_proc->infd >= 0)
4638 nread = read_process_output (proc, wait_proc->infd);
4640 if (nread == 0)
4641 break;
4643 if (0 < nread)
4645 total_nread += nread;
4646 got_some_input = 1;
4648 #ifdef EIO
4649 else if (nread == -1 && EIO == errno)
4650 break;
4651 #endif
4652 #ifdef EAGAIN
4653 else if (nread == -1 && EAGAIN == errno)
4654 break;
4655 #endif
4656 #ifdef EWOULDBLOCK
4657 else if (nread == -1 && EWOULDBLOCK == errno)
4658 break;
4659 #endif
4661 if (total_nread > 0 && do_display)
4662 redisplay_preserve_echo_area (10);
4664 break;
4667 /* Wait till there is something to do */
4669 if (wait_proc && just_wait_proc)
4671 if (wait_proc->infd < 0) /* Terminated */
4672 break;
4673 FD_SET (wait_proc->infd, &Available);
4674 check_delay = 0;
4675 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4677 else if (!NILP (wait_for_cell))
4679 Available = non_process_wait_mask;
4680 check_delay = 0;
4681 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4683 else
4685 if (! read_kbd)
4686 Available = non_keyboard_wait_mask;
4687 else
4688 Available = input_wait_mask;
4689 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4690 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4693 /* If frame size has changed or the window is newly mapped,
4694 redisplay now, before we start to wait. There is a race
4695 condition here; if a SIGIO arrives between now and the select
4696 and indicates that a frame is trashed, the select may block
4697 displaying a trashed screen. */
4698 if (frame_garbaged && do_display)
4700 clear_waiting_for_input ();
4701 redisplay_preserve_echo_area (11);
4702 if (read_kbd < 0)
4703 set_waiting_for_input (&timeout);
4706 no_avail = 0;
4707 if (read_kbd && detect_input_pending ())
4709 nfds = 0;
4710 no_avail = 1;
4712 else
4714 #ifdef NON_BLOCKING_CONNECT
4715 if (check_connect)
4716 Connecting = connect_wait_mask;
4717 #endif
4719 #ifdef ADAPTIVE_READ_BUFFERING
4720 /* Set the timeout for adaptive read buffering if any
4721 process has non-zero read_output_skip and non-zero
4722 read_output_delay, and we are not reading output for a
4723 specific wait_channel. It is not executed if
4724 Vprocess_adaptive_read_buffering is nil. */
4725 if (process_output_skip && check_delay > 0)
4727 int usecs = EMACS_USECS (timeout);
4728 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4729 usecs = READ_OUTPUT_DELAY_MAX;
4730 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4732 proc = chan_process[channel];
4733 if (NILP (proc))
4734 continue;
4735 /* Find minimum non-zero read_output_delay among the
4736 processes with non-zero read_output_skip. */
4737 if (XPROCESS (proc)->read_output_delay > 0)
4739 check_delay--;
4740 if (!XPROCESS (proc)->read_output_skip)
4741 continue;
4742 FD_CLR (channel, &Available);
4743 XPROCESS (proc)->read_output_skip = 0;
4744 if (XPROCESS (proc)->read_output_delay < usecs)
4745 usecs = XPROCESS (proc)->read_output_delay;
4748 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4749 process_output_skip = 0;
4751 #endif
4752 #if defined (USE_GTK) || defined (HAVE_GCONF)
4753 nfds = xg_select
4754 #elif defined (HAVE_NS)
4755 nfds = ns_select
4756 #else
4757 nfds = select
4758 #endif
4759 (max (max (max_process_desc, max_keyboard_desc),
4760 max_gpm_desc) + 1,
4761 &Available,
4762 #ifdef NON_BLOCKING_CONNECT
4763 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4764 #else
4765 (SELECT_TYPE *)0,
4766 #endif
4767 (SELECT_TYPE *)0, &timeout);
4770 xerrno = errno;
4772 /* Make C-g and alarm signals set flags again */
4773 clear_waiting_for_input ();
4775 /* If we woke up due to SIGWINCH, actually change size now. */
4776 do_pending_window_change (0);
4778 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4779 /* We wanted the full specified time, so return now. */
4780 break;
4781 if (nfds < 0)
4783 if (xerrno == EINTR)
4784 no_avail = 1;
4785 else if (xerrno == EBADF)
4787 #ifdef AIX
4788 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4789 the child's closure of the pts gives the parent a SIGHUP, and
4790 the ptc file descriptor is automatically closed,
4791 yielding EBADF here or at select() call above.
4792 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4793 in m/ibmrt-aix.h), and here we just ignore the select error.
4794 Cleanup occurs c/o status_notify after SIGCLD. */
4795 no_avail = 1; /* Cannot depend on values returned */
4796 #else
4797 abort ();
4798 #endif
4800 else
4801 error ("select error: %s", emacs_strerror (xerrno));
4804 if (no_avail)
4806 FD_ZERO (&Available);
4807 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4810 #if 0 /* When polling is used, interrupt_input is 0,
4811 so get_input_pending should read the input.
4812 So this should not be needed. */
4813 /* If we are using polling for input,
4814 and we see input available, make it get read now.
4815 Otherwise it might not actually get read for a second.
4816 And on hpux, since we turn off polling in wait_reading_process_output,
4817 it might never get read at all if we don't spend much time
4818 outside of wait_reading_process_output. */
4819 if (read_kbd && interrupt_input
4820 && keyboard_bit_set (&Available)
4821 && input_polling_used ())
4822 kill (getpid (), SIGALRM);
4823 #endif
4825 /* Check for keyboard input */
4826 /* If there is any, return immediately
4827 to give it higher priority than subprocesses */
4829 if (read_kbd != 0)
4831 int old_timers_run = timers_run;
4832 struct buffer *old_buffer = current_buffer;
4833 Lisp_Object old_window = selected_window;
4834 int leave = 0;
4836 if (detect_input_pending_run_timers (do_display))
4838 swallow_events (do_display);
4839 if (detect_input_pending_run_timers (do_display))
4840 leave = 1;
4843 /* If a timer has run, this might have changed buffers
4844 an alike. Make read_key_sequence aware of that. */
4845 if (timers_run != old_timers_run
4846 && waiting_for_user_input_p == -1
4847 && (old_buffer != current_buffer
4848 || !EQ (old_window, selected_window)))
4849 record_asynch_buffer_change ();
4851 if (leave)
4852 break;
4855 /* If there is unread keyboard input, also return. */
4856 if (read_kbd != 0
4857 && requeued_events_pending_p ())
4858 break;
4860 /* If we are not checking for keyboard input now,
4861 do process events (but don't run any timers).
4862 This is so that X events will be processed.
4863 Otherwise they may have to wait until polling takes place.
4864 That would causes delays in pasting selections, for example.
4866 (We used to do this only if wait_for_cell.) */
4867 if (read_kbd == 0 && detect_input_pending ())
4869 swallow_events (do_display);
4870 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4871 if (detect_input_pending ())
4872 break;
4873 #endif
4876 /* Exit now if the cell we're waiting for became non-nil. */
4877 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4878 break;
4880 #ifdef SIGIO
4881 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4882 go read it. This can happen with X on BSD after logging out.
4883 In that case, there really is no input and no SIGIO,
4884 but select says there is input. */
4886 if (read_kbd && interrupt_input
4887 && keyboard_bit_set (&Available) && ! noninteractive)
4888 kill (getpid (), SIGIO);
4889 #endif
4891 if (! wait_proc)
4892 got_some_input |= nfds > 0;
4894 /* If checking input just got us a size-change event from X,
4895 obey it now if we should. */
4896 if (read_kbd || ! NILP (wait_for_cell))
4897 do_pending_window_change (0);
4899 /* Check for data from a process. */
4900 if (no_avail || nfds == 0)
4901 continue;
4903 /* Really FIRST_PROC_DESC should be 0 on Unix,
4904 but this is safer in the short run. */
4905 for (channel = 0; channel <= max_process_desc; channel++)
4907 if (FD_ISSET (channel, &Available)
4908 && FD_ISSET (channel, &non_keyboard_wait_mask))
4910 int nread;
4912 /* If waiting for this channel, arrange to return as
4913 soon as no more input to be processed. No more
4914 waiting. */
4915 if (wait_channel == channel)
4917 wait_channel = -1;
4918 time_limit = -1;
4919 got_some_input = 1;
4921 proc = chan_process[channel];
4922 if (NILP (proc))
4923 continue;
4925 /* If this is a server stream socket, accept connection. */
4926 if (EQ (XPROCESS (proc)->status, Qlisten))
4928 server_accept_connection (proc, channel);
4929 continue;
4932 /* Read data from the process, starting with our
4933 buffered-ahead character if we have one. */
4935 nread = read_process_output (proc, channel);
4936 if (nread > 0)
4938 /* Since read_process_output can run a filter,
4939 which can call accept-process-output,
4940 don't try to read from any other processes
4941 before doing the select again. */
4942 FD_ZERO (&Available);
4944 if (do_display)
4945 redisplay_preserve_echo_area (12);
4947 #ifdef EWOULDBLOCK
4948 else if (nread == -1 && errno == EWOULDBLOCK)
4950 #endif
4951 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4952 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4953 #ifdef O_NONBLOCK
4954 else if (nread == -1 && errno == EAGAIN)
4956 #else
4957 #ifdef O_NDELAY
4958 else if (nread == -1 && errno == EAGAIN)
4960 /* Note that we cannot distinguish between no input
4961 available now and a closed pipe.
4962 With luck, a closed pipe will be accompanied by
4963 subprocess termination and SIGCHLD. */
4964 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4966 #endif /* O_NDELAY */
4967 #endif /* O_NONBLOCK */
4968 #ifdef HAVE_PTYS
4969 /* On some OSs with ptys, when the process on one end of
4970 a pty exits, the other end gets an error reading with
4971 errno = EIO instead of getting an EOF (0 bytes read).
4972 Therefore, if we get an error reading and errno =
4973 EIO, just continue, because the child process has
4974 exited and should clean itself up soon (e.g. when we
4975 get a SIGCHLD).
4977 However, it has been known to happen that the SIGCHLD
4978 got lost. So raise the signal again just in case.
4979 It can't hurt. */
4980 else if (nread == -1 && errno == EIO)
4982 /* Clear the descriptor now, so we only raise the
4983 signal once. Don't do this if `process' is only
4984 a pty. */
4985 if (XPROCESS (proc)->pid != -2)
4987 FD_CLR (channel, &input_wait_mask);
4988 FD_CLR (channel, &non_keyboard_wait_mask);
4990 kill (getpid (), SIGCHLD);
4993 #endif /* HAVE_PTYS */
4994 /* If we can detect process termination, don't consider the process
4995 gone just because its pipe is closed. */
4996 #ifdef SIGCHLD
4997 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4999 #endif
5000 else
5002 /* Preserve status of processes already terminated. */
5003 XPROCESS (proc)->tick = ++process_tick;
5004 deactivate_process (proc);
5005 if (XPROCESS (proc)->raw_status_new)
5006 update_status (XPROCESS (proc));
5007 if (EQ (XPROCESS (proc)->status, Qrun))
5008 XPROCESS (proc)->status
5009 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5012 #ifdef NON_BLOCKING_CONNECT
5013 if (check_connect && FD_ISSET (channel, &Connecting)
5014 && FD_ISSET (channel, &connect_wait_mask))
5016 struct Lisp_Process *p;
5018 FD_CLR (channel, &connect_wait_mask);
5019 if (--num_pending_connects < 0)
5020 abort ();
5022 proc = chan_process[channel];
5023 if (NILP (proc))
5024 continue;
5026 p = XPROCESS (proc);
5028 #ifdef GNU_LINUX
5029 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5030 So only use it on systems where it is known to work. */
5032 int xlen = sizeof (xerrno);
5033 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5034 xerrno = errno;
5036 #else
5038 struct sockaddr pname;
5039 int pnamelen = sizeof (pname);
5041 /* If connection failed, getpeername will fail. */
5042 xerrno = 0;
5043 if (getpeername (channel, &pname, &pnamelen) < 0)
5045 /* Obtain connect failure code through error slippage. */
5046 char dummy;
5047 xerrno = errno;
5048 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5049 xerrno = errno;
5052 #endif
5053 if (xerrno)
5055 p->tick = ++process_tick;
5056 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5057 deactivate_process (proc);
5059 else
5061 p->status = Qrun;
5062 /* Execute the sentinel here. If we had relied on
5063 status_notify to do it later, it will read input
5064 from the process before calling the sentinel. */
5065 exec_sentinel (proc, build_string ("open\n"));
5066 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5068 FD_SET (p->infd, &input_wait_mask);
5069 FD_SET (p->infd, &non_keyboard_wait_mask);
5073 #endif /* NON_BLOCKING_CONNECT */
5074 } /* end for each file descriptor */
5075 } /* end while exit conditions not met */
5077 unbind_to (count, Qnil);
5079 /* If calling from keyboard input, do not quit
5080 since we want to return C-g as an input character.
5081 Otherwise, do pending quit if requested. */
5082 if (read_kbd >= 0)
5084 /* Prevent input_pending from remaining set if we quit. */
5085 clear_input_pending ();
5086 QUIT;
5089 return got_some_input;
5092 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5094 static Lisp_Object
5095 read_process_output_call (Lisp_Object fun_and_args)
5097 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5100 static Lisp_Object
5101 read_process_output_error_handler (Lisp_Object error)
5103 cmd_error_internal (error, "error in process filter: ");
5104 Vinhibit_quit = Qt;
5105 update_echo_area ();
5106 Fsleep_for (make_number (2), Qnil);
5107 return Qt;
5110 /* Read pending output from the process channel,
5111 starting with our buffered-ahead character if we have one.
5112 Yield number of decoded characters read.
5114 This function reads at most 4096 characters.
5115 If you want to read all available subprocess output,
5116 you must call it repeatedly until it returns zero.
5118 The characters read are decoded according to PROC's coding-system
5119 for decoding. */
5121 static int
5122 read_process_output (Lisp_Object proc, register int channel)
5124 register int nbytes;
5125 char *chars;
5126 register Lisp_Object outstream;
5127 register struct Lisp_Process *p = XPROCESS (proc);
5128 register int opoint;
5129 struct coding_system *coding = proc_decode_coding_system[channel];
5130 int carryover = p->decoding_carryover;
5131 int readmax = 4096;
5132 int count = SPECPDL_INDEX ();
5133 Lisp_Object odeactivate;
5135 chars = (char *) alloca (carryover + readmax);
5136 if (carryover)
5137 /* See the comment above. */
5138 memcpy (chars, SDATA (p->decoding_buf), carryover);
5140 #ifdef DATAGRAM_SOCKETS
5141 /* We have a working select, so proc_buffered_char is always -1. */
5142 if (DATAGRAM_CHAN_P (channel))
5144 int len = datagram_address[channel].len;
5145 nbytes = recvfrom (channel, chars + carryover, readmax,
5146 0, datagram_address[channel].sa, &len);
5148 else
5149 #endif
5150 if (proc_buffered_char[channel] < 0)
5152 nbytes = emacs_read (channel, chars + carryover, readmax);
5153 #ifdef ADAPTIVE_READ_BUFFERING
5154 if (nbytes > 0 && p->adaptive_read_buffering)
5156 int delay = p->read_output_delay;
5157 if (nbytes < 256)
5159 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5161 if (delay == 0)
5162 process_output_delay_count++;
5163 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5166 else if (delay > 0 && (nbytes == readmax))
5168 delay -= READ_OUTPUT_DELAY_INCREMENT;
5169 if (delay == 0)
5170 process_output_delay_count--;
5172 p->read_output_delay = delay;
5173 if (delay)
5175 p->read_output_skip = 1;
5176 process_output_skip = 1;
5179 #endif
5181 else
5183 chars[carryover] = proc_buffered_char[channel];
5184 proc_buffered_char[channel] = -1;
5185 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5186 if (nbytes < 0)
5187 nbytes = 1;
5188 else
5189 nbytes = nbytes + 1;
5192 p->decoding_carryover = 0;
5194 /* At this point, NBYTES holds number of bytes just received
5195 (including the one in proc_buffered_char[channel]). */
5196 if (nbytes <= 0)
5198 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5199 return nbytes;
5200 coding->mode |= CODING_MODE_LAST_BLOCK;
5203 /* Now set NBYTES how many bytes we must decode. */
5204 nbytes += carryover;
5206 odeactivate = Vdeactivate_mark;
5207 /* There's no good reason to let process filters change the current
5208 buffer, and many callers of accept-process-output, sit-for, and
5209 friends don't expect current-buffer to be changed from under them. */
5210 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5212 /* Read and dispose of the process output. */
5213 outstream = p->filter;
5214 if (!NILP (outstream))
5216 Lisp_Object obuffer, okeymap;
5217 Lisp_Object text;
5218 int outer_running_asynch_code = running_asynch_code;
5219 int waiting = waiting_for_user_input_p;
5221 /* No need to gcpro these, because all we do with them later
5222 is test them for EQness, and none of them should be a string. */
5223 XSETBUFFER (obuffer, current_buffer);
5224 okeymap = current_buffer->keymap;
5226 /* We inhibit quit here instead of just catching it so that
5227 hitting ^G when a filter happens to be running won't screw
5228 it up. */
5229 specbind (Qinhibit_quit, Qt);
5230 specbind (Qlast_nonmenu_event, Qt);
5232 /* In case we get recursively called,
5233 and we already saved the match data nonrecursively,
5234 save the same match data in safely recursive fashion. */
5235 if (outer_running_asynch_code)
5237 Lisp_Object tem;
5238 /* Don't clobber the CURRENT match data, either! */
5239 tem = Fmatch_data (Qnil, Qnil, Qnil);
5240 restore_search_regs ();
5241 record_unwind_save_match_data ();
5242 Fset_match_data (tem, Qt);
5245 /* For speed, if a search happens within this code,
5246 save the match data in a special nonrecursive fashion. */
5247 running_asynch_code = 1;
5249 decode_coding_c_string (coding, chars, nbytes, Qt);
5250 text = coding->dst_object;
5251 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5252 /* A new coding system might be found. */
5253 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5255 p->decode_coding_system = Vlast_coding_system_used;
5257 /* Don't call setup_coding_system for
5258 proc_decode_coding_system[channel] here. It is done in
5259 detect_coding called via decode_coding above. */
5261 /* If a coding system for encoding is not yet decided, we set
5262 it as the same as coding-system for decoding.
5264 But, before doing that we must check if
5265 proc_encode_coding_system[p->outfd] surely points to a
5266 valid memory because p->outfd will be changed once EOF is
5267 sent to the process. */
5268 if (NILP (p->encode_coding_system)
5269 && proc_encode_coding_system[p->outfd])
5271 p->encode_coding_system
5272 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5273 setup_coding_system (p->encode_coding_system,
5274 proc_encode_coding_system[p->outfd]);
5278 if (coding->carryover_bytes > 0)
5280 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5281 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5282 memcpy (SDATA (p->decoding_buf), coding->carryover,
5283 coding->carryover_bytes);
5284 p->decoding_carryover = coding->carryover_bytes;
5286 if (SBYTES (text) > 0)
5287 internal_condition_case_1 (read_process_output_call,
5288 Fcons (outstream,
5289 Fcons (proc, Fcons (text, Qnil))),
5290 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5291 read_process_output_error_handler);
5293 /* If we saved the match data nonrecursively, restore it now. */
5294 restore_search_regs ();
5295 running_asynch_code = outer_running_asynch_code;
5297 /* Restore waiting_for_user_input_p as it was
5298 when we were called, in case the filter clobbered it. */
5299 waiting_for_user_input_p = waiting;
5301 #if 0 /* Call record_asynch_buffer_change unconditionally,
5302 because we might have changed minor modes or other things
5303 that affect key bindings. */
5304 if (! EQ (Fcurrent_buffer (), obuffer)
5305 || ! EQ (current_buffer->keymap, okeymap))
5306 #endif
5307 /* But do it only if the caller is actually going to read events.
5308 Otherwise there's no need to make him wake up, and it could
5309 cause trouble (for example it would make sit_for return). */
5310 if (waiting_for_user_input_p == -1)
5311 record_asynch_buffer_change ();
5314 /* If no filter, write into buffer if it isn't dead. */
5315 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5317 Lisp_Object old_read_only;
5318 int old_begv, old_zv;
5319 int old_begv_byte, old_zv_byte;
5320 int before, before_byte;
5321 int opoint_byte;
5322 Lisp_Object text;
5323 struct buffer *b;
5325 Fset_buffer (p->buffer);
5326 opoint = PT;
5327 opoint_byte = PT_BYTE;
5328 old_read_only = current_buffer->read_only;
5329 old_begv = BEGV;
5330 old_zv = ZV;
5331 old_begv_byte = BEGV_BYTE;
5332 old_zv_byte = ZV_BYTE;
5334 current_buffer->read_only = Qnil;
5336 /* Insert new output into buffer
5337 at the current end-of-output marker,
5338 thus preserving logical ordering of input and output. */
5339 if (XMARKER (p->mark)->buffer)
5340 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5341 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5342 ZV_BYTE));
5343 else
5344 SET_PT_BOTH (ZV, ZV_BYTE);
5345 before = PT;
5346 before_byte = PT_BYTE;
5348 /* If the output marker is outside of the visible region, save
5349 the restriction and widen. */
5350 if (! (BEGV <= PT && PT <= ZV))
5351 Fwiden ();
5353 decode_coding_c_string (coding, chars, nbytes, Qt);
5354 text = coding->dst_object;
5355 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5356 /* A new coding system might be found. See the comment in the
5357 similar code in the previous `if' block. */
5358 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5360 p->decode_coding_system = Vlast_coding_system_used;
5361 if (NILP (p->encode_coding_system)
5362 && proc_encode_coding_system[p->outfd])
5364 p->encode_coding_system
5365 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5366 setup_coding_system (p->encode_coding_system,
5367 proc_encode_coding_system[p->outfd]);
5370 if (coding->carryover_bytes > 0)
5372 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5373 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5374 memcpy (SDATA (p->decoding_buf), coding->carryover,
5375 coding->carryover_bytes);
5376 p->decoding_carryover = coding->carryover_bytes;
5378 /* Adjust the multibyteness of TEXT to that of the buffer. */
5379 if (NILP (current_buffer->enable_multibyte_characters)
5380 != ! STRING_MULTIBYTE (text))
5381 text = (STRING_MULTIBYTE (text)
5382 ? Fstring_as_unibyte (text)
5383 : Fstring_to_multibyte (text));
5384 /* Insert before markers in case we are inserting where
5385 the buffer's mark is, and the user's next command is Meta-y. */
5386 insert_from_string_before_markers (text, 0, 0,
5387 SCHARS (text), SBYTES (text), 0);
5389 /* Make sure the process marker's position is valid when the
5390 process buffer is changed in the signal_after_change above.
5391 W3 is known to do that. */
5392 if (BUFFERP (p->buffer)
5393 && (b = XBUFFER (p->buffer), b != current_buffer))
5394 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5395 else
5396 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5398 update_mode_lines++;
5400 /* Make sure opoint and the old restrictions
5401 float ahead of any new text just as point would. */
5402 if (opoint >= before)
5404 opoint += PT - before;
5405 opoint_byte += PT_BYTE - before_byte;
5407 if (old_begv > before)
5409 old_begv += PT - before;
5410 old_begv_byte += PT_BYTE - before_byte;
5412 if (old_zv >= before)
5414 old_zv += PT - before;
5415 old_zv_byte += PT_BYTE - before_byte;
5418 /* If the restriction isn't what it should be, set it. */
5419 if (old_begv != BEGV || old_zv != ZV)
5420 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5423 current_buffer->read_only = old_read_only;
5424 SET_PT_BOTH (opoint, opoint_byte);
5426 /* Handling the process output should not deactivate the mark. */
5427 Vdeactivate_mark = odeactivate;
5429 unbind_to (count, Qnil);
5430 return nbytes;
5433 /* Sending data to subprocess */
5435 jmp_buf send_process_frame;
5436 Lisp_Object process_sent_to;
5438 SIGTYPE
5439 send_process_trap (int ignore)
5441 SIGNAL_THREAD_CHECK (SIGPIPE);
5442 sigunblock (sigmask (SIGPIPE));
5443 longjmp (send_process_frame, 1);
5446 /* Send some data to process PROC.
5447 BUF is the beginning of the data; LEN is the number of characters.
5448 OBJECT is the Lisp object that the data comes from. If OBJECT is
5449 nil or t, it means that the data comes from C string.
5451 If OBJECT is not nil, the data is encoded by PROC's coding-system
5452 for encoding before it is sent.
5454 This function can evaluate Lisp code and can garbage collect. */
5456 static void
5457 send_process (volatile Lisp_Object proc, unsigned char *volatile buf,
5458 volatile int len, volatile Lisp_Object object)
5460 /* Use volatile to protect variables from being clobbered by longjmp. */
5461 struct Lisp_Process *p = XPROCESS (proc);
5462 int rv;
5463 struct coding_system *coding;
5464 struct gcpro gcpro1;
5465 SIGTYPE (*volatile old_sigpipe) (int);
5467 GCPRO1 (object);
5469 if (p->raw_status_new)
5470 update_status (p);
5471 if (! EQ (p->status, Qrun))
5472 error ("Process %s not running", SDATA (p->name));
5473 if (p->outfd < 0)
5474 error ("Output file descriptor of %s is closed", SDATA (p->name));
5476 coding = proc_encode_coding_system[p->outfd];
5477 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5479 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5480 || (BUFFERP (object)
5481 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5482 || EQ (object, Qt))
5484 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5485 /* The coding system for encoding was changed to raw-text
5486 because we sent a unibyte text previously. Now we are
5487 sending a multibyte text, thus we must encode it by the
5488 original coding system specified for the current process. */
5489 setup_coding_system (p->encode_coding_system, coding);
5490 coding->src_multibyte = 1;
5492 else
5494 /* For sending a unibyte text, character code conversion should
5495 not take place but EOL conversion should. So, setup raw-text
5496 or one of the subsidiary if we have not yet done it. */
5497 if (CODING_REQUIRE_ENCODING (coding))
5499 if (CODING_REQUIRE_FLUSHING (coding))
5501 /* But, before changing the coding, we must flush out data. */
5502 coding->mode |= CODING_MODE_LAST_BLOCK;
5503 send_process (proc, "", 0, Qt);
5504 coding->mode &= CODING_MODE_LAST_BLOCK;
5506 setup_coding_system (raw_text_coding_system
5507 (Vlast_coding_system_used),
5508 coding);
5509 coding->src_multibyte = 0;
5512 coding->dst_multibyte = 0;
5514 if (CODING_REQUIRE_ENCODING (coding))
5516 coding->dst_object = Qt;
5517 if (BUFFERP (object))
5519 int from_byte, from, to;
5520 int save_pt, save_pt_byte;
5521 struct buffer *cur = current_buffer;
5523 set_buffer_internal (XBUFFER (object));
5524 save_pt = PT, save_pt_byte = PT_BYTE;
5526 from_byte = PTR_BYTE_POS (buf);
5527 from = BYTE_TO_CHAR (from_byte);
5528 to = BYTE_TO_CHAR (from_byte + len);
5529 TEMP_SET_PT_BOTH (from, from_byte);
5530 encode_coding_object (coding, object, from, from_byte,
5531 to, from_byte + len, Qt);
5532 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5533 set_buffer_internal (cur);
5535 else if (STRINGP (object))
5537 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5538 SBYTES (object), Qt);
5540 else
5542 coding->dst_object = make_unibyte_string (buf, len);
5543 coding->produced = len;
5546 len = coding->produced;
5547 object = coding->dst_object;
5548 buf = SDATA (object);
5551 if (pty_max_bytes == 0)
5553 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5554 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5555 if (pty_max_bytes < 0)
5556 pty_max_bytes = 250;
5557 #else
5558 pty_max_bytes = 250;
5559 #endif
5560 /* Deduct one, to leave space for the eof. */
5561 pty_max_bytes--;
5564 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5565 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5566 when returning with longjmp despite being declared volatile. */
5567 if (!setjmp (send_process_frame))
5569 process_sent_to = proc;
5570 while (len > 0)
5572 int this = len;
5574 /* Send this batch, using one or more write calls. */
5575 while (this > 0)
5577 int outfd = p->outfd;
5578 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5579 #ifdef DATAGRAM_SOCKETS
5580 if (DATAGRAM_CHAN_P (outfd))
5582 rv = sendto (outfd, (char *) buf, this,
5583 0, datagram_address[outfd].sa,
5584 datagram_address[outfd].len);
5585 if (rv < 0 && errno == EMSGSIZE)
5587 signal (SIGPIPE, old_sigpipe);
5588 report_file_error ("sending datagram",
5589 Fcons (proc, Qnil));
5592 else
5593 #endif
5595 rv = emacs_write (outfd, (char *) buf, this);
5596 #ifdef ADAPTIVE_READ_BUFFERING
5597 if (p->read_output_delay > 0
5598 && p->adaptive_read_buffering == 1)
5600 p->read_output_delay = 0;
5601 process_output_delay_count--;
5602 p->read_output_skip = 0;
5604 #endif
5606 signal (SIGPIPE, old_sigpipe);
5608 if (rv < 0)
5610 if (0
5611 #ifdef EWOULDBLOCK
5612 || errno == EWOULDBLOCK
5613 #endif
5614 #ifdef EAGAIN
5615 || errno == EAGAIN
5616 #endif
5618 /* Buffer is full. Wait, accepting input;
5619 that may allow the program
5620 to finish doing output and read more. */
5622 int offset = 0;
5624 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5625 /* A gross hack to work around a bug in FreeBSD.
5626 In the following sequence, read(2) returns
5627 bogus data:
5629 write(2) 1022 bytes
5630 write(2) 954 bytes, get EAGAIN
5631 read(2) 1024 bytes in process_read_output
5632 read(2) 11 bytes in process_read_output
5634 That is, read(2) returns more bytes than have
5635 ever been written successfully. The 1033 bytes
5636 read are the 1022 bytes written successfully
5637 after processing (for example with CRs added if
5638 the terminal is set up that way which it is
5639 here). The same bytes will be seen again in a
5640 later read(2), without the CRs. */
5642 if (errno == EAGAIN)
5644 int flags = FWRITE;
5645 ioctl (p->outfd, TIOCFLUSH, &flags);
5647 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5649 /* Running filters might relocate buffers or strings.
5650 Arrange to relocate BUF. */
5651 if (BUFFERP (object))
5652 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5653 else if (STRINGP (object))
5654 offset = buf - SDATA (object);
5656 #ifdef EMACS_HAS_USECS
5657 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5658 #else
5659 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5660 #endif
5662 if (BUFFERP (object))
5663 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5664 else if (STRINGP (object))
5665 buf = offset + SDATA (object);
5667 rv = 0;
5669 else
5670 /* This is a real error. */
5671 report_file_error ("writing to process", Fcons (proc, Qnil));
5673 buf += rv;
5674 len -= rv;
5675 this -= rv;
5679 else
5681 signal (SIGPIPE, old_sigpipe);
5682 proc = process_sent_to;
5683 p = XPROCESS (proc);
5684 p->raw_status_new = 0;
5685 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5686 p->tick = ++process_tick;
5687 deactivate_process (proc);
5688 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5691 UNGCPRO;
5694 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5695 3, 3, 0,
5696 doc: /* Send current contents of region as input to PROCESS.
5697 PROCESS may be a process, a buffer, the name of a process or buffer, or
5698 nil, indicating the current buffer's process.
5699 Called from program, takes three arguments, PROCESS, START and END.
5700 If the region is more than 500 characters long,
5701 it is sent in several bunches. This may happen even for shorter regions.
5702 Output from processes can arrive in between bunches. */)
5703 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5705 Lisp_Object proc;
5706 int start1, end1;
5708 proc = get_process (process);
5709 validate_region (&start, &end);
5711 if (XINT (start) < GPT && XINT (end) > GPT)
5712 move_gap (XINT (start));
5714 start1 = CHAR_TO_BYTE (XINT (start));
5715 end1 = CHAR_TO_BYTE (XINT (end));
5716 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5717 Fcurrent_buffer ());
5719 return Qnil;
5722 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5723 2, 2, 0,
5724 doc: /* Send PROCESS the contents of STRING as input.
5725 PROCESS may be a process, a buffer, the name of a process or buffer, or
5726 nil, indicating the current buffer's process.
5727 If STRING is more than 500 characters long,
5728 it is sent in several bunches. This may happen even for shorter strings.
5729 Output from processes can arrive in between bunches. */)
5730 (Lisp_Object process, Lisp_Object string)
5732 Lisp_Object proc;
5733 CHECK_STRING (string);
5734 proc = get_process (process);
5735 send_process (proc, SDATA (string),
5736 SBYTES (string), string);
5737 return Qnil;
5740 /* Return the foreground process group for the tty/pty that
5741 the process P uses. */
5742 static int
5743 emacs_get_tty_pgrp (struct Lisp_Process *p)
5745 int gid = -1;
5747 #ifdef TIOCGPGRP
5748 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5750 int fd;
5751 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5752 master side. Try the slave side. */
5753 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5755 if (fd != -1)
5757 ioctl (fd, TIOCGPGRP, &gid);
5758 emacs_close (fd);
5761 #endif /* defined (TIOCGPGRP ) */
5763 return gid;
5766 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5767 Sprocess_running_child_p, 0, 1, 0,
5768 doc: /* Return t if PROCESS has given the terminal to a child.
5769 If the operating system does not make it possible to find out,
5770 return t unconditionally. */)
5771 (Lisp_Object process)
5773 /* Initialize in case ioctl doesn't exist or gives an error,
5774 in a way that will cause returning t. */
5775 int gid;
5776 Lisp_Object proc;
5777 struct Lisp_Process *p;
5779 proc = get_process (process);
5780 p = XPROCESS (proc);
5782 if (!EQ (p->type, Qreal))
5783 error ("Process %s is not a subprocess",
5784 SDATA (p->name));
5785 if (p->infd < 0)
5786 error ("Process %s is not active",
5787 SDATA (p->name));
5789 gid = emacs_get_tty_pgrp (p);
5791 if (gid == p->pid)
5792 return Qnil;
5793 return Qt;
5796 /* send a signal number SIGNO to PROCESS.
5797 If CURRENT_GROUP is t, that means send to the process group
5798 that currently owns the terminal being used to communicate with PROCESS.
5799 This is used for various commands in shell mode.
5800 If CURRENT_GROUP is lambda, that means send to the process group
5801 that currently owns the terminal, but only if it is NOT the shell itself.
5803 If NOMSG is zero, insert signal-announcements into process's buffers
5804 right away.
5806 If we can, we try to signal PROCESS by sending control characters
5807 down the pty. This allows us to signal inferiors who have changed
5808 their uid, for which killpg would return an EPERM error. */
5810 static void
5811 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5812 int nomsg)
5814 Lisp_Object proc;
5815 register struct Lisp_Process *p;
5816 int gid;
5817 int no_pgrp = 0;
5819 proc = get_process (process);
5820 p = XPROCESS (proc);
5822 if (!EQ (p->type, Qreal))
5823 error ("Process %s is not a subprocess",
5824 SDATA (p->name));
5825 if (p->infd < 0)
5826 error ("Process %s is not active",
5827 SDATA (p->name));
5829 if (!p->pty_flag)
5830 current_group = Qnil;
5832 /* If we are using pgrps, get a pgrp number and make it negative. */
5833 if (NILP (current_group))
5834 /* Send the signal to the shell's process group. */
5835 gid = p->pid;
5836 else
5838 #ifdef SIGNALS_VIA_CHARACTERS
5839 /* If possible, send signals to the entire pgrp
5840 by sending an input character to it. */
5842 /* TERMIOS is the latest and bestest, and seems most likely to
5843 work. If the system has it, use it. */
5844 #ifdef HAVE_TERMIOS
5845 struct termios t;
5846 cc_t *sig_char = NULL;
5848 tcgetattr (p->infd, &t);
5850 switch (signo)
5852 case SIGINT:
5853 sig_char = &t.c_cc[VINTR];
5854 break;
5856 case SIGQUIT:
5857 sig_char = &t.c_cc[VQUIT];
5858 break;
5860 case SIGTSTP:
5861 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5862 sig_char = &t.c_cc[VSWTCH];
5863 #else
5864 sig_char = &t.c_cc[VSUSP];
5865 #endif
5866 break;
5869 if (sig_char && *sig_char != CDISABLE)
5871 send_process (proc, sig_char, 1, Qnil);
5872 return;
5874 /* If we can't send the signal with a character,
5875 fall through and send it another way. */
5876 #else /* ! HAVE_TERMIOS */
5878 /* On Berkeley descendants, the following IOCTL's retrieve the
5879 current control characters. */
5880 #if defined (TIOCGLTC) && defined (TIOCGETC)
5882 struct tchars c;
5883 struct ltchars lc;
5885 switch (signo)
5887 case SIGINT:
5888 ioctl (p->infd, TIOCGETC, &c);
5889 send_process (proc, &c.t_intrc, 1, Qnil);
5890 return;
5891 case SIGQUIT:
5892 ioctl (p->infd, TIOCGETC, &c);
5893 send_process (proc, &c.t_quitc, 1, Qnil);
5894 return;
5895 #ifdef SIGTSTP
5896 case SIGTSTP:
5897 ioctl (p->infd, TIOCGLTC, &lc);
5898 send_process (proc, &lc.t_suspc, 1, Qnil);
5899 return;
5900 #endif /* ! defined (SIGTSTP) */
5903 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5905 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5906 characters. */
5907 #ifdef TCGETA
5908 struct termio t;
5909 switch (signo)
5911 case SIGINT:
5912 ioctl (p->infd, TCGETA, &t);
5913 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5914 return;
5915 case SIGQUIT:
5916 ioctl (p->infd, TCGETA, &t);
5917 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5918 return;
5919 #ifdef SIGTSTP
5920 case SIGTSTP:
5921 ioctl (p->infd, TCGETA, &t);
5922 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5923 return;
5924 #endif /* ! defined (SIGTSTP) */
5926 #else /* ! defined (TCGETA) */
5927 Your configuration files are messed up.
5928 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5929 you'd better be using one of the alternatives above! */
5930 #endif /* ! defined (TCGETA) */
5931 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5932 /* In this case, the code above should alway return. */
5933 abort ();
5934 #endif /* ! defined HAVE_TERMIOS */
5936 /* The code above may fall through if it can't
5937 handle the signal. */
5938 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5940 #ifdef TIOCGPGRP
5941 /* Get the current pgrp using the tty itself, if we have that.
5942 Otherwise, use the pty to get the pgrp.
5943 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5944 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5945 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5946 His patch indicates that if TIOCGPGRP returns an error, then
5947 we should just assume that p->pid is also the process group id. */
5949 gid = emacs_get_tty_pgrp (p);
5951 if (gid == -1)
5952 /* If we can't get the information, assume
5953 the shell owns the tty. */
5954 gid = p->pid;
5956 /* It is not clear whether anything really can set GID to -1.
5957 Perhaps on some system one of those ioctls can or could do so.
5958 Or perhaps this is vestigial. */
5959 if (gid == -1)
5960 no_pgrp = 1;
5961 #else /* ! defined (TIOCGPGRP ) */
5962 /* Can't select pgrps on this system, so we know that
5963 the child itself heads the pgrp. */
5964 gid = p->pid;
5965 #endif /* ! defined (TIOCGPGRP ) */
5967 /* If current_group is lambda, and the shell owns the terminal,
5968 don't send any signal. */
5969 if (EQ (current_group, Qlambda) && gid == p->pid)
5970 return;
5973 switch (signo)
5975 #ifdef SIGCONT
5976 case SIGCONT:
5977 p->raw_status_new = 0;
5978 p->status = Qrun;
5979 p->tick = ++process_tick;
5980 if (!nomsg)
5982 status_notify (NULL);
5983 redisplay_preserve_echo_area (13);
5985 break;
5986 #endif /* ! defined (SIGCONT) */
5987 case SIGINT:
5988 case SIGQUIT:
5989 case SIGKILL:
5990 flush_pending_output (p->infd);
5991 break;
5994 /* If we don't have process groups, send the signal to the immediate
5995 subprocess. That isn't really right, but it's better than any
5996 obvious alternative. */
5997 if (no_pgrp)
5999 kill (p->pid, signo);
6000 return;
6003 /* gid may be a pid, or minus a pgrp's number */
6004 #ifdef TIOCSIGSEND
6005 if (!NILP (current_group))
6007 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6008 EMACS_KILLPG (gid, signo);
6010 else
6012 gid = - p->pid;
6013 kill (gid, signo);
6015 #else /* ! defined (TIOCSIGSEND) */
6016 EMACS_KILLPG (gid, signo);
6017 #endif /* ! defined (TIOCSIGSEND) */
6020 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6021 doc: /* Interrupt process PROCESS.
6022 PROCESS may be a process, a buffer, or the name of a process or buffer.
6023 No arg or nil means current buffer's process.
6024 Second arg CURRENT-GROUP non-nil means send signal to
6025 the current process-group of the process's controlling terminal
6026 rather than to the process's own process group.
6027 If the process is a shell, this means interrupt current subjob
6028 rather than the shell.
6030 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6031 don't send the signal. */)
6032 (Lisp_Object process, Lisp_Object current_group)
6034 process_send_signal (process, SIGINT, current_group, 0);
6035 return process;
6038 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6039 doc: /* Kill process PROCESS. May be process or name of one.
6040 See function `interrupt-process' for more details on usage. */)
6041 (Lisp_Object process, Lisp_Object current_group)
6043 process_send_signal (process, SIGKILL, current_group, 0);
6044 return process;
6047 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6048 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6049 See function `interrupt-process' for more details on usage. */)
6050 (Lisp_Object process, Lisp_Object current_group)
6052 process_send_signal (process, SIGQUIT, current_group, 0);
6053 return process;
6056 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6057 doc: /* Stop process PROCESS. May be process or name of one.
6058 See function `interrupt-process' for more details on usage.
6059 If PROCESS is a network or serial process, inhibit handling of incoming
6060 traffic. */)
6061 (Lisp_Object process, Lisp_Object current_group)
6063 #ifdef HAVE_SOCKETS
6064 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6066 struct Lisp_Process *p;
6068 p = XPROCESS (process);
6069 if (NILP (p->command)
6070 && p->infd >= 0)
6072 FD_CLR (p->infd, &input_wait_mask);
6073 FD_CLR (p->infd, &non_keyboard_wait_mask);
6075 p->command = Qt;
6076 return process;
6078 #endif
6079 #ifndef SIGTSTP
6080 error ("No SIGTSTP support");
6081 #else
6082 process_send_signal (process, SIGTSTP, current_group, 0);
6083 #endif
6084 return process;
6087 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6088 doc: /* Continue process PROCESS. May be process or name of one.
6089 See function `interrupt-process' for more details on usage.
6090 If PROCESS is a network or serial process, resume handling of incoming
6091 traffic. */)
6092 (Lisp_Object process, Lisp_Object current_group)
6094 #ifdef HAVE_SOCKETS
6095 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6097 struct Lisp_Process *p;
6099 p = XPROCESS (process);
6100 if (EQ (p->command, Qt)
6101 && p->infd >= 0
6102 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6104 FD_SET (p->infd, &input_wait_mask);
6105 FD_SET (p->infd, &non_keyboard_wait_mask);
6106 #ifdef WINDOWSNT
6107 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6108 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6109 #endif
6110 #ifdef HAVE_TERMIOS
6111 tcflush (p->infd, TCIFLUSH);
6112 #endif
6114 p->command = Qnil;
6115 return process;
6117 #endif
6118 #ifdef SIGCONT
6119 process_send_signal (process, SIGCONT, current_group, 0);
6120 #else
6121 error ("No SIGCONT support");
6122 #endif
6123 return process;
6126 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6127 2, 2, "sProcess (name or number): \nnSignal code: ",
6128 doc: /* Send PROCESS the signal with code SIGCODE.
6129 PROCESS may also be a number specifying the process id of the
6130 process to signal; in this case, the process need not be a child of
6131 this Emacs.
6132 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6133 (Lisp_Object process, Lisp_Object sigcode)
6135 pid_t pid;
6137 if (INTEGERP (process))
6139 pid = XINT (process);
6140 goto got_it;
6143 if (FLOATP (process))
6145 pid = (pid_t) XFLOAT_DATA (process);
6146 goto got_it;
6149 if (STRINGP (process))
6151 Lisp_Object tem;
6152 if (tem = Fget_process (process), NILP (tem))
6154 pid = XINT (Fstring_to_number (process, make_number (10)));
6155 if (pid > 0)
6156 goto got_it;
6158 process = tem;
6160 else
6161 process = get_process (process);
6163 if (NILP (process))
6164 return process;
6166 CHECK_PROCESS (process);
6167 pid = XPROCESS (process)->pid;
6168 if (pid <= 0)
6169 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6171 got_it:
6173 #define parse_signal(NAME, VALUE) \
6174 else if (!xstrcasecmp (name, NAME)) \
6175 XSETINT (sigcode, VALUE)
6177 if (INTEGERP (sigcode))
6179 else
6181 unsigned char *name;
6183 CHECK_SYMBOL (sigcode);
6184 name = SDATA (SYMBOL_NAME (sigcode));
6186 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6187 name += 3;
6189 if (0)
6191 #ifdef SIGUSR1
6192 parse_signal ("usr1", SIGUSR1);
6193 #endif
6194 #ifdef SIGUSR2
6195 parse_signal ("usr2", SIGUSR2);
6196 #endif
6197 #ifdef SIGTERM
6198 parse_signal ("term", SIGTERM);
6199 #endif
6200 #ifdef SIGHUP
6201 parse_signal ("hup", SIGHUP);
6202 #endif
6203 #ifdef SIGINT
6204 parse_signal ("int", SIGINT);
6205 #endif
6206 #ifdef SIGQUIT
6207 parse_signal ("quit", SIGQUIT);
6208 #endif
6209 #ifdef SIGILL
6210 parse_signal ("ill", SIGILL);
6211 #endif
6212 #ifdef SIGABRT
6213 parse_signal ("abrt", SIGABRT);
6214 #endif
6215 #ifdef SIGEMT
6216 parse_signal ("emt", SIGEMT);
6217 #endif
6218 #ifdef SIGKILL
6219 parse_signal ("kill", SIGKILL);
6220 #endif
6221 #ifdef SIGFPE
6222 parse_signal ("fpe", SIGFPE);
6223 #endif
6224 #ifdef SIGBUS
6225 parse_signal ("bus", SIGBUS);
6226 #endif
6227 #ifdef SIGSEGV
6228 parse_signal ("segv", SIGSEGV);
6229 #endif
6230 #ifdef SIGSYS
6231 parse_signal ("sys", SIGSYS);
6232 #endif
6233 #ifdef SIGPIPE
6234 parse_signal ("pipe", SIGPIPE);
6235 #endif
6236 #ifdef SIGALRM
6237 parse_signal ("alrm", SIGALRM);
6238 #endif
6239 #ifdef SIGURG
6240 parse_signal ("urg", SIGURG);
6241 #endif
6242 #ifdef SIGSTOP
6243 parse_signal ("stop", SIGSTOP);
6244 #endif
6245 #ifdef SIGTSTP
6246 parse_signal ("tstp", SIGTSTP);
6247 #endif
6248 #ifdef SIGCONT
6249 parse_signal ("cont", SIGCONT);
6250 #endif
6251 #ifdef SIGCHLD
6252 parse_signal ("chld", SIGCHLD);
6253 #endif
6254 #ifdef SIGTTIN
6255 parse_signal ("ttin", SIGTTIN);
6256 #endif
6257 #ifdef SIGTTOU
6258 parse_signal ("ttou", SIGTTOU);
6259 #endif
6260 #ifdef SIGIO
6261 parse_signal ("io", SIGIO);
6262 #endif
6263 #ifdef SIGXCPU
6264 parse_signal ("xcpu", SIGXCPU);
6265 #endif
6266 #ifdef SIGXFSZ
6267 parse_signal ("xfsz", SIGXFSZ);
6268 #endif
6269 #ifdef SIGVTALRM
6270 parse_signal ("vtalrm", SIGVTALRM);
6271 #endif
6272 #ifdef SIGPROF
6273 parse_signal ("prof", SIGPROF);
6274 #endif
6275 #ifdef SIGWINCH
6276 parse_signal ("winch", SIGWINCH);
6277 #endif
6278 #ifdef SIGINFO
6279 parse_signal ("info", SIGINFO);
6280 #endif
6281 else
6282 error ("Undefined signal name %s", name);
6285 #undef parse_signal
6287 return make_number (kill (pid, XINT (sigcode)));
6290 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6291 doc: /* Make PROCESS see end-of-file in its input.
6292 EOF comes after any text already sent to it.
6293 PROCESS may be a process, a buffer, the name of a process or buffer, or
6294 nil, indicating the current buffer's process.
6295 If PROCESS is a network connection, or is a process communicating
6296 through a pipe (as opposed to a pty), then you cannot send any more
6297 text to PROCESS after you call this function.
6298 If PROCESS is a serial process, wait until all output written to the
6299 process has been transmitted to the serial port. */)
6300 (Lisp_Object process)
6302 Lisp_Object proc;
6303 struct coding_system *coding;
6305 if (DATAGRAM_CONN_P (process))
6306 return process;
6308 proc = get_process (process);
6309 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6311 /* Make sure the process is really alive. */
6312 if (XPROCESS (proc)->raw_status_new)
6313 update_status (XPROCESS (proc));
6314 if (! EQ (XPROCESS (proc)->status, Qrun))
6315 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6317 if (CODING_REQUIRE_FLUSHING (coding))
6319 coding->mode |= CODING_MODE_LAST_BLOCK;
6320 send_process (proc, "", 0, Qnil);
6323 if (XPROCESS (proc)->pty_flag)
6324 send_process (proc, "\004", 1, Qnil);
6325 else if (EQ (XPROCESS (proc)->type, Qserial))
6327 #ifdef HAVE_TERMIOS
6328 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6329 error ("tcdrain() failed: %s", emacs_strerror (errno));
6330 #endif
6331 /* Do nothing on Windows because writes are blocking. */
6333 else
6335 int old_outfd, new_outfd;
6337 #ifdef HAVE_SHUTDOWN
6338 /* If this is a network connection, or socketpair is used
6339 for communication with the subprocess, call shutdown to cause EOF.
6340 (In some old system, shutdown to socketpair doesn't work.
6341 Then we just can't win.) */
6342 if (EQ (XPROCESS (proc)->type, Qnetwork)
6343 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6344 shutdown (XPROCESS (proc)->outfd, 1);
6345 /* In case of socketpair, outfd == infd, so don't close it. */
6346 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6347 emacs_close (XPROCESS (proc)->outfd);
6348 #else /* not HAVE_SHUTDOWN */
6349 emacs_close (XPROCESS (proc)->outfd);
6350 #endif /* not HAVE_SHUTDOWN */
6351 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6352 if (new_outfd < 0)
6353 abort ();
6354 old_outfd = XPROCESS (proc)->outfd;
6356 if (!proc_encode_coding_system[new_outfd])
6357 proc_encode_coding_system[new_outfd]
6358 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6359 memcpy (proc_encode_coding_system[new_outfd],
6360 proc_encode_coding_system[old_outfd],
6361 sizeof (struct coding_system));
6362 memset (proc_encode_coding_system[old_outfd], 0,
6363 sizeof (struct coding_system));
6365 XPROCESS (proc)->outfd = new_outfd;
6367 return process;
6370 /* On receipt of a signal that a child status has changed, loop asking
6371 about children with changed statuses until the system says there
6372 are no more.
6374 All we do is change the status; we do not run sentinels or print
6375 notifications. That is saved for the next time keyboard input is
6376 done, in order to avoid timing errors.
6378 ** WARNING: this can be called during garbage collection.
6379 Therefore, it must not be fooled by the presence of mark bits in
6380 Lisp objects.
6382 ** USG WARNING: Although it is not obvious from the documentation
6383 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6384 signal() before executing at least one wait(), otherwise the
6385 handler will be called again, resulting in an infinite loop. The
6386 relevant portion of the documentation reads "SIGCLD signals will be
6387 queued and the signal-catching function will be continually
6388 reentered until the queue is empty". Invoking signal() causes the
6389 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6390 Inc.
6392 ** Malloc WARNING: This should never call malloc either directly or
6393 indirectly; if it does, that is a bug */
6395 #ifdef SIGCHLD
6396 SIGTYPE
6397 sigchld_handler (int signo)
6399 int old_errno = errno;
6400 Lisp_Object proc;
6401 register struct Lisp_Process *p;
6402 extern EMACS_TIME *input_available_clear_time;
6404 SIGNAL_THREAD_CHECK (signo);
6406 while (1)
6408 pid_t pid;
6409 int w;
6410 Lisp_Object tail;
6412 #ifdef WNOHANG
6413 #ifndef WUNTRACED
6414 #define WUNTRACED 0
6415 #endif /* no WUNTRACED */
6416 /* Keep trying to get a status until we get a definitive result. */
6419 errno = 0;
6420 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6422 while (pid < 0 && errno == EINTR);
6424 if (pid <= 0)
6426 /* PID == 0 means no processes found, PID == -1 means a real
6427 failure. We have done all our job, so return. */
6429 errno = old_errno;
6430 return;
6432 #else
6433 pid = wait (&w);
6434 #endif /* no WNOHANG */
6436 /* Find the process that signaled us, and record its status. */
6438 /* The process can have been deleted by Fdelete_process. */
6439 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6441 Lisp_Object xpid = XCAR (tail);
6442 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6443 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6445 XSETCAR (tail, Qnil);
6446 goto sigchld_end_of_loop;
6450 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6451 p = 0;
6452 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6454 proc = XCDR (XCAR (tail));
6455 p = XPROCESS (proc);
6456 if (EQ (p->type, Qreal) && p->pid == pid)
6457 break;
6458 p = 0;
6461 /* Look for an asynchronous process whose pid hasn't been filled
6462 in yet. */
6463 if (p == 0)
6464 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6466 proc = XCDR (XCAR (tail));
6467 p = XPROCESS (proc);
6468 if (p->pid == -1)
6469 break;
6470 p = 0;
6473 /* Change the status of the process that was found. */
6474 if (p != 0)
6476 int clear_desc_flag = 0;
6478 p->tick = ++process_tick;
6479 p->raw_status = w;
6480 p->raw_status_new = 1;
6482 /* If process has terminated, stop waiting for its output. */
6483 if ((WIFSIGNALED (w) || WIFEXITED (w))
6484 && p->infd >= 0)
6485 clear_desc_flag = 1;
6487 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6488 if (clear_desc_flag)
6490 FD_CLR (p->infd, &input_wait_mask);
6491 FD_CLR (p->infd, &non_keyboard_wait_mask);
6494 /* Tell wait_reading_process_output that it needs to wake up and
6495 look around. */
6496 if (input_available_clear_time)
6497 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6500 /* There was no asynchronous process found for that pid: we have
6501 a synchronous process. */
6502 else
6504 synch_process_alive = 0;
6506 /* Report the status of the synchronous process. */
6507 if (WIFEXITED (w))
6508 synch_process_retcode = WRETCODE (w);
6509 else if (WIFSIGNALED (w))
6510 synch_process_termsig = WTERMSIG (w);
6512 /* Tell wait_reading_process_output that it needs to wake up and
6513 look around. */
6514 if (input_available_clear_time)
6515 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6518 sigchld_end_of_loop:
6521 /* On some systems, we must return right away.
6522 If any more processes want to signal us, we will
6523 get another signal.
6524 Otherwise (on systems that have WNOHANG), loop around
6525 to use up all the processes that have something to tell us. */
6526 #if (defined WINDOWSNT \
6527 || (defined USG && !defined GNU_LINUX \
6528 && !(defined HPUX && defined WNOHANG)))
6529 errno = old_errno;
6530 return;
6531 #endif /* USG, but not HPUX with WNOHANG */
6534 #endif /* SIGCHLD */
6537 static Lisp_Object
6538 exec_sentinel_unwind (Lisp_Object data)
6540 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6541 return Qnil;
6544 static Lisp_Object
6545 exec_sentinel_error_handler (Lisp_Object error)
6547 cmd_error_internal (error, "error in process sentinel: ");
6548 Vinhibit_quit = Qt;
6549 update_echo_area ();
6550 Fsleep_for (make_number (2), Qnil);
6551 return Qt;
6554 static void
6555 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6557 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6558 register struct Lisp_Process *p = XPROCESS (proc);
6559 int count = SPECPDL_INDEX ();
6560 int outer_running_asynch_code = running_asynch_code;
6561 int waiting = waiting_for_user_input_p;
6563 if (inhibit_sentinels)
6564 return;
6566 /* No need to gcpro these, because all we do with them later
6567 is test them for EQness, and none of them should be a string. */
6568 odeactivate = Vdeactivate_mark;
6569 XSETBUFFER (obuffer, current_buffer);
6570 okeymap = current_buffer->keymap;
6572 /* There's no good reason to let sentinels change the current
6573 buffer, and many callers of accept-process-output, sit-for, and
6574 friends don't expect current-buffer to be changed from under them. */
6575 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6577 sentinel = p->sentinel;
6578 if (NILP (sentinel))
6579 return;
6581 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6582 assure that it gets restored no matter how the sentinel exits. */
6583 p->sentinel = Qnil;
6584 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6585 /* Inhibit quit so that random quits don't screw up a running filter. */
6586 specbind (Qinhibit_quit, Qt);
6587 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6589 /* In case we get recursively called,
6590 and we already saved the match data nonrecursively,
6591 save the same match data in safely recursive fashion. */
6592 if (outer_running_asynch_code)
6594 Lisp_Object tem;
6595 tem = Fmatch_data (Qnil, Qnil, Qnil);
6596 restore_search_regs ();
6597 record_unwind_save_match_data ();
6598 Fset_match_data (tem, Qt);
6601 /* For speed, if a search happens within this code,
6602 save the match data in a special nonrecursive fashion. */
6603 running_asynch_code = 1;
6605 internal_condition_case_1 (read_process_output_call,
6606 Fcons (sentinel,
6607 Fcons (proc, Fcons (reason, Qnil))),
6608 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6609 exec_sentinel_error_handler);
6611 /* If we saved the match data nonrecursively, restore it now. */
6612 restore_search_regs ();
6613 running_asynch_code = outer_running_asynch_code;
6615 Vdeactivate_mark = odeactivate;
6617 /* Restore waiting_for_user_input_p as it was
6618 when we were called, in case the filter clobbered it. */
6619 waiting_for_user_input_p = waiting;
6621 #if 0
6622 if (! EQ (Fcurrent_buffer (), obuffer)
6623 || ! EQ (current_buffer->keymap, okeymap))
6624 #endif
6625 /* But do it only if the caller is actually going to read events.
6626 Otherwise there's no need to make him wake up, and it could
6627 cause trouble (for example it would make sit_for return). */
6628 if (waiting_for_user_input_p == -1)
6629 record_asynch_buffer_change ();
6631 unbind_to (count, Qnil);
6634 /* Report all recent events of a change in process status
6635 (either run the sentinel or output a message).
6636 This is usually done while Emacs is waiting for keyboard input
6637 but can be done at other times. */
6639 static void
6640 status_notify (struct Lisp_Process *deleting_process)
6642 register Lisp_Object proc, buffer;
6643 Lisp_Object tail, msg;
6644 struct gcpro gcpro1, gcpro2;
6646 tail = Qnil;
6647 msg = Qnil;
6648 /* We need to gcpro tail; if read_process_output calls a filter
6649 which deletes a process and removes the cons to which tail points
6650 from Vprocess_alist, and then causes a GC, tail is an unprotected
6651 reference. */
6652 GCPRO2 (tail, msg);
6654 /* Set this now, so that if new processes are created by sentinels
6655 that we run, we get called again to handle their status changes. */
6656 update_tick = process_tick;
6658 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6660 Lisp_Object symbol;
6661 register struct Lisp_Process *p;
6663 proc = Fcdr (XCAR (tail));
6664 p = XPROCESS (proc);
6666 if (p->tick != p->update_tick)
6668 p->update_tick = p->tick;
6670 /* If process is still active, read any output that remains. */
6671 while (! EQ (p->filter, Qt)
6672 && ! EQ (p->status, Qconnect)
6673 && ! EQ (p->status, Qlisten)
6674 /* Network or serial process not stopped: */
6675 && ! EQ (p->command, Qt)
6676 && p->infd >= 0
6677 && p != deleting_process
6678 && read_process_output (proc, p->infd) > 0);
6680 buffer = p->buffer;
6682 /* Get the text to use for the message. */
6683 if (p->raw_status_new)
6684 update_status (p);
6685 msg = status_message (p);
6687 /* If process is terminated, deactivate it or delete it. */
6688 symbol = p->status;
6689 if (CONSP (p->status))
6690 symbol = XCAR (p->status);
6692 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6693 || EQ (symbol, Qclosed))
6695 if (delete_exited_processes)
6696 remove_process (proc);
6697 else
6698 deactivate_process (proc);
6701 /* The actions above may have further incremented p->tick.
6702 So set p->update_tick again
6703 so that an error in the sentinel will not cause
6704 this code to be run again. */
6705 p->update_tick = p->tick;
6706 /* Now output the message suitably. */
6707 if (!NILP (p->sentinel))
6708 exec_sentinel (proc, msg);
6709 /* Don't bother with a message in the buffer
6710 when a process becomes runnable. */
6711 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6713 Lisp_Object tem;
6714 struct buffer *old = current_buffer;
6715 int opoint, opoint_byte;
6716 int before, before_byte;
6718 /* Avoid error if buffer is deleted
6719 (probably that's why the process is dead, too) */
6720 if (NILP (XBUFFER (buffer)->name))
6721 continue;
6722 Fset_buffer (buffer);
6724 opoint = PT;
6725 opoint_byte = PT_BYTE;
6726 /* Insert new output into buffer
6727 at the current end-of-output marker,
6728 thus preserving logical ordering of input and output. */
6729 if (XMARKER (p->mark)->buffer)
6730 Fgoto_char (p->mark);
6731 else
6732 SET_PT_BOTH (ZV, ZV_BYTE);
6734 before = PT;
6735 before_byte = PT_BYTE;
6737 tem = current_buffer->read_only;
6738 current_buffer->read_only = Qnil;
6739 insert_string ("\nProcess ");
6740 Finsert (1, &p->name);
6741 insert_string (" ");
6742 Finsert (1, &msg);
6743 current_buffer->read_only = tem;
6744 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6746 if (opoint >= before)
6747 SET_PT_BOTH (opoint + (PT - before),
6748 opoint_byte + (PT_BYTE - before_byte));
6749 else
6750 SET_PT_BOTH (opoint, opoint_byte);
6752 set_buffer_internal (old);
6755 } /* end for */
6757 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6758 UNGCPRO;
6762 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6763 Sset_process_coding_system, 1, 3, 0,
6764 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6765 DECODING will be used to decode subprocess output and ENCODING to
6766 encode subprocess input. */)
6767 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6769 register struct Lisp_Process *p;
6771 CHECK_PROCESS (process);
6772 p = XPROCESS (process);
6773 if (p->infd < 0)
6774 error ("Input file descriptor of %s closed", SDATA (p->name));
6775 if (p->outfd < 0)
6776 error ("Output file descriptor of %s closed", SDATA (p->name));
6777 Fcheck_coding_system (decoding);
6778 Fcheck_coding_system (encoding);
6779 encoding = coding_inherit_eol_type (encoding, Qnil);
6780 p->decode_coding_system = decoding;
6781 p->encode_coding_system = encoding;
6782 setup_process_coding_systems (process);
6784 return Qnil;
6787 DEFUN ("process-coding-system",
6788 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6789 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6790 (register Lisp_Object process)
6792 CHECK_PROCESS (process);
6793 return Fcons (XPROCESS (process)->decode_coding_system,
6794 XPROCESS (process)->encode_coding_system);
6797 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6798 Sset_process_filter_multibyte, 2, 2, 0,
6799 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6800 If FLAG is non-nil, the filter is given multibyte strings.
6801 If FLAG is nil, the filter is given unibyte strings. In this case,
6802 all character code conversion except for end-of-line conversion is
6803 suppressed. */)
6804 (Lisp_Object process, Lisp_Object flag)
6806 register struct Lisp_Process *p;
6808 CHECK_PROCESS (process);
6809 p = XPROCESS (process);
6810 if (NILP (flag))
6811 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6812 setup_process_coding_systems (process);
6814 return Qnil;
6817 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6818 Sprocess_filter_multibyte_p, 1, 1, 0,
6819 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6820 (Lisp_Object process)
6822 register struct Lisp_Process *p;
6823 struct coding_system *coding;
6825 CHECK_PROCESS (process);
6826 p = XPROCESS (process);
6827 coding = proc_decode_coding_system[p->infd];
6828 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6834 static int add_gpm_wait_descriptor_called_flag;
6836 void
6837 add_gpm_wait_descriptor (int desc)
6839 if (! add_gpm_wait_descriptor_called_flag)
6840 FD_CLR (0, &input_wait_mask);
6841 add_gpm_wait_descriptor_called_flag = 1;
6842 FD_SET (desc, &input_wait_mask);
6843 FD_SET (desc, &gpm_wait_mask);
6844 if (desc > max_gpm_desc)
6845 max_gpm_desc = desc;
6848 void
6849 delete_gpm_wait_descriptor (int desc)
6851 int fd;
6852 int lim = max_gpm_desc;
6854 FD_CLR (desc, &input_wait_mask);
6855 FD_CLR (desc, &non_process_wait_mask);
6857 if (desc == max_gpm_desc)
6858 for (fd = 0; fd < lim; fd++)
6859 if (FD_ISSET (fd, &input_wait_mask)
6860 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6861 && !FD_ISSET (fd, &non_process_wait_mask))
6862 max_gpm_desc = fd;
6865 /* Return nonzero if *MASK has a bit set
6866 that corresponds to one of the keyboard input descriptors. */
6868 static int
6869 keyboard_bit_set (fd_set *mask)
6871 int fd;
6873 for (fd = 0; fd <= max_keyboard_desc; fd++)
6874 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6875 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6876 return 1;
6878 return 0;
6881 #else /* not subprocesses */
6883 /* Defined on msdos.c. */
6884 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6885 EMACS_TIME *);
6887 /* Implementation of wait_reading_process_output, assuming that there
6888 are no subprocesses. Used only by the MS-DOS build.
6890 Wait for timeout to elapse and/or keyboard input to be available.
6892 time_limit is:
6893 timeout in seconds, or
6894 zero for no limit, or
6895 -1 means gobble data immediately available but don't wait for any.
6897 read_kbd is a Lisp_Object:
6898 0 to ignore keyboard input, or
6899 1 to return when input is available, or
6900 -1 means caller will actually read the input, so don't throw to
6901 the quit handler.
6903 see full version for other parameters. We know that wait_proc will
6904 always be NULL, since `subprocesses' isn't defined.
6906 do_display != 0 means redisplay should be done to show subprocess
6907 output that arrives.
6909 Return true if we received input from any process. */
6912 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6913 int do_display,
6914 Lisp_Object wait_for_cell,
6915 struct Lisp_Process *wait_proc, int just_wait_proc)
6917 register int nfds;
6918 EMACS_TIME end_time, timeout;
6919 SELECT_TYPE waitchannels;
6920 int xerrno;
6922 /* What does time_limit really mean? */
6923 if (time_limit || microsecs)
6925 EMACS_GET_TIME (end_time);
6926 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6927 EMACS_ADD_TIME (end_time, end_time, timeout);
6930 /* Turn off periodic alarms (in case they are in use)
6931 and then turn off any other atimers,
6932 because the select emulator uses alarms. */
6933 stop_polling ();
6934 turn_on_atimers (0);
6936 while (1)
6938 int timeout_reduced_for_timers = 0;
6940 /* If calling from keyboard input, do not quit
6941 since we want to return C-g as an input character.
6942 Otherwise, do pending quit if requested. */
6943 if (read_kbd >= 0)
6944 QUIT;
6946 /* Exit now if the cell we're waiting for became non-nil. */
6947 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6948 break;
6950 /* Compute time from now till when time limit is up */
6951 /* Exit if already run out */
6952 if (time_limit == -1)
6954 /* -1 specified for timeout means
6955 gobble output available now
6956 but don't wait at all. */
6958 EMACS_SET_SECS_USECS (timeout, 0, 0);
6960 else if (time_limit || microsecs)
6962 EMACS_GET_TIME (timeout);
6963 EMACS_SUB_TIME (timeout, end_time, timeout);
6964 if (EMACS_TIME_NEG_P (timeout))
6965 break;
6967 else
6969 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6972 /* If our caller will not immediately handle keyboard events,
6973 run timer events directly.
6974 (Callers that will immediately read keyboard events
6975 call timer_delay on their own.) */
6976 if (NILP (wait_for_cell))
6978 EMACS_TIME timer_delay;
6982 int old_timers_run = timers_run;
6983 timer_delay = timer_check (1);
6984 if (timers_run != old_timers_run && do_display)
6985 /* We must retry, since a timer may have requeued itself
6986 and that could alter the time delay. */
6987 redisplay_preserve_echo_area (14);
6988 else
6989 break;
6991 while (!detect_input_pending ());
6993 /* If there is unread keyboard input, also return. */
6994 if (read_kbd != 0
6995 && requeued_events_pending_p ())
6996 break;
6998 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7000 EMACS_TIME difference;
7001 EMACS_SUB_TIME (difference, timer_delay, timeout);
7002 if (EMACS_TIME_NEG_P (difference))
7004 timeout = timer_delay;
7005 timeout_reduced_for_timers = 1;
7010 /* Cause C-g and alarm signals to take immediate action,
7011 and cause input available signals to zero out timeout. */
7012 if (read_kbd < 0)
7013 set_waiting_for_input (&timeout);
7015 /* Wait till there is something to do. */
7017 if (! read_kbd && NILP (wait_for_cell))
7018 FD_ZERO (&waitchannels);
7019 else
7020 FD_SET (0, &waitchannels);
7022 /* If a frame has been newly mapped and needs updating,
7023 reprocess its display stuff. */
7024 if (frame_garbaged && do_display)
7026 clear_waiting_for_input ();
7027 redisplay_preserve_echo_area (15);
7028 if (read_kbd < 0)
7029 set_waiting_for_input (&timeout);
7032 if (read_kbd && detect_input_pending ())
7034 nfds = 0;
7035 FD_ZERO (&waitchannels);
7037 else
7038 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7039 &timeout);
7041 xerrno = errno;
7043 /* Make C-g and alarm signals set flags again */
7044 clear_waiting_for_input ();
7046 /* If we woke up due to SIGWINCH, actually change size now. */
7047 do_pending_window_change (0);
7049 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7050 /* We waited the full specified time, so return now. */
7051 break;
7053 if (nfds == -1)
7055 /* If the system call was interrupted, then go around the
7056 loop again. */
7057 if (xerrno == EINTR)
7058 FD_ZERO (&waitchannels);
7059 else
7060 error ("select error: %s", emacs_strerror (xerrno));
7063 /* Check for keyboard input */
7065 if (read_kbd
7066 && detect_input_pending_run_timers (do_display))
7068 swallow_events (do_display);
7069 if (detect_input_pending_run_timers (do_display))
7070 break;
7073 /* If there is unread keyboard input, also return. */
7074 if (read_kbd
7075 && requeued_events_pending_p ())
7076 break;
7078 /* If wait_for_cell. check for keyboard input
7079 but don't run any timers.
7080 ??? (It seems wrong to me to check for keyboard
7081 input at all when wait_for_cell, but the code
7082 has been this way since July 1994.
7083 Try changing this after version 19.31.) */
7084 if (! NILP (wait_for_cell)
7085 && detect_input_pending ())
7087 swallow_events (do_display);
7088 if (detect_input_pending ())
7089 break;
7092 /* Exit now if the cell we're waiting for became non-nil. */
7093 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7094 break;
7097 start_polling ();
7099 return 0;
7102 #endif /* not subprocesses */
7104 /* The following functions are needed even if async subprocesses are
7105 not supported. Some of them are no-op stubs in that case. */
7107 /* Add DESC to the set of keyboard input descriptors. */
7109 void
7110 add_keyboard_wait_descriptor (int desc)
7112 #ifdef subprocesses
7113 FD_SET (desc, &input_wait_mask);
7114 FD_SET (desc, &non_process_wait_mask);
7115 if (desc > max_keyboard_desc)
7116 max_keyboard_desc = desc;
7117 #endif
7120 /* From now on, do not expect DESC to give keyboard input. */
7122 void
7123 delete_keyboard_wait_descriptor (int desc)
7125 #ifdef subprocesses
7126 int fd;
7127 int lim = max_keyboard_desc;
7129 FD_CLR (desc, &input_wait_mask);
7130 FD_CLR (desc, &non_process_wait_mask);
7132 if (desc == max_keyboard_desc)
7133 for (fd = 0; fd < lim; fd++)
7134 if (FD_ISSET (fd, &input_wait_mask)
7135 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7136 && !FD_ISSET (fd, &gpm_wait_mask))
7137 max_keyboard_desc = fd;
7138 #endif /* subprocesses */
7141 /* Setup coding systems of PROCESS. */
7143 void
7144 setup_process_coding_systems (Lisp_Object process)
7146 #ifdef subprocesses
7147 struct Lisp_Process *p = XPROCESS (process);
7148 int inch = p->infd;
7149 int outch = p->outfd;
7150 Lisp_Object coding_system;
7152 if (inch < 0 || outch < 0)
7153 return;
7155 if (!proc_decode_coding_system[inch])
7156 proc_decode_coding_system[inch]
7157 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7158 coding_system = p->decode_coding_system;
7159 if (! NILP (p->filter))
7161 else if (BUFFERP (p->buffer))
7163 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7164 coding_system = raw_text_coding_system (coding_system);
7166 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7168 if (!proc_encode_coding_system[outch])
7169 proc_encode_coding_system[outch]
7170 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7171 setup_coding_system (p->encode_coding_system,
7172 proc_encode_coding_system[outch]);
7173 #endif
7176 /* Close all descriptors currently in use for communication
7177 with subprocess. This is used in a newly-forked subprocess
7178 to get rid of irrelevant descriptors. */
7180 void
7181 close_process_descs (void)
7183 #ifndef DOS_NT
7184 int i;
7185 for (i = 0; i < MAXDESC; i++)
7187 Lisp_Object process;
7188 process = chan_process[i];
7189 if (!NILP (process))
7191 int in = XPROCESS (process)->infd;
7192 int out = XPROCESS (process)->outfd;
7193 if (in >= 0)
7194 emacs_close (in);
7195 if (out >= 0 && in != out)
7196 emacs_close (out);
7199 #endif
7202 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7203 doc: /* Return the (or a) process associated with BUFFER.
7204 BUFFER may be a buffer or the name of one. */)
7205 (register Lisp_Object buffer)
7207 #ifdef subprocesses
7208 register Lisp_Object buf, tail, proc;
7210 if (NILP (buffer)) return Qnil;
7211 buf = Fget_buffer (buffer);
7212 if (NILP (buf)) return Qnil;
7214 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7216 proc = Fcdr (XCAR (tail));
7217 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7218 return proc;
7220 #endif /* subprocesses */
7221 return Qnil;
7224 DEFUN ("process-inherit-coding-system-flag",
7225 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7226 1, 1, 0,
7227 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7228 If this flag is t, `buffer-file-coding-system' of the buffer
7229 associated with PROCESS will inherit the coding system used to decode
7230 the process output. */)
7231 (register Lisp_Object process)
7233 #ifdef subprocesses
7234 CHECK_PROCESS (process);
7235 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7236 #else
7237 /* Ignore the argument and return the value of
7238 inherit-process-coding-system. */
7239 return inherit_process_coding_system ? Qt : Qnil;
7240 #endif
7243 /* Kill all processes associated with `buffer'.
7244 If `buffer' is nil, kill all processes */
7246 void
7247 kill_buffer_processes (Lisp_Object buffer)
7249 #ifdef subprocesses
7250 Lisp_Object tail, proc;
7252 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7254 proc = XCDR (XCAR (tail));
7255 if (PROCESSP (proc)
7256 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7258 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7259 Fdelete_process (proc);
7260 else if (XPROCESS (proc)->infd >= 0)
7261 process_send_signal (proc, SIGHUP, Qnil, 1);
7264 #else /* subprocesses */
7265 /* Since we have no subprocesses, this does nothing. */
7266 #endif /* subprocesses */
7269 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7270 0, 0, 0,
7271 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7272 This is intended for use by asynchronous process output filters and sentinels. */)
7273 (void)
7275 #ifdef subprocesses
7276 return (waiting_for_user_input_p ? Qt : Qnil);
7277 #else
7278 return Qnil;
7279 #endif
7282 /* Stop reading input from keyboard sources. */
7284 void
7285 hold_keyboard_input (void)
7287 kbd_is_on_hold = 1;
7290 /* Resume reading input from keyboard sources. */
7292 void
7293 unhold_keyboard_input (void)
7295 kbd_is_on_hold = 0;
7298 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7301 kbd_on_hold_p (void)
7303 return kbd_is_on_hold;
7307 /* Enumeration of and access to system processes a-la ps(1). */
7309 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7310 0, 0, 0,
7311 doc: /* Return a list of numerical process IDs of all running processes.
7312 If this functionality is unsupported, return nil.
7314 See `process-attributes' for getting attributes of a process given its ID. */)
7315 (void)
7317 return list_system_processes ();
7320 DEFUN ("process-attributes", Fprocess_attributes,
7321 Sprocess_attributes, 1, 1, 0,
7322 doc: /* Return attributes of the process given by its PID, a number.
7324 Value is an alist where each element is a cons cell of the form
7326 \(KEY . VALUE)
7328 If this functionality is unsupported, the value is nil.
7330 See `list-system-processes' for getting a list of all process IDs.
7332 The KEYs of the attributes that this function may return are listed
7333 below, together with the type of the associated VALUE (in parentheses).
7334 Not all platforms support all of these attributes; unsupported
7335 attributes will not appear in the returned alist.
7336 Unless explicitly indicated otherwise, numbers can have either
7337 integer or floating point values.
7339 euid -- Effective user User ID of the process (number)
7340 user -- User name corresponding to euid (string)
7341 egid -- Effective user Group ID of the process (number)
7342 group -- Group name corresponding to egid (string)
7343 comm -- Command name (executable name only) (string)
7344 state -- Process state code, such as "S", "R", or "T" (string)
7345 ppid -- Parent process ID (number)
7346 pgrp -- Process group ID (number)
7347 sess -- Session ID, i.e. process ID of session leader (number)
7348 ttname -- Controlling tty name (string)
7349 tpgid -- ID of foreground process group on the process's tty (number)
7350 minflt -- number of minor page faults (number)
7351 majflt -- number of major page faults (number)
7352 cminflt -- cumulative number of minor page faults (number)
7353 cmajflt -- cumulative number of major page faults (number)
7354 utime -- user time used by the process, in the (HIGH LOW USEC) format
7355 stime -- system time used by the process, in the (HIGH LOW USEC) format
7356 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7357 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7358 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7359 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7360 pri -- priority of the process (number)
7361 nice -- nice value of the process (number)
7362 thcount -- process thread count (number)
7363 start -- time the process started, in the (HIGH LOW USEC) format
7364 vsize -- virtual memory size of the process in KB's (number)
7365 rss -- resident set size of the process in KB's (number)
7366 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7367 pcpu -- percents of CPU time used by the process (floating-point number)
7368 pmem -- percents of total physical memory used by process's resident set
7369 (floating-point number)
7370 args -- command line which invoked the process (string). */)
7371 ( Lisp_Object pid)
7373 return system_process_attributes (pid);
7377 void
7378 init_process (void)
7380 #ifdef subprocesses
7381 register int i;
7383 inhibit_sentinels = 0;
7385 #ifdef SIGCHLD
7386 #ifndef CANNOT_DUMP
7387 if (! noninteractive || initialized)
7388 #endif
7389 signal (SIGCHLD, sigchld_handler);
7390 #endif
7392 FD_ZERO (&input_wait_mask);
7393 FD_ZERO (&non_keyboard_wait_mask);
7394 FD_ZERO (&non_process_wait_mask);
7395 max_process_desc = 0;
7397 #ifdef NON_BLOCKING_CONNECT
7398 FD_ZERO (&connect_wait_mask);
7399 num_pending_connects = 0;
7400 #endif
7402 #ifdef ADAPTIVE_READ_BUFFERING
7403 process_output_delay_count = 0;
7404 process_output_skip = 0;
7405 #endif
7407 /* Don't do this, it caused infinite select loops. The display
7408 method should call add_keyboard_wait_descriptor on stdin if it
7409 needs that. */
7410 #if 0
7411 FD_SET (0, &input_wait_mask);
7412 #endif
7414 Vprocess_alist = Qnil;
7415 #ifdef SIGCHLD
7416 deleted_pid_list = Qnil;
7417 #endif
7418 for (i = 0; i < MAXDESC; i++)
7420 chan_process[i] = Qnil;
7421 proc_buffered_char[i] = -1;
7423 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7424 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7425 #ifdef DATAGRAM_SOCKETS
7426 memset (datagram_address, 0, sizeof datagram_address);
7427 #endif
7429 #ifdef HAVE_SOCKETS
7431 Lisp_Object subfeatures = Qnil;
7432 const struct socket_options *sopt;
7434 #define ADD_SUBFEATURE(key, val) \
7435 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7437 #ifdef NON_BLOCKING_CONNECT
7438 ADD_SUBFEATURE (QCnowait, Qt);
7439 #endif
7440 #ifdef DATAGRAM_SOCKETS
7441 ADD_SUBFEATURE (QCtype, Qdatagram);
7442 #endif
7443 #ifdef HAVE_SEQPACKET
7444 ADD_SUBFEATURE (QCtype, Qseqpacket);
7445 #endif
7446 #ifdef HAVE_LOCAL_SOCKETS
7447 ADD_SUBFEATURE (QCfamily, Qlocal);
7448 #endif
7449 ADD_SUBFEATURE (QCfamily, Qipv4);
7450 #ifdef AF_INET6
7451 ADD_SUBFEATURE (QCfamily, Qipv6);
7452 #endif
7453 #ifdef HAVE_GETSOCKNAME
7454 ADD_SUBFEATURE (QCservice, Qt);
7455 #endif
7456 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7457 ADD_SUBFEATURE (QCserver, Qt);
7458 #endif
7460 for (sopt = socket_options; sopt->name; sopt++)
7461 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7463 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7465 #endif /* HAVE_SOCKETS */
7467 #if defined (DARWIN_OS)
7468 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7469 processes. As such, we only change the default value. */
7470 if (initialized)
7472 char *release = get_operating_system_release ();
7473 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7474 && release[1] == '.')) {
7475 Vprocess_connection_type = Qnil;
7478 #endif
7479 #endif /* subprocesses */
7480 kbd_is_on_hold = 0;
7483 void
7484 syms_of_process (void)
7486 #ifdef subprocesses
7488 Qprocessp = intern_c_string ("processp");
7489 staticpro (&Qprocessp);
7490 Qrun = intern_c_string ("run");
7491 staticpro (&Qrun);
7492 Qstop = intern_c_string ("stop");
7493 staticpro (&Qstop);
7494 Qsignal = intern_c_string ("signal");
7495 staticpro (&Qsignal);
7497 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7498 here again.
7500 Qexit = intern_c_string ("exit");
7501 staticpro (&Qexit); */
7503 Qopen = intern_c_string ("open");
7504 staticpro (&Qopen);
7505 Qclosed = intern_c_string ("closed");
7506 staticpro (&Qclosed);
7507 Qconnect = intern_c_string ("connect");
7508 staticpro (&Qconnect);
7509 Qfailed = intern_c_string ("failed");
7510 staticpro (&Qfailed);
7511 Qlisten = intern_c_string ("listen");
7512 staticpro (&Qlisten);
7513 Qlocal = intern_c_string ("local");
7514 staticpro (&Qlocal);
7515 Qipv4 = intern_c_string ("ipv4");
7516 staticpro (&Qipv4);
7517 #ifdef AF_INET6
7518 Qipv6 = intern_c_string ("ipv6");
7519 staticpro (&Qipv6);
7520 #endif
7521 Qdatagram = intern_c_string ("datagram");
7522 staticpro (&Qdatagram);
7523 Qseqpacket = intern_c_string ("seqpacket");
7524 staticpro (&Qseqpacket);
7526 QCport = intern_c_string (":port");
7527 staticpro (&QCport);
7528 QCspeed = intern_c_string (":speed");
7529 staticpro (&QCspeed);
7530 QCprocess = intern_c_string (":process");
7531 staticpro (&QCprocess);
7533 QCbytesize = intern_c_string (":bytesize");
7534 staticpro (&QCbytesize);
7535 QCstopbits = intern_c_string (":stopbits");
7536 staticpro (&QCstopbits);
7537 QCparity = intern_c_string (":parity");
7538 staticpro (&QCparity);
7539 Qodd = intern_c_string ("odd");
7540 staticpro (&Qodd);
7541 Qeven = intern_c_string ("even");
7542 staticpro (&Qeven);
7543 QCflowcontrol = intern_c_string (":flowcontrol");
7544 staticpro (&QCflowcontrol);
7545 Qhw = intern_c_string ("hw");
7546 staticpro (&Qhw);
7547 Qsw = intern_c_string ("sw");
7548 staticpro (&Qsw);
7549 QCsummary = intern_c_string (":summary");
7550 staticpro (&QCsummary);
7552 Qreal = intern_c_string ("real");
7553 staticpro (&Qreal);
7554 Qnetwork = intern_c_string ("network");
7555 staticpro (&Qnetwork);
7556 Qserial = intern_c_string ("serial");
7557 staticpro (&Qserial);
7558 QCbuffer = intern_c_string (":buffer");
7559 staticpro (&QCbuffer);
7560 QChost = intern_c_string (":host");
7561 staticpro (&QChost);
7562 QCservice = intern_c_string (":service");
7563 staticpro (&QCservice);
7564 QClocal = intern_c_string (":local");
7565 staticpro (&QClocal);
7566 QCremote = intern_c_string (":remote");
7567 staticpro (&QCremote);
7568 QCcoding = intern_c_string (":coding");
7569 staticpro (&QCcoding);
7570 QCserver = intern_c_string (":server");
7571 staticpro (&QCserver);
7572 QCnowait = intern_c_string (":nowait");
7573 staticpro (&QCnowait);
7574 QCsentinel = intern_c_string (":sentinel");
7575 staticpro (&QCsentinel);
7576 QClog = intern_c_string (":log");
7577 staticpro (&QClog);
7578 QCnoquery = intern_c_string (":noquery");
7579 staticpro (&QCnoquery);
7580 QCstop = intern_c_string (":stop");
7581 staticpro (&QCstop);
7582 QCoptions = intern_c_string (":options");
7583 staticpro (&QCoptions);
7584 QCplist = intern_c_string (":plist");
7585 staticpro (&QCplist);
7587 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7588 staticpro (&Qlast_nonmenu_event);
7590 staticpro (&Vprocess_alist);
7591 #ifdef SIGCHLD
7592 staticpro (&deleted_pid_list);
7593 #endif
7595 #endif /* subprocesses */
7597 QCname = intern_c_string (":name");
7598 staticpro (&QCname);
7599 QCtype = intern_c_string (":type");
7600 staticpro (&QCtype);
7602 Qeuid = intern_c_string ("euid");
7603 staticpro (&Qeuid);
7604 Qegid = intern_c_string ("egid");
7605 staticpro (&Qegid);
7606 Quser = intern_c_string ("user");
7607 staticpro (&Quser);
7608 Qgroup = intern_c_string ("group");
7609 staticpro (&Qgroup);
7610 Qcomm = intern_c_string ("comm");
7611 staticpro (&Qcomm);
7612 Qstate = intern_c_string ("state");
7613 staticpro (&Qstate);
7614 Qppid = intern_c_string ("ppid");
7615 staticpro (&Qppid);
7616 Qpgrp = intern_c_string ("pgrp");
7617 staticpro (&Qpgrp);
7618 Qsess = intern_c_string ("sess");
7619 staticpro (&Qsess);
7620 Qttname = intern_c_string ("ttname");
7621 staticpro (&Qttname);
7622 Qtpgid = intern_c_string ("tpgid");
7623 staticpro (&Qtpgid);
7624 Qminflt = intern_c_string ("minflt");
7625 staticpro (&Qminflt);
7626 Qmajflt = intern_c_string ("majflt");
7627 staticpro (&Qmajflt);
7628 Qcminflt = intern_c_string ("cminflt");
7629 staticpro (&Qcminflt);
7630 Qcmajflt = intern_c_string ("cmajflt");
7631 staticpro (&Qcmajflt);
7632 Qutime = intern_c_string ("utime");
7633 staticpro (&Qutime);
7634 Qstime = intern_c_string ("stime");
7635 staticpro (&Qstime);
7636 Qtime = intern_c_string ("time");
7637 staticpro (&Qtime);
7638 Qcutime = intern_c_string ("cutime");
7639 staticpro (&Qcutime);
7640 Qcstime = intern_c_string ("cstime");
7641 staticpro (&Qcstime);
7642 Qctime = intern_c_string ("ctime");
7643 staticpro (&Qctime);
7644 Qpri = intern_c_string ("pri");
7645 staticpro (&Qpri);
7646 Qnice = intern_c_string ("nice");
7647 staticpro (&Qnice);
7648 Qthcount = intern_c_string ("thcount");
7649 staticpro (&Qthcount);
7650 Qstart = intern_c_string ("start");
7651 staticpro (&Qstart);
7652 Qvsize = intern_c_string ("vsize");
7653 staticpro (&Qvsize);
7654 Qrss = intern_c_string ("rss");
7655 staticpro (&Qrss);
7656 Qetime = intern_c_string ("etime");
7657 staticpro (&Qetime);
7658 Qpcpu = intern_c_string ("pcpu");
7659 staticpro (&Qpcpu);
7660 Qpmem = intern_c_string ("pmem");
7661 staticpro (&Qpmem);
7662 Qargs = intern_c_string ("args");
7663 staticpro (&Qargs);
7665 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7666 doc: /* *Non-nil means delete processes immediately when they exit.
7667 A value of nil means don't delete them until `list-processes' is run. */);
7669 delete_exited_processes = 1;
7671 #ifdef subprocesses
7672 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7673 doc: /* Control type of device used to communicate with subprocesses.
7674 Values are nil to use a pipe, or t or `pty' to use a pty.
7675 The value has no effect if the system has no ptys or if all ptys are busy:
7676 then a pipe is used in any case.
7677 The value takes effect when `start-process' is called. */);
7678 Vprocess_connection_type = Qt;
7680 #ifdef ADAPTIVE_READ_BUFFERING
7681 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7682 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7683 On some systems, when Emacs reads the output from a subprocess, the output data
7684 is read in very small blocks, potentially resulting in very poor performance.
7685 This behavior can be remedied to some extent by setting this variable to a
7686 non-nil value, as it will automatically delay reading from such processes, to
7687 allow them to produce more output before Emacs tries to read it.
7688 If the value is t, the delay is reset after each write to the process; any other
7689 non-nil value means that the delay is not reset on write.
7690 The variable takes effect when `start-process' is called. */);
7691 Vprocess_adaptive_read_buffering = Qt;
7692 #endif
7694 defsubr (&Sprocessp);
7695 defsubr (&Sget_process);
7696 defsubr (&Sdelete_process);
7697 defsubr (&Sprocess_status);
7698 defsubr (&Sprocess_exit_status);
7699 defsubr (&Sprocess_id);
7700 defsubr (&Sprocess_name);
7701 defsubr (&Sprocess_tty_name);
7702 defsubr (&Sprocess_command);
7703 defsubr (&Sset_process_buffer);
7704 defsubr (&Sprocess_buffer);
7705 defsubr (&Sprocess_mark);
7706 defsubr (&Sset_process_filter);
7707 defsubr (&Sprocess_filter);
7708 defsubr (&Sset_process_sentinel);
7709 defsubr (&Sprocess_sentinel);
7710 defsubr (&Sset_process_window_size);
7711 defsubr (&Sset_process_inherit_coding_system_flag);
7712 defsubr (&Sset_process_query_on_exit_flag);
7713 defsubr (&Sprocess_query_on_exit_flag);
7714 defsubr (&Sprocess_contact);
7715 defsubr (&Sprocess_plist);
7716 defsubr (&Sset_process_plist);
7717 defsubr (&Slist_processes);
7718 defsubr (&Sprocess_list);
7719 defsubr (&Sstart_process);
7720 #ifdef HAVE_SERIAL
7721 defsubr (&Sserial_process_configure);
7722 defsubr (&Smake_serial_process);
7723 #endif /* HAVE_SERIAL */
7724 #ifdef HAVE_SOCKETS
7725 defsubr (&Sset_network_process_option);
7726 defsubr (&Smake_network_process);
7727 defsubr (&Sformat_network_address);
7728 #endif /* HAVE_SOCKETS */
7729 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7730 #ifdef SIOCGIFCONF
7731 defsubr (&Snetwork_interface_list);
7732 #endif
7733 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7734 defsubr (&Snetwork_interface_info);
7735 #endif
7736 #endif /* HAVE_SOCKETS ... */
7737 #ifdef DATAGRAM_SOCKETS
7738 defsubr (&Sprocess_datagram_address);
7739 defsubr (&Sset_process_datagram_address);
7740 #endif
7741 defsubr (&Saccept_process_output);
7742 defsubr (&Sprocess_send_region);
7743 defsubr (&Sprocess_send_string);
7744 defsubr (&Sinterrupt_process);
7745 defsubr (&Skill_process);
7746 defsubr (&Squit_process);
7747 defsubr (&Sstop_process);
7748 defsubr (&Scontinue_process);
7749 defsubr (&Sprocess_running_child_p);
7750 defsubr (&Sprocess_send_eof);
7751 defsubr (&Ssignal_process);
7752 defsubr (&Swaiting_for_user_input_p);
7753 defsubr (&Sprocess_type);
7754 defsubr (&Sset_process_coding_system);
7755 defsubr (&Sprocess_coding_system);
7756 defsubr (&Sset_process_filter_multibyte);
7757 defsubr (&Sprocess_filter_multibyte_p);
7759 #endif /* subprocesses */
7761 defsubr (&Sget_buffer_process);
7762 defsubr (&Sprocess_inherit_coding_system_flag);
7763 defsubr (&Slist_system_processes);
7764 defsubr (&Sprocess_attributes);
7767 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7768 (do not change this comment) */