* etc/NEWS: Misc fixes for ImageMagick section.
[emacs.git] / src / process.c
blobf348dca7d3564db9d59330328b8127c25256d3ce
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 #include <stdlib.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #include <fcntl.h>
41 /* Only MS-DOS does not define `subprocesses'. */
42 #ifdef subprocesses
44 #include <sys/socket.h>
45 #include <netdb.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
49 /* Are local (unix) sockets supported? */
50 #if defined (HAVE_SYS_UN_H)
51 #if !defined (AF_LOCAL) && defined (AF_UNIX)
52 #define AF_LOCAL AF_UNIX
53 #endif
54 #ifdef AF_LOCAL
55 #define HAVE_LOCAL_SOCKETS
56 #include <sys/un.h>
57 #endif
58 #endif
60 #if defined(HAVE_SYS_IOCTL_H)
61 #include <sys/ioctl.h>
62 #if defined(HAVE_NET_IF_H)
63 #include <net/if.h>
64 #endif /* HAVE_NET_IF_H */
65 #endif /* HAVE_SYS_IOCTL_H */
67 #ifdef NEED_BSDTTY
68 #include <bsdtty.h>
69 #endif
71 #ifdef HAVE_SYS_WAIT
72 #include <sys/wait.h>
73 #endif
75 #ifdef HAVE_RES_INIT
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <resolv.h>
79 #endif
81 #ifdef HAVE_UTIL_H
82 #include <util.h>
83 #endif
85 #endif /* subprocesses */
87 #include "lisp.h"
88 #include "systime.h"
89 #include "systty.h"
91 #include "window.h"
92 #include "buffer.h"
93 #include "character.h"
94 #include "coding.h"
95 #include "process.h"
96 #include "frame.h"
97 #include "termhooks.h"
98 #include "termopts.h"
99 #include "commands.h"
100 #include "keyboard.h"
101 #include "blockinput.h"
102 #include "dispextern.h"
103 #include "composite.h"
104 #include "atimer.h"
105 #include "sysselect.h"
106 #include "syssignal.h"
107 #include "syswait.h"
109 #if defined (USE_GTK) || defined (HAVE_GCONF)
110 #include "xgselect.h"
111 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
112 #ifdef HAVE_NS
113 #include "nsterm.h"
114 #endif
115 extern int timers_run;
117 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
118 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
119 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
120 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
121 Lisp_Object QCname, QCtype;
123 /* Non-zero if keyboard input is on hold, zero otherwise. */
125 static int kbd_is_on_hold;
127 /* Nonzero means delete a process right away if it exits. */
128 static int delete_exited_processes;
130 /* Nonzero means don't run process sentinels. This is used
131 when exiting. */
132 int inhibit_sentinels;
134 #ifdef subprocesses
136 Lisp_Object Qprocessp;
137 Lisp_Object Qrun, Qstop, Qsignal;
138 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
139 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
140 Lisp_Object Qreal, Qnetwork, Qserial;
141 #ifdef AF_INET6
142 Lisp_Object Qipv6;
143 #endif
144 Lisp_Object QCport, QCspeed, QCprocess;
145 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
146 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
147 Lisp_Object QCbuffer, QChost, QCservice;
148 Lisp_Object QClocal, QCremote, QCcoding;
149 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
150 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
151 Lisp_Object Qlast_nonmenu_event;
152 /* QCfamily is declared and initialized in xfaces.c,
153 QCfilter in keyboard.c. */
154 extern Lisp_Object QCfamily, QCfilter;
156 /* Qexit is declared and initialized in eval.c. */
158 /* QCfamily is defined in xfaces.c. */
159 extern Lisp_Object QCfamily;
160 /* QCfilter is defined in keyboard.c. */
161 extern Lisp_Object QCfilter;
163 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
164 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
165 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
166 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
168 /* Define first descriptor number available for subprocesses. */
169 #define FIRST_PROC_DESC 3
171 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
172 testing SIGCHLD. */
174 #if !defined (SIGCHLD) && defined (SIGCLD)
175 #define SIGCHLD SIGCLD
176 #endif /* SIGCLD */
178 extern const char *get_operating_system_release (void);
180 /* From sysdep.c or w32.c */
181 extern int serial_open (char *port);
182 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
184 #ifndef HAVE_H_ERRNO
185 extern int h_errno;
186 #endif
188 /* t means use pty, nil means use a pipe,
189 maybe other values to come. */
190 static Lisp_Object Vprocess_connection_type;
192 /* These next two vars are non-static since sysdep.c uses them in the
193 emulation of `select'. */
194 /* Number of events of change of status of a process. */
195 int process_tick;
196 /* Number of events for which the user or sentinel has been notified. */
197 int update_tick;
199 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
201 #ifdef BROKEN_NON_BLOCKING_CONNECT
202 #undef NON_BLOCKING_CONNECT
203 #else
204 #ifndef NON_BLOCKING_CONNECT
205 #ifdef HAVE_SELECT
206 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
207 #if defined (O_NONBLOCK) || defined (O_NDELAY)
208 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
209 #define NON_BLOCKING_CONNECT
210 #endif /* EWOULDBLOCK || EINPROGRESS */
211 #endif /* O_NONBLOCK || O_NDELAY */
212 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
213 #endif /* HAVE_SELECT */
214 #endif /* NON_BLOCKING_CONNECT */
215 #endif /* BROKEN_NON_BLOCKING_CONNECT */
217 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
222 #ifdef BROKEN_DATAGRAM_SOCKETS
223 #undef DATAGRAM_SOCKETS
224 #else
225 #ifndef DATAGRAM_SOCKETS
226 #if defined (HAVE_SELECT) || defined (FIONREAD)
227 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
228 #define DATAGRAM_SOCKETS
229 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
230 #endif /* HAVE_SELECT || FIONREAD */
231 #endif /* DATAGRAM_SOCKETS */
232 #endif /* BROKEN_DATAGRAM_SOCKETS */
234 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
235 # define HAVE_SEQPACKET
236 #endif
238 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
239 #ifdef EMACS_HAS_USECS
240 #define ADAPTIVE_READ_BUFFERING
241 #endif
242 #endif
244 #ifdef ADAPTIVE_READ_BUFFERING
245 #define READ_OUTPUT_DELAY_INCREMENT 10000
246 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
247 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
249 /* Number of processes which have a non-zero read_output_delay,
250 and therefore might be delayed for adaptive read buffering. */
252 static int process_output_delay_count;
254 /* Non-zero if any process has non-nil read_output_skip. */
256 static int process_output_skip;
258 /* Non-nil means to delay reading process output to improve buffering.
259 A value of t means that delay is reset after each send, any other
260 non-nil value does not reset the delay. A value of nil disables
261 adaptive read buffering completely. */
262 static Lisp_Object Vprocess_adaptive_read_buffering;
263 #else
264 #define process_output_delay_count 0
265 #endif
267 static int keyboard_bit_set (SELECT_TYPE *);
268 static void deactivate_process (Lisp_Object);
269 static void status_notify (struct Lisp_Process *);
270 static int read_process_output (Lisp_Object, int);
271 static void create_pty (Lisp_Object);
273 /* If we support a window system, turn on the code to poll periodically
274 to detect C-g. It isn't actually used when doing interrupt input. */
275 #ifdef HAVE_WINDOW_SYSTEM
276 #define POLL_FOR_INPUT
277 #endif
279 static Lisp_Object get_process (register Lisp_Object name);
280 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
282 /* Mask of bits indicating the descriptors that we wait for input on. */
284 static SELECT_TYPE input_wait_mask;
286 /* Mask that excludes keyboard input descriptor(s). */
288 static SELECT_TYPE non_keyboard_wait_mask;
290 /* Mask that excludes process input descriptor(s). */
292 static SELECT_TYPE non_process_wait_mask;
294 /* Mask for the gpm mouse input descriptor. */
296 static SELECT_TYPE gpm_wait_mask;
298 #ifdef NON_BLOCKING_CONNECT
299 /* Mask of bits indicating the descriptors that we wait for connect to
300 complete on. Once they complete, they are removed from this mask
301 and added to the input_wait_mask and non_keyboard_wait_mask. */
303 static SELECT_TYPE connect_wait_mask;
305 /* Number of bits set in connect_wait_mask. */
306 static int num_pending_connects;
308 #define IF_NON_BLOCKING_CONNECT(s) s
309 #else /* NON_BLOCKING_CONNECT */
310 #define IF_NON_BLOCKING_CONNECT(s)
311 #endif /* NON_BLOCKING_CONNECT */
313 /* The largest descriptor currently in use for a process object. */
314 static int max_process_desc;
316 /* The largest descriptor currently in use for keyboard input. */
317 static int max_keyboard_desc;
319 /* The largest descriptor currently in use for gpm mouse input. */
320 static int max_gpm_desc;
322 /* Indexed by descriptor, gives the process (if any) for that descriptor */
323 Lisp_Object chan_process[MAXDESC];
325 /* Alist of elements (NAME . PROCESS) */
326 Lisp_Object Vprocess_alist;
328 /* Buffered-ahead input char from process, indexed by channel.
329 -1 means empty (no char is buffered).
330 Used on sys V where the only way to tell if there is any
331 output from the process is to read at least one char.
332 Always -1 on systems that support FIONREAD. */
334 /* Don't make static; need to access externally. */
335 int proc_buffered_char[MAXDESC];
337 /* Table of `struct coding-system' for each process. */
338 static struct coding_system *proc_decode_coding_system[MAXDESC];
339 static struct coding_system *proc_encode_coding_system[MAXDESC];
341 #ifdef DATAGRAM_SOCKETS
342 /* Table of `partner address' for datagram sockets. */
343 struct sockaddr_and_len {
344 struct sockaddr *sa;
345 int len;
346 } datagram_address[MAXDESC];
347 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
348 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
349 #else
350 #define DATAGRAM_CHAN_P(chan) (0)
351 #define DATAGRAM_CONN_P(proc) (0)
352 #endif
354 /* Maximum number of bytes to send to a pty without an eof. */
355 static int pty_max_bytes;
357 #ifdef HAVE_PTYS
358 #ifdef HAVE_PTY_H
359 #include <pty.h>
360 #endif
361 /* The file name of the pty opened by allocate_pty. */
363 static char pty_name[24];
364 #endif
366 /* Compute the Lisp form of the process status, p->status, from
367 the numeric status that was returned by `wait'. */
369 static Lisp_Object status_convert (int);
371 static void
372 update_status (struct Lisp_Process *p)
374 eassert (p->raw_status_new);
375 p->status = status_convert (p->raw_status);
376 p->raw_status_new = 0;
379 /* Convert a process status word in Unix format to
380 the list that we use internally. */
382 static Lisp_Object
383 status_convert (int w)
385 if (WIFSTOPPED (w))
386 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
387 else if (WIFEXITED (w))
388 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
389 WCOREDUMP (w) ? Qt : Qnil));
390 else if (WIFSIGNALED (w))
391 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
392 WCOREDUMP (w) ? Qt : Qnil));
393 else
394 return Qrun;
397 /* Given a status-list, extract the three pieces of information
398 and store them individually through the three pointers. */
400 static void
401 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
403 Lisp_Object tem;
405 if (SYMBOLP (l))
407 *symbol = l;
408 *code = 0;
409 *coredump = 0;
411 else
413 *symbol = XCAR (l);
414 tem = XCDR (l);
415 *code = XFASTINT (XCAR (tem));
416 tem = XCDR (tem);
417 *coredump = !NILP (tem);
421 /* Return a string describing a process status list. */
423 static Lisp_Object
424 status_message (struct Lisp_Process *p)
426 Lisp_Object status = p->status;
427 Lisp_Object symbol;
428 int code, coredump;
429 Lisp_Object string, string2;
431 decode_status (status, &symbol, &code, &coredump);
433 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
435 char *signame;
436 synchronize_system_messages_locale ();
437 signame = strsignal (code);
438 if (signame == 0)
439 string = build_string ("unknown");
440 else
442 int c1, c2;
444 string = make_unibyte_string (signame, strlen (signame));
445 if (! NILP (Vlocale_coding_system))
446 string = (code_convert_string_norecord
447 (string, Vlocale_coding_system, 0));
448 c1 = STRING_CHAR ((char *) SDATA (string));
449 c2 = DOWNCASE (c1);
450 if (c1 != c2)
451 Faset (string, make_number (0), make_number (c2));
453 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
454 return concat2 (string, string2);
456 else if (EQ (symbol, Qexit))
458 if (NETCONN1_P (p))
459 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
460 if (code == 0)
461 return build_string ("finished\n");
462 string = Fnumber_to_string (make_number (code));
463 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
464 return concat3 (build_string ("exited abnormally with code "),
465 string, string2);
467 else if (EQ (symbol, Qfailed))
469 string = Fnumber_to_string (make_number (code));
470 string2 = build_string ("\n");
471 return concat3 (build_string ("failed with code "),
472 string, string2);
474 else
475 return Fcopy_sequence (Fsymbol_name (symbol));
478 #ifdef HAVE_PTYS
480 /* Open an available pty, returning a file descriptor.
481 Return -1 on failure.
482 The file name of the terminal corresponding to the pty
483 is left in the variable pty_name. */
485 static int
486 allocate_pty (void)
488 register int c, i;
489 int fd;
491 #ifdef PTY_ITERATION
492 PTY_ITERATION
493 #else
494 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
495 for (i = 0; i < 16; i++)
496 #endif
498 struct stat stb; /* Used in some PTY_OPEN. */
499 #ifdef PTY_NAME_SPRINTF
500 PTY_NAME_SPRINTF
501 #else
502 sprintf (pty_name, "/dev/pty%c%x", c, i);
503 #endif /* no PTY_NAME_SPRINTF */
505 #ifdef PTY_OPEN
506 PTY_OPEN;
507 #else /* no PTY_OPEN */
509 { /* Some systems name their pseudoterminals so that there are gaps in
510 the usual sequence - for example, on HP9000/S700 systems, there
511 are no pseudoterminals with names ending in 'f'. So we wait for
512 three failures in a row before deciding that we've reached the
513 end of the ptys. */
514 int failed_count = 0;
516 if (stat (pty_name, &stb) < 0)
518 failed_count++;
519 if (failed_count >= 3)
520 return -1;
522 else
523 failed_count = 0;
525 # ifdef O_NONBLOCK
526 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
527 # else
528 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
529 # endif
531 #endif /* no PTY_OPEN */
533 if (fd >= 0)
535 /* check to make certain that both sides are available
536 this avoids a nasty yet stupid bug in rlogins */
537 #ifdef PTY_TTY_NAME_SPRINTF
538 PTY_TTY_NAME_SPRINTF
539 #else
540 sprintf (pty_name, "/dev/tty%c%x", c, i);
541 #endif /* no PTY_TTY_NAME_SPRINTF */
542 if (access (pty_name, 6) != 0)
544 emacs_close (fd);
545 # ifndef __sgi
546 continue;
547 # else
548 return -1;
549 # endif /* __sgi */
551 setup_pty (fd);
552 return fd;
555 return -1;
557 #endif /* HAVE_PTYS */
559 static Lisp_Object
560 make_process (Lisp_Object name)
562 register Lisp_Object val, tem, name1;
563 register struct Lisp_Process *p;
564 char suffix[10];
565 register int i;
567 p = allocate_process ();
569 p->infd = -1;
570 p->outfd = -1;
571 p->tick = 0;
572 p->update_tick = 0;
573 p->pid = 0;
574 p->pty_flag = 0;
575 p->raw_status_new = 0;
576 p->status = Qrun;
577 p->mark = Fmake_marker ();
578 p->kill_without_query = 0;
580 #ifdef ADAPTIVE_READ_BUFFERING
581 p->adaptive_read_buffering = 0;
582 p->read_output_delay = 0;
583 p->read_output_skip = 0;
584 #endif
586 /* If name is already in use, modify it until it is unused. */
588 name1 = name;
589 for (i = 1; ; i++)
591 tem = Fget_process (name1);
592 if (NILP (tem)) break;
593 sprintf (suffix, "<%d>", i);
594 name1 = concat2 (name, build_string (suffix));
596 name = name1;
597 p->name = name;
598 XSETPROCESS (val, p);
599 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
600 return val;
603 static void
604 remove_process (register Lisp_Object proc)
606 register Lisp_Object pair;
608 pair = Frassq (proc, Vprocess_alist);
609 Vprocess_alist = Fdelq (pair, Vprocess_alist);
611 deactivate_process (proc);
615 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
616 doc: /* Return t if OBJECT is a process. */)
617 (Lisp_Object object)
619 return PROCESSP (object) ? Qt : Qnil;
622 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
623 doc: /* Return the process named NAME, or nil if there is none. */)
624 (register Lisp_Object name)
626 if (PROCESSP (name))
627 return name;
628 CHECK_STRING (name);
629 return Fcdr (Fassoc (name, Vprocess_alist));
632 /* This is how commands for the user decode process arguments. It
633 accepts a process, a process name, a buffer, a buffer name, or nil.
634 Buffers denote the first process in the buffer, and nil denotes the
635 current buffer. */
637 static Lisp_Object
638 get_process (register Lisp_Object name)
640 register Lisp_Object proc, obj;
641 if (STRINGP (name))
643 obj = Fget_process (name);
644 if (NILP (obj))
645 obj = Fget_buffer (name);
646 if (NILP (obj))
647 error ("Process %s does not exist", SDATA (name));
649 else if (NILP (name))
650 obj = Fcurrent_buffer ();
651 else
652 obj = name;
654 /* Now obj should be either a buffer object or a process object.
656 if (BUFFERP (obj))
658 proc = Fget_buffer_process (obj);
659 if (NILP (proc))
660 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
662 else
664 CHECK_PROCESS (obj);
665 proc = obj;
667 return proc;
671 #ifdef SIGCHLD
672 /* Fdelete_process promises to immediately forget about the process, but in
673 reality, Emacs needs to remember those processes until they have been
674 treated by sigchld_handler; otherwise this handler would consider the
675 process as being synchronous and say that the synchronous process is
676 dead. */
677 static Lisp_Object deleted_pid_list;
678 #endif
680 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
681 doc: /* Delete PROCESS: kill it and forget about it immediately.
682 PROCESS may be a process, a buffer, the name of a process or buffer, or
683 nil, indicating the current buffer's process. */)
684 (register Lisp_Object process)
686 register struct Lisp_Process *p;
688 process = get_process (process);
689 p = XPROCESS (process);
691 p->raw_status_new = 0;
692 if (NETCONN1_P (p) || SERIALCONN1_P (p))
694 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
695 p->tick = ++process_tick;
696 status_notify (p);
697 redisplay_preserve_echo_area (13);
699 else if (p->infd >= 0)
701 #ifdef SIGCHLD
702 Lisp_Object symbol;
703 /* Assignment to EMACS_INT stops GCC whining about limited range
704 of data type. */
705 EMACS_INT pid = p->pid;
707 /* No problem storing the pid here, as it is still in Vprocess_alist. */
708 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
709 /* GC treated elements set to nil. */
710 Fdelq (Qnil, deleted_pid_list));
711 /* If the process has already signaled, remove it from the list. */
712 if (p->raw_status_new)
713 update_status (p);
714 symbol = p->status;
715 if (CONSP (p->status))
716 symbol = XCAR (p->status);
717 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
718 deleted_pid_list
719 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
720 else
721 #endif
723 Fkill_process (process, Qnil);
724 /* Do this now, since remove_process will make sigchld_handler do nothing. */
725 p->status
726 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
727 p->tick = ++process_tick;
728 status_notify (p);
729 redisplay_preserve_echo_area (13);
732 remove_process (process);
733 return Qnil;
736 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
737 doc: /* Return the status of PROCESS.
738 The returned value is one of the following symbols:
739 run -- for a process that is running.
740 stop -- for a process stopped but continuable.
741 exit -- for a process that has exited.
742 signal -- for a process that has got a fatal signal.
743 open -- for a network stream connection that is open.
744 listen -- for a network stream server that is listening.
745 closed -- for a network stream connection that is closed.
746 connect -- when waiting for a non-blocking connection to complete.
747 failed -- when a non-blocking connection has failed.
748 nil -- if arg is a process name and no such process exists.
749 PROCESS may be a process, a buffer, the name of a process, or
750 nil, indicating the current buffer's process. */)
751 (register Lisp_Object process)
753 register struct Lisp_Process *p;
754 register Lisp_Object status;
756 if (STRINGP (process))
757 process = Fget_process (process);
758 else
759 process = get_process (process);
761 if (NILP (process))
762 return process;
764 p = XPROCESS (process);
765 if (p->raw_status_new)
766 update_status (p);
767 status = p->status;
768 if (CONSP (status))
769 status = XCAR (status);
770 if (NETCONN1_P (p) || SERIALCONN1_P (p))
772 if (EQ (status, Qexit))
773 status = Qclosed;
774 else if (EQ (p->command, Qt))
775 status = Qstop;
776 else if (EQ (status, Qrun))
777 status = Qopen;
779 return status;
782 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
783 1, 1, 0,
784 doc: /* Return the exit status of PROCESS or the signal number that killed it.
785 If PROCESS has not yet exited or died, return 0. */)
786 (register Lisp_Object process)
788 CHECK_PROCESS (process);
789 if (XPROCESS (process)->raw_status_new)
790 update_status (XPROCESS (process));
791 if (CONSP (XPROCESS (process)->status))
792 return XCAR (XCDR (XPROCESS (process)->status));
793 return make_number (0);
796 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
797 doc: /* Return the process id of PROCESS.
798 This is the pid of the external process which PROCESS uses or talks to.
799 For a network connection, this value is nil. */)
800 (register Lisp_Object process)
802 /* Assignment to EMACS_INT stops GCC whining about limited range of
803 data type. */
804 EMACS_INT pid;
806 CHECK_PROCESS (process);
807 pid = XPROCESS (process)->pid;
808 return (pid ? make_fixnum_or_float (pid) : Qnil);
811 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
812 doc: /* Return the name of PROCESS, as a string.
813 This is the name of the program invoked in PROCESS,
814 possibly modified to make it unique among process names. */)
815 (register Lisp_Object process)
817 CHECK_PROCESS (process);
818 return XPROCESS (process)->name;
821 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
822 doc: /* Return the command that was executed to start PROCESS.
823 This is a list of strings, the first string being the program executed
824 and the rest of the strings being the arguments given to it.
825 For a network or serial process, this is nil (process is running) or t
826 \(process is stopped). */)
827 (register Lisp_Object process)
829 CHECK_PROCESS (process);
830 return XPROCESS (process)->command;
833 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
834 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
835 This is the terminal that the process itself reads and writes on,
836 not the name of the pty that Emacs uses to talk with that terminal. */)
837 (register Lisp_Object process)
839 CHECK_PROCESS (process);
840 return XPROCESS (process)->tty_name;
843 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
844 2, 2, 0,
845 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
846 (register Lisp_Object process, Lisp_Object buffer)
848 struct Lisp_Process *p;
850 CHECK_PROCESS (process);
851 if (!NILP (buffer))
852 CHECK_BUFFER (buffer);
853 p = XPROCESS (process);
854 p->buffer = buffer;
855 if (NETCONN1_P (p) || SERIALCONN1_P (p))
856 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
857 setup_process_coding_systems (process);
858 return buffer;
861 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
862 1, 1, 0,
863 doc: /* Return the buffer PROCESS is associated with.
864 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
865 (register Lisp_Object process)
867 CHECK_PROCESS (process);
868 return XPROCESS (process)->buffer;
871 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
872 1, 1, 0,
873 doc: /* Return the marker for the end of the last output from PROCESS. */)
874 (register Lisp_Object process)
876 CHECK_PROCESS (process);
877 return XPROCESS (process)->mark;
880 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
881 2, 2, 0,
882 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
883 A value of t means stop accepting output from the process.
885 When a process has a filter, its buffer is not used for output.
886 Instead, each time it does output, the entire string of output is
887 passed to the filter.
889 The filter gets two arguments: the process and the string of output.
890 The string argument is normally a multibyte string, except:
891 - if the process' input coding system is no-conversion or raw-text,
892 it is a unibyte string (the non-converted input), or else
893 - if `default-enable-multibyte-characters' is nil, it is a unibyte
894 string (the result of converting the decoded input multibyte
895 string to unibyte with `string-make-unibyte'). */)
896 (register Lisp_Object process, Lisp_Object filter)
898 struct Lisp_Process *p;
900 CHECK_PROCESS (process);
901 p = XPROCESS (process);
903 /* Don't signal an error if the process' input file descriptor
904 is closed. This could make debugging Lisp more difficult,
905 for example when doing something like
907 (setq process (start-process ...))
908 (debug)
909 (set-process-filter process ...) */
911 if (p->infd >= 0)
913 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
915 FD_CLR (p->infd, &input_wait_mask);
916 FD_CLR (p->infd, &non_keyboard_wait_mask);
918 else if (EQ (p->filter, Qt)
919 /* Network or serial process not stopped: */
920 && !EQ (p->command, Qt))
922 FD_SET (p->infd, &input_wait_mask);
923 FD_SET (p->infd, &non_keyboard_wait_mask);
927 p->filter = filter;
928 if (NETCONN1_P (p) || SERIALCONN1_P (p))
929 p->childp = Fplist_put (p->childp, QCfilter, filter);
930 setup_process_coding_systems (process);
931 return filter;
934 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
935 1, 1, 0,
936 doc: /* Returns the filter function of PROCESS; nil if none.
937 See `set-process-filter' for more info on filter functions. */)
938 (register Lisp_Object process)
940 CHECK_PROCESS (process);
941 return XPROCESS (process)->filter;
944 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
945 2, 2, 0,
946 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
947 The sentinel is called as a function when the process changes state.
948 It gets two arguments: the process, and a string describing the change. */)
949 (register Lisp_Object process, Lisp_Object sentinel)
951 struct Lisp_Process *p;
953 CHECK_PROCESS (process);
954 p = XPROCESS (process);
956 p->sentinel = sentinel;
957 if (NETCONN1_P (p) || SERIALCONN1_P (p))
958 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
959 return sentinel;
962 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
963 1, 1, 0,
964 doc: /* Return the sentinel of PROCESS; nil if none.
965 See `set-process-sentinel' for more info on sentinels. */)
966 (register Lisp_Object process)
968 CHECK_PROCESS (process);
969 return XPROCESS (process)->sentinel;
972 DEFUN ("set-process-window-size", Fset_process_window_size,
973 Sset_process_window_size, 3, 3, 0,
974 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
975 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
977 CHECK_PROCESS (process);
978 CHECK_NATNUM (height);
979 CHECK_NATNUM (width);
981 if (XPROCESS (process)->infd < 0
982 || set_window_size (XPROCESS (process)->infd,
983 XINT (height), XINT (width)) <= 0)
984 return Qnil;
985 else
986 return Qt;
989 DEFUN ("set-process-inherit-coding-system-flag",
990 Fset_process_inherit_coding_system_flag,
991 Sset_process_inherit_coding_system_flag, 2, 2, 0,
992 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
993 If the second argument FLAG is non-nil, then the variable
994 `buffer-file-coding-system' of the buffer associated with PROCESS
995 will be bound to the value of the coding system used to decode
996 the process output.
998 This is useful when the coding system specified for the process buffer
999 leaves either the character code conversion or the end-of-line conversion
1000 unspecified, or if the coding system used to decode the process output
1001 is more appropriate for saving the process buffer.
1003 Binding the variable `inherit-process-coding-system' to non-nil before
1004 starting the process is an alternative way of setting the inherit flag
1005 for the process which will run. */)
1006 (register Lisp_Object process, Lisp_Object flag)
1008 CHECK_PROCESS (process);
1009 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1010 return flag;
1013 DEFUN ("set-process-query-on-exit-flag",
1014 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1015 2, 2, 0,
1016 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1017 If the second argument FLAG is non-nil, Emacs will query the user before
1018 exiting or killing a buffer if PROCESS is running. */)
1019 (register Lisp_Object process, Lisp_Object flag)
1021 CHECK_PROCESS (process);
1022 XPROCESS (process)->kill_without_query = NILP (flag);
1023 return flag;
1026 DEFUN ("process-query-on-exit-flag",
1027 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1028 1, 1, 0,
1029 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1030 (register Lisp_Object process)
1032 CHECK_PROCESS (process);
1033 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1036 #ifdef DATAGRAM_SOCKETS
1037 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1038 #endif
1040 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1041 1, 2, 0,
1042 doc: /* Return the contact info of PROCESS; t for a real child.
1043 For a network or serial connection, the value depends on the optional
1044 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1045 SERVICE) for a network connection or (PORT SPEED) for a serial
1046 connection. If KEY is t, the complete contact information for the
1047 connection is returned, else the specific value for the keyword KEY is
1048 returned. See `make-network-process' or `make-serial-process' for a
1049 list of keywords. */)
1050 (register Lisp_Object process, Lisp_Object key)
1052 Lisp_Object contact;
1054 CHECK_PROCESS (process);
1055 contact = XPROCESS (process)->childp;
1057 #ifdef DATAGRAM_SOCKETS
1058 if (DATAGRAM_CONN_P (process)
1059 && (EQ (key, Qt) || EQ (key, QCremote)))
1060 contact = Fplist_put (contact, QCremote,
1061 Fprocess_datagram_address (process));
1062 #endif
1064 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1065 return contact;
1066 if (NILP (key) && NETCONN_P (process))
1067 return Fcons (Fplist_get (contact, QChost),
1068 Fcons (Fplist_get (contact, QCservice), Qnil));
1069 if (NILP (key) && SERIALCONN_P (process))
1070 return Fcons (Fplist_get (contact, QCport),
1071 Fcons (Fplist_get (contact, QCspeed), Qnil));
1072 return Fplist_get (contact, key);
1075 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1076 1, 1, 0,
1077 doc: /* Return the plist of PROCESS. */)
1078 (register Lisp_Object process)
1080 CHECK_PROCESS (process);
1081 return XPROCESS (process)->plist;
1084 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1085 2, 2, 0,
1086 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1087 (register Lisp_Object process, Lisp_Object plist)
1089 CHECK_PROCESS (process);
1090 CHECK_LIST (plist);
1092 XPROCESS (process)->plist = plist;
1093 return plist;
1096 #if 0 /* Turned off because we don't currently record this info
1097 in the process. Perhaps add it. */
1098 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1099 doc: /* Return the connection type of PROCESS.
1100 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1101 a socket connection. */)
1102 (Lisp_Object process)
1104 return XPROCESS (process)->type;
1106 #endif
1108 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1109 doc: /* Return the connection type of PROCESS.
1110 The value is either the symbol `real', `network', or `serial'.
1111 PROCESS may be a process, a buffer, the name of a process or buffer, or
1112 nil, indicating the current buffer's process. */)
1113 (Lisp_Object process)
1115 Lisp_Object proc;
1116 proc = get_process (process);
1117 return XPROCESS (proc)->type;
1120 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1121 1, 2, 0,
1122 doc: /* Convert network ADDRESS from internal format to a string.
1123 A 4 or 5 element vector represents an IPv4 address (with port number).
1124 An 8 or 9 element vector represents an IPv6 address (with port number).
1125 If optional second argument OMIT-PORT is non-nil, don't include a port
1126 number in the string, even when present in ADDRESS.
1127 Returns nil if format of ADDRESS is invalid. */)
1128 (Lisp_Object address, Lisp_Object omit_port)
1130 if (NILP (address))
1131 return Qnil;
1133 if (STRINGP (address)) /* AF_LOCAL */
1134 return address;
1136 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1138 register struct Lisp_Vector *p = XVECTOR (address);
1139 Lisp_Object args[10];
1140 int nargs, i;
1142 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1144 args[0] = build_string ("%d.%d.%d.%d");
1145 nargs = 4;
1147 else if (p->size == 5)
1149 args[0] = build_string ("%d.%d.%d.%d:%d");
1150 nargs = 5;
1152 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1154 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1155 nargs = 8;
1157 else if (p->size == 9)
1159 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1160 nargs = 9;
1162 else
1163 return Qnil;
1165 for (i = 0; i < nargs; i++)
1167 EMACS_INT element = XINT (p->contents[i]);
1169 if (element < 0 || element > 65535)
1170 return Qnil;
1172 if (nargs <= 5 /* IPv4 */
1173 && i < 4 /* host, not port */
1174 && element > 255)
1175 return Qnil;
1177 args[i+1] = p->contents[i];
1180 return Fformat (nargs+1, args);
1183 if (CONSP (address))
1185 Lisp_Object args[2];
1186 args[0] = build_string ("<Family %d>");
1187 args[1] = Fcar (address);
1188 return Fformat (2, args);
1191 return Qnil;
1194 static Lisp_Object
1195 list_processes_1 (Lisp_Object query_only)
1197 register Lisp_Object tail, tem;
1198 Lisp_Object proc, minspace, tem1;
1199 register struct Lisp_Process *p;
1200 char tembuf[300];
1201 int w_proc, w_buffer, w_tty;
1202 int exited = 0;
1203 Lisp_Object i_status, i_buffer, i_tty, i_command;
1205 w_proc = 4; /* Proc */
1206 w_buffer = 6; /* Buffer */
1207 w_tty = 0; /* Omit if no ttys */
1209 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1211 int i;
1213 proc = Fcdr (XCAR (tail));
1214 p = XPROCESS (proc);
1215 if (NILP (p->type))
1216 continue;
1217 if (!NILP (query_only) && p->kill_without_query)
1218 continue;
1219 if (STRINGP (p->name)
1220 && ( i = SCHARS (p->name), (i > w_proc)))
1221 w_proc = i;
1222 if (!NILP (p->buffer))
1224 if (NILP (XBUFFER (p->buffer)->name))
1226 if (w_buffer < 8)
1227 w_buffer = 8; /* (Killed) */
1229 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1230 w_buffer = i;
1232 if (STRINGP (p->tty_name)
1233 && (i = SCHARS (p->tty_name), (i > w_tty)))
1234 w_tty = i;
1237 XSETFASTINT (i_status, w_proc + 1);
1238 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1239 if (w_tty)
1241 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1242 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1244 else
1246 i_tty = Qnil;
1247 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1250 XSETFASTINT (minspace, 1);
1252 set_buffer_internal (XBUFFER (Vstandard_output));
1253 current_buffer->undo_list = Qt;
1255 current_buffer->truncate_lines = Qt;
1257 write_string ("Proc", -1);
1258 Findent_to (i_status, minspace); write_string ("Status", -1);
1259 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1260 if (!NILP (i_tty))
1262 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1264 Findent_to (i_command, minspace); write_string ("Command", -1);
1265 write_string ("\n", -1);
1267 write_string ("----", -1);
1268 Findent_to (i_status, minspace); write_string ("------", -1);
1269 Findent_to (i_buffer, minspace); write_string ("------", -1);
1270 if (!NILP (i_tty))
1272 Findent_to (i_tty, minspace); write_string ("---", -1);
1274 Findent_to (i_command, minspace); write_string ("-------", -1);
1275 write_string ("\n", -1);
1277 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1279 Lisp_Object symbol;
1281 proc = Fcdr (XCAR (tail));
1282 p = XPROCESS (proc);
1283 if (NILP (p->type))
1284 continue;
1285 if (!NILP (query_only) && p->kill_without_query)
1286 continue;
1288 Finsert (1, &p->name);
1289 Findent_to (i_status, minspace);
1291 if (p->raw_status_new)
1292 update_status (p);
1293 symbol = p->status;
1294 if (CONSP (p->status))
1295 symbol = XCAR (p->status);
1297 if (EQ (symbol, Qsignal))
1299 Lisp_Object tem;
1300 tem = Fcar (Fcdr (p->status));
1301 Fprinc (symbol, Qnil);
1303 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1305 if (EQ (symbol, Qexit))
1306 write_string ("closed", -1);
1307 else if (EQ (p->command, Qt))
1308 write_string ("stopped", -1);
1309 else if (EQ (symbol, Qrun))
1310 write_string ("open", -1);
1311 else
1312 Fprinc (symbol, Qnil);
1314 else if (SERIALCONN1_P (p))
1316 write_string ("running", -1);
1318 else
1319 Fprinc (symbol, Qnil);
1321 if (EQ (symbol, Qexit))
1323 Lisp_Object tem;
1324 tem = Fcar (Fcdr (p->status));
1325 if (XFASTINT (tem))
1327 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1328 write_string (tembuf, -1);
1332 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1333 exited++;
1335 Findent_to (i_buffer, minspace);
1336 if (NILP (p->buffer))
1337 insert_string ("(none)");
1338 else if (NILP (XBUFFER (p->buffer)->name))
1339 insert_string ("(Killed)");
1340 else
1341 Finsert (1, &XBUFFER (p->buffer)->name);
1343 if (!NILP (i_tty))
1345 Findent_to (i_tty, minspace);
1346 if (STRINGP (p->tty_name))
1347 Finsert (1, &p->tty_name);
1350 Findent_to (i_command, minspace);
1352 if (EQ (p->status, Qlisten))
1354 Lisp_Object port = Fplist_get (p->childp, QCservice);
1355 if (INTEGERP (port))
1356 port = Fnumber_to_string (port);
1357 if (NILP (port))
1358 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1359 sprintf (tembuf, "(network %s server on %s)\n",
1360 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1361 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1362 insert_string (tembuf);
1364 else if (NETCONN1_P (p))
1366 /* For a local socket, there is no host name,
1367 so display service instead. */
1368 Lisp_Object host = Fplist_get (p->childp, QChost);
1369 if (!STRINGP (host))
1371 host = Fplist_get (p->childp, QCservice);
1372 if (INTEGERP (host))
1373 host = Fnumber_to_string (host);
1375 if (NILP (host))
1376 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1377 sprintf (tembuf, "(network %s connection to %s)\n",
1378 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1379 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1380 insert_string (tembuf);
1382 else if (SERIALCONN1_P (p))
1384 Lisp_Object port = Fplist_get (p->childp, QCport);
1385 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1386 insert_string ("(serial port ");
1387 if (STRINGP (port))
1388 insert_string (SDATA (port));
1389 else
1390 insert_string ("?");
1391 if (INTEGERP (speed))
1393 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1394 insert_string (tembuf);
1396 insert_string (")\n");
1398 else
1400 tem = p->command;
1401 while (1)
1403 tem1 = Fcar (tem);
1404 if (NILP (tem1))
1405 break;
1406 Finsert (1, &tem1);
1407 tem = Fcdr (tem);
1408 if (NILP (tem))
1409 break;
1410 insert_string (" ");
1412 insert_string ("\n");
1415 if (exited)
1417 status_notify (NULL);
1418 redisplay_preserve_echo_area (13);
1420 return Qnil;
1423 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1424 doc: /* Display a list of all processes.
1425 If optional argument QUERY-ONLY is non-nil, only processes with
1426 the query-on-exit flag set will be listed.
1427 Any process listed as exited or signaled is actually eliminated
1428 after the listing is made. */)
1429 (Lisp_Object query_only)
1431 internal_with_output_to_temp_buffer ("*Process List*",
1432 list_processes_1, query_only);
1433 return Qnil;
1436 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1437 doc: /* Return a list of all processes. */)
1438 (void)
1440 return Fmapcar (Qcdr, Vprocess_alist);
1443 /* Starting asynchronous inferior processes. */
1445 static Lisp_Object start_process_unwind (Lisp_Object proc);
1447 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1448 doc: /* Start a program in a subprocess. Return the process object for it.
1449 NAME is name for process. It is modified if necessary to make it unique.
1450 BUFFER is the buffer (or buffer name) to associate with the process.
1452 Process output (both standard output and standard error streams) goes
1453 at end of BUFFER, unless you specify an output stream or filter
1454 function to handle the output. BUFFER may also be nil, meaning that
1455 this process is not associated with any buffer.
1457 PROGRAM is the program file name. It is searched for in PATH. If
1458 nil, just associate a pty with the buffer. Remaining arguments are
1459 strings to give program as arguments.
1461 If you want to separate standard output from standard error, invoke
1462 the command through a shell and redirect one of them using the shell
1463 syntax.
1465 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1466 (int nargs, register Lisp_Object *args)
1468 Lisp_Object buffer, name, program, proc, current_dir, tem;
1469 register unsigned char **new_argv;
1470 register int i;
1471 int count = SPECPDL_INDEX ();
1473 buffer = args[1];
1474 if (!NILP (buffer))
1475 buffer = Fget_buffer_create (buffer);
1477 /* Make sure that the child will be able to chdir to the current
1478 buffer's current directory, or its unhandled equivalent. We
1479 can't just have the child check for an error when it does the
1480 chdir, since it's in a vfork.
1482 We have to GCPRO around this because Fexpand_file_name and
1483 Funhandled_file_name_directory might call a file name handling
1484 function. The argument list is protected by the caller, so all
1485 we really have to worry about is buffer. */
1487 struct gcpro gcpro1, gcpro2;
1489 current_dir = current_buffer->directory;
1491 GCPRO2 (buffer, current_dir);
1493 current_dir = Funhandled_file_name_directory (current_dir);
1494 if (NILP (current_dir))
1495 /* If the file name handler says that current_dir is unreachable, use
1496 a sensible default. */
1497 current_dir = build_string ("~/");
1498 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1499 if (NILP (Ffile_accessible_directory_p (current_dir)))
1500 report_file_error ("Setting current directory",
1501 Fcons (current_buffer->directory, Qnil));
1503 UNGCPRO;
1506 name = args[0];
1507 CHECK_STRING (name);
1509 program = args[2];
1511 if (!NILP (program))
1512 CHECK_STRING (program);
1514 proc = make_process (name);
1515 /* If an error occurs and we can't start the process, we want to
1516 remove it from the process list. This means that each error
1517 check in create_process doesn't need to call remove_process
1518 itself; it's all taken care of here. */
1519 record_unwind_protect (start_process_unwind, proc);
1521 XPROCESS (proc)->childp = Qt;
1522 XPROCESS (proc)->plist = Qnil;
1523 XPROCESS (proc)->type = Qreal;
1524 XPROCESS (proc)->buffer = buffer;
1525 XPROCESS (proc)->sentinel = Qnil;
1526 XPROCESS (proc)->filter = Qnil;
1527 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1529 #ifdef ADAPTIVE_READ_BUFFERING
1530 XPROCESS (proc)->adaptive_read_buffering
1531 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1532 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1533 #endif
1535 /* Make the process marker point into the process buffer (if any). */
1536 if (BUFFERP (buffer))
1537 set_marker_both (XPROCESS (proc)->mark, buffer,
1538 BUF_ZV (XBUFFER (buffer)),
1539 BUF_ZV_BYTE (XBUFFER (buffer)));
1542 /* Decide coding systems for communicating with the process. Here
1543 we don't setup the structure coding_system nor pay attention to
1544 unibyte mode. They are done in create_process. */
1546 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1547 Lisp_Object coding_systems = Qt;
1548 Lisp_Object val, *args2;
1549 struct gcpro gcpro1, gcpro2;
1551 val = Vcoding_system_for_read;
1552 if (NILP (val))
1554 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1555 args2[0] = Qstart_process;
1556 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1557 GCPRO2 (proc, current_dir);
1558 if (!NILP (program))
1559 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1560 UNGCPRO;
1561 if (CONSP (coding_systems))
1562 val = XCAR (coding_systems);
1563 else if (CONSP (Vdefault_process_coding_system))
1564 val = XCAR (Vdefault_process_coding_system);
1566 XPROCESS (proc)->decode_coding_system = val;
1568 val = Vcoding_system_for_write;
1569 if (NILP (val))
1571 if (EQ (coding_systems, Qt))
1573 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1574 args2[0] = Qstart_process;
1575 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1576 GCPRO2 (proc, current_dir);
1577 if (!NILP (program))
1578 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1579 UNGCPRO;
1581 if (CONSP (coding_systems))
1582 val = XCDR (coding_systems);
1583 else if (CONSP (Vdefault_process_coding_system))
1584 val = XCDR (Vdefault_process_coding_system);
1586 XPROCESS (proc)->encode_coding_system = val;
1590 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1591 XPROCESS (proc)->decoding_carryover = 0;
1592 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1594 XPROCESS (proc)->inherit_coding_system_flag
1595 = !(NILP (buffer) || !inherit_process_coding_system);
1597 if (!NILP (program))
1599 /* If program file name is not absolute, search our path for it.
1600 Put the name we will really use in TEM. */
1601 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1602 && !(SCHARS (program) > 1
1603 && IS_DEVICE_SEP (SREF (program, 1))))
1605 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1607 tem = Qnil;
1608 GCPRO4 (name, program, buffer, current_dir);
1609 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1610 UNGCPRO;
1611 if (NILP (tem))
1612 report_file_error ("Searching for program", Fcons (program, Qnil));
1613 tem = Fexpand_file_name (tem, Qnil);
1615 else
1617 if (!NILP (Ffile_directory_p (program)))
1618 error ("Specified program for new process is a directory");
1619 tem = program;
1622 /* If program file name starts with /: for quoting a magic name,
1623 discard that. */
1624 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1625 && SREF (tem, 1) == ':')
1626 tem = Fsubstring (tem, make_number (2), Qnil);
1629 struct gcpro gcpro1;
1630 GCPRO1 (tem);
1632 /* Encode the file name and put it in NEW_ARGV.
1633 That's where the child will use it to execute the program. */
1634 tem = Fcons (ENCODE_FILE (tem), Qnil);
1636 /* Here we encode arguments by the coding system used for sending
1637 data to the process. We don't support using different coding
1638 systems for encoding arguments and for encoding data sent to the
1639 process. */
1641 for (i = 3; i < nargs; i++)
1643 tem = Fcons (args[i], tem);
1644 CHECK_STRING (XCAR (tem));
1645 if (STRING_MULTIBYTE (XCAR (tem)))
1646 XSETCAR (tem,
1647 code_convert_string_norecord
1648 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1651 UNGCPRO;
1654 /* Now that everything is encoded we can collect the strings into
1655 NEW_ARGV. */
1656 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1657 new_argv[nargs - 2] = 0;
1659 for (i = nargs - 3; i >= 0; i--)
1661 new_argv[i] = SDATA (XCAR (tem));
1662 tem = XCDR (tem);
1665 create_process (proc, (char **) new_argv, current_dir);
1667 else
1668 create_pty (proc);
1670 return unbind_to (count, proc);
1673 /* This function is the unwind_protect form for Fstart_process. If
1674 PROC doesn't have its pid set, then we know someone has signaled
1675 an error and the process wasn't started successfully, so we should
1676 remove it from the process list. */
1677 static Lisp_Object
1678 start_process_unwind (Lisp_Object proc)
1680 if (!PROCESSP (proc))
1681 abort ();
1683 /* Was PROC started successfully? */
1684 if (XPROCESS (proc)->pid == -1)
1685 remove_process (proc);
1687 return Qnil;
1690 static void
1691 create_process_1 (struct atimer *timer)
1693 /* Nothing to do. */
1697 void
1698 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1700 int inchannel, outchannel;
1701 pid_t pid;
1702 int sv[2];
1703 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1704 int wait_child_setup[2];
1705 #endif
1706 sigset_t procmask;
1707 sigset_t blocked;
1708 struct sigaction sigint_action;
1709 struct sigaction sigquit_action;
1710 #ifdef AIX
1711 struct sigaction sighup_action;
1712 #endif
1713 /* Use volatile to protect variables from being clobbered by longjmp. */
1714 volatile int forkin, forkout;
1715 volatile int pty_flag = 0;
1716 #ifndef USE_CRT_DLL
1717 extern char **environ;
1718 #endif
1720 inchannel = outchannel = -1;
1722 #ifdef HAVE_PTYS
1723 if (!NILP (Vprocess_connection_type))
1724 outchannel = inchannel = allocate_pty ();
1726 if (inchannel >= 0)
1728 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1729 /* On most USG systems it does not work to open the pty's tty here,
1730 then close it and reopen it in the child. */
1731 #ifdef O_NOCTTY
1732 /* Don't let this terminal become our controlling terminal
1733 (in case we don't have one). */
1734 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1735 #else
1736 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1737 #endif
1738 if (forkin < 0)
1739 report_file_error ("Opening pty", Qnil);
1740 #else
1741 forkin = forkout = -1;
1742 #endif /* not USG, or USG_SUBTTY_WORKS */
1743 pty_flag = 1;
1745 else
1746 #endif /* HAVE_PTYS */
1748 int tem;
1749 tem = pipe (sv);
1750 if (tem < 0)
1751 report_file_error ("Creating pipe", Qnil);
1752 inchannel = sv[0];
1753 forkout = sv[1];
1754 tem = pipe (sv);
1755 if (tem < 0)
1757 emacs_close (inchannel);
1758 emacs_close (forkout);
1759 report_file_error ("Creating pipe", Qnil);
1761 outchannel = sv[1];
1762 forkin = sv[0];
1765 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1767 int tem;
1769 tem = pipe (wait_child_setup);
1770 if (tem < 0)
1771 report_file_error ("Creating pipe", Qnil);
1772 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1773 if (tem >= 0)
1774 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1775 if (tem < 0)
1777 emacs_close (wait_child_setup[0]);
1778 emacs_close (wait_child_setup[1]);
1779 report_file_error ("Setting file descriptor flags", Qnil);
1782 #endif
1784 #if 0
1785 /* Replaced by close_process_descs */
1786 set_exclusive_use (inchannel);
1787 set_exclusive_use (outchannel);
1788 #endif
1790 #ifdef O_NONBLOCK
1791 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1792 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1793 #else
1794 #ifdef O_NDELAY
1795 fcntl (inchannel, F_SETFL, O_NDELAY);
1796 fcntl (outchannel, F_SETFL, O_NDELAY);
1797 #endif
1798 #endif
1800 /* Record this as an active process, with its channels.
1801 As a result, child_setup will close Emacs's side of the pipes. */
1802 chan_process[inchannel] = process;
1803 XPROCESS (process)->infd = inchannel;
1804 XPROCESS (process)->outfd = outchannel;
1806 /* Previously we recorded the tty descriptor used in the subprocess.
1807 It was only used for getting the foreground tty process, so now
1808 we just reopen the device (see emacs_get_tty_pgrp) as this is
1809 more portable (see USG_SUBTTY_WORKS above). */
1811 XPROCESS (process)->pty_flag = pty_flag;
1812 XPROCESS (process)->status = Qrun;
1813 setup_process_coding_systems (process);
1815 /* Delay interrupts until we have a chance to store
1816 the new fork's pid in its process structure */
1817 sigemptyset (&blocked);
1818 #ifdef SIGCHLD
1819 sigaddset (&blocked, SIGCHLD);
1820 #endif
1821 #ifdef HAVE_WORKING_VFORK
1822 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1823 this sets the parent's signal handlers as well as the child's.
1824 So delay all interrupts whose handlers the child might munge,
1825 and record the current handlers so they can be restored later. */
1826 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1827 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1828 #ifdef AIX
1829 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1830 #endif
1831 #endif /* HAVE_WORKING_VFORK */
1832 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1834 FD_SET (inchannel, &input_wait_mask);
1835 FD_SET (inchannel, &non_keyboard_wait_mask);
1836 if (inchannel > max_process_desc)
1837 max_process_desc = inchannel;
1839 /* Until we store the proper pid, enable sigchld_handler
1840 to recognize an unknown pid as standing for this process.
1841 It is very important not to let this `marker' value stay
1842 in the table after this function has returned; if it does
1843 it might cause call-process to hang and subsequent asynchronous
1844 processes to get their return values scrambled. */
1845 XPROCESS (process)->pid = -1;
1847 BLOCK_INPUT;
1850 /* child_setup must clobber environ on systems with true vfork.
1851 Protect it from permanent change. */
1852 char **save_environ = environ;
1854 current_dir = ENCODE_FILE (current_dir);
1856 #ifndef WINDOWSNT
1857 pid = vfork ();
1858 if (pid == 0)
1859 #endif /* not WINDOWSNT */
1861 int xforkin = forkin;
1862 int xforkout = forkout;
1864 #if 0 /* This was probably a mistake--it duplicates code later on,
1865 but fails to handle all the cases. */
1866 /* Make sure SIGCHLD is not blocked in the child. */
1867 sigsetmask (SIGEMPTYMASK);
1868 #endif
1870 /* Make the pty be the controlling terminal of the process. */
1871 #ifdef HAVE_PTYS
1872 /* First, disconnect its current controlling terminal. */
1873 #ifdef HAVE_SETSID
1874 /* We tried doing setsid only if pty_flag, but it caused
1875 process_set_signal to fail on SGI when using a pipe. */
1876 setsid ();
1877 /* Make the pty's terminal the controlling terminal. */
1878 if (pty_flag && xforkin >= 0)
1880 #ifdef TIOCSCTTY
1881 /* We ignore the return value
1882 because faith@cs.unc.edu says that is necessary on Linux. */
1883 ioctl (xforkin, TIOCSCTTY, 0);
1884 #endif
1886 #else /* not HAVE_SETSID */
1887 #ifdef USG
1888 /* It's very important to call setpgrp here and no time
1889 afterwards. Otherwise, we lose our controlling tty which
1890 is set when we open the pty. */
1891 setpgrp ();
1892 #endif /* USG */
1893 #endif /* not HAVE_SETSID */
1894 #if defined (LDISC1)
1895 if (pty_flag && xforkin >= 0)
1897 struct termios t;
1898 tcgetattr (xforkin, &t);
1899 t.c_lflag = LDISC1;
1900 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1901 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1903 #else
1904 #if defined (NTTYDISC) && defined (TIOCSETD)
1905 if (pty_flag && xforkin >= 0)
1907 /* Use new line discipline. */
1908 int ldisc = NTTYDISC;
1909 ioctl (xforkin, TIOCSETD, &ldisc);
1911 #endif
1912 #endif
1913 #ifdef TIOCNOTTY
1914 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1915 can do TIOCSPGRP only to the process's controlling tty. */
1916 if (pty_flag)
1918 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1919 I can't test it since I don't have 4.3. */
1920 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1921 if (j >= 0)
1923 ioctl (j, TIOCNOTTY, 0);
1924 emacs_close (j);
1926 #ifndef USG
1927 /* In order to get a controlling terminal on some versions
1928 of BSD, it is necessary to put the process in pgrp 0
1929 before it opens the terminal. */
1930 #ifdef HAVE_SETPGID
1931 setpgid (0, 0);
1932 #else
1933 setpgrp (0, 0);
1934 #endif
1935 #endif
1937 #endif /* TIOCNOTTY */
1939 #if !defined (DONT_REOPEN_PTY)
1940 /*** There is a suggestion that this ought to be a
1941 conditional on TIOCSPGRP,
1942 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1943 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1944 that system does seem to need this code, even though
1945 both HAVE_SETSID and TIOCSCTTY are defined. */
1946 /* Now close the pty (if we had it open) and reopen it.
1947 This makes the pty the controlling terminal of the subprocess. */
1948 if (pty_flag)
1951 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1952 would work? */
1953 if (xforkin >= 0)
1954 emacs_close (xforkin);
1955 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1957 if (xforkin < 0)
1959 emacs_write (1, "Couldn't open the pty terminal ", 31);
1960 emacs_write (1, pty_name, strlen (pty_name));
1961 emacs_write (1, "\n", 1);
1962 _exit (1);
1966 #endif /* not DONT_REOPEN_PTY */
1968 #ifdef SETUP_SLAVE_PTY
1969 if (pty_flag)
1971 SETUP_SLAVE_PTY;
1973 #endif /* SETUP_SLAVE_PTY */
1974 #ifdef AIX
1975 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1976 Now reenable it in the child, so it will die when we want it to. */
1977 if (pty_flag)
1978 signal (SIGHUP, SIG_DFL);
1979 #endif
1980 #endif /* HAVE_PTYS */
1982 signal (SIGINT, SIG_DFL);
1983 signal (SIGQUIT, SIG_DFL);
1985 /* Stop blocking signals in the child. */
1986 sigprocmask (SIG_SETMASK, &procmask, 0);
1988 if (pty_flag)
1989 child_setup_tty (xforkout);
1990 #ifdef WINDOWSNT
1991 pid = child_setup (xforkin, xforkout, xforkout,
1992 new_argv, 1, current_dir);
1993 #else /* not WINDOWSNT */
1994 #ifdef FD_CLOEXEC
1995 emacs_close (wait_child_setup[0]);
1996 #endif
1997 child_setup (xforkin, xforkout, xforkout,
1998 new_argv, 1, current_dir);
1999 #endif /* not WINDOWSNT */
2001 environ = save_environ;
2004 UNBLOCK_INPUT;
2006 /* This runs in the Emacs process. */
2007 if (pid < 0)
2009 if (forkin >= 0)
2010 emacs_close (forkin);
2011 if (forkin != forkout && forkout >= 0)
2012 emacs_close (forkout);
2014 else
2016 /* vfork succeeded. */
2017 XPROCESS (process)->pid = pid;
2019 #ifdef WINDOWSNT
2020 register_child (pid, inchannel);
2021 #endif /* WINDOWSNT */
2023 /* If the subfork execv fails, and it exits,
2024 this close hangs. I don't know why.
2025 So have an interrupt jar it loose. */
2027 struct atimer *timer;
2028 EMACS_TIME offset;
2030 stop_polling ();
2031 EMACS_SET_SECS_USECS (offset, 1, 0);
2032 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2034 if (forkin >= 0)
2035 emacs_close (forkin);
2037 cancel_atimer (timer);
2038 start_polling ();
2041 if (forkin != forkout && forkout >= 0)
2042 emacs_close (forkout);
2044 #ifdef HAVE_PTYS
2045 if (pty_flag)
2046 XPROCESS (process)->tty_name = build_string (pty_name);
2047 else
2048 #endif
2049 XPROCESS (process)->tty_name = Qnil;
2051 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2052 /* Wait for child_setup to complete in case that vfork is
2053 actually defined as fork. The descriptor wait_child_setup[1]
2054 of a pipe is closed at the child side either by close-on-exec
2055 on successful execvp or the _exit call in child_setup. */
2057 char dummy;
2059 emacs_close (wait_child_setup[1]);
2060 emacs_read (wait_child_setup[0], &dummy, 1);
2061 emacs_close (wait_child_setup[0]);
2063 #endif
2066 /* Restore the signal state whether vfork succeeded or not.
2067 (We will signal an error, below, if it failed.) */
2068 #ifdef HAVE_WORKING_VFORK
2069 /* Restore the parent's signal handlers. */
2070 sigaction (SIGINT, &sigint_action, 0);
2071 sigaction (SIGQUIT, &sigquit_action, 0);
2072 #ifdef AIX
2073 sigaction (SIGHUP, &sighup_action, 0);
2074 #endif
2075 #endif /* HAVE_WORKING_VFORK */
2076 /* Stop blocking signals in the parent. */
2077 sigprocmask (SIG_SETMASK, &procmask, 0);
2079 /* Now generate the error if vfork failed. */
2080 if (pid < 0)
2081 report_file_error ("Doing vfork", Qnil);
2084 void
2085 create_pty (Lisp_Object process)
2087 int inchannel, outchannel;
2089 /* Use volatile to protect variables from being clobbered by longjmp. */
2090 volatile int forkin, forkout;
2091 volatile int pty_flag = 0;
2093 inchannel = outchannel = -1;
2095 #ifdef HAVE_PTYS
2096 if (!NILP (Vprocess_connection_type))
2097 outchannel = inchannel = allocate_pty ();
2099 if (inchannel >= 0)
2101 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2102 /* On most USG systems it does not work to open the pty's tty here,
2103 then close it and reopen it in the child. */
2104 #ifdef O_NOCTTY
2105 /* Don't let this terminal become our controlling terminal
2106 (in case we don't have one). */
2107 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2108 #else
2109 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2110 #endif
2111 if (forkin < 0)
2112 report_file_error ("Opening pty", Qnil);
2113 #if defined (DONT_REOPEN_PTY)
2114 /* In the case that vfork is defined as fork, the parent process
2115 (Emacs) may send some data before the child process completes
2116 tty options setup. So we setup tty before forking. */
2117 child_setup_tty (forkout);
2118 #endif /* DONT_REOPEN_PTY */
2119 #else
2120 forkin = forkout = -1;
2121 #endif /* not USG, or USG_SUBTTY_WORKS */
2122 pty_flag = 1;
2124 #endif /* HAVE_PTYS */
2126 #ifdef O_NONBLOCK
2127 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2128 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2129 #else
2130 #ifdef O_NDELAY
2131 fcntl (inchannel, F_SETFL, O_NDELAY);
2132 fcntl (outchannel, F_SETFL, O_NDELAY);
2133 #endif
2134 #endif
2136 /* Record this as an active process, with its channels.
2137 As a result, child_setup will close Emacs's side of the pipes. */
2138 chan_process[inchannel] = process;
2139 XPROCESS (process)->infd = inchannel;
2140 XPROCESS (process)->outfd = outchannel;
2142 /* Previously we recorded the tty descriptor used in the subprocess.
2143 It was only used for getting the foreground tty process, so now
2144 we just reopen the device (see emacs_get_tty_pgrp) as this is
2145 more portable (see USG_SUBTTY_WORKS above). */
2147 XPROCESS (process)->pty_flag = pty_flag;
2148 XPROCESS (process)->status = Qrun;
2149 setup_process_coding_systems (process);
2151 FD_SET (inchannel, &input_wait_mask);
2152 FD_SET (inchannel, &non_keyboard_wait_mask);
2153 if (inchannel > max_process_desc)
2154 max_process_desc = inchannel;
2156 XPROCESS (process)->pid = -2;
2157 #ifdef HAVE_PTYS
2158 if (pty_flag)
2159 XPROCESS (process)->tty_name = build_string (pty_name);
2160 else
2161 #endif
2162 XPROCESS (process)->tty_name = Qnil;
2166 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2167 The address family of sa is not included in the result. */
2169 static Lisp_Object
2170 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2172 Lisp_Object address;
2173 int i;
2174 unsigned char *cp;
2175 register struct Lisp_Vector *p;
2177 /* Workaround for a bug in getsockname on BSD: Names bound to
2178 sockets in the UNIX domain are inaccessible; getsockname returns
2179 a zero length name. */
2180 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2181 return empty_unibyte_string;
2183 switch (sa->sa_family)
2185 case AF_INET:
2187 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2188 len = sizeof (sin->sin_addr) + 1;
2189 address = Fmake_vector (make_number (len), Qnil);
2190 p = XVECTOR (address);
2191 p->contents[--len] = make_number (ntohs (sin->sin_port));
2192 cp = (unsigned char *) &sin->sin_addr;
2193 break;
2195 #ifdef AF_INET6
2196 case AF_INET6:
2198 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2199 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2200 len = sizeof (sin6->sin6_addr)/2 + 1;
2201 address = Fmake_vector (make_number (len), Qnil);
2202 p = XVECTOR (address);
2203 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2204 for (i = 0; i < len; i++)
2205 p->contents[i] = make_number (ntohs (ip6[i]));
2206 return address;
2208 #endif
2209 #ifdef HAVE_LOCAL_SOCKETS
2210 case AF_LOCAL:
2212 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2213 for (i = 0; i < sizeof (sockun->sun_path); i++)
2214 if (sockun->sun_path[i] == 0)
2215 break;
2216 return make_unibyte_string (sockun->sun_path, i);
2218 #endif
2219 default:
2220 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2221 address = Fcons (make_number (sa->sa_family),
2222 Fmake_vector (make_number (len), Qnil));
2223 p = XVECTOR (XCDR (address));
2224 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2225 break;
2228 i = 0;
2229 while (i < len)
2230 p->contents[i++] = make_number (*cp++);
2232 return address;
2236 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2238 static int
2239 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2241 register struct Lisp_Vector *p;
2243 if (VECTORP (address))
2245 p = XVECTOR (address);
2246 if (p->size == 5)
2248 *familyp = AF_INET;
2249 return sizeof (struct sockaddr_in);
2251 #ifdef AF_INET6
2252 else if (p->size == 9)
2254 *familyp = AF_INET6;
2255 return sizeof (struct sockaddr_in6);
2257 #endif
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 else if (STRINGP (address))
2262 *familyp = AF_LOCAL;
2263 return sizeof (struct sockaddr_un);
2265 #endif
2266 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2268 struct sockaddr *sa;
2269 *familyp = XINT (XCAR (address));
2270 p = XVECTOR (XCDR (address));
2271 return p->size + sizeof (sa->sa_family);
2273 return 0;
2276 /* Convert an address object (vector or string) to an internal sockaddr.
2278 The address format has been basically validated by
2279 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2280 it could have come from user data. So if FAMILY is not valid,
2281 we return after zeroing *SA. */
2283 static void
2284 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2286 register struct Lisp_Vector *p;
2287 register unsigned char *cp = NULL;
2288 register int i;
2290 memset (sa, 0, len);
2292 if (VECTORP (address))
2294 p = XVECTOR (address);
2295 if (family == AF_INET)
2297 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2298 len = sizeof (sin->sin_addr) + 1;
2299 i = XINT (p->contents[--len]);
2300 sin->sin_port = htons (i);
2301 cp = (unsigned char *)&sin->sin_addr;
2302 sa->sa_family = family;
2304 #ifdef AF_INET6
2305 else if (family == AF_INET6)
2307 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2308 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2309 len = sizeof (sin6->sin6_addr) + 1;
2310 i = XINT (p->contents[--len]);
2311 sin6->sin6_port = htons (i);
2312 for (i = 0; i < len; i++)
2313 if (INTEGERP (p->contents[i]))
2315 int j = XFASTINT (p->contents[i]) & 0xffff;
2316 ip6[i] = ntohs (j);
2318 sa->sa_family = family;
2319 return;
2321 #endif
2322 else
2323 return;
2325 else if (STRINGP (address))
2327 #ifdef HAVE_LOCAL_SOCKETS
2328 if (family == AF_LOCAL)
2330 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2331 cp = SDATA (address);
2332 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2333 sockun->sun_path[i] = *cp++;
2334 sa->sa_family = family;
2336 #endif
2337 return;
2339 else
2341 p = XVECTOR (XCDR (address));
2342 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2345 for (i = 0; i < len; i++)
2346 if (INTEGERP (p->contents[i]))
2347 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2350 #ifdef DATAGRAM_SOCKETS
2351 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2352 1, 1, 0,
2353 doc: /* Get the current datagram address associated with PROCESS. */)
2354 (Lisp_Object process)
2356 int channel;
2358 CHECK_PROCESS (process);
2360 if (!DATAGRAM_CONN_P (process))
2361 return Qnil;
2363 channel = XPROCESS (process)->infd;
2364 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2365 datagram_address[channel].len);
2368 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2369 2, 2, 0,
2370 doc: /* Set the datagram address for PROCESS to ADDRESS.
2371 Returns nil upon error setting address, ADDRESS otherwise. */)
2372 (Lisp_Object process, Lisp_Object address)
2374 int channel;
2375 int family, len;
2377 CHECK_PROCESS (process);
2379 if (!DATAGRAM_CONN_P (process))
2380 return Qnil;
2382 channel = XPROCESS (process)->infd;
2384 len = get_lisp_to_sockaddr_size (address, &family);
2385 if (datagram_address[channel].len != len)
2386 return Qnil;
2387 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2388 return address;
2390 #endif
2393 static const struct socket_options {
2394 /* The name of this option. Should be lowercase version of option
2395 name without SO_ prefix. */
2396 const char *name;
2397 /* Option level SOL_... */
2398 int optlevel;
2399 /* Option number SO_... */
2400 int optnum;
2401 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2402 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2403 } socket_options[] =
2405 #ifdef SO_BINDTODEVICE
2406 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2407 #endif
2408 #ifdef SO_BROADCAST
2409 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2410 #endif
2411 #ifdef SO_DONTROUTE
2412 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2413 #endif
2414 #ifdef SO_KEEPALIVE
2415 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2416 #endif
2417 #ifdef SO_LINGER
2418 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2419 #endif
2420 #ifdef SO_OOBINLINE
2421 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2422 #endif
2423 #ifdef SO_PRIORITY
2424 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2425 #endif
2426 #ifdef SO_REUSEADDR
2427 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2428 #endif
2429 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2432 /* Set option OPT to value VAL on socket S.
2434 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2435 Signals an error if setting a known option fails.
2438 static int
2439 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2441 char *name;
2442 const struct socket_options *sopt;
2443 int ret = 0;
2445 CHECK_SYMBOL (opt);
2447 name = (char *) SDATA (SYMBOL_NAME (opt));
2448 for (sopt = socket_options; sopt->name; sopt++)
2449 if (strcmp (name, sopt->name) == 0)
2450 break;
2452 switch (sopt->opttype)
2454 case SOPT_BOOL:
2456 int optval;
2457 optval = NILP (val) ? 0 : 1;
2458 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2459 &optval, sizeof (optval));
2460 break;
2463 case SOPT_INT:
2465 int optval;
2466 if (INTEGERP (val))
2467 optval = XINT (val);
2468 else
2469 error ("Bad option value for %s", name);
2470 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2471 &optval, sizeof (optval));
2472 break;
2475 #ifdef SO_BINDTODEVICE
2476 case SOPT_IFNAME:
2478 char devname[IFNAMSIZ+1];
2480 /* This is broken, at least in the Linux 2.4 kernel.
2481 To unbind, the arg must be a zero integer, not the empty string.
2482 This should work on all systems. KFS. 2003-09-23. */
2483 memset (devname, 0, sizeof devname);
2484 if (STRINGP (val))
2486 char *arg = (char *) SDATA (val);
2487 int len = min (strlen (arg), IFNAMSIZ);
2488 memcpy (devname, arg, len);
2490 else if (!NILP (val))
2491 error ("Bad option value for %s", name);
2492 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2493 devname, IFNAMSIZ);
2494 break;
2496 #endif
2498 #ifdef SO_LINGER
2499 case SOPT_LINGER:
2501 struct linger linger;
2503 linger.l_onoff = 1;
2504 linger.l_linger = 0;
2505 if (INTEGERP (val))
2506 linger.l_linger = XINT (val);
2507 else
2508 linger.l_onoff = NILP (val) ? 0 : 1;
2509 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2510 &linger, sizeof (linger));
2511 break;
2513 #endif
2515 default:
2516 return 0;
2519 if (ret < 0)
2520 report_file_error ("Cannot set network option",
2521 Fcons (opt, Fcons (val, Qnil)));
2522 return (1 << sopt->optbit);
2526 DEFUN ("set-network-process-option",
2527 Fset_network_process_option, Sset_network_process_option,
2528 3, 4, 0,
2529 doc: /* For network process PROCESS set option OPTION to value VALUE.
2530 See `make-network-process' for a list of options and values.
2531 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2532 OPTION is not a supported option, return nil instead; otherwise return t. */)
2533 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2535 int s;
2536 struct Lisp_Process *p;
2538 CHECK_PROCESS (process);
2539 p = XPROCESS (process);
2540 if (!NETCONN1_P (p))
2541 error ("Process is not a network process");
2543 s = p->infd;
2544 if (s < 0)
2545 error ("Process is not running");
2547 if (set_socket_option (s, option, value))
2549 p->childp = Fplist_put (p->childp, option, value);
2550 return Qt;
2553 if (NILP (no_error))
2554 error ("Unknown or unsupported option");
2556 return Qnil;
2560 DEFUN ("serial-process-configure",
2561 Fserial_process_configure,
2562 Sserial_process_configure,
2563 0, MANY, 0,
2564 doc: /* Configure speed, bytesize, etc. of a serial process.
2566 Arguments are specified as keyword/argument pairs. Attributes that
2567 are not given are re-initialized from the process's current
2568 configuration (available via the function `process-contact') or set to
2569 reasonable default values. The following arguments are defined:
2571 :process PROCESS
2572 :name NAME
2573 :buffer BUFFER
2574 :port PORT
2575 -- Any of these arguments can be given to identify the process that is
2576 to be configured. If none of these arguments is given, the current
2577 buffer's process is used.
2579 :speed SPEED -- SPEED is the speed of the serial port in bits per
2580 second, also called baud rate. Any value can be given for SPEED, but
2581 most serial ports work only at a few defined values between 1200 and
2582 115200, with 9600 being the most common value. If SPEED is nil, the
2583 serial port is not configured any further, i.e., all other arguments
2584 are ignored. This may be useful for special serial ports such as
2585 Bluetooth-to-serial converters which can only be configured through AT
2586 commands. A value of nil for SPEED can be used only when passed
2587 through `make-serial-process' or `serial-term'.
2589 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2590 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2592 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2593 `odd' (use odd parity), or the symbol `even' (use even parity). If
2594 PARITY is not given, no parity is used.
2596 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2597 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2598 is not given or nil, 1 stopbit is used.
2600 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2601 flowcontrol to be used, which is either nil (don't use flowcontrol),
2602 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2603 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2604 flowcontrol is used.
2606 `serial-process-configure' is called by `make-serial-process' for the
2607 initial configuration of the serial port.
2609 Examples:
2611 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2613 \(serial-process-configure
2614 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2616 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2618 usage: (serial-process-configure &rest ARGS) */)
2619 (int nargs, Lisp_Object *args)
2621 struct Lisp_Process *p;
2622 Lisp_Object contact = Qnil;
2623 Lisp_Object proc = Qnil;
2624 struct gcpro gcpro1;
2626 contact = Flist (nargs, args);
2627 GCPRO1 (contact);
2629 proc = Fplist_get (contact, QCprocess);
2630 if (NILP (proc))
2631 proc = Fplist_get (contact, QCname);
2632 if (NILP (proc))
2633 proc = Fplist_get (contact, QCbuffer);
2634 if (NILP (proc))
2635 proc = Fplist_get (contact, QCport);
2636 proc = get_process (proc);
2637 p = XPROCESS (proc);
2638 if (!EQ (p->type, Qserial))
2639 error ("Not a serial process");
2641 if (NILP (Fplist_get (p->childp, QCspeed)))
2643 UNGCPRO;
2644 return Qnil;
2647 serial_configure (p, contact);
2649 UNGCPRO;
2650 return Qnil;
2653 /* Used by make-serial-process to recover from errors. */
2654 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2656 if (!PROCESSP (proc))
2657 abort ();
2658 remove_process (proc);
2659 return Qnil;
2662 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2663 0, MANY, 0,
2664 doc: /* Create and return a serial port process.
2666 In Emacs, serial port connections are represented by process objects,
2667 so input and output work as for subprocesses, and `delete-process'
2668 closes a serial port connection. However, a serial process has no
2669 process id, it cannot be signaled, and the status codes are different
2670 from normal processes.
2672 `make-serial-process' creates a process and a buffer, on which you
2673 probably want to use `process-send-string'. Try \\[serial-term] for
2674 an interactive terminal. See below for examples.
2676 Arguments are specified as keyword/argument pairs. The following
2677 arguments are defined:
2679 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2680 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2681 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2682 the backslashes in strings).
2684 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2685 which is called by `make-serial-process'.
2687 :name NAME -- NAME is the name of the process. If NAME is not given,
2688 the value of PORT is used.
2690 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2691 with the process. Process output goes at the end of that buffer,
2692 unless you specify an output stream or filter function to handle the
2693 output. If BUFFER is not given, the value of NAME is used.
2695 :coding CODING -- If CODING is a symbol, it specifies the coding
2696 system used for both reading and writing for this process. If CODING
2697 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2698 ENCODING is used for writing.
2700 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2701 the process is running. If BOOL is not given, query before exiting.
2703 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2704 In the stopped state, a serial process does not accept incoming data,
2705 but you can send outgoing data. The stopped state is cleared by
2706 `continue-process' and set by `stop-process'.
2708 :filter FILTER -- Install FILTER as the process filter.
2710 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2712 :plist PLIST -- Install PLIST as the initial plist of the process.
2714 :speed
2715 :bytesize
2716 :parity
2717 :stopbits
2718 :flowcontrol
2719 -- These arguments are handled by `serial-process-configure', which is
2720 called by `make-serial-process'.
2722 The original argument list, possibly modified by later configuration,
2723 is available via the function `process-contact'.
2725 Examples:
2727 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2729 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2731 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2733 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2735 usage: (make-serial-process &rest ARGS) */)
2736 (int nargs, Lisp_Object *args)
2738 int fd = -1;
2739 Lisp_Object proc, contact, port;
2740 struct Lisp_Process *p;
2741 struct gcpro gcpro1;
2742 Lisp_Object name, buffer;
2743 Lisp_Object tem, val;
2744 int specpdl_count = -1;
2746 if (nargs == 0)
2747 return Qnil;
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2752 port = Fplist_get (contact, QCport);
2753 if (NILP (port))
2754 error ("No port specified");
2755 CHECK_STRING (port);
2757 if (NILP (Fplist_member (contact, QCspeed)))
2758 error (":speed not specified");
2759 if (!NILP (Fplist_get (contact, QCspeed)))
2760 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2762 name = Fplist_get (contact, QCname);
2763 if (NILP (name))
2764 name = port;
2765 CHECK_STRING (name);
2766 proc = make_process (name);
2767 specpdl_count = SPECPDL_INDEX ();
2768 record_unwind_protect (make_serial_process_unwind, proc);
2769 p = XPROCESS (proc);
2771 fd = serial_open ((char*) SDATA (port));
2772 p->infd = fd;
2773 p->outfd = fd;
2774 if (fd > max_process_desc)
2775 max_process_desc = fd;
2776 chan_process[fd] = proc;
2778 buffer = Fplist_get (contact, QCbuffer);
2779 if (NILP (buffer))
2780 buffer = name;
2781 buffer = Fget_buffer_create (buffer);
2782 p->buffer = buffer;
2784 p->childp = contact;
2785 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2786 p->type = Qserial;
2787 p->sentinel = Fplist_get (contact, QCsentinel);
2788 p->filter = Fplist_get (contact, QCfilter);
2789 p->log = Qnil;
2790 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2791 p->kill_without_query = 1;
2792 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2793 p->command = Qt;
2794 p->pty_flag = 0;
2796 if (!EQ (p->command, Qt))
2798 FD_SET (fd, &input_wait_mask);
2799 FD_SET (fd, &non_keyboard_wait_mask);
2802 if (BUFFERP (buffer))
2804 set_marker_both (p->mark, buffer,
2805 BUF_ZV (XBUFFER (buffer)),
2806 BUF_ZV_BYTE (XBUFFER (buffer)));
2809 tem = Fplist_member (contact, QCcoding);
2810 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2811 tem = Qnil;
2813 val = Qnil;
2814 if (!NILP (tem))
2816 val = XCAR (XCDR (tem));
2817 if (CONSP (val))
2818 val = XCAR (val);
2820 else if (!NILP (Vcoding_system_for_read))
2821 val = Vcoding_system_for_read;
2822 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2823 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2824 val = Qnil;
2825 p->decode_coding_system = val;
2827 val = Qnil;
2828 if (!NILP (tem))
2830 val = XCAR (XCDR (tem));
2831 if (CONSP (val))
2832 val = XCDR (val);
2834 else if (!NILP (Vcoding_system_for_write))
2835 val = Vcoding_system_for_write;
2836 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2837 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2838 val = Qnil;
2839 p->encode_coding_system = val;
2841 setup_process_coding_systems (proc);
2842 p->decoding_buf = make_uninit_string (0);
2843 p->decoding_carryover = 0;
2844 p->encoding_buf = make_uninit_string (0);
2845 p->inherit_coding_system_flag
2846 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2848 Fserial_process_configure (nargs, args);
2850 specpdl_ptr = specpdl + specpdl_count;
2852 UNGCPRO;
2853 return proc;
2856 /* Create a network stream/datagram client/server process. Treated
2857 exactly like a normal process when reading and writing. Primary
2858 differences are in status display and process deletion. A network
2859 connection has no PID; you cannot signal it. All you can do is
2860 stop/continue it and deactivate/close it via delete-process */
2862 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2863 0, MANY, 0,
2864 doc: /* Create and return a network server or client process.
2866 In Emacs, network connections are represented by process objects, so
2867 input and output work as for subprocesses and `delete-process' closes
2868 a network connection. However, a network process has no process id,
2869 it cannot be signaled, and the status codes are different from normal
2870 processes.
2872 Arguments are specified as keyword/argument pairs. The following
2873 arguments are defined:
2875 :name NAME -- NAME is name for process. It is modified if necessary
2876 to make it unique.
2878 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2879 with the process. Process output goes at end of that buffer, unless
2880 you specify an output stream or filter function to handle the output.
2881 BUFFER may be also nil, meaning that this process is not associated
2882 with any buffer.
2884 :host HOST -- HOST is name of the host to connect to, or its IP
2885 address. The symbol `local' specifies the local host. If specified
2886 for a server process, it must be a valid name or address for the local
2887 host, and only clients connecting to that address will be accepted.
2889 :service SERVICE -- SERVICE is name of the service desired, or an
2890 integer specifying a port number to connect to. If SERVICE is t,
2891 a random port number is selected for the server. (If Emacs was
2892 compiled with getaddrinfo, a port number can also be specified as a
2893 string, e.g. "80", as well as an integer. This is not portable.)
2895 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2896 stream type connection, `datagram' creates a datagram type connection,
2897 `seqpacket' creates a reliable datagram connection.
2899 :family FAMILY -- FAMILY is the address (and protocol) family for the
2900 service specified by HOST and SERVICE. The default (nil) is to use
2901 whatever address family (IPv4 or IPv6) that is defined for the host
2902 and port number specified by HOST and SERVICE. Other address families
2903 supported are:
2904 local -- for a local (i.e. UNIX) address specified by SERVICE.
2905 ipv4 -- use IPv4 address family only.
2906 ipv6 -- use IPv6 address family only.
2908 :local ADDRESS -- ADDRESS is the local address used for the connection.
2909 This parameter is ignored when opening a client process. When specified
2910 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2912 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2913 connection. This parameter is ignored when opening a stream server
2914 process. For a datagram server process, it specifies the initial
2915 setting of the remote datagram address. When specified for a client
2916 process, the FAMILY, HOST, and SERVICE args are ignored.
2918 The format of ADDRESS depends on the address family:
2919 - An IPv4 address is represented as an vector of integers [A B C D P]
2920 corresponding to numeric IP address A.B.C.D and port number P.
2921 - A local address is represented as a string with the address in the
2922 local address space.
2923 - An "unsupported family" address is represented by a cons (F . AV)
2924 where F is the family number and AV is a vector containing the socket
2925 address data with one element per address data byte. Do not rely on
2926 this format in portable code, as it may depend on implementation
2927 defined constants, data sizes, and data structure alignment.
2929 :coding CODING -- If CODING is a symbol, it specifies the coding
2930 system used for both reading and writing for this process. If CODING
2931 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2932 ENCODING is used for writing.
2934 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2935 return without waiting for the connection to complete; instead, the
2936 sentinel function will be called with second arg matching "open" (if
2937 successful) or "failed" when the connect completes. Default is to use
2938 a blocking connect (i.e. wait) for stream type connections.
2940 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2941 running when Emacs is exited.
2943 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2944 In the stopped state, a server process does not accept new
2945 connections, and a client process does not handle incoming traffic.
2946 The stopped state is cleared by `continue-process' and set by
2947 `stop-process'.
2949 :filter FILTER -- Install FILTER as the process filter.
2951 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2952 process filter are multibyte, otherwise they are unibyte.
2953 If this keyword is not specified, the strings are multibyte if
2954 `default-enable-multibyte-characters' is non-nil.
2956 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2958 :log LOG -- Install LOG as the server process log function. This
2959 function is called when the server accepts a network connection from a
2960 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2961 is the server process, CLIENT is the new process for the connection,
2962 and MESSAGE is a string.
2964 :plist PLIST -- Install PLIST as the new process' initial plist.
2966 :server QLEN -- if QLEN is non-nil, create a server process for the
2967 specified FAMILY, SERVICE, and connection type (stream or datagram).
2968 If QLEN is an integer, it is used as the max. length of the server's
2969 pending connection queue (also known as the backlog); the default
2970 queue length is 5. Default is to create a client process.
2972 The following network options can be specified for this connection:
2974 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2975 :dontroute BOOL -- Only send to directly connected hosts.
2976 :keepalive BOOL -- Send keep-alive messages on network stream.
2977 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2978 :oobinline BOOL -- Place out-of-band data in receive data stream.
2979 :priority INT -- Set protocol defined priority for sent packets.
2980 :reuseaddr BOOL -- Allow reusing a recently used local address
2981 (this is allowed by default for a server process).
2982 :bindtodevice NAME -- bind to interface NAME. Using this may require
2983 special privileges on some systems.
2985 Consult the relevant system programmer's manual pages for more
2986 information on using these options.
2989 A server process will listen for and accept connections from clients.
2990 When a client connection is accepted, a new network process is created
2991 for the connection with the following parameters:
2993 - The client's process name is constructed by concatenating the server
2994 process' NAME and a client identification string.
2995 - If the FILTER argument is non-nil, the client process will not get a
2996 separate process buffer; otherwise, the client's process buffer is a newly
2997 created buffer named after the server process' BUFFER name or process
2998 NAME concatenated with the client identification string.
2999 - The connection type and the process filter and sentinel parameters are
3000 inherited from the server process' TYPE, FILTER and SENTINEL.
3001 - The client process' contact info is set according to the client's
3002 addressing information (typically an IP address and a port number).
3003 - The client process' plist is initialized from the server's plist.
3005 Notice that the FILTER and SENTINEL args are never used directly by
3006 the server process. Also, the BUFFER argument is not used directly by
3007 the server process, but via the optional :log function, accepted (and
3008 failed) connections may be logged in the server process' buffer.
3010 The original argument list, modified with the actual connection
3011 information, is available via the `process-contact' function.
3013 usage: (make-network-process &rest ARGS) */)
3014 (int nargs, Lisp_Object *args)
3016 Lisp_Object proc;
3017 Lisp_Object contact;
3018 struct Lisp_Process *p;
3019 #ifdef HAVE_GETADDRINFO
3020 struct addrinfo ai, *res, *lres;
3021 struct addrinfo hints;
3022 const char *portstring;
3023 char portbuf[128];
3024 #else /* HAVE_GETADDRINFO */
3025 struct _emacs_addrinfo
3027 int ai_family;
3028 int ai_socktype;
3029 int ai_protocol;
3030 int ai_addrlen;
3031 struct sockaddr *ai_addr;
3032 struct _emacs_addrinfo *ai_next;
3033 } ai, *res, *lres;
3034 #endif /* HAVE_GETADDRINFO */
3035 struct sockaddr_in address_in;
3036 #ifdef HAVE_LOCAL_SOCKETS
3037 struct sockaddr_un address_un;
3038 #endif
3039 int port;
3040 int ret = 0;
3041 int xerrno = 0;
3042 int s = -1, outch, inch;
3043 struct gcpro gcpro1;
3044 int count = SPECPDL_INDEX ();
3045 int count1;
3046 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3047 Lisp_Object tem;
3048 Lisp_Object name, buffer, host, service, address;
3049 Lisp_Object filter, sentinel;
3050 int is_non_blocking_client = 0;
3051 int is_server = 0, backlog = 5;
3052 int socktype;
3053 int family = -1;
3055 if (nargs == 0)
3056 return Qnil;
3058 /* Save arguments for process-contact and clone-process. */
3059 contact = Flist (nargs, args);
3060 GCPRO1 (contact);
3062 #ifdef WINDOWSNT
3063 /* Ensure socket support is loaded if available. */
3064 init_winsock (TRUE);
3065 #endif
3067 /* :type TYPE (nil: stream, datagram */
3068 tem = Fplist_get (contact, QCtype);
3069 if (NILP (tem))
3070 socktype = SOCK_STREAM;
3071 #ifdef DATAGRAM_SOCKETS
3072 else if (EQ (tem, Qdatagram))
3073 socktype = SOCK_DGRAM;
3074 #endif
3075 #ifdef HAVE_SEQPACKET
3076 else if (EQ (tem, Qseqpacket))
3077 socktype = SOCK_SEQPACKET;
3078 #endif
3079 else
3080 error ("Unsupported connection type");
3082 /* :server BOOL */
3083 tem = Fplist_get (contact, QCserver);
3084 if (!NILP (tem))
3086 /* Don't support network sockets when non-blocking mode is
3087 not available, since a blocked Emacs is not useful. */
3088 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3089 error ("Network servers not supported");
3090 #else
3091 is_server = 1;
3092 if (INTEGERP (tem))
3093 backlog = XINT (tem);
3094 #endif
3097 /* Make QCaddress an alias for :local (server) or :remote (client). */
3098 QCaddress = is_server ? QClocal : QCremote;
3100 /* :nowait BOOL */
3101 if (!is_server && socktype != SOCK_DGRAM
3102 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3104 #ifndef NON_BLOCKING_CONNECT
3105 error ("Non-blocking connect not supported");
3106 #else
3107 is_non_blocking_client = 1;
3108 #endif
3111 name = Fplist_get (contact, QCname);
3112 buffer = Fplist_get (contact, QCbuffer);
3113 filter = Fplist_get (contact, QCfilter);
3114 sentinel = Fplist_get (contact, QCsentinel);
3116 CHECK_STRING (name);
3118 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3119 ai.ai_socktype = socktype;
3120 ai.ai_protocol = 0;
3121 ai.ai_next = NULL;
3122 res = &ai;
3124 /* :local ADDRESS or :remote ADDRESS */
3125 address = Fplist_get (contact, QCaddress);
3126 if (!NILP (address))
3128 host = service = Qnil;
3130 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3131 error ("Malformed :address");
3132 ai.ai_family = family;
3133 ai.ai_addr = alloca (ai.ai_addrlen);
3134 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3135 goto open_socket;
3138 /* :family FAMILY -- nil (for Inet), local, or integer. */
3139 tem = Fplist_get (contact, QCfamily);
3140 if (NILP (tem))
3142 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3143 family = AF_UNSPEC;
3144 #else
3145 family = AF_INET;
3146 #endif
3148 #ifdef HAVE_LOCAL_SOCKETS
3149 else if (EQ (tem, Qlocal))
3150 family = AF_LOCAL;
3151 #endif
3152 #ifdef AF_INET6
3153 else if (EQ (tem, Qipv6))
3154 family = AF_INET6;
3155 #endif
3156 else if (EQ (tem, Qipv4))
3157 family = AF_INET;
3158 else if (INTEGERP (tem))
3159 family = XINT (tem);
3160 else
3161 error ("Unknown address family");
3163 ai.ai_family = family;
3165 /* :service SERVICE -- string, integer (port number), or t (random port). */
3166 service = Fplist_get (contact, QCservice);
3168 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3169 host = Fplist_get (contact, QChost);
3170 if (!NILP (host))
3172 if (EQ (host, Qlocal))
3173 host = build_string ("localhost");
3174 CHECK_STRING (host);
3177 #ifdef HAVE_LOCAL_SOCKETS
3178 if (family == AF_LOCAL)
3180 if (!NILP (host))
3182 message (":family local ignores the :host \"%s\" property",
3183 SDATA (host));
3184 contact = Fplist_put (contact, QChost, Qnil);
3185 host = Qnil;
3187 CHECK_STRING (service);
3188 memset (&address_un, 0, sizeof address_un);
3189 address_un.sun_family = AF_LOCAL;
3190 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3191 ai.ai_addr = (struct sockaddr *) &address_un;
3192 ai.ai_addrlen = sizeof address_un;
3193 goto open_socket;
3195 #endif
3197 /* Slow down polling to every ten seconds.
3198 Some kernels have a bug which causes retrying connect to fail
3199 after a connect. Polling can interfere with gethostbyname too. */
3200 #ifdef POLL_FOR_INPUT
3201 if (socktype != SOCK_DGRAM)
3203 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3204 bind_polling_period (10);
3206 #endif
3208 #ifdef HAVE_GETADDRINFO
3209 /* If we have a host, use getaddrinfo to resolve both host and service.
3210 Otherwise, use getservbyname to lookup the service. */
3211 if (!NILP (host))
3214 /* SERVICE can either be a string or int.
3215 Convert to a C string for later use by getaddrinfo. */
3216 if (EQ (service, Qt))
3217 portstring = "0";
3218 else if (INTEGERP (service))
3220 sprintf (portbuf, "%ld", (long) XINT (service));
3221 portstring = portbuf;
3223 else
3225 CHECK_STRING (service);
3226 portstring = SDATA (service);
3229 immediate_quit = 1;
3230 QUIT;
3231 memset (&hints, 0, sizeof (hints));
3232 hints.ai_flags = 0;
3233 hints.ai_family = family;
3234 hints.ai_socktype = socktype;
3235 hints.ai_protocol = 0;
3237 #ifdef HAVE_RES_INIT
3238 res_init ();
3239 #endif
3241 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3242 if (ret)
3243 #ifdef HAVE_GAI_STRERROR
3244 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3245 #else
3246 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3247 #endif
3248 immediate_quit = 0;
3250 goto open_socket;
3252 #endif /* HAVE_GETADDRINFO */
3254 /* We end up here if getaddrinfo is not defined, or in case no hostname
3255 has been specified (e.g. for a local server process). */
3257 if (EQ (service, Qt))
3258 port = 0;
3259 else if (INTEGERP (service))
3260 port = htons ((unsigned short) XINT (service));
3261 else
3263 struct servent *svc_info;
3264 CHECK_STRING (service);
3265 svc_info = getservbyname (SDATA (service),
3266 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3267 if (svc_info == 0)
3268 error ("Unknown service: %s", SDATA (service));
3269 port = svc_info->s_port;
3272 memset (&address_in, 0, sizeof address_in);
3273 address_in.sin_family = family;
3274 address_in.sin_addr.s_addr = INADDR_ANY;
3275 address_in.sin_port = port;
3277 #ifndef HAVE_GETADDRINFO
3278 if (!NILP (host))
3280 struct hostent *host_info_ptr;
3282 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3283 as it may `hang' Emacs for a very long time. */
3284 immediate_quit = 1;
3285 QUIT;
3287 #ifdef HAVE_RES_INIT
3288 res_init ();
3289 #endif
3291 host_info_ptr = gethostbyname (SDATA (host));
3292 immediate_quit = 0;
3294 if (host_info_ptr)
3296 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3297 host_info_ptr->h_length);
3298 family = host_info_ptr->h_addrtype;
3299 address_in.sin_family = family;
3301 else
3302 /* Attempt to interpret host as numeric inet address */
3304 unsigned long numeric_addr;
3305 numeric_addr = inet_addr ((char *) SDATA (host));
3306 if (numeric_addr == -1)
3307 error ("Unknown host \"%s\"", SDATA (host));
3309 memcpy (&address_in.sin_addr, &numeric_addr,
3310 sizeof (address_in.sin_addr));
3314 #endif /* not HAVE_GETADDRINFO */
3316 ai.ai_family = family;
3317 ai.ai_addr = (struct sockaddr *) &address_in;
3318 ai.ai_addrlen = sizeof address_in;
3320 open_socket:
3322 /* Do this in case we never enter the for-loop below. */
3323 count1 = SPECPDL_INDEX ();
3324 s = -1;
3326 for (lres = res; lres; lres = lres->ai_next)
3328 int optn, optbits;
3330 retry_connect:
3332 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3333 if (s < 0)
3335 xerrno = errno;
3336 continue;
3339 #ifdef DATAGRAM_SOCKETS
3340 if (!is_server && socktype == SOCK_DGRAM)
3341 break;
3342 #endif /* DATAGRAM_SOCKETS */
3344 #ifdef NON_BLOCKING_CONNECT
3345 if (is_non_blocking_client)
3347 #ifdef O_NONBLOCK
3348 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3349 #else
3350 ret = fcntl (s, F_SETFL, O_NDELAY);
3351 #endif
3352 if (ret < 0)
3354 xerrno = errno;
3355 emacs_close (s);
3356 s = -1;
3357 continue;
3360 #endif
3362 /* Make us close S if quit. */
3363 record_unwind_protect (close_file_unwind, make_number (s));
3365 /* Parse network options in the arg list.
3366 We simply ignore anything which isn't a known option (including other keywords).
3367 An error is signaled if setting a known option fails. */
3368 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3369 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3371 if (is_server)
3373 /* Configure as a server socket. */
3375 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3376 explicit :reuseaddr key to override this. */
3377 #ifdef HAVE_LOCAL_SOCKETS
3378 if (family != AF_LOCAL)
3379 #endif
3380 if (!(optbits & (1 << OPIX_REUSEADDR)))
3382 int optval = 1;
3383 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3384 report_file_error ("Cannot set reuse option on server socket", Qnil);
3387 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3388 report_file_error ("Cannot bind server socket", Qnil);
3390 #ifdef HAVE_GETSOCKNAME
3391 if (EQ (service, Qt))
3393 struct sockaddr_in sa1;
3394 int len1 = sizeof (sa1);
3395 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3397 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3398 service = make_number (ntohs (sa1.sin_port));
3399 contact = Fplist_put (contact, QCservice, service);
3402 #endif
3404 if (socktype != SOCK_DGRAM && listen (s, backlog))
3405 report_file_error ("Cannot listen on server socket", Qnil);
3407 break;
3410 immediate_quit = 1;
3411 QUIT;
3413 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3414 xerrno = errno;
3416 if (ret == 0 || xerrno == EISCONN)
3418 /* The unwind-protect will be discarded afterwards.
3419 Likewise for immediate_quit. */
3420 break;
3423 #ifdef NON_BLOCKING_CONNECT
3424 #ifdef EINPROGRESS
3425 if (is_non_blocking_client && xerrno == EINPROGRESS)
3426 break;
3427 #else
3428 #ifdef EWOULDBLOCK
3429 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3430 break;
3431 #endif
3432 #endif
3433 #endif
3435 #ifndef WINDOWSNT
3436 if (xerrno == EINTR)
3438 /* Unlike most other syscalls connect() cannot be called
3439 again. (That would return EALREADY.) The proper way to
3440 wait for completion is select(). */
3441 int sc, len;
3442 SELECT_TYPE fdset;
3443 retry_select:
3444 FD_ZERO (&fdset);
3445 FD_SET (s, &fdset);
3446 QUIT;
3447 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3448 (EMACS_TIME *)0);
3449 if (sc == -1)
3451 if (errno == EINTR)
3452 goto retry_select;
3453 else
3454 report_file_error ("select failed", Qnil);
3456 eassert (sc > 0);
3458 len = sizeof xerrno;
3459 eassert (FD_ISSET (s, &fdset));
3460 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3461 report_file_error ("getsockopt failed", Qnil);
3462 if (xerrno)
3463 errno = xerrno, report_file_error ("error during connect", Qnil);
3464 else
3465 break;
3467 #endif /* !WINDOWSNT */
3469 immediate_quit = 0;
3471 /* Discard the unwind protect closing S. */
3472 specpdl_ptr = specpdl + count1;
3473 emacs_close (s);
3474 s = -1;
3476 #ifdef WINDOWSNT
3477 if (xerrno == EINTR)
3478 goto retry_connect;
3479 #endif
3482 if (s >= 0)
3484 #ifdef DATAGRAM_SOCKETS
3485 if (socktype == SOCK_DGRAM)
3487 if (datagram_address[s].sa)
3488 abort ();
3489 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3490 datagram_address[s].len = lres->ai_addrlen;
3491 if (is_server)
3493 Lisp_Object remote;
3494 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3495 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3497 int rfamily, rlen;
3498 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3499 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3500 conv_lisp_to_sockaddr (rfamily, remote,
3501 datagram_address[s].sa, rlen);
3504 else
3505 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3507 #endif
3508 contact = Fplist_put (contact, QCaddress,
3509 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3510 #ifdef HAVE_GETSOCKNAME
3511 if (!is_server)
3513 struct sockaddr_in sa1;
3514 int len1 = sizeof (sa1);
3515 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3516 contact = Fplist_put (contact, QClocal,
3517 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3519 #endif
3522 immediate_quit = 0;
3524 #ifdef HAVE_GETADDRINFO
3525 if (res != &ai)
3527 BLOCK_INPUT;
3528 freeaddrinfo (res);
3529 UNBLOCK_INPUT;
3531 #endif
3533 /* Discard the unwind protect for closing S, if any. */
3534 specpdl_ptr = specpdl + count1;
3536 /* Unwind bind_polling_period and request_sigio. */
3537 unbind_to (count, Qnil);
3539 if (s < 0)
3541 /* If non-blocking got this far - and failed - assume non-blocking is
3542 not supported after all. This is probably a wrong assumption, but
3543 the normal blocking calls to open-network-stream handles this error
3544 better. */
3545 if (is_non_blocking_client)
3546 return Qnil;
3548 errno = xerrno;
3549 if (is_server)
3550 report_file_error ("make server process failed", contact);
3551 else
3552 report_file_error ("make client process failed", contact);
3555 inch = s;
3556 outch = s;
3558 if (!NILP (buffer))
3559 buffer = Fget_buffer_create (buffer);
3560 proc = make_process (name);
3562 chan_process[inch] = proc;
3564 #ifdef O_NONBLOCK
3565 fcntl (inch, F_SETFL, O_NONBLOCK);
3566 #else
3567 #ifdef O_NDELAY
3568 fcntl (inch, F_SETFL, O_NDELAY);
3569 #endif
3570 #endif
3572 p = XPROCESS (proc);
3574 p->childp = contact;
3575 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3576 p->type = Qnetwork;
3578 p->buffer = buffer;
3579 p->sentinel = sentinel;
3580 p->filter = filter;
3581 p->log = Fplist_get (contact, QClog);
3582 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3583 p->kill_without_query = 1;
3584 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3585 p->command = Qt;
3586 p->pid = 0;
3587 p->infd = inch;
3588 p->outfd = outch;
3589 if (is_server && socktype != SOCK_DGRAM)
3590 p->status = Qlisten;
3592 /* Make the process marker point into the process buffer (if any). */
3593 if (BUFFERP (buffer))
3594 set_marker_both (p->mark, buffer,
3595 BUF_ZV (XBUFFER (buffer)),
3596 BUF_ZV_BYTE (XBUFFER (buffer)));
3598 #ifdef NON_BLOCKING_CONNECT
3599 if (is_non_blocking_client)
3601 /* We may get here if connect did succeed immediately. However,
3602 in that case, we still need to signal this like a non-blocking
3603 connection. */
3604 p->status = Qconnect;
3605 if (!FD_ISSET (inch, &connect_wait_mask))
3607 FD_SET (inch, &connect_wait_mask);
3608 num_pending_connects++;
3611 else
3612 #endif
3613 /* A server may have a client filter setting of Qt, but it must
3614 still listen for incoming connects unless it is stopped. */
3615 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3616 || (EQ (p->status, Qlisten) && NILP (p->command)))
3618 FD_SET (inch, &input_wait_mask);
3619 FD_SET (inch, &non_keyboard_wait_mask);
3622 if (inch > max_process_desc)
3623 max_process_desc = inch;
3625 tem = Fplist_member (contact, QCcoding);
3626 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3627 tem = Qnil; /* No error message (too late!). */
3630 /* Setup coding systems for communicating with the network stream. */
3631 struct gcpro gcpro1;
3632 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3633 Lisp_Object coding_systems = Qt;
3634 Lisp_Object args[5], val;
3636 if (!NILP (tem))
3638 val = XCAR (XCDR (tem));
3639 if (CONSP (val))
3640 val = XCAR (val);
3642 else if (!NILP (Vcoding_system_for_read))
3643 val = Vcoding_system_for_read;
3644 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3645 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3646 /* We dare not decode end-of-line format by setting VAL to
3647 Qraw_text, because the existing Emacs Lisp libraries
3648 assume that they receive bare code including a sequene of
3649 CR LF. */
3650 val = Qnil;
3651 else
3653 if (NILP (host) || NILP (service))
3654 coding_systems = Qnil;
3655 else
3657 args[0] = Qopen_network_stream, args[1] = name,
3658 args[2] = buffer, args[3] = host, args[4] = service;
3659 GCPRO1 (proc);
3660 coding_systems = Ffind_operation_coding_system (5, args);
3661 UNGCPRO;
3663 if (CONSP (coding_systems))
3664 val = XCAR (coding_systems);
3665 else if (CONSP (Vdefault_process_coding_system))
3666 val = XCAR (Vdefault_process_coding_system);
3667 else
3668 val = Qnil;
3670 p->decode_coding_system = val;
3672 if (!NILP (tem))
3674 val = XCAR (XCDR (tem));
3675 if (CONSP (val))
3676 val = XCDR (val);
3678 else if (!NILP (Vcoding_system_for_write))
3679 val = Vcoding_system_for_write;
3680 else if (NILP (current_buffer->enable_multibyte_characters))
3681 val = Qnil;
3682 else
3684 if (EQ (coding_systems, Qt))
3686 if (NILP (host) || NILP (service))
3687 coding_systems = Qnil;
3688 else
3690 args[0] = Qopen_network_stream, args[1] = name,
3691 args[2] = buffer, args[3] = host, args[4] = service;
3692 GCPRO1 (proc);
3693 coding_systems = Ffind_operation_coding_system (5, args);
3694 UNGCPRO;
3697 if (CONSP (coding_systems))
3698 val = XCDR (coding_systems);
3699 else if (CONSP (Vdefault_process_coding_system))
3700 val = XCDR (Vdefault_process_coding_system);
3701 else
3702 val = Qnil;
3704 p->encode_coding_system = val;
3706 setup_process_coding_systems (proc);
3708 p->decoding_buf = make_uninit_string (0);
3709 p->decoding_carryover = 0;
3710 p->encoding_buf = make_uninit_string (0);
3712 p->inherit_coding_system_flag
3713 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3715 UNGCPRO;
3716 return proc;
3720 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3722 #ifdef SIOCGIFCONF
3723 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3724 doc: /* Return an alist of all network interfaces and their network address.
3725 Each element is a cons, the car of which is a string containing the
3726 interface name, and the cdr is the network address in internal
3727 format; see the description of ADDRESS in `make-network-process'. */)
3728 (void)
3730 struct ifconf ifconf;
3731 struct ifreq *ifreqs = NULL;
3732 int ifaces = 0;
3733 int buf_size, s;
3734 Lisp_Object res;
3736 s = socket (AF_INET, SOCK_STREAM, 0);
3737 if (s < 0)
3738 return Qnil;
3740 again:
3741 ifaces += 25;
3742 buf_size = ifaces * sizeof (ifreqs[0]);
3743 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3744 if (!ifreqs)
3746 close (s);
3747 return Qnil;
3750 ifconf.ifc_len = buf_size;
3751 ifconf.ifc_req = ifreqs;
3752 if (ioctl (s, SIOCGIFCONF, &ifconf))
3754 close (s);
3755 return Qnil;
3758 if (ifconf.ifc_len == buf_size)
3759 goto again;
3761 close (s);
3762 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3764 res = Qnil;
3765 while (--ifaces >= 0)
3767 struct ifreq *ifq = &ifreqs[ifaces];
3768 char namebuf[sizeof (ifq->ifr_name) + 1];
3769 if (ifq->ifr_addr.sa_family != AF_INET)
3770 continue;
3771 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3772 namebuf[sizeof (ifq->ifr_name)] = 0;
3773 res = Fcons (Fcons (build_string (namebuf),
3774 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3775 sizeof (struct sockaddr))),
3776 res);
3779 return res;
3781 #endif /* SIOCGIFCONF */
3783 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3785 struct ifflag_def {
3786 int flag_bit;
3787 const char *flag_sym;
3790 static const struct ifflag_def ifflag_table[] = {
3791 #ifdef IFF_UP
3792 { IFF_UP, "up" },
3793 #endif
3794 #ifdef IFF_BROADCAST
3795 { IFF_BROADCAST, "broadcast" },
3796 #endif
3797 #ifdef IFF_DEBUG
3798 { IFF_DEBUG, "debug" },
3799 #endif
3800 #ifdef IFF_LOOPBACK
3801 { IFF_LOOPBACK, "loopback" },
3802 #endif
3803 #ifdef IFF_POINTOPOINT
3804 { IFF_POINTOPOINT, "pointopoint" },
3805 #endif
3806 #ifdef IFF_RUNNING
3807 { IFF_RUNNING, "running" },
3808 #endif
3809 #ifdef IFF_NOARP
3810 { IFF_NOARP, "noarp" },
3811 #endif
3812 #ifdef IFF_PROMISC
3813 { IFF_PROMISC, "promisc" },
3814 #endif
3815 #ifdef IFF_NOTRAILERS
3816 { IFF_NOTRAILERS, "notrailers" },
3817 #endif
3818 #ifdef IFF_ALLMULTI
3819 { IFF_ALLMULTI, "allmulti" },
3820 #endif
3821 #ifdef IFF_MASTER
3822 { IFF_MASTER, "master" },
3823 #endif
3824 #ifdef IFF_SLAVE
3825 { IFF_SLAVE, "slave" },
3826 #endif
3827 #ifdef IFF_MULTICAST
3828 { IFF_MULTICAST, "multicast" },
3829 #endif
3830 #ifdef IFF_PORTSEL
3831 { IFF_PORTSEL, "portsel" },
3832 #endif
3833 #ifdef IFF_AUTOMEDIA
3834 { IFF_AUTOMEDIA, "automedia" },
3835 #endif
3836 #ifdef IFF_DYNAMIC
3837 { IFF_DYNAMIC, "dynamic" },
3838 #endif
3839 #ifdef IFF_OACTIVE
3840 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3841 #endif
3842 #ifdef IFF_SIMPLEX
3843 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3844 #endif
3845 #ifdef IFF_LINK0
3846 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3847 #endif
3848 #ifdef IFF_LINK1
3849 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3850 #endif
3851 #ifdef IFF_LINK2
3852 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3853 #endif
3854 { 0, 0 }
3857 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3858 doc: /* Return information about network interface named IFNAME.
3859 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3860 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3861 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3862 FLAGS is the current flags of the interface. */)
3863 (Lisp_Object ifname)
3865 struct ifreq rq;
3866 Lisp_Object res = Qnil;
3867 Lisp_Object elt;
3868 int s;
3869 int any = 0;
3871 CHECK_STRING (ifname);
3873 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3874 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3876 s = socket (AF_INET, SOCK_STREAM, 0);
3877 if (s < 0)
3878 return Qnil;
3880 elt = Qnil;
3881 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3882 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3884 int flags = rq.ifr_flags;
3885 const struct ifflag_def *fp;
3886 int fnum;
3888 any++;
3889 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3891 if (flags & fp->flag_bit)
3893 elt = Fcons (intern (fp->flag_sym), elt);
3894 flags -= fp->flag_bit;
3897 for (fnum = 0; flags && fnum < 32; fnum++)
3899 if (flags & (1 << fnum))
3901 elt = Fcons (make_number (fnum), elt);
3905 #endif
3906 res = Fcons (elt, res);
3908 elt = Qnil;
3909 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3910 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3912 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3913 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3914 int n;
3916 any++;
3917 for (n = 0; n < 6; n++)
3918 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3919 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3921 #endif
3922 res = Fcons (elt, res);
3924 elt = Qnil;
3925 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3926 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3928 any++;
3929 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3930 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3931 #else
3932 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3933 #endif
3935 #endif
3936 res = Fcons (elt, res);
3938 elt = Qnil;
3939 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3940 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3942 any++;
3943 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3945 #endif
3946 res = Fcons (elt, res);
3948 elt = Qnil;
3949 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3950 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3952 any++;
3953 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3955 #endif
3956 res = Fcons (elt, res);
3958 close (s);
3960 return any ? res : Qnil;
3962 #endif
3963 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
3965 /* Turn off input and output for process PROC. */
3967 void
3968 deactivate_process (Lisp_Object proc)
3970 register int inchannel, outchannel;
3971 register struct Lisp_Process *p = XPROCESS (proc);
3973 inchannel = p->infd;
3974 outchannel = p->outfd;
3976 #ifdef ADAPTIVE_READ_BUFFERING
3977 if (p->read_output_delay > 0)
3979 if (--process_output_delay_count < 0)
3980 process_output_delay_count = 0;
3981 p->read_output_delay = 0;
3982 p->read_output_skip = 0;
3984 #endif
3986 if (inchannel >= 0)
3988 /* Beware SIGCHLD hereabouts. */
3989 flush_pending_output (inchannel);
3990 emacs_close (inchannel);
3991 if (outchannel >= 0 && outchannel != inchannel)
3992 emacs_close (outchannel);
3994 p->infd = -1;
3995 p->outfd = -1;
3996 #ifdef DATAGRAM_SOCKETS
3997 if (DATAGRAM_CHAN_P (inchannel))
3999 xfree (datagram_address[inchannel].sa);
4000 datagram_address[inchannel].sa = 0;
4001 datagram_address[inchannel].len = 0;
4003 #endif
4004 chan_process[inchannel] = Qnil;
4005 FD_CLR (inchannel, &input_wait_mask);
4006 FD_CLR (inchannel, &non_keyboard_wait_mask);
4007 #ifdef NON_BLOCKING_CONNECT
4008 if (FD_ISSET (inchannel, &connect_wait_mask))
4010 FD_CLR (inchannel, &connect_wait_mask);
4011 if (--num_pending_connects < 0)
4012 abort ();
4014 #endif
4015 if (inchannel == max_process_desc)
4017 int i;
4018 /* We just closed the highest-numbered process input descriptor,
4019 so recompute the highest-numbered one now. */
4020 max_process_desc = 0;
4021 for (i = 0; i < MAXDESC; i++)
4022 if (!NILP (chan_process[i]))
4023 max_process_desc = i;
4029 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4030 0, 4, 0,
4031 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4032 It is read into the process' buffers or given to their filter functions.
4033 Non-nil arg PROCESS means do not return until some output has been received
4034 from PROCESS.
4036 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4037 and milliseconds to wait; return after that much time whether or not
4038 there is any subprocess output. If SECONDS is a floating point number,
4039 it specifies a fractional number of seconds to wait.
4040 The MILLISEC argument is obsolete and should be avoided.
4042 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4043 from PROCESS, suspending reading output from other processes.
4044 If JUST-THIS-ONE is an integer, don't run any timers either.
4045 Return non-nil if we received any output before the timeout expired. */)
4046 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4048 int secs, usecs = 0;
4050 if (! NILP (process))
4051 CHECK_PROCESS (process);
4052 else
4053 just_this_one = Qnil;
4055 if (!NILP (millisec))
4056 { /* Obsolete calling convention using integers rather than floats. */
4057 CHECK_NUMBER (millisec);
4058 if (NILP (seconds))
4059 seconds = make_float (XINT (millisec) / 1000.0);
4060 else
4062 CHECK_NUMBER (seconds);
4063 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4067 if (!NILP (seconds))
4069 if (INTEGERP (seconds))
4070 secs = XINT (seconds);
4071 else if (FLOATP (seconds))
4073 double timeout = XFLOAT_DATA (seconds);
4074 secs = (int) timeout;
4075 usecs = (int) ((timeout - (double) secs) * 1000000);
4077 else
4078 wrong_type_argument (Qnumberp, seconds);
4080 if (secs < 0 || (secs == 0 && usecs == 0))
4081 secs = -1, usecs = 0;
4083 else
4084 secs = NILP (process) ? -1 : 0;
4086 return
4087 (wait_reading_process_output (secs, usecs, 0, 0,
4088 Qnil,
4089 !NILP (process) ? XPROCESS (process) : NULL,
4090 NILP (just_this_one) ? 0 :
4091 !INTEGERP (just_this_one) ? 1 : -1)
4092 ? Qt : Qnil);
4095 /* Accept a connection for server process SERVER on CHANNEL. */
4097 static int connect_counter = 0;
4099 static void
4100 server_accept_connection (Lisp_Object server, int channel)
4102 Lisp_Object proc, caller, name, buffer;
4103 Lisp_Object contact, host, service;
4104 struct Lisp_Process *ps= XPROCESS (server);
4105 struct Lisp_Process *p;
4106 int s;
4107 union u_sockaddr {
4108 struct sockaddr sa;
4109 struct sockaddr_in in;
4110 #ifdef AF_INET6
4111 struct sockaddr_in6 in6;
4112 #endif
4113 #ifdef HAVE_LOCAL_SOCKETS
4114 struct sockaddr_un un;
4115 #endif
4116 } saddr;
4117 int len = sizeof saddr;
4119 s = accept (channel, &saddr.sa, &len);
4121 if (s < 0)
4123 int code = errno;
4125 if (code == EAGAIN)
4126 return;
4127 #ifdef EWOULDBLOCK
4128 if (code == EWOULDBLOCK)
4129 return;
4130 #endif
4132 if (!NILP (ps->log))
4133 call3 (ps->log, server, Qnil,
4134 concat3 (build_string ("accept failed with code"),
4135 Fnumber_to_string (make_number (code)),
4136 build_string ("\n")));
4137 return;
4140 connect_counter++;
4142 /* Setup a new process to handle the connection. */
4144 /* Generate a unique identification of the caller, and build contact
4145 information for this process. */
4146 host = Qt;
4147 service = Qnil;
4148 switch (saddr.sa.sa_family)
4150 case AF_INET:
4152 Lisp_Object args[5];
4153 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4154 args[0] = build_string ("%d.%d.%d.%d");
4155 args[1] = make_number (*ip++);
4156 args[2] = make_number (*ip++);
4157 args[3] = make_number (*ip++);
4158 args[4] = make_number (*ip++);
4159 host = Fformat (5, args);
4160 service = make_number (ntohs (saddr.in.sin_port));
4162 args[0] = build_string (" <%s:%d>");
4163 args[1] = host;
4164 args[2] = service;
4165 caller = Fformat (3, args);
4167 break;
4169 #ifdef AF_INET6
4170 case AF_INET6:
4172 Lisp_Object args[9];
4173 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4174 int i;
4175 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4176 for (i = 0; i < 8; i++)
4177 args[i+1] = make_number (ntohs (ip6[i]));
4178 host = Fformat (9, args);
4179 service = make_number (ntohs (saddr.in.sin_port));
4181 args[0] = build_string (" <[%s]:%d>");
4182 args[1] = host;
4183 args[2] = service;
4184 caller = Fformat (3, args);
4186 break;
4187 #endif
4189 #ifdef HAVE_LOCAL_SOCKETS
4190 case AF_LOCAL:
4191 #endif
4192 default:
4193 caller = Fnumber_to_string (make_number (connect_counter));
4194 caller = concat3 (build_string (" <"), caller, build_string (">"));
4195 break;
4198 /* Create a new buffer name for this process if it doesn't have a
4199 filter. The new buffer name is based on the buffer name or
4200 process name of the server process concatenated with the caller
4201 identification. */
4203 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4204 buffer = Qnil;
4205 else
4207 buffer = ps->buffer;
4208 if (!NILP (buffer))
4209 buffer = Fbuffer_name (buffer);
4210 else
4211 buffer = ps->name;
4212 if (!NILP (buffer))
4214 buffer = concat2 (buffer, caller);
4215 buffer = Fget_buffer_create (buffer);
4219 /* Generate a unique name for the new server process. Combine the
4220 server process name with the caller identification. */
4222 name = concat2 (ps->name, caller);
4223 proc = make_process (name);
4225 chan_process[s] = proc;
4227 #ifdef O_NONBLOCK
4228 fcntl (s, F_SETFL, O_NONBLOCK);
4229 #else
4230 #ifdef O_NDELAY
4231 fcntl (s, F_SETFL, O_NDELAY);
4232 #endif
4233 #endif
4235 p = XPROCESS (proc);
4237 /* Build new contact information for this setup. */
4238 contact = Fcopy_sequence (ps->childp);
4239 contact = Fplist_put (contact, QCserver, Qnil);
4240 contact = Fplist_put (contact, QChost, host);
4241 if (!NILP (service))
4242 contact = Fplist_put (contact, QCservice, service);
4243 contact = Fplist_put (contact, QCremote,
4244 conv_sockaddr_to_lisp (&saddr.sa, len));
4245 #ifdef HAVE_GETSOCKNAME
4246 len = sizeof saddr;
4247 if (getsockname (s, &saddr.sa, &len) == 0)
4248 contact = Fplist_put (contact, QClocal,
4249 conv_sockaddr_to_lisp (&saddr.sa, len));
4250 #endif
4252 p->childp = contact;
4253 p->plist = Fcopy_sequence (ps->plist);
4254 p->type = Qnetwork;
4256 p->buffer = buffer;
4257 p->sentinel = ps->sentinel;
4258 p->filter = ps->filter;
4259 p->command = Qnil;
4260 p->pid = 0;
4261 p->infd = s;
4262 p->outfd = s;
4263 p->status = Qrun;
4265 /* Client processes for accepted connections are not stopped initially. */
4266 if (!EQ (p->filter, Qt))
4268 FD_SET (s, &input_wait_mask);
4269 FD_SET (s, &non_keyboard_wait_mask);
4272 if (s > max_process_desc)
4273 max_process_desc = s;
4275 /* Setup coding system for new process based on server process.
4276 This seems to be the proper thing to do, as the coding system
4277 of the new process should reflect the settings at the time the
4278 server socket was opened; not the current settings. */
4280 p->decode_coding_system = ps->decode_coding_system;
4281 p->encode_coding_system = ps->encode_coding_system;
4282 setup_process_coding_systems (proc);
4284 p->decoding_buf = make_uninit_string (0);
4285 p->decoding_carryover = 0;
4286 p->encoding_buf = make_uninit_string (0);
4288 p->inherit_coding_system_flag
4289 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4291 if (!NILP (ps->log))
4292 call3 (ps->log, server, proc,
4293 concat3 (build_string ("accept from "),
4294 (STRINGP (host) ? host : build_string ("-")),
4295 build_string ("\n")));
4297 if (!NILP (p->sentinel))
4298 exec_sentinel (proc,
4299 concat3 (build_string ("open from "),
4300 (STRINGP (host) ? host : build_string ("-")),
4301 build_string ("\n")));
4304 /* This variable is different from waiting_for_input in keyboard.c.
4305 It is used to communicate to a lisp process-filter/sentinel (via the
4306 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4307 for user-input when that process-filter was called.
4308 waiting_for_input cannot be used as that is by definition 0 when
4309 lisp code is being evalled.
4310 This is also used in record_asynch_buffer_change.
4311 For that purpose, this must be 0
4312 when not inside wait_reading_process_output. */
4313 static int waiting_for_user_input_p;
4315 static Lisp_Object
4316 wait_reading_process_output_unwind (Lisp_Object data)
4318 waiting_for_user_input_p = XINT (data);
4319 return Qnil;
4322 /* This is here so breakpoints can be put on it. */
4323 static void
4324 wait_reading_process_output_1 (void)
4328 /* Use a wrapper around select to work around a bug in gdb 5.3.
4329 Normally, the wrapper is optimized away by inlining.
4331 If emacs is stopped inside select, the gdb backtrace doesn't
4332 show the function which called select, so it is practically
4333 impossible to step through wait_reading_process_output. */
4335 #ifndef select
4336 static INLINE int
4337 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4339 return select (n, rfd, wfd, xfd, tmo);
4341 #define select select_wrapper
4342 #endif
4344 /* Read and dispose of subprocess output while waiting for timeout to
4345 elapse and/or keyboard input to be available.
4347 TIME_LIMIT is:
4348 timeout in seconds, or
4349 zero for no limit, or
4350 -1 means gobble data immediately available but don't wait for any.
4352 MICROSECS is:
4353 an additional duration to wait, measured in microseconds.
4354 If this is nonzero and time_limit is 0, then the timeout
4355 consists of MICROSECS only.
4357 READ_KBD is a lisp value:
4358 0 to ignore keyboard input, or
4359 1 to return when input is available, or
4360 -1 meaning caller will actually read the input, so don't throw to
4361 the quit handler, or
4363 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4364 output that arrives.
4366 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4367 (and gobble terminal input into the buffer if any arrives).
4369 If WAIT_PROC is specified, wait until something arrives from that
4370 process. The return value is true if we read some input from
4371 that process.
4373 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4374 (suspending output from other processes). A negative value
4375 means don't run any timers either.
4377 If WAIT_PROC is specified, then the function returns true if we
4378 received input from that process before the timeout elapsed.
4379 Otherwise, return true if we received input from any process. */
4382 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4383 int do_display,
4384 Lisp_Object wait_for_cell,
4385 struct Lisp_Process *wait_proc, int just_wait_proc)
4387 register int channel, nfds;
4388 SELECT_TYPE Available;
4389 #ifdef NON_BLOCKING_CONNECT
4390 SELECT_TYPE Connecting;
4391 int check_connect;
4392 #endif
4393 int check_delay, no_avail;
4394 int xerrno;
4395 Lisp_Object proc;
4396 EMACS_TIME timeout, end_time;
4397 int wait_channel = -1;
4398 int got_some_input = 0;
4399 int count = SPECPDL_INDEX ();
4401 FD_ZERO (&Available);
4402 #ifdef NON_BLOCKING_CONNECT
4403 FD_ZERO (&Connecting);
4404 #endif
4406 if (time_limit == 0 && wait_proc && !NILP (Vinhibit_quit)
4407 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4408 message ("Blocking call to accept-process-output with quit inhibited!!");
4410 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4411 if (wait_proc != NULL)
4412 wait_channel = wait_proc->infd;
4414 record_unwind_protect (wait_reading_process_output_unwind,
4415 make_number (waiting_for_user_input_p));
4416 waiting_for_user_input_p = read_kbd;
4418 /* Since we may need to wait several times,
4419 compute the absolute time to return at. */
4420 if (time_limit || microsecs)
4422 EMACS_GET_TIME (end_time);
4423 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4424 EMACS_ADD_TIME (end_time, end_time, timeout);
4427 while (1)
4429 int timeout_reduced_for_timers = 0;
4431 /* If calling from keyboard input, do not quit
4432 since we want to return C-g as an input character.
4433 Otherwise, do pending quit if requested. */
4434 if (read_kbd >= 0)
4435 QUIT;
4436 #ifdef SYNC_INPUT
4437 else
4438 process_pending_signals ();
4439 #endif
4441 /* Exit now if the cell we're waiting for became non-nil. */
4442 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4443 break;
4445 /* Compute time from now till when time limit is up */
4446 /* Exit if already run out */
4447 if (time_limit == -1)
4449 /* -1 specified for timeout means
4450 gobble output available now
4451 but don't wait at all. */
4453 EMACS_SET_SECS_USECS (timeout, 0, 0);
4455 else if (time_limit || microsecs)
4457 EMACS_GET_TIME (timeout);
4458 EMACS_SUB_TIME (timeout, end_time, timeout);
4459 if (EMACS_TIME_NEG_P (timeout))
4460 break;
4462 else
4464 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4467 /* Normally we run timers here.
4468 But not if wait_for_cell; in those cases,
4469 the wait is supposed to be short,
4470 and those callers cannot handle running arbitrary Lisp code here. */
4471 if (NILP (wait_for_cell)
4472 && just_wait_proc >= 0)
4474 EMACS_TIME timer_delay;
4478 int old_timers_run = timers_run;
4479 struct buffer *old_buffer = current_buffer;
4480 Lisp_Object old_window = selected_window;
4482 timer_delay = timer_check (1);
4484 /* If a timer has run, this might have changed buffers
4485 an alike. Make read_key_sequence aware of that. */
4486 if (timers_run != old_timers_run
4487 && (old_buffer != current_buffer
4488 || !EQ (old_window, selected_window))
4489 && waiting_for_user_input_p == -1)
4490 record_asynch_buffer_change ();
4492 if (timers_run != old_timers_run && do_display)
4493 /* We must retry, since a timer may have requeued itself
4494 and that could alter the time_delay. */
4495 redisplay_preserve_echo_area (9);
4496 else
4497 break;
4499 while (!detect_input_pending ());
4501 /* If there is unread keyboard input, also return. */
4502 if (read_kbd != 0
4503 && requeued_events_pending_p ())
4504 break;
4506 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4508 EMACS_TIME difference;
4509 EMACS_SUB_TIME (difference, timer_delay, timeout);
4510 if (EMACS_TIME_NEG_P (difference))
4512 timeout = timer_delay;
4513 timeout_reduced_for_timers = 1;
4516 /* If time_limit is -1, we are not going to wait at all. */
4517 else if (time_limit != -1)
4519 /* This is so a breakpoint can be put here. */
4520 wait_reading_process_output_1 ();
4524 /* Cause C-g and alarm signals to take immediate action,
4525 and cause input available signals to zero out timeout.
4527 It is important that we do this before checking for process
4528 activity. If we get a SIGCHLD after the explicit checks for
4529 process activity, timeout is the only way we will know. */
4530 if (read_kbd < 0)
4531 set_waiting_for_input (&timeout);
4533 /* If status of something has changed, and no input is
4534 available, notify the user of the change right away. After
4535 this explicit check, we'll let the SIGCHLD handler zap
4536 timeout to get our attention. */
4537 if (update_tick != process_tick)
4539 SELECT_TYPE Atemp;
4540 #ifdef NON_BLOCKING_CONNECT
4541 SELECT_TYPE Ctemp;
4542 #endif
4544 if (kbd_on_hold_p ())
4545 FD_ZERO (&Atemp);
4546 else
4547 Atemp = input_wait_mask;
4548 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4550 EMACS_SET_SECS_USECS (timeout, 0, 0);
4551 if ((select (max (max (max_process_desc, max_keyboard_desc),
4552 max_gpm_desc) + 1,
4553 &Atemp,
4554 #ifdef NON_BLOCKING_CONNECT
4555 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4556 #else
4557 (SELECT_TYPE *)0,
4558 #endif
4559 (SELECT_TYPE *)0, &timeout)
4560 <= 0))
4562 /* It's okay for us to do this and then continue with
4563 the loop, since timeout has already been zeroed out. */
4564 clear_waiting_for_input ();
4565 status_notify (NULL);
4566 if (do_display) redisplay_preserve_echo_area (13);
4570 /* Don't wait for output from a non-running process. Just
4571 read whatever data has already been received. */
4572 if (wait_proc && wait_proc->raw_status_new)
4573 update_status (wait_proc);
4574 if (wait_proc
4575 && ! EQ (wait_proc->status, Qrun)
4576 && ! EQ (wait_proc->status, Qconnect))
4578 int nread, total_nread = 0;
4580 clear_waiting_for_input ();
4581 XSETPROCESS (proc, wait_proc);
4583 /* Read data from the process, until we exhaust it. */
4584 while (wait_proc->infd >= 0)
4586 nread = read_process_output (proc, wait_proc->infd);
4588 if (nread == 0)
4589 break;
4591 if (0 < nread)
4593 total_nread += nread;
4594 got_some_input = 1;
4596 #ifdef EIO
4597 else if (nread == -1 && EIO == errno)
4598 break;
4599 #endif
4600 #ifdef EAGAIN
4601 else if (nread == -1 && EAGAIN == errno)
4602 break;
4603 #endif
4604 #ifdef EWOULDBLOCK
4605 else if (nread == -1 && EWOULDBLOCK == errno)
4606 break;
4607 #endif
4609 if (total_nread > 0 && do_display)
4610 redisplay_preserve_echo_area (10);
4612 break;
4615 /* Wait till there is something to do */
4617 if (wait_proc && just_wait_proc)
4619 if (wait_proc->infd < 0) /* Terminated */
4620 break;
4621 FD_SET (wait_proc->infd, &Available);
4622 check_delay = 0;
4623 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4625 else if (!NILP (wait_for_cell))
4627 Available = non_process_wait_mask;
4628 check_delay = 0;
4629 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4631 else
4633 if (! read_kbd)
4634 Available = non_keyboard_wait_mask;
4635 else
4636 Available = input_wait_mask;
4637 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4638 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4641 /* If frame size has changed or the window is newly mapped,
4642 redisplay now, before we start to wait. There is a race
4643 condition here; if a SIGIO arrives between now and the select
4644 and indicates that a frame is trashed, the select may block
4645 displaying a trashed screen. */
4646 if (frame_garbaged && do_display)
4648 clear_waiting_for_input ();
4649 redisplay_preserve_echo_area (11);
4650 if (read_kbd < 0)
4651 set_waiting_for_input (&timeout);
4654 no_avail = 0;
4655 if (read_kbd && detect_input_pending ())
4657 nfds = 0;
4658 no_avail = 1;
4660 else
4662 #ifdef NON_BLOCKING_CONNECT
4663 if (check_connect)
4664 Connecting = connect_wait_mask;
4665 #endif
4667 #ifdef ADAPTIVE_READ_BUFFERING
4668 /* Set the timeout for adaptive read buffering if any
4669 process has non-zero read_output_skip and non-zero
4670 read_output_delay, and we are not reading output for a
4671 specific wait_channel. It is not executed if
4672 Vprocess_adaptive_read_buffering is nil. */
4673 if (process_output_skip && check_delay > 0)
4675 int usecs = EMACS_USECS (timeout);
4676 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4677 usecs = READ_OUTPUT_DELAY_MAX;
4678 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4680 proc = chan_process[channel];
4681 if (NILP (proc))
4682 continue;
4683 /* Find minimum non-zero read_output_delay among the
4684 processes with non-zero read_output_skip. */
4685 if (XPROCESS (proc)->read_output_delay > 0)
4687 check_delay--;
4688 if (!XPROCESS (proc)->read_output_skip)
4689 continue;
4690 FD_CLR (channel, &Available);
4691 XPROCESS (proc)->read_output_skip = 0;
4692 if (XPROCESS (proc)->read_output_delay < usecs)
4693 usecs = XPROCESS (proc)->read_output_delay;
4696 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4697 process_output_skip = 0;
4699 #endif
4700 #if defined (USE_GTK) || defined (HAVE_GCONF)
4701 nfds = xg_select
4702 #elif defined (HAVE_NS)
4703 nfds = ns_select
4704 #else
4705 nfds = select
4706 #endif
4707 (max (max (max_process_desc, max_keyboard_desc),
4708 max_gpm_desc) + 1,
4709 &Available,
4710 #ifdef NON_BLOCKING_CONNECT
4711 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4712 #else
4713 (SELECT_TYPE *)0,
4714 #endif
4715 (SELECT_TYPE *)0, &timeout);
4718 xerrno = errno;
4720 /* Make C-g and alarm signals set flags again */
4721 clear_waiting_for_input ();
4723 /* If we woke up due to SIGWINCH, actually change size now. */
4724 do_pending_window_change (0);
4726 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4727 /* We wanted the full specified time, so return now. */
4728 break;
4729 if (nfds < 0)
4731 if (xerrno == EINTR)
4732 no_avail = 1;
4733 else if (xerrno == EBADF)
4735 #ifdef AIX
4736 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4737 the child's closure of the pts gives the parent a SIGHUP, and
4738 the ptc file descriptor is automatically closed,
4739 yielding EBADF here or at select() call above.
4740 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4741 in m/ibmrt-aix.h), and here we just ignore the select error.
4742 Cleanup occurs c/o status_notify after SIGCLD. */
4743 no_avail = 1; /* Cannot depend on values returned */
4744 #else
4745 abort ();
4746 #endif
4748 else
4749 error ("select error: %s", emacs_strerror (xerrno));
4752 if (no_avail)
4754 FD_ZERO (&Available);
4755 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4758 #if 0 /* When polling is used, interrupt_input is 0,
4759 so get_input_pending should read the input.
4760 So this should not be needed. */
4761 /* If we are using polling for input,
4762 and we see input available, make it get read now.
4763 Otherwise it might not actually get read for a second.
4764 And on hpux, since we turn off polling in wait_reading_process_output,
4765 it might never get read at all if we don't spend much time
4766 outside of wait_reading_process_output. */
4767 if (read_kbd && interrupt_input
4768 && keyboard_bit_set (&Available)
4769 && input_polling_used ())
4770 kill (getpid (), SIGALRM);
4771 #endif
4773 /* Check for keyboard input */
4774 /* If there is any, return immediately
4775 to give it higher priority than subprocesses */
4777 if (read_kbd != 0)
4779 int old_timers_run = timers_run;
4780 struct buffer *old_buffer = current_buffer;
4781 Lisp_Object old_window = selected_window;
4782 int leave = 0;
4784 if (detect_input_pending_run_timers (do_display))
4786 swallow_events (do_display);
4787 if (detect_input_pending_run_timers (do_display))
4788 leave = 1;
4791 /* If a timer has run, this might have changed buffers
4792 an alike. Make read_key_sequence aware of that. */
4793 if (timers_run != old_timers_run
4794 && waiting_for_user_input_p == -1
4795 && (old_buffer != current_buffer
4796 || !EQ (old_window, selected_window)))
4797 record_asynch_buffer_change ();
4799 if (leave)
4800 break;
4803 /* If there is unread keyboard input, also return. */
4804 if (read_kbd != 0
4805 && requeued_events_pending_p ())
4806 break;
4808 /* If we are not checking for keyboard input now,
4809 do process events (but don't run any timers).
4810 This is so that X events will be processed.
4811 Otherwise they may have to wait until polling takes place.
4812 That would causes delays in pasting selections, for example.
4814 (We used to do this only if wait_for_cell.) */
4815 if (read_kbd == 0 && detect_input_pending ())
4817 swallow_events (do_display);
4818 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4819 if (detect_input_pending ())
4820 break;
4821 #endif
4824 /* Exit now if the cell we're waiting for became non-nil. */
4825 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4826 break;
4828 #ifdef SIGIO
4829 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4830 go read it. This can happen with X on BSD after logging out.
4831 In that case, there really is no input and no SIGIO,
4832 but select says there is input. */
4834 if (read_kbd && interrupt_input
4835 && keyboard_bit_set (&Available) && ! noninteractive)
4836 kill (getpid (), SIGIO);
4837 #endif
4839 if (! wait_proc)
4840 got_some_input |= nfds > 0;
4842 /* If checking input just got us a size-change event from X,
4843 obey it now if we should. */
4844 if (read_kbd || ! NILP (wait_for_cell))
4845 do_pending_window_change (0);
4847 /* Check for data from a process. */
4848 if (no_avail || nfds == 0)
4849 continue;
4851 /* Really FIRST_PROC_DESC should be 0 on Unix,
4852 but this is safer in the short run. */
4853 for (channel = 0; channel <= max_process_desc; channel++)
4855 if (FD_ISSET (channel, &Available)
4856 && FD_ISSET (channel, &non_keyboard_wait_mask))
4858 int nread;
4860 /* If waiting for this channel, arrange to return as
4861 soon as no more input to be processed. No more
4862 waiting. */
4863 if (wait_channel == channel)
4865 wait_channel = -1;
4866 time_limit = -1;
4867 got_some_input = 1;
4869 proc = chan_process[channel];
4870 if (NILP (proc))
4871 continue;
4873 /* If this is a server stream socket, accept connection. */
4874 if (EQ (XPROCESS (proc)->status, Qlisten))
4876 server_accept_connection (proc, channel);
4877 continue;
4880 /* Read data from the process, starting with our
4881 buffered-ahead character if we have one. */
4883 nread = read_process_output (proc, channel);
4884 if (nread > 0)
4886 /* Since read_process_output can run a filter,
4887 which can call accept-process-output,
4888 don't try to read from any other processes
4889 before doing the select again. */
4890 FD_ZERO (&Available);
4892 if (do_display)
4893 redisplay_preserve_echo_area (12);
4895 #ifdef EWOULDBLOCK
4896 else if (nread == -1 && errno == EWOULDBLOCK)
4898 #endif
4899 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4900 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4901 #ifdef O_NONBLOCK
4902 else if (nread == -1 && errno == EAGAIN)
4904 #else
4905 #ifdef O_NDELAY
4906 else if (nread == -1 && errno == EAGAIN)
4908 /* Note that we cannot distinguish between no input
4909 available now and a closed pipe.
4910 With luck, a closed pipe will be accompanied by
4911 subprocess termination and SIGCHLD. */
4912 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4914 #endif /* O_NDELAY */
4915 #endif /* O_NONBLOCK */
4916 #ifdef HAVE_PTYS
4917 /* On some OSs with ptys, when the process on one end of
4918 a pty exits, the other end gets an error reading with
4919 errno = EIO instead of getting an EOF (0 bytes read).
4920 Therefore, if we get an error reading and errno =
4921 EIO, just continue, because the child process has
4922 exited and should clean itself up soon (e.g. when we
4923 get a SIGCHLD).
4925 However, it has been known to happen that the SIGCHLD
4926 got lost. So raise the signal again just in case.
4927 It can't hurt. */
4928 else if (nread == -1 && errno == EIO)
4930 /* Clear the descriptor now, so we only raise the
4931 signal once. Don't do this if `process' is only
4932 a pty. */
4933 if (XPROCESS (proc)->pid != -2)
4935 FD_CLR (channel, &input_wait_mask);
4936 FD_CLR (channel, &non_keyboard_wait_mask);
4938 kill (getpid (), SIGCHLD);
4941 #endif /* HAVE_PTYS */
4942 /* If we can detect process termination, don't consider the process
4943 gone just because its pipe is closed. */
4944 #ifdef SIGCHLD
4945 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4947 #endif
4948 else
4950 /* Preserve status of processes already terminated. */
4951 XPROCESS (proc)->tick = ++process_tick;
4952 deactivate_process (proc);
4953 if (XPROCESS (proc)->raw_status_new)
4954 update_status (XPROCESS (proc));
4955 if (EQ (XPROCESS (proc)->status, Qrun))
4956 XPROCESS (proc)->status
4957 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4960 #ifdef NON_BLOCKING_CONNECT
4961 if (check_connect && FD_ISSET (channel, &Connecting)
4962 && FD_ISSET (channel, &connect_wait_mask))
4964 struct Lisp_Process *p;
4966 FD_CLR (channel, &connect_wait_mask);
4967 if (--num_pending_connects < 0)
4968 abort ();
4970 proc = chan_process[channel];
4971 if (NILP (proc))
4972 continue;
4974 p = XPROCESS (proc);
4976 #ifdef GNU_LINUX
4977 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4978 So only use it on systems where it is known to work. */
4980 int xlen = sizeof (xerrno);
4981 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4982 xerrno = errno;
4984 #else
4986 struct sockaddr pname;
4987 int pnamelen = sizeof (pname);
4989 /* If connection failed, getpeername will fail. */
4990 xerrno = 0;
4991 if (getpeername (channel, &pname, &pnamelen) < 0)
4993 /* Obtain connect failure code through error slippage. */
4994 char dummy;
4995 xerrno = errno;
4996 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4997 xerrno = errno;
5000 #endif
5001 if (xerrno)
5003 p->tick = ++process_tick;
5004 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5005 deactivate_process (proc);
5007 else
5009 p->status = Qrun;
5010 /* Execute the sentinel here. If we had relied on
5011 status_notify to do it later, it will read input
5012 from the process before calling the sentinel. */
5013 exec_sentinel (proc, build_string ("open\n"));
5014 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5016 FD_SET (p->infd, &input_wait_mask);
5017 FD_SET (p->infd, &non_keyboard_wait_mask);
5021 #endif /* NON_BLOCKING_CONNECT */
5022 } /* end for each file descriptor */
5023 } /* end while exit conditions not met */
5025 unbind_to (count, Qnil);
5027 /* If calling from keyboard input, do not quit
5028 since we want to return C-g as an input character.
5029 Otherwise, do pending quit if requested. */
5030 if (read_kbd >= 0)
5032 /* Prevent input_pending from remaining set if we quit. */
5033 clear_input_pending ();
5034 QUIT;
5037 return got_some_input;
5040 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5042 static Lisp_Object
5043 read_process_output_call (Lisp_Object fun_and_args)
5045 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5048 static Lisp_Object
5049 read_process_output_error_handler (Lisp_Object error)
5051 cmd_error_internal (error, "error in process filter: ");
5052 Vinhibit_quit = Qt;
5053 update_echo_area ();
5054 Fsleep_for (make_number (2), Qnil);
5055 return Qt;
5058 /* Read pending output from the process channel,
5059 starting with our buffered-ahead character if we have one.
5060 Yield number of decoded characters read.
5062 This function reads at most 4096 characters.
5063 If you want to read all available subprocess output,
5064 you must call it repeatedly until it returns zero.
5066 The characters read are decoded according to PROC's coding-system
5067 for decoding. */
5069 static int
5070 read_process_output (Lisp_Object proc, register int channel)
5072 register int nbytes;
5073 char *chars;
5074 register Lisp_Object outstream;
5075 register struct Lisp_Process *p = XPROCESS (proc);
5076 register int opoint;
5077 struct coding_system *coding = proc_decode_coding_system[channel];
5078 int carryover = p->decoding_carryover;
5079 int readmax = 4096;
5080 int count = SPECPDL_INDEX ();
5081 Lisp_Object odeactivate;
5083 chars = (char *) alloca (carryover + readmax);
5084 if (carryover)
5085 /* See the comment above. */
5086 memcpy (chars, SDATA (p->decoding_buf), carryover);
5088 #ifdef DATAGRAM_SOCKETS
5089 /* We have a working select, so proc_buffered_char is always -1. */
5090 if (DATAGRAM_CHAN_P (channel))
5092 int len = datagram_address[channel].len;
5093 nbytes = recvfrom (channel, chars + carryover, readmax,
5094 0, datagram_address[channel].sa, &len);
5096 else
5097 #endif
5098 if (proc_buffered_char[channel] < 0)
5100 nbytes = emacs_read (channel, chars + carryover, readmax);
5101 #ifdef ADAPTIVE_READ_BUFFERING
5102 if (nbytes > 0 && p->adaptive_read_buffering)
5104 int delay = p->read_output_delay;
5105 if (nbytes < 256)
5107 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5109 if (delay == 0)
5110 process_output_delay_count++;
5111 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5114 else if (delay > 0 && (nbytes == readmax))
5116 delay -= READ_OUTPUT_DELAY_INCREMENT;
5117 if (delay == 0)
5118 process_output_delay_count--;
5120 p->read_output_delay = delay;
5121 if (delay)
5123 p->read_output_skip = 1;
5124 process_output_skip = 1;
5127 #endif
5129 else
5131 chars[carryover] = proc_buffered_char[channel];
5132 proc_buffered_char[channel] = -1;
5133 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5134 if (nbytes < 0)
5135 nbytes = 1;
5136 else
5137 nbytes = nbytes + 1;
5140 p->decoding_carryover = 0;
5142 /* At this point, NBYTES holds number of bytes just received
5143 (including the one in proc_buffered_char[channel]). */
5144 if (nbytes <= 0)
5146 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5147 return nbytes;
5148 coding->mode |= CODING_MODE_LAST_BLOCK;
5151 /* Now set NBYTES how many bytes we must decode. */
5152 nbytes += carryover;
5154 odeactivate = Vdeactivate_mark;
5155 /* There's no good reason to let process filters change the current
5156 buffer, and many callers of accept-process-output, sit-for, and
5157 friends don't expect current-buffer to be changed from under them. */
5158 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5160 /* Read and dispose of the process output. */
5161 outstream = p->filter;
5162 if (!NILP (outstream))
5164 Lisp_Object obuffer, okeymap;
5165 Lisp_Object text;
5166 int outer_running_asynch_code = running_asynch_code;
5167 int waiting = waiting_for_user_input_p;
5169 /* No need to gcpro these, because all we do with them later
5170 is test them for EQness, and none of them should be a string. */
5171 XSETBUFFER (obuffer, current_buffer);
5172 okeymap = current_buffer->keymap;
5174 /* We inhibit quit here instead of just catching it so that
5175 hitting ^G when a filter happens to be running won't screw
5176 it up. */
5177 specbind (Qinhibit_quit, Qt);
5178 specbind (Qlast_nonmenu_event, Qt);
5180 /* In case we get recursively called,
5181 and we already saved the match data nonrecursively,
5182 save the same match data in safely recursive fashion. */
5183 if (outer_running_asynch_code)
5185 Lisp_Object tem;
5186 /* Don't clobber the CURRENT match data, either! */
5187 tem = Fmatch_data (Qnil, Qnil, Qnil);
5188 restore_search_regs ();
5189 record_unwind_save_match_data ();
5190 Fset_match_data (tem, Qt);
5193 /* For speed, if a search happens within this code,
5194 save the match data in a special nonrecursive fashion. */
5195 running_asynch_code = 1;
5197 decode_coding_c_string (coding, chars, nbytes, Qt);
5198 text = coding->dst_object;
5199 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5200 /* A new coding system might be found. */
5201 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5203 p->decode_coding_system = Vlast_coding_system_used;
5205 /* Don't call setup_coding_system for
5206 proc_decode_coding_system[channel] here. It is done in
5207 detect_coding called via decode_coding above. */
5209 /* If a coding system for encoding is not yet decided, we set
5210 it as the same as coding-system for decoding.
5212 But, before doing that we must check if
5213 proc_encode_coding_system[p->outfd] surely points to a
5214 valid memory because p->outfd will be changed once EOF is
5215 sent to the process. */
5216 if (NILP (p->encode_coding_system)
5217 && proc_encode_coding_system[p->outfd])
5219 p->encode_coding_system
5220 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5221 setup_coding_system (p->encode_coding_system,
5222 proc_encode_coding_system[p->outfd]);
5226 if (coding->carryover_bytes > 0)
5228 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5229 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5230 memcpy (SDATA (p->decoding_buf), coding->carryover,
5231 coding->carryover_bytes);
5232 p->decoding_carryover = coding->carryover_bytes;
5234 if (SBYTES (text) > 0)
5235 internal_condition_case_1 (read_process_output_call,
5236 Fcons (outstream,
5237 Fcons (proc, Fcons (text, Qnil))),
5238 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5239 read_process_output_error_handler);
5241 /* If we saved the match data nonrecursively, restore it now. */
5242 restore_search_regs ();
5243 running_asynch_code = outer_running_asynch_code;
5245 /* Restore waiting_for_user_input_p as it was
5246 when we were called, in case the filter clobbered it. */
5247 waiting_for_user_input_p = waiting;
5249 #if 0 /* Call record_asynch_buffer_change unconditionally,
5250 because we might have changed minor modes or other things
5251 that affect key bindings. */
5252 if (! EQ (Fcurrent_buffer (), obuffer)
5253 || ! EQ (current_buffer->keymap, okeymap))
5254 #endif
5255 /* But do it only if the caller is actually going to read events.
5256 Otherwise there's no need to make him wake up, and it could
5257 cause trouble (for example it would make sit_for return). */
5258 if (waiting_for_user_input_p == -1)
5259 record_asynch_buffer_change ();
5262 /* If no filter, write into buffer if it isn't dead. */
5263 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5265 Lisp_Object old_read_only;
5266 int old_begv, old_zv;
5267 int old_begv_byte, old_zv_byte;
5268 int before, before_byte;
5269 int opoint_byte;
5270 Lisp_Object text;
5271 struct buffer *b;
5273 Fset_buffer (p->buffer);
5274 opoint = PT;
5275 opoint_byte = PT_BYTE;
5276 old_read_only = current_buffer->read_only;
5277 old_begv = BEGV;
5278 old_zv = ZV;
5279 old_begv_byte = BEGV_BYTE;
5280 old_zv_byte = ZV_BYTE;
5282 current_buffer->read_only = Qnil;
5284 /* Insert new output into buffer
5285 at the current end-of-output marker,
5286 thus preserving logical ordering of input and output. */
5287 if (XMARKER (p->mark)->buffer)
5288 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5289 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5290 ZV_BYTE));
5291 else
5292 SET_PT_BOTH (ZV, ZV_BYTE);
5293 before = PT;
5294 before_byte = PT_BYTE;
5296 /* If the output marker is outside of the visible region, save
5297 the restriction and widen. */
5298 if (! (BEGV <= PT && PT <= ZV))
5299 Fwiden ();
5301 decode_coding_c_string (coding, chars, nbytes, Qt);
5302 text = coding->dst_object;
5303 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5304 /* A new coding system might be found. See the comment in the
5305 similar code in the previous `if' block. */
5306 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5308 p->decode_coding_system = Vlast_coding_system_used;
5309 if (NILP (p->encode_coding_system)
5310 && proc_encode_coding_system[p->outfd])
5312 p->encode_coding_system
5313 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5314 setup_coding_system (p->encode_coding_system,
5315 proc_encode_coding_system[p->outfd]);
5318 if (coding->carryover_bytes > 0)
5320 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5321 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5322 memcpy (SDATA (p->decoding_buf), coding->carryover,
5323 coding->carryover_bytes);
5324 p->decoding_carryover = coding->carryover_bytes;
5326 /* Adjust the multibyteness of TEXT to that of the buffer. */
5327 if (NILP (current_buffer->enable_multibyte_characters)
5328 != ! STRING_MULTIBYTE (text))
5329 text = (STRING_MULTIBYTE (text)
5330 ? Fstring_as_unibyte (text)
5331 : Fstring_to_multibyte (text));
5332 /* Insert before markers in case we are inserting where
5333 the buffer's mark is, and the user's next command is Meta-y. */
5334 insert_from_string_before_markers (text, 0, 0,
5335 SCHARS (text), SBYTES (text), 0);
5337 /* Make sure the process marker's position is valid when the
5338 process buffer is changed in the signal_after_change above.
5339 W3 is known to do that. */
5340 if (BUFFERP (p->buffer)
5341 && (b = XBUFFER (p->buffer), b != current_buffer))
5342 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5343 else
5344 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5346 update_mode_lines++;
5348 /* Make sure opoint and the old restrictions
5349 float ahead of any new text just as point would. */
5350 if (opoint >= before)
5352 opoint += PT - before;
5353 opoint_byte += PT_BYTE - before_byte;
5355 if (old_begv > before)
5357 old_begv += PT - before;
5358 old_begv_byte += PT_BYTE - before_byte;
5360 if (old_zv >= before)
5362 old_zv += PT - before;
5363 old_zv_byte += PT_BYTE - before_byte;
5366 /* If the restriction isn't what it should be, set it. */
5367 if (old_begv != BEGV || old_zv != ZV)
5368 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5371 current_buffer->read_only = old_read_only;
5372 SET_PT_BOTH (opoint, opoint_byte);
5374 /* Handling the process output should not deactivate the mark. */
5375 Vdeactivate_mark = odeactivate;
5377 unbind_to (count, Qnil);
5378 return nbytes;
5381 /* Sending data to subprocess */
5383 jmp_buf send_process_frame;
5384 Lisp_Object process_sent_to;
5386 SIGTYPE
5387 send_process_trap (int ignore)
5389 SIGNAL_THREAD_CHECK (SIGPIPE);
5390 sigunblock (sigmask (SIGPIPE));
5391 longjmp (send_process_frame, 1);
5394 /* Send some data to process PROC.
5395 BUF is the beginning of the data; LEN is the number of characters.
5396 OBJECT is the Lisp object that the data comes from. If OBJECT is
5397 nil or t, it means that the data comes from C string.
5399 If OBJECT is not nil, the data is encoded by PROC's coding-system
5400 for encoding before it is sent.
5402 This function can evaluate Lisp code and can garbage collect. */
5404 static void
5405 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5406 volatile int len, volatile Lisp_Object object)
5408 /* Use volatile to protect variables from being clobbered by longjmp. */
5409 struct Lisp_Process *p = XPROCESS (proc);
5410 int rv;
5411 struct coding_system *coding;
5412 struct gcpro gcpro1;
5413 SIGTYPE (*volatile old_sigpipe) (int);
5415 GCPRO1 (object);
5417 if (p->raw_status_new)
5418 update_status (p);
5419 if (! EQ (p->status, Qrun))
5420 error ("Process %s not running", SDATA (p->name));
5421 if (p->outfd < 0)
5422 error ("Output file descriptor of %s is closed", SDATA (p->name));
5424 coding = proc_encode_coding_system[p->outfd];
5425 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5427 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5428 || (BUFFERP (object)
5429 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5430 || EQ (object, Qt))
5432 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5433 /* The coding system for encoding was changed to raw-text
5434 because we sent a unibyte text previously. Now we are
5435 sending a multibyte text, thus we must encode it by the
5436 original coding system specified for the current process. */
5437 setup_coding_system (p->encode_coding_system, coding);
5438 coding->src_multibyte = 1;
5440 else
5442 /* For sending a unibyte text, character code conversion should
5443 not take place but EOL conversion should. So, setup raw-text
5444 or one of the subsidiary if we have not yet done it. */
5445 if (CODING_REQUIRE_ENCODING (coding))
5447 if (CODING_REQUIRE_FLUSHING (coding))
5449 /* But, before changing the coding, we must flush out data. */
5450 coding->mode |= CODING_MODE_LAST_BLOCK;
5451 send_process (proc, "", 0, Qt);
5452 coding->mode &= CODING_MODE_LAST_BLOCK;
5454 setup_coding_system (raw_text_coding_system
5455 (Vlast_coding_system_used),
5456 coding);
5457 coding->src_multibyte = 0;
5460 coding->dst_multibyte = 0;
5462 if (CODING_REQUIRE_ENCODING (coding))
5464 coding->dst_object = Qt;
5465 if (BUFFERP (object))
5467 int from_byte, from, to;
5468 int save_pt, save_pt_byte;
5469 struct buffer *cur = current_buffer;
5471 set_buffer_internal (XBUFFER (object));
5472 save_pt = PT, save_pt_byte = PT_BYTE;
5474 from_byte = PTR_BYTE_POS (buf);
5475 from = BYTE_TO_CHAR (from_byte);
5476 to = BYTE_TO_CHAR (from_byte + len);
5477 TEMP_SET_PT_BOTH (from, from_byte);
5478 encode_coding_object (coding, object, from, from_byte,
5479 to, from_byte + len, Qt);
5480 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5481 set_buffer_internal (cur);
5483 else if (STRINGP (object))
5485 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5486 SBYTES (object), Qt);
5488 else
5490 coding->dst_object = make_unibyte_string (buf, len);
5491 coding->produced = len;
5494 len = coding->produced;
5495 object = coding->dst_object;
5496 buf = SDATA (object);
5499 if (pty_max_bytes == 0)
5501 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5502 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5503 if (pty_max_bytes < 0)
5504 pty_max_bytes = 250;
5505 #else
5506 pty_max_bytes = 250;
5507 #endif
5508 /* Deduct one, to leave space for the eof. */
5509 pty_max_bytes--;
5512 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5513 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5514 when returning with longjmp despite being declared volatile. */
5515 if (!setjmp (send_process_frame))
5517 process_sent_to = proc;
5518 while (len > 0)
5520 int this = len;
5522 /* Send this batch, using one or more write calls. */
5523 while (this > 0)
5525 int outfd = p->outfd;
5526 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5527 #ifdef DATAGRAM_SOCKETS
5528 if (DATAGRAM_CHAN_P (outfd))
5530 rv = sendto (outfd, (char *) buf, this,
5531 0, datagram_address[outfd].sa,
5532 datagram_address[outfd].len);
5533 if (rv < 0 && errno == EMSGSIZE)
5535 signal (SIGPIPE, old_sigpipe);
5536 report_file_error ("sending datagram",
5537 Fcons (proc, Qnil));
5540 else
5541 #endif
5543 rv = emacs_write (outfd, (char *) buf, this);
5544 #ifdef ADAPTIVE_READ_BUFFERING
5545 if (p->read_output_delay > 0
5546 && p->adaptive_read_buffering == 1)
5548 p->read_output_delay = 0;
5549 process_output_delay_count--;
5550 p->read_output_skip = 0;
5552 #endif
5554 signal (SIGPIPE, old_sigpipe);
5556 if (rv < 0)
5558 if (0
5559 #ifdef EWOULDBLOCK
5560 || errno == EWOULDBLOCK
5561 #endif
5562 #ifdef EAGAIN
5563 || errno == EAGAIN
5564 #endif
5566 /* Buffer is full. Wait, accepting input;
5567 that may allow the program
5568 to finish doing output and read more. */
5570 int offset = 0;
5572 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5573 /* A gross hack to work around a bug in FreeBSD.
5574 In the following sequence, read(2) returns
5575 bogus data:
5577 write(2) 1022 bytes
5578 write(2) 954 bytes, get EAGAIN
5579 read(2) 1024 bytes in process_read_output
5580 read(2) 11 bytes in process_read_output
5582 That is, read(2) returns more bytes than have
5583 ever been written successfully. The 1033 bytes
5584 read are the 1022 bytes written successfully
5585 after processing (for example with CRs added if
5586 the terminal is set up that way which it is
5587 here). The same bytes will be seen again in a
5588 later read(2), without the CRs. */
5590 if (errno == EAGAIN)
5592 int flags = FWRITE;
5593 ioctl (p->outfd, TIOCFLUSH, &flags);
5595 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5597 /* Running filters might relocate buffers or strings.
5598 Arrange to relocate BUF. */
5599 if (BUFFERP (object))
5600 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5601 else if (STRINGP (object))
5602 offset = buf - SDATA (object);
5604 #ifdef EMACS_HAS_USECS
5605 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5606 #else
5607 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5608 #endif
5610 if (BUFFERP (object))
5611 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5612 else if (STRINGP (object))
5613 buf = offset + SDATA (object);
5615 rv = 0;
5617 else
5618 /* This is a real error. */
5619 report_file_error ("writing to process", Fcons (proc, Qnil));
5621 buf += rv;
5622 len -= rv;
5623 this -= rv;
5627 else
5629 signal (SIGPIPE, old_sigpipe);
5630 proc = process_sent_to;
5631 p = XPROCESS (proc);
5632 p->raw_status_new = 0;
5633 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5634 p->tick = ++process_tick;
5635 deactivate_process (proc);
5636 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5639 UNGCPRO;
5642 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5643 3, 3, 0,
5644 doc: /* Send current contents of region as input to PROCESS.
5645 PROCESS may be a process, a buffer, the name of a process or buffer, or
5646 nil, indicating the current buffer's process.
5647 Called from program, takes three arguments, PROCESS, START and END.
5648 If the region is more than 500 characters long,
5649 it is sent in several bunches. This may happen even for shorter regions.
5650 Output from processes can arrive in between bunches. */)
5651 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5653 Lisp_Object proc;
5654 int start1, end1;
5656 proc = get_process (process);
5657 validate_region (&start, &end);
5659 if (XINT (start) < GPT && XINT (end) > GPT)
5660 move_gap (XINT (start));
5662 start1 = CHAR_TO_BYTE (XINT (start));
5663 end1 = CHAR_TO_BYTE (XINT (end));
5664 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5665 Fcurrent_buffer ());
5667 return Qnil;
5670 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5671 2, 2, 0,
5672 doc: /* Send PROCESS the contents of STRING as input.
5673 PROCESS may be a process, a buffer, the name of a process or buffer, or
5674 nil, indicating the current buffer's process.
5675 If STRING is more than 500 characters long,
5676 it is sent in several bunches. This may happen even for shorter strings.
5677 Output from processes can arrive in between bunches. */)
5678 (Lisp_Object process, Lisp_Object string)
5680 Lisp_Object proc;
5681 CHECK_STRING (string);
5682 proc = get_process (process);
5683 send_process (proc, SDATA (string),
5684 SBYTES (string), string);
5685 return Qnil;
5688 /* Return the foreground process group for the tty/pty that
5689 the process P uses. */
5690 static int
5691 emacs_get_tty_pgrp (struct Lisp_Process *p)
5693 int gid = -1;
5695 #ifdef TIOCGPGRP
5696 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5698 int fd;
5699 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5700 master side. Try the slave side. */
5701 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5703 if (fd != -1)
5705 ioctl (fd, TIOCGPGRP, &gid);
5706 emacs_close (fd);
5709 #endif /* defined (TIOCGPGRP ) */
5711 return gid;
5714 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5715 Sprocess_running_child_p, 0, 1, 0,
5716 doc: /* Return t if PROCESS has given the terminal to a child.
5717 If the operating system does not make it possible to find out,
5718 return t unconditionally. */)
5719 (Lisp_Object process)
5721 /* Initialize in case ioctl doesn't exist or gives an error,
5722 in a way that will cause returning t. */
5723 int gid;
5724 Lisp_Object proc;
5725 struct Lisp_Process *p;
5727 proc = get_process (process);
5728 p = XPROCESS (proc);
5730 if (!EQ (p->type, Qreal))
5731 error ("Process %s is not a subprocess",
5732 SDATA (p->name));
5733 if (p->infd < 0)
5734 error ("Process %s is not active",
5735 SDATA (p->name));
5737 gid = emacs_get_tty_pgrp (p);
5739 if (gid == p->pid)
5740 return Qnil;
5741 return Qt;
5744 /* send a signal number SIGNO to PROCESS.
5745 If CURRENT_GROUP is t, that means send to the process group
5746 that currently owns the terminal being used to communicate with PROCESS.
5747 This is used for various commands in shell mode.
5748 If CURRENT_GROUP is lambda, that means send to the process group
5749 that currently owns the terminal, but only if it is NOT the shell itself.
5751 If NOMSG is zero, insert signal-announcements into process's buffers
5752 right away.
5754 If we can, we try to signal PROCESS by sending control characters
5755 down the pty. This allows us to signal inferiors who have changed
5756 their uid, for which killpg would return an EPERM error. */
5758 static void
5759 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5760 int nomsg)
5762 Lisp_Object proc;
5763 register struct Lisp_Process *p;
5764 int gid;
5765 int no_pgrp = 0;
5767 proc = get_process (process);
5768 p = XPROCESS (proc);
5770 if (!EQ (p->type, Qreal))
5771 error ("Process %s is not a subprocess",
5772 SDATA (p->name));
5773 if (p->infd < 0)
5774 error ("Process %s is not active",
5775 SDATA (p->name));
5777 if (!p->pty_flag)
5778 current_group = Qnil;
5780 /* If we are using pgrps, get a pgrp number and make it negative. */
5781 if (NILP (current_group))
5782 /* Send the signal to the shell's process group. */
5783 gid = p->pid;
5784 else
5786 #ifdef SIGNALS_VIA_CHARACTERS
5787 /* If possible, send signals to the entire pgrp
5788 by sending an input character to it. */
5790 struct termios t;
5791 cc_t *sig_char = NULL;
5793 tcgetattr (p->infd, &t);
5795 switch (signo)
5797 case SIGINT:
5798 sig_char = &t.c_cc[VINTR];
5799 break;
5801 case SIGQUIT:
5802 sig_char = &t.c_cc[VQUIT];
5803 break;
5805 case SIGTSTP:
5806 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5807 sig_char = &t.c_cc[VSWTCH];
5808 #else
5809 sig_char = &t.c_cc[VSUSP];
5810 #endif
5811 break;
5814 if (sig_char && *sig_char != CDISABLE)
5816 send_process (proc, sig_char, 1, Qnil);
5817 return;
5819 /* If we can't send the signal with a character,
5820 fall through and send it another way. */
5822 /* The code above may fall through if it can't
5823 handle the signal. */
5824 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5826 #ifdef TIOCGPGRP
5827 /* Get the current pgrp using the tty itself, if we have that.
5828 Otherwise, use the pty to get the pgrp.
5829 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5830 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5831 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5832 His patch indicates that if TIOCGPGRP returns an error, then
5833 we should just assume that p->pid is also the process group id. */
5835 gid = emacs_get_tty_pgrp (p);
5837 if (gid == -1)
5838 /* If we can't get the information, assume
5839 the shell owns the tty. */
5840 gid = p->pid;
5842 /* It is not clear whether anything really can set GID to -1.
5843 Perhaps on some system one of those ioctls can or could do so.
5844 Or perhaps this is vestigial. */
5845 if (gid == -1)
5846 no_pgrp = 1;
5847 #else /* ! defined (TIOCGPGRP ) */
5848 /* Can't select pgrps on this system, so we know that
5849 the child itself heads the pgrp. */
5850 gid = p->pid;
5851 #endif /* ! defined (TIOCGPGRP ) */
5853 /* If current_group is lambda, and the shell owns the terminal,
5854 don't send any signal. */
5855 if (EQ (current_group, Qlambda) && gid == p->pid)
5856 return;
5859 switch (signo)
5861 #ifdef SIGCONT
5862 case SIGCONT:
5863 p->raw_status_new = 0;
5864 p->status = Qrun;
5865 p->tick = ++process_tick;
5866 if (!nomsg)
5868 status_notify (NULL);
5869 redisplay_preserve_echo_area (13);
5871 break;
5872 #endif /* ! defined (SIGCONT) */
5873 case SIGINT:
5874 case SIGQUIT:
5875 case SIGKILL:
5876 flush_pending_output (p->infd);
5877 break;
5880 /* If we don't have process groups, send the signal to the immediate
5881 subprocess. That isn't really right, but it's better than any
5882 obvious alternative. */
5883 if (no_pgrp)
5885 kill (p->pid, signo);
5886 return;
5889 /* gid may be a pid, or minus a pgrp's number */
5890 #ifdef TIOCSIGSEND
5891 if (!NILP (current_group))
5893 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5894 EMACS_KILLPG (gid, signo);
5896 else
5898 gid = - p->pid;
5899 kill (gid, signo);
5901 #else /* ! defined (TIOCSIGSEND) */
5902 EMACS_KILLPG (gid, signo);
5903 #endif /* ! defined (TIOCSIGSEND) */
5906 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5907 doc: /* Interrupt process PROCESS.
5908 PROCESS may be a process, a buffer, or the name of a process or buffer.
5909 No arg or nil means current buffer's process.
5910 Second arg CURRENT-GROUP non-nil means send signal to
5911 the current process-group of the process's controlling terminal
5912 rather than to the process's own process group.
5913 If the process is a shell, this means interrupt current subjob
5914 rather than the shell.
5916 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5917 don't send the signal. */)
5918 (Lisp_Object process, Lisp_Object current_group)
5920 process_send_signal (process, SIGINT, current_group, 0);
5921 return process;
5924 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5925 doc: /* Kill process PROCESS. May be process or name of one.
5926 See function `interrupt-process' for more details on usage. */)
5927 (Lisp_Object process, Lisp_Object current_group)
5929 process_send_signal (process, SIGKILL, current_group, 0);
5930 return process;
5933 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5934 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5935 See function `interrupt-process' for more details on usage. */)
5936 (Lisp_Object process, Lisp_Object current_group)
5938 process_send_signal (process, SIGQUIT, current_group, 0);
5939 return process;
5942 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5943 doc: /* Stop process PROCESS. May be process or name of one.
5944 See function `interrupt-process' for more details on usage.
5945 If PROCESS is a network or serial process, inhibit handling of incoming
5946 traffic. */)
5947 (Lisp_Object process, Lisp_Object current_group)
5949 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5951 struct Lisp_Process *p;
5953 p = XPROCESS (process);
5954 if (NILP (p->command)
5955 && p->infd >= 0)
5957 FD_CLR (p->infd, &input_wait_mask);
5958 FD_CLR (p->infd, &non_keyboard_wait_mask);
5960 p->command = Qt;
5961 return process;
5963 #ifndef SIGTSTP
5964 error ("No SIGTSTP support");
5965 #else
5966 process_send_signal (process, SIGTSTP, current_group, 0);
5967 #endif
5968 return process;
5971 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5972 doc: /* Continue process PROCESS. May be process or name of one.
5973 See function `interrupt-process' for more details on usage.
5974 If PROCESS is a network or serial process, resume handling of incoming
5975 traffic. */)
5976 (Lisp_Object process, Lisp_Object current_group)
5978 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5980 struct Lisp_Process *p;
5982 p = XPROCESS (process);
5983 if (EQ (p->command, Qt)
5984 && p->infd >= 0
5985 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5987 FD_SET (p->infd, &input_wait_mask);
5988 FD_SET (p->infd, &non_keyboard_wait_mask);
5989 #ifdef WINDOWSNT
5990 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5991 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5992 #else /* not WINDOWSNT */
5993 tcflush (p->infd, TCIFLUSH);
5994 #endif /* not WINDOWSNT */
5996 p->command = Qnil;
5997 return process;
5999 #ifdef SIGCONT
6000 process_send_signal (process, SIGCONT, current_group, 0);
6001 #else
6002 error ("No SIGCONT support");
6003 #endif
6004 return process;
6007 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6008 2, 2, "sProcess (name or number): \nnSignal code: ",
6009 doc: /* Send PROCESS the signal with code SIGCODE.
6010 PROCESS may also be a number specifying the process id of the
6011 process to signal; in this case, the process need not be a child of
6012 this Emacs.
6013 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6014 (Lisp_Object process, Lisp_Object sigcode)
6016 pid_t pid;
6018 if (INTEGERP (process))
6020 pid = XINT (process);
6021 goto got_it;
6024 if (FLOATP (process))
6026 pid = (pid_t) XFLOAT_DATA (process);
6027 goto got_it;
6030 if (STRINGP (process))
6032 Lisp_Object tem;
6033 if (tem = Fget_process (process), NILP (tem))
6035 pid = XINT (Fstring_to_number (process, make_number (10)));
6036 if (pid > 0)
6037 goto got_it;
6039 process = tem;
6041 else
6042 process = get_process (process);
6044 if (NILP (process))
6045 return process;
6047 CHECK_PROCESS (process);
6048 pid = XPROCESS (process)->pid;
6049 if (pid <= 0)
6050 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6052 got_it:
6054 #define parse_signal(NAME, VALUE) \
6055 else if (!xstrcasecmp (name, NAME)) \
6056 XSETINT (sigcode, VALUE)
6058 if (INTEGERP (sigcode))
6060 else
6062 unsigned char *name;
6064 CHECK_SYMBOL (sigcode);
6065 name = SDATA (SYMBOL_NAME (sigcode));
6067 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6068 name += 3;
6070 if (0)
6072 #ifdef SIGUSR1
6073 parse_signal ("usr1", SIGUSR1);
6074 #endif
6075 #ifdef SIGUSR2
6076 parse_signal ("usr2", SIGUSR2);
6077 #endif
6078 #ifdef SIGTERM
6079 parse_signal ("term", SIGTERM);
6080 #endif
6081 #ifdef SIGHUP
6082 parse_signal ("hup", SIGHUP);
6083 #endif
6084 #ifdef SIGINT
6085 parse_signal ("int", SIGINT);
6086 #endif
6087 #ifdef SIGQUIT
6088 parse_signal ("quit", SIGQUIT);
6089 #endif
6090 #ifdef SIGILL
6091 parse_signal ("ill", SIGILL);
6092 #endif
6093 #ifdef SIGABRT
6094 parse_signal ("abrt", SIGABRT);
6095 #endif
6096 #ifdef SIGEMT
6097 parse_signal ("emt", SIGEMT);
6098 #endif
6099 #ifdef SIGKILL
6100 parse_signal ("kill", SIGKILL);
6101 #endif
6102 #ifdef SIGFPE
6103 parse_signal ("fpe", SIGFPE);
6104 #endif
6105 #ifdef SIGBUS
6106 parse_signal ("bus", SIGBUS);
6107 #endif
6108 #ifdef SIGSEGV
6109 parse_signal ("segv", SIGSEGV);
6110 #endif
6111 #ifdef SIGSYS
6112 parse_signal ("sys", SIGSYS);
6113 #endif
6114 #ifdef SIGPIPE
6115 parse_signal ("pipe", SIGPIPE);
6116 #endif
6117 #ifdef SIGALRM
6118 parse_signal ("alrm", SIGALRM);
6119 #endif
6120 #ifdef SIGURG
6121 parse_signal ("urg", SIGURG);
6122 #endif
6123 #ifdef SIGSTOP
6124 parse_signal ("stop", SIGSTOP);
6125 #endif
6126 #ifdef SIGTSTP
6127 parse_signal ("tstp", SIGTSTP);
6128 #endif
6129 #ifdef SIGCONT
6130 parse_signal ("cont", SIGCONT);
6131 #endif
6132 #ifdef SIGCHLD
6133 parse_signal ("chld", SIGCHLD);
6134 #endif
6135 #ifdef SIGTTIN
6136 parse_signal ("ttin", SIGTTIN);
6137 #endif
6138 #ifdef SIGTTOU
6139 parse_signal ("ttou", SIGTTOU);
6140 #endif
6141 #ifdef SIGIO
6142 parse_signal ("io", SIGIO);
6143 #endif
6144 #ifdef SIGXCPU
6145 parse_signal ("xcpu", SIGXCPU);
6146 #endif
6147 #ifdef SIGXFSZ
6148 parse_signal ("xfsz", SIGXFSZ);
6149 #endif
6150 #ifdef SIGVTALRM
6151 parse_signal ("vtalrm", SIGVTALRM);
6152 #endif
6153 #ifdef SIGPROF
6154 parse_signal ("prof", SIGPROF);
6155 #endif
6156 #ifdef SIGWINCH
6157 parse_signal ("winch", SIGWINCH);
6158 #endif
6159 #ifdef SIGINFO
6160 parse_signal ("info", SIGINFO);
6161 #endif
6162 else
6163 error ("Undefined signal name %s", name);
6166 #undef parse_signal
6168 return make_number (kill (pid, XINT (sigcode)));
6171 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6172 doc: /* Make PROCESS see end-of-file in its input.
6173 EOF comes after any text already sent to it.
6174 PROCESS may be a process, a buffer, the name of a process or buffer, or
6175 nil, indicating the current buffer's process.
6176 If PROCESS is a network connection, or is a process communicating
6177 through a pipe (as opposed to a pty), then you cannot send any more
6178 text to PROCESS after you call this function.
6179 If PROCESS is a serial process, wait until all output written to the
6180 process has been transmitted to the serial port. */)
6181 (Lisp_Object process)
6183 Lisp_Object proc;
6184 struct coding_system *coding;
6186 if (DATAGRAM_CONN_P (process))
6187 return process;
6189 proc = get_process (process);
6190 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6192 /* Make sure the process is really alive. */
6193 if (XPROCESS (proc)->raw_status_new)
6194 update_status (XPROCESS (proc));
6195 if (! EQ (XPROCESS (proc)->status, Qrun))
6196 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6198 if (CODING_REQUIRE_FLUSHING (coding))
6200 coding->mode |= CODING_MODE_LAST_BLOCK;
6201 send_process (proc, "", 0, Qnil);
6204 if (XPROCESS (proc)->pty_flag)
6205 send_process (proc, "\004", 1, Qnil);
6206 else if (EQ (XPROCESS (proc)->type, Qserial))
6208 #ifndef WINDOWSNT
6209 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6210 error ("tcdrain() failed: %s", emacs_strerror (errno));
6211 #endif /* not WINDOWSNT */
6212 /* Do nothing on Windows because writes are blocking. */
6214 else
6216 int old_outfd, new_outfd;
6218 #ifdef HAVE_SHUTDOWN
6219 /* If this is a network connection, or socketpair is used
6220 for communication with the subprocess, call shutdown to cause EOF.
6221 (In some old system, shutdown to socketpair doesn't work.
6222 Then we just can't win.) */
6223 if (EQ (XPROCESS (proc)->type, Qnetwork)
6224 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6225 shutdown (XPROCESS (proc)->outfd, 1);
6226 /* In case of socketpair, outfd == infd, so don't close it. */
6227 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6228 emacs_close (XPROCESS (proc)->outfd);
6229 #else /* not HAVE_SHUTDOWN */
6230 emacs_close (XPROCESS (proc)->outfd);
6231 #endif /* not HAVE_SHUTDOWN */
6232 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6233 if (new_outfd < 0)
6234 abort ();
6235 old_outfd = XPROCESS (proc)->outfd;
6237 if (!proc_encode_coding_system[new_outfd])
6238 proc_encode_coding_system[new_outfd]
6239 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6240 memcpy (proc_encode_coding_system[new_outfd],
6241 proc_encode_coding_system[old_outfd],
6242 sizeof (struct coding_system));
6243 memset (proc_encode_coding_system[old_outfd], 0,
6244 sizeof (struct coding_system));
6246 XPROCESS (proc)->outfd = new_outfd;
6248 return process;
6251 /* On receipt of a signal that a child status has changed, loop asking
6252 about children with changed statuses until the system says there
6253 are no more.
6255 All we do is change the status; we do not run sentinels or print
6256 notifications. That is saved for the next time keyboard input is
6257 done, in order to avoid timing errors.
6259 ** WARNING: this can be called during garbage collection.
6260 Therefore, it must not be fooled by the presence of mark bits in
6261 Lisp objects.
6263 ** USG WARNING: Although it is not obvious from the documentation
6264 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6265 signal() before executing at least one wait(), otherwise the
6266 handler will be called again, resulting in an infinite loop. The
6267 relevant portion of the documentation reads "SIGCLD signals will be
6268 queued and the signal-catching function will be continually
6269 reentered until the queue is empty". Invoking signal() causes the
6270 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6271 Inc.
6273 ** Malloc WARNING: This should never call malloc either directly or
6274 indirectly; if it does, that is a bug */
6276 #ifdef SIGCHLD
6277 SIGTYPE
6278 sigchld_handler (int signo)
6280 int old_errno = errno;
6281 Lisp_Object proc;
6282 struct Lisp_Process *p;
6284 SIGNAL_THREAD_CHECK (signo);
6286 while (1)
6288 pid_t pid;
6289 int w;
6290 Lisp_Object tail;
6292 #ifdef WNOHANG
6293 #ifndef WUNTRACED
6294 #define WUNTRACED 0
6295 #endif /* no WUNTRACED */
6296 /* Keep trying to get a status until we get a definitive result. */
6299 errno = 0;
6300 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6302 while (pid < 0 && errno == EINTR);
6304 if (pid <= 0)
6306 /* PID == 0 means no processes found, PID == -1 means a real
6307 failure. We have done all our job, so return. */
6309 errno = old_errno;
6310 return;
6312 #else
6313 pid = wait (&w);
6314 #endif /* no WNOHANG */
6316 /* Find the process that signaled us, and record its status. */
6318 /* The process can have been deleted by Fdelete_process. */
6319 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6321 Lisp_Object xpid = XCAR (tail);
6322 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6323 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6325 XSETCAR (tail, Qnil);
6326 goto sigchld_end_of_loop;
6330 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6331 p = 0;
6332 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6334 proc = XCDR (XCAR (tail));
6335 p = XPROCESS (proc);
6336 if (EQ (p->type, Qreal) && p->pid == pid)
6337 break;
6338 p = 0;
6341 /* Look for an asynchronous process whose pid hasn't been filled
6342 in yet. */
6343 if (p == 0)
6344 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6346 proc = XCDR (XCAR (tail));
6347 p = XPROCESS (proc);
6348 if (p->pid == -1)
6349 break;
6350 p = 0;
6353 /* Change the status of the process that was found. */
6354 if (p != 0)
6356 int clear_desc_flag = 0;
6358 p->tick = ++process_tick;
6359 p->raw_status = w;
6360 p->raw_status_new = 1;
6362 /* If process has terminated, stop waiting for its output. */
6363 if ((WIFSIGNALED (w) || WIFEXITED (w))
6364 && p->infd >= 0)
6365 clear_desc_flag = 1;
6367 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6368 if (clear_desc_flag)
6370 FD_CLR (p->infd, &input_wait_mask);
6371 FD_CLR (p->infd, &non_keyboard_wait_mask);
6374 /* Tell wait_reading_process_output that it needs to wake up and
6375 look around. */
6376 if (input_available_clear_time)
6377 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6380 /* There was no asynchronous process found for that pid: we have
6381 a synchronous process. */
6382 else
6384 synch_process_alive = 0;
6386 /* Report the status of the synchronous process. */
6387 if (WIFEXITED (w))
6388 synch_process_retcode = WRETCODE (w);
6389 else if (WIFSIGNALED (w))
6390 synch_process_termsig = WTERMSIG (w);
6392 /* Tell wait_reading_process_output that it needs to wake up and
6393 look around. */
6394 if (input_available_clear_time)
6395 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6398 sigchld_end_of_loop:
6401 /* On some systems, we must return right away.
6402 If any more processes want to signal us, we will
6403 get another signal.
6404 Otherwise (on systems that have WNOHANG), loop around
6405 to use up all the processes that have something to tell us. */
6406 #if (defined WINDOWSNT \
6407 || (defined USG && !defined GNU_LINUX \
6408 && !(defined HPUX && defined WNOHANG)))
6409 errno = old_errno;
6410 return;
6411 #endif /* USG, but not HPUX with WNOHANG */
6414 #endif /* SIGCHLD */
6417 static Lisp_Object
6418 exec_sentinel_unwind (Lisp_Object data)
6420 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6421 return Qnil;
6424 static Lisp_Object
6425 exec_sentinel_error_handler (Lisp_Object error)
6427 cmd_error_internal (error, "error in process sentinel: ");
6428 Vinhibit_quit = Qt;
6429 update_echo_area ();
6430 Fsleep_for (make_number (2), Qnil);
6431 return Qt;
6434 static void
6435 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6437 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6438 register struct Lisp_Process *p = XPROCESS (proc);
6439 int count = SPECPDL_INDEX ();
6440 int outer_running_asynch_code = running_asynch_code;
6441 int waiting = waiting_for_user_input_p;
6443 if (inhibit_sentinels)
6444 return;
6446 /* No need to gcpro these, because all we do with them later
6447 is test them for EQness, and none of them should be a string. */
6448 odeactivate = Vdeactivate_mark;
6449 XSETBUFFER (obuffer, current_buffer);
6450 okeymap = current_buffer->keymap;
6452 /* There's no good reason to let sentinels change the current
6453 buffer, and many callers of accept-process-output, sit-for, and
6454 friends don't expect current-buffer to be changed from under them. */
6455 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6457 sentinel = p->sentinel;
6458 if (NILP (sentinel))
6459 return;
6461 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6462 assure that it gets restored no matter how the sentinel exits. */
6463 p->sentinel = Qnil;
6464 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6465 /* Inhibit quit so that random quits don't screw up a running filter. */
6466 specbind (Qinhibit_quit, Qt);
6467 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6469 /* In case we get recursively called,
6470 and we already saved the match data nonrecursively,
6471 save the same match data in safely recursive fashion. */
6472 if (outer_running_asynch_code)
6474 Lisp_Object tem;
6475 tem = Fmatch_data (Qnil, Qnil, Qnil);
6476 restore_search_regs ();
6477 record_unwind_save_match_data ();
6478 Fset_match_data (tem, Qt);
6481 /* For speed, if a search happens within this code,
6482 save the match data in a special nonrecursive fashion. */
6483 running_asynch_code = 1;
6485 internal_condition_case_1 (read_process_output_call,
6486 Fcons (sentinel,
6487 Fcons (proc, Fcons (reason, Qnil))),
6488 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6489 exec_sentinel_error_handler);
6491 /* If we saved the match data nonrecursively, restore it now. */
6492 restore_search_regs ();
6493 running_asynch_code = outer_running_asynch_code;
6495 Vdeactivate_mark = odeactivate;
6497 /* Restore waiting_for_user_input_p as it was
6498 when we were called, in case the filter clobbered it. */
6499 waiting_for_user_input_p = waiting;
6501 #if 0
6502 if (! EQ (Fcurrent_buffer (), obuffer)
6503 || ! EQ (current_buffer->keymap, okeymap))
6504 #endif
6505 /* But do it only if the caller is actually going to read events.
6506 Otherwise there's no need to make him wake up, and it could
6507 cause trouble (for example it would make sit_for return). */
6508 if (waiting_for_user_input_p == -1)
6509 record_asynch_buffer_change ();
6511 unbind_to (count, Qnil);
6514 /* Report all recent events of a change in process status
6515 (either run the sentinel or output a message).
6516 This is usually done while Emacs is waiting for keyboard input
6517 but can be done at other times. */
6519 static void
6520 status_notify (struct Lisp_Process *deleting_process)
6522 register Lisp_Object proc, buffer;
6523 Lisp_Object tail, msg;
6524 struct gcpro gcpro1, gcpro2;
6526 tail = Qnil;
6527 msg = Qnil;
6528 /* We need to gcpro tail; if read_process_output calls a filter
6529 which deletes a process and removes the cons to which tail points
6530 from Vprocess_alist, and then causes a GC, tail is an unprotected
6531 reference. */
6532 GCPRO2 (tail, msg);
6534 /* Set this now, so that if new processes are created by sentinels
6535 that we run, we get called again to handle their status changes. */
6536 update_tick = process_tick;
6538 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6540 Lisp_Object symbol;
6541 register struct Lisp_Process *p;
6543 proc = Fcdr (XCAR (tail));
6544 p = XPROCESS (proc);
6546 if (p->tick != p->update_tick)
6548 p->update_tick = p->tick;
6550 /* If process is still active, read any output that remains. */
6551 while (! EQ (p->filter, Qt)
6552 && ! EQ (p->status, Qconnect)
6553 && ! EQ (p->status, Qlisten)
6554 /* Network or serial process not stopped: */
6555 && ! EQ (p->command, Qt)
6556 && p->infd >= 0
6557 && p != deleting_process
6558 && read_process_output (proc, p->infd) > 0);
6560 buffer = p->buffer;
6562 /* Get the text to use for the message. */
6563 if (p->raw_status_new)
6564 update_status (p);
6565 msg = status_message (p);
6567 /* If process is terminated, deactivate it or delete it. */
6568 symbol = p->status;
6569 if (CONSP (p->status))
6570 symbol = XCAR (p->status);
6572 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6573 || EQ (symbol, Qclosed))
6575 if (delete_exited_processes)
6576 remove_process (proc);
6577 else
6578 deactivate_process (proc);
6581 /* The actions above may have further incremented p->tick.
6582 So set p->update_tick again
6583 so that an error in the sentinel will not cause
6584 this code to be run again. */
6585 p->update_tick = p->tick;
6586 /* Now output the message suitably. */
6587 if (!NILP (p->sentinel))
6588 exec_sentinel (proc, msg);
6589 /* Don't bother with a message in the buffer
6590 when a process becomes runnable. */
6591 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6593 Lisp_Object tem;
6594 struct buffer *old = current_buffer;
6595 int opoint, opoint_byte;
6596 int before, before_byte;
6598 /* Avoid error if buffer is deleted
6599 (probably that's why the process is dead, too) */
6600 if (NILP (XBUFFER (buffer)->name))
6601 continue;
6602 Fset_buffer (buffer);
6604 opoint = PT;
6605 opoint_byte = PT_BYTE;
6606 /* Insert new output into buffer
6607 at the current end-of-output marker,
6608 thus preserving logical ordering of input and output. */
6609 if (XMARKER (p->mark)->buffer)
6610 Fgoto_char (p->mark);
6611 else
6612 SET_PT_BOTH (ZV, ZV_BYTE);
6614 before = PT;
6615 before_byte = PT_BYTE;
6617 tem = current_buffer->read_only;
6618 current_buffer->read_only = Qnil;
6619 insert_string ("\nProcess ");
6620 Finsert (1, &p->name);
6621 insert_string (" ");
6622 Finsert (1, &msg);
6623 current_buffer->read_only = tem;
6624 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6626 if (opoint >= before)
6627 SET_PT_BOTH (opoint + (PT - before),
6628 opoint_byte + (PT_BYTE - before_byte));
6629 else
6630 SET_PT_BOTH (opoint, opoint_byte);
6632 set_buffer_internal (old);
6635 } /* end for */
6637 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6638 UNGCPRO;
6642 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6643 Sset_process_coding_system, 1, 3, 0,
6644 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6645 DECODING will be used to decode subprocess output and ENCODING to
6646 encode subprocess input. */)
6647 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6649 register struct Lisp_Process *p;
6651 CHECK_PROCESS (process);
6652 p = XPROCESS (process);
6653 if (p->infd < 0)
6654 error ("Input file descriptor of %s closed", SDATA (p->name));
6655 if (p->outfd < 0)
6656 error ("Output file descriptor of %s closed", SDATA (p->name));
6657 Fcheck_coding_system (decoding);
6658 Fcheck_coding_system (encoding);
6659 encoding = coding_inherit_eol_type (encoding, Qnil);
6660 p->decode_coding_system = decoding;
6661 p->encode_coding_system = encoding;
6662 setup_process_coding_systems (process);
6664 return Qnil;
6667 DEFUN ("process-coding-system",
6668 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6669 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6670 (register Lisp_Object process)
6672 CHECK_PROCESS (process);
6673 return Fcons (XPROCESS (process)->decode_coding_system,
6674 XPROCESS (process)->encode_coding_system);
6677 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6678 Sset_process_filter_multibyte, 2, 2, 0,
6679 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6680 If FLAG is non-nil, the filter is given multibyte strings.
6681 If FLAG is nil, the filter is given unibyte strings. In this case,
6682 all character code conversion except for end-of-line conversion is
6683 suppressed. */)
6684 (Lisp_Object process, Lisp_Object flag)
6686 register struct Lisp_Process *p;
6688 CHECK_PROCESS (process);
6689 p = XPROCESS (process);
6690 if (NILP (flag))
6691 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6692 setup_process_coding_systems (process);
6694 return Qnil;
6697 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6698 Sprocess_filter_multibyte_p, 1, 1, 0,
6699 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6700 (Lisp_Object process)
6702 register struct Lisp_Process *p;
6703 struct coding_system *coding;
6705 CHECK_PROCESS (process);
6706 p = XPROCESS (process);
6707 coding = proc_decode_coding_system[p->infd];
6708 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6714 static int add_gpm_wait_descriptor_called_flag;
6716 void
6717 add_gpm_wait_descriptor (int desc)
6719 if (! add_gpm_wait_descriptor_called_flag)
6720 FD_CLR (0, &input_wait_mask);
6721 add_gpm_wait_descriptor_called_flag = 1;
6722 FD_SET (desc, &input_wait_mask);
6723 FD_SET (desc, &gpm_wait_mask);
6724 if (desc > max_gpm_desc)
6725 max_gpm_desc = desc;
6728 void
6729 delete_gpm_wait_descriptor (int desc)
6731 int fd;
6732 int lim = max_gpm_desc;
6734 FD_CLR (desc, &input_wait_mask);
6735 FD_CLR (desc, &non_process_wait_mask);
6737 if (desc == max_gpm_desc)
6738 for (fd = 0; fd < lim; fd++)
6739 if (FD_ISSET (fd, &input_wait_mask)
6740 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6741 && !FD_ISSET (fd, &non_process_wait_mask))
6742 max_gpm_desc = fd;
6745 /* Return nonzero if *MASK has a bit set
6746 that corresponds to one of the keyboard input descriptors. */
6748 static int
6749 keyboard_bit_set (fd_set *mask)
6751 int fd;
6753 for (fd = 0; fd <= max_keyboard_desc; fd++)
6754 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6755 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6756 return 1;
6758 return 0;
6761 #else /* not subprocesses */
6763 /* Defined on msdos.c. */
6764 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6765 EMACS_TIME *);
6767 /* Implementation of wait_reading_process_output, assuming that there
6768 are no subprocesses. Used only by the MS-DOS build.
6770 Wait for timeout to elapse and/or keyboard input to be available.
6772 time_limit is:
6773 timeout in seconds, or
6774 zero for no limit, or
6775 -1 means gobble data immediately available but don't wait for any.
6777 read_kbd is a Lisp_Object:
6778 0 to ignore keyboard input, or
6779 1 to return when input is available, or
6780 -1 means caller will actually read the input, so don't throw to
6781 the quit handler.
6783 see full version for other parameters. We know that wait_proc will
6784 always be NULL, since `subprocesses' isn't defined.
6786 do_display != 0 means redisplay should be done to show subprocess
6787 output that arrives.
6789 Return true if we received input from any process. */
6792 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6793 int do_display,
6794 Lisp_Object wait_for_cell,
6795 struct Lisp_Process *wait_proc, int just_wait_proc)
6797 register int nfds;
6798 EMACS_TIME end_time, timeout;
6799 SELECT_TYPE waitchannels;
6800 int xerrno;
6802 /* What does time_limit really mean? */
6803 if (time_limit || microsecs)
6805 EMACS_GET_TIME (end_time);
6806 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6807 EMACS_ADD_TIME (end_time, end_time, timeout);
6810 /* Turn off periodic alarms (in case they are in use)
6811 and then turn off any other atimers,
6812 because the select emulator uses alarms. */
6813 stop_polling ();
6814 turn_on_atimers (0);
6816 while (1)
6818 int timeout_reduced_for_timers = 0;
6820 /* If calling from keyboard input, do not quit
6821 since we want to return C-g as an input character.
6822 Otherwise, do pending quit if requested. */
6823 if (read_kbd >= 0)
6824 QUIT;
6826 /* Exit now if the cell we're waiting for became non-nil. */
6827 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6828 break;
6830 /* Compute time from now till when time limit is up */
6831 /* Exit if already run out */
6832 if (time_limit == -1)
6834 /* -1 specified for timeout means
6835 gobble output available now
6836 but don't wait at all. */
6838 EMACS_SET_SECS_USECS (timeout, 0, 0);
6840 else if (time_limit || microsecs)
6842 EMACS_GET_TIME (timeout);
6843 EMACS_SUB_TIME (timeout, end_time, timeout);
6844 if (EMACS_TIME_NEG_P (timeout))
6845 break;
6847 else
6849 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6852 /* If our caller will not immediately handle keyboard events,
6853 run timer events directly.
6854 (Callers that will immediately read keyboard events
6855 call timer_delay on their own.) */
6856 if (NILP (wait_for_cell))
6858 EMACS_TIME timer_delay;
6862 int old_timers_run = timers_run;
6863 timer_delay = timer_check (1);
6864 if (timers_run != old_timers_run && do_display)
6865 /* We must retry, since a timer may have requeued itself
6866 and that could alter the time delay. */
6867 redisplay_preserve_echo_area (14);
6868 else
6869 break;
6871 while (!detect_input_pending ());
6873 /* If there is unread keyboard input, also return. */
6874 if (read_kbd != 0
6875 && requeued_events_pending_p ())
6876 break;
6878 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6880 EMACS_TIME difference;
6881 EMACS_SUB_TIME (difference, timer_delay, timeout);
6882 if (EMACS_TIME_NEG_P (difference))
6884 timeout = timer_delay;
6885 timeout_reduced_for_timers = 1;
6890 /* Cause C-g and alarm signals to take immediate action,
6891 and cause input available signals to zero out timeout. */
6892 if (read_kbd < 0)
6893 set_waiting_for_input (&timeout);
6895 /* Wait till there is something to do. */
6897 if (! read_kbd && NILP (wait_for_cell))
6898 FD_ZERO (&waitchannels);
6899 else
6900 FD_SET (0, &waitchannels);
6902 /* If a frame has been newly mapped and needs updating,
6903 reprocess its display stuff. */
6904 if (frame_garbaged && do_display)
6906 clear_waiting_for_input ();
6907 redisplay_preserve_echo_area (15);
6908 if (read_kbd < 0)
6909 set_waiting_for_input (&timeout);
6912 if (read_kbd && detect_input_pending ())
6914 nfds = 0;
6915 FD_ZERO (&waitchannels);
6917 else
6918 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6919 &timeout);
6921 xerrno = errno;
6923 /* Make C-g and alarm signals set flags again */
6924 clear_waiting_for_input ();
6926 /* If we woke up due to SIGWINCH, actually change size now. */
6927 do_pending_window_change (0);
6929 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6930 /* We waited the full specified time, so return now. */
6931 break;
6933 if (nfds == -1)
6935 /* If the system call was interrupted, then go around the
6936 loop again. */
6937 if (xerrno == EINTR)
6938 FD_ZERO (&waitchannels);
6939 else
6940 error ("select error: %s", emacs_strerror (xerrno));
6943 /* Check for keyboard input */
6945 if (read_kbd
6946 && detect_input_pending_run_timers (do_display))
6948 swallow_events (do_display);
6949 if (detect_input_pending_run_timers (do_display))
6950 break;
6953 /* If there is unread keyboard input, also return. */
6954 if (read_kbd
6955 && requeued_events_pending_p ())
6956 break;
6958 /* If wait_for_cell. check for keyboard input
6959 but don't run any timers.
6960 ??? (It seems wrong to me to check for keyboard
6961 input at all when wait_for_cell, but the code
6962 has been this way since July 1994.
6963 Try changing this after version 19.31.) */
6964 if (! NILP (wait_for_cell)
6965 && detect_input_pending ())
6967 swallow_events (do_display);
6968 if (detect_input_pending ())
6969 break;
6972 /* Exit now if the cell we're waiting for became non-nil. */
6973 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6974 break;
6977 start_polling ();
6979 return 0;
6982 #endif /* not subprocesses */
6984 /* The following functions are needed even if async subprocesses are
6985 not supported. Some of them are no-op stubs in that case. */
6987 /* Add DESC to the set of keyboard input descriptors. */
6989 void
6990 add_keyboard_wait_descriptor (int desc)
6992 #ifdef subprocesses
6993 FD_SET (desc, &input_wait_mask);
6994 FD_SET (desc, &non_process_wait_mask);
6995 if (desc > max_keyboard_desc)
6996 max_keyboard_desc = desc;
6997 #endif
7000 /* From now on, do not expect DESC to give keyboard input. */
7002 void
7003 delete_keyboard_wait_descriptor (int desc)
7005 #ifdef subprocesses
7006 int fd;
7007 int lim = max_keyboard_desc;
7009 FD_CLR (desc, &input_wait_mask);
7010 FD_CLR (desc, &non_process_wait_mask);
7012 if (desc == max_keyboard_desc)
7013 for (fd = 0; fd < lim; fd++)
7014 if (FD_ISSET (fd, &input_wait_mask)
7015 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7016 && !FD_ISSET (fd, &gpm_wait_mask))
7017 max_keyboard_desc = fd;
7018 #endif /* subprocesses */
7021 /* Setup coding systems of PROCESS. */
7023 void
7024 setup_process_coding_systems (Lisp_Object process)
7026 #ifdef subprocesses
7027 struct Lisp_Process *p = XPROCESS (process);
7028 int inch = p->infd;
7029 int outch = p->outfd;
7030 Lisp_Object coding_system;
7032 if (inch < 0 || outch < 0)
7033 return;
7035 if (!proc_decode_coding_system[inch])
7036 proc_decode_coding_system[inch]
7037 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7038 coding_system = p->decode_coding_system;
7039 if (! NILP (p->filter))
7041 else if (BUFFERP (p->buffer))
7043 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7044 coding_system = raw_text_coding_system (coding_system);
7046 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7048 if (!proc_encode_coding_system[outch])
7049 proc_encode_coding_system[outch]
7050 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7051 setup_coding_system (p->encode_coding_system,
7052 proc_encode_coding_system[outch]);
7053 #endif
7056 /* Close all descriptors currently in use for communication
7057 with subprocess. This is used in a newly-forked subprocess
7058 to get rid of irrelevant descriptors. */
7060 void
7061 close_process_descs (void)
7063 #ifndef DOS_NT
7064 int i;
7065 for (i = 0; i < MAXDESC; i++)
7067 Lisp_Object process;
7068 process = chan_process[i];
7069 if (!NILP (process))
7071 int in = XPROCESS (process)->infd;
7072 int out = XPROCESS (process)->outfd;
7073 if (in >= 0)
7074 emacs_close (in);
7075 if (out >= 0 && in != out)
7076 emacs_close (out);
7079 #endif
7082 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7083 doc: /* Return the (or a) process associated with BUFFER.
7084 BUFFER may be a buffer or the name of one. */)
7085 (register Lisp_Object buffer)
7087 #ifdef subprocesses
7088 register Lisp_Object buf, tail, proc;
7090 if (NILP (buffer)) return Qnil;
7091 buf = Fget_buffer (buffer);
7092 if (NILP (buf)) return Qnil;
7094 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7096 proc = Fcdr (XCAR (tail));
7097 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7098 return proc;
7100 #endif /* subprocesses */
7101 return Qnil;
7104 DEFUN ("process-inherit-coding-system-flag",
7105 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7106 1, 1, 0,
7107 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7108 If this flag is t, `buffer-file-coding-system' of the buffer
7109 associated with PROCESS will inherit the coding system used to decode
7110 the process output. */)
7111 (register Lisp_Object process)
7113 #ifdef subprocesses
7114 CHECK_PROCESS (process);
7115 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7116 #else
7117 /* Ignore the argument and return the value of
7118 inherit-process-coding-system. */
7119 return inherit_process_coding_system ? Qt : Qnil;
7120 #endif
7123 /* Kill all processes associated with `buffer'.
7124 If `buffer' is nil, kill all processes */
7126 void
7127 kill_buffer_processes (Lisp_Object buffer)
7129 #ifdef subprocesses
7130 Lisp_Object tail, proc;
7132 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7134 proc = XCDR (XCAR (tail));
7135 if (PROCESSP (proc)
7136 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7138 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7139 Fdelete_process (proc);
7140 else if (XPROCESS (proc)->infd >= 0)
7141 process_send_signal (proc, SIGHUP, Qnil, 1);
7144 #else /* subprocesses */
7145 /* Since we have no subprocesses, this does nothing. */
7146 #endif /* subprocesses */
7149 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7150 0, 0, 0,
7151 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7152 This is intended for use by asynchronous process output filters and sentinels. */)
7153 (void)
7155 #ifdef subprocesses
7156 return (waiting_for_user_input_p ? Qt : Qnil);
7157 #else
7158 return Qnil;
7159 #endif
7162 /* Stop reading input from keyboard sources. */
7164 void
7165 hold_keyboard_input (void)
7167 kbd_is_on_hold = 1;
7170 /* Resume reading input from keyboard sources. */
7172 void
7173 unhold_keyboard_input (void)
7175 kbd_is_on_hold = 0;
7178 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7181 kbd_on_hold_p (void)
7183 return kbd_is_on_hold;
7187 /* Enumeration of and access to system processes a-la ps(1). */
7189 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7190 0, 0, 0,
7191 doc: /* Return a list of numerical process IDs of all running processes.
7192 If this functionality is unsupported, return nil.
7194 See `process-attributes' for getting attributes of a process given its ID. */)
7195 (void)
7197 return list_system_processes ();
7200 DEFUN ("process-attributes", Fprocess_attributes,
7201 Sprocess_attributes, 1, 1, 0,
7202 doc: /* Return attributes of the process given by its PID, a number.
7204 Value is an alist where each element is a cons cell of the form
7206 \(KEY . VALUE)
7208 If this functionality is unsupported, the value is nil.
7210 See `list-system-processes' for getting a list of all process IDs.
7212 The KEYs of the attributes that this function may return are listed
7213 below, together with the type of the associated VALUE (in parentheses).
7214 Not all platforms support all of these attributes; unsupported
7215 attributes will not appear in the returned alist.
7216 Unless explicitly indicated otherwise, numbers can have either
7217 integer or floating point values.
7219 euid -- Effective user User ID of the process (number)
7220 user -- User name corresponding to euid (string)
7221 egid -- Effective user Group ID of the process (number)
7222 group -- Group name corresponding to egid (string)
7223 comm -- Command name (executable name only) (string)
7224 state -- Process state code, such as "S", "R", or "T" (string)
7225 ppid -- Parent process ID (number)
7226 pgrp -- Process group ID (number)
7227 sess -- Session ID, i.e. process ID of session leader (number)
7228 ttname -- Controlling tty name (string)
7229 tpgid -- ID of foreground process group on the process's tty (number)
7230 minflt -- number of minor page faults (number)
7231 majflt -- number of major page faults (number)
7232 cminflt -- cumulative number of minor page faults (number)
7233 cmajflt -- cumulative number of major page faults (number)
7234 utime -- user time used by the process, in the (HIGH LOW USEC) format
7235 stime -- system time used by the process, in the (HIGH LOW USEC) format
7236 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7237 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7238 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7239 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7240 pri -- priority of the process (number)
7241 nice -- nice value of the process (number)
7242 thcount -- process thread count (number)
7243 start -- time the process started, in the (HIGH LOW USEC) format
7244 vsize -- virtual memory size of the process in KB's (number)
7245 rss -- resident set size of the process in KB's (number)
7246 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7247 pcpu -- percents of CPU time used by the process (floating-point number)
7248 pmem -- percents of total physical memory used by process's resident set
7249 (floating-point number)
7250 args -- command line which invoked the process (string). */)
7251 ( Lisp_Object pid)
7253 return system_process_attributes (pid);
7257 void
7258 init_process (void)
7260 #ifdef subprocesses
7261 register int i;
7263 inhibit_sentinels = 0;
7265 #ifdef SIGCHLD
7266 #ifndef CANNOT_DUMP
7267 if (! noninteractive || initialized)
7268 #endif
7269 signal (SIGCHLD, sigchld_handler);
7270 #endif
7272 FD_ZERO (&input_wait_mask);
7273 FD_ZERO (&non_keyboard_wait_mask);
7274 FD_ZERO (&non_process_wait_mask);
7275 max_process_desc = 0;
7277 #ifdef NON_BLOCKING_CONNECT
7278 FD_ZERO (&connect_wait_mask);
7279 num_pending_connects = 0;
7280 #endif
7282 #ifdef ADAPTIVE_READ_BUFFERING
7283 process_output_delay_count = 0;
7284 process_output_skip = 0;
7285 #endif
7287 /* Don't do this, it caused infinite select loops. The display
7288 method should call add_keyboard_wait_descriptor on stdin if it
7289 needs that. */
7290 #if 0
7291 FD_SET (0, &input_wait_mask);
7292 #endif
7294 Vprocess_alist = Qnil;
7295 #ifdef SIGCHLD
7296 deleted_pid_list = Qnil;
7297 #endif
7298 for (i = 0; i < MAXDESC; i++)
7300 chan_process[i] = Qnil;
7301 proc_buffered_char[i] = -1;
7303 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7304 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7305 #ifdef DATAGRAM_SOCKETS
7306 memset (datagram_address, 0, sizeof datagram_address);
7307 #endif
7310 Lisp_Object subfeatures = Qnil;
7311 const struct socket_options *sopt;
7313 #define ADD_SUBFEATURE(key, val) \
7314 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7316 #ifdef NON_BLOCKING_CONNECT
7317 ADD_SUBFEATURE (QCnowait, Qt);
7318 #endif
7319 #ifdef DATAGRAM_SOCKETS
7320 ADD_SUBFEATURE (QCtype, Qdatagram);
7321 #endif
7322 #ifdef HAVE_SEQPACKET
7323 ADD_SUBFEATURE (QCtype, Qseqpacket);
7324 #endif
7325 #ifdef HAVE_LOCAL_SOCKETS
7326 ADD_SUBFEATURE (QCfamily, Qlocal);
7327 #endif
7328 ADD_SUBFEATURE (QCfamily, Qipv4);
7329 #ifdef AF_INET6
7330 ADD_SUBFEATURE (QCfamily, Qipv6);
7331 #endif
7332 #ifdef HAVE_GETSOCKNAME
7333 ADD_SUBFEATURE (QCservice, Qt);
7334 #endif
7335 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7336 ADD_SUBFEATURE (QCserver, Qt);
7337 #endif
7339 for (sopt = socket_options; sopt->name; sopt++)
7340 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7342 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7345 #if defined (DARWIN_OS)
7346 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7347 processes. As such, we only change the default value. */
7348 if (initialized)
7350 const char *release = get_operating_system_release ();
7351 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7352 && release[1] == '.')) {
7353 Vprocess_connection_type = Qnil;
7356 #endif
7357 #endif /* subprocesses */
7358 kbd_is_on_hold = 0;
7361 void
7362 syms_of_process (void)
7364 #ifdef subprocesses
7366 Qprocessp = intern_c_string ("processp");
7367 staticpro (&Qprocessp);
7368 Qrun = intern_c_string ("run");
7369 staticpro (&Qrun);
7370 Qstop = intern_c_string ("stop");
7371 staticpro (&Qstop);
7372 Qsignal = intern_c_string ("signal");
7373 staticpro (&Qsignal);
7375 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7376 here again.
7378 Qexit = intern_c_string ("exit");
7379 staticpro (&Qexit); */
7381 Qopen = intern_c_string ("open");
7382 staticpro (&Qopen);
7383 Qclosed = intern_c_string ("closed");
7384 staticpro (&Qclosed);
7385 Qconnect = intern_c_string ("connect");
7386 staticpro (&Qconnect);
7387 Qfailed = intern_c_string ("failed");
7388 staticpro (&Qfailed);
7389 Qlisten = intern_c_string ("listen");
7390 staticpro (&Qlisten);
7391 Qlocal = intern_c_string ("local");
7392 staticpro (&Qlocal);
7393 Qipv4 = intern_c_string ("ipv4");
7394 staticpro (&Qipv4);
7395 #ifdef AF_INET6
7396 Qipv6 = intern_c_string ("ipv6");
7397 staticpro (&Qipv6);
7398 #endif
7399 Qdatagram = intern_c_string ("datagram");
7400 staticpro (&Qdatagram);
7401 Qseqpacket = intern_c_string ("seqpacket");
7402 staticpro (&Qseqpacket);
7404 QCport = intern_c_string (":port");
7405 staticpro (&QCport);
7406 QCspeed = intern_c_string (":speed");
7407 staticpro (&QCspeed);
7408 QCprocess = intern_c_string (":process");
7409 staticpro (&QCprocess);
7411 QCbytesize = intern_c_string (":bytesize");
7412 staticpro (&QCbytesize);
7413 QCstopbits = intern_c_string (":stopbits");
7414 staticpro (&QCstopbits);
7415 QCparity = intern_c_string (":parity");
7416 staticpro (&QCparity);
7417 Qodd = intern_c_string ("odd");
7418 staticpro (&Qodd);
7419 Qeven = intern_c_string ("even");
7420 staticpro (&Qeven);
7421 QCflowcontrol = intern_c_string (":flowcontrol");
7422 staticpro (&QCflowcontrol);
7423 Qhw = intern_c_string ("hw");
7424 staticpro (&Qhw);
7425 Qsw = intern_c_string ("sw");
7426 staticpro (&Qsw);
7427 QCsummary = intern_c_string (":summary");
7428 staticpro (&QCsummary);
7430 Qreal = intern_c_string ("real");
7431 staticpro (&Qreal);
7432 Qnetwork = intern_c_string ("network");
7433 staticpro (&Qnetwork);
7434 Qserial = intern_c_string ("serial");
7435 staticpro (&Qserial);
7436 QCbuffer = intern_c_string (":buffer");
7437 staticpro (&QCbuffer);
7438 QChost = intern_c_string (":host");
7439 staticpro (&QChost);
7440 QCservice = intern_c_string (":service");
7441 staticpro (&QCservice);
7442 QClocal = intern_c_string (":local");
7443 staticpro (&QClocal);
7444 QCremote = intern_c_string (":remote");
7445 staticpro (&QCremote);
7446 QCcoding = intern_c_string (":coding");
7447 staticpro (&QCcoding);
7448 QCserver = intern_c_string (":server");
7449 staticpro (&QCserver);
7450 QCnowait = intern_c_string (":nowait");
7451 staticpro (&QCnowait);
7452 QCsentinel = intern_c_string (":sentinel");
7453 staticpro (&QCsentinel);
7454 QClog = intern_c_string (":log");
7455 staticpro (&QClog);
7456 QCnoquery = intern_c_string (":noquery");
7457 staticpro (&QCnoquery);
7458 QCstop = intern_c_string (":stop");
7459 staticpro (&QCstop);
7460 QCoptions = intern_c_string (":options");
7461 staticpro (&QCoptions);
7462 QCplist = intern_c_string (":plist");
7463 staticpro (&QCplist);
7465 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7466 staticpro (&Qlast_nonmenu_event);
7468 staticpro (&Vprocess_alist);
7469 #ifdef SIGCHLD
7470 staticpro (&deleted_pid_list);
7471 #endif
7473 #endif /* subprocesses */
7475 QCname = intern_c_string (":name");
7476 staticpro (&QCname);
7477 QCtype = intern_c_string (":type");
7478 staticpro (&QCtype);
7480 Qeuid = intern_c_string ("euid");
7481 staticpro (&Qeuid);
7482 Qegid = intern_c_string ("egid");
7483 staticpro (&Qegid);
7484 Quser = intern_c_string ("user");
7485 staticpro (&Quser);
7486 Qgroup = intern_c_string ("group");
7487 staticpro (&Qgroup);
7488 Qcomm = intern_c_string ("comm");
7489 staticpro (&Qcomm);
7490 Qstate = intern_c_string ("state");
7491 staticpro (&Qstate);
7492 Qppid = intern_c_string ("ppid");
7493 staticpro (&Qppid);
7494 Qpgrp = intern_c_string ("pgrp");
7495 staticpro (&Qpgrp);
7496 Qsess = intern_c_string ("sess");
7497 staticpro (&Qsess);
7498 Qttname = intern_c_string ("ttname");
7499 staticpro (&Qttname);
7500 Qtpgid = intern_c_string ("tpgid");
7501 staticpro (&Qtpgid);
7502 Qminflt = intern_c_string ("minflt");
7503 staticpro (&Qminflt);
7504 Qmajflt = intern_c_string ("majflt");
7505 staticpro (&Qmajflt);
7506 Qcminflt = intern_c_string ("cminflt");
7507 staticpro (&Qcminflt);
7508 Qcmajflt = intern_c_string ("cmajflt");
7509 staticpro (&Qcmajflt);
7510 Qutime = intern_c_string ("utime");
7511 staticpro (&Qutime);
7512 Qstime = intern_c_string ("stime");
7513 staticpro (&Qstime);
7514 Qtime = intern_c_string ("time");
7515 staticpro (&Qtime);
7516 Qcutime = intern_c_string ("cutime");
7517 staticpro (&Qcutime);
7518 Qcstime = intern_c_string ("cstime");
7519 staticpro (&Qcstime);
7520 Qctime = intern_c_string ("ctime");
7521 staticpro (&Qctime);
7522 Qpri = intern_c_string ("pri");
7523 staticpro (&Qpri);
7524 Qnice = intern_c_string ("nice");
7525 staticpro (&Qnice);
7526 Qthcount = intern_c_string ("thcount");
7527 staticpro (&Qthcount);
7528 Qstart = intern_c_string ("start");
7529 staticpro (&Qstart);
7530 Qvsize = intern_c_string ("vsize");
7531 staticpro (&Qvsize);
7532 Qrss = intern_c_string ("rss");
7533 staticpro (&Qrss);
7534 Qetime = intern_c_string ("etime");
7535 staticpro (&Qetime);
7536 Qpcpu = intern_c_string ("pcpu");
7537 staticpro (&Qpcpu);
7538 Qpmem = intern_c_string ("pmem");
7539 staticpro (&Qpmem);
7540 Qargs = intern_c_string ("args");
7541 staticpro (&Qargs);
7543 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7544 doc: /* *Non-nil means delete processes immediately when they exit.
7545 A value of nil means don't delete them until `list-processes' is run. */);
7547 delete_exited_processes = 1;
7549 #ifdef subprocesses
7550 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7551 doc: /* Control type of device used to communicate with subprocesses.
7552 Values are nil to use a pipe, or t or `pty' to use a pty.
7553 The value has no effect if the system has no ptys or if all ptys are busy:
7554 then a pipe is used in any case.
7555 The value takes effect when `start-process' is called. */);
7556 Vprocess_connection_type = Qt;
7558 #ifdef ADAPTIVE_READ_BUFFERING
7559 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7560 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7561 On some systems, when Emacs reads the output from a subprocess, the output data
7562 is read in very small blocks, potentially resulting in very poor performance.
7563 This behavior can be remedied to some extent by setting this variable to a
7564 non-nil value, as it will automatically delay reading from such processes, to
7565 allow them to produce more output before Emacs tries to read it.
7566 If the value is t, the delay is reset after each write to the process; any other
7567 non-nil value means that the delay is not reset on write.
7568 The variable takes effect when `start-process' is called. */);
7569 Vprocess_adaptive_read_buffering = Qt;
7570 #endif
7572 defsubr (&Sprocessp);
7573 defsubr (&Sget_process);
7574 defsubr (&Sdelete_process);
7575 defsubr (&Sprocess_status);
7576 defsubr (&Sprocess_exit_status);
7577 defsubr (&Sprocess_id);
7578 defsubr (&Sprocess_name);
7579 defsubr (&Sprocess_tty_name);
7580 defsubr (&Sprocess_command);
7581 defsubr (&Sset_process_buffer);
7582 defsubr (&Sprocess_buffer);
7583 defsubr (&Sprocess_mark);
7584 defsubr (&Sset_process_filter);
7585 defsubr (&Sprocess_filter);
7586 defsubr (&Sset_process_sentinel);
7587 defsubr (&Sprocess_sentinel);
7588 defsubr (&Sset_process_window_size);
7589 defsubr (&Sset_process_inherit_coding_system_flag);
7590 defsubr (&Sset_process_query_on_exit_flag);
7591 defsubr (&Sprocess_query_on_exit_flag);
7592 defsubr (&Sprocess_contact);
7593 defsubr (&Sprocess_plist);
7594 defsubr (&Sset_process_plist);
7595 defsubr (&Slist_processes);
7596 defsubr (&Sprocess_list);
7597 defsubr (&Sstart_process);
7598 defsubr (&Sserial_process_configure);
7599 defsubr (&Smake_serial_process);
7600 defsubr (&Sset_network_process_option);
7601 defsubr (&Smake_network_process);
7602 defsubr (&Sformat_network_address);
7603 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7604 #ifdef SIOCGIFCONF
7605 defsubr (&Snetwork_interface_list);
7606 #endif
7607 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7608 defsubr (&Snetwork_interface_info);
7609 #endif
7610 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7611 #ifdef DATAGRAM_SOCKETS
7612 defsubr (&Sprocess_datagram_address);
7613 defsubr (&Sset_process_datagram_address);
7614 #endif
7615 defsubr (&Saccept_process_output);
7616 defsubr (&Sprocess_send_region);
7617 defsubr (&Sprocess_send_string);
7618 defsubr (&Sinterrupt_process);
7619 defsubr (&Skill_process);
7620 defsubr (&Squit_process);
7621 defsubr (&Sstop_process);
7622 defsubr (&Scontinue_process);
7623 defsubr (&Sprocess_running_child_p);
7624 defsubr (&Sprocess_send_eof);
7625 defsubr (&Ssignal_process);
7626 defsubr (&Swaiting_for_user_input_p);
7627 defsubr (&Sprocess_type);
7628 defsubr (&Sset_process_coding_system);
7629 defsubr (&Sprocess_coding_system);
7630 defsubr (&Sset_process_filter_multibyte);
7631 defsubr (&Sprocess_filter_multibyte_p);
7633 #endif /* subprocesses */
7635 defsubr (&Sget_buffer_process);
7636 defsubr (&Sprocess_inherit_coding_system_flag);
7637 defsubr (&Slist_system_processes);
7638 defsubr (&Sprocess_attributes);
7641 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7642 (do not change this comment) */