* progmodes/prolog.el (prolog-mode): Use define-derived-mode.
[emacs.git] / src / process.c
bloba09ac297a2d935303b338a7a2e15b204d6e41a48
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>
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
33 #ifdef subprocesses
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #include <setjmp.h>
42 #ifdef HAVE_INTTYPES_H
43 #include <inttypes.h>
44 #endif
45 #ifdef STDC_HEADERS
46 #include <stdlib.h>
47 #endif
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52 #include <fcntl.h>
54 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
60 /* Are local (unix) sockets supported? */
61 #if defined (HAVE_SYS_UN_H)
62 #if !defined (AF_LOCAL) && defined (AF_UNIX)
63 #define AF_LOCAL AF_UNIX
64 #endif
65 #ifdef AF_LOCAL
66 #define HAVE_LOCAL_SOCKETS
67 #include <sys/un.h>
68 #endif
69 #endif
70 #endif /* HAVE_SOCKETS */
72 #if defined(HAVE_SYS_IOCTL_H)
73 #include <sys/ioctl.h>
74 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
75 #include <fcntl.h>
76 #endif /* HAVE_PTYS and no O_NDELAY */
77 #endif /* HAVE_SYS_IOCTL_H */
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
83 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
84 #ifdef HAVE_SOCKETS
85 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
86 /* sys/ioctl.h may have been included already */
87 #ifndef SIOCGIFADDR
88 #include <sys/ioctl.h>
89 #endif
90 #include <net/if.h>
91 #endif
92 #endif
94 #ifdef HAVE_SYS_WAIT
95 #include <sys/wait.h>
96 #endif
98 #ifdef HAVE_RES_INIT
99 #include <netinet/in.h>
100 #include <arpa/nameser.h>
101 #include <resolv.h>
102 #endif
104 #include "lisp.h"
105 #include "systime.h"
106 #include "systty.h"
108 #include "window.h"
109 #include "buffer.h"
110 #include "character.h"
111 #include "coding.h"
112 #include "process.h"
113 #include "frame.h"
114 #include "termhooks.h"
115 #include "termopts.h"
116 #include "commands.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "dispextern.h"
120 #include "composite.h"
121 #include "atimer.h"
123 #if defined (USE_GTK) || defined (HAVE_GCONF)
124 #include "xgselect.h"
125 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
127 Lisp_Object Qprocessp;
128 Lisp_Object Qrun, Qstop, Qsignal;
129 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
130 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
131 Lisp_Object Qreal, Qnetwork, Qserial;
132 #ifdef AF_INET6
133 Lisp_Object Qipv6;
134 #endif
135 Lisp_Object QCport, QCspeed, QCprocess;
136 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
137 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
138 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
139 Lisp_Object QClocal, QCremote, QCcoding;
140 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
141 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
142 Lisp_Object Qlast_nonmenu_event;
143 /* QCfamily is declared and initialized in xfaces.c,
144 QCfilter in keyboard.c. */
145 extern Lisp_Object QCfamily, QCfilter;
147 /* Qexit is declared and initialized in eval.c. */
149 /* QCfamily is defined in xfaces.c. */
150 extern Lisp_Object QCfamily;
151 /* QCfilter is defined in keyboard.c. */
152 extern Lisp_Object QCfilter;
154 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
155 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
156 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
157 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
159 #ifdef HAVE_SOCKETS
160 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
161 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
162 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
163 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
164 #else
165 #define NETCONN_P(p) 0
166 #define NETCONN1_P(p) 0
167 #define SERIALCONN_P(p) 0
168 #define SERIALCONN1_P(p) 0
169 #endif /* HAVE_SOCKETS */
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
174 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
175 testing SIGCHLD. */
177 #if !defined (SIGCHLD) && defined (SIGCLD)
178 #define SIGCHLD SIGCLD
179 #endif /* SIGCLD */
181 #include "syssignal.h"
183 #include "syswait.h"
185 extern char *get_operating_system_release ();
187 /* Serial processes require termios or Windows. */
188 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
189 #define HAVE_SERIAL
190 #endif
192 #ifdef HAVE_SERIAL
193 /* From sysdep.c or w32.c */
194 extern int serial_open (char *port);
195 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
196 #endif
198 #ifndef HAVE_H_ERRNO
199 extern int h_errno;
200 #endif
202 /* t means use pty, nil means use a pipe,
203 maybe other values to come. */
204 static Lisp_Object Vprocess_connection_type;
206 /* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
208 /* Number of events of change of status of a process. */
209 int process_tick;
210 /* Number of events for which the user or sentinel has been notified. */
211 int update_tick;
213 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
215 #ifdef BROKEN_NON_BLOCKING_CONNECT
216 #undef NON_BLOCKING_CONNECT
217 #else
218 #ifndef NON_BLOCKING_CONNECT
219 #ifdef HAVE_SOCKETS
220 #ifdef HAVE_SELECT
221 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
222 #if defined (O_NONBLOCK) || defined (O_NDELAY)
223 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
224 #define NON_BLOCKING_CONNECT
225 #endif /* EWOULDBLOCK || EINPROGRESS */
226 #endif /* O_NONBLOCK || O_NDELAY */
227 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
228 #endif /* HAVE_SELECT */
229 #endif /* HAVE_SOCKETS */
230 #endif /* NON_BLOCKING_CONNECT */
231 #endif /* BROKEN_NON_BLOCKING_CONNECT */
233 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
234 this system. We need to read full packets, so we need a
235 "non-destructive" select. So we require either native select,
236 or emulation of select using FIONREAD. */
238 #ifdef BROKEN_DATAGRAM_SOCKETS
239 #undef DATAGRAM_SOCKETS
240 #else
241 #ifndef DATAGRAM_SOCKETS
242 #ifdef HAVE_SOCKETS
243 #if defined (HAVE_SELECT) || defined (FIONREAD)
244 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
245 #define DATAGRAM_SOCKETS
246 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
247 #endif /* HAVE_SELECT || FIONREAD */
248 #endif /* HAVE_SOCKETS */
249 #endif /* DATAGRAM_SOCKETS */
250 #endif /* BROKEN_DATAGRAM_SOCKETS */
252 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
253 # define HAVE_SEQPACKET
254 #endif
256 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
257 #ifdef EMACS_HAS_USECS
258 #define ADAPTIVE_READ_BUFFERING
259 #endif
260 #endif
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT 10000
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count;
272 /* Non-zero if any process has non-nil read_output_skip. */
274 static int process_output_skip;
276 /* Non-nil means to delay reading process output to improve buffering.
277 A value of t means that delay is reset after each send, any other
278 non-nil value does not reset the delay. A value of nil disables
279 adaptive read buffering completely. */
280 static Lisp_Object Vprocess_adaptive_read_buffering;
281 #else
282 #define process_output_delay_count 0
283 #endif
286 #include "sysselect.h"
288 static int keyboard_bit_set P_ ((SELECT_TYPE *));
289 static void deactivate_process P_ ((Lisp_Object));
290 static void status_notify P_ ((struct Lisp_Process *));
291 static int read_process_output P_ ((Lisp_Object, int));
292 static void create_pty P_ ((Lisp_Object));
294 /* If we support a window system, turn on the code to poll periodically
295 to detect C-g. It isn't actually used when doing interrupt input. */
296 #ifdef HAVE_WINDOW_SYSTEM
297 #define POLL_FOR_INPUT
298 #endif
300 static Lisp_Object get_process ();
301 static void exec_sentinel ();
303 extern int timers_run;
305 /* Mask of bits indicating the descriptors that we wait for input on. */
307 static SELECT_TYPE input_wait_mask;
309 /* Mask that excludes keyboard input descriptor(s). */
311 static SELECT_TYPE non_keyboard_wait_mask;
313 /* Mask that excludes process input descriptor(s). */
315 static SELECT_TYPE non_process_wait_mask;
317 /* Mask for the gpm mouse input descriptor. */
319 static SELECT_TYPE gpm_wait_mask;
321 #ifdef NON_BLOCKING_CONNECT
322 /* Mask of bits indicating the descriptors that we wait for connect to
323 complete on. Once they complete, they are removed from this mask
324 and added to the input_wait_mask and non_keyboard_wait_mask. */
326 static SELECT_TYPE connect_wait_mask;
328 /* Number of bits set in connect_wait_mask. */
329 static int num_pending_connects;
331 #define IF_NON_BLOCKING_CONNECT(s) s
332 #else
333 #define IF_NON_BLOCKING_CONNECT(s)
334 #endif
336 /* The largest descriptor currently in use for a process object. */
337 static int max_process_desc;
339 /* The largest descriptor currently in use for keyboard input. */
340 static int max_keyboard_desc;
342 /* The largest descriptor currently in use for gpm mouse input. */
343 static int max_gpm_desc;
345 /* Nonzero means delete a process right away if it exits. */
346 static int delete_exited_processes;
348 /* Indexed by descriptor, gives the process (if any) for that descriptor */
349 Lisp_Object chan_process[MAXDESC];
351 /* Alist of elements (NAME . PROCESS) */
352 Lisp_Object Vprocess_alist;
354 /* Buffered-ahead input char from process, indexed by channel.
355 -1 means empty (no char is buffered).
356 Used on sys V where the only way to tell if there is any
357 output from the process is to read at least one char.
358 Always -1 on systems that support FIONREAD. */
360 /* Don't make static; need to access externally. */
361 int proc_buffered_char[MAXDESC];
363 /* Table of `struct coding-system' for each process. */
364 static struct coding_system *proc_decode_coding_system[MAXDESC];
365 static struct coding_system *proc_encode_coding_system[MAXDESC];
367 #ifdef DATAGRAM_SOCKETS
368 /* Table of `partner address' for datagram sockets. */
369 struct sockaddr_and_len {
370 struct sockaddr *sa;
371 int len;
372 } datagram_address[MAXDESC];
373 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
374 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
375 #else
376 #define DATAGRAM_CHAN_P(chan) (0)
377 #define DATAGRAM_CONN_P(proc) (0)
378 #endif
380 /* Maximum number of bytes to send to a pty without an eof. */
381 static int pty_max_bytes;
383 /* Nonzero means don't run process sentinels. This is used
384 when exiting. */
385 int inhibit_sentinels;
387 #ifdef HAVE_PTYS
388 #ifdef HAVE_PTY_H
389 #include <pty.h>
390 #endif
391 /* The file name of the pty opened by allocate_pty. */
393 static char pty_name[24];
394 #endif
396 /* Compute the Lisp form of the process status, p->status, from
397 the numeric status that was returned by `wait'. */
399 static Lisp_Object status_convert (int);
401 static void
402 update_status (p)
403 struct Lisp_Process *p;
405 eassert (p->raw_status_new);
406 p->status = status_convert (p->raw_status);
407 p->raw_status_new = 0;
410 /* Convert a process status word in Unix format to
411 the list that we use internally. */
413 static Lisp_Object
414 status_convert (int w)
416 if (WIFSTOPPED (w))
417 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
418 else if (WIFEXITED (w))
419 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
420 WCOREDUMP (w) ? Qt : Qnil));
421 else if (WIFSIGNALED (w))
422 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
423 WCOREDUMP (w) ? Qt : Qnil));
424 else
425 return Qrun;
428 /* Given a status-list, extract the three pieces of information
429 and store them individually through the three pointers. */
431 static void
432 decode_status (l, symbol, code, coredump)
433 Lisp_Object l;
434 Lisp_Object *symbol;
435 int *code;
436 int *coredump;
438 Lisp_Object tem;
440 if (SYMBOLP (l))
442 *symbol = l;
443 *code = 0;
444 *coredump = 0;
446 else
448 *symbol = XCAR (l);
449 tem = XCDR (l);
450 *code = XFASTINT (XCAR (tem));
451 tem = XCDR (tem);
452 *coredump = !NILP (tem);
456 /* Return a string describing a process status list. */
458 static Lisp_Object
459 status_message (p)
460 struct Lisp_Process *p;
462 Lisp_Object status = p->status;
463 Lisp_Object symbol;
464 int code, coredump;
465 Lisp_Object string, string2;
467 decode_status (status, &symbol, &code, &coredump);
469 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
471 char *signame;
472 synchronize_system_messages_locale ();
473 signame = strsignal (code);
474 if (signame == 0)
475 string = build_string ("unknown");
476 else
478 int c1, c2;
480 string = make_unibyte_string (signame, strlen (signame));
481 if (! NILP (Vlocale_coding_system))
482 string = (code_convert_string_norecord
483 (string, Vlocale_coding_system, 0));
484 c1 = STRING_CHAR ((char *) SDATA (string));
485 c2 = DOWNCASE (c1);
486 if (c1 != c2)
487 Faset (string, make_number (0), make_number (c2));
489 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
490 return concat2 (string, string2);
492 else if (EQ (symbol, Qexit))
494 if (NETCONN1_P (p))
495 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
496 if (code == 0)
497 return build_string ("finished\n");
498 string = Fnumber_to_string (make_number (code));
499 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
500 return concat3 (build_string ("exited abnormally with code "),
501 string, string2);
503 else if (EQ (symbol, Qfailed))
505 string = Fnumber_to_string (make_number (code));
506 string2 = build_string ("\n");
507 return concat3 (build_string ("failed with code "),
508 string, string2);
510 else
511 return Fcopy_sequence (Fsymbol_name (symbol));
514 #ifdef HAVE_PTYS
516 /* Open an available pty, returning a file descriptor.
517 Return -1 on failure.
518 The file name of the terminal corresponding to the pty
519 is left in the variable pty_name. */
521 static int
522 allocate_pty ()
524 register int c, i;
525 int fd;
527 #ifdef PTY_ITERATION
528 PTY_ITERATION
529 #else
530 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
531 for (i = 0; i < 16; i++)
532 #endif
534 struct stat stb; /* Used in some PTY_OPEN. */
535 #ifdef PTY_NAME_SPRINTF
536 PTY_NAME_SPRINTF
537 #else
538 sprintf (pty_name, "/dev/pty%c%x", c, i);
539 #endif /* no PTY_NAME_SPRINTF */
541 #ifdef PTY_OPEN
542 PTY_OPEN;
543 #else /* no PTY_OPEN */
545 { /* Some systems name their pseudoterminals so that there are gaps in
546 the usual sequence - for example, on HP9000/S700 systems, there
547 are no pseudoterminals with names ending in 'f'. So we wait for
548 three failures in a row before deciding that we've reached the
549 end of the ptys. */
550 int failed_count = 0;
552 if (stat (pty_name, &stb) < 0)
554 failed_count++;
555 if (failed_count >= 3)
556 return -1;
558 else
559 failed_count = 0;
561 # ifdef O_NONBLOCK
562 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
563 # else
564 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
565 # endif
567 #endif /* no PTY_OPEN */
569 if (fd >= 0)
571 /* check to make certain that both sides are available
572 this avoids a nasty yet stupid bug in rlogins */
573 #ifdef PTY_TTY_NAME_SPRINTF
574 PTY_TTY_NAME_SPRINTF
575 #else
576 sprintf (pty_name, "/dev/tty%c%x", c, i);
577 #endif /* no PTY_TTY_NAME_SPRINTF */
578 if (access (pty_name, 6) != 0)
580 emacs_close (fd);
581 # ifndef __sgi
582 continue;
583 # else
584 return -1;
585 # endif /* __sgi */
587 setup_pty (fd);
588 return fd;
591 return -1;
593 #endif /* HAVE_PTYS */
595 static Lisp_Object
596 make_process (name)
597 Lisp_Object name;
599 register Lisp_Object val, tem, name1;
600 register struct Lisp_Process *p;
601 char suffix[10];
602 register int i;
604 p = allocate_process ();
606 p->infd = -1;
607 p->outfd = -1;
608 p->tick = 0;
609 p->update_tick = 0;
610 p->pid = 0;
611 p->pty_flag = 0;
612 p->raw_status_new = 0;
613 p->status = Qrun;
614 p->mark = Fmake_marker ();
615 p->kill_without_query = 0;
617 #ifdef ADAPTIVE_READ_BUFFERING
618 p->adaptive_read_buffering = 0;
619 p->read_output_delay = 0;
620 p->read_output_skip = 0;
621 #endif
623 /* If name is already in use, modify it until it is unused. */
625 name1 = name;
626 for (i = 1; ; i++)
628 tem = Fget_process (name1);
629 if (NILP (tem)) break;
630 sprintf (suffix, "<%d>", i);
631 name1 = concat2 (name, build_string (suffix));
633 name = name1;
634 p->name = name;
635 XSETPROCESS (val, p);
636 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
637 return val;
640 static void
641 remove_process (proc)
642 register Lisp_Object proc;
644 register Lisp_Object pair;
646 pair = Frassq (proc, Vprocess_alist);
647 Vprocess_alist = Fdelq (pair, Vprocess_alist);
649 deactivate_process (proc);
652 /* Setup coding systems of PROCESS. */
654 void
655 setup_process_coding_systems (process)
656 Lisp_Object process;
658 struct Lisp_Process *p = XPROCESS (process);
659 int inch = p->infd;
660 int outch = p->outfd;
661 Lisp_Object coding_system;
663 if (inch < 0 || outch < 0)
664 return;
666 if (!proc_decode_coding_system[inch])
667 proc_decode_coding_system[inch]
668 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
669 coding_system = p->decode_coding_system;
670 if (! NILP (p->filter))
672 else if (BUFFERP (p->buffer))
674 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
675 coding_system = raw_text_coding_system (coding_system);
677 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
679 if (!proc_encode_coding_system[outch])
680 proc_encode_coding_system[outch]
681 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
682 setup_coding_system (p->encode_coding_system,
683 proc_encode_coding_system[outch]);
686 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
687 doc: /* Return t if OBJECT is a process. */)
688 (object)
689 Lisp_Object object;
691 return PROCESSP (object) ? Qt : Qnil;
694 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
695 doc: /* Return the process named NAME, or nil if there is none. */)
696 (name)
697 register Lisp_Object name;
699 if (PROCESSP (name))
700 return name;
701 CHECK_STRING (name);
702 return Fcdr (Fassoc (name, Vprocess_alist));
705 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
706 doc: /* Return the (or a) process associated with BUFFER.
707 BUFFER may be a buffer or the name of one. */)
708 (buffer)
709 register Lisp_Object buffer;
711 register Lisp_Object buf, tail, proc;
713 if (NILP (buffer)) return Qnil;
714 buf = Fget_buffer (buffer);
715 if (NILP (buf)) return Qnil;
717 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
719 proc = Fcdr (XCAR (tail));
720 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
721 return proc;
723 return Qnil;
726 /* This is how commands for the user decode process arguments. It
727 accepts a process, a process name, a buffer, a buffer name, or nil.
728 Buffers denote the first process in the buffer, and nil denotes the
729 current buffer. */
731 static Lisp_Object
732 get_process (name)
733 register Lisp_Object name;
735 register Lisp_Object proc, obj;
736 if (STRINGP (name))
738 obj = Fget_process (name);
739 if (NILP (obj))
740 obj = Fget_buffer (name);
741 if (NILP (obj))
742 error ("Process %s does not exist", SDATA (name));
744 else if (NILP (name))
745 obj = Fcurrent_buffer ();
746 else
747 obj = name;
749 /* Now obj should be either a buffer object or a process object.
751 if (BUFFERP (obj))
753 proc = Fget_buffer_process (obj);
754 if (NILP (proc))
755 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
757 else
759 CHECK_PROCESS (obj);
760 proc = obj;
762 return proc;
766 #ifdef SIGCHLD
767 /* Fdelete_process promises to immediately forget about the process, but in
768 reality, Emacs needs to remember those processes until they have been
769 treated by sigchld_handler; otherwise this handler would consider the
770 process as being synchronous and say that the synchronous process is
771 dead. */
772 static Lisp_Object deleted_pid_list;
773 #endif
775 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
776 doc: /* Delete PROCESS: kill it and forget about it immediately.
777 PROCESS may be a process, a buffer, the name of a process or buffer, or
778 nil, indicating the current buffer's process. */)
779 (process)
780 register Lisp_Object process;
782 register struct Lisp_Process *p;
784 process = get_process (process);
785 p = XPROCESS (process);
787 p->raw_status_new = 0;
788 if (NETCONN1_P (p) || SERIALCONN1_P (p))
790 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
791 p->tick = ++process_tick;
792 status_notify (p);
793 redisplay_preserve_echo_area (13);
795 else if (p->infd >= 0)
797 #ifdef SIGCHLD
798 Lisp_Object symbol;
799 /* Assignment to EMACS_INT stops GCC whining about limited range
800 of data type. */
801 EMACS_INT pid = p->pid;
803 /* No problem storing the pid here, as it is still in Vprocess_alist. */
804 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
805 /* GC treated elements set to nil. */
806 Fdelq (Qnil, deleted_pid_list));
807 /* If the process has already signaled, remove it from the list. */
808 if (p->raw_status_new)
809 update_status (p);
810 symbol = p->status;
811 if (CONSP (p->status))
812 symbol = XCAR (p->status);
813 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
814 deleted_pid_list
815 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
816 else
817 #endif
819 Fkill_process (process, Qnil);
820 /* Do this now, since remove_process will make sigchld_handler do nothing. */
821 p->status
822 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
823 p->tick = ++process_tick;
824 status_notify (p);
825 redisplay_preserve_echo_area (13);
828 remove_process (process);
829 return Qnil;
832 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
833 doc: /* Return the status of PROCESS.
834 The returned value is one of the following symbols:
835 run -- for a process that is running.
836 stop -- for a process stopped but continuable.
837 exit -- for a process that has exited.
838 signal -- for a process that has got a fatal signal.
839 open -- for a network stream connection that is open.
840 listen -- for a network stream server that is listening.
841 closed -- for a network stream connection that is closed.
842 connect -- when waiting for a non-blocking connection to complete.
843 failed -- when a non-blocking connection has failed.
844 nil -- if arg is a process name and no such process exists.
845 PROCESS may be a process, a buffer, the name of a process, or
846 nil, indicating the current buffer's process. */)
847 (process)
848 register Lisp_Object process;
850 register struct Lisp_Process *p;
851 register Lisp_Object status;
853 if (STRINGP (process))
854 process = Fget_process (process);
855 else
856 process = get_process (process);
858 if (NILP (process))
859 return process;
861 p = XPROCESS (process);
862 if (p->raw_status_new)
863 update_status (p);
864 status = p->status;
865 if (CONSP (status))
866 status = XCAR (status);
867 if (NETCONN1_P (p) || SERIALCONN1_P (p))
869 if (EQ (status, Qexit))
870 status = Qclosed;
871 else if (EQ (p->command, Qt))
872 status = Qstop;
873 else if (EQ (status, Qrun))
874 status = Qopen;
876 return status;
879 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
880 1, 1, 0,
881 doc: /* Return the exit status of PROCESS or the signal number that killed it.
882 If PROCESS has not yet exited or died, return 0. */)
883 (process)
884 register Lisp_Object process;
886 CHECK_PROCESS (process);
887 if (XPROCESS (process)->raw_status_new)
888 update_status (XPROCESS (process));
889 if (CONSP (XPROCESS (process)->status))
890 return XCAR (XCDR (XPROCESS (process)->status));
891 return make_number (0);
894 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
895 doc: /* Return the process id of PROCESS.
896 This is the pid of the external process which PROCESS uses or talks to.
897 For a network connection, this value is nil. */)
898 (process)
899 register Lisp_Object process;
901 /* Assignment to EMACS_INT stops GCC whining about limited range of
902 data type. */
903 EMACS_INT pid;
905 CHECK_PROCESS (process);
906 pid = XPROCESS (process)->pid;
907 return (pid ? make_fixnum_or_float (pid) : Qnil);
910 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
911 doc: /* Return the name of PROCESS, as a string.
912 This is the name of the program invoked in PROCESS,
913 possibly modified to make it unique among process names. */)
914 (process)
915 register Lisp_Object process;
917 CHECK_PROCESS (process);
918 return XPROCESS (process)->name;
921 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
922 doc: /* Return the command that was executed to start PROCESS.
923 This is a list of strings, the first string being the program executed
924 and the rest of the strings being the arguments given to it.
925 For a network or serial process, this is nil (process is running) or t
926 \(process is stopped). */)
927 (process)
928 register Lisp_Object process;
930 CHECK_PROCESS (process);
931 return XPROCESS (process)->command;
934 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
935 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
936 This is the terminal that the process itself reads and writes on,
937 not the name of the pty that Emacs uses to talk with that terminal. */)
938 (process)
939 register Lisp_Object process;
941 CHECK_PROCESS (process);
942 return XPROCESS (process)->tty_name;
945 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
946 2, 2, 0,
947 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
948 (process, buffer)
949 register Lisp_Object process, buffer;
951 struct Lisp_Process *p;
953 CHECK_PROCESS (process);
954 if (!NILP (buffer))
955 CHECK_BUFFER (buffer);
956 p = XPROCESS (process);
957 p->buffer = buffer;
958 if (NETCONN1_P (p) || SERIALCONN1_P (p))
959 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
960 setup_process_coding_systems (process);
961 return buffer;
964 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
965 1, 1, 0,
966 doc: /* Return the buffer PROCESS is associated with.
967 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
968 (process)
969 register Lisp_Object process;
971 CHECK_PROCESS (process);
972 return XPROCESS (process)->buffer;
975 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
976 1, 1, 0,
977 doc: /* Return the marker for the end of the last output from PROCESS. */)
978 (process)
979 register Lisp_Object process;
981 CHECK_PROCESS (process);
982 return XPROCESS (process)->mark;
985 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
986 2, 2, 0,
987 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
988 A value of t means stop accepting output from the process.
990 When a process has a filter, its buffer is not used for output.
991 Instead, each time it does output, the entire string of output is
992 passed to the filter.
994 The filter gets two arguments: the process and the string of output.
995 The string argument is normally a multibyte string, except:
996 - if the process' input coding system is no-conversion or raw-text,
997 it is a unibyte string (the non-converted input), or else
998 - if `default-enable-multibyte-characters' is nil, it is a unibyte
999 string (the result of converting the decoded input multibyte
1000 string to unibyte with `string-make-unibyte'). */)
1001 (process, filter)
1002 register Lisp_Object process, filter;
1004 struct Lisp_Process *p;
1006 CHECK_PROCESS (process);
1007 p = XPROCESS (process);
1009 /* Don't signal an error if the process' input file descriptor
1010 is closed. This could make debugging Lisp more difficult,
1011 for example when doing something like
1013 (setq process (start-process ...))
1014 (debug)
1015 (set-process-filter process ...) */
1017 if (p->infd >= 0)
1019 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1021 FD_CLR (p->infd, &input_wait_mask);
1022 FD_CLR (p->infd, &non_keyboard_wait_mask);
1024 else if (EQ (p->filter, Qt)
1025 /* Network or serial process not stopped: */
1026 && !EQ (p->command, Qt))
1028 FD_SET (p->infd, &input_wait_mask);
1029 FD_SET (p->infd, &non_keyboard_wait_mask);
1033 p->filter = filter;
1034 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1035 p->childp = Fplist_put (p->childp, QCfilter, filter);
1036 setup_process_coding_systems (process);
1037 return filter;
1040 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1041 1, 1, 0,
1042 doc: /* Returns the filter function of PROCESS; nil if none.
1043 See `set-process-filter' for more info on filter functions. */)
1044 (process)
1045 register Lisp_Object process;
1047 CHECK_PROCESS (process);
1048 return XPROCESS (process)->filter;
1051 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1052 2, 2, 0,
1053 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1054 The sentinel is called as a function when the process changes state.
1055 It gets two arguments: the process, and a string describing the change. */)
1056 (process, sentinel)
1057 register Lisp_Object process, sentinel;
1059 struct Lisp_Process *p;
1061 CHECK_PROCESS (process);
1062 p = XPROCESS (process);
1064 p->sentinel = sentinel;
1065 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1066 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1067 return sentinel;
1070 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1071 1, 1, 0,
1072 doc: /* Return the sentinel of PROCESS; nil if none.
1073 See `set-process-sentinel' for more info on sentinels. */)
1074 (process)
1075 register Lisp_Object process;
1077 CHECK_PROCESS (process);
1078 return XPROCESS (process)->sentinel;
1081 DEFUN ("set-process-window-size", Fset_process_window_size,
1082 Sset_process_window_size, 3, 3, 0,
1083 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1084 (process, height, width)
1085 register Lisp_Object process, height, width;
1087 CHECK_PROCESS (process);
1088 CHECK_NATNUM (height);
1089 CHECK_NATNUM (width);
1091 if (XPROCESS (process)->infd < 0
1092 || set_window_size (XPROCESS (process)->infd,
1093 XINT (height), XINT (width)) <= 0)
1094 return Qnil;
1095 else
1096 return Qt;
1099 DEFUN ("set-process-inherit-coding-system-flag",
1100 Fset_process_inherit_coding_system_flag,
1101 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1102 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1103 If the second argument FLAG is non-nil, then the variable
1104 `buffer-file-coding-system' of the buffer associated with PROCESS
1105 will be bound to the value of the coding system used to decode
1106 the process output.
1108 This is useful when the coding system specified for the process buffer
1109 leaves either the character code conversion or the end-of-line conversion
1110 unspecified, or if the coding system used to decode the process output
1111 is more appropriate for saving the process buffer.
1113 Binding the variable `inherit-process-coding-system' to non-nil before
1114 starting the process is an alternative way of setting the inherit flag
1115 for the process which will run. */)
1116 (process, flag)
1117 register Lisp_Object process, flag;
1119 CHECK_PROCESS (process);
1120 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1121 return flag;
1124 DEFUN ("process-inherit-coding-system-flag",
1125 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1126 1, 1, 0,
1127 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1128 If this flag is t, `buffer-file-coding-system' of the buffer
1129 associated with PROCESS will inherit the coding system used to decode
1130 the process output. */)
1131 (process)
1132 register Lisp_Object process;
1134 CHECK_PROCESS (process);
1135 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1138 DEFUN ("set-process-query-on-exit-flag",
1139 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1140 2, 2, 0,
1141 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1142 If the second argument FLAG is non-nil, Emacs will query the user before
1143 exiting or killing a buffer if PROCESS is running. */)
1144 (process, flag)
1145 register Lisp_Object process, flag;
1147 CHECK_PROCESS (process);
1148 XPROCESS (process)->kill_without_query = NILP (flag);
1149 return flag;
1152 DEFUN ("process-query-on-exit-flag",
1153 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1154 1, 1, 0,
1155 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1156 (process)
1157 register Lisp_Object process;
1159 CHECK_PROCESS (process);
1160 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1163 #ifdef DATAGRAM_SOCKETS
1164 Lisp_Object Fprocess_datagram_address ();
1165 #endif
1167 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1168 1, 2, 0,
1169 doc: /* Return the contact info of PROCESS; t for a real child.
1170 For a network or serial connection, the value depends on the optional
1171 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1172 SERVICE) for a network connection or (PORT SPEED) for a serial
1173 connection. If KEY is t, the complete contact information for the
1174 connection is returned, else the specific value for the keyword KEY is
1175 returned. See `make-network-process' or `make-serial-process' for a
1176 list of keywords. */)
1177 (process, key)
1178 register Lisp_Object process, key;
1180 Lisp_Object contact;
1182 CHECK_PROCESS (process);
1183 contact = XPROCESS (process)->childp;
1185 #ifdef DATAGRAM_SOCKETS
1186 if (DATAGRAM_CONN_P (process)
1187 && (EQ (key, Qt) || EQ (key, QCremote)))
1188 contact = Fplist_put (contact, QCremote,
1189 Fprocess_datagram_address (process));
1190 #endif
1192 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1193 return contact;
1194 if (NILP (key) && NETCONN_P (process))
1195 return Fcons (Fplist_get (contact, QChost),
1196 Fcons (Fplist_get (contact, QCservice), Qnil));
1197 if (NILP (key) && SERIALCONN_P (process))
1198 return Fcons (Fplist_get (contact, QCport),
1199 Fcons (Fplist_get (contact, QCspeed), Qnil));
1200 return Fplist_get (contact, key);
1203 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1204 1, 1, 0,
1205 doc: /* Return the plist of PROCESS. */)
1206 (process)
1207 register Lisp_Object process;
1209 CHECK_PROCESS (process);
1210 return XPROCESS (process)->plist;
1213 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1214 2, 2, 0,
1215 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1216 (process, plist)
1217 register Lisp_Object process, plist;
1219 CHECK_PROCESS (process);
1220 CHECK_LIST (plist);
1222 XPROCESS (process)->plist = plist;
1223 return plist;
1226 #if 0 /* Turned off because we don't currently record this info
1227 in the process. Perhaps add it. */
1228 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1229 doc: /* Return the connection type of PROCESS.
1230 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1231 a socket connection. */)
1232 (process)
1233 Lisp_Object process;
1235 return XPROCESS (process)->type;
1237 #endif
1239 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1240 doc: /* Return the connection type of PROCESS.
1241 The value is either the symbol `real', `network', or `serial'.
1242 PROCESS may be a process, a buffer, the name of a process or buffer, or
1243 nil, indicating the current buffer's process. */)
1244 (process)
1245 Lisp_Object process;
1247 Lisp_Object proc;
1248 proc = get_process (process);
1249 return XPROCESS (proc)->type;
1252 #ifdef HAVE_SOCKETS
1253 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1254 1, 2, 0,
1255 doc: /* Convert network ADDRESS from internal format to a string.
1256 A 4 or 5 element vector represents an IPv4 address (with port number).
1257 An 8 or 9 element vector represents an IPv6 address (with port number).
1258 If optional second argument OMIT-PORT is non-nil, don't include a port
1259 number in the string, even when present in ADDRESS.
1260 Returns nil if format of ADDRESS is invalid. */)
1261 (address, omit_port)
1262 Lisp_Object address, omit_port;
1264 if (NILP (address))
1265 return Qnil;
1267 if (STRINGP (address)) /* AF_LOCAL */
1268 return address;
1270 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1272 register struct Lisp_Vector *p = XVECTOR (address);
1273 Lisp_Object args[10];
1274 int nargs, i;
1276 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1278 args[0] = build_string ("%d.%d.%d.%d");
1279 nargs = 4;
1281 else if (p->size == 5)
1283 args[0] = build_string ("%d.%d.%d.%d:%d");
1284 nargs = 5;
1286 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1288 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1289 nargs = 8;
1291 else if (p->size == 9)
1293 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1294 nargs = 9;
1296 else
1297 return Qnil;
1299 for (i = 0; i < nargs; i++)
1301 EMACS_INT element = XINT (p->contents[i]);
1303 if (element < 0 || element > 65535)
1304 return Qnil;
1306 if (nargs <= 5 /* IPv4 */
1307 && i < 4 /* host, not port */
1308 && element > 255)
1309 return Qnil;
1311 args[i+1] = p->contents[i];
1314 return Fformat (nargs+1, args);
1317 if (CONSP (address))
1319 Lisp_Object args[2];
1320 args[0] = build_string ("<Family %d>");
1321 args[1] = Fcar (address);
1322 return Fformat (2, args);
1325 return Qnil;
1327 #endif
1329 static Lisp_Object
1330 list_processes_1 (query_only)
1331 Lisp_Object query_only;
1333 register Lisp_Object tail, tem;
1334 Lisp_Object proc, minspace, tem1;
1335 register struct Lisp_Process *p;
1336 char tembuf[300];
1337 int w_proc, w_buffer, w_tty;
1338 int exited = 0;
1339 Lisp_Object i_status, i_buffer, i_tty, i_command;
1341 w_proc = 4; /* Proc */
1342 w_buffer = 6; /* Buffer */
1343 w_tty = 0; /* Omit if no ttys */
1345 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1347 int i;
1349 proc = Fcdr (XCAR (tail));
1350 p = XPROCESS (proc);
1351 if (NILP (p->type))
1352 continue;
1353 if (!NILP (query_only) && p->kill_without_query)
1354 continue;
1355 if (STRINGP (p->name)
1356 && ( i = SCHARS (p->name), (i > w_proc)))
1357 w_proc = i;
1358 if (!NILP (p->buffer))
1360 if (NILP (XBUFFER (p->buffer)->name))
1362 if (w_buffer < 8)
1363 w_buffer = 8; /* (Killed) */
1365 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1366 w_buffer = i;
1368 if (STRINGP (p->tty_name)
1369 && (i = SCHARS (p->tty_name), (i > w_tty)))
1370 w_tty = i;
1373 XSETFASTINT (i_status, w_proc + 1);
1374 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1375 if (w_tty)
1377 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1378 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1380 else
1382 i_tty = Qnil;
1383 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1386 XSETFASTINT (minspace, 1);
1388 set_buffer_internal (XBUFFER (Vstandard_output));
1389 current_buffer->undo_list = Qt;
1391 current_buffer->truncate_lines = Qt;
1393 write_string ("Proc", -1);
1394 Findent_to (i_status, minspace); write_string ("Status", -1);
1395 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1396 if (!NILP (i_tty))
1398 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1400 Findent_to (i_command, minspace); write_string ("Command", -1);
1401 write_string ("\n", -1);
1403 write_string ("----", -1);
1404 Findent_to (i_status, minspace); write_string ("------", -1);
1405 Findent_to (i_buffer, minspace); write_string ("------", -1);
1406 if (!NILP (i_tty))
1408 Findent_to (i_tty, minspace); write_string ("---", -1);
1410 Findent_to (i_command, minspace); write_string ("-------", -1);
1411 write_string ("\n", -1);
1413 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1415 Lisp_Object symbol;
1417 proc = Fcdr (XCAR (tail));
1418 p = XPROCESS (proc);
1419 if (NILP (p->type))
1420 continue;
1421 if (!NILP (query_only) && p->kill_without_query)
1422 continue;
1424 Finsert (1, &p->name);
1425 Findent_to (i_status, minspace);
1427 if (p->raw_status_new)
1428 update_status (p);
1429 symbol = p->status;
1430 if (CONSP (p->status))
1431 symbol = XCAR (p->status);
1433 if (EQ (symbol, Qsignal))
1435 Lisp_Object tem;
1436 tem = Fcar (Fcdr (p->status));
1437 Fprinc (symbol, Qnil);
1439 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1441 if (EQ (symbol, Qexit))
1442 write_string ("closed", -1);
1443 else if (EQ (p->command, Qt))
1444 write_string ("stopped", -1);
1445 else if (EQ (symbol, Qrun))
1446 write_string ("open", -1);
1447 else
1448 Fprinc (symbol, Qnil);
1450 else if (SERIALCONN1_P (p))
1452 write_string ("running", -1);
1454 else
1455 Fprinc (symbol, Qnil);
1457 if (EQ (symbol, Qexit))
1459 Lisp_Object tem;
1460 tem = Fcar (Fcdr (p->status));
1461 if (XFASTINT (tem))
1463 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1464 write_string (tembuf, -1);
1468 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1469 exited++;
1471 Findent_to (i_buffer, minspace);
1472 if (NILP (p->buffer))
1473 insert_string ("(none)");
1474 else if (NILP (XBUFFER (p->buffer)->name))
1475 insert_string ("(Killed)");
1476 else
1477 Finsert (1, &XBUFFER (p->buffer)->name);
1479 if (!NILP (i_tty))
1481 Findent_to (i_tty, minspace);
1482 if (STRINGP (p->tty_name))
1483 Finsert (1, &p->tty_name);
1486 Findent_to (i_command, minspace);
1488 if (EQ (p->status, Qlisten))
1490 Lisp_Object port = Fplist_get (p->childp, QCservice);
1491 if (INTEGERP (port))
1492 port = Fnumber_to_string (port);
1493 if (NILP (port))
1494 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1495 sprintf (tembuf, "(network %s server on %s)\n",
1496 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1497 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1498 insert_string (tembuf);
1500 else if (NETCONN1_P (p))
1502 /* For a local socket, there is no host name,
1503 so display service instead. */
1504 Lisp_Object host = Fplist_get (p->childp, QChost);
1505 if (!STRINGP (host))
1507 host = Fplist_get (p->childp, QCservice);
1508 if (INTEGERP (host))
1509 host = Fnumber_to_string (host);
1511 if (NILP (host))
1512 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1513 sprintf (tembuf, "(network %s connection to %s)\n",
1514 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1515 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1516 insert_string (tembuf);
1518 else if (SERIALCONN1_P (p))
1520 Lisp_Object port = Fplist_get (p->childp, QCport);
1521 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1522 insert_string ("(serial port ");
1523 if (STRINGP (port))
1524 insert_string (SDATA (port));
1525 else
1526 insert_string ("?");
1527 if (INTEGERP (speed))
1529 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1530 insert_string (tembuf);
1532 insert_string (")\n");
1534 else
1536 tem = p->command;
1537 while (1)
1539 tem1 = Fcar (tem);
1540 if (NILP (tem1))
1541 break;
1542 Finsert (1, &tem1);
1543 tem = Fcdr (tem);
1544 if (NILP (tem))
1545 break;
1546 insert_string (" ");
1548 insert_string ("\n");
1551 if (exited)
1553 status_notify (NULL);
1554 redisplay_preserve_echo_area (13);
1556 return Qnil;
1559 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1560 doc: /* Display a list of all processes.
1561 If optional argument QUERY-ONLY is non-nil, only processes with
1562 the query-on-exit flag set will be listed.
1563 Any process listed as exited or signaled is actually eliminated
1564 after the listing is made. */)
1565 (query_only)
1566 Lisp_Object query_only;
1568 internal_with_output_to_temp_buffer ("*Process List*",
1569 list_processes_1, query_only);
1570 return Qnil;
1573 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1574 doc: /* Return a list of all processes. */)
1577 return Fmapcar (Qcdr, Vprocess_alist);
1580 /* Starting asynchronous inferior processes. */
1582 static Lisp_Object start_process_unwind ();
1584 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1585 doc: /* Start a program in a subprocess. Return the process object for it.
1586 NAME is name for process. It is modified if necessary to make it unique.
1587 BUFFER is the buffer (or buffer name) to associate with the process.
1589 Process output (both standard output and standard error streams) goes
1590 at end of BUFFER, unless you specify an output stream or filter
1591 function to handle the output. BUFFER may also be nil, meaning that
1592 this process is not associated with any buffer.
1594 PROGRAM is the program file name. It is searched for in PATH. If
1595 nil, just associate a pty with the buffer. Remaining arguments are
1596 strings to give program as arguments.
1598 If you want to separate standard output from standard error, invoke
1599 the command through a shell and redirect one of them using the shell
1600 syntax.
1602 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1603 (nargs, args)
1604 int nargs;
1605 register Lisp_Object *args;
1607 Lisp_Object buffer, name, program, proc, current_dir, tem;
1608 register unsigned char **new_argv;
1609 register int i;
1610 int count = SPECPDL_INDEX ();
1612 buffer = args[1];
1613 if (!NILP (buffer))
1614 buffer = Fget_buffer_create (buffer);
1616 /* Make sure that the child will be able to chdir to the current
1617 buffer's current directory, or its unhandled equivalent. We
1618 can't just have the child check for an error when it does the
1619 chdir, since it's in a vfork.
1621 We have to GCPRO around this because Fexpand_file_name and
1622 Funhandled_file_name_directory might call a file name handling
1623 function. The argument list is protected by the caller, so all
1624 we really have to worry about is buffer. */
1626 struct gcpro gcpro1, gcpro2;
1628 current_dir = current_buffer->directory;
1630 GCPRO2 (buffer, current_dir);
1632 current_dir = Funhandled_file_name_directory (current_dir);
1633 if (NILP (current_dir))
1634 /* If the file name handler says that current_dir is unreachable, use
1635 a sensible default. */
1636 current_dir = build_string ("~/");
1637 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1638 if (NILP (Ffile_accessible_directory_p (current_dir)))
1639 report_file_error ("Setting current directory",
1640 Fcons (current_buffer->directory, Qnil));
1642 UNGCPRO;
1645 name = args[0];
1646 CHECK_STRING (name);
1648 program = args[2];
1650 if (!NILP (program))
1651 CHECK_STRING (program);
1653 proc = make_process (name);
1654 /* If an error occurs and we can't start the process, we want to
1655 remove it from the process list. This means that each error
1656 check in create_process doesn't need to call remove_process
1657 itself; it's all taken care of here. */
1658 record_unwind_protect (start_process_unwind, proc);
1660 XPROCESS (proc)->childp = Qt;
1661 XPROCESS (proc)->plist = Qnil;
1662 XPROCESS (proc)->type = Qreal;
1663 XPROCESS (proc)->buffer = buffer;
1664 XPROCESS (proc)->sentinel = Qnil;
1665 XPROCESS (proc)->filter = Qnil;
1666 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1668 #ifdef ADAPTIVE_READ_BUFFERING
1669 XPROCESS (proc)->adaptive_read_buffering
1670 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1671 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1672 #endif
1674 /* Make the process marker point into the process buffer (if any). */
1675 if (BUFFERP (buffer))
1676 set_marker_both (XPROCESS (proc)->mark, buffer,
1677 BUF_ZV (XBUFFER (buffer)),
1678 BUF_ZV_BYTE (XBUFFER (buffer)));
1681 /* Decide coding systems for communicating with the process. Here
1682 we don't setup the structure coding_system nor pay attention to
1683 unibyte mode. They are done in create_process. */
1685 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1686 Lisp_Object coding_systems = Qt;
1687 Lisp_Object val, *args2;
1688 struct gcpro gcpro1, gcpro2;
1690 val = Vcoding_system_for_read;
1691 if (NILP (val))
1693 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1694 args2[0] = Qstart_process;
1695 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1696 GCPRO2 (proc, current_dir);
1697 if (!NILP (program))
1698 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1699 UNGCPRO;
1700 if (CONSP (coding_systems))
1701 val = XCAR (coding_systems);
1702 else if (CONSP (Vdefault_process_coding_system))
1703 val = XCAR (Vdefault_process_coding_system);
1705 XPROCESS (proc)->decode_coding_system = val;
1707 val = Vcoding_system_for_write;
1708 if (NILP (val))
1710 if (EQ (coding_systems, Qt))
1712 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1713 args2[0] = Qstart_process;
1714 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1715 GCPRO2 (proc, current_dir);
1716 if (!NILP (program))
1717 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1718 UNGCPRO;
1720 if (CONSP (coding_systems))
1721 val = XCDR (coding_systems);
1722 else if (CONSP (Vdefault_process_coding_system))
1723 val = XCDR (Vdefault_process_coding_system);
1725 XPROCESS (proc)->encode_coding_system = val;
1729 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1730 XPROCESS (proc)->decoding_carryover = 0;
1731 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1733 XPROCESS (proc)->inherit_coding_system_flag
1734 = !(NILP (buffer) || !inherit_process_coding_system);
1736 if (!NILP (program))
1738 /* If program file name is not absolute, search our path for it.
1739 Put the name we will really use in TEM. */
1740 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1741 && !(SCHARS (program) > 1
1742 && IS_DEVICE_SEP (SREF (program, 1))))
1744 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1746 tem = Qnil;
1747 GCPRO4 (name, program, buffer, current_dir);
1748 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1749 UNGCPRO;
1750 if (NILP (tem))
1751 report_file_error ("Searching for program", Fcons (program, Qnil));
1752 tem = Fexpand_file_name (tem, Qnil);
1754 else
1756 if (!NILP (Ffile_directory_p (program)))
1757 error ("Specified program for new process is a directory");
1758 tem = program;
1761 /* If program file name starts with /: for quoting a magic name,
1762 discard that. */
1763 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1764 && SREF (tem, 1) == ':')
1765 tem = Fsubstring (tem, make_number (2), Qnil);
1768 struct gcpro gcpro1;
1769 GCPRO1 (tem);
1771 /* Encode the file name and put it in NEW_ARGV.
1772 That's where the child will use it to execute the program. */
1773 tem = Fcons (ENCODE_FILE (tem), Qnil);
1775 /* Here we encode arguments by the coding system used for sending
1776 data to the process. We don't support using different coding
1777 systems for encoding arguments and for encoding data sent to the
1778 process. */
1780 for (i = 3; i < nargs; i++)
1782 tem = Fcons (args[i], tem);
1783 CHECK_STRING (XCAR (tem));
1784 if (STRING_MULTIBYTE (XCAR (tem)))
1785 XSETCAR (tem,
1786 code_convert_string_norecord
1787 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1790 UNGCPRO;
1793 /* Now that everything is encoded we can collect the strings into
1794 NEW_ARGV. */
1795 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1796 new_argv[nargs - 2] = 0;
1798 for (i = nargs - 3; i >= 0; i--)
1800 new_argv[i] = SDATA (XCAR (tem));
1801 tem = XCDR (tem);
1804 create_process (proc, (char **) new_argv, current_dir);
1806 else
1807 create_pty (proc);
1809 return unbind_to (count, proc);
1812 /* This function is the unwind_protect form for Fstart_process. If
1813 PROC doesn't have its pid set, then we know someone has signaled
1814 an error and the process wasn't started successfully, so we should
1815 remove it from the process list. */
1816 static Lisp_Object
1817 start_process_unwind (proc)
1818 Lisp_Object proc;
1820 if (!PROCESSP (proc))
1821 abort ();
1823 /* Was PROC started successfully? */
1824 if (XPROCESS (proc)->pid == -1)
1825 remove_process (proc);
1827 return Qnil;
1830 static void
1831 create_process_1 (timer)
1832 struct atimer *timer;
1834 /* Nothing to do. */
1838 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1839 #ifdef USG
1840 #ifdef SIGCHLD
1841 /* Mimic blocking of signals on system V, which doesn't really have it. */
1843 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1844 int sigchld_deferred;
1846 SIGTYPE
1847 create_process_sigchld ()
1849 signal (SIGCHLD, create_process_sigchld);
1851 sigchld_deferred = 1;
1853 #endif
1854 #endif
1855 #endif
1857 void
1858 create_process (process, new_argv, current_dir)
1859 Lisp_Object process;
1860 char **new_argv;
1861 Lisp_Object current_dir;
1863 int inchannel, outchannel;
1864 pid_t pid;
1865 int sv[2];
1866 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1867 int wait_child_setup[2];
1868 #endif
1869 sigset_t procmask;
1870 sigset_t blocked;
1871 struct sigaction sigint_action;
1872 struct sigaction sigquit_action;
1873 #ifdef AIX
1874 struct sigaction sighup_action;
1875 #endif
1876 /* Use volatile to protect variables from being clobbered by longjmp. */
1877 volatile int forkin, forkout;
1878 volatile int pty_flag = 0;
1879 #ifndef USE_CRT_DLL
1880 extern char **environ;
1881 #endif
1883 inchannel = outchannel = -1;
1885 #ifdef HAVE_PTYS
1886 if (!NILP (Vprocess_connection_type))
1887 outchannel = inchannel = allocate_pty ();
1889 if (inchannel >= 0)
1891 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1892 /* On most USG systems it does not work to open the pty's tty here,
1893 then close it and reopen it in the child. */
1894 #ifdef O_NOCTTY
1895 /* Don't let this terminal become our controlling terminal
1896 (in case we don't have one). */
1897 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1898 #else
1899 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1900 #endif
1901 if (forkin < 0)
1902 report_file_error ("Opening pty", Qnil);
1903 #else
1904 forkin = forkout = -1;
1905 #endif /* not USG, or USG_SUBTTY_WORKS */
1906 pty_flag = 1;
1908 else
1909 #endif /* HAVE_PTYS */
1911 int tem;
1912 tem = pipe (sv);
1913 if (tem < 0)
1914 report_file_error ("Creating pipe", Qnil);
1915 inchannel = sv[0];
1916 forkout = sv[1];
1917 tem = pipe (sv);
1918 if (tem < 0)
1920 emacs_close (inchannel);
1921 emacs_close (forkout);
1922 report_file_error ("Creating pipe", Qnil);
1924 outchannel = sv[1];
1925 forkin = sv[0];
1928 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1930 int tem;
1932 tem = pipe (wait_child_setup);
1933 if (tem < 0)
1934 report_file_error ("Creating pipe", Qnil);
1935 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1936 if (tem >= 0)
1937 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1938 if (tem < 0)
1940 emacs_close (wait_child_setup[0]);
1941 emacs_close (wait_child_setup[1]);
1942 report_file_error ("Setting file descriptor flags", Qnil);
1945 #endif
1947 #if 0
1948 /* Replaced by close_process_descs */
1949 set_exclusive_use (inchannel);
1950 set_exclusive_use (outchannel);
1951 #endif
1953 #ifdef O_NONBLOCK
1954 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1955 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1956 #else
1957 #ifdef O_NDELAY
1958 fcntl (inchannel, F_SETFL, O_NDELAY);
1959 fcntl (outchannel, F_SETFL, O_NDELAY);
1960 #endif
1961 #endif
1963 /* Record this as an active process, with its channels.
1964 As a result, child_setup will close Emacs's side of the pipes. */
1965 chan_process[inchannel] = process;
1966 XPROCESS (process)->infd = inchannel;
1967 XPROCESS (process)->outfd = outchannel;
1969 /* Previously we recorded the tty descriptor used in the subprocess.
1970 It was only used for getting the foreground tty process, so now
1971 we just reopen the device (see emacs_get_tty_pgrp) as this is
1972 more portable (see USG_SUBTTY_WORKS above). */
1974 XPROCESS (process)->pty_flag = pty_flag;
1975 XPROCESS (process)->status = Qrun;
1976 setup_process_coding_systems (process);
1978 /* Delay interrupts until we have a chance to store
1979 the new fork's pid in its process structure */
1980 sigemptyset (&blocked);
1981 #ifdef SIGCHLD
1982 sigaddset (&blocked, SIGCHLD);
1983 #endif
1984 #ifdef HAVE_WORKING_VFORK
1985 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1986 this sets the parent's signal handlers as well as the child's.
1987 So delay all interrupts whose handlers the child might munge,
1988 and record the current handlers so they can be restored later. */
1989 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1990 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1991 #ifdef AIX
1992 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1993 #endif
1994 #endif /* HAVE_WORKING_VFORK */
1995 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1997 FD_SET (inchannel, &input_wait_mask);
1998 FD_SET (inchannel, &non_keyboard_wait_mask);
1999 if (inchannel > max_process_desc)
2000 max_process_desc = inchannel;
2002 /* Until we store the proper pid, enable sigchld_handler
2003 to recognize an unknown pid as standing for this process.
2004 It is very important not to let this `marker' value stay
2005 in the table after this function has returned; if it does
2006 it might cause call-process to hang and subsequent asynchronous
2007 processes to get their return values scrambled. */
2008 XPROCESS (process)->pid = -1;
2010 BLOCK_INPUT;
2013 /* child_setup must clobber environ on systems with true vfork.
2014 Protect it from permanent change. */
2015 char **save_environ = environ;
2017 current_dir = ENCODE_FILE (current_dir);
2019 #ifndef WINDOWSNT
2020 pid = vfork ();
2021 if (pid == 0)
2022 #endif /* not WINDOWSNT */
2024 int xforkin = forkin;
2025 int xforkout = forkout;
2027 #if 0 /* This was probably a mistake--it duplicates code later on,
2028 but fails to handle all the cases. */
2029 /* Make sure SIGCHLD is not blocked in the child. */
2030 sigsetmask (SIGEMPTYMASK);
2031 #endif
2033 /* Make the pty be the controlling terminal of the process. */
2034 #ifdef HAVE_PTYS
2035 /* First, disconnect its current controlling terminal. */
2036 #ifdef HAVE_SETSID
2037 /* We tried doing setsid only if pty_flag, but it caused
2038 process_set_signal to fail on SGI when using a pipe. */
2039 setsid ();
2040 /* Make the pty's terminal the controlling terminal. */
2041 if (pty_flag)
2043 #ifdef TIOCSCTTY
2044 /* We ignore the return value
2045 because faith@cs.unc.edu says that is necessary on Linux. */
2046 ioctl (xforkin, TIOCSCTTY, 0);
2047 #endif
2049 #else /* not HAVE_SETSID */
2050 #ifdef USG
2051 /* It's very important to call setpgrp here and no time
2052 afterwards. Otherwise, we lose our controlling tty which
2053 is set when we open the pty. */
2054 setpgrp ();
2055 #endif /* USG */
2056 #endif /* not HAVE_SETSID */
2057 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2058 if (pty_flag && xforkin >= 0)
2060 struct termios t;
2061 tcgetattr (xforkin, &t);
2062 t.c_lflag = LDISC1;
2063 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2064 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2066 #else
2067 #if defined (NTTYDISC) && defined (TIOCSETD)
2068 if (pty_flag && xforkin >= 0)
2070 /* Use new line discipline. */
2071 int ldisc = NTTYDISC;
2072 ioctl (xforkin, TIOCSETD, &ldisc);
2074 #endif
2075 #endif
2076 #ifdef TIOCNOTTY
2077 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2078 can do TIOCSPGRP only to the process's controlling tty. */
2079 if (pty_flag)
2081 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2082 I can't test it since I don't have 4.3. */
2083 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2084 ioctl (j, TIOCNOTTY, 0);
2085 emacs_close (j);
2086 #ifndef USG
2087 /* In order to get a controlling terminal on some versions
2088 of BSD, it is necessary to put the process in pgrp 0
2089 before it opens the terminal. */
2090 #ifdef HAVE_SETPGID
2091 setpgid (0, 0);
2092 #else
2093 setpgrp (0, 0);
2094 #endif
2095 #endif
2097 #endif /* TIOCNOTTY */
2099 #if !defined (DONT_REOPEN_PTY)
2100 /*** There is a suggestion that this ought to be a
2101 conditional on TIOCSPGRP,
2102 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2103 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2104 that system does seem to need this code, even though
2105 both HAVE_SETSID and TIOCSCTTY are defined. */
2106 /* Now close the pty (if we had it open) and reopen it.
2107 This makes the pty the controlling terminal of the subprocess. */
2108 if (pty_flag)
2111 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2112 would work? */
2113 if (xforkin >= 0)
2114 emacs_close (xforkin);
2115 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2117 if (xforkin < 0)
2119 emacs_write (1, "Couldn't open the pty terminal ", 31);
2120 emacs_write (1, pty_name, strlen (pty_name));
2121 emacs_write (1, "\n", 1);
2122 _exit (1);
2126 #endif /* not DONT_REOPEN_PTY */
2128 #ifdef SETUP_SLAVE_PTY
2129 if (pty_flag)
2131 SETUP_SLAVE_PTY;
2133 #endif /* SETUP_SLAVE_PTY */
2134 #ifdef AIX
2135 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2136 Now reenable it in the child, so it will die when we want it to. */
2137 if (pty_flag)
2138 signal (SIGHUP, SIG_DFL);
2139 #endif
2140 #endif /* HAVE_PTYS */
2142 signal (SIGINT, SIG_DFL);
2143 signal (SIGQUIT, SIG_DFL);
2145 /* Stop blocking signals in the child. */
2146 sigprocmask (SIG_SETMASK, &procmask, 0);
2148 if (pty_flag)
2149 child_setup_tty (xforkout);
2150 #ifdef WINDOWSNT
2151 pid = child_setup (xforkin, xforkout, xforkout,
2152 new_argv, 1, current_dir);
2153 #else /* not WINDOWSNT */
2154 #ifdef FD_CLOEXEC
2155 emacs_close (wait_child_setup[0]);
2156 #endif
2157 child_setup (xforkin, xforkout, xforkout,
2158 new_argv, 1, current_dir);
2159 #endif /* not WINDOWSNT */
2161 environ = save_environ;
2164 UNBLOCK_INPUT;
2166 /* This runs in the Emacs process. */
2167 if (pid < 0)
2169 if (forkin >= 0)
2170 emacs_close (forkin);
2171 if (forkin != forkout && forkout >= 0)
2172 emacs_close (forkout);
2174 else
2176 /* vfork succeeded. */
2177 XPROCESS (process)->pid = pid;
2179 #ifdef WINDOWSNT
2180 register_child (pid, inchannel);
2181 #endif /* WINDOWSNT */
2183 /* If the subfork execv fails, and it exits,
2184 this close hangs. I don't know why.
2185 So have an interrupt jar it loose. */
2187 struct atimer *timer;
2188 EMACS_TIME offset;
2190 stop_polling ();
2191 EMACS_SET_SECS_USECS (offset, 1, 0);
2192 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2194 if (forkin >= 0)
2195 emacs_close (forkin);
2197 cancel_atimer (timer);
2198 start_polling ();
2201 if (forkin != forkout && forkout >= 0)
2202 emacs_close (forkout);
2204 #ifdef HAVE_PTYS
2205 if (pty_flag)
2206 XPROCESS (process)->tty_name = build_string (pty_name);
2207 else
2208 #endif
2209 XPROCESS (process)->tty_name = Qnil;
2211 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2212 /* Wait for child_setup to complete in case that vfork is
2213 actually defined as fork. The descriptor wait_child_setup[1]
2214 of a pipe is closed at the child side either by close-on-exec
2215 on successful execvp or the _exit call in child_setup. */
2217 char dummy;
2219 emacs_close (wait_child_setup[1]);
2220 emacs_read (wait_child_setup[0], &dummy, 1);
2221 emacs_close (wait_child_setup[0]);
2223 #endif
2226 /* Restore the signal state whether vfork succeeded or not.
2227 (We will signal an error, below, if it failed.) */
2228 #ifdef HAVE_WORKING_VFORK
2229 /* Restore the parent's signal handlers. */
2230 sigaction (SIGINT, &sigint_action, 0);
2231 sigaction (SIGQUIT, &sigquit_action, 0);
2232 #ifdef AIX
2233 sigaction (SIGHUP, &sighup_action, 0);
2234 #endif
2235 #endif /* HAVE_WORKING_VFORK */
2236 /* Stop blocking signals in the parent. */
2237 sigprocmask (SIG_SETMASK, &procmask, 0);
2239 /* Now generate the error if vfork failed. */
2240 if (pid < 0)
2241 report_file_error ("Doing vfork", Qnil);
2244 void
2245 create_pty (process)
2246 Lisp_Object process;
2248 int inchannel, outchannel;
2250 /* Use volatile to protect variables from being clobbered by longjmp. */
2251 volatile int forkin, forkout;
2252 volatile int pty_flag = 0;
2254 inchannel = outchannel = -1;
2256 #ifdef HAVE_PTYS
2257 if (!NILP (Vprocess_connection_type))
2258 outchannel = inchannel = allocate_pty ();
2260 if (inchannel >= 0)
2262 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2263 /* On most USG systems it does not work to open the pty's tty here,
2264 then close it and reopen it in the child. */
2265 #ifdef O_NOCTTY
2266 /* Don't let this terminal become our controlling terminal
2267 (in case we don't have one). */
2268 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2269 #else
2270 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2271 #endif
2272 if (forkin < 0)
2273 report_file_error ("Opening pty", Qnil);
2274 #if defined (DONT_REOPEN_PTY)
2275 /* In the case that vfork is defined as fork, the parent process
2276 (Emacs) may send some data before the child process completes
2277 tty options setup. So we setup tty before forking. */
2278 child_setup_tty (forkout);
2279 #endif /* DONT_REOPEN_PTY */
2280 #else
2281 forkin = forkout = -1;
2282 #endif /* not USG, or USG_SUBTTY_WORKS */
2283 pty_flag = 1;
2285 #endif /* HAVE_PTYS */
2287 #ifdef O_NONBLOCK
2288 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2289 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2290 #else
2291 #ifdef O_NDELAY
2292 fcntl (inchannel, F_SETFL, O_NDELAY);
2293 fcntl (outchannel, F_SETFL, O_NDELAY);
2294 #endif
2295 #endif
2297 /* Record this as an active process, with its channels.
2298 As a result, child_setup will close Emacs's side of the pipes. */
2299 chan_process[inchannel] = process;
2300 XPROCESS (process)->infd = inchannel;
2301 XPROCESS (process)->outfd = outchannel;
2303 /* Previously we recorded the tty descriptor used in the subprocess.
2304 It was only used for getting the foreground tty process, so now
2305 we just reopen the device (see emacs_get_tty_pgrp) as this is
2306 more portable (see USG_SUBTTY_WORKS above). */
2308 XPROCESS (process)->pty_flag = pty_flag;
2309 XPROCESS (process)->status = Qrun;
2310 setup_process_coding_systems (process);
2312 FD_SET (inchannel, &input_wait_mask);
2313 FD_SET (inchannel, &non_keyboard_wait_mask);
2314 if (inchannel > max_process_desc)
2315 max_process_desc = inchannel;
2317 XPROCESS (process)->pid = -2;
2318 #ifdef HAVE_PTYS
2319 if (pty_flag)
2320 XPROCESS (process)->tty_name = build_string (pty_name);
2321 else
2322 #endif
2323 XPROCESS (process)->tty_name = Qnil;
2327 #ifdef HAVE_SOCKETS
2329 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2330 The address family of sa is not included in the result. */
2332 static Lisp_Object
2333 conv_sockaddr_to_lisp (sa, len)
2334 struct sockaddr *sa;
2335 int len;
2337 Lisp_Object address;
2338 int i;
2339 unsigned char *cp;
2340 register struct Lisp_Vector *p;
2342 /* Workaround for a bug in getsockname on BSD: Names bound to
2343 sockets in the UNIX domain are inaccessible; getsockname returns
2344 a zero length name. */
2345 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2346 return empty_unibyte_string;
2348 switch (sa->sa_family)
2350 case AF_INET:
2352 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2353 len = sizeof (sin->sin_addr) + 1;
2354 address = Fmake_vector (make_number (len), Qnil);
2355 p = XVECTOR (address);
2356 p->contents[--len] = make_number (ntohs (sin->sin_port));
2357 cp = (unsigned char *) &sin->sin_addr;
2358 break;
2360 #ifdef AF_INET6
2361 case AF_INET6:
2363 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2364 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2365 len = sizeof (sin6->sin6_addr)/2 + 1;
2366 address = Fmake_vector (make_number (len), Qnil);
2367 p = XVECTOR (address);
2368 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2369 for (i = 0; i < len; i++)
2370 p->contents[i] = make_number (ntohs (ip6[i]));
2371 return address;
2373 #endif
2374 #ifdef HAVE_LOCAL_SOCKETS
2375 case AF_LOCAL:
2377 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2378 for (i = 0; i < sizeof (sockun->sun_path); i++)
2379 if (sockun->sun_path[i] == 0)
2380 break;
2381 return make_unibyte_string (sockun->sun_path, i);
2383 #endif
2384 default:
2385 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2386 address = Fcons (make_number (sa->sa_family),
2387 Fmake_vector (make_number (len), Qnil));
2388 p = XVECTOR (XCDR (address));
2389 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2390 break;
2393 i = 0;
2394 while (i < len)
2395 p->contents[i++] = make_number (*cp++);
2397 return address;
2401 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2403 static int
2404 get_lisp_to_sockaddr_size (address, familyp)
2405 Lisp_Object address;
2406 int *familyp;
2408 register struct Lisp_Vector *p;
2410 if (VECTORP (address))
2412 p = XVECTOR (address);
2413 if (p->size == 5)
2415 *familyp = AF_INET;
2416 return sizeof (struct sockaddr_in);
2418 #ifdef AF_INET6
2419 else if (p->size == 9)
2421 *familyp = AF_INET6;
2422 return sizeof (struct sockaddr_in6);
2424 #endif
2426 #ifdef HAVE_LOCAL_SOCKETS
2427 else if (STRINGP (address))
2429 *familyp = AF_LOCAL;
2430 return sizeof (struct sockaddr_un);
2432 #endif
2433 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2435 struct sockaddr *sa;
2436 *familyp = XINT (XCAR (address));
2437 p = XVECTOR (XCDR (address));
2438 return p->size + sizeof (sa->sa_family);
2440 return 0;
2443 /* Convert an address object (vector or string) to an internal sockaddr.
2445 The address format has been basically validated by
2446 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2447 it could have come from user data. So if FAMILY is not valid,
2448 we return after zeroing *SA. */
2450 static void
2451 conv_lisp_to_sockaddr (family, address, sa, len)
2452 int family;
2453 Lisp_Object address;
2454 struct sockaddr *sa;
2455 int len;
2457 register struct Lisp_Vector *p;
2458 register unsigned char *cp = NULL;
2459 register int i;
2461 bzero (sa, len);
2463 if (VECTORP (address))
2465 p = XVECTOR (address);
2466 if (family == AF_INET)
2468 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2469 len = sizeof (sin->sin_addr) + 1;
2470 i = XINT (p->contents[--len]);
2471 sin->sin_port = htons (i);
2472 cp = (unsigned char *)&sin->sin_addr;
2473 sa->sa_family = family;
2475 #ifdef AF_INET6
2476 else if (family == AF_INET6)
2478 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2479 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2480 len = sizeof (sin6->sin6_addr) + 1;
2481 i = XINT (p->contents[--len]);
2482 sin6->sin6_port = htons (i);
2483 for (i = 0; i < len; i++)
2484 if (INTEGERP (p->contents[i]))
2486 int j = XFASTINT (p->contents[i]) & 0xffff;
2487 ip6[i] = ntohs (j);
2489 sa->sa_family = family;
2491 #endif
2492 return;
2494 else if (STRINGP (address))
2496 #ifdef HAVE_LOCAL_SOCKETS
2497 if (family == AF_LOCAL)
2499 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2500 cp = SDATA (address);
2501 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2502 sockun->sun_path[i] = *cp++;
2503 sa->sa_family = family;
2505 #endif
2506 return;
2508 else
2510 p = XVECTOR (XCDR (address));
2511 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2514 for (i = 0; i < len; i++)
2515 if (INTEGERP (p->contents[i]))
2516 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2519 #ifdef DATAGRAM_SOCKETS
2520 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2521 1, 1, 0,
2522 doc: /* Get the current datagram address associated with PROCESS. */)
2523 (process)
2524 Lisp_Object process;
2526 int channel;
2528 CHECK_PROCESS (process);
2530 if (!DATAGRAM_CONN_P (process))
2531 return Qnil;
2533 channel = XPROCESS (process)->infd;
2534 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2535 datagram_address[channel].len);
2538 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2539 2, 2, 0,
2540 doc: /* Set the datagram address for PROCESS to ADDRESS.
2541 Returns nil upon error setting address, ADDRESS otherwise. */)
2542 (process, address)
2543 Lisp_Object process, address;
2545 int channel;
2546 int family, len;
2548 CHECK_PROCESS (process);
2550 if (!DATAGRAM_CONN_P (process))
2551 return Qnil;
2553 channel = XPROCESS (process)->infd;
2555 len = get_lisp_to_sockaddr_size (address, &family);
2556 if (datagram_address[channel].len != len)
2557 return Qnil;
2558 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2559 return address;
2561 #endif
2564 static const struct socket_options {
2565 /* The name of this option. Should be lowercase version of option
2566 name without SO_ prefix. */
2567 char *name;
2568 /* Option level SOL_... */
2569 int optlevel;
2570 /* Option number SO_... */
2571 int optnum;
2572 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2573 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2574 } socket_options[] =
2576 #ifdef SO_BINDTODEVICE
2577 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2578 #endif
2579 #ifdef SO_BROADCAST
2580 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2581 #endif
2582 #ifdef SO_DONTROUTE
2583 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2584 #endif
2585 #ifdef SO_KEEPALIVE
2586 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2587 #endif
2588 #ifdef SO_LINGER
2589 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2590 #endif
2591 #ifdef SO_OOBINLINE
2592 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2593 #endif
2594 #ifdef SO_PRIORITY
2595 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2596 #endif
2597 #ifdef SO_REUSEADDR
2598 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2599 #endif
2600 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2603 /* Set option OPT to value VAL on socket S.
2605 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2606 Signals an error if setting a known option fails.
2609 static int
2610 set_socket_option (s, opt, val)
2611 int s;
2612 Lisp_Object opt, val;
2614 char *name;
2615 const struct socket_options *sopt;
2616 int ret = 0;
2618 CHECK_SYMBOL (opt);
2620 name = (char *) SDATA (SYMBOL_NAME (opt));
2621 for (sopt = socket_options; sopt->name; sopt++)
2622 if (strcmp (name, sopt->name) == 0)
2623 break;
2625 switch (sopt->opttype)
2627 case SOPT_BOOL:
2629 int optval;
2630 optval = NILP (val) ? 0 : 1;
2631 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2632 &optval, sizeof (optval));
2633 break;
2636 case SOPT_INT:
2638 int optval;
2639 if (INTEGERP (val))
2640 optval = XINT (val);
2641 else
2642 error ("Bad option value for %s", name);
2643 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2644 &optval, sizeof (optval));
2645 break;
2648 #ifdef SO_BINDTODEVICE
2649 case SOPT_IFNAME:
2651 char devname[IFNAMSIZ+1];
2653 /* This is broken, at least in the Linux 2.4 kernel.
2654 To unbind, the arg must be a zero integer, not the empty string.
2655 This should work on all systems. KFS. 2003-09-23. */
2656 bzero (devname, sizeof devname);
2657 if (STRINGP (val))
2659 char *arg = (char *) SDATA (val);
2660 int len = min (strlen (arg), IFNAMSIZ);
2661 bcopy (arg, devname, len);
2663 else if (!NILP (val))
2664 error ("Bad option value for %s", name);
2665 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2666 devname, IFNAMSIZ);
2667 break;
2669 #endif
2671 #ifdef SO_LINGER
2672 case SOPT_LINGER:
2674 struct linger linger;
2676 linger.l_onoff = 1;
2677 linger.l_linger = 0;
2678 if (INTEGERP (val))
2679 linger.l_linger = XINT (val);
2680 else
2681 linger.l_onoff = NILP (val) ? 0 : 1;
2682 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2683 &linger, sizeof (linger));
2684 break;
2686 #endif
2688 default:
2689 return 0;
2692 if (ret < 0)
2693 report_file_error ("Cannot set network option",
2694 Fcons (opt, Fcons (val, Qnil)));
2695 return (1 << sopt->optbit);
2699 DEFUN ("set-network-process-option",
2700 Fset_network_process_option, Sset_network_process_option,
2701 3, 4, 0,
2702 doc: /* For network process PROCESS set option OPTION to value VALUE.
2703 See `make-network-process' for a list of options and values.
2704 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2705 OPTION is not a supported option, return nil instead; otherwise return t. */)
2706 (process, option, value, no_error)
2707 Lisp_Object process, option, value;
2708 Lisp_Object no_error;
2710 int s;
2711 struct Lisp_Process *p;
2713 CHECK_PROCESS (process);
2714 p = XPROCESS (process);
2715 if (!NETCONN1_P (p))
2716 error ("Process is not a network process");
2718 s = p->infd;
2719 if (s < 0)
2720 error ("Process is not running");
2722 if (set_socket_option (s, option, value))
2724 p->childp = Fplist_put (p->childp, option, value);
2725 return Qt;
2728 if (NILP (no_error))
2729 error ("Unknown or unsupported option");
2731 return Qnil;
2735 #ifdef HAVE_SERIAL
2736 DEFUN ("serial-process-configure",
2737 Fserial_process_configure,
2738 Sserial_process_configure,
2739 0, MANY, 0,
2740 doc: /* Configure speed, bytesize, etc. of a serial process.
2742 Arguments are specified as keyword/argument pairs. Attributes that
2743 are not given are re-initialized from the process's current
2744 configuration (available via the function `process-contact') or set to
2745 reasonable default values. The following arguments are defined:
2747 :process PROCESS
2748 :name NAME
2749 :buffer BUFFER
2750 :port PORT
2751 -- Any of these arguments can be given to identify the process that is
2752 to be configured. If none of these arguments is given, the current
2753 buffer's process is used.
2755 :speed SPEED -- SPEED is the speed of the serial port in bits per
2756 second, also called baud rate. Any value can be given for SPEED, but
2757 most serial ports work only at a few defined values between 1200 and
2758 115200, with 9600 being the most common value. If SPEED is nil, the
2759 serial port is not configured any further, i.e., all other arguments
2760 are ignored. This may be useful for special serial ports such as
2761 Bluetooth-to-serial converters which can only be configured through AT
2762 commands. A value of nil for SPEED can be used only when passed
2763 through `make-serial-process' or `serial-term'.
2765 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2766 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2768 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2769 `odd' (use odd parity), or the symbol `even' (use even parity). If
2770 PARITY is not given, no parity is used.
2772 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2773 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2774 is not given or nil, 1 stopbit is used.
2776 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2777 flowcontrol to be used, which is either nil (don't use flowcontrol),
2778 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2779 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2780 flowcontrol is used.
2782 `serial-process-configure' is called by `make-serial-process' for the
2783 initial configuration of the serial port.
2785 Examples:
2787 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2789 \(serial-process-configure
2790 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2792 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2794 usage: (serial-process-configure &rest ARGS) */)
2795 (nargs, args)
2796 int nargs;
2797 Lisp_Object *args;
2799 struct Lisp_Process *p;
2800 Lisp_Object contact = Qnil;
2801 Lisp_Object proc = Qnil;
2802 struct gcpro gcpro1;
2804 contact = Flist (nargs, args);
2805 GCPRO1 (contact);
2807 proc = Fplist_get (contact, QCprocess);
2808 if (NILP (proc))
2809 proc = Fplist_get (contact, QCname);
2810 if (NILP (proc))
2811 proc = Fplist_get (contact, QCbuffer);
2812 if (NILP (proc))
2813 proc = Fplist_get (contact, QCport);
2814 proc = get_process (proc);
2815 p = XPROCESS (proc);
2816 if (!EQ (p->type, Qserial))
2817 error ("Not a serial process");
2819 if (NILP (Fplist_get (p->childp, QCspeed)))
2821 UNGCPRO;
2822 return Qnil;
2825 serial_configure (p, contact);
2827 UNGCPRO;
2828 return Qnil;
2831 /* Used by make-serial-process to recover from errors. */
2832 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2834 if (!PROCESSP (proc))
2835 abort ();
2836 remove_process (proc);
2837 return Qnil;
2840 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2841 0, MANY, 0,
2842 doc: /* Create and return a serial port process.
2844 In Emacs, serial port connections are represented by process objects,
2845 so input and output work as for subprocesses, and `delete-process'
2846 closes a serial port connection. However, a serial process has no
2847 process id, it cannot be signaled, and the status codes are different
2848 from normal processes.
2850 `make-serial-process' creates a process and a buffer, on which you
2851 probably want to use `process-send-string'. Try \\[serial-term] for
2852 an interactive terminal. See below for examples.
2854 Arguments are specified as keyword/argument pairs. The following
2855 arguments are defined:
2857 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2858 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2859 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2860 the backslashes in strings).
2862 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2863 which is called by `make-serial-process'.
2865 :name NAME -- NAME is the name of the process. If NAME is not given,
2866 the value of PORT is used.
2868 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2869 with the process. Process output goes at the end of that buffer,
2870 unless you specify an output stream or filter function to handle the
2871 output. If BUFFER is not given, the value of NAME is used.
2873 :coding CODING -- If CODING is a symbol, it specifies the coding
2874 system used for both reading and writing for this process. If CODING
2875 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2876 ENCODING is used for writing.
2878 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2879 the process is running. If BOOL is not given, query before exiting.
2881 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2882 In the stopped state, a serial process does not accept incoming data,
2883 but you can send outgoing data. The stopped state is cleared by
2884 `continue-process' and set by `stop-process'.
2886 :filter FILTER -- Install FILTER as the process filter.
2888 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2890 :plist PLIST -- Install PLIST as the initial plist of the process.
2892 :speed
2893 :bytesize
2894 :parity
2895 :stopbits
2896 :flowcontrol
2897 -- These arguments are handled by `serial-process-configure', which is
2898 called by `make-serial-process'.
2900 The original argument list, possibly modified by later configuration,
2901 is available via the function `process-contact'.
2903 Examples:
2905 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2907 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2909 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2911 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2913 usage: (make-serial-process &rest ARGS) */)
2914 (nargs, args)
2915 int nargs;
2916 Lisp_Object *args;
2918 int fd = -1;
2919 Lisp_Object proc, contact, port;
2920 struct Lisp_Process *p;
2921 struct gcpro gcpro1;
2922 Lisp_Object name, buffer;
2923 Lisp_Object tem, val;
2924 int specpdl_count = -1;
2926 if (nargs == 0)
2927 return Qnil;
2929 contact = Flist (nargs, args);
2930 GCPRO1 (contact);
2932 port = Fplist_get (contact, QCport);
2933 if (NILP (port))
2934 error ("No port specified");
2935 CHECK_STRING (port);
2937 if (NILP (Fplist_member (contact, QCspeed)))
2938 error (":speed not specified");
2939 if (!NILP (Fplist_get (contact, QCspeed)))
2940 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2942 name = Fplist_get (contact, QCname);
2943 if (NILP (name))
2944 name = port;
2945 CHECK_STRING (name);
2946 proc = make_process (name);
2947 specpdl_count = SPECPDL_INDEX ();
2948 record_unwind_protect (make_serial_process_unwind, proc);
2949 p = XPROCESS (proc);
2951 fd = serial_open ((char*) SDATA (port));
2952 p->infd = fd;
2953 p->outfd = fd;
2954 if (fd > max_process_desc)
2955 max_process_desc = fd;
2956 chan_process[fd] = proc;
2958 buffer = Fplist_get (contact, QCbuffer);
2959 if (NILP (buffer))
2960 buffer = name;
2961 buffer = Fget_buffer_create (buffer);
2962 p->buffer = buffer;
2964 p->childp = contact;
2965 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2966 p->type = Qserial;
2967 p->sentinel = Fplist_get (contact, QCsentinel);
2968 p->filter = Fplist_get (contact, QCfilter);
2969 p->log = Qnil;
2970 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2971 p->kill_without_query = 1;
2972 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2973 p->command = Qt;
2974 p->pty_flag = 0;
2976 if (!EQ (p->command, Qt))
2978 FD_SET (fd, &input_wait_mask);
2979 FD_SET (fd, &non_keyboard_wait_mask);
2982 if (BUFFERP (buffer))
2984 set_marker_both (p->mark, buffer,
2985 BUF_ZV (XBUFFER (buffer)),
2986 BUF_ZV_BYTE (XBUFFER (buffer)));
2989 tem = Fplist_member (contact, QCcoding);
2990 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2991 tem = Qnil;
2993 val = Qnil;
2994 if (!NILP (tem))
2996 val = XCAR (XCDR (tem));
2997 if (CONSP (val))
2998 val = XCAR (val);
3000 else if (!NILP (Vcoding_system_for_read))
3001 val = Vcoding_system_for_read;
3002 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3003 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3004 val = Qnil;
3005 p->decode_coding_system = val;
3007 val = Qnil;
3008 if (!NILP (tem))
3010 val = XCAR (XCDR (tem));
3011 if (CONSP (val))
3012 val = XCDR (val);
3014 else if (!NILP (Vcoding_system_for_write))
3015 val = Vcoding_system_for_write;
3016 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3017 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3018 val = Qnil;
3019 p->encode_coding_system = val;
3021 setup_process_coding_systems (proc);
3022 p->decoding_buf = make_uninit_string (0);
3023 p->decoding_carryover = 0;
3024 p->encoding_buf = make_uninit_string (0);
3025 p->inherit_coding_system_flag
3026 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3028 Fserial_process_configure(nargs, args);
3030 specpdl_ptr = specpdl + specpdl_count;
3032 UNGCPRO;
3033 return proc;
3035 #endif /* HAVE_SERIAL */
3037 /* Create a network stream/datagram client/server process. Treated
3038 exactly like a normal process when reading and writing. Primary
3039 differences are in status display and process deletion. A network
3040 connection has no PID; you cannot signal it. All you can do is
3041 stop/continue it and deactivate/close it via delete-process */
3043 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3044 0, MANY, 0,
3045 doc: /* Create and return a network server or client process.
3047 In Emacs, network connections are represented by process objects, so
3048 input and output work as for subprocesses and `delete-process' closes
3049 a network connection. However, a network process has no process id,
3050 it cannot be signaled, and the status codes are different from normal
3051 processes.
3053 Arguments are specified as keyword/argument pairs. The following
3054 arguments are defined:
3056 :name NAME -- NAME is name for process. It is modified if necessary
3057 to make it unique.
3059 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3060 with the process. Process output goes at end of that buffer, unless
3061 you specify an output stream or filter function to handle the output.
3062 BUFFER may be also nil, meaning that this process is not associated
3063 with any buffer.
3065 :host HOST -- HOST is name of the host to connect to, or its IP
3066 address. The symbol `local' specifies the local host. If specified
3067 for a server process, it must be a valid name or address for the local
3068 host, and only clients connecting to that address will be accepted.
3070 :service SERVICE -- SERVICE is name of the service desired, or an
3071 integer specifying a port number to connect to. If SERVICE is t,
3072 a random port number is selected for the server. (If Emacs was
3073 compiled with getaddrinfo, a port number can also be specified as a
3074 string, e.g. "80", as well as an integer. This is not portable.)
3076 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3077 stream type connection, `datagram' creates a datagram type connection,
3078 `seqpacket' creates a reliable datagram connection.
3080 :family FAMILY -- FAMILY is the address (and protocol) family for the
3081 service specified by HOST and SERVICE. The default (nil) is to use
3082 whatever address family (IPv4 or IPv6) that is defined for the host
3083 and port number specified by HOST and SERVICE. Other address families
3084 supported are:
3085 local -- for a local (i.e. UNIX) address specified by SERVICE.
3086 ipv4 -- use IPv4 address family only.
3087 ipv6 -- use IPv6 address family only.
3089 :local ADDRESS -- ADDRESS is the local address used for the connection.
3090 This parameter is ignored when opening a client process. When specified
3091 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3093 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3094 connection. This parameter is ignored when opening a stream server
3095 process. For a datagram server process, it specifies the initial
3096 setting of the remote datagram address. When specified for a client
3097 process, the FAMILY, HOST, and SERVICE args are ignored.
3099 The format of ADDRESS depends on the address family:
3100 - An IPv4 address is represented as an vector of integers [A B C D P]
3101 corresponding to numeric IP address A.B.C.D and port number P.
3102 - A local address is represented as a string with the address in the
3103 local address space.
3104 - An "unsupported family" address is represented by a cons (F . AV)
3105 where F is the family number and AV is a vector containing the socket
3106 address data with one element per address data byte. Do not rely on
3107 this format in portable code, as it may depend on implementation
3108 defined constants, data sizes, and data structure alignment.
3110 :coding CODING -- If CODING is a symbol, it specifies the coding
3111 system used for both reading and writing for this process. If CODING
3112 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3113 ENCODING is used for writing.
3115 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3116 return without waiting for the connection to complete; instead, the
3117 sentinel function will be called with second arg matching "open" (if
3118 successful) or "failed" when the connect completes. Default is to use
3119 a blocking connect (i.e. wait) for stream type connections.
3121 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3122 running when Emacs is exited.
3124 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3125 In the stopped state, a server process does not accept new
3126 connections, and a client process does not handle incoming traffic.
3127 The stopped state is cleared by `continue-process' and set by
3128 `stop-process'.
3130 :filter FILTER -- Install FILTER as the process filter.
3132 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3133 process filter are multibyte, otherwise they are unibyte.
3134 If this keyword is not specified, the strings are multibyte if
3135 `default-enable-multibyte-characters' is non-nil.
3137 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3139 :log LOG -- Install LOG as the server process log function. This
3140 function is called when the server accepts a network connection from a
3141 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3142 is the server process, CLIENT is the new process for the connection,
3143 and MESSAGE is a string.
3145 :plist PLIST -- Install PLIST as the new process' initial plist.
3147 :server QLEN -- if QLEN is non-nil, create a server process for the
3148 specified FAMILY, SERVICE, and connection type (stream or datagram).
3149 If QLEN is an integer, it is used as the max. length of the server's
3150 pending connection queue (also known as the backlog); the default
3151 queue length is 5. Default is to create a client process.
3153 The following network options can be specified for this connection:
3155 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3156 :dontroute BOOL -- Only send to directly connected hosts.
3157 :keepalive BOOL -- Send keep-alive messages on network stream.
3158 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3159 :oobinline BOOL -- Place out-of-band data in receive data stream.
3160 :priority INT -- Set protocol defined priority for sent packets.
3161 :reuseaddr BOOL -- Allow reusing a recently used local address
3162 (this is allowed by default for a server process).
3163 :bindtodevice NAME -- bind to interface NAME. Using this may require
3164 special privileges on some systems.
3166 Consult the relevant system programmer's manual pages for more
3167 information on using these options.
3170 A server process will listen for and accept connections from clients.
3171 When a client connection is accepted, a new network process is created
3172 for the connection with the following parameters:
3174 - The client's process name is constructed by concatenating the server
3175 process' NAME and a client identification string.
3176 - If the FILTER argument is non-nil, the client process will not get a
3177 separate process buffer; otherwise, the client's process buffer is a newly
3178 created buffer named after the server process' BUFFER name or process
3179 NAME concatenated with the client identification string.
3180 - The connection type and the process filter and sentinel parameters are
3181 inherited from the server process' TYPE, FILTER and SENTINEL.
3182 - The client process' contact info is set according to the client's
3183 addressing information (typically an IP address and a port number).
3184 - The client process' plist is initialized from the server's plist.
3186 Notice that the FILTER and SENTINEL args are never used directly by
3187 the server process. Also, the BUFFER argument is not used directly by
3188 the server process, but via the optional :log function, accepted (and
3189 failed) connections may be logged in the server process' buffer.
3191 The original argument list, modified with the actual connection
3192 information, is available via the `process-contact' function.
3194 usage: (make-network-process &rest ARGS) */)
3195 (nargs, args)
3196 int nargs;
3197 Lisp_Object *args;
3199 Lisp_Object proc;
3200 Lisp_Object contact;
3201 struct Lisp_Process *p;
3202 #ifdef HAVE_GETADDRINFO
3203 struct addrinfo ai, *res, *lres;
3204 struct addrinfo hints;
3205 char *portstring, portbuf[128];
3206 #else /* HAVE_GETADDRINFO */
3207 struct _emacs_addrinfo
3209 int ai_family;
3210 int ai_socktype;
3211 int ai_protocol;
3212 int ai_addrlen;
3213 struct sockaddr *ai_addr;
3214 struct _emacs_addrinfo *ai_next;
3215 } ai, *res, *lres;
3216 #endif /* HAVE_GETADDRINFO */
3217 struct sockaddr_in address_in;
3218 #ifdef HAVE_LOCAL_SOCKETS
3219 struct sockaddr_un address_un;
3220 #endif
3221 int port;
3222 int ret = 0;
3223 int xerrno = 0;
3224 int s = -1, outch, inch;
3225 struct gcpro gcpro1;
3226 int count = SPECPDL_INDEX ();
3227 int count1;
3228 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3229 Lisp_Object tem;
3230 Lisp_Object name, buffer, host, service, address;
3231 Lisp_Object filter, sentinel;
3232 int is_non_blocking_client = 0;
3233 int is_server = 0, backlog = 5;
3234 int socktype;
3235 int family = -1;
3237 if (nargs == 0)
3238 return Qnil;
3240 /* Save arguments for process-contact and clone-process. */
3241 contact = Flist (nargs, args);
3242 GCPRO1 (contact);
3244 #ifdef WINDOWSNT
3245 /* Ensure socket support is loaded if available. */
3246 init_winsock (TRUE);
3247 #endif
3249 /* :type TYPE (nil: stream, datagram */
3250 tem = Fplist_get (contact, QCtype);
3251 if (NILP (tem))
3252 socktype = SOCK_STREAM;
3253 #ifdef DATAGRAM_SOCKETS
3254 else if (EQ (tem, Qdatagram))
3255 socktype = SOCK_DGRAM;
3256 #endif
3257 #ifdef HAVE_SEQPACKET
3258 else if (EQ (tem, Qseqpacket))
3259 socktype = SOCK_SEQPACKET;
3260 #endif
3261 else
3262 error ("Unsupported connection type");
3264 /* :server BOOL */
3265 tem = Fplist_get (contact, QCserver);
3266 if (!NILP (tem))
3268 /* Don't support network sockets when non-blocking mode is
3269 not available, since a blocked Emacs is not useful. */
3270 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3271 error ("Network servers not supported");
3272 #else
3273 is_server = 1;
3274 if (INTEGERP (tem))
3275 backlog = XINT (tem);
3276 #endif
3279 /* Make QCaddress an alias for :local (server) or :remote (client). */
3280 QCaddress = is_server ? QClocal : QCremote;
3282 /* :nowait BOOL */
3283 if (!is_server && socktype != SOCK_DGRAM
3284 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3286 #ifndef NON_BLOCKING_CONNECT
3287 error ("Non-blocking connect not supported");
3288 #else
3289 is_non_blocking_client = 1;
3290 #endif
3293 name = Fplist_get (contact, QCname);
3294 buffer = Fplist_get (contact, QCbuffer);
3295 filter = Fplist_get (contact, QCfilter);
3296 sentinel = Fplist_get (contact, QCsentinel);
3298 CHECK_STRING (name);
3300 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3301 ai.ai_socktype = socktype;
3302 ai.ai_protocol = 0;
3303 ai.ai_next = NULL;
3304 res = &ai;
3306 /* :local ADDRESS or :remote ADDRESS */
3307 address = Fplist_get (contact, QCaddress);
3308 if (!NILP (address))
3310 host = service = Qnil;
3312 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3313 error ("Malformed :address");
3314 ai.ai_family = family;
3315 ai.ai_addr = alloca (ai.ai_addrlen);
3316 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3317 goto open_socket;
3320 /* :family FAMILY -- nil (for Inet), local, or integer. */
3321 tem = Fplist_get (contact, QCfamily);
3322 if (NILP (tem))
3324 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3325 family = AF_UNSPEC;
3326 #else
3327 family = AF_INET;
3328 #endif
3330 #ifdef HAVE_LOCAL_SOCKETS
3331 else if (EQ (tem, Qlocal))
3332 family = AF_LOCAL;
3333 #endif
3334 #ifdef AF_INET6
3335 else if (EQ (tem, Qipv6))
3336 family = AF_INET6;
3337 #endif
3338 else if (EQ (tem, Qipv4))
3339 family = AF_INET;
3340 else if (INTEGERP (tem))
3341 family = XINT (tem);
3342 else
3343 error ("Unknown address family");
3345 ai.ai_family = family;
3347 /* :service SERVICE -- string, integer (port number), or t (random port). */
3348 service = Fplist_get (contact, QCservice);
3350 #ifdef HAVE_LOCAL_SOCKETS
3351 if (family == AF_LOCAL)
3353 /* Host is not used. */
3354 host = Qnil;
3355 CHECK_STRING (service);
3356 bzero (&address_un, sizeof address_un);
3357 address_un.sun_family = AF_LOCAL;
3358 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3359 ai.ai_addr = (struct sockaddr *) &address_un;
3360 ai.ai_addrlen = sizeof address_un;
3361 goto open_socket;
3363 #endif
3365 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3366 host = Fplist_get (contact, QChost);
3367 if (!NILP (host))
3369 if (EQ (host, Qlocal))
3370 host = build_string ("localhost");
3371 CHECK_STRING (host);
3374 /* Slow down polling to every ten seconds.
3375 Some kernels have a bug which causes retrying connect to fail
3376 after a connect. Polling can interfere with gethostbyname too. */
3377 #ifdef POLL_FOR_INPUT
3378 if (socktype != SOCK_DGRAM)
3380 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3381 bind_polling_period (10);
3383 #endif
3385 #ifdef HAVE_GETADDRINFO
3386 /* If we have a host, use getaddrinfo to resolve both host and service.
3387 Otherwise, use getservbyname to lookup the service. */
3388 if (!NILP (host))
3391 /* SERVICE can either be a string or int.
3392 Convert to a C string for later use by getaddrinfo. */
3393 if (EQ (service, Qt))
3394 portstring = "0";
3395 else if (INTEGERP (service))
3397 sprintf (portbuf, "%ld", (long) XINT (service));
3398 portstring = portbuf;
3400 else
3402 CHECK_STRING (service);
3403 portstring = SDATA (service);
3406 immediate_quit = 1;
3407 QUIT;
3408 memset (&hints, 0, sizeof (hints));
3409 hints.ai_flags = 0;
3410 hints.ai_family = family;
3411 hints.ai_socktype = socktype;
3412 hints.ai_protocol = 0;
3414 #ifdef HAVE_RES_INIT
3415 res_init ();
3416 #endif
3418 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3419 if (ret)
3420 #ifdef HAVE_GAI_STRERROR
3421 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3422 #else
3423 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3424 #endif
3425 immediate_quit = 0;
3427 goto open_socket;
3429 #endif /* HAVE_GETADDRINFO */
3431 /* We end up here if getaddrinfo is not defined, or in case no hostname
3432 has been specified (e.g. for a local server process). */
3434 if (EQ (service, Qt))
3435 port = 0;
3436 else if (INTEGERP (service))
3437 port = htons ((unsigned short) XINT (service));
3438 else
3440 struct servent *svc_info;
3441 CHECK_STRING (service);
3442 svc_info = getservbyname (SDATA (service),
3443 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3444 if (svc_info == 0)
3445 error ("Unknown service: %s", SDATA (service));
3446 port = svc_info->s_port;
3449 bzero (&address_in, sizeof address_in);
3450 address_in.sin_family = family;
3451 address_in.sin_addr.s_addr = INADDR_ANY;
3452 address_in.sin_port = port;
3454 #ifndef HAVE_GETADDRINFO
3455 if (!NILP (host))
3457 struct hostent *host_info_ptr;
3459 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3460 as it may `hang' Emacs for a very long time. */
3461 immediate_quit = 1;
3462 QUIT;
3464 #ifdef HAVE_RES_INIT
3465 res_init ();
3466 #endif
3468 host_info_ptr = gethostbyname (SDATA (host));
3469 immediate_quit = 0;
3471 if (host_info_ptr)
3473 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3474 host_info_ptr->h_length);
3475 family = host_info_ptr->h_addrtype;
3476 address_in.sin_family = family;
3478 else
3479 /* Attempt to interpret host as numeric inet address */
3481 unsigned long numeric_addr;
3482 numeric_addr = inet_addr ((char *) SDATA (host));
3483 if (numeric_addr == -1)
3484 error ("Unknown host \"%s\"", SDATA (host));
3486 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3487 sizeof (address_in.sin_addr));
3491 #endif /* not HAVE_GETADDRINFO */
3493 ai.ai_family = family;
3494 ai.ai_addr = (struct sockaddr *) &address_in;
3495 ai.ai_addrlen = sizeof address_in;
3497 open_socket:
3499 /* Do this in case we never enter the for-loop below. */
3500 count1 = SPECPDL_INDEX ();
3501 s = -1;
3503 for (lres = res; lres; lres = lres->ai_next)
3505 int optn, optbits;
3507 retry_connect:
3509 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3510 if (s < 0)
3512 xerrno = errno;
3513 continue;
3516 #ifdef DATAGRAM_SOCKETS
3517 if (!is_server && socktype == SOCK_DGRAM)
3518 break;
3519 #endif /* DATAGRAM_SOCKETS */
3521 #ifdef NON_BLOCKING_CONNECT
3522 if (is_non_blocking_client)
3524 #ifdef O_NONBLOCK
3525 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3526 #else
3527 ret = fcntl (s, F_SETFL, O_NDELAY);
3528 #endif
3529 if (ret < 0)
3531 xerrno = errno;
3532 emacs_close (s);
3533 s = -1;
3534 continue;
3537 #endif
3539 /* Make us close S if quit. */
3540 record_unwind_protect (close_file_unwind, make_number (s));
3542 /* Parse network options in the arg list.
3543 We simply ignore anything which isn't a known option (including other keywords).
3544 An error is signaled if setting a known option fails. */
3545 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3546 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3548 if (is_server)
3550 /* Configure as a server socket. */
3552 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3553 explicit :reuseaddr key to override this. */
3554 #ifdef HAVE_LOCAL_SOCKETS
3555 if (family != AF_LOCAL)
3556 #endif
3557 if (!(optbits & (1 << OPIX_REUSEADDR)))
3559 int optval = 1;
3560 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3561 report_file_error ("Cannot set reuse option on server socket", Qnil);
3564 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3565 report_file_error ("Cannot bind server socket", Qnil);
3567 #ifdef HAVE_GETSOCKNAME
3568 if (EQ (service, Qt))
3570 struct sockaddr_in sa1;
3571 int len1 = sizeof (sa1);
3572 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3574 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3575 service = make_number (ntohs (sa1.sin_port));
3576 contact = Fplist_put (contact, QCservice, service);
3579 #endif
3581 if (socktype != SOCK_DGRAM && listen (s, backlog))
3582 report_file_error ("Cannot listen on server socket", Qnil);
3584 break;
3587 immediate_quit = 1;
3588 QUIT;
3590 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3591 xerrno = errno;
3593 if (ret == 0 || xerrno == EISCONN)
3595 /* The unwind-protect will be discarded afterwards.
3596 Likewise for immediate_quit. */
3597 break;
3600 #ifdef NON_BLOCKING_CONNECT
3601 #ifdef EINPROGRESS
3602 if (is_non_blocking_client && xerrno == EINPROGRESS)
3603 break;
3604 #else
3605 #ifdef EWOULDBLOCK
3606 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3607 break;
3608 #endif
3609 #endif
3610 #endif
3612 #ifndef WINDOWSNT
3613 if (xerrno == EINTR)
3615 /* Unlike most other syscalls connect() cannot be called
3616 again. (That would return EALREADY.) The proper way to
3617 wait for completion is select(). */
3618 int sc, len;
3619 SELECT_TYPE fdset;
3620 retry_select:
3621 FD_ZERO (&fdset);
3622 FD_SET (s, &fdset);
3623 QUIT;
3624 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3625 (EMACS_TIME *)0);
3626 if (sc == -1)
3628 if (errno == EINTR)
3629 goto retry_select;
3630 else
3631 report_file_error ("select failed", Qnil);
3633 eassert (sc > 0);
3635 len = sizeof xerrno;
3636 eassert (FD_ISSET (s, &fdset));
3637 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3638 report_file_error ("getsockopt failed", Qnil);
3639 if (xerrno)
3640 errno = xerrno, report_file_error ("error during connect", Qnil);
3641 else
3642 break;
3644 #endif /* !WINDOWSNT */
3646 immediate_quit = 0;
3648 /* Discard the unwind protect closing S. */
3649 specpdl_ptr = specpdl + count1;
3650 emacs_close (s);
3651 s = -1;
3653 #ifdef WINDOWSNT
3654 if (xerrno == EINTR)
3655 goto retry_connect;
3656 #endif
3659 if (s >= 0)
3661 #ifdef DATAGRAM_SOCKETS
3662 if (socktype == SOCK_DGRAM)
3664 if (datagram_address[s].sa)
3665 abort ();
3666 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3667 datagram_address[s].len = lres->ai_addrlen;
3668 if (is_server)
3670 Lisp_Object remote;
3671 bzero (datagram_address[s].sa, lres->ai_addrlen);
3672 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3674 int rfamily, rlen;
3675 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3676 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3677 conv_lisp_to_sockaddr (rfamily, remote,
3678 datagram_address[s].sa, rlen);
3681 else
3682 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3684 #endif
3685 contact = Fplist_put (contact, QCaddress,
3686 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3687 #ifdef HAVE_GETSOCKNAME
3688 if (!is_server)
3690 struct sockaddr_in sa1;
3691 int len1 = sizeof (sa1);
3692 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3693 contact = Fplist_put (contact, QClocal,
3694 conv_sockaddr_to_lisp (&sa1, len1));
3696 #endif
3699 immediate_quit = 0;
3701 #ifdef HAVE_GETADDRINFO
3702 if (res != &ai)
3704 BLOCK_INPUT;
3705 freeaddrinfo (res);
3706 UNBLOCK_INPUT;
3708 #endif
3710 /* Discard the unwind protect for closing S, if any. */
3711 specpdl_ptr = specpdl + count1;
3713 /* Unwind bind_polling_period and request_sigio. */
3714 unbind_to (count, Qnil);
3716 if (s < 0)
3718 /* If non-blocking got this far - and failed - assume non-blocking is
3719 not supported after all. This is probably a wrong assumption, but
3720 the normal blocking calls to open-network-stream handles this error
3721 better. */
3722 if (is_non_blocking_client)
3723 return Qnil;
3725 errno = xerrno;
3726 if (is_server)
3727 report_file_error ("make server process failed", contact);
3728 else
3729 report_file_error ("make client process failed", contact);
3732 inch = s;
3733 outch = s;
3735 if (!NILP (buffer))
3736 buffer = Fget_buffer_create (buffer);
3737 proc = make_process (name);
3739 chan_process[inch] = proc;
3741 #ifdef O_NONBLOCK
3742 fcntl (inch, F_SETFL, O_NONBLOCK);
3743 #else
3744 #ifdef O_NDELAY
3745 fcntl (inch, F_SETFL, O_NDELAY);
3746 #endif
3747 #endif
3749 p = XPROCESS (proc);
3751 p->childp = contact;
3752 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3753 p->type = Qnetwork;
3755 p->buffer = buffer;
3756 p->sentinel = sentinel;
3757 p->filter = filter;
3758 p->log = Fplist_get (contact, QClog);
3759 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3760 p->kill_without_query = 1;
3761 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3762 p->command = Qt;
3763 p->pid = 0;
3764 p->infd = inch;
3765 p->outfd = outch;
3766 if (is_server && socktype != SOCK_DGRAM)
3767 p->status = Qlisten;
3769 /* Make the process marker point into the process buffer (if any). */
3770 if (BUFFERP (buffer))
3771 set_marker_both (p->mark, buffer,
3772 BUF_ZV (XBUFFER (buffer)),
3773 BUF_ZV_BYTE (XBUFFER (buffer)));
3775 #ifdef NON_BLOCKING_CONNECT
3776 if (is_non_blocking_client)
3778 /* We may get here if connect did succeed immediately. However,
3779 in that case, we still need to signal this like a non-blocking
3780 connection. */
3781 p->status = Qconnect;
3782 if (!FD_ISSET (inch, &connect_wait_mask))
3784 FD_SET (inch, &connect_wait_mask);
3785 num_pending_connects++;
3788 else
3789 #endif
3790 /* A server may have a client filter setting of Qt, but it must
3791 still listen for incoming connects unless it is stopped. */
3792 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3793 || (EQ (p->status, Qlisten) && NILP (p->command)))
3795 FD_SET (inch, &input_wait_mask);
3796 FD_SET (inch, &non_keyboard_wait_mask);
3799 if (inch > max_process_desc)
3800 max_process_desc = inch;
3802 tem = Fplist_member (contact, QCcoding);
3803 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3804 tem = Qnil; /* No error message (too late!). */
3807 /* Setup coding systems for communicating with the network stream. */
3808 struct gcpro gcpro1;
3809 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3810 Lisp_Object coding_systems = Qt;
3811 Lisp_Object args[5], val;
3813 if (!NILP (tem))
3815 val = XCAR (XCDR (tem));
3816 if (CONSP (val))
3817 val = XCAR (val);
3819 else if (!NILP (Vcoding_system_for_read))
3820 val = Vcoding_system_for_read;
3821 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3822 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3823 /* We dare not decode end-of-line format by setting VAL to
3824 Qraw_text, because the existing Emacs Lisp libraries
3825 assume that they receive bare code including a sequene of
3826 CR LF. */
3827 val = Qnil;
3828 else
3830 if (NILP (host) || NILP (service))
3831 coding_systems = Qnil;
3832 else
3834 args[0] = Qopen_network_stream, args[1] = name,
3835 args[2] = buffer, args[3] = host, args[4] = service;
3836 GCPRO1 (proc);
3837 coding_systems = Ffind_operation_coding_system (5, args);
3838 UNGCPRO;
3840 if (CONSP (coding_systems))
3841 val = XCAR (coding_systems);
3842 else if (CONSP (Vdefault_process_coding_system))
3843 val = XCAR (Vdefault_process_coding_system);
3844 else
3845 val = Qnil;
3847 p->decode_coding_system = val;
3849 if (!NILP (tem))
3851 val = XCAR (XCDR (tem));
3852 if (CONSP (val))
3853 val = XCDR (val);
3855 else if (!NILP (Vcoding_system_for_write))
3856 val = Vcoding_system_for_write;
3857 else if (NILP (current_buffer->enable_multibyte_characters))
3858 val = Qnil;
3859 else
3861 if (EQ (coding_systems, Qt))
3863 if (NILP (host) || NILP (service))
3864 coding_systems = Qnil;
3865 else
3867 args[0] = Qopen_network_stream, args[1] = name,
3868 args[2] = buffer, args[3] = host, args[4] = service;
3869 GCPRO1 (proc);
3870 coding_systems = Ffind_operation_coding_system (5, args);
3871 UNGCPRO;
3874 if (CONSP (coding_systems))
3875 val = XCDR (coding_systems);
3876 else if (CONSP (Vdefault_process_coding_system))
3877 val = XCDR (Vdefault_process_coding_system);
3878 else
3879 val = Qnil;
3881 p->encode_coding_system = val;
3883 setup_process_coding_systems (proc);
3885 p->decoding_buf = make_uninit_string (0);
3886 p->decoding_carryover = 0;
3887 p->encoding_buf = make_uninit_string (0);
3889 p->inherit_coding_system_flag
3890 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3892 UNGCPRO;
3893 return proc;
3895 #endif /* HAVE_SOCKETS */
3898 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3900 #ifdef SIOCGIFCONF
3901 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3902 doc: /* Return an alist of all network interfaces and their network address.
3903 Each element is a cons, the car of which is a string containing the
3904 interface name, and the cdr is the network address in internal
3905 format; see the description of ADDRESS in `make-network-process'. */)
3908 struct ifconf ifconf;
3909 struct ifreq *ifreqs = NULL;
3910 int ifaces = 0;
3911 int buf_size, s;
3912 Lisp_Object res;
3914 s = socket (AF_INET, SOCK_STREAM, 0);
3915 if (s < 0)
3916 return Qnil;
3918 again:
3919 ifaces += 25;
3920 buf_size = ifaces * sizeof(ifreqs[0]);
3921 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3922 if (!ifreqs)
3924 close (s);
3925 return Qnil;
3928 ifconf.ifc_len = buf_size;
3929 ifconf.ifc_req = ifreqs;
3930 if (ioctl (s, SIOCGIFCONF, &ifconf))
3932 close (s);
3933 return Qnil;
3936 if (ifconf.ifc_len == buf_size)
3937 goto again;
3939 close (s);
3940 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3942 res = Qnil;
3943 while (--ifaces >= 0)
3945 struct ifreq *ifq = &ifreqs[ifaces];
3946 char namebuf[sizeof (ifq->ifr_name) + 1];
3947 if (ifq->ifr_addr.sa_family != AF_INET)
3948 continue;
3949 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3950 namebuf[sizeof (ifq->ifr_name)] = 0;
3951 res = Fcons (Fcons (build_string (namebuf),
3952 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3953 sizeof (struct sockaddr))),
3954 res);
3957 return res;
3959 #endif /* SIOCGIFCONF */
3961 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3963 struct ifflag_def {
3964 int flag_bit;
3965 const char *flag_sym;
3968 static const struct ifflag_def ifflag_table[] = {
3969 #ifdef IFF_UP
3970 { IFF_UP, "up" },
3971 #endif
3972 #ifdef IFF_BROADCAST
3973 { IFF_BROADCAST, "broadcast" },
3974 #endif
3975 #ifdef IFF_DEBUG
3976 { IFF_DEBUG, "debug" },
3977 #endif
3978 #ifdef IFF_LOOPBACK
3979 { IFF_LOOPBACK, "loopback" },
3980 #endif
3981 #ifdef IFF_POINTOPOINT
3982 { IFF_POINTOPOINT, "pointopoint" },
3983 #endif
3984 #ifdef IFF_RUNNING
3985 { IFF_RUNNING, "running" },
3986 #endif
3987 #ifdef IFF_NOARP
3988 { IFF_NOARP, "noarp" },
3989 #endif
3990 #ifdef IFF_PROMISC
3991 { IFF_PROMISC, "promisc" },
3992 #endif
3993 #ifdef IFF_NOTRAILERS
3994 { IFF_NOTRAILERS, "notrailers" },
3995 #endif
3996 #ifdef IFF_ALLMULTI
3997 { IFF_ALLMULTI, "allmulti" },
3998 #endif
3999 #ifdef IFF_MASTER
4000 { IFF_MASTER, "master" },
4001 #endif
4002 #ifdef IFF_SLAVE
4003 { IFF_SLAVE, "slave" },
4004 #endif
4005 #ifdef IFF_MULTICAST
4006 { IFF_MULTICAST, "multicast" },
4007 #endif
4008 #ifdef IFF_PORTSEL
4009 { IFF_PORTSEL, "portsel" },
4010 #endif
4011 #ifdef IFF_AUTOMEDIA
4012 { IFF_AUTOMEDIA, "automedia" },
4013 #endif
4014 #ifdef IFF_DYNAMIC
4015 { IFF_DYNAMIC, "dynamic" },
4016 #endif
4017 #ifdef IFF_OACTIVE
4018 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
4019 #endif
4020 #ifdef IFF_SIMPLEX
4021 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
4022 #endif
4023 #ifdef IFF_LINK0
4024 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
4025 #endif
4026 #ifdef IFF_LINK1
4027 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
4028 #endif
4029 #ifdef IFF_LINK2
4030 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
4031 #endif
4032 { 0, 0 }
4035 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
4036 doc: /* Return information about network interface named IFNAME.
4037 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4038 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4039 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
4040 FLAGS is the current flags of the interface. */)
4041 (ifname)
4042 Lisp_Object ifname;
4044 struct ifreq rq;
4045 Lisp_Object res = Qnil;
4046 Lisp_Object elt;
4047 int s;
4048 int any = 0;
4050 CHECK_STRING (ifname);
4052 bzero (rq.ifr_name, sizeof rq.ifr_name);
4053 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
4055 s = socket (AF_INET, SOCK_STREAM, 0);
4056 if (s < 0)
4057 return Qnil;
4059 elt = Qnil;
4060 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
4061 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4063 int flags = rq.ifr_flags;
4064 const struct ifflag_def *fp;
4065 int fnum;
4067 any++;
4068 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4070 if (flags & fp->flag_bit)
4072 elt = Fcons (intern (fp->flag_sym), elt);
4073 flags -= fp->flag_bit;
4076 for (fnum = 0; flags && fnum < 32; fnum++)
4078 if (flags & (1 << fnum))
4080 elt = Fcons (make_number (fnum), elt);
4084 #endif
4085 res = Fcons (elt, res);
4087 elt = Qnil;
4088 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4089 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4091 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4092 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4093 int n;
4095 any++;
4096 for (n = 0; n < 6; n++)
4097 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4098 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4100 #endif
4101 res = Fcons (elt, res);
4103 elt = Qnil;
4104 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4105 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4107 any++;
4108 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4109 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4110 #else
4111 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4112 #endif
4114 #endif
4115 res = Fcons (elt, res);
4117 elt = Qnil;
4118 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4119 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4121 any++;
4122 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4124 #endif
4125 res = Fcons (elt, res);
4127 elt = Qnil;
4128 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4129 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4131 any++;
4132 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4134 #endif
4135 res = Fcons (elt, res);
4137 close (s);
4139 return any ? res : Qnil;
4141 #endif
4142 #endif /* HAVE_SOCKETS */
4144 /* Turn off input and output for process PROC. */
4146 void
4147 deactivate_process (proc)
4148 Lisp_Object proc;
4150 register int inchannel, outchannel;
4151 register struct Lisp_Process *p = XPROCESS (proc);
4153 inchannel = p->infd;
4154 outchannel = p->outfd;
4156 #ifdef ADAPTIVE_READ_BUFFERING
4157 if (p->read_output_delay > 0)
4159 if (--process_output_delay_count < 0)
4160 process_output_delay_count = 0;
4161 p->read_output_delay = 0;
4162 p->read_output_skip = 0;
4164 #endif
4166 if (inchannel >= 0)
4168 /* Beware SIGCHLD hereabouts. */
4169 flush_pending_output (inchannel);
4170 emacs_close (inchannel);
4171 if (outchannel >= 0 && outchannel != inchannel)
4172 emacs_close (outchannel);
4174 p->infd = -1;
4175 p->outfd = -1;
4176 #ifdef DATAGRAM_SOCKETS
4177 if (DATAGRAM_CHAN_P (inchannel))
4179 xfree (datagram_address[inchannel].sa);
4180 datagram_address[inchannel].sa = 0;
4181 datagram_address[inchannel].len = 0;
4183 #endif
4184 chan_process[inchannel] = Qnil;
4185 FD_CLR (inchannel, &input_wait_mask);
4186 FD_CLR (inchannel, &non_keyboard_wait_mask);
4187 #ifdef NON_BLOCKING_CONNECT
4188 if (FD_ISSET (inchannel, &connect_wait_mask))
4190 FD_CLR (inchannel, &connect_wait_mask);
4191 if (--num_pending_connects < 0)
4192 abort ();
4194 #endif
4195 if (inchannel == max_process_desc)
4197 int i;
4198 /* We just closed the highest-numbered process input descriptor,
4199 so recompute the highest-numbered one now. */
4200 max_process_desc = 0;
4201 for (i = 0; i < MAXDESC; i++)
4202 if (!NILP (chan_process[i]))
4203 max_process_desc = i;
4208 /* Close all descriptors currently in use for communication
4209 with subprocess. This is used in a newly-forked subprocess
4210 to get rid of irrelevant descriptors. */
4212 void
4213 close_process_descs ()
4215 #ifndef WINDOWSNT
4216 int i;
4217 for (i = 0; i < MAXDESC; i++)
4219 Lisp_Object process;
4220 process = chan_process[i];
4221 if (!NILP (process))
4223 int in = XPROCESS (process)->infd;
4224 int out = XPROCESS (process)->outfd;
4225 if (in >= 0)
4226 emacs_close (in);
4227 if (out >= 0 && in != out)
4228 emacs_close (out);
4231 #endif
4234 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4235 0, 4, 0,
4236 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4237 It is read into the process' buffers or given to their filter functions.
4238 Non-nil arg PROCESS means do not return until some output has been received
4239 from PROCESS.
4241 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4242 and milliseconds to wait; return after that much time whether or not
4243 there is any subprocess output. If SECONDS is a floating point number,
4244 it specifies a fractional number of seconds to wait.
4245 The MILLISEC argument is obsolete and should be avoided.
4247 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4248 from PROCESS, suspending reading output from other processes.
4249 If JUST-THIS-ONE is an integer, don't run any timers either.
4250 Return non-nil if we received any output before the timeout expired. */)
4251 (process, seconds, millisec, just_this_one)
4252 register Lisp_Object process, seconds, millisec, just_this_one;
4254 int secs, usecs = 0;
4256 if (! NILP (process))
4257 CHECK_PROCESS (process);
4258 else
4259 just_this_one = Qnil;
4261 if (!NILP (millisec))
4262 { /* Obsolete calling convention using integers rather than floats. */
4263 CHECK_NUMBER (millisec);
4264 if (NILP (seconds))
4265 seconds = make_float (XINT (millisec) / 1000.0);
4266 else
4268 CHECK_NUMBER (seconds);
4269 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4273 if (!NILP (seconds))
4275 if (INTEGERP (seconds))
4276 secs = XINT (seconds);
4277 else if (FLOATP (seconds))
4279 double timeout = XFLOAT_DATA (seconds);
4280 secs = (int) timeout;
4281 usecs = (int) ((timeout - (double) secs) * 1000000);
4283 else
4284 wrong_type_argument (Qnumberp, seconds);
4286 if (secs < 0 || (secs == 0 && usecs == 0))
4287 secs = -1, usecs = 0;
4289 else
4290 secs = NILP (process) ? -1 : 0;
4292 return
4293 (wait_reading_process_output (secs, usecs, 0, 0,
4294 Qnil,
4295 !NILP (process) ? XPROCESS (process) : NULL,
4296 NILP (just_this_one) ? 0 :
4297 !INTEGERP (just_this_one) ? 1 : -1)
4298 ? Qt : Qnil);
4301 /* Accept a connection for server process SERVER on CHANNEL. */
4303 static int connect_counter = 0;
4305 static void
4306 server_accept_connection (server, channel)
4307 Lisp_Object server;
4308 int channel;
4310 Lisp_Object proc, caller, name, buffer;
4311 Lisp_Object contact, host, service;
4312 struct Lisp_Process *ps= XPROCESS (server);
4313 struct Lisp_Process *p;
4314 int s;
4315 union u_sockaddr {
4316 struct sockaddr sa;
4317 struct sockaddr_in in;
4318 #ifdef AF_INET6
4319 struct sockaddr_in6 in6;
4320 #endif
4321 #ifdef HAVE_LOCAL_SOCKETS
4322 struct sockaddr_un un;
4323 #endif
4324 } saddr;
4325 int len = sizeof saddr;
4327 s = accept (channel, &saddr.sa, &len);
4329 if (s < 0)
4331 int code = errno;
4333 if (code == EAGAIN)
4334 return;
4335 #ifdef EWOULDBLOCK
4336 if (code == EWOULDBLOCK)
4337 return;
4338 #endif
4340 if (!NILP (ps->log))
4341 call3 (ps->log, server, Qnil,
4342 concat3 (build_string ("accept failed with code"),
4343 Fnumber_to_string (make_number (code)),
4344 build_string ("\n")));
4345 return;
4348 connect_counter++;
4350 /* Setup a new process to handle the connection. */
4352 /* Generate a unique identification of the caller, and build contact
4353 information for this process. */
4354 host = Qt;
4355 service = Qnil;
4356 switch (saddr.sa.sa_family)
4358 case AF_INET:
4360 Lisp_Object args[5];
4361 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4362 args[0] = build_string ("%d.%d.%d.%d");
4363 args[1] = make_number (*ip++);
4364 args[2] = make_number (*ip++);
4365 args[3] = make_number (*ip++);
4366 args[4] = make_number (*ip++);
4367 host = Fformat (5, args);
4368 service = make_number (ntohs (saddr.in.sin_port));
4370 args[0] = build_string (" <%s:%d>");
4371 args[1] = host;
4372 args[2] = service;
4373 caller = Fformat (3, args);
4375 break;
4377 #ifdef AF_INET6
4378 case AF_INET6:
4380 Lisp_Object args[9];
4381 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4382 int i;
4383 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4384 for (i = 0; i < 8; i++)
4385 args[i+1] = make_number (ntohs(ip6[i]));
4386 host = Fformat (9, args);
4387 service = make_number (ntohs (saddr.in.sin_port));
4389 args[0] = build_string (" <[%s]:%d>");
4390 args[1] = host;
4391 args[2] = service;
4392 caller = Fformat (3, args);
4394 break;
4395 #endif
4397 #ifdef HAVE_LOCAL_SOCKETS
4398 case AF_LOCAL:
4399 #endif
4400 default:
4401 caller = Fnumber_to_string (make_number (connect_counter));
4402 caller = concat3 (build_string (" <"), caller, build_string (">"));
4403 break;
4406 /* Create a new buffer name for this process if it doesn't have a
4407 filter. The new buffer name is based on the buffer name or
4408 process name of the server process concatenated with the caller
4409 identification. */
4411 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4412 buffer = Qnil;
4413 else
4415 buffer = ps->buffer;
4416 if (!NILP (buffer))
4417 buffer = Fbuffer_name (buffer);
4418 else
4419 buffer = ps->name;
4420 if (!NILP (buffer))
4422 buffer = concat2 (buffer, caller);
4423 buffer = Fget_buffer_create (buffer);
4427 /* Generate a unique name for the new server process. Combine the
4428 server process name with the caller identification. */
4430 name = concat2 (ps->name, caller);
4431 proc = make_process (name);
4433 chan_process[s] = proc;
4435 #ifdef O_NONBLOCK
4436 fcntl (s, F_SETFL, O_NONBLOCK);
4437 #else
4438 #ifdef O_NDELAY
4439 fcntl (s, F_SETFL, O_NDELAY);
4440 #endif
4441 #endif
4443 p = XPROCESS (proc);
4445 /* Build new contact information for this setup. */
4446 contact = Fcopy_sequence (ps->childp);
4447 contact = Fplist_put (contact, QCserver, Qnil);
4448 contact = Fplist_put (contact, QChost, host);
4449 if (!NILP (service))
4450 contact = Fplist_put (contact, QCservice, service);
4451 contact = Fplist_put (contact, QCremote,
4452 conv_sockaddr_to_lisp (&saddr.sa, len));
4453 #ifdef HAVE_GETSOCKNAME
4454 len = sizeof saddr;
4455 if (getsockname (s, &saddr.sa, &len) == 0)
4456 contact = Fplist_put (contact, QClocal,
4457 conv_sockaddr_to_lisp (&saddr.sa, len));
4458 #endif
4460 p->childp = contact;
4461 p->plist = Fcopy_sequence (ps->plist);
4462 p->type = Qnetwork;
4464 p->buffer = buffer;
4465 p->sentinel = ps->sentinel;
4466 p->filter = ps->filter;
4467 p->command = Qnil;
4468 p->pid = 0;
4469 p->infd = s;
4470 p->outfd = s;
4471 p->status = Qrun;
4473 /* Client processes for accepted connections are not stopped initially. */
4474 if (!EQ (p->filter, Qt))
4476 FD_SET (s, &input_wait_mask);
4477 FD_SET (s, &non_keyboard_wait_mask);
4480 if (s > max_process_desc)
4481 max_process_desc = s;
4483 /* Setup coding system for new process based on server process.
4484 This seems to be the proper thing to do, as the coding system
4485 of the new process should reflect the settings at the time the
4486 server socket was opened; not the current settings. */
4488 p->decode_coding_system = ps->decode_coding_system;
4489 p->encode_coding_system = ps->encode_coding_system;
4490 setup_process_coding_systems (proc);
4492 p->decoding_buf = make_uninit_string (0);
4493 p->decoding_carryover = 0;
4494 p->encoding_buf = make_uninit_string (0);
4496 p->inherit_coding_system_flag
4497 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4499 if (!NILP (ps->log))
4500 call3 (ps->log, server, proc,
4501 concat3 (build_string ("accept from "),
4502 (STRINGP (host) ? host : build_string ("-")),
4503 build_string ("\n")));
4505 if (!NILP (p->sentinel))
4506 exec_sentinel (proc,
4507 concat3 (build_string ("open from "),
4508 (STRINGP (host) ? host : build_string ("-")),
4509 build_string ("\n")));
4512 /* This variable is different from waiting_for_input in keyboard.c.
4513 It is used to communicate to a lisp process-filter/sentinel (via the
4514 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4515 for user-input when that process-filter was called.
4516 waiting_for_input cannot be used as that is by definition 0 when
4517 lisp code is being evalled.
4518 This is also used in record_asynch_buffer_change.
4519 For that purpose, this must be 0
4520 when not inside wait_reading_process_output. */
4521 static int waiting_for_user_input_p;
4523 static Lisp_Object
4524 wait_reading_process_output_unwind (data)
4525 Lisp_Object data;
4527 waiting_for_user_input_p = XINT (data);
4528 return Qnil;
4531 /* This is here so breakpoints can be put on it. */
4532 static void
4533 wait_reading_process_output_1 ()
4537 /* Use a wrapper around select to work around a bug in gdb 5.3.
4538 Normally, the wrapper is optimized away by inlining.
4540 If emacs is stopped inside select, the gdb backtrace doesn't
4541 show the function which called select, so it is practically
4542 impossible to step through wait_reading_process_output. */
4544 #ifndef select
4545 static INLINE int
4546 select_wrapper (n, rfd, wfd, xfd, tmo)
4547 int n;
4548 SELECT_TYPE *rfd, *wfd, *xfd;
4549 EMACS_TIME *tmo;
4551 return select (n, rfd, wfd, xfd, tmo);
4553 #define select select_wrapper
4554 #endif
4556 /* Read and dispose of subprocess output while waiting for timeout to
4557 elapse and/or keyboard input to be available.
4559 TIME_LIMIT is:
4560 timeout in seconds, or
4561 zero for no limit, or
4562 -1 means gobble data immediately available but don't wait for any.
4564 MICROSECS is:
4565 an additional duration to wait, measured in microseconds.
4566 If this is nonzero and time_limit is 0, then the timeout
4567 consists of MICROSECS only.
4569 READ_KBD is a lisp value:
4570 0 to ignore keyboard input, or
4571 1 to return when input is available, or
4572 -1 meaning caller will actually read the input, so don't throw to
4573 the quit handler, or
4575 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4576 output that arrives.
4578 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4579 (and gobble terminal input into the buffer if any arrives).
4581 If WAIT_PROC is specified, wait until something arrives from that
4582 process. The return value is true if we read some input from
4583 that process.
4585 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4586 (suspending output from other processes). A negative value
4587 means don't run any timers either.
4589 If WAIT_PROC is specified, then the function returns true if we
4590 received input from that process before the timeout elapsed.
4591 Otherwise, return true if we received input from any process. */
4594 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4595 wait_for_cell, wait_proc, just_wait_proc)
4596 int time_limit, microsecs, read_kbd, do_display;
4597 Lisp_Object wait_for_cell;
4598 struct Lisp_Process *wait_proc;
4599 int just_wait_proc;
4601 register int channel, nfds;
4602 SELECT_TYPE Available;
4603 #ifdef NON_BLOCKING_CONNECT
4604 SELECT_TYPE Connecting;
4605 int check_connect;
4606 #endif
4607 int check_delay, no_avail;
4608 int xerrno;
4609 Lisp_Object proc;
4610 EMACS_TIME timeout, end_time;
4611 int wait_channel = -1;
4612 int got_some_input = 0;
4613 int count = SPECPDL_INDEX ();
4615 FD_ZERO (&Available);
4616 #ifdef NON_BLOCKING_CONNECT
4617 FD_ZERO (&Connecting);
4618 #endif
4620 if (time_limit == 0 && wait_proc && !NILP (Vinhibit_quit)
4621 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4622 message ("Blocking call to accept-process-output with quit inhibited!!");
4624 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4625 if (wait_proc != NULL)
4626 wait_channel = wait_proc->infd;
4628 record_unwind_protect (wait_reading_process_output_unwind,
4629 make_number (waiting_for_user_input_p));
4630 waiting_for_user_input_p = read_kbd;
4632 /* Since we may need to wait several times,
4633 compute the absolute time to return at. */
4634 if (time_limit || microsecs)
4636 EMACS_GET_TIME (end_time);
4637 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4638 EMACS_ADD_TIME (end_time, end_time, timeout);
4641 while (1)
4643 int timeout_reduced_for_timers = 0;
4645 /* If calling from keyboard input, do not quit
4646 since we want to return C-g as an input character.
4647 Otherwise, do pending quit if requested. */
4648 if (read_kbd >= 0)
4649 QUIT;
4650 #ifdef SYNC_INPUT
4651 else
4652 process_pending_signals ();
4653 #endif
4655 /* Exit now if the cell we're waiting for became non-nil. */
4656 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4657 break;
4659 /* Compute time from now till when time limit is up */
4660 /* Exit if already run out */
4661 if (time_limit == -1)
4663 /* -1 specified for timeout means
4664 gobble output available now
4665 but don't wait at all. */
4667 EMACS_SET_SECS_USECS (timeout, 0, 0);
4669 else if (time_limit || microsecs)
4671 EMACS_GET_TIME (timeout);
4672 EMACS_SUB_TIME (timeout, end_time, timeout);
4673 if (EMACS_TIME_NEG_P (timeout))
4674 break;
4676 else
4678 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4681 /* Normally we run timers here.
4682 But not if wait_for_cell; in those cases,
4683 the wait is supposed to be short,
4684 and those callers cannot handle running arbitrary Lisp code here. */
4685 if (NILP (wait_for_cell)
4686 && just_wait_proc >= 0)
4688 EMACS_TIME timer_delay;
4692 int old_timers_run = timers_run;
4693 struct buffer *old_buffer = current_buffer;
4694 Lisp_Object old_window = selected_window;
4696 timer_delay = timer_check (1);
4698 /* If a timer has run, this might have changed buffers
4699 an alike. Make read_key_sequence aware of that. */
4700 if (timers_run != old_timers_run
4701 && (old_buffer != current_buffer
4702 || !EQ (old_window, selected_window))
4703 && waiting_for_user_input_p == -1)
4704 record_asynch_buffer_change ();
4706 if (timers_run != old_timers_run && do_display)
4707 /* We must retry, since a timer may have requeued itself
4708 and that could alter the time_delay. */
4709 redisplay_preserve_echo_area (9);
4710 else
4711 break;
4713 while (!detect_input_pending ());
4715 /* If there is unread keyboard input, also return. */
4716 if (read_kbd != 0
4717 && requeued_events_pending_p ())
4718 break;
4720 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4722 EMACS_TIME difference;
4723 EMACS_SUB_TIME (difference, timer_delay, timeout);
4724 if (EMACS_TIME_NEG_P (difference))
4726 timeout = timer_delay;
4727 timeout_reduced_for_timers = 1;
4730 /* If time_limit is -1, we are not going to wait at all. */
4731 else if (time_limit != -1)
4733 /* This is so a breakpoint can be put here. */
4734 wait_reading_process_output_1 ();
4738 /* Cause C-g and alarm signals to take immediate action,
4739 and cause input available signals to zero out timeout.
4741 It is important that we do this before checking for process
4742 activity. If we get a SIGCHLD after the explicit checks for
4743 process activity, timeout is the only way we will know. */
4744 if (read_kbd < 0)
4745 set_waiting_for_input (&timeout);
4747 /* If status of something has changed, and no input is
4748 available, notify the user of the change right away. After
4749 this explicit check, we'll let the SIGCHLD handler zap
4750 timeout to get our attention. */
4751 if (update_tick != process_tick)
4753 SELECT_TYPE Atemp;
4754 #ifdef NON_BLOCKING_CONNECT
4755 SELECT_TYPE Ctemp;
4756 #endif
4758 Atemp = input_wait_mask;
4759 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4761 EMACS_SET_SECS_USECS (timeout, 0, 0);
4762 if ((select (max (max (max_process_desc, max_keyboard_desc),
4763 max_gpm_desc) + 1,
4764 &Atemp,
4765 #ifdef NON_BLOCKING_CONNECT
4766 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4767 #else
4768 (SELECT_TYPE *)0,
4769 #endif
4770 (SELECT_TYPE *)0, &timeout)
4771 <= 0))
4773 /* It's okay for us to do this and then continue with
4774 the loop, since timeout has already been zeroed out. */
4775 clear_waiting_for_input ();
4776 status_notify (NULL);
4777 if (do_display) redisplay_preserve_echo_area (13);
4781 /* Don't wait for output from a non-running process. Just
4782 read whatever data has already been received. */
4783 if (wait_proc && wait_proc->raw_status_new)
4784 update_status (wait_proc);
4785 if (wait_proc
4786 && ! EQ (wait_proc->status, Qrun)
4787 && ! EQ (wait_proc->status, Qconnect))
4789 int nread, total_nread = 0;
4791 clear_waiting_for_input ();
4792 XSETPROCESS (proc, wait_proc);
4794 /* Read data from the process, until we exhaust it. */
4795 while (wait_proc->infd >= 0)
4797 nread = read_process_output (proc, wait_proc->infd);
4799 if (nread == 0)
4800 break;
4802 if (0 < nread)
4804 total_nread += nread;
4805 got_some_input = 1;
4807 #ifdef EIO
4808 else if (nread == -1 && EIO == errno)
4809 break;
4810 #endif
4811 #ifdef EAGAIN
4812 else if (nread == -1 && EAGAIN == errno)
4813 break;
4814 #endif
4815 #ifdef EWOULDBLOCK
4816 else if (nread == -1 && EWOULDBLOCK == errno)
4817 break;
4818 #endif
4820 if (total_nread > 0 && do_display)
4821 redisplay_preserve_echo_area (10);
4823 break;
4826 /* Wait till there is something to do */
4828 if (wait_proc && just_wait_proc)
4830 if (wait_proc->infd < 0) /* Terminated */
4831 break;
4832 FD_SET (wait_proc->infd, &Available);
4833 check_delay = 0;
4834 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4836 else if (!NILP (wait_for_cell))
4838 Available = non_process_wait_mask;
4839 check_delay = 0;
4840 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4842 else
4844 if (! read_kbd)
4845 Available = non_keyboard_wait_mask;
4846 else
4847 Available = input_wait_mask;
4848 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4849 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4852 /* If frame size has changed or the window is newly mapped,
4853 redisplay now, before we start to wait. There is a race
4854 condition here; if a SIGIO arrives between now and the select
4855 and indicates that a frame is trashed, the select may block
4856 displaying a trashed screen. */
4857 if (frame_garbaged && do_display)
4859 clear_waiting_for_input ();
4860 redisplay_preserve_echo_area (11);
4861 if (read_kbd < 0)
4862 set_waiting_for_input (&timeout);
4865 no_avail = 0;
4866 if (read_kbd && detect_input_pending ())
4868 nfds = 0;
4869 no_avail = 1;
4871 else
4873 #ifdef NON_BLOCKING_CONNECT
4874 if (check_connect)
4875 Connecting = connect_wait_mask;
4876 #endif
4878 #ifdef ADAPTIVE_READ_BUFFERING
4879 /* Set the timeout for adaptive read buffering if any
4880 process has non-zero read_output_skip and non-zero
4881 read_output_delay, and we are not reading output for a
4882 specific wait_channel. It is not executed if
4883 Vprocess_adaptive_read_buffering is nil. */
4884 if (process_output_skip && check_delay > 0)
4886 int usecs = EMACS_USECS (timeout);
4887 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4888 usecs = READ_OUTPUT_DELAY_MAX;
4889 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4891 proc = chan_process[channel];
4892 if (NILP (proc))
4893 continue;
4894 /* Find minimum non-zero read_output_delay among the
4895 processes with non-zero read_output_skip. */
4896 if (XPROCESS (proc)->read_output_delay > 0)
4898 check_delay--;
4899 if (!XPROCESS (proc)->read_output_skip)
4900 continue;
4901 FD_CLR (channel, &Available);
4902 XPROCESS (proc)->read_output_skip = 0;
4903 if (XPROCESS (proc)->read_output_delay < usecs)
4904 usecs = XPROCESS (proc)->read_output_delay;
4907 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4908 process_output_skip = 0;
4910 #endif
4911 #if defined (USE_GTK) || defined (HAVE_GCONF)
4912 nfds = xg_select
4913 #elif defined (HAVE_NS)
4914 nfds = ns_select
4915 #else
4916 nfds = select
4917 #endif
4918 (max (max (max_process_desc, max_keyboard_desc),
4919 max_gpm_desc) + 1,
4920 &Available,
4921 #ifdef NON_BLOCKING_CONNECT
4922 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4923 #else
4924 (SELECT_TYPE *)0,
4925 #endif
4926 (SELECT_TYPE *)0, &timeout);
4929 xerrno = errno;
4931 /* Make C-g and alarm signals set flags again */
4932 clear_waiting_for_input ();
4934 /* If we woke up due to SIGWINCH, actually change size now. */
4935 do_pending_window_change (0);
4937 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4938 /* We wanted the full specified time, so return now. */
4939 break;
4940 if (nfds < 0)
4942 if (xerrno == EINTR)
4943 no_avail = 1;
4944 else if (xerrno == EBADF)
4946 #ifdef AIX
4947 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4948 the child's closure of the pts gives the parent a SIGHUP, and
4949 the ptc file descriptor is automatically closed,
4950 yielding EBADF here or at select() call above.
4951 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4952 in m/ibmrt-aix.h), and here we just ignore the select error.
4953 Cleanup occurs c/o status_notify after SIGCLD. */
4954 no_avail = 1; /* Cannot depend on values returned */
4955 #else
4956 abort ();
4957 #endif
4959 else
4960 error ("select error: %s", emacs_strerror (xerrno));
4963 if (no_avail)
4965 FD_ZERO (&Available);
4966 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4969 #if 0 /* When polling is used, interrupt_input is 0,
4970 so get_input_pending should read the input.
4971 So this should not be needed. */
4972 /* If we are using polling for input,
4973 and we see input available, make it get read now.
4974 Otherwise it might not actually get read for a second.
4975 And on hpux, since we turn off polling in wait_reading_process_output,
4976 it might never get read at all if we don't spend much time
4977 outside of wait_reading_process_output. */
4978 if (read_kbd && interrupt_input
4979 && keyboard_bit_set (&Available)
4980 && input_polling_used ())
4981 kill (getpid (), SIGALRM);
4982 #endif
4984 /* Check for keyboard input */
4985 /* If there is any, return immediately
4986 to give it higher priority than subprocesses */
4988 if (read_kbd != 0)
4990 int old_timers_run = timers_run;
4991 struct buffer *old_buffer = current_buffer;
4992 Lisp_Object old_window = selected_window;
4993 int leave = 0;
4995 if (detect_input_pending_run_timers (do_display))
4997 swallow_events (do_display);
4998 if (detect_input_pending_run_timers (do_display))
4999 leave = 1;
5002 /* If a timer has run, this might have changed buffers
5003 an alike. Make read_key_sequence aware of that. */
5004 if (timers_run != old_timers_run
5005 && waiting_for_user_input_p == -1
5006 && (old_buffer != current_buffer
5007 || !EQ (old_window, selected_window)))
5008 record_asynch_buffer_change ();
5010 if (leave)
5011 break;
5014 /* If there is unread keyboard input, also return. */
5015 if (read_kbd != 0
5016 && requeued_events_pending_p ())
5017 break;
5019 /* If we are not checking for keyboard input now,
5020 do process events (but don't run any timers).
5021 This is so that X events will be processed.
5022 Otherwise they may have to wait until polling takes place.
5023 That would causes delays in pasting selections, for example.
5025 (We used to do this only if wait_for_cell.) */
5026 if (read_kbd == 0 && detect_input_pending ())
5028 swallow_events (do_display);
5029 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5030 if (detect_input_pending ())
5031 break;
5032 #endif
5035 /* Exit now if the cell we're waiting for became non-nil. */
5036 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5037 break;
5039 #ifdef SIGIO
5040 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5041 go read it. This can happen with X on BSD after logging out.
5042 In that case, there really is no input and no SIGIO,
5043 but select says there is input. */
5045 if (read_kbd && interrupt_input
5046 && keyboard_bit_set (&Available) && ! noninteractive)
5047 kill (getpid (), SIGIO);
5048 #endif
5050 if (! wait_proc)
5051 got_some_input |= nfds > 0;
5053 /* If checking input just got us a size-change event from X,
5054 obey it now if we should. */
5055 if (read_kbd || ! NILP (wait_for_cell))
5056 do_pending_window_change (0);
5058 /* Check for data from a process. */
5059 if (no_avail || nfds == 0)
5060 continue;
5062 /* Really FIRST_PROC_DESC should be 0 on Unix,
5063 but this is safer in the short run. */
5064 for (channel = 0; channel <= max_process_desc; channel++)
5066 if (FD_ISSET (channel, &Available)
5067 && FD_ISSET (channel, &non_keyboard_wait_mask))
5069 int nread;
5071 /* If waiting for this channel, arrange to return as
5072 soon as no more input to be processed. No more
5073 waiting. */
5074 if (wait_channel == channel)
5076 wait_channel = -1;
5077 time_limit = -1;
5078 got_some_input = 1;
5080 proc = chan_process[channel];
5081 if (NILP (proc))
5082 continue;
5084 /* If this is a server stream socket, accept connection. */
5085 if (EQ (XPROCESS (proc)->status, Qlisten))
5087 server_accept_connection (proc, channel);
5088 continue;
5091 /* Read data from the process, starting with our
5092 buffered-ahead character if we have one. */
5094 nread = read_process_output (proc, channel);
5095 if (nread > 0)
5097 /* Since read_process_output can run a filter,
5098 which can call accept-process-output,
5099 don't try to read from any other processes
5100 before doing the select again. */
5101 FD_ZERO (&Available);
5103 if (do_display)
5104 redisplay_preserve_echo_area (12);
5106 #ifdef EWOULDBLOCK
5107 else if (nread == -1 && errno == EWOULDBLOCK)
5109 #endif
5110 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5111 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5112 #ifdef O_NONBLOCK
5113 else if (nread == -1 && errno == EAGAIN)
5115 #else
5116 #ifdef O_NDELAY
5117 else if (nread == -1 && errno == EAGAIN)
5119 /* Note that we cannot distinguish between no input
5120 available now and a closed pipe.
5121 With luck, a closed pipe will be accompanied by
5122 subprocess termination and SIGCHLD. */
5123 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5125 #endif /* O_NDELAY */
5126 #endif /* O_NONBLOCK */
5127 #ifdef HAVE_PTYS
5128 /* On some OSs with ptys, when the process on one end of
5129 a pty exits, the other end gets an error reading with
5130 errno = EIO instead of getting an EOF (0 bytes read).
5131 Therefore, if we get an error reading and errno =
5132 EIO, just continue, because the child process has
5133 exited and should clean itself up soon (e.g. when we
5134 get a SIGCHLD).
5136 However, it has been known to happen that the SIGCHLD
5137 got lost. So raise the signal again just in case.
5138 It can't hurt. */
5139 else if (nread == -1 && errno == EIO)
5141 /* Clear the descriptor now, so we only raise the
5142 signal once. Don't do this if `process' is only
5143 a pty. */
5144 if (XPROCESS (proc)->pid != -2)
5146 FD_CLR (channel, &input_wait_mask);
5147 FD_CLR (channel, &non_keyboard_wait_mask);
5149 kill (getpid (), SIGCHLD);
5152 #endif /* HAVE_PTYS */
5153 /* If we can detect process termination, don't consider the process
5154 gone just because its pipe is closed. */
5155 #ifdef SIGCHLD
5156 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5158 #endif
5159 else
5161 /* Preserve status of processes already terminated. */
5162 XPROCESS (proc)->tick = ++process_tick;
5163 deactivate_process (proc);
5164 if (XPROCESS (proc)->raw_status_new)
5165 update_status (XPROCESS (proc));
5166 if (EQ (XPROCESS (proc)->status, Qrun))
5167 XPROCESS (proc)->status
5168 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5171 #ifdef NON_BLOCKING_CONNECT
5172 if (check_connect && FD_ISSET (channel, &Connecting)
5173 && FD_ISSET (channel, &connect_wait_mask))
5175 struct Lisp_Process *p;
5177 FD_CLR (channel, &connect_wait_mask);
5178 if (--num_pending_connects < 0)
5179 abort ();
5181 proc = chan_process[channel];
5182 if (NILP (proc))
5183 continue;
5185 p = XPROCESS (proc);
5187 #ifdef GNU_LINUX
5188 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5189 So only use it on systems where it is known to work. */
5191 int xlen = sizeof(xerrno);
5192 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5193 xerrno = errno;
5195 #else
5197 struct sockaddr pname;
5198 int pnamelen = sizeof(pname);
5200 /* If connection failed, getpeername will fail. */
5201 xerrno = 0;
5202 if (getpeername(channel, &pname, &pnamelen) < 0)
5204 /* Obtain connect failure code through error slippage. */
5205 char dummy;
5206 xerrno = errno;
5207 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5208 xerrno = errno;
5211 #endif
5212 if (xerrno)
5214 p->tick = ++process_tick;
5215 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5216 deactivate_process (proc);
5218 else
5220 p->status = Qrun;
5221 /* Execute the sentinel here. If we had relied on
5222 status_notify to do it later, it will read input
5223 from the process before calling the sentinel. */
5224 exec_sentinel (proc, build_string ("open\n"));
5225 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5227 FD_SET (p->infd, &input_wait_mask);
5228 FD_SET (p->infd, &non_keyboard_wait_mask);
5232 #endif /* NON_BLOCKING_CONNECT */
5233 } /* end for each file descriptor */
5234 } /* end while exit conditions not met */
5236 unbind_to (count, Qnil);
5238 /* If calling from keyboard input, do not quit
5239 since we want to return C-g as an input character.
5240 Otherwise, do pending quit if requested. */
5241 if (read_kbd >= 0)
5243 /* Prevent input_pending from remaining set if we quit. */
5244 clear_input_pending ();
5245 QUIT;
5248 return got_some_input;
5251 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5253 static Lisp_Object
5254 read_process_output_call (fun_and_args)
5255 Lisp_Object fun_and_args;
5257 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5260 static Lisp_Object
5261 read_process_output_error_handler (error)
5262 Lisp_Object error;
5264 cmd_error_internal (error, "error in process filter: ");
5265 Vinhibit_quit = Qt;
5266 update_echo_area ();
5267 Fsleep_for (make_number (2), Qnil);
5268 return Qt;
5271 /* Read pending output from the process channel,
5272 starting with our buffered-ahead character if we have one.
5273 Yield number of decoded characters read.
5275 This function reads at most 4096 characters.
5276 If you want to read all available subprocess output,
5277 you must call it repeatedly until it returns zero.
5279 The characters read are decoded according to PROC's coding-system
5280 for decoding. */
5282 static int
5283 read_process_output (proc, channel)
5284 Lisp_Object proc;
5285 register int channel;
5287 register int nbytes;
5288 char *chars;
5289 register Lisp_Object outstream;
5290 register struct Lisp_Process *p = XPROCESS (proc);
5291 register int opoint;
5292 struct coding_system *coding = proc_decode_coding_system[channel];
5293 int carryover = p->decoding_carryover;
5294 int readmax = 4096;
5295 int count = SPECPDL_INDEX ();
5296 Lisp_Object odeactivate;
5298 chars = (char *) alloca (carryover + readmax);
5299 if (carryover)
5300 /* See the comment above. */
5301 bcopy (SDATA (p->decoding_buf), chars, carryover);
5303 #ifdef DATAGRAM_SOCKETS
5304 /* We have a working select, so proc_buffered_char is always -1. */
5305 if (DATAGRAM_CHAN_P (channel))
5307 int len = datagram_address[channel].len;
5308 nbytes = recvfrom (channel, chars + carryover, readmax,
5309 0, datagram_address[channel].sa, &len);
5311 else
5312 #endif
5313 if (proc_buffered_char[channel] < 0)
5315 nbytes = emacs_read (channel, chars + carryover, readmax);
5316 #ifdef ADAPTIVE_READ_BUFFERING
5317 if (nbytes > 0 && p->adaptive_read_buffering)
5319 int delay = p->read_output_delay;
5320 if (nbytes < 256)
5322 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5324 if (delay == 0)
5325 process_output_delay_count++;
5326 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5329 else if (delay > 0 && (nbytes == readmax))
5331 delay -= READ_OUTPUT_DELAY_INCREMENT;
5332 if (delay == 0)
5333 process_output_delay_count--;
5335 p->read_output_delay = delay;
5336 if (delay)
5338 p->read_output_skip = 1;
5339 process_output_skip = 1;
5342 #endif
5344 else
5346 chars[carryover] = proc_buffered_char[channel];
5347 proc_buffered_char[channel] = -1;
5348 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5349 if (nbytes < 0)
5350 nbytes = 1;
5351 else
5352 nbytes = nbytes + 1;
5355 p->decoding_carryover = 0;
5357 /* At this point, NBYTES holds number of bytes just received
5358 (including the one in proc_buffered_char[channel]). */
5359 if (nbytes <= 0)
5361 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5362 return nbytes;
5363 coding->mode |= CODING_MODE_LAST_BLOCK;
5366 /* Now set NBYTES how many bytes we must decode. */
5367 nbytes += carryover;
5369 odeactivate = Vdeactivate_mark;
5370 /* There's no good reason to let process filters change the current
5371 buffer, and many callers of accept-process-output, sit-for, and
5372 friends don't expect current-buffer to be changed from under them. */
5373 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5375 /* Read and dispose of the process output. */
5376 outstream = p->filter;
5377 if (!NILP (outstream))
5379 Lisp_Object obuffer, okeymap;
5380 Lisp_Object text;
5381 int outer_running_asynch_code = running_asynch_code;
5382 int waiting = waiting_for_user_input_p;
5384 /* No need to gcpro these, because all we do with them later
5385 is test them for EQness, and none of them should be a string. */
5386 XSETBUFFER (obuffer, current_buffer);
5387 okeymap = current_buffer->keymap;
5389 /* We inhibit quit here instead of just catching it so that
5390 hitting ^G when a filter happens to be running won't screw
5391 it up. */
5392 specbind (Qinhibit_quit, Qt);
5393 specbind (Qlast_nonmenu_event, Qt);
5395 /* In case we get recursively called,
5396 and we already saved the match data nonrecursively,
5397 save the same match data in safely recursive fashion. */
5398 if (outer_running_asynch_code)
5400 Lisp_Object tem;
5401 /* Don't clobber the CURRENT match data, either! */
5402 tem = Fmatch_data (Qnil, Qnil, Qnil);
5403 restore_search_regs ();
5404 record_unwind_save_match_data ();
5405 Fset_match_data (tem, Qt);
5408 /* For speed, if a search happens within this code,
5409 save the match data in a special nonrecursive fashion. */
5410 running_asynch_code = 1;
5412 decode_coding_c_string (coding, chars, nbytes, Qt);
5413 text = coding->dst_object;
5414 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5415 /* A new coding system might be found. */
5416 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5418 p->decode_coding_system = Vlast_coding_system_used;
5420 /* Don't call setup_coding_system for
5421 proc_decode_coding_system[channel] here. It is done in
5422 detect_coding called via decode_coding above. */
5424 /* If a coding system for encoding is not yet decided, we set
5425 it as the same as coding-system for decoding.
5427 But, before doing that we must check if
5428 proc_encode_coding_system[p->outfd] surely points to a
5429 valid memory because p->outfd will be changed once EOF is
5430 sent to the process. */
5431 if (NILP (p->encode_coding_system)
5432 && proc_encode_coding_system[p->outfd])
5434 p->encode_coding_system
5435 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5436 setup_coding_system (p->encode_coding_system,
5437 proc_encode_coding_system[p->outfd]);
5441 if (coding->carryover_bytes > 0)
5443 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5444 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5445 bcopy (coding->carryover, SDATA (p->decoding_buf),
5446 coding->carryover_bytes);
5447 p->decoding_carryover = coding->carryover_bytes;
5449 if (SBYTES (text) > 0)
5450 internal_condition_case_1 (read_process_output_call,
5451 Fcons (outstream,
5452 Fcons (proc, Fcons (text, Qnil))),
5453 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5454 read_process_output_error_handler);
5456 /* If we saved the match data nonrecursively, restore it now. */
5457 restore_search_regs ();
5458 running_asynch_code = outer_running_asynch_code;
5460 /* Restore waiting_for_user_input_p as it was
5461 when we were called, in case the filter clobbered it. */
5462 waiting_for_user_input_p = waiting;
5464 #if 0 /* Call record_asynch_buffer_change unconditionally,
5465 because we might have changed minor modes or other things
5466 that affect key bindings. */
5467 if (! EQ (Fcurrent_buffer (), obuffer)
5468 || ! EQ (current_buffer->keymap, okeymap))
5469 #endif
5470 /* But do it only if the caller is actually going to read events.
5471 Otherwise there's no need to make him wake up, and it could
5472 cause trouble (for example it would make sit_for return). */
5473 if (waiting_for_user_input_p == -1)
5474 record_asynch_buffer_change ();
5477 /* If no filter, write into buffer if it isn't dead. */
5478 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5480 Lisp_Object old_read_only;
5481 int old_begv, old_zv;
5482 int old_begv_byte, old_zv_byte;
5483 int before, before_byte;
5484 int opoint_byte;
5485 Lisp_Object text;
5486 struct buffer *b;
5488 Fset_buffer (p->buffer);
5489 opoint = PT;
5490 opoint_byte = PT_BYTE;
5491 old_read_only = current_buffer->read_only;
5492 old_begv = BEGV;
5493 old_zv = ZV;
5494 old_begv_byte = BEGV_BYTE;
5495 old_zv_byte = ZV_BYTE;
5497 current_buffer->read_only = Qnil;
5499 /* Insert new output into buffer
5500 at the current end-of-output marker,
5501 thus preserving logical ordering of input and output. */
5502 if (XMARKER (p->mark)->buffer)
5503 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5504 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5505 ZV_BYTE));
5506 else
5507 SET_PT_BOTH (ZV, ZV_BYTE);
5508 before = PT;
5509 before_byte = PT_BYTE;
5511 /* If the output marker is outside of the visible region, save
5512 the restriction and widen. */
5513 if (! (BEGV <= PT && PT <= ZV))
5514 Fwiden ();
5516 decode_coding_c_string (coding, chars, nbytes, Qt);
5517 text = coding->dst_object;
5518 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5519 /* A new coding system might be found. See the comment in the
5520 similar code in the previous `if' block. */
5521 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5523 p->decode_coding_system = Vlast_coding_system_used;
5524 if (NILP (p->encode_coding_system)
5525 && proc_encode_coding_system[p->outfd])
5527 p->encode_coding_system
5528 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5529 setup_coding_system (p->encode_coding_system,
5530 proc_encode_coding_system[p->outfd]);
5533 if (coding->carryover_bytes > 0)
5535 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5536 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5537 bcopy (coding->carryover, SDATA (p->decoding_buf),
5538 coding->carryover_bytes);
5539 p->decoding_carryover = coding->carryover_bytes;
5541 /* Adjust the multibyteness of TEXT to that of the buffer. */
5542 if (NILP (current_buffer->enable_multibyte_characters)
5543 != ! STRING_MULTIBYTE (text))
5544 text = (STRING_MULTIBYTE (text)
5545 ? Fstring_as_unibyte (text)
5546 : Fstring_to_multibyte (text));
5547 /* Insert before markers in case we are inserting where
5548 the buffer's mark is, and the user's next command is Meta-y. */
5549 insert_from_string_before_markers (text, 0, 0,
5550 SCHARS (text), SBYTES (text), 0);
5552 /* Make sure the process marker's position is valid when the
5553 process buffer is changed in the signal_after_change above.
5554 W3 is known to do that. */
5555 if (BUFFERP (p->buffer)
5556 && (b = XBUFFER (p->buffer), b != current_buffer))
5557 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5558 else
5559 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5561 update_mode_lines++;
5563 /* Make sure opoint and the old restrictions
5564 float ahead of any new text just as point would. */
5565 if (opoint >= before)
5567 opoint += PT - before;
5568 opoint_byte += PT_BYTE - before_byte;
5570 if (old_begv > before)
5572 old_begv += PT - before;
5573 old_begv_byte += PT_BYTE - before_byte;
5575 if (old_zv >= before)
5577 old_zv += PT - before;
5578 old_zv_byte += PT_BYTE - before_byte;
5581 /* If the restriction isn't what it should be, set it. */
5582 if (old_begv != BEGV || old_zv != ZV)
5583 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5586 current_buffer->read_only = old_read_only;
5587 SET_PT_BOTH (opoint, opoint_byte);
5589 /* Handling the process output should not deactivate the mark. */
5590 Vdeactivate_mark = odeactivate;
5592 unbind_to (count, Qnil);
5593 return nbytes;
5596 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5597 0, 0, 0,
5598 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5599 This is intended for use by asynchronous process output filters and sentinels. */)
5602 return (waiting_for_user_input_p ? Qt : Qnil);
5605 /* Sending data to subprocess */
5607 jmp_buf send_process_frame;
5608 Lisp_Object process_sent_to;
5610 SIGTYPE
5611 send_process_trap ()
5613 SIGNAL_THREAD_CHECK (SIGPIPE);
5614 sigunblock (sigmask (SIGPIPE));
5615 longjmp (send_process_frame, 1);
5618 /* Send some data to process PROC.
5619 BUF is the beginning of the data; LEN is the number of characters.
5620 OBJECT is the Lisp object that the data comes from. If OBJECT is
5621 nil or t, it means that the data comes from C string.
5623 If OBJECT is not nil, the data is encoded by PROC's coding-system
5624 for encoding before it is sent.
5626 This function can evaluate Lisp code and can garbage collect. */
5628 static void
5629 send_process (proc, buf, len, object)
5630 volatile Lisp_Object proc;
5631 unsigned char *volatile buf;
5632 volatile int len;
5633 volatile Lisp_Object object;
5635 /* Use volatile to protect variables from being clobbered by longjmp. */
5636 struct Lisp_Process *p = XPROCESS (proc);
5637 int rv;
5638 struct coding_system *coding;
5639 struct gcpro gcpro1;
5640 SIGTYPE (*volatile old_sigpipe) ();
5642 GCPRO1 (object);
5644 if (p->raw_status_new)
5645 update_status (p);
5646 if (! EQ (p->status, Qrun))
5647 error ("Process %s not running", SDATA (p->name));
5648 if (p->outfd < 0)
5649 error ("Output file descriptor of %s is closed", SDATA (p->name));
5651 coding = proc_encode_coding_system[p->outfd];
5652 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5654 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5655 || (BUFFERP (object)
5656 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5657 || EQ (object, Qt))
5659 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5660 /* The coding system for encoding was changed to raw-text
5661 because we sent a unibyte text previously. Now we are
5662 sending a multibyte text, thus we must encode it by the
5663 original coding system specified for the current process. */
5664 setup_coding_system (p->encode_coding_system, coding);
5665 coding->src_multibyte = 1;
5667 else
5669 /* For sending a unibyte text, character code conversion should
5670 not take place but EOL conversion should. So, setup raw-text
5671 or one of the subsidiary if we have not yet done it. */
5672 if (CODING_REQUIRE_ENCODING (coding))
5674 if (CODING_REQUIRE_FLUSHING (coding))
5676 /* But, before changing the coding, we must flush out data. */
5677 coding->mode |= CODING_MODE_LAST_BLOCK;
5678 send_process (proc, "", 0, Qt);
5679 coding->mode &= CODING_MODE_LAST_BLOCK;
5681 setup_coding_system (raw_text_coding_system
5682 (Vlast_coding_system_used),
5683 coding);
5684 coding->src_multibyte = 0;
5687 coding->dst_multibyte = 0;
5689 if (CODING_REQUIRE_ENCODING (coding))
5691 coding->dst_object = Qt;
5692 if (BUFFERP (object))
5694 int from_byte, from, to;
5695 int save_pt, save_pt_byte;
5696 struct buffer *cur = current_buffer;
5698 set_buffer_internal (XBUFFER (object));
5699 save_pt = PT, save_pt_byte = PT_BYTE;
5701 from_byte = PTR_BYTE_POS (buf);
5702 from = BYTE_TO_CHAR (from_byte);
5703 to = BYTE_TO_CHAR (from_byte + len);
5704 TEMP_SET_PT_BOTH (from, from_byte);
5705 encode_coding_object (coding, object, from, from_byte,
5706 to, from_byte + len, Qt);
5707 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5708 set_buffer_internal (cur);
5710 else if (STRINGP (object))
5712 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5713 SBYTES (object), Qt);
5715 else
5717 coding->dst_object = make_unibyte_string (buf, len);
5718 coding->produced = len;
5721 len = coding->produced;
5722 object = coding->dst_object;
5723 buf = SDATA (object);
5726 if (pty_max_bytes == 0)
5728 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5729 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5730 if (pty_max_bytes < 0)
5731 pty_max_bytes = 250;
5732 #else
5733 pty_max_bytes = 250;
5734 #endif
5735 /* Deduct one, to leave space for the eof. */
5736 pty_max_bytes--;
5739 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5740 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5741 when returning with longjmp despite being declared volatile. */
5742 if (!setjmp (send_process_frame))
5744 process_sent_to = proc;
5745 while (len > 0)
5747 int this = len;
5749 /* Send this batch, using one or more write calls. */
5750 while (this > 0)
5752 int outfd = p->outfd;
5753 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5754 #ifdef DATAGRAM_SOCKETS
5755 if (DATAGRAM_CHAN_P (outfd))
5757 rv = sendto (outfd, (char *) buf, this,
5758 0, datagram_address[outfd].sa,
5759 datagram_address[outfd].len);
5760 if (rv < 0 && errno == EMSGSIZE)
5762 signal (SIGPIPE, old_sigpipe);
5763 report_file_error ("sending datagram",
5764 Fcons (proc, Qnil));
5767 else
5768 #endif
5770 rv = emacs_write (outfd, (char *) buf, this);
5771 #ifdef ADAPTIVE_READ_BUFFERING
5772 if (p->read_output_delay > 0
5773 && p->adaptive_read_buffering == 1)
5775 p->read_output_delay = 0;
5776 process_output_delay_count--;
5777 p->read_output_skip = 0;
5779 #endif
5781 signal (SIGPIPE, old_sigpipe);
5783 if (rv < 0)
5785 if (0
5786 #ifdef EWOULDBLOCK
5787 || errno == EWOULDBLOCK
5788 #endif
5789 #ifdef EAGAIN
5790 || errno == EAGAIN
5791 #endif
5793 /* Buffer is full. Wait, accepting input;
5794 that may allow the program
5795 to finish doing output and read more. */
5797 int offset = 0;
5799 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5800 /* A gross hack to work around a bug in FreeBSD.
5801 In the following sequence, read(2) returns
5802 bogus data:
5804 write(2) 1022 bytes
5805 write(2) 954 bytes, get EAGAIN
5806 read(2) 1024 bytes in process_read_output
5807 read(2) 11 bytes in process_read_output
5809 That is, read(2) returns more bytes than have
5810 ever been written successfully. The 1033 bytes
5811 read are the 1022 bytes written successfully
5812 after processing (for example with CRs added if
5813 the terminal is set up that way which it is
5814 here). The same bytes will be seen again in a
5815 later read(2), without the CRs. */
5817 if (errno == EAGAIN)
5819 int flags = FWRITE;
5820 ioctl (p->outfd, TIOCFLUSH, &flags);
5822 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5824 /* Running filters might relocate buffers or strings.
5825 Arrange to relocate BUF. */
5826 if (BUFFERP (object))
5827 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5828 else if (STRINGP (object))
5829 offset = buf - SDATA (object);
5831 #ifdef EMACS_HAS_USECS
5832 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5833 #else
5834 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5835 #endif
5837 if (BUFFERP (object))
5838 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5839 else if (STRINGP (object))
5840 buf = offset + SDATA (object);
5842 rv = 0;
5844 else
5845 /* This is a real error. */
5846 report_file_error ("writing to process", Fcons (proc, Qnil));
5848 buf += rv;
5849 len -= rv;
5850 this -= rv;
5854 else
5856 signal (SIGPIPE, old_sigpipe);
5857 proc = process_sent_to;
5858 p = XPROCESS (proc);
5859 p->raw_status_new = 0;
5860 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5861 p->tick = ++process_tick;
5862 deactivate_process (proc);
5863 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5866 UNGCPRO;
5869 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5870 3, 3, 0,
5871 doc: /* Send current contents of region as input to PROCESS.
5872 PROCESS may be a process, a buffer, the name of a process or buffer, or
5873 nil, indicating the current buffer's process.
5874 Called from program, takes three arguments, PROCESS, START and END.
5875 If the region is more than 500 characters long,
5876 it is sent in several bunches. This may happen even for shorter regions.
5877 Output from processes can arrive in between bunches. */)
5878 (process, start, end)
5879 Lisp_Object process, start, end;
5881 Lisp_Object proc;
5882 int start1, end1;
5884 proc = get_process (process);
5885 validate_region (&start, &end);
5887 if (XINT (start) < GPT && XINT (end) > GPT)
5888 move_gap (XINT (start));
5890 start1 = CHAR_TO_BYTE (XINT (start));
5891 end1 = CHAR_TO_BYTE (XINT (end));
5892 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5893 Fcurrent_buffer ());
5895 return Qnil;
5898 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5899 2, 2, 0,
5900 doc: /* Send PROCESS the contents of STRING as input.
5901 PROCESS may be a process, a buffer, the name of a process or buffer, or
5902 nil, indicating the current buffer's process.
5903 If STRING is more than 500 characters long,
5904 it is sent in several bunches. This may happen even for shorter strings.
5905 Output from processes can arrive in between bunches. */)
5906 (process, string)
5907 Lisp_Object process, string;
5909 Lisp_Object proc;
5910 CHECK_STRING (string);
5911 proc = get_process (process);
5912 send_process (proc, SDATA (string),
5913 SBYTES (string), string);
5914 return Qnil;
5917 /* Return the foreground process group for the tty/pty that
5918 the process P uses. */
5919 static int
5920 emacs_get_tty_pgrp (p)
5921 struct Lisp_Process *p;
5923 int gid = -1;
5925 #ifdef TIOCGPGRP
5926 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5928 int fd;
5929 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5930 master side. Try the slave side. */
5931 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5933 if (fd != -1)
5935 ioctl (fd, TIOCGPGRP, &gid);
5936 emacs_close (fd);
5939 #endif /* defined (TIOCGPGRP ) */
5941 return gid;
5944 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5945 Sprocess_running_child_p, 0, 1, 0,
5946 doc: /* Return t if PROCESS has given the terminal to a child.
5947 If the operating system does not make it possible to find out,
5948 return t unconditionally. */)
5949 (process)
5950 Lisp_Object process;
5952 /* Initialize in case ioctl doesn't exist or gives an error,
5953 in a way that will cause returning t. */
5954 int gid;
5955 Lisp_Object proc;
5956 struct Lisp_Process *p;
5958 proc = get_process (process);
5959 p = XPROCESS (proc);
5961 if (!EQ (p->type, Qreal))
5962 error ("Process %s is not a subprocess",
5963 SDATA (p->name));
5964 if (p->infd < 0)
5965 error ("Process %s is not active",
5966 SDATA (p->name));
5968 gid = emacs_get_tty_pgrp (p);
5970 if (gid == p->pid)
5971 return Qnil;
5972 return Qt;
5975 /* send a signal number SIGNO to PROCESS.
5976 If CURRENT_GROUP is t, that means send to the process group
5977 that currently owns the terminal being used to communicate with PROCESS.
5978 This is used for various commands in shell mode.
5979 If CURRENT_GROUP is lambda, that means send to the process group
5980 that currently owns the terminal, but only if it is NOT the shell itself.
5982 If NOMSG is zero, insert signal-announcements into process's buffers
5983 right away.
5985 If we can, we try to signal PROCESS by sending control characters
5986 down the pty. This allows us to signal inferiors who have changed
5987 their uid, for which killpg would return an EPERM error. */
5989 static void
5990 process_send_signal (process, signo, current_group, nomsg)
5991 Lisp_Object process;
5992 int signo;
5993 Lisp_Object current_group;
5994 int nomsg;
5996 Lisp_Object proc;
5997 register struct Lisp_Process *p;
5998 int gid;
5999 int no_pgrp = 0;
6001 proc = get_process (process);
6002 p = XPROCESS (proc);
6004 if (!EQ (p->type, Qreal))
6005 error ("Process %s is not a subprocess",
6006 SDATA (p->name));
6007 if (p->infd < 0)
6008 error ("Process %s is not active",
6009 SDATA (p->name));
6011 if (!p->pty_flag)
6012 current_group = Qnil;
6014 /* If we are using pgrps, get a pgrp number and make it negative. */
6015 if (NILP (current_group))
6016 /* Send the signal to the shell's process group. */
6017 gid = p->pid;
6018 else
6020 #ifdef SIGNALS_VIA_CHARACTERS
6021 /* If possible, send signals to the entire pgrp
6022 by sending an input character to it. */
6024 /* TERMIOS is the latest and bestest, and seems most likely to
6025 work. If the system has it, use it. */
6026 #ifdef HAVE_TERMIOS
6027 struct termios t;
6028 cc_t *sig_char = NULL;
6030 tcgetattr (p->infd, &t);
6032 switch (signo)
6034 case SIGINT:
6035 sig_char = &t.c_cc[VINTR];
6036 break;
6038 case SIGQUIT:
6039 sig_char = &t.c_cc[VQUIT];
6040 break;
6042 case SIGTSTP:
6043 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6044 sig_char = &t.c_cc[VSWTCH];
6045 #else
6046 sig_char = &t.c_cc[VSUSP];
6047 #endif
6048 break;
6051 if (sig_char && *sig_char != CDISABLE)
6053 send_process (proc, sig_char, 1, Qnil);
6054 return;
6056 /* If we can't send the signal with a character,
6057 fall through and send it another way. */
6058 #else /* ! HAVE_TERMIOS */
6060 /* On Berkeley descendants, the following IOCTL's retrieve the
6061 current control characters. */
6062 #if defined (TIOCGLTC) && defined (TIOCGETC)
6064 struct tchars c;
6065 struct ltchars lc;
6067 switch (signo)
6069 case SIGINT:
6070 ioctl (p->infd, TIOCGETC, &c);
6071 send_process (proc, &c.t_intrc, 1, Qnil);
6072 return;
6073 case SIGQUIT:
6074 ioctl (p->infd, TIOCGETC, &c);
6075 send_process (proc, &c.t_quitc, 1, Qnil);
6076 return;
6077 #ifdef SIGTSTP
6078 case SIGTSTP:
6079 ioctl (p->infd, TIOCGLTC, &lc);
6080 send_process (proc, &lc.t_suspc, 1, Qnil);
6081 return;
6082 #endif /* ! defined (SIGTSTP) */
6085 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6087 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6088 characters. */
6089 #ifdef TCGETA
6090 struct termio t;
6091 switch (signo)
6093 case SIGINT:
6094 ioctl (p->infd, TCGETA, &t);
6095 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6096 return;
6097 case SIGQUIT:
6098 ioctl (p->infd, TCGETA, &t);
6099 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6100 return;
6101 #ifdef SIGTSTP
6102 case SIGTSTP:
6103 ioctl (p->infd, TCGETA, &t);
6104 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6105 return;
6106 #endif /* ! defined (SIGTSTP) */
6108 #else /* ! defined (TCGETA) */
6109 Your configuration files are messed up.
6110 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6111 you'd better be using one of the alternatives above! */
6112 #endif /* ! defined (TCGETA) */
6113 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6114 /* In this case, the code above should alway return. */
6115 abort ();
6116 #endif /* ! defined HAVE_TERMIOS */
6118 /* The code above may fall through if it can't
6119 handle the signal. */
6120 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6122 #ifdef TIOCGPGRP
6123 /* Get the current pgrp using the tty itself, if we have that.
6124 Otherwise, use the pty to get the pgrp.
6125 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6126 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6127 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6128 His patch indicates that if TIOCGPGRP returns an error, then
6129 we should just assume that p->pid is also the process group id. */
6131 gid = emacs_get_tty_pgrp (p);
6133 if (gid == -1)
6134 /* If we can't get the information, assume
6135 the shell owns the tty. */
6136 gid = p->pid;
6138 /* It is not clear whether anything really can set GID to -1.
6139 Perhaps on some system one of those ioctls can or could do so.
6140 Or perhaps this is vestigial. */
6141 if (gid == -1)
6142 no_pgrp = 1;
6143 #else /* ! defined (TIOCGPGRP ) */
6144 /* Can't select pgrps on this system, so we know that
6145 the child itself heads the pgrp. */
6146 gid = p->pid;
6147 #endif /* ! defined (TIOCGPGRP ) */
6149 /* If current_group is lambda, and the shell owns the terminal,
6150 don't send any signal. */
6151 if (EQ (current_group, Qlambda) && gid == p->pid)
6152 return;
6155 switch (signo)
6157 #ifdef SIGCONT
6158 case SIGCONT:
6159 p->raw_status_new = 0;
6160 p->status = Qrun;
6161 p->tick = ++process_tick;
6162 if (!nomsg)
6164 status_notify (NULL);
6165 redisplay_preserve_echo_area (13);
6167 break;
6168 #endif /* ! defined (SIGCONT) */
6169 case SIGINT:
6170 case SIGQUIT:
6171 case SIGKILL:
6172 flush_pending_output (p->infd);
6173 break;
6176 /* If we don't have process groups, send the signal to the immediate
6177 subprocess. That isn't really right, but it's better than any
6178 obvious alternative. */
6179 if (no_pgrp)
6181 kill (p->pid, signo);
6182 return;
6185 /* gid may be a pid, or minus a pgrp's number */
6186 #ifdef TIOCSIGSEND
6187 if (!NILP (current_group))
6189 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6190 EMACS_KILLPG (gid, signo);
6192 else
6194 gid = - p->pid;
6195 kill (gid, signo);
6197 #else /* ! defined (TIOCSIGSEND) */
6198 EMACS_KILLPG (gid, signo);
6199 #endif /* ! defined (TIOCSIGSEND) */
6202 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6203 doc: /* Interrupt process PROCESS.
6204 PROCESS may be a process, a buffer, or the name of a process or buffer.
6205 No arg or nil means current buffer's process.
6206 Second arg CURRENT-GROUP non-nil means send signal to
6207 the current process-group of the process's controlling terminal
6208 rather than to the process's own process group.
6209 If the process is a shell, this means interrupt current subjob
6210 rather than the shell.
6212 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6213 don't send the signal. */)
6214 (process, current_group)
6215 Lisp_Object process, current_group;
6217 process_send_signal (process, SIGINT, current_group, 0);
6218 return process;
6221 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6222 doc: /* Kill process PROCESS. May be process or name of one.
6223 See function `interrupt-process' for more details on usage. */)
6224 (process, current_group)
6225 Lisp_Object process, current_group;
6227 process_send_signal (process, SIGKILL, current_group, 0);
6228 return process;
6231 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6232 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6233 See function `interrupt-process' for more details on usage. */)
6234 (process, current_group)
6235 Lisp_Object process, current_group;
6237 process_send_signal (process, SIGQUIT, current_group, 0);
6238 return process;
6241 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6242 doc: /* Stop process PROCESS. May be process or name of one.
6243 See function `interrupt-process' for more details on usage.
6244 If PROCESS is a network or serial process, inhibit handling of incoming
6245 traffic. */)
6246 (process, current_group)
6247 Lisp_Object process, current_group;
6249 #ifdef HAVE_SOCKETS
6250 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6252 struct Lisp_Process *p;
6254 p = XPROCESS (process);
6255 if (NILP (p->command)
6256 && p->infd >= 0)
6258 FD_CLR (p->infd, &input_wait_mask);
6259 FD_CLR (p->infd, &non_keyboard_wait_mask);
6261 p->command = Qt;
6262 return process;
6264 #endif
6265 #ifndef SIGTSTP
6266 error ("No SIGTSTP support");
6267 #else
6268 process_send_signal (process, SIGTSTP, current_group, 0);
6269 #endif
6270 return process;
6273 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6274 doc: /* Continue process PROCESS. May be process or name of one.
6275 See function `interrupt-process' for more details on usage.
6276 If PROCESS is a network or serial process, resume handling of incoming
6277 traffic. */)
6278 (process, current_group)
6279 Lisp_Object process, current_group;
6281 #ifdef HAVE_SOCKETS
6282 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6284 struct Lisp_Process *p;
6286 p = XPROCESS (process);
6287 if (EQ (p->command, Qt)
6288 && p->infd >= 0
6289 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6291 FD_SET (p->infd, &input_wait_mask);
6292 FD_SET (p->infd, &non_keyboard_wait_mask);
6293 #ifdef WINDOWSNT
6294 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6295 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6296 #endif
6297 #ifdef HAVE_TERMIOS
6298 tcflush (p->infd, TCIFLUSH);
6299 #endif
6301 p->command = Qnil;
6302 return process;
6304 #endif
6305 #ifdef SIGCONT
6306 process_send_signal (process, SIGCONT, current_group, 0);
6307 #else
6308 error ("No SIGCONT support");
6309 #endif
6310 return process;
6313 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6314 2, 2, "sProcess (name or number): \nnSignal code: ",
6315 doc: /* Send PROCESS the signal with code SIGCODE.
6316 PROCESS may also be a number specifying the process id of the
6317 process to signal; in this case, the process need not be a child of
6318 this Emacs.
6319 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6320 (process, sigcode)
6321 Lisp_Object process, sigcode;
6323 pid_t pid;
6325 if (INTEGERP (process))
6327 pid = XINT (process);
6328 goto got_it;
6331 if (FLOATP (process))
6333 pid = (pid_t) XFLOAT_DATA (process);
6334 goto got_it;
6337 if (STRINGP (process))
6339 Lisp_Object tem;
6340 if (tem = Fget_process (process), NILP (tem))
6342 pid = XINT (Fstring_to_number (process, make_number (10)));
6343 if (pid > 0)
6344 goto got_it;
6346 process = tem;
6348 else
6349 process = get_process (process);
6351 if (NILP (process))
6352 return process;
6354 CHECK_PROCESS (process);
6355 pid = XPROCESS (process)->pid;
6356 if (pid <= 0)
6357 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6359 got_it:
6361 #define parse_signal(NAME, VALUE) \
6362 else if (!xstrcasecmp (name, NAME)) \
6363 XSETINT (sigcode, VALUE)
6365 if (INTEGERP (sigcode))
6367 else
6369 unsigned char *name;
6371 CHECK_SYMBOL (sigcode);
6372 name = SDATA (SYMBOL_NAME (sigcode));
6374 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6375 name += 3;
6377 if (0)
6379 #ifdef SIGUSR1
6380 parse_signal ("usr1", SIGUSR1);
6381 #endif
6382 #ifdef SIGUSR2
6383 parse_signal ("usr2", SIGUSR2);
6384 #endif
6385 #ifdef SIGTERM
6386 parse_signal ("term", SIGTERM);
6387 #endif
6388 #ifdef SIGHUP
6389 parse_signal ("hup", SIGHUP);
6390 #endif
6391 #ifdef SIGINT
6392 parse_signal ("int", SIGINT);
6393 #endif
6394 #ifdef SIGQUIT
6395 parse_signal ("quit", SIGQUIT);
6396 #endif
6397 #ifdef SIGILL
6398 parse_signal ("ill", SIGILL);
6399 #endif
6400 #ifdef SIGABRT
6401 parse_signal ("abrt", SIGABRT);
6402 #endif
6403 #ifdef SIGEMT
6404 parse_signal ("emt", SIGEMT);
6405 #endif
6406 #ifdef SIGKILL
6407 parse_signal ("kill", SIGKILL);
6408 #endif
6409 #ifdef SIGFPE
6410 parse_signal ("fpe", SIGFPE);
6411 #endif
6412 #ifdef SIGBUS
6413 parse_signal ("bus", SIGBUS);
6414 #endif
6415 #ifdef SIGSEGV
6416 parse_signal ("segv", SIGSEGV);
6417 #endif
6418 #ifdef SIGSYS
6419 parse_signal ("sys", SIGSYS);
6420 #endif
6421 #ifdef SIGPIPE
6422 parse_signal ("pipe", SIGPIPE);
6423 #endif
6424 #ifdef SIGALRM
6425 parse_signal ("alrm", SIGALRM);
6426 #endif
6427 #ifdef SIGURG
6428 parse_signal ("urg", SIGURG);
6429 #endif
6430 #ifdef SIGSTOP
6431 parse_signal ("stop", SIGSTOP);
6432 #endif
6433 #ifdef SIGTSTP
6434 parse_signal ("tstp", SIGTSTP);
6435 #endif
6436 #ifdef SIGCONT
6437 parse_signal ("cont", SIGCONT);
6438 #endif
6439 #ifdef SIGCHLD
6440 parse_signal ("chld", SIGCHLD);
6441 #endif
6442 #ifdef SIGTTIN
6443 parse_signal ("ttin", SIGTTIN);
6444 #endif
6445 #ifdef SIGTTOU
6446 parse_signal ("ttou", SIGTTOU);
6447 #endif
6448 #ifdef SIGIO
6449 parse_signal ("io", SIGIO);
6450 #endif
6451 #ifdef SIGXCPU
6452 parse_signal ("xcpu", SIGXCPU);
6453 #endif
6454 #ifdef SIGXFSZ
6455 parse_signal ("xfsz", SIGXFSZ);
6456 #endif
6457 #ifdef SIGVTALRM
6458 parse_signal ("vtalrm", SIGVTALRM);
6459 #endif
6460 #ifdef SIGPROF
6461 parse_signal ("prof", SIGPROF);
6462 #endif
6463 #ifdef SIGWINCH
6464 parse_signal ("winch", SIGWINCH);
6465 #endif
6466 #ifdef SIGINFO
6467 parse_signal ("info", SIGINFO);
6468 #endif
6469 else
6470 error ("Undefined signal name %s", name);
6473 #undef parse_signal
6475 return make_number (kill (pid, XINT (sigcode)));
6478 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6479 doc: /* Make PROCESS see end-of-file in its input.
6480 EOF comes after any text already sent to it.
6481 PROCESS may be a process, a buffer, the name of a process or buffer, or
6482 nil, indicating the current buffer's process.
6483 If PROCESS is a network connection, or is a process communicating
6484 through a pipe (as opposed to a pty), then you cannot send any more
6485 text to PROCESS after you call this function.
6486 If PROCESS is a serial process, wait until all output written to the
6487 process has been transmitted to the serial port. */)
6488 (process)
6489 Lisp_Object process;
6491 Lisp_Object proc;
6492 struct coding_system *coding;
6494 if (DATAGRAM_CONN_P (process))
6495 return process;
6497 proc = get_process (process);
6498 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6500 /* Make sure the process is really alive. */
6501 if (XPROCESS (proc)->raw_status_new)
6502 update_status (XPROCESS (proc));
6503 if (! EQ (XPROCESS (proc)->status, Qrun))
6504 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6506 if (CODING_REQUIRE_FLUSHING (coding))
6508 coding->mode |= CODING_MODE_LAST_BLOCK;
6509 send_process (proc, "", 0, Qnil);
6512 if (XPROCESS (proc)->pty_flag)
6513 send_process (proc, "\004", 1, Qnil);
6514 else if (EQ (XPROCESS (proc)->type, Qserial))
6516 #ifdef HAVE_TERMIOS
6517 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6518 error ("tcdrain() failed: %s", emacs_strerror (errno));
6519 #endif
6520 /* Do nothing on Windows because writes are blocking. */
6522 else
6524 int old_outfd, new_outfd;
6526 #ifdef HAVE_SHUTDOWN
6527 /* If this is a network connection, or socketpair is used
6528 for communication with the subprocess, call shutdown to cause EOF.
6529 (In some old system, shutdown to socketpair doesn't work.
6530 Then we just can't win.) */
6531 if (EQ (XPROCESS (proc)->type, Qnetwork)
6532 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6533 shutdown (XPROCESS (proc)->outfd, 1);
6534 /* In case of socketpair, outfd == infd, so don't close it. */
6535 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6536 emacs_close (XPROCESS (proc)->outfd);
6537 #else /* not HAVE_SHUTDOWN */
6538 emacs_close (XPROCESS (proc)->outfd);
6539 #endif /* not HAVE_SHUTDOWN */
6540 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6541 if (new_outfd < 0)
6542 abort ();
6543 old_outfd = XPROCESS (proc)->outfd;
6545 if (!proc_encode_coding_system[new_outfd])
6546 proc_encode_coding_system[new_outfd]
6547 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6548 bcopy (proc_encode_coding_system[old_outfd],
6549 proc_encode_coding_system[new_outfd],
6550 sizeof (struct coding_system));
6551 bzero (proc_encode_coding_system[old_outfd],
6552 sizeof (struct coding_system));
6554 XPROCESS (proc)->outfd = new_outfd;
6556 return process;
6559 /* Kill all processes associated with `buffer'.
6560 If `buffer' is nil, kill all processes */
6562 void
6563 kill_buffer_processes (buffer)
6564 Lisp_Object buffer;
6566 Lisp_Object tail, proc;
6568 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6570 proc = XCDR (XCAR (tail));
6571 if (PROCESSP (proc)
6572 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6574 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6575 Fdelete_process (proc);
6576 else if (XPROCESS (proc)->infd >= 0)
6577 process_send_signal (proc, SIGHUP, Qnil, 1);
6582 /* On receipt of a signal that a child status has changed, loop asking
6583 about children with changed statuses until the system says there
6584 are no more.
6586 All we do is change the status; we do not run sentinels or print
6587 notifications. That is saved for the next time keyboard input is
6588 done, in order to avoid timing errors.
6590 ** WARNING: this can be called during garbage collection.
6591 Therefore, it must not be fooled by the presence of mark bits in
6592 Lisp objects.
6594 ** USG WARNING: Although it is not obvious from the documentation
6595 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6596 signal() before executing at least one wait(), otherwise the
6597 handler will be called again, resulting in an infinite loop. The
6598 relevant portion of the documentation reads "SIGCLD signals will be
6599 queued and the signal-catching function will be continually
6600 reentered until the queue is empty". Invoking signal() causes the
6601 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6602 Inc.
6604 ** Malloc WARNING: This should never call malloc either directly or
6605 indirectly; if it does, that is a bug */
6607 #ifdef SIGCHLD
6608 SIGTYPE
6609 sigchld_handler (signo)
6610 int signo;
6612 int old_errno = errno;
6613 Lisp_Object proc;
6614 register struct Lisp_Process *p;
6615 extern EMACS_TIME *input_available_clear_time;
6617 SIGNAL_THREAD_CHECK (signo);
6619 while (1)
6621 pid_t pid;
6622 int w;
6623 Lisp_Object tail;
6625 #ifdef WNOHANG
6626 #ifndef WUNTRACED
6627 #define WUNTRACED 0
6628 #endif /* no WUNTRACED */
6629 /* Keep trying to get a status until we get a definitive result. */
6632 errno = 0;
6633 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6635 while (pid < 0 && errno == EINTR);
6637 if (pid <= 0)
6639 /* PID == 0 means no processes found, PID == -1 means a real
6640 failure. We have done all our job, so return. */
6642 errno = old_errno;
6643 return;
6645 #else
6646 pid = wait (&w);
6647 #endif /* no WNOHANG */
6649 /* Find the process that signaled us, and record its status. */
6651 /* The process can have been deleted by Fdelete_process. */
6652 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6654 Lisp_Object xpid = XCAR (tail);
6655 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6656 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6658 XSETCAR (tail, Qnil);
6659 goto sigchld_end_of_loop;
6663 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6664 p = 0;
6665 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6667 proc = XCDR (XCAR (tail));
6668 p = XPROCESS (proc);
6669 if (EQ (p->type, Qreal) && p->pid == pid)
6670 break;
6671 p = 0;
6674 /* Look for an asynchronous process whose pid hasn't been filled
6675 in yet. */
6676 if (p == 0)
6677 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6679 proc = XCDR (XCAR (tail));
6680 p = XPROCESS (proc);
6681 if (p->pid == -1)
6682 break;
6683 p = 0;
6686 /* Change the status of the process that was found. */
6687 if (p != 0)
6689 int clear_desc_flag = 0;
6691 p->tick = ++process_tick;
6692 p->raw_status = w;
6693 p->raw_status_new = 1;
6695 /* If process has terminated, stop waiting for its output. */
6696 if ((WIFSIGNALED (w) || WIFEXITED (w))
6697 && p->infd >= 0)
6698 clear_desc_flag = 1;
6700 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6701 if (clear_desc_flag)
6703 FD_CLR (p->infd, &input_wait_mask);
6704 FD_CLR (p->infd, &non_keyboard_wait_mask);
6707 /* Tell wait_reading_process_output that it needs to wake up and
6708 look around. */
6709 if (input_available_clear_time)
6710 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6713 /* There was no asynchronous process found for that pid: we have
6714 a synchronous process. */
6715 else
6717 synch_process_alive = 0;
6719 /* Report the status of the synchronous process. */
6720 if (WIFEXITED (w))
6721 synch_process_retcode = WRETCODE (w);
6722 else if (WIFSIGNALED (w))
6723 synch_process_termsig = WTERMSIG (w);
6725 /* Tell wait_reading_process_output that it needs to wake up and
6726 look around. */
6727 if (input_available_clear_time)
6728 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6731 sigchld_end_of_loop:
6734 /* On some systems, we must return right away.
6735 If any more processes want to signal us, we will
6736 get another signal.
6737 Otherwise (on systems that have WNOHANG), loop around
6738 to use up all the processes that have something to tell us. */
6739 #if (defined WINDOWSNT \
6740 || (defined USG && !defined GNU_LINUX \
6741 && !(defined HPUX && defined WNOHANG)))
6742 errno = old_errno;
6743 return;
6744 #endif /* USG, but not HPUX with WNOHANG */
6747 #endif /* SIGCHLD */
6750 static Lisp_Object
6751 exec_sentinel_unwind (data)
6752 Lisp_Object data;
6754 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6755 return Qnil;
6758 static Lisp_Object
6759 exec_sentinel_error_handler (error)
6760 Lisp_Object error;
6762 cmd_error_internal (error, "error in process sentinel: ");
6763 Vinhibit_quit = Qt;
6764 update_echo_area ();
6765 Fsleep_for (make_number (2), Qnil);
6766 return Qt;
6769 static void
6770 exec_sentinel (proc, reason)
6771 Lisp_Object proc, reason;
6773 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6774 register struct Lisp_Process *p = XPROCESS (proc);
6775 int count = SPECPDL_INDEX ();
6776 int outer_running_asynch_code = running_asynch_code;
6777 int waiting = waiting_for_user_input_p;
6779 if (inhibit_sentinels)
6780 return;
6782 /* No need to gcpro these, because all we do with them later
6783 is test them for EQness, and none of them should be a string. */
6784 odeactivate = Vdeactivate_mark;
6785 XSETBUFFER (obuffer, current_buffer);
6786 okeymap = current_buffer->keymap;
6788 /* There's no good reason to let sentinels change the current
6789 buffer, and many callers of accept-process-output, sit-for, and
6790 friends don't expect current-buffer to be changed from under them. */
6791 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6793 sentinel = p->sentinel;
6794 if (NILP (sentinel))
6795 return;
6797 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6798 assure that it gets restored no matter how the sentinel exits. */
6799 p->sentinel = Qnil;
6800 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6801 /* Inhibit quit so that random quits don't screw up a running filter. */
6802 specbind (Qinhibit_quit, Qt);
6803 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6805 /* In case we get recursively called,
6806 and we already saved the match data nonrecursively,
6807 save the same match data in safely recursive fashion. */
6808 if (outer_running_asynch_code)
6810 Lisp_Object tem;
6811 tem = Fmatch_data (Qnil, Qnil, Qnil);
6812 restore_search_regs ();
6813 record_unwind_save_match_data ();
6814 Fset_match_data (tem, Qt);
6817 /* For speed, if a search happens within this code,
6818 save the match data in a special nonrecursive fashion. */
6819 running_asynch_code = 1;
6821 internal_condition_case_1 (read_process_output_call,
6822 Fcons (sentinel,
6823 Fcons (proc, Fcons (reason, Qnil))),
6824 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6825 exec_sentinel_error_handler);
6827 /* If we saved the match data nonrecursively, restore it now. */
6828 restore_search_regs ();
6829 running_asynch_code = outer_running_asynch_code;
6831 Vdeactivate_mark = odeactivate;
6833 /* Restore waiting_for_user_input_p as it was
6834 when we were called, in case the filter clobbered it. */
6835 waiting_for_user_input_p = waiting;
6837 #if 0
6838 if (! EQ (Fcurrent_buffer (), obuffer)
6839 || ! EQ (current_buffer->keymap, okeymap))
6840 #endif
6841 /* But do it only if the caller is actually going to read events.
6842 Otherwise there's no need to make him wake up, and it could
6843 cause trouble (for example it would make sit_for return). */
6844 if (waiting_for_user_input_p == -1)
6845 record_asynch_buffer_change ();
6847 unbind_to (count, Qnil);
6850 /* Report all recent events of a change in process status
6851 (either run the sentinel or output a message).
6852 This is usually done while Emacs is waiting for keyboard input
6853 but can be done at other times. */
6855 static void
6856 status_notify (deleting_process)
6857 struct Lisp_Process *deleting_process;
6859 register Lisp_Object proc, buffer;
6860 Lisp_Object tail, msg;
6861 struct gcpro gcpro1, gcpro2;
6863 tail = Qnil;
6864 msg = Qnil;
6865 /* We need to gcpro tail; if read_process_output calls a filter
6866 which deletes a process and removes the cons to which tail points
6867 from Vprocess_alist, and then causes a GC, tail is an unprotected
6868 reference. */
6869 GCPRO2 (tail, msg);
6871 /* Set this now, so that if new processes are created by sentinels
6872 that we run, we get called again to handle their status changes. */
6873 update_tick = process_tick;
6875 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6877 Lisp_Object symbol;
6878 register struct Lisp_Process *p;
6880 proc = Fcdr (XCAR (tail));
6881 p = XPROCESS (proc);
6883 if (p->tick != p->update_tick)
6885 p->update_tick = p->tick;
6887 /* If process is still active, read any output that remains. */
6888 while (! EQ (p->filter, Qt)
6889 && ! EQ (p->status, Qconnect)
6890 && ! EQ (p->status, Qlisten)
6891 /* Network or serial process not stopped: */
6892 && ! EQ (p->command, Qt)
6893 && p->infd >= 0
6894 && p != deleting_process
6895 && read_process_output (proc, p->infd) > 0);
6897 buffer = p->buffer;
6899 /* Get the text to use for the message. */
6900 if (p->raw_status_new)
6901 update_status (p);
6902 msg = status_message (p);
6904 /* If process is terminated, deactivate it or delete it. */
6905 symbol = p->status;
6906 if (CONSP (p->status))
6907 symbol = XCAR (p->status);
6909 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6910 || EQ (symbol, Qclosed))
6912 if (delete_exited_processes)
6913 remove_process (proc);
6914 else
6915 deactivate_process (proc);
6918 /* The actions above may have further incremented p->tick.
6919 So set p->update_tick again
6920 so that an error in the sentinel will not cause
6921 this code to be run again. */
6922 p->update_tick = p->tick;
6923 /* Now output the message suitably. */
6924 if (!NILP (p->sentinel))
6925 exec_sentinel (proc, msg);
6926 /* Don't bother with a message in the buffer
6927 when a process becomes runnable. */
6928 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6930 Lisp_Object tem;
6931 struct buffer *old = current_buffer;
6932 int opoint, opoint_byte;
6933 int before, before_byte;
6935 /* Avoid error if buffer is deleted
6936 (probably that's why the process is dead, too) */
6937 if (NILP (XBUFFER (buffer)->name))
6938 continue;
6939 Fset_buffer (buffer);
6941 opoint = PT;
6942 opoint_byte = PT_BYTE;
6943 /* Insert new output into buffer
6944 at the current end-of-output marker,
6945 thus preserving logical ordering of input and output. */
6946 if (XMARKER (p->mark)->buffer)
6947 Fgoto_char (p->mark);
6948 else
6949 SET_PT_BOTH (ZV, ZV_BYTE);
6951 before = PT;
6952 before_byte = PT_BYTE;
6954 tem = current_buffer->read_only;
6955 current_buffer->read_only = Qnil;
6956 insert_string ("\nProcess ");
6957 Finsert (1, &p->name);
6958 insert_string (" ");
6959 Finsert (1, &msg);
6960 current_buffer->read_only = tem;
6961 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6963 if (opoint >= before)
6964 SET_PT_BOTH (opoint + (PT - before),
6965 opoint_byte + (PT_BYTE - before_byte));
6966 else
6967 SET_PT_BOTH (opoint, opoint_byte);
6969 set_buffer_internal (old);
6972 } /* end for */
6974 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6975 UNGCPRO;
6979 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6980 Sset_process_coding_system, 1, 3, 0,
6981 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6982 DECODING will be used to decode subprocess output and ENCODING to
6983 encode subprocess input. */)
6984 (process, decoding, encoding)
6985 register Lisp_Object process, decoding, encoding;
6987 register struct Lisp_Process *p;
6989 CHECK_PROCESS (process);
6990 p = XPROCESS (process);
6991 if (p->infd < 0)
6992 error ("Input file descriptor of %s closed", SDATA (p->name));
6993 if (p->outfd < 0)
6994 error ("Output file descriptor of %s closed", SDATA (p->name));
6995 Fcheck_coding_system (decoding);
6996 Fcheck_coding_system (encoding);
6997 encoding = coding_inherit_eol_type (encoding, Qnil);
6998 p->decode_coding_system = decoding;
6999 p->encode_coding_system = encoding;
7000 setup_process_coding_systems (process);
7002 return Qnil;
7005 DEFUN ("process-coding-system",
7006 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7007 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7008 (process)
7009 register Lisp_Object process;
7011 CHECK_PROCESS (process);
7012 return Fcons (XPROCESS (process)->decode_coding_system,
7013 XPROCESS (process)->encode_coding_system);
7016 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7017 Sset_process_filter_multibyte, 2, 2, 0,
7018 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7019 If FLAG is non-nil, the filter is given multibyte strings.
7020 If FLAG is nil, the filter is given unibyte strings. In this case,
7021 all character code conversion except for end-of-line conversion is
7022 suppressed. */)
7023 (process, flag)
7024 Lisp_Object process, flag;
7026 register struct Lisp_Process *p;
7028 CHECK_PROCESS (process);
7029 p = XPROCESS (process);
7030 if (NILP (flag))
7031 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
7032 setup_process_coding_systems (process);
7034 return Qnil;
7037 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7038 Sprocess_filter_multibyte_p, 1, 1, 0,
7039 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7040 (process)
7041 Lisp_Object process;
7043 register struct Lisp_Process *p;
7044 struct coding_system *coding;
7046 CHECK_PROCESS (process);
7047 p = XPROCESS (process);
7048 coding = proc_decode_coding_system[p->infd];
7049 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7054 /* Add DESC to the set of keyboard input descriptors. */
7056 void
7057 add_keyboard_wait_descriptor (desc)
7058 int desc;
7060 FD_SET (desc, &input_wait_mask);
7061 FD_SET (desc, &non_process_wait_mask);
7062 if (desc > max_keyboard_desc)
7063 max_keyboard_desc = desc;
7066 static int add_gpm_wait_descriptor_called_flag;
7068 void
7069 add_gpm_wait_descriptor (desc)
7070 int desc;
7072 if (! add_gpm_wait_descriptor_called_flag)
7073 FD_CLR (0, &input_wait_mask);
7074 add_gpm_wait_descriptor_called_flag = 1;
7075 FD_SET (desc, &input_wait_mask);
7076 FD_SET (desc, &gpm_wait_mask);
7077 if (desc > max_gpm_desc)
7078 max_gpm_desc = desc;
7081 /* From now on, do not expect DESC to give keyboard input. */
7083 void
7084 delete_keyboard_wait_descriptor (desc)
7085 int desc;
7087 int fd;
7088 int lim = max_keyboard_desc;
7090 FD_CLR (desc, &input_wait_mask);
7091 FD_CLR (desc, &non_process_wait_mask);
7093 if (desc == max_keyboard_desc)
7094 for (fd = 0; fd < lim; fd++)
7095 if (FD_ISSET (fd, &input_wait_mask)
7096 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7097 && !FD_ISSET (fd, &gpm_wait_mask))
7098 max_keyboard_desc = fd;
7101 void
7102 delete_gpm_wait_descriptor (desc)
7103 int desc;
7105 int fd;
7106 int lim = max_gpm_desc;
7108 FD_CLR (desc, &input_wait_mask);
7109 FD_CLR (desc, &non_process_wait_mask);
7111 if (desc == max_gpm_desc)
7112 for (fd = 0; fd < lim; fd++)
7113 if (FD_ISSET (fd, &input_wait_mask)
7114 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7115 && !FD_ISSET (fd, &non_process_wait_mask))
7116 max_gpm_desc = fd;
7119 /* Return nonzero if *MASK has a bit set
7120 that corresponds to one of the keyboard input descriptors. */
7122 static int
7123 keyboard_bit_set (mask)
7124 SELECT_TYPE *mask;
7126 int fd;
7128 for (fd = 0; fd <= max_keyboard_desc; fd++)
7129 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7130 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7131 return 1;
7133 return 0;
7136 /* Enumeration of and access to system processes a-la ps(1). */
7138 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7139 0, 0, 0,
7140 doc: /* Return a list of numerical process IDs of all running processes.
7141 If this functionality is unsupported, return nil.
7143 See `process-attributes' for getting attributes of a process given its ID. */)
7146 return list_system_processes ();
7149 DEFUN ("process-attributes", Fprocess_attributes,
7150 Sprocess_attributes, 1, 1, 0,
7151 doc: /* Return attributes of the process given by its PID, a number.
7153 Value is an alist where each element is a cons cell of the form
7155 \(KEY . VALUE)
7157 If this functionality is unsupported, the value is nil.
7159 See `list-system-processes' for getting a list of all process IDs.
7161 The KEYs of the attributes that this function may return are listed
7162 below, together with the type of the associated VALUE (in parentheses).
7163 Not all platforms support all of these attributes; unsupported
7164 attributes will not appear in the returned alist.
7165 Unless explicitly indicated otherwise, numbers can have either
7166 integer or floating point values.
7168 euid -- Effective user User ID of the process (number)
7169 user -- User name corresponding to euid (string)
7170 egid -- Effective user Group ID of the process (number)
7171 group -- Group name corresponding to egid (string)
7172 comm -- Command name (executable name only) (string)
7173 state -- Process state code, such as "S", "R", or "T" (string)
7174 ppid -- Parent process ID (number)
7175 pgrp -- Process group ID (number)
7176 sess -- Session ID, i.e. process ID of session leader (number)
7177 ttname -- Controlling tty name (string)
7178 tpgid -- ID of foreground process group on the process's tty (number)
7179 minflt -- number of minor page faults (number)
7180 majflt -- number of major page faults (number)
7181 cminflt -- cumulative number of minor page faults (number)
7182 cmajflt -- cumulative number of major page faults (number)
7183 utime -- user time used by the process, in the (HIGH LOW USEC) format
7184 stime -- system time used by the process, in the (HIGH LOW USEC) format
7185 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7186 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7187 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7188 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7189 pri -- priority of the process (number)
7190 nice -- nice value of the process (number)
7191 thcount -- process thread count (number)
7192 start -- time the process started, in the (HIGH LOW USEC) format
7193 vsize -- virtual memory size of the process in KB's (number)
7194 rss -- resident set size of the process in KB's (number)
7195 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7196 pcpu -- percents of CPU time used by the process (floating-point number)
7197 pmem -- percents of total physical memory used by process's resident set
7198 (floating-point number)
7199 args -- command line which invoked the process (string). */)
7200 (pid)
7202 Lisp_Object pid;
7204 return system_process_attributes (pid);
7207 void
7208 init_process ()
7210 register int i;
7212 inhibit_sentinels = 0;
7214 #ifdef SIGCHLD
7215 #ifndef CANNOT_DUMP
7216 if (! noninteractive || initialized)
7217 #endif
7218 signal (SIGCHLD, sigchld_handler);
7219 #endif
7221 FD_ZERO (&input_wait_mask);
7222 FD_ZERO (&non_keyboard_wait_mask);
7223 FD_ZERO (&non_process_wait_mask);
7224 max_process_desc = 0;
7226 #ifdef NON_BLOCKING_CONNECT
7227 FD_ZERO (&connect_wait_mask);
7228 num_pending_connects = 0;
7229 #endif
7231 #ifdef ADAPTIVE_READ_BUFFERING
7232 process_output_delay_count = 0;
7233 process_output_skip = 0;
7234 #endif
7236 /* Don't do this, it caused infinite select loops. The display
7237 method should call add_keyboard_wait_descriptor on stdin if it
7238 needs that. */
7239 #if 0
7240 FD_SET (0, &input_wait_mask);
7241 #endif
7243 Vprocess_alist = Qnil;
7244 #ifdef SIGCHLD
7245 deleted_pid_list = Qnil;
7246 #endif
7247 for (i = 0; i < MAXDESC; i++)
7249 chan_process[i] = Qnil;
7250 proc_buffered_char[i] = -1;
7252 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7253 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7254 #ifdef DATAGRAM_SOCKETS
7255 bzero (datagram_address, sizeof datagram_address);
7256 #endif
7258 #ifdef HAVE_SOCKETS
7260 Lisp_Object subfeatures = Qnil;
7261 const struct socket_options *sopt;
7263 #define ADD_SUBFEATURE(key, val) \
7264 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7266 #ifdef NON_BLOCKING_CONNECT
7267 ADD_SUBFEATURE (QCnowait, Qt);
7268 #endif
7269 #ifdef DATAGRAM_SOCKETS
7270 ADD_SUBFEATURE (QCtype, Qdatagram);
7271 #endif
7272 #ifdef HAVE_SEQPACKET
7273 ADD_SUBFEATURE (QCtype, Qseqpacket);
7274 #endif
7275 #ifdef HAVE_LOCAL_SOCKETS
7276 ADD_SUBFEATURE (QCfamily, Qlocal);
7277 #endif
7278 ADD_SUBFEATURE (QCfamily, Qipv4);
7279 #ifdef AF_INET6
7280 ADD_SUBFEATURE (QCfamily, Qipv6);
7281 #endif
7282 #ifdef HAVE_GETSOCKNAME
7283 ADD_SUBFEATURE (QCservice, Qt);
7284 #endif
7285 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7286 ADD_SUBFEATURE (QCserver, Qt);
7287 #endif
7289 for (sopt = socket_options; sopt->name; sopt++)
7290 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7292 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7294 #endif /* HAVE_SOCKETS */
7296 #if defined (DARWIN_OS)
7297 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7298 processes. As such, we only change the default value. */
7299 if (initialized)
7301 char *release = get_operating_system_release();
7302 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7303 && release[1] == '.')) {
7304 Vprocess_connection_type = Qnil;
7307 #endif
7310 void
7311 syms_of_process ()
7313 Qprocessp = intern_c_string ("processp");
7314 staticpro (&Qprocessp);
7315 Qrun = intern_c_string ("run");
7316 staticpro (&Qrun);
7317 Qstop = intern_c_string ("stop");
7318 staticpro (&Qstop);
7319 Qsignal = intern_c_string ("signal");
7320 staticpro (&Qsignal);
7322 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7323 here again.
7325 Qexit = intern_c_string ("exit");
7326 staticpro (&Qexit); */
7328 Qopen = intern_c_string ("open");
7329 staticpro (&Qopen);
7330 Qclosed = intern_c_string ("closed");
7331 staticpro (&Qclosed);
7332 Qconnect = intern_c_string ("connect");
7333 staticpro (&Qconnect);
7334 Qfailed = intern_c_string ("failed");
7335 staticpro (&Qfailed);
7336 Qlisten = intern_c_string ("listen");
7337 staticpro (&Qlisten);
7338 Qlocal = intern_c_string ("local");
7339 staticpro (&Qlocal);
7340 Qipv4 = intern_c_string ("ipv4");
7341 staticpro (&Qipv4);
7342 #ifdef AF_INET6
7343 Qipv6 = intern_c_string ("ipv6");
7344 staticpro (&Qipv6);
7345 #endif
7346 Qdatagram = intern_c_string ("datagram");
7347 staticpro (&Qdatagram);
7348 Qseqpacket = intern_c_string ("seqpacket");
7349 staticpro (&Qseqpacket);
7351 QCport = intern_c_string (":port");
7352 staticpro (&QCport);
7353 QCspeed = intern_c_string (":speed");
7354 staticpro (&QCspeed);
7355 QCprocess = intern_c_string (":process");
7356 staticpro (&QCprocess);
7358 QCbytesize = intern_c_string (":bytesize");
7359 staticpro (&QCbytesize);
7360 QCstopbits = intern_c_string (":stopbits");
7361 staticpro (&QCstopbits);
7362 QCparity = intern_c_string (":parity");
7363 staticpro (&QCparity);
7364 Qodd = intern_c_string ("odd");
7365 staticpro (&Qodd);
7366 Qeven = intern_c_string ("even");
7367 staticpro (&Qeven);
7368 QCflowcontrol = intern_c_string (":flowcontrol");
7369 staticpro (&QCflowcontrol);
7370 Qhw = intern_c_string ("hw");
7371 staticpro (&Qhw);
7372 Qsw = intern_c_string ("sw");
7373 staticpro (&Qsw);
7374 QCsummary = intern_c_string (":summary");
7375 staticpro (&QCsummary);
7377 Qreal = intern_c_string ("real");
7378 staticpro (&Qreal);
7379 Qnetwork = intern_c_string ("network");
7380 staticpro (&Qnetwork);
7381 Qserial = intern_c_string ("serial");
7382 staticpro (&Qserial);
7384 QCname = intern_c_string (":name");
7385 staticpro (&QCname);
7386 QCbuffer = intern_c_string (":buffer");
7387 staticpro (&QCbuffer);
7388 QChost = intern_c_string (":host");
7389 staticpro (&QChost);
7390 QCservice = intern_c_string (":service");
7391 staticpro (&QCservice);
7392 QCtype = intern_c_string (":type");
7393 staticpro (&QCtype);
7394 QClocal = intern_c_string (":local");
7395 staticpro (&QClocal);
7396 QCremote = intern_c_string (":remote");
7397 staticpro (&QCremote);
7398 QCcoding = intern_c_string (":coding");
7399 staticpro (&QCcoding);
7400 QCserver = intern_c_string (":server");
7401 staticpro (&QCserver);
7402 QCnowait = intern_c_string (":nowait");
7403 staticpro (&QCnowait);
7404 QCsentinel = intern_c_string (":sentinel");
7405 staticpro (&QCsentinel);
7406 QClog = intern_c_string (":log");
7407 staticpro (&QClog);
7408 QCnoquery = intern_c_string (":noquery");
7409 staticpro (&QCnoquery);
7410 QCstop = intern_c_string (":stop");
7411 staticpro (&QCstop);
7412 QCoptions = intern_c_string (":options");
7413 staticpro (&QCoptions);
7414 QCplist = intern_c_string (":plist");
7415 staticpro (&QCplist);
7417 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7418 staticpro (&Qlast_nonmenu_event);
7420 staticpro (&Vprocess_alist);
7421 #ifdef SIGCHLD
7422 staticpro (&deleted_pid_list);
7423 #endif
7425 Qeuid = intern_c_string ("euid");
7426 staticpro (&Qeuid);
7427 Qegid = intern_c_string ("egid");
7428 staticpro (&Qegid);
7429 Quser = intern_c_string ("user");
7430 staticpro (&Quser);
7431 Qgroup = intern_c_string ("group");
7432 staticpro (&Qgroup);
7433 Qcomm = intern_c_string ("comm");
7434 staticpro (&Qcomm);
7435 Qstate = intern_c_string ("state");
7436 staticpro (&Qstate);
7437 Qppid = intern_c_string ("ppid");
7438 staticpro (&Qppid);
7439 Qpgrp = intern_c_string ("pgrp");
7440 staticpro (&Qpgrp);
7441 Qsess = intern_c_string ("sess");
7442 staticpro (&Qsess);
7443 Qttname = intern_c_string ("ttname");
7444 staticpro (&Qttname);
7445 Qtpgid = intern_c_string ("tpgid");
7446 staticpro (&Qtpgid);
7447 Qminflt = intern_c_string ("minflt");
7448 staticpro (&Qminflt);
7449 Qmajflt = intern_c_string ("majflt");
7450 staticpro (&Qmajflt);
7451 Qcminflt = intern_c_string ("cminflt");
7452 staticpro (&Qcminflt);
7453 Qcmajflt = intern_c_string ("cmajflt");
7454 staticpro (&Qcmajflt);
7455 Qutime = intern_c_string ("utime");
7456 staticpro (&Qutime);
7457 Qstime = intern_c_string ("stime");
7458 staticpro (&Qstime);
7459 Qtime = intern_c_string ("time");
7460 staticpro (&Qtime);
7461 Qcutime = intern_c_string ("cutime");
7462 staticpro (&Qcutime);
7463 Qcstime = intern_c_string ("cstime");
7464 staticpro (&Qcstime);
7465 Qctime = intern_c_string ("ctime");
7466 staticpro (&Qctime);
7467 Qpri = intern_c_string ("pri");
7468 staticpro (&Qpri);
7469 Qnice = intern_c_string ("nice");
7470 staticpro (&Qnice);
7471 Qthcount = intern_c_string ("thcount");
7472 staticpro (&Qthcount);
7473 Qstart = intern_c_string ("start");
7474 staticpro (&Qstart);
7475 Qvsize = intern_c_string ("vsize");
7476 staticpro (&Qvsize);
7477 Qrss = intern_c_string ("rss");
7478 staticpro (&Qrss);
7479 Qetime = intern_c_string ("etime");
7480 staticpro (&Qetime);
7481 Qpcpu = intern_c_string ("pcpu");
7482 staticpro (&Qpcpu);
7483 Qpmem = intern_c_string ("pmem");
7484 staticpro (&Qpmem);
7485 Qargs = intern_c_string ("args");
7486 staticpro (&Qargs);
7488 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7489 doc: /* *Non-nil means delete processes immediately when they exit.
7490 A value of nil means don't delete them until `list-processes' is run. */);
7492 delete_exited_processes = 1;
7494 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7495 doc: /* Control type of device used to communicate with subprocesses.
7496 Values are nil to use a pipe, or t or `pty' to use a pty.
7497 The value has no effect if the system has no ptys or if all ptys are busy:
7498 then a pipe is used in any case.
7499 The value takes effect when `start-process' is called. */);
7500 Vprocess_connection_type = Qt;
7502 #ifdef ADAPTIVE_READ_BUFFERING
7503 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7504 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7505 On some systems, when Emacs reads the output from a subprocess, the output data
7506 is read in very small blocks, potentially resulting in very poor performance.
7507 This behavior can be remedied to some extent by setting this variable to a
7508 non-nil value, as it will automatically delay reading from such processes, to
7509 allow them to produce more output before Emacs tries to read it.
7510 If the value is t, the delay is reset after each write to the process; any other
7511 non-nil value means that the delay is not reset on write.
7512 The variable takes effect when `start-process' is called. */);
7513 Vprocess_adaptive_read_buffering = Qt;
7514 #endif
7516 defsubr (&Sprocessp);
7517 defsubr (&Sget_process);
7518 defsubr (&Sget_buffer_process);
7519 defsubr (&Sdelete_process);
7520 defsubr (&Sprocess_status);
7521 defsubr (&Sprocess_exit_status);
7522 defsubr (&Sprocess_id);
7523 defsubr (&Sprocess_name);
7524 defsubr (&Sprocess_tty_name);
7525 defsubr (&Sprocess_command);
7526 defsubr (&Sset_process_buffer);
7527 defsubr (&Sprocess_buffer);
7528 defsubr (&Sprocess_mark);
7529 defsubr (&Sset_process_filter);
7530 defsubr (&Sprocess_filter);
7531 defsubr (&Sset_process_sentinel);
7532 defsubr (&Sprocess_sentinel);
7533 defsubr (&Sset_process_window_size);
7534 defsubr (&Sset_process_inherit_coding_system_flag);
7535 defsubr (&Sprocess_inherit_coding_system_flag);
7536 defsubr (&Sset_process_query_on_exit_flag);
7537 defsubr (&Sprocess_query_on_exit_flag);
7538 defsubr (&Sprocess_contact);
7539 defsubr (&Sprocess_plist);
7540 defsubr (&Sset_process_plist);
7541 defsubr (&Slist_processes);
7542 defsubr (&Sprocess_list);
7543 defsubr (&Sstart_process);
7544 #ifdef HAVE_SERIAL
7545 defsubr (&Sserial_process_configure);
7546 defsubr (&Smake_serial_process);
7547 #endif /* HAVE_SERIAL */
7548 #ifdef HAVE_SOCKETS
7549 defsubr (&Sset_network_process_option);
7550 defsubr (&Smake_network_process);
7551 defsubr (&Sformat_network_address);
7552 #endif /* HAVE_SOCKETS */
7553 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7554 #ifdef SIOCGIFCONF
7555 defsubr (&Snetwork_interface_list);
7556 #endif
7557 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7558 defsubr (&Snetwork_interface_info);
7559 #endif
7560 #endif /* HAVE_SOCKETS ... */
7561 #ifdef DATAGRAM_SOCKETS
7562 defsubr (&Sprocess_datagram_address);
7563 defsubr (&Sset_process_datagram_address);
7564 #endif
7565 defsubr (&Saccept_process_output);
7566 defsubr (&Sprocess_send_region);
7567 defsubr (&Sprocess_send_string);
7568 defsubr (&Sinterrupt_process);
7569 defsubr (&Skill_process);
7570 defsubr (&Squit_process);
7571 defsubr (&Sstop_process);
7572 defsubr (&Scontinue_process);
7573 defsubr (&Sprocess_running_child_p);
7574 defsubr (&Sprocess_send_eof);
7575 defsubr (&Ssignal_process);
7576 defsubr (&Swaiting_for_user_input_p);
7577 defsubr (&Sprocess_type);
7578 defsubr (&Sset_process_coding_system);
7579 defsubr (&Sprocess_coding_system);
7580 defsubr (&Sset_process_filter_multibyte);
7581 defsubr (&Sprocess_filter_multibyte_p);
7582 defsubr (&Slist_system_processes);
7583 defsubr (&Sprocess_attributes);
7587 #else /* not subprocesses */
7589 #include <sys/types.h>
7590 #include <errno.h>
7591 #include <sys/stat.h>
7592 #include <stdlib.h>
7593 #include <fcntl.h>
7594 #include <setjmp.h>
7595 #ifdef HAVE_UNISTD_H
7596 #include <unistd.h>
7597 #endif
7599 #include "lisp.h"
7600 #include "systime.h"
7601 #include "character.h"
7602 #include "coding.h"
7603 #include "termopts.h"
7604 #include "sysselect.h"
7606 extern int frame_garbaged;
7608 extern EMACS_TIME timer_check ();
7609 extern int timers_run;
7611 Lisp_Object QCtype, QCname;
7613 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7614 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7615 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7616 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7618 /* As described above, except assuming that there are no subprocesses:
7620 Wait for timeout to elapse and/or keyboard input to be available.
7622 time_limit is:
7623 timeout in seconds, or
7624 zero for no limit, or
7625 -1 means gobble data immediately available but don't wait for any.
7627 read_kbd is a Lisp_Object:
7628 0 to ignore keyboard input, or
7629 1 to return when input is available, or
7630 -1 means caller will actually read the input, so don't throw to
7631 the quit handler.
7633 see full version for other parameters. We know that wait_proc will
7634 always be NULL, since `subprocesses' isn't defined.
7636 do_display != 0 means redisplay should be done to show subprocess
7637 output that arrives.
7639 Return true if we received input from any process. */
7642 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7643 wait_for_cell, wait_proc, just_wait_proc)
7644 int time_limit, microsecs, read_kbd, do_display;
7645 Lisp_Object wait_for_cell;
7646 struct Lisp_Process *wait_proc;
7647 int just_wait_proc;
7649 register int nfds;
7650 EMACS_TIME end_time, timeout;
7651 SELECT_TYPE waitchannels;
7652 int xerrno;
7654 /* What does time_limit really mean? */
7655 if (time_limit || microsecs)
7657 EMACS_GET_TIME (end_time);
7658 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7659 EMACS_ADD_TIME (end_time, end_time, timeout);
7662 /* Turn off periodic alarms (in case they are in use)
7663 and then turn off any other atimers,
7664 because the select emulator uses alarms. */
7665 stop_polling ();
7666 turn_on_atimers (0);
7668 while (1)
7670 int timeout_reduced_for_timers = 0;
7672 /* If calling from keyboard input, do not quit
7673 since we want to return C-g as an input character.
7674 Otherwise, do pending quit if requested. */
7675 if (read_kbd >= 0)
7676 QUIT;
7678 /* Exit now if the cell we're waiting for became non-nil. */
7679 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7680 break;
7682 /* Compute time from now till when time limit is up */
7683 /* Exit if already run out */
7684 if (time_limit == -1)
7686 /* -1 specified for timeout means
7687 gobble output available now
7688 but don't wait at all. */
7690 EMACS_SET_SECS_USECS (timeout, 0, 0);
7692 else if (time_limit || microsecs)
7694 EMACS_GET_TIME (timeout);
7695 EMACS_SUB_TIME (timeout, end_time, timeout);
7696 if (EMACS_TIME_NEG_P (timeout))
7697 break;
7699 else
7701 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7704 /* If our caller will not immediately handle keyboard events,
7705 run timer events directly.
7706 (Callers that will immediately read keyboard events
7707 call timer_delay on their own.) */
7708 if (NILP (wait_for_cell))
7710 EMACS_TIME timer_delay;
7714 int old_timers_run = timers_run;
7715 timer_delay = timer_check (1);
7716 if (timers_run != old_timers_run && do_display)
7717 /* We must retry, since a timer may have requeued itself
7718 and that could alter the time delay. */
7719 redisplay_preserve_echo_area (14);
7720 else
7721 break;
7723 while (!detect_input_pending ());
7725 /* If there is unread keyboard input, also return. */
7726 if (read_kbd != 0
7727 && requeued_events_pending_p ())
7728 break;
7730 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7732 EMACS_TIME difference;
7733 EMACS_SUB_TIME (difference, timer_delay, timeout);
7734 if (EMACS_TIME_NEG_P (difference))
7736 timeout = timer_delay;
7737 timeout_reduced_for_timers = 1;
7742 /* Cause C-g and alarm signals to take immediate action,
7743 and cause input available signals to zero out timeout. */
7744 if (read_kbd < 0)
7745 set_waiting_for_input (&timeout);
7747 /* Wait till there is something to do. */
7749 if (! read_kbd && NILP (wait_for_cell))
7750 FD_ZERO (&waitchannels);
7751 else
7752 FD_SET (0, &waitchannels);
7754 /* If a frame has been newly mapped and needs updating,
7755 reprocess its display stuff. */
7756 if (frame_garbaged && do_display)
7758 clear_waiting_for_input ();
7759 redisplay_preserve_echo_area (15);
7760 if (read_kbd < 0)
7761 set_waiting_for_input (&timeout);
7764 if (read_kbd && detect_input_pending ())
7766 nfds = 0;
7767 FD_ZERO (&waitchannels);
7769 else
7770 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7771 &timeout);
7773 xerrno = errno;
7775 /* Make C-g and alarm signals set flags again */
7776 clear_waiting_for_input ();
7778 /* If we woke up due to SIGWINCH, actually change size now. */
7779 do_pending_window_change (0);
7781 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7782 /* We waited the full specified time, so return now. */
7783 break;
7785 if (nfds == -1)
7787 /* If the system call was interrupted, then go around the
7788 loop again. */
7789 if (xerrno == EINTR)
7790 FD_ZERO (&waitchannels);
7791 else
7792 error ("select error: %s", emacs_strerror (xerrno));
7794 #ifdef SOLARIS2
7795 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7796 /* System sometimes fails to deliver SIGIO. */
7797 kill (getpid (), SIGIO);
7798 #endif
7799 #ifdef SIGIO
7800 if (read_kbd && interrupt_input && (waitchannels & 1))
7801 kill (getpid (), SIGIO);
7802 #endif
7804 /* Check for keyboard input */
7806 if (read_kbd
7807 && detect_input_pending_run_timers (do_display))
7809 swallow_events (do_display);
7810 if (detect_input_pending_run_timers (do_display))
7811 break;
7814 /* If there is unread keyboard input, also return. */
7815 if (read_kbd
7816 && requeued_events_pending_p ())
7817 break;
7819 /* If wait_for_cell. check for keyboard input
7820 but don't run any timers.
7821 ??? (It seems wrong to me to check for keyboard
7822 input at all when wait_for_cell, but the code
7823 has been this way since July 1994.
7824 Try changing this after version 19.31.) */
7825 if (! NILP (wait_for_cell)
7826 && detect_input_pending ())
7828 swallow_events (do_display);
7829 if (detect_input_pending ())
7830 break;
7833 /* Exit now if the cell we're waiting for became non-nil. */
7834 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7835 break;
7838 start_polling ();
7840 return 0;
7844 /* Don't confuse make-docfile by having two doc strings for this function.
7845 make-docfile does not pay attention to #if, for good reason! */
7846 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7848 (name)
7849 register Lisp_Object name;
7851 return Qnil;
7854 /* Don't confuse make-docfile by having two doc strings for this function.
7855 make-docfile does not pay attention to #if, for good reason! */
7856 DEFUN ("process-inherit-coding-system-flag",
7857 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7858 1, 1, 0,
7860 (process)
7861 register Lisp_Object process;
7863 /* Ignore the argument and return the value of
7864 inherit-process-coding-system. */
7865 return inherit_process_coding_system ? Qt : Qnil;
7868 /* Kill all processes associated with `buffer'.
7869 If `buffer' is nil, kill all processes.
7870 Since we have no subprocesses, this does nothing. */
7872 void
7873 kill_buffer_processes (buffer)
7874 Lisp_Object buffer;
7878 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7879 0, 0, 0,
7880 doc: /* Return a list of numerical process IDs of all running processes.
7881 If this functionality is unsupported, return nil.
7883 See `process-attributes' for getting attributes of a process given its ID. */)
7886 return list_system_processes ();
7889 DEFUN ("process-attributes", Fprocess_attributes,
7890 Sprocess_attributes, 1, 1, 0,
7891 doc: /* Return attributes of the process given by its PID, a number.
7893 Value is an alist where each element is a cons cell of the form
7895 \(KEY . VALUE)
7897 If this functionality is unsupported, the value is nil.
7899 See `list-system-processes' for getting a list of all process IDs.
7901 The KEYs of the attributes that this function may return are listed
7902 below, together with the type of the associated VALUE (in parentheses).
7903 Not all platforms support all of these attributes; unsupported
7904 attributes will not appear in the returned alist.
7905 Unless explicitly indicated otherwise, numbers can have either
7906 integer or floating point values.
7908 euid -- Effective user User ID of the process (number)
7909 user -- User name corresponding to euid (string)
7910 egid -- Effective user Group ID of the process (number)
7911 group -- Group name corresponding to egid (string)
7912 comm -- Command name (executable name only) (string)
7913 state -- Process state code, such as "S", "R", or "T" (string)
7914 ppid -- Parent process ID (number)
7915 pgrp -- Process group ID (number)
7916 sess -- Session ID, i.e. process ID of session leader (number)
7917 ttname -- Controlling tty name (string)
7918 tpgid -- ID of foreground process group on the process's tty (number)
7919 minflt -- number of minor page faults (number)
7920 majflt -- number of major page faults (number)
7921 cminflt -- cumulative number of minor page faults (number)
7922 cmajflt -- cumulative number of major page faults (number)
7923 utime -- user time used by the process, in the (HIGH LOW USEC) format
7924 stime -- system time used by the process, in the (HIGH LOW USEC) format
7925 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7926 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7927 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7928 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7929 pri -- priority of the process (number)
7930 nice -- nice value of the process (number)
7931 thcount -- process thread count (number)
7932 start -- time the process started, in the (HIGH LOW USEC) format
7933 vsize -- virtual memory size of the process in KB's (number)
7934 rss -- resident set size of the process in KB's (number)
7935 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7936 pcpu -- percents of CPU time used by the process (floating-point number)
7937 pmem -- percents of total physical memory used by process's resident set
7938 (floating-point number)
7939 args -- command line which invoked the process (string). */)
7940 (pid)
7942 Lisp_Object pid;
7944 return system_process_attributes (pid);
7947 void
7948 init_process ()
7952 void
7953 syms_of_process ()
7955 QCtype = intern_c_string (":type");
7956 staticpro (&QCtype);
7957 QCname = intern_c_string (":name");
7958 staticpro (&QCname);
7959 QCtype = intern_c_string (":type");
7960 staticpro (&QCtype);
7961 QCname = intern_c_string (":name");
7962 staticpro (&QCname);
7963 Qeuid = intern_c_string ("euid");
7964 staticpro (&Qeuid);
7965 Qegid = intern_c_string ("egid");
7966 staticpro (&Qegid);
7967 Quser = intern_c_string ("user");
7968 staticpro (&Quser);
7969 Qgroup = intern_c_string ("group");
7970 staticpro (&Qgroup);
7971 Qcomm = intern_c_string ("comm");
7972 staticpro (&Qcomm);
7973 Qstate = intern_c_string ("state");
7974 staticpro (&Qstate);
7975 Qppid = intern_c_string ("ppid");
7976 staticpro (&Qppid);
7977 Qpgrp = intern_c_string ("pgrp");
7978 staticpro (&Qpgrp);
7979 Qsess = intern_c_string ("sess");
7980 staticpro (&Qsess);
7981 Qttname = intern_c_string ("ttname");
7982 staticpro (&Qttname);
7983 Qtpgid = intern_c_string ("tpgid");
7984 staticpro (&Qtpgid);
7985 Qminflt = intern_c_string ("minflt");
7986 staticpro (&Qminflt);
7987 Qmajflt = intern_c_string ("majflt");
7988 staticpro (&Qmajflt);
7989 Qcminflt = intern_c_string ("cminflt");
7990 staticpro (&Qcminflt);
7991 Qcmajflt = intern_c_string ("cmajflt");
7992 staticpro (&Qcmajflt);
7993 Qutime = intern_c_string ("utime");
7994 staticpro (&Qutime);
7995 Qstime = intern_c_string ("stime");
7996 staticpro (&Qstime);
7997 Qtime = intern_c_string ("time");
7998 staticpro (&Qtime);
7999 Qcutime = intern_c_string ("cutime");
8000 staticpro (&Qcutime);
8001 Qcstime = intern_c_string ("cstime");
8002 staticpro (&Qcstime);
8003 Qctime = intern_c_string ("ctime");
8004 staticpro (&Qctime);
8005 Qpri = intern_c_string ("pri");
8006 staticpro (&Qpri);
8007 Qnice = intern_c_string ("nice");
8008 staticpro (&Qnice);
8009 Qthcount = intern_c_string ("thcount");
8010 staticpro (&Qthcount);
8011 Qstart = intern_c_string ("start");
8012 staticpro (&Qstart);
8013 Qvsize = intern_c_string ("vsize");
8014 staticpro (&Qvsize);
8015 Qrss = intern_c_string ("rss");
8016 staticpro (&Qrss);
8017 Qetime = intern_c_string ("etime");
8018 staticpro (&Qetime);
8019 Qpcpu = intern_c_string ("pcpu");
8020 staticpro (&Qpcpu);
8021 Qpmem = intern_c_string ("pmem");
8022 staticpro (&Qpmem);
8023 Qargs = intern_c_string ("args");
8024 staticpro (&Qargs);
8026 defsubr (&Sget_buffer_process);
8027 defsubr (&Sprocess_inherit_coding_system_flag);
8028 defsubr (&Slist_system_processes);
8029 defsubr (&Sprocess_attributes);
8033 #endif /* not subprocesses */
8035 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
8036 (do not change this comment) */