Introduce a new comment style "c" flag.
[emacs.git] / src / process.c
blob4a6586230775bac62d5fac2367071611f0ab44a4
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* some typedefs are used in sys/file.h */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34 #ifdef STDC_HEADERS
35 #include <stdlib.h>
36 #endif
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #include <fcntl.h>
43 /* Only MS-DOS does not define `subprocesses'. */
44 #ifdef subprocesses
46 #include <sys/socket.h>
47 #include <netdb.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
51 /* Are local (unix) sockets supported? */
52 #if defined (HAVE_SYS_UN_H)
53 #if !defined (AF_LOCAL) && defined (AF_UNIX)
54 #define AF_LOCAL AF_UNIX
55 #endif
56 #ifdef AF_LOCAL
57 #define HAVE_LOCAL_SOCKETS
58 #include <sys/un.h>
59 #endif
60 #endif
62 #if defined(HAVE_SYS_IOCTL_H)
63 #include <sys/ioctl.h>
64 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
65 #include <fcntl.h>
66 #endif /* HAVE_PTYS and no O_NDELAY */
67 #if defined(HAVE_NET_IF_H)
68 #include <net/if.h>
69 #endif /* HAVE_NET_IF_H */
70 #endif /* HAVE_SYS_IOCTL_H */
72 #ifdef NEED_BSDTTY
73 #include <bsdtty.h>
74 #endif
76 #ifdef HAVE_SYS_WAIT
77 #include <sys/wait.h>
78 #endif
80 #ifdef HAVE_RES_INIT
81 #include <netinet/in.h>
82 #include <arpa/nameser.h>
83 #include <resolv.h>
84 #endif
86 #ifdef HAVE_UTIL_H
87 #include <util.h>
88 #endif
90 #endif /* subprocesses */
92 #include "lisp.h"
93 #include "systime.h"
94 #include "systty.h"
96 #include "window.h"
97 #include "buffer.h"
98 #include "character.h"
99 #include "coding.h"
100 #include "process.h"
101 #include "frame.h"
102 #include "termhooks.h"
103 #include "termopts.h"
104 #include "commands.h"
105 #include "keyboard.h"
106 #include "blockinput.h"
107 #include "dispextern.h"
108 #include "composite.h"
109 #include "atimer.h"
110 #include "sysselect.h"
111 #include "syssignal.h"
112 #include "syswait.h"
114 #if defined (USE_GTK) || defined (HAVE_GCONF)
115 #include "xgselect.h"
116 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
117 #ifdef HAVE_NS
118 #include "nsterm.h"
119 #endif
120 extern int timers_run;
122 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
123 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
124 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
125 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
126 Lisp_Object QCname, QCtype;
128 /* Non-zero if keyboard input is on hold, zero otherwise. */
130 static int kbd_is_on_hold;
132 /* Nonzero means delete a process right away if it exits. */
133 static int delete_exited_processes;
135 /* Nonzero means don't run process sentinels. This is used
136 when exiting. */
137 int inhibit_sentinels;
139 #ifdef subprocesses
141 Lisp_Object Qprocessp;
142 Lisp_Object Qrun, Qstop, Qsignal;
143 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
144 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
145 Lisp_Object Qreal, Qnetwork, Qserial;
146 #ifdef AF_INET6
147 Lisp_Object Qipv6;
148 #endif
149 Lisp_Object QCport, QCspeed, QCprocess;
150 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
151 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
152 Lisp_Object QCbuffer, QChost, QCservice;
153 Lisp_Object QClocal, QCremote, QCcoding;
154 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
155 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
156 Lisp_Object Qlast_nonmenu_event;
157 /* QCfamily is declared and initialized in xfaces.c,
158 QCfilter in keyboard.c. */
159 extern Lisp_Object QCfamily, QCfilter;
161 /* Qexit is declared and initialized in eval.c. */
163 /* QCfamily is defined in xfaces.c. */
164 extern Lisp_Object QCfamily;
165 /* QCfilter is defined in keyboard.c. */
166 extern Lisp_Object QCfilter;
168 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
169 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
170 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
171 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
173 /* Define first descriptor number available for subprocesses. */
174 #define FIRST_PROC_DESC 3
176 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
177 testing SIGCHLD. */
179 #if !defined (SIGCHLD) && defined (SIGCLD)
180 #define SIGCHLD SIGCLD
181 #endif /* SIGCLD */
183 extern const char *get_operating_system_release (void);
185 /* Serial processes require termios or Windows. */
186 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
187 #define HAVE_SERIAL
188 #endif
190 #ifdef HAVE_SERIAL
191 /* From sysdep.c or w32.c */
192 extern int serial_open (char *port);
193 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
194 #endif
196 #ifndef HAVE_H_ERRNO
197 extern int h_errno;
198 #endif
200 /* t means use pty, nil means use a pipe,
201 maybe other values to come. */
202 static Lisp_Object Vprocess_connection_type;
204 /* These next two vars are non-static since sysdep.c uses them in the
205 emulation of `select'. */
206 /* Number of events of change of status of a process. */
207 int process_tick;
208 /* Number of events for which the user or sentinel has been notified. */
209 int update_tick;
211 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
213 #ifdef BROKEN_NON_BLOCKING_CONNECT
214 #undef NON_BLOCKING_CONNECT
215 #else
216 #ifndef NON_BLOCKING_CONNECT
217 #ifdef HAVE_SELECT
218 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
219 #if defined (O_NONBLOCK) || defined (O_NDELAY)
220 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
221 #define NON_BLOCKING_CONNECT
222 #endif /* EWOULDBLOCK || EINPROGRESS */
223 #endif /* O_NONBLOCK || O_NDELAY */
224 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
225 #endif /* HAVE_SELECT */
226 #endif /* NON_BLOCKING_CONNECT */
227 #endif /* BROKEN_NON_BLOCKING_CONNECT */
229 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
230 this system. We need to read full packets, so we need a
231 "non-destructive" select. So we require either native select,
232 or emulation of select using FIONREAD. */
234 #ifdef BROKEN_DATAGRAM_SOCKETS
235 #undef DATAGRAM_SOCKETS
236 #else
237 #ifndef DATAGRAM_SOCKETS
238 #if defined (HAVE_SELECT) || defined (FIONREAD)
239 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
240 #define DATAGRAM_SOCKETS
241 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
242 #endif /* HAVE_SELECT || FIONREAD */
243 #endif /* DATAGRAM_SOCKETS */
244 #endif /* BROKEN_DATAGRAM_SOCKETS */
246 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
247 # define HAVE_SEQPACKET
248 #endif
250 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
251 #ifdef EMACS_HAS_USECS
252 #define ADAPTIVE_READ_BUFFERING
253 #endif
254 #endif
256 #ifdef ADAPTIVE_READ_BUFFERING
257 #define READ_OUTPUT_DELAY_INCREMENT 10000
258 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
259 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
261 /* Number of processes which have a non-zero read_output_delay,
262 and therefore might be delayed for adaptive read buffering. */
264 static int process_output_delay_count;
266 /* Non-zero if any process has non-nil read_output_skip. */
268 static int process_output_skip;
270 /* Non-nil means to delay reading process output to improve buffering.
271 A value of t means that delay is reset after each send, any other
272 non-nil value does not reset the delay. A value of nil disables
273 adaptive read buffering completely. */
274 static Lisp_Object Vprocess_adaptive_read_buffering;
275 #else
276 #define process_output_delay_count 0
277 #endif
279 static int keyboard_bit_set (SELECT_TYPE *);
280 static void deactivate_process (Lisp_Object);
281 static void status_notify (struct Lisp_Process *);
282 static int read_process_output (Lisp_Object, int);
283 static void create_pty (Lisp_Object);
285 /* If we support a window system, turn on the code to poll periodically
286 to detect C-g. It isn't actually used when doing interrupt input. */
287 #ifdef HAVE_WINDOW_SYSTEM
288 #define POLL_FOR_INPUT
289 #endif
291 static Lisp_Object get_process (register Lisp_Object name);
292 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
294 /* Mask of bits indicating the descriptors that we wait for input on. */
296 static SELECT_TYPE input_wait_mask;
298 /* Mask that excludes keyboard input descriptor(s). */
300 static SELECT_TYPE non_keyboard_wait_mask;
302 /* Mask that excludes process input descriptor(s). */
304 static SELECT_TYPE non_process_wait_mask;
306 /* Mask for the gpm mouse input descriptor. */
308 static SELECT_TYPE gpm_wait_mask;
310 #ifdef NON_BLOCKING_CONNECT
311 /* Mask of bits indicating the descriptors that we wait for connect to
312 complete on. Once they complete, they are removed from this mask
313 and added to the input_wait_mask and non_keyboard_wait_mask. */
315 static SELECT_TYPE connect_wait_mask;
317 /* Number of bits set in connect_wait_mask. */
318 static int num_pending_connects;
320 #define IF_NON_BLOCKING_CONNECT(s) s
321 #else /* NON_BLOCKING_CONNECT */
322 #define IF_NON_BLOCKING_CONNECT(s)
323 #endif /* NON_BLOCKING_CONNECT */
325 /* The largest descriptor currently in use for a process object. */
326 static int max_process_desc;
328 /* The largest descriptor currently in use for keyboard input. */
329 static int max_keyboard_desc;
331 /* The largest descriptor currently in use for gpm mouse input. */
332 static int max_gpm_desc;
334 /* Indexed by descriptor, gives the process (if any) for that descriptor */
335 Lisp_Object chan_process[MAXDESC];
337 /* Alist of elements (NAME . PROCESS) */
338 Lisp_Object Vprocess_alist;
340 /* Buffered-ahead input char from process, indexed by channel.
341 -1 means empty (no char is buffered).
342 Used on sys V where the only way to tell if there is any
343 output from the process is to read at least one char.
344 Always -1 on systems that support FIONREAD. */
346 /* Don't make static; need to access externally. */
347 int proc_buffered_char[MAXDESC];
349 /* Table of `struct coding-system' for each process. */
350 static struct coding_system *proc_decode_coding_system[MAXDESC];
351 static struct coding_system *proc_encode_coding_system[MAXDESC];
353 #ifdef DATAGRAM_SOCKETS
354 /* Table of `partner address' for datagram sockets. */
355 struct sockaddr_and_len {
356 struct sockaddr *sa;
357 int len;
358 } datagram_address[MAXDESC];
359 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
360 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
361 #else
362 #define DATAGRAM_CHAN_P(chan) (0)
363 #define DATAGRAM_CONN_P(proc) (0)
364 #endif
366 /* Maximum number of bytes to send to a pty without an eof. */
367 static int pty_max_bytes;
369 #ifdef HAVE_PTYS
370 #ifdef HAVE_PTY_H
371 #include <pty.h>
372 #endif
373 /* The file name of the pty opened by allocate_pty. */
375 static char pty_name[24];
376 #endif
378 /* Compute the Lisp form of the process status, p->status, from
379 the numeric status that was returned by `wait'. */
381 static Lisp_Object status_convert (int);
383 static void
384 update_status (struct Lisp_Process *p)
386 eassert (p->raw_status_new);
387 p->status = status_convert (p->raw_status);
388 p->raw_status_new = 0;
391 /* Convert a process status word in Unix format to
392 the list that we use internally. */
394 static Lisp_Object
395 status_convert (int w)
397 if (WIFSTOPPED (w))
398 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
399 else if (WIFEXITED (w))
400 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
401 WCOREDUMP (w) ? Qt : Qnil));
402 else if (WIFSIGNALED (w))
403 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
404 WCOREDUMP (w) ? Qt : Qnil));
405 else
406 return Qrun;
409 /* Given a status-list, extract the three pieces of information
410 and store them individually through the three pointers. */
412 static void
413 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
415 Lisp_Object tem;
417 if (SYMBOLP (l))
419 *symbol = l;
420 *code = 0;
421 *coredump = 0;
423 else
425 *symbol = XCAR (l);
426 tem = XCDR (l);
427 *code = XFASTINT (XCAR (tem));
428 tem = XCDR (tem);
429 *coredump = !NILP (tem);
433 /* Return a string describing a process status list. */
435 static Lisp_Object
436 status_message (struct Lisp_Process *p)
438 Lisp_Object status = p->status;
439 Lisp_Object symbol;
440 int code, coredump;
441 Lisp_Object string, string2;
443 decode_status (status, &symbol, &code, &coredump);
445 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
447 char *signame;
448 synchronize_system_messages_locale ();
449 signame = strsignal (code);
450 if (signame == 0)
451 string = build_string ("unknown");
452 else
454 int c1, c2;
456 string = make_unibyte_string (signame, strlen (signame));
457 if (! NILP (Vlocale_coding_system))
458 string = (code_convert_string_norecord
459 (string, Vlocale_coding_system, 0));
460 c1 = STRING_CHAR ((char *) SDATA (string));
461 c2 = DOWNCASE (c1);
462 if (c1 != c2)
463 Faset (string, make_number (0), make_number (c2));
465 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
466 return concat2 (string, string2);
468 else if (EQ (symbol, Qexit))
470 if (NETCONN1_P (p))
471 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
472 if (code == 0)
473 return build_string ("finished\n");
474 string = Fnumber_to_string (make_number (code));
475 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
476 return concat3 (build_string ("exited abnormally with code "),
477 string, string2);
479 else if (EQ (symbol, Qfailed))
481 string = Fnumber_to_string (make_number (code));
482 string2 = build_string ("\n");
483 return concat3 (build_string ("failed with code "),
484 string, string2);
486 else
487 return Fcopy_sequence (Fsymbol_name (symbol));
490 #ifdef HAVE_PTYS
492 /* Open an available pty, returning a file descriptor.
493 Return -1 on failure.
494 The file name of the terminal corresponding to the pty
495 is left in the variable pty_name. */
497 static int
498 allocate_pty (void)
500 register int c, i;
501 int fd;
503 #ifdef PTY_ITERATION
504 PTY_ITERATION
505 #else
506 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
507 for (i = 0; i < 16; i++)
508 #endif
510 struct stat stb; /* Used in some PTY_OPEN. */
511 #ifdef PTY_NAME_SPRINTF
512 PTY_NAME_SPRINTF
513 #else
514 sprintf (pty_name, "/dev/pty%c%x", c, i);
515 #endif /* no PTY_NAME_SPRINTF */
517 #ifdef PTY_OPEN
518 PTY_OPEN;
519 #else /* no PTY_OPEN */
521 { /* Some systems name their pseudoterminals so that there are gaps in
522 the usual sequence - for example, on HP9000/S700 systems, there
523 are no pseudoterminals with names ending in 'f'. So we wait for
524 three failures in a row before deciding that we've reached the
525 end of the ptys. */
526 int failed_count = 0;
528 if (stat (pty_name, &stb) < 0)
530 failed_count++;
531 if (failed_count >= 3)
532 return -1;
534 else
535 failed_count = 0;
537 # ifdef O_NONBLOCK
538 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
539 # else
540 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
541 # endif
543 #endif /* no PTY_OPEN */
545 if (fd >= 0)
547 /* check to make certain that both sides are available
548 this avoids a nasty yet stupid bug in rlogins */
549 #ifdef PTY_TTY_NAME_SPRINTF
550 PTY_TTY_NAME_SPRINTF
551 #else
552 sprintf (pty_name, "/dev/tty%c%x", c, i);
553 #endif /* no PTY_TTY_NAME_SPRINTF */
554 if (access (pty_name, 6) != 0)
556 emacs_close (fd);
557 # ifndef __sgi
558 continue;
559 # else
560 return -1;
561 # endif /* __sgi */
563 setup_pty (fd);
564 return fd;
567 return -1;
569 #endif /* HAVE_PTYS */
571 static Lisp_Object
572 make_process (Lisp_Object name)
574 register Lisp_Object val, tem, name1;
575 register struct Lisp_Process *p;
576 char suffix[10];
577 register int i;
579 p = allocate_process ();
581 p->infd = -1;
582 p->outfd = -1;
583 p->tick = 0;
584 p->update_tick = 0;
585 p->pid = 0;
586 p->pty_flag = 0;
587 p->raw_status_new = 0;
588 p->status = Qrun;
589 p->mark = Fmake_marker ();
590 p->kill_without_query = 0;
592 #ifdef ADAPTIVE_READ_BUFFERING
593 p->adaptive_read_buffering = 0;
594 p->read_output_delay = 0;
595 p->read_output_skip = 0;
596 #endif
598 /* If name is already in use, modify it until it is unused. */
600 name1 = name;
601 for (i = 1; ; i++)
603 tem = Fget_process (name1);
604 if (NILP (tem)) break;
605 sprintf (suffix, "<%d>", i);
606 name1 = concat2 (name, build_string (suffix));
608 name = name1;
609 p->name = name;
610 XSETPROCESS (val, p);
611 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
612 return val;
615 static void
616 remove_process (register Lisp_Object proc)
618 register Lisp_Object pair;
620 pair = Frassq (proc, Vprocess_alist);
621 Vprocess_alist = Fdelq (pair, Vprocess_alist);
623 deactivate_process (proc);
627 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
628 doc: /* Return t if OBJECT is a process. */)
629 (Lisp_Object object)
631 return PROCESSP (object) ? Qt : Qnil;
634 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
635 doc: /* Return the process named NAME, or nil if there is none. */)
636 (register Lisp_Object name)
638 if (PROCESSP (name))
639 return name;
640 CHECK_STRING (name);
641 return Fcdr (Fassoc (name, Vprocess_alist));
644 /* This is how commands for the user decode process arguments. It
645 accepts a process, a process name, a buffer, a buffer name, or nil.
646 Buffers denote the first process in the buffer, and nil denotes the
647 current buffer. */
649 static Lisp_Object
650 get_process (register Lisp_Object name)
652 register Lisp_Object proc, obj;
653 if (STRINGP (name))
655 obj = Fget_process (name);
656 if (NILP (obj))
657 obj = Fget_buffer (name);
658 if (NILP (obj))
659 error ("Process %s does not exist", SDATA (name));
661 else if (NILP (name))
662 obj = Fcurrent_buffer ();
663 else
664 obj = name;
666 /* Now obj should be either a buffer object or a process object.
668 if (BUFFERP (obj))
670 proc = Fget_buffer_process (obj);
671 if (NILP (proc))
672 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
674 else
676 CHECK_PROCESS (obj);
677 proc = obj;
679 return proc;
683 #ifdef SIGCHLD
684 /* Fdelete_process promises to immediately forget about the process, but in
685 reality, Emacs needs to remember those processes until they have been
686 treated by sigchld_handler; otherwise this handler would consider the
687 process as being synchronous and say that the synchronous process is
688 dead. */
689 static Lisp_Object deleted_pid_list;
690 #endif
692 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
693 doc: /* Delete PROCESS: kill it and forget about it immediately.
694 PROCESS may be a process, a buffer, the name of a process or buffer, or
695 nil, indicating the current buffer's process. */)
696 (register Lisp_Object process)
698 register struct Lisp_Process *p;
700 process = get_process (process);
701 p = XPROCESS (process);
703 p->raw_status_new = 0;
704 if (NETCONN1_P (p) || SERIALCONN1_P (p))
706 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
707 p->tick = ++process_tick;
708 status_notify (p);
709 redisplay_preserve_echo_area (13);
711 else if (p->infd >= 0)
713 #ifdef SIGCHLD
714 Lisp_Object symbol;
715 /* Assignment to EMACS_INT stops GCC whining about limited range
716 of data type. */
717 EMACS_INT pid = p->pid;
719 /* No problem storing the pid here, as it is still in Vprocess_alist. */
720 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
721 /* GC treated elements set to nil. */
722 Fdelq (Qnil, deleted_pid_list));
723 /* If the process has already signaled, remove it from the list. */
724 if (p->raw_status_new)
725 update_status (p);
726 symbol = p->status;
727 if (CONSP (p->status))
728 symbol = XCAR (p->status);
729 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
730 deleted_pid_list
731 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
732 else
733 #endif
735 Fkill_process (process, Qnil);
736 /* Do this now, since remove_process will make sigchld_handler do nothing. */
737 p->status
738 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
739 p->tick = ++process_tick;
740 status_notify (p);
741 redisplay_preserve_echo_area (13);
744 remove_process (process);
745 return Qnil;
748 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
749 doc: /* Return the status of PROCESS.
750 The returned value is one of the following symbols:
751 run -- for a process that is running.
752 stop -- for a process stopped but continuable.
753 exit -- for a process that has exited.
754 signal -- for a process that has got a fatal signal.
755 open -- for a network stream connection that is open.
756 listen -- for a network stream server that is listening.
757 closed -- for a network stream connection that is closed.
758 connect -- when waiting for a non-blocking connection to complete.
759 failed -- when a non-blocking connection has failed.
760 nil -- if arg is a process name and no such process exists.
761 PROCESS may be a process, a buffer, the name of a process, or
762 nil, indicating the current buffer's process. */)
763 (register Lisp_Object process)
765 register struct Lisp_Process *p;
766 register Lisp_Object status;
768 if (STRINGP (process))
769 process = Fget_process (process);
770 else
771 process = get_process (process);
773 if (NILP (process))
774 return process;
776 p = XPROCESS (process);
777 if (p->raw_status_new)
778 update_status (p);
779 status = p->status;
780 if (CONSP (status))
781 status = XCAR (status);
782 if (NETCONN1_P (p) || SERIALCONN1_P (p))
784 if (EQ (status, Qexit))
785 status = Qclosed;
786 else if (EQ (p->command, Qt))
787 status = Qstop;
788 else if (EQ (status, Qrun))
789 status = Qopen;
791 return status;
794 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
795 1, 1, 0,
796 doc: /* Return the exit status of PROCESS or the signal number that killed it.
797 If PROCESS has not yet exited or died, return 0. */)
798 (register Lisp_Object process)
800 CHECK_PROCESS (process);
801 if (XPROCESS (process)->raw_status_new)
802 update_status (XPROCESS (process));
803 if (CONSP (XPROCESS (process)->status))
804 return XCAR (XCDR (XPROCESS (process)->status));
805 return make_number (0);
808 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
809 doc: /* Return the process id of PROCESS.
810 This is the pid of the external process which PROCESS uses or talks to.
811 For a network connection, this value is nil. */)
812 (register Lisp_Object process)
814 /* Assignment to EMACS_INT stops GCC whining about limited range of
815 data type. */
816 EMACS_INT pid;
818 CHECK_PROCESS (process);
819 pid = XPROCESS (process)->pid;
820 return (pid ? make_fixnum_or_float (pid) : Qnil);
823 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
824 doc: /* Return the name of PROCESS, as a string.
825 This is the name of the program invoked in PROCESS,
826 possibly modified to make it unique among process names. */)
827 (register Lisp_Object process)
829 CHECK_PROCESS (process);
830 return XPROCESS (process)->name;
833 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
834 doc: /* Return the command that was executed to start PROCESS.
835 This is a list of strings, the first string being the program executed
836 and the rest of the strings being the arguments given to it.
837 For a network or serial process, this is nil (process is running) or t
838 \(process is stopped). */)
839 (register Lisp_Object process)
841 CHECK_PROCESS (process);
842 return XPROCESS (process)->command;
845 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
846 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
847 This is the terminal that the process itself reads and writes on,
848 not the name of the pty that Emacs uses to talk with that terminal. */)
849 (register Lisp_Object process)
851 CHECK_PROCESS (process);
852 return XPROCESS (process)->tty_name;
855 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
856 2, 2, 0,
857 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
858 (register Lisp_Object process, Lisp_Object buffer)
860 struct Lisp_Process *p;
862 CHECK_PROCESS (process);
863 if (!NILP (buffer))
864 CHECK_BUFFER (buffer);
865 p = XPROCESS (process);
866 p->buffer = buffer;
867 if (NETCONN1_P (p) || SERIALCONN1_P (p))
868 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
869 setup_process_coding_systems (process);
870 return buffer;
873 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
874 1, 1, 0,
875 doc: /* Return the buffer PROCESS is associated with.
876 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
877 (register Lisp_Object process)
879 CHECK_PROCESS (process);
880 return XPROCESS (process)->buffer;
883 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
884 1, 1, 0,
885 doc: /* Return the marker for the end of the last output from PROCESS. */)
886 (register Lisp_Object process)
888 CHECK_PROCESS (process);
889 return XPROCESS (process)->mark;
892 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
893 2, 2, 0,
894 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
895 A value of t means stop accepting output from the process.
897 When a process has a filter, its buffer is not used for output.
898 Instead, each time it does output, the entire string of output is
899 passed to the filter.
901 The filter gets two arguments: the process and the string of output.
902 The string argument is normally a multibyte string, except:
903 - if the process' input coding system is no-conversion or raw-text,
904 it is a unibyte string (the non-converted input), or else
905 - if `default-enable-multibyte-characters' is nil, it is a unibyte
906 string (the result of converting the decoded input multibyte
907 string to unibyte with `string-make-unibyte'). */)
908 (register Lisp_Object process, Lisp_Object filter)
910 struct Lisp_Process *p;
912 CHECK_PROCESS (process);
913 p = XPROCESS (process);
915 /* Don't signal an error if the process' input file descriptor
916 is closed. This could make debugging Lisp more difficult,
917 for example when doing something like
919 (setq process (start-process ...))
920 (debug)
921 (set-process-filter process ...) */
923 if (p->infd >= 0)
925 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
927 FD_CLR (p->infd, &input_wait_mask);
928 FD_CLR (p->infd, &non_keyboard_wait_mask);
930 else if (EQ (p->filter, Qt)
931 /* Network or serial process not stopped: */
932 && !EQ (p->command, Qt))
934 FD_SET (p->infd, &input_wait_mask);
935 FD_SET (p->infd, &non_keyboard_wait_mask);
939 p->filter = filter;
940 if (NETCONN1_P (p) || SERIALCONN1_P (p))
941 p->childp = Fplist_put (p->childp, QCfilter, filter);
942 setup_process_coding_systems (process);
943 return filter;
946 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
947 1, 1, 0,
948 doc: /* Returns the filter function of PROCESS; nil if none.
949 See `set-process-filter' for more info on filter functions. */)
950 (register Lisp_Object process)
952 CHECK_PROCESS (process);
953 return XPROCESS (process)->filter;
956 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
957 2, 2, 0,
958 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
959 The sentinel is called as a function when the process changes state.
960 It gets two arguments: the process, and a string describing the change. */)
961 (register Lisp_Object process, Lisp_Object sentinel)
963 struct Lisp_Process *p;
965 CHECK_PROCESS (process);
966 p = XPROCESS (process);
968 p->sentinel = sentinel;
969 if (NETCONN1_P (p) || SERIALCONN1_P (p))
970 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
971 return sentinel;
974 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
975 1, 1, 0,
976 doc: /* Return the sentinel of PROCESS; nil if none.
977 See `set-process-sentinel' for more info on sentinels. */)
978 (register Lisp_Object process)
980 CHECK_PROCESS (process);
981 return XPROCESS (process)->sentinel;
984 DEFUN ("set-process-window-size", Fset_process_window_size,
985 Sset_process_window_size, 3, 3, 0,
986 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
987 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
989 CHECK_PROCESS (process);
990 CHECK_NATNUM (height);
991 CHECK_NATNUM (width);
993 if (XPROCESS (process)->infd < 0
994 || set_window_size (XPROCESS (process)->infd,
995 XINT (height), XINT (width)) <= 0)
996 return Qnil;
997 else
998 return Qt;
1001 DEFUN ("set-process-inherit-coding-system-flag",
1002 Fset_process_inherit_coding_system_flag,
1003 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1004 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1005 If the second argument FLAG is non-nil, then the variable
1006 `buffer-file-coding-system' of the buffer associated with PROCESS
1007 will be bound to the value of the coding system used to decode
1008 the process output.
1010 This is useful when the coding system specified for the process buffer
1011 leaves either the character code conversion or the end-of-line conversion
1012 unspecified, or if the coding system used to decode the process output
1013 is more appropriate for saving the process buffer.
1015 Binding the variable `inherit-process-coding-system' to non-nil before
1016 starting the process is an alternative way of setting the inherit flag
1017 for the process which will run. */)
1018 (register Lisp_Object process, Lisp_Object flag)
1020 CHECK_PROCESS (process);
1021 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1022 return flag;
1025 DEFUN ("set-process-query-on-exit-flag",
1026 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1027 2, 2, 0,
1028 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1029 If the second argument FLAG is non-nil, Emacs will query the user before
1030 exiting or killing a buffer if PROCESS is running. */)
1031 (register Lisp_Object process, Lisp_Object flag)
1033 CHECK_PROCESS (process);
1034 XPROCESS (process)->kill_without_query = NILP (flag);
1035 return flag;
1038 DEFUN ("process-query-on-exit-flag",
1039 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1040 1, 1, 0,
1041 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1042 (register Lisp_Object process)
1044 CHECK_PROCESS (process);
1045 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1048 #ifdef DATAGRAM_SOCKETS
1049 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1050 #endif
1052 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1053 1, 2, 0,
1054 doc: /* Return the contact info of PROCESS; t for a real child.
1055 For a network or serial connection, the value depends on the optional
1056 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1057 SERVICE) for a network connection or (PORT SPEED) for a serial
1058 connection. If KEY is t, the complete contact information for the
1059 connection is returned, else the specific value for the keyword KEY is
1060 returned. See `make-network-process' or `make-serial-process' for a
1061 list of keywords. */)
1062 (register Lisp_Object process, Lisp_Object key)
1064 Lisp_Object contact;
1066 CHECK_PROCESS (process);
1067 contact = XPROCESS (process)->childp;
1069 #ifdef DATAGRAM_SOCKETS
1070 if (DATAGRAM_CONN_P (process)
1071 && (EQ (key, Qt) || EQ (key, QCremote)))
1072 contact = Fplist_put (contact, QCremote,
1073 Fprocess_datagram_address (process));
1074 #endif
1076 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1077 return contact;
1078 if (NILP (key) && NETCONN_P (process))
1079 return Fcons (Fplist_get (contact, QChost),
1080 Fcons (Fplist_get (contact, QCservice), Qnil));
1081 if (NILP (key) && SERIALCONN_P (process))
1082 return Fcons (Fplist_get (contact, QCport),
1083 Fcons (Fplist_get (contact, QCspeed), Qnil));
1084 return Fplist_get (contact, key);
1087 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1088 1, 1, 0,
1089 doc: /* Return the plist of PROCESS. */)
1090 (register Lisp_Object process)
1092 CHECK_PROCESS (process);
1093 return XPROCESS (process)->plist;
1096 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1097 2, 2, 0,
1098 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1099 (register Lisp_Object process, Lisp_Object plist)
1101 CHECK_PROCESS (process);
1102 CHECK_LIST (plist);
1104 XPROCESS (process)->plist = plist;
1105 return plist;
1108 #if 0 /* Turned off because we don't currently record this info
1109 in the process. Perhaps add it. */
1110 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1111 doc: /* Return the connection type of PROCESS.
1112 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1113 a socket connection. */)
1114 (Lisp_Object process)
1116 return XPROCESS (process)->type;
1118 #endif
1120 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1121 doc: /* Return the connection type of PROCESS.
1122 The value is either the symbol `real', `network', or `serial'.
1123 PROCESS may be a process, a buffer, the name of a process or buffer, or
1124 nil, indicating the current buffer's process. */)
1125 (Lisp_Object process)
1127 Lisp_Object proc;
1128 proc = get_process (process);
1129 return XPROCESS (proc)->type;
1132 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1133 1, 2, 0,
1134 doc: /* Convert network ADDRESS from internal format to a string.
1135 A 4 or 5 element vector represents an IPv4 address (with port number).
1136 An 8 or 9 element vector represents an IPv6 address (with port number).
1137 If optional second argument OMIT-PORT is non-nil, don't include a port
1138 number in the string, even when present in ADDRESS.
1139 Returns nil if format of ADDRESS is invalid. */)
1140 (Lisp_Object address, Lisp_Object omit_port)
1142 if (NILP (address))
1143 return Qnil;
1145 if (STRINGP (address)) /* AF_LOCAL */
1146 return address;
1148 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1150 register struct Lisp_Vector *p = XVECTOR (address);
1151 Lisp_Object args[10];
1152 int nargs, i;
1154 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1156 args[0] = build_string ("%d.%d.%d.%d");
1157 nargs = 4;
1159 else if (p->size == 5)
1161 args[0] = build_string ("%d.%d.%d.%d:%d");
1162 nargs = 5;
1164 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1166 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1167 nargs = 8;
1169 else if (p->size == 9)
1171 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1172 nargs = 9;
1174 else
1175 return Qnil;
1177 for (i = 0; i < nargs; i++)
1179 EMACS_INT element = XINT (p->contents[i]);
1181 if (element < 0 || element > 65535)
1182 return Qnil;
1184 if (nargs <= 5 /* IPv4 */
1185 && i < 4 /* host, not port */
1186 && element > 255)
1187 return Qnil;
1189 args[i+1] = p->contents[i];
1192 return Fformat (nargs+1, args);
1195 if (CONSP (address))
1197 Lisp_Object args[2];
1198 args[0] = build_string ("<Family %d>");
1199 args[1] = Fcar (address);
1200 return Fformat (2, args);
1203 return Qnil;
1206 static Lisp_Object
1207 list_processes_1 (Lisp_Object query_only)
1209 register Lisp_Object tail, tem;
1210 Lisp_Object proc, minspace, tem1;
1211 register struct Lisp_Process *p;
1212 char tembuf[300];
1213 int w_proc, w_buffer, w_tty;
1214 int exited = 0;
1215 Lisp_Object i_status, i_buffer, i_tty, i_command;
1217 w_proc = 4; /* Proc */
1218 w_buffer = 6; /* Buffer */
1219 w_tty = 0; /* Omit if no ttys */
1221 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1223 int i;
1225 proc = Fcdr (XCAR (tail));
1226 p = XPROCESS (proc);
1227 if (NILP (p->type))
1228 continue;
1229 if (!NILP (query_only) && p->kill_without_query)
1230 continue;
1231 if (STRINGP (p->name)
1232 && ( i = SCHARS (p->name), (i > w_proc)))
1233 w_proc = i;
1234 if (!NILP (p->buffer))
1236 if (NILP (XBUFFER (p->buffer)->name))
1238 if (w_buffer < 8)
1239 w_buffer = 8; /* (Killed) */
1241 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1242 w_buffer = i;
1244 if (STRINGP (p->tty_name)
1245 && (i = SCHARS (p->tty_name), (i > w_tty)))
1246 w_tty = i;
1249 XSETFASTINT (i_status, w_proc + 1);
1250 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1251 if (w_tty)
1253 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1254 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1256 else
1258 i_tty = Qnil;
1259 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1262 XSETFASTINT (minspace, 1);
1264 set_buffer_internal (XBUFFER (Vstandard_output));
1265 current_buffer->undo_list = Qt;
1267 current_buffer->truncate_lines = Qt;
1269 write_string ("Proc", -1);
1270 Findent_to (i_status, minspace); write_string ("Status", -1);
1271 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1272 if (!NILP (i_tty))
1274 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1276 Findent_to (i_command, minspace); write_string ("Command", -1);
1277 write_string ("\n", -1);
1279 write_string ("----", -1);
1280 Findent_to (i_status, minspace); write_string ("------", -1);
1281 Findent_to (i_buffer, minspace); write_string ("------", -1);
1282 if (!NILP (i_tty))
1284 Findent_to (i_tty, minspace); write_string ("---", -1);
1286 Findent_to (i_command, minspace); write_string ("-------", -1);
1287 write_string ("\n", -1);
1289 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1291 Lisp_Object symbol;
1293 proc = Fcdr (XCAR (tail));
1294 p = XPROCESS (proc);
1295 if (NILP (p->type))
1296 continue;
1297 if (!NILP (query_only) && p->kill_without_query)
1298 continue;
1300 Finsert (1, &p->name);
1301 Findent_to (i_status, minspace);
1303 if (p->raw_status_new)
1304 update_status (p);
1305 symbol = p->status;
1306 if (CONSP (p->status))
1307 symbol = XCAR (p->status);
1309 if (EQ (symbol, Qsignal))
1311 Lisp_Object tem;
1312 tem = Fcar (Fcdr (p->status));
1313 Fprinc (symbol, Qnil);
1315 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1317 if (EQ (symbol, Qexit))
1318 write_string ("closed", -1);
1319 else if (EQ (p->command, Qt))
1320 write_string ("stopped", -1);
1321 else if (EQ (symbol, Qrun))
1322 write_string ("open", -1);
1323 else
1324 Fprinc (symbol, Qnil);
1326 else if (SERIALCONN1_P (p))
1328 write_string ("running", -1);
1330 else
1331 Fprinc (symbol, Qnil);
1333 if (EQ (symbol, Qexit))
1335 Lisp_Object tem;
1336 tem = Fcar (Fcdr (p->status));
1337 if (XFASTINT (tem))
1339 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1340 write_string (tembuf, -1);
1344 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1345 exited++;
1347 Findent_to (i_buffer, minspace);
1348 if (NILP (p->buffer))
1349 insert_string ("(none)");
1350 else if (NILP (XBUFFER (p->buffer)->name))
1351 insert_string ("(Killed)");
1352 else
1353 Finsert (1, &XBUFFER (p->buffer)->name);
1355 if (!NILP (i_tty))
1357 Findent_to (i_tty, minspace);
1358 if (STRINGP (p->tty_name))
1359 Finsert (1, &p->tty_name);
1362 Findent_to (i_command, minspace);
1364 if (EQ (p->status, Qlisten))
1366 Lisp_Object port = Fplist_get (p->childp, QCservice);
1367 if (INTEGERP (port))
1368 port = Fnumber_to_string (port);
1369 if (NILP (port))
1370 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1371 sprintf (tembuf, "(network %s server on %s)\n",
1372 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1373 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1374 insert_string (tembuf);
1376 else if (NETCONN1_P (p))
1378 /* For a local socket, there is no host name,
1379 so display service instead. */
1380 Lisp_Object host = Fplist_get (p->childp, QChost);
1381 if (!STRINGP (host))
1383 host = Fplist_get (p->childp, QCservice);
1384 if (INTEGERP (host))
1385 host = Fnumber_to_string (host);
1387 if (NILP (host))
1388 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1389 sprintf (tembuf, "(network %s connection to %s)\n",
1390 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1391 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1392 insert_string (tembuf);
1394 else if (SERIALCONN1_P (p))
1396 Lisp_Object port = Fplist_get (p->childp, QCport);
1397 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1398 insert_string ("(serial port ");
1399 if (STRINGP (port))
1400 insert_string (SDATA (port));
1401 else
1402 insert_string ("?");
1403 if (INTEGERP (speed))
1405 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1406 insert_string (tembuf);
1408 insert_string (")\n");
1410 else
1412 tem = p->command;
1413 while (1)
1415 tem1 = Fcar (tem);
1416 if (NILP (tem1))
1417 break;
1418 Finsert (1, &tem1);
1419 tem = Fcdr (tem);
1420 if (NILP (tem))
1421 break;
1422 insert_string (" ");
1424 insert_string ("\n");
1427 if (exited)
1429 status_notify (NULL);
1430 redisplay_preserve_echo_area (13);
1432 return Qnil;
1435 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1436 doc: /* Display a list of all processes.
1437 If optional argument QUERY-ONLY is non-nil, only processes with
1438 the query-on-exit flag set will be listed.
1439 Any process listed as exited or signaled is actually eliminated
1440 after the listing is made. */)
1441 (Lisp_Object query_only)
1443 internal_with_output_to_temp_buffer ("*Process List*",
1444 list_processes_1, query_only);
1445 return Qnil;
1448 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1449 doc: /* Return a list of all processes. */)
1450 (void)
1452 return Fmapcar (Qcdr, Vprocess_alist);
1455 /* Starting asynchronous inferior processes. */
1457 static Lisp_Object start_process_unwind (Lisp_Object proc);
1459 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1460 doc: /* Start a program in a subprocess. Return the process object for it.
1461 NAME is name for process. It is modified if necessary to make it unique.
1462 BUFFER is the buffer (or buffer name) to associate with the process.
1464 Process output (both standard output and standard error streams) goes
1465 at end of BUFFER, unless you specify an output stream or filter
1466 function to handle the output. BUFFER may also be nil, meaning that
1467 this process is not associated with any buffer.
1469 PROGRAM is the program file name. It is searched for in PATH. If
1470 nil, just associate a pty with the buffer. Remaining arguments are
1471 strings to give program as arguments.
1473 If you want to separate standard output from standard error, invoke
1474 the command through a shell and redirect one of them using the shell
1475 syntax.
1477 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1478 (int nargs, register Lisp_Object *args)
1480 Lisp_Object buffer, name, program, proc, current_dir, tem;
1481 register unsigned char **new_argv;
1482 register int i;
1483 int count = SPECPDL_INDEX ();
1485 buffer = args[1];
1486 if (!NILP (buffer))
1487 buffer = Fget_buffer_create (buffer);
1489 /* Make sure that the child will be able to chdir to the current
1490 buffer's current directory, or its unhandled equivalent. We
1491 can't just have the child check for an error when it does the
1492 chdir, since it's in a vfork.
1494 We have to GCPRO around this because Fexpand_file_name and
1495 Funhandled_file_name_directory might call a file name handling
1496 function. The argument list is protected by the caller, so all
1497 we really have to worry about is buffer. */
1499 struct gcpro gcpro1, gcpro2;
1501 current_dir = current_buffer->directory;
1503 GCPRO2 (buffer, current_dir);
1505 current_dir = Funhandled_file_name_directory (current_dir);
1506 if (NILP (current_dir))
1507 /* If the file name handler says that current_dir is unreachable, use
1508 a sensible default. */
1509 current_dir = build_string ("~/");
1510 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1511 if (NILP (Ffile_accessible_directory_p (current_dir)))
1512 report_file_error ("Setting current directory",
1513 Fcons (current_buffer->directory, Qnil));
1515 UNGCPRO;
1518 name = args[0];
1519 CHECK_STRING (name);
1521 program = args[2];
1523 if (!NILP (program))
1524 CHECK_STRING (program);
1526 proc = make_process (name);
1527 /* If an error occurs and we can't start the process, we want to
1528 remove it from the process list. This means that each error
1529 check in create_process doesn't need to call remove_process
1530 itself; it's all taken care of here. */
1531 record_unwind_protect (start_process_unwind, proc);
1533 XPROCESS (proc)->childp = Qt;
1534 XPROCESS (proc)->plist = Qnil;
1535 XPROCESS (proc)->type = Qreal;
1536 XPROCESS (proc)->buffer = buffer;
1537 XPROCESS (proc)->sentinel = Qnil;
1538 XPROCESS (proc)->filter = Qnil;
1539 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1541 #ifdef ADAPTIVE_READ_BUFFERING
1542 XPROCESS (proc)->adaptive_read_buffering
1543 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1544 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1545 #endif
1547 /* Make the process marker point into the process buffer (if any). */
1548 if (BUFFERP (buffer))
1549 set_marker_both (XPROCESS (proc)->mark, buffer,
1550 BUF_ZV (XBUFFER (buffer)),
1551 BUF_ZV_BYTE (XBUFFER (buffer)));
1554 /* Decide coding systems for communicating with the process. Here
1555 we don't setup the structure coding_system nor pay attention to
1556 unibyte mode. They are done in create_process. */
1558 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1559 Lisp_Object coding_systems = Qt;
1560 Lisp_Object val, *args2;
1561 struct gcpro gcpro1, gcpro2;
1563 val = Vcoding_system_for_read;
1564 if (NILP (val))
1566 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1567 args2[0] = Qstart_process;
1568 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1569 GCPRO2 (proc, current_dir);
1570 if (!NILP (program))
1571 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1572 UNGCPRO;
1573 if (CONSP (coding_systems))
1574 val = XCAR (coding_systems);
1575 else if (CONSP (Vdefault_process_coding_system))
1576 val = XCAR (Vdefault_process_coding_system);
1578 XPROCESS (proc)->decode_coding_system = val;
1580 val = Vcoding_system_for_write;
1581 if (NILP (val))
1583 if (EQ (coding_systems, Qt))
1585 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1586 args2[0] = Qstart_process;
1587 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1588 GCPRO2 (proc, current_dir);
1589 if (!NILP (program))
1590 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1591 UNGCPRO;
1593 if (CONSP (coding_systems))
1594 val = XCDR (coding_systems);
1595 else if (CONSP (Vdefault_process_coding_system))
1596 val = XCDR (Vdefault_process_coding_system);
1598 XPROCESS (proc)->encode_coding_system = val;
1602 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1603 XPROCESS (proc)->decoding_carryover = 0;
1604 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1606 XPROCESS (proc)->inherit_coding_system_flag
1607 = !(NILP (buffer) || !inherit_process_coding_system);
1609 if (!NILP (program))
1611 /* If program file name is not absolute, search our path for it.
1612 Put the name we will really use in TEM. */
1613 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1614 && !(SCHARS (program) > 1
1615 && IS_DEVICE_SEP (SREF (program, 1))))
1617 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1619 tem = Qnil;
1620 GCPRO4 (name, program, buffer, current_dir);
1621 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1622 UNGCPRO;
1623 if (NILP (tem))
1624 report_file_error ("Searching for program", Fcons (program, Qnil));
1625 tem = Fexpand_file_name (tem, Qnil);
1627 else
1629 if (!NILP (Ffile_directory_p (program)))
1630 error ("Specified program for new process is a directory");
1631 tem = program;
1634 /* If program file name starts with /: for quoting a magic name,
1635 discard that. */
1636 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1637 && SREF (tem, 1) == ':')
1638 tem = Fsubstring (tem, make_number (2), Qnil);
1641 struct gcpro gcpro1;
1642 GCPRO1 (tem);
1644 /* Encode the file name and put it in NEW_ARGV.
1645 That's where the child will use it to execute the program. */
1646 tem = Fcons (ENCODE_FILE (tem), Qnil);
1648 /* Here we encode arguments by the coding system used for sending
1649 data to the process. We don't support using different coding
1650 systems for encoding arguments and for encoding data sent to the
1651 process. */
1653 for (i = 3; i < nargs; i++)
1655 tem = Fcons (args[i], tem);
1656 CHECK_STRING (XCAR (tem));
1657 if (STRING_MULTIBYTE (XCAR (tem)))
1658 XSETCAR (tem,
1659 code_convert_string_norecord
1660 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1663 UNGCPRO;
1666 /* Now that everything is encoded we can collect the strings into
1667 NEW_ARGV. */
1668 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1669 new_argv[nargs - 2] = 0;
1671 for (i = nargs - 3; i >= 0; i--)
1673 new_argv[i] = SDATA (XCAR (tem));
1674 tem = XCDR (tem);
1677 create_process (proc, (char **) new_argv, current_dir);
1679 else
1680 create_pty (proc);
1682 return unbind_to (count, proc);
1685 /* This function is the unwind_protect form for Fstart_process. If
1686 PROC doesn't have its pid set, then we know someone has signaled
1687 an error and the process wasn't started successfully, so we should
1688 remove it from the process list. */
1689 static Lisp_Object
1690 start_process_unwind (Lisp_Object proc)
1692 if (!PROCESSP (proc))
1693 abort ();
1695 /* Was PROC started successfully? */
1696 if (XPROCESS (proc)->pid == -1)
1697 remove_process (proc);
1699 return Qnil;
1702 static void
1703 create_process_1 (struct atimer *timer)
1705 /* Nothing to do. */
1709 void
1710 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1712 int inchannel, outchannel;
1713 pid_t pid;
1714 int sv[2];
1715 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1716 int wait_child_setup[2];
1717 #endif
1718 sigset_t procmask;
1719 sigset_t blocked;
1720 struct sigaction sigint_action;
1721 struct sigaction sigquit_action;
1722 #ifdef AIX
1723 struct sigaction sighup_action;
1724 #endif
1725 /* Use volatile to protect variables from being clobbered by longjmp. */
1726 volatile int forkin, forkout;
1727 volatile int pty_flag = 0;
1728 #ifndef USE_CRT_DLL
1729 extern char **environ;
1730 #endif
1732 inchannel = outchannel = -1;
1734 #ifdef HAVE_PTYS
1735 if (!NILP (Vprocess_connection_type))
1736 outchannel = inchannel = allocate_pty ();
1738 if (inchannel >= 0)
1740 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1741 /* On most USG systems it does not work to open the pty's tty here,
1742 then close it and reopen it in the child. */
1743 #ifdef O_NOCTTY
1744 /* Don't let this terminal become our controlling terminal
1745 (in case we don't have one). */
1746 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1747 #else
1748 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1749 #endif
1750 if (forkin < 0)
1751 report_file_error ("Opening pty", Qnil);
1752 #else
1753 forkin = forkout = -1;
1754 #endif /* not USG, or USG_SUBTTY_WORKS */
1755 pty_flag = 1;
1757 else
1758 #endif /* HAVE_PTYS */
1760 int tem;
1761 tem = pipe (sv);
1762 if (tem < 0)
1763 report_file_error ("Creating pipe", Qnil);
1764 inchannel = sv[0];
1765 forkout = sv[1];
1766 tem = pipe (sv);
1767 if (tem < 0)
1769 emacs_close (inchannel);
1770 emacs_close (forkout);
1771 report_file_error ("Creating pipe", Qnil);
1773 outchannel = sv[1];
1774 forkin = sv[0];
1777 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1779 int tem;
1781 tem = pipe (wait_child_setup);
1782 if (tem < 0)
1783 report_file_error ("Creating pipe", Qnil);
1784 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1785 if (tem >= 0)
1786 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1787 if (tem < 0)
1789 emacs_close (wait_child_setup[0]);
1790 emacs_close (wait_child_setup[1]);
1791 report_file_error ("Setting file descriptor flags", Qnil);
1794 #endif
1796 #if 0
1797 /* Replaced by close_process_descs */
1798 set_exclusive_use (inchannel);
1799 set_exclusive_use (outchannel);
1800 #endif
1802 #ifdef O_NONBLOCK
1803 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1804 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1805 #else
1806 #ifdef O_NDELAY
1807 fcntl (inchannel, F_SETFL, O_NDELAY);
1808 fcntl (outchannel, F_SETFL, O_NDELAY);
1809 #endif
1810 #endif
1812 /* Record this as an active process, with its channels.
1813 As a result, child_setup will close Emacs's side of the pipes. */
1814 chan_process[inchannel] = process;
1815 XPROCESS (process)->infd = inchannel;
1816 XPROCESS (process)->outfd = outchannel;
1818 /* Previously we recorded the tty descriptor used in the subprocess.
1819 It was only used for getting the foreground tty process, so now
1820 we just reopen the device (see emacs_get_tty_pgrp) as this is
1821 more portable (see USG_SUBTTY_WORKS above). */
1823 XPROCESS (process)->pty_flag = pty_flag;
1824 XPROCESS (process)->status = Qrun;
1825 setup_process_coding_systems (process);
1827 /* Delay interrupts until we have a chance to store
1828 the new fork's pid in its process structure */
1829 sigemptyset (&blocked);
1830 #ifdef SIGCHLD
1831 sigaddset (&blocked, SIGCHLD);
1832 #endif
1833 #ifdef HAVE_WORKING_VFORK
1834 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1835 this sets the parent's signal handlers as well as the child's.
1836 So delay all interrupts whose handlers the child might munge,
1837 and record the current handlers so they can be restored later. */
1838 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1839 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1840 #ifdef AIX
1841 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1842 #endif
1843 #endif /* HAVE_WORKING_VFORK */
1844 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1846 FD_SET (inchannel, &input_wait_mask);
1847 FD_SET (inchannel, &non_keyboard_wait_mask);
1848 if (inchannel > max_process_desc)
1849 max_process_desc = inchannel;
1851 /* Until we store the proper pid, enable sigchld_handler
1852 to recognize an unknown pid as standing for this process.
1853 It is very important not to let this `marker' value stay
1854 in the table after this function has returned; if it does
1855 it might cause call-process to hang and subsequent asynchronous
1856 processes to get their return values scrambled. */
1857 XPROCESS (process)->pid = -1;
1859 BLOCK_INPUT;
1862 /* child_setup must clobber environ on systems with true vfork.
1863 Protect it from permanent change. */
1864 char **save_environ = environ;
1866 current_dir = ENCODE_FILE (current_dir);
1868 #ifndef WINDOWSNT
1869 pid = vfork ();
1870 if (pid == 0)
1871 #endif /* not WINDOWSNT */
1873 int xforkin = forkin;
1874 int xforkout = forkout;
1876 #if 0 /* This was probably a mistake--it duplicates code later on,
1877 but fails to handle all the cases. */
1878 /* Make sure SIGCHLD is not blocked in the child. */
1879 sigsetmask (SIGEMPTYMASK);
1880 #endif
1882 /* Make the pty be the controlling terminal of the process. */
1883 #ifdef HAVE_PTYS
1884 /* First, disconnect its current controlling terminal. */
1885 #ifdef HAVE_SETSID
1886 /* We tried doing setsid only if pty_flag, but it caused
1887 process_set_signal to fail on SGI when using a pipe. */
1888 setsid ();
1889 /* Make the pty's terminal the controlling terminal. */
1890 if (pty_flag && xforkin >= 0)
1892 #ifdef TIOCSCTTY
1893 /* We ignore the return value
1894 because faith@cs.unc.edu says that is necessary on Linux. */
1895 ioctl (xforkin, TIOCSCTTY, 0);
1896 #endif
1898 #else /* not HAVE_SETSID */
1899 #ifdef USG
1900 /* It's very important to call setpgrp here and no time
1901 afterwards. Otherwise, we lose our controlling tty which
1902 is set when we open the pty. */
1903 setpgrp ();
1904 #endif /* USG */
1905 #endif /* not HAVE_SETSID */
1906 #if defined (HAVE_TERMIOS) && defined (LDISC1)
1907 if (pty_flag && xforkin >= 0)
1909 struct termios t;
1910 tcgetattr (xforkin, &t);
1911 t.c_lflag = LDISC1;
1912 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1913 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1915 #else
1916 #if defined (NTTYDISC) && defined (TIOCSETD)
1917 if (pty_flag && xforkin >= 0)
1919 /* Use new line discipline. */
1920 int ldisc = NTTYDISC;
1921 ioctl (xforkin, TIOCSETD, &ldisc);
1923 #endif
1924 #endif
1925 #ifdef TIOCNOTTY
1926 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1927 can do TIOCSPGRP only to the process's controlling tty. */
1928 if (pty_flag)
1930 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1931 I can't test it since I don't have 4.3. */
1932 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1933 if (j >= 0)
1935 ioctl (j, TIOCNOTTY, 0);
1936 emacs_close (j);
1938 #ifndef USG
1939 /* In order to get a controlling terminal on some versions
1940 of BSD, it is necessary to put the process in pgrp 0
1941 before it opens the terminal. */
1942 #ifdef HAVE_SETPGID
1943 setpgid (0, 0);
1944 #else
1945 setpgrp (0, 0);
1946 #endif
1947 #endif
1949 #endif /* TIOCNOTTY */
1951 #if !defined (DONT_REOPEN_PTY)
1952 /*** There is a suggestion that this ought to be a
1953 conditional on TIOCSPGRP,
1954 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1955 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1956 that system does seem to need this code, even though
1957 both HAVE_SETSID and TIOCSCTTY are defined. */
1958 /* Now close the pty (if we had it open) and reopen it.
1959 This makes the pty the controlling terminal of the subprocess. */
1960 if (pty_flag)
1963 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1964 would work? */
1965 if (xforkin >= 0)
1966 emacs_close (xforkin);
1967 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1969 if (xforkin < 0)
1971 emacs_write (1, "Couldn't open the pty terminal ", 31);
1972 emacs_write (1, pty_name, strlen (pty_name));
1973 emacs_write (1, "\n", 1);
1974 _exit (1);
1978 #endif /* not DONT_REOPEN_PTY */
1980 #ifdef SETUP_SLAVE_PTY
1981 if (pty_flag)
1983 SETUP_SLAVE_PTY;
1985 #endif /* SETUP_SLAVE_PTY */
1986 #ifdef AIX
1987 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1988 Now reenable it in the child, so it will die when we want it to. */
1989 if (pty_flag)
1990 signal (SIGHUP, SIG_DFL);
1991 #endif
1992 #endif /* HAVE_PTYS */
1994 signal (SIGINT, SIG_DFL);
1995 signal (SIGQUIT, SIG_DFL);
1997 /* Stop blocking signals in the child. */
1998 sigprocmask (SIG_SETMASK, &procmask, 0);
2000 if (pty_flag)
2001 child_setup_tty (xforkout);
2002 #ifdef WINDOWSNT
2003 pid = child_setup (xforkin, xforkout, xforkout,
2004 new_argv, 1, current_dir);
2005 #else /* not WINDOWSNT */
2006 #ifdef FD_CLOEXEC
2007 emacs_close (wait_child_setup[0]);
2008 #endif
2009 child_setup (xforkin, xforkout, xforkout,
2010 new_argv, 1, current_dir);
2011 #endif /* not WINDOWSNT */
2013 environ = save_environ;
2016 UNBLOCK_INPUT;
2018 /* This runs in the Emacs process. */
2019 if (pid < 0)
2021 if (forkin >= 0)
2022 emacs_close (forkin);
2023 if (forkin != forkout && forkout >= 0)
2024 emacs_close (forkout);
2026 else
2028 /* vfork succeeded. */
2029 XPROCESS (process)->pid = pid;
2031 #ifdef WINDOWSNT
2032 register_child (pid, inchannel);
2033 #endif /* WINDOWSNT */
2035 /* If the subfork execv fails, and it exits,
2036 this close hangs. I don't know why.
2037 So have an interrupt jar it loose. */
2039 struct atimer *timer;
2040 EMACS_TIME offset;
2042 stop_polling ();
2043 EMACS_SET_SECS_USECS (offset, 1, 0);
2044 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2046 if (forkin >= 0)
2047 emacs_close (forkin);
2049 cancel_atimer (timer);
2050 start_polling ();
2053 if (forkin != forkout && forkout >= 0)
2054 emacs_close (forkout);
2056 #ifdef HAVE_PTYS
2057 if (pty_flag)
2058 XPROCESS (process)->tty_name = build_string (pty_name);
2059 else
2060 #endif
2061 XPROCESS (process)->tty_name = Qnil;
2063 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2064 /* Wait for child_setup to complete in case that vfork is
2065 actually defined as fork. The descriptor wait_child_setup[1]
2066 of a pipe is closed at the child side either by close-on-exec
2067 on successful execvp or the _exit call in child_setup. */
2069 char dummy;
2071 emacs_close (wait_child_setup[1]);
2072 emacs_read (wait_child_setup[0], &dummy, 1);
2073 emacs_close (wait_child_setup[0]);
2075 #endif
2078 /* Restore the signal state whether vfork succeeded or not.
2079 (We will signal an error, below, if it failed.) */
2080 #ifdef HAVE_WORKING_VFORK
2081 /* Restore the parent's signal handlers. */
2082 sigaction (SIGINT, &sigint_action, 0);
2083 sigaction (SIGQUIT, &sigquit_action, 0);
2084 #ifdef AIX
2085 sigaction (SIGHUP, &sighup_action, 0);
2086 #endif
2087 #endif /* HAVE_WORKING_VFORK */
2088 /* Stop blocking signals in the parent. */
2089 sigprocmask (SIG_SETMASK, &procmask, 0);
2091 /* Now generate the error if vfork failed. */
2092 if (pid < 0)
2093 report_file_error ("Doing vfork", Qnil);
2096 void
2097 create_pty (Lisp_Object process)
2099 int inchannel, outchannel;
2101 /* Use volatile to protect variables from being clobbered by longjmp. */
2102 volatile int forkin, forkout;
2103 volatile int pty_flag = 0;
2105 inchannel = outchannel = -1;
2107 #ifdef HAVE_PTYS
2108 if (!NILP (Vprocess_connection_type))
2109 outchannel = inchannel = allocate_pty ();
2111 if (inchannel >= 0)
2113 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2114 /* On most USG systems it does not work to open the pty's tty here,
2115 then close it and reopen it in the child. */
2116 #ifdef O_NOCTTY
2117 /* Don't let this terminal become our controlling terminal
2118 (in case we don't have one). */
2119 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2120 #else
2121 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2122 #endif
2123 if (forkin < 0)
2124 report_file_error ("Opening pty", Qnil);
2125 #if defined (DONT_REOPEN_PTY)
2126 /* In the case that vfork is defined as fork, the parent process
2127 (Emacs) may send some data before the child process completes
2128 tty options setup. So we setup tty before forking. */
2129 child_setup_tty (forkout);
2130 #endif /* DONT_REOPEN_PTY */
2131 #else
2132 forkin = forkout = -1;
2133 #endif /* not USG, or USG_SUBTTY_WORKS */
2134 pty_flag = 1;
2136 #endif /* HAVE_PTYS */
2138 #ifdef O_NONBLOCK
2139 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2140 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2141 #else
2142 #ifdef O_NDELAY
2143 fcntl (inchannel, F_SETFL, O_NDELAY);
2144 fcntl (outchannel, F_SETFL, O_NDELAY);
2145 #endif
2146 #endif
2148 /* Record this as an active process, with its channels.
2149 As a result, child_setup will close Emacs's side of the pipes. */
2150 chan_process[inchannel] = process;
2151 XPROCESS (process)->infd = inchannel;
2152 XPROCESS (process)->outfd = outchannel;
2154 /* Previously we recorded the tty descriptor used in the subprocess.
2155 It was only used for getting the foreground tty process, so now
2156 we just reopen the device (see emacs_get_tty_pgrp) as this is
2157 more portable (see USG_SUBTTY_WORKS above). */
2159 XPROCESS (process)->pty_flag = pty_flag;
2160 XPROCESS (process)->status = Qrun;
2161 setup_process_coding_systems (process);
2163 FD_SET (inchannel, &input_wait_mask);
2164 FD_SET (inchannel, &non_keyboard_wait_mask);
2165 if (inchannel > max_process_desc)
2166 max_process_desc = inchannel;
2168 XPROCESS (process)->pid = -2;
2169 #ifdef HAVE_PTYS
2170 if (pty_flag)
2171 XPROCESS (process)->tty_name = build_string (pty_name);
2172 else
2173 #endif
2174 XPROCESS (process)->tty_name = Qnil;
2178 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2179 The address family of sa is not included in the result. */
2181 static Lisp_Object
2182 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2184 Lisp_Object address;
2185 int i;
2186 unsigned char *cp;
2187 register struct Lisp_Vector *p;
2189 /* Workaround for a bug in getsockname on BSD: Names bound to
2190 sockets in the UNIX domain are inaccessible; getsockname returns
2191 a zero length name. */
2192 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2193 return empty_unibyte_string;
2195 switch (sa->sa_family)
2197 case AF_INET:
2199 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2200 len = sizeof (sin->sin_addr) + 1;
2201 address = Fmake_vector (make_number (len), Qnil);
2202 p = XVECTOR (address);
2203 p->contents[--len] = make_number (ntohs (sin->sin_port));
2204 cp = (unsigned char *) &sin->sin_addr;
2205 break;
2207 #ifdef AF_INET6
2208 case AF_INET6:
2210 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2211 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2212 len = sizeof (sin6->sin6_addr)/2 + 1;
2213 address = Fmake_vector (make_number (len), Qnil);
2214 p = XVECTOR (address);
2215 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2216 for (i = 0; i < len; i++)
2217 p->contents[i] = make_number (ntohs (ip6[i]));
2218 return address;
2220 #endif
2221 #ifdef HAVE_LOCAL_SOCKETS
2222 case AF_LOCAL:
2224 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2225 for (i = 0; i < sizeof (sockun->sun_path); i++)
2226 if (sockun->sun_path[i] == 0)
2227 break;
2228 return make_unibyte_string (sockun->sun_path, i);
2230 #endif
2231 default:
2232 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2233 address = Fcons (make_number (sa->sa_family),
2234 Fmake_vector (make_number (len), Qnil));
2235 p = XVECTOR (XCDR (address));
2236 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2237 break;
2240 i = 0;
2241 while (i < len)
2242 p->contents[i++] = make_number (*cp++);
2244 return address;
2248 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2250 static int
2251 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2253 register struct Lisp_Vector *p;
2255 if (VECTORP (address))
2257 p = XVECTOR (address);
2258 if (p->size == 5)
2260 *familyp = AF_INET;
2261 return sizeof (struct sockaddr_in);
2263 #ifdef AF_INET6
2264 else if (p->size == 9)
2266 *familyp = AF_INET6;
2267 return sizeof (struct sockaddr_in6);
2269 #endif
2271 #ifdef HAVE_LOCAL_SOCKETS
2272 else if (STRINGP (address))
2274 *familyp = AF_LOCAL;
2275 return sizeof (struct sockaddr_un);
2277 #endif
2278 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2280 struct sockaddr *sa;
2281 *familyp = XINT (XCAR (address));
2282 p = XVECTOR (XCDR (address));
2283 return p->size + sizeof (sa->sa_family);
2285 return 0;
2288 /* Convert an address object (vector or string) to an internal sockaddr.
2290 The address format has been basically validated by
2291 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2292 it could have come from user data. So if FAMILY is not valid,
2293 we return after zeroing *SA. */
2295 static void
2296 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2298 register struct Lisp_Vector *p;
2299 register unsigned char *cp = NULL;
2300 register int i;
2302 memset (sa, 0, len);
2304 if (VECTORP (address))
2306 p = XVECTOR (address);
2307 if (family == AF_INET)
2309 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2310 len = sizeof (sin->sin_addr) + 1;
2311 i = XINT (p->contents[--len]);
2312 sin->sin_port = htons (i);
2313 cp = (unsigned char *)&sin->sin_addr;
2314 sa->sa_family = family;
2316 #ifdef AF_INET6
2317 else if (family == AF_INET6)
2319 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2320 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2321 len = sizeof (sin6->sin6_addr) + 1;
2322 i = XINT (p->contents[--len]);
2323 sin6->sin6_port = htons (i);
2324 for (i = 0; i < len; i++)
2325 if (INTEGERP (p->contents[i]))
2327 int j = XFASTINT (p->contents[i]) & 0xffff;
2328 ip6[i] = ntohs (j);
2330 sa->sa_family = family;
2331 return;
2333 #endif
2334 else
2335 return;
2337 else if (STRINGP (address))
2339 #ifdef HAVE_LOCAL_SOCKETS
2340 if (family == AF_LOCAL)
2342 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2343 cp = SDATA (address);
2344 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2345 sockun->sun_path[i] = *cp++;
2346 sa->sa_family = family;
2348 #endif
2349 return;
2351 else
2353 p = XVECTOR (XCDR (address));
2354 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2357 for (i = 0; i < len; i++)
2358 if (INTEGERP (p->contents[i]))
2359 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2362 #ifdef DATAGRAM_SOCKETS
2363 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2364 1, 1, 0,
2365 doc: /* Get the current datagram address associated with PROCESS. */)
2366 (Lisp_Object process)
2368 int channel;
2370 CHECK_PROCESS (process);
2372 if (!DATAGRAM_CONN_P (process))
2373 return Qnil;
2375 channel = XPROCESS (process)->infd;
2376 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2377 datagram_address[channel].len);
2380 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2381 2, 2, 0,
2382 doc: /* Set the datagram address for PROCESS to ADDRESS.
2383 Returns nil upon error setting address, ADDRESS otherwise. */)
2384 (Lisp_Object process, Lisp_Object address)
2386 int channel;
2387 int family, len;
2389 CHECK_PROCESS (process);
2391 if (!DATAGRAM_CONN_P (process))
2392 return Qnil;
2394 channel = XPROCESS (process)->infd;
2396 len = get_lisp_to_sockaddr_size (address, &family);
2397 if (datagram_address[channel].len != len)
2398 return Qnil;
2399 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2400 return address;
2402 #endif
2405 static const struct socket_options {
2406 /* The name of this option. Should be lowercase version of option
2407 name without SO_ prefix. */
2408 const char *name;
2409 /* Option level SOL_... */
2410 int optlevel;
2411 /* Option number SO_... */
2412 int optnum;
2413 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2414 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2415 } socket_options[] =
2417 #ifdef SO_BINDTODEVICE
2418 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2419 #endif
2420 #ifdef SO_BROADCAST
2421 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2422 #endif
2423 #ifdef SO_DONTROUTE
2424 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2425 #endif
2426 #ifdef SO_KEEPALIVE
2427 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2428 #endif
2429 #ifdef SO_LINGER
2430 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2431 #endif
2432 #ifdef SO_OOBINLINE
2433 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2434 #endif
2435 #ifdef SO_PRIORITY
2436 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2437 #endif
2438 #ifdef SO_REUSEADDR
2439 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2440 #endif
2441 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2444 /* Set option OPT to value VAL on socket S.
2446 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2447 Signals an error if setting a known option fails.
2450 static int
2451 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2453 char *name;
2454 const struct socket_options *sopt;
2455 int ret = 0;
2457 CHECK_SYMBOL (opt);
2459 name = (char *) SDATA (SYMBOL_NAME (opt));
2460 for (sopt = socket_options; sopt->name; sopt++)
2461 if (strcmp (name, sopt->name) == 0)
2462 break;
2464 switch (sopt->opttype)
2466 case SOPT_BOOL:
2468 int optval;
2469 optval = NILP (val) ? 0 : 1;
2470 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2471 &optval, sizeof (optval));
2472 break;
2475 case SOPT_INT:
2477 int optval;
2478 if (INTEGERP (val))
2479 optval = XINT (val);
2480 else
2481 error ("Bad option value for %s", name);
2482 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2483 &optval, sizeof (optval));
2484 break;
2487 #ifdef SO_BINDTODEVICE
2488 case SOPT_IFNAME:
2490 char devname[IFNAMSIZ+1];
2492 /* This is broken, at least in the Linux 2.4 kernel.
2493 To unbind, the arg must be a zero integer, not the empty string.
2494 This should work on all systems. KFS. 2003-09-23. */
2495 memset (devname, 0, sizeof devname);
2496 if (STRINGP (val))
2498 char *arg = (char *) SDATA (val);
2499 int len = min (strlen (arg), IFNAMSIZ);
2500 memcpy (devname, arg, len);
2502 else if (!NILP (val))
2503 error ("Bad option value for %s", name);
2504 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2505 devname, IFNAMSIZ);
2506 break;
2508 #endif
2510 #ifdef SO_LINGER
2511 case SOPT_LINGER:
2513 struct linger linger;
2515 linger.l_onoff = 1;
2516 linger.l_linger = 0;
2517 if (INTEGERP (val))
2518 linger.l_linger = XINT (val);
2519 else
2520 linger.l_onoff = NILP (val) ? 0 : 1;
2521 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2522 &linger, sizeof (linger));
2523 break;
2525 #endif
2527 default:
2528 return 0;
2531 if (ret < 0)
2532 report_file_error ("Cannot set network option",
2533 Fcons (opt, Fcons (val, Qnil)));
2534 return (1 << sopt->optbit);
2538 DEFUN ("set-network-process-option",
2539 Fset_network_process_option, Sset_network_process_option,
2540 3, 4, 0,
2541 doc: /* For network process PROCESS set option OPTION to value VALUE.
2542 See `make-network-process' for a list of options and values.
2543 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2544 OPTION is not a supported option, return nil instead; otherwise return t. */)
2545 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2547 int s;
2548 struct Lisp_Process *p;
2550 CHECK_PROCESS (process);
2551 p = XPROCESS (process);
2552 if (!NETCONN1_P (p))
2553 error ("Process is not a network process");
2555 s = p->infd;
2556 if (s < 0)
2557 error ("Process is not running");
2559 if (set_socket_option (s, option, value))
2561 p->childp = Fplist_put (p->childp, option, value);
2562 return Qt;
2565 if (NILP (no_error))
2566 error ("Unknown or unsupported option");
2568 return Qnil;
2572 #ifdef HAVE_SERIAL
2573 DEFUN ("serial-process-configure",
2574 Fserial_process_configure,
2575 Sserial_process_configure,
2576 0, MANY, 0,
2577 doc: /* Configure speed, bytesize, etc. of a serial process.
2579 Arguments are specified as keyword/argument pairs. Attributes that
2580 are not given are re-initialized from the process's current
2581 configuration (available via the function `process-contact') or set to
2582 reasonable default values. The following arguments are defined:
2584 :process PROCESS
2585 :name NAME
2586 :buffer BUFFER
2587 :port PORT
2588 -- Any of these arguments can be given to identify the process that is
2589 to be configured. If none of these arguments is given, the current
2590 buffer's process is used.
2592 :speed SPEED -- SPEED is the speed of the serial port in bits per
2593 second, also called baud rate. Any value can be given for SPEED, but
2594 most serial ports work only at a few defined values between 1200 and
2595 115200, with 9600 being the most common value. If SPEED is nil, the
2596 serial port is not configured any further, i.e., all other arguments
2597 are ignored. This may be useful for special serial ports such as
2598 Bluetooth-to-serial converters which can only be configured through AT
2599 commands. A value of nil for SPEED can be used only when passed
2600 through `make-serial-process' or `serial-term'.
2602 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2603 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2605 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2606 `odd' (use odd parity), or the symbol `even' (use even parity). If
2607 PARITY is not given, no parity is used.
2609 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2610 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2611 is not given or nil, 1 stopbit is used.
2613 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2614 flowcontrol to be used, which is either nil (don't use flowcontrol),
2615 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2616 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2617 flowcontrol is used.
2619 `serial-process-configure' is called by `make-serial-process' for the
2620 initial configuration of the serial port.
2622 Examples:
2624 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2626 \(serial-process-configure
2627 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2629 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2631 usage: (serial-process-configure &rest ARGS) */)
2632 (int nargs, Lisp_Object *args)
2634 struct Lisp_Process *p;
2635 Lisp_Object contact = Qnil;
2636 Lisp_Object proc = Qnil;
2637 struct gcpro gcpro1;
2639 contact = Flist (nargs, args);
2640 GCPRO1 (contact);
2642 proc = Fplist_get (contact, QCprocess);
2643 if (NILP (proc))
2644 proc = Fplist_get (contact, QCname);
2645 if (NILP (proc))
2646 proc = Fplist_get (contact, QCbuffer);
2647 if (NILP (proc))
2648 proc = Fplist_get (contact, QCport);
2649 proc = get_process (proc);
2650 p = XPROCESS (proc);
2651 if (!EQ (p->type, Qserial))
2652 error ("Not a serial process");
2654 if (NILP (Fplist_get (p->childp, QCspeed)))
2656 UNGCPRO;
2657 return Qnil;
2660 serial_configure (p, contact);
2662 UNGCPRO;
2663 return Qnil;
2666 /* Used by make-serial-process to recover from errors. */
2667 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2669 if (!PROCESSP (proc))
2670 abort ();
2671 remove_process (proc);
2672 return Qnil;
2675 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2676 0, MANY, 0,
2677 doc: /* Create and return a serial port process.
2679 In Emacs, serial port connections are represented by process objects,
2680 so input and output work as for subprocesses, and `delete-process'
2681 closes a serial port connection. However, a serial process has no
2682 process id, it cannot be signaled, and the status codes are different
2683 from normal processes.
2685 `make-serial-process' creates a process and a buffer, on which you
2686 probably want to use `process-send-string'. Try \\[serial-term] for
2687 an interactive terminal. See below for examples.
2689 Arguments are specified as keyword/argument pairs. The following
2690 arguments are defined:
2692 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2693 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2694 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2695 the backslashes in strings).
2697 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2698 which is called by `make-serial-process'.
2700 :name NAME -- NAME is the name of the process. If NAME is not given,
2701 the value of PORT is used.
2703 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2704 with the process. Process output goes at the end of that buffer,
2705 unless you specify an output stream or filter function to handle the
2706 output. If BUFFER is not given, the value of NAME is used.
2708 :coding CODING -- If CODING is a symbol, it specifies the coding
2709 system used for both reading and writing for this process. If CODING
2710 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2711 ENCODING is used for writing.
2713 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2714 the process is running. If BOOL is not given, query before exiting.
2716 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2717 In the stopped state, a serial process does not accept incoming data,
2718 but you can send outgoing data. The stopped state is cleared by
2719 `continue-process' and set by `stop-process'.
2721 :filter FILTER -- Install FILTER as the process filter.
2723 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2725 :plist PLIST -- Install PLIST as the initial plist of the process.
2727 :speed
2728 :bytesize
2729 :parity
2730 :stopbits
2731 :flowcontrol
2732 -- These arguments are handled by `serial-process-configure', which is
2733 called by `make-serial-process'.
2735 The original argument list, possibly modified by later configuration,
2736 is available via the function `process-contact'.
2738 Examples:
2740 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2742 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2744 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2746 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2748 usage: (make-serial-process &rest ARGS) */)
2749 (int nargs, Lisp_Object *args)
2751 int fd = -1;
2752 Lisp_Object proc, contact, port;
2753 struct Lisp_Process *p;
2754 struct gcpro gcpro1;
2755 Lisp_Object name, buffer;
2756 Lisp_Object tem, val;
2757 int specpdl_count = -1;
2759 if (nargs == 0)
2760 return Qnil;
2762 contact = Flist (nargs, args);
2763 GCPRO1 (contact);
2765 port = Fplist_get (contact, QCport);
2766 if (NILP (port))
2767 error ("No port specified");
2768 CHECK_STRING (port);
2770 if (NILP (Fplist_member (contact, QCspeed)))
2771 error (":speed not specified");
2772 if (!NILP (Fplist_get (contact, QCspeed)))
2773 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2775 name = Fplist_get (contact, QCname);
2776 if (NILP (name))
2777 name = port;
2778 CHECK_STRING (name);
2779 proc = make_process (name);
2780 specpdl_count = SPECPDL_INDEX ();
2781 record_unwind_protect (make_serial_process_unwind, proc);
2782 p = XPROCESS (proc);
2784 fd = serial_open ((char*) SDATA (port));
2785 p->infd = fd;
2786 p->outfd = fd;
2787 if (fd > max_process_desc)
2788 max_process_desc = fd;
2789 chan_process[fd] = proc;
2791 buffer = Fplist_get (contact, QCbuffer);
2792 if (NILP (buffer))
2793 buffer = name;
2794 buffer = Fget_buffer_create (buffer);
2795 p->buffer = buffer;
2797 p->childp = contact;
2798 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2799 p->type = Qserial;
2800 p->sentinel = Fplist_get (contact, QCsentinel);
2801 p->filter = Fplist_get (contact, QCfilter);
2802 p->log = Qnil;
2803 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2804 p->kill_without_query = 1;
2805 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2806 p->command = Qt;
2807 p->pty_flag = 0;
2809 if (!EQ (p->command, Qt))
2811 FD_SET (fd, &input_wait_mask);
2812 FD_SET (fd, &non_keyboard_wait_mask);
2815 if (BUFFERP (buffer))
2817 set_marker_both (p->mark, buffer,
2818 BUF_ZV (XBUFFER (buffer)),
2819 BUF_ZV_BYTE (XBUFFER (buffer)));
2822 tem = Fplist_member (contact, QCcoding);
2823 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2824 tem = Qnil;
2826 val = Qnil;
2827 if (!NILP (tem))
2829 val = XCAR (XCDR (tem));
2830 if (CONSP (val))
2831 val = XCAR (val);
2833 else if (!NILP (Vcoding_system_for_read))
2834 val = Vcoding_system_for_read;
2835 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2836 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2837 val = Qnil;
2838 p->decode_coding_system = val;
2840 val = Qnil;
2841 if (!NILP (tem))
2843 val = XCAR (XCDR (tem));
2844 if (CONSP (val))
2845 val = XCDR (val);
2847 else if (!NILP (Vcoding_system_for_write))
2848 val = Vcoding_system_for_write;
2849 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2850 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2851 val = Qnil;
2852 p->encode_coding_system = val;
2854 setup_process_coding_systems (proc);
2855 p->decoding_buf = make_uninit_string (0);
2856 p->decoding_carryover = 0;
2857 p->encoding_buf = make_uninit_string (0);
2858 p->inherit_coding_system_flag
2859 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2861 Fserial_process_configure (nargs, args);
2863 specpdl_ptr = specpdl + specpdl_count;
2865 UNGCPRO;
2866 return proc;
2868 #endif /* HAVE_SERIAL */
2870 /* Create a network stream/datagram client/server process. Treated
2871 exactly like a normal process when reading and writing. Primary
2872 differences are in status display and process deletion. A network
2873 connection has no PID; you cannot signal it. All you can do is
2874 stop/continue it and deactivate/close it via delete-process */
2876 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2877 0, MANY, 0,
2878 doc: /* Create and return a network server or client process.
2880 In Emacs, network connections are represented by process objects, so
2881 input and output work as for subprocesses and `delete-process' closes
2882 a network connection. However, a network process has no process id,
2883 it cannot be signaled, and the status codes are different from normal
2884 processes.
2886 Arguments are specified as keyword/argument pairs. The following
2887 arguments are defined:
2889 :name NAME -- NAME is name for process. It is modified if necessary
2890 to make it unique.
2892 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2893 with the process. Process output goes at end of that buffer, unless
2894 you specify an output stream or filter function to handle the output.
2895 BUFFER may be also nil, meaning that this process is not associated
2896 with any buffer.
2898 :host HOST -- HOST is name of the host to connect to, or its IP
2899 address. The symbol `local' specifies the local host. If specified
2900 for a server process, it must be a valid name or address for the local
2901 host, and only clients connecting to that address will be accepted.
2903 :service SERVICE -- SERVICE is name of the service desired, or an
2904 integer specifying a port number to connect to. If SERVICE is t,
2905 a random port number is selected for the server. (If Emacs was
2906 compiled with getaddrinfo, a port number can also be specified as a
2907 string, e.g. "80", as well as an integer. This is not portable.)
2909 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2910 stream type connection, `datagram' creates a datagram type connection,
2911 `seqpacket' creates a reliable datagram connection.
2913 :family FAMILY -- FAMILY is the address (and protocol) family for the
2914 service specified by HOST and SERVICE. The default (nil) is to use
2915 whatever address family (IPv4 or IPv6) that is defined for the host
2916 and port number specified by HOST and SERVICE. Other address families
2917 supported are:
2918 local -- for a local (i.e. UNIX) address specified by SERVICE.
2919 ipv4 -- use IPv4 address family only.
2920 ipv6 -- use IPv6 address family only.
2922 :local ADDRESS -- ADDRESS is the local address used for the connection.
2923 This parameter is ignored when opening a client process. When specified
2924 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2926 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2927 connection. This parameter is ignored when opening a stream server
2928 process. For a datagram server process, it specifies the initial
2929 setting of the remote datagram address. When specified for a client
2930 process, the FAMILY, HOST, and SERVICE args are ignored.
2932 The format of ADDRESS depends on the address family:
2933 - An IPv4 address is represented as an vector of integers [A B C D P]
2934 corresponding to numeric IP address A.B.C.D and port number P.
2935 - A local address is represented as a string with the address in the
2936 local address space.
2937 - An "unsupported family" address is represented by a cons (F . AV)
2938 where F is the family number and AV is a vector containing the socket
2939 address data with one element per address data byte. Do not rely on
2940 this format in portable code, as it may depend on implementation
2941 defined constants, data sizes, and data structure alignment.
2943 :coding CODING -- If CODING is a symbol, it specifies the coding
2944 system used for both reading and writing for this process. If CODING
2945 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2946 ENCODING is used for writing.
2948 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2949 return without waiting for the connection to complete; instead, the
2950 sentinel function will be called with second arg matching "open" (if
2951 successful) or "failed" when the connect completes. Default is to use
2952 a blocking connect (i.e. wait) for stream type connections.
2954 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2955 running when Emacs is exited.
2957 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2958 In the stopped state, a server process does not accept new
2959 connections, and a client process does not handle incoming traffic.
2960 The stopped state is cleared by `continue-process' and set by
2961 `stop-process'.
2963 :filter FILTER -- Install FILTER as the process filter.
2965 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2966 process filter are multibyte, otherwise they are unibyte.
2967 If this keyword is not specified, the strings are multibyte if
2968 `default-enable-multibyte-characters' is non-nil.
2970 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2972 :log LOG -- Install LOG as the server process log function. This
2973 function is called when the server accepts a network connection from a
2974 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2975 is the server process, CLIENT is the new process for the connection,
2976 and MESSAGE is a string.
2978 :plist PLIST -- Install PLIST as the new process' initial plist.
2980 :server QLEN -- if QLEN is non-nil, create a server process for the
2981 specified FAMILY, SERVICE, and connection type (stream or datagram).
2982 If QLEN is an integer, it is used as the max. length of the server's
2983 pending connection queue (also known as the backlog); the default
2984 queue length is 5. Default is to create a client process.
2986 The following network options can be specified for this connection:
2988 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2989 :dontroute BOOL -- Only send to directly connected hosts.
2990 :keepalive BOOL -- Send keep-alive messages on network stream.
2991 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2992 :oobinline BOOL -- Place out-of-band data in receive data stream.
2993 :priority INT -- Set protocol defined priority for sent packets.
2994 :reuseaddr BOOL -- Allow reusing a recently used local address
2995 (this is allowed by default for a server process).
2996 :bindtodevice NAME -- bind to interface NAME. Using this may require
2997 special privileges on some systems.
2999 Consult the relevant system programmer's manual pages for more
3000 information on using these options.
3003 A server process will listen for and accept connections from clients.
3004 When a client connection is accepted, a new network process is created
3005 for the connection with the following parameters:
3007 - The client's process name is constructed by concatenating the server
3008 process' NAME and a client identification string.
3009 - If the FILTER argument is non-nil, the client process will not get a
3010 separate process buffer; otherwise, the client's process buffer is a newly
3011 created buffer named after the server process' BUFFER name or process
3012 NAME concatenated with the client identification string.
3013 - The connection type and the process filter and sentinel parameters are
3014 inherited from the server process' TYPE, FILTER and SENTINEL.
3015 - The client process' contact info is set according to the client's
3016 addressing information (typically an IP address and a port number).
3017 - The client process' plist is initialized from the server's plist.
3019 Notice that the FILTER and SENTINEL args are never used directly by
3020 the server process. Also, the BUFFER argument is not used directly by
3021 the server process, but via the optional :log function, accepted (and
3022 failed) connections may be logged in the server process' buffer.
3024 The original argument list, modified with the actual connection
3025 information, is available via the `process-contact' function.
3027 usage: (make-network-process &rest ARGS) */)
3028 (int nargs, Lisp_Object *args)
3030 Lisp_Object proc;
3031 Lisp_Object contact;
3032 struct Lisp_Process *p;
3033 #ifdef HAVE_GETADDRINFO
3034 struct addrinfo ai, *res, *lres;
3035 struct addrinfo hints;
3036 const char *portstring;
3037 char portbuf[128];
3038 #else /* HAVE_GETADDRINFO */
3039 struct _emacs_addrinfo
3041 int ai_family;
3042 int ai_socktype;
3043 int ai_protocol;
3044 int ai_addrlen;
3045 struct sockaddr *ai_addr;
3046 struct _emacs_addrinfo *ai_next;
3047 } ai, *res, *lres;
3048 #endif /* HAVE_GETADDRINFO */
3049 struct sockaddr_in address_in;
3050 #ifdef HAVE_LOCAL_SOCKETS
3051 struct sockaddr_un address_un;
3052 #endif
3053 int port;
3054 int ret = 0;
3055 int xerrno = 0;
3056 int s = -1, outch, inch;
3057 struct gcpro gcpro1;
3058 int count = SPECPDL_INDEX ();
3059 int count1;
3060 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3061 Lisp_Object tem;
3062 Lisp_Object name, buffer, host, service, address;
3063 Lisp_Object filter, sentinel;
3064 int is_non_blocking_client = 0;
3065 int is_server = 0, backlog = 5;
3066 int socktype;
3067 int family = -1;
3069 if (nargs == 0)
3070 return Qnil;
3072 /* Save arguments for process-contact and clone-process. */
3073 contact = Flist (nargs, args);
3074 GCPRO1 (contact);
3076 #ifdef WINDOWSNT
3077 /* Ensure socket support is loaded if available. */
3078 init_winsock (TRUE);
3079 #endif
3081 /* :type TYPE (nil: stream, datagram */
3082 tem = Fplist_get (contact, QCtype);
3083 if (NILP (tem))
3084 socktype = SOCK_STREAM;
3085 #ifdef DATAGRAM_SOCKETS
3086 else if (EQ (tem, Qdatagram))
3087 socktype = SOCK_DGRAM;
3088 #endif
3089 #ifdef HAVE_SEQPACKET
3090 else if (EQ (tem, Qseqpacket))
3091 socktype = SOCK_SEQPACKET;
3092 #endif
3093 else
3094 error ("Unsupported connection type");
3096 /* :server BOOL */
3097 tem = Fplist_get (contact, QCserver);
3098 if (!NILP (tem))
3100 /* Don't support network sockets when non-blocking mode is
3101 not available, since a blocked Emacs is not useful. */
3102 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3103 error ("Network servers not supported");
3104 #else
3105 is_server = 1;
3106 if (INTEGERP (tem))
3107 backlog = XINT (tem);
3108 #endif
3111 /* Make QCaddress an alias for :local (server) or :remote (client). */
3112 QCaddress = is_server ? QClocal : QCremote;
3114 /* :nowait BOOL */
3115 if (!is_server && socktype != SOCK_DGRAM
3116 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3118 #ifndef NON_BLOCKING_CONNECT
3119 error ("Non-blocking connect not supported");
3120 #else
3121 is_non_blocking_client = 1;
3122 #endif
3125 name = Fplist_get (contact, QCname);
3126 buffer = Fplist_get (contact, QCbuffer);
3127 filter = Fplist_get (contact, QCfilter);
3128 sentinel = Fplist_get (contact, QCsentinel);
3130 CHECK_STRING (name);
3132 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3133 ai.ai_socktype = socktype;
3134 ai.ai_protocol = 0;
3135 ai.ai_next = NULL;
3136 res = &ai;
3138 /* :local ADDRESS or :remote ADDRESS */
3139 address = Fplist_get (contact, QCaddress);
3140 if (!NILP (address))
3142 host = service = Qnil;
3144 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3145 error ("Malformed :address");
3146 ai.ai_family = family;
3147 ai.ai_addr = alloca (ai.ai_addrlen);
3148 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3149 goto open_socket;
3152 /* :family FAMILY -- nil (for Inet), local, or integer. */
3153 tem = Fplist_get (contact, QCfamily);
3154 if (NILP (tem))
3156 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3157 family = AF_UNSPEC;
3158 #else
3159 family = AF_INET;
3160 #endif
3162 #ifdef HAVE_LOCAL_SOCKETS
3163 else if (EQ (tem, Qlocal))
3164 family = AF_LOCAL;
3165 #endif
3166 #ifdef AF_INET6
3167 else if (EQ (tem, Qipv6))
3168 family = AF_INET6;
3169 #endif
3170 else if (EQ (tem, Qipv4))
3171 family = AF_INET;
3172 else if (INTEGERP (tem))
3173 family = XINT (tem);
3174 else
3175 error ("Unknown address family");
3177 ai.ai_family = family;
3179 /* :service SERVICE -- string, integer (port number), or t (random port). */
3180 service = Fplist_get (contact, QCservice);
3182 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3183 host = Fplist_get (contact, QChost);
3184 if (!NILP (host))
3186 if (EQ (host, Qlocal))
3187 host = build_string ("localhost");
3188 CHECK_STRING (host);
3191 #ifdef HAVE_LOCAL_SOCKETS
3192 if (family == AF_LOCAL)
3194 if (!NILP (host))
3196 message (":family local ignores the :host \"%s\" property",
3197 SDATA (host));
3198 contact = Fplist_put (contact, QChost, Qnil);
3199 host = Qnil;
3201 CHECK_STRING (service);
3202 memset (&address_un, 0, sizeof address_un);
3203 address_un.sun_family = AF_LOCAL;
3204 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3205 ai.ai_addr = (struct sockaddr *) &address_un;
3206 ai.ai_addrlen = sizeof address_un;
3207 goto open_socket;
3209 #endif
3211 /* Slow down polling to every ten seconds.
3212 Some kernels have a bug which causes retrying connect to fail
3213 after a connect. Polling can interfere with gethostbyname too. */
3214 #ifdef POLL_FOR_INPUT
3215 if (socktype != SOCK_DGRAM)
3217 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3218 bind_polling_period (10);
3220 #endif
3222 #ifdef HAVE_GETADDRINFO
3223 /* If we have a host, use getaddrinfo to resolve both host and service.
3224 Otherwise, use getservbyname to lookup the service. */
3225 if (!NILP (host))
3228 /* SERVICE can either be a string or int.
3229 Convert to a C string for later use by getaddrinfo. */
3230 if (EQ (service, Qt))
3231 portstring = "0";
3232 else if (INTEGERP (service))
3234 sprintf (portbuf, "%ld", (long) XINT (service));
3235 portstring = portbuf;
3237 else
3239 CHECK_STRING (service);
3240 portstring = SDATA (service);
3243 immediate_quit = 1;
3244 QUIT;
3245 memset (&hints, 0, sizeof (hints));
3246 hints.ai_flags = 0;
3247 hints.ai_family = family;
3248 hints.ai_socktype = socktype;
3249 hints.ai_protocol = 0;
3251 #ifdef HAVE_RES_INIT
3252 res_init ();
3253 #endif
3255 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3256 if (ret)
3257 #ifdef HAVE_GAI_STRERROR
3258 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3259 #else
3260 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3261 #endif
3262 immediate_quit = 0;
3264 goto open_socket;
3266 #endif /* HAVE_GETADDRINFO */
3268 /* We end up here if getaddrinfo is not defined, or in case no hostname
3269 has been specified (e.g. for a local server process). */
3271 if (EQ (service, Qt))
3272 port = 0;
3273 else if (INTEGERP (service))
3274 port = htons ((unsigned short) XINT (service));
3275 else
3277 struct servent *svc_info;
3278 CHECK_STRING (service);
3279 svc_info = getservbyname (SDATA (service),
3280 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3281 if (svc_info == 0)
3282 error ("Unknown service: %s", SDATA (service));
3283 port = svc_info->s_port;
3286 memset (&address_in, 0, sizeof address_in);
3287 address_in.sin_family = family;
3288 address_in.sin_addr.s_addr = INADDR_ANY;
3289 address_in.sin_port = port;
3291 #ifndef HAVE_GETADDRINFO
3292 if (!NILP (host))
3294 struct hostent *host_info_ptr;
3296 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3297 as it may `hang' Emacs for a very long time. */
3298 immediate_quit = 1;
3299 QUIT;
3301 #ifdef HAVE_RES_INIT
3302 res_init ();
3303 #endif
3305 host_info_ptr = gethostbyname (SDATA (host));
3306 immediate_quit = 0;
3308 if (host_info_ptr)
3310 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3311 host_info_ptr->h_length);
3312 family = host_info_ptr->h_addrtype;
3313 address_in.sin_family = family;
3315 else
3316 /* Attempt to interpret host as numeric inet address */
3318 unsigned long numeric_addr;
3319 numeric_addr = inet_addr ((char *) SDATA (host));
3320 if (numeric_addr == -1)
3321 error ("Unknown host \"%s\"", SDATA (host));
3323 memcpy (&address_in.sin_addr, &numeric_addr,
3324 sizeof (address_in.sin_addr));
3328 #endif /* not HAVE_GETADDRINFO */
3330 ai.ai_family = family;
3331 ai.ai_addr = (struct sockaddr *) &address_in;
3332 ai.ai_addrlen = sizeof address_in;
3334 open_socket:
3336 /* Do this in case we never enter the for-loop below. */
3337 count1 = SPECPDL_INDEX ();
3338 s = -1;
3340 for (lres = res; lres; lres = lres->ai_next)
3342 int optn, optbits;
3344 retry_connect:
3346 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3347 if (s < 0)
3349 xerrno = errno;
3350 continue;
3353 #ifdef DATAGRAM_SOCKETS
3354 if (!is_server && socktype == SOCK_DGRAM)
3355 break;
3356 #endif /* DATAGRAM_SOCKETS */
3358 #ifdef NON_BLOCKING_CONNECT
3359 if (is_non_blocking_client)
3361 #ifdef O_NONBLOCK
3362 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3363 #else
3364 ret = fcntl (s, F_SETFL, O_NDELAY);
3365 #endif
3366 if (ret < 0)
3368 xerrno = errno;
3369 emacs_close (s);
3370 s = -1;
3371 continue;
3374 #endif
3376 /* Make us close S if quit. */
3377 record_unwind_protect (close_file_unwind, make_number (s));
3379 /* Parse network options in the arg list.
3380 We simply ignore anything which isn't a known option (including other keywords).
3381 An error is signaled if setting a known option fails. */
3382 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3383 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3385 if (is_server)
3387 /* Configure as a server socket. */
3389 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3390 explicit :reuseaddr key to override this. */
3391 #ifdef HAVE_LOCAL_SOCKETS
3392 if (family != AF_LOCAL)
3393 #endif
3394 if (!(optbits & (1 << OPIX_REUSEADDR)))
3396 int optval = 1;
3397 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3398 report_file_error ("Cannot set reuse option on server socket", Qnil);
3401 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3402 report_file_error ("Cannot bind server socket", Qnil);
3404 #ifdef HAVE_GETSOCKNAME
3405 if (EQ (service, Qt))
3407 struct sockaddr_in sa1;
3408 int len1 = sizeof (sa1);
3409 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3411 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3412 service = make_number (ntohs (sa1.sin_port));
3413 contact = Fplist_put (contact, QCservice, service);
3416 #endif
3418 if (socktype != SOCK_DGRAM && listen (s, backlog))
3419 report_file_error ("Cannot listen on server socket", Qnil);
3421 break;
3424 immediate_quit = 1;
3425 QUIT;
3427 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3428 xerrno = errno;
3430 if (ret == 0 || xerrno == EISCONN)
3432 /* The unwind-protect will be discarded afterwards.
3433 Likewise for immediate_quit. */
3434 break;
3437 #ifdef NON_BLOCKING_CONNECT
3438 #ifdef EINPROGRESS
3439 if (is_non_blocking_client && xerrno == EINPROGRESS)
3440 break;
3441 #else
3442 #ifdef EWOULDBLOCK
3443 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3444 break;
3445 #endif
3446 #endif
3447 #endif
3449 #ifndef WINDOWSNT
3450 if (xerrno == EINTR)
3452 /* Unlike most other syscalls connect() cannot be called
3453 again. (That would return EALREADY.) The proper way to
3454 wait for completion is select(). */
3455 int sc, len;
3456 SELECT_TYPE fdset;
3457 retry_select:
3458 FD_ZERO (&fdset);
3459 FD_SET (s, &fdset);
3460 QUIT;
3461 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3462 (EMACS_TIME *)0);
3463 if (sc == -1)
3465 if (errno == EINTR)
3466 goto retry_select;
3467 else
3468 report_file_error ("select failed", Qnil);
3470 eassert (sc > 0);
3472 len = sizeof xerrno;
3473 eassert (FD_ISSET (s, &fdset));
3474 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3475 report_file_error ("getsockopt failed", Qnil);
3476 if (xerrno)
3477 errno = xerrno, report_file_error ("error during connect", Qnil);
3478 else
3479 break;
3481 #endif /* !WINDOWSNT */
3483 immediate_quit = 0;
3485 /* Discard the unwind protect closing S. */
3486 specpdl_ptr = specpdl + count1;
3487 emacs_close (s);
3488 s = -1;
3490 #ifdef WINDOWSNT
3491 if (xerrno == EINTR)
3492 goto retry_connect;
3493 #endif
3496 if (s >= 0)
3498 #ifdef DATAGRAM_SOCKETS
3499 if (socktype == SOCK_DGRAM)
3501 if (datagram_address[s].sa)
3502 abort ();
3503 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3504 datagram_address[s].len = lres->ai_addrlen;
3505 if (is_server)
3507 Lisp_Object remote;
3508 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3509 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3511 int rfamily, rlen;
3512 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3513 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3514 conv_lisp_to_sockaddr (rfamily, remote,
3515 datagram_address[s].sa, rlen);
3518 else
3519 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3521 #endif
3522 contact = Fplist_put (contact, QCaddress,
3523 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3524 #ifdef HAVE_GETSOCKNAME
3525 if (!is_server)
3527 struct sockaddr_in sa1;
3528 int len1 = sizeof (sa1);
3529 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3530 contact = Fplist_put (contact, QClocal,
3531 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3533 #endif
3536 immediate_quit = 0;
3538 #ifdef HAVE_GETADDRINFO
3539 if (res != &ai)
3541 BLOCK_INPUT;
3542 freeaddrinfo (res);
3543 UNBLOCK_INPUT;
3545 #endif
3547 /* Discard the unwind protect for closing S, if any. */
3548 specpdl_ptr = specpdl + count1;
3550 /* Unwind bind_polling_period and request_sigio. */
3551 unbind_to (count, Qnil);
3553 if (s < 0)
3555 /* If non-blocking got this far - and failed - assume non-blocking is
3556 not supported after all. This is probably a wrong assumption, but
3557 the normal blocking calls to open-network-stream handles this error
3558 better. */
3559 if (is_non_blocking_client)
3560 return Qnil;
3562 errno = xerrno;
3563 if (is_server)
3564 report_file_error ("make server process failed", contact);
3565 else
3566 report_file_error ("make client process failed", contact);
3569 inch = s;
3570 outch = s;
3572 if (!NILP (buffer))
3573 buffer = Fget_buffer_create (buffer);
3574 proc = make_process (name);
3576 chan_process[inch] = proc;
3578 #ifdef O_NONBLOCK
3579 fcntl (inch, F_SETFL, O_NONBLOCK);
3580 #else
3581 #ifdef O_NDELAY
3582 fcntl (inch, F_SETFL, O_NDELAY);
3583 #endif
3584 #endif
3586 p = XPROCESS (proc);
3588 p->childp = contact;
3589 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3590 p->type = Qnetwork;
3592 p->buffer = buffer;
3593 p->sentinel = sentinel;
3594 p->filter = filter;
3595 p->log = Fplist_get (contact, QClog);
3596 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3597 p->kill_without_query = 1;
3598 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3599 p->command = Qt;
3600 p->pid = 0;
3601 p->infd = inch;
3602 p->outfd = outch;
3603 if (is_server && socktype != SOCK_DGRAM)
3604 p->status = Qlisten;
3606 /* Make the process marker point into the process buffer (if any). */
3607 if (BUFFERP (buffer))
3608 set_marker_both (p->mark, buffer,
3609 BUF_ZV (XBUFFER (buffer)),
3610 BUF_ZV_BYTE (XBUFFER (buffer)));
3612 #ifdef NON_BLOCKING_CONNECT
3613 if (is_non_blocking_client)
3615 /* We may get here if connect did succeed immediately. However,
3616 in that case, we still need to signal this like a non-blocking
3617 connection. */
3618 p->status = Qconnect;
3619 if (!FD_ISSET (inch, &connect_wait_mask))
3621 FD_SET (inch, &connect_wait_mask);
3622 num_pending_connects++;
3625 else
3626 #endif
3627 /* A server may have a client filter setting of Qt, but it must
3628 still listen for incoming connects unless it is stopped. */
3629 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3630 || (EQ (p->status, Qlisten) && NILP (p->command)))
3632 FD_SET (inch, &input_wait_mask);
3633 FD_SET (inch, &non_keyboard_wait_mask);
3636 if (inch > max_process_desc)
3637 max_process_desc = inch;
3639 tem = Fplist_member (contact, QCcoding);
3640 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3641 tem = Qnil; /* No error message (too late!). */
3644 /* Setup coding systems for communicating with the network stream. */
3645 struct gcpro gcpro1;
3646 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3647 Lisp_Object coding_systems = Qt;
3648 Lisp_Object args[5], val;
3650 if (!NILP (tem))
3652 val = XCAR (XCDR (tem));
3653 if (CONSP (val))
3654 val = XCAR (val);
3656 else if (!NILP (Vcoding_system_for_read))
3657 val = Vcoding_system_for_read;
3658 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3659 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3660 /* We dare not decode end-of-line format by setting VAL to
3661 Qraw_text, because the existing Emacs Lisp libraries
3662 assume that they receive bare code including a sequene of
3663 CR LF. */
3664 val = Qnil;
3665 else
3667 if (NILP (host) || NILP (service))
3668 coding_systems = Qnil;
3669 else
3671 args[0] = Qopen_network_stream, args[1] = name,
3672 args[2] = buffer, args[3] = host, args[4] = service;
3673 GCPRO1 (proc);
3674 coding_systems = Ffind_operation_coding_system (5, args);
3675 UNGCPRO;
3677 if (CONSP (coding_systems))
3678 val = XCAR (coding_systems);
3679 else if (CONSP (Vdefault_process_coding_system))
3680 val = XCAR (Vdefault_process_coding_system);
3681 else
3682 val = Qnil;
3684 p->decode_coding_system = val;
3686 if (!NILP (tem))
3688 val = XCAR (XCDR (tem));
3689 if (CONSP (val))
3690 val = XCDR (val);
3692 else if (!NILP (Vcoding_system_for_write))
3693 val = Vcoding_system_for_write;
3694 else if (NILP (current_buffer->enable_multibyte_characters))
3695 val = Qnil;
3696 else
3698 if (EQ (coding_systems, Qt))
3700 if (NILP (host) || NILP (service))
3701 coding_systems = Qnil;
3702 else
3704 args[0] = Qopen_network_stream, args[1] = name,
3705 args[2] = buffer, args[3] = host, args[4] = service;
3706 GCPRO1 (proc);
3707 coding_systems = Ffind_operation_coding_system (5, args);
3708 UNGCPRO;
3711 if (CONSP (coding_systems))
3712 val = XCDR (coding_systems);
3713 else if (CONSP (Vdefault_process_coding_system))
3714 val = XCDR (Vdefault_process_coding_system);
3715 else
3716 val = Qnil;
3718 p->encode_coding_system = val;
3720 setup_process_coding_systems (proc);
3722 p->decoding_buf = make_uninit_string (0);
3723 p->decoding_carryover = 0;
3724 p->encoding_buf = make_uninit_string (0);
3726 p->inherit_coding_system_flag
3727 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3729 UNGCPRO;
3730 return proc;
3734 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3736 #ifdef SIOCGIFCONF
3737 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3738 doc: /* Return an alist of all network interfaces and their network address.
3739 Each element is a cons, the car of which is a string containing the
3740 interface name, and the cdr is the network address in internal
3741 format; see the description of ADDRESS in `make-network-process'. */)
3742 (void)
3744 struct ifconf ifconf;
3745 struct ifreq *ifreqs = NULL;
3746 int ifaces = 0;
3747 int buf_size, s;
3748 Lisp_Object res;
3750 s = socket (AF_INET, SOCK_STREAM, 0);
3751 if (s < 0)
3752 return Qnil;
3754 again:
3755 ifaces += 25;
3756 buf_size = ifaces * sizeof (ifreqs[0]);
3757 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3758 if (!ifreqs)
3760 close (s);
3761 return Qnil;
3764 ifconf.ifc_len = buf_size;
3765 ifconf.ifc_req = ifreqs;
3766 if (ioctl (s, SIOCGIFCONF, &ifconf))
3768 close (s);
3769 return Qnil;
3772 if (ifconf.ifc_len == buf_size)
3773 goto again;
3775 close (s);
3776 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3778 res = Qnil;
3779 while (--ifaces >= 0)
3781 struct ifreq *ifq = &ifreqs[ifaces];
3782 char namebuf[sizeof (ifq->ifr_name) + 1];
3783 if (ifq->ifr_addr.sa_family != AF_INET)
3784 continue;
3785 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3786 namebuf[sizeof (ifq->ifr_name)] = 0;
3787 res = Fcons (Fcons (build_string (namebuf),
3788 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3789 sizeof (struct sockaddr))),
3790 res);
3793 return res;
3795 #endif /* SIOCGIFCONF */
3797 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3799 struct ifflag_def {
3800 int flag_bit;
3801 const char *flag_sym;
3804 static const struct ifflag_def ifflag_table[] = {
3805 #ifdef IFF_UP
3806 { IFF_UP, "up" },
3807 #endif
3808 #ifdef IFF_BROADCAST
3809 { IFF_BROADCAST, "broadcast" },
3810 #endif
3811 #ifdef IFF_DEBUG
3812 { IFF_DEBUG, "debug" },
3813 #endif
3814 #ifdef IFF_LOOPBACK
3815 { IFF_LOOPBACK, "loopback" },
3816 #endif
3817 #ifdef IFF_POINTOPOINT
3818 { IFF_POINTOPOINT, "pointopoint" },
3819 #endif
3820 #ifdef IFF_RUNNING
3821 { IFF_RUNNING, "running" },
3822 #endif
3823 #ifdef IFF_NOARP
3824 { IFF_NOARP, "noarp" },
3825 #endif
3826 #ifdef IFF_PROMISC
3827 { IFF_PROMISC, "promisc" },
3828 #endif
3829 #ifdef IFF_NOTRAILERS
3830 { IFF_NOTRAILERS, "notrailers" },
3831 #endif
3832 #ifdef IFF_ALLMULTI
3833 { IFF_ALLMULTI, "allmulti" },
3834 #endif
3835 #ifdef IFF_MASTER
3836 { IFF_MASTER, "master" },
3837 #endif
3838 #ifdef IFF_SLAVE
3839 { IFF_SLAVE, "slave" },
3840 #endif
3841 #ifdef IFF_MULTICAST
3842 { IFF_MULTICAST, "multicast" },
3843 #endif
3844 #ifdef IFF_PORTSEL
3845 { IFF_PORTSEL, "portsel" },
3846 #endif
3847 #ifdef IFF_AUTOMEDIA
3848 { IFF_AUTOMEDIA, "automedia" },
3849 #endif
3850 #ifdef IFF_DYNAMIC
3851 { IFF_DYNAMIC, "dynamic" },
3852 #endif
3853 #ifdef IFF_OACTIVE
3854 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3855 #endif
3856 #ifdef IFF_SIMPLEX
3857 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3858 #endif
3859 #ifdef IFF_LINK0
3860 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3861 #endif
3862 #ifdef IFF_LINK1
3863 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3864 #endif
3865 #ifdef IFF_LINK2
3866 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3867 #endif
3868 { 0, 0 }
3871 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3872 doc: /* Return information about network interface named IFNAME.
3873 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3874 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3875 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3876 FLAGS is the current flags of the interface. */)
3877 (Lisp_Object ifname)
3879 struct ifreq rq;
3880 Lisp_Object res = Qnil;
3881 Lisp_Object elt;
3882 int s;
3883 int any = 0;
3885 CHECK_STRING (ifname);
3887 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3888 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3890 s = socket (AF_INET, SOCK_STREAM, 0);
3891 if (s < 0)
3892 return Qnil;
3894 elt = Qnil;
3895 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3896 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3898 int flags = rq.ifr_flags;
3899 const struct ifflag_def *fp;
3900 int fnum;
3902 any++;
3903 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3905 if (flags & fp->flag_bit)
3907 elt = Fcons (intern (fp->flag_sym), elt);
3908 flags -= fp->flag_bit;
3911 for (fnum = 0; flags && fnum < 32; fnum++)
3913 if (flags & (1 << fnum))
3915 elt = Fcons (make_number (fnum), elt);
3919 #endif
3920 res = Fcons (elt, res);
3922 elt = Qnil;
3923 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3924 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3926 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3927 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3928 int n;
3930 any++;
3931 for (n = 0; n < 6; n++)
3932 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3933 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3935 #endif
3936 res = Fcons (elt, res);
3938 elt = Qnil;
3939 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
3940 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3942 any++;
3943 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3944 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3945 #else
3946 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3947 #endif
3949 #endif
3950 res = Fcons (elt, res);
3952 elt = Qnil;
3953 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3954 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3956 any++;
3957 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3959 #endif
3960 res = Fcons (elt, res);
3962 elt = Qnil;
3963 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3964 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3966 any++;
3967 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3969 #endif
3970 res = Fcons (elt, res);
3972 close (s);
3974 return any ? res : Qnil;
3976 #endif
3977 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
3979 /* Turn off input and output for process PROC. */
3981 void
3982 deactivate_process (Lisp_Object proc)
3984 register int inchannel, outchannel;
3985 register struct Lisp_Process *p = XPROCESS (proc);
3987 inchannel = p->infd;
3988 outchannel = p->outfd;
3990 #ifdef ADAPTIVE_READ_BUFFERING
3991 if (p->read_output_delay > 0)
3993 if (--process_output_delay_count < 0)
3994 process_output_delay_count = 0;
3995 p->read_output_delay = 0;
3996 p->read_output_skip = 0;
3998 #endif
4000 if (inchannel >= 0)
4002 /* Beware SIGCHLD hereabouts. */
4003 flush_pending_output (inchannel);
4004 emacs_close (inchannel);
4005 if (outchannel >= 0 && outchannel != inchannel)
4006 emacs_close (outchannel);
4008 p->infd = -1;
4009 p->outfd = -1;
4010 #ifdef DATAGRAM_SOCKETS
4011 if (DATAGRAM_CHAN_P (inchannel))
4013 xfree (datagram_address[inchannel].sa);
4014 datagram_address[inchannel].sa = 0;
4015 datagram_address[inchannel].len = 0;
4017 #endif
4018 chan_process[inchannel] = Qnil;
4019 FD_CLR (inchannel, &input_wait_mask);
4020 FD_CLR (inchannel, &non_keyboard_wait_mask);
4021 #ifdef NON_BLOCKING_CONNECT
4022 if (FD_ISSET (inchannel, &connect_wait_mask))
4024 FD_CLR (inchannel, &connect_wait_mask);
4025 if (--num_pending_connects < 0)
4026 abort ();
4028 #endif
4029 if (inchannel == max_process_desc)
4031 int i;
4032 /* We just closed the highest-numbered process input descriptor,
4033 so recompute the highest-numbered one now. */
4034 max_process_desc = 0;
4035 for (i = 0; i < MAXDESC; i++)
4036 if (!NILP (chan_process[i]))
4037 max_process_desc = i;
4043 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4044 0, 4, 0,
4045 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4046 It is read into the process' buffers or given to their filter functions.
4047 Non-nil arg PROCESS means do not return until some output has been received
4048 from PROCESS.
4050 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4051 and milliseconds to wait; return after that much time whether or not
4052 there is any subprocess output. If SECONDS is a floating point number,
4053 it specifies a fractional number of seconds to wait.
4054 The MILLISEC argument is obsolete and should be avoided.
4056 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4057 from PROCESS, suspending reading output from other processes.
4058 If JUST-THIS-ONE is an integer, don't run any timers either.
4059 Return non-nil if we received any output before the timeout expired. */)
4060 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4062 int secs, usecs = 0;
4064 if (! NILP (process))
4065 CHECK_PROCESS (process);
4066 else
4067 just_this_one = Qnil;
4069 if (!NILP (millisec))
4070 { /* Obsolete calling convention using integers rather than floats. */
4071 CHECK_NUMBER (millisec);
4072 if (NILP (seconds))
4073 seconds = make_float (XINT (millisec) / 1000.0);
4074 else
4076 CHECK_NUMBER (seconds);
4077 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4081 if (!NILP (seconds))
4083 if (INTEGERP (seconds))
4084 secs = XINT (seconds);
4085 else if (FLOATP (seconds))
4087 double timeout = XFLOAT_DATA (seconds);
4088 secs = (int) timeout;
4089 usecs = (int) ((timeout - (double) secs) * 1000000);
4091 else
4092 wrong_type_argument (Qnumberp, seconds);
4094 if (secs < 0 || (secs == 0 && usecs == 0))
4095 secs = -1, usecs = 0;
4097 else
4098 secs = NILP (process) ? -1 : 0;
4100 return
4101 (wait_reading_process_output (secs, usecs, 0, 0,
4102 Qnil,
4103 !NILP (process) ? XPROCESS (process) : NULL,
4104 NILP (just_this_one) ? 0 :
4105 !INTEGERP (just_this_one) ? 1 : -1)
4106 ? Qt : Qnil);
4109 /* Accept a connection for server process SERVER on CHANNEL. */
4111 static int connect_counter = 0;
4113 static void
4114 server_accept_connection (Lisp_Object server, int channel)
4116 Lisp_Object proc, caller, name, buffer;
4117 Lisp_Object contact, host, service;
4118 struct Lisp_Process *ps= XPROCESS (server);
4119 struct Lisp_Process *p;
4120 int s;
4121 union u_sockaddr {
4122 struct sockaddr sa;
4123 struct sockaddr_in in;
4124 #ifdef AF_INET6
4125 struct sockaddr_in6 in6;
4126 #endif
4127 #ifdef HAVE_LOCAL_SOCKETS
4128 struct sockaddr_un un;
4129 #endif
4130 } saddr;
4131 int len = sizeof saddr;
4133 s = accept (channel, &saddr.sa, &len);
4135 if (s < 0)
4137 int code = errno;
4139 if (code == EAGAIN)
4140 return;
4141 #ifdef EWOULDBLOCK
4142 if (code == EWOULDBLOCK)
4143 return;
4144 #endif
4146 if (!NILP (ps->log))
4147 call3 (ps->log, server, Qnil,
4148 concat3 (build_string ("accept failed with code"),
4149 Fnumber_to_string (make_number (code)),
4150 build_string ("\n")));
4151 return;
4154 connect_counter++;
4156 /* Setup a new process to handle the connection. */
4158 /* Generate a unique identification of the caller, and build contact
4159 information for this process. */
4160 host = Qt;
4161 service = Qnil;
4162 switch (saddr.sa.sa_family)
4164 case AF_INET:
4166 Lisp_Object args[5];
4167 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4168 args[0] = build_string ("%d.%d.%d.%d");
4169 args[1] = make_number (*ip++);
4170 args[2] = make_number (*ip++);
4171 args[3] = make_number (*ip++);
4172 args[4] = make_number (*ip++);
4173 host = Fformat (5, args);
4174 service = make_number (ntohs (saddr.in.sin_port));
4176 args[0] = build_string (" <%s:%d>");
4177 args[1] = host;
4178 args[2] = service;
4179 caller = Fformat (3, args);
4181 break;
4183 #ifdef AF_INET6
4184 case AF_INET6:
4186 Lisp_Object args[9];
4187 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4188 int i;
4189 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4190 for (i = 0; i < 8; i++)
4191 args[i+1] = make_number (ntohs (ip6[i]));
4192 host = Fformat (9, args);
4193 service = make_number (ntohs (saddr.in.sin_port));
4195 args[0] = build_string (" <[%s]:%d>");
4196 args[1] = host;
4197 args[2] = service;
4198 caller = Fformat (3, args);
4200 break;
4201 #endif
4203 #ifdef HAVE_LOCAL_SOCKETS
4204 case AF_LOCAL:
4205 #endif
4206 default:
4207 caller = Fnumber_to_string (make_number (connect_counter));
4208 caller = concat3 (build_string (" <"), caller, build_string (">"));
4209 break;
4212 /* Create a new buffer name for this process if it doesn't have a
4213 filter. The new buffer name is based on the buffer name or
4214 process name of the server process concatenated with the caller
4215 identification. */
4217 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4218 buffer = Qnil;
4219 else
4221 buffer = ps->buffer;
4222 if (!NILP (buffer))
4223 buffer = Fbuffer_name (buffer);
4224 else
4225 buffer = ps->name;
4226 if (!NILP (buffer))
4228 buffer = concat2 (buffer, caller);
4229 buffer = Fget_buffer_create (buffer);
4233 /* Generate a unique name for the new server process. Combine the
4234 server process name with the caller identification. */
4236 name = concat2 (ps->name, caller);
4237 proc = make_process (name);
4239 chan_process[s] = proc;
4241 #ifdef O_NONBLOCK
4242 fcntl (s, F_SETFL, O_NONBLOCK);
4243 #else
4244 #ifdef O_NDELAY
4245 fcntl (s, F_SETFL, O_NDELAY);
4246 #endif
4247 #endif
4249 p = XPROCESS (proc);
4251 /* Build new contact information for this setup. */
4252 contact = Fcopy_sequence (ps->childp);
4253 contact = Fplist_put (contact, QCserver, Qnil);
4254 contact = Fplist_put (contact, QChost, host);
4255 if (!NILP (service))
4256 contact = Fplist_put (contact, QCservice, service);
4257 contact = Fplist_put (contact, QCremote,
4258 conv_sockaddr_to_lisp (&saddr.sa, len));
4259 #ifdef HAVE_GETSOCKNAME
4260 len = sizeof saddr;
4261 if (getsockname (s, &saddr.sa, &len) == 0)
4262 contact = Fplist_put (contact, QClocal,
4263 conv_sockaddr_to_lisp (&saddr.sa, len));
4264 #endif
4266 p->childp = contact;
4267 p->plist = Fcopy_sequence (ps->plist);
4268 p->type = Qnetwork;
4270 p->buffer = buffer;
4271 p->sentinel = ps->sentinel;
4272 p->filter = ps->filter;
4273 p->command = Qnil;
4274 p->pid = 0;
4275 p->infd = s;
4276 p->outfd = s;
4277 p->status = Qrun;
4279 /* Client processes for accepted connections are not stopped initially. */
4280 if (!EQ (p->filter, Qt))
4282 FD_SET (s, &input_wait_mask);
4283 FD_SET (s, &non_keyboard_wait_mask);
4286 if (s > max_process_desc)
4287 max_process_desc = s;
4289 /* Setup coding system for new process based on server process.
4290 This seems to be the proper thing to do, as the coding system
4291 of the new process should reflect the settings at the time the
4292 server socket was opened; not the current settings. */
4294 p->decode_coding_system = ps->decode_coding_system;
4295 p->encode_coding_system = ps->encode_coding_system;
4296 setup_process_coding_systems (proc);
4298 p->decoding_buf = make_uninit_string (0);
4299 p->decoding_carryover = 0;
4300 p->encoding_buf = make_uninit_string (0);
4302 p->inherit_coding_system_flag
4303 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4305 if (!NILP (ps->log))
4306 call3 (ps->log, server, proc,
4307 concat3 (build_string ("accept from "),
4308 (STRINGP (host) ? host : build_string ("-")),
4309 build_string ("\n")));
4311 if (!NILP (p->sentinel))
4312 exec_sentinel (proc,
4313 concat3 (build_string ("open from "),
4314 (STRINGP (host) ? host : build_string ("-")),
4315 build_string ("\n")));
4318 /* This variable is different from waiting_for_input in keyboard.c.
4319 It is used to communicate to a lisp process-filter/sentinel (via the
4320 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4321 for user-input when that process-filter was called.
4322 waiting_for_input cannot be used as that is by definition 0 when
4323 lisp code is being evalled.
4324 This is also used in record_asynch_buffer_change.
4325 For that purpose, this must be 0
4326 when not inside wait_reading_process_output. */
4327 static int waiting_for_user_input_p;
4329 static Lisp_Object
4330 wait_reading_process_output_unwind (Lisp_Object data)
4332 waiting_for_user_input_p = XINT (data);
4333 return Qnil;
4336 /* This is here so breakpoints can be put on it. */
4337 static void
4338 wait_reading_process_output_1 (void)
4342 /* Use a wrapper around select to work around a bug in gdb 5.3.
4343 Normally, the wrapper is optimized away by inlining.
4345 If emacs is stopped inside select, the gdb backtrace doesn't
4346 show the function which called select, so it is practically
4347 impossible to step through wait_reading_process_output. */
4349 #ifndef select
4350 static INLINE int
4351 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4353 return select (n, rfd, wfd, xfd, tmo);
4355 #define select select_wrapper
4356 #endif
4358 /* Read and dispose of subprocess output while waiting for timeout to
4359 elapse and/or keyboard input to be available.
4361 TIME_LIMIT is:
4362 timeout in seconds, or
4363 zero for no limit, or
4364 -1 means gobble data immediately available but don't wait for any.
4366 MICROSECS is:
4367 an additional duration to wait, measured in microseconds.
4368 If this is nonzero and time_limit is 0, then the timeout
4369 consists of MICROSECS only.
4371 READ_KBD is a lisp value:
4372 0 to ignore keyboard input, or
4373 1 to return when input is available, or
4374 -1 meaning caller will actually read the input, so don't throw to
4375 the quit handler, or
4377 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4378 output that arrives.
4380 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4381 (and gobble terminal input into the buffer if any arrives).
4383 If WAIT_PROC is specified, wait until something arrives from that
4384 process. The return value is true if we read some input from
4385 that process.
4387 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4388 (suspending output from other processes). A negative value
4389 means don't run any timers either.
4391 If WAIT_PROC is specified, then the function returns true if we
4392 received input from that process before the timeout elapsed.
4393 Otherwise, return true if we received input from any process. */
4396 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4397 int do_display,
4398 Lisp_Object wait_for_cell,
4399 struct Lisp_Process *wait_proc, int just_wait_proc)
4401 register int channel, nfds;
4402 SELECT_TYPE Available;
4403 #ifdef NON_BLOCKING_CONNECT
4404 SELECT_TYPE Connecting;
4405 int check_connect;
4406 #endif
4407 int check_delay, no_avail;
4408 int xerrno;
4409 Lisp_Object proc;
4410 EMACS_TIME timeout, end_time;
4411 int wait_channel = -1;
4412 int got_some_input = 0;
4413 int count = SPECPDL_INDEX ();
4415 FD_ZERO (&Available);
4416 #ifdef NON_BLOCKING_CONNECT
4417 FD_ZERO (&Connecting);
4418 #endif
4420 if (time_limit == 0 && wait_proc && !NILP (Vinhibit_quit)
4421 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4422 message ("Blocking call to accept-process-output with quit inhibited!!");
4424 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4425 if (wait_proc != NULL)
4426 wait_channel = wait_proc->infd;
4428 record_unwind_protect (wait_reading_process_output_unwind,
4429 make_number (waiting_for_user_input_p));
4430 waiting_for_user_input_p = read_kbd;
4432 /* Since we may need to wait several times,
4433 compute the absolute time to return at. */
4434 if (time_limit || microsecs)
4436 EMACS_GET_TIME (end_time);
4437 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4438 EMACS_ADD_TIME (end_time, end_time, timeout);
4441 while (1)
4443 int timeout_reduced_for_timers = 0;
4445 /* If calling from keyboard input, do not quit
4446 since we want to return C-g as an input character.
4447 Otherwise, do pending quit if requested. */
4448 if (read_kbd >= 0)
4449 QUIT;
4450 #ifdef SYNC_INPUT
4451 else
4452 process_pending_signals ();
4453 #endif
4455 /* Exit now if the cell we're waiting for became non-nil. */
4456 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4457 break;
4459 /* Compute time from now till when time limit is up */
4460 /* Exit if already run out */
4461 if (time_limit == -1)
4463 /* -1 specified for timeout means
4464 gobble output available now
4465 but don't wait at all. */
4467 EMACS_SET_SECS_USECS (timeout, 0, 0);
4469 else if (time_limit || microsecs)
4471 EMACS_GET_TIME (timeout);
4472 EMACS_SUB_TIME (timeout, end_time, timeout);
4473 if (EMACS_TIME_NEG_P (timeout))
4474 break;
4476 else
4478 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4481 /* Normally we run timers here.
4482 But not if wait_for_cell; in those cases,
4483 the wait is supposed to be short,
4484 and those callers cannot handle running arbitrary Lisp code here. */
4485 if (NILP (wait_for_cell)
4486 && just_wait_proc >= 0)
4488 EMACS_TIME timer_delay;
4492 int old_timers_run = timers_run;
4493 struct buffer *old_buffer = current_buffer;
4494 Lisp_Object old_window = selected_window;
4496 timer_delay = timer_check (1);
4498 /* If a timer has run, this might have changed buffers
4499 an alike. Make read_key_sequence aware of that. */
4500 if (timers_run != old_timers_run
4501 && (old_buffer != current_buffer
4502 || !EQ (old_window, selected_window))
4503 && waiting_for_user_input_p == -1)
4504 record_asynch_buffer_change ();
4506 if (timers_run != old_timers_run && do_display)
4507 /* We must retry, since a timer may have requeued itself
4508 and that could alter the time_delay. */
4509 redisplay_preserve_echo_area (9);
4510 else
4511 break;
4513 while (!detect_input_pending ());
4515 /* If there is unread keyboard input, also return. */
4516 if (read_kbd != 0
4517 && requeued_events_pending_p ())
4518 break;
4520 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4522 EMACS_TIME difference;
4523 EMACS_SUB_TIME (difference, timer_delay, timeout);
4524 if (EMACS_TIME_NEG_P (difference))
4526 timeout = timer_delay;
4527 timeout_reduced_for_timers = 1;
4530 /* If time_limit is -1, we are not going to wait at all. */
4531 else if (time_limit != -1)
4533 /* This is so a breakpoint can be put here. */
4534 wait_reading_process_output_1 ();
4538 /* Cause C-g and alarm signals to take immediate action,
4539 and cause input available signals to zero out timeout.
4541 It is important that we do this before checking for process
4542 activity. If we get a SIGCHLD after the explicit checks for
4543 process activity, timeout is the only way we will know. */
4544 if (read_kbd < 0)
4545 set_waiting_for_input (&timeout);
4547 /* If status of something has changed, and no input is
4548 available, notify the user of the change right away. After
4549 this explicit check, we'll let the SIGCHLD handler zap
4550 timeout to get our attention. */
4551 if (update_tick != process_tick)
4553 SELECT_TYPE Atemp;
4554 #ifdef NON_BLOCKING_CONNECT
4555 SELECT_TYPE Ctemp;
4556 #endif
4558 if (kbd_on_hold_p ())
4559 FD_ZERO (&Atemp);
4560 else
4561 Atemp = input_wait_mask;
4562 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4564 EMACS_SET_SECS_USECS (timeout, 0, 0);
4565 if ((select (max (max (max_process_desc, max_keyboard_desc),
4566 max_gpm_desc) + 1,
4567 &Atemp,
4568 #ifdef NON_BLOCKING_CONNECT
4569 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4570 #else
4571 (SELECT_TYPE *)0,
4572 #endif
4573 (SELECT_TYPE *)0, &timeout)
4574 <= 0))
4576 /* It's okay for us to do this and then continue with
4577 the loop, since timeout has already been zeroed out. */
4578 clear_waiting_for_input ();
4579 status_notify (NULL);
4580 if (do_display) redisplay_preserve_echo_area (13);
4584 /* Don't wait for output from a non-running process. Just
4585 read whatever data has already been received. */
4586 if (wait_proc && wait_proc->raw_status_new)
4587 update_status (wait_proc);
4588 if (wait_proc
4589 && ! EQ (wait_proc->status, Qrun)
4590 && ! EQ (wait_proc->status, Qconnect))
4592 int nread, total_nread = 0;
4594 clear_waiting_for_input ();
4595 XSETPROCESS (proc, wait_proc);
4597 /* Read data from the process, until we exhaust it. */
4598 while (wait_proc->infd >= 0)
4600 nread = read_process_output (proc, wait_proc->infd);
4602 if (nread == 0)
4603 break;
4605 if (0 < nread)
4607 total_nread += nread;
4608 got_some_input = 1;
4610 #ifdef EIO
4611 else if (nread == -1 && EIO == errno)
4612 break;
4613 #endif
4614 #ifdef EAGAIN
4615 else if (nread == -1 && EAGAIN == errno)
4616 break;
4617 #endif
4618 #ifdef EWOULDBLOCK
4619 else if (nread == -1 && EWOULDBLOCK == errno)
4620 break;
4621 #endif
4623 if (total_nread > 0 && do_display)
4624 redisplay_preserve_echo_area (10);
4626 break;
4629 /* Wait till there is something to do */
4631 if (wait_proc && just_wait_proc)
4633 if (wait_proc->infd < 0) /* Terminated */
4634 break;
4635 FD_SET (wait_proc->infd, &Available);
4636 check_delay = 0;
4637 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4639 else if (!NILP (wait_for_cell))
4641 Available = non_process_wait_mask;
4642 check_delay = 0;
4643 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4645 else
4647 if (! read_kbd)
4648 Available = non_keyboard_wait_mask;
4649 else
4650 Available = input_wait_mask;
4651 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4652 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4655 /* If frame size has changed or the window is newly mapped,
4656 redisplay now, before we start to wait. There is a race
4657 condition here; if a SIGIO arrives between now and the select
4658 and indicates that a frame is trashed, the select may block
4659 displaying a trashed screen. */
4660 if (frame_garbaged && do_display)
4662 clear_waiting_for_input ();
4663 redisplay_preserve_echo_area (11);
4664 if (read_kbd < 0)
4665 set_waiting_for_input (&timeout);
4668 no_avail = 0;
4669 if (read_kbd && detect_input_pending ())
4671 nfds = 0;
4672 no_avail = 1;
4674 else
4676 #ifdef NON_BLOCKING_CONNECT
4677 if (check_connect)
4678 Connecting = connect_wait_mask;
4679 #endif
4681 #ifdef ADAPTIVE_READ_BUFFERING
4682 /* Set the timeout for adaptive read buffering if any
4683 process has non-zero read_output_skip and non-zero
4684 read_output_delay, and we are not reading output for a
4685 specific wait_channel. It is not executed if
4686 Vprocess_adaptive_read_buffering is nil. */
4687 if (process_output_skip && check_delay > 0)
4689 int usecs = EMACS_USECS (timeout);
4690 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4691 usecs = READ_OUTPUT_DELAY_MAX;
4692 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4694 proc = chan_process[channel];
4695 if (NILP (proc))
4696 continue;
4697 /* Find minimum non-zero read_output_delay among the
4698 processes with non-zero read_output_skip. */
4699 if (XPROCESS (proc)->read_output_delay > 0)
4701 check_delay--;
4702 if (!XPROCESS (proc)->read_output_skip)
4703 continue;
4704 FD_CLR (channel, &Available);
4705 XPROCESS (proc)->read_output_skip = 0;
4706 if (XPROCESS (proc)->read_output_delay < usecs)
4707 usecs = XPROCESS (proc)->read_output_delay;
4710 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4711 process_output_skip = 0;
4713 #endif
4714 #if defined (USE_GTK) || defined (HAVE_GCONF)
4715 nfds = xg_select
4716 #elif defined (HAVE_NS)
4717 nfds = ns_select
4718 #else
4719 nfds = select
4720 #endif
4721 (max (max (max_process_desc, max_keyboard_desc),
4722 max_gpm_desc) + 1,
4723 &Available,
4724 #ifdef NON_BLOCKING_CONNECT
4725 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4726 #else
4727 (SELECT_TYPE *)0,
4728 #endif
4729 (SELECT_TYPE *)0, &timeout);
4732 xerrno = errno;
4734 /* Make C-g and alarm signals set flags again */
4735 clear_waiting_for_input ();
4737 /* If we woke up due to SIGWINCH, actually change size now. */
4738 do_pending_window_change (0);
4740 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4741 /* We wanted the full specified time, so return now. */
4742 break;
4743 if (nfds < 0)
4745 if (xerrno == EINTR)
4746 no_avail = 1;
4747 else if (xerrno == EBADF)
4749 #ifdef AIX
4750 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4751 the child's closure of the pts gives the parent a SIGHUP, and
4752 the ptc file descriptor is automatically closed,
4753 yielding EBADF here or at select() call above.
4754 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4755 in m/ibmrt-aix.h), and here we just ignore the select error.
4756 Cleanup occurs c/o status_notify after SIGCLD. */
4757 no_avail = 1; /* Cannot depend on values returned */
4758 #else
4759 abort ();
4760 #endif
4762 else
4763 error ("select error: %s", emacs_strerror (xerrno));
4766 if (no_avail)
4768 FD_ZERO (&Available);
4769 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4772 #if 0 /* When polling is used, interrupt_input is 0,
4773 so get_input_pending should read the input.
4774 So this should not be needed. */
4775 /* If we are using polling for input,
4776 and we see input available, make it get read now.
4777 Otherwise it might not actually get read for a second.
4778 And on hpux, since we turn off polling in wait_reading_process_output,
4779 it might never get read at all if we don't spend much time
4780 outside of wait_reading_process_output. */
4781 if (read_kbd && interrupt_input
4782 && keyboard_bit_set (&Available)
4783 && input_polling_used ())
4784 kill (getpid (), SIGALRM);
4785 #endif
4787 /* Check for keyboard input */
4788 /* If there is any, return immediately
4789 to give it higher priority than subprocesses */
4791 if (read_kbd != 0)
4793 int old_timers_run = timers_run;
4794 struct buffer *old_buffer = current_buffer;
4795 Lisp_Object old_window = selected_window;
4796 int leave = 0;
4798 if (detect_input_pending_run_timers (do_display))
4800 swallow_events (do_display);
4801 if (detect_input_pending_run_timers (do_display))
4802 leave = 1;
4805 /* If a timer has run, this might have changed buffers
4806 an alike. Make read_key_sequence aware of that. */
4807 if (timers_run != old_timers_run
4808 && waiting_for_user_input_p == -1
4809 && (old_buffer != current_buffer
4810 || !EQ (old_window, selected_window)))
4811 record_asynch_buffer_change ();
4813 if (leave)
4814 break;
4817 /* If there is unread keyboard input, also return. */
4818 if (read_kbd != 0
4819 && requeued_events_pending_p ())
4820 break;
4822 /* If we are not checking for keyboard input now,
4823 do process events (but don't run any timers).
4824 This is so that X events will be processed.
4825 Otherwise they may have to wait until polling takes place.
4826 That would causes delays in pasting selections, for example.
4828 (We used to do this only if wait_for_cell.) */
4829 if (read_kbd == 0 && detect_input_pending ())
4831 swallow_events (do_display);
4832 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4833 if (detect_input_pending ())
4834 break;
4835 #endif
4838 /* Exit now if the cell we're waiting for became non-nil. */
4839 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4840 break;
4842 #ifdef SIGIO
4843 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4844 go read it. This can happen with X on BSD after logging out.
4845 In that case, there really is no input and no SIGIO,
4846 but select says there is input. */
4848 if (read_kbd && interrupt_input
4849 && keyboard_bit_set (&Available) && ! noninteractive)
4850 kill (getpid (), SIGIO);
4851 #endif
4853 if (! wait_proc)
4854 got_some_input |= nfds > 0;
4856 /* If checking input just got us a size-change event from X,
4857 obey it now if we should. */
4858 if (read_kbd || ! NILP (wait_for_cell))
4859 do_pending_window_change (0);
4861 /* Check for data from a process. */
4862 if (no_avail || nfds == 0)
4863 continue;
4865 /* Really FIRST_PROC_DESC should be 0 on Unix,
4866 but this is safer in the short run. */
4867 for (channel = 0; channel <= max_process_desc; channel++)
4869 if (FD_ISSET (channel, &Available)
4870 && FD_ISSET (channel, &non_keyboard_wait_mask))
4872 int nread;
4874 /* If waiting for this channel, arrange to return as
4875 soon as no more input to be processed. No more
4876 waiting. */
4877 if (wait_channel == channel)
4879 wait_channel = -1;
4880 time_limit = -1;
4881 got_some_input = 1;
4883 proc = chan_process[channel];
4884 if (NILP (proc))
4885 continue;
4887 /* If this is a server stream socket, accept connection. */
4888 if (EQ (XPROCESS (proc)->status, Qlisten))
4890 server_accept_connection (proc, channel);
4891 continue;
4894 /* Read data from the process, starting with our
4895 buffered-ahead character if we have one. */
4897 nread = read_process_output (proc, channel);
4898 if (nread > 0)
4900 /* Since read_process_output can run a filter,
4901 which can call accept-process-output,
4902 don't try to read from any other processes
4903 before doing the select again. */
4904 FD_ZERO (&Available);
4906 if (do_display)
4907 redisplay_preserve_echo_area (12);
4909 #ifdef EWOULDBLOCK
4910 else if (nread == -1 && errno == EWOULDBLOCK)
4912 #endif
4913 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4914 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4915 #ifdef O_NONBLOCK
4916 else if (nread == -1 && errno == EAGAIN)
4918 #else
4919 #ifdef O_NDELAY
4920 else if (nread == -1 && errno == EAGAIN)
4922 /* Note that we cannot distinguish between no input
4923 available now and a closed pipe.
4924 With luck, a closed pipe will be accompanied by
4925 subprocess termination and SIGCHLD. */
4926 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4928 #endif /* O_NDELAY */
4929 #endif /* O_NONBLOCK */
4930 #ifdef HAVE_PTYS
4931 /* On some OSs with ptys, when the process on one end of
4932 a pty exits, the other end gets an error reading with
4933 errno = EIO instead of getting an EOF (0 bytes read).
4934 Therefore, if we get an error reading and errno =
4935 EIO, just continue, because the child process has
4936 exited and should clean itself up soon (e.g. when we
4937 get a SIGCHLD).
4939 However, it has been known to happen that the SIGCHLD
4940 got lost. So raise the signal again just in case.
4941 It can't hurt. */
4942 else if (nread == -1 && errno == EIO)
4944 /* Clear the descriptor now, so we only raise the
4945 signal once. Don't do this if `process' is only
4946 a pty. */
4947 if (XPROCESS (proc)->pid != -2)
4949 FD_CLR (channel, &input_wait_mask);
4950 FD_CLR (channel, &non_keyboard_wait_mask);
4952 kill (getpid (), SIGCHLD);
4955 #endif /* HAVE_PTYS */
4956 /* If we can detect process termination, don't consider the process
4957 gone just because its pipe is closed. */
4958 #ifdef SIGCHLD
4959 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4961 #endif
4962 else
4964 /* Preserve status of processes already terminated. */
4965 XPROCESS (proc)->tick = ++process_tick;
4966 deactivate_process (proc);
4967 if (XPROCESS (proc)->raw_status_new)
4968 update_status (XPROCESS (proc));
4969 if (EQ (XPROCESS (proc)->status, Qrun))
4970 XPROCESS (proc)->status
4971 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4974 #ifdef NON_BLOCKING_CONNECT
4975 if (check_connect && FD_ISSET (channel, &Connecting)
4976 && FD_ISSET (channel, &connect_wait_mask))
4978 struct Lisp_Process *p;
4980 FD_CLR (channel, &connect_wait_mask);
4981 if (--num_pending_connects < 0)
4982 abort ();
4984 proc = chan_process[channel];
4985 if (NILP (proc))
4986 continue;
4988 p = XPROCESS (proc);
4990 #ifdef GNU_LINUX
4991 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4992 So only use it on systems where it is known to work. */
4994 int xlen = sizeof (xerrno);
4995 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4996 xerrno = errno;
4998 #else
5000 struct sockaddr pname;
5001 int pnamelen = sizeof (pname);
5003 /* If connection failed, getpeername will fail. */
5004 xerrno = 0;
5005 if (getpeername (channel, &pname, &pnamelen) < 0)
5007 /* Obtain connect failure code through error slippage. */
5008 char dummy;
5009 xerrno = errno;
5010 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5011 xerrno = errno;
5014 #endif
5015 if (xerrno)
5017 p->tick = ++process_tick;
5018 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5019 deactivate_process (proc);
5021 else
5023 p->status = Qrun;
5024 /* Execute the sentinel here. If we had relied on
5025 status_notify to do it later, it will read input
5026 from the process before calling the sentinel. */
5027 exec_sentinel (proc, build_string ("open\n"));
5028 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5030 FD_SET (p->infd, &input_wait_mask);
5031 FD_SET (p->infd, &non_keyboard_wait_mask);
5035 #endif /* NON_BLOCKING_CONNECT */
5036 } /* end for each file descriptor */
5037 } /* end while exit conditions not met */
5039 unbind_to (count, Qnil);
5041 /* If calling from keyboard input, do not quit
5042 since we want to return C-g as an input character.
5043 Otherwise, do pending quit if requested. */
5044 if (read_kbd >= 0)
5046 /* Prevent input_pending from remaining set if we quit. */
5047 clear_input_pending ();
5048 QUIT;
5051 return got_some_input;
5054 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5056 static Lisp_Object
5057 read_process_output_call (Lisp_Object fun_and_args)
5059 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5062 static Lisp_Object
5063 read_process_output_error_handler (Lisp_Object error)
5065 cmd_error_internal (error, "error in process filter: ");
5066 Vinhibit_quit = Qt;
5067 update_echo_area ();
5068 Fsleep_for (make_number (2), Qnil);
5069 return Qt;
5072 /* Read pending output from the process channel,
5073 starting with our buffered-ahead character if we have one.
5074 Yield number of decoded characters read.
5076 This function reads at most 4096 characters.
5077 If you want to read all available subprocess output,
5078 you must call it repeatedly until it returns zero.
5080 The characters read are decoded according to PROC's coding-system
5081 for decoding. */
5083 static int
5084 read_process_output (Lisp_Object proc, register int channel)
5086 register int nbytes;
5087 char *chars;
5088 register Lisp_Object outstream;
5089 register struct Lisp_Process *p = XPROCESS (proc);
5090 register int opoint;
5091 struct coding_system *coding = proc_decode_coding_system[channel];
5092 int carryover = p->decoding_carryover;
5093 int readmax = 4096;
5094 int count = SPECPDL_INDEX ();
5095 Lisp_Object odeactivate;
5097 chars = (char *) alloca (carryover + readmax);
5098 if (carryover)
5099 /* See the comment above. */
5100 memcpy (chars, SDATA (p->decoding_buf), carryover);
5102 #ifdef DATAGRAM_SOCKETS
5103 /* We have a working select, so proc_buffered_char is always -1. */
5104 if (DATAGRAM_CHAN_P (channel))
5106 int len = datagram_address[channel].len;
5107 nbytes = recvfrom (channel, chars + carryover, readmax,
5108 0, datagram_address[channel].sa, &len);
5110 else
5111 #endif
5112 if (proc_buffered_char[channel] < 0)
5114 nbytes = emacs_read (channel, chars + carryover, readmax);
5115 #ifdef ADAPTIVE_READ_BUFFERING
5116 if (nbytes > 0 && p->adaptive_read_buffering)
5118 int delay = p->read_output_delay;
5119 if (nbytes < 256)
5121 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5123 if (delay == 0)
5124 process_output_delay_count++;
5125 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5128 else if (delay > 0 && (nbytes == readmax))
5130 delay -= READ_OUTPUT_DELAY_INCREMENT;
5131 if (delay == 0)
5132 process_output_delay_count--;
5134 p->read_output_delay = delay;
5135 if (delay)
5137 p->read_output_skip = 1;
5138 process_output_skip = 1;
5141 #endif
5143 else
5145 chars[carryover] = proc_buffered_char[channel];
5146 proc_buffered_char[channel] = -1;
5147 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5148 if (nbytes < 0)
5149 nbytes = 1;
5150 else
5151 nbytes = nbytes + 1;
5154 p->decoding_carryover = 0;
5156 /* At this point, NBYTES holds number of bytes just received
5157 (including the one in proc_buffered_char[channel]). */
5158 if (nbytes <= 0)
5160 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5161 return nbytes;
5162 coding->mode |= CODING_MODE_LAST_BLOCK;
5165 /* Now set NBYTES how many bytes we must decode. */
5166 nbytes += carryover;
5168 odeactivate = Vdeactivate_mark;
5169 /* There's no good reason to let process filters change the current
5170 buffer, and many callers of accept-process-output, sit-for, and
5171 friends don't expect current-buffer to be changed from under them. */
5172 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5174 /* Read and dispose of the process output. */
5175 outstream = p->filter;
5176 if (!NILP (outstream))
5178 Lisp_Object obuffer, okeymap;
5179 Lisp_Object text;
5180 int outer_running_asynch_code = running_asynch_code;
5181 int waiting = waiting_for_user_input_p;
5183 /* No need to gcpro these, because all we do with them later
5184 is test them for EQness, and none of them should be a string. */
5185 XSETBUFFER (obuffer, current_buffer);
5186 okeymap = current_buffer->keymap;
5188 /* We inhibit quit here instead of just catching it so that
5189 hitting ^G when a filter happens to be running won't screw
5190 it up. */
5191 specbind (Qinhibit_quit, Qt);
5192 specbind (Qlast_nonmenu_event, Qt);
5194 /* In case we get recursively called,
5195 and we already saved the match data nonrecursively,
5196 save the same match data in safely recursive fashion. */
5197 if (outer_running_asynch_code)
5199 Lisp_Object tem;
5200 /* Don't clobber the CURRENT match data, either! */
5201 tem = Fmatch_data (Qnil, Qnil, Qnil);
5202 restore_search_regs ();
5203 record_unwind_save_match_data ();
5204 Fset_match_data (tem, Qt);
5207 /* For speed, if a search happens within this code,
5208 save the match data in a special nonrecursive fashion. */
5209 running_asynch_code = 1;
5211 decode_coding_c_string (coding, chars, nbytes, Qt);
5212 text = coding->dst_object;
5213 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5214 /* A new coding system might be found. */
5215 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5217 p->decode_coding_system = Vlast_coding_system_used;
5219 /* Don't call setup_coding_system for
5220 proc_decode_coding_system[channel] here. It is done in
5221 detect_coding called via decode_coding above. */
5223 /* If a coding system for encoding is not yet decided, we set
5224 it as the same as coding-system for decoding.
5226 But, before doing that we must check if
5227 proc_encode_coding_system[p->outfd] surely points to a
5228 valid memory because p->outfd will be changed once EOF is
5229 sent to the process. */
5230 if (NILP (p->encode_coding_system)
5231 && proc_encode_coding_system[p->outfd])
5233 p->encode_coding_system
5234 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5235 setup_coding_system (p->encode_coding_system,
5236 proc_encode_coding_system[p->outfd]);
5240 if (coding->carryover_bytes > 0)
5242 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5243 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5244 memcpy (SDATA (p->decoding_buf), coding->carryover,
5245 coding->carryover_bytes);
5246 p->decoding_carryover = coding->carryover_bytes;
5248 if (SBYTES (text) > 0)
5249 internal_condition_case_1 (read_process_output_call,
5250 Fcons (outstream,
5251 Fcons (proc, Fcons (text, Qnil))),
5252 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5253 read_process_output_error_handler);
5255 /* If we saved the match data nonrecursively, restore it now. */
5256 restore_search_regs ();
5257 running_asynch_code = outer_running_asynch_code;
5259 /* Restore waiting_for_user_input_p as it was
5260 when we were called, in case the filter clobbered it. */
5261 waiting_for_user_input_p = waiting;
5263 #if 0 /* Call record_asynch_buffer_change unconditionally,
5264 because we might have changed minor modes or other things
5265 that affect key bindings. */
5266 if (! EQ (Fcurrent_buffer (), obuffer)
5267 || ! EQ (current_buffer->keymap, okeymap))
5268 #endif
5269 /* But do it only if the caller is actually going to read events.
5270 Otherwise there's no need to make him wake up, and it could
5271 cause trouble (for example it would make sit_for return). */
5272 if (waiting_for_user_input_p == -1)
5273 record_asynch_buffer_change ();
5276 /* If no filter, write into buffer if it isn't dead. */
5277 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5279 Lisp_Object old_read_only;
5280 int old_begv, old_zv;
5281 int old_begv_byte, old_zv_byte;
5282 int before, before_byte;
5283 int opoint_byte;
5284 Lisp_Object text;
5285 struct buffer *b;
5287 Fset_buffer (p->buffer);
5288 opoint = PT;
5289 opoint_byte = PT_BYTE;
5290 old_read_only = current_buffer->read_only;
5291 old_begv = BEGV;
5292 old_zv = ZV;
5293 old_begv_byte = BEGV_BYTE;
5294 old_zv_byte = ZV_BYTE;
5296 current_buffer->read_only = Qnil;
5298 /* Insert new output into buffer
5299 at the current end-of-output marker,
5300 thus preserving logical ordering of input and output. */
5301 if (XMARKER (p->mark)->buffer)
5302 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5303 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5304 ZV_BYTE));
5305 else
5306 SET_PT_BOTH (ZV, ZV_BYTE);
5307 before = PT;
5308 before_byte = PT_BYTE;
5310 /* If the output marker is outside of the visible region, save
5311 the restriction and widen. */
5312 if (! (BEGV <= PT && PT <= ZV))
5313 Fwiden ();
5315 decode_coding_c_string (coding, chars, nbytes, Qt);
5316 text = coding->dst_object;
5317 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5318 /* A new coding system might be found. See the comment in the
5319 similar code in the previous `if' block. */
5320 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5322 p->decode_coding_system = Vlast_coding_system_used;
5323 if (NILP (p->encode_coding_system)
5324 && proc_encode_coding_system[p->outfd])
5326 p->encode_coding_system
5327 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5328 setup_coding_system (p->encode_coding_system,
5329 proc_encode_coding_system[p->outfd]);
5332 if (coding->carryover_bytes > 0)
5334 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5335 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5336 memcpy (SDATA (p->decoding_buf), coding->carryover,
5337 coding->carryover_bytes);
5338 p->decoding_carryover = coding->carryover_bytes;
5340 /* Adjust the multibyteness of TEXT to that of the buffer. */
5341 if (NILP (current_buffer->enable_multibyte_characters)
5342 != ! STRING_MULTIBYTE (text))
5343 text = (STRING_MULTIBYTE (text)
5344 ? Fstring_as_unibyte (text)
5345 : Fstring_to_multibyte (text));
5346 /* Insert before markers in case we are inserting where
5347 the buffer's mark is, and the user's next command is Meta-y. */
5348 insert_from_string_before_markers (text, 0, 0,
5349 SCHARS (text), SBYTES (text), 0);
5351 /* Make sure the process marker's position is valid when the
5352 process buffer is changed in the signal_after_change above.
5353 W3 is known to do that. */
5354 if (BUFFERP (p->buffer)
5355 && (b = XBUFFER (p->buffer), b != current_buffer))
5356 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5357 else
5358 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5360 update_mode_lines++;
5362 /* Make sure opoint and the old restrictions
5363 float ahead of any new text just as point would. */
5364 if (opoint >= before)
5366 opoint += PT - before;
5367 opoint_byte += PT_BYTE - before_byte;
5369 if (old_begv > before)
5371 old_begv += PT - before;
5372 old_begv_byte += PT_BYTE - before_byte;
5374 if (old_zv >= before)
5376 old_zv += PT - before;
5377 old_zv_byte += PT_BYTE - before_byte;
5380 /* If the restriction isn't what it should be, set it. */
5381 if (old_begv != BEGV || old_zv != ZV)
5382 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5385 current_buffer->read_only = old_read_only;
5386 SET_PT_BOTH (opoint, opoint_byte);
5388 /* Handling the process output should not deactivate the mark. */
5389 Vdeactivate_mark = odeactivate;
5391 unbind_to (count, Qnil);
5392 return nbytes;
5395 /* Sending data to subprocess */
5397 jmp_buf send_process_frame;
5398 Lisp_Object process_sent_to;
5400 SIGTYPE
5401 send_process_trap (int ignore)
5403 SIGNAL_THREAD_CHECK (SIGPIPE);
5404 sigunblock (sigmask (SIGPIPE));
5405 longjmp (send_process_frame, 1);
5408 /* Send some data to process PROC.
5409 BUF is the beginning of the data; LEN is the number of characters.
5410 OBJECT is the Lisp object that the data comes from. If OBJECT is
5411 nil or t, it means that the data comes from C string.
5413 If OBJECT is not nil, the data is encoded by PROC's coding-system
5414 for encoding before it is sent.
5416 This function can evaluate Lisp code and can garbage collect. */
5418 static void
5419 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5420 volatile int len, volatile Lisp_Object object)
5422 /* Use volatile to protect variables from being clobbered by longjmp. */
5423 struct Lisp_Process *p = XPROCESS (proc);
5424 int rv;
5425 struct coding_system *coding;
5426 struct gcpro gcpro1;
5427 SIGTYPE (*volatile old_sigpipe) (int);
5429 GCPRO1 (object);
5431 if (p->raw_status_new)
5432 update_status (p);
5433 if (! EQ (p->status, Qrun))
5434 error ("Process %s not running", SDATA (p->name));
5435 if (p->outfd < 0)
5436 error ("Output file descriptor of %s is closed", SDATA (p->name));
5438 coding = proc_encode_coding_system[p->outfd];
5439 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5441 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5442 || (BUFFERP (object)
5443 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5444 || EQ (object, Qt))
5446 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5447 /* The coding system for encoding was changed to raw-text
5448 because we sent a unibyte text previously. Now we are
5449 sending a multibyte text, thus we must encode it by the
5450 original coding system specified for the current process. */
5451 setup_coding_system (p->encode_coding_system, coding);
5452 coding->src_multibyte = 1;
5454 else
5456 /* For sending a unibyte text, character code conversion should
5457 not take place but EOL conversion should. So, setup raw-text
5458 or one of the subsidiary if we have not yet done it. */
5459 if (CODING_REQUIRE_ENCODING (coding))
5461 if (CODING_REQUIRE_FLUSHING (coding))
5463 /* But, before changing the coding, we must flush out data. */
5464 coding->mode |= CODING_MODE_LAST_BLOCK;
5465 send_process (proc, "", 0, Qt);
5466 coding->mode &= CODING_MODE_LAST_BLOCK;
5468 setup_coding_system (raw_text_coding_system
5469 (Vlast_coding_system_used),
5470 coding);
5471 coding->src_multibyte = 0;
5474 coding->dst_multibyte = 0;
5476 if (CODING_REQUIRE_ENCODING (coding))
5478 coding->dst_object = Qt;
5479 if (BUFFERP (object))
5481 int from_byte, from, to;
5482 int save_pt, save_pt_byte;
5483 struct buffer *cur = current_buffer;
5485 set_buffer_internal (XBUFFER (object));
5486 save_pt = PT, save_pt_byte = PT_BYTE;
5488 from_byte = PTR_BYTE_POS (buf);
5489 from = BYTE_TO_CHAR (from_byte);
5490 to = BYTE_TO_CHAR (from_byte + len);
5491 TEMP_SET_PT_BOTH (from, from_byte);
5492 encode_coding_object (coding, object, from, from_byte,
5493 to, from_byte + len, Qt);
5494 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5495 set_buffer_internal (cur);
5497 else if (STRINGP (object))
5499 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5500 SBYTES (object), Qt);
5502 else
5504 coding->dst_object = make_unibyte_string (buf, len);
5505 coding->produced = len;
5508 len = coding->produced;
5509 object = coding->dst_object;
5510 buf = SDATA (object);
5513 if (pty_max_bytes == 0)
5515 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5516 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5517 if (pty_max_bytes < 0)
5518 pty_max_bytes = 250;
5519 #else
5520 pty_max_bytes = 250;
5521 #endif
5522 /* Deduct one, to leave space for the eof. */
5523 pty_max_bytes--;
5526 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5527 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5528 when returning with longjmp despite being declared volatile. */
5529 if (!setjmp (send_process_frame))
5531 process_sent_to = proc;
5532 while (len > 0)
5534 int this = len;
5536 /* Send this batch, using one or more write calls. */
5537 while (this > 0)
5539 int outfd = p->outfd;
5540 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5541 #ifdef DATAGRAM_SOCKETS
5542 if (DATAGRAM_CHAN_P (outfd))
5544 rv = sendto (outfd, (char *) buf, this,
5545 0, datagram_address[outfd].sa,
5546 datagram_address[outfd].len);
5547 if (rv < 0 && errno == EMSGSIZE)
5549 signal (SIGPIPE, old_sigpipe);
5550 report_file_error ("sending datagram",
5551 Fcons (proc, Qnil));
5554 else
5555 #endif
5557 rv = emacs_write (outfd, (char *) buf, this);
5558 #ifdef ADAPTIVE_READ_BUFFERING
5559 if (p->read_output_delay > 0
5560 && p->adaptive_read_buffering == 1)
5562 p->read_output_delay = 0;
5563 process_output_delay_count--;
5564 p->read_output_skip = 0;
5566 #endif
5568 signal (SIGPIPE, old_sigpipe);
5570 if (rv < 0)
5572 if (0
5573 #ifdef EWOULDBLOCK
5574 || errno == EWOULDBLOCK
5575 #endif
5576 #ifdef EAGAIN
5577 || errno == EAGAIN
5578 #endif
5580 /* Buffer is full. Wait, accepting input;
5581 that may allow the program
5582 to finish doing output and read more. */
5584 int offset = 0;
5586 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5587 /* A gross hack to work around a bug in FreeBSD.
5588 In the following sequence, read(2) returns
5589 bogus data:
5591 write(2) 1022 bytes
5592 write(2) 954 bytes, get EAGAIN
5593 read(2) 1024 bytes in process_read_output
5594 read(2) 11 bytes in process_read_output
5596 That is, read(2) returns more bytes than have
5597 ever been written successfully. The 1033 bytes
5598 read are the 1022 bytes written successfully
5599 after processing (for example with CRs added if
5600 the terminal is set up that way which it is
5601 here). The same bytes will be seen again in a
5602 later read(2), without the CRs. */
5604 if (errno == EAGAIN)
5606 int flags = FWRITE;
5607 ioctl (p->outfd, TIOCFLUSH, &flags);
5609 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5611 /* Running filters might relocate buffers or strings.
5612 Arrange to relocate BUF. */
5613 if (BUFFERP (object))
5614 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5615 else if (STRINGP (object))
5616 offset = buf - SDATA (object);
5618 #ifdef EMACS_HAS_USECS
5619 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5620 #else
5621 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5622 #endif
5624 if (BUFFERP (object))
5625 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5626 else if (STRINGP (object))
5627 buf = offset + SDATA (object);
5629 rv = 0;
5631 else
5632 /* This is a real error. */
5633 report_file_error ("writing to process", Fcons (proc, Qnil));
5635 buf += rv;
5636 len -= rv;
5637 this -= rv;
5641 else
5643 signal (SIGPIPE, old_sigpipe);
5644 proc = process_sent_to;
5645 p = XPROCESS (proc);
5646 p->raw_status_new = 0;
5647 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5648 p->tick = ++process_tick;
5649 deactivate_process (proc);
5650 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5653 UNGCPRO;
5656 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5657 3, 3, 0,
5658 doc: /* Send current contents of region as input to PROCESS.
5659 PROCESS may be a process, a buffer, the name of a process or buffer, or
5660 nil, indicating the current buffer's process.
5661 Called from program, takes three arguments, PROCESS, START and END.
5662 If the region is more than 500 characters long,
5663 it is sent in several bunches. This may happen even for shorter regions.
5664 Output from processes can arrive in between bunches. */)
5665 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5667 Lisp_Object proc;
5668 int start1, end1;
5670 proc = get_process (process);
5671 validate_region (&start, &end);
5673 if (XINT (start) < GPT && XINT (end) > GPT)
5674 move_gap (XINT (start));
5676 start1 = CHAR_TO_BYTE (XINT (start));
5677 end1 = CHAR_TO_BYTE (XINT (end));
5678 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5679 Fcurrent_buffer ());
5681 return Qnil;
5684 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5685 2, 2, 0,
5686 doc: /* Send PROCESS the contents of STRING as input.
5687 PROCESS may be a process, a buffer, the name of a process or buffer, or
5688 nil, indicating the current buffer's process.
5689 If STRING is more than 500 characters long,
5690 it is sent in several bunches. This may happen even for shorter strings.
5691 Output from processes can arrive in between bunches. */)
5692 (Lisp_Object process, Lisp_Object string)
5694 Lisp_Object proc;
5695 CHECK_STRING (string);
5696 proc = get_process (process);
5697 send_process (proc, SDATA (string),
5698 SBYTES (string), string);
5699 return Qnil;
5702 /* Return the foreground process group for the tty/pty that
5703 the process P uses. */
5704 static int
5705 emacs_get_tty_pgrp (struct Lisp_Process *p)
5707 int gid = -1;
5709 #ifdef TIOCGPGRP
5710 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5712 int fd;
5713 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5714 master side. Try the slave side. */
5715 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5717 if (fd != -1)
5719 ioctl (fd, TIOCGPGRP, &gid);
5720 emacs_close (fd);
5723 #endif /* defined (TIOCGPGRP ) */
5725 return gid;
5728 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5729 Sprocess_running_child_p, 0, 1, 0,
5730 doc: /* Return t if PROCESS has given the terminal to a child.
5731 If the operating system does not make it possible to find out,
5732 return t unconditionally. */)
5733 (Lisp_Object process)
5735 /* Initialize in case ioctl doesn't exist or gives an error,
5736 in a way that will cause returning t. */
5737 int gid;
5738 Lisp_Object proc;
5739 struct Lisp_Process *p;
5741 proc = get_process (process);
5742 p = XPROCESS (proc);
5744 if (!EQ (p->type, Qreal))
5745 error ("Process %s is not a subprocess",
5746 SDATA (p->name));
5747 if (p->infd < 0)
5748 error ("Process %s is not active",
5749 SDATA (p->name));
5751 gid = emacs_get_tty_pgrp (p);
5753 if (gid == p->pid)
5754 return Qnil;
5755 return Qt;
5758 /* send a signal number SIGNO to PROCESS.
5759 If CURRENT_GROUP is t, that means send to the process group
5760 that currently owns the terminal being used to communicate with PROCESS.
5761 This is used for various commands in shell mode.
5762 If CURRENT_GROUP is lambda, that means send to the process group
5763 that currently owns the terminal, but only if it is NOT the shell itself.
5765 If NOMSG is zero, insert signal-announcements into process's buffers
5766 right away.
5768 If we can, we try to signal PROCESS by sending control characters
5769 down the pty. This allows us to signal inferiors who have changed
5770 their uid, for which killpg would return an EPERM error. */
5772 static void
5773 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5774 int nomsg)
5776 Lisp_Object proc;
5777 register struct Lisp_Process *p;
5778 int gid;
5779 int no_pgrp = 0;
5781 proc = get_process (process);
5782 p = XPROCESS (proc);
5784 if (!EQ (p->type, Qreal))
5785 error ("Process %s is not a subprocess",
5786 SDATA (p->name));
5787 if (p->infd < 0)
5788 error ("Process %s is not active",
5789 SDATA (p->name));
5791 if (!p->pty_flag)
5792 current_group = Qnil;
5794 /* If we are using pgrps, get a pgrp number and make it negative. */
5795 if (NILP (current_group))
5796 /* Send the signal to the shell's process group. */
5797 gid = p->pid;
5798 else
5800 #ifdef SIGNALS_VIA_CHARACTERS
5801 /* If possible, send signals to the entire pgrp
5802 by sending an input character to it. */
5804 /* TERMIOS is the latest and bestest, and seems most likely to
5805 work. If the system has it, use it. */
5806 #ifdef HAVE_TERMIOS
5807 struct termios t;
5808 cc_t *sig_char = NULL;
5810 tcgetattr (p->infd, &t);
5812 switch (signo)
5814 case SIGINT:
5815 sig_char = &t.c_cc[VINTR];
5816 break;
5818 case SIGQUIT:
5819 sig_char = &t.c_cc[VQUIT];
5820 break;
5822 case SIGTSTP:
5823 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5824 sig_char = &t.c_cc[VSWTCH];
5825 #else
5826 sig_char = &t.c_cc[VSUSP];
5827 #endif
5828 break;
5831 if (sig_char && *sig_char != CDISABLE)
5833 send_process (proc, sig_char, 1, Qnil);
5834 return;
5836 /* If we can't send the signal with a character,
5837 fall through and send it another way. */
5838 #else /* ! HAVE_TERMIOS */
5840 /* On Berkeley descendants, the following IOCTL's retrieve the
5841 current control characters. */
5842 #if defined (TIOCGLTC) && defined (TIOCGETC)
5844 struct tchars c;
5845 struct ltchars lc;
5847 switch (signo)
5849 case SIGINT:
5850 ioctl (p->infd, TIOCGETC, &c);
5851 send_process (proc, &c.t_intrc, 1, Qnil);
5852 return;
5853 case SIGQUIT:
5854 ioctl (p->infd, TIOCGETC, &c);
5855 send_process (proc, &c.t_quitc, 1, Qnil);
5856 return;
5857 #ifdef SIGTSTP
5858 case SIGTSTP:
5859 ioctl (p->infd, TIOCGLTC, &lc);
5860 send_process (proc, &lc.t_suspc, 1, Qnil);
5861 return;
5862 #endif /* ! defined (SIGTSTP) */
5865 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5867 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5868 characters. */
5869 #ifdef TCGETA
5870 struct termio t;
5871 switch (signo)
5873 case SIGINT:
5874 ioctl (p->infd, TCGETA, &t);
5875 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5876 return;
5877 case SIGQUIT:
5878 ioctl (p->infd, TCGETA, &t);
5879 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5880 return;
5881 #ifdef SIGTSTP
5882 case SIGTSTP:
5883 ioctl (p->infd, TCGETA, &t);
5884 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5885 return;
5886 #endif /* ! defined (SIGTSTP) */
5888 #else /* ! defined (TCGETA) */
5889 Your configuration files are messed up.
5890 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5891 you'd better be using one of the alternatives above! */
5892 #endif /* ! defined (TCGETA) */
5893 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5894 /* In this case, the code above should alway return. */
5895 abort ();
5896 #endif /* ! defined HAVE_TERMIOS */
5898 /* The code above may fall through if it can't
5899 handle the signal. */
5900 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5902 #ifdef TIOCGPGRP
5903 /* Get the current pgrp using the tty itself, if we have that.
5904 Otherwise, use the pty to get the pgrp.
5905 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5906 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5907 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5908 His patch indicates that if TIOCGPGRP returns an error, then
5909 we should just assume that p->pid is also the process group id. */
5911 gid = emacs_get_tty_pgrp (p);
5913 if (gid == -1)
5914 /* If we can't get the information, assume
5915 the shell owns the tty. */
5916 gid = p->pid;
5918 /* It is not clear whether anything really can set GID to -1.
5919 Perhaps on some system one of those ioctls can or could do so.
5920 Or perhaps this is vestigial. */
5921 if (gid == -1)
5922 no_pgrp = 1;
5923 #else /* ! defined (TIOCGPGRP ) */
5924 /* Can't select pgrps on this system, so we know that
5925 the child itself heads the pgrp. */
5926 gid = p->pid;
5927 #endif /* ! defined (TIOCGPGRP ) */
5929 /* If current_group is lambda, and the shell owns the terminal,
5930 don't send any signal. */
5931 if (EQ (current_group, Qlambda) && gid == p->pid)
5932 return;
5935 switch (signo)
5937 #ifdef SIGCONT
5938 case SIGCONT:
5939 p->raw_status_new = 0;
5940 p->status = Qrun;
5941 p->tick = ++process_tick;
5942 if (!nomsg)
5944 status_notify (NULL);
5945 redisplay_preserve_echo_area (13);
5947 break;
5948 #endif /* ! defined (SIGCONT) */
5949 case SIGINT:
5950 case SIGQUIT:
5951 case SIGKILL:
5952 flush_pending_output (p->infd);
5953 break;
5956 /* If we don't have process groups, send the signal to the immediate
5957 subprocess. That isn't really right, but it's better than any
5958 obvious alternative. */
5959 if (no_pgrp)
5961 kill (p->pid, signo);
5962 return;
5965 /* gid may be a pid, or minus a pgrp's number */
5966 #ifdef TIOCSIGSEND
5967 if (!NILP (current_group))
5969 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5970 EMACS_KILLPG (gid, signo);
5972 else
5974 gid = - p->pid;
5975 kill (gid, signo);
5977 #else /* ! defined (TIOCSIGSEND) */
5978 EMACS_KILLPG (gid, signo);
5979 #endif /* ! defined (TIOCSIGSEND) */
5982 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5983 doc: /* Interrupt process PROCESS.
5984 PROCESS may be a process, a buffer, or the name of a process or buffer.
5985 No arg or nil means current buffer's process.
5986 Second arg CURRENT-GROUP non-nil means send signal to
5987 the current process-group of the process's controlling terminal
5988 rather than to the process's own process group.
5989 If the process is a shell, this means interrupt current subjob
5990 rather than the shell.
5992 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5993 don't send the signal. */)
5994 (Lisp_Object process, Lisp_Object current_group)
5996 process_send_signal (process, SIGINT, current_group, 0);
5997 return process;
6000 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6001 doc: /* Kill process PROCESS. May be process or name of one.
6002 See function `interrupt-process' for more details on usage. */)
6003 (Lisp_Object process, Lisp_Object current_group)
6005 process_send_signal (process, SIGKILL, current_group, 0);
6006 return process;
6009 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6010 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6011 See function `interrupt-process' for more details on usage. */)
6012 (Lisp_Object process, Lisp_Object current_group)
6014 process_send_signal (process, SIGQUIT, current_group, 0);
6015 return process;
6018 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6019 doc: /* Stop process PROCESS. May be process or name of one.
6020 See function `interrupt-process' for more details on usage.
6021 If PROCESS is a network or serial process, inhibit handling of incoming
6022 traffic. */)
6023 (Lisp_Object process, Lisp_Object current_group)
6025 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6027 struct Lisp_Process *p;
6029 p = XPROCESS (process);
6030 if (NILP (p->command)
6031 && p->infd >= 0)
6033 FD_CLR (p->infd, &input_wait_mask);
6034 FD_CLR (p->infd, &non_keyboard_wait_mask);
6036 p->command = Qt;
6037 return process;
6039 #ifndef SIGTSTP
6040 error ("No SIGTSTP support");
6041 #else
6042 process_send_signal (process, SIGTSTP, current_group, 0);
6043 #endif
6044 return process;
6047 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6048 doc: /* Continue process PROCESS. May be process or name of one.
6049 See function `interrupt-process' for more details on usage.
6050 If PROCESS is a network or serial process, resume handling of incoming
6051 traffic. */)
6052 (Lisp_Object process, Lisp_Object current_group)
6054 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6056 struct Lisp_Process *p;
6058 p = XPROCESS (process);
6059 if (EQ (p->command, Qt)
6060 && p->infd >= 0
6061 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6063 FD_SET (p->infd, &input_wait_mask);
6064 FD_SET (p->infd, &non_keyboard_wait_mask);
6065 #ifdef WINDOWSNT
6066 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6067 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6068 #endif
6069 #ifdef HAVE_TERMIOS
6070 tcflush (p->infd, TCIFLUSH);
6071 #endif
6073 p->command = Qnil;
6074 return process;
6076 #ifdef SIGCONT
6077 process_send_signal (process, SIGCONT, current_group, 0);
6078 #else
6079 error ("No SIGCONT support");
6080 #endif
6081 return process;
6084 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6085 2, 2, "sProcess (name or number): \nnSignal code: ",
6086 doc: /* Send PROCESS the signal with code SIGCODE.
6087 PROCESS may also be a number specifying the process id of the
6088 process to signal; in this case, the process need not be a child of
6089 this Emacs.
6090 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6091 (Lisp_Object process, Lisp_Object sigcode)
6093 pid_t pid;
6095 if (INTEGERP (process))
6097 pid = XINT (process);
6098 goto got_it;
6101 if (FLOATP (process))
6103 pid = (pid_t) XFLOAT_DATA (process);
6104 goto got_it;
6107 if (STRINGP (process))
6109 Lisp_Object tem;
6110 if (tem = Fget_process (process), NILP (tem))
6112 pid = XINT (Fstring_to_number (process, make_number (10)));
6113 if (pid > 0)
6114 goto got_it;
6116 process = tem;
6118 else
6119 process = get_process (process);
6121 if (NILP (process))
6122 return process;
6124 CHECK_PROCESS (process);
6125 pid = XPROCESS (process)->pid;
6126 if (pid <= 0)
6127 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6129 got_it:
6131 #define parse_signal(NAME, VALUE) \
6132 else if (!xstrcasecmp (name, NAME)) \
6133 XSETINT (sigcode, VALUE)
6135 if (INTEGERP (sigcode))
6137 else
6139 unsigned char *name;
6141 CHECK_SYMBOL (sigcode);
6142 name = SDATA (SYMBOL_NAME (sigcode));
6144 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6145 name += 3;
6147 if (0)
6149 #ifdef SIGUSR1
6150 parse_signal ("usr1", SIGUSR1);
6151 #endif
6152 #ifdef SIGUSR2
6153 parse_signal ("usr2", SIGUSR2);
6154 #endif
6155 #ifdef SIGTERM
6156 parse_signal ("term", SIGTERM);
6157 #endif
6158 #ifdef SIGHUP
6159 parse_signal ("hup", SIGHUP);
6160 #endif
6161 #ifdef SIGINT
6162 parse_signal ("int", SIGINT);
6163 #endif
6164 #ifdef SIGQUIT
6165 parse_signal ("quit", SIGQUIT);
6166 #endif
6167 #ifdef SIGILL
6168 parse_signal ("ill", SIGILL);
6169 #endif
6170 #ifdef SIGABRT
6171 parse_signal ("abrt", SIGABRT);
6172 #endif
6173 #ifdef SIGEMT
6174 parse_signal ("emt", SIGEMT);
6175 #endif
6176 #ifdef SIGKILL
6177 parse_signal ("kill", SIGKILL);
6178 #endif
6179 #ifdef SIGFPE
6180 parse_signal ("fpe", SIGFPE);
6181 #endif
6182 #ifdef SIGBUS
6183 parse_signal ("bus", SIGBUS);
6184 #endif
6185 #ifdef SIGSEGV
6186 parse_signal ("segv", SIGSEGV);
6187 #endif
6188 #ifdef SIGSYS
6189 parse_signal ("sys", SIGSYS);
6190 #endif
6191 #ifdef SIGPIPE
6192 parse_signal ("pipe", SIGPIPE);
6193 #endif
6194 #ifdef SIGALRM
6195 parse_signal ("alrm", SIGALRM);
6196 #endif
6197 #ifdef SIGURG
6198 parse_signal ("urg", SIGURG);
6199 #endif
6200 #ifdef SIGSTOP
6201 parse_signal ("stop", SIGSTOP);
6202 #endif
6203 #ifdef SIGTSTP
6204 parse_signal ("tstp", SIGTSTP);
6205 #endif
6206 #ifdef SIGCONT
6207 parse_signal ("cont", SIGCONT);
6208 #endif
6209 #ifdef SIGCHLD
6210 parse_signal ("chld", SIGCHLD);
6211 #endif
6212 #ifdef SIGTTIN
6213 parse_signal ("ttin", SIGTTIN);
6214 #endif
6215 #ifdef SIGTTOU
6216 parse_signal ("ttou", SIGTTOU);
6217 #endif
6218 #ifdef SIGIO
6219 parse_signal ("io", SIGIO);
6220 #endif
6221 #ifdef SIGXCPU
6222 parse_signal ("xcpu", SIGXCPU);
6223 #endif
6224 #ifdef SIGXFSZ
6225 parse_signal ("xfsz", SIGXFSZ);
6226 #endif
6227 #ifdef SIGVTALRM
6228 parse_signal ("vtalrm", SIGVTALRM);
6229 #endif
6230 #ifdef SIGPROF
6231 parse_signal ("prof", SIGPROF);
6232 #endif
6233 #ifdef SIGWINCH
6234 parse_signal ("winch", SIGWINCH);
6235 #endif
6236 #ifdef SIGINFO
6237 parse_signal ("info", SIGINFO);
6238 #endif
6239 else
6240 error ("Undefined signal name %s", name);
6243 #undef parse_signal
6245 return make_number (kill (pid, XINT (sigcode)));
6248 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6249 doc: /* Make PROCESS see end-of-file in its input.
6250 EOF comes after any text already sent to it.
6251 PROCESS may be a process, a buffer, the name of a process or buffer, or
6252 nil, indicating the current buffer's process.
6253 If PROCESS is a network connection, or is a process communicating
6254 through a pipe (as opposed to a pty), then you cannot send any more
6255 text to PROCESS after you call this function.
6256 If PROCESS is a serial process, wait until all output written to the
6257 process has been transmitted to the serial port. */)
6258 (Lisp_Object process)
6260 Lisp_Object proc;
6261 struct coding_system *coding;
6263 if (DATAGRAM_CONN_P (process))
6264 return process;
6266 proc = get_process (process);
6267 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6269 /* Make sure the process is really alive. */
6270 if (XPROCESS (proc)->raw_status_new)
6271 update_status (XPROCESS (proc));
6272 if (! EQ (XPROCESS (proc)->status, Qrun))
6273 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6275 if (CODING_REQUIRE_FLUSHING (coding))
6277 coding->mode |= CODING_MODE_LAST_BLOCK;
6278 send_process (proc, "", 0, Qnil);
6281 if (XPROCESS (proc)->pty_flag)
6282 send_process (proc, "\004", 1, Qnil);
6283 else if (EQ (XPROCESS (proc)->type, Qserial))
6285 #ifdef HAVE_TERMIOS
6286 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6287 error ("tcdrain() failed: %s", emacs_strerror (errno));
6288 #endif
6289 /* Do nothing on Windows because writes are blocking. */
6291 else
6293 int old_outfd, new_outfd;
6295 #ifdef HAVE_SHUTDOWN
6296 /* If this is a network connection, or socketpair is used
6297 for communication with the subprocess, call shutdown to cause EOF.
6298 (In some old system, shutdown to socketpair doesn't work.
6299 Then we just can't win.) */
6300 if (EQ (XPROCESS (proc)->type, Qnetwork)
6301 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6302 shutdown (XPROCESS (proc)->outfd, 1);
6303 /* In case of socketpair, outfd == infd, so don't close it. */
6304 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6305 emacs_close (XPROCESS (proc)->outfd);
6306 #else /* not HAVE_SHUTDOWN */
6307 emacs_close (XPROCESS (proc)->outfd);
6308 #endif /* not HAVE_SHUTDOWN */
6309 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6310 if (new_outfd < 0)
6311 abort ();
6312 old_outfd = XPROCESS (proc)->outfd;
6314 if (!proc_encode_coding_system[new_outfd])
6315 proc_encode_coding_system[new_outfd]
6316 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6317 memcpy (proc_encode_coding_system[new_outfd],
6318 proc_encode_coding_system[old_outfd],
6319 sizeof (struct coding_system));
6320 memset (proc_encode_coding_system[old_outfd], 0,
6321 sizeof (struct coding_system));
6323 XPROCESS (proc)->outfd = new_outfd;
6325 return process;
6328 /* On receipt of a signal that a child status has changed, loop asking
6329 about children with changed statuses until the system says there
6330 are no more.
6332 All we do is change the status; we do not run sentinels or print
6333 notifications. That is saved for the next time keyboard input is
6334 done, in order to avoid timing errors.
6336 ** WARNING: this can be called during garbage collection.
6337 Therefore, it must not be fooled by the presence of mark bits in
6338 Lisp objects.
6340 ** USG WARNING: Although it is not obvious from the documentation
6341 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6342 signal() before executing at least one wait(), otherwise the
6343 handler will be called again, resulting in an infinite loop. The
6344 relevant portion of the documentation reads "SIGCLD signals will be
6345 queued and the signal-catching function will be continually
6346 reentered until the queue is empty". Invoking signal() causes the
6347 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6348 Inc.
6350 ** Malloc WARNING: This should never call malloc either directly or
6351 indirectly; if it does, that is a bug */
6353 #ifdef SIGCHLD
6354 SIGTYPE
6355 sigchld_handler (int signo)
6357 int old_errno = errno;
6358 Lisp_Object proc;
6359 struct Lisp_Process *p;
6361 SIGNAL_THREAD_CHECK (signo);
6363 while (1)
6365 pid_t pid;
6366 int w;
6367 Lisp_Object tail;
6369 #ifdef WNOHANG
6370 #ifndef WUNTRACED
6371 #define WUNTRACED 0
6372 #endif /* no WUNTRACED */
6373 /* Keep trying to get a status until we get a definitive result. */
6376 errno = 0;
6377 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6379 while (pid < 0 && errno == EINTR);
6381 if (pid <= 0)
6383 /* PID == 0 means no processes found, PID == -1 means a real
6384 failure. We have done all our job, so return. */
6386 errno = old_errno;
6387 return;
6389 #else
6390 pid = wait (&w);
6391 #endif /* no WNOHANG */
6393 /* Find the process that signaled us, and record its status. */
6395 /* The process can have been deleted by Fdelete_process. */
6396 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6398 Lisp_Object xpid = XCAR (tail);
6399 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6400 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6402 XSETCAR (tail, Qnil);
6403 goto sigchld_end_of_loop;
6407 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6408 p = 0;
6409 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6411 proc = XCDR (XCAR (tail));
6412 p = XPROCESS (proc);
6413 if (EQ (p->type, Qreal) && p->pid == pid)
6414 break;
6415 p = 0;
6418 /* Look for an asynchronous process whose pid hasn't been filled
6419 in yet. */
6420 if (p == 0)
6421 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6423 proc = XCDR (XCAR (tail));
6424 p = XPROCESS (proc);
6425 if (p->pid == -1)
6426 break;
6427 p = 0;
6430 /* Change the status of the process that was found. */
6431 if (p != 0)
6433 int clear_desc_flag = 0;
6435 p->tick = ++process_tick;
6436 p->raw_status = w;
6437 p->raw_status_new = 1;
6439 /* If process has terminated, stop waiting for its output. */
6440 if ((WIFSIGNALED (w) || WIFEXITED (w))
6441 && p->infd >= 0)
6442 clear_desc_flag = 1;
6444 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6445 if (clear_desc_flag)
6447 FD_CLR (p->infd, &input_wait_mask);
6448 FD_CLR (p->infd, &non_keyboard_wait_mask);
6451 /* Tell wait_reading_process_output that it needs to wake up and
6452 look around. */
6453 if (input_available_clear_time)
6454 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6457 /* There was no asynchronous process found for that pid: we have
6458 a synchronous process. */
6459 else
6461 synch_process_alive = 0;
6463 /* Report the status of the synchronous process. */
6464 if (WIFEXITED (w))
6465 synch_process_retcode = WRETCODE (w);
6466 else if (WIFSIGNALED (w))
6467 synch_process_termsig = WTERMSIG (w);
6469 /* Tell wait_reading_process_output that it needs to wake up and
6470 look around. */
6471 if (input_available_clear_time)
6472 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6475 sigchld_end_of_loop:
6478 /* On some systems, we must return right away.
6479 If any more processes want to signal us, we will
6480 get another signal.
6481 Otherwise (on systems that have WNOHANG), loop around
6482 to use up all the processes that have something to tell us. */
6483 #if (defined WINDOWSNT \
6484 || (defined USG && !defined GNU_LINUX \
6485 && !(defined HPUX && defined WNOHANG)))
6486 errno = old_errno;
6487 return;
6488 #endif /* USG, but not HPUX with WNOHANG */
6491 #endif /* SIGCHLD */
6494 static Lisp_Object
6495 exec_sentinel_unwind (Lisp_Object data)
6497 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6498 return Qnil;
6501 static Lisp_Object
6502 exec_sentinel_error_handler (Lisp_Object error)
6504 cmd_error_internal (error, "error in process sentinel: ");
6505 Vinhibit_quit = Qt;
6506 update_echo_area ();
6507 Fsleep_for (make_number (2), Qnil);
6508 return Qt;
6511 static void
6512 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6514 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6515 register struct Lisp_Process *p = XPROCESS (proc);
6516 int count = SPECPDL_INDEX ();
6517 int outer_running_asynch_code = running_asynch_code;
6518 int waiting = waiting_for_user_input_p;
6520 if (inhibit_sentinels)
6521 return;
6523 /* No need to gcpro these, because all we do with them later
6524 is test them for EQness, and none of them should be a string. */
6525 odeactivate = Vdeactivate_mark;
6526 XSETBUFFER (obuffer, current_buffer);
6527 okeymap = current_buffer->keymap;
6529 /* There's no good reason to let sentinels change the current
6530 buffer, and many callers of accept-process-output, sit-for, and
6531 friends don't expect current-buffer to be changed from under them. */
6532 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6534 sentinel = p->sentinel;
6535 if (NILP (sentinel))
6536 return;
6538 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6539 assure that it gets restored no matter how the sentinel exits. */
6540 p->sentinel = Qnil;
6541 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6542 /* Inhibit quit so that random quits don't screw up a running filter. */
6543 specbind (Qinhibit_quit, Qt);
6544 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6546 /* In case we get recursively called,
6547 and we already saved the match data nonrecursively,
6548 save the same match data in safely recursive fashion. */
6549 if (outer_running_asynch_code)
6551 Lisp_Object tem;
6552 tem = Fmatch_data (Qnil, Qnil, Qnil);
6553 restore_search_regs ();
6554 record_unwind_save_match_data ();
6555 Fset_match_data (tem, Qt);
6558 /* For speed, if a search happens within this code,
6559 save the match data in a special nonrecursive fashion. */
6560 running_asynch_code = 1;
6562 internal_condition_case_1 (read_process_output_call,
6563 Fcons (sentinel,
6564 Fcons (proc, Fcons (reason, Qnil))),
6565 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6566 exec_sentinel_error_handler);
6568 /* If we saved the match data nonrecursively, restore it now. */
6569 restore_search_regs ();
6570 running_asynch_code = outer_running_asynch_code;
6572 Vdeactivate_mark = odeactivate;
6574 /* Restore waiting_for_user_input_p as it was
6575 when we were called, in case the filter clobbered it. */
6576 waiting_for_user_input_p = waiting;
6578 #if 0
6579 if (! EQ (Fcurrent_buffer (), obuffer)
6580 || ! EQ (current_buffer->keymap, okeymap))
6581 #endif
6582 /* But do it only if the caller is actually going to read events.
6583 Otherwise there's no need to make him wake up, and it could
6584 cause trouble (for example it would make sit_for return). */
6585 if (waiting_for_user_input_p == -1)
6586 record_asynch_buffer_change ();
6588 unbind_to (count, Qnil);
6591 /* Report all recent events of a change in process status
6592 (either run the sentinel or output a message).
6593 This is usually done while Emacs is waiting for keyboard input
6594 but can be done at other times. */
6596 static void
6597 status_notify (struct Lisp_Process *deleting_process)
6599 register Lisp_Object proc, buffer;
6600 Lisp_Object tail, msg;
6601 struct gcpro gcpro1, gcpro2;
6603 tail = Qnil;
6604 msg = Qnil;
6605 /* We need to gcpro tail; if read_process_output calls a filter
6606 which deletes a process and removes the cons to which tail points
6607 from Vprocess_alist, and then causes a GC, tail is an unprotected
6608 reference. */
6609 GCPRO2 (tail, msg);
6611 /* Set this now, so that if new processes are created by sentinels
6612 that we run, we get called again to handle their status changes. */
6613 update_tick = process_tick;
6615 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6617 Lisp_Object symbol;
6618 register struct Lisp_Process *p;
6620 proc = Fcdr (XCAR (tail));
6621 p = XPROCESS (proc);
6623 if (p->tick != p->update_tick)
6625 p->update_tick = p->tick;
6627 /* If process is still active, read any output that remains. */
6628 while (! EQ (p->filter, Qt)
6629 && ! EQ (p->status, Qconnect)
6630 && ! EQ (p->status, Qlisten)
6631 /* Network or serial process not stopped: */
6632 && ! EQ (p->command, Qt)
6633 && p->infd >= 0
6634 && p != deleting_process
6635 && read_process_output (proc, p->infd) > 0);
6637 buffer = p->buffer;
6639 /* Get the text to use for the message. */
6640 if (p->raw_status_new)
6641 update_status (p);
6642 msg = status_message (p);
6644 /* If process is terminated, deactivate it or delete it. */
6645 symbol = p->status;
6646 if (CONSP (p->status))
6647 symbol = XCAR (p->status);
6649 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6650 || EQ (symbol, Qclosed))
6652 if (delete_exited_processes)
6653 remove_process (proc);
6654 else
6655 deactivate_process (proc);
6658 /* The actions above may have further incremented p->tick.
6659 So set p->update_tick again
6660 so that an error in the sentinel will not cause
6661 this code to be run again. */
6662 p->update_tick = p->tick;
6663 /* Now output the message suitably. */
6664 if (!NILP (p->sentinel))
6665 exec_sentinel (proc, msg);
6666 /* Don't bother with a message in the buffer
6667 when a process becomes runnable. */
6668 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6670 Lisp_Object tem;
6671 struct buffer *old = current_buffer;
6672 int opoint, opoint_byte;
6673 int before, before_byte;
6675 /* Avoid error if buffer is deleted
6676 (probably that's why the process is dead, too) */
6677 if (NILP (XBUFFER (buffer)->name))
6678 continue;
6679 Fset_buffer (buffer);
6681 opoint = PT;
6682 opoint_byte = PT_BYTE;
6683 /* Insert new output into buffer
6684 at the current end-of-output marker,
6685 thus preserving logical ordering of input and output. */
6686 if (XMARKER (p->mark)->buffer)
6687 Fgoto_char (p->mark);
6688 else
6689 SET_PT_BOTH (ZV, ZV_BYTE);
6691 before = PT;
6692 before_byte = PT_BYTE;
6694 tem = current_buffer->read_only;
6695 current_buffer->read_only = Qnil;
6696 insert_string ("\nProcess ");
6697 Finsert (1, &p->name);
6698 insert_string (" ");
6699 Finsert (1, &msg);
6700 current_buffer->read_only = tem;
6701 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6703 if (opoint >= before)
6704 SET_PT_BOTH (opoint + (PT - before),
6705 opoint_byte + (PT_BYTE - before_byte));
6706 else
6707 SET_PT_BOTH (opoint, opoint_byte);
6709 set_buffer_internal (old);
6712 } /* end for */
6714 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6715 UNGCPRO;
6719 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6720 Sset_process_coding_system, 1, 3, 0,
6721 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6722 DECODING will be used to decode subprocess output and ENCODING to
6723 encode subprocess input. */)
6724 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6726 register struct Lisp_Process *p;
6728 CHECK_PROCESS (process);
6729 p = XPROCESS (process);
6730 if (p->infd < 0)
6731 error ("Input file descriptor of %s closed", SDATA (p->name));
6732 if (p->outfd < 0)
6733 error ("Output file descriptor of %s closed", SDATA (p->name));
6734 Fcheck_coding_system (decoding);
6735 Fcheck_coding_system (encoding);
6736 encoding = coding_inherit_eol_type (encoding, Qnil);
6737 p->decode_coding_system = decoding;
6738 p->encode_coding_system = encoding;
6739 setup_process_coding_systems (process);
6741 return Qnil;
6744 DEFUN ("process-coding-system",
6745 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6746 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6747 (register Lisp_Object process)
6749 CHECK_PROCESS (process);
6750 return Fcons (XPROCESS (process)->decode_coding_system,
6751 XPROCESS (process)->encode_coding_system);
6754 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6755 Sset_process_filter_multibyte, 2, 2, 0,
6756 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6757 If FLAG is non-nil, the filter is given multibyte strings.
6758 If FLAG is nil, the filter is given unibyte strings. In this case,
6759 all character code conversion except for end-of-line conversion is
6760 suppressed. */)
6761 (Lisp_Object process, Lisp_Object flag)
6763 register struct Lisp_Process *p;
6765 CHECK_PROCESS (process);
6766 p = XPROCESS (process);
6767 if (NILP (flag))
6768 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6769 setup_process_coding_systems (process);
6771 return Qnil;
6774 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6775 Sprocess_filter_multibyte_p, 1, 1, 0,
6776 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6777 (Lisp_Object process)
6779 register struct Lisp_Process *p;
6780 struct coding_system *coding;
6782 CHECK_PROCESS (process);
6783 p = XPROCESS (process);
6784 coding = proc_decode_coding_system[p->infd];
6785 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6791 static int add_gpm_wait_descriptor_called_flag;
6793 void
6794 add_gpm_wait_descriptor (int desc)
6796 if (! add_gpm_wait_descriptor_called_flag)
6797 FD_CLR (0, &input_wait_mask);
6798 add_gpm_wait_descriptor_called_flag = 1;
6799 FD_SET (desc, &input_wait_mask);
6800 FD_SET (desc, &gpm_wait_mask);
6801 if (desc > max_gpm_desc)
6802 max_gpm_desc = desc;
6805 void
6806 delete_gpm_wait_descriptor (int desc)
6808 int fd;
6809 int lim = max_gpm_desc;
6811 FD_CLR (desc, &input_wait_mask);
6812 FD_CLR (desc, &non_process_wait_mask);
6814 if (desc == max_gpm_desc)
6815 for (fd = 0; fd < lim; fd++)
6816 if (FD_ISSET (fd, &input_wait_mask)
6817 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6818 && !FD_ISSET (fd, &non_process_wait_mask))
6819 max_gpm_desc = fd;
6822 /* Return nonzero if *MASK has a bit set
6823 that corresponds to one of the keyboard input descriptors. */
6825 static int
6826 keyboard_bit_set (fd_set *mask)
6828 int fd;
6830 for (fd = 0; fd <= max_keyboard_desc; fd++)
6831 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6832 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6833 return 1;
6835 return 0;
6838 #else /* not subprocesses */
6840 /* Defined on msdos.c. */
6841 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6842 EMACS_TIME *);
6844 /* Implementation of wait_reading_process_output, assuming that there
6845 are no subprocesses. Used only by the MS-DOS build.
6847 Wait for timeout to elapse and/or keyboard input to be available.
6849 time_limit is:
6850 timeout in seconds, or
6851 zero for no limit, or
6852 -1 means gobble data immediately available but don't wait for any.
6854 read_kbd is a Lisp_Object:
6855 0 to ignore keyboard input, or
6856 1 to return when input is available, or
6857 -1 means caller will actually read the input, so don't throw to
6858 the quit handler.
6860 see full version for other parameters. We know that wait_proc will
6861 always be NULL, since `subprocesses' isn't defined.
6863 do_display != 0 means redisplay should be done to show subprocess
6864 output that arrives.
6866 Return true if we received input from any process. */
6869 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6870 int do_display,
6871 Lisp_Object wait_for_cell,
6872 struct Lisp_Process *wait_proc, int just_wait_proc)
6874 register int nfds;
6875 EMACS_TIME end_time, timeout;
6876 SELECT_TYPE waitchannels;
6877 int xerrno;
6879 /* What does time_limit really mean? */
6880 if (time_limit || microsecs)
6882 EMACS_GET_TIME (end_time);
6883 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6884 EMACS_ADD_TIME (end_time, end_time, timeout);
6887 /* Turn off periodic alarms (in case they are in use)
6888 and then turn off any other atimers,
6889 because the select emulator uses alarms. */
6890 stop_polling ();
6891 turn_on_atimers (0);
6893 while (1)
6895 int timeout_reduced_for_timers = 0;
6897 /* If calling from keyboard input, do not quit
6898 since we want to return C-g as an input character.
6899 Otherwise, do pending quit if requested. */
6900 if (read_kbd >= 0)
6901 QUIT;
6903 /* Exit now if the cell we're waiting for became non-nil. */
6904 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6905 break;
6907 /* Compute time from now till when time limit is up */
6908 /* Exit if already run out */
6909 if (time_limit == -1)
6911 /* -1 specified for timeout means
6912 gobble output available now
6913 but don't wait at all. */
6915 EMACS_SET_SECS_USECS (timeout, 0, 0);
6917 else if (time_limit || microsecs)
6919 EMACS_GET_TIME (timeout);
6920 EMACS_SUB_TIME (timeout, end_time, timeout);
6921 if (EMACS_TIME_NEG_P (timeout))
6922 break;
6924 else
6926 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6929 /* If our caller will not immediately handle keyboard events,
6930 run timer events directly.
6931 (Callers that will immediately read keyboard events
6932 call timer_delay on their own.) */
6933 if (NILP (wait_for_cell))
6935 EMACS_TIME timer_delay;
6939 int old_timers_run = timers_run;
6940 timer_delay = timer_check (1);
6941 if (timers_run != old_timers_run && do_display)
6942 /* We must retry, since a timer may have requeued itself
6943 and that could alter the time delay. */
6944 redisplay_preserve_echo_area (14);
6945 else
6946 break;
6948 while (!detect_input_pending ());
6950 /* If there is unread keyboard input, also return. */
6951 if (read_kbd != 0
6952 && requeued_events_pending_p ())
6953 break;
6955 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6957 EMACS_TIME difference;
6958 EMACS_SUB_TIME (difference, timer_delay, timeout);
6959 if (EMACS_TIME_NEG_P (difference))
6961 timeout = timer_delay;
6962 timeout_reduced_for_timers = 1;
6967 /* Cause C-g and alarm signals to take immediate action,
6968 and cause input available signals to zero out timeout. */
6969 if (read_kbd < 0)
6970 set_waiting_for_input (&timeout);
6972 /* Wait till there is something to do. */
6974 if (! read_kbd && NILP (wait_for_cell))
6975 FD_ZERO (&waitchannels);
6976 else
6977 FD_SET (0, &waitchannels);
6979 /* If a frame has been newly mapped and needs updating,
6980 reprocess its display stuff. */
6981 if (frame_garbaged && do_display)
6983 clear_waiting_for_input ();
6984 redisplay_preserve_echo_area (15);
6985 if (read_kbd < 0)
6986 set_waiting_for_input (&timeout);
6989 if (read_kbd && detect_input_pending ())
6991 nfds = 0;
6992 FD_ZERO (&waitchannels);
6994 else
6995 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6996 &timeout);
6998 xerrno = errno;
7000 /* Make C-g and alarm signals set flags again */
7001 clear_waiting_for_input ();
7003 /* If we woke up due to SIGWINCH, actually change size now. */
7004 do_pending_window_change (0);
7006 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7007 /* We waited the full specified time, so return now. */
7008 break;
7010 if (nfds == -1)
7012 /* If the system call was interrupted, then go around the
7013 loop again. */
7014 if (xerrno == EINTR)
7015 FD_ZERO (&waitchannels);
7016 else
7017 error ("select error: %s", emacs_strerror (xerrno));
7020 /* Check for keyboard input */
7022 if (read_kbd
7023 && detect_input_pending_run_timers (do_display))
7025 swallow_events (do_display);
7026 if (detect_input_pending_run_timers (do_display))
7027 break;
7030 /* If there is unread keyboard input, also return. */
7031 if (read_kbd
7032 && requeued_events_pending_p ())
7033 break;
7035 /* If wait_for_cell. check for keyboard input
7036 but don't run any timers.
7037 ??? (It seems wrong to me to check for keyboard
7038 input at all when wait_for_cell, but the code
7039 has been this way since July 1994.
7040 Try changing this after version 19.31.) */
7041 if (! NILP (wait_for_cell)
7042 && detect_input_pending ())
7044 swallow_events (do_display);
7045 if (detect_input_pending ())
7046 break;
7049 /* Exit now if the cell we're waiting for became non-nil. */
7050 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7051 break;
7054 start_polling ();
7056 return 0;
7059 #endif /* not subprocesses */
7061 /* The following functions are needed even if async subprocesses are
7062 not supported. Some of them are no-op stubs in that case. */
7064 /* Add DESC to the set of keyboard input descriptors. */
7066 void
7067 add_keyboard_wait_descriptor (int desc)
7069 #ifdef subprocesses
7070 FD_SET (desc, &input_wait_mask);
7071 FD_SET (desc, &non_process_wait_mask);
7072 if (desc > max_keyboard_desc)
7073 max_keyboard_desc = desc;
7074 #endif
7077 /* From now on, do not expect DESC to give keyboard input. */
7079 void
7080 delete_keyboard_wait_descriptor (int desc)
7082 #ifdef subprocesses
7083 int fd;
7084 int lim = max_keyboard_desc;
7086 FD_CLR (desc, &input_wait_mask);
7087 FD_CLR (desc, &non_process_wait_mask);
7089 if (desc == max_keyboard_desc)
7090 for (fd = 0; fd < lim; fd++)
7091 if (FD_ISSET (fd, &input_wait_mask)
7092 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7093 && !FD_ISSET (fd, &gpm_wait_mask))
7094 max_keyboard_desc = fd;
7095 #endif /* subprocesses */
7098 /* Setup coding systems of PROCESS. */
7100 void
7101 setup_process_coding_systems (Lisp_Object process)
7103 #ifdef subprocesses
7104 struct Lisp_Process *p = XPROCESS (process);
7105 int inch = p->infd;
7106 int outch = p->outfd;
7107 Lisp_Object coding_system;
7109 if (inch < 0 || outch < 0)
7110 return;
7112 if (!proc_decode_coding_system[inch])
7113 proc_decode_coding_system[inch]
7114 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7115 coding_system = p->decode_coding_system;
7116 if (! NILP (p->filter))
7118 else if (BUFFERP (p->buffer))
7120 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7121 coding_system = raw_text_coding_system (coding_system);
7123 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7125 if (!proc_encode_coding_system[outch])
7126 proc_encode_coding_system[outch]
7127 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7128 setup_coding_system (p->encode_coding_system,
7129 proc_encode_coding_system[outch]);
7130 #endif
7133 /* Close all descriptors currently in use for communication
7134 with subprocess. This is used in a newly-forked subprocess
7135 to get rid of irrelevant descriptors. */
7137 void
7138 close_process_descs (void)
7140 #ifndef DOS_NT
7141 int i;
7142 for (i = 0; i < MAXDESC; i++)
7144 Lisp_Object process;
7145 process = chan_process[i];
7146 if (!NILP (process))
7148 int in = XPROCESS (process)->infd;
7149 int out = XPROCESS (process)->outfd;
7150 if (in >= 0)
7151 emacs_close (in);
7152 if (out >= 0 && in != out)
7153 emacs_close (out);
7156 #endif
7159 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7160 doc: /* Return the (or a) process associated with BUFFER.
7161 BUFFER may be a buffer or the name of one. */)
7162 (register Lisp_Object buffer)
7164 #ifdef subprocesses
7165 register Lisp_Object buf, tail, proc;
7167 if (NILP (buffer)) return Qnil;
7168 buf = Fget_buffer (buffer);
7169 if (NILP (buf)) return Qnil;
7171 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7173 proc = Fcdr (XCAR (tail));
7174 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7175 return proc;
7177 #endif /* subprocesses */
7178 return Qnil;
7181 DEFUN ("process-inherit-coding-system-flag",
7182 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7183 1, 1, 0,
7184 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7185 If this flag is t, `buffer-file-coding-system' of the buffer
7186 associated with PROCESS will inherit the coding system used to decode
7187 the process output. */)
7188 (register Lisp_Object process)
7190 #ifdef subprocesses
7191 CHECK_PROCESS (process);
7192 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7193 #else
7194 /* Ignore the argument and return the value of
7195 inherit-process-coding-system. */
7196 return inherit_process_coding_system ? Qt : Qnil;
7197 #endif
7200 /* Kill all processes associated with `buffer'.
7201 If `buffer' is nil, kill all processes */
7203 void
7204 kill_buffer_processes (Lisp_Object buffer)
7206 #ifdef subprocesses
7207 Lisp_Object tail, proc;
7209 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7211 proc = XCDR (XCAR (tail));
7212 if (PROCESSP (proc)
7213 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7215 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7216 Fdelete_process (proc);
7217 else if (XPROCESS (proc)->infd >= 0)
7218 process_send_signal (proc, SIGHUP, Qnil, 1);
7221 #else /* subprocesses */
7222 /* Since we have no subprocesses, this does nothing. */
7223 #endif /* subprocesses */
7226 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7227 0, 0, 0,
7228 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7229 This is intended for use by asynchronous process output filters and sentinels. */)
7230 (void)
7232 #ifdef subprocesses
7233 return (waiting_for_user_input_p ? Qt : Qnil);
7234 #else
7235 return Qnil;
7236 #endif
7239 /* Stop reading input from keyboard sources. */
7241 void
7242 hold_keyboard_input (void)
7244 kbd_is_on_hold = 1;
7247 /* Resume reading input from keyboard sources. */
7249 void
7250 unhold_keyboard_input (void)
7252 kbd_is_on_hold = 0;
7255 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7258 kbd_on_hold_p (void)
7260 return kbd_is_on_hold;
7264 /* Enumeration of and access to system processes a-la ps(1). */
7266 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7267 0, 0, 0,
7268 doc: /* Return a list of numerical process IDs of all running processes.
7269 If this functionality is unsupported, return nil.
7271 See `process-attributes' for getting attributes of a process given its ID. */)
7272 (void)
7274 return list_system_processes ();
7277 DEFUN ("process-attributes", Fprocess_attributes,
7278 Sprocess_attributes, 1, 1, 0,
7279 doc: /* Return attributes of the process given by its PID, a number.
7281 Value is an alist where each element is a cons cell of the form
7283 \(KEY . VALUE)
7285 If this functionality is unsupported, the value is nil.
7287 See `list-system-processes' for getting a list of all process IDs.
7289 The KEYs of the attributes that this function may return are listed
7290 below, together with the type of the associated VALUE (in parentheses).
7291 Not all platforms support all of these attributes; unsupported
7292 attributes will not appear in the returned alist.
7293 Unless explicitly indicated otherwise, numbers can have either
7294 integer or floating point values.
7296 euid -- Effective user User ID of the process (number)
7297 user -- User name corresponding to euid (string)
7298 egid -- Effective user Group ID of the process (number)
7299 group -- Group name corresponding to egid (string)
7300 comm -- Command name (executable name only) (string)
7301 state -- Process state code, such as "S", "R", or "T" (string)
7302 ppid -- Parent process ID (number)
7303 pgrp -- Process group ID (number)
7304 sess -- Session ID, i.e. process ID of session leader (number)
7305 ttname -- Controlling tty name (string)
7306 tpgid -- ID of foreground process group on the process's tty (number)
7307 minflt -- number of minor page faults (number)
7308 majflt -- number of major page faults (number)
7309 cminflt -- cumulative number of minor page faults (number)
7310 cmajflt -- cumulative number of major page faults (number)
7311 utime -- user time used by the process, in the (HIGH LOW USEC) format
7312 stime -- system time used by the process, in the (HIGH LOW USEC) format
7313 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7314 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7315 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7316 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7317 pri -- priority of the process (number)
7318 nice -- nice value of the process (number)
7319 thcount -- process thread count (number)
7320 start -- time the process started, in the (HIGH LOW USEC) format
7321 vsize -- virtual memory size of the process in KB's (number)
7322 rss -- resident set size of the process in KB's (number)
7323 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7324 pcpu -- percents of CPU time used by the process (floating-point number)
7325 pmem -- percents of total physical memory used by process's resident set
7326 (floating-point number)
7327 args -- command line which invoked the process (string). */)
7328 ( Lisp_Object pid)
7330 return system_process_attributes (pid);
7334 void
7335 init_process (void)
7337 #ifdef subprocesses
7338 register int i;
7340 inhibit_sentinels = 0;
7342 #ifdef SIGCHLD
7343 #ifndef CANNOT_DUMP
7344 if (! noninteractive || initialized)
7345 #endif
7346 signal (SIGCHLD, sigchld_handler);
7347 #endif
7349 FD_ZERO (&input_wait_mask);
7350 FD_ZERO (&non_keyboard_wait_mask);
7351 FD_ZERO (&non_process_wait_mask);
7352 max_process_desc = 0;
7354 #ifdef NON_BLOCKING_CONNECT
7355 FD_ZERO (&connect_wait_mask);
7356 num_pending_connects = 0;
7357 #endif
7359 #ifdef ADAPTIVE_READ_BUFFERING
7360 process_output_delay_count = 0;
7361 process_output_skip = 0;
7362 #endif
7364 /* Don't do this, it caused infinite select loops. The display
7365 method should call add_keyboard_wait_descriptor on stdin if it
7366 needs that. */
7367 #if 0
7368 FD_SET (0, &input_wait_mask);
7369 #endif
7371 Vprocess_alist = Qnil;
7372 #ifdef SIGCHLD
7373 deleted_pid_list = Qnil;
7374 #endif
7375 for (i = 0; i < MAXDESC; i++)
7377 chan_process[i] = Qnil;
7378 proc_buffered_char[i] = -1;
7380 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7381 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7382 #ifdef DATAGRAM_SOCKETS
7383 memset (datagram_address, 0, sizeof datagram_address);
7384 #endif
7387 Lisp_Object subfeatures = Qnil;
7388 const struct socket_options *sopt;
7390 #define ADD_SUBFEATURE(key, val) \
7391 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7393 #ifdef NON_BLOCKING_CONNECT
7394 ADD_SUBFEATURE (QCnowait, Qt);
7395 #endif
7396 #ifdef DATAGRAM_SOCKETS
7397 ADD_SUBFEATURE (QCtype, Qdatagram);
7398 #endif
7399 #ifdef HAVE_SEQPACKET
7400 ADD_SUBFEATURE (QCtype, Qseqpacket);
7401 #endif
7402 #ifdef HAVE_LOCAL_SOCKETS
7403 ADD_SUBFEATURE (QCfamily, Qlocal);
7404 #endif
7405 ADD_SUBFEATURE (QCfamily, Qipv4);
7406 #ifdef AF_INET6
7407 ADD_SUBFEATURE (QCfamily, Qipv6);
7408 #endif
7409 #ifdef HAVE_GETSOCKNAME
7410 ADD_SUBFEATURE (QCservice, Qt);
7411 #endif
7412 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7413 ADD_SUBFEATURE (QCserver, Qt);
7414 #endif
7416 for (sopt = socket_options; sopt->name; sopt++)
7417 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7419 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7422 #if defined (DARWIN_OS)
7423 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7424 processes. As such, we only change the default value. */
7425 if (initialized)
7427 const char *release = get_operating_system_release ();
7428 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7429 && release[1] == '.')) {
7430 Vprocess_connection_type = Qnil;
7433 #endif
7434 #endif /* subprocesses */
7435 kbd_is_on_hold = 0;
7438 void
7439 syms_of_process (void)
7441 #ifdef subprocesses
7443 Qprocessp = intern_c_string ("processp");
7444 staticpro (&Qprocessp);
7445 Qrun = intern_c_string ("run");
7446 staticpro (&Qrun);
7447 Qstop = intern_c_string ("stop");
7448 staticpro (&Qstop);
7449 Qsignal = intern_c_string ("signal");
7450 staticpro (&Qsignal);
7452 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7453 here again.
7455 Qexit = intern_c_string ("exit");
7456 staticpro (&Qexit); */
7458 Qopen = intern_c_string ("open");
7459 staticpro (&Qopen);
7460 Qclosed = intern_c_string ("closed");
7461 staticpro (&Qclosed);
7462 Qconnect = intern_c_string ("connect");
7463 staticpro (&Qconnect);
7464 Qfailed = intern_c_string ("failed");
7465 staticpro (&Qfailed);
7466 Qlisten = intern_c_string ("listen");
7467 staticpro (&Qlisten);
7468 Qlocal = intern_c_string ("local");
7469 staticpro (&Qlocal);
7470 Qipv4 = intern_c_string ("ipv4");
7471 staticpro (&Qipv4);
7472 #ifdef AF_INET6
7473 Qipv6 = intern_c_string ("ipv6");
7474 staticpro (&Qipv6);
7475 #endif
7476 Qdatagram = intern_c_string ("datagram");
7477 staticpro (&Qdatagram);
7478 Qseqpacket = intern_c_string ("seqpacket");
7479 staticpro (&Qseqpacket);
7481 QCport = intern_c_string (":port");
7482 staticpro (&QCport);
7483 QCspeed = intern_c_string (":speed");
7484 staticpro (&QCspeed);
7485 QCprocess = intern_c_string (":process");
7486 staticpro (&QCprocess);
7488 QCbytesize = intern_c_string (":bytesize");
7489 staticpro (&QCbytesize);
7490 QCstopbits = intern_c_string (":stopbits");
7491 staticpro (&QCstopbits);
7492 QCparity = intern_c_string (":parity");
7493 staticpro (&QCparity);
7494 Qodd = intern_c_string ("odd");
7495 staticpro (&Qodd);
7496 Qeven = intern_c_string ("even");
7497 staticpro (&Qeven);
7498 QCflowcontrol = intern_c_string (":flowcontrol");
7499 staticpro (&QCflowcontrol);
7500 Qhw = intern_c_string ("hw");
7501 staticpro (&Qhw);
7502 Qsw = intern_c_string ("sw");
7503 staticpro (&Qsw);
7504 QCsummary = intern_c_string (":summary");
7505 staticpro (&QCsummary);
7507 Qreal = intern_c_string ("real");
7508 staticpro (&Qreal);
7509 Qnetwork = intern_c_string ("network");
7510 staticpro (&Qnetwork);
7511 Qserial = intern_c_string ("serial");
7512 staticpro (&Qserial);
7513 QCbuffer = intern_c_string (":buffer");
7514 staticpro (&QCbuffer);
7515 QChost = intern_c_string (":host");
7516 staticpro (&QChost);
7517 QCservice = intern_c_string (":service");
7518 staticpro (&QCservice);
7519 QClocal = intern_c_string (":local");
7520 staticpro (&QClocal);
7521 QCremote = intern_c_string (":remote");
7522 staticpro (&QCremote);
7523 QCcoding = intern_c_string (":coding");
7524 staticpro (&QCcoding);
7525 QCserver = intern_c_string (":server");
7526 staticpro (&QCserver);
7527 QCnowait = intern_c_string (":nowait");
7528 staticpro (&QCnowait);
7529 QCsentinel = intern_c_string (":sentinel");
7530 staticpro (&QCsentinel);
7531 QClog = intern_c_string (":log");
7532 staticpro (&QClog);
7533 QCnoquery = intern_c_string (":noquery");
7534 staticpro (&QCnoquery);
7535 QCstop = intern_c_string (":stop");
7536 staticpro (&QCstop);
7537 QCoptions = intern_c_string (":options");
7538 staticpro (&QCoptions);
7539 QCplist = intern_c_string (":plist");
7540 staticpro (&QCplist);
7542 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7543 staticpro (&Qlast_nonmenu_event);
7545 staticpro (&Vprocess_alist);
7546 #ifdef SIGCHLD
7547 staticpro (&deleted_pid_list);
7548 #endif
7550 #endif /* subprocesses */
7552 QCname = intern_c_string (":name");
7553 staticpro (&QCname);
7554 QCtype = intern_c_string (":type");
7555 staticpro (&QCtype);
7557 Qeuid = intern_c_string ("euid");
7558 staticpro (&Qeuid);
7559 Qegid = intern_c_string ("egid");
7560 staticpro (&Qegid);
7561 Quser = intern_c_string ("user");
7562 staticpro (&Quser);
7563 Qgroup = intern_c_string ("group");
7564 staticpro (&Qgroup);
7565 Qcomm = intern_c_string ("comm");
7566 staticpro (&Qcomm);
7567 Qstate = intern_c_string ("state");
7568 staticpro (&Qstate);
7569 Qppid = intern_c_string ("ppid");
7570 staticpro (&Qppid);
7571 Qpgrp = intern_c_string ("pgrp");
7572 staticpro (&Qpgrp);
7573 Qsess = intern_c_string ("sess");
7574 staticpro (&Qsess);
7575 Qttname = intern_c_string ("ttname");
7576 staticpro (&Qttname);
7577 Qtpgid = intern_c_string ("tpgid");
7578 staticpro (&Qtpgid);
7579 Qminflt = intern_c_string ("minflt");
7580 staticpro (&Qminflt);
7581 Qmajflt = intern_c_string ("majflt");
7582 staticpro (&Qmajflt);
7583 Qcminflt = intern_c_string ("cminflt");
7584 staticpro (&Qcminflt);
7585 Qcmajflt = intern_c_string ("cmajflt");
7586 staticpro (&Qcmajflt);
7587 Qutime = intern_c_string ("utime");
7588 staticpro (&Qutime);
7589 Qstime = intern_c_string ("stime");
7590 staticpro (&Qstime);
7591 Qtime = intern_c_string ("time");
7592 staticpro (&Qtime);
7593 Qcutime = intern_c_string ("cutime");
7594 staticpro (&Qcutime);
7595 Qcstime = intern_c_string ("cstime");
7596 staticpro (&Qcstime);
7597 Qctime = intern_c_string ("ctime");
7598 staticpro (&Qctime);
7599 Qpri = intern_c_string ("pri");
7600 staticpro (&Qpri);
7601 Qnice = intern_c_string ("nice");
7602 staticpro (&Qnice);
7603 Qthcount = intern_c_string ("thcount");
7604 staticpro (&Qthcount);
7605 Qstart = intern_c_string ("start");
7606 staticpro (&Qstart);
7607 Qvsize = intern_c_string ("vsize");
7608 staticpro (&Qvsize);
7609 Qrss = intern_c_string ("rss");
7610 staticpro (&Qrss);
7611 Qetime = intern_c_string ("etime");
7612 staticpro (&Qetime);
7613 Qpcpu = intern_c_string ("pcpu");
7614 staticpro (&Qpcpu);
7615 Qpmem = intern_c_string ("pmem");
7616 staticpro (&Qpmem);
7617 Qargs = intern_c_string ("args");
7618 staticpro (&Qargs);
7620 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7621 doc: /* *Non-nil means delete processes immediately when they exit.
7622 A value of nil means don't delete them until `list-processes' is run. */);
7624 delete_exited_processes = 1;
7626 #ifdef subprocesses
7627 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7628 doc: /* Control type of device used to communicate with subprocesses.
7629 Values are nil to use a pipe, or t or `pty' to use a pty.
7630 The value has no effect if the system has no ptys or if all ptys are busy:
7631 then a pipe is used in any case.
7632 The value takes effect when `start-process' is called. */);
7633 Vprocess_connection_type = Qt;
7635 #ifdef ADAPTIVE_READ_BUFFERING
7636 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7637 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7638 On some systems, when Emacs reads the output from a subprocess, the output data
7639 is read in very small blocks, potentially resulting in very poor performance.
7640 This behavior can be remedied to some extent by setting this variable to a
7641 non-nil value, as it will automatically delay reading from such processes, to
7642 allow them to produce more output before Emacs tries to read it.
7643 If the value is t, the delay is reset after each write to the process; any other
7644 non-nil value means that the delay is not reset on write.
7645 The variable takes effect when `start-process' is called. */);
7646 Vprocess_adaptive_read_buffering = Qt;
7647 #endif
7649 defsubr (&Sprocessp);
7650 defsubr (&Sget_process);
7651 defsubr (&Sdelete_process);
7652 defsubr (&Sprocess_status);
7653 defsubr (&Sprocess_exit_status);
7654 defsubr (&Sprocess_id);
7655 defsubr (&Sprocess_name);
7656 defsubr (&Sprocess_tty_name);
7657 defsubr (&Sprocess_command);
7658 defsubr (&Sset_process_buffer);
7659 defsubr (&Sprocess_buffer);
7660 defsubr (&Sprocess_mark);
7661 defsubr (&Sset_process_filter);
7662 defsubr (&Sprocess_filter);
7663 defsubr (&Sset_process_sentinel);
7664 defsubr (&Sprocess_sentinel);
7665 defsubr (&Sset_process_window_size);
7666 defsubr (&Sset_process_inherit_coding_system_flag);
7667 defsubr (&Sset_process_query_on_exit_flag);
7668 defsubr (&Sprocess_query_on_exit_flag);
7669 defsubr (&Sprocess_contact);
7670 defsubr (&Sprocess_plist);
7671 defsubr (&Sset_process_plist);
7672 defsubr (&Slist_processes);
7673 defsubr (&Sprocess_list);
7674 defsubr (&Sstart_process);
7675 #ifdef HAVE_SERIAL
7676 defsubr (&Sserial_process_configure);
7677 defsubr (&Smake_serial_process);
7678 #endif /* HAVE_SERIAL */
7679 defsubr (&Sset_network_process_option);
7680 defsubr (&Smake_network_process);
7681 defsubr (&Sformat_network_address);
7682 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7683 #ifdef SIOCGIFCONF
7684 defsubr (&Snetwork_interface_list);
7685 #endif
7686 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7687 defsubr (&Snetwork_interface_info);
7688 #endif
7689 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7690 #ifdef DATAGRAM_SOCKETS
7691 defsubr (&Sprocess_datagram_address);
7692 defsubr (&Sset_process_datagram_address);
7693 #endif
7694 defsubr (&Saccept_process_output);
7695 defsubr (&Sprocess_send_region);
7696 defsubr (&Sprocess_send_string);
7697 defsubr (&Sinterrupt_process);
7698 defsubr (&Skill_process);
7699 defsubr (&Squit_process);
7700 defsubr (&Sstop_process);
7701 defsubr (&Scontinue_process);
7702 defsubr (&Sprocess_running_child_p);
7703 defsubr (&Sprocess_send_eof);
7704 defsubr (&Ssignal_process);
7705 defsubr (&Swaiting_for_user_input_p);
7706 defsubr (&Sprocess_type);
7707 defsubr (&Sset_process_coding_system);
7708 defsubr (&Sprocess_coding_system);
7709 defsubr (&Sset_process_filter_multibyte);
7710 defsubr (&Sprocess_filter_multibyte_p);
7712 #endif /* subprocesses */
7714 defsubr (&Sget_buffer_process);
7715 defsubr (&Sprocess_inherit_coding_system_flag);
7716 defsubr (&Slist_system_processes);
7717 defsubr (&Sprocess_attributes);
7720 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7721 (do not change this comment) */