* cus-start.el (all): Add native condition for font-use-system-font.
[emacs.git] / src / process.c
blob90f2a9aa6bb5232a4e85159de6749e77401cb238
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 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(BSD_SYSTEM)
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 /* BSD_SYSTEM */
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;
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 USE_CRT_DLL
199 extern int errno;
200 #endif
202 #ifndef HAVE_H_ERRNO
203 extern int h_errno;
204 #endif
206 /* t means use pty, nil means use a pipe,
207 maybe other values to come. */
208 static Lisp_Object Vprocess_connection_type;
210 /* These next two vars are non-static since sysdep.c uses them in the
211 emulation of `select'. */
212 /* Number of events of change of status of a process. */
213 int process_tick;
214 /* Number of events for which the user or sentinel has been notified. */
215 int update_tick;
217 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
219 #ifdef BROKEN_NON_BLOCKING_CONNECT
220 #undef NON_BLOCKING_CONNECT
221 #else
222 #ifndef NON_BLOCKING_CONNECT
223 #ifdef HAVE_SOCKETS
224 #ifdef HAVE_SELECT
225 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
226 #if defined (O_NONBLOCK) || defined (O_NDELAY)
227 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
228 #define NON_BLOCKING_CONNECT
229 #endif /* EWOULDBLOCK || EINPROGRESS */
230 #endif /* O_NONBLOCK || O_NDELAY */
231 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
232 #endif /* HAVE_SELECT */
233 #endif /* HAVE_SOCKETS */
234 #endif /* NON_BLOCKING_CONNECT */
235 #endif /* BROKEN_NON_BLOCKING_CONNECT */
237 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
238 this system. We need to read full packets, so we need a
239 "non-destructive" select. So we require either native select,
240 or emulation of select using FIONREAD. */
242 #ifdef BROKEN_DATAGRAM_SOCKETS
243 #undef DATAGRAM_SOCKETS
244 #else
245 #ifndef DATAGRAM_SOCKETS
246 #ifdef HAVE_SOCKETS
247 #if defined (HAVE_SELECT) || defined (FIONREAD)
248 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
249 #define DATAGRAM_SOCKETS
250 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
251 #endif /* HAVE_SELECT || FIONREAD */
252 #endif /* HAVE_SOCKETS */
253 #endif /* DATAGRAM_SOCKETS */
254 #endif /* BROKEN_DATAGRAM_SOCKETS */
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 #ifdef POSIX_SIGNALS
1870 sigset_t procmask;
1871 sigset_t blocked;
1872 struct sigaction sigint_action;
1873 struct sigaction sigquit_action;
1874 #ifdef AIX
1875 struct sigaction sighup_action;
1876 #endif
1877 #else /* !POSIX_SIGNALS */
1878 #if 0
1879 #ifdef SIGCHLD
1880 SIGTYPE (*sigchld)();
1881 #endif
1882 #endif /* 0 */
1883 #endif /* !POSIX_SIGNALS */
1884 /* Use volatile to protect variables from being clobbered by longjmp. */
1885 volatile int forkin, forkout;
1886 volatile int pty_flag = 0;
1887 #ifndef USE_CRT_DLL
1888 extern char **environ;
1889 #endif
1891 inchannel = outchannel = -1;
1893 #ifdef HAVE_PTYS
1894 if (!NILP (Vprocess_connection_type))
1895 outchannel = inchannel = allocate_pty ();
1897 if (inchannel >= 0)
1899 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1900 /* On most USG systems it does not work to open the pty's tty here,
1901 then close it and reopen it in the child. */
1902 #ifdef O_NOCTTY
1903 /* Don't let this terminal become our controlling terminal
1904 (in case we don't have one). */
1905 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1906 #else
1907 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1908 #endif
1909 if (forkin < 0)
1910 report_file_error ("Opening pty", Qnil);
1911 #else
1912 forkin = forkout = -1;
1913 #endif /* not USG, or USG_SUBTTY_WORKS */
1914 pty_flag = 1;
1916 else
1917 #endif /* HAVE_PTYS */
1919 int tem;
1920 tem = pipe (sv);
1921 if (tem < 0)
1922 report_file_error ("Creating pipe", Qnil);
1923 inchannel = sv[0];
1924 forkout = sv[1];
1925 tem = pipe (sv);
1926 if (tem < 0)
1928 emacs_close (inchannel);
1929 emacs_close (forkout);
1930 report_file_error ("Creating pipe", Qnil);
1932 outchannel = sv[1];
1933 forkin = sv[0];
1936 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1938 int tem;
1940 tem = pipe (wait_child_setup);
1941 if (tem < 0)
1942 report_file_error ("Creating pipe", Qnil);
1943 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1944 if (tem >= 0)
1945 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1946 if (tem < 0)
1948 emacs_close (wait_child_setup[0]);
1949 emacs_close (wait_child_setup[1]);
1950 report_file_error ("Setting file descriptor flags", Qnil);
1953 #endif
1955 #if 0
1956 /* Replaced by close_process_descs */
1957 set_exclusive_use (inchannel);
1958 set_exclusive_use (outchannel);
1959 #endif
1961 #ifdef O_NONBLOCK
1962 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1963 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1964 #else
1965 #ifdef O_NDELAY
1966 fcntl (inchannel, F_SETFL, O_NDELAY);
1967 fcntl (outchannel, F_SETFL, O_NDELAY);
1968 #endif
1969 #endif
1971 /* Record this as an active process, with its channels.
1972 As a result, child_setup will close Emacs's side of the pipes. */
1973 chan_process[inchannel] = process;
1974 XPROCESS (process)->infd = inchannel;
1975 XPROCESS (process)->outfd = outchannel;
1977 /* Previously we recorded the tty descriptor used in the subprocess.
1978 It was only used for getting the foreground tty process, so now
1979 we just reopen the device (see emacs_get_tty_pgrp) as this is
1980 more portable (see USG_SUBTTY_WORKS above). */
1982 XPROCESS (process)->pty_flag = pty_flag;
1983 XPROCESS (process)->status = Qrun;
1984 setup_process_coding_systems (process);
1986 /* Delay interrupts until we have a chance to store
1987 the new fork's pid in its process structure */
1988 #ifdef POSIX_SIGNALS
1989 sigemptyset (&blocked);
1990 #ifdef SIGCHLD
1991 sigaddset (&blocked, SIGCHLD);
1992 #endif
1993 #ifdef HAVE_WORKING_VFORK
1994 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1995 this sets the parent's signal handlers as well as the child's.
1996 So delay all interrupts whose handlers the child might munge,
1997 and record the current handlers so they can be restored later. */
1998 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1999 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
2000 #ifdef AIX
2001 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
2002 #endif
2003 #endif /* HAVE_WORKING_VFORK */
2004 sigprocmask (SIG_BLOCK, &blocked, &procmask);
2005 #else /* !POSIX_SIGNALS */
2006 #ifdef SIGCHLD
2007 #if defined (BSD_SYSTEM) || defined (HPUX)
2008 sigsetmask (sigmask (SIGCHLD));
2009 #else /* ordinary USG */
2010 #if 0
2011 sigchld_deferred = 0;
2012 sigchld = signal (SIGCHLD, create_process_sigchld);
2013 #endif
2014 #endif /* ordinary USG */
2015 #endif /* SIGCHLD */
2016 #endif /* !POSIX_SIGNALS */
2018 FD_SET (inchannel, &input_wait_mask);
2019 FD_SET (inchannel, &non_keyboard_wait_mask);
2020 if (inchannel > max_process_desc)
2021 max_process_desc = inchannel;
2023 /* Until we store the proper pid, enable sigchld_handler
2024 to recognize an unknown pid as standing for this process.
2025 It is very important not to let this `marker' value stay
2026 in the table after this function has returned; if it does
2027 it might cause call-process to hang and subsequent asynchronous
2028 processes to get their return values scrambled. */
2029 XPROCESS (process)->pid = -1;
2031 BLOCK_INPUT;
2034 /* child_setup must clobber environ on systems with true vfork.
2035 Protect it from permanent change. */
2036 char **save_environ = environ;
2038 current_dir = ENCODE_FILE (current_dir);
2040 #ifndef WINDOWSNT
2041 pid = vfork ();
2042 if (pid == 0)
2043 #endif /* not WINDOWSNT */
2045 int xforkin = forkin;
2046 int xforkout = forkout;
2048 #if 0 /* This was probably a mistake--it duplicates code later on,
2049 but fails to handle all the cases. */
2050 /* Make sure SIGCHLD is not blocked in the child. */
2051 sigsetmask (SIGEMPTYMASK);
2052 #endif
2054 /* Make the pty be the controlling terminal of the process. */
2055 #ifdef HAVE_PTYS
2056 /* First, disconnect its current controlling terminal. */
2057 #ifdef HAVE_SETSID
2058 /* We tried doing setsid only if pty_flag, but it caused
2059 process_set_signal to fail on SGI when using a pipe. */
2060 setsid ();
2061 /* Make the pty's terminal the controlling terminal. */
2062 if (pty_flag)
2064 #ifdef TIOCSCTTY
2065 /* We ignore the return value
2066 because faith@cs.unc.edu says that is necessary on Linux. */
2067 ioctl (xforkin, TIOCSCTTY, 0);
2068 #endif
2070 #else /* not HAVE_SETSID */
2071 #ifdef USG
2072 /* It's very important to call setpgrp here and no time
2073 afterwards. Otherwise, we lose our controlling tty which
2074 is set when we open the pty. */
2075 setpgrp ();
2076 #endif /* USG */
2077 #endif /* not HAVE_SETSID */
2078 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2079 if (pty_flag && xforkin >= 0)
2081 struct termios t;
2082 tcgetattr (xforkin, &t);
2083 t.c_lflag = LDISC1;
2084 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2085 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2087 #else
2088 #if defined (NTTYDISC) && defined (TIOCSETD)
2089 if (pty_flag && xforkin >= 0)
2091 /* Use new line discipline. */
2092 int ldisc = NTTYDISC;
2093 ioctl (xforkin, TIOCSETD, &ldisc);
2095 #endif
2096 #endif
2097 #ifdef TIOCNOTTY
2098 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2099 can do TIOCSPGRP only to the process's controlling tty. */
2100 if (pty_flag)
2102 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2103 I can't test it since I don't have 4.3. */
2104 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2105 ioctl (j, TIOCNOTTY, 0);
2106 emacs_close (j);
2107 #ifndef USG
2108 /* In order to get a controlling terminal on some versions
2109 of BSD, it is necessary to put the process in pgrp 0
2110 before it opens the terminal. */
2111 #ifdef HAVE_SETPGID
2112 setpgid (0, 0);
2113 #else
2114 setpgrp (0, 0);
2115 #endif
2116 #endif
2118 #endif /* TIOCNOTTY */
2120 #if !defined (DONT_REOPEN_PTY)
2121 /*** There is a suggestion that this ought to be a
2122 conditional on TIOCSPGRP,
2123 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2124 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2125 that system does seem to need this code, even though
2126 both HAVE_SETSID and TIOCSCTTY are defined. */
2127 /* Now close the pty (if we had it open) and reopen it.
2128 This makes the pty the controlling terminal of the subprocess. */
2129 if (pty_flag)
2132 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2133 would work? */
2134 if (xforkin >= 0)
2135 emacs_close (xforkin);
2136 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2138 if (xforkin < 0)
2140 emacs_write (1, "Couldn't open the pty terminal ", 31);
2141 emacs_write (1, pty_name, strlen (pty_name));
2142 emacs_write (1, "\n", 1);
2143 _exit (1);
2147 #endif /* not DONT_REOPEN_PTY */
2149 #ifdef SETUP_SLAVE_PTY
2150 if (pty_flag)
2152 SETUP_SLAVE_PTY;
2154 #endif /* SETUP_SLAVE_PTY */
2155 #ifdef AIX
2156 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2157 Now reenable it in the child, so it will die when we want it to. */
2158 if (pty_flag)
2159 signal (SIGHUP, SIG_DFL);
2160 #endif
2161 #endif /* HAVE_PTYS */
2163 signal (SIGINT, SIG_DFL);
2164 signal (SIGQUIT, SIG_DFL);
2166 /* Stop blocking signals in the child. */
2167 #ifdef POSIX_SIGNALS
2168 sigprocmask (SIG_SETMASK, &procmask, 0);
2169 #else /* !POSIX_SIGNALS */
2170 #ifdef SIGCHLD
2171 #if defined (BSD_SYSTEM) || defined (HPUX)
2172 sigsetmask (SIGEMPTYMASK);
2173 #else /* ordinary USG */
2174 #if 0
2175 signal (SIGCHLD, sigchld);
2176 #endif
2177 #endif /* ordinary USG */
2178 #endif /* SIGCHLD */
2179 #endif /* !POSIX_SIGNALS */
2181 if (pty_flag)
2182 child_setup_tty (xforkout);
2183 #ifdef WINDOWSNT
2184 pid = child_setup (xforkin, xforkout, xforkout,
2185 new_argv, 1, current_dir);
2186 #else /* not WINDOWSNT */
2187 #ifdef FD_CLOEXEC
2188 emacs_close (wait_child_setup[0]);
2189 #endif
2190 child_setup (xforkin, xforkout, xforkout,
2191 new_argv, 1, current_dir);
2192 #endif /* not WINDOWSNT */
2194 environ = save_environ;
2197 UNBLOCK_INPUT;
2199 /* This runs in the Emacs process. */
2200 if (pid < 0)
2202 if (forkin >= 0)
2203 emacs_close (forkin);
2204 if (forkin != forkout && forkout >= 0)
2205 emacs_close (forkout);
2207 else
2209 /* vfork succeeded. */
2210 XPROCESS (process)->pid = pid;
2212 #ifdef WINDOWSNT
2213 register_child (pid, inchannel);
2214 #endif /* WINDOWSNT */
2216 /* If the subfork execv fails, and it exits,
2217 this close hangs. I don't know why.
2218 So have an interrupt jar it loose. */
2220 struct atimer *timer;
2221 EMACS_TIME offset;
2223 stop_polling ();
2224 EMACS_SET_SECS_USECS (offset, 1, 0);
2225 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2227 if (forkin >= 0)
2228 emacs_close (forkin);
2230 cancel_atimer (timer);
2231 start_polling ();
2234 if (forkin != forkout && forkout >= 0)
2235 emacs_close (forkout);
2237 #ifdef HAVE_PTYS
2238 if (pty_flag)
2239 XPROCESS (process)->tty_name = build_string (pty_name);
2240 else
2241 #endif
2242 XPROCESS (process)->tty_name = Qnil;
2244 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2245 /* Wait for child_setup to complete in case that vfork is
2246 actually defined as fork. The descriptor wait_child_setup[1]
2247 of a pipe is closed at the child side either by close-on-exec
2248 on successful execvp or the _exit call in child_setup. */
2250 char dummy;
2252 emacs_close (wait_child_setup[1]);
2253 emacs_read (wait_child_setup[0], &dummy, 1);
2254 emacs_close (wait_child_setup[0]);
2256 #endif
2259 /* Restore the signal state whether vfork succeeded or not.
2260 (We will signal an error, below, if it failed.) */
2261 #ifdef POSIX_SIGNALS
2262 #ifdef HAVE_WORKING_VFORK
2263 /* Restore the parent's signal handlers. */
2264 sigaction (SIGINT, &sigint_action, 0);
2265 sigaction (SIGQUIT, &sigquit_action, 0);
2266 #ifdef AIX
2267 sigaction (SIGHUP, &sighup_action, 0);
2268 #endif
2269 #endif /* HAVE_WORKING_VFORK */
2270 /* Stop blocking signals in the parent. */
2271 sigprocmask (SIG_SETMASK, &procmask, 0);
2272 #else /* !POSIX_SIGNALS */
2273 #ifdef SIGCHLD
2274 #if defined (BSD_SYSTEM) || defined (HPUX)
2275 sigsetmask (SIGEMPTYMASK);
2276 #else /* ordinary USG */
2277 #if 0
2278 signal (SIGCHLD, sigchld);
2279 /* Now really handle any of these signals
2280 that came in during this function. */
2281 if (sigchld_deferred)
2282 kill (getpid (), SIGCHLD);
2283 #endif
2284 #endif /* ordinary USG */
2285 #endif /* SIGCHLD */
2286 #endif /* !POSIX_SIGNALS */
2288 /* Now generate the error if vfork failed. */
2289 if (pid < 0)
2290 report_file_error ("Doing vfork", Qnil);
2293 void
2294 create_pty (process)
2295 Lisp_Object process;
2297 int inchannel, outchannel;
2299 /* Use volatile to protect variables from being clobbered by longjmp. */
2300 volatile int forkin, forkout;
2301 volatile int pty_flag = 0;
2303 inchannel = outchannel = -1;
2305 #ifdef HAVE_PTYS
2306 if (!NILP (Vprocess_connection_type))
2307 outchannel = inchannel = allocate_pty ();
2309 if (inchannel >= 0)
2311 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2312 /* On most USG systems it does not work to open the pty's tty here,
2313 then close it and reopen it in the child. */
2314 #ifdef O_NOCTTY
2315 /* Don't let this terminal become our controlling terminal
2316 (in case we don't have one). */
2317 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2318 #else
2319 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2320 #endif
2321 if (forkin < 0)
2322 report_file_error ("Opening pty", Qnil);
2323 #if defined (DONT_REOPEN_PTY)
2324 /* In the case that vfork is defined as fork, the parent process
2325 (Emacs) may send some data before the child process completes
2326 tty options setup. So we setup tty before forking. */
2327 child_setup_tty (forkout);
2328 #endif /* DONT_REOPEN_PTY */
2329 #else
2330 forkin = forkout = -1;
2331 #endif /* not USG, or USG_SUBTTY_WORKS */
2332 pty_flag = 1;
2334 #endif /* HAVE_PTYS */
2336 #ifdef O_NONBLOCK
2337 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2338 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2339 #else
2340 #ifdef O_NDELAY
2341 fcntl (inchannel, F_SETFL, O_NDELAY);
2342 fcntl (outchannel, F_SETFL, O_NDELAY);
2343 #endif
2344 #endif
2346 /* Record this as an active process, with its channels.
2347 As a result, child_setup will close Emacs's side of the pipes. */
2348 chan_process[inchannel] = process;
2349 XPROCESS (process)->infd = inchannel;
2350 XPROCESS (process)->outfd = outchannel;
2352 /* Previously we recorded the tty descriptor used in the subprocess.
2353 It was only used for getting the foreground tty process, so now
2354 we just reopen the device (see emacs_get_tty_pgrp) as this is
2355 more portable (see USG_SUBTTY_WORKS above). */
2357 XPROCESS (process)->pty_flag = pty_flag;
2358 XPROCESS (process)->status = Qrun;
2359 setup_process_coding_systems (process);
2361 FD_SET (inchannel, &input_wait_mask);
2362 FD_SET (inchannel, &non_keyboard_wait_mask);
2363 if (inchannel > max_process_desc)
2364 max_process_desc = inchannel;
2366 XPROCESS (process)->pid = -2;
2367 #ifdef HAVE_PTYS
2368 if (pty_flag)
2369 XPROCESS (process)->tty_name = build_string (pty_name);
2370 else
2371 #endif
2372 XPROCESS (process)->tty_name = Qnil;
2376 #ifdef HAVE_SOCKETS
2378 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2379 The address family of sa is not included in the result. */
2381 static Lisp_Object
2382 conv_sockaddr_to_lisp (sa, len)
2383 struct sockaddr *sa;
2384 int len;
2386 Lisp_Object address;
2387 int i;
2388 unsigned char *cp;
2389 register struct Lisp_Vector *p;
2391 /* Workaround for a bug in getsockname on BSD: Names bound to
2392 sockets in the UNIX domain are inaccessible; getsockname returns
2393 a zero length name. */
2394 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2395 return empty_unibyte_string;
2397 switch (sa->sa_family)
2399 case AF_INET:
2401 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2402 len = sizeof (sin->sin_addr) + 1;
2403 address = Fmake_vector (make_number (len), Qnil);
2404 p = XVECTOR (address);
2405 p->contents[--len] = make_number (ntohs (sin->sin_port));
2406 cp = (unsigned char *) &sin->sin_addr;
2407 break;
2409 #ifdef AF_INET6
2410 case AF_INET6:
2412 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2413 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2414 len = sizeof (sin6->sin6_addr)/2 + 1;
2415 address = Fmake_vector (make_number (len), Qnil);
2416 p = XVECTOR (address);
2417 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2418 for (i = 0; i < len; i++)
2419 p->contents[i] = make_number (ntohs (ip6[i]));
2420 return address;
2422 #endif
2423 #ifdef HAVE_LOCAL_SOCKETS
2424 case AF_LOCAL:
2426 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2427 for (i = 0; i < sizeof (sockun->sun_path); i++)
2428 if (sockun->sun_path[i] == 0)
2429 break;
2430 return make_unibyte_string (sockun->sun_path, i);
2432 #endif
2433 default:
2434 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2435 address = Fcons (make_number (sa->sa_family),
2436 Fmake_vector (make_number (len), Qnil));
2437 p = XVECTOR (XCDR (address));
2438 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2439 break;
2442 i = 0;
2443 while (i < len)
2444 p->contents[i++] = make_number (*cp++);
2446 return address;
2450 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2452 static int
2453 get_lisp_to_sockaddr_size (address, familyp)
2454 Lisp_Object address;
2455 int *familyp;
2457 register struct Lisp_Vector *p;
2459 if (VECTORP (address))
2461 p = XVECTOR (address);
2462 if (p->size == 5)
2464 *familyp = AF_INET;
2465 return sizeof (struct sockaddr_in);
2467 #ifdef AF_INET6
2468 else if (p->size == 9)
2470 *familyp = AF_INET6;
2471 return sizeof (struct sockaddr_in6);
2473 #endif
2475 #ifdef HAVE_LOCAL_SOCKETS
2476 else if (STRINGP (address))
2478 *familyp = AF_LOCAL;
2479 return sizeof (struct sockaddr_un);
2481 #endif
2482 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2484 struct sockaddr *sa;
2485 *familyp = XINT (XCAR (address));
2486 p = XVECTOR (XCDR (address));
2487 return p->size + sizeof (sa->sa_family);
2489 return 0;
2492 /* Convert an address object (vector or string) to an internal sockaddr.
2494 The address format has been basically validated by
2495 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2496 it could have come from user data. So if FAMILY is not valid,
2497 we return after zeroing *SA. */
2499 static void
2500 conv_lisp_to_sockaddr (family, address, sa, len)
2501 int family;
2502 Lisp_Object address;
2503 struct sockaddr *sa;
2504 int len;
2506 register struct Lisp_Vector *p;
2507 register unsigned char *cp = NULL;
2508 register int i;
2510 bzero (sa, len);
2512 if (VECTORP (address))
2514 p = XVECTOR (address);
2515 if (family == AF_INET)
2517 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2518 len = sizeof (sin->sin_addr) + 1;
2519 i = XINT (p->contents[--len]);
2520 sin->sin_port = htons (i);
2521 cp = (unsigned char *)&sin->sin_addr;
2522 sa->sa_family = family;
2524 #ifdef AF_INET6
2525 else if (family == AF_INET6)
2527 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2528 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2529 len = sizeof (sin6->sin6_addr) + 1;
2530 i = XINT (p->contents[--len]);
2531 sin6->sin6_port = htons (i);
2532 for (i = 0; i < len; i++)
2533 if (INTEGERP (p->contents[i]))
2535 int j = XFASTINT (p->contents[i]) & 0xffff;
2536 ip6[i] = ntohs (j);
2538 sa->sa_family = family;
2540 #endif
2541 return;
2543 else if (STRINGP (address))
2545 #ifdef HAVE_LOCAL_SOCKETS
2546 if (family == AF_LOCAL)
2548 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2549 cp = SDATA (address);
2550 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2551 sockun->sun_path[i] = *cp++;
2552 sa->sa_family = family;
2554 #endif
2555 return;
2557 else
2559 p = XVECTOR (XCDR (address));
2560 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2563 for (i = 0; i < len; i++)
2564 if (INTEGERP (p->contents[i]))
2565 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2568 #ifdef DATAGRAM_SOCKETS
2569 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2570 1, 1, 0,
2571 doc: /* Get the current datagram address associated with PROCESS. */)
2572 (process)
2573 Lisp_Object process;
2575 int channel;
2577 CHECK_PROCESS (process);
2579 if (!DATAGRAM_CONN_P (process))
2580 return Qnil;
2582 channel = XPROCESS (process)->infd;
2583 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2584 datagram_address[channel].len);
2587 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2588 2, 2, 0,
2589 doc: /* Set the datagram address for PROCESS to ADDRESS.
2590 Returns nil upon error setting address, ADDRESS otherwise. */)
2591 (process, address)
2592 Lisp_Object process, address;
2594 int channel;
2595 int family, len;
2597 CHECK_PROCESS (process);
2599 if (!DATAGRAM_CONN_P (process))
2600 return Qnil;
2602 channel = XPROCESS (process)->infd;
2604 len = get_lisp_to_sockaddr_size (address, &family);
2605 if (datagram_address[channel].len != len)
2606 return Qnil;
2607 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2608 return address;
2610 #endif
2613 static const struct socket_options {
2614 /* The name of this option. Should be lowercase version of option
2615 name without SO_ prefix. */
2616 char *name;
2617 /* Option level SOL_... */
2618 int optlevel;
2619 /* Option number SO_... */
2620 int optnum;
2621 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2622 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2623 } socket_options[] =
2625 #ifdef SO_BINDTODEVICE
2626 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2627 #endif
2628 #ifdef SO_BROADCAST
2629 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2630 #endif
2631 #ifdef SO_DONTROUTE
2632 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2633 #endif
2634 #ifdef SO_KEEPALIVE
2635 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2636 #endif
2637 #ifdef SO_LINGER
2638 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2639 #endif
2640 #ifdef SO_OOBINLINE
2641 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2642 #endif
2643 #ifdef SO_PRIORITY
2644 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2645 #endif
2646 #ifdef SO_REUSEADDR
2647 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2648 #endif
2649 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2652 /* Set option OPT to value VAL on socket S.
2654 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2655 Signals an error if setting a known option fails.
2658 static int
2659 set_socket_option (s, opt, val)
2660 int s;
2661 Lisp_Object opt, val;
2663 char *name;
2664 const struct socket_options *sopt;
2665 int ret = 0;
2667 CHECK_SYMBOL (opt);
2669 name = (char *) SDATA (SYMBOL_NAME (opt));
2670 for (sopt = socket_options; sopt->name; sopt++)
2671 if (strcmp (name, sopt->name) == 0)
2672 break;
2674 switch (sopt->opttype)
2676 case SOPT_BOOL:
2678 int optval;
2679 optval = NILP (val) ? 0 : 1;
2680 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2681 &optval, sizeof (optval));
2682 break;
2685 case SOPT_INT:
2687 int optval;
2688 if (INTEGERP (val))
2689 optval = XINT (val);
2690 else
2691 error ("Bad option value for %s", name);
2692 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2693 &optval, sizeof (optval));
2694 break;
2697 #ifdef SO_BINDTODEVICE
2698 case SOPT_IFNAME:
2700 char devname[IFNAMSIZ+1];
2702 /* This is broken, at least in the Linux 2.4 kernel.
2703 To unbind, the arg must be a zero integer, not the empty string.
2704 This should work on all systems. KFS. 2003-09-23. */
2705 bzero (devname, sizeof devname);
2706 if (STRINGP (val))
2708 char *arg = (char *) SDATA (val);
2709 int len = min (strlen (arg), IFNAMSIZ);
2710 bcopy (arg, devname, len);
2712 else if (!NILP (val))
2713 error ("Bad option value for %s", name);
2714 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2715 devname, IFNAMSIZ);
2716 break;
2718 #endif
2720 #ifdef SO_LINGER
2721 case SOPT_LINGER:
2723 struct linger linger;
2725 linger.l_onoff = 1;
2726 linger.l_linger = 0;
2727 if (INTEGERP (val))
2728 linger.l_linger = XINT (val);
2729 else
2730 linger.l_onoff = NILP (val) ? 0 : 1;
2731 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2732 &linger, sizeof (linger));
2733 break;
2735 #endif
2737 default:
2738 return 0;
2741 if (ret < 0)
2742 report_file_error ("Cannot set network option",
2743 Fcons (opt, Fcons (val, Qnil)));
2744 return (1 << sopt->optbit);
2748 DEFUN ("set-network-process-option",
2749 Fset_network_process_option, Sset_network_process_option,
2750 3, 4, 0,
2751 doc: /* For network process PROCESS set option OPTION to value VALUE.
2752 See `make-network-process' for a list of options and values.
2753 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2754 OPTION is not a supported option, return nil instead; otherwise return t. */)
2755 (process, option, value, no_error)
2756 Lisp_Object process, option, value;
2757 Lisp_Object no_error;
2759 int s;
2760 struct Lisp_Process *p;
2762 CHECK_PROCESS (process);
2763 p = XPROCESS (process);
2764 if (!NETCONN1_P (p))
2765 error ("Process is not a network process");
2767 s = p->infd;
2768 if (s < 0)
2769 error ("Process is not running");
2771 if (set_socket_option (s, option, value))
2773 p->childp = Fplist_put (p->childp, option, value);
2774 return Qt;
2777 if (NILP (no_error))
2778 error ("Unknown or unsupported option");
2780 return Qnil;
2784 #ifdef HAVE_SERIAL
2785 DEFUN ("serial-process-configure",
2786 Fserial_process_configure,
2787 Sserial_process_configure,
2788 0, MANY, 0,
2789 doc: /* Configure speed, bytesize, etc. of a serial process.
2791 Arguments are specified as keyword/argument pairs. Attributes that
2792 are not given are re-initialized from the process's current
2793 configuration (available via the function `process-contact') or set to
2794 reasonable default values. The following arguments are defined:
2796 :process PROCESS
2797 :name NAME
2798 :buffer BUFFER
2799 :port PORT
2800 -- Any of these arguments can be given to identify the process that is
2801 to be configured. If none of these arguments is given, the current
2802 buffer's process is used.
2804 :speed SPEED -- SPEED is the speed of the serial port in bits per
2805 second, also called baud rate. Any value can be given for SPEED, but
2806 most serial ports work only at a few defined values between 1200 and
2807 115200, with 9600 being the most common value. If SPEED is nil, the
2808 serial port is not configured any further, i.e., all other arguments
2809 are ignored. This may be useful for special serial ports such as
2810 Bluetooth-to-serial converters which can only be configured through AT
2811 commands. A value of nil for SPEED can be used only when passed
2812 through `make-serial-process' or `serial-term'.
2814 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2815 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2817 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2818 `odd' (use odd parity), or the symbol `even' (use even parity). If
2819 PARITY is not given, no parity is used.
2821 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2822 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2823 is not given or nil, 1 stopbit is used.
2825 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2826 flowcontrol to be used, which is either nil (don't use flowcontrol),
2827 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2828 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2829 flowcontrol is used.
2831 `serial-process-configure' is called by `make-serial-process' for the
2832 initial configuration of the serial port.
2834 Examples:
2836 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2838 \(serial-process-configure
2839 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2841 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2843 usage: (serial-process-configure &rest ARGS) */)
2844 (nargs, args)
2845 int nargs;
2846 Lisp_Object *args;
2848 struct Lisp_Process *p;
2849 Lisp_Object contact = Qnil;
2850 Lisp_Object proc = Qnil;
2851 struct gcpro gcpro1;
2853 contact = Flist (nargs, args);
2854 GCPRO1 (contact);
2856 proc = Fplist_get (contact, QCprocess);
2857 if (NILP (proc))
2858 proc = Fplist_get (contact, QCname);
2859 if (NILP (proc))
2860 proc = Fplist_get (contact, QCbuffer);
2861 if (NILP (proc))
2862 proc = Fplist_get (contact, QCport);
2863 proc = get_process (proc);
2864 p = XPROCESS (proc);
2865 if (!EQ (p->type, Qserial))
2866 error ("Not a serial process");
2868 if (NILP (Fplist_get (p->childp, QCspeed)))
2870 UNGCPRO;
2871 return Qnil;
2874 serial_configure (p, contact);
2876 UNGCPRO;
2877 return Qnil;
2880 /* Used by make-serial-process to recover from errors. */
2881 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2883 if (!PROCESSP (proc))
2884 abort ();
2885 remove_process (proc);
2886 return Qnil;
2889 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2890 0, MANY, 0,
2891 doc: /* Create and return a serial port process.
2893 In Emacs, serial port connections are represented by process objects,
2894 so input and output work as for subprocesses, and `delete-process'
2895 closes a serial port connection. However, a serial process has no
2896 process id, it cannot be signaled, and the status codes are different
2897 from normal processes.
2899 `make-serial-process' creates a process and a buffer, on which you
2900 probably want to use `process-send-string'. Try \\[serial-term] for
2901 an interactive terminal. See below for examples.
2903 Arguments are specified as keyword/argument pairs. The following
2904 arguments are defined:
2906 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2907 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2908 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2909 the backslashes in strings).
2911 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2912 which is called by `make-serial-process'.
2914 :name NAME -- NAME is the name of the process. If NAME is not given,
2915 the value of PORT is used.
2917 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2918 with the process. Process output goes at the end of that buffer,
2919 unless you specify an output stream or filter function to handle the
2920 output. If BUFFER is not given, the value of NAME is used.
2922 :coding CODING -- If CODING is a symbol, it specifies the coding
2923 system used for both reading and writing for this process. If CODING
2924 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2925 ENCODING is used for writing.
2927 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2928 the process is running. If BOOL is not given, query before exiting.
2930 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2931 In the stopped state, a serial process does not accept incoming data,
2932 but you can send outgoing data. The stopped state is cleared by
2933 `continue-process' and set by `stop-process'.
2935 :filter FILTER -- Install FILTER as the process filter.
2937 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2939 :plist PLIST -- Install PLIST as the initial plist of the process.
2941 :speed
2942 :bytesize
2943 :parity
2944 :stopbits
2945 :flowcontrol
2946 -- These arguments are handled by `serial-process-configure', which is
2947 called by `make-serial-process'.
2949 The original argument list, possibly modified by later configuration,
2950 is available via the function `process-contact'.
2952 Examples:
2954 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2956 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2958 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2960 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2962 usage: (make-serial-process &rest ARGS) */)
2963 (nargs, args)
2964 int nargs;
2965 Lisp_Object *args;
2967 int fd = -1;
2968 Lisp_Object proc, contact, port;
2969 struct Lisp_Process *p;
2970 struct gcpro gcpro1;
2971 Lisp_Object name, buffer;
2972 Lisp_Object tem, val;
2973 int specpdl_count = -1;
2975 if (nargs == 0)
2976 return Qnil;
2978 contact = Flist (nargs, args);
2979 GCPRO1 (contact);
2981 port = Fplist_get (contact, QCport);
2982 if (NILP (port))
2983 error ("No port specified");
2984 CHECK_STRING (port);
2986 if (NILP (Fplist_member (contact, QCspeed)))
2987 error (":speed not specified");
2988 if (!NILP (Fplist_get (contact, QCspeed)))
2989 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2991 name = Fplist_get (contact, QCname);
2992 if (NILP (name))
2993 name = port;
2994 CHECK_STRING (name);
2995 proc = make_process (name);
2996 specpdl_count = SPECPDL_INDEX ();
2997 record_unwind_protect (make_serial_process_unwind, proc);
2998 p = XPROCESS (proc);
3000 fd = serial_open ((char*) SDATA (port));
3001 p->infd = fd;
3002 p->outfd = fd;
3003 if (fd > max_process_desc)
3004 max_process_desc = fd;
3005 chan_process[fd] = proc;
3007 buffer = Fplist_get (contact, QCbuffer);
3008 if (NILP (buffer))
3009 buffer = name;
3010 buffer = Fget_buffer_create (buffer);
3011 p->buffer = buffer;
3013 p->childp = contact;
3014 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3015 p->type = Qserial;
3016 p->sentinel = Fplist_get (contact, QCsentinel);
3017 p->filter = Fplist_get (contact, QCfilter);
3018 p->log = Qnil;
3019 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3020 p->kill_without_query = 1;
3021 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3022 p->command = Qt;
3023 p->pty_flag = 0;
3025 if (!EQ (p->command, Qt))
3027 FD_SET (fd, &input_wait_mask);
3028 FD_SET (fd, &non_keyboard_wait_mask);
3031 if (BUFFERP (buffer))
3033 set_marker_both (p->mark, buffer,
3034 BUF_ZV (XBUFFER (buffer)),
3035 BUF_ZV_BYTE (XBUFFER (buffer)));
3038 tem = Fplist_member (contact, QCcoding);
3039 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3040 tem = Qnil;
3042 val = Qnil;
3043 if (!NILP (tem))
3045 val = XCAR (XCDR (tem));
3046 if (CONSP (val))
3047 val = XCAR (val);
3049 else if (!NILP (Vcoding_system_for_read))
3050 val = Vcoding_system_for_read;
3051 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3052 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3053 val = Qnil;
3054 p->decode_coding_system = val;
3056 val = Qnil;
3057 if (!NILP (tem))
3059 val = XCAR (XCDR (tem));
3060 if (CONSP (val))
3061 val = XCDR (val);
3063 else if (!NILP (Vcoding_system_for_write))
3064 val = Vcoding_system_for_write;
3065 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3066 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3067 val = Qnil;
3068 p->encode_coding_system = val;
3070 setup_process_coding_systems (proc);
3071 p->decoding_buf = make_uninit_string (0);
3072 p->decoding_carryover = 0;
3073 p->encoding_buf = make_uninit_string (0);
3074 p->inherit_coding_system_flag
3075 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3077 Fserial_process_configure(nargs, args);
3079 specpdl_ptr = specpdl + specpdl_count;
3081 UNGCPRO;
3082 return proc;
3084 #endif /* HAVE_SERIAL */
3086 /* Create a network stream/datagram client/server process. Treated
3087 exactly like a normal process when reading and writing. Primary
3088 differences are in status display and process deletion. A network
3089 connection has no PID; you cannot signal it. All you can do is
3090 stop/continue it and deactivate/close it via delete-process */
3092 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3093 0, MANY, 0,
3094 doc: /* Create and return a network server or client process.
3096 In Emacs, network connections are represented by process objects, so
3097 input and output work as for subprocesses and `delete-process' closes
3098 a network connection. However, a network process has no process id,
3099 it cannot be signaled, and the status codes are different from normal
3100 processes.
3102 Arguments are specified as keyword/argument pairs. The following
3103 arguments are defined:
3105 :name NAME -- NAME is name for process. It is modified if necessary
3106 to make it unique.
3108 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3109 with the process. Process output goes at end of that buffer, unless
3110 you specify an output stream or filter function to handle the output.
3111 BUFFER may be also nil, meaning that this process is not associated
3112 with any buffer.
3114 :host HOST -- HOST is name of the host to connect to, or its IP
3115 address. The symbol `local' specifies the local host. If specified
3116 for a server process, it must be a valid name or address for the local
3117 host, and only clients connecting to that address will be accepted.
3119 :service SERVICE -- SERVICE is name of the service desired, or an
3120 integer specifying a port number to connect to. If SERVICE is t,
3121 a random port number is selected for the server. (If Emacs was
3122 compiled with getaddrinfo, a port number can also be specified as a
3123 string, e.g. "80", as well as an integer. This is not portable.)
3125 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3126 stream type connection, `datagram' creates a datagram type connection.
3128 :family FAMILY -- FAMILY is the address (and protocol) family for the
3129 service specified by HOST and SERVICE. The default (nil) is to use
3130 whatever address family (IPv4 or IPv6) that is defined for the host
3131 and port number specified by HOST and SERVICE. Other address families
3132 supported are:
3133 local -- for a local (i.e. UNIX) address specified by SERVICE.
3134 ipv4 -- use IPv4 address family only.
3135 ipv6 -- use IPv6 address family only.
3137 :local ADDRESS -- ADDRESS is the local address used for the connection.
3138 This parameter is ignored when opening a client process. When specified
3139 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3141 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3142 connection. This parameter is ignored when opening a stream server
3143 process. For a datagram server process, it specifies the initial
3144 setting of the remote datagram address. When specified for a client
3145 process, the FAMILY, HOST, and SERVICE args are ignored.
3147 The format of ADDRESS depends on the address family:
3148 - An IPv4 address is represented as an vector of integers [A B C D P]
3149 corresponding to numeric IP address A.B.C.D and port number P.
3150 - A local address is represented as a string with the address in the
3151 local address space.
3152 - An "unsupported family" address is represented by a cons (F . AV)
3153 where F is the family number and AV is a vector containing the socket
3154 address data with one element per address data byte. Do not rely on
3155 this format in portable code, as it may depend on implementation
3156 defined constants, data sizes, and data structure alignment.
3158 :coding CODING -- If CODING is a symbol, it specifies the coding
3159 system used for both reading and writing for this process. If CODING
3160 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3161 ENCODING is used for writing.
3163 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3164 return without waiting for the connection to complete; instead, the
3165 sentinel function will be called with second arg matching "open" (if
3166 successful) or "failed" when the connect completes. Default is to use
3167 a blocking connect (i.e. wait) for stream type connections.
3169 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3170 running when Emacs is exited.
3172 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3173 In the stopped state, a server process does not accept new
3174 connections, and a client process does not handle incoming traffic.
3175 The stopped state is cleared by `continue-process' and set by
3176 `stop-process'.
3178 :filter FILTER -- Install FILTER as the process filter.
3180 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3181 process filter are multibyte, otherwise they are unibyte.
3182 If this keyword is not specified, the strings are multibyte if
3183 `default-enable-multibyte-characters' is non-nil.
3185 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3187 :log LOG -- Install LOG as the server process log function. This
3188 function is called when the server accepts a network connection from a
3189 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3190 is the server process, CLIENT is the new process for the connection,
3191 and MESSAGE is a string.
3193 :plist PLIST -- Install PLIST as the new process' initial plist.
3195 :server QLEN -- if QLEN is non-nil, create a server process for the
3196 specified FAMILY, SERVICE, and connection type (stream or datagram).
3197 If QLEN is an integer, it is used as the max. length of the server's
3198 pending connection queue (also known as the backlog); the default
3199 queue length is 5. Default is to create a client process.
3201 The following network options can be specified for this connection:
3203 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3204 :dontroute BOOL -- Only send to directly connected hosts.
3205 :keepalive BOOL -- Send keep-alive messages on network stream.
3206 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3207 :oobinline BOOL -- Place out-of-band data in receive data stream.
3208 :priority INT -- Set protocol defined priority for sent packets.
3209 :reuseaddr BOOL -- Allow reusing a recently used local address
3210 (this is allowed by default for a server process).
3211 :bindtodevice NAME -- bind to interface NAME. Using this may require
3212 special privileges on some systems.
3214 Consult the relevant system programmer's manual pages for more
3215 information on using these options.
3218 A server process will listen for and accept connections from clients.
3219 When a client connection is accepted, a new network process is created
3220 for the connection with the following parameters:
3222 - The client's process name is constructed by concatenating the server
3223 process' NAME and a client identification string.
3224 - If the FILTER argument is non-nil, the client process will not get a
3225 separate process buffer; otherwise, the client's process buffer is a newly
3226 created buffer named after the server process' BUFFER name or process
3227 NAME concatenated with the client identification string.
3228 - The connection type and the process filter and sentinel parameters are
3229 inherited from the server process' TYPE, FILTER and SENTINEL.
3230 - The client process' contact info is set according to the client's
3231 addressing information (typically an IP address and a port number).
3232 - The client process' plist is initialized from the server's plist.
3234 Notice that the FILTER and SENTINEL args are never used directly by
3235 the server process. Also, the BUFFER argument is not used directly by
3236 the server process, but via the optional :log function, accepted (and
3237 failed) connections may be logged in the server process' buffer.
3239 The original argument list, modified with the actual connection
3240 information, is available via the `process-contact' function.
3242 usage: (make-network-process &rest ARGS) */)
3243 (nargs, args)
3244 int nargs;
3245 Lisp_Object *args;
3247 Lisp_Object proc;
3248 Lisp_Object contact;
3249 struct Lisp_Process *p;
3250 #ifdef HAVE_GETADDRINFO
3251 struct addrinfo ai, *res, *lres;
3252 struct addrinfo hints;
3253 char *portstring, portbuf[128];
3254 #else /* HAVE_GETADDRINFO */
3255 struct _emacs_addrinfo
3257 int ai_family;
3258 int ai_socktype;
3259 int ai_protocol;
3260 int ai_addrlen;
3261 struct sockaddr *ai_addr;
3262 struct _emacs_addrinfo *ai_next;
3263 } ai, *res, *lres;
3264 #endif /* HAVE_GETADDRINFO */
3265 struct sockaddr_in address_in;
3266 #ifdef HAVE_LOCAL_SOCKETS
3267 struct sockaddr_un address_un;
3268 #endif
3269 int port;
3270 int ret = 0;
3271 int xerrno = 0;
3272 int s = -1, outch, inch;
3273 struct gcpro gcpro1;
3274 int count = SPECPDL_INDEX ();
3275 int count1;
3276 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3277 Lisp_Object tem;
3278 Lisp_Object name, buffer, host, service, address;
3279 Lisp_Object filter, sentinel;
3280 int is_non_blocking_client = 0;
3281 int is_server = 0, backlog = 5;
3282 int socktype;
3283 int family = -1;
3285 if (nargs == 0)
3286 return Qnil;
3288 /* Save arguments for process-contact and clone-process. */
3289 contact = Flist (nargs, args);
3290 GCPRO1 (contact);
3292 #ifdef WINDOWSNT
3293 /* Ensure socket support is loaded if available. */
3294 init_winsock (TRUE);
3295 #endif
3297 /* :type TYPE (nil: stream, datagram */
3298 tem = Fplist_get (contact, QCtype);
3299 if (NILP (tem))
3300 socktype = SOCK_STREAM;
3301 #ifdef DATAGRAM_SOCKETS
3302 else if (EQ (tem, Qdatagram))
3303 socktype = SOCK_DGRAM;
3304 #endif
3305 else
3306 error ("Unsupported connection type");
3308 /* :server BOOL */
3309 tem = Fplist_get (contact, QCserver);
3310 if (!NILP (tem))
3312 /* Don't support network sockets when non-blocking mode is
3313 not available, since a blocked Emacs is not useful. */
3314 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3315 error ("Network servers not supported");
3316 #else
3317 is_server = 1;
3318 if (INTEGERP (tem))
3319 backlog = XINT (tem);
3320 #endif
3323 /* Make QCaddress an alias for :local (server) or :remote (client). */
3324 QCaddress = is_server ? QClocal : QCremote;
3326 /* :nowait BOOL */
3327 if (!is_server && socktype == SOCK_STREAM
3328 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3330 #ifndef NON_BLOCKING_CONNECT
3331 error ("Non-blocking connect not supported");
3332 #else
3333 is_non_blocking_client = 1;
3334 #endif
3337 name = Fplist_get (contact, QCname);
3338 buffer = Fplist_get (contact, QCbuffer);
3339 filter = Fplist_get (contact, QCfilter);
3340 sentinel = Fplist_get (contact, QCsentinel);
3342 CHECK_STRING (name);
3344 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3345 ai.ai_socktype = socktype;
3346 ai.ai_protocol = 0;
3347 ai.ai_next = NULL;
3348 res = &ai;
3350 /* :local ADDRESS or :remote ADDRESS */
3351 address = Fplist_get (contact, QCaddress);
3352 if (!NILP (address))
3354 host = service = Qnil;
3356 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3357 error ("Malformed :address");
3358 ai.ai_family = family;
3359 ai.ai_addr = alloca (ai.ai_addrlen);
3360 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3361 goto open_socket;
3364 /* :family FAMILY -- nil (for Inet), local, or integer. */
3365 tem = Fplist_get (contact, QCfamily);
3366 if (NILP (tem))
3368 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3369 family = AF_UNSPEC;
3370 #else
3371 family = AF_INET;
3372 #endif
3374 #ifdef HAVE_LOCAL_SOCKETS
3375 else if (EQ (tem, Qlocal))
3376 family = AF_LOCAL;
3377 #endif
3378 #ifdef AF_INET6
3379 else if (EQ (tem, Qipv6))
3380 family = AF_INET6;
3381 #endif
3382 else if (EQ (tem, Qipv4))
3383 family = AF_INET;
3384 else if (INTEGERP (tem))
3385 family = XINT (tem);
3386 else
3387 error ("Unknown address family");
3389 ai.ai_family = family;
3391 /* :service SERVICE -- string, integer (port number), or t (random port). */
3392 service = Fplist_get (contact, QCservice);
3394 #ifdef HAVE_LOCAL_SOCKETS
3395 if (family == AF_LOCAL)
3397 /* Host is not used. */
3398 host = Qnil;
3399 CHECK_STRING (service);
3400 bzero (&address_un, sizeof address_un);
3401 address_un.sun_family = AF_LOCAL;
3402 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3403 ai.ai_addr = (struct sockaddr *) &address_un;
3404 ai.ai_addrlen = sizeof address_un;
3405 goto open_socket;
3407 #endif
3409 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3410 host = Fplist_get (contact, QChost);
3411 if (!NILP (host))
3413 if (EQ (host, Qlocal))
3414 host = build_string ("localhost");
3415 CHECK_STRING (host);
3418 /* Slow down polling to every ten seconds.
3419 Some kernels have a bug which causes retrying connect to fail
3420 after a connect. Polling can interfere with gethostbyname too. */
3421 #ifdef POLL_FOR_INPUT
3422 if (socktype == SOCK_STREAM)
3424 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3425 bind_polling_period (10);
3427 #endif
3429 #ifdef HAVE_GETADDRINFO
3430 /* If we have a host, use getaddrinfo to resolve both host and service.
3431 Otherwise, use getservbyname to lookup the service. */
3432 if (!NILP (host))
3435 /* SERVICE can either be a string or int.
3436 Convert to a C string for later use by getaddrinfo. */
3437 if (EQ (service, Qt))
3438 portstring = "0";
3439 else if (INTEGERP (service))
3441 sprintf (portbuf, "%ld", (long) XINT (service));
3442 portstring = portbuf;
3444 else
3446 CHECK_STRING (service);
3447 portstring = SDATA (service);
3450 immediate_quit = 1;
3451 QUIT;
3452 memset (&hints, 0, sizeof (hints));
3453 hints.ai_flags = 0;
3454 hints.ai_family = family;
3455 hints.ai_socktype = socktype;
3456 hints.ai_protocol = 0;
3458 #ifdef HAVE_RES_INIT
3459 res_init ();
3460 #endif
3462 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3463 if (ret)
3464 #ifdef HAVE_GAI_STRERROR
3465 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3466 #else
3467 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3468 #endif
3469 immediate_quit = 0;
3471 goto open_socket;
3473 #endif /* HAVE_GETADDRINFO */
3475 /* We end up here if getaddrinfo is not defined, or in case no hostname
3476 has been specified (e.g. for a local server process). */
3478 if (EQ (service, Qt))
3479 port = 0;
3480 else if (INTEGERP (service))
3481 port = htons ((unsigned short) XINT (service));
3482 else
3484 struct servent *svc_info;
3485 CHECK_STRING (service);
3486 svc_info = getservbyname (SDATA (service),
3487 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3488 if (svc_info == 0)
3489 error ("Unknown service: %s", SDATA (service));
3490 port = svc_info->s_port;
3493 bzero (&address_in, sizeof address_in);
3494 address_in.sin_family = family;
3495 address_in.sin_addr.s_addr = INADDR_ANY;
3496 address_in.sin_port = port;
3498 #ifndef HAVE_GETADDRINFO
3499 if (!NILP (host))
3501 struct hostent *host_info_ptr;
3503 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3504 as it may `hang' Emacs for a very long time. */
3505 immediate_quit = 1;
3506 QUIT;
3508 #ifdef HAVE_RES_INIT
3509 res_init ();
3510 #endif
3512 host_info_ptr = gethostbyname (SDATA (host));
3513 immediate_quit = 0;
3515 if (host_info_ptr)
3517 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3518 host_info_ptr->h_length);
3519 family = host_info_ptr->h_addrtype;
3520 address_in.sin_family = family;
3522 else
3523 /* Attempt to interpret host as numeric inet address */
3525 unsigned long numeric_addr;
3526 numeric_addr = inet_addr ((char *) SDATA (host));
3527 if (numeric_addr == -1)
3528 error ("Unknown host \"%s\"", SDATA (host));
3530 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3531 sizeof (address_in.sin_addr));
3535 #endif /* not HAVE_GETADDRINFO */
3537 ai.ai_family = family;
3538 ai.ai_addr = (struct sockaddr *) &address_in;
3539 ai.ai_addrlen = sizeof address_in;
3541 open_socket:
3543 /* Do this in case we never enter the for-loop below. */
3544 count1 = SPECPDL_INDEX ();
3545 s = -1;
3547 for (lres = res; lres; lres = lres->ai_next)
3549 int optn, optbits;
3551 retry_connect:
3553 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3554 if (s < 0)
3556 xerrno = errno;
3557 continue;
3560 #ifdef DATAGRAM_SOCKETS
3561 if (!is_server && socktype == SOCK_DGRAM)
3562 break;
3563 #endif /* DATAGRAM_SOCKETS */
3565 #ifdef NON_BLOCKING_CONNECT
3566 if (is_non_blocking_client)
3568 #ifdef O_NONBLOCK
3569 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3570 #else
3571 ret = fcntl (s, F_SETFL, O_NDELAY);
3572 #endif
3573 if (ret < 0)
3575 xerrno = errno;
3576 emacs_close (s);
3577 s = -1;
3578 continue;
3581 #endif
3583 /* Make us close S if quit. */
3584 record_unwind_protect (close_file_unwind, make_number (s));
3586 /* Parse network options in the arg list.
3587 We simply ignore anything which isn't a known option (including other keywords).
3588 An error is signaled if setting a known option fails. */
3589 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3590 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3592 if (is_server)
3594 /* Configure as a server socket. */
3596 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3597 explicit :reuseaddr key to override this. */
3598 #ifdef HAVE_LOCAL_SOCKETS
3599 if (family != AF_LOCAL)
3600 #endif
3601 if (!(optbits & (1 << OPIX_REUSEADDR)))
3603 int optval = 1;
3604 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3605 report_file_error ("Cannot set reuse option on server socket", Qnil);
3608 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3609 report_file_error ("Cannot bind server socket", Qnil);
3611 #ifdef HAVE_GETSOCKNAME
3612 if (EQ (service, Qt))
3614 struct sockaddr_in sa1;
3615 int len1 = sizeof (sa1);
3616 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3618 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3619 service = make_number (ntohs (sa1.sin_port));
3620 contact = Fplist_put (contact, QCservice, service);
3623 #endif
3625 if (socktype == SOCK_STREAM && listen (s, backlog))
3626 report_file_error ("Cannot listen on server socket", Qnil);
3628 break;
3631 immediate_quit = 1;
3632 QUIT;
3634 /* This turns off all alarm-based interrupts; the
3635 bind_polling_period call above doesn't always turn all the
3636 short-interval ones off, especially if interrupt_input is
3637 set.
3639 It'd be nice to be able to control the connect timeout
3640 though. Would non-blocking connect calls be portable?
3642 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3644 turn_on_atimers (0);
3646 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3647 xerrno = errno;
3649 turn_on_atimers (1);
3651 if (ret == 0 || xerrno == EISCONN)
3653 /* The unwind-protect will be discarded afterwards.
3654 Likewise for immediate_quit. */
3655 break;
3658 #ifdef NON_BLOCKING_CONNECT
3659 #ifdef EINPROGRESS
3660 if (is_non_blocking_client && xerrno == EINPROGRESS)
3661 break;
3662 #else
3663 #ifdef EWOULDBLOCK
3664 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3665 break;
3666 #endif
3667 #endif
3668 #endif
3670 immediate_quit = 0;
3672 /* Discard the unwind protect closing S. */
3673 specpdl_ptr = specpdl + count1;
3674 emacs_close (s);
3675 s = -1;
3677 if (xerrno == EINTR)
3678 goto retry_connect;
3681 if (s >= 0)
3683 #ifdef DATAGRAM_SOCKETS
3684 if (socktype == SOCK_DGRAM)
3686 if (datagram_address[s].sa)
3687 abort ();
3688 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3689 datagram_address[s].len = lres->ai_addrlen;
3690 if (is_server)
3692 Lisp_Object remote;
3693 bzero (datagram_address[s].sa, lres->ai_addrlen);
3694 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3696 int rfamily, rlen;
3697 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3698 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3699 conv_lisp_to_sockaddr (rfamily, remote,
3700 datagram_address[s].sa, rlen);
3703 else
3704 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3706 #endif
3707 contact = Fplist_put (contact, QCaddress,
3708 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3709 #ifdef HAVE_GETSOCKNAME
3710 if (!is_server)
3712 struct sockaddr_in sa1;
3713 int len1 = sizeof (sa1);
3714 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3715 contact = Fplist_put (contact, QClocal,
3716 conv_sockaddr_to_lisp (&sa1, len1));
3718 #endif
3721 immediate_quit = 0;
3723 #ifdef HAVE_GETADDRINFO
3724 if (res != &ai)
3726 BLOCK_INPUT;
3727 freeaddrinfo (res);
3728 UNBLOCK_INPUT;
3730 #endif
3732 /* Discard the unwind protect for closing S, if any. */
3733 specpdl_ptr = specpdl + count1;
3735 /* Unwind bind_polling_period and request_sigio. */
3736 unbind_to (count, Qnil);
3738 if (s < 0)
3740 /* If non-blocking got this far - and failed - assume non-blocking is
3741 not supported after all. This is probably a wrong assumption, but
3742 the normal blocking calls to open-network-stream handles this error
3743 better. */
3744 if (is_non_blocking_client)
3745 return Qnil;
3747 errno = xerrno;
3748 if (is_server)
3749 report_file_error ("make server process failed", contact);
3750 else
3751 report_file_error ("make client process failed", contact);
3754 inch = s;
3755 outch = s;
3757 if (!NILP (buffer))
3758 buffer = Fget_buffer_create (buffer);
3759 proc = make_process (name);
3761 chan_process[inch] = proc;
3763 #ifdef O_NONBLOCK
3764 fcntl (inch, F_SETFL, O_NONBLOCK);
3765 #else
3766 #ifdef O_NDELAY
3767 fcntl (inch, F_SETFL, O_NDELAY);
3768 #endif
3769 #endif
3771 p = XPROCESS (proc);
3773 p->childp = contact;
3774 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3775 p->type = Qnetwork;
3777 p->buffer = buffer;
3778 p->sentinel = sentinel;
3779 p->filter = filter;
3780 p->log = Fplist_get (contact, QClog);
3781 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3782 p->kill_without_query = 1;
3783 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3784 p->command = Qt;
3785 p->pid = 0;
3786 p->infd = inch;
3787 p->outfd = outch;
3788 if (is_server && socktype == SOCK_STREAM)
3789 p->status = Qlisten;
3791 /* Make the process marker point into the process buffer (if any). */
3792 if (BUFFERP (buffer))
3793 set_marker_both (p->mark, buffer,
3794 BUF_ZV (XBUFFER (buffer)),
3795 BUF_ZV_BYTE (XBUFFER (buffer)));
3797 #ifdef NON_BLOCKING_CONNECT
3798 if (is_non_blocking_client)
3800 /* We may get here if connect did succeed immediately. However,
3801 in that case, we still need to signal this like a non-blocking
3802 connection. */
3803 p->status = Qconnect;
3804 if (!FD_ISSET (inch, &connect_wait_mask))
3806 FD_SET (inch, &connect_wait_mask);
3807 num_pending_connects++;
3810 else
3811 #endif
3812 /* A server may have a client filter setting of Qt, but it must
3813 still listen for incoming connects unless it is stopped. */
3814 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3815 || (EQ (p->status, Qlisten) && NILP (p->command)))
3817 FD_SET (inch, &input_wait_mask);
3818 FD_SET (inch, &non_keyboard_wait_mask);
3821 if (inch > max_process_desc)
3822 max_process_desc = inch;
3824 tem = Fplist_member (contact, QCcoding);
3825 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3826 tem = Qnil; /* No error message (too late!). */
3829 /* Setup coding systems for communicating with the network stream. */
3830 struct gcpro gcpro1;
3831 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3832 Lisp_Object coding_systems = Qt;
3833 Lisp_Object args[5], val;
3835 if (!NILP (tem))
3837 val = XCAR (XCDR (tem));
3838 if (CONSP (val))
3839 val = XCAR (val);
3841 else if (!NILP (Vcoding_system_for_read))
3842 val = Vcoding_system_for_read;
3843 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3844 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3845 /* We dare not decode end-of-line format by setting VAL to
3846 Qraw_text, because the existing Emacs Lisp libraries
3847 assume that they receive bare code including a sequene of
3848 CR LF. */
3849 val = Qnil;
3850 else
3852 if (NILP (host) || NILP (service))
3853 coding_systems = Qnil;
3854 else
3856 args[0] = Qopen_network_stream, args[1] = name,
3857 args[2] = buffer, args[3] = host, args[4] = service;
3858 GCPRO1 (proc);
3859 coding_systems = Ffind_operation_coding_system (5, args);
3860 UNGCPRO;
3862 if (CONSP (coding_systems))
3863 val = XCAR (coding_systems);
3864 else if (CONSP (Vdefault_process_coding_system))
3865 val = XCAR (Vdefault_process_coding_system);
3866 else
3867 val = Qnil;
3869 p->decode_coding_system = val;
3871 if (!NILP (tem))
3873 val = XCAR (XCDR (tem));
3874 if (CONSP (val))
3875 val = XCDR (val);
3877 else if (!NILP (Vcoding_system_for_write))
3878 val = Vcoding_system_for_write;
3879 else if (NILP (current_buffer->enable_multibyte_characters))
3880 val = Qnil;
3881 else
3883 if (EQ (coding_systems, Qt))
3885 if (NILP (host) || NILP (service))
3886 coding_systems = Qnil;
3887 else
3889 args[0] = Qopen_network_stream, args[1] = name,
3890 args[2] = buffer, args[3] = host, args[4] = service;
3891 GCPRO1 (proc);
3892 coding_systems = Ffind_operation_coding_system (5, args);
3893 UNGCPRO;
3896 if (CONSP (coding_systems))
3897 val = XCDR (coding_systems);
3898 else if (CONSP (Vdefault_process_coding_system))
3899 val = XCDR (Vdefault_process_coding_system);
3900 else
3901 val = Qnil;
3903 p->encode_coding_system = val;
3905 setup_process_coding_systems (proc);
3907 p->decoding_buf = make_uninit_string (0);
3908 p->decoding_carryover = 0;
3909 p->encoding_buf = make_uninit_string (0);
3911 p->inherit_coding_system_flag
3912 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3914 UNGCPRO;
3915 return proc;
3917 #endif /* HAVE_SOCKETS */
3920 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3922 #ifdef SIOCGIFCONF
3923 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3924 doc: /* Return an alist of all network interfaces and their network address.
3925 Each element is a cons, the car of which is a string containing the
3926 interface name, and the cdr is the network address in internal
3927 format; see the description of ADDRESS in `make-network-process'. */)
3930 struct ifconf ifconf;
3931 struct ifreq *ifreqs = NULL;
3932 int ifaces = 0;
3933 int buf_size, s;
3934 Lisp_Object res;
3936 s = socket (AF_INET, SOCK_STREAM, 0);
3937 if (s < 0)
3938 return Qnil;
3940 again:
3941 ifaces += 25;
3942 buf_size = ifaces * sizeof(ifreqs[0]);
3943 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3944 if (!ifreqs)
3946 close (s);
3947 return Qnil;
3950 ifconf.ifc_len = buf_size;
3951 ifconf.ifc_req = ifreqs;
3952 if (ioctl (s, SIOCGIFCONF, &ifconf))
3954 close (s);
3955 return Qnil;
3958 if (ifconf.ifc_len == buf_size)
3959 goto again;
3961 close (s);
3962 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3964 res = Qnil;
3965 while (--ifaces >= 0)
3967 struct ifreq *ifq = &ifreqs[ifaces];
3968 char namebuf[sizeof (ifq->ifr_name) + 1];
3969 if (ifq->ifr_addr.sa_family != AF_INET)
3970 continue;
3971 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3972 namebuf[sizeof (ifq->ifr_name)] = 0;
3973 res = Fcons (Fcons (build_string (namebuf),
3974 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3975 sizeof (struct sockaddr))),
3976 res);
3979 return res;
3981 #endif /* SIOCGIFCONF */
3983 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3985 struct ifflag_def {
3986 int flag_bit;
3987 const char *flag_sym;
3990 static const struct ifflag_def ifflag_table[] = {
3991 #ifdef IFF_UP
3992 { IFF_UP, "up" },
3993 #endif
3994 #ifdef IFF_BROADCAST
3995 { IFF_BROADCAST, "broadcast" },
3996 #endif
3997 #ifdef IFF_DEBUG
3998 { IFF_DEBUG, "debug" },
3999 #endif
4000 #ifdef IFF_LOOPBACK
4001 { IFF_LOOPBACK, "loopback" },
4002 #endif
4003 #ifdef IFF_POINTOPOINT
4004 { IFF_POINTOPOINT, "pointopoint" },
4005 #endif
4006 #ifdef IFF_RUNNING
4007 { IFF_RUNNING, "running" },
4008 #endif
4009 #ifdef IFF_NOARP
4010 { IFF_NOARP, "noarp" },
4011 #endif
4012 #ifdef IFF_PROMISC
4013 { IFF_PROMISC, "promisc" },
4014 #endif
4015 #ifdef IFF_NOTRAILERS
4016 { IFF_NOTRAILERS, "notrailers" },
4017 #endif
4018 #ifdef IFF_ALLMULTI
4019 { IFF_ALLMULTI, "allmulti" },
4020 #endif
4021 #ifdef IFF_MASTER
4022 { IFF_MASTER, "master" },
4023 #endif
4024 #ifdef IFF_SLAVE
4025 { IFF_SLAVE, "slave" },
4026 #endif
4027 #ifdef IFF_MULTICAST
4028 { IFF_MULTICAST, "multicast" },
4029 #endif
4030 #ifdef IFF_PORTSEL
4031 { IFF_PORTSEL, "portsel" },
4032 #endif
4033 #ifdef IFF_AUTOMEDIA
4034 { IFF_AUTOMEDIA, "automedia" },
4035 #endif
4036 #ifdef IFF_DYNAMIC
4037 { IFF_DYNAMIC, "dynamic" },
4038 #endif
4039 #ifdef IFF_OACTIVE
4040 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
4041 #endif
4042 #ifdef IFF_SIMPLEX
4043 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
4044 #endif
4045 #ifdef IFF_LINK0
4046 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
4047 #endif
4048 #ifdef IFF_LINK1
4049 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
4050 #endif
4051 #ifdef IFF_LINK2
4052 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
4053 #endif
4054 { 0, 0 }
4057 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
4058 doc: /* Return information about network interface named IFNAME.
4059 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4060 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4061 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
4062 FLAGS is the current flags of the interface. */)
4063 (ifname)
4064 Lisp_Object ifname;
4066 struct ifreq rq;
4067 Lisp_Object res = Qnil;
4068 Lisp_Object elt;
4069 int s;
4070 int any = 0;
4072 CHECK_STRING (ifname);
4074 bzero (rq.ifr_name, sizeof rq.ifr_name);
4075 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
4077 s = socket (AF_INET, SOCK_STREAM, 0);
4078 if (s < 0)
4079 return Qnil;
4081 elt = Qnil;
4082 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
4083 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4085 int flags = rq.ifr_flags;
4086 const struct ifflag_def *fp;
4087 int fnum;
4089 any++;
4090 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4092 if (flags & fp->flag_bit)
4094 elt = Fcons (intern (fp->flag_sym), elt);
4095 flags -= fp->flag_bit;
4098 for (fnum = 0; flags && fnum < 32; fnum++)
4100 if (flags & (1 << fnum))
4102 elt = Fcons (make_number (fnum), elt);
4106 #endif
4107 res = Fcons (elt, res);
4109 elt = Qnil;
4110 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4111 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4113 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4114 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4115 int n;
4117 any++;
4118 for (n = 0; n < 6; n++)
4119 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4120 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4122 #endif
4123 res = Fcons (elt, res);
4125 elt = Qnil;
4126 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4127 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4129 any++;
4130 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4131 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4132 #else
4133 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4134 #endif
4136 #endif
4137 res = Fcons (elt, res);
4139 elt = Qnil;
4140 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4141 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4143 any++;
4144 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4146 #endif
4147 res = Fcons (elt, res);
4149 elt = Qnil;
4150 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4151 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4153 any++;
4154 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4156 #endif
4157 res = Fcons (elt, res);
4159 close (s);
4161 return any ? res : Qnil;
4163 #endif
4164 #endif /* HAVE_SOCKETS */
4166 /* Turn off input and output for process PROC. */
4168 void
4169 deactivate_process (proc)
4170 Lisp_Object proc;
4172 register int inchannel, outchannel;
4173 register struct Lisp_Process *p = XPROCESS (proc);
4175 inchannel = p->infd;
4176 outchannel = p->outfd;
4178 #ifdef ADAPTIVE_READ_BUFFERING
4179 if (p->read_output_delay > 0)
4181 if (--process_output_delay_count < 0)
4182 process_output_delay_count = 0;
4183 p->read_output_delay = 0;
4184 p->read_output_skip = 0;
4186 #endif
4188 if (inchannel >= 0)
4190 /* Beware SIGCHLD hereabouts. */
4191 flush_pending_output (inchannel);
4192 emacs_close (inchannel);
4193 if (outchannel >= 0 && outchannel != inchannel)
4194 emacs_close (outchannel);
4196 p->infd = -1;
4197 p->outfd = -1;
4198 #ifdef DATAGRAM_SOCKETS
4199 if (DATAGRAM_CHAN_P (inchannel))
4201 xfree (datagram_address[inchannel].sa);
4202 datagram_address[inchannel].sa = 0;
4203 datagram_address[inchannel].len = 0;
4205 #endif
4206 chan_process[inchannel] = Qnil;
4207 FD_CLR (inchannel, &input_wait_mask);
4208 FD_CLR (inchannel, &non_keyboard_wait_mask);
4209 #ifdef NON_BLOCKING_CONNECT
4210 if (FD_ISSET (inchannel, &connect_wait_mask))
4212 FD_CLR (inchannel, &connect_wait_mask);
4213 if (--num_pending_connects < 0)
4214 abort ();
4216 #endif
4217 if (inchannel == max_process_desc)
4219 int i;
4220 /* We just closed the highest-numbered process input descriptor,
4221 so recompute the highest-numbered one now. */
4222 max_process_desc = 0;
4223 for (i = 0; i < MAXDESC; i++)
4224 if (!NILP (chan_process[i]))
4225 max_process_desc = i;
4230 /* Close all descriptors currently in use for communication
4231 with subprocess. This is used in a newly-forked subprocess
4232 to get rid of irrelevant descriptors. */
4234 void
4235 close_process_descs ()
4237 #ifndef WINDOWSNT
4238 int i;
4239 for (i = 0; i < MAXDESC; i++)
4241 Lisp_Object process;
4242 process = chan_process[i];
4243 if (!NILP (process))
4245 int in = XPROCESS (process)->infd;
4246 int out = XPROCESS (process)->outfd;
4247 if (in >= 0)
4248 emacs_close (in);
4249 if (out >= 0 && in != out)
4250 emacs_close (out);
4253 #endif
4256 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4257 0, 4, 0,
4258 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4259 It is read into the process' buffers or given to their filter functions.
4260 Non-nil arg PROCESS means do not return until some output has been received
4261 from PROCESS.
4263 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4264 and milliseconds to wait; return after that much time whether or not
4265 there is any subprocess output. If SECONDS is a floating point number,
4266 it specifies a fractional number of seconds to wait.
4267 The MILLISEC argument is obsolete and should be avoided.
4269 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4270 from PROCESS, suspending reading output from other processes.
4271 If JUST-THIS-ONE is an integer, don't run any timers either.
4272 Return non-nil if we received any output before the timeout expired. */)
4273 (process, seconds, millisec, just_this_one)
4274 register Lisp_Object process, seconds, millisec, just_this_one;
4276 int secs, usecs = 0;
4278 if (! NILP (process))
4279 CHECK_PROCESS (process);
4280 else
4281 just_this_one = Qnil;
4283 if (!NILP (millisec))
4284 { /* Obsolete calling convention using integers rather than floats. */
4285 CHECK_NUMBER (millisec);
4286 if (NILP (seconds))
4287 seconds = make_float (XINT (millisec) / 1000.0);
4288 else
4290 CHECK_NUMBER (seconds);
4291 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4295 if (!NILP (seconds))
4297 if (INTEGERP (seconds))
4298 secs = XINT (seconds);
4299 else if (FLOATP (seconds))
4301 double timeout = XFLOAT_DATA (seconds);
4302 secs = (int) timeout;
4303 usecs = (int) ((timeout - (double) secs) * 1000000);
4305 else
4306 wrong_type_argument (Qnumberp, seconds);
4308 if (secs < 0 || (secs == 0 && usecs == 0))
4309 secs = -1, usecs = 0;
4311 else
4312 secs = NILP (process) ? -1 : 0;
4314 return
4315 (wait_reading_process_output (secs, usecs, 0, 0,
4316 Qnil,
4317 !NILP (process) ? XPROCESS (process) : NULL,
4318 NILP (just_this_one) ? 0 :
4319 !INTEGERP (just_this_one) ? 1 : -1)
4320 ? Qt : Qnil);
4323 /* Accept a connection for server process SERVER on CHANNEL. */
4325 static int connect_counter = 0;
4327 static void
4328 server_accept_connection (server, channel)
4329 Lisp_Object server;
4330 int channel;
4332 Lisp_Object proc, caller, name, buffer;
4333 Lisp_Object contact, host, service;
4334 struct Lisp_Process *ps= XPROCESS (server);
4335 struct Lisp_Process *p;
4336 int s;
4337 union u_sockaddr {
4338 struct sockaddr sa;
4339 struct sockaddr_in in;
4340 #ifdef AF_INET6
4341 struct sockaddr_in6 in6;
4342 #endif
4343 #ifdef HAVE_LOCAL_SOCKETS
4344 struct sockaddr_un un;
4345 #endif
4346 } saddr;
4347 int len = sizeof saddr;
4349 s = accept (channel, &saddr.sa, &len);
4351 if (s < 0)
4353 int code = errno;
4355 if (code == EAGAIN)
4356 return;
4357 #ifdef EWOULDBLOCK
4358 if (code == EWOULDBLOCK)
4359 return;
4360 #endif
4362 if (!NILP (ps->log))
4363 call3 (ps->log, server, Qnil,
4364 concat3 (build_string ("accept failed with code"),
4365 Fnumber_to_string (make_number (code)),
4366 build_string ("\n")));
4367 return;
4370 connect_counter++;
4372 /* Setup a new process to handle the connection. */
4374 /* Generate a unique identification of the caller, and build contact
4375 information for this process. */
4376 host = Qt;
4377 service = Qnil;
4378 switch (saddr.sa.sa_family)
4380 case AF_INET:
4382 Lisp_Object args[5];
4383 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4384 args[0] = build_string ("%d.%d.%d.%d");
4385 args[1] = make_number (*ip++);
4386 args[2] = make_number (*ip++);
4387 args[3] = make_number (*ip++);
4388 args[4] = make_number (*ip++);
4389 host = Fformat (5, args);
4390 service = make_number (ntohs (saddr.in.sin_port));
4392 args[0] = build_string (" <%s:%d>");
4393 args[1] = host;
4394 args[2] = service;
4395 caller = Fformat (3, args);
4397 break;
4399 #ifdef AF_INET6
4400 case AF_INET6:
4402 Lisp_Object args[9];
4403 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4404 int i;
4405 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4406 for (i = 0; i < 8; i++)
4407 args[i+1] = make_number (ntohs(ip6[i]));
4408 host = Fformat (9, args);
4409 service = make_number (ntohs (saddr.in.sin_port));
4411 args[0] = build_string (" <[%s]:%d>");
4412 args[1] = host;
4413 args[2] = service;
4414 caller = Fformat (3, args);
4416 break;
4417 #endif
4419 #ifdef HAVE_LOCAL_SOCKETS
4420 case AF_LOCAL:
4421 #endif
4422 default:
4423 caller = Fnumber_to_string (make_number (connect_counter));
4424 caller = concat3 (build_string (" <"), caller, build_string (">"));
4425 break;
4428 /* Create a new buffer name for this process if it doesn't have a
4429 filter. The new buffer name is based on the buffer name or
4430 process name of the server process concatenated with the caller
4431 identification. */
4433 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4434 buffer = Qnil;
4435 else
4437 buffer = ps->buffer;
4438 if (!NILP (buffer))
4439 buffer = Fbuffer_name (buffer);
4440 else
4441 buffer = ps->name;
4442 if (!NILP (buffer))
4444 buffer = concat2 (buffer, caller);
4445 buffer = Fget_buffer_create (buffer);
4449 /* Generate a unique name for the new server process. Combine the
4450 server process name with the caller identification. */
4452 name = concat2 (ps->name, caller);
4453 proc = make_process (name);
4455 chan_process[s] = proc;
4457 #ifdef O_NONBLOCK
4458 fcntl (s, F_SETFL, O_NONBLOCK);
4459 #else
4460 #ifdef O_NDELAY
4461 fcntl (s, F_SETFL, O_NDELAY);
4462 #endif
4463 #endif
4465 p = XPROCESS (proc);
4467 /* Build new contact information for this setup. */
4468 contact = Fcopy_sequence (ps->childp);
4469 contact = Fplist_put (contact, QCserver, Qnil);
4470 contact = Fplist_put (contact, QChost, host);
4471 if (!NILP (service))
4472 contact = Fplist_put (contact, QCservice, service);
4473 contact = Fplist_put (contact, QCremote,
4474 conv_sockaddr_to_lisp (&saddr.sa, len));
4475 #ifdef HAVE_GETSOCKNAME
4476 len = sizeof saddr;
4477 if (getsockname (s, &saddr.sa, &len) == 0)
4478 contact = Fplist_put (contact, QClocal,
4479 conv_sockaddr_to_lisp (&saddr.sa, len));
4480 #endif
4482 p->childp = contact;
4483 p->plist = Fcopy_sequence (ps->plist);
4484 p->type = Qnetwork;
4486 p->buffer = buffer;
4487 p->sentinel = ps->sentinel;
4488 p->filter = ps->filter;
4489 p->command = Qnil;
4490 p->pid = 0;
4491 p->infd = s;
4492 p->outfd = s;
4493 p->status = Qrun;
4495 /* Client processes for accepted connections are not stopped initially. */
4496 if (!EQ (p->filter, Qt))
4498 FD_SET (s, &input_wait_mask);
4499 FD_SET (s, &non_keyboard_wait_mask);
4502 if (s > max_process_desc)
4503 max_process_desc = s;
4505 /* Setup coding system for new process based on server process.
4506 This seems to be the proper thing to do, as the coding system
4507 of the new process should reflect the settings at the time the
4508 server socket was opened; not the current settings. */
4510 p->decode_coding_system = ps->decode_coding_system;
4511 p->encode_coding_system = ps->encode_coding_system;
4512 setup_process_coding_systems (proc);
4514 p->decoding_buf = make_uninit_string (0);
4515 p->decoding_carryover = 0;
4516 p->encoding_buf = make_uninit_string (0);
4518 p->inherit_coding_system_flag
4519 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4521 if (!NILP (ps->log))
4522 call3 (ps->log, server, proc,
4523 concat3 (build_string ("accept from "),
4524 (STRINGP (host) ? host : build_string ("-")),
4525 build_string ("\n")));
4527 if (!NILP (p->sentinel))
4528 exec_sentinel (proc,
4529 concat3 (build_string ("open from "),
4530 (STRINGP (host) ? host : build_string ("-")),
4531 build_string ("\n")));
4534 /* This variable is different from waiting_for_input in keyboard.c.
4535 It is used to communicate to a lisp process-filter/sentinel (via the
4536 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4537 for user-input when that process-filter was called.
4538 waiting_for_input cannot be used as that is by definition 0 when
4539 lisp code is being evalled.
4540 This is also used in record_asynch_buffer_change.
4541 For that purpose, this must be 0
4542 when not inside wait_reading_process_output. */
4543 static int waiting_for_user_input_p;
4545 static Lisp_Object
4546 wait_reading_process_output_unwind (data)
4547 Lisp_Object data;
4549 waiting_for_user_input_p = XINT (data);
4550 return Qnil;
4553 /* This is here so breakpoints can be put on it. */
4554 static void
4555 wait_reading_process_output_1 ()
4559 /* Use a wrapper around select to work around a bug in gdb 5.3.
4560 Normally, the wrapper is optimzed away by inlining.
4562 If emacs is stopped inside select, the gdb backtrace doesn't
4563 show the function which called select, so it is practically
4564 impossible to step through wait_reading_process_output. */
4566 #ifndef select
4567 static INLINE int
4568 select_wrapper (n, rfd, wfd, xfd, tmo)
4569 int n;
4570 SELECT_TYPE *rfd, *wfd, *xfd;
4571 EMACS_TIME *tmo;
4573 return select (n, rfd, wfd, xfd, tmo);
4575 #define select select_wrapper
4576 #endif
4578 /* Read and dispose of subprocess output while waiting for timeout to
4579 elapse and/or keyboard input to be available.
4581 TIME_LIMIT is:
4582 timeout in seconds, or
4583 zero for no limit, or
4584 -1 means gobble data immediately available but don't wait for any.
4586 MICROSECS is:
4587 an additional duration to wait, measured in microseconds.
4588 If this is nonzero and time_limit is 0, then the timeout
4589 consists of MICROSECS only.
4591 READ_KBD is a lisp value:
4592 0 to ignore keyboard input, or
4593 1 to return when input is available, or
4594 -1 meaning caller will actually read the input, so don't throw to
4595 the quit handler, or
4597 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4598 output that arrives.
4600 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4601 (and gobble terminal input into the buffer if any arrives).
4603 If WAIT_PROC is specified, wait until something arrives from that
4604 process. The return value is true if we read some input from
4605 that process.
4607 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4608 (suspending output from other processes). A negative value
4609 means don't run any timers either.
4611 If WAIT_PROC is specified, then the function returns true if we
4612 received input from that process before the timeout elapsed.
4613 Otherwise, return true if we received input from any process. */
4616 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4617 wait_for_cell, wait_proc, just_wait_proc)
4618 int time_limit, microsecs, read_kbd, do_display;
4619 Lisp_Object wait_for_cell;
4620 struct Lisp_Process *wait_proc;
4621 int just_wait_proc;
4623 register int channel, nfds;
4624 SELECT_TYPE Available;
4625 #ifdef NON_BLOCKING_CONNECT
4626 SELECT_TYPE Connecting;
4627 int check_connect;
4628 #endif
4629 int check_delay, no_avail;
4630 int xerrno;
4631 Lisp_Object proc;
4632 EMACS_TIME timeout, end_time;
4633 int wait_channel = -1;
4634 int got_some_input = 0;
4635 int count = SPECPDL_INDEX ();
4637 FD_ZERO (&Available);
4638 #ifdef NON_BLOCKING_CONNECT
4639 FD_ZERO (&Connecting);
4640 #endif
4642 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4643 if (wait_proc != NULL)
4644 wait_channel = wait_proc->infd;
4646 record_unwind_protect (wait_reading_process_output_unwind,
4647 make_number (waiting_for_user_input_p));
4648 waiting_for_user_input_p = read_kbd;
4650 /* Since we may need to wait several times,
4651 compute the absolute time to return at. */
4652 if (time_limit || microsecs)
4654 EMACS_GET_TIME (end_time);
4655 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4656 EMACS_ADD_TIME (end_time, end_time, timeout);
4659 while (1)
4661 int timeout_reduced_for_timers = 0;
4663 /* If calling from keyboard input, do not quit
4664 since we want to return C-g as an input character.
4665 Otherwise, do pending quit if requested. */
4666 if (read_kbd >= 0)
4667 QUIT;
4668 #ifdef SYNC_INPUT
4669 else
4670 process_pending_signals ();
4671 #endif
4673 /* Exit now if the cell we're waiting for became non-nil. */
4674 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4675 break;
4677 /* Compute time from now till when time limit is up */
4678 /* Exit if already run out */
4679 if (time_limit == -1)
4681 /* -1 specified for timeout means
4682 gobble output available now
4683 but don't wait at all. */
4685 EMACS_SET_SECS_USECS (timeout, 0, 0);
4687 else if (time_limit || microsecs)
4689 EMACS_GET_TIME (timeout);
4690 EMACS_SUB_TIME (timeout, end_time, timeout);
4691 if (EMACS_TIME_NEG_P (timeout))
4692 break;
4694 else
4696 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4699 /* Normally we run timers here.
4700 But not if wait_for_cell; in those cases,
4701 the wait is supposed to be short,
4702 and those callers cannot handle running arbitrary Lisp code here. */
4703 if (NILP (wait_for_cell)
4704 && just_wait_proc >= 0)
4706 EMACS_TIME timer_delay;
4710 int old_timers_run = timers_run;
4711 struct buffer *old_buffer = current_buffer;
4712 Lisp_Object old_window = selected_window;
4714 timer_delay = timer_check (1);
4716 /* If a timer has run, this might have changed buffers
4717 an alike. Make read_key_sequence aware of that. */
4718 if (timers_run != old_timers_run
4719 && (old_buffer != current_buffer
4720 || !EQ (old_window, selected_window))
4721 && waiting_for_user_input_p == -1)
4722 record_asynch_buffer_change ();
4724 if (timers_run != old_timers_run && do_display)
4725 /* We must retry, since a timer may have requeued itself
4726 and that could alter the time_delay. */
4727 redisplay_preserve_echo_area (9);
4728 else
4729 break;
4731 while (!detect_input_pending ());
4733 /* If there is unread keyboard input, also return. */
4734 if (read_kbd != 0
4735 && requeued_events_pending_p ())
4736 break;
4738 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4740 EMACS_TIME difference;
4741 EMACS_SUB_TIME (difference, timer_delay, timeout);
4742 if (EMACS_TIME_NEG_P (difference))
4744 timeout = timer_delay;
4745 timeout_reduced_for_timers = 1;
4748 /* If time_limit is -1, we are not going to wait at all. */
4749 else if (time_limit != -1)
4751 /* This is so a breakpoint can be put here. */
4752 wait_reading_process_output_1 ();
4756 /* Cause C-g and alarm signals to take immediate action,
4757 and cause input available signals to zero out timeout.
4759 It is important that we do this before checking for process
4760 activity. If we get a SIGCHLD after the explicit checks for
4761 process activity, timeout is the only way we will know. */
4762 if (read_kbd < 0)
4763 set_waiting_for_input (&timeout);
4765 /* If status of something has changed, and no input is
4766 available, notify the user of the change right away. After
4767 this explicit check, we'll let the SIGCHLD handler zap
4768 timeout to get our attention. */
4769 if (update_tick != process_tick)
4771 SELECT_TYPE Atemp;
4772 #ifdef NON_BLOCKING_CONNECT
4773 SELECT_TYPE Ctemp;
4774 #endif
4776 Atemp = input_wait_mask;
4777 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4779 EMACS_SET_SECS_USECS (timeout, 0, 0);
4780 if ((select (max (max (max_process_desc, max_keyboard_desc),
4781 max_gpm_desc) + 1,
4782 &Atemp,
4783 #ifdef NON_BLOCKING_CONNECT
4784 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4785 #else
4786 (SELECT_TYPE *)0,
4787 #endif
4788 (SELECT_TYPE *)0, &timeout)
4789 <= 0))
4791 /* It's okay for us to do this and then continue with
4792 the loop, since timeout has already been zeroed out. */
4793 clear_waiting_for_input ();
4794 status_notify (NULL);
4795 if (do_display) redisplay_preserve_echo_area (13);
4799 /* Don't wait for output from a non-running process. Just
4800 read whatever data has already been received. */
4801 if (wait_proc && wait_proc->raw_status_new)
4802 update_status (wait_proc);
4803 if (wait_proc
4804 && ! EQ (wait_proc->status, Qrun)
4805 && ! EQ (wait_proc->status, Qconnect))
4807 int nread, total_nread = 0;
4809 clear_waiting_for_input ();
4810 XSETPROCESS (proc, wait_proc);
4812 /* Read data from the process, until we exhaust it. */
4813 while (wait_proc->infd >= 0)
4815 nread = read_process_output (proc, wait_proc->infd);
4817 if (nread == 0)
4818 break;
4820 if (0 < nread)
4822 total_nread += nread;
4823 got_some_input = 1;
4825 #ifdef EIO
4826 else if (nread == -1 && EIO == errno)
4827 break;
4828 #endif
4829 #ifdef EAGAIN
4830 else if (nread == -1 && EAGAIN == errno)
4831 break;
4832 #endif
4833 #ifdef EWOULDBLOCK
4834 else if (nread == -1 && EWOULDBLOCK == errno)
4835 break;
4836 #endif
4838 if (total_nread > 0 && do_display)
4839 redisplay_preserve_echo_area (10);
4841 break;
4844 /* Wait till there is something to do */
4846 if (wait_proc && just_wait_proc)
4848 if (wait_proc->infd < 0) /* Terminated */
4849 break;
4850 FD_SET (wait_proc->infd, &Available);
4851 check_delay = 0;
4852 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4854 else if (!NILP (wait_for_cell))
4856 Available = non_process_wait_mask;
4857 check_delay = 0;
4858 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4860 else
4862 if (! read_kbd)
4863 Available = non_keyboard_wait_mask;
4864 else
4865 Available = input_wait_mask;
4866 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4867 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4870 /* If frame size has changed or the window is newly mapped,
4871 redisplay now, before we start to wait. There is a race
4872 condition here; if a SIGIO arrives between now and the select
4873 and indicates that a frame is trashed, the select may block
4874 displaying a trashed screen. */
4875 if (frame_garbaged && do_display)
4877 clear_waiting_for_input ();
4878 redisplay_preserve_echo_area (11);
4879 if (read_kbd < 0)
4880 set_waiting_for_input (&timeout);
4883 no_avail = 0;
4884 if (read_kbd && detect_input_pending ())
4886 nfds = 0;
4887 no_avail = 1;
4889 else
4891 #ifdef NON_BLOCKING_CONNECT
4892 if (check_connect)
4893 Connecting = connect_wait_mask;
4894 #endif
4896 #ifdef ADAPTIVE_READ_BUFFERING
4897 /* Set the timeout for adaptive read buffering if any
4898 process has non-zero read_output_skip and non-zero
4899 read_output_delay, and we are not reading output for a
4900 specific wait_channel. It is not executed if
4901 Vprocess_adaptive_read_buffering is nil. */
4902 if (process_output_skip && check_delay > 0)
4904 int usecs = EMACS_USECS (timeout);
4905 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4906 usecs = READ_OUTPUT_DELAY_MAX;
4907 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4909 proc = chan_process[channel];
4910 if (NILP (proc))
4911 continue;
4912 /* Find minimum non-zero read_output_delay among the
4913 processes with non-zero read_output_skip. */
4914 if (XPROCESS (proc)->read_output_delay > 0)
4916 check_delay--;
4917 if (!XPROCESS (proc)->read_output_skip)
4918 continue;
4919 FD_CLR (channel, &Available);
4920 XPROCESS (proc)->read_output_skip = 0;
4921 if (XPROCESS (proc)->read_output_delay < usecs)
4922 usecs = XPROCESS (proc)->read_output_delay;
4925 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4926 process_output_skip = 0;
4928 #endif
4929 #if defined (USE_GTK) || defined (HAVE_GCONF)
4930 nfds = xg_select
4931 #elif defined (HAVE_NS)
4932 nfds = ns_select
4933 #else
4934 nfds = select
4935 #endif
4936 (max (max (max_process_desc, max_keyboard_desc),
4937 max_gpm_desc) + 1,
4938 &Available,
4939 #ifdef NON_BLOCKING_CONNECT
4940 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4941 #else
4942 (SELECT_TYPE *)0,
4943 #endif
4944 (SELECT_TYPE *)0, &timeout);
4947 xerrno = errno;
4949 /* Make C-g and alarm signals set flags again */
4950 clear_waiting_for_input ();
4952 /* If we woke up due to SIGWINCH, actually change size now. */
4953 do_pending_window_change (0);
4955 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4956 /* We wanted the full specified time, so return now. */
4957 break;
4958 if (nfds < 0)
4960 if (xerrno == EINTR)
4961 no_avail = 1;
4962 else if (xerrno == EBADF)
4964 #ifdef AIX
4965 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4966 the child's closure of the pts gives the parent a SIGHUP, and
4967 the ptc file descriptor is automatically closed,
4968 yielding EBADF here or at select() call above.
4969 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4970 in m/ibmrt-aix.h), and here we just ignore the select error.
4971 Cleanup occurs c/o status_notify after SIGCLD. */
4972 no_avail = 1; /* Cannot depend on values returned */
4973 #else
4974 abort ();
4975 #endif
4977 else
4978 error ("select error: %s", emacs_strerror (xerrno));
4981 if (no_avail)
4983 FD_ZERO (&Available);
4984 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4987 #if 0 /* When polling is used, interrupt_input is 0,
4988 so get_input_pending should read the input.
4989 So this should not be needed. */
4990 /* If we are using polling for input,
4991 and we see input available, make it get read now.
4992 Otherwise it might not actually get read for a second.
4993 And on hpux, since we turn off polling in wait_reading_process_output,
4994 it might never get read at all if we don't spend much time
4995 outside of wait_reading_process_output. */
4996 if (read_kbd && interrupt_input
4997 && keyboard_bit_set (&Available)
4998 && input_polling_used ())
4999 kill (getpid (), SIGALRM);
5000 #endif
5002 /* Check for keyboard input */
5003 /* If there is any, return immediately
5004 to give it higher priority than subprocesses */
5006 if (read_kbd != 0)
5008 int old_timers_run = timers_run;
5009 struct buffer *old_buffer = current_buffer;
5010 Lisp_Object old_window = selected_window;
5011 int leave = 0;
5013 if (detect_input_pending_run_timers (do_display))
5015 swallow_events (do_display);
5016 if (detect_input_pending_run_timers (do_display))
5017 leave = 1;
5020 /* If a timer has run, this might have changed buffers
5021 an alike. Make read_key_sequence aware of that. */
5022 if (timers_run != old_timers_run
5023 && waiting_for_user_input_p == -1
5024 && (old_buffer != current_buffer
5025 || !EQ (old_window, selected_window)))
5026 record_asynch_buffer_change ();
5028 if (leave)
5029 break;
5032 /* If there is unread keyboard input, also return. */
5033 if (read_kbd != 0
5034 && requeued_events_pending_p ())
5035 break;
5037 /* If we are not checking for keyboard input now,
5038 do process events (but don't run any timers).
5039 This is so that X events will be processed.
5040 Otherwise they may have to wait until polling takes place.
5041 That would causes delays in pasting selections, for example.
5043 (We used to do this only if wait_for_cell.) */
5044 if (read_kbd == 0 && detect_input_pending ())
5046 swallow_events (do_display);
5047 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5048 if (detect_input_pending ())
5049 break;
5050 #endif
5053 /* Exit now if the cell we're waiting for became non-nil. */
5054 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5055 break;
5057 #ifdef SIGIO
5058 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5059 go read it. This can happen with X on BSD after logging out.
5060 In that case, there really is no input and no SIGIO,
5061 but select says there is input. */
5063 if (read_kbd && interrupt_input
5064 && keyboard_bit_set (&Available) && ! noninteractive)
5065 kill (getpid (), SIGIO);
5066 #endif
5068 if (! wait_proc)
5069 got_some_input |= nfds > 0;
5071 /* If checking input just got us a size-change event from X,
5072 obey it now if we should. */
5073 if (read_kbd || ! NILP (wait_for_cell))
5074 do_pending_window_change (0);
5076 /* Check for data from a process. */
5077 if (no_avail || nfds == 0)
5078 continue;
5080 /* Really FIRST_PROC_DESC should be 0 on Unix,
5081 but this is safer in the short run. */
5082 for (channel = 0; channel <= max_process_desc; channel++)
5084 if (FD_ISSET (channel, &Available)
5085 && FD_ISSET (channel, &non_keyboard_wait_mask))
5087 int nread;
5089 /* If waiting for this channel, arrange to return as
5090 soon as no more input to be processed. No more
5091 waiting. */
5092 if (wait_channel == channel)
5094 wait_channel = -1;
5095 time_limit = -1;
5096 got_some_input = 1;
5098 proc = chan_process[channel];
5099 if (NILP (proc))
5100 continue;
5102 /* If this is a server stream socket, accept connection. */
5103 if (EQ (XPROCESS (proc)->status, Qlisten))
5105 server_accept_connection (proc, channel);
5106 continue;
5109 /* Read data from the process, starting with our
5110 buffered-ahead character if we have one. */
5112 nread = read_process_output (proc, channel);
5113 if (nread > 0)
5115 /* Since read_process_output can run a filter,
5116 which can call accept-process-output,
5117 don't try to read from any other processes
5118 before doing the select again. */
5119 FD_ZERO (&Available);
5121 if (do_display)
5122 redisplay_preserve_echo_area (12);
5124 #ifdef EWOULDBLOCK
5125 else if (nread == -1 && errno == EWOULDBLOCK)
5127 #endif
5128 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5129 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5130 #ifdef O_NONBLOCK
5131 else if (nread == -1 && errno == EAGAIN)
5133 #else
5134 #ifdef O_NDELAY
5135 else if (nread == -1 && errno == EAGAIN)
5137 /* Note that we cannot distinguish between no input
5138 available now and a closed pipe.
5139 With luck, a closed pipe will be accompanied by
5140 subprocess termination and SIGCHLD. */
5141 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5143 #endif /* O_NDELAY */
5144 #endif /* O_NONBLOCK */
5145 #ifdef HAVE_PTYS
5146 /* On some OSs with ptys, when the process on one end of
5147 a pty exits, the other end gets an error reading with
5148 errno = EIO instead of getting an EOF (0 bytes read).
5149 Therefore, if we get an error reading and errno =
5150 EIO, just continue, because the child process has
5151 exited and should clean itself up soon (e.g. when we
5152 get a SIGCHLD).
5154 However, it has been known to happen that the SIGCHLD
5155 got lost. So raise the signal again just in case.
5156 It can't hurt. */
5157 else if (nread == -1 && errno == EIO)
5159 /* Clear the descriptor now, so we only raise the
5160 signal once. Don't do this if `process' is only
5161 a pty. */
5162 if (XPROCESS (proc)->pid != -2)
5164 FD_CLR (channel, &input_wait_mask);
5165 FD_CLR (channel, &non_keyboard_wait_mask);
5167 kill (getpid (), SIGCHLD);
5170 #endif /* HAVE_PTYS */
5171 /* If we can detect process termination, don't consider the process
5172 gone just because its pipe is closed. */
5173 #ifdef SIGCHLD
5174 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5176 #endif
5177 else
5179 /* Preserve status of processes already terminated. */
5180 XPROCESS (proc)->tick = ++process_tick;
5181 deactivate_process (proc);
5182 if (XPROCESS (proc)->raw_status_new)
5183 update_status (XPROCESS (proc));
5184 if (EQ (XPROCESS (proc)->status, Qrun))
5185 XPROCESS (proc)->status
5186 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5189 #ifdef NON_BLOCKING_CONNECT
5190 if (check_connect && FD_ISSET (channel, &Connecting)
5191 && FD_ISSET (channel, &connect_wait_mask))
5193 struct Lisp_Process *p;
5195 FD_CLR (channel, &connect_wait_mask);
5196 if (--num_pending_connects < 0)
5197 abort ();
5199 proc = chan_process[channel];
5200 if (NILP (proc))
5201 continue;
5203 p = XPROCESS (proc);
5205 #ifdef GNU_LINUX
5206 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5207 So only use it on systems where it is known to work. */
5209 int xlen = sizeof(xerrno);
5210 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5211 xerrno = errno;
5213 #else
5215 struct sockaddr pname;
5216 int pnamelen = sizeof(pname);
5218 /* If connection failed, getpeername will fail. */
5219 xerrno = 0;
5220 if (getpeername(channel, &pname, &pnamelen) < 0)
5222 /* Obtain connect failure code through error slippage. */
5223 char dummy;
5224 xerrno = errno;
5225 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5226 xerrno = errno;
5229 #endif
5230 if (xerrno)
5232 p->tick = ++process_tick;
5233 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5234 deactivate_process (proc);
5236 else
5238 p->status = Qrun;
5239 /* Execute the sentinel here. If we had relied on
5240 status_notify to do it later, it will read input
5241 from the process before calling the sentinel. */
5242 exec_sentinel (proc, build_string ("open\n"));
5243 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5245 FD_SET (p->infd, &input_wait_mask);
5246 FD_SET (p->infd, &non_keyboard_wait_mask);
5250 #endif /* NON_BLOCKING_CONNECT */
5251 } /* end for each file descriptor */
5252 } /* end while exit conditions not met */
5254 unbind_to (count, Qnil);
5256 /* If calling from keyboard input, do not quit
5257 since we want to return C-g as an input character.
5258 Otherwise, do pending quit if requested. */
5259 if (read_kbd >= 0)
5261 /* Prevent input_pending from remaining set if we quit. */
5262 clear_input_pending ();
5263 QUIT;
5266 return got_some_input;
5269 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5271 static Lisp_Object
5272 read_process_output_call (fun_and_args)
5273 Lisp_Object fun_and_args;
5275 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5278 static Lisp_Object
5279 read_process_output_error_handler (error)
5280 Lisp_Object error;
5282 cmd_error_internal (error, "error in process filter: ");
5283 Vinhibit_quit = Qt;
5284 update_echo_area ();
5285 Fsleep_for (make_number (2), Qnil);
5286 return Qt;
5289 /* Read pending output from the process channel,
5290 starting with our buffered-ahead character if we have one.
5291 Yield number of decoded characters read.
5293 This function reads at most 4096 characters.
5294 If you want to read all available subprocess output,
5295 you must call it repeatedly until it returns zero.
5297 The characters read are decoded according to PROC's coding-system
5298 for decoding. */
5300 static int
5301 read_process_output (proc, channel)
5302 Lisp_Object proc;
5303 register int channel;
5305 register int nbytes;
5306 char *chars;
5307 register Lisp_Object outstream;
5308 register struct Lisp_Process *p = XPROCESS (proc);
5309 register int opoint;
5310 struct coding_system *coding = proc_decode_coding_system[channel];
5311 int carryover = p->decoding_carryover;
5312 int readmax = 4096;
5314 chars = (char *) alloca (carryover + readmax);
5315 if (carryover)
5316 /* See the comment above. */
5317 bcopy (SDATA (p->decoding_buf), chars, carryover);
5319 #ifdef DATAGRAM_SOCKETS
5320 /* We have a working select, so proc_buffered_char is always -1. */
5321 if (DATAGRAM_CHAN_P (channel))
5323 int len = datagram_address[channel].len;
5324 nbytes = recvfrom (channel, chars + carryover, readmax,
5325 0, datagram_address[channel].sa, &len);
5327 else
5328 #endif
5329 if (proc_buffered_char[channel] < 0)
5331 nbytes = emacs_read (channel, chars + carryover, readmax);
5332 #ifdef ADAPTIVE_READ_BUFFERING
5333 if (nbytes > 0 && p->adaptive_read_buffering)
5335 int delay = p->read_output_delay;
5336 if (nbytes < 256)
5338 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5340 if (delay == 0)
5341 process_output_delay_count++;
5342 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5345 else if (delay > 0 && (nbytes == readmax))
5347 delay -= READ_OUTPUT_DELAY_INCREMENT;
5348 if (delay == 0)
5349 process_output_delay_count--;
5351 p->read_output_delay = delay;
5352 if (delay)
5354 p->read_output_skip = 1;
5355 process_output_skip = 1;
5358 #endif
5360 else
5362 chars[carryover] = proc_buffered_char[channel];
5363 proc_buffered_char[channel] = -1;
5364 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5365 if (nbytes < 0)
5366 nbytes = 1;
5367 else
5368 nbytes = nbytes + 1;
5371 p->decoding_carryover = 0;
5373 /* At this point, NBYTES holds number of bytes just received
5374 (including the one in proc_buffered_char[channel]). */
5375 if (nbytes <= 0)
5377 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5378 return nbytes;
5379 coding->mode |= CODING_MODE_LAST_BLOCK;
5382 /* Now set NBYTES how many bytes we must decode. */
5383 nbytes += carryover;
5385 /* Read and dispose of the process output. */
5386 outstream = p->filter;
5387 if (!NILP (outstream))
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 int count = SPECPDL_INDEX ();
5393 Lisp_Object odeactivate;
5394 Lisp_Object obuffer, okeymap;
5395 Lisp_Object text;
5396 int outer_running_asynch_code = running_asynch_code;
5397 int waiting = waiting_for_user_input_p;
5399 /* No need to gcpro these, because all we do with them later
5400 is test them for EQness, and none of them should be a string. */
5401 odeactivate = Vdeactivate_mark;
5402 XSETBUFFER (obuffer, current_buffer);
5403 okeymap = current_buffer->keymap;
5405 specbind (Qinhibit_quit, Qt);
5406 specbind (Qlast_nonmenu_event, Qt);
5408 /* In case we get recursively called,
5409 and we already saved the match data nonrecursively,
5410 save the same match data in safely recursive fashion. */
5411 if (outer_running_asynch_code)
5413 Lisp_Object tem;
5414 /* Don't clobber the CURRENT match data, either! */
5415 tem = Fmatch_data (Qnil, Qnil, Qnil);
5416 restore_search_regs ();
5417 record_unwind_save_match_data ();
5418 Fset_match_data (tem, Qt);
5421 /* For speed, if a search happens within this code,
5422 save the match data in a special nonrecursive fashion. */
5423 running_asynch_code = 1;
5425 decode_coding_c_string (coding, chars, nbytes, Qt);
5426 text = coding->dst_object;
5427 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5428 /* A new coding system might be found. */
5429 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5431 p->decode_coding_system = Vlast_coding_system_used;
5433 /* Don't call setup_coding_system for
5434 proc_decode_coding_system[channel] here. It is done in
5435 detect_coding called via decode_coding above. */
5437 /* If a coding system for encoding is not yet decided, we set
5438 it as the same as coding-system for decoding.
5440 But, before doing that we must check if
5441 proc_encode_coding_system[p->outfd] surely points to a
5442 valid memory because p->outfd will be changed once EOF is
5443 sent to the process. */
5444 if (NILP (p->encode_coding_system)
5445 && proc_encode_coding_system[p->outfd])
5447 p->encode_coding_system
5448 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5449 setup_coding_system (p->encode_coding_system,
5450 proc_encode_coding_system[p->outfd]);
5454 if (coding->carryover_bytes > 0)
5456 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5457 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5458 bcopy (coding->carryover, SDATA (p->decoding_buf),
5459 coding->carryover_bytes);
5460 p->decoding_carryover = coding->carryover_bytes;
5462 if (SBYTES (text) > 0)
5463 internal_condition_case_1 (read_process_output_call,
5464 Fcons (outstream,
5465 Fcons (proc, Fcons (text, Qnil))),
5466 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5467 read_process_output_error_handler);
5469 /* If we saved the match data nonrecursively, restore it now. */
5470 restore_search_regs ();
5471 running_asynch_code = outer_running_asynch_code;
5473 /* Handling the process output should not deactivate the mark. */
5474 Vdeactivate_mark = odeactivate;
5476 /* Restore waiting_for_user_input_p as it was
5477 when we were called, in case the filter clobbered it. */
5478 waiting_for_user_input_p = waiting;
5480 #if 0 /* Call record_asynch_buffer_change unconditionally,
5481 because we might have changed minor modes or other things
5482 that affect key bindings. */
5483 if (! EQ (Fcurrent_buffer (), obuffer)
5484 || ! EQ (current_buffer->keymap, okeymap))
5485 #endif
5486 /* But do it only if the caller is actually going to read events.
5487 Otherwise there's no need to make him wake up, and it could
5488 cause trouble (for example it would make sit_for return). */
5489 if (waiting_for_user_input_p == -1)
5490 record_asynch_buffer_change ();
5492 unbind_to (count, Qnil);
5493 return nbytes;
5496 /* If no filter, write into buffer if it isn't dead. */
5497 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5499 Lisp_Object old_read_only;
5500 int old_begv, old_zv;
5501 int old_begv_byte, old_zv_byte;
5502 Lisp_Object odeactivate;
5503 int before, before_byte;
5504 int opoint_byte;
5505 Lisp_Object text;
5506 struct buffer *b;
5507 int count = SPECPDL_INDEX ();
5509 odeactivate = Vdeactivate_mark;
5511 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5512 Fset_buffer (p->buffer);
5513 opoint = PT;
5514 opoint_byte = PT_BYTE;
5515 old_read_only = current_buffer->read_only;
5516 old_begv = BEGV;
5517 old_zv = ZV;
5518 old_begv_byte = BEGV_BYTE;
5519 old_zv_byte = ZV_BYTE;
5521 current_buffer->read_only = Qnil;
5523 /* Insert new output into buffer
5524 at the current end-of-output marker,
5525 thus preserving logical ordering of input and output. */
5526 if (XMARKER (p->mark)->buffer)
5527 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5528 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5529 ZV_BYTE));
5530 else
5531 SET_PT_BOTH (ZV, ZV_BYTE);
5532 before = PT;
5533 before_byte = PT_BYTE;
5535 /* If the output marker is outside of the visible region, save
5536 the restriction and widen. */
5537 if (! (BEGV <= PT && PT <= ZV))
5538 Fwiden ();
5540 decode_coding_c_string (coding, chars, nbytes, Qt);
5541 text = coding->dst_object;
5542 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5543 /* A new coding system might be found. See the comment in the
5544 similar code in the previous `if' block. */
5545 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5547 p->decode_coding_system = Vlast_coding_system_used;
5548 if (NILP (p->encode_coding_system)
5549 && proc_encode_coding_system[p->outfd])
5551 p->encode_coding_system
5552 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5553 setup_coding_system (p->encode_coding_system,
5554 proc_encode_coding_system[p->outfd]);
5557 if (coding->carryover_bytes > 0)
5559 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5560 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5561 bcopy (coding->carryover, SDATA (p->decoding_buf),
5562 coding->carryover_bytes);
5563 p->decoding_carryover = coding->carryover_bytes;
5565 /* Adjust the multibyteness of TEXT to that of the buffer. */
5566 if (NILP (current_buffer->enable_multibyte_characters)
5567 != ! STRING_MULTIBYTE (text))
5568 text = (STRING_MULTIBYTE (text)
5569 ? Fstring_as_unibyte (text)
5570 : Fstring_to_multibyte (text));
5571 /* Insert before markers in case we are inserting where
5572 the buffer's mark is, and the user's next command is Meta-y. */
5573 insert_from_string_before_markers (text, 0, 0,
5574 SCHARS (text), SBYTES (text), 0);
5576 /* Make sure the process marker's position is valid when the
5577 process buffer is changed in the signal_after_change above.
5578 W3 is known to do that. */
5579 if (BUFFERP (p->buffer)
5580 && (b = XBUFFER (p->buffer), b != current_buffer))
5581 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5582 else
5583 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5585 update_mode_lines++;
5587 /* Make sure opoint and the old restrictions
5588 float ahead of any new text just as point would. */
5589 if (opoint >= before)
5591 opoint += PT - before;
5592 opoint_byte += PT_BYTE - before_byte;
5594 if (old_begv > before)
5596 old_begv += PT - before;
5597 old_begv_byte += PT_BYTE - before_byte;
5599 if (old_zv >= before)
5601 old_zv += PT - before;
5602 old_zv_byte += PT_BYTE - before_byte;
5605 /* If the restriction isn't what it should be, set it. */
5606 if (old_begv != BEGV || old_zv != ZV)
5607 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5609 /* Handling the process output should not deactivate the mark. */
5610 Vdeactivate_mark = odeactivate;
5612 current_buffer->read_only = old_read_only;
5613 SET_PT_BOTH (opoint, opoint_byte);
5614 unbind_to (count, Qnil);
5616 return nbytes;
5619 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5620 0, 0, 0,
5621 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5622 This is intended for use by asynchronous process output filters and sentinels. */)
5625 return (waiting_for_user_input_p ? Qt : Qnil);
5628 /* Sending data to subprocess */
5630 jmp_buf send_process_frame;
5631 Lisp_Object process_sent_to;
5633 SIGTYPE
5634 send_process_trap ()
5636 SIGNAL_THREAD_CHECK (SIGPIPE);
5637 sigunblock (sigmask (SIGPIPE));
5638 longjmp (send_process_frame, 1);
5641 /* Send some data to process PROC.
5642 BUF is the beginning of the data; LEN is the number of characters.
5643 OBJECT is the Lisp object that the data comes from. If OBJECT is
5644 nil or t, it means that the data comes from C string.
5646 If OBJECT is not nil, the data is encoded by PROC's coding-system
5647 for encoding before it is sent.
5649 This function can evaluate Lisp code and can garbage collect. */
5651 static void
5652 send_process (proc, buf, len, object)
5653 volatile Lisp_Object proc;
5654 unsigned char *volatile buf;
5655 volatile int len;
5656 volatile Lisp_Object object;
5658 /* Use volatile to protect variables from being clobbered by longjmp. */
5659 struct Lisp_Process *p = XPROCESS (proc);
5660 int rv;
5661 struct coding_system *coding;
5662 struct gcpro gcpro1;
5663 SIGTYPE (*volatile old_sigpipe) ();
5665 GCPRO1 (object);
5667 if (p->raw_status_new)
5668 update_status (p);
5669 if (! EQ (p->status, Qrun))
5670 error ("Process %s not running", SDATA (p->name));
5671 if (p->outfd < 0)
5672 error ("Output file descriptor of %s is closed", SDATA (p->name));
5674 coding = proc_encode_coding_system[p->outfd];
5675 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5677 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5678 || (BUFFERP (object)
5679 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5680 || EQ (object, Qt))
5682 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5683 /* The coding system for encoding was changed to raw-text
5684 because we sent a unibyte text previously. Now we are
5685 sending a multibyte text, thus we must encode it by the
5686 original coding system specified for the current process. */
5687 setup_coding_system (p->encode_coding_system, coding);
5688 coding->src_multibyte = 1;
5690 else
5692 /* For sending a unibyte text, character code conversion should
5693 not take place but EOL conversion should. So, setup raw-text
5694 or one of the subsidiary if we have not yet done it. */
5695 if (CODING_REQUIRE_ENCODING (coding))
5697 if (CODING_REQUIRE_FLUSHING (coding))
5699 /* But, before changing the coding, we must flush out data. */
5700 coding->mode |= CODING_MODE_LAST_BLOCK;
5701 send_process (proc, "", 0, Qt);
5702 coding->mode &= CODING_MODE_LAST_BLOCK;
5704 setup_coding_system (raw_text_coding_system
5705 (Vlast_coding_system_used),
5706 coding);
5707 coding->src_multibyte = 0;
5710 coding->dst_multibyte = 0;
5712 if (CODING_REQUIRE_ENCODING (coding))
5714 coding->dst_object = Qt;
5715 if (BUFFERP (object))
5717 int from_byte, from, to;
5718 int save_pt, save_pt_byte;
5719 struct buffer *cur = current_buffer;
5721 set_buffer_internal (XBUFFER (object));
5722 save_pt = PT, save_pt_byte = PT_BYTE;
5724 from_byte = PTR_BYTE_POS (buf);
5725 from = BYTE_TO_CHAR (from_byte);
5726 to = BYTE_TO_CHAR (from_byte + len);
5727 TEMP_SET_PT_BOTH (from, from_byte);
5728 encode_coding_object (coding, object, from, from_byte,
5729 to, from_byte + len, Qt);
5730 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5731 set_buffer_internal (cur);
5733 else if (STRINGP (object))
5735 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5736 SBYTES (object), Qt);
5738 else
5740 coding->dst_object = make_unibyte_string (buf, len);
5741 coding->produced = len;
5744 len = coding->produced;
5745 object = coding->dst_object;
5746 buf = SDATA (object);
5749 if (pty_max_bytes == 0)
5751 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5752 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5753 if (pty_max_bytes < 0)
5754 pty_max_bytes = 250;
5755 #else
5756 pty_max_bytes = 250;
5757 #endif
5758 /* Deduct one, to leave space for the eof. */
5759 pty_max_bytes--;
5762 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5763 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5764 when returning with longjmp despite being declared volatile. */
5765 if (!setjmp (send_process_frame))
5767 process_sent_to = proc;
5768 while (len > 0)
5770 int this = len;
5772 /* Decide how much data we can send in one batch.
5773 Long lines need to be split into multiple batches. */
5774 if (p->pty_flag)
5776 /* Starting this at zero is always correct when not the first
5777 iteration because the previous iteration ended by sending C-d.
5778 It may not be correct for the first iteration
5779 if a partial line was sent in a separate send_process call.
5780 If that proves worth handling, we need to save linepos
5781 in the process object. */
5782 int linepos = 0;
5783 unsigned char *ptr = (unsigned char *) buf;
5784 unsigned char *end = (unsigned char *) buf + len;
5786 /* Scan through this text for a line that is too long. */
5787 while (ptr != end && linepos < pty_max_bytes)
5789 if (*ptr == '\n')
5790 linepos = 0;
5791 else
5792 linepos++;
5793 ptr++;
5795 /* If we found one, break the line there
5796 and put in a C-d to force the buffer through. */
5797 this = ptr - buf;
5800 /* Send this batch, using one or more write calls. */
5801 while (this > 0)
5803 int outfd = p->outfd;
5804 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5805 #ifdef DATAGRAM_SOCKETS
5806 if (DATAGRAM_CHAN_P (outfd))
5808 rv = sendto (outfd, (char *) buf, this,
5809 0, datagram_address[outfd].sa,
5810 datagram_address[outfd].len);
5811 if (rv < 0 && errno == EMSGSIZE)
5813 signal (SIGPIPE, old_sigpipe);
5814 report_file_error ("sending datagram",
5815 Fcons (proc, Qnil));
5818 else
5819 #endif
5821 rv = emacs_write (outfd, (char *) buf, this);
5822 #ifdef ADAPTIVE_READ_BUFFERING
5823 if (p->read_output_delay > 0
5824 && p->adaptive_read_buffering == 1)
5826 p->read_output_delay = 0;
5827 process_output_delay_count--;
5828 p->read_output_skip = 0;
5830 #endif
5832 signal (SIGPIPE, old_sigpipe);
5834 if (rv < 0)
5836 if (0
5837 #ifdef EWOULDBLOCK
5838 || errno == EWOULDBLOCK
5839 #endif
5840 #ifdef EAGAIN
5841 || errno == EAGAIN
5842 #endif
5844 /* Buffer is full. Wait, accepting input;
5845 that may allow the program
5846 to finish doing output and read more. */
5848 int offset = 0;
5850 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5851 /* A gross hack to work around a bug in FreeBSD.
5852 In the following sequence, read(2) returns
5853 bogus data:
5855 write(2) 1022 bytes
5856 write(2) 954 bytes, get EAGAIN
5857 read(2) 1024 bytes in process_read_output
5858 read(2) 11 bytes in process_read_output
5860 That is, read(2) returns more bytes than have
5861 ever been written successfully. The 1033 bytes
5862 read are the 1022 bytes written successfully
5863 after processing (for example with CRs added if
5864 the terminal is set up that way which it is
5865 here). The same bytes will be seen again in a
5866 later read(2), without the CRs. */
5868 if (errno == EAGAIN)
5870 int flags = FWRITE;
5871 ioctl (p->outfd, TIOCFLUSH, &flags);
5873 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5875 /* Running filters might relocate buffers or strings.
5876 Arrange to relocate BUF. */
5877 if (BUFFERP (object))
5878 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5879 else if (STRINGP (object))
5880 offset = buf - SDATA (object);
5882 #ifdef EMACS_HAS_USECS
5883 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5884 #else
5885 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5886 #endif
5888 if (BUFFERP (object))
5889 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5890 else if (STRINGP (object))
5891 buf = offset + SDATA (object);
5893 rv = 0;
5895 else
5896 /* This is a real error. */
5897 report_file_error ("writing to process", Fcons (proc, Qnil));
5899 buf += rv;
5900 len -= rv;
5901 this -= rv;
5904 /* If we sent just part of the string, put in an EOF (C-d)
5905 to force it through, before we send the rest. */
5906 if (len > 0)
5907 Fprocess_send_eof (proc);
5910 else
5912 signal (SIGPIPE, old_sigpipe);
5913 proc = process_sent_to;
5914 p = XPROCESS (proc);
5915 p->raw_status_new = 0;
5916 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5917 p->tick = ++process_tick;
5918 deactivate_process (proc);
5919 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5922 UNGCPRO;
5925 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5926 3, 3, 0,
5927 doc: /* Send current contents of region as input to PROCESS.
5928 PROCESS may be a process, a buffer, the name of a process or buffer, or
5929 nil, indicating the current buffer's process.
5930 Called from program, takes three arguments, PROCESS, START and END.
5931 If the region is more than 500 characters long,
5932 it is sent in several bunches. This may happen even for shorter regions.
5933 Output from processes can arrive in between bunches. */)
5934 (process, start, end)
5935 Lisp_Object process, start, end;
5937 Lisp_Object proc;
5938 int start1, end1;
5940 proc = get_process (process);
5941 validate_region (&start, &end);
5943 if (XINT (start) < GPT && XINT (end) > GPT)
5944 move_gap (XINT (start));
5946 start1 = CHAR_TO_BYTE (XINT (start));
5947 end1 = CHAR_TO_BYTE (XINT (end));
5948 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5949 Fcurrent_buffer ());
5951 return Qnil;
5954 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5955 2, 2, 0,
5956 doc: /* Send PROCESS the contents of STRING as input.
5957 PROCESS may be a process, a buffer, the name of a process or buffer, or
5958 nil, indicating the current buffer's process.
5959 If STRING is more than 500 characters long,
5960 it is sent in several bunches. This may happen even for shorter strings.
5961 Output from processes can arrive in between bunches. */)
5962 (process, string)
5963 Lisp_Object process, string;
5965 Lisp_Object proc;
5966 CHECK_STRING (string);
5967 proc = get_process (process);
5968 send_process (proc, SDATA (string),
5969 SBYTES (string), string);
5970 return Qnil;
5973 /* Return the foreground process group for the tty/pty that
5974 the process P uses. */
5975 static int
5976 emacs_get_tty_pgrp (p)
5977 struct Lisp_Process *p;
5979 int gid = -1;
5981 #ifdef TIOCGPGRP
5982 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5984 int fd;
5985 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5986 master side. Try the slave side. */
5987 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5989 if (fd != -1)
5991 ioctl (fd, TIOCGPGRP, &gid);
5992 emacs_close (fd);
5995 #endif /* defined (TIOCGPGRP ) */
5997 return gid;
6000 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6001 Sprocess_running_child_p, 0, 1, 0,
6002 doc: /* Return t if PROCESS has given the terminal to a child.
6003 If the operating system does not make it possible to find out,
6004 return t unconditionally. */)
6005 (process)
6006 Lisp_Object process;
6008 /* Initialize in case ioctl doesn't exist or gives an error,
6009 in a way that will cause returning t. */
6010 int gid;
6011 Lisp_Object proc;
6012 struct Lisp_Process *p;
6014 proc = get_process (process);
6015 p = XPROCESS (proc);
6017 if (!EQ (p->type, Qreal))
6018 error ("Process %s is not a subprocess",
6019 SDATA (p->name));
6020 if (p->infd < 0)
6021 error ("Process %s is not active",
6022 SDATA (p->name));
6024 gid = emacs_get_tty_pgrp (p);
6026 if (gid == p->pid)
6027 return Qnil;
6028 return Qt;
6031 /* send a signal number SIGNO to PROCESS.
6032 If CURRENT_GROUP is t, that means send to the process group
6033 that currently owns the terminal being used to communicate with PROCESS.
6034 This is used for various commands in shell mode.
6035 If CURRENT_GROUP is lambda, that means send to the process group
6036 that currently owns the terminal, but only if it is NOT the shell itself.
6038 If NOMSG is zero, insert signal-announcements into process's buffers
6039 right away.
6041 If we can, we try to signal PROCESS by sending control characters
6042 down the pty. This allows us to signal inferiors who have changed
6043 their uid, for which killpg would return an EPERM error. */
6045 static void
6046 process_send_signal (process, signo, current_group, nomsg)
6047 Lisp_Object process;
6048 int signo;
6049 Lisp_Object current_group;
6050 int nomsg;
6052 Lisp_Object proc;
6053 register struct Lisp_Process *p;
6054 int gid;
6055 int no_pgrp = 0;
6057 proc = get_process (process);
6058 p = XPROCESS (proc);
6060 if (!EQ (p->type, Qreal))
6061 error ("Process %s is not a subprocess",
6062 SDATA (p->name));
6063 if (p->infd < 0)
6064 error ("Process %s is not active",
6065 SDATA (p->name));
6067 if (!p->pty_flag)
6068 current_group = Qnil;
6070 /* If we are using pgrps, get a pgrp number and make it negative. */
6071 if (NILP (current_group))
6072 /* Send the signal to the shell's process group. */
6073 gid = p->pid;
6074 else
6076 #ifdef SIGNALS_VIA_CHARACTERS
6077 /* If possible, send signals to the entire pgrp
6078 by sending an input character to it. */
6080 /* TERMIOS is the latest and bestest, and seems most likely to
6081 work. If the system has it, use it. */
6082 #ifdef HAVE_TERMIOS
6083 struct termios t;
6084 cc_t *sig_char = NULL;
6086 tcgetattr (p->infd, &t);
6088 switch (signo)
6090 case SIGINT:
6091 sig_char = &t.c_cc[VINTR];
6092 break;
6094 case SIGQUIT:
6095 sig_char = &t.c_cc[VQUIT];
6096 break;
6098 case SIGTSTP:
6099 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6100 sig_char = &t.c_cc[VSWTCH];
6101 #else
6102 sig_char = &t.c_cc[VSUSP];
6103 #endif
6104 break;
6107 if (sig_char && *sig_char != CDISABLE)
6109 send_process (proc, sig_char, 1, Qnil);
6110 return;
6112 /* If we can't send the signal with a character,
6113 fall through and send it another way. */
6114 #else /* ! HAVE_TERMIOS */
6116 /* On Berkeley descendants, the following IOCTL's retrieve the
6117 current control characters. */
6118 #if defined (TIOCGLTC) && defined (TIOCGETC)
6120 struct tchars c;
6121 struct ltchars lc;
6123 switch (signo)
6125 case SIGINT:
6126 ioctl (p->infd, TIOCGETC, &c);
6127 send_process (proc, &c.t_intrc, 1, Qnil);
6128 return;
6129 case SIGQUIT:
6130 ioctl (p->infd, TIOCGETC, &c);
6131 send_process (proc, &c.t_quitc, 1, Qnil);
6132 return;
6133 #ifdef SIGTSTP
6134 case SIGTSTP:
6135 ioctl (p->infd, TIOCGLTC, &lc);
6136 send_process (proc, &lc.t_suspc, 1, Qnil);
6137 return;
6138 #endif /* ! defined (SIGTSTP) */
6141 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6143 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6144 characters. */
6145 #ifdef TCGETA
6146 struct termio t;
6147 switch (signo)
6149 case SIGINT:
6150 ioctl (p->infd, TCGETA, &t);
6151 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6152 return;
6153 case SIGQUIT:
6154 ioctl (p->infd, TCGETA, &t);
6155 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6156 return;
6157 #ifdef SIGTSTP
6158 case SIGTSTP:
6159 ioctl (p->infd, TCGETA, &t);
6160 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6161 return;
6162 #endif /* ! defined (SIGTSTP) */
6164 #else /* ! defined (TCGETA) */
6165 Your configuration files are messed up.
6166 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6167 you'd better be using one of the alternatives above! */
6168 #endif /* ! defined (TCGETA) */
6169 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6170 /* In this case, the code above should alway return. */
6171 abort ();
6172 #endif /* ! defined HAVE_TERMIOS */
6174 /* The code above may fall through if it can't
6175 handle the signal. */
6176 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6178 #ifdef TIOCGPGRP
6179 /* Get the current pgrp using the tty itself, if we have that.
6180 Otherwise, use the pty to get the pgrp.
6181 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6182 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6183 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6184 His patch indicates that if TIOCGPGRP returns an error, then
6185 we should just assume that p->pid is also the process group id. */
6187 gid = emacs_get_tty_pgrp (p);
6189 if (gid == -1)
6190 /* If we can't get the information, assume
6191 the shell owns the tty. */
6192 gid = p->pid;
6194 /* It is not clear whether anything really can set GID to -1.
6195 Perhaps on some system one of those ioctls can or could do so.
6196 Or perhaps this is vestigial. */
6197 if (gid == -1)
6198 no_pgrp = 1;
6199 #else /* ! defined (TIOCGPGRP ) */
6200 /* Can't select pgrps on this system, so we know that
6201 the child itself heads the pgrp. */
6202 gid = p->pid;
6203 #endif /* ! defined (TIOCGPGRP ) */
6205 /* If current_group is lambda, and the shell owns the terminal,
6206 don't send any signal. */
6207 if (EQ (current_group, Qlambda) && gid == p->pid)
6208 return;
6211 switch (signo)
6213 #ifdef SIGCONT
6214 case SIGCONT:
6215 p->raw_status_new = 0;
6216 p->status = Qrun;
6217 p->tick = ++process_tick;
6218 if (!nomsg)
6220 status_notify (NULL);
6221 redisplay_preserve_echo_area (13);
6223 break;
6224 #endif /* ! defined (SIGCONT) */
6225 case SIGINT:
6226 case SIGQUIT:
6227 case SIGKILL:
6228 flush_pending_output (p->infd);
6229 break;
6232 /* If we don't have process groups, send the signal to the immediate
6233 subprocess. That isn't really right, but it's better than any
6234 obvious alternative. */
6235 if (no_pgrp)
6237 kill (p->pid, signo);
6238 return;
6241 /* gid may be a pid, or minus a pgrp's number */
6242 #ifdef TIOCSIGSEND
6243 if (!NILP (current_group))
6245 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6246 EMACS_KILLPG (gid, signo);
6248 else
6250 gid = - p->pid;
6251 kill (gid, signo);
6253 #else /* ! defined (TIOCSIGSEND) */
6254 EMACS_KILLPG (gid, signo);
6255 #endif /* ! defined (TIOCSIGSEND) */
6258 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6259 doc: /* Interrupt process PROCESS.
6260 PROCESS may be a process, a buffer, or the name of a process or buffer.
6261 No arg or nil means current buffer's process.
6262 Second arg CURRENT-GROUP non-nil means send signal to
6263 the current process-group of the process's controlling terminal
6264 rather than to the process's own process group.
6265 If the process is a shell, this means interrupt current subjob
6266 rather than the shell.
6268 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6269 don't send the signal. */)
6270 (process, current_group)
6271 Lisp_Object process, current_group;
6273 process_send_signal (process, SIGINT, current_group, 0);
6274 return process;
6277 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6278 doc: /* Kill process PROCESS. May be process or name of one.
6279 See function `interrupt-process' for more details on usage. */)
6280 (process, current_group)
6281 Lisp_Object process, current_group;
6283 process_send_signal (process, SIGKILL, current_group, 0);
6284 return process;
6287 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6288 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6289 See function `interrupt-process' for more details on usage. */)
6290 (process, current_group)
6291 Lisp_Object process, current_group;
6293 process_send_signal (process, SIGQUIT, current_group, 0);
6294 return process;
6297 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6298 doc: /* Stop process PROCESS. May be process or name of one.
6299 See function `interrupt-process' for more details on usage.
6300 If PROCESS is a network or serial process, inhibit handling of incoming
6301 traffic. */)
6302 (process, current_group)
6303 Lisp_Object process, current_group;
6305 #ifdef HAVE_SOCKETS
6306 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6308 struct Lisp_Process *p;
6310 p = XPROCESS (process);
6311 if (NILP (p->command)
6312 && p->infd >= 0)
6314 FD_CLR (p->infd, &input_wait_mask);
6315 FD_CLR (p->infd, &non_keyboard_wait_mask);
6317 p->command = Qt;
6318 return process;
6320 #endif
6321 #ifndef SIGTSTP
6322 error ("No SIGTSTP support");
6323 #else
6324 process_send_signal (process, SIGTSTP, current_group, 0);
6325 #endif
6326 return process;
6329 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6330 doc: /* Continue process PROCESS. May be process or name of one.
6331 See function `interrupt-process' for more details on usage.
6332 If PROCESS is a network or serial process, resume handling of incoming
6333 traffic. */)
6334 (process, current_group)
6335 Lisp_Object process, current_group;
6337 #ifdef HAVE_SOCKETS
6338 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6340 struct Lisp_Process *p;
6342 p = XPROCESS (process);
6343 if (EQ (p->command, Qt)
6344 && p->infd >= 0
6345 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6347 FD_SET (p->infd, &input_wait_mask);
6348 FD_SET (p->infd, &non_keyboard_wait_mask);
6349 #ifdef WINDOWSNT
6350 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6351 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6352 #endif
6353 #ifdef HAVE_TERMIOS
6354 tcflush (p->infd, TCIFLUSH);
6355 #endif
6357 p->command = Qnil;
6358 return process;
6360 #endif
6361 #ifdef SIGCONT
6362 process_send_signal (process, SIGCONT, current_group, 0);
6363 #else
6364 error ("No SIGCONT support");
6365 #endif
6366 return process;
6369 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6370 2, 2, "sProcess (name or number): \nnSignal code: ",
6371 doc: /* Send PROCESS the signal with code SIGCODE.
6372 PROCESS may also be a number specifying the process id of the
6373 process to signal; in this case, the process need not be a child of
6374 this Emacs.
6375 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6376 (process, sigcode)
6377 Lisp_Object process, sigcode;
6379 pid_t pid;
6381 if (INTEGERP (process))
6383 pid = XINT (process);
6384 goto got_it;
6387 if (FLOATP (process))
6389 pid = (pid_t) XFLOAT_DATA (process);
6390 goto got_it;
6393 if (STRINGP (process))
6395 Lisp_Object tem;
6396 if (tem = Fget_process (process), NILP (tem))
6398 pid = XINT (Fstring_to_number (process, make_number (10)));
6399 if (pid > 0)
6400 goto got_it;
6402 process = tem;
6404 else
6405 process = get_process (process);
6407 if (NILP (process))
6408 return process;
6410 CHECK_PROCESS (process);
6411 pid = XPROCESS (process)->pid;
6412 if (pid <= 0)
6413 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6415 got_it:
6417 #define parse_signal(NAME, VALUE) \
6418 else if (!xstrcasecmp (name, NAME)) \
6419 XSETINT (sigcode, VALUE)
6421 if (INTEGERP (sigcode))
6423 else
6425 unsigned char *name;
6427 CHECK_SYMBOL (sigcode);
6428 name = SDATA (SYMBOL_NAME (sigcode));
6430 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6431 name += 3;
6433 if (0)
6435 #ifdef SIGUSR1
6436 parse_signal ("usr1", SIGUSR1);
6437 #endif
6438 #ifdef SIGUSR2
6439 parse_signal ("usr2", SIGUSR2);
6440 #endif
6441 #ifdef SIGTERM
6442 parse_signal ("term", SIGTERM);
6443 #endif
6444 #ifdef SIGHUP
6445 parse_signal ("hup", SIGHUP);
6446 #endif
6447 #ifdef SIGINT
6448 parse_signal ("int", SIGINT);
6449 #endif
6450 #ifdef SIGQUIT
6451 parse_signal ("quit", SIGQUIT);
6452 #endif
6453 #ifdef SIGILL
6454 parse_signal ("ill", SIGILL);
6455 #endif
6456 #ifdef SIGABRT
6457 parse_signal ("abrt", SIGABRT);
6458 #endif
6459 #ifdef SIGEMT
6460 parse_signal ("emt", SIGEMT);
6461 #endif
6462 #ifdef SIGKILL
6463 parse_signal ("kill", SIGKILL);
6464 #endif
6465 #ifdef SIGFPE
6466 parse_signal ("fpe", SIGFPE);
6467 #endif
6468 #ifdef SIGBUS
6469 parse_signal ("bus", SIGBUS);
6470 #endif
6471 #ifdef SIGSEGV
6472 parse_signal ("segv", SIGSEGV);
6473 #endif
6474 #ifdef SIGSYS
6475 parse_signal ("sys", SIGSYS);
6476 #endif
6477 #ifdef SIGPIPE
6478 parse_signal ("pipe", SIGPIPE);
6479 #endif
6480 #ifdef SIGALRM
6481 parse_signal ("alrm", SIGALRM);
6482 #endif
6483 #ifdef SIGURG
6484 parse_signal ("urg", SIGURG);
6485 #endif
6486 #ifdef SIGSTOP
6487 parse_signal ("stop", SIGSTOP);
6488 #endif
6489 #ifdef SIGTSTP
6490 parse_signal ("tstp", SIGTSTP);
6491 #endif
6492 #ifdef SIGCONT
6493 parse_signal ("cont", SIGCONT);
6494 #endif
6495 #ifdef SIGCHLD
6496 parse_signal ("chld", SIGCHLD);
6497 #endif
6498 #ifdef SIGTTIN
6499 parse_signal ("ttin", SIGTTIN);
6500 #endif
6501 #ifdef SIGTTOU
6502 parse_signal ("ttou", SIGTTOU);
6503 #endif
6504 #ifdef SIGIO
6505 parse_signal ("io", SIGIO);
6506 #endif
6507 #ifdef SIGXCPU
6508 parse_signal ("xcpu", SIGXCPU);
6509 #endif
6510 #ifdef SIGXFSZ
6511 parse_signal ("xfsz", SIGXFSZ);
6512 #endif
6513 #ifdef SIGVTALRM
6514 parse_signal ("vtalrm", SIGVTALRM);
6515 #endif
6516 #ifdef SIGPROF
6517 parse_signal ("prof", SIGPROF);
6518 #endif
6519 #ifdef SIGWINCH
6520 parse_signal ("winch", SIGWINCH);
6521 #endif
6522 #ifdef SIGINFO
6523 parse_signal ("info", SIGINFO);
6524 #endif
6525 else
6526 error ("Undefined signal name %s", name);
6529 #undef parse_signal
6531 return make_number (kill (pid, XINT (sigcode)));
6534 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6535 doc: /* Make PROCESS see end-of-file in its input.
6536 EOF comes after any text already sent to it.
6537 PROCESS may be a process, a buffer, the name of a process or buffer, or
6538 nil, indicating the current buffer's process.
6539 If PROCESS is a network connection, or is a process communicating
6540 through a pipe (as opposed to a pty), then you cannot send any more
6541 text to PROCESS after you call this function.
6542 If PROCESS is a serial process, wait until all output written to the
6543 process has been transmitted to the serial port. */)
6544 (process)
6545 Lisp_Object process;
6547 Lisp_Object proc;
6548 struct coding_system *coding;
6550 if (DATAGRAM_CONN_P (process))
6551 return process;
6553 proc = get_process (process);
6554 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6556 /* Make sure the process is really alive. */
6557 if (XPROCESS (proc)->raw_status_new)
6558 update_status (XPROCESS (proc));
6559 if (! EQ (XPROCESS (proc)->status, Qrun))
6560 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6562 if (CODING_REQUIRE_FLUSHING (coding))
6564 coding->mode |= CODING_MODE_LAST_BLOCK;
6565 send_process (proc, "", 0, Qnil);
6568 if (XPROCESS (proc)->pty_flag)
6569 send_process (proc, "\004", 1, Qnil);
6570 else if (EQ (XPROCESS (proc)->type, Qserial))
6572 #ifdef HAVE_TERMIOS
6573 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6574 error ("tcdrain() failed: %s", emacs_strerror (errno));
6575 #endif
6576 /* Do nothing on Windows because writes are blocking. */
6578 else
6580 int old_outfd, new_outfd;
6582 #ifdef HAVE_SHUTDOWN
6583 /* If this is a network connection, or socketpair is used
6584 for communication with the subprocess, call shutdown to cause EOF.
6585 (In some old system, shutdown to socketpair doesn't work.
6586 Then we just can't win.) */
6587 if (EQ (XPROCESS (proc)->type, Qnetwork)
6588 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6589 shutdown (XPROCESS (proc)->outfd, 1);
6590 /* In case of socketpair, outfd == infd, so don't close it. */
6591 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6592 emacs_close (XPROCESS (proc)->outfd);
6593 #else /* not HAVE_SHUTDOWN */
6594 emacs_close (XPROCESS (proc)->outfd);
6595 #endif /* not HAVE_SHUTDOWN */
6596 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6597 if (new_outfd < 0)
6598 abort ();
6599 old_outfd = XPROCESS (proc)->outfd;
6601 if (!proc_encode_coding_system[new_outfd])
6602 proc_encode_coding_system[new_outfd]
6603 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6604 bcopy (proc_encode_coding_system[old_outfd],
6605 proc_encode_coding_system[new_outfd],
6606 sizeof (struct coding_system));
6607 bzero (proc_encode_coding_system[old_outfd],
6608 sizeof (struct coding_system));
6610 XPROCESS (proc)->outfd = new_outfd;
6612 return process;
6615 /* Kill all processes associated with `buffer'.
6616 If `buffer' is nil, kill all processes */
6618 void
6619 kill_buffer_processes (buffer)
6620 Lisp_Object buffer;
6622 Lisp_Object tail, proc;
6624 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6626 proc = XCDR (XCAR (tail));
6627 if (PROCESSP (proc)
6628 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6630 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6631 Fdelete_process (proc);
6632 else if (XPROCESS (proc)->infd >= 0)
6633 process_send_signal (proc, SIGHUP, Qnil, 1);
6638 /* On receipt of a signal that a child status has changed, loop asking
6639 about children with changed statuses until the system says there
6640 are no more.
6642 All we do is change the status; we do not run sentinels or print
6643 notifications. That is saved for the next time keyboard input is
6644 done, in order to avoid timing errors.
6646 ** WARNING: this can be called during garbage collection.
6647 Therefore, it must not be fooled by the presence of mark bits in
6648 Lisp objects.
6650 ** USG WARNING: Although it is not obvious from the documentation
6651 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6652 signal() before executing at least one wait(), otherwise the
6653 handler will be called again, resulting in an infinite loop. The
6654 relevant portion of the documentation reads "SIGCLD signals will be
6655 queued and the signal-catching function will be continually
6656 reentered until the queue is empty". Invoking signal() causes the
6657 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6658 Inc.
6660 ** Malloc WARNING: This should never call malloc either directly or
6661 indirectly; if it does, that is a bug */
6663 #ifdef SIGCHLD
6664 SIGTYPE
6665 sigchld_handler (signo)
6666 int signo;
6668 int old_errno = errno;
6669 Lisp_Object proc;
6670 register struct Lisp_Process *p;
6671 extern EMACS_TIME *input_available_clear_time;
6673 SIGNAL_THREAD_CHECK (signo);
6675 while (1)
6677 pid_t pid;
6678 int w;
6679 Lisp_Object tail;
6681 #ifdef WNOHANG
6682 #ifndef WUNTRACED
6683 #define WUNTRACED 0
6684 #endif /* no WUNTRACED */
6685 /* Keep trying to get a status until we get a definitive result. */
6688 errno = 0;
6689 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6691 while (pid < 0 && errno == EINTR);
6693 if (pid <= 0)
6695 /* PID == 0 means no processes found, PID == -1 means a real
6696 failure. We have done all our job, so return. */
6698 /* USG systems forget handlers when they are used;
6699 must reestablish each time */
6700 #if defined (USG) && !defined (POSIX_SIGNALS)
6701 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6702 #endif
6703 errno = old_errno;
6704 return;
6706 #else
6707 pid = wait (&w);
6708 #endif /* no WNOHANG */
6710 /* Find the process that signaled us, and record its status. */
6712 /* The process can have been deleted by Fdelete_process. */
6713 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6715 Lisp_Object xpid = XCAR (tail);
6716 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6717 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6719 XSETCAR (tail, Qnil);
6720 goto sigchld_end_of_loop;
6724 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6725 p = 0;
6726 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6728 proc = XCDR (XCAR (tail));
6729 p = XPROCESS (proc);
6730 if (EQ (p->type, Qreal) && p->pid == pid)
6731 break;
6732 p = 0;
6735 /* Look for an asynchronous process whose pid hasn't been filled
6736 in yet. */
6737 if (p == 0)
6738 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6740 proc = XCDR (XCAR (tail));
6741 p = XPROCESS (proc);
6742 if (p->pid == -1)
6743 break;
6744 p = 0;
6747 /* Change the status of the process that was found. */
6748 if (p != 0)
6750 int clear_desc_flag = 0;
6752 p->tick = ++process_tick;
6753 p->raw_status = w;
6754 p->raw_status_new = 1;
6756 /* If process has terminated, stop waiting for its output. */
6757 if ((WIFSIGNALED (w) || WIFEXITED (w))
6758 && p->infd >= 0)
6759 clear_desc_flag = 1;
6761 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6762 if (clear_desc_flag)
6764 FD_CLR (p->infd, &input_wait_mask);
6765 FD_CLR (p->infd, &non_keyboard_wait_mask);
6768 /* Tell wait_reading_process_output that it needs to wake up and
6769 look around. */
6770 if (input_available_clear_time)
6771 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6774 /* There was no asynchronous process found for that pid: we have
6775 a synchronous process. */
6776 else
6778 synch_process_alive = 0;
6780 /* Report the status of the synchronous process. */
6781 if (WIFEXITED (w))
6782 synch_process_retcode = WRETCODE (w);
6783 else if (WIFSIGNALED (w))
6784 synch_process_termsig = WTERMSIG (w);
6786 /* Tell wait_reading_process_output that it needs to wake up and
6787 look around. */
6788 if (input_available_clear_time)
6789 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6792 sigchld_end_of_loop:
6795 /* On some systems, we must return right away.
6796 If any more processes want to signal us, we will
6797 get another signal.
6798 Otherwise (on systems that have WNOHANG), loop around
6799 to use up all the processes that have something to tell us. */
6800 #if (defined WINDOWSNT \
6801 || (defined USG && !defined GNU_LINUX \
6802 && !(defined HPUX && defined WNOHANG)))
6803 #if defined (USG) && ! defined (POSIX_SIGNALS)
6804 signal (signo, sigchld_handler);
6805 #endif
6806 errno = old_errno;
6807 return;
6808 #endif /* USG, but not HPUX with WNOHANG */
6811 #endif /* SIGCHLD */
6814 static Lisp_Object
6815 exec_sentinel_unwind (data)
6816 Lisp_Object data;
6818 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6819 return Qnil;
6822 static Lisp_Object
6823 exec_sentinel_error_handler (error)
6824 Lisp_Object error;
6826 cmd_error_internal (error, "error in process sentinel: ");
6827 Vinhibit_quit = Qt;
6828 update_echo_area ();
6829 Fsleep_for (make_number (2), Qnil);
6830 return Qt;
6833 static void
6834 exec_sentinel (proc, reason)
6835 Lisp_Object proc, reason;
6837 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6838 register struct Lisp_Process *p = XPROCESS (proc);
6839 int count = SPECPDL_INDEX ();
6840 int outer_running_asynch_code = running_asynch_code;
6841 int waiting = waiting_for_user_input_p;
6843 if (inhibit_sentinels)
6844 return;
6846 /* No need to gcpro these, because all we do with them later
6847 is test them for EQness, and none of them should be a string. */
6848 odeactivate = Vdeactivate_mark;
6849 XSETBUFFER (obuffer, current_buffer);
6850 okeymap = current_buffer->keymap;
6852 sentinel = p->sentinel;
6853 if (NILP (sentinel))
6854 return;
6856 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6857 assure that it gets restored no matter how the sentinel exits. */
6858 p->sentinel = Qnil;
6859 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6860 /* Inhibit quit so that random quits don't screw up a running filter. */
6861 specbind (Qinhibit_quit, Qt);
6862 specbind (Qlast_nonmenu_event, Qt);
6864 /* In case we get recursively called,
6865 and we already saved the match data nonrecursively,
6866 save the same match data in safely recursive fashion. */
6867 if (outer_running_asynch_code)
6869 Lisp_Object tem;
6870 tem = Fmatch_data (Qnil, Qnil, Qnil);
6871 restore_search_regs ();
6872 record_unwind_save_match_data ();
6873 Fset_match_data (tem, Qt);
6876 /* For speed, if a search happens within this code,
6877 save the match data in a special nonrecursive fashion. */
6878 running_asynch_code = 1;
6880 internal_condition_case_1 (read_process_output_call,
6881 Fcons (sentinel,
6882 Fcons (proc, Fcons (reason, Qnil))),
6883 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6884 exec_sentinel_error_handler);
6886 /* If we saved the match data nonrecursively, restore it now. */
6887 restore_search_regs ();
6888 running_asynch_code = outer_running_asynch_code;
6890 Vdeactivate_mark = odeactivate;
6892 /* Restore waiting_for_user_input_p as it was
6893 when we were called, in case the filter clobbered it. */
6894 waiting_for_user_input_p = waiting;
6896 #if 0
6897 if (! EQ (Fcurrent_buffer (), obuffer)
6898 || ! EQ (current_buffer->keymap, okeymap))
6899 #endif
6900 /* But do it only if the caller is actually going to read events.
6901 Otherwise there's no need to make him wake up, and it could
6902 cause trouble (for example it would make sit_for return). */
6903 if (waiting_for_user_input_p == -1)
6904 record_asynch_buffer_change ();
6906 unbind_to (count, Qnil);
6909 /* Report all recent events of a change in process status
6910 (either run the sentinel or output a message).
6911 This is usually done while Emacs is waiting for keyboard input
6912 but can be done at other times. */
6914 static void
6915 status_notify (deleting_process)
6916 struct Lisp_Process *deleting_process;
6918 register Lisp_Object proc, buffer;
6919 Lisp_Object tail, msg;
6920 struct gcpro gcpro1, gcpro2;
6922 tail = Qnil;
6923 msg = Qnil;
6924 /* We need to gcpro tail; if read_process_output calls a filter
6925 which deletes a process and removes the cons to which tail points
6926 from Vprocess_alist, and then causes a GC, tail is an unprotected
6927 reference. */
6928 GCPRO2 (tail, msg);
6930 /* Set this now, so that if new processes are created by sentinels
6931 that we run, we get called again to handle their status changes. */
6932 update_tick = process_tick;
6934 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6936 Lisp_Object symbol;
6937 register struct Lisp_Process *p;
6939 proc = Fcdr (XCAR (tail));
6940 p = XPROCESS (proc);
6942 if (p->tick != p->update_tick)
6944 p->update_tick = p->tick;
6946 /* If process is still active, read any output that remains. */
6947 while (! EQ (p->filter, Qt)
6948 && ! EQ (p->status, Qconnect)
6949 && ! EQ (p->status, Qlisten)
6950 /* Network or serial process not stopped: */
6951 && ! EQ (p->command, Qt)
6952 && p->infd >= 0
6953 && p != deleting_process
6954 && read_process_output (proc, p->infd) > 0);
6956 buffer = p->buffer;
6958 /* Get the text to use for the message. */
6959 if (p->raw_status_new)
6960 update_status (p);
6961 msg = status_message (p);
6963 /* If process is terminated, deactivate it or delete it. */
6964 symbol = p->status;
6965 if (CONSP (p->status))
6966 symbol = XCAR (p->status);
6968 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6969 || EQ (symbol, Qclosed))
6971 if (delete_exited_processes)
6972 remove_process (proc);
6973 else
6974 deactivate_process (proc);
6977 /* The actions above may have further incremented p->tick.
6978 So set p->update_tick again
6979 so that an error in the sentinel will not cause
6980 this code to be run again. */
6981 p->update_tick = p->tick;
6982 /* Now output the message suitably. */
6983 if (!NILP (p->sentinel))
6984 exec_sentinel (proc, msg);
6985 /* Don't bother with a message in the buffer
6986 when a process becomes runnable. */
6987 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6989 Lisp_Object ro, tem;
6990 struct buffer *old = current_buffer;
6991 int opoint, opoint_byte;
6992 int before, before_byte;
6994 ro = XBUFFER (buffer)->read_only;
6996 /* Avoid error if buffer is deleted
6997 (probably that's why the process is dead, too) */
6998 if (NILP (XBUFFER (buffer)->name))
6999 continue;
7000 Fset_buffer (buffer);
7002 opoint = PT;
7003 opoint_byte = PT_BYTE;
7004 /* Insert new output into buffer
7005 at the current end-of-output marker,
7006 thus preserving logical ordering of input and output. */
7007 if (XMARKER (p->mark)->buffer)
7008 Fgoto_char (p->mark);
7009 else
7010 SET_PT_BOTH (ZV, ZV_BYTE);
7012 before = PT;
7013 before_byte = PT_BYTE;
7015 tem = current_buffer->read_only;
7016 current_buffer->read_only = Qnil;
7017 insert_string ("\nProcess ");
7018 Finsert (1, &p->name);
7019 insert_string (" ");
7020 Finsert (1, &msg);
7021 current_buffer->read_only = tem;
7022 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7024 if (opoint >= before)
7025 SET_PT_BOTH (opoint + (PT - before),
7026 opoint_byte + (PT_BYTE - before_byte));
7027 else
7028 SET_PT_BOTH (opoint, opoint_byte);
7030 set_buffer_internal (old);
7033 } /* end for */
7035 update_mode_lines++; /* in case buffers use %s in mode-line-format */
7036 UNGCPRO;
7040 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7041 Sset_process_coding_system, 1, 3, 0,
7042 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7043 DECODING will be used to decode subprocess output and ENCODING to
7044 encode subprocess input. */)
7045 (process, decoding, encoding)
7046 register Lisp_Object process, decoding, encoding;
7048 register struct Lisp_Process *p;
7050 CHECK_PROCESS (process);
7051 p = XPROCESS (process);
7052 if (p->infd < 0)
7053 error ("Input file descriptor of %s closed", SDATA (p->name));
7054 if (p->outfd < 0)
7055 error ("Output file descriptor of %s closed", SDATA (p->name));
7056 Fcheck_coding_system (decoding);
7057 Fcheck_coding_system (encoding);
7058 encoding = coding_inherit_eol_type (encoding, Qnil);
7059 p->decode_coding_system = decoding;
7060 p->encode_coding_system = encoding;
7061 setup_process_coding_systems (process);
7063 return Qnil;
7066 DEFUN ("process-coding-system",
7067 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7068 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7069 (process)
7070 register Lisp_Object process;
7072 CHECK_PROCESS (process);
7073 return Fcons (XPROCESS (process)->decode_coding_system,
7074 XPROCESS (process)->encode_coding_system);
7077 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7078 Sset_process_filter_multibyte, 2, 2, 0,
7079 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7080 If FLAG is non-nil, the filter is given multibyte strings.
7081 If FLAG is nil, the filter is given unibyte strings. In this case,
7082 all character code conversion except for end-of-line conversion is
7083 suppressed. */)
7084 (process, flag)
7085 Lisp_Object process, flag;
7087 register struct Lisp_Process *p;
7089 CHECK_PROCESS (process);
7090 p = XPROCESS (process);
7091 if (NILP (flag))
7092 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
7093 setup_process_coding_systems (process);
7095 return Qnil;
7098 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7099 Sprocess_filter_multibyte_p, 1, 1, 0,
7100 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7101 (process)
7102 Lisp_Object process;
7104 register struct Lisp_Process *p;
7105 struct coding_system *coding;
7107 CHECK_PROCESS (process);
7108 p = XPROCESS (process);
7109 coding = proc_decode_coding_system[p->infd];
7110 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7115 /* Add DESC to the set of keyboard input descriptors. */
7117 void
7118 add_keyboard_wait_descriptor (desc)
7119 int desc;
7121 FD_SET (desc, &input_wait_mask);
7122 FD_SET (desc, &non_process_wait_mask);
7123 if (desc > max_keyboard_desc)
7124 max_keyboard_desc = desc;
7127 static int add_gpm_wait_descriptor_called_flag;
7129 void
7130 add_gpm_wait_descriptor (desc)
7131 int desc;
7133 if (! add_gpm_wait_descriptor_called_flag)
7134 FD_CLR (0, &input_wait_mask);
7135 add_gpm_wait_descriptor_called_flag = 1;
7136 FD_SET (desc, &input_wait_mask);
7137 FD_SET (desc, &gpm_wait_mask);
7138 if (desc > max_gpm_desc)
7139 max_gpm_desc = desc;
7142 /* From now on, do not expect DESC to give keyboard input. */
7144 void
7145 delete_keyboard_wait_descriptor (desc)
7146 int desc;
7148 int fd;
7149 int lim = max_keyboard_desc;
7151 FD_CLR (desc, &input_wait_mask);
7152 FD_CLR (desc, &non_process_wait_mask);
7154 if (desc == max_keyboard_desc)
7155 for (fd = 0; fd < lim; fd++)
7156 if (FD_ISSET (fd, &input_wait_mask)
7157 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7158 && !FD_ISSET (fd, &gpm_wait_mask))
7159 max_keyboard_desc = fd;
7162 void
7163 delete_gpm_wait_descriptor (desc)
7164 int desc;
7166 int fd;
7167 int lim = max_gpm_desc;
7169 FD_CLR (desc, &input_wait_mask);
7170 FD_CLR (desc, &non_process_wait_mask);
7172 if (desc == max_gpm_desc)
7173 for (fd = 0; fd < lim; fd++)
7174 if (FD_ISSET (fd, &input_wait_mask)
7175 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7176 && !FD_ISSET (fd, &non_process_wait_mask))
7177 max_gpm_desc = fd;
7180 /* Return nonzero if *MASK has a bit set
7181 that corresponds to one of the keyboard input descriptors. */
7183 static int
7184 keyboard_bit_set (mask)
7185 SELECT_TYPE *mask;
7187 int fd;
7189 for (fd = 0; fd <= max_keyboard_desc; fd++)
7190 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7191 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7192 return 1;
7194 return 0;
7197 /* Enumeration of and access to system processes a-la ps(1). */
7199 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7200 0, 0, 0,
7201 doc: /* Return a list of numerical process IDs of all running processes.
7202 If this functionality is unsupported, return nil.
7204 See `process-attributes' for getting attributes of a process given its ID. */)
7207 return list_system_processes ();
7210 DEFUN ("process-attributes", Fprocess_attributes,
7211 Sprocess_attributes, 1, 1, 0,
7212 doc: /* Return attributes of the process given by its PID, a number.
7214 Value is an alist where each element is a cons cell of the form
7216 \(KEY . VALUE)
7218 If this functionality is unsupported, the value is nil.
7220 See `list-system-processes' for getting a list of all process IDs.
7222 The KEYs of the attributes that this function may return are listed
7223 below, together with the type of the associated VALUE (in parentheses).
7224 Not all platforms support all of these attributes; unsupported
7225 attributes will not appear in the returned alist.
7226 Unless explicitly indicated otherwise, numbers can have either
7227 integer or floating point values.
7229 euid -- Effective user User ID of the process (number)
7230 user -- User name corresponding to euid (string)
7231 egid -- Effective user Group ID of the process (number)
7232 group -- Group name corresponding to egid (string)
7233 comm -- Command name (executable name only) (string)
7234 state -- Process state code, such as "S", "R", or "T" (string)
7235 ppid -- Parent process ID (number)
7236 pgrp -- Process group ID (number)
7237 sess -- Session ID, i.e. process ID of session leader (number)
7238 ttname -- Controlling tty name (string)
7239 tpgid -- ID of foreground process group on the process's tty (number)
7240 minflt -- number of minor page faults (number)
7241 majflt -- number of major page faults (number)
7242 cminflt -- cumulative number of minor page faults (number)
7243 cmajflt -- cumulative number of major page faults (number)
7244 utime -- user time used by the process, in the (HIGH LOW USEC) format
7245 stime -- system time used by the process, in the (HIGH LOW USEC) format
7246 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7247 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7248 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7249 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7250 pri -- priority of the process (number)
7251 nice -- nice value of the process (number)
7252 thcount -- process thread count (number)
7253 start -- time the process started, in the (HIGH LOW USEC) format
7254 vsize -- virtual memory size of the process in KB's (number)
7255 rss -- resident set size of the process in KB's (number)
7256 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7257 pcpu -- percents of CPU time used by the process (floating-point number)
7258 pmem -- percents of total physical memory used by process's resident set
7259 (floating-point number)
7260 args -- command line which invoked the process (string). */)
7261 (pid)
7263 Lisp_Object pid;
7265 return system_process_attributes (pid);
7268 void
7269 init_process ()
7271 register int i;
7273 inhibit_sentinels = 0;
7275 #ifdef SIGCHLD
7276 #ifndef CANNOT_DUMP
7277 if (! noninteractive || initialized)
7278 #endif
7279 signal (SIGCHLD, sigchld_handler);
7280 #endif
7282 FD_ZERO (&input_wait_mask);
7283 FD_ZERO (&non_keyboard_wait_mask);
7284 FD_ZERO (&non_process_wait_mask);
7285 max_process_desc = 0;
7287 #ifdef NON_BLOCKING_CONNECT
7288 FD_ZERO (&connect_wait_mask);
7289 num_pending_connects = 0;
7290 #endif
7292 #ifdef ADAPTIVE_READ_BUFFERING
7293 process_output_delay_count = 0;
7294 process_output_skip = 0;
7295 #endif
7297 /* Don't do this, it caused infinite select loops. The display
7298 method should call add_keyboard_wait_descriptor on stdin if it
7299 needs that. */
7300 #if 0
7301 FD_SET (0, &input_wait_mask);
7302 #endif
7304 Vprocess_alist = Qnil;
7305 #ifdef SIGCHLD
7306 deleted_pid_list = Qnil;
7307 #endif
7308 for (i = 0; i < MAXDESC; i++)
7310 chan_process[i] = Qnil;
7311 proc_buffered_char[i] = -1;
7313 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7314 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7315 #ifdef DATAGRAM_SOCKETS
7316 bzero (datagram_address, sizeof datagram_address);
7317 #endif
7319 #ifdef HAVE_SOCKETS
7321 Lisp_Object subfeatures = Qnil;
7322 const struct socket_options *sopt;
7324 #define ADD_SUBFEATURE(key, val) \
7325 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7327 #ifdef NON_BLOCKING_CONNECT
7328 ADD_SUBFEATURE (QCnowait, Qt);
7329 #endif
7330 #ifdef DATAGRAM_SOCKETS
7331 ADD_SUBFEATURE (QCtype, Qdatagram);
7332 #endif
7333 #ifdef HAVE_LOCAL_SOCKETS
7334 ADD_SUBFEATURE (QCfamily, Qlocal);
7335 #endif
7336 ADD_SUBFEATURE (QCfamily, Qipv4);
7337 #ifdef AF_INET6
7338 ADD_SUBFEATURE (QCfamily, Qipv6);
7339 #endif
7340 #ifdef HAVE_GETSOCKNAME
7341 ADD_SUBFEATURE (QCservice, Qt);
7342 #endif
7343 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7344 ADD_SUBFEATURE (QCserver, Qt);
7345 #endif
7347 for (sopt = socket_options; sopt->name; sopt++)
7348 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7350 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7352 #endif /* HAVE_SOCKETS */
7354 #if defined (DARWIN_OS)
7355 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7356 processes. As such, we only change the default value. */
7357 if (initialized)
7359 char *release = get_operating_system_release();
7360 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7361 && release[1] == '.')) {
7362 Vprocess_connection_type = Qnil;
7365 #endif
7368 void
7369 syms_of_process ()
7371 Qprocessp = intern_c_string ("processp");
7372 staticpro (&Qprocessp);
7373 Qrun = intern_c_string ("run");
7374 staticpro (&Qrun);
7375 Qstop = intern_c_string ("stop");
7376 staticpro (&Qstop);
7377 Qsignal = intern_c_string ("signal");
7378 staticpro (&Qsignal);
7380 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7381 here again.
7383 Qexit = intern_c_string ("exit");
7384 staticpro (&Qexit); */
7386 Qopen = intern_c_string ("open");
7387 staticpro (&Qopen);
7388 Qclosed = intern_c_string ("closed");
7389 staticpro (&Qclosed);
7390 Qconnect = intern_c_string ("connect");
7391 staticpro (&Qconnect);
7392 Qfailed = intern_c_string ("failed");
7393 staticpro (&Qfailed);
7394 Qlisten = intern_c_string ("listen");
7395 staticpro (&Qlisten);
7396 Qlocal = intern_c_string ("local");
7397 staticpro (&Qlocal);
7398 Qipv4 = intern_c_string ("ipv4");
7399 staticpro (&Qipv4);
7400 #ifdef AF_INET6
7401 Qipv6 = intern_c_string ("ipv6");
7402 staticpro (&Qipv6);
7403 #endif
7404 Qdatagram = intern_c_string ("datagram");
7405 staticpro (&Qdatagram);
7407 QCport = intern_c_string (":port");
7408 staticpro (&QCport);
7409 QCspeed = intern_c_string (":speed");
7410 staticpro (&QCspeed);
7411 QCprocess = intern_c_string (":process");
7412 staticpro (&QCprocess);
7414 QCbytesize = intern_c_string (":bytesize");
7415 staticpro (&QCbytesize);
7416 QCstopbits = intern_c_string (":stopbits");
7417 staticpro (&QCstopbits);
7418 QCparity = intern_c_string (":parity");
7419 staticpro (&QCparity);
7420 Qodd = intern_c_string ("odd");
7421 staticpro (&Qodd);
7422 Qeven = intern_c_string ("even");
7423 staticpro (&Qeven);
7424 QCflowcontrol = intern_c_string (":flowcontrol");
7425 staticpro (&QCflowcontrol);
7426 Qhw = intern_c_string ("hw");
7427 staticpro (&Qhw);
7428 Qsw = intern_c_string ("sw");
7429 staticpro (&Qsw);
7430 QCsummary = intern_c_string (":summary");
7431 staticpro (&QCsummary);
7433 Qreal = intern_c_string ("real");
7434 staticpro (&Qreal);
7435 Qnetwork = intern_c_string ("network");
7436 staticpro (&Qnetwork);
7437 Qserial = intern_c_string ("serial");
7438 staticpro (&Qserial);
7440 QCname = intern_c_string (":name");
7441 staticpro (&QCname);
7442 QCbuffer = intern_c_string (":buffer");
7443 staticpro (&QCbuffer);
7444 QChost = intern_c_string (":host");
7445 staticpro (&QChost);
7446 QCservice = intern_c_string (":service");
7447 staticpro (&QCservice);
7448 QCtype = intern_c_string (":type");
7449 staticpro (&QCtype);
7450 QClocal = intern_c_string (":local");
7451 staticpro (&QClocal);
7452 QCremote = intern_c_string (":remote");
7453 staticpro (&QCremote);
7454 QCcoding = intern_c_string (":coding");
7455 staticpro (&QCcoding);
7456 QCserver = intern_c_string (":server");
7457 staticpro (&QCserver);
7458 QCnowait = intern_c_string (":nowait");
7459 staticpro (&QCnowait);
7460 QCsentinel = intern_c_string (":sentinel");
7461 staticpro (&QCsentinel);
7462 QClog = intern_c_string (":log");
7463 staticpro (&QClog);
7464 QCnoquery = intern_c_string (":noquery");
7465 staticpro (&QCnoquery);
7466 QCstop = intern_c_string (":stop");
7467 staticpro (&QCstop);
7468 QCoptions = intern_c_string (":options");
7469 staticpro (&QCoptions);
7470 QCplist = intern_c_string (":plist");
7471 staticpro (&QCplist);
7473 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7474 staticpro (&Qlast_nonmenu_event);
7476 staticpro (&Vprocess_alist);
7477 #ifdef SIGCHLD
7478 staticpro (&deleted_pid_list);
7479 #endif
7481 Qeuid = intern_c_string ("euid");
7482 staticpro (&Qeuid);
7483 Qegid = intern_c_string ("egid");
7484 staticpro (&Qegid);
7485 Quser = intern_c_string ("user");
7486 staticpro (&Quser);
7487 Qgroup = intern_c_string ("group");
7488 staticpro (&Qgroup);
7489 Qcomm = intern_c_string ("comm");
7490 staticpro (&Qcomm);
7491 Qstate = intern_c_string ("state");
7492 staticpro (&Qstate);
7493 Qppid = intern_c_string ("ppid");
7494 staticpro (&Qppid);
7495 Qpgrp = intern_c_string ("pgrp");
7496 staticpro (&Qpgrp);
7497 Qsess = intern_c_string ("sess");
7498 staticpro (&Qsess);
7499 Qttname = intern_c_string ("ttname");
7500 staticpro (&Qttname);
7501 Qtpgid = intern_c_string ("tpgid");
7502 staticpro (&Qtpgid);
7503 Qminflt = intern_c_string ("minflt");
7504 staticpro (&Qminflt);
7505 Qmajflt = intern_c_string ("majflt");
7506 staticpro (&Qmajflt);
7507 Qcminflt = intern_c_string ("cminflt");
7508 staticpro (&Qcminflt);
7509 Qcmajflt = intern_c_string ("cmajflt");
7510 staticpro (&Qcmajflt);
7511 Qutime = intern_c_string ("utime");
7512 staticpro (&Qutime);
7513 Qstime = intern_c_string ("stime");
7514 staticpro (&Qstime);
7515 Qtime = intern_c_string ("time");
7516 staticpro (&Qtime);
7517 Qcutime = intern_c_string ("cutime");
7518 staticpro (&Qcutime);
7519 Qcstime = intern_c_string ("cstime");
7520 staticpro (&Qcstime);
7521 Qctime = intern_c_string ("ctime");
7522 staticpro (&Qctime);
7523 Qpri = intern_c_string ("pri");
7524 staticpro (&Qpri);
7525 Qnice = intern_c_string ("nice");
7526 staticpro (&Qnice);
7527 Qthcount = intern_c_string ("thcount");
7528 staticpro (&Qthcount);
7529 Qstart = intern_c_string ("start");
7530 staticpro (&Qstart);
7531 Qvsize = intern_c_string ("vsize");
7532 staticpro (&Qvsize);
7533 Qrss = intern_c_string ("rss");
7534 staticpro (&Qrss);
7535 Qetime = intern_c_string ("etime");
7536 staticpro (&Qetime);
7537 Qpcpu = intern_c_string ("pcpu");
7538 staticpro (&Qpcpu);
7539 Qpmem = intern_c_string ("pmem");
7540 staticpro (&Qpmem);
7541 Qargs = intern_c_string ("args");
7542 staticpro (&Qargs);
7544 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7545 doc: /* *Non-nil means delete processes immediately when they exit.
7546 A value of nil means don't delete them until `list-processes' is run. */);
7548 delete_exited_processes = 1;
7550 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7551 doc: /* Control type of device used to communicate with subprocesses.
7552 Values are nil to use a pipe, or t or `pty' to use a pty.
7553 The value has no effect if the system has no ptys or if all ptys are busy:
7554 then a pipe is used in any case.
7555 The value takes effect when `start-process' is called. */);
7556 Vprocess_connection_type = Qt;
7558 #ifdef ADAPTIVE_READ_BUFFERING
7559 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7560 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7561 On some systems, when Emacs reads the output from a subprocess, the output data
7562 is read in very small blocks, potentially resulting in very poor performance.
7563 This behavior can be remedied to some extent by setting this variable to a
7564 non-nil value, as it will automatically delay reading from such processes, to
7565 allow them to produce more output before Emacs tries to read it.
7566 If the value is t, the delay is reset after each write to the process; any other
7567 non-nil value means that the delay is not reset on write.
7568 The variable takes effect when `start-process' is called. */);
7569 Vprocess_adaptive_read_buffering = Qt;
7570 #endif
7572 defsubr (&Sprocessp);
7573 defsubr (&Sget_process);
7574 defsubr (&Sget_buffer_process);
7575 defsubr (&Sdelete_process);
7576 defsubr (&Sprocess_status);
7577 defsubr (&Sprocess_exit_status);
7578 defsubr (&Sprocess_id);
7579 defsubr (&Sprocess_name);
7580 defsubr (&Sprocess_tty_name);
7581 defsubr (&Sprocess_command);
7582 defsubr (&Sset_process_buffer);
7583 defsubr (&Sprocess_buffer);
7584 defsubr (&Sprocess_mark);
7585 defsubr (&Sset_process_filter);
7586 defsubr (&Sprocess_filter);
7587 defsubr (&Sset_process_sentinel);
7588 defsubr (&Sprocess_sentinel);
7589 defsubr (&Sset_process_window_size);
7590 defsubr (&Sset_process_inherit_coding_system_flag);
7591 defsubr (&Sprocess_inherit_coding_system_flag);
7592 defsubr (&Sset_process_query_on_exit_flag);
7593 defsubr (&Sprocess_query_on_exit_flag);
7594 defsubr (&Sprocess_contact);
7595 defsubr (&Sprocess_plist);
7596 defsubr (&Sset_process_plist);
7597 defsubr (&Slist_processes);
7598 defsubr (&Sprocess_list);
7599 defsubr (&Sstart_process);
7600 #ifdef HAVE_SERIAL
7601 defsubr (&Sserial_process_configure);
7602 defsubr (&Smake_serial_process);
7603 #endif /* HAVE_SERIAL */
7604 #ifdef HAVE_SOCKETS
7605 defsubr (&Sset_network_process_option);
7606 defsubr (&Smake_network_process);
7607 defsubr (&Sformat_network_address);
7608 #endif /* HAVE_SOCKETS */
7609 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7610 #ifdef SIOCGIFCONF
7611 defsubr (&Snetwork_interface_list);
7612 #endif
7613 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7614 defsubr (&Snetwork_interface_info);
7615 #endif
7616 #endif /* HAVE_SOCKETS ... */
7617 #ifdef DATAGRAM_SOCKETS
7618 defsubr (&Sprocess_datagram_address);
7619 defsubr (&Sset_process_datagram_address);
7620 #endif
7621 defsubr (&Saccept_process_output);
7622 defsubr (&Sprocess_send_region);
7623 defsubr (&Sprocess_send_string);
7624 defsubr (&Sinterrupt_process);
7625 defsubr (&Skill_process);
7626 defsubr (&Squit_process);
7627 defsubr (&Sstop_process);
7628 defsubr (&Scontinue_process);
7629 defsubr (&Sprocess_running_child_p);
7630 defsubr (&Sprocess_send_eof);
7631 defsubr (&Ssignal_process);
7632 defsubr (&Swaiting_for_user_input_p);
7633 defsubr (&Sprocess_type);
7634 defsubr (&Sset_process_coding_system);
7635 defsubr (&Sprocess_coding_system);
7636 defsubr (&Sset_process_filter_multibyte);
7637 defsubr (&Sprocess_filter_multibyte_p);
7638 defsubr (&Slist_system_processes);
7639 defsubr (&Sprocess_attributes);
7643 #else /* not subprocesses */
7645 #include <sys/types.h>
7646 #include <errno.h>
7647 #include <sys/stat.h>
7648 #include <stdlib.h>
7649 #include <fcntl.h>
7650 #include <setjmp.h>
7651 #ifdef HAVE_UNISTD_H
7652 #include <unistd.h>
7653 #endif
7655 #include "lisp.h"
7656 #include "systime.h"
7657 #include "character.h"
7658 #include "coding.h"
7659 #include "termopts.h"
7660 #include "sysselect.h"
7662 extern int frame_garbaged;
7664 extern EMACS_TIME timer_check ();
7665 extern int timers_run;
7667 Lisp_Object QCtype, QCname;
7669 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7670 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7671 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7672 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7674 /* As described above, except assuming that there are no subprocesses:
7676 Wait for timeout to elapse and/or keyboard input to be available.
7678 time_limit is:
7679 timeout in seconds, or
7680 zero for no limit, or
7681 -1 means gobble data immediately available but don't wait for any.
7683 read_kbd is a Lisp_Object:
7684 0 to ignore keyboard input, or
7685 1 to return when input is available, or
7686 -1 means caller will actually read the input, so don't throw to
7687 the quit handler.
7689 see full version for other parameters. We know that wait_proc will
7690 always be NULL, since `subprocesses' isn't defined.
7692 do_display != 0 means redisplay should be done to show subprocess
7693 output that arrives.
7695 Return true if we received input from any process. */
7698 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7699 wait_for_cell, wait_proc, just_wait_proc)
7700 int time_limit, microsecs, read_kbd, do_display;
7701 Lisp_Object wait_for_cell;
7702 struct Lisp_Process *wait_proc;
7703 int just_wait_proc;
7705 register int nfds;
7706 EMACS_TIME end_time, timeout;
7707 SELECT_TYPE waitchannels;
7708 int xerrno;
7710 /* What does time_limit really mean? */
7711 if (time_limit || microsecs)
7713 EMACS_GET_TIME (end_time);
7714 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7715 EMACS_ADD_TIME (end_time, end_time, timeout);
7718 /* Turn off periodic alarms (in case they are in use)
7719 and then turn off any other atimers,
7720 because the select emulator uses alarms. */
7721 stop_polling ();
7722 turn_on_atimers (0);
7724 while (1)
7726 int timeout_reduced_for_timers = 0;
7728 /* If calling from keyboard input, do not quit
7729 since we want to return C-g as an input character.
7730 Otherwise, do pending quit if requested. */
7731 if (read_kbd >= 0)
7732 QUIT;
7734 /* Exit now if the cell we're waiting for became non-nil. */
7735 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7736 break;
7738 /* Compute time from now till when time limit is up */
7739 /* Exit if already run out */
7740 if (time_limit == -1)
7742 /* -1 specified for timeout means
7743 gobble output available now
7744 but don't wait at all. */
7746 EMACS_SET_SECS_USECS (timeout, 0, 0);
7748 else if (time_limit || microsecs)
7750 EMACS_GET_TIME (timeout);
7751 EMACS_SUB_TIME (timeout, end_time, timeout);
7752 if (EMACS_TIME_NEG_P (timeout))
7753 break;
7755 else
7757 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7760 /* If our caller will not immediately handle keyboard events,
7761 run timer events directly.
7762 (Callers that will immediately read keyboard events
7763 call timer_delay on their own.) */
7764 if (NILP (wait_for_cell))
7766 EMACS_TIME timer_delay;
7770 int old_timers_run = timers_run;
7771 timer_delay = timer_check (1);
7772 if (timers_run != old_timers_run && do_display)
7773 /* We must retry, since a timer may have requeued itself
7774 and that could alter the time delay. */
7775 redisplay_preserve_echo_area (14);
7776 else
7777 break;
7779 while (!detect_input_pending ());
7781 /* If there is unread keyboard input, also return. */
7782 if (read_kbd != 0
7783 && requeued_events_pending_p ())
7784 break;
7786 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7788 EMACS_TIME difference;
7789 EMACS_SUB_TIME (difference, timer_delay, timeout);
7790 if (EMACS_TIME_NEG_P (difference))
7792 timeout = timer_delay;
7793 timeout_reduced_for_timers = 1;
7798 /* Cause C-g and alarm signals to take immediate action,
7799 and cause input available signals to zero out timeout. */
7800 if (read_kbd < 0)
7801 set_waiting_for_input (&timeout);
7803 /* Wait till there is something to do. */
7805 if (! read_kbd && NILP (wait_for_cell))
7806 FD_ZERO (&waitchannels);
7807 else
7808 FD_SET (0, &waitchannels);
7810 /* If a frame has been newly mapped and needs updating,
7811 reprocess its display stuff. */
7812 if (frame_garbaged && do_display)
7814 clear_waiting_for_input ();
7815 redisplay_preserve_echo_area (15);
7816 if (read_kbd < 0)
7817 set_waiting_for_input (&timeout);
7820 if (read_kbd && detect_input_pending ())
7822 nfds = 0;
7823 FD_ZERO (&waitchannels);
7825 else
7826 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7827 &timeout);
7829 xerrno = errno;
7831 /* Make C-g and alarm signals set flags again */
7832 clear_waiting_for_input ();
7834 /* If we woke up due to SIGWINCH, actually change size now. */
7835 do_pending_window_change (0);
7837 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7838 /* We waited the full specified time, so return now. */
7839 break;
7841 if (nfds == -1)
7843 /* If the system call was interrupted, then go around the
7844 loop again. */
7845 if (xerrno == EINTR)
7846 FD_ZERO (&waitchannels);
7847 else
7848 error ("select error: %s", emacs_strerror (xerrno));
7850 #ifdef SOLARIS2
7851 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7852 /* System sometimes fails to deliver SIGIO. */
7853 kill (getpid (), SIGIO);
7854 #endif
7855 #ifdef SIGIO
7856 if (read_kbd && interrupt_input && (waitchannels & 1))
7857 kill (getpid (), SIGIO);
7858 #endif
7860 /* Check for keyboard input */
7862 if (read_kbd
7863 && detect_input_pending_run_timers (do_display))
7865 swallow_events (do_display);
7866 if (detect_input_pending_run_timers (do_display))
7867 break;
7870 /* If there is unread keyboard input, also return. */
7871 if (read_kbd
7872 && requeued_events_pending_p ())
7873 break;
7875 /* If wait_for_cell. check for keyboard input
7876 but don't run any timers.
7877 ??? (It seems wrong to me to check for keyboard
7878 input at all when wait_for_cell, but the code
7879 has been this way since July 1994.
7880 Try changing this after version 19.31.) */
7881 if (! NILP (wait_for_cell)
7882 && detect_input_pending ())
7884 swallow_events (do_display);
7885 if (detect_input_pending ())
7886 break;
7889 /* Exit now if the cell we're waiting for became non-nil. */
7890 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7891 break;
7894 start_polling ();
7896 return 0;
7900 /* Don't confuse make-docfile by having two doc strings for this function.
7901 make-docfile does not pay attention to #if, for good reason! */
7902 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7904 (name)
7905 register Lisp_Object name;
7907 return Qnil;
7910 /* Don't confuse make-docfile by having two doc strings for this function.
7911 make-docfile does not pay attention to #if, for good reason! */
7912 DEFUN ("process-inherit-coding-system-flag",
7913 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7914 1, 1, 0,
7916 (process)
7917 register Lisp_Object process;
7919 /* Ignore the argument and return the value of
7920 inherit-process-coding-system. */
7921 return inherit_process_coding_system ? Qt : Qnil;
7924 /* Kill all processes associated with `buffer'.
7925 If `buffer' is nil, kill all processes.
7926 Since we have no subprocesses, this does nothing. */
7928 void
7929 kill_buffer_processes (buffer)
7930 Lisp_Object buffer;
7934 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7935 0, 0, 0,
7936 doc: /* Return a list of numerical process IDs of all running processes.
7937 If this functionality is unsupported, return nil.
7939 See `process-attributes' for getting attributes of a process given its ID. */)
7942 return list_system_processes ();
7945 DEFUN ("process-attributes", Fprocess_attributes,
7946 Sprocess_attributes, 1, 1, 0,
7947 doc: /* Return attributes of the process given by its PID, a number.
7949 Value is an alist where each element is a cons cell of the form
7951 \(KEY . VALUE)
7953 If this functionality is unsupported, the value is nil.
7955 See `list-system-processes' for getting a list of all process IDs.
7957 The KEYs of the attributes that this function may return are listed
7958 below, together with the type of the associated VALUE (in parentheses).
7959 Not all platforms support all of these attributes; unsupported
7960 attributes will not appear in the returned alist.
7961 Unless explicitly indicated otherwise, numbers can have either
7962 integer or floating point values.
7964 euid -- Effective user User ID of the process (number)
7965 user -- User name corresponding to euid (string)
7966 egid -- Effective user Group ID of the process (number)
7967 group -- Group name corresponding to egid (string)
7968 comm -- Command name (executable name only) (string)
7969 state -- Process state code, such as "S", "R", or "T" (string)
7970 ppid -- Parent process ID (number)
7971 pgrp -- Process group ID (number)
7972 sess -- Session ID, i.e. process ID of session leader (number)
7973 ttname -- Controlling tty name (string)
7974 tpgid -- ID of foreground process group on the process's tty (number)
7975 minflt -- number of minor page faults (number)
7976 majflt -- number of major page faults (number)
7977 cminflt -- cumulative number of minor page faults (number)
7978 cmajflt -- cumulative number of major page faults (number)
7979 utime -- user time used by the process, in the (HIGH LOW USEC) format
7980 stime -- system time used by the process, in the (HIGH LOW USEC) format
7981 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7982 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7983 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7984 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7985 pri -- priority of the process (number)
7986 nice -- nice value of the process (number)
7987 thcount -- process thread count (number)
7988 start -- time the process started, in the (HIGH LOW USEC) format
7989 vsize -- virtual memory size of the process in KB's (number)
7990 rss -- resident set size of the process in KB's (number)
7991 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7992 pcpu -- percents of CPU time used by the process (floating-point number)
7993 pmem -- percents of total physical memory used by process's resident set
7994 (floating-point number)
7995 args -- command line which invoked the process (string). */)
7996 (pid)
7998 Lisp_Object pid;
8000 return system_process_attributes (pid);
8003 void
8004 init_process ()
8008 void
8009 syms_of_process ()
8011 QCtype = intern_c_string (":type");
8012 staticpro (&QCtype);
8013 QCname = intern_c_string (":name");
8014 staticpro (&QCname);
8015 QCtype = intern_c_string (":type");
8016 staticpro (&QCtype);
8017 QCname = intern_c_string (":name");
8018 staticpro (&QCname);
8019 Qeuid = intern_c_string ("euid");
8020 staticpro (&Qeuid);
8021 Qegid = intern_c_string ("egid");
8022 staticpro (&Qegid);
8023 Quser = intern_c_string ("user");
8024 staticpro (&Quser);
8025 Qgroup = intern_c_string ("group");
8026 staticpro (&Qgroup);
8027 Qcomm = intern_c_string ("comm");
8028 staticpro (&Qcomm);
8029 Qstate = intern_c_string ("state");
8030 staticpro (&Qstate);
8031 Qppid = intern_c_string ("ppid");
8032 staticpro (&Qppid);
8033 Qpgrp = intern_c_string ("pgrp");
8034 staticpro (&Qpgrp);
8035 Qsess = intern_c_string ("sess");
8036 staticpro (&Qsess);
8037 Qttname = intern_c_string ("ttname");
8038 staticpro (&Qttname);
8039 Qtpgid = intern_c_string ("tpgid");
8040 staticpro (&Qtpgid);
8041 Qminflt = intern_c_string ("minflt");
8042 staticpro (&Qminflt);
8043 Qmajflt = intern_c_string ("majflt");
8044 staticpro (&Qmajflt);
8045 Qcminflt = intern_c_string ("cminflt");
8046 staticpro (&Qcminflt);
8047 Qcmajflt = intern_c_string ("cmajflt");
8048 staticpro (&Qcmajflt);
8049 Qutime = intern_c_string ("utime");
8050 staticpro (&Qutime);
8051 Qstime = intern_c_string ("stime");
8052 staticpro (&Qstime);
8053 Qtime = intern_c_string ("time");
8054 staticpro (&Qtime);
8055 Qcutime = intern_c_string ("cutime");
8056 staticpro (&Qcutime);
8057 Qcstime = intern_c_string ("cstime");
8058 staticpro (&Qcstime);
8059 Qctime = intern_c_string ("ctime");
8060 staticpro (&Qctime);
8061 Qpri = intern_c_string ("pri");
8062 staticpro (&Qpri);
8063 Qnice = intern_c_string ("nice");
8064 staticpro (&Qnice);
8065 Qthcount = intern_c_string ("thcount");
8066 staticpro (&Qthcount);
8067 Qstart = intern_c_string ("start");
8068 staticpro (&Qstart);
8069 Qvsize = intern_c_string ("vsize");
8070 staticpro (&Qvsize);
8071 Qrss = intern_c_string ("rss");
8072 staticpro (&Qrss);
8073 Qetime = intern_c_string ("etime");
8074 staticpro (&Qetime);
8075 Qpcpu = intern_c_string ("pcpu");
8076 staticpro (&Qpcpu);
8077 Qpmem = intern_c_string ("pmem");
8078 staticpro (&Qpmem);
8079 Qargs = intern_c_string ("args");
8080 staticpro (&Qargs);
8082 defsubr (&Sget_buffer_process);
8083 defsubr (&Sprocess_inherit_coding_system_flag);
8084 defsubr (&Slist_system_processes);
8085 defsubr (&Sprocess_attributes);
8089 #endif /* not subprocesses */
8091 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
8092 (do not change this comment) */