Convert DEFUNs to standard C.
[emacs.git] / src / process.c
blob1eefae1adc910421fb270425a58b8e8dea261c0c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <signal.h>
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
33 #ifdef subprocesses
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #include <setjmp.h>
42 #ifdef HAVE_INTTYPES_H
43 #include <inttypes.h>
44 #endif
45 #ifdef STDC_HEADERS
46 #include <stdlib.h>
47 #endif
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52 #include <fcntl.h>
54 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
60 /* Are local (unix) sockets supported? */
61 #if defined (HAVE_SYS_UN_H)
62 #if !defined (AF_LOCAL) && defined (AF_UNIX)
63 #define AF_LOCAL AF_UNIX
64 #endif
65 #ifdef AF_LOCAL
66 #define HAVE_LOCAL_SOCKETS
67 #include <sys/un.h>
68 #endif
69 #endif
70 #endif /* HAVE_SOCKETS */
72 #if defined(HAVE_SYS_IOCTL_H)
73 #include <sys/ioctl.h>
74 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
75 #include <fcntl.h>
76 #endif /* HAVE_PTYS and no O_NDELAY */
77 #endif /* HAVE_SYS_IOCTL_H */
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
83 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
84 #ifdef HAVE_SOCKETS
85 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
86 /* sys/ioctl.h may have been included already */
87 #ifndef SIOCGIFADDR
88 #include <sys/ioctl.h>
89 #endif
90 #include <net/if.h>
91 #endif
92 #endif
94 #ifdef HAVE_SYS_WAIT
95 #include <sys/wait.h>
96 #endif
98 #ifdef HAVE_RES_INIT
99 #include <netinet/in.h>
100 #include <arpa/nameser.h>
101 #include <resolv.h>
102 #endif
104 #include "lisp.h"
105 #include "systime.h"
106 #include "systty.h"
108 #include "window.h"
109 #include "buffer.h"
110 #include "character.h"
111 #include "coding.h"
112 #include "process.h"
113 #include "frame.h"
114 #include "termhooks.h"
115 #include "termopts.h"
116 #include "commands.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "dispextern.h"
120 #include "composite.h"
121 #include "atimer.h"
123 #if defined (USE_GTK) || defined (HAVE_GCONF)
124 #include "xgselect.h"
125 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
127 Lisp_Object Qprocessp;
128 Lisp_Object Qrun, Qstop, Qsignal;
129 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
130 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
131 Lisp_Object Qreal, Qnetwork, Qserial;
132 #ifdef AF_INET6
133 Lisp_Object Qipv6;
134 #endif
135 Lisp_Object QCport, QCspeed, QCprocess;
136 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
137 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
138 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
139 Lisp_Object QClocal, QCremote, QCcoding;
140 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
141 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
142 Lisp_Object Qlast_nonmenu_event;
143 /* QCfamily is declared and initialized in xfaces.c,
144 QCfilter in keyboard.c. */
145 extern Lisp_Object QCfamily, QCfilter;
147 /* Qexit is declared and initialized in eval.c. */
149 /* QCfamily is defined in xfaces.c. */
150 extern Lisp_Object QCfamily;
151 /* QCfilter is defined in keyboard.c. */
152 extern Lisp_Object QCfilter;
154 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
155 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
156 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
157 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
159 #ifdef HAVE_SOCKETS
160 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
161 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
162 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
163 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
164 #else
165 #define NETCONN_P(p) 0
166 #define NETCONN1_P(p) 0
167 #define SERIALCONN_P(p) 0
168 #define SERIALCONN1_P(p) 0
169 #endif /* HAVE_SOCKETS */
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
174 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
175 testing SIGCHLD. */
177 #if !defined (SIGCHLD) && defined (SIGCLD)
178 #define SIGCHLD SIGCLD
179 #endif /* SIGCLD */
181 #include "syssignal.h"
183 #include "syswait.h"
185 extern char *get_operating_system_release (void);
187 /* Serial processes require termios or Windows. */
188 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
189 #define HAVE_SERIAL
190 #endif
192 #ifdef HAVE_SERIAL
193 /* From sysdep.c or w32.c */
194 extern int serial_open (char *port);
195 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
196 #endif
198 #ifndef HAVE_H_ERRNO
199 extern int h_errno;
200 #endif
202 /* t means use pty, nil means use a pipe,
203 maybe other values to come. */
204 static Lisp_Object Vprocess_connection_type;
206 /* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
208 /* Number of events of change of status of a process. */
209 int process_tick;
210 /* Number of events for which the user or sentinel has been notified. */
211 int update_tick;
213 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
215 #ifdef BROKEN_NON_BLOCKING_CONNECT
216 #undef NON_BLOCKING_CONNECT
217 #else
218 #ifndef NON_BLOCKING_CONNECT
219 #ifdef HAVE_SOCKETS
220 #ifdef HAVE_SELECT
221 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
222 #if defined (O_NONBLOCK) || defined (O_NDELAY)
223 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
224 #define NON_BLOCKING_CONNECT
225 #endif /* EWOULDBLOCK || EINPROGRESS */
226 #endif /* O_NONBLOCK || O_NDELAY */
227 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
228 #endif /* HAVE_SELECT */
229 #endif /* HAVE_SOCKETS */
230 #endif /* NON_BLOCKING_CONNECT */
231 #endif /* BROKEN_NON_BLOCKING_CONNECT */
233 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
234 this system. We need to read full packets, so we need a
235 "non-destructive" select. So we require either native select,
236 or emulation of select using FIONREAD. */
238 #ifdef BROKEN_DATAGRAM_SOCKETS
239 #undef DATAGRAM_SOCKETS
240 #else
241 #ifndef DATAGRAM_SOCKETS
242 #ifdef HAVE_SOCKETS
243 #if defined (HAVE_SELECT) || defined (FIONREAD)
244 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
245 #define DATAGRAM_SOCKETS
246 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
247 #endif /* HAVE_SELECT || FIONREAD */
248 #endif /* HAVE_SOCKETS */
249 #endif /* DATAGRAM_SOCKETS */
250 #endif /* BROKEN_DATAGRAM_SOCKETS */
252 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
253 # define HAVE_SEQPACKET
254 #endif
256 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
257 #ifdef EMACS_HAS_USECS
258 #define ADAPTIVE_READ_BUFFERING
259 #endif
260 #endif
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT 10000
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count;
272 /* Non-zero if any process has non-nil read_output_skip. */
274 static int process_output_skip;
276 /* Non-nil means to delay reading process output to improve buffering.
277 A value of t means that delay is reset after each send, any other
278 non-nil value does not reset the delay. A value of nil disables
279 adaptive read buffering completely. */
280 static Lisp_Object Vprocess_adaptive_read_buffering;
281 #else
282 #define process_output_delay_count 0
283 #endif
286 #include "sysselect.h"
288 static int keyboard_bit_set (SELECT_TYPE *);
289 static void deactivate_process (Lisp_Object);
290 static void status_notify (struct Lisp_Process *);
291 static int read_process_output (Lisp_Object, int);
292 static void create_pty (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 (register Lisp_Object name);
301 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
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 /* Non-zero if keyboard input is on hold, zero otherwise. */
311 static int kbd_is_on_hold;
313 /* Mask that excludes keyboard input descriptor(s). */
315 static SELECT_TYPE non_keyboard_wait_mask;
317 /* Mask that excludes process input descriptor(s). */
319 static SELECT_TYPE non_process_wait_mask;
321 /* Mask for the gpm mouse input descriptor. */
323 static SELECT_TYPE gpm_wait_mask;
325 #ifdef NON_BLOCKING_CONNECT
326 /* Mask of bits indicating the descriptors that we wait for connect to
327 complete on. Once they complete, they are removed from this mask
328 and added to the input_wait_mask and non_keyboard_wait_mask. */
330 static SELECT_TYPE connect_wait_mask;
332 /* Number of bits set in connect_wait_mask. */
333 static int num_pending_connects;
335 #define IF_NON_BLOCKING_CONNECT(s) s
336 #else
337 #define IF_NON_BLOCKING_CONNECT(s)
338 #endif
340 /* The largest descriptor currently in use for a process object. */
341 static int max_process_desc;
343 /* The largest descriptor currently in use for keyboard input. */
344 static int max_keyboard_desc;
346 /* The largest descriptor currently in use for gpm mouse input. */
347 static int max_gpm_desc;
349 /* Nonzero means delete a process right away if it exits. */
350 static int delete_exited_processes;
352 /* Indexed by descriptor, gives the process (if any) for that descriptor */
353 Lisp_Object chan_process[MAXDESC];
355 /* Alist of elements (NAME . PROCESS) */
356 Lisp_Object Vprocess_alist;
358 /* Buffered-ahead input char from process, indexed by channel.
359 -1 means empty (no char is buffered).
360 Used on sys V where the only way to tell if there is any
361 output from the process is to read at least one char.
362 Always -1 on systems that support FIONREAD. */
364 /* Don't make static; need to access externally. */
365 int proc_buffered_char[MAXDESC];
367 /* Table of `struct coding-system' for each process. */
368 static struct coding_system *proc_decode_coding_system[MAXDESC];
369 static struct coding_system *proc_encode_coding_system[MAXDESC];
371 #ifdef DATAGRAM_SOCKETS
372 /* Table of `partner address' for datagram sockets. */
373 struct sockaddr_and_len {
374 struct sockaddr *sa;
375 int len;
376 } datagram_address[MAXDESC];
377 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
378 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
379 #else
380 #define DATAGRAM_CHAN_P(chan) (0)
381 #define DATAGRAM_CONN_P(proc) (0)
382 #endif
384 /* Maximum number of bytes to send to a pty without an eof. */
385 static int pty_max_bytes;
387 /* Nonzero means don't run process sentinels. This is used
388 when exiting. */
389 int inhibit_sentinels;
391 #ifdef HAVE_PTYS
392 #ifdef HAVE_PTY_H
393 #include <pty.h>
394 #endif
395 /* The file name of the pty opened by allocate_pty. */
397 static char pty_name[24];
398 #endif
400 /* Compute the Lisp form of the process status, p->status, from
401 the numeric status that was returned by `wait'. */
403 static Lisp_Object status_convert (int);
405 static void
406 update_status (struct Lisp_Process *p)
408 eassert (p->raw_status_new);
409 p->status = status_convert (p->raw_status);
410 p->raw_status_new = 0;
413 /* Convert a process status word in Unix format to
414 the list that we use internally. */
416 static Lisp_Object
417 status_convert (int w)
419 if (WIFSTOPPED (w))
420 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
421 else if (WIFEXITED (w))
422 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
423 WCOREDUMP (w) ? Qt : Qnil));
424 else if (WIFSIGNALED (w))
425 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
426 WCOREDUMP (w) ? Qt : Qnil));
427 else
428 return Qrun;
431 /* Given a status-list, extract the three pieces of information
432 and store them individually through the three pointers. */
434 static void
435 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
437 Lisp_Object tem;
439 if (SYMBOLP (l))
441 *symbol = l;
442 *code = 0;
443 *coredump = 0;
445 else
447 *symbol = XCAR (l);
448 tem = XCDR (l);
449 *code = XFASTINT (XCAR (tem));
450 tem = XCDR (tem);
451 *coredump = !NILP (tem);
455 /* Return a string describing a process status list. */
457 static Lisp_Object
458 status_message (struct Lisp_Process *p)
460 Lisp_Object status = p->status;
461 Lisp_Object symbol;
462 int code, coredump;
463 Lisp_Object string, string2;
465 decode_status (status, &symbol, &code, &coredump);
467 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
469 char *signame;
470 synchronize_system_messages_locale ();
471 signame = strsignal (code);
472 if (signame == 0)
473 string = build_string ("unknown");
474 else
476 int c1, c2;
478 string = make_unibyte_string (signame, strlen (signame));
479 if (! NILP (Vlocale_coding_system))
480 string = (code_convert_string_norecord
481 (string, Vlocale_coding_system, 0));
482 c1 = STRING_CHAR ((char *) SDATA (string));
483 c2 = DOWNCASE (c1);
484 if (c1 != c2)
485 Faset (string, make_number (0), make_number (c2));
487 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
488 return concat2 (string, string2);
490 else if (EQ (symbol, Qexit))
492 if (NETCONN1_P (p))
493 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
494 if (code == 0)
495 return build_string ("finished\n");
496 string = Fnumber_to_string (make_number (code));
497 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
498 return concat3 (build_string ("exited abnormally with code "),
499 string, string2);
501 else if (EQ (symbol, Qfailed))
503 string = Fnumber_to_string (make_number (code));
504 string2 = build_string ("\n");
505 return concat3 (build_string ("failed with code "),
506 string, string2);
508 else
509 return Fcopy_sequence (Fsymbol_name (symbol));
512 #ifdef HAVE_PTYS
514 /* Open an available pty, returning a file descriptor.
515 Return -1 on failure.
516 The file name of the terminal corresponding to the pty
517 is left in the variable pty_name. */
519 static int
520 allocate_pty (void)
522 register int c, i;
523 int fd;
525 #ifdef PTY_ITERATION
526 PTY_ITERATION
527 #else
528 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
529 for (i = 0; i < 16; i++)
530 #endif
532 struct stat stb; /* Used in some PTY_OPEN. */
533 #ifdef PTY_NAME_SPRINTF
534 PTY_NAME_SPRINTF
535 #else
536 sprintf (pty_name, "/dev/pty%c%x", c, i);
537 #endif /* no PTY_NAME_SPRINTF */
539 #ifdef PTY_OPEN
540 PTY_OPEN;
541 #else /* no PTY_OPEN */
543 { /* Some systems name their pseudoterminals so that there are gaps in
544 the usual sequence - for example, on HP9000/S700 systems, there
545 are no pseudoterminals with names ending in 'f'. So we wait for
546 three failures in a row before deciding that we've reached the
547 end of the ptys. */
548 int failed_count = 0;
550 if (stat (pty_name, &stb) < 0)
552 failed_count++;
553 if (failed_count >= 3)
554 return -1;
556 else
557 failed_count = 0;
559 # ifdef O_NONBLOCK
560 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
561 # else
562 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
563 # endif
565 #endif /* no PTY_OPEN */
567 if (fd >= 0)
569 /* check to make certain that both sides are available
570 this avoids a nasty yet stupid bug in rlogins */
571 #ifdef PTY_TTY_NAME_SPRINTF
572 PTY_TTY_NAME_SPRINTF
573 #else
574 sprintf (pty_name, "/dev/tty%c%x", c, i);
575 #endif /* no PTY_TTY_NAME_SPRINTF */
576 if (access (pty_name, 6) != 0)
578 emacs_close (fd);
579 # ifndef __sgi
580 continue;
581 # else
582 return -1;
583 # endif /* __sgi */
585 setup_pty (fd);
586 return fd;
589 return -1;
591 #endif /* HAVE_PTYS */
593 static Lisp_Object
594 make_process (Lisp_Object name)
596 register Lisp_Object val, tem, name1;
597 register struct Lisp_Process *p;
598 char suffix[10];
599 register int i;
601 p = allocate_process ();
603 p->infd = -1;
604 p->outfd = -1;
605 p->tick = 0;
606 p->update_tick = 0;
607 p->pid = 0;
608 p->pty_flag = 0;
609 p->raw_status_new = 0;
610 p->status = Qrun;
611 p->mark = Fmake_marker ();
612 p->kill_without_query = 0;
614 #ifdef ADAPTIVE_READ_BUFFERING
615 p->adaptive_read_buffering = 0;
616 p->read_output_delay = 0;
617 p->read_output_skip = 0;
618 #endif
620 /* If name is already in use, modify it until it is unused. */
622 name1 = name;
623 for (i = 1; ; i++)
625 tem = Fget_process (name1);
626 if (NILP (tem)) break;
627 sprintf (suffix, "<%d>", i);
628 name1 = concat2 (name, build_string (suffix));
630 name = name1;
631 p->name = name;
632 XSETPROCESS (val, p);
633 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
634 return val;
637 static void
638 remove_process (register Lisp_Object proc)
640 register Lisp_Object pair;
642 pair = Frassq (proc, Vprocess_alist);
643 Vprocess_alist = Fdelq (pair, Vprocess_alist);
645 deactivate_process (proc);
648 /* Setup coding systems of PROCESS. */
650 void
651 setup_process_coding_systems (Lisp_Object process)
653 struct Lisp_Process *p = XPROCESS (process);
654 int inch = p->infd;
655 int outch = p->outfd;
656 Lisp_Object coding_system;
658 if (inch < 0 || outch < 0)
659 return;
661 if (!proc_decode_coding_system[inch])
662 proc_decode_coding_system[inch]
663 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
664 coding_system = p->decode_coding_system;
665 if (! NILP (p->filter))
667 else if (BUFFERP (p->buffer))
669 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
670 coding_system = raw_text_coding_system (coding_system);
672 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
674 if (!proc_encode_coding_system[outch])
675 proc_encode_coding_system[outch]
676 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
677 setup_coding_system (p->encode_coding_system,
678 proc_encode_coding_system[outch]);
681 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
682 doc: /* Return t if OBJECT is a process. */)
683 (Lisp_Object object)
685 return PROCESSP (object) ? Qt : Qnil;
688 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
689 doc: /* Return the process named NAME, or nil if there is none. */)
690 (register Lisp_Object name)
692 if (PROCESSP (name))
693 return name;
694 CHECK_STRING (name);
695 return Fcdr (Fassoc (name, Vprocess_alist));
698 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
699 doc: /* Return the (or a) process associated with BUFFER.
700 BUFFER may be a buffer or the name of one. */)
701 (register Lisp_Object buffer)
703 register Lisp_Object buf, tail, proc;
705 if (NILP (buffer)) return Qnil;
706 buf = Fget_buffer (buffer);
707 if (NILP (buf)) return Qnil;
709 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
711 proc = Fcdr (XCAR (tail));
712 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
713 return proc;
715 return Qnil;
718 /* This is how commands for the user decode process arguments. It
719 accepts a process, a process name, a buffer, a buffer name, or nil.
720 Buffers denote the first process in the buffer, and nil denotes the
721 current buffer. */
723 static Lisp_Object
724 get_process (register Lisp_Object name)
726 register Lisp_Object proc, obj;
727 if (STRINGP (name))
729 obj = Fget_process (name);
730 if (NILP (obj))
731 obj = Fget_buffer (name);
732 if (NILP (obj))
733 error ("Process %s does not exist", SDATA (name));
735 else if (NILP (name))
736 obj = Fcurrent_buffer ();
737 else
738 obj = name;
740 /* Now obj should be either a buffer object or a process object.
742 if (BUFFERP (obj))
744 proc = Fget_buffer_process (obj);
745 if (NILP (proc))
746 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
748 else
750 CHECK_PROCESS (obj);
751 proc = obj;
753 return proc;
757 #ifdef SIGCHLD
758 /* Fdelete_process promises to immediately forget about the process, but in
759 reality, Emacs needs to remember those processes until they have been
760 treated by sigchld_handler; otherwise this handler would consider the
761 process as being synchronous and say that the synchronous process is
762 dead. */
763 static Lisp_Object deleted_pid_list;
764 #endif
766 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
767 doc: /* Delete PROCESS: kill it and forget about it immediately.
768 PROCESS may be a process, a buffer, the name of a process or buffer, or
769 nil, indicating the current buffer's process. */)
770 (register Lisp_Object process)
772 register struct Lisp_Process *p;
774 process = get_process (process);
775 p = XPROCESS (process);
777 p->raw_status_new = 0;
778 if (NETCONN1_P (p) || SERIALCONN1_P (p))
780 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
781 p->tick = ++process_tick;
782 status_notify (p);
783 redisplay_preserve_echo_area (13);
785 else if (p->infd >= 0)
787 #ifdef SIGCHLD
788 Lisp_Object symbol;
789 /* Assignment to EMACS_INT stops GCC whining about limited range
790 of data type. */
791 EMACS_INT pid = p->pid;
793 /* No problem storing the pid here, as it is still in Vprocess_alist. */
794 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
795 /* GC treated elements set to nil. */
796 Fdelq (Qnil, deleted_pid_list));
797 /* If the process has already signaled, remove it from the list. */
798 if (p->raw_status_new)
799 update_status (p);
800 symbol = p->status;
801 if (CONSP (p->status))
802 symbol = XCAR (p->status);
803 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
804 deleted_pid_list
805 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
806 else
807 #endif
809 Fkill_process (process, Qnil);
810 /* Do this now, since remove_process will make sigchld_handler do nothing. */
811 p->status
812 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
813 p->tick = ++process_tick;
814 status_notify (p);
815 redisplay_preserve_echo_area (13);
818 remove_process (process);
819 return Qnil;
822 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
823 doc: /* Return the status of PROCESS.
824 The returned value is one of the following symbols:
825 run -- for a process that is running.
826 stop -- for a process stopped but continuable.
827 exit -- for a process that has exited.
828 signal -- for a process that has got a fatal signal.
829 open -- for a network stream connection that is open.
830 listen -- for a network stream server that is listening.
831 closed -- for a network stream connection that is closed.
832 connect -- when waiting for a non-blocking connection to complete.
833 failed -- when a non-blocking connection has failed.
834 nil -- if arg is a process name and no such process exists.
835 PROCESS may be a process, a buffer, the name of a process, or
836 nil, indicating the current buffer's process. */)
837 (register Lisp_Object process)
839 register struct Lisp_Process *p;
840 register Lisp_Object status;
842 if (STRINGP (process))
843 process = Fget_process (process);
844 else
845 process = get_process (process);
847 if (NILP (process))
848 return process;
850 p = XPROCESS (process);
851 if (p->raw_status_new)
852 update_status (p);
853 status = p->status;
854 if (CONSP (status))
855 status = XCAR (status);
856 if (NETCONN1_P (p) || SERIALCONN1_P (p))
858 if (EQ (status, Qexit))
859 status = Qclosed;
860 else if (EQ (p->command, Qt))
861 status = Qstop;
862 else if (EQ (status, Qrun))
863 status = Qopen;
865 return status;
868 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
869 1, 1, 0,
870 doc: /* Return the exit status of PROCESS or the signal number that killed it.
871 If PROCESS has not yet exited or died, return 0. */)
872 (register Lisp_Object process)
874 CHECK_PROCESS (process);
875 if (XPROCESS (process)->raw_status_new)
876 update_status (XPROCESS (process));
877 if (CONSP (XPROCESS (process)->status))
878 return XCAR (XCDR (XPROCESS (process)->status));
879 return make_number (0);
882 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
883 doc: /* Return the process id of PROCESS.
884 This is the pid of the external process which PROCESS uses or talks to.
885 For a network connection, this value is nil. */)
886 (register Lisp_Object process)
888 /* Assignment to EMACS_INT stops GCC whining about limited range of
889 data type. */
890 EMACS_INT pid;
892 CHECK_PROCESS (process);
893 pid = XPROCESS (process)->pid;
894 return (pid ? make_fixnum_or_float (pid) : Qnil);
897 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
898 doc: /* Return the name of PROCESS, as a string.
899 This is the name of the program invoked in PROCESS,
900 possibly modified to make it unique among process names. */)
901 (register Lisp_Object process)
903 CHECK_PROCESS (process);
904 return XPROCESS (process)->name;
907 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
908 doc: /* Return the command that was executed to start PROCESS.
909 This is a list of strings, the first string being the program executed
910 and the rest of the strings being the arguments given to it.
911 For a network or serial process, this is nil (process is running) or t
912 \(process is stopped). */)
913 (register Lisp_Object process)
915 CHECK_PROCESS (process);
916 return XPROCESS (process)->command;
919 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
920 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
921 This is the terminal that the process itself reads and writes on,
922 not the name of the pty that Emacs uses to talk with that terminal. */)
923 (register Lisp_Object process)
925 CHECK_PROCESS (process);
926 return XPROCESS (process)->tty_name;
929 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
930 2, 2, 0,
931 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
932 (register Lisp_Object process, Lisp_Object buffer)
934 struct Lisp_Process *p;
936 CHECK_PROCESS (process);
937 if (!NILP (buffer))
938 CHECK_BUFFER (buffer);
939 p = XPROCESS (process);
940 p->buffer = buffer;
941 if (NETCONN1_P (p) || SERIALCONN1_P (p))
942 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
943 setup_process_coding_systems (process);
944 return buffer;
947 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
948 1, 1, 0,
949 doc: /* Return the buffer PROCESS is associated with.
950 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
951 (register Lisp_Object process)
953 CHECK_PROCESS (process);
954 return XPROCESS (process)->buffer;
957 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
958 1, 1, 0,
959 doc: /* Return the marker for the end of the last output from PROCESS. */)
960 (register Lisp_Object process)
962 CHECK_PROCESS (process);
963 return XPROCESS (process)->mark;
966 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
967 2, 2, 0,
968 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
969 A value of t means stop accepting output from the process.
971 When a process has a filter, its buffer is not used for output.
972 Instead, each time it does output, the entire string of output is
973 passed to the filter.
975 The filter gets two arguments: the process and the string of output.
976 The string argument is normally a multibyte string, except:
977 - if the process' input coding system is no-conversion or raw-text,
978 it is a unibyte string (the non-converted input), or else
979 - if `default-enable-multibyte-characters' is nil, it is a unibyte
980 string (the result of converting the decoded input multibyte
981 string to unibyte with `string-make-unibyte'). */)
982 (register Lisp_Object process, Lisp_Object filter)
984 struct Lisp_Process *p;
986 CHECK_PROCESS (process);
987 p = XPROCESS (process);
989 /* Don't signal an error if the process' input file descriptor
990 is closed. This could make debugging Lisp more difficult,
991 for example when doing something like
993 (setq process (start-process ...))
994 (debug)
995 (set-process-filter process ...) */
997 if (p->infd >= 0)
999 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1001 FD_CLR (p->infd, &input_wait_mask);
1002 FD_CLR (p->infd, &non_keyboard_wait_mask);
1004 else if (EQ (p->filter, Qt)
1005 /* Network or serial process not stopped: */
1006 && !EQ (p->command, Qt))
1008 FD_SET (p->infd, &input_wait_mask);
1009 FD_SET (p->infd, &non_keyboard_wait_mask);
1013 p->filter = filter;
1014 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1015 p->childp = Fplist_put (p->childp, QCfilter, filter);
1016 setup_process_coding_systems (process);
1017 return filter;
1020 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1021 1, 1, 0,
1022 doc: /* Returns the filter function of PROCESS; nil if none.
1023 See `set-process-filter' for more info on filter functions. */)
1024 (register Lisp_Object process)
1026 CHECK_PROCESS (process);
1027 return XPROCESS (process)->filter;
1030 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1031 2, 2, 0,
1032 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1033 The sentinel is called as a function when the process changes state.
1034 It gets two arguments: the process, and a string describing the change. */)
1035 (register Lisp_Object process, Lisp_Object sentinel)
1037 struct Lisp_Process *p;
1039 CHECK_PROCESS (process);
1040 p = XPROCESS (process);
1042 p->sentinel = sentinel;
1043 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1044 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1045 return sentinel;
1048 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1049 1, 1, 0,
1050 doc: /* Return the sentinel of PROCESS; nil if none.
1051 See `set-process-sentinel' for more info on sentinels. */)
1052 (register Lisp_Object process)
1054 CHECK_PROCESS (process);
1055 return XPROCESS (process)->sentinel;
1058 DEFUN ("set-process-window-size", Fset_process_window_size,
1059 Sset_process_window_size, 3, 3, 0,
1060 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1061 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1063 CHECK_PROCESS (process);
1064 CHECK_NATNUM (height);
1065 CHECK_NATNUM (width);
1067 if (XPROCESS (process)->infd < 0
1068 || set_window_size (XPROCESS (process)->infd,
1069 XINT (height), XINT (width)) <= 0)
1070 return Qnil;
1071 else
1072 return Qt;
1075 DEFUN ("set-process-inherit-coding-system-flag",
1076 Fset_process_inherit_coding_system_flag,
1077 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1078 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1079 If the second argument FLAG is non-nil, then the variable
1080 `buffer-file-coding-system' of the buffer associated with PROCESS
1081 will be bound to the value of the coding system used to decode
1082 the process output.
1084 This is useful when the coding system specified for the process buffer
1085 leaves either the character code conversion or the end-of-line conversion
1086 unspecified, or if the coding system used to decode the process output
1087 is more appropriate for saving the process buffer.
1089 Binding the variable `inherit-process-coding-system' to non-nil before
1090 starting the process is an alternative way of setting the inherit flag
1091 for the process which will run. */)
1092 (register Lisp_Object process, Lisp_Object flag)
1094 CHECK_PROCESS (process);
1095 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1096 return flag;
1099 DEFUN ("process-inherit-coding-system-flag",
1100 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1101 1, 1, 0,
1102 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1103 If this flag is t, `buffer-file-coding-system' of the buffer
1104 associated with PROCESS will inherit the coding system used to decode
1105 the process output. */)
1106 (register Lisp_Object process)
1108 CHECK_PROCESS (process);
1109 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1112 DEFUN ("set-process-query-on-exit-flag",
1113 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1114 2, 2, 0,
1115 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1116 If the second argument FLAG is non-nil, Emacs will query the user before
1117 exiting or killing a buffer if PROCESS is running. */)
1118 (register Lisp_Object process, Lisp_Object flag)
1120 CHECK_PROCESS (process);
1121 XPROCESS (process)->kill_without_query = NILP (flag);
1122 return flag;
1125 DEFUN ("process-query-on-exit-flag",
1126 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1127 1, 1, 0,
1128 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1129 (register Lisp_Object process)
1131 CHECK_PROCESS (process);
1132 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1135 #ifdef DATAGRAM_SOCKETS
1136 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1137 #endif
1139 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1140 1, 2, 0,
1141 doc: /* Return the contact info of PROCESS; t for a real child.
1142 For a network or serial connection, the value depends on the optional
1143 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1144 SERVICE) for a network connection or (PORT SPEED) for a serial
1145 connection. If KEY is t, the complete contact information for the
1146 connection is returned, else the specific value for the keyword KEY is
1147 returned. See `make-network-process' or `make-serial-process' for a
1148 list of keywords. */)
1149 (register Lisp_Object process, Lisp_Object key)
1151 Lisp_Object contact;
1153 CHECK_PROCESS (process);
1154 contact = XPROCESS (process)->childp;
1156 #ifdef DATAGRAM_SOCKETS
1157 if (DATAGRAM_CONN_P (process)
1158 && (EQ (key, Qt) || EQ (key, QCremote)))
1159 contact = Fplist_put (contact, QCremote,
1160 Fprocess_datagram_address (process));
1161 #endif
1163 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1164 return contact;
1165 if (NILP (key) && NETCONN_P (process))
1166 return Fcons (Fplist_get (contact, QChost),
1167 Fcons (Fplist_get (contact, QCservice), Qnil));
1168 if (NILP (key) && SERIALCONN_P (process))
1169 return Fcons (Fplist_get (contact, QCport),
1170 Fcons (Fplist_get (contact, QCspeed), Qnil));
1171 return Fplist_get (contact, key);
1174 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1175 1, 1, 0,
1176 doc: /* Return the plist of PROCESS. */)
1177 (register Lisp_Object process)
1179 CHECK_PROCESS (process);
1180 return XPROCESS (process)->plist;
1183 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1184 2, 2, 0,
1185 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1186 (register Lisp_Object process, Lisp_Object plist)
1188 CHECK_PROCESS (process);
1189 CHECK_LIST (plist);
1191 XPROCESS (process)->plist = plist;
1192 return plist;
1195 #if 0 /* Turned off because we don't currently record this info
1196 in the process. Perhaps add it. */
1197 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1198 doc: /* Return the connection type of PROCESS.
1199 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1200 a socket connection. */)
1201 (Lisp_Object process)
1203 return XPROCESS (process)->type;
1205 #endif
1207 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1208 doc: /* Return the connection type of PROCESS.
1209 The value is either the symbol `real', `network', or `serial'.
1210 PROCESS may be a process, a buffer, the name of a process or buffer, or
1211 nil, indicating the current buffer's process. */)
1212 (Lisp_Object process)
1214 Lisp_Object proc;
1215 proc = get_process (process);
1216 return XPROCESS (proc)->type;
1219 #ifdef HAVE_SOCKETS
1220 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1221 1, 2, 0,
1222 doc: /* Convert network ADDRESS from internal format to a string.
1223 A 4 or 5 element vector represents an IPv4 address (with port number).
1224 An 8 or 9 element vector represents an IPv6 address (with port number).
1225 If optional second argument OMIT-PORT is non-nil, don't include a port
1226 number in the string, even when present in ADDRESS.
1227 Returns nil if format of ADDRESS is invalid. */)
1228 (Lisp_Object address, Lisp_Object omit_port)
1230 if (NILP (address))
1231 return Qnil;
1233 if (STRINGP (address)) /* AF_LOCAL */
1234 return address;
1236 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1238 register struct Lisp_Vector *p = XVECTOR (address);
1239 Lisp_Object args[10];
1240 int nargs, i;
1242 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1244 args[0] = build_string ("%d.%d.%d.%d");
1245 nargs = 4;
1247 else if (p->size == 5)
1249 args[0] = build_string ("%d.%d.%d.%d:%d");
1250 nargs = 5;
1252 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1254 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1255 nargs = 8;
1257 else if (p->size == 9)
1259 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1260 nargs = 9;
1262 else
1263 return Qnil;
1265 for (i = 0; i < nargs; i++)
1267 EMACS_INT element = XINT (p->contents[i]);
1269 if (element < 0 || element > 65535)
1270 return Qnil;
1272 if (nargs <= 5 /* IPv4 */
1273 && i < 4 /* host, not port */
1274 && element > 255)
1275 return Qnil;
1277 args[i+1] = p->contents[i];
1280 return Fformat (nargs+1, args);
1283 if (CONSP (address))
1285 Lisp_Object args[2];
1286 args[0] = build_string ("<Family %d>");
1287 args[1] = Fcar (address);
1288 return Fformat (2, args);
1291 return Qnil;
1293 #endif
1295 static Lisp_Object
1296 list_processes_1 (Lisp_Object query_only)
1298 register Lisp_Object tail, tem;
1299 Lisp_Object proc, minspace, tem1;
1300 register struct Lisp_Process *p;
1301 char tembuf[300];
1302 int w_proc, w_buffer, w_tty;
1303 int exited = 0;
1304 Lisp_Object i_status, i_buffer, i_tty, i_command;
1306 w_proc = 4; /* Proc */
1307 w_buffer = 6; /* Buffer */
1308 w_tty = 0; /* Omit if no ttys */
1310 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1312 int i;
1314 proc = Fcdr (XCAR (tail));
1315 p = XPROCESS (proc);
1316 if (NILP (p->type))
1317 continue;
1318 if (!NILP (query_only) && p->kill_without_query)
1319 continue;
1320 if (STRINGP (p->name)
1321 && ( i = SCHARS (p->name), (i > w_proc)))
1322 w_proc = i;
1323 if (!NILP (p->buffer))
1325 if (NILP (XBUFFER (p->buffer)->name))
1327 if (w_buffer < 8)
1328 w_buffer = 8; /* (Killed) */
1330 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1331 w_buffer = i;
1333 if (STRINGP (p->tty_name)
1334 && (i = SCHARS (p->tty_name), (i > w_tty)))
1335 w_tty = i;
1338 XSETFASTINT (i_status, w_proc + 1);
1339 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1340 if (w_tty)
1342 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1343 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1345 else
1347 i_tty = Qnil;
1348 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1351 XSETFASTINT (minspace, 1);
1353 set_buffer_internal (XBUFFER (Vstandard_output));
1354 current_buffer->undo_list = Qt;
1356 current_buffer->truncate_lines = Qt;
1358 write_string ("Proc", -1);
1359 Findent_to (i_status, minspace); write_string ("Status", -1);
1360 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1361 if (!NILP (i_tty))
1363 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1365 Findent_to (i_command, minspace); write_string ("Command", -1);
1366 write_string ("\n", -1);
1368 write_string ("----", -1);
1369 Findent_to (i_status, minspace); write_string ("------", -1);
1370 Findent_to (i_buffer, minspace); write_string ("------", -1);
1371 if (!NILP (i_tty))
1373 Findent_to (i_tty, minspace); write_string ("---", -1);
1375 Findent_to (i_command, minspace); write_string ("-------", -1);
1376 write_string ("\n", -1);
1378 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1380 Lisp_Object symbol;
1382 proc = Fcdr (XCAR (tail));
1383 p = XPROCESS (proc);
1384 if (NILP (p->type))
1385 continue;
1386 if (!NILP (query_only) && p->kill_without_query)
1387 continue;
1389 Finsert (1, &p->name);
1390 Findent_to (i_status, minspace);
1392 if (p->raw_status_new)
1393 update_status (p);
1394 symbol = p->status;
1395 if (CONSP (p->status))
1396 symbol = XCAR (p->status);
1398 if (EQ (symbol, Qsignal))
1400 Lisp_Object tem;
1401 tem = Fcar (Fcdr (p->status));
1402 Fprinc (symbol, Qnil);
1404 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1406 if (EQ (symbol, Qexit))
1407 write_string ("closed", -1);
1408 else if (EQ (p->command, Qt))
1409 write_string ("stopped", -1);
1410 else if (EQ (symbol, Qrun))
1411 write_string ("open", -1);
1412 else
1413 Fprinc (symbol, Qnil);
1415 else if (SERIALCONN1_P (p))
1417 write_string ("running", -1);
1419 else
1420 Fprinc (symbol, Qnil);
1422 if (EQ (symbol, Qexit))
1424 Lisp_Object tem;
1425 tem = Fcar (Fcdr (p->status));
1426 if (XFASTINT (tem))
1428 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1429 write_string (tembuf, -1);
1433 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1434 exited++;
1436 Findent_to (i_buffer, minspace);
1437 if (NILP (p->buffer))
1438 insert_string ("(none)");
1439 else if (NILP (XBUFFER (p->buffer)->name))
1440 insert_string ("(Killed)");
1441 else
1442 Finsert (1, &XBUFFER (p->buffer)->name);
1444 if (!NILP (i_tty))
1446 Findent_to (i_tty, minspace);
1447 if (STRINGP (p->tty_name))
1448 Finsert (1, &p->tty_name);
1451 Findent_to (i_command, minspace);
1453 if (EQ (p->status, Qlisten))
1455 Lisp_Object port = Fplist_get (p->childp, QCservice);
1456 if (INTEGERP (port))
1457 port = Fnumber_to_string (port);
1458 if (NILP (port))
1459 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1460 sprintf (tembuf, "(network %s server on %s)\n",
1461 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1462 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1463 insert_string (tembuf);
1465 else if (NETCONN1_P (p))
1467 /* For a local socket, there is no host name,
1468 so display service instead. */
1469 Lisp_Object host = Fplist_get (p->childp, QChost);
1470 if (!STRINGP (host))
1472 host = Fplist_get (p->childp, QCservice);
1473 if (INTEGERP (host))
1474 host = Fnumber_to_string (host);
1476 if (NILP (host))
1477 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1478 sprintf (tembuf, "(network %s connection to %s)\n",
1479 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1480 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1481 insert_string (tembuf);
1483 else if (SERIALCONN1_P (p))
1485 Lisp_Object port = Fplist_get (p->childp, QCport);
1486 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1487 insert_string ("(serial port ");
1488 if (STRINGP (port))
1489 insert_string (SDATA (port));
1490 else
1491 insert_string ("?");
1492 if (INTEGERP (speed))
1494 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1495 insert_string (tembuf);
1497 insert_string (")\n");
1499 else
1501 tem = p->command;
1502 while (1)
1504 tem1 = Fcar (tem);
1505 if (NILP (tem1))
1506 break;
1507 Finsert (1, &tem1);
1508 tem = Fcdr (tem);
1509 if (NILP (tem))
1510 break;
1511 insert_string (" ");
1513 insert_string ("\n");
1516 if (exited)
1518 status_notify (NULL);
1519 redisplay_preserve_echo_area (13);
1521 return Qnil;
1524 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1525 doc: /* Display a list of all processes.
1526 If optional argument QUERY-ONLY is non-nil, only processes with
1527 the query-on-exit flag set will be listed.
1528 Any process listed as exited or signaled is actually eliminated
1529 after the listing is made. */)
1530 (Lisp_Object query_only)
1532 internal_with_output_to_temp_buffer ("*Process List*",
1533 list_processes_1, query_only);
1534 return Qnil;
1537 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1538 doc: /* Return a list of all processes. */)
1539 (void)
1541 return Fmapcar (Qcdr, Vprocess_alist);
1544 /* Starting asynchronous inferior processes. */
1546 static Lisp_Object start_process_unwind (Lisp_Object proc);
1548 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1549 doc: /* Start a program in a subprocess. Return the process object for it.
1550 NAME is name for process. It is modified if necessary to make it unique.
1551 BUFFER is the buffer (or buffer name) to associate with the process.
1553 Process output (both standard output and standard error streams) goes
1554 at end of BUFFER, unless you specify an output stream or filter
1555 function to handle the output. BUFFER may also be nil, meaning that
1556 this process is not associated with any buffer.
1558 PROGRAM is the program file name. It is searched for in PATH. If
1559 nil, just associate a pty with the buffer. Remaining arguments are
1560 strings to give program as arguments.
1562 If you want to separate standard output from standard error, invoke
1563 the command through a shell and redirect one of them using the shell
1564 syntax.
1566 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1567 (int nargs, register Lisp_Object *args)
1569 Lisp_Object buffer, name, program, proc, current_dir, tem;
1570 register unsigned char **new_argv;
1571 register int i;
1572 int count = SPECPDL_INDEX ();
1574 buffer = args[1];
1575 if (!NILP (buffer))
1576 buffer = Fget_buffer_create (buffer);
1578 /* Make sure that the child will be able to chdir to the current
1579 buffer's current directory, or its unhandled equivalent. We
1580 can't just have the child check for an error when it does the
1581 chdir, since it's in a vfork.
1583 We have to GCPRO around this because Fexpand_file_name and
1584 Funhandled_file_name_directory might call a file name handling
1585 function. The argument list is protected by the caller, so all
1586 we really have to worry about is buffer. */
1588 struct gcpro gcpro1, gcpro2;
1590 current_dir = current_buffer->directory;
1592 GCPRO2 (buffer, current_dir);
1594 current_dir = Funhandled_file_name_directory (current_dir);
1595 if (NILP (current_dir))
1596 /* If the file name handler says that current_dir is unreachable, use
1597 a sensible default. */
1598 current_dir = build_string ("~/");
1599 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1600 if (NILP (Ffile_accessible_directory_p (current_dir)))
1601 report_file_error ("Setting current directory",
1602 Fcons (current_buffer->directory, Qnil));
1604 UNGCPRO;
1607 name = args[0];
1608 CHECK_STRING (name);
1610 program = args[2];
1612 if (!NILP (program))
1613 CHECK_STRING (program);
1615 proc = make_process (name);
1616 /* If an error occurs and we can't start the process, we want to
1617 remove it from the process list. This means that each error
1618 check in create_process doesn't need to call remove_process
1619 itself; it's all taken care of here. */
1620 record_unwind_protect (start_process_unwind, proc);
1622 XPROCESS (proc)->childp = Qt;
1623 XPROCESS (proc)->plist = Qnil;
1624 XPROCESS (proc)->type = Qreal;
1625 XPROCESS (proc)->buffer = buffer;
1626 XPROCESS (proc)->sentinel = Qnil;
1627 XPROCESS (proc)->filter = Qnil;
1628 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1630 #ifdef ADAPTIVE_READ_BUFFERING
1631 XPROCESS (proc)->adaptive_read_buffering
1632 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1633 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1634 #endif
1636 /* Make the process marker point into the process buffer (if any). */
1637 if (BUFFERP (buffer))
1638 set_marker_both (XPROCESS (proc)->mark, buffer,
1639 BUF_ZV (XBUFFER (buffer)),
1640 BUF_ZV_BYTE (XBUFFER (buffer)));
1643 /* Decide coding systems for communicating with the process. Here
1644 we don't setup the structure coding_system nor pay attention to
1645 unibyte mode. They are done in create_process. */
1647 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1648 Lisp_Object coding_systems = Qt;
1649 Lisp_Object val, *args2;
1650 struct gcpro gcpro1, gcpro2;
1652 val = Vcoding_system_for_read;
1653 if (NILP (val))
1655 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1656 args2[0] = Qstart_process;
1657 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1658 GCPRO2 (proc, current_dir);
1659 if (!NILP (program))
1660 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1661 UNGCPRO;
1662 if (CONSP (coding_systems))
1663 val = XCAR (coding_systems);
1664 else if (CONSP (Vdefault_process_coding_system))
1665 val = XCAR (Vdefault_process_coding_system);
1667 XPROCESS (proc)->decode_coding_system = val;
1669 val = Vcoding_system_for_write;
1670 if (NILP (val))
1672 if (EQ (coding_systems, Qt))
1674 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1675 args2[0] = Qstart_process;
1676 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1677 GCPRO2 (proc, current_dir);
1678 if (!NILP (program))
1679 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1680 UNGCPRO;
1682 if (CONSP (coding_systems))
1683 val = XCDR (coding_systems);
1684 else if (CONSP (Vdefault_process_coding_system))
1685 val = XCDR (Vdefault_process_coding_system);
1687 XPROCESS (proc)->encode_coding_system = val;
1691 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1692 XPROCESS (proc)->decoding_carryover = 0;
1693 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1695 XPROCESS (proc)->inherit_coding_system_flag
1696 = !(NILP (buffer) || !inherit_process_coding_system);
1698 if (!NILP (program))
1700 /* If program file name is not absolute, search our path for it.
1701 Put the name we will really use in TEM. */
1702 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1703 && !(SCHARS (program) > 1
1704 && IS_DEVICE_SEP (SREF (program, 1))))
1706 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1708 tem = Qnil;
1709 GCPRO4 (name, program, buffer, current_dir);
1710 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1711 UNGCPRO;
1712 if (NILP (tem))
1713 report_file_error ("Searching for program", Fcons (program, Qnil));
1714 tem = Fexpand_file_name (tem, Qnil);
1716 else
1718 if (!NILP (Ffile_directory_p (program)))
1719 error ("Specified program for new process is a directory");
1720 tem = program;
1723 /* If program file name starts with /: for quoting a magic name,
1724 discard that. */
1725 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1726 && SREF (tem, 1) == ':')
1727 tem = Fsubstring (tem, make_number (2), Qnil);
1730 struct gcpro gcpro1;
1731 GCPRO1 (tem);
1733 /* Encode the file name and put it in NEW_ARGV.
1734 That's where the child will use it to execute the program. */
1735 tem = Fcons (ENCODE_FILE (tem), Qnil);
1737 /* Here we encode arguments by the coding system used for sending
1738 data to the process. We don't support using different coding
1739 systems for encoding arguments and for encoding data sent to the
1740 process. */
1742 for (i = 3; i < nargs; i++)
1744 tem = Fcons (args[i], tem);
1745 CHECK_STRING (XCAR (tem));
1746 if (STRING_MULTIBYTE (XCAR (tem)))
1747 XSETCAR (tem,
1748 code_convert_string_norecord
1749 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1752 UNGCPRO;
1755 /* Now that everything is encoded we can collect the strings into
1756 NEW_ARGV. */
1757 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1758 new_argv[nargs - 2] = 0;
1760 for (i = nargs - 3; i >= 0; i--)
1762 new_argv[i] = SDATA (XCAR (tem));
1763 tem = XCDR (tem);
1766 create_process (proc, (char **) new_argv, current_dir);
1768 else
1769 create_pty (proc);
1771 return unbind_to (count, proc);
1774 /* This function is the unwind_protect form for Fstart_process. If
1775 PROC doesn't have its pid set, then we know someone has signaled
1776 an error and the process wasn't started successfully, so we should
1777 remove it from the process list. */
1778 static Lisp_Object
1779 start_process_unwind (Lisp_Object proc)
1781 if (!PROCESSP (proc))
1782 abort ();
1784 /* Was PROC started successfully? */
1785 if (XPROCESS (proc)->pid == -1)
1786 remove_process (proc);
1788 return Qnil;
1791 static void
1792 create_process_1 (struct atimer *timer)
1794 /* Nothing to do. */
1798 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1799 #ifdef USG
1800 #ifdef SIGCHLD
1801 /* Mimic blocking of signals on system V, which doesn't really have it. */
1803 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1804 int sigchld_deferred;
1806 SIGTYPE
1807 create_process_sigchld ()
1809 signal (SIGCHLD, create_process_sigchld);
1811 sigchld_deferred = 1;
1813 #endif
1814 #endif
1815 #endif
1817 void
1818 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1820 int inchannel, outchannel;
1821 pid_t pid;
1822 int sv[2];
1823 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1824 int wait_child_setup[2];
1825 #endif
1826 sigset_t procmask;
1827 sigset_t blocked;
1828 struct sigaction sigint_action;
1829 struct sigaction sigquit_action;
1830 #ifdef AIX
1831 struct sigaction sighup_action;
1832 #endif
1833 /* Use volatile to protect variables from being clobbered by longjmp. */
1834 volatile int forkin, forkout;
1835 volatile int pty_flag = 0;
1836 #ifndef USE_CRT_DLL
1837 extern char **environ;
1838 #endif
1840 inchannel = outchannel = -1;
1842 #ifdef HAVE_PTYS
1843 if (!NILP (Vprocess_connection_type))
1844 outchannel = inchannel = allocate_pty ();
1846 if (inchannel >= 0)
1848 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1849 /* On most USG systems it does not work to open the pty's tty here,
1850 then close it and reopen it in the child. */
1851 #ifdef O_NOCTTY
1852 /* Don't let this terminal become our controlling terminal
1853 (in case we don't have one). */
1854 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1855 #else
1856 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1857 #endif
1858 if (forkin < 0)
1859 report_file_error ("Opening pty", Qnil);
1860 #else
1861 forkin = forkout = -1;
1862 #endif /* not USG, or USG_SUBTTY_WORKS */
1863 pty_flag = 1;
1865 else
1866 #endif /* HAVE_PTYS */
1868 int tem;
1869 tem = pipe (sv);
1870 if (tem < 0)
1871 report_file_error ("Creating pipe", Qnil);
1872 inchannel = sv[0];
1873 forkout = sv[1];
1874 tem = pipe (sv);
1875 if (tem < 0)
1877 emacs_close (inchannel);
1878 emacs_close (forkout);
1879 report_file_error ("Creating pipe", Qnil);
1881 outchannel = sv[1];
1882 forkin = sv[0];
1885 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1887 int tem;
1889 tem = pipe (wait_child_setup);
1890 if (tem < 0)
1891 report_file_error ("Creating pipe", Qnil);
1892 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1893 if (tem >= 0)
1894 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1895 if (tem < 0)
1897 emacs_close (wait_child_setup[0]);
1898 emacs_close (wait_child_setup[1]);
1899 report_file_error ("Setting file descriptor flags", Qnil);
1902 #endif
1904 #if 0
1905 /* Replaced by close_process_descs */
1906 set_exclusive_use (inchannel);
1907 set_exclusive_use (outchannel);
1908 #endif
1910 #ifdef O_NONBLOCK
1911 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1912 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1913 #else
1914 #ifdef O_NDELAY
1915 fcntl (inchannel, F_SETFL, O_NDELAY);
1916 fcntl (outchannel, F_SETFL, O_NDELAY);
1917 #endif
1918 #endif
1920 /* Record this as an active process, with its channels.
1921 As a result, child_setup will close Emacs's side of the pipes. */
1922 chan_process[inchannel] = process;
1923 XPROCESS (process)->infd = inchannel;
1924 XPROCESS (process)->outfd = outchannel;
1926 /* Previously we recorded the tty descriptor used in the subprocess.
1927 It was only used for getting the foreground tty process, so now
1928 we just reopen the device (see emacs_get_tty_pgrp) as this is
1929 more portable (see USG_SUBTTY_WORKS above). */
1931 XPROCESS (process)->pty_flag = pty_flag;
1932 XPROCESS (process)->status = Qrun;
1933 setup_process_coding_systems (process);
1935 /* Delay interrupts until we have a chance to store
1936 the new fork's pid in its process structure */
1937 sigemptyset (&blocked);
1938 #ifdef SIGCHLD
1939 sigaddset (&blocked, SIGCHLD);
1940 #endif
1941 #ifdef HAVE_WORKING_VFORK
1942 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1943 this sets the parent's signal handlers as well as the child's.
1944 So delay all interrupts whose handlers the child might munge,
1945 and record the current handlers so they can be restored later. */
1946 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1947 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1948 #ifdef AIX
1949 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1950 #endif
1951 #endif /* HAVE_WORKING_VFORK */
1952 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1954 FD_SET (inchannel, &input_wait_mask);
1955 FD_SET (inchannel, &non_keyboard_wait_mask);
1956 if (inchannel > max_process_desc)
1957 max_process_desc = inchannel;
1959 /* Until we store the proper pid, enable sigchld_handler
1960 to recognize an unknown pid as standing for this process.
1961 It is very important not to let this `marker' value stay
1962 in the table after this function has returned; if it does
1963 it might cause call-process to hang and subsequent asynchronous
1964 processes to get their return values scrambled. */
1965 XPROCESS (process)->pid = -1;
1967 BLOCK_INPUT;
1970 /* child_setup must clobber environ on systems with true vfork.
1971 Protect it from permanent change. */
1972 char **save_environ = environ;
1974 current_dir = ENCODE_FILE (current_dir);
1976 #ifndef WINDOWSNT
1977 pid = vfork ();
1978 if (pid == 0)
1979 #endif /* not WINDOWSNT */
1981 int xforkin = forkin;
1982 int xforkout = forkout;
1984 #if 0 /* This was probably a mistake--it duplicates code later on,
1985 but fails to handle all the cases. */
1986 /* Make sure SIGCHLD is not blocked in the child. */
1987 sigsetmask (SIGEMPTYMASK);
1988 #endif
1990 /* Make the pty be the controlling terminal of the process. */
1991 #ifdef HAVE_PTYS
1992 /* First, disconnect its current controlling terminal. */
1993 #ifdef HAVE_SETSID
1994 /* We tried doing setsid only if pty_flag, but it caused
1995 process_set_signal to fail on SGI when using a pipe. */
1996 setsid ();
1997 /* Make the pty's terminal the controlling terminal. */
1998 if (pty_flag && xforkin >= 0)
2000 #ifdef TIOCSCTTY
2001 /* We ignore the return value
2002 because faith@cs.unc.edu says that is necessary on Linux. */
2003 ioctl (xforkin, TIOCSCTTY, 0);
2004 #endif
2006 #else /* not HAVE_SETSID */
2007 #ifdef USG
2008 /* It's very important to call setpgrp here and no time
2009 afterwards. Otherwise, we lose our controlling tty which
2010 is set when we open the pty. */
2011 setpgrp ();
2012 #endif /* USG */
2013 #endif /* not HAVE_SETSID */
2014 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2015 if (pty_flag && xforkin >= 0)
2017 struct termios t;
2018 tcgetattr (xforkin, &t);
2019 t.c_lflag = LDISC1;
2020 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2021 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2023 #else
2024 #if defined (NTTYDISC) && defined (TIOCSETD)
2025 if (pty_flag && xforkin >= 0)
2027 /* Use new line discipline. */
2028 int ldisc = NTTYDISC;
2029 ioctl (xforkin, TIOCSETD, &ldisc);
2031 #endif
2032 #endif
2033 #ifdef TIOCNOTTY
2034 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2035 can do TIOCSPGRP only to the process's controlling tty. */
2036 if (pty_flag)
2038 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2039 I can't test it since I don't have 4.3. */
2040 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2041 if (j >= 0)
2043 ioctl (j, TIOCNOTTY, 0);
2044 emacs_close (j);
2046 #ifndef USG
2047 /* In order to get a controlling terminal on some versions
2048 of BSD, it is necessary to put the process in pgrp 0
2049 before it opens the terminal. */
2050 #ifdef HAVE_SETPGID
2051 setpgid (0, 0);
2052 #else
2053 setpgrp (0, 0);
2054 #endif
2055 #endif
2057 #endif /* TIOCNOTTY */
2059 #if !defined (DONT_REOPEN_PTY)
2060 /*** There is a suggestion that this ought to be a
2061 conditional on TIOCSPGRP,
2062 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2063 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2064 that system does seem to need this code, even though
2065 both HAVE_SETSID and TIOCSCTTY are defined. */
2066 /* Now close the pty (if we had it open) and reopen it.
2067 This makes the pty the controlling terminal of the subprocess. */
2068 if (pty_flag)
2071 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2072 would work? */
2073 if (xforkin >= 0)
2074 emacs_close (xforkin);
2075 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2077 if (xforkin < 0)
2079 emacs_write (1, "Couldn't open the pty terminal ", 31);
2080 emacs_write (1, pty_name, strlen (pty_name));
2081 emacs_write (1, "\n", 1);
2082 _exit (1);
2086 #endif /* not DONT_REOPEN_PTY */
2088 #ifdef SETUP_SLAVE_PTY
2089 if (pty_flag)
2091 SETUP_SLAVE_PTY;
2093 #endif /* SETUP_SLAVE_PTY */
2094 #ifdef AIX
2095 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2096 Now reenable it in the child, so it will die when we want it to. */
2097 if (pty_flag)
2098 signal (SIGHUP, SIG_DFL);
2099 #endif
2100 #endif /* HAVE_PTYS */
2102 signal (SIGINT, SIG_DFL);
2103 signal (SIGQUIT, SIG_DFL);
2105 /* Stop blocking signals in the child. */
2106 sigprocmask (SIG_SETMASK, &procmask, 0);
2108 if (pty_flag)
2109 child_setup_tty (xforkout);
2110 #ifdef WINDOWSNT
2111 pid = child_setup (xforkin, xforkout, xforkout,
2112 new_argv, 1, current_dir);
2113 #else /* not WINDOWSNT */
2114 #ifdef FD_CLOEXEC
2115 emacs_close (wait_child_setup[0]);
2116 #endif
2117 child_setup (xforkin, xforkout, xforkout,
2118 new_argv, 1, current_dir);
2119 #endif /* not WINDOWSNT */
2121 environ = save_environ;
2124 UNBLOCK_INPUT;
2126 /* This runs in the Emacs process. */
2127 if (pid < 0)
2129 if (forkin >= 0)
2130 emacs_close (forkin);
2131 if (forkin != forkout && forkout >= 0)
2132 emacs_close (forkout);
2134 else
2136 /* vfork succeeded. */
2137 XPROCESS (process)->pid = pid;
2139 #ifdef WINDOWSNT
2140 register_child (pid, inchannel);
2141 #endif /* WINDOWSNT */
2143 /* If the subfork execv fails, and it exits,
2144 this close hangs. I don't know why.
2145 So have an interrupt jar it loose. */
2147 struct atimer *timer;
2148 EMACS_TIME offset;
2150 stop_polling ();
2151 EMACS_SET_SECS_USECS (offset, 1, 0);
2152 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2154 if (forkin >= 0)
2155 emacs_close (forkin);
2157 cancel_atimer (timer);
2158 start_polling ();
2161 if (forkin != forkout && forkout >= 0)
2162 emacs_close (forkout);
2164 #ifdef HAVE_PTYS
2165 if (pty_flag)
2166 XPROCESS (process)->tty_name = build_string (pty_name);
2167 else
2168 #endif
2169 XPROCESS (process)->tty_name = Qnil;
2171 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2172 /* Wait for child_setup to complete in case that vfork is
2173 actually defined as fork. The descriptor wait_child_setup[1]
2174 of a pipe is closed at the child side either by close-on-exec
2175 on successful execvp or the _exit call in child_setup. */
2177 char dummy;
2179 emacs_close (wait_child_setup[1]);
2180 emacs_read (wait_child_setup[0], &dummy, 1);
2181 emacs_close (wait_child_setup[0]);
2183 #endif
2186 /* Restore the signal state whether vfork succeeded or not.
2187 (We will signal an error, below, if it failed.) */
2188 #ifdef HAVE_WORKING_VFORK
2189 /* Restore the parent's signal handlers. */
2190 sigaction (SIGINT, &sigint_action, 0);
2191 sigaction (SIGQUIT, &sigquit_action, 0);
2192 #ifdef AIX
2193 sigaction (SIGHUP, &sighup_action, 0);
2194 #endif
2195 #endif /* HAVE_WORKING_VFORK */
2196 /* Stop blocking signals in the parent. */
2197 sigprocmask (SIG_SETMASK, &procmask, 0);
2199 /* Now generate the error if vfork failed. */
2200 if (pid < 0)
2201 report_file_error ("Doing vfork", Qnil);
2204 void
2205 create_pty (Lisp_Object process)
2207 int inchannel, outchannel;
2209 /* Use volatile to protect variables from being clobbered by longjmp. */
2210 volatile int forkin, forkout;
2211 volatile int pty_flag = 0;
2213 inchannel = outchannel = -1;
2215 #ifdef HAVE_PTYS
2216 if (!NILP (Vprocess_connection_type))
2217 outchannel = inchannel = allocate_pty ();
2219 if (inchannel >= 0)
2221 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2222 /* On most USG systems it does not work to open the pty's tty here,
2223 then close it and reopen it in the child. */
2224 #ifdef O_NOCTTY
2225 /* Don't let this terminal become our controlling terminal
2226 (in case we don't have one). */
2227 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2228 #else
2229 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2230 #endif
2231 if (forkin < 0)
2232 report_file_error ("Opening pty", Qnil);
2233 #if defined (DONT_REOPEN_PTY)
2234 /* In the case that vfork is defined as fork, the parent process
2235 (Emacs) may send some data before the child process completes
2236 tty options setup. So we setup tty before forking. */
2237 child_setup_tty (forkout);
2238 #endif /* DONT_REOPEN_PTY */
2239 #else
2240 forkin = forkout = -1;
2241 #endif /* not USG, or USG_SUBTTY_WORKS */
2242 pty_flag = 1;
2244 #endif /* HAVE_PTYS */
2246 #ifdef O_NONBLOCK
2247 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2248 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2249 #else
2250 #ifdef O_NDELAY
2251 fcntl (inchannel, F_SETFL, O_NDELAY);
2252 fcntl (outchannel, F_SETFL, O_NDELAY);
2253 #endif
2254 #endif
2256 /* Record this as an active process, with its channels.
2257 As a result, child_setup will close Emacs's side of the pipes. */
2258 chan_process[inchannel] = process;
2259 XPROCESS (process)->infd = inchannel;
2260 XPROCESS (process)->outfd = outchannel;
2262 /* Previously we recorded the tty descriptor used in the subprocess.
2263 It was only used for getting the foreground tty process, so now
2264 we just reopen the device (see emacs_get_tty_pgrp) as this is
2265 more portable (see USG_SUBTTY_WORKS above). */
2267 XPROCESS (process)->pty_flag = pty_flag;
2268 XPROCESS (process)->status = Qrun;
2269 setup_process_coding_systems (process);
2271 FD_SET (inchannel, &input_wait_mask);
2272 FD_SET (inchannel, &non_keyboard_wait_mask);
2273 if (inchannel > max_process_desc)
2274 max_process_desc = inchannel;
2276 XPROCESS (process)->pid = -2;
2277 #ifdef HAVE_PTYS
2278 if (pty_flag)
2279 XPROCESS (process)->tty_name = build_string (pty_name);
2280 else
2281 #endif
2282 XPROCESS (process)->tty_name = Qnil;
2286 #ifdef HAVE_SOCKETS
2288 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2289 The address family of sa is not included in the result. */
2291 static Lisp_Object
2292 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2294 Lisp_Object address;
2295 int i;
2296 unsigned char *cp;
2297 register struct Lisp_Vector *p;
2299 /* Workaround for a bug in getsockname on BSD: Names bound to
2300 sockets in the UNIX domain are inaccessible; getsockname returns
2301 a zero length name. */
2302 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2303 return empty_unibyte_string;
2305 switch (sa->sa_family)
2307 case AF_INET:
2309 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2310 len = sizeof (sin->sin_addr) + 1;
2311 address = Fmake_vector (make_number (len), Qnil);
2312 p = XVECTOR (address);
2313 p->contents[--len] = make_number (ntohs (sin->sin_port));
2314 cp = (unsigned char *) &sin->sin_addr;
2315 break;
2317 #ifdef AF_INET6
2318 case AF_INET6:
2320 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2321 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2322 len = sizeof (sin6->sin6_addr)/2 + 1;
2323 address = Fmake_vector (make_number (len), Qnil);
2324 p = XVECTOR (address);
2325 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2326 for (i = 0; i < len; i++)
2327 p->contents[i] = make_number (ntohs (ip6[i]));
2328 return address;
2330 #endif
2331 #ifdef HAVE_LOCAL_SOCKETS
2332 case AF_LOCAL:
2334 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2335 for (i = 0; i < sizeof (sockun->sun_path); i++)
2336 if (sockun->sun_path[i] == 0)
2337 break;
2338 return make_unibyte_string (sockun->sun_path, i);
2340 #endif
2341 default:
2342 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2343 address = Fcons (make_number (sa->sa_family),
2344 Fmake_vector (make_number (len), Qnil));
2345 p = XVECTOR (XCDR (address));
2346 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2347 break;
2350 i = 0;
2351 while (i < len)
2352 p->contents[i++] = make_number (*cp++);
2354 return address;
2358 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2360 static int
2361 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2363 register struct Lisp_Vector *p;
2365 if (VECTORP (address))
2367 p = XVECTOR (address);
2368 if (p->size == 5)
2370 *familyp = AF_INET;
2371 return sizeof (struct sockaddr_in);
2373 #ifdef AF_INET6
2374 else if (p->size == 9)
2376 *familyp = AF_INET6;
2377 return sizeof (struct sockaddr_in6);
2379 #endif
2381 #ifdef HAVE_LOCAL_SOCKETS
2382 else if (STRINGP (address))
2384 *familyp = AF_LOCAL;
2385 return sizeof (struct sockaddr_un);
2387 #endif
2388 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2390 struct sockaddr *sa;
2391 *familyp = XINT (XCAR (address));
2392 p = XVECTOR (XCDR (address));
2393 return p->size + sizeof (sa->sa_family);
2395 return 0;
2398 /* Convert an address object (vector or string) to an internal sockaddr.
2400 The address format has been basically validated by
2401 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2402 it could have come from user data. So if FAMILY is not valid,
2403 we return after zeroing *SA. */
2405 static void
2406 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2408 register struct Lisp_Vector *p;
2409 register unsigned char *cp = NULL;
2410 register int i;
2412 memset (sa, 0, len);
2414 if (VECTORP (address))
2416 p = XVECTOR (address);
2417 if (family == AF_INET)
2419 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2420 len = sizeof (sin->sin_addr) + 1;
2421 i = XINT (p->contents[--len]);
2422 sin->sin_port = htons (i);
2423 cp = (unsigned char *)&sin->sin_addr;
2424 sa->sa_family = family;
2426 #ifdef AF_INET6
2427 else if (family == AF_INET6)
2429 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2430 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2431 len = sizeof (sin6->sin6_addr) + 1;
2432 i = XINT (p->contents[--len]);
2433 sin6->sin6_port = htons (i);
2434 for (i = 0; i < len; i++)
2435 if (INTEGERP (p->contents[i]))
2437 int j = XFASTINT (p->contents[i]) & 0xffff;
2438 ip6[i] = ntohs (j);
2440 sa->sa_family = family;
2441 return;
2443 #endif
2444 else
2445 return;
2447 else if (STRINGP (address))
2449 #ifdef HAVE_LOCAL_SOCKETS
2450 if (family == AF_LOCAL)
2452 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2453 cp = SDATA (address);
2454 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2455 sockun->sun_path[i] = *cp++;
2456 sa->sa_family = family;
2458 #endif
2459 return;
2461 else
2463 p = XVECTOR (XCDR (address));
2464 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2467 for (i = 0; i < len; i++)
2468 if (INTEGERP (p->contents[i]))
2469 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2472 #ifdef DATAGRAM_SOCKETS
2473 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2474 1, 1, 0,
2475 doc: /* Get the current datagram address associated with PROCESS. */)
2476 (Lisp_Object process)
2478 int channel;
2480 CHECK_PROCESS (process);
2482 if (!DATAGRAM_CONN_P (process))
2483 return Qnil;
2485 channel = XPROCESS (process)->infd;
2486 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2487 datagram_address[channel].len);
2490 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2491 2, 2, 0,
2492 doc: /* Set the datagram address for PROCESS to ADDRESS.
2493 Returns nil upon error setting address, ADDRESS otherwise. */)
2494 (Lisp_Object process, Lisp_Object address)
2496 int channel;
2497 int family, len;
2499 CHECK_PROCESS (process);
2501 if (!DATAGRAM_CONN_P (process))
2502 return Qnil;
2504 channel = XPROCESS (process)->infd;
2506 len = get_lisp_to_sockaddr_size (address, &family);
2507 if (datagram_address[channel].len != len)
2508 return Qnil;
2509 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2510 return address;
2512 #endif
2515 static const struct socket_options {
2516 /* The name of this option. Should be lowercase version of option
2517 name without SO_ prefix. */
2518 char *name;
2519 /* Option level SOL_... */
2520 int optlevel;
2521 /* Option number SO_... */
2522 int optnum;
2523 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2524 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2525 } socket_options[] =
2527 #ifdef SO_BINDTODEVICE
2528 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2529 #endif
2530 #ifdef SO_BROADCAST
2531 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2532 #endif
2533 #ifdef SO_DONTROUTE
2534 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2535 #endif
2536 #ifdef SO_KEEPALIVE
2537 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2538 #endif
2539 #ifdef SO_LINGER
2540 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2541 #endif
2542 #ifdef SO_OOBINLINE
2543 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2544 #endif
2545 #ifdef SO_PRIORITY
2546 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2547 #endif
2548 #ifdef SO_REUSEADDR
2549 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2550 #endif
2551 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2554 /* Set option OPT to value VAL on socket S.
2556 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2557 Signals an error if setting a known option fails.
2560 static int
2561 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2563 char *name;
2564 const struct socket_options *sopt;
2565 int ret = 0;
2567 CHECK_SYMBOL (opt);
2569 name = (char *) SDATA (SYMBOL_NAME (opt));
2570 for (sopt = socket_options; sopt->name; sopt++)
2571 if (strcmp (name, sopt->name) == 0)
2572 break;
2574 switch (sopt->opttype)
2576 case SOPT_BOOL:
2578 int optval;
2579 optval = NILP (val) ? 0 : 1;
2580 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2581 &optval, sizeof (optval));
2582 break;
2585 case SOPT_INT:
2587 int optval;
2588 if (INTEGERP (val))
2589 optval = XINT (val);
2590 else
2591 error ("Bad option value for %s", name);
2592 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2593 &optval, sizeof (optval));
2594 break;
2597 #ifdef SO_BINDTODEVICE
2598 case SOPT_IFNAME:
2600 char devname[IFNAMSIZ+1];
2602 /* This is broken, at least in the Linux 2.4 kernel.
2603 To unbind, the arg must be a zero integer, not the empty string.
2604 This should work on all systems. KFS. 2003-09-23. */
2605 memset (devname, 0, sizeof devname);
2606 if (STRINGP (val))
2608 char *arg = (char *) SDATA (val);
2609 int len = min (strlen (arg), IFNAMSIZ);
2610 memcpy (devname, arg, len);
2612 else if (!NILP (val))
2613 error ("Bad option value for %s", name);
2614 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2615 devname, IFNAMSIZ);
2616 break;
2618 #endif
2620 #ifdef SO_LINGER
2621 case SOPT_LINGER:
2623 struct linger linger;
2625 linger.l_onoff = 1;
2626 linger.l_linger = 0;
2627 if (INTEGERP (val))
2628 linger.l_linger = XINT (val);
2629 else
2630 linger.l_onoff = NILP (val) ? 0 : 1;
2631 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2632 &linger, sizeof (linger));
2633 break;
2635 #endif
2637 default:
2638 return 0;
2641 if (ret < 0)
2642 report_file_error ("Cannot set network option",
2643 Fcons (opt, Fcons (val, Qnil)));
2644 return (1 << sopt->optbit);
2648 DEFUN ("set-network-process-option",
2649 Fset_network_process_option, Sset_network_process_option,
2650 3, 4, 0,
2651 doc: /* For network process PROCESS set option OPTION to value VALUE.
2652 See `make-network-process' for a list of options and values.
2653 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2654 OPTION is not a supported option, return nil instead; otherwise return t. */)
2655 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2657 int s;
2658 struct Lisp_Process *p;
2660 CHECK_PROCESS (process);
2661 p = XPROCESS (process);
2662 if (!NETCONN1_P (p))
2663 error ("Process is not a network process");
2665 s = p->infd;
2666 if (s < 0)
2667 error ("Process is not running");
2669 if (set_socket_option (s, option, value))
2671 p->childp = Fplist_put (p->childp, option, value);
2672 return Qt;
2675 if (NILP (no_error))
2676 error ("Unknown or unsupported option");
2678 return Qnil;
2682 #ifdef HAVE_SERIAL
2683 DEFUN ("serial-process-configure",
2684 Fserial_process_configure,
2685 Sserial_process_configure,
2686 0, MANY, 0,
2687 doc: /* Configure speed, bytesize, etc. of a serial process.
2689 Arguments are specified as keyword/argument pairs. Attributes that
2690 are not given are re-initialized from the process's current
2691 configuration (available via the function `process-contact') or set to
2692 reasonable default values. The following arguments are defined:
2694 :process PROCESS
2695 :name NAME
2696 :buffer BUFFER
2697 :port PORT
2698 -- Any of these arguments can be given to identify the process that is
2699 to be configured. If none of these arguments is given, the current
2700 buffer's process is used.
2702 :speed SPEED -- SPEED is the speed of the serial port in bits per
2703 second, also called baud rate. Any value can be given for SPEED, but
2704 most serial ports work only at a few defined values between 1200 and
2705 115200, with 9600 being the most common value. If SPEED is nil, the
2706 serial port is not configured any further, i.e., all other arguments
2707 are ignored. This may be useful for special serial ports such as
2708 Bluetooth-to-serial converters which can only be configured through AT
2709 commands. A value of nil for SPEED can be used only when passed
2710 through `make-serial-process' or `serial-term'.
2712 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2713 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2715 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2716 `odd' (use odd parity), or the symbol `even' (use even parity). If
2717 PARITY is not given, no parity is used.
2719 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2720 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2721 is not given or nil, 1 stopbit is used.
2723 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2724 flowcontrol to be used, which is either nil (don't use flowcontrol),
2725 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2726 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2727 flowcontrol is used.
2729 `serial-process-configure' is called by `make-serial-process' for the
2730 initial configuration of the serial port.
2732 Examples:
2734 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2736 \(serial-process-configure
2737 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2739 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2741 usage: (serial-process-configure &rest ARGS) */)
2742 (int nargs, Lisp_Object *args)
2744 struct Lisp_Process *p;
2745 Lisp_Object contact = Qnil;
2746 Lisp_Object proc = Qnil;
2747 struct gcpro gcpro1;
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2752 proc = Fplist_get (contact, QCprocess);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCname);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCbuffer);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCport);
2759 proc = get_process (proc);
2760 p = XPROCESS (proc);
2761 if (!EQ (p->type, Qserial))
2762 error ("Not a serial process");
2764 if (NILP (Fplist_get (p->childp, QCspeed)))
2766 UNGCPRO;
2767 return Qnil;
2770 serial_configure (p, contact);
2772 UNGCPRO;
2773 return Qnil;
2776 /* Used by make-serial-process to recover from errors. */
2777 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2779 if (!PROCESSP (proc))
2780 abort ();
2781 remove_process (proc);
2782 return Qnil;
2785 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2786 0, MANY, 0,
2787 doc: /* Create and return a serial port process.
2789 In Emacs, serial port connections are represented by process objects,
2790 so input and output work as for subprocesses, and `delete-process'
2791 closes a serial port connection. However, a serial process has no
2792 process id, it cannot be signaled, and the status codes are different
2793 from normal processes.
2795 `make-serial-process' creates a process and a buffer, on which you
2796 probably want to use `process-send-string'. Try \\[serial-term] for
2797 an interactive terminal. See below for examples.
2799 Arguments are specified as keyword/argument pairs. The following
2800 arguments are defined:
2802 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2803 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2804 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2805 the backslashes in strings).
2807 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2808 which is called by `make-serial-process'.
2810 :name NAME -- NAME is the name of the process. If NAME is not given,
2811 the value of PORT is used.
2813 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2814 with the process. Process output goes at the end of that buffer,
2815 unless you specify an output stream or filter function to handle the
2816 output. If BUFFER is not given, the value of NAME is used.
2818 :coding CODING -- If CODING is a symbol, it specifies the coding
2819 system used for both reading and writing for this process. If CODING
2820 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2821 ENCODING is used for writing.
2823 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2824 the process is running. If BOOL is not given, query before exiting.
2826 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2827 In the stopped state, a serial process does not accept incoming data,
2828 but you can send outgoing data. The stopped state is cleared by
2829 `continue-process' and set by `stop-process'.
2831 :filter FILTER -- Install FILTER as the process filter.
2833 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2835 :plist PLIST -- Install PLIST as the initial plist of the process.
2837 :speed
2838 :bytesize
2839 :parity
2840 :stopbits
2841 :flowcontrol
2842 -- These arguments are handled by `serial-process-configure', which is
2843 called by `make-serial-process'.
2845 The original argument list, possibly modified by later configuration,
2846 is available via the function `process-contact'.
2848 Examples:
2850 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2852 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2854 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2856 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2858 usage: (make-serial-process &rest ARGS) */)
2859 (int nargs, Lisp_Object *args)
2861 int fd = -1;
2862 Lisp_Object proc, contact, port;
2863 struct Lisp_Process *p;
2864 struct gcpro gcpro1;
2865 Lisp_Object name, buffer;
2866 Lisp_Object tem, val;
2867 int specpdl_count = -1;
2869 if (nargs == 0)
2870 return Qnil;
2872 contact = Flist (nargs, args);
2873 GCPRO1 (contact);
2875 port = Fplist_get (contact, QCport);
2876 if (NILP (port))
2877 error ("No port specified");
2878 CHECK_STRING (port);
2880 if (NILP (Fplist_member (contact, QCspeed)))
2881 error (":speed not specified");
2882 if (!NILP (Fplist_get (contact, QCspeed)))
2883 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2885 name = Fplist_get (contact, QCname);
2886 if (NILP (name))
2887 name = port;
2888 CHECK_STRING (name);
2889 proc = make_process (name);
2890 specpdl_count = SPECPDL_INDEX ();
2891 record_unwind_protect (make_serial_process_unwind, proc);
2892 p = XPROCESS (proc);
2894 fd = serial_open ((char*) SDATA (port));
2895 p->infd = fd;
2896 p->outfd = fd;
2897 if (fd > max_process_desc)
2898 max_process_desc = fd;
2899 chan_process[fd] = proc;
2901 buffer = Fplist_get (contact, QCbuffer);
2902 if (NILP (buffer))
2903 buffer = name;
2904 buffer = Fget_buffer_create (buffer);
2905 p->buffer = buffer;
2907 p->childp = contact;
2908 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2909 p->type = Qserial;
2910 p->sentinel = Fplist_get (contact, QCsentinel);
2911 p->filter = Fplist_get (contact, QCfilter);
2912 p->log = Qnil;
2913 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2914 p->kill_without_query = 1;
2915 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2916 p->command = Qt;
2917 p->pty_flag = 0;
2919 if (!EQ (p->command, Qt))
2921 FD_SET (fd, &input_wait_mask);
2922 FD_SET (fd, &non_keyboard_wait_mask);
2925 if (BUFFERP (buffer))
2927 set_marker_both (p->mark, buffer,
2928 BUF_ZV (XBUFFER (buffer)),
2929 BUF_ZV_BYTE (XBUFFER (buffer)));
2932 tem = Fplist_member (contact, QCcoding);
2933 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2934 tem = Qnil;
2936 val = Qnil;
2937 if (!NILP (tem))
2939 val = XCAR (XCDR (tem));
2940 if (CONSP (val))
2941 val = XCAR (val);
2943 else if (!NILP (Vcoding_system_for_read))
2944 val = Vcoding_system_for_read;
2945 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2946 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2947 val = Qnil;
2948 p->decode_coding_system = val;
2950 val = Qnil;
2951 if (!NILP (tem))
2953 val = XCAR (XCDR (tem));
2954 if (CONSP (val))
2955 val = XCDR (val);
2957 else if (!NILP (Vcoding_system_for_write))
2958 val = Vcoding_system_for_write;
2959 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2960 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2961 val = Qnil;
2962 p->encode_coding_system = val;
2964 setup_process_coding_systems (proc);
2965 p->decoding_buf = make_uninit_string (0);
2966 p->decoding_carryover = 0;
2967 p->encoding_buf = make_uninit_string (0);
2968 p->inherit_coding_system_flag
2969 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2971 Fserial_process_configure (nargs, args);
2973 specpdl_ptr = specpdl + specpdl_count;
2975 UNGCPRO;
2976 return proc;
2978 #endif /* HAVE_SERIAL */
2980 /* Create a network stream/datagram client/server process. Treated
2981 exactly like a normal process when reading and writing. Primary
2982 differences are in status display and process deletion. A network
2983 connection has no PID; you cannot signal it. All you can do is
2984 stop/continue it and deactivate/close it via delete-process */
2986 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2987 0, MANY, 0,
2988 doc: /* Create and return a network server or client process.
2990 In Emacs, network connections are represented by process objects, so
2991 input and output work as for subprocesses and `delete-process' closes
2992 a network connection. However, a network process has no process id,
2993 it cannot be signaled, and the status codes are different from normal
2994 processes.
2996 Arguments are specified as keyword/argument pairs. The following
2997 arguments are defined:
2999 :name NAME -- NAME is name for process. It is modified if necessary
3000 to make it unique.
3002 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3003 with the process. Process output goes at end of that buffer, unless
3004 you specify an output stream or filter function to handle the output.
3005 BUFFER may be also nil, meaning that this process is not associated
3006 with any buffer.
3008 :host HOST -- HOST is name of the host to connect to, or its IP
3009 address. The symbol `local' specifies the local host. If specified
3010 for a server process, it must be a valid name or address for the local
3011 host, and only clients connecting to that address will be accepted.
3013 :service SERVICE -- SERVICE is name of the service desired, or an
3014 integer specifying a port number to connect to. If SERVICE is t,
3015 a random port number is selected for the server. (If Emacs was
3016 compiled with getaddrinfo, a port number can also be specified as a
3017 string, e.g. "80", as well as an integer. This is not portable.)
3019 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3020 stream type connection, `datagram' creates a datagram type connection,
3021 `seqpacket' creates a reliable datagram connection.
3023 :family FAMILY -- FAMILY is the address (and protocol) family for the
3024 service specified by HOST and SERVICE. The default (nil) is to use
3025 whatever address family (IPv4 or IPv6) that is defined for the host
3026 and port number specified by HOST and SERVICE. Other address families
3027 supported are:
3028 local -- for a local (i.e. UNIX) address specified by SERVICE.
3029 ipv4 -- use IPv4 address family only.
3030 ipv6 -- use IPv6 address family only.
3032 :local ADDRESS -- ADDRESS is the local address used for the connection.
3033 This parameter is ignored when opening a client process. When specified
3034 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3036 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3037 connection. This parameter is ignored when opening a stream server
3038 process. For a datagram server process, it specifies the initial
3039 setting of the remote datagram address. When specified for a client
3040 process, the FAMILY, HOST, and SERVICE args are ignored.
3042 The format of ADDRESS depends on the address family:
3043 - An IPv4 address is represented as an vector of integers [A B C D P]
3044 corresponding to numeric IP address A.B.C.D and port number P.
3045 - A local address is represented as a string with the address in the
3046 local address space.
3047 - An "unsupported family" address is represented by a cons (F . AV)
3048 where F is the family number and AV is a vector containing the socket
3049 address data with one element per address data byte. Do not rely on
3050 this format in portable code, as it may depend on implementation
3051 defined constants, data sizes, and data structure alignment.
3053 :coding CODING -- If CODING is a symbol, it specifies the coding
3054 system used for both reading and writing for this process. If CODING
3055 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3056 ENCODING is used for writing.
3058 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3059 return without waiting for the connection to complete; instead, the
3060 sentinel function will be called with second arg matching "open" (if
3061 successful) or "failed" when the connect completes. Default is to use
3062 a blocking connect (i.e. wait) for stream type connections.
3064 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3065 running when Emacs is exited.
3067 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3068 In the stopped state, a server process does not accept new
3069 connections, and a client process does not handle incoming traffic.
3070 The stopped state is cleared by `continue-process' and set by
3071 `stop-process'.
3073 :filter FILTER -- Install FILTER as the process filter.
3075 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3076 process filter are multibyte, otherwise they are unibyte.
3077 If this keyword is not specified, the strings are multibyte if
3078 `default-enable-multibyte-characters' is non-nil.
3080 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3082 :log LOG -- Install LOG as the server process log function. This
3083 function is called when the server accepts a network connection from a
3084 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3085 is the server process, CLIENT is the new process for the connection,
3086 and MESSAGE is a string.
3088 :plist PLIST -- Install PLIST as the new process' initial plist.
3090 :server QLEN -- if QLEN is non-nil, create a server process for the
3091 specified FAMILY, SERVICE, and connection type (stream or datagram).
3092 If QLEN is an integer, it is used as the max. length of the server's
3093 pending connection queue (also known as the backlog); the default
3094 queue length is 5. Default is to create a client process.
3096 The following network options can be specified for this connection:
3098 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3099 :dontroute BOOL -- Only send to directly connected hosts.
3100 :keepalive BOOL -- Send keep-alive messages on network stream.
3101 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3102 :oobinline BOOL -- Place out-of-band data in receive data stream.
3103 :priority INT -- Set protocol defined priority for sent packets.
3104 :reuseaddr BOOL -- Allow reusing a recently used local address
3105 (this is allowed by default for a server process).
3106 :bindtodevice NAME -- bind to interface NAME. Using this may require
3107 special privileges on some systems.
3109 Consult the relevant system programmer's manual pages for more
3110 information on using these options.
3113 A server process will listen for and accept connections from clients.
3114 When a client connection is accepted, a new network process is created
3115 for the connection with the following parameters:
3117 - The client's process name is constructed by concatenating the server
3118 process' NAME and a client identification string.
3119 - If the FILTER argument is non-nil, the client process will not get a
3120 separate process buffer; otherwise, the client's process buffer is a newly
3121 created buffer named after the server process' BUFFER name or process
3122 NAME concatenated with the client identification string.
3123 - The connection type and the process filter and sentinel parameters are
3124 inherited from the server process' TYPE, FILTER and SENTINEL.
3125 - The client process' contact info is set according to the client's
3126 addressing information (typically an IP address and a port number).
3127 - The client process' plist is initialized from the server's plist.
3129 Notice that the FILTER and SENTINEL args are never used directly by
3130 the server process. Also, the BUFFER argument is not used directly by
3131 the server process, but via the optional :log function, accepted (and
3132 failed) connections may be logged in the server process' buffer.
3134 The original argument list, modified with the actual connection
3135 information, is available via the `process-contact' function.
3137 usage: (make-network-process &rest ARGS) */)
3138 (int nargs, Lisp_Object *args)
3140 Lisp_Object proc;
3141 Lisp_Object contact;
3142 struct Lisp_Process *p;
3143 #ifdef HAVE_GETADDRINFO
3144 struct addrinfo ai, *res, *lres;
3145 struct addrinfo hints;
3146 char *portstring, portbuf[128];
3147 #else /* HAVE_GETADDRINFO */
3148 struct _emacs_addrinfo
3150 int ai_family;
3151 int ai_socktype;
3152 int ai_protocol;
3153 int ai_addrlen;
3154 struct sockaddr *ai_addr;
3155 struct _emacs_addrinfo *ai_next;
3156 } ai, *res, *lres;
3157 #endif /* HAVE_GETADDRINFO */
3158 struct sockaddr_in address_in;
3159 #ifdef HAVE_LOCAL_SOCKETS
3160 struct sockaddr_un address_un;
3161 #endif
3162 int port;
3163 int ret = 0;
3164 int xerrno = 0;
3165 int s = -1, outch, inch;
3166 struct gcpro gcpro1;
3167 int count = SPECPDL_INDEX ();
3168 int count1;
3169 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3170 Lisp_Object tem;
3171 Lisp_Object name, buffer, host, service, address;
3172 Lisp_Object filter, sentinel;
3173 int is_non_blocking_client = 0;
3174 int is_server = 0, backlog = 5;
3175 int socktype;
3176 int family = -1;
3178 if (nargs == 0)
3179 return Qnil;
3181 /* Save arguments for process-contact and clone-process. */
3182 contact = Flist (nargs, args);
3183 GCPRO1 (contact);
3185 #ifdef WINDOWSNT
3186 /* Ensure socket support is loaded if available. */
3187 init_winsock (TRUE);
3188 #endif
3190 /* :type TYPE (nil: stream, datagram */
3191 tem = Fplist_get (contact, QCtype);
3192 if (NILP (tem))
3193 socktype = SOCK_STREAM;
3194 #ifdef DATAGRAM_SOCKETS
3195 else if (EQ (tem, Qdatagram))
3196 socktype = SOCK_DGRAM;
3197 #endif
3198 #ifdef HAVE_SEQPACKET
3199 else if (EQ (tem, Qseqpacket))
3200 socktype = SOCK_SEQPACKET;
3201 #endif
3202 else
3203 error ("Unsupported connection type");
3205 /* :server BOOL */
3206 tem = Fplist_get (contact, QCserver);
3207 if (!NILP (tem))
3209 /* Don't support network sockets when non-blocking mode is
3210 not available, since a blocked Emacs is not useful. */
3211 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3212 error ("Network servers not supported");
3213 #else
3214 is_server = 1;
3215 if (INTEGERP (tem))
3216 backlog = XINT (tem);
3217 #endif
3220 /* Make QCaddress an alias for :local (server) or :remote (client). */
3221 QCaddress = is_server ? QClocal : QCremote;
3223 /* :nowait BOOL */
3224 if (!is_server && socktype != SOCK_DGRAM
3225 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3227 #ifndef NON_BLOCKING_CONNECT
3228 error ("Non-blocking connect not supported");
3229 #else
3230 is_non_blocking_client = 1;
3231 #endif
3234 name = Fplist_get (contact, QCname);
3235 buffer = Fplist_get (contact, QCbuffer);
3236 filter = Fplist_get (contact, QCfilter);
3237 sentinel = Fplist_get (contact, QCsentinel);
3239 CHECK_STRING (name);
3241 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3242 ai.ai_socktype = socktype;
3243 ai.ai_protocol = 0;
3244 ai.ai_next = NULL;
3245 res = &ai;
3247 /* :local ADDRESS or :remote ADDRESS */
3248 address = Fplist_get (contact, QCaddress);
3249 if (!NILP (address))
3251 host = service = Qnil;
3253 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3254 error ("Malformed :address");
3255 ai.ai_family = family;
3256 ai.ai_addr = alloca (ai.ai_addrlen);
3257 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3258 goto open_socket;
3261 /* :family FAMILY -- nil (for Inet), local, or integer. */
3262 tem = Fplist_get (contact, QCfamily);
3263 if (NILP (tem))
3265 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3266 family = AF_UNSPEC;
3267 #else
3268 family = AF_INET;
3269 #endif
3271 #ifdef HAVE_LOCAL_SOCKETS
3272 else if (EQ (tem, Qlocal))
3273 family = AF_LOCAL;
3274 #endif
3275 #ifdef AF_INET6
3276 else if (EQ (tem, Qipv6))
3277 family = AF_INET6;
3278 #endif
3279 else if (EQ (tem, Qipv4))
3280 family = AF_INET;
3281 else if (INTEGERP (tem))
3282 family = XINT (tem);
3283 else
3284 error ("Unknown address family");
3286 ai.ai_family = family;
3288 /* :service SERVICE -- string, integer (port number), or t (random port). */
3289 service = Fplist_get (contact, QCservice);
3291 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3292 host = Fplist_get (contact, QChost);
3293 if (!NILP (host))
3295 if (EQ (host, Qlocal))
3296 host = build_string ("localhost");
3297 CHECK_STRING (host);
3300 #ifdef HAVE_LOCAL_SOCKETS
3301 if (family == AF_LOCAL)
3303 if (!NILP (host))
3305 message (":family local ignores the :host \"%s\" property",
3306 SDATA (host));
3307 contact = Fplist_put (contact, QChost, Qnil);
3308 host = Qnil;
3310 CHECK_STRING (service);
3311 memset (&address_un, 0, sizeof address_un);
3312 address_un.sun_family = AF_LOCAL;
3313 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3314 ai.ai_addr = (struct sockaddr *) &address_un;
3315 ai.ai_addrlen = sizeof address_un;
3316 goto open_socket;
3318 #endif
3320 /* Slow down polling to every ten seconds.
3321 Some kernels have a bug which causes retrying connect to fail
3322 after a connect. Polling can interfere with gethostbyname too. */
3323 #ifdef POLL_FOR_INPUT
3324 if (socktype != SOCK_DGRAM)
3326 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3327 bind_polling_period (10);
3329 #endif
3331 #ifdef HAVE_GETADDRINFO
3332 /* If we have a host, use getaddrinfo to resolve both host and service.
3333 Otherwise, use getservbyname to lookup the service. */
3334 if (!NILP (host))
3337 /* SERVICE can either be a string or int.
3338 Convert to a C string for later use by getaddrinfo. */
3339 if (EQ (service, Qt))
3340 portstring = "0";
3341 else if (INTEGERP (service))
3343 sprintf (portbuf, "%ld", (long) XINT (service));
3344 portstring = portbuf;
3346 else
3348 CHECK_STRING (service);
3349 portstring = SDATA (service);
3352 immediate_quit = 1;
3353 QUIT;
3354 memset (&hints, 0, sizeof (hints));
3355 hints.ai_flags = 0;
3356 hints.ai_family = family;
3357 hints.ai_socktype = socktype;
3358 hints.ai_protocol = 0;
3360 #ifdef HAVE_RES_INIT
3361 res_init ();
3362 #endif
3364 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3365 if (ret)
3366 #ifdef HAVE_GAI_STRERROR
3367 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3368 #else
3369 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3370 #endif
3371 immediate_quit = 0;
3373 goto open_socket;
3375 #endif /* HAVE_GETADDRINFO */
3377 /* We end up here if getaddrinfo is not defined, or in case no hostname
3378 has been specified (e.g. for a local server process). */
3380 if (EQ (service, Qt))
3381 port = 0;
3382 else if (INTEGERP (service))
3383 port = htons ((unsigned short) XINT (service));
3384 else
3386 struct servent *svc_info;
3387 CHECK_STRING (service);
3388 svc_info = getservbyname (SDATA (service),
3389 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3390 if (svc_info == 0)
3391 error ("Unknown service: %s", SDATA (service));
3392 port = svc_info->s_port;
3395 memset (&address_in, 0, sizeof address_in);
3396 address_in.sin_family = family;
3397 address_in.sin_addr.s_addr = INADDR_ANY;
3398 address_in.sin_port = port;
3400 #ifndef HAVE_GETADDRINFO
3401 if (!NILP (host))
3403 struct hostent *host_info_ptr;
3405 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3406 as it may `hang' Emacs for a very long time. */
3407 immediate_quit = 1;
3408 QUIT;
3410 #ifdef HAVE_RES_INIT
3411 res_init ();
3412 #endif
3414 host_info_ptr = gethostbyname (SDATA (host));
3415 immediate_quit = 0;
3417 if (host_info_ptr)
3419 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3420 host_info_ptr->h_length);
3421 family = host_info_ptr->h_addrtype;
3422 address_in.sin_family = family;
3424 else
3425 /* Attempt to interpret host as numeric inet address */
3427 unsigned long numeric_addr;
3428 numeric_addr = inet_addr ((char *) SDATA (host));
3429 if (numeric_addr == -1)
3430 error ("Unknown host \"%s\"", SDATA (host));
3432 memcpy (&address_in.sin_addr, &numeric_addr,
3433 sizeof (address_in.sin_addr));
3437 #endif /* not HAVE_GETADDRINFO */
3439 ai.ai_family = family;
3440 ai.ai_addr = (struct sockaddr *) &address_in;
3441 ai.ai_addrlen = sizeof address_in;
3443 open_socket:
3445 /* Do this in case we never enter the for-loop below. */
3446 count1 = SPECPDL_INDEX ();
3447 s = -1;
3449 for (lres = res; lres; lres = lres->ai_next)
3451 int optn, optbits;
3453 retry_connect:
3455 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3456 if (s < 0)
3458 xerrno = errno;
3459 continue;
3462 #ifdef DATAGRAM_SOCKETS
3463 if (!is_server && socktype == SOCK_DGRAM)
3464 break;
3465 #endif /* DATAGRAM_SOCKETS */
3467 #ifdef NON_BLOCKING_CONNECT
3468 if (is_non_blocking_client)
3470 #ifdef O_NONBLOCK
3471 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3472 #else
3473 ret = fcntl (s, F_SETFL, O_NDELAY);
3474 #endif
3475 if (ret < 0)
3477 xerrno = errno;
3478 emacs_close (s);
3479 s = -1;
3480 continue;
3483 #endif
3485 /* Make us close S if quit. */
3486 record_unwind_protect (close_file_unwind, make_number (s));
3488 /* Parse network options in the arg list.
3489 We simply ignore anything which isn't a known option (including other keywords).
3490 An error is signaled if setting a known option fails. */
3491 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3492 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3494 if (is_server)
3496 /* Configure as a server socket. */
3498 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3499 explicit :reuseaddr key to override this. */
3500 #ifdef HAVE_LOCAL_SOCKETS
3501 if (family != AF_LOCAL)
3502 #endif
3503 if (!(optbits & (1 << OPIX_REUSEADDR)))
3505 int optval = 1;
3506 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3507 report_file_error ("Cannot set reuse option on server socket", Qnil);
3510 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3511 report_file_error ("Cannot bind server socket", Qnil);
3513 #ifdef HAVE_GETSOCKNAME
3514 if (EQ (service, Qt))
3516 struct sockaddr_in sa1;
3517 int len1 = sizeof (sa1);
3518 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3520 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3521 service = make_number (ntohs (sa1.sin_port));
3522 contact = Fplist_put (contact, QCservice, service);
3525 #endif
3527 if (socktype != SOCK_DGRAM && listen (s, backlog))
3528 report_file_error ("Cannot listen on server socket", Qnil);
3530 break;
3533 immediate_quit = 1;
3534 QUIT;
3536 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3537 xerrno = errno;
3539 if (ret == 0 || xerrno == EISCONN)
3541 /* The unwind-protect will be discarded afterwards.
3542 Likewise for immediate_quit. */
3543 break;
3546 #ifdef NON_BLOCKING_CONNECT
3547 #ifdef EINPROGRESS
3548 if (is_non_blocking_client && xerrno == EINPROGRESS)
3549 break;
3550 #else
3551 #ifdef EWOULDBLOCK
3552 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3553 break;
3554 #endif
3555 #endif
3556 #endif
3558 #ifndef WINDOWSNT
3559 if (xerrno == EINTR)
3561 /* Unlike most other syscalls connect() cannot be called
3562 again. (That would return EALREADY.) The proper way to
3563 wait for completion is select(). */
3564 int sc, len;
3565 SELECT_TYPE fdset;
3566 retry_select:
3567 FD_ZERO (&fdset);
3568 FD_SET (s, &fdset);
3569 QUIT;
3570 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3571 (EMACS_TIME *)0);
3572 if (sc == -1)
3574 if (errno == EINTR)
3575 goto retry_select;
3576 else
3577 report_file_error ("select failed", Qnil);
3579 eassert (sc > 0);
3581 len = sizeof xerrno;
3582 eassert (FD_ISSET (s, &fdset));
3583 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3584 report_file_error ("getsockopt failed", Qnil);
3585 if (xerrno)
3586 errno = xerrno, report_file_error ("error during connect", Qnil);
3587 else
3588 break;
3590 #endif /* !WINDOWSNT */
3592 immediate_quit = 0;
3594 /* Discard the unwind protect closing S. */
3595 specpdl_ptr = specpdl + count1;
3596 emacs_close (s);
3597 s = -1;
3599 #ifdef WINDOWSNT
3600 if (xerrno == EINTR)
3601 goto retry_connect;
3602 #endif
3605 if (s >= 0)
3607 #ifdef DATAGRAM_SOCKETS
3608 if (socktype == SOCK_DGRAM)
3610 if (datagram_address[s].sa)
3611 abort ();
3612 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3613 datagram_address[s].len = lres->ai_addrlen;
3614 if (is_server)
3616 Lisp_Object remote;
3617 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3618 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3620 int rfamily, rlen;
3621 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3622 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3623 conv_lisp_to_sockaddr (rfamily, remote,
3624 datagram_address[s].sa, rlen);
3627 else
3628 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3630 #endif
3631 contact = Fplist_put (contact, QCaddress,
3632 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3633 #ifdef HAVE_GETSOCKNAME
3634 if (!is_server)
3636 struct sockaddr_in sa1;
3637 int len1 = sizeof (sa1);
3638 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3639 contact = Fplist_put (contact, QClocal,
3640 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3642 #endif
3645 immediate_quit = 0;
3647 #ifdef HAVE_GETADDRINFO
3648 if (res != &ai)
3650 BLOCK_INPUT;
3651 freeaddrinfo (res);
3652 UNBLOCK_INPUT;
3654 #endif
3656 /* Discard the unwind protect for closing S, if any. */
3657 specpdl_ptr = specpdl + count1;
3659 /* Unwind bind_polling_period and request_sigio. */
3660 unbind_to (count, Qnil);
3662 if (s < 0)
3664 /* If non-blocking got this far - and failed - assume non-blocking is
3665 not supported after all. This is probably a wrong assumption, but
3666 the normal blocking calls to open-network-stream handles this error
3667 better. */
3668 if (is_non_blocking_client)
3669 return Qnil;
3671 errno = xerrno;
3672 if (is_server)
3673 report_file_error ("make server process failed", contact);
3674 else
3675 report_file_error ("make client process failed", contact);
3678 inch = s;
3679 outch = s;
3681 if (!NILP (buffer))
3682 buffer = Fget_buffer_create (buffer);
3683 proc = make_process (name);
3685 chan_process[inch] = proc;
3687 #ifdef O_NONBLOCK
3688 fcntl (inch, F_SETFL, O_NONBLOCK);
3689 #else
3690 #ifdef O_NDELAY
3691 fcntl (inch, F_SETFL, O_NDELAY);
3692 #endif
3693 #endif
3695 p = XPROCESS (proc);
3697 p->childp = contact;
3698 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3699 p->type = Qnetwork;
3701 p->buffer = buffer;
3702 p->sentinel = sentinel;
3703 p->filter = filter;
3704 p->log = Fplist_get (contact, QClog);
3705 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3706 p->kill_without_query = 1;
3707 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3708 p->command = Qt;
3709 p->pid = 0;
3710 p->infd = inch;
3711 p->outfd = outch;
3712 if (is_server && socktype != SOCK_DGRAM)
3713 p->status = Qlisten;
3715 /* Make the process marker point into the process buffer (if any). */
3716 if (BUFFERP (buffer))
3717 set_marker_both (p->mark, buffer,
3718 BUF_ZV (XBUFFER (buffer)),
3719 BUF_ZV_BYTE (XBUFFER (buffer)));
3721 #ifdef NON_BLOCKING_CONNECT
3722 if (is_non_blocking_client)
3724 /* We may get here if connect did succeed immediately. However,
3725 in that case, we still need to signal this like a non-blocking
3726 connection. */
3727 p->status = Qconnect;
3728 if (!FD_ISSET (inch, &connect_wait_mask))
3730 FD_SET (inch, &connect_wait_mask);
3731 num_pending_connects++;
3734 else
3735 #endif
3736 /* A server may have a client filter setting of Qt, but it must
3737 still listen for incoming connects unless it is stopped. */
3738 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3739 || (EQ (p->status, Qlisten) && NILP (p->command)))
3741 FD_SET (inch, &input_wait_mask);
3742 FD_SET (inch, &non_keyboard_wait_mask);
3745 if (inch > max_process_desc)
3746 max_process_desc = inch;
3748 tem = Fplist_member (contact, QCcoding);
3749 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3750 tem = Qnil; /* No error message (too late!). */
3753 /* Setup coding systems for communicating with the network stream. */
3754 struct gcpro gcpro1;
3755 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3756 Lisp_Object coding_systems = Qt;
3757 Lisp_Object args[5], val;
3759 if (!NILP (tem))
3761 val = XCAR (XCDR (tem));
3762 if (CONSP (val))
3763 val = XCAR (val);
3765 else if (!NILP (Vcoding_system_for_read))
3766 val = Vcoding_system_for_read;
3767 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3768 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3769 /* We dare not decode end-of-line format by setting VAL to
3770 Qraw_text, because the existing Emacs Lisp libraries
3771 assume that they receive bare code including a sequene of
3772 CR LF. */
3773 val = Qnil;
3774 else
3776 if (NILP (host) || NILP (service))
3777 coding_systems = Qnil;
3778 else
3780 args[0] = Qopen_network_stream, args[1] = name,
3781 args[2] = buffer, args[3] = host, args[4] = service;
3782 GCPRO1 (proc);
3783 coding_systems = Ffind_operation_coding_system (5, args);
3784 UNGCPRO;
3786 if (CONSP (coding_systems))
3787 val = XCAR (coding_systems);
3788 else if (CONSP (Vdefault_process_coding_system))
3789 val = XCAR (Vdefault_process_coding_system);
3790 else
3791 val = Qnil;
3793 p->decode_coding_system = val;
3795 if (!NILP (tem))
3797 val = XCAR (XCDR (tem));
3798 if (CONSP (val))
3799 val = XCDR (val);
3801 else if (!NILP (Vcoding_system_for_write))
3802 val = Vcoding_system_for_write;
3803 else if (NILP (current_buffer->enable_multibyte_characters))
3804 val = Qnil;
3805 else
3807 if (EQ (coding_systems, Qt))
3809 if (NILP (host) || NILP (service))
3810 coding_systems = Qnil;
3811 else
3813 args[0] = Qopen_network_stream, args[1] = name,
3814 args[2] = buffer, args[3] = host, args[4] = service;
3815 GCPRO1 (proc);
3816 coding_systems = Ffind_operation_coding_system (5, args);
3817 UNGCPRO;
3820 if (CONSP (coding_systems))
3821 val = XCDR (coding_systems);
3822 else if (CONSP (Vdefault_process_coding_system))
3823 val = XCDR (Vdefault_process_coding_system);
3824 else
3825 val = Qnil;
3827 p->encode_coding_system = val;
3829 setup_process_coding_systems (proc);
3831 p->decoding_buf = make_uninit_string (0);
3832 p->decoding_carryover = 0;
3833 p->encoding_buf = make_uninit_string (0);
3835 p->inherit_coding_system_flag
3836 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3838 UNGCPRO;
3839 return proc;
3841 #endif /* HAVE_SOCKETS */
3844 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3846 #ifdef SIOCGIFCONF
3847 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3848 doc: /* Return an alist of all network interfaces and their network address.
3849 Each element is a cons, the car of which is a string containing the
3850 interface name, and the cdr is the network address in internal
3851 format; see the description of ADDRESS in `make-network-process'. */)
3852 (void)
3854 struct ifconf ifconf;
3855 struct ifreq *ifreqs = NULL;
3856 int ifaces = 0;
3857 int buf_size, s;
3858 Lisp_Object res;
3860 s = socket (AF_INET, SOCK_STREAM, 0);
3861 if (s < 0)
3862 return Qnil;
3864 again:
3865 ifaces += 25;
3866 buf_size = ifaces * sizeof (ifreqs[0]);
3867 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3868 if (!ifreqs)
3870 close (s);
3871 return Qnil;
3874 ifconf.ifc_len = buf_size;
3875 ifconf.ifc_req = ifreqs;
3876 if (ioctl (s, SIOCGIFCONF, &ifconf))
3878 close (s);
3879 return Qnil;
3882 if (ifconf.ifc_len == buf_size)
3883 goto again;
3885 close (s);
3886 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3888 res = Qnil;
3889 while (--ifaces >= 0)
3891 struct ifreq *ifq = &ifreqs[ifaces];
3892 char namebuf[sizeof (ifq->ifr_name) + 1];
3893 if (ifq->ifr_addr.sa_family != AF_INET)
3894 continue;
3895 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3896 namebuf[sizeof (ifq->ifr_name)] = 0;
3897 res = Fcons (Fcons (build_string (namebuf),
3898 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3899 sizeof (struct sockaddr))),
3900 res);
3903 return res;
3905 #endif /* SIOCGIFCONF */
3907 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3909 struct ifflag_def {
3910 int flag_bit;
3911 const char *flag_sym;
3914 static const struct ifflag_def ifflag_table[] = {
3915 #ifdef IFF_UP
3916 { IFF_UP, "up" },
3917 #endif
3918 #ifdef IFF_BROADCAST
3919 { IFF_BROADCAST, "broadcast" },
3920 #endif
3921 #ifdef IFF_DEBUG
3922 { IFF_DEBUG, "debug" },
3923 #endif
3924 #ifdef IFF_LOOPBACK
3925 { IFF_LOOPBACK, "loopback" },
3926 #endif
3927 #ifdef IFF_POINTOPOINT
3928 { IFF_POINTOPOINT, "pointopoint" },
3929 #endif
3930 #ifdef IFF_RUNNING
3931 { IFF_RUNNING, "running" },
3932 #endif
3933 #ifdef IFF_NOARP
3934 { IFF_NOARP, "noarp" },
3935 #endif
3936 #ifdef IFF_PROMISC
3937 { IFF_PROMISC, "promisc" },
3938 #endif
3939 #ifdef IFF_NOTRAILERS
3940 { IFF_NOTRAILERS, "notrailers" },
3941 #endif
3942 #ifdef IFF_ALLMULTI
3943 { IFF_ALLMULTI, "allmulti" },
3944 #endif
3945 #ifdef IFF_MASTER
3946 { IFF_MASTER, "master" },
3947 #endif
3948 #ifdef IFF_SLAVE
3949 { IFF_SLAVE, "slave" },
3950 #endif
3951 #ifdef IFF_MULTICAST
3952 { IFF_MULTICAST, "multicast" },
3953 #endif
3954 #ifdef IFF_PORTSEL
3955 { IFF_PORTSEL, "portsel" },
3956 #endif
3957 #ifdef IFF_AUTOMEDIA
3958 { IFF_AUTOMEDIA, "automedia" },
3959 #endif
3960 #ifdef IFF_DYNAMIC
3961 { IFF_DYNAMIC, "dynamic" },
3962 #endif
3963 #ifdef IFF_OACTIVE
3964 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3965 #endif
3966 #ifdef IFF_SIMPLEX
3967 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3968 #endif
3969 #ifdef IFF_LINK0
3970 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3971 #endif
3972 #ifdef IFF_LINK1
3973 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3974 #endif
3975 #ifdef IFF_LINK2
3976 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3977 #endif
3978 { 0, 0 }
3981 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3982 doc: /* Return information about network interface named IFNAME.
3983 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3984 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3985 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3986 FLAGS is the current flags of the interface. */)
3987 (Lisp_Object ifname)
3989 struct ifreq rq;
3990 Lisp_Object res = Qnil;
3991 Lisp_Object elt;
3992 int s;
3993 int any = 0;
3995 CHECK_STRING (ifname);
3997 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3998 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
4000 s = socket (AF_INET, SOCK_STREAM, 0);
4001 if (s < 0)
4002 return Qnil;
4004 elt = Qnil;
4005 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
4006 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4008 int flags = rq.ifr_flags;
4009 const struct ifflag_def *fp;
4010 int fnum;
4012 any++;
4013 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4015 if (flags & fp->flag_bit)
4017 elt = Fcons (intern (fp->flag_sym), elt);
4018 flags -= fp->flag_bit;
4021 for (fnum = 0; flags && fnum < 32; fnum++)
4023 if (flags & (1 << fnum))
4025 elt = Fcons (make_number (fnum), elt);
4029 #endif
4030 res = Fcons (elt, res);
4032 elt = Qnil;
4033 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4034 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4036 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4037 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4038 int n;
4040 any++;
4041 for (n = 0; n < 6; n++)
4042 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4043 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4045 #endif
4046 res = Fcons (elt, res);
4048 elt = Qnil;
4049 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4050 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4052 any++;
4053 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4054 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4055 #else
4056 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4057 #endif
4059 #endif
4060 res = Fcons (elt, res);
4062 elt = Qnil;
4063 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4064 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4066 any++;
4067 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4069 #endif
4070 res = Fcons (elt, res);
4072 elt = Qnil;
4073 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4074 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4076 any++;
4077 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4079 #endif
4080 res = Fcons (elt, res);
4082 close (s);
4084 return any ? res : Qnil;
4086 #endif
4087 #endif /* HAVE_SOCKETS */
4089 /* Turn off input and output for process PROC. */
4091 void
4092 deactivate_process (Lisp_Object proc)
4094 register int inchannel, outchannel;
4095 register struct Lisp_Process *p = XPROCESS (proc);
4097 inchannel = p->infd;
4098 outchannel = p->outfd;
4100 #ifdef ADAPTIVE_READ_BUFFERING
4101 if (p->read_output_delay > 0)
4103 if (--process_output_delay_count < 0)
4104 process_output_delay_count = 0;
4105 p->read_output_delay = 0;
4106 p->read_output_skip = 0;
4108 #endif
4110 if (inchannel >= 0)
4112 /* Beware SIGCHLD hereabouts. */
4113 flush_pending_output (inchannel);
4114 emacs_close (inchannel);
4115 if (outchannel >= 0 && outchannel != inchannel)
4116 emacs_close (outchannel);
4118 p->infd = -1;
4119 p->outfd = -1;
4120 #ifdef DATAGRAM_SOCKETS
4121 if (DATAGRAM_CHAN_P (inchannel))
4123 xfree (datagram_address[inchannel].sa);
4124 datagram_address[inchannel].sa = 0;
4125 datagram_address[inchannel].len = 0;
4127 #endif
4128 chan_process[inchannel] = Qnil;
4129 FD_CLR (inchannel, &input_wait_mask);
4130 FD_CLR (inchannel, &non_keyboard_wait_mask);
4131 #ifdef NON_BLOCKING_CONNECT
4132 if (FD_ISSET (inchannel, &connect_wait_mask))
4134 FD_CLR (inchannel, &connect_wait_mask);
4135 if (--num_pending_connects < 0)
4136 abort ();
4138 #endif
4139 if (inchannel == max_process_desc)
4141 int i;
4142 /* We just closed the highest-numbered process input descriptor,
4143 so recompute the highest-numbered one now. */
4144 max_process_desc = 0;
4145 for (i = 0; i < MAXDESC; i++)
4146 if (!NILP (chan_process[i]))
4147 max_process_desc = i;
4152 /* Close all descriptors currently in use for communication
4153 with subprocess. This is used in a newly-forked subprocess
4154 to get rid of irrelevant descriptors. */
4156 void
4157 close_process_descs (void)
4159 #ifndef WINDOWSNT
4160 int i;
4161 for (i = 0; i < MAXDESC; i++)
4163 Lisp_Object process;
4164 process = chan_process[i];
4165 if (!NILP (process))
4167 int in = XPROCESS (process)->infd;
4168 int out = XPROCESS (process)->outfd;
4169 if (in >= 0)
4170 emacs_close (in);
4171 if (out >= 0 && in != out)
4172 emacs_close (out);
4175 #endif
4178 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4179 0, 4, 0,
4180 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4181 It is read into the process' buffers or given to their filter functions.
4182 Non-nil arg PROCESS means do not return until some output has been received
4183 from PROCESS.
4185 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4186 and milliseconds to wait; return after that much time whether or not
4187 there is any subprocess output. If SECONDS is a floating point number,
4188 it specifies a fractional number of seconds to wait.
4189 The MILLISEC argument is obsolete and should be avoided.
4191 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4192 from PROCESS, suspending reading output from other processes.
4193 If JUST-THIS-ONE is an integer, don't run any timers either.
4194 Return non-nil if we received any output before the timeout expired. */)
4195 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4197 int secs, usecs = 0;
4199 if (! NILP (process))
4200 CHECK_PROCESS (process);
4201 else
4202 just_this_one = Qnil;
4204 if (!NILP (millisec))
4205 { /* Obsolete calling convention using integers rather than floats. */
4206 CHECK_NUMBER (millisec);
4207 if (NILP (seconds))
4208 seconds = make_float (XINT (millisec) / 1000.0);
4209 else
4211 CHECK_NUMBER (seconds);
4212 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4216 if (!NILP (seconds))
4218 if (INTEGERP (seconds))
4219 secs = XINT (seconds);
4220 else if (FLOATP (seconds))
4222 double timeout = XFLOAT_DATA (seconds);
4223 secs = (int) timeout;
4224 usecs = (int) ((timeout - (double) secs) * 1000000);
4226 else
4227 wrong_type_argument (Qnumberp, seconds);
4229 if (secs < 0 || (secs == 0 && usecs == 0))
4230 secs = -1, usecs = 0;
4232 else
4233 secs = NILP (process) ? -1 : 0;
4235 return
4236 (wait_reading_process_output (secs, usecs, 0, 0,
4237 Qnil,
4238 !NILP (process) ? XPROCESS (process) : NULL,
4239 NILP (just_this_one) ? 0 :
4240 !INTEGERP (just_this_one) ? 1 : -1)
4241 ? Qt : Qnil);
4244 /* Accept a connection for server process SERVER on CHANNEL. */
4246 static int connect_counter = 0;
4248 static void
4249 server_accept_connection (Lisp_Object server, int channel)
4251 Lisp_Object proc, caller, name, buffer;
4252 Lisp_Object contact, host, service;
4253 struct Lisp_Process *ps= XPROCESS (server);
4254 struct Lisp_Process *p;
4255 int s;
4256 union u_sockaddr {
4257 struct sockaddr sa;
4258 struct sockaddr_in in;
4259 #ifdef AF_INET6
4260 struct sockaddr_in6 in6;
4261 #endif
4262 #ifdef HAVE_LOCAL_SOCKETS
4263 struct sockaddr_un un;
4264 #endif
4265 } saddr;
4266 int len = sizeof saddr;
4268 s = accept (channel, &saddr.sa, &len);
4270 if (s < 0)
4272 int code = errno;
4274 if (code == EAGAIN)
4275 return;
4276 #ifdef EWOULDBLOCK
4277 if (code == EWOULDBLOCK)
4278 return;
4279 #endif
4281 if (!NILP (ps->log))
4282 call3 (ps->log, server, Qnil,
4283 concat3 (build_string ("accept failed with code"),
4284 Fnumber_to_string (make_number (code)),
4285 build_string ("\n")));
4286 return;
4289 connect_counter++;
4291 /* Setup a new process to handle the connection. */
4293 /* Generate a unique identification of the caller, and build contact
4294 information for this process. */
4295 host = Qt;
4296 service = Qnil;
4297 switch (saddr.sa.sa_family)
4299 case AF_INET:
4301 Lisp_Object args[5];
4302 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4303 args[0] = build_string ("%d.%d.%d.%d");
4304 args[1] = make_number (*ip++);
4305 args[2] = make_number (*ip++);
4306 args[3] = make_number (*ip++);
4307 args[4] = make_number (*ip++);
4308 host = Fformat (5, args);
4309 service = make_number (ntohs (saddr.in.sin_port));
4311 args[0] = build_string (" <%s:%d>");
4312 args[1] = host;
4313 args[2] = service;
4314 caller = Fformat (3, args);
4316 break;
4318 #ifdef AF_INET6
4319 case AF_INET6:
4321 Lisp_Object args[9];
4322 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4323 int i;
4324 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4325 for (i = 0; i < 8; i++)
4326 args[i+1] = make_number (ntohs (ip6[i]));
4327 host = Fformat (9, args);
4328 service = make_number (ntohs (saddr.in.sin_port));
4330 args[0] = build_string (" <[%s]:%d>");
4331 args[1] = host;
4332 args[2] = service;
4333 caller = Fformat (3, args);
4335 break;
4336 #endif
4338 #ifdef HAVE_LOCAL_SOCKETS
4339 case AF_LOCAL:
4340 #endif
4341 default:
4342 caller = Fnumber_to_string (make_number (connect_counter));
4343 caller = concat3 (build_string (" <"), caller, build_string (">"));
4344 break;
4347 /* Create a new buffer name for this process if it doesn't have a
4348 filter. The new buffer name is based on the buffer name or
4349 process name of the server process concatenated with the caller
4350 identification. */
4352 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4353 buffer = Qnil;
4354 else
4356 buffer = ps->buffer;
4357 if (!NILP (buffer))
4358 buffer = Fbuffer_name (buffer);
4359 else
4360 buffer = ps->name;
4361 if (!NILP (buffer))
4363 buffer = concat2 (buffer, caller);
4364 buffer = Fget_buffer_create (buffer);
4368 /* Generate a unique name for the new server process. Combine the
4369 server process name with the caller identification. */
4371 name = concat2 (ps->name, caller);
4372 proc = make_process (name);
4374 chan_process[s] = proc;
4376 #ifdef O_NONBLOCK
4377 fcntl (s, F_SETFL, O_NONBLOCK);
4378 #else
4379 #ifdef O_NDELAY
4380 fcntl (s, F_SETFL, O_NDELAY);
4381 #endif
4382 #endif
4384 p = XPROCESS (proc);
4386 /* Build new contact information for this setup. */
4387 contact = Fcopy_sequence (ps->childp);
4388 contact = Fplist_put (contact, QCserver, Qnil);
4389 contact = Fplist_put (contact, QChost, host);
4390 if (!NILP (service))
4391 contact = Fplist_put (contact, QCservice, service);
4392 contact = Fplist_put (contact, QCremote,
4393 conv_sockaddr_to_lisp (&saddr.sa, len));
4394 #ifdef HAVE_GETSOCKNAME
4395 len = sizeof saddr;
4396 if (getsockname (s, &saddr.sa, &len) == 0)
4397 contact = Fplist_put (contact, QClocal,
4398 conv_sockaddr_to_lisp (&saddr.sa, len));
4399 #endif
4401 p->childp = contact;
4402 p->plist = Fcopy_sequence (ps->plist);
4403 p->type = Qnetwork;
4405 p->buffer = buffer;
4406 p->sentinel = ps->sentinel;
4407 p->filter = ps->filter;
4408 p->command = Qnil;
4409 p->pid = 0;
4410 p->infd = s;
4411 p->outfd = s;
4412 p->status = Qrun;
4414 /* Client processes for accepted connections are not stopped initially. */
4415 if (!EQ (p->filter, Qt))
4417 FD_SET (s, &input_wait_mask);
4418 FD_SET (s, &non_keyboard_wait_mask);
4421 if (s > max_process_desc)
4422 max_process_desc = s;
4424 /* Setup coding system for new process based on server process.
4425 This seems to be the proper thing to do, as the coding system
4426 of the new process should reflect the settings at the time the
4427 server socket was opened; not the current settings. */
4429 p->decode_coding_system = ps->decode_coding_system;
4430 p->encode_coding_system = ps->encode_coding_system;
4431 setup_process_coding_systems (proc);
4433 p->decoding_buf = make_uninit_string (0);
4434 p->decoding_carryover = 0;
4435 p->encoding_buf = make_uninit_string (0);
4437 p->inherit_coding_system_flag
4438 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4440 if (!NILP (ps->log))
4441 call3 (ps->log, server, proc,
4442 concat3 (build_string ("accept from "),
4443 (STRINGP (host) ? host : build_string ("-")),
4444 build_string ("\n")));
4446 if (!NILP (p->sentinel))
4447 exec_sentinel (proc,
4448 concat3 (build_string ("open from "),
4449 (STRINGP (host) ? host : build_string ("-")),
4450 build_string ("\n")));
4453 /* This variable is different from waiting_for_input in keyboard.c.
4454 It is used to communicate to a lisp process-filter/sentinel (via the
4455 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4456 for user-input when that process-filter was called.
4457 waiting_for_input cannot be used as that is by definition 0 when
4458 lisp code is being evalled.
4459 This is also used in record_asynch_buffer_change.
4460 For that purpose, this must be 0
4461 when not inside wait_reading_process_output. */
4462 static int waiting_for_user_input_p;
4464 static Lisp_Object
4465 wait_reading_process_output_unwind (Lisp_Object data)
4467 waiting_for_user_input_p = XINT (data);
4468 return Qnil;
4471 /* This is here so breakpoints can be put on it. */
4472 static void
4473 wait_reading_process_output_1 (void)
4477 /* Use a wrapper around select to work around a bug in gdb 5.3.
4478 Normally, the wrapper is optimized away by inlining.
4480 If emacs is stopped inside select, the gdb backtrace doesn't
4481 show the function which called select, so it is practically
4482 impossible to step through wait_reading_process_output. */
4484 #ifndef select
4485 static INLINE int
4486 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4488 return select (n, rfd, wfd, xfd, tmo);
4490 #define select select_wrapper
4491 #endif
4493 /* Read and dispose of subprocess output while waiting for timeout to
4494 elapse and/or keyboard input to be available.
4496 TIME_LIMIT is:
4497 timeout in seconds, or
4498 zero for no limit, or
4499 -1 means gobble data immediately available but don't wait for any.
4501 MICROSECS is:
4502 an additional duration to wait, measured in microseconds.
4503 If this is nonzero and time_limit is 0, then the timeout
4504 consists of MICROSECS only.
4506 READ_KBD is a lisp value:
4507 0 to ignore keyboard input, or
4508 1 to return when input is available, or
4509 -1 meaning caller will actually read the input, so don't throw to
4510 the quit handler, or
4512 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4513 output that arrives.
4515 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4516 (and gobble terminal input into the buffer if any arrives).
4518 If WAIT_PROC is specified, wait until something arrives from that
4519 process. The return value is true if we read some input from
4520 that process.
4522 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4523 (suspending output from other processes). A negative value
4524 means don't run any timers either.
4526 If WAIT_PROC is specified, then the function returns true if we
4527 received input from that process before the timeout elapsed.
4528 Otherwise, return true if we received input from any process. */
4531 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4532 wait_for_cell, wait_proc, just_wait_proc)
4533 int time_limit, microsecs, read_kbd, do_display;
4534 Lisp_Object wait_for_cell;
4535 struct Lisp_Process *wait_proc;
4536 int just_wait_proc;
4538 register int channel, nfds;
4539 SELECT_TYPE Available;
4540 #ifdef NON_BLOCKING_CONNECT
4541 SELECT_TYPE Connecting;
4542 int check_connect;
4543 #endif
4544 int check_delay, no_avail;
4545 int xerrno;
4546 Lisp_Object proc;
4547 EMACS_TIME timeout, end_time;
4548 int wait_channel = -1;
4549 int got_some_input = 0;
4550 int count = SPECPDL_INDEX ();
4552 FD_ZERO (&Available);
4553 #ifdef NON_BLOCKING_CONNECT
4554 FD_ZERO (&Connecting);
4555 #endif
4557 if (time_limit == 0 && wait_proc && !NILP (Vinhibit_quit)
4558 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4559 message ("Blocking call to accept-process-output with quit inhibited!!");
4561 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4562 if (wait_proc != NULL)
4563 wait_channel = wait_proc->infd;
4565 record_unwind_protect (wait_reading_process_output_unwind,
4566 make_number (waiting_for_user_input_p));
4567 waiting_for_user_input_p = read_kbd;
4569 /* Since we may need to wait several times,
4570 compute the absolute time to return at. */
4571 if (time_limit || microsecs)
4573 EMACS_GET_TIME (end_time);
4574 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4575 EMACS_ADD_TIME (end_time, end_time, timeout);
4578 while (1)
4580 int timeout_reduced_for_timers = 0;
4582 /* If calling from keyboard input, do not quit
4583 since we want to return C-g as an input character.
4584 Otherwise, do pending quit if requested. */
4585 if (read_kbd >= 0)
4586 QUIT;
4587 #ifdef SYNC_INPUT
4588 else
4589 process_pending_signals ();
4590 #endif
4592 /* Exit now if the cell we're waiting for became non-nil. */
4593 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4594 break;
4596 /* Compute time from now till when time limit is up */
4597 /* Exit if already run out */
4598 if (time_limit == -1)
4600 /* -1 specified for timeout means
4601 gobble output available now
4602 but don't wait at all. */
4604 EMACS_SET_SECS_USECS (timeout, 0, 0);
4606 else if (time_limit || microsecs)
4608 EMACS_GET_TIME (timeout);
4609 EMACS_SUB_TIME (timeout, end_time, timeout);
4610 if (EMACS_TIME_NEG_P (timeout))
4611 break;
4613 else
4615 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4618 /* Normally we run timers here.
4619 But not if wait_for_cell; in those cases,
4620 the wait is supposed to be short,
4621 and those callers cannot handle running arbitrary Lisp code here. */
4622 if (NILP (wait_for_cell)
4623 && just_wait_proc >= 0)
4625 EMACS_TIME timer_delay;
4629 int old_timers_run = timers_run;
4630 struct buffer *old_buffer = current_buffer;
4631 Lisp_Object old_window = selected_window;
4633 timer_delay = timer_check (1);
4635 /* If a timer has run, this might have changed buffers
4636 an alike. Make read_key_sequence aware of that. */
4637 if (timers_run != old_timers_run
4638 && (old_buffer != current_buffer
4639 || !EQ (old_window, selected_window))
4640 && waiting_for_user_input_p == -1)
4641 record_asynch_buffer_change ();
4643 if (timers_run != old_timers_run && do_display)
4644 /* We must retry, since a timer may have requeued itself
4645 and that could alter the time_delay. */
4646 redisplay_preserve_echo_area (9);
4647 else
4648 break;
4650 while (!detect_input_pending ());
4652 /* If there is unread keyboard input, also return. */
4653 if (read_kbd != 0
4654 && requeued_events_pending_p ())
4655 break;
4657 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4659 EMACS_TIME difference;
4660 EMACS_SUB_TIME (difference, timer_delay, timeout);
4661 if (EMACS_TIME_NEG_P (difference))
4663 timeout = timer_delay;
4664 timeout_reduced_for_timers = 1;
4667 /* If time_limit is -1, we are not going to wait at all. */
4668 else if (time_limit != -1)
4670 /* This is so a breakpoint can be put here. */
4671 wait_reading_process_output_1 ();
4675 /* Cause C-g and alarm signals to take immediate action,
4676 and cause input available signals to zero out timeout.
4678 It is important that we do this before checking for process
4679 activity. If we get a SIGCHLD after the explicit checks for
4680 process activity, timeout is the only way we will know. */
4681 if (read_kbd < 0)
4682 set_waiting_for_input (&timeout);
4684 /* If status of something has changed, and no input is
4685 available, notify the user of the change right away. After
4686 this explicit check, we'll let the SIGCHLD handler zap
4687 timeout to get our attention. */
4688 if (update_tick != process_tick)
4690 SELECT_TYPE Atemp;
4691 #ifdef NON_BLOCKING_CONNECT
4692 SELECT_TYPE Ctemp;
4693 #endif
4695 if (kbd_on_hold_p ())
4696 FD_ZERO (&Atemp);
4697 else
4698 Atemp = input_wait_mask;
4699 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4701 EMACS_SET_SECS_USECS (timeout, 0, 0);
4702 if ((select (max (max (max_process_desc, max_keyboard_desc),
4703 max_gpm_desc) + 1,
4704 &Atemp,
4705 #ifdef NON_BLOCKING_CONNECT
4706 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4707 #else
4708 (SELECT_TYPE *)0,
4709 #endif
4710 (SELECT_TYPE *)0, &timeout)
4711 <= 0))
4713 /* It's okay for us to do this and then continue with
4714 the loop, since timeout has already been zeroed out. */
4715 clear_waiting_for_input ();
4716 status_notify (NULL);
4717 if (do_display) redisplay_preserve_echo_area (13);
4721 /* Don't wait for output from a non-running process. Just
4722 read whatever data has already been received. */
4723 if (wait_proc && wait_proc->raw_status_new)
4724 update_status (wait_proc);
4725 if (wait_proc
4726 && ! EQ (wait_proc->status, Qrun)
4727 && ! EQ (wait_proc->status, Qconnect))
4729 int nread, total_nread = 0;
4731 clear_waiting_for_input ();
4732 XSETPROCESS (proc, wait_proc);
4734 /* Read data from the process, until we exhaust it. */
4735 while (wait_proc->infd >= 0)
4737 nread = read_process_output (proc, wait_proc->infd);
4739 if (nread == 0)
4740 break;
4742 if (0 < nread)
4744 total_nread += nread;
4745 got_some_input = 1;
4747 #ifdef EIO
4748 else if (nread == -1 && EIO == errno)
4749 break;
4750 #endif
4751 #ifdef EAGAIN
4752 else if (nread == -1 && EAGAIN == errno)
4753 break;
4754 #endif
4755 #ifdef EWOULDBLOCK
4756 else if (nread == -1 && EWOULDBLOCK == errno)
4757 break;
4758 #endif
4760 if (total_nread > 0 && do_display)
4761 redisplay_preserve_echo_area (10);
4763 break;
4766 /* Wait till there is something to do */
4768 if (wait_proc && just_wait_proc)
4770 if (wait_proc->infd < 0) /* Terminated */
4771 break;
4772 FD_SET (wait_proc->infd, &Available);
4773 check_delay = 0;
4774 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4776 else if (!NILP (wait_for_cell))
4778 Available = non_process_wait_mask;
4779 check_delay = 0;
4780 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4782 else
4784 if (! read_kbd)
4785 Available = non_keyboard_wait_mask;
4786 else
4787 Available = input_wait_mask;
4788 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4789 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4792 /* If frame size has changed or the window is newly mapped,
4793 redisplay now, before we start to wait. There is a race
4794 condition here; if a SIGIO arrives between now and the select
4795 and indicates that a frame is trashed, the select may block
4796 displaying a trashed screen. */
4797 if (frame_garbaged && do_display)
4799 clear_waiting_for_input ();
4800 redisplay_preserve_echo_area (11);
4801 if (read_kbd < 0)
4802 set_waiting_for_input (&timeout);
4805 no_avail = 0;
4806 if (read_kbd && detect_input_pending ())
4808 nfds = 0;
4809 no_avail = 1;
4811 else
4813 #ifdef NON_BLOCKING_CONNECT
4814 if (check_connect)
4815 Connecting = connect_wait_mask;
4816 #endif
4818 #ifdef ADAPTIVE_READ_BUFFERING
4819 /* Set the timeout for adaptive read buffering if any
4820 process has non-zero read_output_skip and non-zero
4821 read_output_delay, and we are not reading output for a
4822 specific wait_channel. It is not executed if
4823 Vprocess_adaptive_read_buffering is nil. */
4824 if (process_output_skip && check_delay > 0)
4826 int usecs = EMACS_USECS (timeout);
4827 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4828 usecs = READ_OUTPUT_DELAY_MAX;
4829 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4831 proc = chan_process[channel];
4832 if (NILP (proc))
4833 continue;
4834 /* Find minimum non-zero read_output_delay among the
4835 processes with non-zero read_output_skip. */
4836 if (XPROCESS (proc)->read_output_delay > 0)
4838 check_delay--;
4839 if (!XPROCESS (proc)->read_output_skip)
4840 continue;
4841 FD_CLR (channel, &Available);
4842 XPROCESS (proc)->read_output_skip = 0;
4843 if (XPROCESS (proc)->read_output_delay < usecs)
4844 usecs = XPROCESS (proc)->read_output_delay;
4847 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4848 process_output_skip = 0;
4850 #endif
4851 #if defined (USE_GTK) || defined (HAVE_GCONF)
4852 nfds = xg_select
4853 #elif defined (HAVE_NS)
4854 nfds = ns_select
4855 #else
4856 nfds = select
4857 #endif
4858 (max (max (max_process_desc, max_keyboard_desc),
4859 max_gpm_desc) + 1,
4860 &Available,
4861 #ifdef NON_BLOCKING_CONNECT
4862 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4863 #else
4864 (SELECT_TYPE *)0,
4865 #endif
4866 (SELECT_TYPE *)0, &timeout);
4869 xerrno = errno;
4871 /* Make C-g and alarm signals set flags again */
4872 clear_waiting_for_input ();
4874 /* If we woke up due to SIGWINCH, actually change size now. */
4875 do_pending_window_change (0);
4877 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4878 /* We wanted the full specified time, so return now. */
4879 break;
4880 if (nfds < 0)
4882 if (xerrno == EINTR)
4883 no_avail = 1;
4884 else if (xerrno == EBADF)
4886 #ifdef AIX
4887 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4888 the child's closure of the pts gives the parent a SIGHUP, and
4889 the ptc file descriptor is automatically closed,
4890 yielding EBADF here or at select() call above.
4891 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4892 in m/ibmrt-aix.h), and here we just ignore the select error.
4893 Cleanup occurs c/o status_notify after SIGCLD. */
4894 no_avail = 1; /* Cannot depend on values returned */
4895 #else
4896 abort ();
4897 #endif
4899 else
4900 error ("select error: %s", emacs_strerror (xerrno));
4903 if (no_avail)
4905 FD_ZERO (&Available);
4906 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4909 #if 0 /* When polling is used, interrupt_input is 0,
4910 so get_input_pending should read the input.
4911 So this should not be needed. */
4912 /* If we are using polling for input,
4913 and we see input available, make it get read now.
4914 Otherwise it might not actually get read for a second.
4915 And on hpux, since we turn off polling in wait_reading_process_output,
4916 it might never get read at all if we don't spend much time
4917 outside of wait_reading_process_output. */
4918 if (read_kbd && interrupt_input
4919 && keyboard_bit_set (&Available)
4920 && input_polling_used ())
4921 kill (getpid (), SIGALRM);
4922 #endif
4924 /* Check for keyboard input */
4925 /* If there is any, return immediately
4926 to give it higher priority than subprocesses */
4928 if (read_kbd != 0)
4930 int old_timers_run = timers_run;
4931 struct buffer *old_buffer = current_buffer;
4932 Lisp_Object old_window = selected_window;
4933 int leave = 0;
4935 if (detect_input_pending_run_timers (do_display))
4937 swallow_events (do_display);
4938 if (detect_input_pending_run_timers (do_display))
4939 leave = 1;
4942 /* If a timer has run, this might have changed buffers
4943 an alike. Make read_key_sequence aware of that. */
4944 if (timers_run != old_timers_run
4945 && waiting_for_user_input_p == -1
4946 && (old_buffer != current_buffer
4947 || !EQ (old_window, selected_window)))
4948 record_asynch_buffer_change ();
4950 if (leave)
4951 break;
4954 /* If there is unread keyboard input, also return. */
4955 if (read_kbd != 0
4956 && requeued_events_pending_p ())
4957 break;
4959 /* If we are not checking for keyboard input now,
4960 do process events (but don't run any timers).
4961 This is so that X events will be processed.
4962 Otherwise they may have to wait until polling takes place.
4963 That would causes delays in pasting selections, for example.
4965 (We used to do this only if wait_for_cell.) */
4966 if (read_kbd == 0 && detect_input_pending ())
4968 swallow_events (do_display);
4969 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4970 if (detect_input_pending ())
4971 break;
4972 #endif
4975 /* Exit now if the cell we're waiting for became non-nil. */
4976 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4977 break;
4979 #ifdef SIGIO
4980 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4981 go read it. This can happen with X on BSD after logging out.
4982 In that case, there really is no input and no SIGIO,
4983 but select says there is input. */
4985 if (read_kbd && interrupt_input
4986 && keyboard_bit_set (&Available) && ! noninteractive)
4987 kill (getpid (), SIGIO);
4988 #endif
4990 if (! wait_proc)
4991 got_some_input |= nfds > 0;
4993 /* If checking input just got us a size-change event from X,
4994 obey it now if we should. */
4995 if (read_kbd || ! NILP (wait_for_cell))
4996 do_pending_window_change (0);
4998 /* Check for data from a process. */
4999 if (no_avail || nfds == 0)
5000 continue;
5002 /* Really FIRST_PROC_DESC should be 0 on Unix,
5003 but this is safer in the short run. */
5004 for (channel = 0; channel <= max_process_desc; channel++)
5006 if (FD_ISSET (channel, &Available)
5007 && FD_ISSET (channel, &non_keyboard_wait_mask))
5009 int nread;
5011 /* If waiting for this channel, arrange to return as
5012 soon as no more input to be processed. No more
5013 waiting. */
5014 if (wait_channel == channel)
5016 wait_channel = -1;
5017 time_limit = -1;
5018 got_some_input = 1;
5020 proc = chan_process[channel];
5021 if (NILP (proc))
5022 continue;
5024 /* If this is a server stream socket, accept connection. */
5025 if (EQ (XPROCESS (proc)->status, Qlisten))
5027 server_accept_connection (proc, channel);
5028 continue;
5031 /* Read data from the process, starting with our
5032 buffered-ahead character if we have one. */
5034 nread = read_process_output (proc, channel);
5035 if (nread > 0)
5037 /* Since read_process_output can run a filter,
5038 which can call accept-process-output,
5039 don't try to read from any other processes
5040 before doing the select again. */
5041 FD_ZERO (&Available);
5043 if (do_display)
5044 redisplay_preserve_echo_area (12);
5046 #ifdef EWOULDBLOCK
5047 else if (nread == -1 && errno == EWOULDBLOCK)
5049 #endif
5050 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5051 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5052 #ifdef O_NONBLOCK
5053 else if (nread == -1 && errno == EAGAIN)
5055 #else
5056 #ifdef O_NDELAY
5057 else if (nread == -1 && errno == EAGAIN)
5059 /* Note that we cannot distinguish between no input
5060 available now and a closed pipe.
5061 With luck, a closed pipe will be accompanied by
5062 subprocess termination and SIGCHLD. */
5063 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5065 #endif /* O_NDELAY */
5066 #endif /* O_NONBLOCK */
5067 #ifdef HAVE_PTYS
5068 /* On some OSs with ptys, when the process on one end of
5069 a pty exits, the other end gets an error reading with
5070 errno = EIO instead of getting an EOF (0 bytes read).
5071 Therefore, if we get an error reading and errno =
5072 EIO, just continue, because the child process has
5073 exited and should clean itself up soon (e.g. when we
5074 get a SIGCHLD).
5076 However, it has been known to happen that the SIGCHLD
5077 got lost. So raise the signal again just in case.
5078 It can't hurt. */
5079 else if (nread == -1 && errno == EIO)
5081 /* Clear the descriptor now, so we only raise the
5082 signal once. Don't do this if `process' is only
5083 a pty. */
5084 if (XPROCESS (proc)->pid != -2)
5086 FD_CLR (channel, &input_wait_mask);
5087 FD_CLR (channel, &non_keyboard_wait_mask);
5089 kill (getpid (), SIGCHLD);
5092 #endif /* HAVE_PTYS */
5093 /* If we can detect process termination, don't consider the process
5094 gone just because its pipe is closed. */
5095 #ifdef SIGCHLD
5096 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5098 #endif
5099 else
5101 /* Preserve status of processes already terminated. */
5102 XPROCESS (proc)->tick = ++process_tick;
5103 deactivate_process (proc);
5104 if (XPROCESS (proc)->raw_status_new)
5105 update_status (XPROCESS (proc));
5106 if (EQ (XPROCESS (proc)->status, Qrun))
5107 XPROCESS (proc)->status
5108 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5111 #ifdef NON_BLOCKING_CONNECT
5112 if (check_connect && FD_ISSET (channel, &Connecting)
5113 && FD_ISSET (channel, &connect_wait_mask))
5115 struct Lisp_Process *p;
5117 FD_CLR (channel, &connect_wait_mask);
5118 if (--num_pending_connects < 0)
5119 abort ();
5121 proc = chan_process[channel];
5122 if (NILP (proc))
5123 continue;
5125 p = XPROCESS (proc);
5127 #ifdef GNU_LINUX
5128 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5129 So only use it on systems where it is known to work. */
5131 int xlen = sizeof (xerrno);
5132 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5133 xerrno = errno;
5135 #else
5137 struct sockaddr pname;
5138 int pnamelen = sizeof (pname);
5140 /* If connection failed, getpeername will fail. */
5141 xerrno = 0;
5142 if (getpeername (channel, &pname, &pnamelen) < 0)
5144 /* Obtain connect failure code through error slippage. */
5145 char dummy;
5146 xerrno = errno;
5147 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5148 xerrno = errno;
5151 #endif
5152 if (xerrno)
5154 p->tick = ++process_tick;
5155 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5156 deactivate_process (proc);
5158 else
5160 p->status = Qrun;
5161 /* Execute the sentinel here. If we had relied on
5162 status_notify to do it later, it will read input
5163 from the process before calling the sentinel. */
5164 exec_sentinel (proc, build_string ("open\n"));
5165 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5167 FD_SET (p->infd, &input_wait_mask);
5168 FD_SET (p->infd, &non_keyboard_wait_mask);
5172 #endif /* NON_BLOCKING_CONNECT */
5173 } /* end for each file descriptor */
5174 } /* end while exit conditions not met */
5176 unbind_to (count, Qnil);
5178 /* If calling from keyboard input, do not quit
5179 since we want to return C-g as an input character.
5180 Otherwise, do pending quit if requested. */
5181 if (read_kbd >= 0)
5183 /* Prevent input_pending from remaining set if we quit. */
5184 clear_input_pending ();
5185 QUIT;
5188 return got_some_input;
5191 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5193 static Lisp_Object
5194 read_process_output_call (Lisp_Object fun_and_args)
5196 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5199 static Lisp_Object
5200 read_process_output_error_handler (Lisp_Object error)
5202 cmd_error_internal (error, "error in process filter: ");
5203 Vinhibit_quit = Qt;
5204 update_echo_area ();
5205 Fsleep_for (make_number (2), Qnil);
5206 return Qt;
5209 /* Read pending output from the process channel,
5210 starting with our buffered-ahead character if we have one.
5211 Yield number of decoded characters read.
5213 This function reads at most 4096 characters.
5214 If you want to read all available subprocess output,
5215 you must call it repeatedly until it returns zero.
5217 The characters read are decoded according to PROC's coding-system
5218 for decoding. */
5220 static int
5221 read_process_output (Lisp_Object proc, register int channel)
5223 register int nbytes;
5224 char *chars;
5225 register Lisp_Object outstream;
5226 register struct Lisp_Process *p = XPROCESS (proc);
5227 register int opoint;
5228 struct coding_system *coding = proc_decode_coding_system[channel];
5229 int carryover = p->decoding_carryover;
5230 int readmax = 4096;
5231 int count = SPECPDL_INDEX ();
5232 Lisp_Object odeactivate;
5234 chars = (char *) alloca (carryover + readmax);
5235 if (carryover)
5236 /* See the comment above. */
5237 memcpy (chars, SDATA (p->decoding_buf), carryover);
5239 #ifdef DATAGRAM_SOCKETS
5240 /* We have a working select, so proc_buffered_char is always -1. */
5241 if (DATAGRAM_CHAN_P (channel))
5243 int len = datagram_address[channel].len;
5244 nbytes = recvfrom (channel, chars + carryover, readmax,
5245 0, datagram_address[channel].sa, &len);
5247 else
5248 #endif
5249 if (proc_buffered_char[channel] < 0)
5251 nbytes = emacs_read (channel, chars + carryover, readmax);
5252 #ifdef ADAPTIVE_READ_BUFFERING
5253 if (nbytes > 0 && p->adaptive_read_buffering)
5255 int delay = p->read_output_delay;
5256 if (nbytes < 256)
5258 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5260 if (delay == 0)
5261 process_output_delay_count++;
5262 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5265 else if (delay > 0 && (nbytes == readmax))
5267 delay -= READ_OUTPUT_DELAY_INCREMENT;
5268 if (delay == 0)
5269 process_output_delay_count--;
5271 p->read_output_delay = delay;
5272 if (delay)
5274 p->read_output_skip = 1;
5275 process_output_skip = 1;
5278 #endif
5280 else
5282 chars[carryover] = proc_buffered_char[channel];
5283 proc_buffered_char[channel] = -1;
5284 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5285 if (nbytes < 0)
5286 nbytes = 1;
5287 else
5288 nbytes = nbytes + 1;
5291 p->decoding_carryover = 0;
5293 /* At this point, NBYTES holds number of bytes just received
5294 (including the one in proc_buffered_char[channel]). */
5295 if (nbytes <= 0)
5297 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5298 return nbytes;
5299 coding->mode |= CODING_MODE_LAST_BLOCK;
5302 /* Now set NBYTES how many bytes we must decode. */
5303 nbytes += carryover;
5305 odeactivate = Vdeactivate_mark;
5306 /* There's no good reason to let process filters change the current
5307 buffer, and many callers of accept-process-output, sit-for, and
5308 friends don't expect current-buffer to be changed from under them. */
5309 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5311 /* Read and dispose of the process output. */
5312 outstream = p->filter;
5313 if (!NILP (outstream))
5315 Lisp_Object obuffer, okeymap;
5316 Lisp_Object text;
5317 int outer_running_asynch_code = running_asynch_code;
5318 int waiting = waiting_for_user_input_p;
5320 /* No need to gcpro these, because all we do with them later
5321 is test them for EQness, and none of them should be a string. */
5322 XSETBUFFER (obuffer, current_buffer);
5323 okeymap = current_buffer->keymap;
5325 /* We inhibit quit here instead of just catching it so that
5326 hitting ^G when a filter happens to be running won't screw
5327 it up. */
5328 specbind (Qinhibit_quit, Qt);
5329 specbind (Qlast_nonmenu_event, Qt);
5331 /* In case we get recursively called,
5332 and we already saved the match data nonrecursively,
5333 save the same match data in safely recursive fashion. */
5334 if (outer_running_asynch_code)
5336 Lisp_Object tem;
5337 /* Don't clobber the CURRENT match data, either! */
5338 tem = Fmatch_data (Qnil, Qnil, Qnil);
5339 restore_search_regs ();
5340 record_unwind_save_match_data ();
5341 Fset_match_data (tem, Qt);
5344 /* For speed, if a search happens within this code,
5345 save the match data in a special nonrecursive fashion. */
5346 running_asynch_code = 1;
5348 decode_coding_c_string (coding, chars, nbytes, Qt);
5349 text = coding->dst_object;
5350 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5351 /* A new coding system might be found. */
5352 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5354 p->decode_coding_system = Vlast_coding_system_used;
5356 /* Don't call setup_coding_system for
5357 proc_decode_coding_system[channel] here. It is done in
5358 detect_coding called via decode_coding above. */
5360 /* If a coding system for encoding is not yet decided, we set
5361 it as the same as coding-system for decoding.
5363 But, before doing that we must check if
5364 proc_encode_coding_system[p->outfd] surely points to a
5365 valid memory because p->outfd will be changed once EOF is
5366 sent to the process. */
5367 if (NILP (p->encode_coding_system)
5368 && proc_encode_coding_system[p->outfd])
5370 p->encode_coding_system
5371 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5372 setup_coding_system (p->encode_coding_system,
5373 proc_encode_coding_system[p->outfd]);
5377 if (coding->carryover_bytes > 0)
5379 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5380 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5381 memcpy (SDATA (p->decoding_buf), coding->carryover,
5382 coding->carryover_bytes);
5383 p->decoding_carryover = coding->carryover_bytes;
5385 if (SBYTES (text) > 0)
5386 internal_condition_case_1 (read_process_output_call,
5387 Fcons (outstream,
5388 Fcons (proc, Fcons (text, Qnil))),
5389 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5390 read_process_output_error_handler);
5392 /* If we saved the match data nonrecursively, restore it now. */
5393 restore_search_regs ();
5394 running_asynch_code = outer_running_asynch_code;
5396 /* Restore waiting_for_user_input_p as it was
5397 when we were called, in case the filter clobbered it. */
5398 waiting_for_user_input_p = waiting;
5400 #if 0 /* Call record_asynch_buffer_change unconditionally,
5401 because we might have changed minor modes or other things
5402 that affect key bindings. */
5403 if (! EQ (Fcurrent_buffer (), obuffer)
5404 || ! EQ (current_buffer->keymap, okeymap))
5405 #endif
5406 /* But do it only if the caller is actually going to read events.
5407 Otherwise there's no need to make him wake up, and it could
5408 cause trouble (for example it would make sit_for return). */
5409 if (waiting_for_user_input_p == -1)
5410 record_asynch_buffer_change ();
5413 /* If no filter, write into buffer if it isn't dead. */
5414 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5416 Lisp_Object old_read_only;
5417 int old_begv, old_zv;
5418 int old_begv_byte, old_zv_byte;
5419 int before, before_byte;
5420 int opoint_byte;
5421 Lisp_Object text;
5422 struct buffer *b;
5424 Fset_buffer (p->buffer);
5425 opoint = PT;
5426 opoint_byte = PT_BYTE;
5427 old_read_only = current_buffer->read_only;
5428 old_begv = BEGV;
5429 old_zv = ZV;
5430 old_begv_byte = BEGV_BYTE;
5431 old_zv_byte = ZV_BYTE;
5433 current_buffer->read_only = Qnil;
5435 /* Insert new output into buffer
5436 at the current end-of-output marker,
5437 thus preserving logical ordering of input and output. */
5438 if (XMARKER (p->mark)->buffer)
5439 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5440 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5441 ZV_BYTE));
5442 else
5443 SET_PT_BOTH (ZV, ZV_BYTE);
5444 before = PT;
5445 before_byte = PT_BYTE;
5447 /* If the output marker is outside of the visible region, save
5448 the restriction and widen. */
5449 if (! (BEGV <= PT && PT <= ZV))
5450 Fwiden ();
5452 decode_coding_c_string (coding, chars, nbytes, Qt);
5453 text = coding->dst_object;
5454 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5455 /* A new coding system might be found. See the comment in the
5456 similar code in the previous `if' block. */
5457 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5459 p->decode_coding_system = Vlast_coding_system_used;
5460 if (NILP (p->encode_coding_system)
5461 && proc_encode_coding_system[p->outfd])
5463 p->encode_coding_system
5464 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5465 setup_coding_system (p->encode_coding_system,
5466 proc_encode_coding_system[p->outfd]);
5469 if (coding->carryover_bytes > 0)
5471 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5472 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5473 memcpy (SDATA (p->decoding_buf), coding->carryover,
5474 coding->carryover_bytes);
5475 p->decoding_carryover = coding->carryover_bytes;
5477 /* Adjust the multibyteness of TEXT to that of the buffer. */
5478 if (NILP (current_buffer->enable_multibyte_characters)
5479 != ! STRING_MULTIBYTE (text))
5480 text = (STRING_MULTIBYTE (text)
5481 ? Fstring_as_unibyte (text)
5482 : Fstring_to_multibyte (text));
5483 /* Insert before markers in case we are inserting where
5484 the buffer's mark is, and the user's next command is Meta-y. */
5485 insert_from_string_before_markers (text, 0, 0,
5486 SCHARS (text), SBYTES (text), 0);
5488 /* Make sure the process marker's position is valid when the
5489 process buffer is changed in the signal_after_change above.
5490 W3 is known to do that. */
5491 if (BUFFERP (p->buffer)
5492 && (b = XBUFFER (p->buffer), b != current_buffer))
5493 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5494 else
5495 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5497 update_mode_lines++;
5499 /* Make sure opoint and the old restrictions
5500 float ahead of any new text just as point would. */
5501 if (opoint >= before)
5503 opoint += PT - before;
5504 opoint_byte += PT_BYTE - before_byte;
5506 if (old_begv > before)
5508 old_begv += PT - before;
5509 old_begv_byte += PT_BYTE - before_byte;
5511 if (old_zv >= before)
5513 old_zv += PT - before;
5514 old_zv_byte += PT_BYTE - before_byte;
5517 /* If the restriction isn't what it should be, set it. */
5518 if (old_begv != BEGV || old_zv != ZV)
5519 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5522 current_buffer->read_only = old_read_only;
5523 SET_PT_BOTH (opoint, opoint_byte);
5525 /* Handling the process output should not deactivate the mark. */
5526 Vdeactivate_mark = odeactivate;
5528 unbind_to (count, Qnil);
5529 return nbytes;
5532 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5533 0, 0, 0,
5534 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5535 This is intended for use by asynchronous process output filters and sentinels. */)
5536 (void)
5538 return (waiting_for_user_input_p ? Qt : Qnil);
5541 /* Sending data to subprocess */
5543 jmp_buf send_process_frame;
5544 Lisp_Object process_sent_to;
5546 SIGTYPE
5547 send_process_trap (int ignore)
5549 SIGNAL_THREAD_CHECK (SIGPIPE);
5550 sigunblock (sigmask (SIGPIPE));
5551 longjmp (send_process_frame, 1);
5554 /* Send some data to process PROC.
5555 BUF is the beginning of the data; LEN is the number of characters.
5556 OBJECT is the Lisp object that the data comes from. If OBJECT is
5557 nil or t, it means that the data comes from C string.
5559 If OBJECT is not nil, the data is encoded by PROC's coding-system
5560 for encoding before it is sent.
5562 This function can evaluate Lisp code and can garbage collect. */
5564 static void
5565 send_process (volatile Lisp_Object proc, unsigned char *volatile buf,
5566 volatile int len, volatile Lisp_Object object)
5568 /* Use volatile to protect variables from being clobbered by longjmp. */
5569 struct Lisp_Process *p = XPROCESS (proc);
5570 int rv;
5571 struct coding_system *coding;
5572 struct gcpro gcpro1;
5573 SIGTYPE (*volatile old_sigpipe) (int);
5575 GCPRO1 (object);
5577 if (p->raw_status_new)
5578 update_status (p);
5579 if (! EQ (p->status, Qrun))
5580 error ("Process %s not running", SDATA (p->name));
5581 if (p->outfd < 0)
5582 error ("Output file descriptor of %s is closed", SDATA (p->name));
5584 coding = proc_encode_coding_system[p->outfd];
5585 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5587 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5588 || (BUFFERP (object)
5589 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5590 || EQ (object, Qt))
5592 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5593 /* The coding system for encoding was changed to raw-text
5594 because we sent a unibyte text previously. Now we are
5595 sending a multibyte text, thus we must encode it by the
5596 original coding system specified for the current process. */
5597 setup_coding_system (p->encode_coding_system, coding);
5598 coding->src_multibyte = 1;
5600 else
5602 /* For sending a unibyte text, character code conversion should
5603 not take place but EOL conversion should. So, setup raw-text
5604 or one of the subsidiary if we have not yet done it. */
5605 if (CODING_REQUIRE_ENCODING (coding))
5607 if (CODING_REQUIRE_FLUSHING (coding))
5609 /* But, before changing the coding, we must flush out data. */
5610 coding->mode |= CODING_MODE_LAST_BLOCK;
5611 send_process (proc, "", 0, Qt);
5612 coding->mode &= CODING_MODE_LAST_BLOCK;
5614 setup_coding_system (raw_text_coding_system
5615 (Vlast_coding_system_used),
5616 coding);
5617 coding->src_multibyte = 0;
5620 coding->dst_multibyte = 0;
5622 if (CODING_REQUIRE_ENCODING (coding))
5624 coding->dst_object = Qt;
5625 if (BUFFERP (object))
5627 int from_byte, from, to;
5628 int save_pt, save_pt_byte;
5629 struct buffer *cur = current_buffer;
5631 set_buffer_internal (XBUFFER (object));
5632 save_pt = PT, save_pt_byte = PT_BYTE;
5634 from_byte = PTR_BYTE_POS (buf);
5635 from = BYTE_TO_CHAR (from_byte);
5636 to = BYTE_TO_CHAR (from_byte + len);
5637 TEMP_SET_PT_BOTH (from, from_byte);
5638 encode_coding_object (coding, object, from, from_byte,
5639 to, from_byte + len, Qt);
5640 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5641 set_buffer_internal (cur);
5643 else if (STRINGP (object))
5645 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5646 SBYTES (object), Qt);
5648 else
5650 coding->dst_object = make_unibyte_string (buf, len);
5651 coding->produced = len;
5654 len = coding->produced;
5655 object = coding->dst_object;
5656 buf = SDATA (object);
5659 if (pty_max_bytes == 0)
5661 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5662 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5663 if (pty_max_bytes < 0)
5664 pty_max_bytes = 250;
5665 #else
5666 pty_max_bytes = 250;
5667 #endif
5668 /* Deduct one, to leave space for the eof. */
5669 pty_max_bytes--;
5672 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5673 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5674 when returning with longjmp despite being declared volatile. */
5675 if (!setjmp (send_process_frame))
5677 process_sent_to = proc;
5678 while (len > 0)
5680 int this = len;
5682 /* Send this batch, using one or more write calls. */
5683 while (this > 0)
5685 int outfd = p->outfd;
5686 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5687 #ifdef DATAGRAM_SOCKETS
5688 if (DATAGRAM_CHAN_P (outfd))
5690 rv = sendto (outfd, (char *) buf, this,
5691 0, datagram_address[outfd].sa,
5692 datagram_address[outfd].len);
5693 if (rv < 0 && errno == EMSGSIZE)
5695 signal (SIGPIPE, old_sigpipe);
5696 report_file_error ("sending datagram",
5697 Fcons (proc, Qnil));
5700 else
5701 #endif
5703 rv = emacs_write (outfd, (char *) buf, this);
5704 #ifdef ADAPTIVE_READ_BUFFERING
5705 if (p->read_output_delay > 0
5706 && p->adaptive_read_buffering == 1)
5708 p->read_output_delay = 0;
5709 process_output_delay_count--;
5710 p->read_output_skip = 0;
5712 #endif
5714 signal (SIGPIPE, old_sigpipe);
5716 if (rv < 0)
5718 if (0
5719 #ifdef EWOULDBLOCK
5720 || errno == EWOULDBLOCK
5721 #endif
5722 #ifdef EAGAIN
5723 || errno == EAGAIN
5724 #endif
5726 /* Buffer is full. Wait, accepting input;
5727 that may allow the program
5728 to finish doing output and read more. */
5730 int offset = 0;
5732 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5733 /* A gross hack to work around a bug in FreeBSD.
5734 In the following sequence, read(2) returns
5735 bogus data:
5737 write(2) 1022 bytes
5738 write(2) 954 bytes, get EAGAIN
5739 read(2) 1024 bytes in process_read_output
5740 read(2) 11 bytes in process_read_output
5742 That is, read(2) returns more bytes than have
5743 ever been written successfully. The 1033 bytes
5744 read are the 1022 bytes written successfully
5745 after processing (for example with CRs added if
5746 the terminal is set up that way which it is
5747 here). The same bytes will be seen again in a
5748 later read(2), without the CRs. */
5750 if (errno == EAGAIN)
5752 int flags = FWRITE;
5753 ioctl (p->outfd, TIOCFLUSH, &flags);
5755 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5757 /* Running filters might relocate buffers or strings.
5758 Arrange to relocate BUF. */
5759 if (BUFFERP (object))
5760 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5761 else if (STRINGP (object))
5762 offset = buf - SDATA (object);
5764 #ifdef EMACS_HAS_USECS
5765 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5766 #else
5767 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5768 #endif
5770 if (BUFFERP (object))
5771 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5772 else if (STRINGP (object))
5773 buf = offset + SDATA (object);
5775 rv = 0;
5777 else
5778 /* This is a real error. */
5779 report_file_error ("writing to process", Fcons (proc, Qnil));
5781 buf += rv;
5782 len -= rv;
5783 this -= rv;
5787 else
5789 signal (SIGPIPE, old_sigpipe);
5790 proc = process_sent_to;
5791 p = XPROCESS (proc);
5792 p->raw_status_new = 0;
5793 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5794 p->tick = ++process_tick;
5795 deactivate_process (proc);
5796 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5799 UNGCPRO;
5802 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5803 3, 3, 0,
5804 doc: /* Send current contents of region as input to PROCESS.
5805 PROCESS may be a process, a buffer, the name of a process or buffer, or
5806 nil, indicating the current buffer's process.
5807 Called from program, takes three arguments, PROCESS, START and END.
5808 If the region is more than 500 characters long,
5809 it is sent in several bunches. This may happen even for shorter regions.
5810 Output from processes can arrive in between bunches. */)
5811 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5813 Lisp_Object proc;
5814 int start1, end1;
5816 proc = get_process (process);
5817 validate_region (&start, &end);
5819 if (XINT (start) < GPT && XINT (end) > GPT)
5820 move_gap (XINT (start));
5822 start1 = CHAR_TO_BYTE (XINT (start));
5823 end1 = CHAR_TO_BYTE (XINT (end));
5824 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5825 Fcurrent_buffer ());
5827 return Qnil;
5830 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5831 2, 2, 0,
5832 doc: /* Send PROCESS the contents of STRING as input.
5833 PROCESS may be a process, a buffer, the name of a process or buffer, or
5834 nil, indicating the current buffer's process.
5835 If STRING is more than 500 characters long,
5836 it is sent in several bunches. This may happen even for shorter strings.
5837 Output from processes can arrive in between bunches. */)
5838 (Lisp_Object process, Lisp_Object string)
5840 Lisp_Object proc;
5841 CHECK_STRING (string);
5842 proc = get_process (process);
5843 send_process (proc, SDATA (string),
5844 SBYTES (string), string);
5845 return Qnil;
5848 /* Return the foreground process group for the tty/pty that
5849 the process P uses. */
5850 static int
5851 emacs_get_tty_pgrp (struct Lisp_Process *p)
5853 int gid = -1;
5855 #ifdef TIOCGPGRP
5856 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5858 int fd;
5859 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5860 master side. Try the slave side. */
5861 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5863 if (fd != -1)
5865 ioctl (fd, TIOCGPGRP, &gid);
5866 emacs_close (fd);
5869 #endif /* defined (TIOCGPGRP ) */
5871 return gid;
5874 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5875 Sprocess_running_child_p, 0, 1, 0,
5876 doc: /* Return t if PROCESS has given the terminal to a child.
5877 If the operating system does not make it possible to find out,
5878 return t unconditionally. */)
5879 (Lisp_Object process)
5881 /* Initialize in case ioctl doesn't exist or gives an error,
5882 in a way that will cause returning t. */
5883 int gid;
5884 Lisp_Object proc;
5885 struct Lisp_Process *p;
5887 proc = get_process (process);
5888 p = XPROCESS (proc);
5890 if (!EQ (p->type, Qreal))
5891 error ("Process %s is not a subprocess",
5892 SDATA (p->name));
5893 if (p->infd < 0)
5894 error ("Process %s is not active",
5895 SDATA (p->name));
5897 gid = emacs_get_tty_pgrp (p);
5899 if (gid == p->pid)
5900 return Qnil;
5901 return Qt;
5904 /* send a signal number SIGNO to PROCESS.
5905 If CURRENT_GROUP is t, that means send to the process group
5906 that currently owns the terminal being used to communicate with PROCESS.
5907 This is used for various commands in shell mode.
5908 If CURRENT_GROUP is lambda, that means send to the process group
5909 that currently owns the terminal, but only if it is NOT the shell itself.
5911 If NOMSG is zero, insert signal-announcements into process's buffers
5912 right away.
5914 If we can, we try to signal PROCESS by sending control characters
5915 down the pty. This allows us to signal inferiors who have changed
5916 their uid, for which killpg would return an EPERM error. */
5918 static void
5919 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5920 int nomsg)
5922 Lisp_Object proc;
5923 register struct Lisp_Process *p;
5924 int gid;
5925 int no_pgrp = 0;
5927 proc = get_process (process);
5928 p = XPROCESS (proc);
5930 if (!EQ (p->type, Qreal))
5931 error ("Process %s is not a subprocess",
5932 SDATA (p->name));
5933 if (p->infd < 0)
5934 error ("Process %s is not active",
5935 SDATA (p->name));
5937 if (!p->pty_flag)
5938 current_group = Qnil;
5940 /* If we are using pgrps, get a pgrp number and make it negative. */
5941 if (NILP (current_group))
5942 /* Send the signal to the shell's process group. */
5943 gid = p->pid;
5944 else
5946 #ifdef SIGNALS_VIA_CHARACTERS
5947 /* If possible, send signals to the entire pgrp
5948 by sending an input character to it. */
5950 /* TERMIOS is the latest and bestest, and seems most likely to
5951 work. If the system has it, use it. */
5952 #ifdef HAVE_TERMIOS
5953 struct termios t;
5954 cc_t *sig_char = NULL;
5956 tcgetattr (p->infd, &t);
5958 switch (signo)
5960 case SIGINT:
5961 sig_char = &t.c_cc[VINTR];
5962 break;
5964 case SIGQUIT:
5965 sig_char = &t.c_cc[VQUIT];
5966 break;
5968 case SIGTSTP:
5969 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5970 sig_char = &t.c_cc[VSWTCH];
5971 #else
5972 sig_char = &t.c_cc[VSUSP];
5973 #endif
5974 break;
5977 if (sig_char && *sig_char != CDISABLE)
5979 send_process (proc, sig_char, 1, Qnil);
5980 return;
5982 /* If we can't send the signal with a character,
5983 fall through and send it another way. */
5984 #else /* ! HAVE_TERMIOS */
5986 /* On Berkeley descendants, the following IOCTL's retrieve the
5987 current control characters. */
5988 #if defined (TIOCGLTC) && defined (TIOCGETC)
5990 struct tchars c;
5991 struct ltchars lc;
5993 switch (signo)
5995 case SIGINT:
5996 ioctl (p->infd, TIOCGETC, &c);
5997 send_process (proc, &c.t_intrc, 1, Qnil);
5998 return;
5999 case SIGQUIT:
6000 ioctl (p->infd, TIOCGETC, &c);
6001 send_process (proc, &c.t_quitc, 1, Qnil);
6002 return;
6003 #ifdef SIGTSTP
6004 case SIGTSTP:
6005 ioctl (p->infd, TIOCGLTC, &lc);
6006 send_process (proc, &lc.t_suspc, 1, Qnil);
6007 return;
6008 #endif /* ! defined (SIGTSTP) */
6011 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6013 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6014 characters. */
6015 #ifdef TCGETA
6016 struct termio t;
6017 switch (signo)
6019 case SIGINT:
6020 ioctl (p->infd, TCGETA, &t);
6021 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6022 return;
6023 case SIGQUIT:
6024 ioctl (p->infd, TCGETA, &t);
6025 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6026 return;
6027 #ifdef SIGTSTP
6028 case SIGTSTP:
6029 ioctl (p->infd, TCGETA, &t);
6030 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6031 return;
6032 #endif /* ! defined (SIGTSTP) */
6034 #else /* ! defined (TCGETA) */
6035 Your configuration files are messed up.
6036 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6037 you'd better be using one of the alternatives above! */
6038 #endif /* ! defined (TCGETA) */
6039 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6040 /* In this case, the code above should alway return. */
6041 abort ();
6042 #endif /* ! defined HAVE_TERMIOS */
6044 /* The code above may fall through if it can't
6045 handle the signal. */
6046 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6048 #ifdef TIOCGPGRP
6049 /* Get the current pgrp using the tty itself, if we have that.
6050 Otherwise, use the pty to get the pgrp.
6051 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6052 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6053 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6054 His patch indicates that if TIOCGPGRP returns an error, then
6055 we should just assume that p->pid is also the process group id. */
6057 gid = emacs_get_tty_pgrp (p);
6059 if (gid == -1)
6060 /* If we can't get the information, assume
6061 the shell owns the tty. */
6062 gid = p->pid;
6064 /* It is not clear whether anything really can set GID to -1.
6065 Perhaps on some system one of those ioctls can or could do so.
6066 Or perhaps this is vestigial. */
6067 if (gid == -1)
6068 no_pgrp = 1;
6069 #else /* ! defined (TIOCGPGRP ) */
6070 /* Can't select pgrps on this system, so we know that
6071 the child itself heads the pgrp. */
6072 gid = p->pid;
6073 #endif /* ! defined (TIOCGPGRP ) */
6075 /* If current_group is lambda, and the shell owns the terminal,
6076 don't send any signal. */
6077 if (EQ (current_group, Qlambda) && gid == p->pid)
6078 return;
6081 switch (signo)
6083 #ifdef SIGCONT
6084 case SIGCONT:
6085 p->raw_status_new = 0;
6086 p->status = Qrun;
6087 p->tick = ++process_tick;
6088 if (!nomsg)
6090 status_notify (NULL);
6091 redisplay_preserve_echo_area (13);
6093 break;
6094 #endif /* ! defined (SIGCONT) */
6095 case SIGINT:
6096 case SIGQUIT:
6097 case SIGKILL:
6098 flush_pending_output (p->infd);
6099 break;
6102 /* If we don't have process groups, send the signal to the immediate
6103 subprocess. That isn't really right, but it's better than any
6104 obvious alternative. */
6105 if (no_pgrp)
6107 kill (p->pid, signo);
6108 return;
6111 /* gid may be a pid, or minus a pgrp's number */
6112 #ifdef TIOCSIGSEND
6113 if (!NILP (current_group))
6115 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6116 EMACS_KILLPG (gid, signo);
6118 else
6120 gid = - p->pid;
6121 kill (gid, signo);
6123 #else /* ! defined (TIOCSIGSEND) */
6124 EMACS_KILLPG (gid, signo);
6125 #endif /* ! defined (TIOCSIGSEND) */
6128 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6129 doc: /* Interrupt process PROCESS.
6130 PROCESS may be a process, a buffer, or the name of a process or buffer.
6131 No arg or nil means current buffer's process.
6132 Second arg CURRENT-GROUP non-nil means send signal to
6133 the current process-group of the process's controlling terminal
6134 rather than to the process's own process group.
6135 If the process is a shell, this means interrupt current subjob
6136 rather than the shell.
6138 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6139 don't send the signal. */)
6140 (Lisp_Object process, Lisp_Object current_group)
6142 process_send_signal (process, SIGINT, current_group, 0);
6143 return process;
6146 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6147 doc: /* Kill process PROCESS. May be process or name of one.
6148 See function `interrupt-process' for more details on usage. */)
6149 (Lisp_Object process, Lisp_Object current_group)
6151 process_send_signal (process, SIGKILL, current_group, 0);
6152 return process;
6155 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6156 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6157 See function `interrupt-process' for more details on usage. */)
6158 (Lisp_Object process, Lisp_Object current_group)
6160 process_send_signal (process, SIGQUIT, current_group, 0);
6161 return process;
6164 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6165 doc: /* Stop process PROCESS. May be process or name of one.
6166 See function `interrupt-process' for more details on usage.
6167 If PROCESS is a network or serial process, inhibit handling of incoming
6168 traffic. */)
6169 (Lisp_Object process, Lisp_Object current_group)
6171 #ifdef HAVE_SOCKETS
6172 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6174 struct Lisp_Process *p;
6176 p = XPROCESS (process);
6177 if (NILP (p->command)
6178 && p->infd >= 0)
6180 FD_CLR (p->infd, &input_wait_mask);
6181 FD_CLR (p->infd, &non_keyboard_wait_mask);
6183 p->command = Qt;
6184 return process;
6186 #endif
6187 #ifndef SIGTSTP
6188 error ("No SIGTSTP support");
6189 #else
6190 process_send_signal (process, SIGTSTP, current_group, 0);
6191 #endif
6192 return process;
6195 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6196 doc: /* Continue process PROCESS. May be process or name of one.
6197 See function `interrupt-process' for more details on usage.
6198 If PROCESS is a network or serial process, resume handling of incoming
6199 traffic. */)
6200 (Lisp_Object process, Lisp_Object current_group)
6202 #ifdef HAVE_SOCKETS
6203 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6205 struct Lisp_Process *p;
6207 p = XPROCESS (process);
6208 if (EQ (p->command, Qt)
6209 && p->infd >= 0
6210 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6212 FD_SET (p->infd, &input_wait_mask);
6213 FD_SET (p->infd, &non_keyboard_wait_mask);
6214 #ifdef WINDOWSNT
6215 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6216 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6217 #endif
6218 #ifdef HAVE_TERMIOS
6219 tcflush (p->infd, TCIFLUSH);
6220 #endif
6222 p->command = Qnil;
6223 return process;
6225 #endif
6226 #ifdef SIGCONT
6227 process_send_signal (process, SIGCONT, current_group, 0);
6228 #else
6229 error ("No SIGCONT support");
6230 #endif
6231 return process;
6234 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6235 2, 2, "sProcess (name or number): \nnSignal code: ",
6236 doc: /* Send PROCESS the signal with code SIGCODE.
6237 PROCESS may also be a number specifying the process id of the
6238 process to signal; in this case, the process need not be a child of
6239 this Emacs.
6240 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6241 (Lisp_Object process, Lisp_Object sigcode)
6243 pid_t pid;
6245 if (INTEGERP (process))
6247 pid = XINT (process);
6248 goto got_it;
6251 if (FLOATP (process))
6253 pid = (pid_t) XFLOAT_DATA (process);
6254 goto got_it;
6257 if (STRINGP (process))
6259 Lisp_Object tem;
6260 if (tem = Fget_process (process), NILP (tem))
6262 pid = XINT (Fstring_to_number (process, make_number (10)));
6263 if (pid > 0)
6264 goto got_it;
6266 process = tem;
6268 else
6269 process = get_process (process);
6271 if (NILP (process))
6272 return process;
6274 CHECK_PROCESS (process);
6275 pid = XPROCESS (process)->pid;
6276 if (pid <= 0)
6277 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6279 got_it:
6281 #define parse_signal(NAME, VALUE) \
6282 else if (!xstrcasecmp (name, NAME)) \
6283 XSETINT (sigcode, VALUE)
6285 if (INTEGERP (sigcode))
6287 else
6289 unsigned char *name;
6291 CHECK_SYMBOL (sigcode);
6292 name = SDATA (SYMBOL_NAME (sigcode));
6294 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6295 name += 3;
6297 if (0)
6299 #ifdef SIGUSR1
6300 parse_signal ("usr1", SIGUSR1);
6301 #endif
6302 #ifdef SIGUSR2
6303 parse_signal ("usr2", SIGUSR2);
6304 #endif
6305 #ifdef SIGTERM
6306 parse_signal ("term", SIGTERM);
6307 #endif
6308 #ifdef SIGHUP
6309 parse_signal ("hup", SIGHUP);
6310 #endif
6311 #ifdef SIGINT
6312 parse_signal ("int", SIGINT);
6313 #endif
6314 #ifdef SIGQUIT
6315 parse_signal ("quit", SIGQUIT);
6316 #endif
6317 #ifdef SIGILL
6318 parse_signal ("ill", SIGILL);
6319 #endif
6320 #ifdef SIGABRT
6321 parse_signal ("abrt", SIGABRT);
6322 #endif
6323 #ifdef SIGEMT
6324 parse_signal ("emt", SIGEMT);
6325 #endif
6326 #ifdef SIGKILL
6327 parse_signal ("kill", SIGKILL);
6328 #endif
6329 #ifdef SIGFPE
6330 parse_signal ("fpe", SIGFPE);
6331 #endif
6332 #ifdef SIGBUS
6333 parse_signal ("bus", SIGBUS);
6334 #endif
6335 #ifdef SIGSEGV
6336 parse_signal ("segv", SIGSEGV);
6337 #endif
6338 #ifdef SIGSYS
6339 parse_signal ("sys", SIGSYS);
6340 #endif
6341 #ifdef SIGPIPE
6342 parse_signal ("pipe", SIGPIPE);
6343 #endif
6344 #ifdef SIGALRM
6345 parse_signal ("alrm", SIGALRM);
6346 #endif
6347 #ifdef SIGURG
6348 parse_signal ("urg", SIGURG);
6349 #endif
6350 #ifdef SIGSTOP
6351 parse_signal ("stop", SIGSTOP);
6352 #endif
6353 #ifdef SIGTSTP
6354 parse_signal ("tstp", SIGTSTP);
6355 #endif
6356 #ifdef SIGCONT
6357 parse_signal ("cont", SIGCONT);
6358 #endif
6359 #ifdef SIGCHLD
6360 parse_signal ("chld", SIGCHLD);
6361 #endif
6362 #ifdef SIGTTIN
6363 parse_signal ("ttin", SIGTTIN);
6364 #endif
6365 #ifdef SIGTTOU
6366 parse_signal ("ttou", SIGTTOU);
6367 #endif
6368 #ifdef SIGIO
6369 parse_signal ("io", SIGIO);
6370 #endif
6371 #ifdef SIGXCPU
6372 parse_signal ("xcpu", SIGXCPU);
6373 #endif
6374 #ifdef SIGXFSZ
6375 parse_signal ("xfsz", SIGXFSZ);
6376 #endif
6377 #ifdef SIGVTALRM
6378 parse_signal ("vtalrm", SIGVTALRM);
6379 #endif
6380 #ifdef SIGPROF
6381 parse_signal ("prof", SIGPROF);
6382 #endif
6383 #ifdef SIGWINCH
6384 parse_signal ("winch", SIGWINCH);
6385 #endif
6386 #ifdef SIGINFO
6387 parse_signal ("info", SIGINFO);
6388 #endif
6389 else
6390 error ("Undefined signal name %s", name);
6393 #undef parse_signal
6395 return make_number (kill (pid, XINT (sigcode)));
6398 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6399 doc: /* Make PROCESS see end-of-file in its input.
6400 EOF comes after any text already sent to it.
6401 PROCESS may be a process, a buffer, the name of a process or buffer, or
6402 nil, indicating the current buffer's process.
6403 If PROCESS is a network connection, or is a process communicating
6404 through a pipe (as opposed to a pty), then you cannot send any more
6405 text to PROCESS after you call this function.
6406 If PROCESS is a serial process, wait until all output written to the
6407 process has been transmitted to the serial port. */)
6408 (Lisp_Object process)
6410 Lisp_Object proc;
6411 struct coding_system *coding;
6413 if (DATAGRAM_CONN_P (process))
6414 return process;
6416 proc = get_process (process);
6417 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6419 /* Make sure the process is really alive. */
6420 if (XPROCESS (proc)->raw_status_new)
6421 update_status (XPROCESS (proc));
6422 if (! EQ (XPROCESS (proc)->status, Qrun))
6423 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6425 if (CODING_REQUIRE_FLUSHING (coding))
6427 coding->mode |= CODING_MODE_LAST_BLOCK;
6428 send_process (proc, "", 0, Qnil);
6431 if (XPROCESS (proc)->pty_flag)
6432 send_process (proc, "\004", 1, Qnil);
6433 else if (EQ (XPROCESS (proc)->type, Qserial))
6435 #ifdef HAVE_TERMIOS
6436 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6437 error ("tcdrain() failed: %s", emacs_strerror (errno));
6438 #endif
6439 /* Do nothing on Windows because writes are blocking. */
6441 else
6443 int old_outfd, new_outfd;
6445 #ifdef HAVE_SHUTDOWN
6446 /* If this is a network connection, or socketpair is used
6447 for communication with the subprocess, call shutdown to cause EOF.
6448 (In some old system, shutdown to socketpair doesn't work.
6449 Then we just can't win.) */
6450 if (EQ (XPROCESS (proc)->type, Qnetwork)
6451 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6452 shutdown (XPROCESS (proc)->outfd, 1);
6453 /* In case of socketpair, outfd == infd, so don't close it. */
6454 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6455 emacs_close (XPROCESS (proc)->outfd);
6456 #else /* not HAVE_SHUTDOWN */
6457 emacs_close (XPROCESS (proc)->outfd);
6458 #endif /* not HAVE_SHUTDOWN */
6459 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6460 if (new_outfd < 0)
6461 abort ();
6462 old_outfd = XPROCESS (proc)->outfd;
6464 if (!proc_encode_coding_system[new_outfd])
6465 proc_encode_coding_system[new_outfd]
6466 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6467 memcpy (proc_encode_coding_system[new_outfd],
6468 proc_encode_coding_system[old_outfd],
6469 sizeof (struct coding_system));
6470 memset (proc_encode_coding_system[old_outfd], 0,
6471 sizeof (struct coding_system));
6473 XPROCESS (proc)->outfd = new_outfd;
6475 return process;
6478 /* Kill all processes associated with `buffer'.
6479 If `buffer' is nil, kill all processes */
6481 void
6482 kill_buffer_processes (Lisp_Object buffer)
6484 Lisp_Object tail, proc;
6486 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6488 proc = XCDR (XCAR (tail));
6489 if (PROCESSP (proc)
6490 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6492 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6493 Fdelete_process (proc);
6494 else if (XPROCESS (proc)->infd >= 0)
6495 process_send_signal (proc, SIGHUP, Qnil, 1);
6500 /* On receipt of a signal that a child status has changed, loop asking
6501 about children with changed statuses until the system says there
6502 are no more.
6504 All we do is change the status; we do not run sentinels or print
6505 notifications. That is saved for the next time keyboard input is
6506 done, in order to avoid timing errors.
6508 ** WARNING: this can be called during garbage collection.
6509 Therefore, it must not be fooled by the presence of mark bits in
6510 Lisp objects.
6512 ** USG WARNING: Although it is not obvious from the documentation
6513 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6514 signal() before executing at least one wait(), otherwise the
6515 handler will be called again, resulting in an infinite loop. The
6516 relevant portion of the documentation reads "SIGCLD signals will be
6517 queued and the signal-catching function will be continually
6518 reentered until the queue is empty". Invoking signal() causes the
6519 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6520 Inc.
6522 ** Malloc WARNING: This should never call malloc either directly or
6523 indirectly; if it does, that is a bug */
6525 #ifdef SIGCHLD
6526 SIGTYPE
6527 sigchld_handler (int signo)
6529 int old_errno = errno;
6530 Lisp_Object proc;
6531 register struct Lisp_Process *p;
6532 extern EMACS_TIME *input_available_clear_time;
6534 SIGNAL_THREAD_CHECK (signo);
6536 while (1)
6538 pid_t pid;
6539 int w;
6540 Lisp_Object tail;
6542 #ifdef WNOHANG
6543 #ifndef WUNTRACED
6544 #define WUNTRACED 0
6545 #endif /* no WUNTRACED */
6546 /* Keep trying to get a status until we get a definitive result. */
6549 errno = 0;
6550 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6552 while (pid < 0 && errno == EINTR);
6554 if (pid <= 0)
6556 /* PID == 0 means no processes found, PID == -1 means a real
6557 failure. We have done all our job, so return. */
6559 errno = old_errno;
6560 return;
6562 #else
6563 pid = wait (&w);
6564 #endif /* no WNOHANG */
6566 /* Find the process that signaled us, and record its status. */
6568 /* The process can have been deleted by Fdelete_process. */
6569 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6571 Lisp_Object xpid = XCAR (tail);
6572 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6573 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6575 XSETCAR (tail, Qnil);
6576 goto sigchld_end_of_loop;
6580 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6581 p = 0;
6582 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6584 proc = XCDR (XCAR (tail));
6585 p = XPROCESS (proc);
6586 if (EQ (p->type, Qreal) && p->pid == pid)
6587 break;
6588 p = 0;
6591 /* Look for an asynchronous process whose pid hasn't been filled
6592 in yet. */
6593 if (p == 0)
6594 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6596 proc = XCDR (XCAR (tail));
6597 p = XPROCESS (proc);
6598 if (p->pid == -1)
6599 break;
6600 p = 0;
6603 /* Change the status of the process that was found. */
6604 if (p != 0)
6606 int clear_desc_flag = 0;
6608 p->tick = ++process_tick;
6609 p->raw_status = w;
6610 p->raw_status_new = 1;
6612 /* If process has terminated, stop waiting for its output. */
6613 if ((WIFSIGNALED (w) || WIFEXITED (w))
6614 && p->infd >= 0)
6615 clear_desc_flag = 1;
6617 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6618 if (clear_desc_flag)
6620 FD_CLR (p->infd, &input_wait_mask);
6621 FD_CLR (p->infd, &non_keyboard_wait_mask);
6624 /* Tell wait_reading_process_output that it needs to wake up and
6625 look around. */
6626 if (input_available_clear_time)
6627 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6630 /* There was no asynchronous process found for that pid: we have
6631 a synchronous process. */
6632 else
6634 synch_process_alive = 0;
6636 /* Report the status of the synchronous process. */
6637 if (WIFEXITED (w))
6638 synch_process_retcode = WRETCODE (w);
6639 else if (WIFSIGNALED (w))
6640 synch_process_termsig = WTERMSIG (w);
6642 /* Tell wait_reading_process_output that it needs to wake up and
6643 look around. */
6644 if (input_available_clear_time)
6645 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6648 sigchld_end_of_loop:
6651 /* On some systems, we must return right away.
6652 If any more processes want to signal us, we will
6653 get another signal.
6654 Otherwise (on systems that have WNOHANG), loop around
6655 to use up all the processes that have something to tell us. */
6656 #if (defined WINDOWSNT \
6657 || (defined USG && !defined GNU_LINUX \
6658 && !(defined HPUX && defined WNOHANG)))
6659 errno = old_errno;
6660 return;
6661 #endif /* USG, but not HPUX with WNOHANG */
6664 #endif /* SIGCHLD */
6667 static Lisp_Object
6668 exec_sentinel_unwind (Lisp_Object data)
6670 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6671 return Qnil;
6674 static Lisp_Object
6675 exec_sentinel_error_handler (Lisp_Object error)
6677 cmd_error_internal (error, "error in process sentinel: ");
6678 Vinhibit_quit = Qt;
6679 update_echo_area ();
6680 Fsleep_for (make_number (2), Qnil);
6681 return Qt;
6684 static void
6685 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6687 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6688 register struct Lisp_Process *p = XPROCESS (proc);
6689 int count = SPECPDL_INDEX ();
6690 int outer_running_asynch_code = running_asynch_code;
6691 int waiting = waiting_for_user_input_p;
6693 if (inhibit_sentinels)
6694 return;
6696 /* No need to gcpro these, because all we do with them later
6697 is test them for EQness, and none of them should be a string. */
6698 odeactivate = Vdeactivate_mark;
6699 XSETBUFFER (obuffer, current_buffer);
6700 okeymap = current_buffer->keymap;
6702 /* There's no good reason to let sentinels change the current
6703 buffer, and many callers of accept-process-output, sit-for, and
6704 friends don't expect current-buffer to be changed from under them. */
6705 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6707 sentinel = p->sentinel;
6708 if (NILP (sentinel))
6709 return;
6711 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6712 assure that it gets restored no matter how the sentinel exits. */
6713 p->sentinel = Qnil;
6714 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6715 /* Inhibit quit so that random quits don't screw up a running filter. */
6716 specbind (Qinhibit_quit, Qt);
6717 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6719 /* In case we get recursively called,
6720 and we already saved the match data nonrecursively,
6721 save the same match data in safely recursive fashion. */
6722 if (outer_running_asynch_code)
6724 Lisp_Object tem;
6725 tem = Fmatch_data (Qnil, Qnil, Qnil);
6726 restore_search_regs ();
6727 record_unwind_save_match_data ();
6728 Fset_match_data (tem, Qt);
6731 /* For speed, if a search happens within this code,
6732 save the match data in a special nonrecursive fashion. */
6733 running_asynch_code = 1;
6735 internal_condition_case_1 (read_process_output_call,
6736 Fcons (sentinel,
6737 Fcons (proc, Fcons (reason, Qnil))),
6738 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6739 exec_sentinel_error_handler);
6741 /* If we saved the match data nonrecursively, restore it now. */
6742 restore_search_regs ();
6743 running_asynch_code = outer_running_asynch_code;
6745 Vdeactivate_mark = odeactivate;
6747 /* Restore waiting_for_user_input_p as it was
6748 when we were called, in case the filter clobbered it. */
6749 waiting_for_user_input_p = waiting;
6751 #if 0
6752 if (! EQ (Fcurrent_buffer (), obuffer)
6753 || ! EQ (current_buffer->keymap, okeymap))
6754 #endif
6755 /* But do it only if the caller is actually going to read events.
6756 Otherwise there's no need to make him wake up, and it could
6757 cause trouble (for example it would make sit_for return). */
6758 if (waiting_for_user_input_p == -1)
6759 record_asynch_buffer_change ();
6761 unbind_to (count, Qnil);
6764 /* Report all recent events of a change in process status
6765 (either run the sentinel or output a message).
6766 This is usually done while Emacs is waiting for keyboard input
6767 but can be done at other times. */
6769 static void
6770 status_notify (struct Lisp_Process *deleting_process)
6772 register Lisp_Object proc, buffer;
6773 Lisp_Object tail, msg;
6774 struct gcpro gcpro1, gcpro2;
6776 tail = Qnil;
6777 msg = Qnil;
6778 /* We need to gcpro tail; if read_process_output calls a filter
6779 which deletes a process and removes the cons to which tail points
6780 from Vprocess_alist, and then causes a GC, tail is an unprotected
6781 reference. */
6782 GCPRO2 (tail, msg);
6784 /* Set this now, so that if new processes are created by sentinels
6785 that we run, we get called again to handle their status changes. */
6786 update_tick = process_tick;
6788 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6790 Lisp_Object symbol;
6791 register struct Lisp_Process *p;
6793 proc = Fcdr (XCAR (tail));
6794 p = XPROCESS (proc);
6796 if (p->tick != p->update_tick)
6798 p->update_tick = p->tick;
6800 /* If process is still active, read any output that remains. */
6801 while (! EQ (p->filter, Qt)
6802 && ! EQ (p->status, Qconnect)
6803 && ! EQ (p->status, Qlisten)
6804 /* Network or serial process not stopped: */
6805 && ! EQ (p->command, Qt)
6806 && p->infd >= 0
6807 && p != deleting_process
6808 && read_process_output (proc, p->infd) > 0);
6810 buffer = p->buffer;
6812 /* Get the text to use for the message. */
6813 if (p->raw_status_new)
6814 update_status (p);
6815 msg = status_message (p);
6817 /* If process is terminated, deactivate it or delete it. */
6818 symbol = p->status;
6819 if (CONSP (p->status))
6820 symbol = XCAR (p->status);
6822 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6823 || EQ (symbol, Qclosed))
6825 if (delete_exited_processes)
6826 remove_process (proc);
6827 else
6828 deactivate_process (proc);
6831 /* The actions above may have further incremented p->tick.
6832 So set p->update_tick again
6833 so that an error in the sentinel will not cause
6834 this code to be run again. */
6835 p->update_tick = p->tick;
6836 /* Now output the message suitably. */
6837 if (!NILP (p->sentinel))
6838 exec_sentinel (proc, msg);
6839 /* Don't bother with a message in the buffer
6840 when a process becomes runnable. */
6841 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6843 Lisp_Object tem;
6844 struct buffer *old = current_buffer;
6845 int opoint, opoint_byte;
6846 int before, before_byte;
6848 /* Avoid error if buffer is deleted
6849 (probably that's why the process is dead, too) */
6850 if (NILP (XBUFFER (buffer)->name))
6851 continue;
6852 Fset_buffer (buffer);
6854 opoint = PT;
6855 opoint_byte = PT_BYTE;
6856 /* Insert new output into buffer
6857 at the current end-of-output marker,
6858 thus preserving logical ordering of input and output. */
6859 if (XMARKER (p->mark)->buffer)
6860 Fgoto_char (p->mark);
6861 else
6862 SET_PT_BOTH (ZV, ZV_BYTE);
6864 before = PT;
6865 before_byte = PT_BYTE;
6867 tem = current_buffer->read_only;
6868 current_buffer->read_only = Qnil;
6869 insert_string ("\nProcess ");
6870 Finsert (1, &p->name);
6871 insert_string (" ");
6872 Finsert (1, &msg);
6873 current_buffer->read_only = tem;
6874 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6876 if (opoint >= before)
6877 SET_PT_BOTH (opoint + (PT - before),
6878 opoint_byte + (PT_BYTE - before_byte));
6879 else
6880 SET_PT_BOTH (opoint, opoint_byte);
6882 set_buffer_internal (old);
6885 } /* end for */
6887 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6888 UNGCPRO;
6892 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6893 Sset_process_coding_system, 1, 3, 0,
6894 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6895 DECODING will be used to decode subprocess output and ENCODING to
6896 encode subprocess input. */)
6897 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6899 register struct Lisp_Process *p;
6901 CHECK_PROCESS (process);
6902 p = XPROCESS (process);
6903 if (p->infd < 0)
6904 error ("Input file descriptor of %s closed", SDATA (p->name));
6905 if (p->outfd < 0)
6906 error ("Output file descriptor of %s closed", SDATA (p->name));
6907 Fcheck_coding_system (decoding);
6908 Fcheck_coding_system (encoding);
6909 encoding = coding_inherit_eol_type (encoding, Qnil);
6910 p->decode_coding_system = decoding;
6911 p->encode_coding_system = encoding;
6912 setup_process_coding_systems (process);
6914 return Qnil;
6917 DEFUN ("process-coding-system",
6918 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6919 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6920 (register Lisp_Object process)
6922 CHECK_PROCESS (process);
6923 return Fcons (XPROCESS (process)->decode_coding_system,
6924 XPROCESS (process)->encode_coding_system);
6927 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6928 Sset_process_filter_multibyte, 2, 2, 0,
6929 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6930 If FLAG is non-nil, the filter is given multibyte strings.
6931 If FLAG is nil, the filter is given unibyte strings. In this case,
6932 all character code conversion except for end-of-line conversion is
6933 suppressed. */)
6934 (Lisp_Object process, Lisp_Object flag)
6936 register struct Lisp_Process *p;
6938 CHECK_PROCESS (process);
6939 p = XPROCESS (process);
6940 if (NILP (flag))
6941 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6942 setup_process_coding_systems (process);
6944 return Qnil;
6947 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6948 Sprocess_filter_multibyte_p, 1, 1, 0,
6949 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6950 (Lisp_Object process)
6952 register struct Lisp_Process *p;
6953 struct coding_system *coding;
6955 CHECK_PROCESS (process);
6956 p = XPROCESS (process);
6957 coding = proc_decode_coding_system[p->infd];
6958 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6963 /* Stop reading input from keyboard sources. */
6965 void
6966 hold_keyboard_input (void)
6968 kbd_is_on_hold = 1;
6971 /* Resume reading input from keyboard sources. */
6973 void
6974 unhold_keyboard_input (void)
6976 kbd_is_on_hold = 0;
6979 /* Return non-zero if keyboard input is on hold, zero otherwise. */
6982 kbd_on_hold_p (void)
6984 return kbd_is_on_hold;
6987 /* Add DESC to the set of keyboard input descriptors. */
6989 void
6990 add_keyboard_wait_descriptor (int desc)
6992 FD_SET (desc, &input_wait_mask);
6993 FD_SET (desc, &non_process_wait_mask);
6994 if (desc > max_keyboard_desc)
6995 max_keyboard_desc = desc;
6998 static int add_gpm_wait_descriptor_called_flag;
7000 void
7001 add_gpm_wait_descriptor (int desc)
7003 if (! add_gpm_wait_descriptor_called_flag)
7004 FD_CLR (0, &input_wait_mask);
7005 add_gpm_wait_descriptor_called_flag = 1;
7006 FD_SET (desc, &input_wait_mask);
7007 FD_SET (desc, &gpm_wait_mask);
7008 if (desc > max_gpm_desc)
7009 max_gpm_desc = desc;
7012 /* From now on, do not expect DESC to give keyboard input. */
7014 void
7015 delete_keyboard_wait_descriptor (int desc)
7017 int fd;
7018 int lim = max_keyboard_desc;
7020 FD_CLR (desc, &input_wait_mask);
7021 FD_CLR (desc, &non_process_wait_mask);
7023 if (desc == max_keyboard_desc)
7024 for (fd = 0; fd < lim; fd++)
7025 if (FD_ISSET (fd, &input_wait_mask)
7026 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7027 && !FD_ISSET (fd, &gpm_wait_mask))
7028 max_keyboard_desc = fd;
7031 void
7032 delete_gpm_wait_descriptor (int desc)
7034 int fd;
7035 int lim = max_gpm_desc;
7037 FD_CLR (desc, &input_wait_mask);
7038 FD_CLR (desc, &non_process_wait_mask);
7040 if (desc == max_gpm_desc)
7041 for (fd = 0; fd < lim; fd++)
7042 if (FD_ISSET (fd, &input_wait_mask)
7043 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7044 && !FD_ISSET (fd, &non_process_wait_mask))
7045 max_gpm_desc = fd;
7048 /* Return nonzero if *MASK has a bit set
7049 that corresponds to one of the keyboard input descriptors. */
7051 static int
7052 keyboard_bit_set (fd_set *mask)
7054 int fd;
7056 for (fd = 0; fd <= max_keyboard_desc; fd++)
7057 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7058 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7059 return 1;
7061 return 0;
7064 /* Enumeration of and access to system processes a-la ps(1). */
7066 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7067 0, 0, 0,
7068 doc: /* Return a list of numerical process IDs of all running processes.
7069 If this functionality is unsupported, return nil.
7071 See `process-attributes' for getting attributes of a process given its ID. */)
7072 (void)
7074 return list_system_processes ();
7077 DEFUN ("process-attributes", Fprocess_attributes,
7078 Sprocess_attributes, 1, 1, 0,
7079 doc: /* Return attributes of the process given by its PID, a number.
7081 Value is an alist where each element is a cons cell of the form
7083 \(KEY . VALUE)
7085 If this functionality is unsupported, the value is nil.
7087 See `list-system-processes' for getting a list of all process IDs.
7089 The KEYs of the attributes that this function may return are listed
7090 below, together with the type of the associated VALUE (in parentheses).
7091 Not all platforms support all of these attributes; unsupported
7092 attributes will not appear in the returned alist.
7093 Unless explicitly indicated otherwise, numbers can have either
7094 integer or floating point values.
7096 euid -- Effective user User ID of the process (number)
7097 user -- User name corresponding to euid (string)
7098 egid -- Effective user Group ID of the process (number)
7099 group -- Group name corresponding to egid (string)
7100 comm -- Command name (executable name only) (string)
7101 state -- Process state code, such as "S", "R", or "T" (string)
7102 ppid -- Parent process ID (number)
7103 pgrp -- Process group ID (number)
7104 sess -- Session ID, i.e. process ID of session leader (number)
7105 ttname -- Controlling tty name (string)
7106 tpgid -- ID of foreground process group on the process's tty (number)
7107 minflt -- number of minor page faults (number)
7108 majflt -- number of major page faults (number)
7109 cminflt -- cumulative number of minor page faults (number)
7110 cmajflt -- cumulative number of major page faults (number)
7111 utime -- user time used by the process, in the (HIGH LOW USEC) format
7112 stime -- system time used by the process, in the (HIGH LOW USEC) format
7113 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7114 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7115 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7116 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7117 pri -- priority of the process (number)
7118 nice -- nice value of the process (number)
7119 thcount -- process thread count (number)
7120 start -- time the process started, in the (HIGH LOW USEC) format
7121 vsize -- virtual memory size of the process in KB's (number)
7122 rss -- resident set size of the process in KB's (number)
7123 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7124 pcpu -- percents of CPU time used by the process (floating-point number)
7125 pmem -- percents of total physical memory used by process's resident set
7126 (floating-point number)
7127 args -- command line which invoked the process (string). */)
7128 ( Lisp_Object pid)
7130 return system_process_attributes (pid);
7133 void
7134 init_process (void)
7136 register int i;
7138 inhibit_sentinels = 0;
7140 #ifdef SIGCHLD
7141 #ifndef CANNOT_DUMP
7142 if (! noninteractive || initialized)
7143 #endif
7144 signal (SIGCHLD, sigchld_handler);
7145 #endif
7147 FD_ZERO (&input_wait_mask);
7148 FD_ZERO (&non_keyboard_wait_mask);
7149 FD_ZERO (&non_process_wait_mask);
7150 max_process_desc = 0;
7152 #ifdef NON_BLOCKING_CONNECT
7153 FD_ZERO (&connect_wait_mask);
7154 num_pending_connects = 0;
7155 #endif
7157 #ifdef ADAPTIVE_READ_BUFFERING
7158 process_output_delay_count = 0;
7159 process_output_skip = 0;
7160 #endif
7162 /* Don't do this, it caused infinite select loops. The display
7163 method should call add_keyboard_wait_descriptor on stdin if it
7164 needs that. */
7165 #if 0
7166 FD_SET (0, &input_wait_mask);
7167 #endif
7169 Vprocess_alist = Qnil;
7170 #ifdef SIGCHLD
7171 deleted_pid_list = Qnil;
7172 #endif
7173 for (i = 0; i < MAXDESC; i++)
7175 chan_process[i] = Qnil;
7176 proc_buffered_char[i] = -1;
7178 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7179 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7180 #ifdef DATAGRAM_SOCKETS
7181 memset (datagram_address, 0, sizeof datagram_address);
7182 #endif
7184 #ifdef HAVE_SOCKETS
7186 Lisp_Object subfeatures = Qnil;
7187 const struct socket_options *sopt;
7189 #define ADD_SUBFEATURE(key, val) \
7190 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7192 #ifdef NON_BLOCKING_CONNECT
7193 ADD_SUBFEATURE (QCnowait, Qt);
7194 #endif
7195 #ifdef DATAGRAM_SOCKETS
7196 ADD_SUBFEATURE (QCtype, Qdatagram);
7197 #endif
7198 #ifdef HAVE_SEQPACKET
7199 ADD_SUBFEATURE (QCtype, Qseqpacket);
7200 #endif
7201 #ifdef HAVE_LOCAL_SOCKETS
7202 ADD_SUBFEATURE (QCfamily, Qlocal);
7203 #endif
7204 ADD_SUBFEATURE (QCfamily, Qipv4);
7205 #ifdef AF_INET6
7206 ADD_SUBFEATURE (QCfamily, Qipv6);
7207 #endif
7208 #ifdef HAVE_GETSOCKNAME
7209 ADD_SUBFEATURE (QCservice, Qt);
7210 #endif
7211 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7212 ADD_SUBFEATURE (QCserver, Qt);
7213 #endif
7215 for (sopt = socket_options; sopt->name; sopt++)
7216 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7218 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7220 #endif /* HAVE_SOCKETS */
7222 #if defined (DARWIN_OS)
7223 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7224 processes. As such, we only change the default value. */
7225 if (initialized)
7227 char *release = get_operating_system_release ();
7228 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7229 && release[1] == '.')) {
7230 Vprocess_connection_type = Qnil;
7233 #endif
7236 void
7237 syms_of_process (void)
7239 Qprocessp = intern_c_string ("processp");
7240 staticpro (&Qprocessp);
7241 Qrun = intern_c_string ("run");
7242 staticpro (&Qrun);
7243 Qstop = intern_c_string ("stop");
7244 staticpro (&Qstop);
7245 Qsignal = intern_c_string ("signal");
7246 staticpro (&Qsignal);
7248 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7249 here again.
7251 Qexit = intern_c_string ("exit");
7252 staticpro (&Qexit); */
7254 Qopen = intern_c_string ("open");
7255 staticpro (&Qopen);
7256 Qclosed = intern_c_string ("closed");
7257 staticpro (&Qclosed);
7258 Qconnect = intern_c_string ("connect");
7259 staticpro (&Qconnect);
7260 Qfailed = intern_c_string ("failed");
7261 staticpro (&Qfailed);
7262 Qlisten = intern_c_string ("listen");
7263 staticpro (&Qlisten);
7264 Qlocal = intern_c_string ("local");
7265 staticpro (&Qlocal);
7266 Qipv4 = intern_c_string ("ipv4");
7267 staticpro (&Qipv4);
7268 #ifdef AF_INET6
7269 Qipv6 = intern_c_string ("ipv6");
7270 staticpro (&Qipv6);
7271 #endif
7272 Qdatagram = intern_c_string ("datagram");
7273 staticpro (&Qdatagram);
7274 Qseqpacket = intern_c_string ("seqpacket");
7275 staticpro (&Qseqpacket);
7277 QCport = intern_c_string (":port");
7278 staticpro (&QCport);
7279 QCspeed = intern_c_string (":speed");
7280 staticpro (&QCspeed);
7281 QCprocess = intern_c_string (":process");
7282 staticpro (&QCprocess);
7284 QCbytesize = intern_c_string (":bytesize");
7285 staticpro (&QCbytesize);
7286 QCstopbits = intern_c_string (":stopbits");
7287 staticpro (&QCstopbits);
7288 QCparity = intern_c_string (":parity");
7289 staticpro (&QCparity);
7290 Qodd = intern_c_string ("odd");
7291 staticpro (&Qodd);
7292 Qeven = intern_c_string ("even");
7293 staticpro (&Qeven);
7294 QCflowcontrol = intern_c_string (":flowcontrol");
7295 staticpro (&QCflowcontrol);
7296 Qhw = intern_c_string ("hw");
7297 staticpro (&Qhw);
7298 Qsw = intern_c_string ("sw");
7299 staticpro (&Qsw);
7300 QCsummary = intern_c_string (":summary");
7301 staticpro (&QCsummary);
7303 Qreal = intern_c_string ("real");
7304 staticpro (&Qreal);
7305 Qnetwork = intern_c_string ("network");
7306 staticpro (&Qnetwork);
7307 Qserial = intern_c_string ("serial");
7308 staticpro (&Qserial);
7310 QCname = intern_c_string (":name");
7311 staticpro (&QCname);
7312 QCbuffer = intern_c_string (":buffer");
7313 staticpro (&QCbuffer);
7314 QChost = intern_c_string (":host");
7315 staticpro (&QChost);
7316 QCservice = intern_c_string (":service");
7317 staticpro (&QCservice);
7318 QCtype = intern_c_string (":type");
7319 staticpro (&QCtype);
7320 QClocal = intern_c_string (":local");
7321 staticpro (&QClocal);
7322 QCremote = intern_c_string (":remote");
7323 staticpro (&QCremote);
7324 QCcoding = intern_c_string (":coding");
7325 staticpro (&QCcoding);
7326 QCserver = intern_c_string (":server");
7327 staticpro (&QCserver);
7328 QCnowait = intern_c_string (":nowait");
7329 staticpro (&QCnowait);
7330 QCsentinel = intern_c_string (":sentinel");
7331 staticpro (&QCsentinel);
7332 QClog = intern_c_string (":log");
7333 staticpro (&QClog);
7334 QCnoquery = intern_c_string (":noquery");
7335 staticpro (&QCnoquery);
7336 QCstop = intern_c_string (":stop");
7337 staticpro (&QCstop);
7338 QCoptions = intern_c_string (":options");
7339 staticpro (&QCoptions);
7340 QCplist = intern_c_string (":plist");
7341 staticpro (&QCplist);
7343 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7344 staticpro (&Qlast_nonmenu_event);
7346 staticpro (&Vprocess_alist);
7347 #ifdef SIGCHLD
7348 staticpro (&deleted_pid_list);
7349 #endif
7351 Qeuid = intern_c_string ("euid");
7352 staticpro (&Qeuid);
7353 Qegid = intern_c_string ("egid");
7354 staticpro (&Qegid);
7355 Quser = intern_c_string ("user");
7356 staticpro (&Quser);
7357 Qgroup = intern_c_string ("group");
7358 staticpro (&Qgroup);
7359 Qcomm = intern_c_string ("comm");
7360 staticpro (&Qcomm);
7361 Qstate = intern_c_string ("state");
7362 staticpro (&Qstate);
7363 Qppid = intern_c_string ("ppid");
7364 staticpro (&Qppid);
7365 Qpgrp = intern_c_string ("pgrp");
7366 staticpro (&Qpgrp);
7367 Qsess = intern_c_string ("sess");
7368 staticpro (&Qsess);
7369 Qttname = intern_c_string ("ttname");
7370 staticpro (&Qttname);
7371 Qtpgid = intern_c_string ("tpgid");
7372 staticpro (&Qtpgid);
7373 Qminflt = intern_c_string ("minflt");
7374 staticpro (&Qminflt);
7375 Qmajflt = intern_c_string ("majflt");
7376 staticpro (&Qmajflt);
7377 Qcminflt = intern_c_string ("cminflt");
7378 staticpro (&Qcminflt);
7379 Qcmajflt = intern_c_string ("cmajflt");
7380 staticpro (&Qcmajflt);
7381 Qutime = intern_c_string ("utime");
7382 staticpro (&Qutime);
7383 Qstime = intern_c_string ("stime");
7384 staticpro (&Qstime);
7385 Qtime = intern_c_string ("time");
7386 staticpro (&Qtime);
7387 Qcutime = intern_c_string ("cutime");
7388 staticpro (&Qcutime);
7389 Qcstime = intern_c_string ("cstime");
7390 staticpro (&Qcstime);
7391 Qctime = intern_c_string ("ctime");
7392 staticpro (&Qctime);
7393 Qpri = intern_c_string ("pri");
7394 staticpro (&Qpri);
7395 Qnice = intern_c_string ("nice");
7396 staticpro (&Qnice);
7397 Qthcount = intern_c_string ("thcount");
7398 staticpro (&Qthcount);
7399 Qstart = intern_c_string ("start");
7400 staticpro (&Qstart);
7401 Qvsize = intern_c_string ("vsize");
7402 staticpro (&Qvsize);
7403 Qrss = intern_c_string ("rss");
7404 staticpro (&Qrss);
7405 Qetime = intern_c_string ("etime");
7406 staticpro (&Qetime);
7407 Qpcpu = intern_c_string ("pcpu");
7408 staticpro (&Qpcpu);
7409 Qpmem = intern_c_string ("pmem");
7410 staticpro (&Qpmem);
7411 Qargs = intern_c_string ("args");
7412 staticpro (&Qargs);
7414 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7415 doc: /* *Non-nil means delete processes immediately when they exit.
7416 A value of nil means don't delete them until `list-processes' is run. */);
7418 delete_exited_processes = 1;
7420 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7421 doc: /* Control type of device used to communicate with subprocesses.
7422 Values are nil to use a pipe, or t or `pty' to use a pty.
7423 The value has no effect if the system has no ptys or if all ptys are busy:
7424 then a pipe is used in any case.
7425 The value takes effect when `start-process' is called. */);
7426 Vprocess_connection_type = Qt;
7428 #ifdef ADAPTIVE_READ_BUFFERING
7429 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7430 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7431 On some systems, when Emacs reads the output from a subprocess, the output data
7432 is read in very small blocks, potentially resulting in very poor performance.
7433 This behavior can be remedied to some extent by setting this variable to a
7434 non-nil value, as it will automatically delay reading from such processes, to
7435 allow them to produce more output before Emacs tries to read it.
7436 If the value is t, the delay is reset after each write to the process; any other
7437 non-nil value means that the delay is not reset on write.
7438 The variable takes effect when `start-process' is called. */);
7439 Vprocess_adaptive_read_buffering = Qt;
7440 #endif
7442 defsubr (&Sprocessp);
7443 defsubr (&Sget_process);
7444 defsubr (&Sget_buffer_process);
7445 defsubr (&Sdelete_process);
7446 defsubr (&Sprocess_status);
7447 defsubr (&Sprocess_exit_status);
7448 defsubr (&Sprocess_id);
7449 defsubr (&Sprocess_name);
7450 defsubr (&Sprocess_tty_name);
7451 defsubr (&Sprocess_command);
7452 defsubr (&Sset_process_buffer);
7453 defsubr (&Sprocess_buffer);
7454 defsubr (&Sprocess_mark);
7455 defsubr (&Sset_process_filter);
7456 defsubr (&Sprocess_filter);
7457 defsubr (&Sset_process_sentinel);
7458 defsubr (&Sprocess_sentinel);
7459 defsubr (&Sset_process_window_size);
7460 defsubr (&Sset_process_inherit_coding_system_flag);
7461 defsubr (&Sprocess_inherit_coding_system_flag);
7462 defsubr (&Sset_process_query_on_exit_flag);
7463 defsubr (&Sprocess_query_on_exit_flag);
7464 defsubr (&Sprocess_contact);
7465 defsubr (&Sprocess_plist);
7466 defsubr (&Sset_process_plist);
7467 defsubr (&Slist_processes);
7468 defsubr (&Sprocess_list);
7469 defsubr (&Sstart_process);
7470 #ifdef HAVE_SERIAL
7471 defsubr (&Sserial_process_configure);
7472 defsubr (&Smake_serial_process);
7473 #endif /* HAVE_SERIAL */
7474 #ifdef HAVE_SOCKETS
7475 defsubr (&Sset_network_process_option);
7476 defsubr (&Smake_network_process);
7477 defsubr (&Sformat_network_address);
7478 #endif /* HAVE_SOCKETS */
7479 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7480 #ifdef SIOCGIFCONF
7481 defsubr (&Snetwork_interface_list);
7482 #endif
7483 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7484 defsubr (&Snetwork_interface_info);
7485 #endif
7486 #endif /* HAVE_SOCKETS ... */
7487 #ifdef DATAGRAM_SOCKETS
7488 defsubr (&Sprocess_datagram_address);
7489 defsubr (&Sset_process_datagram_address);
7490 #endif
7491 defsubr (&Saccept_process_output);
7492 defsubr (&Sprocess_send_region);
7493 defsubr (&Sprocess_send_string);
7494 defsubr (&Sinterrupt_process);
7495 defsubr (&Skill_process);
7496 defsubr (&Squit_process);
7497 defsubr (&Sstop_process);
7498 defsubr (&Scontinue_process);
7499 defsubr (&Sprocess_running_child_p);
7500 defsubr (&Sprocess_send_eof);
7501 defsubr (&Ssignal_process);
7502 defsubr (&Swaiting_for_user_input_p);
7503 defsubr (&Sprocess_type);
7504 defsubr (&Sset_process_coding_system);
7505 defsubr (&Sprocess_coding_system);
7506 defsubr (&Sset_process_filter_multibyte);
7507 defsubr (&Sprocess_filter_multibyte_p);
7508 defsubr (&Slist_system_processes);
7509 defsubr (&Sprocess_attributes);
7513 #else /* not subprocesses */
7515 #include <sys/types.h>
7516 #include <errno.h>
7517 #include <sys/stat.h>
7518 #include <stdlib.h>
7519 #include <fcntl.h>
7520 #include <setjmp.h>
7521 #ifdef HAVE_UNISTD_H
7522 #include <unistd.h>
7523 #endif
7525 #include "lisp.h"
7526 #include "systime.h"
7527 #include "character.h"
7528 #include "coding.h"
7529 #include "termopts.h"
7530 #include "sysselect.h"
7532 extern int frame_garbaged;
7534 extern EMACS_TIME timer_check ();
7535 extern int timers_run;
7537 Lisp_Object QCtype, QCname;
7539 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7540 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7541 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7542 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7544 /* Non-zero if keyboard input is on hold, zero otherwise. */
7545 static int kbd_is_on_hold;
7547 /* As described above, except assuming that there are no subprocesses:
7549 Wait for timeout to elapse and/or keyboard input to be available.
7551 time_limit is:
7552 timeout in seconds, or
7553 zero for no limit, or
7554 -1 means gobble data immediately available but don't wait for any.
7556 read_kbd is a Lisp_Object:
7557 0 to ignore keyboard input, or
7558 1 to return when input is available, or
7559 -1 means caller will actually read the input, so don't throw to
7560 the quit handler.
7562 see full version for other parameters. We know that wait_proc will
7563 always be NULL, since `subprocesses' isn't defined.
7565 do_display != 0 means redisplay should be done to show subprocess
7566 output that arrives.
7568 Return true if we received input from any process. */
7571 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7572 wait_for_cell, wait_proc, just_wait_proc)
7573 int time_limit, microsecs, read_kbd, do_display;
7574 Lisp_Object wait_for_cell;
7575 struct Lisp_Process *wait_proc;
7576 int just_wait_proc;
7578 register int nfds;
7579 EMACS_TIME end_time, timeout;
7580 SELECT_TYPE waitchannels;
7581 int xerrno;
7583 /* What does time_limit really mean? */
7584 if (time_limit || microsecs)
7586 EMACS_GET_TIME (end_time);
7587 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7588 EMACS_ADD_TIME (end_time, end_time, timeout);
7591 /* Turn off periodic alarms (in case they are in use)
7592 and then turn off any other atimers,
7593 because the select emulator uses alarms. */
7594 stop_polling ();
7595 turn_on_atimers (0);
7597 while (1)
7599 int timeout_reduced_for_timers = 0;
7601 /* If calling from keyboard input, do not quit
7602 since we want to return C-g as an input character.
7603 Otherwise, do pending quit if requested. */
7604 if (read_kbd >= 0)
7605 QUIT;
7607 /* Exit now if the cell we're waiting for became non-nil. */
7608 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7609 break;
7611 /* Compute time from now till when time limit is up */
7612 /* Exit if already run out */
7613 if (time_limit == -1)
7615 /* -1 specified for timeout means
7616 gobble output available now
7617 but don't wait at all. */
7619 EMACS_SET_SECS_USECS (timeout, 0, 0);
7621 else if (time_limit || microsecs)
7623 EMACS_GET_TIME (timeout);
7624 EMACS_SUB_TIME (timeout, end_time, timeout);
7625 if (EMACS_TIME_NEG_P (timeout))
7626 break;
7628 else
7630 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7633 /* If our caller will not immediately handle keyboard events,
7634 run timer events directly.
7635 (Callers that will immediately read keyboard events
7636 call timer_delay on their own.) */
7637 if (NILP (wait_for_cell))
7639 EMACS_TIME timer_delay;
7643 int old_timers_run = timers_run;
7644 timer_delay = timer_check (1);
7645 if (timers_run != old_timers_run && do_display)
7646 /* We must retry, since a timer may have requeued itself
7647 and that could alter the time delay. */
7648 redisplay_preserve_echo_area (14);
7649 else
7650 break;
7652 while (!detect_input_pending ());
7654 /* If there is unread keyboard input, also return. */
7655 if (read_kbd != 0
7656 && requeued_events_pending_p ())
7657 break;
7659 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7661 EMACS_TIME difference;
7662 EMACS_SUB_TIME (difference, timer_delay, timeout);
7663 if (EMACS_TIME_NEG_P (difference))
7665 timeout = timer_delay;
7666 timeout_reduced_for_timers = 1;
7671 /* Cause C-g and alarm signals to take immediate action,
7672 and cause input available signals to zero out timeout. */
7673 if (read_kbd < 0)
7674 set_waiting_for_input (&timeout);
7676 /* Wait till there is something to do. */
7678 if (! read_kbd && NILP (wait_for_cell))
7679 FD_ZERO (&waitchannels);
7680 else
7681 FD_SET (0, &waitchannels);
7683 /* If a frame has been newly mapped and needs updating,
7684 reprocess its display stuff. */
7685 if (frame_garbaged && do_display)
7687 clear_waiting_for_input ();
7688 redisplay_preserve_echo_area (15);
7689 if (read_kbd < 0)
7690 set_waiting_for_input (&timeout);
7693 if (read_kbd && detect_input_pending ())
7695 nfds = 0;
7696 FD_ZERO (&waitchannels);
7698 else
7699 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7700 &timeout);
7702 xerrno = errno;
7704 /* Make C-g and alarm signals set flags again */
7705 clear_waiting_for_input ();
7707 /* If we woke up due to SIGWINCH, actually change size now. */
7708 do_pending_window_change (0);
7710 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7711 /* We waited the full specified time, so return now. */
7712 break;
7714 if (nfds == -1)
7716 /* If the system call was interrupted, then go around the
7717 loop again. */
7718 if (xerrno == EINTR)
7719 FD_ZERO (&waitchannels);
7720 else
7721 error ("select error: %s", emacs_strerror (xerrno));
7723 #ifdef SOLARIS2
7724 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7725 /* System sometimes fails to deliver SIGIO. */
7726 kill (getpid (), SIGIO);
7727 #endif
7728 #ifdef SIGIO
7729 if (read_kbd && interrupt_input && (waitchannels & 1))
7730 kill (getpid (), SIGIO);
7731 #endif
7733 /* Check for keyboard input */
7735 if (read_kbd
7736 && detect_input_pending_run_timers (do_display))
7738 swallow_events (do_display);
7739 if (detect_input_pending_run_timers (do_display))
7740 break;
7743 /* If there is unread keyboard input, also return. */
7744 if (read_kbd
7745 && requeued_events_pending_p ())
7746 break;
7748 /* If wait_for_cell. check for keyboard input
7749 but don't run any timers.
7750 ??? (It seems wrong to me to check for keyboard
7751 input at all when wait_for_cell, but the code
7752 has been this way since July 1994.
7753 Try changing this after version 19.31.) */
7754 if (! NILP (wait_for_cell)
7755 && detect_input_pending ())
7757 swallow_events (do_display);
7758 if (detect_input_pending ())
7759 break;
7762 /* Exit now if the cell we're waiting for became non-nil. */
7763 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7764 break;
7767 start_polling ();
7769 return 0;
7773 /* Don't confuse make-docfile by having two doc strings for this function.
7774 make-docfile does not pay attention to #if, for good reason! */
7775 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7777 (register Lisp_Object name)
7779 return Qnil;
7782 /* Don't confuse make-docfile by having two doc strings for this function.
7783 make-docfile does not pay attention to #if, for good reason! */
7784 DEFUN ("process-inherit-coding-system-flag",
7785 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7786 1, 1, 0,
7788 (register Lisp_Object process)
7790 /* Ignore the argument and return the value of
7791 inherit-process-coding-system. */
7792 return inherit_process_coding_system ? Qt : Qnil;
7795 /* Kill all processes associated with `buffer'.
7796 If `buffer' is nil, kill all processes.
7797 Since we have no subprocesses, this does nothing. */
7799 void
7800 kill_buffer_processes (buffer)
7801 Lisp_Object buffer;
7806 /* Stop reading input from keyboard sources. */
7808 void
7809 hold_keyboard_input (void)
7811 kbd_is_on_hold = 1;
7814 /* Resume reading input from keyboard sources. */
7816 void
7817 unhold_keyboard_input (void)
7819 kbd_is_on_hold = 0;
7822 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7825 kbd_on_hold_p (void)
7827 return kbd_is_on_hold;
7830 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7831 0, 0, 0,
7832 doc: /* Return a list of numerical process IDs of all running processes.
7833 If this functionality is unsupported, return nil.
7835 See `process-attributes' for getting attributes of a process given its ID. */)
7836 (void)
7838 return list_system_processes ();
7841 DEFUN ("process-attributes", Fprocess_attributes,
7842 Sprocess_attributes, 1, 1, 0,
7843 doc: /* Return attributes of the process given by its PID, a number.
7845 Value is an alist where each element is a cons cell of the form
7847 \(KEY . VALUE)
7849 If this functionality is unsupported, the value is nil.
7851 See `list-system-processes' for getting a list of all process IDs.
7853 The KEYs of the attributes that this function may return are listed
7854 below, together with the type of the associated VALUE (in parentheses).
7855 Not all platforms support all of these attributes; unsupported
7856 attributes will not appear in the returned alist.
7857 Unless explicitly indicated otherwise, numbers can have either
7858 integer or floating point values.
7860 euid -- Effective user User ID of the process (number)
7861 user -- User name corresponding to euid (string)
7862 egid -- Effective user Group ID of the process (number)
7863 group -- Group name corresponding to egid (string)
7864 comm -- Command name (executable name only) (string)
7865 state -- Process state code, such as "S", "R", or "T" (string)
7866 ppid -- Parent process ID (number)
7867 pgrp -- Process group ID (number)
7868 sess -- Session ID, i.e. process ID of session leader (number)
7869 ttname -- Controlling tty name (string)
7870 tpgid -- ID of foreground process group on the process's tty (number)
7871 minflt -- number of minor page faults (number)
7872 majflt -- number of major page faults (number)
7873 cminflt -- cumulative number of minor page faults (number)
7874 cmajflt -- cumulative number of major page faults (number)
7875 utime -- user time used by the process, in the (HIGH LOW USEC) format
7876 stime -- system time used by the process, in the (HIGH LOW USEC) format
7877 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7878 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7879 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7880 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7881 pri -- priority of the process (number)
7882 nice -- nice value of the process (number)
7883 thcount -- process thread count (number)
7884 start -- time the process started, in the (HIGH LOW USEC) format
7885 vsize -- virtual memory size of the process in KB's (number)
7886 rss -- resident set size of the process in KB's (number)
7887 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7888 pcpu -- percents of CPU time used by the process (floating-point number)
7889 pmem -- percents of total physical memory used by process's resident set
7890 (floating-point number)
7891 args -- command line which invoked the process (string). */)
7892 ( Lisp_Object pid)
7894 return system_process_attributes (pid);
7897 void
7898 init_process ()
7900 kbd_is_on_hold = 0;
7903 void
7904 syms_of_process ()
7906 QCtype = intern_c_string (":type");
7907 staticpro (&QCtype);
7908 QCname = intern_c_string (":name");
7909 staticpro (&QCname);
7910 QCtype = intern_c_string (":type");
7911 staticpro (&QCtype);
7912 QCname = intern_c_string (":name");
7913 staticpro (&QCname);
7914 Qeuid = intern_c_string ("euid");
7915 staticpro (&Qeuid);
7916 Qegid = intern_c_string ("egid");
7917 staticpro (&Qegid);
7918 Quser = intern_c_string ("user");
7919 staticpro (&Quser);
7920 Qgroup = intern_c_string ("group");
7921 staticpro (&Qgroup);
7922 Qcomm = intern_c_string ("comm");
7923 staticpro (&Qcomm);
7924 Qstate = intern_c_string ("state");
7925 staticpro (&Qstate);
7926 Qppid = intern_c_string ("ppid");
7927 staticpro (&Qppid);
7928 Qpgrp = intern_c_string ("pgrp");
7929 staticpro (&Qpgrp);
7930 Qsess = intern_c_string ("sess");
7931 staticpro (&Qsess);
7932 Qttname = intern_c_string ("ttname");
7933 staticpro (&Qttname);
7934 Qtpgid = intern_c_string ("tpgid");
7935 staticpro (&Qtpgid);
7936 Qminflt = intern_c_string ("minflt");
7937 staticpro (&Qminflt);
7938 Qmajflt = intern_c_string ("majflt");
7939 staticpro (&Qmajflt);
7940 Qcminflt = intern_c_string ("cminflt");
7941 staticpro (&Qcminflt);
7942 Qcmajflt = intern_c_string ("cmajflt");
7943 staticpro (&Qcmajflt);
7944 Qutime = intern_c_string ("utime");
7945 staticpro (&Qutime);
7946 Qstime = intern_c_string ("stime");
7947 staticpro (&Qstime);
7948 Qtime = intern_c_string ("time");
7949 staticpro (&Qtime);
7950 Qcutime = intern_c_string ("cutime");
7951 staticpro (&Qcutime);
7952 Qcstime = intern_c_string ("cstime");
7953 staticpro (&Qcstime);
7954 Qctime = intern_c_string ("ctime");
7955 staticpro (&Qctime);
7956 Qpri = intern_c_string ("pri");
7957 staticpro (&Qpri);
7958 Qnice = intern_c_string ("nice");
7959 staticpro (&Qnice);
7960 Qthcount = intern_c_string ("thcount");
7961 staticpro (&Qthcount);
7962 Qstart = intern_c_string ("start");
7963 staticpro (&Qstart);
7964 Qvsize = intern_c_string ("vsize");
7965 staticpro (&Qvsize);
7966 Qrss = intern_c_string ("rss");
7967 staticpro (&Qrss);
7968 Qetime = intern_c_string ("etime");
7969 staticpro (&Qetime);
7970 Qpcpu = intern_c_string ("pcpu");
7971 staticpro (&Qpcpu);
7972 Qpmem = intern_c_string ("pmem");
7973 staticpro (&Qpmem);
7974 Qargs = intern_c_string ("args");
7975 staticpro (&Qargs);
7977 defsubr (&Sget_buffer_process);
7978 defsubr (&Sprocess_inherit_coding_system_flag);
7979 defsubr (&Slist_system_processes);
7980 defsubr (&Sprocess_attributes);
7984 #endif /* not subprocesses */
7986 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7987 (do not change this comment) */